text:
Q: cdkDropListDropped event not emitted when item is dropped I am trying to do drag and drop without deleting the item from the dragged list. I followed an example Working demo and tried to reproduce the same. Unfortunately it was not working and I found that the cdkDropListDropped event is emitted. You can find the issue in this link Problematic demo
I want to achieve like the Working demo
Please show me where I am wrong.

A: I found I had to move the directives cdkDropList and cdkDropListConnectedTo="drop-list" from the div with ID div1 to the parent div so the HTML becomes:

        {{type.text}}

At this point the cdkDropListDropped event fired and called the itemDropped function. The problem then was, there was a runtime error on the following line:
copyArrayItem(
     event.previousContainer.data,
     event.container.data,
     event.previousIndex,
     event.currentIndex
);

After copying the itemDropped method from your working demo StackBlitz, it then started work. Please see this StackBlitz for a demo.


text:
Q: AngularJS Directives - specify defaults for callbacks I have a directive that takes a few methods as callbacks. All of them require attributes to work.
scope: {
    onEventOne: '&?',
    onEventTwo: '&?'
}

function someWork() {
    onEventOne()(myVar);
    onEventTwo()(myOtherVar);
}

My problem is when I don't have some of those callbacks defined, as they are not all required.
<div>
    <myDirective on-event-one="customHandler"></myDirective>
</div>

In the code above, when calling onEventOne()(myVar); everuthing works, but when calling onEventTwo()(myOtherVar); I get TypeError: undefined is not a function.
I tried using the link function to set a blank function as default,
function linkFunction(scope, element, attrs) {
    if (!attrs.onEventOne) {scope.onEventOne = scope.blankHandler;}
    if (!attrs.onEventTwo) {scope.onEventTwo = scope.blankHandler;}
}

but that causes the the default function to be called while still throwing TypeError: undefined is not a function.
How do I set these default functions?

A: The usage of your functions implies that blankHandler must return one more "blank" function (angular.noop is convenient here). This is what I would do in link function in your case:
var blankHandler = function() {
    return angular.noop;
};

if (!attrs.onEventOne) {scope.onEventOne = blankHandler;}
if (!attrs.onEventTwo) {scope.onEventTwo = blankHandler;}

scope.onEventOne()(myVar);
scope.onEventTwo()(myOtherVar);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Alertdialog running ongoing dosen't dismiss or cancel According this answer , I wanna to show dilaog until the next 10 posts is loaded so I created the static alertDialog method to use it in different places in my app, but the problem is the dialog doesn't cancel or dismiss

setProgressDialog in Utils class
 public static AlertDialog setProgressDialog(Context context) {

        int llPadding = 30;
        LinearLayout ll = new LinearLayout(context);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setPadding(llPadding, llPadding, llPadding, llPadding);
        ll.setGravity(Gravity.CENTER);
        LinearLayout.LayoutParams llParam = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        llParam.gravity = Gravity.CENTER;
        ll.setLayoutParams(llParam);

        ProgressBar progressBar = new ProgressBar(context);
        progressBar.setIndeterminate(true);
        progressBar.setPadding(0, 0, llPadding, 0);
        progressBar.setLayoutParams(llParam);

        llParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        llParam.gravity = Gravity.CENTER;
        TextView tvText = new TextView(context);
        tvText.setText("Loading ...");
        tvText.setTextColor(context.getResources().getColor(R.color.black));
        tvText.setTextSize(20);
        tvText.setLayoutParams(llParam);

        ll.addView(progressBar);
        ll.addView(tvText);

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setCancelable(false);
        builder.setView(ll);

        AlertDialog dialog = builder.create();
        dialog.show();
        Window window = dialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
            layoutParams.copyFrom(dialog.getWindow().getAttributes());
            layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
            layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
            dialog.getWindow().setAttributes(layoutParams);
        }
        return dialog;
    }

then I used it in HomeFragment on click load more button
binding.loadMoreBtn.setOnClickListener(view -> {

            Utils.setProgressDialog(requireContext());

            if (Utils.hasNetworkAccess(requireContext())) {
                postViewModel.getPosts();
//                Log.w(TAG, "loadMoreBtn: "+dialog.isShowing() );
            } else {
                postViewModel.getAllItemsFromDataBase.getValue();
            }
            Utils.setProgressDialog(requireContext()).cancel();
            Utils.setProgressDialog(requireContext()).dismiss();

        });

PS: I tried also to create dialog AlertDialog dialog = Utils.setProgressDialog(requireContext()); instead to call the method directly then dialod.show(), and after the getPosts cancel or dismiss it but it dosen't appear

A:
binding.loadMoreBtn.setOnClickListener(view -> {

        Utils.setProgressDialog(requireContext());

        if (Utils.hasNetworkAccess(requireContext())) {
            postViewModel.getPosts(); //                Log.w(TAG, "loadMoreBtn: "+dialog.isShowing() );
        } else {
            postViewModel.getAllItemsFromDataBase.getValue();
        }
        Utils.setProgressDialog(requireContext()).cancel();
        Utils.setProgressDialog(requireContext()).dismiss();

    });

Here you invoked the static method Utils.setProgressDialog() multiple times; and each time it is called, it returns back a brand new dialog, so you'd dismiss a dialog that is not displayed on the screen.
Instead, you need to store the dialog that is returned from the first call to the method into a variable:
AlertDialog dialog = Utils.setProgressDialog(requireContext());

And then call dismiss on that dialog version: dialog.dismiss() or dialog.cancel() whenever you need to dismiss it.

A: I fixed it by adding a flag boolean in the viewmodel to detect loading state
public final MutableLiveData<Boolean> isLoading = new MutableLiveData<>();

