text:
Q: TensorFlow Custom Object Detection Disappointing Result - Why? I have just started TF Object Detection API two weeks ago, and manage to train a model to recognize a custom object, in my case, a Mecanum wheel.
Here's the details:

*

*No. of training images = 125

*All training images are around 500 x 500 (plus minus)

*Transfer Learning

*Model used = ssd_mobilenet_v1_coco

*batch size = 2

*total steps ran = 12715

*loss is around 0.5000 - 2.5000, some time it fluctuate to more than 10, I am not sure why

Here's the result:
The first image is encouraging.
The second image starts to disappoint me a little. I expect the model to detect FOUR (four boxes) Mecanum wheel. Why?
Then, I suspect that's there's something wrong with my trained model. I tried with the sample test images, the third image and fourth image, then I am sure that this is totally not the model I first aim for.
I have been reading this post which I think our problems are quite similar (and he manage to solve it). He mentioned that the input image needs to be less than 600 x 1024, so I tried with fifth image and unsurprisingly, the result is again disappointing.
I went through the tutorial series by sentdex and in the comment sections, I notice that there are many people face this problem too. So, what to do now?
Can someone please help me to edit the list? Why can't I make it to one paragraph one list?

A: 125 images? You will not be able to get very good results with that many images. If you want to validate that this is indeed the problem, try training with just subsets of your original 125 images.
For example, how bad is the output when you train on 10 images?
Does it get better when you use 50 images?
Does it get better yet when you use 125 images?
If the accuracy improves with increasing dataset size, you can extrapolate and guess that with 1000 images, you will be able to do even better. I would guess that that is your problem.


text:
Q: SUMIF#N/A with Subtotal I have a question on the formula that I have been trying to combine below formula and did not success.
=SUMIF(A2:A9,"<>#N/A",A2:A9)
=SUBTOTAL(9,A2:A9)

A: Use your filter to hide rows under Amount that have the value #N/A (error) and write the same formula for Subtotal it will give you the same result as Sumif

Also you can write "#N/A" (add quotes) Subtotal will understand it as text and ignore it
Usually Sum and Subtotal cannot ignore error and it result with error but it ignore text
If your Excel has the function Aggregate you can use it, Aggregate with special argument ignore error, hidden rows...
=aggregate(9,3,A2:A9)
9 for Sum
3 to ignore error, hidden rows and other aggregates
For more information on using Subtotal to sum visible rows click on
https://exceljet.net/formula/sum-visible-rows-in-a-filtered-list

redpajama_set_name: RedPajamaStackExchange


text:
Q: App is Lagging/Hanging. Why? I made a simple profile in my android app and after uploading image to firebase storage my app is lagging in speed, the image uploaded is in KBs size and in my profile I am using a Navigation Drawer whose sliding animation is also hanging. I am unable to figure out whats going wrong.

A: Maybe your are using the Main thread for doing all the job. This is one reason for UI thread to hang(i.e) the app didn't hang but it waits for the main UI thread to complete its work.
Generally, the app hangs for this reason. As suggested by Commonsware track methods. Also, try using background threads instead of main thread.


text:
Q: How can I deactivate several buttons when I click a button? I am having a button pattern in my python and qt  UI. The pattern is 3x3 which means 9 buttons in total.
Every button has a specific function. Now I am looking for a way to disable the other 8 buttons while 1 button is checked and re activate the other 8 buttons when the button is unchecked.
I tried to create a list of buttons to iterate through it when I click a button but I failed getting it to work since my buttons in the list becoming a string.
class Startscreen(QDialog):
    def __init__(self):
        super(Startscreen,self).__init__()
        loadUi("Main.ui",self)
        self.pushButton.clicked.connect(self.funct1)
        self.pushButton_2.clicked.connect(self.funct2)
        self.pushButton_3.clicked.connect(self.funct3)
        self.pushButton_4.clicked.connect(self.funct4)
        self.pushButton_5.clicked.connect(self.funct5)
        self.pushButton_6.clicked.connect(self.funct6)
        self.pushButton_7.clicked.connect(self.funct7)
        self.pushButton_8.clicked.connect(self.funct8)
        self.pushButton_9.clicked.connect(self.funct9)

    def funct1(self,checked):
        if checked:
            self.dosomething(1)
        elif not checked:
            print("i am not checked")

there are 8 other def functions. So I need help to find a way how to disable the other 8 buttons when 1 function is called.
I dont wanna copy paste self.pushButton_2-9.setEnabled(False) every time.
Is there some more elegant way to do that ?


text:
Q: Question about an inequation described by matrices. $A=(a_{ij})_{1 \le i, j \le n}$ is a matrix that$\sum_\limits{i=1}^{n} a_{ij}=1$ for every j and $\sum_\limits{j=1}^n a_{ij} = 1$ for every i and $a_{ij} \ge 0$.And
$$\begin{equation}
  \begin{pmatrix}
  y_1 \\
  \vdots \\
  y_n \\
  \end{pmatrix}
  =\mathbf{A}
  \begin{pmatrix}
  x_1 \\
  \vdots \\
  x_n
  \end{pmatrix}
  \end{equation}$$
$y_i$ and $x_i$ are all nonnegative.Prove that : $y_1 \cdots y_n \ge x_1 \cdots x_n$
It may somehow matter to convex function.

A: Hint:
If any $y_i$ is zero, from the condition on $a_{ij}$, at least one $x_k$ must be zero, so we may consider only positive $x_i,y_j$. Also the doubly stochastic matrix represents the majorization $x \succ y$, so by Karamata's Inequality, with the concave $\log$ function,  $\sum \log y_i \geqslant \sum \log x_i$.


text:
Q: Show that the linear operator $T_{B}:{\cal M}_{n}(\mathbb{C})\longrightarrow {\cal M}_{n}(\mathbb{C})$ has determinant zero. Let $B\in {\cal M}_{n}(\mathbb{C})$ and let $T_{B}$ the linear operator defined by $T_{B}(A)=AB-BA$. I need to show that it has determinant zero. To show that I exhibited a nonzero matrix $A$ such that $T_{B}(A)=0$, which is equivalent to show that $\ker(T_{B})\ne\{0\}$ and then $T_{B}$ is not invertible, which implies that it has determinant zero. The matrix that I exhibited was the identity matrix $I_{n}$. What I want to know if the argument is right. Thanks!.

A: What you did is fine.
Another possibility is to show that $T_B$ is not surjective. That's so because, for each $A\in\mathcal M_n(\mathbb C)$,$$\operatorname{tr}\bigl(T_B(A)\bigr)=\operatorname{tr}(AB-BA)=0.$$Therefore, for instance, $\operatorname{Id}_n\notin T_B\bigl(\mathcal M_n(\mathbb C)\bigr)$.


text:
Q: Ecranning quotes in Windows CMD Can I do something like ecranning quotes in variable? For example,
if "%1"=="/?" goto :help

Will return error if argument is "

A: Try "%~1". The tilde modifier will strip quotes from %1, if present.
Unfortunately there is no general safe way to process strings with special chars (quotes, parentheses, caret) in batch files. There are always some cases that blow up whatever you write.


text:
Q: GMaps4Rails MarkerCluster anchorText I have a special marker cluster where the text is not properly aligned.
I have tried everything to move the text position:
 Gmaps.map.customClusterer = function () {

    return [
        {
            textSize: 10,
            textColor: '#000',
            url: '<%= asset_path 'grey-dot-2.png' %>',
            height: 38,
            width: 38,
            raw: 'anchorText: [5,0]',
            anchorText: [5,0],
            opt_anchorText: [5,0]
        }
    ];
};

But the text is always rendered in the same place. Any idea?

A: Try    anchor: [5, 0]
I was having a similar issue and I think it was just a different markerCluster version being used.


text:
Q: Calling a script from a formula I am hoping you can help me with this question, so I created an alert message in google script, that works just fine, but I can't figure out how to "call the script" from a formula, so what I need is to use it as the TRUE value of an IF, my script is called AlertMessage, so I'm hoping to do something like this - IF(B3="Test", AlertMessage(),"") - Any assistance is appreciated, thank you!

A: Google Sheets formulas could call scripts, more specifically, there is a special type of Google Apps Script function than can be called this way, they are named custom functions. They are great to take advantage of JavaScript capabilities but please bear in mind that custom functions have several limitations, i.e. they should be included in a bounded script, their execution time limit is 30 seconds, they can't execute methods that require authorization, they can't open ui elements like alerts and prompts.
You might use JSDoc to show a on the function emerging help a description of the function as well of the parameters.
/**
 * Returns an alert message
 *
 * @customfunction
 */
function AlertMessage(){
   return 'Alert!'
}

A: I believe if you try it you will get the Error: Cannot call SpreadsheetApp.getUi() from this context.

A: According to the documentation all you need to do is to open the spreadsheet that you want to use, then open Apps Script from the settings of the Spreadsheet to "link" that script with the spreadsheet and use the function as if it was any other regular Google Sheets function.
If you created a separate script I think it will not work because the script needs to be opened from the spreadsheet.

A: The custom function will return the value inside the cell and can be the neighbor. But you can't return a message as Browser.msgbox or toast.


text:
Q: Internal Salesforce.com Error in a trigger when upserting Records Actually i was trying to understand flow, that's why i have create this trigger. I have created a CSV with 4 Records having 2 existing Records (which have another field changed value), 2 new record. When I upsert this CSV I  get an error Internal Salesforce.com Error and a mail from support@salesforce.com that "Please contact salesforce.com Customer Support "
It would be helpful if anyone can tell me output of trigger when upserting this CSV.

 trigger check on faculty__c (after update, after insert) {

        system.debug('This is Trigger.new size '+trigger.new.size());
        system.debug(trigger.new);

        if(trigger.isUpdate){

            system.debug('This is after update trigger.new' + trigger.new.size());
            system.debug(trigger.new);
            system.debug('This is after update trigger.old' +trigger.old.size());
            system.debug(trigger.old);

        }

        if(trigger.isInsert){

            system.debug('This is after insert ' +trigger.new.size());
            system.debug(trigger.new);
        }

    }

A: You need to modify the code in this trigger. At this point, it could execute in a Before context and not just in an After context.
trigger check on faculty__c (after update, after insert) {

        system.debug('This is Trigger.new size '+trigger.new.size());
        // system.debug(trigger.new);
        // the above line won't return anything

    if(trigger.isAfter){

        if(trigger.isInsert){

            system.debug('This is after insert ' +trigger.new.size());
            // system.debug(trigger.new);
            // the above line won't return anything
        }

        if(trigger.isUpdate){

            system.debug('This is after update trigger.new' + trigger.new.size());
            // system.debug(trigger.new);
            // the above line won't return anything
            system.debug('This is after update trigger.old' +trigger.old.size());
            // system.debug(trigger.old);
            // the above line won't return anything

        }

    }

}

