text:
Q: Ggplot error : haven_labelled/vctrs_vctr/double I am new here and still studying R so I am dealing with an error.
Here is what I get from console

Don't know how to automatically pick scale for object of type haven_labelled/vctrs_vctr/double. Defaulting to continuous.

I don't know what can I do to make it work. I want to get a scatterplot.
ggplot(data = diagnoza, aes(x = Plecc, y = P32.01))

Don't know how to automatically pick scale for object of type haven_labelled/vctrs_vctr/double. Defaulting to continuous.

A: Adding geom_point as suggested by @zx8754 gives me a scatter plot. There is still the warning you reported which is related to some of your variables being of type haven_labelled, so I guess you imported your data from SPSS.
To get rid of this warning you could convert your variables to R factors using haven::as_factor. Probably it would be best to do that for the whole dataset after importing your data.
diagnoza <- structure(list(Plecc = c(2, 2, 2, 1, 2, 1, 1, 1, 2, 2, 1, 2,
                                     1, 1, 1, 1, 2, 1, 1, 2), P32.01 = structure(c(3, 4, 5, 5, 5,
                                                                                5, 5, 4, 3, 5, 3, 4, 3, 4, 5, 5, 5, 3, 4, 5), label = "P32.01. odpoczynek w domu (oglądanie TV)", format.spss = "F1.0", display_width = 12L, labels = c(Nigdy = 1,
                                                                                Rzadko = 2, `Od czasu do czasu` = 3, Często = 4, `Bardzo często` = 5
                                                                                ), class = c("haven_labelled", "vctrs_vctr", "double"))), row.names = c(NA,
                                                                                -20L), class = c("tbl_df", "tbl", "data.frame"))

library(haven)
library(ggplot2)

# Convert labelled vector to a factor
diagnoza$P32.01 <- haven::as_factor(diagnoza$P32.01)

ggplot(data = diagnoza, aes(x = Plecc, y = P32.01)) +
  geom_point()


text:
Q: VBA to find specific text in word doc and copy this text from word doc into a cell in excel Hello stackoverflow community.
What I'm doing until now, is I manually copy a price from the word document, which I previously open, and paste it into an Excel sheet.
It is the only .docx file opened at the time on computer, so we just need to find the price in currently opened word file.
I'd like U to help me automate this task.
This picture shows the part of the document from where I copy the price.
In this example it's 605.000. But I don't know the price before I check it in the word file.
The word file is a place where I learn what the price is.

The selected text occurs only once in the whole document therefore I need VBA to copy what's after "brutto w kwocie " and up to the first coma.
Yes - only the amount of money without decimal values, because they're always ,00.
But not only seven signs, because if I had apartment price 1.250.000 then the macro that copies only 7 signs wouldn't work.
Sub Find_Price()
    'Variables declaration
    Dim WordApp As Word.Application
    Dim WordDoc As Word.Document
    Dim TextToFind As String
    Dim ApartmentPrice As String
    Dim Rng As Word.Range
    Application.ScreenUpdating = False
    'This is the text I'm looking for in .ActiveDocument
    TextToFind = "brutto w kwocie "
    'Start Word and create an object
    'Set WordApp = CreateObject("Word.Application")
    'Reference already opened Word document from excel VBA console
    Set WordApp = GetObject(, "Word.Application")
    WordApp.Application.Visible = True
    Set Rng = WordApp.ActiveDocument.Content
    'Set WordDoc = WordApp.ActiveDocument   'I don't know how to finish this line

        Rng.Find.Execute FindText:=TextToFind, Forward:=True
                'what this "Forward:=True" means??
        If Rng.Find.Found Then
            If Rng.Information(wdWithInTable) Then
              'I don't know how to write this part of the code.
              'Please don't remove my question again - I've researched 16h for this info.
              MsgBox "Price is " & ApartmentPrice & " pln."
            End If
        Else
            MsgBox "Apartment price was not found!"
        End If
    Set ws = ActiveSheet       'currently opened sheet on currently opened.xlsm file
    ws.Range("E27").Activate
    ws.Paste
End Sub

Then I need to strip the number from this ridiculous dot in the middle of the amount, so please help me clear 605.000 into 60500 or 1.250.000 into 1250000.
When I have this number (the price) in my clipboard, I need to paste it into currently opened excel file, into .activesheet (because the name of the excel file and excel sheet will change many times a day).
But the destination cell will always be E27 - it will never change.

Thank you guys for all the help.

EDIT 24.01.2020
This is the above mentioned code amended by me to my best abilities.
Sub Find_Corrected()
    'Variables declaration
    'Dim WordApp As Object
    Dim WordApp As Word.Application
    'Dim WordDoc As Object
    Dim WordDoc As Word.Document
    Dim TextToFind As String
    Dim ApartmentPrice As String
    Dim Rng As Word.Range
    Application.ScreenUpdating = False
        'This is the text I'm looking for in .ActiveDocument
        TextToFind = "brutto w kwocie "
        'Start Word and create an object
        'Set WordApp = CreateObject("Word.Application")
        'Reference already opened Word document from excel VBA console
        Set WordApp = GetObject(, "Word.Application")
        Set WordDoc = WordApp.ActiveDocument
        Set Rng = WordApp.ActiveDocument.Content
        WordApp.Application.Visible = True
        'Set WordDoc = WordApp.Documents.Open(FilePath & "Form1.docx")
        'Set WordDoc = WordApp.ActiveDocument     'I don't know how to finish this line  :-(
            Rng.Find.Execute FindText:=TextToFind, Forward:=True
                    'what this "Forward:=True" means??
            With Rng.Find
                .Text = "brutto w kwocie "
                .Execute
                    If .Found = True Then
                        Rng.MoveEnd wdWord, 3
                        Rng.Copy
                        MsgBox "Copied value equals " & Rng.Value & " Roesler conquers."
                    Else
                        MsgBox "Requested range was not found!"
                    End If
            End With
    'Set ws = ActiveSheet       ' currently opened sheet on currently opened.xlsm file
    'ws.Range("E27").Activate
    'ws.Paste
End Sub

And this is the error it returns.

A: You can use the same method that I used in an answer to another of your questions.
Create a range, set it equal to the whole document, search along the range, move until your desired stop range, then move the start of the range up to your numbers.
Dim srchRng as Range
Set srchRng = ActiveDocument.Content

With srchRng.Find
    .Text = "brutto w kwocie "
    .Execute
    If .Found = True Then
        Dim numberStart as Long
        numberStart = Len(srchRng.Text) + 1
        srchRng.MoveEndUntil Cset:=","

        Dim myNum as String
        myNum = Mid(srchRng.Text, numberStart)
    End If
End With

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I change the color of programmatically UIIMage Array Animation? I am currently making a Swift application with multiple UIImage elements. I am at the point where I need to add animations into my game. In order to reduce the projects fie size I have made a single shatter animation for every colored glass object. I have successfully changed the Images tint color for the first image in the animation but not the proceeding images. What is the best way to achieve this with the following code?
shatterImages = createImagesArray(total: 26, imagePrefix: "Shatter")

func createImagesArray(total: Int, imagePrefix: String) -> [UIImage] {
    var imageArray: [UIImage] = []

    for imageCount in 1..<total {
        let imageName = "\(imagePrefix)-\(imageCount).png"
        let image = UIImage(named: imageName)!

        imageArray.append(image)

    }
    return imageArray
}

func animate(imageView: UIImageView, images: [UIImage]) {
    let templateImage = imageView.image?.withRenderingMode(.alwaysTemplate)
    imageView.image = templateImage
    imageView.tintColor = UIColor.blue
    imageView.animationImages = images
    imageView.animationDuration = 0.7
    imageView.animationRepeatCount = 1
    imageView.startAnimating()
}

 DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                if self.game.correctValue == self.game.rightDiamondValue {
                    self.animate(imageView: self.rightGlass, images: self.shatterImages)
                        self.updateLabel()
                    } else {
                        self.gameOver()
                    }
            }


text:
Q: Trying to view Post Infos on graph.facebook I use:
https://graph.facebook.com/<postid>

to view infos about a post placed on the Facebook wall by some users.
(postid = userid_postid, e.g. 25255265222_12622622626 so dont worry about the format).
I recieve following, but I´m sure the Post exists:
{
"error": {
"message": "Unsupported get request.",
  "type": "GraphMethodException",
  "code": 100
  }
}

Why do I get the Error message? Whats wrong?
thx 4 help
Neil

A: You can't access Users' posts without using an active access_token
Try:
https://graph.facebook.com/{User_ID}_{POST_ID}?access_token={Active Access Toke}

Or (Works as well):
https://graph.facebook.com/{POST_ID}?access_token={Active Access Toke}

PS: Did you use the Graph API Explorer?


text: Q: Reason for concatenation of a random string 'r' with an input before computing its cryptographic hash In a Coursera course on Bitcoin, one of the properties of cryptographic hash functions mentioned was 'Hiding' - given an output of a hash function it should be infeasible to find its input.  According to the course, we must concatenate a random string 'r' to the input 'x' before hashing it.My questions are: 1) Why do we concatenate 'r' and 'x' - is it only to reduce the probability of an adversary being able to find the input by trying to hash high-probability values as inputs and comparing them with the original output?2) If I wish to use the hash generated (after concatenating 'r' and 'x') to verify another file having the same content as 'x', where would I get the same 'r' from (which would be required for correct verification)?


text:
Q: Uncaught Soap Error I am making a soap call from inside a try...catch block,
        $request->l_Request->Year = $year;
//      $request->l_Request->Period = $period;
        try {
            /**
             *
             * perform getMake request
             * @var stdClass
             */
            $response = $client->getSeries($request);
            $series = $response->getSeriesResult->Lookup_Struc;
            return $series;
        } catch (SoapFault $exception) {
            /**
             * log exception on soap request
             */
            $this->getLogger()->log($exception->getMessage(), Zend_Log::ERR);
            $this->getLogger()->log($exception->getTraceAsString(), Zend_Log::INFO);
            return false;
        }  catch (Exception $exception) {
            /**
             * log exception on soap request
             */
            $this->getLogger()->log($exception->getMessage(), Zend_Log::ERR);
            $this->getLogger()->log($exception->getTraceAsString(), Zend_Log::INFO);
            return false;
        }

Here's how my output/error looks like

( ! ) Fatal error: SOAP-ERROR: Encoding: object has no 'Period'
  property in C:\wamp\www\FHH\library\Zend\Soap\Client.php on line 1121

But I am unable to catch soap-error using try catch, Is there special way to handle this.

A: I use the following class in my applications to turn errors into exceptions:
class ErrorHandler
{
    public function __construct()
    {
        set_error_handler( array( __CLASS__, 'handleError' ));
    }

    static public function handleError( $errno, $errstr, $errfile,
                                        $errline, array $errcontext )
    {
        throw new ErrorException( $errstr, 0, $errno, $errfile, $errline );
    }
}

You just need to create an instance of it:
$errorHandler = new ErrorHandler();