and use it in getPosts() like this
public void getPosts() {
        Log.e(TAG, finalURL.getValue());

        isLoading.setValue(true);
        repository.remoteDataSource.getPostList(finalURL.getValue())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Response<PostList>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull Response<PostList> postListResponse) {

                        if (postListResponse.isSuccessful()) {
                            if (postListResponse.body() != null
                                    && postListResponse.body().getNextPageToken() != null) {
                                Log.e(TAG, postListResponse.body().getNextPageToken());
                                token.setValue(postListResponse.body().getNextPageToken());
                                isLoading.setValue(false);
                            }
                            postListMutableLiveData.setValue(postListResponse.body());

and finally in the fragment on button click
binding.loadMoreBtn.setOnClickListener(view -> {
            AlertDialog dialog = Utils.setProgressDialog(requireContext());

            postViewModel.isLoading.observe(getViewLifecycleOwner(), isLoading -> {
                if (isLoading) {
                    dialog.show();
                } else {
                    dialog.dismiss();
                }
            });

            if (Utils.hasNetworkAccess(requireContext())) {
                postViewModel.getPosts();
                Log.w(TAG, "loadMoreBtn: " + dialog.isShowing());
            } else {
                postViewModel.isLoading.postValue(true);
                postViewModel.getAllItemsFromDataBase.getValue();
                postViewModel.isLoading.postValue(false);
            }

        });


text:
Q: What's causing the pointer to reset? I'm working on a program for class that creates a Linked List off of a templated class to hold information about Students, Faculty, and Administration. Student, Administrator, and Faculty all inherit a class called Person. My problem is in my list class along with my RecordsOffice class, when the program leaves the addToList function, the head pointer resets it's data and I can't see what I have just added to the list.
This is the TemplatedList class
//Author:Angelo Todaro
//TemplatedList.h
//Header file for the TemplatedList class

#include "person.h"
#include "student.h"
#include "administrator.h"
#include "faculty.h"

using namespace std;
#ifndef TemplatedList_H
#define TemplatedList_H

template<class T>
struct Node{
    T *data;
    Node *next;
};

template <class T, typename T2>
class TemplatedList{
public:
    /*Default Constructor
    *Constructs an object of the TemplatedList class*/
    TemplatedList();

    /*Default Destructor
    *Destructs an object of the TemplatedList class*/
    ~TemplatedList();

    /*Accessor Method for head node
    *Provides user access to the value of the head node*/
    T getHead() const;

    /*Modifier Method for head node
    *Provides the user access to change the value of the head node*/
    void setHead(T *newHead);

    /*addToList
    *Adds a Student to the list*/
    void addToList(T *newStudent);

    /*deleteFromList
    *Deletes a Student from the list*/
    void deleteFromList(T2 number);

    /*printStudent
    *prints the information of the specified student*/
    void printSingle(T2 number);

    /*printList
    *prints the entire list of students*/
    void printList();

private:
    T *head;
};

#endif

/*Default Constructor
*Constructs an object of the TemplatedList class*/
template <class T, typename T2>
TemplatedList<T,T2>::TemplatedList(){
    head = new T;
    head->next=NULL;
    head->data=NULL;
}

/*Default Destructor
*Destructs an object of the TemplatedList class*/
template <class T, typename T2>
TemplatedList<T,T2>::~TemplatedList(){
    delete head;
    head=NULL;
}

/*Accessor Method for head node
*Provides user access to the value of the head node*/
template <class T, typename T2>
T TemplatedList<T,T2>::getHead() const{
    return head;
}

/*Modifier Method for head node
*Provides the user access to change the value of the head node*/
template <class T, typename T2>
void TemplatedList<T,T2>::setHead(T *newHead){
    head=newHead;
}

/*addToList
*Adds a Person to the list*/
template <class T, typename T2>
void TemplatedList<T,T2>::addToList(T *newPerson){
    T *curr=head;
    T *prev=curr;
    cout << "Adding ";
    newPerson->data->print();
    cout << endl;
    if(head->next==NULL && head->data==NULL)//if list has not been initialized
    {

        head->data=newPerson->data;
        head->data->print();
        head->next=NULL;
    }
    //if new Person's M Number is less than the head's MNumber
    else if(newPerson->data->getMNumber()<head->data->getMNumber())
    {
        newPerson->next=head->next;
        head = newPerson;
    }
    else //all other cases
    {
        while(curr!=NULL &&
                newPerson->data->getMNumber()>curr->data->getMNumber())
        {
            prev=curr;
            curr=curr->next;
        }
            newPerson->next=curr;
            prev->next= newPerson;
        if(curr==NULL)
            newPerson->next=NULL;
    }

}

/*deleteFromList
*Deletes a Person from the list*/
template <class T, typename T2>
void TemplatedList<T,T2>::deleteFromList(T2 number){
    T *curr=head;
    T *prev=head;
    if(head==NULL||head->next==NULL){
        cout << "Can not delete Person (M" << number << "), NOT found!" << endl;
    }
    //if first Person is equal to the selected one to delete
    else if(curr->data->getMNumber()==number)
    {
        prev->next=curr->next;
        delete curr;
        curr=NULL;
    }
    else
    {
        while(curr!=NULL &&
            curr->data->getMNumber()!=number)
        {
            prev=curr;
            curr=curr->next;
        }
        if(curr!=NULL)//If not at end of list
        {
            prev->next=curr->next;
            delete curr;
            curr = NULL;

        }
        else//there is no listing
        {
            cout << "Can not delete Person (M" << number << "), NOT found!" << endl;
        }
    }
    cout << endl;
}

/*printPerson
*prints the information of the specified Person*/
template <class T, typename T2>
void TemplatedList<T,T2>::printSingle(T2 number){
    T *curr=head;
    T *prev=curr;
    while(curr!=NULL && curr->data->getMNumber()!=number)
    {
        prev=curr;
        curr=curr->next;
    }
    if(curr!=NULL)//if match is found
    {
        curr->data->print();
    }
    else//there is no listing
    {
        cout << "Can not print person (M" << number << "), NOT found!" << endl << endl;
    }

}

/*printList
*prints the entire list of Persons*/
template <class T, typename T2>
void TemplatedList<T,T2>::printList(){
    T *curr=head;
    T *prev=curr;
    while(curr!=NULL)
    {
        curr->data->print();
        prev=curr;
        curr=curr->next;
    }
    cout << endl;
}

Here is the implementation of the RecordsOffice class
//Author:Angelo Todaro
//recordsOffice.cpp
//Implementation file for the RecordsOffice class

#include <iostream>
#include <fstream>
#include <cassert>
#include "recordsOffice.h"

/*Default Constructor
Creates an object of the RecordsOffice class*/
RecordsOffice::RecordsOffice(){

}

/*Default Destructor
*Destructs an object of the RecordsOffice class*/
RecordsOffice::~RecordsOffice(){

}

/*Accessor Method for List of Persons
*Provides the user with a way to retrieve m_List*/
TemplatedList<Node<Person>,int> RecordsOffice::getList() const{
    return m_List;
}

/*Modifier Method for List of Persons
*provides a way for the user to modify m_List*/
void RecordsOffice::setList(TemplatedList<Node<Person>,int> newList){
    m_List = newList;
}

/*parseCommands
*parses the command entered and calls appropriate function*/
void RecordsOffice::parseCommands(string fileName){
    ifstream infile;//create new file stream
    infile.open(fileName);//opens file
    assert(infile);//check for valid file
    char command;//stores the value of the current command

    while(infile >> command)
    {
        if(command=='A')
        {
            string name, email, title;//temporary strings  to hold values of Person
            int mnumber;//temporary ints to hold values of Person
            infile >> name >> mnumber >> email >> title;
            Administrator admin = Administrator(name,mnumber,email,title);
            Node<Person> *newper = new Node<Person>;
            newper->data=&admin;
            newper->next=NULL;
            m_List.addToList(newper);
        }
        else if(command=='F')
        {

            string name, email, department;//temporary strings  to hold values of Person
            int mnumber;//temporary ints to hold values of Person
            bool tenured;
            infile >> name >> mnumber >> email >> department >> tenured;
            Faculty fac= Faculty(name,mnumber,email,tenured,department);
            Node<Person> *newper = new Node<Person>;
            newper->data=&fac;
            newper->next=NULL;
            m_List.addToList(newper);
        }
        else if(command=='S')
        {
            string name, email, major;//temporary strings  to hold values of Person
            int mnumber, year;//temporary ints to hold values of Person
            infile >> name >> mnumber >> email >> year >> major;
            Student stu= Student(name,mnumber,email,year,major);
            Node<Person> *newper = new Node<Person>;
            newper->data=&stu;
            newper->next=NULL;
            m_List.addToList(newper);
        }
        else if(command=='D')
        {
                int mnum;//int to store mnumber
                infile >> mnum;
                cout << "Deleting M" << mnum << endl;
                m_List.deleteFromList(mnum);
        }
        else if(command=='P')
        {
                int mnum;//int to store mnumber
                infile >> mnum;
                cout << "Printing M" << mnum << endl;
                m_List.printSingle(mnum);
        }
        else if(command=='L')
        {
                cout << "Listing all Persons" << endl;
                m_List.printList();
        }

    }
}

The file that the program is reading in contains
A   Doe 4444    jdoe3@mtsu.com  President
L
P   4444
F   Johnson 2222    cjLittle@mtsu.com   English 0
P   2222
S   Reed    9999    reed@mtsu.com   1   History
P   9999
L
D   9999
D   2222
D   4444

A: newper->data always points to local variables, when local variables go out of scope, they are actually released, newper->data no longer points to valid data. You need to use dynamic storage duration by new.
Administrator admin = Administrator(name,mnumber,email,title);
newper->data=&admin;

Faculty fac= Faculty(name,mnumber,email,tenured,department);
newper->data=&fac;

Student stu= Student(name,mnumber,email,year,major);
newper->data=&stu;

Try:
Person *admin = new Administrator(name,mnumber,email,title);
newper->data = admin;

Person *fac = new Faculty(name,mnumber,email,tenured,department);
newper->data = fac;

Person * stu = new Student(name,mnumber,email,year,major);
newper->data=stu;


text:
Q: Bash: how to certain lines but exclude certain lines in between? I have a file that looks like this:
a: 0
a: 0
a: 0
a: 1
b: 1
c: 1
d: 1
e: 1
f: 1
a: 2
b: 2
c: 2
d: 2
e: 2
f: 2
a: 3
b: 3
c: 3
d: 3
e: 3
f: 3
c: 4
c: 4
c: 4

I want to capture and output all of the a and c lines of the form <a line><anything other than an a or c line><c line> so the output would look like:
a: 1
c: 1

a: 2
c: 2

a: 3
c: 3

Note that neither the a: 0 lines at the beginning nor the c: 4 lines at the end are captured because they don't follow the pattern I mentioned. Note also that the b lines between the a and c lines are removed.
I've been trying to do this with lookarounds usings Bash's pcregrep, but haven't found a solution yet. Any ideas?
Thanks!

A: Using awk
Try:
$ awk -F: '$1=="a"{aline=$0} $1=="c"{if(aline)print aline ORS $0 ORS; aline=""}' file
a: 1
c: 1

a: 2
c: 2

a: 3
c: 3

How it works
By default, awk reads in one line at a time.

*

*-F:
This tells awk to use : as the field separator.

*$1=="a"{aline=$0}
Everytime an a line is observed, save the line in variable aline.

*$1=="c"{if(aline)print aline ORS $0 ORS; aline=""}
Every time a c line is observed, check to see if we have a nonempty aline.  If so, print aline and the current line, separated by newline characters.  Also, set aline back to an empty string.
Multiline version
For those who prefer their commands spread over several lines:
awk -F: '
    $1=="a"{
        aline=$0
    }

   $1=="c"{
        if(aline)
            print aline ORS $0 ORS
        aline=""
    }' file

Using sed
$ sed -n '/^a/h; /^c/{x;/^a/{p;x;s/$/\n/;p};h}' file
a: 1
c: 1

a: 2
c: 2

a: 3
c: 3

How it works

*

*-n
This tells sed not to print anything unless we explicitly ask it to.

*/^a/h
Any time we have a line that starts with a, we save it to the hold space.

*/^c/{ x; /^a/{ p; x; s/$/\n/; p}; h}
Any time we have a line that starts with c, we:

*

*We swap (x) the pattern space with the hold space.

*If the new pattern space starts with a, then we print (p) it, and swap (x) again, add a new line to the end of the new pattern space (s/$/\n/) and print (p) it.

*Lastly we save the current pattern space (which starts with a c) to the hold space.


text:
Q: How can i change a text of a button without changing it's icon i have a "Pause" button with a pause_circle_outline materialize icon, and when it clicked i want to change the text to "Resume" and changing the icon to play_circle_outline, but when i try to change the text it changed the text and deletes the icon. here is my code snippet example:

jQuery(document).ready(function($){

  $(document.getElementById("pause_btn")).click(function(){
      document.getElementById("pause_btn").innerText = "Resume"
  });
})
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    Pausepause_circle_outline

A:
Both textContent and innerText remove child nodes when altered

Docs
Perhaps place your text within a span with an ID and change its textContent?
that way your i tag should remain untouched.

A: .innerText is a sort of "safe"* way to access a node's innerHTML, which in your case includes both the Pause-text, as well as the  tag.
A way to solve this is to add a span to hold the text. spans don't do anything (as they are inline elements and are by default formatted/shown as a simple text element), but they help by making the text node selectable by document.querySelector!
Example:

var playing = true

window.addEventListener("load", () => {
  document.querySelector("#pause_btn").addEventListener("click", () => {
      playing = !playing
      if(playing) {
        document.querySelector("#pause_btn span").innerText = "Pause"
        document.querySelector("#pause_btn i").innerText = "pause_circle_outline"
      } else {
        document.querySelector("#pause_btn span").innerText = "Resume"
        document.querySelector("#pause_btn i").innerText = "play_circle_outline"
      }
  });
})
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

      Pause
      pause_circle_outline

I also added some extra code to make it clickable multiple times!

*: By safe, in this context, I mean that it's safe from a security issue called XSS. Generally it's better to use innerText when you don't explicitly need to change the HTML itself, but if you do: Make sure that there's NO way a user can input something that gets put into the innerHTML. What I initially meant was simply that writing to either innerHTML and innerText will always overwrite whatever contents the element has, and that innerText is generally the safer of the two.

A: Have you tried putting the icon along with the text to the innerHTML?

jQuery(document).ready(function($){

  $(document.getElementById("pause_btn")).click(function(){
      document.getElementById("pause_btn").innerHTML = 'Resumepause_circle_outline'
  });
})
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    Pausepause_circle_outline


text:
Q: How do I get sum of all figures inside a string but for the whole column? Data:

*

*MEL1INFA73 Confirmed. Ksh29.00 sent to Safaricom Offers  for account Tunukiwa on 21/5/18 at 3:29 AM New M-PESA balance is Ksh5.50. Transaction cost, Ksh0.00.

*MEE6ESSVCS Confirmed. Ksh2,240.00 paid to Naivas West End Plaza. on 14/5/18 at 8:13 PM.New M-PESA balance is Ksh4,753.50. Transaction cost, Ksh0.00.

*MEF1EZ0MNR Confirmed.You have received Ksh10,000.00 from Barclays Bank K LTD 303031 on 15/5/18 at 9:36 AM New M-PESA balance is Ksh14,775.50.  Buy goods with M-PESA.

The following code generates sum of figures in each row other than the whole column:
 <?php
                if(count($json_data["data"]) > 0){ ?>
                    <?php $_count = 1;
                        foreach($json_data["data"] as $row){ ?>

                                <?php
                                $str =$row["msg_body"];
                                preg_match_all("/ksh\s*(\d+\.\d+)/i", $str, $matches);
                                echo array_sum($matches[1]); ?>

                    <?php $_count ++; }
                    ?>
            <?php }else{

                }
            ?>

A: If I understand correctly you just need to store the whole sum and then print it out somewhere. Something like:
<?php
                if(count($json_data["data"]) > 0){ ?>
                    <?php $_count = 1;
                          $totalSum = 0;
                        foreach($json_data["data"] as $row) { ?>

                                <?php
                                $str =$row["msg_body"];
                                preg_match_all("/ksh\s*(\d+\.\d+)/i", $str, $matches);
                                $rowSum = array_sum($matches[1]);
                                $totalSum += $rowSum;
                                echo  $rowSum;?>

                    <?php $_count ++; }
                    ?>

Total sum: <?php echo $totalSum; ?>

            <?php }else{

                }
            ?>

You can adjust your html, of course.

A: Because we are dealing with an array and preg_match_all, then I believe you could implode the array and do one preg_match_all instead of looping it.
$AllItems = implode(" ", $json_data["data"]);
preg_match_all("/ksh\s*(\d+\.\d+)/i", str_replace(",","",$AllItems), $matches);
$total = array_sum($matches[1]);

Example:
https://3v4l.org/Pk7YT
Edit noticed there was commas as thousands separators. That needs to be removed for the regex and summing to work with str_replace.


text:
Q: How to achieve sudo su -  and run all command in ansible I have an ssh access to the box but to run certain commands I need to do sudo su -  and enter the password. Then I can run all the commands under that user.
How can i achieve this ansible. I tried become and sudo nothing worked for me.
Can someone provide me a working example?

A: this is what working for me ...
become: yes
become_method: sudo
become_user: myuser
become_flags: 'su -c'

A: Ansible uses the become directive to control privilege escalation.
If you're using sudo su -, you're using sudo to raise your privileges (and su - merely launches an interactive shell).  become_method should be set to "sudo".
Since you aren't using password-less sudo, you need to tell Ansible that you will be supplying a password.  You can do this in a config file with ansible_become_pass, but a much more secure method is to invoke ansible with --ask-become-pass.


text:
Q: What is wrong with the logic in this sequence? I am a Python beginner, and I decided that I wanted to create a program over my summer holiday, before I did this however I decided I would make a small program before, to practice creating GUI's.  I am working on a joke machine, that uses the random module to select a random integer that will decide which joke is displayed, however it seems to only ever output joke 3, regardless of how many times I run it.
I can't see any issues here, any advice?
joke_select = random.randint (1,3)

joke1 = "Why do you never see elephants hiding in trees?\n because they're really good at it!"
joke2 = "What is grey and can't climb a tree? \n A parking lot"
joke3 = "What is red and bad for your teeth?\n A brick"

if joke_select == '1':
    joke_label = tkinter.Label (main, text = joke1)
elif joke_select == '2':
    joke_label = tkinter.Label (main, text = joke2)
else:
    joke_label = tkinter.Label (main, text = joke3)

def get_joke():
    joke_label.pack ()

A: if joke_select == '1':

joke_select is only ever an integer, but you're comparing it to a string here. Try comparing to an integer instead.
if joke_select == 1:

Likewise for elif joke_select == '2':.

A: Your scripts looks for a string and you generate a number.
if joke_select == 1:
    joke_label = tkinter.Label (main, text = joke1)
elif joke_select == 2:
    joke_label = tkinter.Label (main, text = joke2)
else:
   joke_label = tkinter.Label (main, text = joke3)

will probably work

A: Just a piece of advice: there is no need for whitespace on such things as random.randint (1,3). It would be clearer to have this as random.randint(1,3). There are a few more places in your code where this also applies.


text:
Q: combining two tables query i came across the following problem
i would like to sum someone absence using mysql with across within these twop codes
SELECT  a.nama_account,
             a.jabatan,
             b.nama_tp,
             a.jam_berangkat,
             a.jam_pulang,
             (SUM(IF((jam_awal < jam_berangkat) AND (jam_akhir > jam_pulang),'1','0'))+dinas+dinastp) jum,
             DATEDIFF('$tgl2','$tgl1')+1 jumhar
            FROM t_account a
            LEFT JOIN t_tp b ON a.tp_ID=b.ID
            LEFT JOIN t_user c ON a.userCode=c.userCode
            LEFT JOIN (
                        SELECT  DATE(`tanggal`) tgl,
                            phoneNumber,
                            MIN(TIME( tanggal)) jam_awal,
                            MAX(TIME( tanggal)) jam_akhir,
                            SUM(IF(saran = '1234','1','0')) dinas,
                            SUM(IF(saran = '4321','1','0')) dinastp
                        FROM    t_report
                        WHERE ( tanggal BETWEEN '$tgl1 00:00:00' AND '$tgl2 23:59:59' )
                        GROUP BY DATE(tanggal),phoneNumber
                     ) tlis
                 ON tlis.phoneNumber = a.`imei_number`
            WHERE a.grup_ID = '$grup'
            $queryIf
            AND (c.user_status !='3' AND c.user_status != '999')
            GROUP BY a.`imei_number`
            ORDER BY b.nama_tp,a.jabatan

AND
SELECT  a.nama_account,
             a.jabatan,
             b.nama_tp,
             a.jam_berangkat,
             a.jam_pulang,
             (SUM(IF((jam_awal < jam_berangkat) AND (jam_akhir > '$jampulang_sabtu'),'1','0'))+dinas+dinastp) jum,
             DATEDIFF('$tgl2','$tgl1')+1 jumhar
            FROM t_account a
            LEFT JOIN t_tp b ON a.tp_ID=b.ID
            LEFT JOIN t_user c ON a.userCode=c.userCode
            LEFT JOIN (
                        SELECT  DATE(`tanggal`) tgl,
                            phoneNumber,
                            MIN(TIME( tanggal)) jam_awal,
                            MAX(TIME( tanggal)) jam_akhir,
                            SUM(IF(saran = '1234','1','0')) dinas,
                            SUM(IF(saran = '4321','1','0')) dinastp
                        FROM    t_report
                        WHERE ( tanggal BETWEEN '$tgl1 00:00:00' AND '$tgl2 23:59:59') AND DAYNAME(tanggal)='Saturday'
                        GROUP BY DATE(tanggal),phoneNumber
                     ) tlis
                 ON tlis.phoneNumber = a.`imei_number`
            WHERE a.grup_ID = '$grup'
            $queryIf
            AND (c.user_status !='3' AND c.user_status != '999')
            GROUP BY a.`imei_number`
            ORDER BY b.nama_tp,a.jabatan

i wanna get the combine number of jum in each query, is there anything i can do with 1 query instead having these two? because its a trouble to loopin it on php echo.
thanks

A: @StevenC. it sounds like you need to use a UNION to put the results of the 2 queries together.
Here's how you would do it:
SELECT nama_account,
    jabatan,
    nama_tp,
    jam_berangkat,
    jam_pulang,
    jumhar,
    SUM(jum) AS jumTotal
FROM (
SELECT  a.nama_account,
             a.jabatan,
             b.nama_tp,
             a.jam_berangkat,
             a.jam_pulang,
             (SUM(IF((jam_awal < jam_berangkat) AND (jam_akhir > jam_pulang),'1','0'))+dinas+dinastp) jum,
             DATEDIFF('$tgl2','$tgl1')+1 jumhar
            FROM t_account a
            LEFT JOIN t_tp b ON a.tp_ID=b.ID
            LEFT JOIN t_user c ON a.userCode=c.userCode
            LEFT JOIN (
                        SELECT  DATE(`tanggal`) tgl,
                            phoneNumber,
                            MIN(TIME( tanggal)) jam_awal,
                            MAX(TIME( tanggal)) jam_akhir,
                            SUM(IF(saran = '1234','1','0')) dinas,
                            SUM(IF(saran = '4321','1','0')) dinastp
                        FROM    t_report
                        WHERE ( tanggal BETWEEN '$tgl1 00:00:00' AND '$tgl2 23:59:59' )
                        GROUP BY DATE(tanggal),phoneNumber
                     ) tlis
                 ON tlis.phoneNumber = a.`imei_number`
            WHERE a.grup_ID = '$grup'
            $queryIf
            AND (c.user_status !='3' AND c.user_status != '999')
            GROUP BY a.`imei_number`
            ORDER BY b.nama_tp,a.jabatan

UNION

SELECT  a.nama_account,
             a.jabatan,
             b.nama_tp,
             a.jam_berangkat,
             a.jam_pulang,
             (SUM(IF((jam_awal < jam_berangkat) AND (jam_akhir > '$jampulang_sabtu'),'1','0'))+dinas+dinastp) jum,
             DATEDIFF('$tgl2','$tgl1')+1 jumhar
            FROM t_account a
            LEFT JOIN t_tp b ON a.tp_ID=b.ID
            LEFT JOIN t_user c ON a.userCode=c.userCode
            LEFT JOIN (
                        SELECT  DATE(`tanggal`) tgl,
                            phoneNumber,
                            MIN(TIME( tanggal)) jam_awal,
                            MAX(TIME( tanggal)) jam_akhir,
                            SUM(IF(saran = '1234','1','0')) dinas,
                            SUM(IF(saran = '4321','1','0')) dinastp
                        FROM    t_report
                        WHERE ( tanggal BETWEEN '$tgl1 00:00:00' AND '$tgl2 23:59:59') AND DAYNAME(tanggal)='Saturday'
                        GROUP BY DATE(tanggal),phoneNumber
                     ) tlis
                 ON tlis.phoneNumber = a.`imei_number`
            WHERE a.grup_ID = '$grup'
            $queryIf
            AND (c.user_status !='3' AND c.user_status != '999')
            GROUP BY a.`imei_number`
            ORDER BY b.nama_tp,a.jabatan
) AS derivedTable
GROUP BY nama_account,
    jabatan,
    nama_tp,
    jam_berangkat,
    jam_pulang,
    jumhar;

There you go: the combined total of the values of jum from the 2 queries.
Hope this helps.


text:
Q: Page Object Model for page with many elements I'm currently working on a Selenium solution for my company's website. I'm trying to use the Page Object Model with Page Factories.  The difficulty that I'm encountering is with pages that have many elements on them.  I've seen in examples that it is good practice to create methods to encapsulate each action rather than just access the element directly (i.e. Create a method ClickButtonA() rather than using buttonA.click()
This?
public void login(String username, String password)
{
    usernameInput.sendKeys(username);
    passwordInput.sendKeys(password);
    loginButton.click();
}

Or something like
public void login(String username, String password)
{
    setUsername(username);
    setPassword(password);
    clickLogin();
}

My question is, what is best practice in this scenario?  Should I create methods to perform actions for each and every WebElement in the website or should I just create those on a need to use basis?
I feel like it is better practice to create those methods for every WebElement but  with 50+ elements, I feel like it ends up being a little bloated for redundant methods.


text:
Q: Preprocessors Directives in c++ : what is the output of the following code? Student here. I have the following piece of code and i'm confused about it's output. When i run this code, it tells me the C will be 2 but i though it will be 0. Why is it 2? Ty!
#include <iostream>
using namespace std;

#define A    0
#define B    A+1
#define C    1-B

int main() {
cout<<C<<endl;
return 0;
}

A: The main point here is that you are expecting B to be evaluated befor A. This is true of ordinary C++ code, but the preprocessor simply replaces the directive with its contents.
In this case, this happens as follows.. Take:
cout<<C<<endl;

Substitute C for 1-B:
cout<<1-B<<endl;

B -> A+1
cout<<1-A+1<<endl;

A -> 0
cout<<1-0+1<<endl;

According to the usual rules of C++ operator precedence - and + are equal and associate left-to-right, so, 1 - 0 + 1 is 2.

A: With gcc use the -E flag to see output after preprocessing.
Remove includes and the rest of the code to see output of this:
#define A    0
#define B    A+1
#define C    1-B

A
B
C

to come out as:
0
0 +1
1-0 +1

The preprocessor is just about textual replacement. If you want to define constants then define constants:
const int A = 0;
const int B = A+1;
const int C = 1-B;


text:
Q: Finding the shortest path in a boost graph using Dijkstra I am new to the boost graph library and I am trying to find the shortest path from one vertex to another one in the Graph using the boost graph library. I found some instructions on how to use the predecessor map in order to do that but it won't work for me. When I try to call p[some_vertex] I get an error  saying the [] operator is not defined. Can someone tell me why and what I am doing wrong?
typedef property<edge_weight_t, double, property<edge_index_t, tElementIDVector>> tEdgeProperty;
typedef property<vertex_index_t, tElementID> VertexIDPorperty;
typedef adjacency_list<vecS, setS, directedS, VertexIDPorperty, tEdgeProperty> tGraph;

typedef tGraph::vertex_descriptor tVertex;
typedef tGraph::edge_descriptor tEdge;

vector<tVertex> p(num_vertices(graph));
vector<double> d(num_vertices(graph));
// call dijkstra algorithm from boost to find shortest path
dijkstra_shortest_paths(graph, s,
    predecessor_map(&p[0]).
    distance_map(boost::make_iterator_property_map(d.begin(), get(boost::vertex_index, graph))));

//find path from start to end vertex
list<tVertex> pathVertices;
tVertex current = goal;
while (current != start)
{
    pathVertices.push_front(current);
    current = p[current];     //this is where the error occures
}

A: From cppreference:

std::vector::operator[]
reference       operator[]( size_type pos );
const_reference operator[]( size_type pos ) const;

accepts size_t specifying the position of the vector element.
However in your code, current is of type tVertex.
If you want to use operator[] with tVertex parameter, you should override it.

A: I couldn't get your idea to work and had to make some other changes now, too which is why i changed my predecessor map now to:
typedef boost::property_map < tGraph, boost::vertex_index_t >::type IndexMap;
typedef boost::iterator_property_map < tVertex*, IndexMap, tVertex, tVertex& > PredecessorMap;
tVertex s = start;
IndexMap indexMap = get(vertex_index, graph);
vector<tVertex> p(num_vertices(graph));
PredecessorMap predecessorMap(&p[0], indexMap);
vector<double> d(num_vertices(graph));

// call dijkstra algorithm from boost to find shortest path
dijkstra_shortest_paths(graph, s, predecessor_map(predecessorMap).distance_map(boost::make_iterator_property_map(d.begin(), get(boost::vertex_index, graph))));
//find path from start to end vertex
list<tVertex> pathVertices;
tVertex current = goal;
while (current != start)
{
    pathVertices.push_front(current);
    current = predecessorMap[current];
}

and this actually works now :)


text:
Q: Buttons overriding set height/width (appearing too big) when creating them in a for loop I have a method that creates an array of buttons (simulating a grid). The user can click the buttons and a "marker" (image) will appear on it. The problem I have is that even though I'm setting height and width within my method, when it is called, the buttons appear way too big. Important to note that when the user clicks the button, it "shrinks" to the size I specified... Weird. Here is my method:
def create_grid(self, leng) :
    try:
        global board
        board = grid.Grid(leng)

        frame = tkinter.Frame(self.main_window)
        buttons = []
        for row_index in range(0,leng) :
            row = []
            for column_index in range(0,leng) :
                button = tkinter.Button(frame, height=36, \
                    width = 36, text = "  ", \
                    command=lambda row=row_index, \
                        column=column_index: \
                        self.button_clicked(row,column))
                button.grid(row=row_index, column=column_index)
                row.append(button)
            buttons.append(row)

        self.gomuko_buttons = buttons
        return frame.grid(row=0, column=0)
    except TypeError:
        return

Also, the function that executes when the button is pressed is the following:
def button_clicked(self,row,column) :
    global turns
    grid.Comp = False
    board.place_marker(row, column)
    button = self.gomuko_buttons[row][column]

    button['image'] = self.photo1
    button['state'] = 'disabled'
    turns = turns + 1

Any hint? :(
EDIT:
I solved it thanks to Bryan Oakley's response. Turns out the behaviour for width and height is different for images and text. I solved the problem by simply adding a blank image to the loop, like the following:
button = tkinter.Button(frame, height=0, \
                    width = 0, text = " ", image = self.blank, \
                    command=lambda row=row_index, \
                        column=column_index: \
                        self.button_clicked(row,column))

Thanks!

A: My guess is, you think  you are giving the button a width of 36 pixels, but you are actually giving it a width of 36 characters. In your callback I'm guessing you're giving the button an image, which causes the button to shrink.
In Tkinter, the width option is interpreted differently depending on whether the button has an image or text. If it has just text, it specifies a width in "average sized characters" (actually, the width of the 0 (zero). If you give the button an image, the width option is interpreted as pixels.
This behavior is documented. See, for example, http://effbot.org/tkinterbook/button.htm#Tkinter.Button.config-method


text:
Q: So more elements on page I have 600 elements on page. When all element is loaded page doesen't have lags but after
Element
 $.each(dishs, function(v, k){

                $.each(k.dishs, function(v, dish){

                    if( check_criterion(dish.criterion_first, dish.criterion_second) && dish.price >= default_settings.min && dish.price <= default_settings.max && dish.name.toLowerCase().indexOf( default_settings.search ) + 1 )
                        show = ' style="display: block;" ';
                    else
                        show = ' style="display: none;" ';

                html += '<form crit_2="' + dish.criterion_second + '" crit_1="' + dish.criterion_first + '" name="'+ dish.name +'" price="'+ dish.price +'" '+ show +' action="/order/" method="post" class="add_to_cart_close block col-md-4 col-sm-6 col-xs-12">';
                    html += '<input type="hidden" value="' + dish.id + '" />';

                    html += '
';
                        html += '
';

                            html += '
';
                            if(dish.criterion_first){
                                html += '
';
                                    html += '';
                                    html += '' + criterion_list["item" + dish.criterion_first ] + '';
                                html += '
';
                            }
                            if(dish.criterion_second){

                                html += '
';
                                    html += '';
                                    html += '' + criterion_list["item" + dish.criterion_second ] + '';
                                html += '
';
                            }
                            html += '
';
                            html += '
';

                            if(!dish.image) {

                                html += '

';

                            }  else {

                                html += '

';
                            }

                            html += '
';
                            html += '
';
                                html += '
';

                                    if(!dish.image_all.length) {

                                        html += '
';
                                        html += '';
                                        html += '
';

                                    }  else {

                                        $.each(dish.image_all, function(v, image ) {

                                            html += '
';
                                                html += '';
                                            html += '
';

                                        });

                                    }
                                html += '
';
                            html += '
';
                                        html += '
';
                                        html += '
' + dish.name + '
';

                                        if(dish.weight) {

                                            html += '
' + dish.weight + '
';

                                        }

                                        html += '
';
                                            html += dish.description;
                                        html += '
';
                                        html += '
';
                                            html += '
';
                                                html += '
' +  dish.price + ' a
';
                                            html += '
';
                                            html += '
';
                                            if(dish.supplements.length) {
                                                html += '<input data-toggle="modal" data-target="#modalPopup_' + dish.id + '"  type="submit" class="btn btn-default" value="ЗАКАЗАТЬ">';
                                            }  else {
                                                html += '<input dish_id="' + dish.id + '" shop_id="' + dish.shop_id + '"  type="submit" class="add_to_cart btn btn-default" value="ЗАКАЗАТЬ">';
                                            }
                                            html += '
';
                                        html += '
';
                                    html += '
';
                                html += '</form>';

                                html += '
';
                                  html += '
';
                                    html += '
';
                                      html += '
';
                                        html += '
';
                                            html += '';
                                            html += '
';
                                                html += '
';
                                                    $.each(dish.image_all, function(v, img){

                                                        html += '

';

                                                    });
                                                html += '
';
                                                html += '
';
                                                html += '
';
                                                    html += ' 4,8';
                                                    html += ' 3';
                                                    html += ' 5';
                                                html += '
';
                                                html += '
';
                                                    html += ' Блюдо без мяса';

                                                html += '
';
                                                html += '
';
                                            html += '
';
                                            html += '';

                                            html += '
';
                                                html += '
' +dish.name + '
';
                                                html += '
Вес '+ dish.weight + '
';
                                                html += '
';
                                                    html += '
';
                                                        html += dish.description;
                                                    html += '
';
                                                html += '
';

                                                if(dish.criterion_first || dish.criterion_second) {

                                                    html += '
Состав:';
                                                        if(dish.criterion_first) {
                                                            html += criterion_list[dish.criterion_first];
                                                        }
                                                        if(dish.criterion_second)
                                                        {
                                                            html += criterion_list[dish.criterion_second];
                                                        }
                                                    html += '
';

                                                }

                                                html += '
'

                                                    if(dish.supplements.length) {

                                                        html += '
';
                                                        html += '
Добавки:
';

                                                        $.each(dish.supplements, function(v, supp){

                                                            html += '
';
                                                            html += '<input price="'+ supp.price + '" class="supplement_price" value="'+ supp.id +'" type="checkbox">';
                                                            html += '';
                                                            html += '';
                                                            html += supp.name;
                                                            html += '';
                                                            html += '';
                                                            html += supp.price;
                                                            html += ' р.';
                                                            html += '';
                                                            html += '
';

                                                            });

                                                        html += '
';
                                                    }

                                                    html += '
';
                                                        html += '

';
                                                        html += '
';
                                                            html += '';
                                                            html += '
Цена:
';
                                                            html += '
';
                                                                html += '';
                                                                    html += dish.price;
                                                                html += '';
                                                                html += ' р.';
                                                                html += '<button shop_id="' + dish.shop_id + '" dish_id="' + dish.id + '" data-dismiss="modal" class="add_to_cart btn btn-btn-cart">Заказать</button>';
                                                            html += '
';

                                                            if($('#user').val()) {
                                                                var display = 'block';
                                                                if(dish.favsdish)   var display = 'none;';

                                                                var dis_fav = 'none';
                                                                if(dish.favsdish)   var display = 'block';

                                                                html += '

';
                                                                html += '
';
                                                                html += '<button dish_id="' + dish.id + '" style="margin-left: auto; cursor: pointer; display:' + display + ' " class="add_to_favs btn btn-btn-cart" >В избранное</button>';
                                                                html += '<button dish_id="' + dish.id + '" style="margin-left: auto; cursor: pointer; display: '+ dis_fav  +'" class="remove_from_favs btn btn-btn-cart" >Убрать из избранного</button>';
                                                                html += '
';
                                                            }

                                                        html += '
';
                                                    html += '
';
                                                html += '
';
                                            html += '
';
                                        html += '
';
                                html += '';
                                        html += '
';
                                            html += '
Мнение эксперта
';
                                            html += '
';
                                                html += '
';
                                                    html += '';
                                                    html += '
';
                                                        html += '
 4,9
';
                                                    html += '
';
                                                html += '
';
                                                html += '
';
                                                    html += '
Владислав Фенечкин, эксперт с 11 летним стажем
';
                                                    html += '
Очень тонко и необычно подобраны имена в прототипе. Очень тонко и необычно подобраны имена в прототипе. Очень тонко и необычно подобраны имена в прототипе.
';
                                                    html += '
Показать больше ответов экспертов
';
                                                html += '
';
                                            html += '
';
                                        html += '
';
                                        html += '
';
                                            html += '
Отзывы о блюде (7)
';

                                            html += '';
                                            html += '
';
                                                html += '
';
                                                    html += '';
                                                    html += '
';
                                                        html += '
 4,9
';
                                                    html += '
';
                                                html += '
';
                                                html += '
';
                                                    html += '
Владислав Фенечкин, эксперт с 11 летним стажем
';
                                                    html += '
Очень тонко и необычно подобраны имена в прототипе. Очень тонко и необычно подобраны имена в прототипе. Очень тонко и необычно подобраны имена в прототипе.
';
                                                html += '
';
                                            html += '
';
                                            html += '';

                                            html += '';
                                            html += '
';
                                                html += '
';
                                                    html += '';
                                                    html += '
';
                                                        html += '
 4,9
';
                                                    html += '
';
                                                html += '
';
                                                html += '
';
                                                    html += '
Владислав Фенечкин, эксперт с 11 летним стажем
';
                                                    html += '
Очень тонко и необычно подобраны имена в прототипе. Очень тонко и необычно подобраны имена в прототипе. Очень тонко и необычно подобраны имена в прототипе.
';
                                                html += '
';
                                            html += '
';
                                            html += '';

                                        html += '
';
                                      html += '
';
                                    html += '
';
                                  html += '
';
                                html += '
';

                });

                $('#menu_' + k.sm).next().html(html);
                html = '';
                check_visible_catalogs();
            });

I generate in from AJAX data: than i insert it on page
Got function Show and hide elements So: i try show and hide 600 elements
$('[id^="menu_"]').hide();
$('[id^="menu_"]').next().hide();

And Than:
$('[id^="menu_"]').show();
$('[id^="menu_"]').next().show();
$('[id^="menu_"]').next().children().show();

I Got so strong lags....
How i can fix that lags?

A: cildren() return not first level elements In 600 element i have `3200 childrens


text:
Q: Feature extraction using deep learning for more than one class I have a time series dataset and I want to extract its features using BRNN or CNN -RNN ( python programming language)
First, I train the model with the classification layer and obtain best accuracy.
Then, I want to take the features from one of model's hidden layer.
But I have 41 class how can I extract the features of all these classes and how I know the extracted features belong to which class?
Because I want each class with its extracted features to make some calculation later.

A: A lot of it depends on what you're doing. Generally, you'll want to try an autoencoder or a transformer and do unsupervised/semisupervised learning.
Here's some material that might give some insight into some methods.
https://arxiv.org/abs/2006.07733 (Bootstrap your own latent -- Deepmind)
https://arxiv.org/abs/1610.02242 (Temporal ensembling for semisupervised learning -- Timo Aina)
https://www.coursera.org/lecture/intro-to-deep-learning/autoencoders-101-QqBOa  (Autoencoder -- Andrew Ng)


text:
Q: Getting a SVC/SOAP webservice to a consumable state for force.com I'm wondering if there is a way for me to get a .Net - made web service into a state that Salesforce can recognize?  What I have to work with is a service that is made with Visual Studio and comes with the .svc ending, but as far as i can see it conforms to the SOAP standard.  But when I try to import it into my sandbox for testing i get the error that this WebService is referring to an external XSD source for the XML layout and Salesforce can't deal with that.  I'm not entirely sure what I can do to rectify this.  Can I use some flatting technology to embed the XSD into the svc file and then import it?  I have no control over this external service since it's a third party, and also authenticated.
This webservice would be called with an outbound message via a workflow on a custom object.
Are my options these?

*

*Make a seperate class that handles the logic for calling this external endpoint, including the login/auth process

*Create an Apex class that the workflow does a callout to, and the only thing that class handles is a callout to real logic code that would be the service above.  I don't see how else I can do since I need to authenticate to the external service also.

A: Your question seems to reference two ways of consuming Web Services, both are independent of each other. Outbound Workflow actions have very specific requirements that this service will likely not meet if its been designed independently. So using Outbound Workflow may not be possible, unless you go back to the service provider to change. Otherwise you can choose to attempt to consume the Web Service directly via Apex and Apex Triggers, this approach does not utilise Salesforce Workflow, as it cannot call Apex.
Here is a summary of both just in case.
Outbound Workflow messages must conform to a predefined (by Salesforce) definition. You cannot have such Workflow actions confirm arbitrary Web Services unfortunately. This help topic describes how to obtain the WSDL (Web Service Definition Langauge file). You then need to give that to your service provider or build the web service yourself. For example .Net's VisualStudio will consume the WSDL and generate some stub code to enable you to complete the implementation of the web service.
Consuming the WSDL and calling via Apex. There are a few approaches to getting the best out of the WSDL2Apex tool (accessed under Develop > Apex Classes > Generate from WSDL) to generate your Apex code. It has some feature gaps but also some reasonable workarounds as well.

*

*Review the 'Apex Callouts' section of this article and the formal docs here.

*Review and pay close attention to the supported features here, it's not neccessarly a stopper, depending on the unsupported feature you need. Since you can edit either the WSDL file and/or the Apex generated code to workaround some. Which is sometimes not ideal, if your WSDL is changing often. However maybe prefferable to manually constructing the SOAP messages as per the last option below, which is more fragile and involving.

*Review and pay close attention to the understanding of the generated Apex code here.

*Run the WSDL2Apex tool and editing the WSDL.
4.1 If you get errors such as XML Schema must be embedded.  Download the WSDL (add ?wsdl to the end of a .Net svc URL) and attempt to edit locally before giving it back to the WSDL2Apex tool.
4.2. Often you can edit the WSDL without breaking the contract (structure of the XML packets) it describes. Such as copying (or flattening) in the XSD xsd:schema root tag into the WSDL file body using the wsdl:types element. As shown in the W3C standards doc here.
4.3. Some unsupported data types can be changed to xsd:string. You must then ensure that your Apex code populating the generated member variables of the classes formats things according to the expected data type.

*Once you get the Apex code generated, you may find it still does not work, for example if xsd:extension is used in the schema. However you can modify the generated Apex code to resolve this. The notes here describe how this has been done for the Salesforce Metadata API, but the same approach applies.

*Finally, if you cannot get the WSDL2Apex tool approach to work, but you can get hold of sample of the SOAP XML being transmitted to the service. You can manually make the Web Service call out using the the XML and HTTP features of Apex. As described here.


text:
Q: Synchronize test runner with application under test I'm fixing custom test runner that use java.awt.Robot to manipulate applicaition under test.
After each simplest operation (mouse mote to some component, mouse click) I need test runner TO WAIT for application under test process the event. And ONLY AFTER this continue to check values, clicking some other buttons etc.
There is Robot.waitForIdle() function that could wait for event queue to become empty.
But I still have problems with synchronisation due to early checking values (let suppose values that is not calculated in some background threads but very EDT thread).
My guess this is due to Robot is not putting event to event queue directly but this is favour of underlying OS to put new event generated by Robot to JVM event queue.  And this native calls is asynchronous, means putting new event to event queue is not performed by any of JVM threads not like SwingUtilities.invokeLater() does.
Is it posible to implement some hook to determine or to wait for underlying OS put new event to event queue?
Am I missing anything?
Thanks.

A: SunToolkit#realSync()


text:
Q: What area does the antiderivative represent? Consider the antiderivative of the function $e^{-x},$ which is $-e^{-x}.$ Evaluating the antiderivative at the value $0$ produces $-1.$
I was taught to conceptualize an antiderivative as an area under a curve, or a sum of progressively smaller approximate sections.
But clearly, $-1$ cannot represent the area under under the $e^{-x}$ curve from $0$ to $0$, $0$ to $\infty$, or $-\infty$ to $0$ when you consider that the function is positive for all values of $x$.
Then what sum or area does the value of the antiderivative of $e^{-x}$ actually represent?

A:
Evaluating the antiderivative at the value $0$ produces $-1$. Now, I was taught to conceptualize an antiderivative as an area under a curve

*

*For $t>a,$ the signed area (i.e., the area in the positive vertical region minus the area in the negative vertical region) $A(t)$ enclosed by the curve $y=f(x),$ the $x$-axis, and the vertical lines at $a$ and $t$ is denoted by the (definite) integral $$\int_a^tf(x)\,\mathrm dx,$$ whose elongated-S symbol stands for Sum (of areas).

*If $f$ is continuous on $[a,t],$ then the Fundamental Theorem of Calculus says that this integral is computable using the formula $$\int_a^tf(x)\,\mathrm dx=F(t)-F(a),\tag1$$ where $F$ is an antiderivative of $f,$ that is, any of the infinitely many functions whose derivative (slope function) is $f.$ Therefore, if $f$ is continuous on $[a,t],$ then $$\frac{\mathrm d}{\mathrm dt}\int_a^tf(x)\,\mathrm dx=f(t).\tag2$$ Rewriting $(1):$ if $F$ is continuously differentiable on $[a,t],$ then $$\int_a^t\frac{\mathrm d}{\mathrm dx}F(x)\,\mathrm dx=F(t)-F(a).\tag1$$

*The indefinite integral $$\int f(x)\,\mathrm dx$$ represents every antiderivative of $f,$ if any. For example, \begin{align}\int \frac1x\,\mathrm dx &= \begin{cases} \ln|x|+C_1, &x<0;\\
    \ln|x|+C_2, &x>0.\end{cases}\end{align}
Conceptually, an indefinite integral is not technically the precursor of a definite integral: for example,
for \begin{align}g(x)&= \begin{cases} 2x\sin\frac1{x^3}-\frac3{x^2}\cos\frac1{x^3}, &x\ne0;\\
    0, &x=0,\end{cases}\end{align} $\displaystyle\int_{-1}^1 g(x)\,\mathrm dx$ does not exist even as \begin{align}\int g(x)\,\mathrm dx&= \begin{cases} x^2\sin\frac1{x^3}&+C, &x\ne0;\\
    0&+C, &x=0,\end{cases}\end{align} that is, even as $g$ does have antiderivatives on $[-1,1].$

*Since antidifferentiation and indefinite integration literally reverse differentiation, they are pointwise operations.
On the other hand, definite integration is a computation with reference to some interval.
The Fundamental Theorem of Calculus ($(1)$ & $(2)$ above) shows the surprising intimate relationship between definite integration and differentiation.

*An antiderivative per se does not describe area, and $F_λ(0)=-1$ means that a particular function whose slope is given by $f$ passes through $(0,-1).$
Clearly, a single value of an antiderivative is not useful information; the FTC's power comes from making its two evaluations using the same antiderivative of $f:$ $$\int_a^tf(x)\,\mathrm dx=F_λ(t)-F_λ(a)\\\neq F_λ(t)-F_ω(a).$$

*A pertinent comment by B. Sullivan:

I just finished reading Steven Strogatz's new book about calculus, Infinite Powers. In it, he lays out the "Three Central Problems of Calculus":

*

*Given a curve, find its slope everywhere. [differentiation]

*Given a curve, find another curve whose slope everywhere is that given curve. [antidifferentiation]

*Given a curve, find the area under it. [(definite) integration]

*The actual area enclosed by $y=f(x),$ the $x$-axis, and
the vertical lines at $a$ and $t$ is $$\int_a^t|f(x)|\,\mathrm dx,$$ which does not generally equal $F(t)-F(a).$


text:
Q: Interchanging differentiation and expectation I have a nonnegative random variable $X$ with $E[X] < \infty$, that admits a density wrt to the Lebesgue measure. For arbitrary $K > 0$, I write
$$P(K) = E[\max(X-K,0)]$$
I am interested in the function $K \mapsto P(K)$. My first question is

Under what conditions is $P$ twice differentiable?

My second question is assuming that it exists,

What is $\frac{\partial^2 P}{\partial K^2}$?

With some handwaving I can "show" that $\frac{\partial^2 P}{\partial K^2} = f_{X}(K)$ where $f_X(K)$ is the density of $X$ evaluated at $K$. I reason as follows.
\begin{align}
\frac{\partial^2 P}{\partial K^2} &= \lim_{h\to 0}\frac{P(K+h) - 2P(K) + P(K-h)}{h^2} \\
&= \lim_{h\to 0}\frac{E[\max(X-(K+h),0) - 2\max(X-K,0) + \max(X-(K-h),0)]}{h^2}\\
&\stackrel{(1)}{=}E\left[\lim_{h\to 0}\frac{\max(X-(K+h),0) - 2\max(X-K),0) + \max(X-(K-h),0)}{h^2}\right]\\
&\stackrel{(2)}{=}E\left[\delta_{K}(X)\right]\\
&\stackrel{(3)}{=}f_X(K)
\end{align}
$\delta_K(X) := \delta(X-K)$ denotes the Dirac delta function above.
Things that require justification (as far as I can tell) are the numbered equalities above.
$(1)$ is clear. Some kind of dominated convergence must be invoked here. I did not think about this step in depth to be honest.
$(2)$ is bizarre, to say the least, but my reasoning is there is that the function inside the limit is an isosceles triangle with base $2h$ and height $1/h$ for every $h > 0$. It always integrates to $1$ and is zero outside the interval$[K-h,K+h]$. So as $h \to 0$ it "should" converge to the Dirac delta function in some sense.
$(3)$ is probably justified. Since $X$ admits a density,
$$E\left[\delta_{K}(X)\right] = \int\delta_{K}(x)f_X(x)dx = f_X(K)$$
I see no issue here but I am not absolutely certain either.
I would very much appreciate it if someone could give me hints/pointers as to what needs to be done to make all the arguments here fully precise.

A: Let $\mu$ be the CDF of $X$. Then
$$
P(K)=\mathbb{E}\left(X-K\right)^+=\int_{\mathbb{R}}\left(x-K\right)^+{\rm d}\mu=\int_K^{\infty}\left(x-K\right){\rm d}\mu=\int_K^{\infty}x{\rm d}\mu-K\left(1-\mu(K)\right),
$$
or more clearly,
$$
P(K)=K\mu(K)+\mathbb{E}X-K-e(K),
$$
where
$$
e(K)=\int_0^Kx{\rm d}\mu,
$$
and obviously, $e(\infty)=\mathbb{E}X$.
Thanks to this result, if $\mu$ yields a PDF $f$, i.e., ${\rm d}\mu(x)=f(x){\rm d}x$, then
$$
P'(K)=\mu(K)+Kf(K)-1-Kf(K)=\mu(K)-1,
$$
and thus
$$
P''(K)=f(K).
$$

A: Use the identity $\int_{k}^x1\,dt=x-k$, then change the order of integration:
$$
\begin{align}
P(k)
&=\int_{k}^\infty (x-k)f_X(x)\,dx
\\&=\int_{k}^\infty\left(\int_{k}^x1\,dt\right)\,f_X(x)\,dx
\\&=\int_k^\infty\int_t^\infty f_X(x)\,dx\,dt
\\&=\int_k^\infty \mathbb P(X\ge t)\,dt=\int_k^\infty1-F_X(t)\,dt
\end{align}
$$
Now, using the fundamental theorem of calculus, $P'(k)=-(1-F_X(k))$, and using the fact $X$ has a density $f_X=F_X'$, $P''(k)=f_X(k)$.


text:
Q: Display bitmap in textview I am trying to display bitmap in textview. Below code shows the bitmap in the textview using R.drawable.bitmap_name. How can I pass a bitmap in SpannableStringBuilder? Thanks
 SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append(text).append(" ");
            builder.setSpan(new ImageSpan(MyActivity.this, R.drawable.image_1 ), builder.length() - 1, builder.length(), 0);
            myTv.setText(builder);

A: For instance like this:
builder.setSpan(new ImageSpan(yourBitmap), builder.length() - 1, builder.length(), 0);

ImageSpan has following constructors:
new ImageSpan(Bitmap b)
new ImageSpan(Bitmap b, int verticalAlignment)
new ImageSpan(Context context, Bitmap b)
new ImageSpan(Context context, Bitmap b, int verticalAlignment)


text:
Q: Could not load file or assembly Microsoft.SqlServer.SqlClrProvider on production ASP.net site, where is it? On my ASP.net site I have a reference to Microsoft.SQLserver.SMO. I copied this reference onto my production server and got a could not load error for Microsoft.SqlServer.Management.Sdk.Sfc. This error was fixed by copying the dll from the
C:\Program files\Microsoft Sql Server\110\SDK\Assembilies

However I then got the same error but for Microsoft.SqlServer.SqlClrProvider which is nowhere to be found.
Where can I find the SqlClrProvider dll? It works on my localhost so it must be somewhere.

A: I wanted to make an embedded script in powershell and stumble upon your same problem.
The thing is that Microsoft.SqlServer.SqlClrProvider.dll is not installed in SQL files but in windows assembly.
Assembly folder is special: you can't copy anything with windows UI.
I just needed the Microsoft.SqlServer.SqlClrProvider.dll so that I can load it in my script like that:
[System.Reflection.Assembly]::LoadFile($scriptPath+"dll\Microsoft.SqlServer.SqlClrProvider.dll") | out-null

to copy it you can do the following:
c:\>cd c:\Windows\assembly
c:\Windows\assembly>dir /s Microsoft.SqlServer.SqlClrProvider.dll
# here you get the directory and the file
c:\Windows\assembly>copy c:\Windows\assembly\GAC_MSIL\Microsoft.SqlServer.SqlClrProvider\<version>\Microsoft.SqlServer.SqlClrProvider.dll c:\Users\Administrator\Desktop\

you want to do that on a machine with SQLserver installed otherwise you may not find it.
It's just a workaround. I guess it's not the best thing to do if you need to execute your script in different environments.
hth

A: Copying SqlClrProvider dll into sqlserver Binn directory didn't help in my case.
Cause:
It was cause by using different versions of SQLServer on production machine and target machine.
Solution:
Make sure you are using the same version of SMO libraries as you have on the target machines. If there is SQLServer2008 on the target machine you must use v10 libraries otherwise you would get this error.
MoreDetails:
SqlServer on my target machines was version 2008 (10) and I had SqlServer2014 (12) on my own machine. When I used SMO library visualstudio added v12 libraries (Microsoft.SqlServer.SMO, ...) but smo is just a shell which use SqlClrProvider and it expects to have SqlClrProvider of same version on system assemblies. this caused the application to crash on the target machine since the v12 of SqlClrProvider didn't exist. By using v10 smo libraries I solved the problem

A: Had the same issue but for version 11. To get the right assemblies installed a did the following steps:

*

*Check what version is expected: https://sqlserverbuilds.blogspot.com/. Version 11 => sql server 2012

*Download Microsoft's web platform installer and install it

*Search for 'sql server 2012' and install one or all of the following:

A: The first thing you need to do is disable the GAC Shell extension which allows you to browse the GAC, to do this:

*

*Open "regedit"

*Navigate to
HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Fusion

*Add a new DWORD or 32
bit DWORD named DisableCacheViewer with the Hex value of 0x1 or a
decimal value of 1

That disables the GAC Shell allowing you to fully browse assembly folder, now we can extract the assembly from the GAC and drop it into the bin folder or the dll location on the client machine.

*

*Go to C:\Windows\assembly\GAC_MSIL\Microsoft.SqlServer.SqlClrProvider\

*You may notice more than folder here, this is for each version of SQL server you have installed

*For SQL 2012 it will be : \11.0.0.0__89845dcd8080cc91

*You will then find the file Microsoft.SqlServer.SqlClrProvider.dll

Reference

A: On your development machine or a machine where you have SQL Server installed, the Microsoft.SqlServer.SqlClrProvider.dll file is in your GAC. However, you cannot copy this file without making changes to the registry.
Using the registry editor, go to HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Fusion. Add a new DWORD called DisableCacheViewer. Give it a value of 1.
Once this change is made, you can go to C:\Windows\assembly\GAC_MSIL\Microsoft.SqlServer.SqlClrProvider\ to get the dll you need.
To see a more detailed explanation, follow one of these links:

*

*HOW TO RESOLVE "SQLCLRPROVIDER NOT FOUND" WITHOUT INSTALLING SQL SERVER ON THE CLIENT MACHINE OR NEEDING A DEPLOYMENT PROJECT

*Could not load file or assembly Microsoft.SqlServer.SqlClrProvider

A: I could not solve my issue, while using Microsoft.Sqlerver.SMO reference. So I instead used the System.Data.Sql.SqlDataSourceEnumerator class for all my Sql functionality needs.

A: For people googling this error, and arriving here, there is another possibility.  Go into Services, and make sure that your SQL Server process can run.  On my machine, the password for the user account had changed.  Once I fixed the password, the process started, and I no longer received the above error.


text:
Q: How do I target a specific project with a non-unique name when using the Package Manager (nuget)? I know about '-project' but what if I have multiple projects in my solution that have the same name? They're in different folders.

A: Use: Scaffold Controller FolderName\ProjectName
Also if you look in the Package Manager Console there is the dropdown for Default Project. If you click the dropdown you can see what each of your project names would be.


text:
Q: C# RTF to plain text with RichTextBox not working We use external component (MigraDoc) to compose an RTF document. Which then is converted to plain text by assigning RTF as string to System.Windows.Forms.RichTextBox's Rtf field and reading Text field. This has worked earlier but now we have found a problem (which has been there for a while already).
Plain text conversion is not working on Windows 10 but same application is working on Windows 7. After assigning Rft field, the Text field remains empty and also Rft field doesn't have the value which was just assigned. *
However, earlier version of our application is working on Windows 10 as well. Even there are no direct constitutive changes on this area. One possibly affecting change is .Net target version change from 4.0 to 4.7.2 (but it is hard to verify this anymore).
If I take the RTF string from Windows 7 and save it as file, it opens on WordPad on Windows 7. But it doesn't open on WordPad on Windows 10.
Have somebody else phased similar issues? Or are there any ideas how this could be fixed?

* But instead value:
{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}
{\*\generator Riched20 10.0.19041}\viewkind4\uc1
\pard\f0\fs17\par
}

EDIT:
MigraDoc version is 1.32 i.e. the latest non-beta.

A: If you want to try out the RICHEDIT20W version of RichEdit Control (Rich Text Edit Control v. 3.1), use a Custom Control built like this one. It tries to load the riched20.dll library and, if it succeeds, it then sets the Class name of the Control in the CreateParams override.
You could also try to load the RICHEDIT60W version that is usually shipped with MS Office installations, for testing. This version has also different behavior.
In this case, you have to provide the full path of the library, which depends on the installed Office version and bitness
In practice, you have means to use a specific version of the Control.
Tweak this code to make it act as you prefer. As it is, it allows to switch between ver. RICHEDIT20W and RICHEDIT50W (design-time or run-time)
using System.ComponentModel;
using System.Runtime.InteropServices;

public class RichTextBox20W : RichTextBox {
    private bool m_UseRichedit20 = true;

    public RichTextBox20W() {
         IsRichEdit20Available = LoadLibrary("riched20.dll") != IntPtr.Zero;
    }

    [DefaultValue(true)]
    public bool UseRichedit20 {
        get => m_UseRichedit20 & IsRichEdit20Available;
        set {
            if (value != m_UseRichedit20) {
                m_UseRichedit20 = value;
                RecreateHandle();
            }
        }
    }

    public bool IsRichEdit20Available { get; }

    protected override CreateParams CreateParams {
        get {
            var cp = base.CreateParams;
            if (UseRichedit20) {
                cp.ClassName = "RICHEDIT20W";
            }
            // If the library is not found, the class name is set to RICHEDIT50W
            // which is the default when targeting .NET Framework 4.7.2+
            return cp;
        }
    }

    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    static extern IntPtr LoadLibrary(string lpLibFileName);
}


text:
Q: ServletWrapper uncaught exception after upgrade to WAS 8 Upgraded from RAD 7.5 > RAD 8.5 & WAS 7 > WAS 8. Made jar & JRE reference changes, got past all the hard compile/build errors and am able to start the server w/o error and am able to get to my app's 1st page. Upon entry of some fields and clicking submit, I get the error - any ideas?
ServletWrappe E com.ibm.ws.webcontainer.servlet.ServletWrapper service Uncaught service() exception thrown by servlet action: java.lang.AbstractMethodError: org/w3c/dom/Node.lookupNamespaceURI(Ljava/lang/String;)Ljava/lang/String;
at org.apache.ws.commons.schema.utils.NodeNamespaceContext.getNamespaceURIDomLevel3(NodeNamespaceContext.java:92)
at org.apache.ws.commons.schema.utils.NodeNamespaceContext.getNamespaceURI(NodeNamespaceContext.java:84)
at org.apache.ws.commons.schema.SchemaBuilder.getRefQName(SchemaBuilder.java:570)
at org.apache.ws.commons.schema.SchemaBuilder.handleSimpleContentExtension(SchemaBuilder.java:825)
at org.apache.ws.commons.schema.SchemaBuilder.handleSimpleContent(SchemaBuilder.java:735)
at org.apache.ws.commons.schema.SchemaBuilder.handleComplexType(SchemaBuilder.java:670)
at org.apache.ws.commons.schema.SchemaBuilder.handleXmlSchemaElement(SchemaBuilder.java:205)
at org.apache.ws.commons.schema.SchemaBuilder.build(SchemaBuilder.java:121)
at org.apache.ws.commons.schema.XmlSchemaCollection.read(XmlSchemaCollection.java:512)
at org.apache.ws.commons.schema.XmlSchemaCollection.read(XmlSchemaCollection.java:385)
at org.apache.ws.commons.schema.SchemaBuilder.resolveXmlSchema(SchemaBuilder.java:1892)
at org.apache.ws.commons.schema.SchemaBuilder.handleImport(SchemaBuilder.java:1606)
at org.apache.ws.commons.schema.SchemaBuilder.handleXmlSchemaElement(SchemaBuilder.java:224)
at org.apache.ws.commons.schema.SchemaBuilder.build(SchemaBuilder.java:121)
at org.apache.ws.commons.schema.XmlSchemaCollection.read(XmlSchemaCollection.java:512)
at org.apache.ws.commons.schema.XmlSchemaCollection.read(XmlSchemaCollection.java:385)
at org.apache.ws.commons.schema.SchemaBuilder.resolveXmlSchema(SchemaBuilder.java:1892)
at org.apache.ws.commons.schema.SchemaBuilder.resolveXmlSchema(SchemaBuilder.java:1921)
at org.apache.ws.commons.schema.SchemaBuilder.handleInclude(SchemaBuilder.java:1647)
at org.apache.ws.commons.schema.SchemaBuilder.handleXmlSchemaElement(SchemaBuilder.java:219)
at org.apache.ws.commons.schema.XmlSchemaCollection.read(XmlSchemaCollection.java:481)
at org.apache.axis2.description.WSDLToAxisServiceBuilder$1.run(WSDLToAxisServiceBuilder.java:148)
at org.apache.axis2.description.WSDLToAxisServiceBuilder$1.run(WSDLToAxisServiceBuilder.java:146)
at org.apache.axis2.java.security.AccessController.doPrivileged(AccessController.java:76)
at org.apache.axis2.description.WSDLToAxisServiceBuilder.getXMLSchema(WSDLToAxisServiceBuilder.java:145)
at org.apache.axis2.description.WSDL11ToAxisServiceBuilder.copyExtensibleElements(WSDL11ToAxisServiceBuilder.java:2492)
at org.apache.axis2.description.WSDL11ToAxisServiceBuilder.processTypes(WSDL11ToAxisServiceBuilder.java:420)
at org.apache.axis2.description.WSDL11ToAxisServiceBuilder.processTypes(WSDL11ToAxisServiceBuilder.java:409)
at org.apache.axis2.description.WSDL11ToAxisServiceBuilder.populateService(WSDL11ToAxisServiceBuilder.java:349)
at org.apache.axis2.jaxws.description.impl.EndpointDescriptionImpl.buildAxisServiceFromWSDL(EndpointDescriptionImpl.java:977)
at org.apache.axis2.jaxws.description.impl.EndpointDescriptionImpl.setupAxisService(EndpointDescriptionImpl.java:776)
at org.apache.axis2.jaxws.description.impl.EndpointDescriptionImpl.<init>(EndpointDescriptionImpl.java:275)
at org.apache.axis2.jaxws.description.impl.EndpointDescriptionImpl.<init>(EndpointDescriptionImpl.java:223)
at org.apache.axis2.jaxws.description.impl.ServiceDescriptionImpl.updateEndpointDescription(ServiceDescriptionImpl.java:534)
at org.apache.axis2.jaxws.description.impl.DescriptionFactoryImpl.updateEndpoint(DescriptionFactoryImpl.java:382)
at org.apache.axis2.jaxws.description.DescriptionFactory.updateEndpoint(DescriptionFactory.java:180)
at org.apache.axis2.jaxws.spi.ServiceDelegate.getPort(ServiceDelegate.java:597)
at org.apache.axis2.jaxws.spi.ServiceDelegate.getPort(ServiceDelegate.java:513)
at javax.xml.ws.Service.getPort(Service.java:99)
at com.usbank.soa.basecustomerservice_v_3_0.BaseCustomerService.getBaseCustomerServiceSOAP(BaseCustomerService.java:52)
at com.usbank.soa.basecustomerservice_v_3_0.BaseCustomerServiceRequest.sendRequest(BaseCustomerServiceRequest.java:38)
at com.usb.emailpref.action.emailaction.execute(emailaction.java:178)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:595)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1235)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:779)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:478)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1071)
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3815)
at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:981)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:453)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:515)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:306)
at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:84)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1702)

Because of various posts around the internet that talked about removing SAXParser* classes found in jaxp_1.1.1.jar (as those parsers are in the base WAS 8.5 jars), I removed them. But it still hasn't remedied the problem. As I walked thru my code, the error was being thrown when sending the SOAP message so it's entirely possible it is related to a parsing issue.
Does any one have additional thoughts on this?

A: I ultimately found that I needed to remove crimson_1.1.1.jar, xmlparser_3.3.02.jar, and xercesImpl-2.8.0.jar from the included jars. I also had to remove the parsers folder from jaxp_1.1.1.jar. These jars have since been superseded/replaced in the newer WAS v8.5 standard jars in which the XML formatting method interfaces (these methods at a minimum) have been altered causing the implementation to change. Same notation in the removal of parsers folder from jaxp_1.1.1.jar. Once removed, the error disappeared and my app now works in RAD 8.5 & WAS 8.5.5.5.
By the by since this is SOAP/WSDL/XML related, if you happen to encounter the following error - "CWPOL0040E: The client cannot establish how policy is configured for the service {http://soa.usbank.com/BaseCustomerService_V_3_0}BaseCustomerService because while processing the WSDL document attached to the service the following exception occurred com.ibm.ws.wspolicy.UnsupportedNamespaceException", you'll need to add the argument - " -Dcom.ibm.ws.wspolicy.ignoreWSP12inPackagedWSDL=true" (there's a prefacing space before the hyphen) to the Generic JVM argument list. This error doesn't always happen but did in my case.

A: Super old thread, but just wanted to add another perspective as I fought this same issue. For me, the crimson dependency was the primary culprit. After moving to WAS 8.5 and Java 8, I removed the following:

*

*crimson

*jaxp-api

*xml-apis (ensuring no transitive dependency)

*xercesImpl

*note: did not have a jaxp implementation jar to begin with


text:
Q: Dealing with BTRFS ref/backpointer mismatches, backref missing A btrfs filesystem reported some errors during btrfs receive operation due to some missing extends. From the log:
BTRFS error (device dm-1): unable to find ref byte nr 190303420416 \
      parent 0 root 594  owner 1 offset 0
BTRFS: error (device dm-1) in __btrfs_free_extent:6944: errno=-2 No such entry
BTRFS info (device dm-1): forced readonly
BTRFS: error (device dm-1) in btrfs_run_delayed_refs:2956: errno=-2 No such entry

A btrfs scrub (after a umount + mount) failed with similar errors.
A btrfs check reports issues for 3 extends - each extend issue is reported like this:
checking extents
ref mismatch on [190303420416 16384] extent item 0, found 1
Backref 190303420416 parent 594 root 594 not found in extent tree
backpointer mismatch on [190303420416 16384]
owner ref check failed [190303420416 16384]

My question is: how can I translate those numbers to something useful? For example to check if some files/directories are impacted?
And how to deal with such errors?
A btrfs check --repair seems to work without complaining severely:
  ref mismatch on [190303420416 16384] extent item 0, found 1
* repair deleting extent record: key 190303420416 169 1
* adding new tree backref on start 190303420416 len 16384 parent 0 root 594
  Backref 190303420416 parent 594 root 594 not found in extent tree
  backpointer mismatch on [190303420416 16384]
  owner ref check failed [190303420416 16384]

(the * marks are mine)
Does this mean that the repair was successful without loosing any data?

A: A successful btrfs check --repair command doesn't necessarily yield a consistent btrfs filesystem.
In one case I observed that a btrfs scrub after  btrfs check triggered several WARN_ON() tests in fs/btrfs/extent-tree.c. And receiving snapshot yielded an IO failure (which forced a readonly remount).
Thus, since the runtimes of a btrfs check, followed by a btrfs check --repair and a btrfs scrub can be quite significant - and those actions have uncertain outcomes: a practical alternative is to just re-create the btrfs filesystem and restore a backup.
2021-12-14 Followup: FWIW, these errors were caused by a faulty/low-quality USB hub (vendor string: 'Genesys Logic, Inc.'). After directly attaching the USB disk drives those errors never appeared again. Before that, such errors appeared every few months or so when daily sending snapshots to an external USB drive. I even had another Genesys USB Hub around (differently labeled though) which I tried, but it yielded a similar error pattern.


text:
Q: Put an item containing a Map with multiple type Objects into DynamoDB I have modeled an item class with @DynamoDbBean which has a Map<String, Object> as one of its instance variables.
I am trying to put this item into a table, but the Object obviously needs a converter. The problem is, in my case, the Object type should be able to be either be a String, Number, or Boolean.
I am assuming an AttributeConverter is necessary, but I would only be able to transformTo and transformFrom one set type.
Map example for clarity:
Map<String, Object> mapOfMultipleTypes = Map.of(
              "StringObjectKey", "StringValue",
              "BooleanObjectKey", true,
              "NumberObjectKey", 1
       );

Is there any way of doing this?
Edit:
For those of you having a similar problem, this functionality is currently not available in Java SDK V2.
https://github.com/aws/aws-sdk-java-v2/discussions/3344#discussioncomment-3340248


text:
Q: In C#, is it right approach to use BackgroundWorker when you want to split UI from other logic? I'm currently learning C#, implementing a project with Visual Studio Community. I want it clean and appropriately organized from the start, so, as a general rule, I try not to mix the UI code with the underlying logic; also, I'd like specific parts the code to be used across the whole project.
Hence I made a class populationIdParserWorker in a separate file than the respective UI element, PopulationIdParser. It worked just fine, until I came up with an idea to add a progress bar to the UI. I learned that to make it actually show the progress, I can use BackgroundWorker to introduce the necessary multi-threading. I've been doing some research on how to use it, but I only found such examples, where the actual logic was done inside the UI code, which doesn't seem appropriate to me in terms of bigger projects. So I came up with the idea to pass my worker_DoWork method's arguments to the actual logic, located in populationIdParserWorker class' method process_file_lite. Is it a good practice or should it be done another way? How else can I do it?
Side note: The thing isn't working quite the way it is supposed to, because the progress bar is reaching some point and then the UI holds for a moment, only for the bar to jump to the end immediately. I'm not sure if it has something to do with my method of passing the arguments as a reference - I'm going to check it soon. I'm not convinced yet, because the bar freezes just after all true work has been done, i.e. the remaining lines of the file are meaningless, so they are being read and skipped.
Here are the pieces of code:
From PopulationIdParser.xaml.cs:
private void GenerateFiles_Click(object sender, RoutedEventArgs e)
        {
            ParsingStatus.Value = 0;
            parsingStatusBarPassing.set_all(Convert.ToInt32(ParsingStatus.Minimum), Convert.ToInt32(ParsingStatus.Maximum),
                new IntWithPercentScale(ParsingStatus.Value, ParsingStatus.Maximum));
            parserPathsArgs.set_all(parsingStatusBarPassing,
                SaveBrowser.Text, UsedBrowser.Text, FreeBrowser.Text, default_profs_name);

            BackgroundWorker worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.DoWork += worker_DoWork;
            worker.ProgressChanged += worker_ProgressChanged;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            worker.RunWorkerAsync(parserPathsArgs);
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            populationIdParserWorker.process_file_lite(ref sender, ref e);
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ParsingStatus.Value = e.ProgressPercentage;
            if(e.UserState != null)
            {
                ParsingPercentage.Text = (e.UserState).ToString() + "%";
            }
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("Done.");
        }

From PopulationIdParserWorker.cs:
public void process_file_lite(ref object sender, ref DoWorkEventArgs e)
        {
        ///A file is opened here, some pre-processing is done
            while ((line = file.ReadLine()) != null)
                {
                    ///Parsing is done here
                    parsingProgress = Convert.ToInt32(((double)i / flen) * parsingStatusBar.maximum);
                    parsingProgressPercentage = Convert.ToInt32(parsingProgress / parsingStatusBar.value.get_scale());
                    (sender as BackgroundWorker).ReportProgress(parsingProgress, parsingProgressPercentage);
                    i++;
                }
        }

In PopulationIdParser.xaml.cs: ParsingStatus is the progress bar; parsingStatusBarPassing and parserPathsArgs are utility objects used to store the data to be passed between different classes, UIs, threads etc.
In PopulationIdParserWorker.cs: 'flen' is the lines count of the processed file and parsingStatusBar is an object to store information about the progress bar showing the parsing status.

A: In general, BackgroundWorker is a pretty old and complicated thing. I suggest Task and async/await approach. And maybe IProgress interface + Progress class for callbacks reporting progress.
Let's assume that ParsingStatus is ProgressBar and ParsingPercentage is TextBlock.
IProgress<int> Percentage; // progress callback

// pay attention to 'async' here
private async void GenerateFiles_Click(object sender, RoutedEventArgs e)
{
    Percentage = new Progress<int>(ReportProgress); // assign callback, you may move this to constructor

    int progress = 0;
    int maximum = (int)ParsingStatus.Maximum;
    Percentage?.Report(progress); // report progress

    FileStream fs = File.OpenRead("file.txt");
    long position = 0;
    long length = fs.Length;
    using (StreamReader sr = new StreamReader(fs))
    {
        while (!sr.EndOfStream)
        {
            string line = await sr.ReadLineAsync(); // read file asynchronously
            string result = await ParseLine(line); // call parser
            // save parsed result here

            position += line.Length + Environment.NewLine.Length; // count position
            progress = (int)(position * maximum / length); // calculate progress
            Percentage?.Report(progress); // report progress

            await Task.Delay(50); // just a delay for example.
                                  // never Thread.Sleep() in async methods!
        }
    }
    fs.Close();
}

private async Task<string> ParseLine(string line)
{
    string result = "";
    // do job here with 'line'
    return result;
}

private void ReportProgress(int value)
{
    ParsingStatus.Value = value;
    ParsingPercentage.Text = value + "%";
}

The key feature of IProgress is passing callback execution to the Thread where it was created.
About splitting UI and other App logiс you may use MVVM programming pattern.