I also have a preference and it's something of a convention to put insert code before update code, so you'll notice that I've re-ordered the sequence. The same applies to putting Before code in ahead of After code.
Once you do this, your debug log should give you the following:
This is Trigger.new size 4
This is after insert 2
This is after update trigger.new2
This is after update trigger.old ??
Not certain what this would be, have never checked, could depend on size of existing records or size of trigger.new.
Try it and find out. It's not really important.


text:
Q: jQuery cannot recognize appended cloned elements using jQuery.appendTo() I want to make a list of group inputs allow user to dynamically let user add/remove group row:

        <input id="_denominations[0].id.reference" class="removableHiddenOrder" type="hidden" name="denominations[0].id.reference" value="87-070329-034COP-4444">
        <input id="_denominations[0].denomination" class="removableHiddenDenom" type="hidden" name="denominations[0].denomination" value="10000">

        <input id="_denominations[1].id.reference" class="removableHiddenOrder" type="hidden" name="denominations[1].id.reference" value="87-070329-034COP-4444">
        <input id="_denominations[1].denomination" class="removableHiddenDenom" type="hidden" name="denominations[1].denomination" value="">

        <input id="_denominations[2].id.reference" class="removableHiddenOrder" type="hidden" name="denominations[2].id.reference" value="">
        <input id="_denominations[2].denomination" class="removableHiddenDenom" type="hidden" name="denominations[2].denomination" value="">

        .......

So each row include a group of form-field which include an input or select component(not show in above code) and some hidden fields and a delete link to remove current row from view.
Also I create a link to dynamic add a new row into the section
var rowTemplate = null;
j(document).ready(function() {
    // Save the row template
    rowTemplate = j('.form-denomination:first-child').clone();

    j("#add_link").click(function() {
            add_denomination();
    });
});

and here is the content of add_denomination function that clone the first row and replace any cloned id with new index, and append the cloned row after last row of the list.
function add_denomination() {
    var index = j('.form-denomination').length;
    // set the new row id
    var newRowId = 'row-' + index;
    var newRow = rowTemplate.clone().attr('id', newRowId);

    // Replace the id/name attribute of each input control
    newRow.find('div, input, select, a').each(function() {
        replaceAttribute(j(this), 'id', index);
        replaceAttribute(j(this), 'name', index);
        j(this).val('');
    });

    // add new element to the DOM
    newRow.appendTo('.form-denominations');
    alert("new list size = " + j(".delete-denomination").length);
    console.log("DONE!");
}

each time click on the add-link the pop up alert show the new list size (j(".delete-denomination").length increment by 1), which in my understanding, new row appended successfully.
The problem is the following method
// delete denomination row
j('.delete-denomination').click(function () {
    j(this).parent().remove();
}

ONLY WORKS FOR THE NON-CLONED ROW !!! Using firebug I can clearly see the appended row is successfully appended with same structure and same element as original rows but only difference is the id.
However, each time when I click on deleteBtn-[i], in which i is the cloned/appended row's index, the code even not going into the j('.delete-denomination').click() function, which in my understanding, Dom or jquery didn't recognize the new rows hence the failure of identifying the link by jQuery. It's kind of contradictory to the previous alert message that telling the size of list has grown.
But when I click on deleteBtn-[i] where i is the non-cloned row, everything works fine...
So the question is: how to append/add new doms and make them identified by jQuery or Dom? What is wrong in above processing? Is there any way to refresh the list so that Dom/jQuery understand the appended rows from all perspective?

A: jQuery 1.7+
j(".form-denomination").on("click", ".delete-denomination", function(){
    j(this).parent().remove();
});

jQuery 1.3+
j(".delete-denomination").live("click", function(){
    j(this).parent().remove();
 });

jQuery 1.4.3+
j(".form-denomination").delegate(".delete-denomination", "click", function(){
   j(this).parent().remove();
});

A: The problem is a matter of order and when expressions are evaluated.  When you call jQuery with a selector, the selector is evaluated at that time to select the matching elements which exist at that time.  The click handler is then registered to only those elements.  Elements which are created later are, naturally, not affected.
One solution, demonstrated in another example, uses jQuery's "live events" to apply the selector at the time each event is fired to determine what elements, if any, it would match.   There is a performance implication to this approach.
Another solution is to register the desired event handler on the newly created elements when you create them.

A: Add 'true' to the clone method in order to copy the data as well as the events attached to the original element.
rowTemplate = j('.form-denomination:first-child').clone(true);

This is disabled by default. Here is the clone documentation:
https://api.jquery.com/clone/
P.s. You don't need the click function within the document.ready and it won't bind until after the click.


text:
Q: PHP form one checkbox I've run into an issue I find very confusing. I have a form with one checkbox. I need the form to apply a value of 1 or 0 if the checkbox is checked or not.
<input type="checkbox" name="admin">

Then the PHP, something like this:
$update_data['admin'] = isset($_POST['admin']) ? '1' : '0';

It works if it's checked. I'm not sure how to go about getting the "off" state.

A: PHP Code need to be changed
$update_data['admin'] = empty($_POST['admin']) ? '0' : '1';

isset() will only check whether the value is set i.e. Null or Not. In ur case it set to ZERO
empty on the other hand check for both value is set to null and value is Zero if either of them true then return true .
and in HTML
<input type='checkbox' value ='1' name='admim'>

A: When checkbox is submitted with no value, its value is 'on' if retrieved from $_POST['admin']. I guess you can also do
$update_data['admin'] = ($_POST['admin'] === 'on') ? '1' : '0';

A: Checking if something is defined with isset is different from getting its value. Try this:
 <input type="checkbox" name="admin" value="checked_or_whatever_value_you_like">

 if(isset($_POST['admin'])){
     $update_data['admin'] = $_POST['admin'] == 'checked_or_whatever_value_you_like' ? '1' : '0';
 }

A: Everything should work as intended :)
Just to make sure that for was submitted:
admin