An alternative if you're using ZF1 MVC is to rename the constructor to __initErrorHandler() and add those two methods to your bootstrap class.
I have successfully used this approach in code that uses Zend_Soap_Server, so hopefully it will work for you too.


text:
Q: Unsure of what this tube is on wired motor Upon looking for an answer online I found none, maybe it was the way I was describing it I don't know, on to the point though. On VEX robotics motors there is a tube with the wire looped in through it, here is a picture

It is covered with heat shrink tubing I believe and the inside of it is some sort of metal/ceramic that is more brittle. Maybe it's some sort of resistor because I think the materials of the inside of the resistor and tube are the same. Also there is no tag for Electric Motor yet, maybe should be added for those with 300 rep.

A: It is a ferrite ring to reduce interference from the motor interfering with either the receiver or processor controlling the motor.
Looping the wire through the ferrite ring creates some inductance that provides a low-pass filter.
You will often see the same thing on notebook computer power supplies.


text:
Q: Finding: $\displaystyle\lim_{x\to\infty}x\big((1+\tfrac1x)^x-\mathrm{e}\big) $
Find: $$\displaystyle\lim_{x\to\infty}x\Big(\big(1+\tfrac1x\big)^x-\mathrm{e}\Big) $$

EDIT: so we have here a $\infty\cdot0$ so I'll try LHR, Edit2: I don't think LHR will get me anywhere since it will always be zero in the denominator...
Maybe develop a Taylor series ?
Wrong try:
$\displaystyle\lim_{x\to\infty}(1+\frac1x)^x=\frac 1e$ is a well known limit so:
$\lim_{x\to\infty}x(\displaystyle\lim_{x\to\infty}(1+\frac1x)^x-e)=\lim_{x\to\infty}x(\frac 1e-e)=-\infty $

A: Note that
$$\lim_{x\to\infty}\left(1+\frac 1x\right)^x=e.$$
You can use l'Hôpital's rule.
Yours will be
$$\begin{align}\lim_{x\to\infty}\frac{(1+(1/x))^x-e}{(1/x)}&=\lim_{x\to\infty}\frac{(1+(1/x))^x \{-1+(1+x) \ln(1+(1/x))\}}{-(x+1)/x^2}\\&=\lim_{x\to\infty}\frac{(1+(1/x))^x \{-x+x(1+x) \ln(1+(1/x))\}}{-(x+1)/x}\\&=\frac{e\times (1/2)}{-1+0}\\&=-e/2\end{align}$$
where
$$\begin{align}\lim_{x\to\infty}\{-x+x(1+x)\ln(1+1/x)\}&=\lim_{x\to\infty}\frac{-1+(1+x)\ln(1+(1/x))}{1/x}\\&=\lim_{x\to\infty}\frac{\ln(1+(1/x))-(1/x)}{-1/x^2}\\&=\lim_{x\to\infty}\frac{1/(x^2+x^3)}{2/x^3}\\&=\lim_{x\to\infty}\frac{1}{2+(2/x)}\\&=1/2.\end{align}$$

A: Hint. Set $t=\dfrac{1}{x}$, and hence $t\to 0$, and
$$
x\big((1+\tfrac{1}{x})^x-\mathrm{e}\big)=\frac{(1+t)^{1/t}-\mathrm{e}}{t}=\frac{f(t)-f(0)}{t}
=f'(s),
$$
for some $s\in (0,t)$ (due to the Mean Value Theorem),
where
$$
f(t)=\left\{
\begin{array}{cll}
(1+t)^{1/t} & \text{if} & t>0,\\
\mathrm{e} & \text{if} & t=0.
\end{array}
\right.
$$
Now
$$
f'(t)=\exp\big(\tfrac{1}{t}\ln (1+t)\big)\left(\tfrac{1}{t(1+t)}-\tfrac{\ln(1+ t)}{t^2}\right).
$$
So your limit is just $f'(0)$.
In fact, you don't need to find $f'(0)$ directly, but to compute $f'(t)$, for $t>0$ ,and observe that the limit $\lim_{t\to 0} f'(t)$ exists.
Clearly, $\exp\big(\tfrac{1}{t}\ln (1+t)\big)=(1+t)^{1/t}\to\mathrm{e}$, while, for $g(t)=\ln (1+t)$,
$$
\frac{1}{t(1+t)}-\frac{\ln(1+ t)}{t^2}=\frac{1}{t}\left(g'(t)-\frac{g(t)-g(0)}{t}\right)\to-\frac{1}{2}g''(0).
$$

A: We have:
$$\log\left(1+\frac 1 x\right)^x=x\log\left(1+\frac 1 x\right)=x\left(\frac 1 x-\frac1{2x^2}+o\left(\frac1{x^2}\right)\right)$$
so
$$\left(1+\frac 1 x\right)^x=e\exp\left(-\frac1{2x}+o\left(\frac1{x}\right)\right)=e\left(1-\frac1{2x}+o\left(\frac1{x}\right)\right)$$
hence now it's simple to see that the desired limit is: $$-\frac{e}{2}$$

A: $\displaystyle \begin{aligned}L &= \lim_{x \to \infty}x\left(\left(1 + \frac{1}{x}\right)^{x}- e\right)\\
&= \lim_{x \to \infty}\dfrac{\left(\left(1 + \dfrac{1}{x}\right)^{x}- e\right)}{\dfrac{1}{x}}\\
&= \lim_{y \to 0^{+}}\dfrac{(1 + y)^{1/y} - e}{y}\text{ (by putting }y = 1/x)\\
&= \lim_{y \to 0^{+}}\dfrac{\exp\left(\dfrac{\log(1 + y)}{y}\right) - \exp(1)}{y}\\
&= \lim_{y \to 0^{+}}\dfrac{\exp\left(\dfrac{\log(1 + y)}{y}\right) - \exp(1)}{\dfrac{\log(1 + y)}{y} - 1}\cdot\dfrac{\dfrac{\log(1 + y)}{y} - 1}{y}\\
&= \lim_{z \to 1}\dfrac{\exp(z) - \exp(1)}{z - 1}\cdot\lim_{y \to 0^{+}}\dfrac{\log(1 + y) - y}{y^{2}}\,\,\{\text{by putting }z = (1/y)\log(1 + y)\}\\
&= \exp'(1)\cdot\lim_{y \to 0^{+}}\dfrac{\dfrac{1}{1 + y} - 1}{2y}\text{ (by L'Hospital's Rule)}\\
&= \exp(1)\cdot\lim_{y \to 0^{+}}\frac{-1}{2(1 + y)}\\
&= -\frac{e}{2}\end{aligned}$
One application of LHR is necessary, but the above procedure makes the application of LHR very simple. In the above derivation we have used the fact as $y \to 0^{+}$ the quantity $z = (1/y)\log(1 + y) \to 1$. This limit is pretty standard and a proof can be found in many textbooks and on MSE.

A: It will be easy if you use taylor formula. Let $t = \frac {1}{x}$,then $t \to 0$ as $x \to  \infty$,you will get $$ \lim_{ t \to 0} \frac{1}{t} ( e^{ \frac{1}{t} \log(1+ t)}-e)$$Note $\log(1+t) = t -\frac{t^2}{2}+o(t^2)$ as $t \to 0$ , and $ \frac{1}{t} \log(1+t) = 1 -\frac{t}{2}+o(t)$,then it becomes  $$ \lim_{ t \to 0} \frac{1}{t} ( e^{ \frac{1}{t} \log(1+ t)}-e) =  \lim_{ t \to 0} \frac{1}{t} ( e^{ 1- \frac{t}{2}+ o(t)}-e) = \lim_{ t \to 0} \frac{e}{t} (e^{ - \frac{t}{2}+ o(t)}-1) $$ use taylor formula again in $e^{ - \frac{t}{2}+o(t)} = 1 -\frac{t}{2} +o(t)$ you'll get $$\lim_{ t \to 0} \frac{e}{t} (e^{ - \frac{t}{2}+ o(t)}-1)  = \lim_{ t \to 0} \frac{e}{t} (1 -\frac{t}{2} +o(t)-1)= -\frac{e}{2}+o(1) $$  $o(1) \to 0$ as $t \to 0$ so the limit is $-\frac{e}{2}$


text:
Q: How can i insert multiple different values in single position of list in c++? This code is from
geeksforgeeks
list<int> list1;

list1.assign(3, 2);

list<int>::iterator it = list1.begin();

advance(it, 2);

list1.insert(it, 5);

cout << "The list after inserting"
     << " 1 element using insert() is : ";
for (list<int>::iterator i = list1.begin();
     i != list1.end();
     i++)
    cout << *i << " ";

cout << endl;

list1.insert(it, 2, 7);

cout << "The list after inserting"
     << " multiple elements "
     << "using insert() is : ";

for (list<int>::iterator i = list1.begin();
     i != list1.end();
     i++)
    cout << *i << " ";

cout << endl;

It shows the output like this:-
   The list after inserting 1 element using insert() is : 2 2 5 2
   The list after inserting multiple elements using insert() is: 2 2 5 7 7 2

So, I want to add different values in a single position than the duplication of the same value. Is that even possible?
for ex- inserting 1,3,7 in 3rd position of the list.

A: Check the reference.
You can use one of insert():
template< class InputIt >
void insert( iterator pos, InputIt first, InputIt last);            (until C++11)

template< class InputIt >
iterator insert( const_iterator pos, InputIt first, InputIt last ); (since C++11)

Example:
#include <iostream>
#include <vector>
#include <list>

int main(void) {
    std::list<int> list1 = {2, 2, 5, 2};
    std::vector<int> to_insert = {1, 3, 7};

    std::cout << "before insert:";
    for (int v : list1) std::cout << ' ' << v;
    std::cout << '\n';

    list1.insert(std::next(list1.begin(), 2), to_insert.begin(), to_insert.end());

    std::cout << " after insert:";
    for (int v : list1) std::cout << ' ' << v;
    std::cout << '\n';

    return 0;
}

Output:
before insert: 2 2 5 2
 after insert: 2 2 1 3 7 5 2


text:
Q: Replace the text of a button on button click from a GridView with a custom adapter? I have a GridView which is created via a custom GridViewAdapter which extends a BaseAdapter to create its view. Each cell in the GridView is represented by a button.
Inside of the View getView method, I use a ViewHolder to cache the button.
holder.gridPanel.setText(panel.getNumberPanel());

Then I tried to apply an OnClickListener to this button however the text of the button does not seem to change even though the Toast notification returns the correct value to set the new text of the button to.
holder.gridPanel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Toast.makeText(context, panel.getAlphabetPanel(), Toast.LENGTH_SHORT).show();
            holder.gridPanel.setText(panel.getAlphabetPanel());

        }
    });

What is the correct way of changing the text of a button which has been stored inside of a ViewHolder?
Code:
static class ViewHolder {
    Button gridPanel;

}

public class GridViewAdapter extends BaseAdapter {

    private Context context;
    ArrayList<Panel> panelList;
    Panel panel;

public GridViewAdapter(Context context, ArrayList<Panel> panelList){
    this.context = context;
    this.panelList = panelList;
}

@Override
public int getCount() {
    return panelList.size();
}

@Override
public Object getItem(int position) {
    return panelList.get(position);
}

@Override
public long getItemId(int position) {
    return panelList.indexOf(getItem(position));
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.game_grid_item_layout, parent, false);
        holder = new ViewHolder();
        holder.gridPanel = (Button) convertView.findViewById(R.id.grid_AlphabetPanel);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    panel = panelList.get(position);
    holder.gridPanel.setText(panel.getNumberPanel());

    holder.gridPanel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Toast.makeText(context, panel.getAlphabetPanel(), Toast.LENGTH_SHORT).show();
            holder.gridPanel.setText(panel.getAlphabetPanel());

        }
    });

    return convertView;
}

// below methods are in a different activity

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);
    ArrayList<Panel> panelList = new ArrayList<>();
    ArrayList<String> alphaList = new ArrayList<>();
    ArrayList<String> numberList = new ArrayList<>();
    alphaList.add("A");
    alphaList.add("B");
    alphaList.add("C");
    alphaList.add("D");
    alphaList.add("E");
    numberList.add(Integer.toString(1));
    numberList.add(Integer.toString(2));
    numberList.add(Integer.toString(3));
    numberList.add(Integer.toString(4));
    numberList.add(Integer.toString(5));

    for(int i = 0; i < 5; i++){
        String alp = alphaList.get(i);
        String numb = numberList.get(i);
        Panel panelObject = new Panel(alp, numb);
        panelList.add(panelObject);

    }

    GridView panelGrid = (GridView) findViewById(R.id.gridView_Panel);
    GridViewAdapter gridViewAdapter = new GridViewAdapter(this, panelList);
    panelGrid.setAdapter(gridViewAdapter);

}

A: So I came to an answer if anyone was wondering.
Calling the setOnClickListener when the ViewHolder is being initialised works whereas doing it outside of the loop will not allow the data to be changed.
In code:
if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.game_grid_item_layout, parent, false);
        holder = new ViewHolder();
        holder.gridPanel = (Button) convertView.findViewById(R.id.grid_AlphabetPanel);
        holder.gridPanel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                holder.gridPanel.setText(panel.getAlphabetPanel());
            }
        });

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }


text:
Q: glGetAttribLocation() returns -1 but the variable is uniform, How to fix it? This is my shader 'triangles.vert':
#version 430 core
layout(location = 0) in vec4 vPosition;
layout(location = 1) in vec4 vColor;
uniform mat4 vRota;

out vec4 color;

void main()
{
    color = vColor;
    gl_Position = vRota * vPosition;
}

and this is the snippet of the C++ source:
ShaderInfo shaders[] =
{
    { GL_VERTEX_SHADER, "triangles.vert" },
    { GL_FRAGMENT_SHADER, "triangles.frag" },
    { GL_NONE, NULL }
};

GLuint program = LoadShaders(shaders);
glUseProgram(program);

//...

int vRota_loc = glGetAttribLocation(program, "vRota");

if (vRota_loc == -1)
{
    cout << "No uniform match for 'vRota'" << endl;
}

It returns -1, but I don't know why.
Am I doing something wrong in the shader?
ps LoadShaders() is function for compiling and linking the shader programm. it is given as sourcefile by a book I'm practicing with. So I supose there won't be the error.

A: glGetAttribLocation is for vertex attributes, i.e. in variables in the vertex shader (such as vPosition). You want glGetUniformLocation.

A: A uniform is not an attribute. You need to use glGetUniformLocation
A uniform is consistent for each vertex while an attribute is per vertex.


text:
Q: Error while loading pipe delimited data from flat file into a SQL Server table I am looking at existing SSIS package.
I download the package from source control. Change connection managers to point to my local dev environment.
Task is to read from Flat file and to load into the SQL Server database.
File is a | delimited flat file. In connection manager, Header row delimiter has set as {LF}.
While executing task, I ran into several error and one of that is

curr user file [2]] Error: Data conversion failed. The data conversion for column "customfield_storeid" returned status value 4 and status text "Text was truncated or one or more characters had no match in the target code page.".

I looked into the connection manager, column has set to string[DT_STR] and 'OutputColumnWidth' to 50.
In my database table, that column is of type varchar(50). So it seems there is not anything wrong.
If I could change error output to ignore truncation error, it would not show error. But I do not want to change what has previously set for the package.
How do I  resolve it?


text:
Q: Flutter build iOS error : Encountering error while build flutter app in iOS device I'm trying to build flutter app in iOS device directly running at android studio but it prompt me this error below :

Running Xcode build... Xcode build done.
12.7s Installing and launching...

*

*thread #3, queue = 'com.apple.root.default-qos', stop reason = signal SIGABRT
frame #0: 0x000000019096dec4 libsystem_kernel.dylib`__pthread_kill + 8

Target 0: (Runner) stopped.

After running in Xcode, this is the error it shows up :
The Google Mobile Ads SDK was initialized without an application ID. Google AdMob publishers, follow instructions at https://googlemobileadssdk.page.link/admob-ios-update-plist to set a valid application ID. Google Ad Manager publishers, follow instructions at https://googlemobileadssdk.page.link/ad-manager-ios-update-plist."
This is my info.plist :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>GADApplicationIdentifier</key>
    <string>ca-app-pub-4326637290771071~7544496339</string>
    <key>CFBundleDevelopmentRegion</key>
    <string>$(DEVELOPMENT_LANGUAGE)</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>Stopcard</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>$(FLUTTER_BUILD_NAME)</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleVersion</key>
    <string>$(FLUTTER_BUILD_NUMBER)</string>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationPortraitUpsideDown</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UIViewControllerBasedStatusBarAppearance</key>
    <false/>
</dict>
</plist>

Can someone kindly help me on the issues ?
Thanks in advance

A: You have to add skAdNetworkKey for google like the following
<key>GADApplicationIdentifier</key>
<string>ca-app-pub-3940256099942544~1458002511</string>
<key>SKAdNetworkItems</key>
 <array>
   <dict>
    <key>SKAdNetworkIdentifier</key>
    <string>cstr6suwn9.skadnetwork</string>
  </dict>
</array>


text:
Q: Power of 3 of a Binary Number in GF(2^6) in VHDL? I tried myself in a GF(2^4). With the minimal polynom z^4+z+1:
a(z) = a0 + a1.z + a2.z^2 + a3.z^3
[a(z)]^3 = a0 + a1.z^3 + a2.z^6 + a3.z^9
= a0 + a1.z^3 + a2.(z^3 + z^2) + a3.(z^3+z)
= a0 + a1.z + a2.z^2 + (a1+a2+a3).z^3
Now i have to replace (a0, a1, a2, a3) by (a0, a3, a2, a1 + a2 + a3) The + operator ist just a xor. This is functional.
If i do it on GF(2^6) with minimal polynom z^6+z+1:
a(z) = a0 + a1.z + a2.z^2 + a3.z^3 + a4.z^4 + a5.z^5
[a(z)]^3 = a0 + a1.z^3 + a2.z^6 + a3.z^9 + a4.z^12 + a5.z^15
[a(z)]^3 = a0 + a1.z^3 + a2.(z+1) + a3.(z^4+z^3) + a4.(z^2+1) + a5.(z^5+z^3)
[a(z)]^3 = (a0 + a2 + a4) + a2.z + a4.z^2 + (a1 + a3 + a5).z^3 + a3.z^4 + a5.z^5
Now i should replace (a0, a1, a2, a3, a4, a5) with (a0+a2+a4, a2, a4, a1 + a3 + a5, a3 ,a5)
For example if i want to take the power of 3 from a^11= 100011, it should give a^33 = 010010.

*

*For new a5: a5 = 1

*For new a4: a3 = 0

*For new a3: a1 + a3 + a5 =  1 + 0 + 0 = 1

*For new a2: a4 = 0

*For new a1: a2 = 0

*For new a0: a0+a2+a4 = 1 + 0 + 0 = 1
makes = 101001 which is a^23
Why it works on GF(2^4) and not on GF(2^6)? What is my mistake?


text:
Q: Using an object array inside a method I know what the errors are. I want to know if its possible to do something like this. (Basically looking for an alternative way of doing this but is actually correct.)
Class:
private String[] names = {"Player 1", "Player 2"};

public void setName(Object[] objectName, String name)
    for(int x = 0; x < objectName.length; x++){
        //Problem is below here, "name can not be resolved or is not a field" is doing something like this not possible?
        objectName[x].name = names[x];
    }
}

Edited to show how it would be used.
Class 2:
Public static void methodName(){
    String name;
    ClassName2[] c2 = new ClassName2[2];
    c2[0] = new ClassName2();
    c2[1] = new ClassName2();
    c2[0].setName(c2, name);
}

A: In your exmaple the variable "objectName" must have the same size (or bigger) like "names".
With "String name" you want to define the field/variable you want to set in the object?
Anyways, I suggest you to use ArrayList, look on the example:
public class ArrayObject {

private String[] names = {"Player 1", "Player 2"};

/**
 * @param args
 */
public static void main(String[] args) {
    ArrayList<String> myArrayList = new ArrayList<String>();
    new ArrayObject().setName(myArrayList);
}

public void setName(ArrayList<String> objectName) {
    for(int x = 0; x < names.length; x++) {
        objectName.add(names[x]);
    }

    // Testoutput
    for(int x = 0; x < objectName.size() ; x++) {
        System.out.println(objectName.get(x));
    }
}

}
ArrayList is a dynamic array where you can add as many object as you want, read them and remove any of them.

A: I think you should read about generics and bounded generics in particular: http://docs.oracle.com/javase/tutorial/java/generics/bounded.html


text:
Q: How install GTK 4 in Python On the site gtk.org i see version 4.0 and:

*

*I installed MSYS2 following the instructions (gtk.org/docs/installations/windows)

*Then I installed the pacman-S mingw-w64-x86_64-gtk4 package

*And installed Glade pacman-S mingw-w64-x86_64-glade

*Then I installed all this in python pacman-S mingw-w64-x86_64-python3-gobject
But at startup, it writes that the GTK version is 3.24.24-1
Or maybe I can install GTK4 using pip
(I use Windows 10 and Pycharm with python 3.7)


text:
Q: Python: instance attribute is deleted after shuffling I have a trouble with a strange behaviour of numpy.random.shuffle function.
I add attribute to instances but it is erased after shuffling.
Here is a code illustrating the problem:
#I'm making a class of time series.
class TimeSeries(object):
    def __init__(self, data):
        self.data = data
        self.num_points = len(self.data)

    def __getitem__(self, key):
        return self.data[key]

    def __len__(self):
        return self.num_points

dataset = [TimeSeries(numpy.random.random((10,3))) for _ in range(100)]
#Add new attribute
for ts in dataset:
    ts.weight = 1