If checkbox is unchecked, the value (and it's key) wont be passed to query string.
So, check
If (isset($_POST['submit'])){
  $update_data['admin'] = isset($_POST['admin']) ;
  //actions if form has been submitted.
}

A: It seems to work with me, here is my sample code :
<form action="" method="POST">
    <input type="checkbox" name="admin">
    <input type="submit">
</form>
<?php
    $check = isset($_POST['admin']) ? '1' : '0';
    echo $check;
    var_dump($check);
?>

it will produce 1 string(1) "1" when you check the checkbox and 0 string(1) "0" if it's unchecked.

A: I found the answer in another post. With:
$update_data['admin'] = ($_POST['admin'] == 1) ? '1' : '0';


text:
Q: SQL query comparing column between 2 found sets I have one table, we'll call it BUS and it has two columns called DATE and TAG
I want to do two finds, as shown below
Query 1
select *
from BUS
where DATE < '2009-03-01'

&
Query 2
select *
from BUS
where DATE >= '2009-03-01'

I want to compare these two found sets, and delete any rows where the TAG from query 1 equals the TAG from query 2.
I tried an INTERSECT but I don't think that's the correct way. I can't wrap my head around this kind of query. Any advice?

A: Here is the Query.
delete
from BUS
where DATE < '2009-03-01'
and tag in
(select tag from BUS where DATE >= '2009-03-01')

A: You can simply do:
select tag
from BUS
group by tag
having min(date) < '2009-03-01' and
       max(date) >= '2009-03-01';

A: Another solution to your problem:
-- SELECT b1.*
DELETE b1
FROM BUS b1
  INNER JOIN BUS b2 ON b1.TAG = b2.TAG
WHERE b1.DATE < '2009-03-01' AND b2.DATE >= '2009-03-01';

Before executing the query you can comment out the DELETE statement, uncomment the SELECT statement and check if those are the rows you want gone.
Similar examples can be seen in the documentation (scroll down a bit) and some other SO questions:

*

*https://learn.microsoft.com/en-us/sql/t-sql/statements/delete-transact-sql?view=sql-server-2017

*How to Delete using INNER JOIN with SQL Server?


text:
Q: How to tab through all buttons in a tab group? It seems by default the Tab method for changing focus through widgets only stops once in a QButtonGroup and one is expected to move inside the group with the arrow keys (which only works with radio buttons, anyway). I want, however, to create a button group with QCheckBox inside, with the "exclusive" behaviour but allowing to uncheck all boxes, and where I can use the Tab key to move normally, as if they were not in a group.
The "clearable" part I could get it done with a subclass, but for the tabbing, it seems as soon as a button in the group gets the focus, it changes the focusPolicy for all other buttons such that they don't accept Tab (from 11 to 10), while the button that got the focus changes to 11. How can I disable/override this? Who is messing with the focus policies? I've tried defining a focusInEvent method for a QCheckBox, and I see that it changes "this button's" focusPolicy, but how can I know, from "this button" what the "other buttons" are (given that the final application may have many button groups)? Ideally, I would do something to the QButtonGroup subclass, but I don't know if it has any method that can respond to a focus change in its buttons.
Here is a small example. The "Tab order" button prints the current tab order and focus policies:
#!/usr/bin/env python3

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QSize

class Custom(QWidget):
    def __init__(self, text1, text2):
        QWidget.__init__(self)
        self.box = QCheckBox(text1)
        self.button = QPushButton(text2)
        layout = QHBoxLayout()
        layout.addWidget(self.box)
        layout.addWidget(self.button)
        self.setLayout(layout)
        self._text = f'{text1} {text2}'
        self.setFocusPolicy(QtCore.Qt.ClickFocus)

    def text(self):
        return self._text

class ClearableButtonGroup(QButtonGroup):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.button = None

    def addButton(self, button):
        try:
            super().addButton(button)
            button.pressed.connect(self.button_pressed)
            button.clicked.connect(self.button_clicked)
        except TypeError:
            pass

    def removeButton(self, button):
        try:
            button.pressed.disconnect(self.button_pressed)
            button.clicked.disconnect(self.button_clicked)
            super().removeButton(button)
        except AttributeError:
            pass

    def button_pressed(self):
        if (self.sender() is self.checkedButton()):
            self.button = self.sender()
        else:
            self.button = None

    def button_clicked(self):
        button = self.sender()
        if (button is self.button):
            exclusive = self.exclusive()
            self.setExclusive(False)
            button.setChecked(False)
            self.setExclusive(exclusive)

class HelloWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        centralWidget = QWidget(self)
        self.setCentralWidget(centralWidget)

        gridLayout = QGridLayout(centralWidget)

        self.box1 = Custom('Box 1', 'Button 1')
        self.box2 = Custom('Box 2', 'Button 2')
        self.box3 = Custom('Box 3', 'Button 3')
        self.box4 = Custom('Box 4', 'Button 4')
        gridLayout.addWidget(self.box1, 0, 0)
        gridLayout.addWidget(self.box2, 1, 0)
        gridLayout.addWidget(self.box3, 2, 0)
        gridLayout.addWidget(self.box4, 3, 0)

        button1 = QPushButton('Tab order')
        gridLayout.addWidget(button1, 4, 1)

        button1.clicked.connect(self.tab)

        group = ClearableButtonGroup(self)
        group.setExclusive(True)
        group.addButton(self.box1.box)
        group.addButton(self.box2.box)
        group.addButton(self.box3.box)
        group.addButton(self.box4.box)

    def tab(self):
        print_tab_order(self)

def print_tab_order(widget):
    w = widget
    while True:
        try:
            print('Text: {}; FocusPolicy: {}'.format(w.text(), w.focusPolicy()))
        except AttributeError:
            pass
        w = w.nextInFocusChain()
        if w == widget:
            break
    print('----')

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = HelloWindow()
    mainWin.show()
    sys.exit( app.exec_() )

A: It seems that this behavior is missing, if the QAbstractButton source code is revised it is implemented:
// https://code.qt.io/cgit/qt/qtbase.git/tree/src/widgets/widgets/qabstractbutton.cpp?h=5.14#n1088
void QAbstractButton::keyPressEvent(QKeyEvent *e)
{
    // ...
            d->moveFocus(e->key());
    // ...

// https://code.qt.io/cgit/qt/qtbase.git/tree/src/widgets/widgets/qabstractbutton.cpp?h=5.14#n247
void QAbstractButtonPrivate::moveFocus(int key)
{
    // ...
    if (candidate) {
        if (key == Qt::Key_Up || key == Qt::Key_Left)
            candidate->setFocus(Qt::BacktabFocusReason);
        else
            candidate->setFocus(Qt::TabFocusReason);
    }
}

As it is observed, all the buttons are considered as a unit and there is no way to disable it, so a workaround is to implement a class that has the same functionality, and in a previous post I implemented it which in your case is:
class ButtonManager(QtCore.QObject):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._buttons = []

    @property
    def buttons(self):
        return self._buttons

    def add_button(self, button):
        if isinstance(button, QtWidgets.QAbstractButton):
            button.toggled.connect(self.on_toggled)
            self.buttons.append(button)

    @QtCore.pyqtSlot(bool)
    def on_toggled(self, state):
        button = self.sender()
        if state:
            for b in self.buttons:
                if b != button and b.isChecked():
                    b.blockSignals(True)
                    b.setChecked(False)
                    b.blockSignals(False)

        else:
            button.blockSignals(True)
            button.setChecked(False)
            button.blockSignals(False)

# ...
button1.clicked.connect(self.tab)

button = ButtonManager(self)
button.add_button(self.box1.box)
button.add_button(self.box2.box)
button.add_button(self.box3.box)
button.add_button(self.box4.box)
# ...


text:
Q: Run psql command with postgres role I am try to run psql command with postgres role.
(1) sudo psql -U postgres Since postgres differs from my OS username, I receive the Peer authentication failed for user "postgres" error when I run it.
(2) But when I run sudo -u postgres psql, it succeeds
My terminal image
I'm not sure how the (2) commands can work because, according to a Postgres document, peer authentication happens automatically locally and my current OS username is different from postgres. (I made no changes to pg_hba.config or pg_ident.config files.)
And what is the difference between the (1) and the (2) command?

A: In your first attempt, you used sudo to become the root user (because there was no -u option) and tried to connect as database user postgres, which will fail with peer authentication because root is different from postgres.
In your second attempt, you used sudo to become user postgres and called psql without specifying a username, so that the username defaults to the same as your current operating system user name, namely postgres. Then peer authentication works.


text:
Q: Postgres - Filtering out words but excluding another pattern I'm trying to extract rows that has like '%asian%'. But the issue I'm having is this includes caucasian.
Could someone help me with a pattern that includes any label like '%asian%' but excludes caucasian? I'm mainly looking for an elegant solution. I already have a solution where I have a temp table that includes '%asian%' in the result set, and then I delete any results with caucasian. It's not elegant so I'm looking for a simpler solution to this.
Here is an example of the result set:
label
--------------------
WHITE/CAUCASIAN
Asian/Pacif Isl His
CAUCASIAN
ASIAN

And I would like the result to be
label
--------------------
Asian/Pacif Isl His
ASIAN

A: Try this:
 WHERE label ilike '%asian%' and label not ilike '%caucasian%' ?

source

A: You could try full-text search, but postgres's parser will treat a/b as a file path, so won't help in this case.
Houari's answer is fine but will be slow on big tables.
Try this:
--your table:

create table a (
  label text primary key
);

insert into a values
('WHITE/CAUCASIAN'),
('Asian/Pacif Isl His'),
('CAUCASIAN'),
('ASIAN');

--a function to split your labels into text arrays (splits on forward slash or space):

create or replace function get_terms(text) returns text[] language sql as '
  select regexp_split_to_array(lower($1), ''[\/ ]'');
'

--create a functional index for fast lookup:
create index terms on a using gin (get_terms(label));

--find rows where there is an array overlap:
select * from a where get_terms(label) && array['asian'];

http://sqlfiddle.com/#!15/14407/8


text:
Q: How to use state to update the value of variable in the button value property? I'm trying to write a Figma Plugin and using React.js, this is my first time trying to code, I have a great HTML/CSS knowledge but JS not so much.
Basically I want that the newCornerRadius variable to return the int inside the value property inside the button tag that it is being clicked. But right now I'm only getting the value of the first button, even if I click on the other buttons like 8, 16,...
Figma plugin interface and inspector
this is my ui.tsx code

import * as React from 'react'
import * as ReactDOM from 'react-dom'
import './ui.css'

declare function require(path: string): any

class App extends React.Component {

  cornerRadiusValues = [4, 8, 16, 24, 32, 40, 48];

  cornerRadiusButtons = this.cornerRadiusValues.map((cornerRadiusValue, index) =>
  <button key={index} value={cornerRadiusValue} id="cornerRadiusValue" onClick={() => this.setAttibute()}>{cornerRadiusValue}</button>
  );

  setAttibute = () => {
    const newCornerRadius = parseInt((document.getElementById('cornerRadiusValue') as HTMLInputElement).value);
    parent.postMessage({ pluginMessage: {type:'set-corner-radius-attribute',newCornerRadius}}, '*');
  }

  render() {
    return

      {this.cornerRadiusButtons}

  }
}

ReactDOM.render(<App />, document.getElementById('react-page'))

figma.showUI(__html__)

figma.ui.onmessage = msg => {
  if (msg.type === 'set-corner-radius-attribute') {

    for(const node of figma.currentPage.selection) {
      if ("cornerRadius" in node) {
        node.cornerRadius = msg.newCornerRadius;
      } else {
        console.log('corner radius not available')
      }
    }
  }
}

I think I need to use useState() but I simply can't figure out where and how!
Thanks in advance folks, been using Stack Overflow for almost a decade now, I'm happy to finally join the JS part of it.

A: for access to the value of the button, you can pass the value into the onClick method
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import './ui.css'

declare function require(path: string): any

class App extends React.Component {
state={currentValue:''}
  cornerRadiusValues = [4, 8, 16, 24, 32, 40, 48];

  cornerRadiusButtons = this.cornerRadiusValues.map((cornerRadiusValue, index) =>
  <button key={index} value={cornerRadiusValue} id="cornerRadiusValue"
onClick={() => this.setAttibute(cornerRadiusValue)}>{cornerRadiusValue}</button>
  );

  setAttibute = (value) => {
    this.setState({
...this.state,
currentValue:value
})
  }

  render() {
    return

      {this.cornerRadiusButtons}

  }
}

ReactDOM.render(<App />, document.getElementById('react-page'))

and you can access the value of state inside of component with this command this.state.currentValue

Copy an object to another one

var firstObject = {
    key1 : 'value1',
    key2 : 'value2'
};

var secondObject = {
    ...firstObject,
    key3 : 'value3',
    key4 : 'value4'
};


text:
Q: How to upload image using ReactJS and save into local storage? Here is my code is like:
<input
 type="file"
 id="imageFile"
 name='imageFile'
 onChange={this.imageUpload} />

Now I want to store this image in local storage and display it at another side. So I want to store the image in local storage. My code is inside of image upload function.
My function is like:
imageUpload(e) {
    console.log(e.target.value);
}

My console print is like C:\fakepath\user-bg.jpg

A: First, you should be aware that:

*

*LocalStorage can only store strings, so you can store files using a string representation only (like base64)

*LocalStorage is not really made for storing files, because browsers only offer you limited capacity
If this is really what you want to achieve, here's the solution:
class Hello extends React.Component {

  imageUpload = (e) => {
      const file = e.target.files[0];
      getBase64(file).then(base64 => {
        localStorage["fileBase64"] = base64;
        console.debug("file stored",base64);
      });
  };

  render() {
    return <input
     type="file"
     id="imageFile"
     name='imageFile'
     onChange={this.imageUpload} />;
  }
}

const getBase64 = (file) => {
  return new Promise((resolve,reject) => {
     const reader = new FileReader();
     reader.onload = () => resolve(reader.result);
     reader.onerror = error => reject(error);
     reader.readAsDataURL(file);
  });
}

JsFiddle

A: One implementation to upload files, using Java in the backend and Google App Engine that uses blob Blobstore. First try to call a function in your button that sends the file name:
<input id="btn-chooseImage" className="btn-file"
       onChange={() => this.handleUploadSession()}

After that, call a get function in backend to save the file uploaded and save as a img state to render it.
Js:
handleUploadImg(redirectAction){
     var file = $('#btn-chooseImage')[0].files[0]
     var formData = new FormData();
     formData.append("uploaded_files", file);
     var request = new XMLHttpRequest();
     request.open("POST", redirectAction, true);
     request.send(formData);
     request.onload = function() {
         if (request.status === 200) {
             var response = JSON.parse(request.responseText);
             this.setState({
                 img: '/serve?blob-key=' +response.blobKey.toString()
             });
         }
     }.bind(this);
};

handleUploadSession(){
    var request = new XMLHttpRequest();
    request.open("GET", "/uploadSession");
    request.send();
    request.onload = function () {
        if(request.status === 200){
            var redirectAction = JSON.parse(request.responseText);
            this.handleUploadImg(redirectAction);
        }
    }.bind(this);
}

Java:
@RequestMapping(value = {"/uploadSession"}, method = RequestMethod.GET)
protected void GetUploadSession(HttpServletRequest request,
                                    HttpServletResponse response) throws IOException {

    BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
    String redirectAction = blobstoreService.createUploadUrl("/myView");

    String json = new Gson().toJson(redirectAction);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}


text:
Q: Discord.js Cannot read property 'roles' of undefined let StaffPerms = false;
        let server = client.guilds.cache.get('737183847816364042')
        let member = server.members.cache.get(message.author.id)
        if(member.roles.cache.has('823136963246424064') == true){
            console.log("PERFECT")
        }

This keeps happing and I have no idea why. Each message that comes through this part of code is in DM's.

A: message.author returns a User object. You're trying to fetch a GuildMember using the User id instead of the GuildMember id and so it returns undefined. You could use Guild#member to get the GuildMember object but it will only work if the member is cached. A better solution would be to use GuildMemberManager#fetch.
const guild = client.guilds.cache.get('737183847816364042')
const member = await guild.members.fetch(message.author)
if (member.roles.cache.has('823136963246424064')) {
  // do something
}


text:
Q: Is it possible to edit/modify .so file? I'm developing an Android application which contains native code.
The native code is compiled in a .so file that has important algorithms inside.
I'm really worrying about the possibility that my .so file can be edited or modified and then re-build (re-pack). Like apks they can be modified and repacked to create a new one
I have several questions here:
1) Is there any way to edit/modify .so files and re-build?
2) If there are, how do people do that?
3) How to prevent .so files from being edited then re-built?