dataset[0].weight  #returns 1
numpy.random.shuffle(dataset)
dataset[0].weight  #'numpy.ndarray' object has no attribute 'weight'

I want to keep the weight attribute, but deleted after the shuffle.
I have done some trials.
What I have foud are:

*

*If the data set is small, the problem does not happen. (e.g range(100) >> range(3))

*ids are change after the shuffle.

*If getitem, len methods are not implemented, the problem does not happens.

What's going on in the shuffle function?
Is this a bug? Am I using the function is a wrong way?

A: If you just want to shuffle the main list, you could use
import random
random.shuffle(dataset)


text:
Q: ignoreValidationFailed doesn´t work inside ui:repeat I´m using o:ignoreValidationFailed, but it doesn´t work inside the ui:repeat. When I do the same outside, it works! I tried with mojarra ans MyFaces... I´m using primefaces. If there is another way to skip the validations only for one button...
 <o:form id="rateplanEditByPeriod" prependId="false">

   <h:panelGrid id="cancelationsTable" columns="2" cellpadding="10px" columnClasses="alignTop,alignTop">

    <ui:repeat id="repeat" var="rest" value="#{rateplanByPeriodManaged.rateplanByPeriod.restriction.restTypeCancelation.restTypeCanConfs}"  >

                                        <h:panelGrid columns="8">

                                                <o:ignoreValidationFailed />

                                                    <o:ignoreValidationFailed />

                                        </h:panelGrid>

                                    </ui:repeat>

                                </h:panelGrid>

#{msgs['inventory.editByPeriod.cancel']}

#{msgs['inventory.editByPeriod.confirm']}

        </o:form>

A: I have faced the same issue but with p:datatable
I solved it with
1- add a condition to the required field to know if the ajax come from submit button or not
as @Camilla said.
required="#{!empty param['trans_desc_form:savetransid']}"/>

trans_desc_form is the entire form id and savetransid is the submit button save id
2- I removed @NotNull from my JPA entity which force the validation
@JoinColumn(name = "ITEMNO", referencedColumnName = "ITEMNO")
@ManyToOne(optional = false, fetch = FetchType.LAZY)
//@NotNull
private Item item;

I have created a question for this issue
ignoreValidationFailed doesn´t work inside p:dataTable

A: I don´t know if it´s the best aproach but it worked for me...
<h: inputText id="text1" value="" required="#{!empty param['formName:btnSave']}" />

A: This is not the right way to have a "Cancel" button.
Just put process="@this" in the
, or if you don't need to do any business logic, make it a normal <h:link> which reloads the page (and thus implicitly recreates the request/view scoped bean).
As to <o:ignoreValidationFailed> the failure in <ui:repeat> on its own, please create an issue.