A: The short answer is that anything that a computer can read and understand, it can also modify. There is no bullet-proof signature mechanism in Android for Java or native code. Still, the so files are generally considered much less vulnerable than the Java code, even with obfuscation turned on.
Reverse engineering a shared library is hard but possible. Disassembly, change, and assembly back is not hard if one knows what to change.
There are many ways to strengthen protection of your C++ code against reverse engineering, but none will hold against a determined and well-funded attack. So, if the stakes are very high, consider running the important part of your algorithm on your server, and prey for its security.


text:
Q: SQLite: trouble building FTS5 loadable extension I'm on Mac trying to build FTS5 as loadable extension.
I've downloaded the SQLite sources, successfully executed ./configure and make fts5, obtained fts5.{c,h} files.
Now when trying to build the dynamic library for the extension I get:
gcc -g -fPIC -dynamiclib -o fts5.dylib fts5.c
In file included from fts5Int.h:18:0:
fts5_storage.c: In function 'sqlite3Fts5StorageOpen':
fts5_storage.c:305:9: error: 'sqlite3_api_routines' has no member named '__builtin___snprintf_chk'
In file included from /usr/include/secure/_string.h:33:0,
                 from /usr/include/string.h:192,
                 from fts5Int.h:21:
fts5_storage.c:305:26: warning: passing argument 1 of '__builtin_object_size' makes pointer from integer without a cast
fts5_storage.c:305:26: note: expected 'const void *' but argument is of type 'int'
In file included from fts5Int.h:18:0:
fts5_storage.c:308:11: error: 'sqlite3_api_routines' has no member named '__builtin___snprintf_chk'
In file included from /usr/include/secure/_string.h:33:0,
                 from /usr/include/string.h:192,
                 from fts5Int.h:21:
fts5_storage.c:308:28: warning: passing argument 1 of '__builtin_object_size' makes pointer from integer without a cast
fts5_storage.c:308:28: note: expected 'const void *' but argument is of type 'int'

What am I doing wrong?
I've tried gcc 4.9 and 5.5 from MacPorts on macOS

Interesting enough, on Linux (and with gcc5) I'm getting this error:
❯ gcc -g -fPIC -shared -o fts5.so fts5.c
fts5.h:24:21: fatal error: sqlite3.h: No such file or directory
compilation terminated.

And sure enough there's no sqlite3.h in the root of the sources directory, though I expect it should be created during the make step?
I can of course install libsqlite3-dev but I already have all the sqlite sources, why should I?

A: Thanks to Dan Kennedy from the SQLite dev team the issue is now resolved.
The 1st issue appeared to be the actual problem with SQLite source code when compiled on macOS, and it's now fixed here: http://www.sqlite.org/src/info/cd0471ca9f75e7c8
The 2nd problem was about the header file not generated because it requires a separate make step. So the full build instructions actually look like this:
./configure
make fts5.c sqlite3.h sqlite3ext.h
gcc -O2 -fPIC -shared fts5.c -o fts5.dylib


text:
Q: How to merge multiple Tiff files into one page tiff file? I have a requirement to create a single page tiff file by merging multiple tiff files through itextsharp. till now i only get multi-page tiff files. I there a way create it ?

A: If you are using iText 5, then you will find the PagedImages example in "iText in Action". You tagged the question as a .Net question, so instead of copy/pasting that Java example, I'll copy/past the C# version of that example:
public void AddTif(Document document, String path) {
  RandomAccessFileOrArray ra = new RandomAccessFileOrArray(path);
  int n = TiffImage.GetNumberOfPages(ra);
  Image img;
  for (int i = 1; i <= n; i++) {
    img = TiffImage.GetTiffImage(ra, i);
    img.ScaleToFit(523, 350);
    document.Add(img);
  }
}

If you are using iText 7, I can only give you the Java example for now (the documentation is still under development). You will find plenty of information about Image support in Chapter 3 of "iText 7: Building Blocks". Search for the iText 7 "PagedImages" example.
Important:
These examples explain how to create a PDF from one or more TIFF files with one or more pages. If you really want to create a TIFF file using iText, you are using the wrong tool. iText nor iTextSharp create TIFF files.


text:
Q: Access to virtual machine on vmware I have a virtual machine (VMware) running Windows 7 Ultimate, there is no firewall on the machine.
I can remote desktop to it,
I can successfully ping it from my development machine, and I can successfully ping my development machine from it.
The virtual machine appears in explorer under Network, but if I click on it, it says that windows cant communicate with the device or resource, same goes for trying to access it using UNC notation (\\servername) and even UNC using ip address (\\xxx-xxx-xxx)
Any ideas?

A: The Windows UNC syntax for a networked machine should be \\<name> or \\<ip>.
Edit:
You'll only be able to access shared folders over Microsoft Windows Network (aka SMB). You probably haven't set up shared folders. Read this: VMWare Workstation 4: Using Shared Folders


text:
Q: Possible to publish app to specific app stores? I was wondering, is it possible to publish an app to specific app stores, like ones where I know the ads will be targeted towards them? Or is there a way to set something in my app to do certain features for users in certain countries?

A: Yes.
In iTunesConnect when creating a new App, after the first couple pages there an option at the bottom to "specific stores". Click on this and select only the store you want the app to be available in.


text:
Q: How to read email using PHP's imap function and cronjob I have a PHP script which used for reading the emails and then insert details into database. When I run this script from browser it works perfect but when I tried to run this script using Linux cronjob at specified time then it failed.
Note: I already know how to use cron. My other scripts runs perfectly except this one.

A: I solved the issue by using the curl.
I create a cronjob which call my script with its actual URL like below and it works perfectly for me:
17 16 * * * /usr/bin/curl https://your_script_url


text:
Q: Python: Subtract Previous Row Index from Current Row, Same Index [Without Pandas] I am a Python (and programming as a whole) novice. I have seen hundreds of questions about this but all use the pandas package for data analysis. I already have several hundred lines of code which have not used pandas so I want to avoid pandas if possible, or if I can restructure my data using pandas, I am open for suggestions.
I have several thousand lines of raw data made into lists as entries. I use column to create another list from entries for simplicity of executing my functions.
I want to subtract an index (entries[2]) of a previous row from the same index of the current row. I see two ways of completing this:
current line entries[2] - previous line entries[2]
or
current line Elapsed Time - previous line Elapsed Time
Sample Raw Data:
1 c    4977321 200 200 007 003 033 001 002 003 092 001
2 d    4977789 010 120 100 100
3 e    4977816 175 194 000
4 f    4977868 225 220 100 300 001

Here, index 2 is time (i.e. 4977321)
My Code looks like this:
f = input('Type in File Name: ')  # What Raw Data log do we want to analyze?

def function():
    print_string = ''
    # do something with the data
    print_string += 'Time Delta: ' + str(delta_time)
    if 'Time Delta' in print_string:
        print(print_string)

initial_time = None  # Establishes 0 start point for time (not all captures start at 0ms)
with open(f, "r") as f:
    for line in f:
        entries = line.split()  # Organizes data line as a list, entries as indices
        column = [int(v) for v in entries[3:]]
        delta_time = int(entries[2]) - time
        time = int(entries[2])  # Time expressed in milliseconds
        if initial_time is None:
            initial_time = time
            delta_time = 0
        elap_time = time - initial_time  # Expressed as elapsed time from start of capture in milliseconds
        function()

f.close()

I have left out the bulk of the body of my code (entirely functions) as I did not see it a necessary piece of information.
I want the code to determine a value for delta_time and so it can print after executing the function. I would like the output to look like:
Time Delta: #  (nothing here, no previous line)
Time Delta: #  4977789 - 4977321
Time Delta: #  4977816 - 4977789
Time Delta: #  4977868 - 4977816

FYI, I used elap_time in my function when printing as well, just did not include it here.

A: Declare time before the loop with some default value
time = 0

Afterwards, invert delta_time line with time and do:
delta_time = int(entries[2]) - time
time = int(entries[2])


text:
Q: Slide on gallery app I'm currently working on a app that is a like a gallery app. The app need to load some images from the resources folder and when the user selects one, the app should load the selected image, and if the user slides the screen, the app should load the next image or the previous image.
The problem I have is that when I click the image the app always loads the first image. I try to use a intet with a int to solve it, but the program gives me an error.
I'm quite new in android programing, sorry if it is a simple question.
Here is the code of the app:
Main activity:
package com.example.erasor.pruebaslide;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void Image1 (View view) {
    Intent intent= new Intent(this, Slide.class);
    startActivity(intent);
}

public void Image2 (View view) {
    Intent intent = new Intent(this, Slide.class);
    intent.putExtra("position", 2);
    startActivity(intent);
}
}

Slide activity:
package com.example.erasor.pruebaslide;