text:
Q: Should I really test controllers? I'm trying to get the best codecoverage/development time result
Currently I use rspec+shoulda to test my models and rspec+capybara to write my acceptance tests.
I tried writing a controller test for a simple crud but it kinda took too long and I got a confusing test in the end(my bad probably)
What`s the best pratice on controller testing with rspec?
Here is a gist on my test and my controller(one test does not pass yet):
https://gist.github.com/991687
https://gist.github.com/991685

A: Writing controller tests gives your application permission to lie to you. Some reasons:

*

*controller tests are not executed in the environment they are run in. i.e. they are not at the end of a rack middleware stack, so things like users are not available when using devise (as a single, simple example). As Rails moves more to a rack based setup, more rack middlewares are used, and your environment deviates increasingly from the 'unit' behaviour.

*You're not testing the behaviour of your application, you're testing the implementation. By mocking and stubbing your way through, you're re-implementing implementation in spec form. One easy way to tell if you're doing this; if you don't change the expected behaviour of url response, but do change the implementation of the controller (maybe even map to a different controller), do your tests break? If they do, you're testing implementation not behaviour. You're also setting your self up to be lied to. When you stub and mock, there's no assurances that the mocks or stubs you've setup do what you think they do, or even if the methods they're pretending to be exists after refactoring occurs.

*Calling controller methods is impossible via your applications 'public' api. The only way to get to a controller is via the stack, and the route. If you can't break it from a request via a url, is it really broken?

I use my tests as an assurance the my application is not going to break when I deploy it. Controller tests add nothing to my confidence that my application is indeed functional, and actually their presence decreases my confidence.
One other example, when testing your 'behaviour' of your application, do you care that a particular file template was rendered, or that a certain exception was raised, or instead is the behaviour of your application to return some stuff to the client with a particular status code?
Testing controllers (or views) increases the burden of tests that you impose on yourself, and means that the cost of refactoring is higher than it needs to be because of the potential to break tests.

A: Should you test? yes
There are gems that make testing controllers faster
http://blog.carbonfive.com/2010/12/10/speedy-test-iterations-for-rails-3-with-spork-and-guard/

A: Definitely test the controller. A few painfully learned rules of thumb:

*

*mock out model objects

*stub model object methods that your controller action uses

*sacrifice lots of chickens.

A: I like to have a test on every controller method at least just to eliminate stupid syntax errors that may cause the page to blow up.

A: A lot of people seem to be moving towards the approach of using Cucumber for integration testing in place of writing controller and routing tests.

A: Maybe not.
Sure you can write tests for your controller. It might help write better controllers. But if the logic in your controllers is simple, as it should be, then your controller tests are not where the battle is won.
Personally I prefer well-tested models and a thorough set of integration (acceptance) tests over controller tests any time.
That said, if you have trouble writing tests for controllers, then by all means do test them. At least until you get the hang of it. Then decide whether you want to continue or not. Same goes for every kind of test: try it until you understand it, decide afterwards.

A: The way I view this is that acceptance tests (i.e. Cucumber / Capybara), test the interactions that a user would normally perform on the application. This usually includes things like can a user create a specific resource with valid data and then do they see errors if they enter invalid data. A controller test is more for things that a user shouldn't be able to normally do or extreme edge cases that would be too (cu)cumbersome to test with Cucumber.
Usually when people write controller tests, they are effectively testing the same thing. The only reason to test a controller's method in a controller test are for edge cases.
Edge cases such as if a user enters an invalid ID to a show page they should be shown a 404 page. This is a very simple kind of thing to test with a controller test, and I would recommend doing that. You want to make sure that when they hit the action that they receive a 404 response, boom, simple.
Making sure that your new action responds successfully and doesn't syntax error? Please. That's what your Cucumber features would tell you. If the action suddenly develops a Case of the Whoops, your feature will break and then you will fix that.
Another way of thinking about it is do you want to test a specific action responds in a certain way (i.e. controller tests), or do you care more about that a user can go to that new action and actually go through the whole motions of creating that resource (i.e. acceptance tests)?


text:
Q: R: Populate a new column in a dataframe based on matching one or several possible strings Hypothetical dataframe:
strings      new column
mesh         1
foo          0
bar          0
tack         1
suture       1

I would like the new column to contain "1" if df$strings contains the strings "mesh", "tack", or "sutur". Otherwise it should display zero in the same row. I tried the following:
df$new_column <- ifelse(grepl("mesh" | "tack" | "sutur",
  df$strings, ignore.case = T), "1", "0")

but got this error:
Error in "mesh" | "tack" :
  operations are possible only for numeric, logical or complex types

Thanks in advance.

A: You want to use a single string in grep:
df$new_column <- ifelse(grepl("mesh|tack|sutur", df$strings, ignore.case = T),
                       "1", "0")

will work, but the following will be faster:
df$new_column <- +(grepl("mesh|tack|sutur", df$strings, ignore.case = T))

This will return a 0 and 1 integer vector

A: We can also use %in%
df$new_column <-  as.integer(df$strings %in% c("mesh", "tack", "sutur"))


text:
Q: Не запускается дочерний поток в android studio При запуске потока он не работает.
Просто не выводит залодженные строки
Подскажите, пожалуйста, что может быть, ошибок не выводит
public void RegAuth(View view){

        Button button = (Button)findViewById(R.id.button);
        EditText phone = (EditText) findViewById(R.id.loginPhone);

        if(button.getText().toString().equals(this.reg)){
            startActivity(new Intent("com.example.taxi_full.Registration"));
        } if(button.getText().toString().equals(this.auth)) {
            String url = URL_API+phone.getText().toString();
            new Thread(() -> {
               try {
                   GsonParser parser = new GsonParser();
                   JsonWriter.jsonFileWriter(HttpApi.getId(url));
                   Root_user_one root = parser.parse();
                   Log.d("---ParseLogin---", root.getPhone());
                   Log.d("---Http---", HttpApi.getId(url));
                   JsonWriter.jsonClear();
                   Log.d("---Http---",HttpApi.getId(url));
                   //startActivity(new Intent("com.example.taxi_full.SMS_Code"));

               } catch (IOException e) {
                   Log.d("---ThreadEx--", e.getMessage());
               }
            });

        }

    }

A: При вызове конструктора поток только лишь создаётся, но не начинает своё выполнение. Для того, чтобы созданный при помощи new поток был запущен, необходим вызвать для него метод start().
То есть, например, в такой записи на экран ничего не будет выведено, так как поток не запускается, а только создаётся:
new Thread(() -> System.out.println("Hello, word"));

А при такой записи он уже выполнится, так как не только создаётся, но и сразу же запускается:
new Thread(() -> System.out.println("Hello, word")).start();

Для наглядности это можно даже записать вот так:
Thread thread = new Thread(() -> System.out.println("Hello, word"));
thread.start();

Так что если переписать код в вашей программе следующим образом, то поток должен будет отработать:
new Thread(() -> {
    try {
        GsonParser parser = new GsonParser();
        JsonWriter.jsonFileWriter(HttpApi.getId(url));
        Root_user_one root = parser.parse();
        Log.d("---ParseLogin---", root.getPhone());
        Log.d("---Http---", HttpApi.getId(url));
        JsonWriter.jsonClear();
        Log.d("---Http---",HttpApi.getId(url));
        //startActivity(new Intent("com.example.taxi_full.SMS_Code"));

    } catch (IOException e) {
          Log.d("---ThreadEx--", e.getMessage());
      }
}).start();


text:
Q: Invalid configuration object In my project I need to utilize ts-loader to load antd in a reasonable way. I am getting the following error:
✖ 「wds」: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.module.rules[0].use should be one of these:
   non-empty string | function | object { loader?, options?, ident?, query? } | function | [non-empty string | function | object { loader?, options?, ident?, query? }]
   -> Modifiers applied to the module when rule is matched
   Details:
    * configuration.module.rules[0].use should be a string.
    * configuration.module.rules[0].use should be an instance of function

here is the code in question:
const getTsLoaderRule = env => {
  const rules = [
    { loader: 'cache-loader' },
    {
        loader: 'thread-loader',
        options: {
            // there should be 1 cpu for the fork-ts-checker-webpack-plugin
            workers: require('os').cpus().length - 1
        }
    },
    {
      test: /\.(jsx|tsx|js|ts)$/,
      loader: 'ts-loader',
      options: {
        transpileOnly: true,
        getCustomTransformers: () => ({
          before: [ tsImportPluginFactory( {/*plugin to load antd library*/
            libraryName: 'antd',
            libraryDirectory: 'lib',
            style: true
          }) ]
          }),
          compilerOptions: {
            module: 'es2015'
          }
        },
        exclude: /node_modules/
    },
  ];
  if (env === 'development') {
    rules.unshift({
      loader: 'react-hot-loader/webpack'
    });
  }
  return rules;
};

How do I correctly load plugins with ts-loader?
EDIT
I need to include the ts-loader plugin options as follows to allow the library to be dynamically loaded:
options: {
transpileOnly: true,
getCustomTransformers: () => ({
  before: [ tsImportPluginFactory( {/*plugin to load antd library*/
    libraryName: 'antd',
    libraryDirectory: 'lib',
    style: true
  }) ]
  }),
  compilerOptions: {
    module: 'es2015'
  }
}

More details here.

A: Just use the basic config file here or use the following code:
const path = require('path'); module.exports = {
    entry: './src/index.ts',
     module: {
             rules: [{
                 test: /\.tsx?$/,
                 use: 'ts-loader',
                 exclude: /node_modules/
             }
            ],
         },
    resolve: {
             extensions: ['.tsx', '.ts', '.js']
         },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'main.js'
    } }


text:
Q: One way relay (manual reset )? What I mean by one way relay is manually reset it to run again.
What I need it for:
I want a pump to run when a relay is on(manually turned on), when there is no power the relay trips and stays like that in off position. Because even if the power comes back on I don't want the pump on. Until I reset the relay.
I keep saying a relay, but it doesn't have to be. Anything that could handle 240V.
Is there anything I could use for this?

A: This is a very common requirement for machine controls. You can buy switches with this function built-in - Look on Amazon for "motor safety switch".
A typical DIY circuit is:

simulate this circuit – Schematic created using CircuitLab


text:
Q: Uninstall program using get-process and uninstallstring with call operator (&) I'm trying create a uninstall script to uninstall any program tha I want.
I was using this script:
get-package -Name "XXXXX" | Uninstall-Package
But I saw that when the "provideName" attribut is "Program" it not working, so I use this.
$packageArray = get-package "*XXXX*"
foreach ($package in $packageArray){
$a = $package.ProviderName
if ($a -eq "Programs"){
& {($package.Meta.Attributes["UninstallString"]  -replace '"') /S}
}
if ($a -ne "Programs"){
get-package -Name "*XXXXX*" | Uninstall-Package
}
}

This part bellow was working fine when I have not ""&quot."", like this.
& {($package.Meta.Attributes["UninstallString"]  -replace '"') /S}
Print:

But now I'm getting erro when a uninstall string has "&quot." value, like this.
UninstallString=""&quot";C:\Users\rsantanna\AppData\Local\GoToMeeting\19950\G2MUninstall.exe" /uninstall"
Print.

When it occur I get this error.
& : The term 'C:\Users\rsantanna\AppData\Local\GoToMeeting\19950\G2MUninstall.exe /uninstall' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the
path is correct and try again.
At line:6 char:7

*

*
& ($UninstallString)

*
  ~~~~~~~~~~~~~~~~~~

*

*CategoryInfo          : ObjectNotFound: (C:\Users\rsanta....exe /uninstall:String) [], CommandNotFoundException

*FullyQualifiedErrorId : CommandNotFoundException

Anyone can help me ?

A: *

*You cannot directly execute a string expression such as ($package.Meta.Attributes["UninstallString"]  -replace '"')

*While you can do so via &, the call operator, it only works if the string expression evaluates to a command name or executable file path only.

*

*Notably, you can not use & to execute an entire command line, which is what $package.Meta.Attributes["UninstallString"] typically contains.

*Note that your use of & is with a script block ({ ... }), which allows you to execute arbitrary statements contained in the block; however, perhaps needless to say, these statements are subject to the usual syntax rules, and it is the one and only statement in your block that causes a syntax error (that is actually different from the error you report).
As explained in detail in this answer, the command lines stored in UninstallString registry values are designed for invocation from cmd.exe or from no-shell environments.
Therefore, the simplest solution is to call via cmd.exe /c:
cmd.exe /c "$($package.Meta.Attributes["UninstallString"]) /S"

If your uninstall command line, as returned from $package.Meta.Attributes["UninstallString"], really contains " in lieu of verbatim " characters (double quotes) - which would be unusual - you'll need to replace the former with the latter first:
cmd.exe /c "$($package.Meta.Attributes["UninstallString"] -replace '"', '"') /S"

It's unclear what command produced the " output in your screenshot, but given that it shows the text of an XML document, the use of " instead of " is simply a necessity for encoding literal  " chars.


text:
Q: ActiveMQ Simple Authentication Plugin - user admin is not authorized to create: topic://ActiveMQ.Advisory.Connection I modified our ActiveMQ configuration to use ActiveMQ Simple Authentication Plugin with a single user and password that has all rights to the broker
    <plugins>
        <simpleAuthenticationPlugin>
            <users>
                    <authenticationUser
                    username="admin"
                    password="pass"
                    groups="admins,publishers,consumers" />
            </users>
        </simpleAuthenticationPlugin>
     <authorizationPlugin>
          <map>
              <authorizationMap>
                  <authorizationEntries>
                      <authorizationEntry queue=">" write="producers" read="consumers" admin="admins" />
                  </authorizationEntries>
              </authorizationMap>
          </map>
      </authorizationPlugin>

    </plugins>

My java web app was  previously creating an instance of ActiveMQConnectionFactory by calling createConnection() without any arguments.
    connection = (ActiveMQConnection)connectionFactory.createConnection();

I modified my code to pass the username and password strings defined in my ActiveMQ Simple Authentication Plugin configuration to the overloaded version of the createConnection() method
    String username = "admin";
    String password = "pass";
    connection = (ActiveMQConnection)connectionFactory.createConnection(username, password);

I'm able to compile my code cleanly, but receive 'user is not able to create topic' errors when deploying
    10:51:03,831 ERROR [stderr] (MSC service thread 1-11) javax.jms.JMSException: User admin is not authorized to create: topic://ActiveMQ.Advisory.Connection
    10:51:03,832 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:49)
    10:51:03,832 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.ActiveMQConnection.syncSendPacket(ActiveMQConnection.java:1295)
    10:51:03,833 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.ActiveMQConnection.ensureConnectionInfoSent(ActiveMQConnection.java:1392)
    10:51:03,834 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.ActiveMQConnection.createSession(ActiveMQConnection.java:309)
    10:51:03,834 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.ActiveMQConnection.createQueueSession(ActiveMQConnection.java:1232)
    10:51:03,835 ERROR [stderr] (MSC service thread 1-11)   at com.company.app.anywhere.common.jms.JMSClient.<init>(JMSClient.java:74)
    10:51:03,836 ERROR [stderr] (MSC service thread 1-11)   at com.company.app.anywhere.common.jms.JMSListenerServletTemplate.startJMSConnection(JMSListenerServletTemplate.java:83)
    10:51:03,836 ERROR [stderr] (MSC service thread 1-11)   at com.company.app.anywhere.common.jms.JMSListenerServletTemplate.init(JMSListenerServletTemplate.java:64)
    10:51:03,837 ERROR [stderr] (MSC service thread 1-11)   at com.company.app.anywhere.common.jms.JMSAnywhereServlet.init(JMSAnywhereServlet.java:190)
    10:51:03,837 ERROR [stderr] (MSC service thread 1-11)   at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1202)
    10:51:03,838 ERROR [stderr] (MSC service thread 1-11)   at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1102)
    10:51:03,838 ERROR [stderr] (MSC service thread 1-11)   at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3655)
    10:51:03,838 ERROR [stderr] (MSC service thread 1-11)   at org.apache.catalina.core.StandardContext.start(StandardContext.java:3873)
    10:51:03,839 ERROR [stderr] (MSC service thread 1-11)   at org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:90)
    10:51:03,839 ERROR [stderr] (MSC service thread 1-11)   at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
    10:51:03,840 ERROR [stderr] (MSC service thread 1-11)   at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
    10:51:03,840 ERROR [stderr] (MSC service thread 1-11)   at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    10:51:03,841 ERROR [stderr] (MSC service thread 1-11)   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    10:51:03,841 ERROR [stderr] (MSC service thread 1-11)   at java.lang.Thread.run(Thread.java:680)
    10:51:03,842 ERROR [stderr] (MSC service thread 1-11) Caused by: java.lang.SecurityException: User admin is not authorized to create: topic://ActiveMQ.Advisory.Connection
    10:51:03,842 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.security.AuthorizationBroker.addDestination(AuthorizationBroker.java:76)
    10:51:03,843 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.broker.MutableBrokerFilter.addDestination(MutableBrokerFilter.java:151)
    10:51:03,843 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.broker.region.RegionBroker.send(RegionBroker.java:502)
    10:51:03,844 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.advisory.AdvisoryBroker.fireAdvisory(AdvisoryBroker.java:515)
    10:51:03,844 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.advisory.AdvisoryBroker.fireAdvisory(AdvisoryBroker.java:446)
    10:51:03,844 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.advisory.AdvisoryBroker.fireAdvisory(AdvisoryBroker.java:441)
    10:51:03,845 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.advisory.AdvisoryBroker.addConnection(AdvisoryBroker.java:73)
    10:51:03,846 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.broker.BrokerFilter.addConnection(BrokerFilter.java:85)
    10:51:03,846 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.broker.BrokerFilter.addConnection(BrokerFilter.java:85)
    10:51:03,847 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.broker.BrokerFilter.addConnection(BrokerFilter.java:85)
    10:51:03,848 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.security.SimpleAuthenticationBroker.addConnection(SimpleAuthenticationBroker.java:96)
    10:51:03,848 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.broker.BrokerFilter.addConnection(BrokerFilter.java:85)
    10:51:03,849 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.broker.MutableBrokerFilter.addConnection(MutableBrokerFilter.java:91)
    10:51:03,850 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.broker.TransportConnection.processAddConnection(TransportConnection.java:692)
    10:51:03,851 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.broker.jmx.ManagedTransportConnection.processAddConnection(ManagedTransportConnection.java:83)
    10:51:03,851 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.command.ConnectionInfo.visit(ConnectionInfo.java:137)
    10:51:03,852 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.broker.TransportConnection.service(TransportConnection.java:306)
    10:51:03,853 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.broker.TransportConnection$1.onCommand(TransportConnection.java:179)
    10:51:03,854 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.transport.TransportFilter.onCommand(TransportFilter.java:69)
    10:51:03,854 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.transport.WireFormatNegotiator.onCommand(WireFormatNegotiator.java:113)
    10:51:03,858 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.transport.InactivityMonitor.onCommand(InactivityMonitor.java:227)
    10:51:03,859 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.transport.TransportLogger.onCommand(TransportLogger.java:114)
    10:51:03,860 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.transport.TransportSupport.doConsume(TransportSupport.java:83)
    10:51:03,860 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.transport.tcp.TcpTransport.doRun(TcpTransport.java:220)
    10:51:03,861 ERROR [stderr] (MSC service thread 1-11)   at org.apache.activemq.transport.tcp.TcpTransport.run(TcpTransport.java:202)
    10:51:03,861 ERROR [stderr] (MSC service thread 1-11)   ... 1 more

This seemed straightforward.  I wonder if there is something wrong with the way I set up the createConnection() call?  Any advice appreciated.
Edit:  I've tried adding authorizationPlugin to my config - it seems to produce the same types of errors

A: Your existing config only applies to queues. Try adding:
<authorizationEntry topic=">" write="producers" read="consumers" admin="admins" />


text:
Q: Getting key value of WP_Term object in wordpress How I can get from php on wordpress to a value of WP_Term object. I am using the next code to get the object:
$queried_object = get_the_category( get_queried_object_id());

But this return an Array like this.
Array
(
    [0] => WP_Term Object
        (
            [term_id] => 12
            [name] => Argentina
            ...
        )

)

How I can get only the value for [name] key in this object from php in wordpress?

A: It returns an array because Posts can have multiple categories. You just need to get the item from the array whose name you want, ($queried_object[0] for the first one), then get the value out  of that the same way you would any PHP object:
$name = $queried_object[0]->name;

You should probably include some checks to make sure the post has a category before attempting to use the array or object like this:
$categories = get_the_category( get_queried_object_id() );

if ( ! empty( $categories ) ) {
    $category = $categories[0];
    $name = $category->name;
}


text:
Q: How to use Kotlin extension property of function type with Android data binding? I defined a Kotlin extension property of function type:
@set:BindingAdapter("myListener")
var View.myListener: ((Boolean) -> Unit)?
    get() {
        // ...
    }
    set(value) {
        // ...
    }

I'm now trying to use that in an Android data binding call. First I defined a method against my ViewModel (which is a variable viewModel within my databinding).
@MainThread
fun notify(value: Boolean) {
    if (value) {
        // do stuff
    }
}

Then tried to use that method in my binding layout XML:
<TextView
    ...
    app:myListener="@{viewModel::notify}"
    />

But it gives a compiler error "Listener class 'kotlin.jvm.functions.Function1<? super java.lang.Boolean,kotlin.Unit>' with method 'invoke' did not match signature of any method 'app:myListener'".
I also tried this way, with calling the method in an expression:
<TextView
    ...
    app:myListener="@{(b) -> viewModel.notify(b)}"
    />

But it also gave an error, this time on startup: "cannot find method notify(java.lang.Object) in class com.example.ui.models.MyViewModel".
I've managed to use data binding before with Kotlin extension functions returning types other than function, and I've also used data binding with method reference to listeners that are defined via an interface. But I'm not sure how to combine the two.


text:
Q: How to close the drop down list of JCombobox when we click on custom? I have a JCombobox in which when I select any one from drop down list of JCombobox ,the selected item is opening but when I click on "Custom" among one of the drop down list I have to open a daiolg ,here daiolg is opening but drop down list is not closing I want to hide the drop down when I click on Custom. here is my sample code....
private PropertyChangeSupport   pcs;///here Iam using ActionListener and PopupMenuListener
public void actionPerformed(ActionEvent ae){
if(ae.getSource() instanceof  ComboBox )
{
ComboBox comboBox = (ComboBox)ae.getSource();
Object selectedItem = comboBox.getSelectedItem();
if(selectedItem != null && (!selectedItem.equals("(Custom..)")))
{
pcs.firePropertyChange("ITEM_SELECTED",getCaption(),null);
}}}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e)
{
ComboBox comboBox = (ComboBox)e.getSource();
Object repeatedSelectedItem = comboBox.getSelectedItem();
if(repeatedSelectedItem != null && repeatedSelectedItem.equals("(Custom..)"))
{
invokeCustomFilterDialog(repeatedSelectedItem, comboBox);
}}
private void invokeCustomFilterDialog(Object repeatedSelectedItem, ComboBox comboBox)
{
customFilterDialog.showDialog();    //here Iam opening dailog...
if(customFilterDialog.isCustomFilterAppliedFlag() == true)
{
pcs.firePropertyChange("ITEM_SELECTED",getCaption(),null);
}
else
{comboBox.setSelectedItem(lastSelectedItem);}}
public void popupMenuCanceled(PopupMenuEvent e)
{ }
public void popupMenuWillBecomeVisible(PopupMenuEvent e)
{
ComboBox comboBox = (ComboBox)e.getSource();
this.lastSelectedItem = comboBox.getSelectedItem();
}

A: combobox.getUI().setPopupVisible(combobox, false);

A: You can use SwingUtilities.invokeLater.
For example
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
        final JComboBox comboBox = (JComboBox) e.getSource();
        final Object repeatedSelectedItem = comboBox.getSelectedItem();
        if (repeatedSelectedItem != null
                && repeatedSelectedItem.equals("(Custom..)")) {
            SwingUtilities.invokeLater(new Runnable() {
                  public void run() {
                      invokeCustomFilterDialog(repeatedSelectedItem, comboBox);
                  }
            });

        }
    }


text:
Q: Task Manager Script I need to a script that will pull up the Task Manager in Vista but with processes from all users (like when you click "Show processes from all users").  I don't mind the UAC interruption but I'd like to save some time and go straight to the "all users" version.
I don't care what language per se, just something that'll run it native to Vista without loading any extras.
Thanks.

A: *

*In the vista start menu search bar, type in "taskmgr" (without quotes).

*When the taskmgr.exe program comes up in the results, right click and select "create shortcut."

*On your desktop, right click your new shortcut and select "advanced" under the "shortcut" tab.

*Check "run as administrator."

Now, when you click on this UAC will come up. After you tell it to run, it will open up with all users :)


text:
Q: Breaking out of while loop and sleep I'm trying to make a very simple autoclicker in C# just to get better at it.
I have a form with two numeric text boxes and two buttons. The first text box specifies how much time should be between each click (in msec), and the second text box specifies the number of iterations.
The first button I have is button1, which essentially just starts the program. I have a second button called button2, which will stop the button1_Click function.
Here's what I have:
private void button1_Click(object sender, EventArgs e)
{
    //While a is less than number of specified iterations
    for (int a = 0; a < Convert.ToInt32(numericUpDown2.Value); a++)
    {
        //Sleep for desired time
        System.Threading.Thread.Sleep(Convert.ToInt32(numericUpDown1.Value));

        //Get x/y coordinates of mouse
        int X = Cursor.Position.X;
        int Y = Cursor.Position.Y;

        //Click mouse at x/y coordinates
        mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
    }
}

public void Form_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Escape)
    {
        this.Close();
    }
}

My problem is that my program is stuck in that for loop, and I have no way to break the button1_Click function.
I want it so that if I press F11 or my button2 button, the button1_Click function will immediately stop, but the form itself will still be open. Right now I'm just using the ESC key just for simplicity.

A: Add a 'Timer' object to your form, set it's Interval to the number of milliseconds to 'sleep' (not really). Set it's Enabled property to false.
Handle it's Tick event and put all of your inner-loop code there (the mouse_event call).
In button1_Click (buttonStart would be a better name), set the timer Enabled to true, and in button2_Click (buttonStop) set the timer Enabled to false.

A: Something like this
public Timer myTimer { get; set; }

public Form()
{
   myTimer = new Timer();
   myTimer.Tick += new EventHandler(TimerEventProcessor);
}

private void button1_Click(object sender, EventArgs e)
{
   myTimer.Interval = Convert.ToInt32(numericUpDown1.Value);
   myTimer.Start();
}

public void Form_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Escape)
    {
        myTimer.Stop();
        this.Close();
    }
}

private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
    //Get x/y coordinates of mouse
    int X = Cursor.Position.X;
    int Y = Cursor.Position.Y;
    //Click mouse at x/y coordinates
    mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
}

A: Timer t1;
int ticks = 0;
bool timerInitialized = false
private void button1_Click(object sender, EventArgs e)
{
  if (!timerInitialized)
  {
    t1 = new Timer();
    t1.Tick += Timer_Tick;
    timerInitialized = true;
  }
  button1.Enabled = false;
  t1.Interval = Convert.ToInt32(numericUpDown1.Value);
  ticks = 0;
  t1.Start();
}

private void Timer_Tick(object sender, EventArgs e)
{
  if (ticks <  Convert.ToInt32(numericUpDown2.Value))
  {
    ticks++;

    //Get x/y coordinates of mouse
    int X = Cursor.Position.X;
    int Y = Cursor.Position.Y;
    //Click mouse at x/y coordinates
    mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
  }
  else
  {
    t1.Stop(); //You could Call Stop from every where e.g. from another Button
    button1.Enabled = true;
  }
}

EDIT:
Assign the "Tick" event only once


text:
Q: Set image as background of figure container I would like to set the image from the src-tag as the background of the figure container dynamically with jquery.

Passo Tonale 1883m

A: you can do this way:
$(document).ready(function(){

var source = $("img.cam").attr("src");

$("img.cam").closest("figure").css("background-image","url("+source+")");

    })

FIDDLE DEMO


text:
Q: How to read some certain band diagrams? I have some problems on understanding some semiconductors band diagram.
For instance, I understand quite well something like this:

I understand it because it is quite simple: there are the energy levels (Conduction, Fermi, Intrinsic Fermi and Valence) at right and left, and the transition region between them. Quite fine.
But sometimes I see something different. For instance, for a Metal Oxide Semiconductor structure, I see something like this:

or this in case of a cascade of quantum wells:

So, what are all these strange shapes inside the green circles? In the first picture only at right the energy levels are specified, while the shape in the green circle is not specified: what physical quantity is it? In the second picture there is no specification.

A: Both confusing diagrams show heterostructures (i.e. one device containing different materials), and the different materials can have very different properties.
In the first figure:

*

*At the left is a metal. By definition, a metal has no band gap. So only the Fermi Level is shown.

*In the middle (circled in green) is an insulator. The difference between an insulator and a semiconductor is kind of arbitrary. Both have a band gap, and the top and bottom of the circled parallelogram show the conduction band minimum ($E_c$) and valence band maximum ($E_v$), respectively, for the insulator. Note that the band gap is significantly larger than for the semiconductor at the right. There seems to be a voltage applied across the insulator (typical for how these devices are used), so $E_c$ and $E_v$ are not constant.

*At the right is a semiconductor, which you understand.

In the second figure, only $E_c$ is shown. The discontinuous jumps are where the material changes --- e,g, from GaAs to AlGaAs. The two materials have different band structures, so $E_c$ is discontinuous. The overall downward "slope" of $E_c$ is because some voltage is being put across the device.


text:
Q: my little asm program has a segment fault I am a newbie to assembly language, and here is my little program.
section .data
section .text

global _start
_start:
    nop ; make gdb happy
    ; put your experiments here
    mov eax,4
    ; put your expeirments here
    nop ; make gdb happy

section .bss

This code is compiled with these commands:
nasm -f elf64 -g -F stabs 001.asm -o 001.o
ld -o test 001.o

But when I run, it generates a core dump file with segment fault.
1.Why this little program has a segment fault?
2.How to gdb this with core dump file?
enter image description here

A: Your program doesn't contain code that ends it. After executing the final nop in your code, the CPU continues to execute whatever the memory after that contains until it crashes. To fix this problem, tell the operating system to terminate your process. On amd64 Linux, you can use the following code:
mov eax,60  ; system call 60: exit
xor edi,edi ; set exit status to zero
syscall     ; call the operating system


text:
Q: Куда делать память после удаления указателя? Есть бинарное дерево. Каждый узел в нем - это такая структура:
struct TNode {
    int memory;
    TNode* left;
    TNode* right;
};

Инициализируется узел вот так:
Node* node = new Node;
node->memory = value;
node->left = NULL;
node->right = NULL;

То есть это число и два указателя на другие структуры-узлы. Отсюда у меня вопрос. Если я удалю узел оператором delete, то что будет с памятью, которую я выделил при инициализации оператором new? Указатель удалится, но будет ли дальше занимать место та память, которую я выделил через new? Или она автоматически станет "свободной", поскольку больше указателей на нее нет?

A: При вызове оператора delete / delete[], с указателем ничего не происходит, т.е. если в нем был какой-то адрес, то он таким же и останется, если его не затереть вручную.
Т.е. например не присвоить NULL:
Node * pNode = new Node;
...
delete pNode;
pNode = NULL; // or nulltpr;

Но при этом важно понимать, что адрес на который он указывает — инвалидный.
Т.е. адрес памяти теперь вами больше не может использоваться, и если вы будете дальше его использовать, то либо вы получите SIGSEGV, либо ваша программа тут же упадет, или вам повезет и вы получите UB.
В заключении, скажу что либо вы тщательно затираете указатели сами, либо используйте умные указатели дабы избежать проблем (но при этом скорость выполнения может снизится).
P.S. Если указатель лежит на стеке, то вам с ним ничего не нужно делать, т.к. он сам будет освобожден при утилизации стека, а если же он у вас в другой Node, то ничего страшного, просто перетрите его NULL / nullptr.


text:
Q: Design pattern for multithreaded java application I have a backend that receives requests on a function
update(by_whom, payload);

I then process the request, and answer accordingly.
Every time a user sends a request, the message goes through several processing objects before an answer is produced.
Now, how would I go about handling each user in his very own thread? I don't understand how to dispatch events to tailor-made threads.
Example:
User 1 sends first request -> We make a ThreadUser1 and handle it there.
User 2 sends first request -> We make a ThreadUser2 and handle it there, doesn't matter if request1 from user1 hasn't finished, they can run together.
User 1 sends second request, the first one sent by him hasn't finished -> We dispatch this request on the threadUser1, and it will therefore wait for request1 to finish.
Basically, upon receiving a request, it should only be put in queue behind those sent by the same user, and be run concurrently with everything else.
A way I thought would work:
I thought about posting every request in a concurrent list from the main thread, and have threads check that list (while true), and pick the requests from the user which they belong to.
A few problems with this:
- I'd need to check the whole list everytime for a request by the right user.

*

*This assumes I already have a thread running for every possible user, which I don't, I only know the id of a user when he first texts.

*Efficiency, potentially a huge amount of loops checking the same list over and over.

*A thread should stop after all the requests from that user are finished.
On that last point: it's because I need to have a limit MAX whereby any requests received while we already have MAX threads running, with these new requests not belonging to any current user (aka running thread) are handled normally (queuing in the main thread, one after the other).
I really don't know how to go about this and I'd be very glad if anyone could point me in the right direction.

A: You need your threads to know both what task they are working on, and what user they are working for.  However, you want a limited number of threads.
I think architecturally, the best way to do this is to start the limited number of threads, and have them able to handle tasks from arbitrary users, but not permit multiple threads to work for the same user at the same time.
To do this, keep three Sets of user objects, one Set for all users with incomplete tasks, one Set for users which have a thread assigned to them, and one Set for users which don't have a thread assigned to them.  Put all three Sets in a single, thread safe user tracking object.  You will also need a Map from users to tasks, or if you need tasks to be completed in the order they were queued, from users to queues of tasks.
When you queue a task, synchronize on the user tracking object, then check the Set of users with incomplete tasks.  If the relevant user does not exist, create it and put it in the Set of users with incomplete tasks and also in the Set of users with no associated thread.  Then put the task in a thread safe Map from users to tasks.  Finally, exit synchronization on the user tracking object.  The easiest way to do this synchronization is to put this processing in a synchronized method in the user tracking object.
Threads are each assigned to a user, which may be null.  The thread starts its loop by synchronizing on the user tracking object, then obtains a task if one is available.
To obtain a task, the thread first checks whether it is already assigned to a nonnull user.  If it is, it checks the Map for tasks for that user.  If it finds one, the thread removes the task from the map for servicing.  If it finds no tasks for the user, it removes the user from the Set of users with incomplete tasks, and also from the Set of users with assigned threads, then sets the user it is assigned to to null.
If the thread is assigned to a null user, it checks the Set of users without assigned threads.  If it finds one, it assigns itself to that user and moves that user from the Set of users without assigned threads to the Set of users with assigned threads.  The thread then checks the Map for tasks associated with that user - there is guaranteed to be one - and removes it for servicing.
After obtaining the task, but before servicing it, the thread exits the code block that was synchronized on the user tracking object.  Again, it's probably best to use a synchronized method in the user tracking object for the process of obtaining the task.  After exiting the synchronized block, the thread completes the task.  If the thread ultimately did not obtain a task, because none were available other than to users which already had threads assigned, the thread can sleep for a while before waking up and rechecking, but this should be outside the synchronization block.
You can probably figure out specific classes to use yourself.  You can get more sophisticated by having threads exit rather than sleeping, then restarting them as necessary, but it might be best to keep things simple at first.


text:
Q: How to get the value from table B whose max date is less than the date in table A I have two tables; table A and table B. Table A has StoreNumber, MatNumber and Date. Table B has StoreNumber, MatNumber, Date and ShipmentValue. I have to get the Shipment value from table B  for StoreNumber and MatNumber given that the Maximum Date in Table B for the StoreNumber and MatNumber should be less than the Date for the same StoreNumber and MatNumber in Table A (each row in Table A) . Please see the output table.
Table A:
StoreNumber MatNumber   Date
  A            9    3/30/2020
  A            9    3/30/2020
  B           10    3/18/2020
  B           10    3/18/2020
  A            9    3/13/2020

Table B:
StoreNumber MatNumber   Date    ShipmentValue
       A           9    3/10/2020   2
       A           9    3/12/2020   3
       A           9    3/18/2020   4
       B          10    3/4/2020    7
       B          10    3/7/2020    9
       B          10    3/16/2020   10

Output:
StoreNumber MatNumber   A.Date  B.Date  ShipmentValue
       A           9    3/30/2020   3/18/2020   4
       A           9    3/30/2020   3/18/2020   4
       B          10    3/18/2020   3/16/2020   10
       B          10    3/18/2020   3/16/2020   10
       A           9    3/13/2020   3/12/2020   3

A: This is a place where a lateral join is handy:
select a.*, b.date, b.shipmentvalue
from a left join lateral
     (select b.*
      from b
      where b.storenumber = a.storenumber and
            b.matnumber = a.matnumber and
            b.date <= a.date
      order by b.date desc
      fetch first 1 row only
     ) b
     on 1=1;  -- returns rows in a even when there are no matches

EDIT:
Wow.  Snowflake implements lateral joins and then limits them in a fundamental way.  Another method is more expensive but should work:
select ab.*, b.shipmentValue
from (select a.StoreNumber, a.MatNumber, a.Date, max(b.date) as b_date, b.shipmentvalue
      from a left join
           b
           on b.storenumber = a.storenumber and
              b.matnumber = a.matnumber and
              b.date <= a.date
      group by a.StoreNumber, a.MatNumber, a.Date
     ) ab join
     b
     on b.storenumber = ab.storenumber and
        b.matnumber = ab.matnumber and
        b.date <= ab.b_date

A: Tried with ROW_NUMBER and selecting 1st row after ordering date by desc.
SELECT  A.StoreNumber
        ,A.MatNumber
        ,A.Date
        ,B.Date AS B_Date
        ,B.ShipmentValue
FROM    TableA A
LEFT JOIN
        (
          SELECT  StoreNumber ,MatNumber  , Date   , ShipmentValue
          FROM
              (
                SELECT ROW_NUMBER() OVER (PARTITION BY StoreNumber, MatNumber ORDER BY DATE DESC ) AS ID,*
                FROM TableB
              ) A
          WHERE ID = 1
         ) B
ON   A.StoreNumber  = B.StoreNumber
AND  A.MatNumber    = B.MatNumber


text:
Q: Access the definition body of symbols How can I see the definition of a symbol from within macros?
As a special case, I wonder how to evaluate constant values at compile time using macros.
My approach works for "final val" but not for a local "val":
// scalaVersion := "2.11.0"
import scala.reflect.macros.blackbox.Context
import scala.language.experimental.macros

object Const {
  def m_same(c: Context)(i: c.Tree) = {
    import c.universe._
    val Literal(Constant(_)) = i
    i
  }
  def same(i: Any): Any = macro m_same
}

A local value is not recognized as a Literal(Constant(_)):
import org.scalatest.FreeSpec

class ConstSpec extends FreeSpec {
  "Int literal" in {
    assert(Const.same(42) === 42)
  }

  final val iFinal = "mytest"            // is a Literal(Constant(_))
  "final Int value" in {
    assert(Const.same(iFinal) === iFinal)
  }

  "local Int value" in {
    val iLocal = 42                       // is NOT a Literal(Constant(_))
    assert(Const.same(iLocal) === iLocal) // does NOT compile
  }
}

A: final val has special significance for constants and means inline them.
Your ordinary val looks like:
scala> q"{ val i = 42 ; i }"
res0: reflect.runtime.universe.Tree =
{
  val i = 42;
  i
}

scala> showRaw(res0)
res1: String = Block(List(ValDef(Modifiers(), TermName("i"), TypeTree(), Literal(Constant(42)))), Ident(TermName("i")))

I think Travis Brown's Metaplasm blog, i.e., things you shouldn't try at home with macros, includes examining the surrounding context for a def.
In this case, consulting the enclosing context on a statement basis would discover the def of the i you want, and you could examine its RHS.
Their macro philosophy is to think local and expand local.  I just made that up.  They also offer macro annotations for less-local things like companions.
But wait, they do offer an eval facility on Context. Is that sufficient for your use case?


text:
Q: How can I show 3 column in Xamarin with binding I want to make my grid system like each row has 3 columns. I am binding the products and each product Type, Name and Stock.
Here is my code:
<CollectionView Grid.Row="3" Margin="25" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
                        SelectionMode="None" ItemsSource="{Binding AllProducts}" x:Name="ProductsCollection">
            <CollectionView.ItemsLayout>
                <LinearItemsLayout Orientation="Vertical" ItemSpacing="20"/>
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <pv:PancakeView HasShadow="True" BackgroundColor="#EEF2FF" VerticalOptions="StartAndExpand"
                                    HorizontalOptions="FillAndExpand">
                        <Grid ColumnSpacing="3" HorizontalOptions="FillAndExpand">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="50"/>
                            </Grid.RowDefinitions>
                            <BoxView Grid.RowSpan="1" BackgroundColor="#EEF2FF"/>
                            <BoxView Grid.Column="1" Grid.RowSpan="1" BackgroundColor="#EEF2FF"/>
                            <BoxView Grid.Column="2" Grid.RowSpan="1" BackgroundColor="#EEF2FF"/>
                            <Button
                                Text="{Binding Name}"
                                Grid.Column="0"
                                HorizontalOptions="Center"
                                VerticalOptions="Center"
                                TextColor="Black"
                                BackgroundColor="#EEF2FF"
                                />
                        </Grid>
                    </pv:PancakeView>
                </DataTemplate>
            </CollectionView>

In this way, the products are being shown like each row has one column. So how can I make it 3?
Currently the view is like this:

So what I am trying to achieve is Cola, Water and Soda next to each other.
Here is my product list:
private ObservableCollection<Product> GetProduct()
        {
            return new ObservableCollection<Product>
            {
                new Product { Type = "Drink", Name = "Cola", Stock = 123 },
                new Product { Type = "Drink", Name = "Water", Stock = 123 },
                new Product { Type = "Drink", Name = "Soda", Stock = 123 },
                new Product { Type = "Food", Name = "Pizza", Stock = 123 },
                new Product { Type = "Food", Name = "Salad", Stock = 123 },
                new Product { Type = "Food", Name = "Pasta", Stock = 123 },
                new Product { Type = "Drink", Name = "Cola", Stock = 123 },
                new Product { Type = "Drink", Name = "Cola", Stock = 123 },
                new Product { Type = "Drink", Name = "Cola", Stock = 123 },
                new Product { Type = "Food", Name = "Fries", Stock = 123 },
                new Product { Type = "Food", Name = "Burger", Stock = 123 },
                new Product { Type = "Sauce", Name = "Mayo", Stock = 123 },
                new Product { Type = "Sauce", Name = "Ketchup", Stock = 123 },
            };
        }private ObservableCollection<Product> GetProduct()
        {
            return new ObservableCollection<Product>
            {
                new Product { Type = "Drink", Name = "Cola", Stock = 123 },
                new Product { Type = "Drink", Name = "Water", Stock = 123 },
                new Product { Type = "Drink", Name = "Soda", Stock = 123 },
                new Product { Type = "Food", Name = "Pizza", Stock = 123 },
                new Product { Type = "Food", Name = "Salad", Stock = 123 },
                new Product { Type = "Food", Name = "Pasta", Stock = 123 },
                new Product { Type = "Drink", Name = "Cola", Stock = 123 },
                new Product { Type = "Drink", Name = "Cola", Stock = 123 },
                new Product { Type = "Drink", Name = "Cola", Stock = 123 },
                new Product { Type = "Food", Name = "Fries", Stock = 123 },
                new Product { Type = "Food", Name = "Burger", Stock = 123 },
                new Product { Type = "Sauce", Name = "Mayo", Stock = 123 },
                new Product { Type = "Sauce", Name = "Ketchup", Stock = 123 },
            };
        }

So the Grid.Column needs to be 0, 1, 2 in Row 0 and then when the Row is 1, Grid.Column needs to be 0, 1, 2 again but I dont know is there any dynamic way.
This is what I am trying to achieve:

A: You want the collectionview to display as a grid which has three columns. So you should need to set  <CollectionView.ItemsLayout> as GridItemsLayout. Such as the following code. And the value of the Span means the number of the columns.
 <CollectionView HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
                SelectionMode="None" ItemsSource="{Binding AllProducts}" x:Name="ProductsCollection">
<CollectionView.ItemsLayout>
     <GridItemsLayout Orientation="Vertical" Span="3" />
 </CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
    <DataTemplate>
       <pv:PancakeView HasShadow="True" BackgroundColor="#EEF2FF" VerticalOptions="StartAndExpand"
                            HorizontalOptions="FillAndExpand">
            <Grid HorizontalOptions="FillAndExpand">
                <Grid.ColumnDefinitions>
                  <ColumnDefinition Width="auto"/>
                </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="50"/>
            </Grid.RowDefinitions>
                <Button
                        Text="{Binding Name}"
                        Grid.Column="0"
                        HorizontalOptions="Center"
                        VerticalOptions="Center"
                        TextColor="Black"
                        BackgroundColor="#EEF2FF"
                        />
            </Grid>
     </pv:PancakeView>
    </DataTemplate>
    </CollectionView.ItemTemplate>


text:
Q: Do someone know any good USB PHP server which support debugging? I am doing php work through http://www.usbwebserver.net/en/ and using it with phpstorm. When I try to debug I have seen that Dll could not be loaded PHP_curl so  I can't debug my code.
Do someone know any kind of trick as we have for .net in VWD. I means just put breakpoint and it's hit when browser make request.
Do someone know any good usb server for PHP that support debugging. If something more I want then I want to know how I can debug it like people debug their asp.net apps.

A: As far as I know, you cannot "step" through your code in PHP. Using strict error reporting will help.
When it comes to CURL you can also use curl_error to see what some potential 'fatal' problems are occurring.


text:
Q: Using SQL Server Authentication to connect to SSRS from a WinForms Application I'm busy testing SSRS to see if it's a viable alternative to our current reporting solution. I've set up SSRS on my local machine and have developed a working report using SQL Server Report Builder. Now what I'm trying to do is to call the report from within a WinForms application and display it in a ReportViewer control. The problem is that I've set up SQL Server to use SQL Server Authentication and I'm struggling to figure out how to connect to it programmatically.
The code I've pieced together so far looks like this:
Imports Microsoft.Reporting.WinForms

Public Class frmMain
Public v_report_name As String = "TestReport"
Public v_report_server As String = "http://elnah-ict-dt006:80"
Public v_report_path As String = "/reports_SSRS/"

Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    'create parameter array
    Dim paramlist As New List(Of Microsoft.Reporting.WinForms.ReportParameter)

    'create a specific parameter required by the report
    Dim param1 As New Microsoft.Reporting.WinForms.ReportParameter("ClientID")

    'add values to the parameter here we use a variable that holds the parameter value
    param1.Values.Add("0279")

    'add parameter to array
    paramlist.Add(param1)

    'Set the processing mode for the ReportViewer to Remote
    ReportViewer1.ProcessingMode = ProcessingMode.Remote

    'use the serverreport property of the report viewer to select a report from a remote SSRS server
    ReportViewer1.ServerReport.ReportServerUrl = New System.Uri(v_report_server)
    ReportViewer1.ServerReport.ReportPath = v_report_path & v_report_name
    'select where the report should be generated with the report viewer control or on the report server using the SSRS service.
    'Me.ReportViewer1.ProcessingMode = Microsoft.Reporting.WinForms.ProcessingMode.Remote

    'add the parameterlist to the viewer
    ReportViewer1.ServerReport.SetParameters(paramlist)

    Me.ReportViewer1.RefreshReport()
End Sub
End Class

When it hits the SetParameters line towards the bottom, it gets the following error message:

Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution.RSExecutionConnection.MissingEndpointException
    HResult=0x80131500
    Message=The attempt to connect to the report server failed.  Check your connection information and that the report server is a compatible version.
    Source=Microsoft.ReportViewer.WinForms

I've tried to find examples of how to set the username and password but from what I can tell, most examples are focused on using Windows Authentication. I've tried the following line but it doesn't work:
ReportViewer1.ServerReport.ReportServerCredentials = New ReportServerCredentials("SA", "mypassword")

I haven't worked in VB.NET for ages so please excuse any obvious errors.

A: Here's some code from a Web Forms project I was part of the team for recently:
private void SetCredentials()
{
    var userName = ConfigurationManager.AppSettings["SSRSUserName"];
    var passwordEncrypted = ConfigurationManager.AppSettings["SSRSUserPasswordEncrypted"];
    var passwordPlainText = SI.Crypto3.Crypto.Decrypt(passwordEncrypted, PASSPHRASE);
    var domain = ConfigurationManager.AppSettings["SSRSUserDomain"];

    if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(passwordPlainText) && !string.IsNullOrEmpty(domain))
    {
        this.EventsHubReportViewer.ServerReport.ReportServerCredentials = new ReportServerCredentials(userName, passwordPlainText, domain);
    }
}

That's C# but hopefully you can see that the important part is that last line.  I think that the equivalent in your case should be:
ReportViewer1.ServerReport.ReportServerCredentials = New ReportServerCredentials(userName, password, domain)

The domain value can be an empty String if your on the same domain as the server.
EDIT:
I looked more closely and the ReportServerCredentials class that code is using is one of our own.  In your case, you can use the Microsoft.ReportViewer.WinForms.ReportServerCredentials class, which I don't think has a constructor like that. Looking at the documentation for the NetworkCredentials property of that type indicates that you need to do this:
Dim credentials As New NetworkCredential(userName, password, domain)

ReportViewer1.ServerReport.ReportServerCredentials.NetworkCredentials = credentials


text:
Q: compiler.hooks.normalModuleFactory.tap Cannot read property 'tap' of undefined I am trying to use this plugin from here and it's giving me an error. WHY!
               compiler.hooks.normalModuleFactory.tap(
                                                   ^

TypeError: Cannot read property 'tap' of undefined

Here's the plugin
/*
    MIT License http://www.opensource.org/licenses/mit-license.php
    Author Tobias Koppers @sokra
*/
"use strict";

const path = require("path");

class NormalModuleReplacementPlugin {
    constructor(resourceRegExp, newResource) {
        this.resourceRegExp = resourceRegExp;
        this.newResource = newResource;
    }

    apply(compiler) {
        const resourceRegExp = this.resourceRegExp;
        const newResource = this.newResource;
        compiler.hooks.normalModuleFactory.tap(
            "NormalModuleReplacementPlugin",
            nmf => {
                nmf.hooks.beforeResolve.tap("NormalModuleReplacementPlugin", result => {
                    if (!result) return;
                    if (resourceRegExp.test(result.request)) {
                        if (typeof newResource === "function") {
                            newResource(result);
                        } else {
                            result.request = newResource;
                        }
                    }
                    return result;
                });
                nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => {
                    if (!result) return;
                    if (resourceRegExp.test(result.resource)) {
                        if (typeof newResource === "function") {
                            newResource(result);
                        } else {
                            result.resource = path.resolve(
                                path.dirname(result.resource),
                                newResource
                            );
                        }
                    }
                    return result;
                });
            }
        );
    }
}

module.exports = NormalModuleReplacementPlugin;