import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class Slide extends AppCompatActivity {

private CustomPagerAdapter mCustomPagerAdapter;

private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_slide);

    Intent intent = getIntent();
    int position = intent.getIntExtra("position", 0);

    mCustomPagerAdapter = new CustomPagerAdapter(this);

    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mCustomPagerAdapter);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

}

int[] mResources = {
        R.drawable.image1,
        R.drawable.image2,
        R.drawable.image3,
        R.drawable.image4,
};

class CustomPagerAdapter extends PagerAdapter {

    Context mContext;
    LayoutInflater mLayoutInflater;

    public CustomPagerAdapter(Context context) {
        mContext = context;
        mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return mResources.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((RelativeLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View itemView = mLayoutInflater.inflate(R.layout.fragment_slide, container, false);

        ImageView imageView = (ImageView) itemView.findViewById(R.id.image);
        imageView.setImageResource(mResources[position]);

        container.addView(itemView);

        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object    object) {
        container.removeView((RelativeLayout) object);
    }
}
}

A: I think you are missing the part where you tell the mViewPager which position to display, try this:
mViewPager.setAdapter(mCustomPagerAdapter);
mViewPager.setCurrentItem(position);


text:
Q: Detecting use of ubuntu unity global menu I'm porting a commercial app to Linux, it is to run on several distros. When run on Ubuntu, the GtkMenuBar is removed from the app's window and placed on the main global menu bar. That's fine ... but there is a corresponding empty space in the app window where the menu was removed (it is placed with GtkFixed). I need to be able to detect when this has happened (and ONLY) when it has happened from any distro, so that I can reliably remove the empty space.
What's the best way to detect this? (ie via gtk_widget_... calls) What has been done to the GtkMenuBar to achieve this? Thanks.

A: The problem isn't that anything in particular has been done to the GtkMenuBar (it's just been hidden). The problem is because you're using GtkFixed to position it, and so things do not automatically resize when the MenuBar goes away.
Is there any particular reason you're using a GtkFixed to position things, rather than using the normal box layout structure of GTK+? You may want to look into using GtkApplication and/or GtkBuilder to create and present your user interface, instead, rather than using absolute positioning with GtkFixed.
If you wish to continue using GtkFixed, you'll need to watch a property (or signal) on the GtkMenuBar, and reposition and/or resize the other widgets in your window manually, when the GtkMenuBar is hidden.

A: Here's what I finally had to resort to for multiple distros and the possibility the user has set an exception:
static int menu_proxy = -1;
typedef void *(*KVoidPtoF)();

void *proxylib;
KVoidPtoF gtk_menu_proxy_get;

menu_proxy = 0;
proxylib = dlopen("libappmenu.so", RTLD_NOLOAD | RTLD_LAZY);
if (proxylib)
{
    gtk_menu_proxy_get = (KVoidPtoF)dlsym(proxylib,
        "ubuntu_menu_proxy_get");
    if (gtk_menu_proxy_get && (*gtk_menu_proxy_get)() != 0)
        menu_proxy = 1;
}


text:
Q: Is it possible to make IndexOf case-insensitive in PowerShell? I've got a problem searching an INDEX in an array made up by query sessions command in a terminal server.
This is the problematic script:
# Array of logged users in terminal servers
$a=Get-RDUsersession -CollectionName "BLABLA" -ConnectionBroker BLABLA.BLA.BL

# Array of all users with two columns from active directory
$b=Get-ADUser -filter * -properties TelephoneNumber,SamAccountName

Now imagine logging in the terminal server using the account name TEST instead of test.
If I do:
$c = $b[$b.SamAccountName.indexof("test")].TelephoneNumber

then I don't get the telephone number.
I think that's because of the case sensitivity, isn't it? If I type TEST in the search command, I get the correct number.
Is there any simple way to solve this problem and make the search of the index case-insensitive?
I've read about using the method [StringComparison]"CurrentCultureIgnoreCase", but it seems not working with array.
Thanks.

A: Since $b is an Object[] type, then you would probably want to do a Where-Object.
$b | Where-Object -FilterScript {$_.Samaccountname -like '*Smith*'} | Select-Object -ExpandProperty 'telephoneNumber'

That being said, an array in Powershell can be indexed case-insensitively if it is converted to a [Collections.Generic.List[Object]] type.
$b = [Collections.Generic.List[Object]]$b
$b.FindIndex( {$args[0].sAMAccountName -eq 'test'} )

Note that pulling every single user object in AD and filtering using where-object or index matching can be very slow. You can instead Get-ADUser as needed or pull all ADusers using a filter that pulls only the users returned in $a.
If you insist on having all ADUsers in one spot with one pull, consider looping over the list once to make a hash lookup so you can easily index the hash value.
#Create account lookup hash
$accountlookup = @{}
foreach ($element in $accounts) {
  $accountlookup[$element.SamAccountName] = $element
}

Hope that helps!


text:
Q: How to get percentage difference between two columns of different DataFrames? There are 2 DataFrames with coin pairs and float prices. Need to make new DataFrame with coin pairs and the price difference as a percentage.
First DataFrame in txt
Second DataFrame in txt
I tried this function, it didn't work
def get_diff():
    for i in df2['askPrice']:
        for x in df3['Low price']:
            i = float(i)
            x = float(x)
            try:
                if i > x:
                    res = (round(i) - round(x)) / round(x) * 100
                    print(round(res))
                else:
                    print('lower')
            except ZeroDivisionError:
                print(float('inf'))
get_diff()

A: Let's put the desired calcultaions in a new list then transform it into a column within df3
diff = [((y-x)/x)*100 for (y, x) in zip(df2['askPrice'],df3['Low price'])]

df3['diff'] = diff


text:
Q: Почему в javascript шаблонных строках map цикл получается с запятыми? Есть  javascript  код
 ` ${respons.some_array.map((item, index)=>`

${index}

 `)}`;

это выражение возвращает код с запятыми

0

     ,

1

     ,

2

     ,

3

     ,

4

     ,

5

     ,

6

     ,

7

     "

После использования join('') запятые убираются
Почему получаются запятые и как на них действует join

A: Потому что map возвращает массив, который для перевода в строку пропускается через toString, который разделяет элементы массива запятыми.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString
join - метод массива, который возвращает строку, в которой строковые представления элементы массива разделены строкой, которая передана в join как параметр.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join


text:
Q: How can I make my filter work as an "and" instead of "or" when there are multiple values? I have a working filter with two limitations.
1: It works as an 'or' instead of an 'and' when there are multiple values.
e.g.
filterArr = {'claim_number': null, 'status': 'Approved', 'patient': 'John Connor', 'service_date': null}

this.rows = [
   { 'claim_number': 1234, 'status': 'Approved', 'patient': 'John Connor', 'service_date': '1/10/2018', etc ...}
   { 'claim_number': 4567, 'status': 'Approved', 'patient': 'James Brown', 'service_date': '3/11/2018', etc ...}
   { 'claim_number': 7890, 'status': 'Approved', 'patient': 'Steven Hawkins', 'service_date': '2/1/2018', etc ...}

Currently all of these items would match when only the first one should because only the first one has both "status: Approved" and "patient: John Connor."
2: The second limitation is I want to trigger a match when there is a partial string that matches a full string in this.rows.
e.g.
filterArr = {'claim_number': 12, 'status': 'Approved', 'patient': null, 'service_date': null}

this.rows = [
    { 'claim_number': 1234, 'status': 'Approved', 'patient': 'John
       Connor', 'service_date': '1/10/2018', etc ...}
    { 'claim_number': 4567, 'status': 'Approved', 'patient': 'James
       Brown', 'service_date': '3/11/2018', etc ...}
    { 'claim_number': 7890, 'status': 'Approved', 'patient': 'Steven Hawkins', 'service_date': '2/1/2018', etc ...}

Again only number one should match as it contains the correct "status" and the first two digits in "claim_number."
This should be relatively simple as I had it working when I was passing a specific key, but now that the filter is dynamic it doesn't seem to be working correctly.
I've attached a jsFiddle for reference though it's not executing correctly because I'm using Reactive Forms in an Angular project.  Also, please only include answers that are solved using ES5 or ES6. I can't use flatMap() and other experimental features. Thank you.

A: See if this would work for you:

const rows = [ { 'claim_number': '1234', 'status': 'Approved', 'patient': 'John Connor', 'service_date': '1/10/2018'}, { 'claim_number': '4567', 'status': 'Approved', 'patient': 'James Brown', 'service_date': '3/11/2018'}, { 'claim_number': '7890', 'status': 'Approved', 'patient': 'Steven Hawkins', 'service_date': '2/1/2018'} ]

const filtrate = (i, f) => {
  const vals = Object.values(f).reduce((r,c) => (!!c ? r.push(c) : 0, r), [])
  return vals.every(x => Object.values(i).some(y => y.includes(x)))
}
const filterBy = (arr, f) => arr.filter(x => filtrate(x, f))

console.log(filterBy(rows, {'claim_number': null, 'status': 'Approved', 'patient': 'John Connor', 'service_date': null}))
console.log(filterBy(rows, {'claim_number': '12', 'status': 'Approved', 'patient': null, 'service_date': null}))

The idea is to first clean/sanitize the filter object and once you have only clean values then actually do the whole searching via Array.every & Array.some & Array.includes.
Also note that I converted the numbers to strings since it seems that is your intent if you are going to search if 12 is part of 1234 etc.
Here is the same code expanded for clarity:

const rows = [ { 'claim_number': '1234', 'status': 'Approved', 'patient': 'John Connor', 'service_date': '1/10/2018'}, { 'claim_number': '4567', 'status': 'Approved', 'patient': 'James Brown', 'service_date': '3/11/2018'}, { 'claim_number': '7890', 'status': 'Approved', 'patient': 'Steven Hawkins', 'service_date': '2/1/2018'} ]

const filtrate = (item, filter) => {
  const values = Object.values(filter).reduce((accumulator, current) => {
  if(!!current)
    accumulator.push(current)
    return accumulator
  }, [])
  return values.every(value => {
    return Object.values(item).some(itm => itm.includes(value))
  })
}
const filterBy = (allRows, filterObject) => {
  return allRows.filter(row => filtrate(row, filterObject))
}

console.log(filterBy(rows, {'claim_number': null, 'status': 'Approved', 'patient': 'John Connor', 'service_date': null}))
console.log(filterBy(rows, {'claim_number': '12', 'status': 'Approved', 'patient': null, 'service_date': null}))

A: This is the answer I ultimately ended up using. I found it to be the most straightforward.
@Input() filters: Array<any>;
allRows: Array<any> = [];

applyFilters() {
    this.rows = this.allRows;

    this.rows = this.rows.filter(row => {
        for (let filter of this.filters) {
            const filterVal = this.filtersForm.get(filter.key).value;
            const rowVal = row[filter.key];

            if (!!filterVal && rowVal.toString().toLowerCase().includes(filterVal.toString().toLowerCase())) {
                return true;
            }
        }

        return false;
    })
}


text:
Q: Let $f: \mathbb{R} \to \mathbb{R}$ be a continuous function. Show that {$x-f(x): |x|\leq 1$} is a compact set in $\mathbb{R}$. Question:
Let $f: \mathbb{R} \to \mathbb{R}$ be a continuous function. Show that {$x-f(x): |x|\leq 1$} is a compact set in $\mathbb{R}$.
Attempt:
If $f(x)$ is a continuous function, $f(x)$ is bounded. Let $|f(x)|\leq M$.
Then, $|x-f(x)|\leq |x|+|f(x)|=|x|+M$. Since $|x|$ is bounded by $1$, $|x-f(x)|$ is also bounded.
I'm having difficulty trying to find a reason why it's a closed set. Maybe using the inverse image of $f(x)$?

A: The set is the image of a continuous function : x -f(x) over a closed interval.So it is also a closed interval : if the function takes two values it takes all the values between them and it has maximum and minimum (Weierstrass theorem).


text:
Q: Identity in MVC and JWT + Identity for API part of the application I got the .NET 5 web app (MVC = Model View Controller), here I have added DefaultIdentity with roles. I add a user to the role, I make an attribute for authorization at controller and methods for a specific role and it works, this part is working ok, e.g.  [Authorize(Roles = Admin)]
Now I have added the API Controllers. I want to use the same attributes on API controllers, but this time user would log to the system via API, and get the JWT, and that JWT contains a specific role, and this is not the problem it also works!
But the problem is putting those two together to work!
After I added logic to the ConfigureServices method, I'm not able to access MVC controllers anymore, and API ones are working. What I'm saying is that 401 is returned, it is obvious that I overwrite the rules, but I want to keep both, any tips or solution is welcome!
services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; })
                .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters
                    {
                        ClockSkew = TimeSpan.Zero,
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(key),
                        ValidateIssuer = true,
                        ValidIssuer = appSettings.Issuer,
                        ValidateAudience = true,
                        ValidAudience = appSettings.Issuer,
                        ValidateLifetime = true
                    };
                });

A: i had similar problem, dont remember exactly what it was but im sure it was something with the order of added auths in startup.cs
I have it set like below:
app.UseHttpsRedirection();
app.UseRouting();
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
app.UseCookiePolicy();

services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddRoles<ApplicationRole>()
                .AddEntityFrameworkStores<IdentityContext>();

services.AddAuthentication()
              .AddCookie(cfg => cfg.SlidingExpiration = true)
              .AddJwtBearer(cfg =>
              {
                  cfg.RequireHttpsMetadata = false;
                  cfg.SaveToken = true;
                  cfg.TokenValidationParameters = new TokenValidationParameters()
                  {
                      ValidIssuer = Configuration["Tokens:Issuer"],
                      ValidAudience = Configuration["Tokens:Issuer"],
                      IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
                  };
              });

A: I think you have authentication working, but need to add authorization to your startup services and your api controllers. In .Net Core 5 (or I'm using 3.1), add something like this to your startup services:
// can save "UserCredentials" as a public constant, to re-use in api
services.AddAuthorization(options =>
{
    options.AddPolicy("UserCredentials", policy =>
    {
        policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
        // add additional policies
    });
});

Then in your api controller, reference the new "UserCredentials" policy:
[HttpPost("Post")]
[Authorize(Policy = "UserCredentials")]
public async Task<ActionResult> Post()
{

}

A:
After I added logic to the ConfigureServices method, I'm not able to access MVC controllers anymore, and API ones are working.

In your code, we can find that you configured JwtBearerDefaults.AuthenticationScheme as default authenticate scheme, which cause the issue.
To make both your MVC and API work well, you can try to remove x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; from AddAuthentication method. And then specify the authentication scheme or schemes to use by applying the [Authorize] attribute on your API action(s), like below.
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[HttpGet]
public IActionResult GetAll()
{


text:
Q: Code from python 2.7 to 3.5 (unicode) I am really unfamiliar with python. I just have the code and wanted to upgrade the code to python 3.5.
I changed it and now there is one problem. I had the following code:
map(unicode.strip, set(list))

With Python 2.7 everyything works fine. But with Python 3.5 PyCharm cannot do anything with unicode. So, how do I have to change the code so that Python 3.5 can work with it?
Thanks :)

A: You should change unicode to str.


text:
Q: JavaFX - Show cells in empty table In JavaFX, when a table has no data, there is no grid shown, instead it is a white plane saying "No content in table".
What do I have to do if I want the common grid, just with no content instead of the white plane?

A: I solved the problem using two tricks:

*

*I added one entry to the table with empty values in order to make sure the grid is shown.

*I set setMouseTransparent(true) so the first entry is not clickable and the table really acts as if nothing is there.


text:
Q: place one object on left and second on right My screen looks like this:

Currently, the text comes at the top while the red section (VideoComponent) comes at the bottom. I want the VideoComponent to appear on the left side while all the text should move towards the right. Like a flexbox maybe?
    return (

                In this section.....TEXT

                    <VideoComponent />

    );

The VideoComponent:
    return (

        <Sketch className="sketch" />

)

css for video
.sketch{
    padding-top: 30px;
}

.button{
    padding-left: 0px;
    padding-top: 20px;
}

.secondbutton{
    padding-left: 0px;
    padding-top: 70px;
}

A: If you want the text to wrap around the video, use float. In the example below, I have a paragraph of text that I want to wrap around two images, so I insert the images in the p tag where I want them to be vertically, and use float: left.

img {
  width: 100px;
  height: 100px;
  background: blue;
  margin: 10px;
}

#left {
  float: left;
}

#right {
  float: right;
}

   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

A: I think that flex is better than float.
return (

                <VideoComponent />

                In this section.....TEXT

);

CSS
.context {
   display: flex;
   justify-content: space-between;
}


text:
Q: How do I open a browser window from a desktop notification that's generated from a background page? I have built a simple chrome application which has a background page that shows desktop notifications when a new article is available.
If a user clicks on the notifications when a browser window is open, then they are taken to the new article page and everything is right with the world.
If however the browser is closed when the notification is shown, then the href does not open the browser. I have also tried to capture the click and set a window.open, but that isn't working either.
As an aside, it would also be good if I could check to see if an instance of my app is already open and use that window/tab when the notification is clicked, but that's secondary to the first problem.
Any help would be great!
Thanks

A: Check if chrome window is open. if open the create in new tab else oepn new window.
chrome.windows.getCurrent(function(currentWindow) {
  if (currentWindow != null) {
    return chrome.tabs.create({
      'url': url
    });
  } else {
    return chrome.windows.create({
      'url': url,
      'focused': true
    });
  }
});

A: Have you tried, creating a window then tab using the Chrome API? For example:
linkDOM.addEventListener('click', function() {
  chrome.windows.create({url: 'http://someurl.com'});
}, false);

I usually do the above when programmatically opening a link from extension pages.


text:
Q: How to output a cumulative list from Wordpress API in Ionic infinite scroll I am new to angular and Ionic and I am trying a practical approach of learning by working with sample projects from GitHub.
I have downloaded this project: https://github.com/enappd/ionic4-wordpress-integration and I have modified the WordPress URL where I am pulling the data from.
Currently, the load more infinite scroll seems to replace the output results with the next page results instead of combining the results of the second page with the first page.
I am currently attempting a solution by modifying the home.page.ts like so:
import { Component } from '@angular/core';
import { ToastController, LoadingController } from '@ionic/angular';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  url: string = '#######################'
  items: any = []
  page: any = 1;
  constructor(
    public http: HttpClient,
    public Router: Router,
    public toastCtrl: ToastController,
    public loadingController: LoadingController
  ) {

    this.loadPost(this.url, this.page, true);
  }
  async loadPost(url: string, page, showLoading) {
    const loading = await this.loadingController.create({
      message: 'Loading Your posts'
    });
    if (showLoading) {
      await loading.present();
    }

    const route = this.url + 'wp-json/wp/v2/posts'
    // set pagination
    if (!page) {
      page = '1';
    }

    return new Promise((resolve, reject) => {

      var concat;

      // check if url already has a query param
      if (url.indexOf('?') > 0) {
        concat = '&';
      } else {
        concat = '?';
      }

      this.http.get(route + concat + 'page=' + page)
        .subscribe(data => {

          if (showLoading) {
            loading.dismiss();
          }
          this.items = data;
          console.log(data);
          resolve(this.items);
        },
          error => {
            if (showLoading) {
              loading.dismiss();
            }
            reject(error);
            this.presentToast(error.error.message)
          })
    });
  }
  doRefresh(event) {
    this.loadPost(this.url, 1, false).then(() => {
      event.target.complete()
    }).catch(() => {
      event.target.complete()
    });
  }

  loadMore(event) {

    this.page++;

    this.loadPost(this.url, this.page, false).then(items => {

      let length = items["length"];

      for (var i = 0; i < length; ++i) {
            this.items.push( items[i] );
          }

      console.log(this.items);

      event.target.complete()
    }).catch(() => {
      event.target.complete()
    });

  }

  /*
  loadMore(event) {

    this.page++;

    this.loadPost(this.url, this.page, false).then(() => {
      event.target.complete()
    }).catch(() => {
      event.target.complete()
    });

  }
  */

  async presentToast(msg) {

    let toast = await this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'bottom',
      cssClass: 'normal-toast'
    });

    toast.present();

  }

  goToPostDetails(post) {
    this.Router.navigate([`post-details/${post.id}`]);
  }
}

Please help me to figure out what I am doing wrong.

A: It is because this.items = data; in loadPost(). If this.items exist you should merge two arrays instead of replacing it and then remove:
let length = items["length"];
for (var i = 0; i < length; ++i) {
  this.items.push( items[i] );
}

A: So based on lonwi's answer, I realised I was not suppose to be modifying the loadMore() and therefore reverted to using this for the loadMore()...
loadMore(event) {

    this.page++;

    this.loadPost(this.url, this.page, false).then(() => {
      event.target.complete()
    }).catch(() => {
      event.target.complete()
    });

  }

Furthermore in loadPost(), I have replaced the line this.items = data; with...
let length = data["length"];
          for (var i = 0; i < length; ++i) {
            this.items.push( data[i] );
          }


text:
Q: Canonical example of non-Hausdorff Ellis group Given a dynamical system (that is, for me, a group $G$ acting by homeomorphisms on a compact Hausdorff space $X$), the Ellis group (which can be defined in terms of the universal minimal flow (as here), or just as the ideal group of the enveloping semigroup of the dynamical system) has a natural compact $T_1$ topology, which makes it a semitopological group.
I've seen claims that the topology is typically not $T_2$, but no examples. Are there any specific examples where it is not hard to see that the Ellis group is not Hausdorff?


text:
Q: Tyrion Lannister Acquits Himself? Guess Again! If I were to say that, in his perilous negotiations with the slavers (transcribed below), Tyrion Lannister had "acquitted" himself, would I be saying that Tyrion had A) repaid or settled a debt or obligation incurred (i.e., the insult of the slaver's disparaging assumption) or B) conducted himself in a specified manner? Either sense seems plausible, but not both in the instant case.
Prior to my inquiry I was unfamiliar with sense (A). On the few occasions I've encountered the usage of "acquit" outside of the legal sense of being found "not guilty," it has always collocated with "well," as in the latter sense (B) and the lexicons I've consulted fail to specify the conduct. Is it even possible to "acquit oneself" other than adroitly (well)?
Scene: Boss Slaver and his Lieutenant discussing the fate of their captives

Lt. Slaver: (indicating Jorah Mormont) Salt mines?
Boss Slaver: That ... or a galley-slave. He looks strong enough.
Lt. Slaver: What about the dwarf?
Boss Slaver: Worthless. Cut his throat.
Tyrion: Wait. Wait. Wait, wait, wait! Let's discuss this!
Boss Slaver: And then ... chop off his cock. We'll sell it for a fortune ... a dwarf's cock has magic powers.
Tyrion: Wait. Wait. Wait, wait, wait! You can't just hand a dried cock to a merchant and expect him to pay for it! He has ta know it came from a dwarf! And how could he know, unless he sees the dwarf?
Lt. Slaver: It will be a dwarf-sized cock.
Tyrion: Guess again!

ACQUIT
Collins defines "acquit" thusly:

acquit vb (tr):
3. to repay or settle (something, such as a debt or obligation)
4. to perform (one's part); conduct (oneself)
[C13: from Old French aquiter, from quiter to release, free from, quit]

Whereas, the American Heritage Dictionary of the English Language defines acquit:

2. To conduct (oneself) in a specified manner: acquitted herself well during the interview.
3. Archaic To release or discharge from an obligation, such as a debt.
4. Obsolete To repay.
[Middle English aquiten, from Old French aquiter: a-, to (from Latin ad-; see quite in Indo-European roots).] Definitions/etymology from TFD

SPOILER ALERT: Tyrion manages to hold on to his genitalia ... so far.

A: In my search of Google Books, I came across references to acquitting oneself not only "well" or "honorably", but "creditably", "better than the others". "adequately", and  even "badly".  So there are definitely degrees.
That said, it seems two things are clear:
1)  The usage of "acquit himself" has been declining rather steadily since its zenith (circa 1700), see Ngram.
2) "Acquit oneself" seems to have had a third sense, (perhaps derived from the "debt" one), which seems wider, and very much like  "rid oneself of": to acquit oneself of a duty, of a foolish notion, or of whatever thing one wants to be rid of. Sort of like how one can use quitar in Spanish to describe anything from taking off your clothes to abandoning a relationship.
Sorry I couldn't paste in some examples, but here's the link.

A: For your third sense, Oxford tells us that the idiom is:

(acquit oneself of) archaic Discharge (a duty or responsibility):
they acquitted themselves of their charge with vigilance

PS- I don't think using acquit here makes sense. I think Tyrion was just saving his skin, which isn't much of a 'responsibility', per se; nor a repayment or a settlement. acquit could be used in other cases, though. Say, if Ser Jorah saved Tyrion from the Stone Men out of a sense of responsibility, then it could be said that 'Ser Jorah acquitted himself of his responsibility towards his prisoner'.


text:
Q: Play sound file multiple times (before first time has finished playing) with JavaScript? Im working on a tutorial to improve my JavaScript. I need to make a 'drum kit' where pressing keys makes a sound.
I have a code pen here although it doesn't work fully as I cant reference the audio files: https://codepen.io/anon/pen/vmzjPy
Ive got it working if you tap the keys slowly. However if you tap the same key quickly the sound doesn't play multiples times until the first instance has finished playing.

      A
      clap

      S
      hihat

      D
      kick

      F
      openhat

      G
      boom

      H
      ride

      J
      snare

      K
      tom

      L
      tink

  <audio data-key="65" src="sounds/clap.wav"></audio>
  <audio data-key="83" src="sounds/hihat.wav"></audio>
  <audio data-key="68" src="sounds/kick.wav"></audio>
  <audio data-key="70" src="sounds/openhat.wav"></audio>
  <audio data-key="71" src="sounds/boom.wav"></audio>
  <audio data-key="72" src="sounds/ride.wav"></audio>
  <audio data-key="74" src="sounds/snare.wav"></audio>
  <audio data-key="75" src="sounds/tom.wav"></audio>
  <audio data-key="76" src="sounds/tink.wav"></audio>

A: Audio elements wont play again until they've finished playing, so the solution is to rewind the audio element before you play it:
soundsElem.currentTime = 0;
soundsElem.play();


text:
Q: Java calling a method with object parameters to main method play.java: https://pastebin.com/4bzfE76z
values.java: https://pastebin.com/6mnUzKyA
player.java: https://pastebin.com/qiFymMF6
stats.java: https://pastebin.com/P24AUpXV

I have a method called start in play.java with object parameters. The objects were originally declared in values.java inside the sValues method. I want to call the method start to the main method of play.java but I'm not sure what to write inside the parameters of the call.
Inside values.java:
    player user = new player ();
    user.setP_Name (username);
    user.setP_ATK (atk);
    user.setP_HP (hp);

    stats[] enemies = new stats [3];
    enemies [1] = new stats ();
    enemies [1] = gob;
    enemies [1].getName ();
    enemies [1].getHP ();
    enemies [1].getATK ();
    enemies [1].getMANA ();
    enemies [2] = new stats ();
    enemies [2] = orc;
    enemies [2].getName ();
    enemies [2].getHP ();
    enemies [2].getATK ();
    enemies [2].getMANA ();

Inside play.java, I use the objects like this:
System.out.println ("Hitpoints[HP]: " + enemies [i].getHP ());

and it works great because I included these two objects into the parameter of the method:
public static void start (player user, stats[] enemies)

However, whenever I want to call start in the main method for it to do the things I want it to, it gives me errors. This is how I've been trying to call it:
public static void main (String[] args)
{ //main method
start(player, stats);
} //main method

Am I doing something wrong? Any help appreciated. I'll gladly add more information if needed. New to coding and not sure what specific details need to be provided.
My errors:
{ //main method
    player player = new player();
    start(player, stats);
} //main method

Error on: start(player, stats);
Cannot find symbol. Symbol: variable stats. Location: class play.
This error is given when I hover over "stats" when using netbeans.

A: The main method is the entry point of your program. You have not instantiated anything else yet so there are no objects to pass into your start method.
You might need to give us more of your code, but you might need to try something like this first - and I this is making a lot of assumptions about your code
public static void main (String[] args)
{ //main method
    Player player = new Player(); // This is an instance of your Player class
    // and initialize your stats array.
    Values v = new Values();
    start(player, stats);
} //main method

Also providing the error you are getting may help also.
EDIT
After reviewing your code I can see some problems. In your Values class you have the method sValues which creates the enemies as you said, however they stats[] that you created in that method only has the scope of that method, so when that method is finished, the enemies you created have now disappeared.
You also have a lot of static reference - this is bad practice and you need to remove as much as possible. To do this you can change something like
 Values.sValues();

to
 Values v = new Values(); // in the constructor call what you need to
 v.sValues();

You need to think about where you are going to store your enemies stats array. You could move it to the top of your Values class and add a getter for it then your code could look like this
Values.java
public class values {
    public static String clear = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
    public static String username;
    public static int atk = 1;
    public static int hp = 10;

    private stats[] enemies;

 // .. your other code
public void sValues () // this method should not be static
{ //sValue method
    // .. other code
    enemies = new stats [3];  // Remove the declaration at the start of this line
    // .. other code
}

public stats[] getEnemies()
{
    return enemies;
}

Play.java
public static void main (String[] args)
{
    // Create a player
    player player = new player("Steve", 10, 10);
    // Initialise your values
    Values v = new Values();
    // create the enemies (this could be done in your values constructor)
    v.sValues();
    // Start with these enemies
    start(player, v.getEnemies());
}

A: Seems to me you have to create an instance of values.java and then get the player and stats objects from there to pass on to the main method. where are player, stats being declared in the play.java class?
try:
{
  player player = new player();
  stats[] stats = new stats[5];

  start(player, stats);
} //main method

and initialize stats array with desired values


text:
Q: Bug color with my console menu I am trying to do a menu driven by the keyboard's arrows. For this, I change the background of the selected item, like this:
But once I go to the last item and go up again, this happens:
There is my code for the selected items:
void Print::Select(int pos, int realpos)
{
  if (pos == realpos)
    SetconsoleTextAttribute(handle, 112);
  else
    SetConsoleTextAttribute(handle, m_white);
}

The entire code:
#include <Windows.h>
#include <iostream>
#include <conio.h>
#include "Options.hpp"
#include <math.h>
#define left_arrow  75
#define right_arrow 77
#define down_arrow  80
#define up_arrow    72
#define page_up     73
#define page_down   81
Config g_options;

class Print
{
public:

    void                Infos();
    void                State(bool state);
    void                Select(int pos, int realpos);
    void                Loop();
    void                CheckInput();
    int                 m_red = 0xC;
    int                 m_green = 0xA;
    int                 m_white = 0x7;
    int                 m_selection_color = 70;
    char                m_input;
    int                 m_min = 1;
    int                 m_max = 0;
    unsigned int        m_selection_pos = 1;
    HANDLE              handle = GetStdHandle(STD_OUTPUT_HANDLE);

}; extern Print g_print;

void Print::CheckInput()
{
    m_input = _getch();
    Sleep(30);
    if (m_input == page_up && g_options.current_tab != g_options.tabs[3])
        g_options.current_tab = g_options.tabs[rand() % 3];
    else if (m_input == page_down && g_options.current_tab != g_options.tabs[0])
        g_options.current_tab = g_options.tabs[rand() % 3];

    if (m_input == up_arrow && m_selection_pos != m_min)
        m_selection_pos -= 1;
    else if (m_input == down_arrow && m_selection_pos != m_max)
        m_selection_pos += 1;

    else if (m_input == left_arrow || m_input == right_arrow)
    {
        if (g_options.current_tab == g_options.tabs[0])
        {
            switch (m_selection_pos)
            {
            case 1:
                g_options.aim_enabled = !g_options.aim_enabled; break;
            case 2:
                g_options.aim_autoconfig = !g_options.aim_autoconfig; break;
            case 3:
                g_options.aim_rcs = !g_options.aim_rcs; break;
            case 4:
                if (m_input == right_arrow) { g_options.aim_smooth++; break; }
                else if (m_input == left_arrow) { g_options.aim_smooth--; break; }
            }
        }

        if (g_options.current_tab == g_options.tabs[1])
        {
            switch (m_selection_pos)
            {
            case 1:
                g_options.esp_enabled = !g_options.esp_enabled; break;
            case 2:
                g_options.esp_ennemies = !g_options.esp_ennemies; break;
            case 3:
                g_options.esp_friends = !g_options.esp_friends; break;
            }
        }

        if (g_options.current_tab == g_options.tabs[2])
        {
            switch (m_selection_pos)
            {
            case 1:
                g_options.trigger_enabled = !g_options.trigger_enabled;
            case 2:
                g_options.triggerbot_ennemies = !g_options.esp_ennemies;
            case 3:
                g_options.trigger_team = g_options.trigger_team;
            case 4:
                if (m_input == left_arrow) { g_options.trigger_delay -= 1; break; }
                else if (m_input == right_arrow) { g_options.trigger_delay += 1; break; }
            }
        }

        if (g_options.current_tab == g_options.tabs[3])
            g_options.noflash_enabled = !g_options.noflash_enabled;
    }
}

void Print::Select(int pos, int realpos)
{
    if (pos == realpos)
    {
        SetConsoleTextAttribute(handle, 112);
    }

    else if (pos != realpos)
        SetConsoleTextAttribute(handle, m_white);
}

void Print::State(bool state)
{
    if (state)
    {
        SetConsoleTextAttribute(handle, m_green);
        printf("[ON]\n");
        SetConsoleTextAttribute(handle, m_white);
    }
    else if (!state)
    {
        SetConsoleTextAttribute(handle, m_red);
        printf("[OFF]\n");
        SetConsoleTextAttribute(handle, m_white);
    }
}

void Print::Infos()
{
    system("cls");
    std::cout << "========= " << g_options.current_tab << " =========" << std::endl << std::endl;
    if (g_options.current_tab == g_options.tabs[0])
    {
        Select(1, m_selection_pos); std::cout << "Enabled: "; State(g_options.aim_enabled);
        Select(2, m_selection_pos); std::cout << "Autoconfig: "; State(g_options.aim_autoconfig);
        Select(3, m_selection_pos); std::cout << "Recoil control: "; State(g_options.aim_rcs);
        Select(4, m_selection_pos); std::cout << "Smooth: " << g_options.aim_smooth;
    }
    else if (g_options.current_tab == g_options.tabs[1])
    {
        Select(1, m_selection_pos); std::cout << "Enabled: "; State(g_options.esp_enabled);
        Select(2, m_selection_pos); std::cout << "Glow ennemy: "; State(g_options.esp_ennemies);
        Select(3, m_selection_pos); std::cout << "Glow team: "; State(g_options.esp_friends);
    }
    else if (g_options.current_tab == g_options.tabs[2])
    {
        Select(1, m_selection_pos); std::cout << "Enabled: "; State(g_options.trigger_enabled);
        Select(2, m_selection_pos); std::cout << "Shoot ennemy: "; State(g_options.triggerbot_ennemies);
        Select(3, m_selection_pos); std::cout << "Shoot team: "; State(g_options.trigger_team);
        Select(4, m_selection_pos); std::cout << "Delay: " << g_options.trigger_delay;

    }
    else if (g_options.current_tab == g_options.tabs[3])
    {
        Select(1, m_selection_pos); std::cout << "Noflash: "; State(g_options.noflash_enabled);
    }
}

void Print::Loop()
{
    while (true)
    {
        Infos();
        if (g_options.current_tab == g_options.tabs[0] || g_options.current_tab == g_options.tabs[2])
            m_max = 4;
        else if (g_options.current_tab == g_options.tabs[1])
            m_max = 3;
        else if (g_options.current_tab == g_options.tabs[3])
            m_max = 1;

        CheckInput();

    }
}

I just noticed that the bug occurs only with the smooth option


text:
Q: Segment between intersection of diagonals' bases is parallel to side edges. I have a box $ABCDA'B'C'D'$ where its lower base is $ABCD$ and its higher base is $A'B'C'D'$. Let $O$ be intersection of the diagonals of $ABCD$ and $O'$ be the intersection of the diagonals of $A'B'C'D'$.
How can I prove that $O'O || A'A$? I know it's easy to see it but I don't have a clue in how to prove it geometrically.

A: The quadrilateral $ACC'A'$ is a rectangle.
Indeed, by the definition of a cube $AA'$ is orthogonal to both $AB$ and $AD$. Therefore, since if a line is orthogonal to two transverse lines lying in a plane, then it is orthogonal to the whole plane, $AA'$ is orthogonal to the face $ABCD$. Analogous arguments show that $CC'$ is orthogonal to the same face $ABCD$. Therefore $AA'$ and $CC'$ are parallel to each other and so they lie in a common plane $AA'CC'$. Combined with the fact that $AA'=CC'$ (as edges of a cube) we conclude that $ACC'A'$ is a parallelogram. However, since $AA'$ is orthogonal to face $ABCD$, it is orthogonal to any line lying in $ABCD$. In particular, $AA'$ is orthogonal to $AC$. Thus, $ACC'A'$ is a parallelogram with a right angle, so it is a rectangle.
Consequently $AC = A'C'$ and $AC \,\|\, A'C'$. The points $O$ and $O'$ are the midpoints of the segments $AC$ and $AC'$ respectively. Therefore $$AO = \frac{1}{2} AC = \frac{1}{2} A'C' = A'O$$ and $AO \,\|\, A'O'$. Therefore $AOO'A'$ is a parallelogram (in fact a rectangle) and consequently $AA' = OO'$ and $AA' \,\|\, OO'$. Moreover, $OO'$ is orthogonal to both faces $ABCD$ and $A'B'C'D'$.


text:
Q: how can we change image view background on swipe? As a example,have to draw a layout of images.
I inflated an ImageView into a layout. When I swipe on the screen I need  to change the color of the each circle to green. How should I do it. I tried with gesture detector, but I can't get what I need.

and this is my code.. I create this view by inflating an image view..
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(1024);
        setContentView(R.layout.test);
        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        height = displaymetrics.heightPixels;
        width = displaymetrics.widthPixels;
        count = width/30;
        totalCircles = count * (height/30);
        horizontalSpace = width%30;
        verticalSpace = height%30;
        mRelativeLayout = (RelativeLayout)findViewById(R.id.fl);
        mRelativeLayout.setPadding(horizontalSpace/2, verticalSpace/2, horizontalSpace/2, verticalSpace/2);
        for(int i=1;i<totalCircles+1;i++){
             myButton = new ImageView(this);
             myButton.setId(i);
             myButton.setImageResource(R.drawable.circle_grey);
             LayoutParams lp = new LayoutParams(0,0);
             if(i%count != 1){
                 lp.addRule(RelativeLayout.RIGHT_OF, imgViews.get(i-2).getId());
                 if(imView != null){
                     lp.addRule(RelativeLayout.BELOW, imView.getId());
                 }
                 if(i%count == 0){
                     imView = myButton;
                 }
             }else{
                 if(imView != null){
                     lp.addRule(RelativeLayout.BELOW, imView.getId());
                 }
             }

             mRelativeLayout.addView(myButton,lp);
             myButton.getLayoutParams().width = 30;
             myButton.getLayoutParams().height = 30;
             imgViews.add(myButton);
             myButton.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                     if(event.getAction() == MotionEvent.ACTION_DOWN){
                         System.out.println("Inside touch listener");
                            ImageView imV = (ImageView)v;
                            imV.setImageResource(R.drawable.circle_green);
                     }

                    return false;
                }
            });

        }
    }

A: Jack K Fouani's  answer is partially correct. Instead of imagView.onTouch you need to use gridview.onTouch.
Please check this sample.
gv.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            float currentXPosition = event.getX();
            float currentYPosition = event.getY();
            int position = gv.pointToPosition((int)currentXPosition, (int) currentYPosition);
            //using the position obtained you can change the imageview color.
            }

            return true;
        }
    });

A: Instead of inflating one ImageView. You should fill a GridView where every GridCell contains a circle image. Now
set the OnTouchEvent of those Gridcells to change the ImageView within the GridCell.

A: my advice is to use GrideView with adapter , inside the adapter you will have position for each imagView the position allow you to check if image is touched or not depending on that you can change ImageView color to white or green


text:
Q: IF ELSE statement based on count > 1 or =1 to execute different functions MY SQL php I have a table in MY SQL that may either have an entry in a certain column as 1 or > than 1. Basically based on the current Value of the Entry in the column I would wish to run either of two methods:
Part code:
$db->prepare("SELECT vote_count FROM tbl_voter_count WHERE voter_phone_number  = :phone ");
$sql->bindParam(":phone", $phone );
try {

    $sql->execute();

} catch(PDOException $e) {

    echo $e->getMessage();

}

$data = $sql->fetchAll(PDO::FETCH_ASSOC);
if($data){
foreach ($data as $row) {
$count = $row['vote_count'];
 if($count == 1)
 {
   //Logic 1
 }

   //Logic 2

}

Based on the above,is there a better way of aciving this with far much less code entanglement and Lines.?

A: try {
  $sth->execute();
  foreach($sql->fetchAll(PDO::FETCH_ASSOC) as $row) {
   if($row['vote_count'] == 1) {
     //Logic 1
   } else {
   //Logic 2
   }
  }
} catch ...

edit
I'd recommend using the catch at the end of the request.

A: Your method is fine. You can also do:
$db->prepare("SELECT vote_count > 1 as multivote FROM tbl_voter_count WHERE voter_phone_number  = :phone ");
$sql->bindParam(":phone", $phone );
try {

    $sql->execute();

} catch(PDOException $e) {

    echo $e->getMessage();

}

while ($row = $sql->fetch(PDO::FETCH_ASSOC) {
    if ($row['multivote']) {
        //Logic 1
    } else {
        //Logic 2
    }
}