text:
Q: asp.NET 4.8 WebRequest errors with "The underlying connection was closed: An unexpected error occurred on a send." On one particular website on my web server WebRequests have started throwing the following error: "The underlying connection was closed: An unexpected error occurred on a send."

*

*My asp.NET website is running framework version 4.8.

*I am requesting a page on the same website that is doing the request.

*This code has been in place for years and has suddenly stopped working on this website

*This same code works fine on a different website running on the same webserver

Request code:
Dim myReq As System.Net.WebRequest = System.Net.WebRequest.Create("https://example.com")
myReq.Method = "GET"

myReq.ContentType = "text/html; encoding='utf-32'"

Dim wr As System.Net.WebResponse = myReq.GetResponse()
Dim receiveStream As System.IO.Stream = wr.GetResponseStream()
Dim reader As System.IO.StreamReader = New System.IO.StreamReader(receiveStream, Encoding.UTF8)
Dim content As String = reader.ReadToEnd()

I have tried adding the following to the page doing the request, and the global.asax, but it did not work. It should not be required, though, because I am using .net 4.8:
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12

A: As mentioned in the comments, this is often an issue with the internal DNS or a HOSTS file entry. Either the server is resolving the site's domain to the wrong internal address, or it's trying to access the site's public address and confusing the router.


text:
Q: Subtract two count values with different where clause in influxDb I have a measurement in influxDb with two keys: operation and count. The operation key can store two different values: 'add' and 'delete'.
I want to subtract the sum(count) value when operation='delete' to sum(count) value when operation='add'.
The following query is supported in mysql but it throws and error in influxql:
select (select sum(count) from measurement where operation='add') - (select sum(count) from measurement where operation='delete');
How can this be done using a single influxql query ? I don't think influxql allows two different where clauses in this case.

A: InfluxQL doesn't support this kind of multiquery math. You will need to calculate it on the app level.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I display a timer counting for 10 seconds I have this Javascript code in my website:
<!DOCTYPE html>

      <title>change picture</title>

       <button onclick="displayPreviousImage()">Previous</button>
       <button onclick="displayNextImage()">Next</button>

I want above each image to show the timer counting the seconds to 10 in this format 00:00
The first 00 for minutes and the second 00 for seconds.
In this case there is only seconds but I want to show 00:00 and only the right 00 will be counting since it's only seconds now.
And every 10 seconds the timer will reset and the shown image will change.

A: Ok then, try using this code it will help you :
JAVASCRIPT:
var counter = 0;

setInterval(function () {
if (counter<10)
++counter;
else counter =0;
document.getElementById("count").innerHTML="00:"+counter;
}, 1000);

HTML:

You can test it here.
Edit:
And to make it fit your question try to use this function:
function swap(one, two) {
document.getElementById(one).style.display = 'block';
document.getElementById(two).style.display = 'none';
}

And your code will be:
setInterval(function () {
if (counter<10){
    ++counter;
} else {
    counter =0;
    swap(one,two);
}
    document.getElementById("count").innerHTML="00:"+counter;
}, 1000);

And "one" and "two" here are the ids of your imgages tags.


text:
Q: onMouseEnter and onMouseLeave behaving opposite as expected in my code - why? In a component AddWordPartButton's class, I initialized a state isHovered to false and used onMouseEnter and onMouseLeave to change its value.
Here's the mapping I want (which seems to me that I've defined in the code):

*

*onMouseEnter ⇒ isHovered = true

*onMouseLeave ⇒ isHovered = false
What happens is the opposite of what I expect to happen and I don't see any reason for this behavior.
Here's the mapping that seems to occur:

*

*onMouseEnter ⇒ isHovered = false

*onMouseLeave ⇒ isHovered = true
I use AddWordPartButton in another component with nothing that should be affecting its behavior, calling with this <AddWordPartButton /> inside a render function of the other component - it works perfectly fine except for this.
This is the code:
import React from 'react;

class AddWordPartButton extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            isHovered: false,
        };
        this.onMouseEnterHandler = this.onMouseEnterHandler.bind(this);
        this.onMouseLeaveHandler = this.onMouseLeaveHandler.bind(this);
    }

    onMouseEnterHandler() {
        this.setState({isHovered: true});
        console.log(this.state); //logs false
    }

    onMouseLeaveHandler() {
        this.setState({isHovered: false});
        console.log(this.state); //logs true
    }

    render() {
        <div className={classes.addWordPartButton__Container}
            onMouseEnter={this.onMouseEnterHandler}
            onMouseLeave={this.onMouseLeaveHandler}
        >
        </div>

    }

}

Why is this happening and how can I fix it?

A: set state is async, use this instead, the callback argument to the setState func will fire after it sets state. It is opposite bc you are always logging one step behind the new state update.
onMouseEnterHandler() {
    this.setState(() => ({isHovered: true}), () => console.log(this.state));
}

onMouseLeaveHandler() {
    this.setState(() => ({isHovered: false}), () => console.log(this.state));
}


text:
Q: how to define decryption of caeser cipher Ok So I missed class and am trying to do the work they did in there. One of the problems was fixing a caeser cipher. I believe I have fixed all except for the last part which is of course the part I'm stuck on. This is what I have.
#Change to T to lowercase in plaintext
#add : to the end of if statement
def encrypt(plaintext, alphabet, key):
        plaintext = plaintext.lower()
        cipherText = ""
        for ch in plaintext:
            idx = alphabet.find(ch)
            if idx >= 0 and idx <= 25:
                cipherText = cipherText + key[idx]
            else:
                cipherText = cipherText + ch
                #add return ciphertext
        return cipherText
#add def to decrypt line
def decrypt(cipherText, alphabet, key):
        plainText = ""
        for ch in cipherText:
            idx = key.find(ch)
            #add and idx <= 25 to if statement
            if idx >= 0 and idx <= 25:
                plaintext = plaintext + alphabet[idx]
            else:
                plaintext = plaintext + ch
        return plaintext
#got rid of def main
#have myCipher = encrypt
# define both myCipher and my plain to the encrypt and decrypt
alphabet = "abcdefghijklmnopqrstuvwxyz"
key = "nopqrstuvwxyzabcdefghijklm"
plaintext = input("Enter the text you want to encrypt: " )
myCipher = encrypt(plaintext, alphabet, key)
myPlain = decrypt(cipherText,alphabet, key)

print(myCipher)
print("Checking if decryption works: ")
print(myPlain)

When I run the code it says cipherText is not defined in
myPlain = decrypt(cipherText,alphabet, key)

I have tried a few different options but I seem to be going further from fixing it than what I have it as now. So is a way I can define cipherText  in that line or do I have to redo that line and change it to something else?
This is the error I get when I tried to change cipherText as LalolDublin suggested
 Traceback (most recent call last):
  File "C:\Users\David\Downloads\caeser (2).py", line 32, in <module>
    myPlain = decrypt(myCipher ,alphabet, key)
  File "C:\Users\David\Downloads\caeser (2).py", line 21, in decrypt
    plaintext = plaintext + alphabet[idx]
UnboundLocalError: local variable 'plaintext' referenced before assignment

A: you can't use cipherText it's a local variable only within that function...
myCipher = encrypt(plaintext, alphabet, key)
myPlain = decrypt(myCipher ,alphabet, key)

A: Ok as LalolnDublin stated I needed to put myCipher instead of cipherText, he was right but I also needed to change the position of where I entered the code so that it could work properly. This is the finished product if anyone has a similar problem as I did here.
key = "nopqrstuvwxyzabcdefghijklm"
plainText = input("Enter the text you want to encrypt: " )
alphabet = "abcdefghijklmnopqrstuvwxyz"
def encrypt(plainText, key, alphabet):
        plainText = plainText.lower()
        cipherText = ""
        for ch in plainText:
            idx = alphabet.find(ch)
            if idx >= 0 and idx <= 25:
                cipherText = cipherText + key[idx]
            else:
                cipherText = cipherText + ch
        return cipherText
myCipher = encrypt(plainText, key, alphabet)
def decrypt(myCipher, plainText, alphabet, key):
        plainText = ""
        for ch in myCipher:
            idx = key.find(ch)
            if idx >= 0 and idx <=25:
                plainText = plainText + alphabet[idx]
            else:
                plainText = plainText + ch
        return plainText
myPlain = decrypt(myCipher, plainText, alphabet, key)

print(myCipher)

print("Checking if decryption works: ")

print(myPlain)


text:
Q: can't remove PHPMyAdmin folder : "rm: cannot remove... Operation not permitted" There is folder come with XAMPP called (PHPMyAdmin), I can't remove it from my PC and I don't have any permission, Access under the owner is (no list, no create/delete, no access) and under Group is (None) and for Security context is (unknown), therefore how can I remove this folder.
As root I tried the remove the folder, I got the following error:
rm: cannot remove '/opt/lampp/phpmyadmin/tbl_gis_visualization.php': Operation not permitted

A: Usually you need to be root to remove files in that location, that's if we're talking /opt/lampp/ location here. To remove that folder use sudo to run the command as root:
sudo rm -rf /path/to/PHPMyAdmin

A: It is possible that the immutable flag is on.
You can execute the below in order to modify it:
sudo chattr -i /opt/lampp/phpmyadmin/tbl_gis_visualization.php

man chattr

chattr - change file attributes on a Linux file system
A file with the `i' attribute cannot be modified: it cannot be  deleted or  renamed,  no  link  can  be created to this file and no
  data can be written to the file.  Only the superuser or a  process
  possessing  the        CAP_LINUX_IMMUTABLE capability can set or clear
  this attribute.

Similar issues in PHPAdmin were a file in phpadmin was flagged as immutable and chattr was used in order to allow delete the file:

*

*help-i-cant-delete-phpmyadmins-setup-php -

*Cannot-edit-config-inc-php-Can-t-open-file-for-writing

@GeorgeUdosen question in the below comment:

*

*Does the -i flag on a file prevent root from removing the parent folder?

Answer: Setting the +i flag on a file prevent root from removing the parent folder.
$ mkdir alx
$ cd alx/
$ sudo chattr +i xyz
[sudo] password for [snip]:
$ sudo rm xyz
rm: cannot remove 'xyz': Operation not permitted
$ cd ..
$ sudo rm -rf alx/
rm: cannot remove 'alx/xyz': Operation not permitted


text:
Q: Can gdb's tui be divided into three windows?
*

*When I use gdb tui for debugging. I can use layout split to display the source code window and assembly window at the same time. But I also want to see the value of the register. If I use layout regs to display the register window, it will replace the source code window with the register window. Can I display source code, assembly code, and register windows at the same time?

*When tui is displayed, I want to use the commands I used before. When I use the up and down arrow keys, the code window moves up and down. Is there any way to prevent me from re-entering the previously used commands?


text:
Q: Can superstring theories predict our 4 dimensions? Popular science literature is replete with the necessity for superstring theories to live in at least 10 dimensions, requiring at least 6 of them to be compactified so that they are not observable. But can they predict that 4 dimensions are not compactified? Or conversely, for a superstring theory in e.g. 10 dimensions, are there arguments against compactifying 7 dimensions? or only 5? Arguments other than being ruled out by observation I mean.
My question has been marked as a duplicate of Q10651. Only the answer A10723 is relevant to my question. It quotes a paper "Relaxing to Three Dimensions by Karsh and Randall which seems to address my exact question:

We propose a new selection principle for distinguishing among possible vacua that we call the "relaxation principle." The idea is that the universe will naturally select among possible vacua through its cosmological evolution, and the configuration with the biggest filling fraction is the likeliest. We apply this idea to the question of the number of dimensions of space. We show that under conventional (but higher-dimensional) FRW evolution, a universe filled with equal numbers of branes and antibranes will naturally come to be dominated by 3-branes and 7-branes. We show why this might explain the number of dimensions that are experienced in our visible universe.

But this is far too advanced for me as I can barely recognise buzzwords! And answer A10723 is of rather low quality, just a vague description of the goal of the paper which does not give any hindsight into the physics in there. In any case, this also mean that the other question, Q10075, mine is marked as a duplicate of, has even poorer answers than they look like at first glance. Following the cited by link on the page of Karsh and Randall paper turns out several citations which look to address my question and Q10075, but again at a level I can't grasp.


text:
Q: Asp Gridview: How Prevent Empty columns from binding? I have created a Asp GridView with 5 columns. But not always does the sql query return 5 columns, certain times it is 4 and 3 as well. So, when lesser number of columns are returned, I get the following error:-
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'ExactRate3'
How to prevent this?

A: Remove static columns from GridView and set property AutoGenerateColumns='true'

A: You can make sure the query always return 5 values, even if you select only 3 columns. You can aslo set the value for those dummy columns.
SELECT ExactRate1, ExactRate2, NULL AS ExactRate3, 'emptyString' AS ExactRate4, 0 AS ExactRate5

This way the GridView databinding will find ExactRate3 and not throw an error.


text:
Q: How do I make multiple celery workers run the same tasks? I have one task that is checking a url speed, but i want that to be executed by multiple celery workers in different servers. I want the same url to be checked by multiple workers.
How can I do that?

A: If you could set ignore_result=True . Try Broadcast
If you couldn't, check Routing Tasks and send the task multiple times to different queues, for different IDC for example, and corresponding workers.


text:
Q: Problem with authentication from different domains using Django sessions I am developing a bookmarklet which essentially adds a toolbar to a web page user is currently looking at. To use it, user needs to be logged in.
To login user clicks on 'Singin' which displays a standard form containing Username, Password etc fields. When user successfully logs in they may chose to navigate to a different web-site. When on another page, they (a) re-load the bookmarklet (b) their session is retrieved from the server (c) user doesn't need to login again. Pretty standard I've would have thought.
Using Django sessions and JQuery.
I'm having troubles implementing the above usecase. Here are some problems I've encountered:

*

*Cross domain POST AJAX requests are disallowed. That was solved with JSONp. I doubt it is a very secure approach but for now it works.

*My server returns the session id in a cookie, however when the user navigates to a different page I don't really know how to retrieve that session id to send back to my server. Can I even read third party cookies from my JavaScript?

I'm looking for some guidelines on implementing the above usecase. Ideally I don't want to redirect user to another page for them to sign in. Any suggestion would be greatly appreciated.
Thanks.

A: There's not really a great way to handle this. Your best bet might to be making a Chrome extension (or Firefox Addon) to achieve similar functionality -- these extensions are able to bypass the browser's security restrictions and grant you access to all of a web page's information.
Sorry for the bad news :(


text:
Q: MYSQL Updating row to maximum value of similar rows I have a table like this in MYSQL:
ID   |   NAME    |  VALUE  |
----------------------------
 1   |   Bob     |  1      |
 2   |   Bob     |  2      |
 3   |   Jack    |  5      |
 4   |   Jack    |  8      |
 5   |   Jack    |  10     |

and I'm trying to update the VALUE column to the highest value of rows with same NAME. So the result should be:
ID   |   NAME    |  VALUE  |
----------------------------
 1   |   Bob     |  2      |
 2   |   Bob     |  2      |
 3   |   Jack    |  10     |
 4   |   Jack    |  10     |
 5   |   Jack    |  10     |

I managed to get the max value like this:
SELECT MAX(Value) max FROM `table` GROUP BY Name having count(*) >1 AND MAX(Value) != MIN(Value)

But can't figure out how to put it in my update
Update table set Value = (SELECT MAX(Value) max FROM `table` GROUP BY Name having count(*) >1 AND MAX(Value) != MIN(Value))

Doesn't work. I'd appreciate any help.

A: This is easier than other answers are making it.
UPDATE MyTable AS t1 INNER JOIN MyTable AS t2 USING (Name)
SET Value = GREATEST(t1.Value, t2.Value);

You don't have to find the largest value. You just have to join each row to the set of rows with the same name, and set the Value to the greater Value of the two joined rows. This is a no-op on some rows, but it will apply to every row in turn.

A: Create a temporary table consisting of ID NAME and MAX VALUE as follows:
CREATE TEMP TABLE TABLE1 AS
(SELECT NAME,MAX(Value) value FROM `table` GROUP BY Name having count(*) >1
AND MAX(Value) != MIN(Value)
);

Use this temporary table to do your update as follows:
UPDATE
Table_A
SET
    Table_A.value = Table_B.value
FROM
    `table` AS Table_A
    INNER JOIN TABLE1 AS Table_B
    ON Table_A.NAME = Table_B.NAME

Also this code is somewhat of an approximation as i am not familiar with mysql but i am familiar with sql.
Let me know if this doesn't help.

A: You may use this query. The table is joined with a subquery (table t2) that contains the results you want to update your table with:
UPDATE `table` t1,
   (SELECT Name, MAX(Value) maxv, MIN(Value) minv
    FROM `table`
    GROUP BY Name
    HAVING COUNT(*)>1 AND maxv != minv) t2
SET t1.Value = t2.maxv
WHERE t1.Name = t2.Name;

If you want to know how will the values be updated, you can first run an equivalent SELECT query:
SELECT t1.*, t2.maxv
FROM `table` t1,
   (SELECT Name, MAX(Value) maxv, MIN(Value) minv
    FROM `table`
    GROUP BY Name
    HAVING COUNT(*)>1 AND maxv != minv) t2
WHERE t1.Name = t2.Name;

This query will display all the fields of table, followed by the new value maxv. You can check the current value and the new value, and if it looks fine, you may run the UPDATE query.

A: Simple left join would do the trick.
Try this out and let me know in case of any queries.
select a.id,a.name,b.value
from
table a
left join
(select name,max(value) as value from table group by name) b
on a.name=b.name;

A: http://sqlfiddle.com/#!9/f79a3/1
UPDATE t1
INNER JOIN (SELECT name, MAX(`value`) max_value
           FROM t1 GROUP BY name) t2
ON t1.name = t2.name
SET t1.value = t2.max_value;


text:
Q: IdentityServer4 - Using External Authentication I am trying to implement an Authorization server using IdentityServer4, using the Hybrid Flow.
let's say url is : auth.company.com
To authenticate users, the company uses a simple .NET MVC login/password form.
url : client.company.com/login.html
My question is : how can i plug the authentication system into the IdentityServer4 ?
I've tried adding this :
Startup.cs / ConfigureServices()
services.AddIdentityServer(SetupIdentityServer)
 private static void SetupIdentityServer(IdentityServerOptions options)
        {
            options.UserInteraction.LoginUrl = @"client.company.com/login.html";
            options.UserInteraction.LoginReturnUrlParameter = "referrer";

        }

But it resulted in too many redirections error between auth server and authentication server
Thank you

A: I just replied to another question very similar to this so this is a shameless copy and paste of that:
This will not work as the identity server needs to issue its own cookie once authentication has taken place. This cookie is what allows the authorise endpoint to know who is signed in.
The intention of this model is that authentication takes place on the IDP or it's negotiated with an external provider via a suitable protocol. Therefore the appropriate approach in this case is to move the login UI into your identity server application. It's entirely up to you exactly how that is done and where it gets it's data from but it must be your identityserver4 that issues the cookie.


text:
Q: Is this Python function able to be be converted to Javascript? I am working with ciphers; encrypting and decrypting and I'm currently working with the Polybius Cipher with the modern Latin alphabet. For example, the letters 'a' is the 2-digit code, '11' and 'abc' is '11 12 13'.
I have found a solution in Python:
# Python Program to implement polybius cipher

# function to display polybius cipher text
def polybiusCipher(s):

        # convert each character to its encrypted code
        for char in s:

                # finding row of the table
                row = int((ord(char) - ord('a')) / 5) + 1

                # finding column of the table
                col = ((ord(char) - ord('a')) % 5) + 1

                # if character is 'k'
                if char == 'k':
                        row = row - 1
                        col = 5 - col + 1

                # if character is greater than 'j'
                elif ord(char) >= ord('j'):
                        if col == 1 :
                            col = 6
                            row = row - 1

                        col = col - 1

                print(row, col, end ='', sep ='')

I am trying to convert it and keep getting NaN as I am misusing something, or multiple things. Here is what I have so far:
function polybius(input, encode = true) {
  for (let i = 0; i < input.length; i++) {
    let letter = input[i];

    let row = letter.charCodeAt(0 - letter.charCodeAt(97)) / 5 + 1;

    let col = letter.charCodeAt(0 - (letter.charCodeAt(97) % 5)) + 1;

    if (letter.charCodeAt(0) === letter.charCodeAt(107)) {
      row = row - 1;
      col = 5 - col + 1;
    } else if (letter.charCodeAt(0) >= letter.charCodeAt(106)) {
      if (col === 1) {
        col = 6;
        row = row - 1;
      }
      col = col - 1;
    }
    return `${row}${col} `;
  }
}

A: let row = letter.charCodeAt(i - letter.charCodeAt('a')) / 5 + 1; is not correct since the char code of the letter itself is letter.charCodeAt(0) and the char code of 'a' is 'a'.charCodeAt(0). Moreover, you need to use Math.floor to round down.
Thus, it should be let row = Math.floor((letter.charCodeAt(0) - 'a'.charCodeAt(0)) / 5) + 1;.
There is a similar problem with the col initialization and it should be let col = (letter.charCodeAt(0) - 'a'.charCodeAt(0)) % 5 + 1;.
Next, to check if the letter is k, there is no need to compare char codes, you can directly use letter === 'k'. For the comparison to see if the letter is greater than or equal to 'j', a similar issue exists and you can directly use >= 'j'.
Finally, you return in the first iteration of the loop, so it will only run once. Instead, you can build a string to output or return at the end.
function polybius(input, encode = true) {
  let str = '';
  for (let i = 0; i < input.length; i++) {
    let letter = input[i];

    let row = Math.floor((letter.charCodeAt(0) - 'a'.charCodeAt(0)) / 5) + 1;

    let col = (letter.charCodeAt(0) - 'a'.charCodeAt(0)) % 5 + 1;

    if (letter === 'k') {
      row = row - 1;
      col = 5 - col + 1;
    } else if (letter >= 'j') {
      if (col === 1) {
        col = 6;
        row = row - 1;
      }
      col = col - 1;
    }
   str += `${row}${col} `;
  }
  console.log(str);
}


text:
Q: How can I install 32-bit dependencies on a 64-bit machine using dnf builddep? I am trying to install the build dependencies for Wine, so that I can do a bit of hacking with it. I am running Fedora 22, 64-bit.
I have installed the 64-bit dependencies successfully using dnf builddep:

# dnf --version
1.1.0

# dnf list wine
Available Packages
wine.i686                                                           1.7.47-1.fc22                                                         updates
wine.src                                                            1.7.47-1.fc22                                                         updates-source
wine.x86_64                                                         1.7.47-1.fc22                                                         updates

# dnf builddep wine
Package ImageMagick-devel-6.8.8.10-9.fc22.x86_64 is already installed, skipping.
Package alsa-lib-devel-1.0.29-1.fc22.x86_64 is already installed, skipping.
Package audiofile-devel-1:0.3.6-6.fc22.x86_64 is already installed, skipping.
Package autoconf-2.69-20.fc22.noarch is already installed, skipping.
...

And now my problem - I want to also install the 32-bit dependencies, but cannot get it to work.  Here are the things I have tried:

# dnf builddep wine.i386
no package matched: wine.i386
Error: Some packages could not be found.

# dnf builddep wine.i686
no package matched: wine.i686
Error: Some packages could not be found.

# dnf builddep wine-1.7.47-1.fc22.i686
no package matched: wine-1.7.47-1.fc22.i686
Error: Some packages could not be found.

# dnf builddep wine --target=i686
Error: unrecognized arguments: --target=i686

I have even tried some deprecated yum commands:

# yum-builddep wine --target=i386
# yum-builddep wine --target=i686
# yum-builddep wine-1.7.47-1.fc22.i686

The above result in:

 --> Already installed : zlib-devel-1.2.8-7.fc22.x86_64
 --> Already installed : unixODBC-devel-2.3.2-6.fc22.x86_64
 --> Already installed : sane-backends-devel-1.0.24-14.fc22.x86_64
...

How can I get dnf builddep to install the 32 bit dependencies for wine? The dnf command does not appear to support a --target option.
One obvious workaround is to get the list of packages individually and install them with dnf install; however, I am curious to know if dnf builddep can do it.

A: Red Hat bugzilla suggests to use setarch i686 dnf builddep .... According to the listed output this seems to work as expected.
https://bugzilla.redhat.com/show_bug.cgi?id=1312633


text:
Q: MVC ValidateAntiForgeryToken multi-tabs problem We'd been getting "A required anti-forgery token was not supplied or was invalid." errors, and on some further investigation, I've managed to recreate the problem in its simplest form - i'm either doing something completely wrong, or this is a limitation of the anti-forgery token system.
Either way, I'd appreciate some advice!
Empty MVC 2 project:
one view page, one controller
view:
<%--Sign in form:--%>
<% using(Html.BeginForm("SignIn", "Home", FormMethod.Post)) {%>
    <%= Html.AntiForgeryToken()%>
    <input type="submit" value="Sign in" />
<%}%>

Controller:
public ActionResult Index()
{
    ViewData["status"] = "Index";
    return View();
}

[ValidateAntiForgeryToken]
public ActionResult SignIn()
{
    ViewData["status"] = "Signed In!";
    FormsAuthentication.SetAuthCookie("username", false);
    return View("Index");
}

[EDIT: simplified code example]
In order to recreate the exception, open two non-signed-in tabs - sign-in on the first tab, and then sign-in on the second tab.
The second tab will always throw an anti-forgery exception, when I guess correct behaviour would be to redirect to the signed-in page (sharing the session/authentication of the original signed-in tab)
Any advice would be appreciated!
Cheers,
Dave

A: Looking at the MVC 2 source code it looks like the AntiForgeryToken hidden field includes the User.Identity.Name serialized, if your signed in. In line 69 of the ValidateAntiForgeryTokenAttribute it seems to then check your token with the current User.Identity.Name.
    string currentUsername = AntiForgeryData.GetUsername(filterContext.HttpContext.User);
    if (!String.Equals(formToken.Username, currentUsername, StringComparison.OrdinalIgnoreCase)) {
        // error: form token is not valid for this user
        // (don't care about cookie token)
        throw CreateValidationException();
    }

Because in your other tab you are now signed in the code above invalidates the existing token which doesn't contain the User.Identity.Name.
This could be fixed by adding a !string.IsNullOrEmpty(formToken.Username) around that check but I don't know if that will open up security issues plus it means having a custom MVC 2 Build.

A: You could use the same salt:
<% using(Html.BeginForm("SignIn", "Home", FormMethod.Post)) {%>
    <%= Html.AntiForgeryToken("123")%>
    <input type="submit" value="Sign in" />
<%}%>

<% using(Html.BeginForm("Protected", "Home", FormMethod.Post)) {%>
    <%= Html.AntiForgeryToken("456")%>
    <input type="submit" value="Do secret stuff" />
<%}%>

And in your controller:
[ValidateAntiForgeryToken(Salt = "123")]
public ActionResult SignIn()
{
    ViewData["status"] = "Signed In!";
    FormsAuthentication.SetAuthCookie("username", false);
    return View("Index");
}

[Authorize]
[ValidateAntiForgeryToken(Salt = "456")]
public ActionResult Protected()
{
    ViewData["status"] = "Authed";
    return View("Index");
}

Do the same with the other token but make sure to pick a different salt.

A: The real answer to this problem is simply that you shouldn't use an anti-forgery token on login forms!
It's pointless to "forge" being a user on a login form - they aren't logged in!


text:
Q: git: merge changes from a branch that reverted a previous merge Sorry for the confusing title, but I couldn't come up with a better one.
Here's my problem.  I have 2 branches, develop and feature.  I followed this process:

*

*write code in feature

*merge feature into develop

*discover a bug, revert the merge

*write some unrelated code and commit directly to develop.

Now I want to merge the changes I made directly to develop back into feature.  The problem is that when I do that, it blows away all the changes I had previously made in feature.  I assume this happens because the revert in step 3 is more recent than any code changes in feature, so it applies that revert over the changes.
Is it possible to do what I'm trying to do?  The only thing I could think of is to revert the revert in develop, then merge, then revert the revert of the revert.  That seems kind of cumbersome.

A: I think you can rectify the situation in two steps:
1) Do an interactive rebase of develop and remove the revert commit, i.e.
git rebase -i HEAD~6    # or however far back is the merge commit

Delete the line containing the revert commit and complete the rebase.  At this point, develop now has the original merge commit, but no revert.
2) Do a rebase on develop, specifying the hash of the commit from which both develop and feature originated.  By default, rebase will ignore the merge commit entirely, thereby removing it:
git checkout feature
git rebase <SHA-1>

where <SHA-1> here is from the commit whence feature branched off from develop.
After these two steps, your develop branch will have neither merge commit nor revert commit, and you should be safe merging it into feature.
I strongly recommend reading the answer given by @torek in this question:
Accidentally merged in wrong branch to mine. Is there a way to remove these unwanted files?

A: Normally you make a feature branch and you work on that branch to complete your feature. Then you merge your feature to the develop branch and after some time the develop state goes live.
In your case if you have changes on the develop branch i would prefer a rebase on your feature branch. Then you get all changes and your feature branch is rewritten to the last commit of your dev branch.
Atlassian has a good tutorial how you can work with feature branches.
https://www.atlassian.com/git/tutorials/comparing-workflows#feature-branch-workflow


text:
Q: Ordering and grouping in php/MySQL I have a table with user_id and lap_time and I'm running the following query:
SELECT `Lap`.`id`, `Lap`.`user_id`, `Lap`.`lap_time`
FROM `laps` AS `Lap`
WHERE `Lap`.`lap_time` < 57370
GROUP BY `Lap`.`user_id`
ORDER BY `Lap`.`lap_time` ASC

I am trying to get the all the laps that are quicker than X but only unique users.
The query above doesn't return the users top lap, its like I need to order the GROUP BY if that makes sense?
Users can have many laps, so there could be 10 laps faster than X but they're all by same user, so I just want the top lap for that user.
Hope that makes sense and someone can help!

A: The query you have will return every lap for every user that's lower than 57370.  If you only want each user's best lap, just add a MIN around the lap_time
SELECT `Lap`.`id`, `Lap`.`user_id`, min(`Lap`.`lap_time`) as `best_lap_time`
FROM `laps` AS `Lap`
WHERE `Lap`.`lap_time` < 57370
GROUP BY `Lap`.`user_id`

Also, you query formatting is pretty overkill.  No reason to make a table alias when there's only one table in the query. Unless you copy-pasted this from some program that generated it for you.
EDIT
Sorry, you are right - the min time won't always match up with the ID.  This should do the trick
select l.id
     , l.user_id
     , (select min(lap_time)
          from lap
         where lap_time < 57370
           and user_id = l.user_id
       ) as best_lap_time
 group by l.user_id
having best_lap_time is not null
 order by best_lap_time asc;

A: I think you should use a SELECT COUNT(*) AS some_field, group by that field and use MAX to get the top-result per user.

A: When dealing with similar situations I've added a sub-query to ensure there isn't a faster time for that user:
WHERE Lap.lap_time < 57370 AND NOT EXISTS (select 1 from laps where laps.user_id = Lap.user_id and laps.lap_time < Lap.lap_time)

A: This query will give you the fastest lap for each user_id(where lap_time is below 57370) and match it up with the correct record id. and in general, joins have a bit better performance with mysql than sub selects do.
select l2.id,
       l1.user_id,
       l1.lap_time
  from lap l1
  inner join lap l2
     on l1.id = l2.id
  where l1.lap_time < 57370
  group by l1.user_id
  having min(l1.lap_time);


text:
Q: How to change battery mode on my laptop? I installed Ubuntu 11.10 last day and tried to change battery mode( change balanced mode to power save mode like on windows ) on my laptop , but I don't know how to do it.
Is there anyway to do that? Is there any program to do that?

A: I don't know any program that can make modes for the battery.
But you can always change the settings by clicking on the battery icon (in the upper right corner), then click "Power Settings", change what ever you want to.
To access and modify the brightness settings, open the dash, go to System Settings, and click on Brightness and Lock.


text:
Q: Why can I set properties during instantiation through __init__, but not through another method? This is working
class a:
    def __init__(self,ka,sif):
        self.ka = ka
        self.sif = sif
    def b(self):
        pass

c = a("d","e")
c
print(c.ka,c.sif)

but
This is not working
class a:
    def __init__(self):
        pass
    def b(self,ka,sif):
        self.ka = ka
        self.sif = sif

c = a().b("d","e")
c
print(c.ka,c.sif)

Why?
I expected the get same result. Why these are not have same results.

A: a("d","e") will call __init__ and return the new instance of the class a. Regular methods do not have this behavior.
The b method does not return anything (so it implicitly returns None); if you want to be able to chain that method, add return self at the end.

A: To be even more explicit about how to fix this:
c = a()
c.b("d", "e")
print(c.ka, c.sif)

Now we're not depending on b to return anything (which it doesn't).

A: a is an instance of type. Like any other class, an instance of type is callable because type.__call__ is defined, so a() is equivalent to type.__call__(a).
You can imagine the definition of __call__ looks something like this, if it were written in pure Python:
class type:

    def __call__(self, *args, **kwargs):
        obj = self.__new__(self, *args, **kwargs)
        if isinstance(obj, self):
            obj.__init__(*args, **kwargs)
        return obj

If you were to unwrap this, a call like
c = a()

is like the following code:
c = a.__new__()
if isinstance(c, a):
    c.__init__()

So, you should be able to see that
c = a()
c.b(...)

is quite different from
c = a().b(...)

in terms of what is actually assigned to the name c. In the latter case, you lose the reference to the new instance of a once its b method completes.


text:
Q: .net web.config how to use   with request headers as input? We have some logic in the web.config which requires ip whitelisting to access our websites.
We want to allow load testing without having to whitelist IP, as the load test will come from dynamic IPs.  In the load test tool we can set a request header, such as
  loadtester: true

In the rewrite rules are "input" variables, which, from looking at examples, include:

*

*REMOTE_ADDR

*HTTP_X_Forwarded_For

*HTTP_HOST

*REQUEST_FILENAME

*SERVER_PORT

*URL

*REQUEST_URI

But I cant find one for reqeuest headers.  Are these documented anywhere?
Any idea how I would parse the headers and check the one i am looking for?  We would like to allow traffic with a specific header, even if the IP is not whitelisted.
example extract from web.config:
    <rule name="Whitelist sites" stopProcessing="true">
      <match url=".*" />
      <conditions>
        <add input="{REMOTE_ADDR}" pattern="82\.7\.151\.45" negate="true"/>
        <add input="{HTTP_X_Forwarded_For}" pattern="82\.7\.151\.45" negate="true"/>
      </conditions>
      <action type="CustomResponse" statusCode="403" statusReason="Forbidden" statusDescription="The requested site is not accessible" />
    </rule>
  </rules>
</rewrite>
</system.webServer>

Update: I found this resource: https://www.w3schools.com/ASP/coll_servervariables.asp
In it there is a variable called "HTTP_<HeaderName>" I'll try!

A: You can access the headers by prefixing their name with HEADER_
Untested, but this should work: <add input="{HEADER_LOADTESTER}" pattern="true" negate="true"/>
(personally i would go with a random string for the header/value if your using this approach to protect a publicly accessible service)


text:
Q: angular.js $destroy event - should I manually unbind? I'm trying to figure out if angular base automatically unbinds watchers and scope events bound with $scope.$on(...) or $scope.$watch(...) when scope is destroyed?
Suppose I have following code:
$scope.$on('someEvents', handleSomeEvent);
$scope.$watch('someProperty', handleSomePropertyChange);

Do I need to manually unbind these watchers and events when $destroy event is triggered on scope?

A: As previously answered, Angular indeed takes care of cleaning things for you, whenever possible. So if you do $scope.$on('someEvents', handleSomeEvent);, once the scope is destroyed (eg when you go to another page/view in your app), the event is automatically removed.
One important thing to note though, is that $rootScope is of course never destroyed, unless you quit your app. So if you do $rootScope.$on('someEvents', handleSomeEvent);, you may have to remove the event yourself, depending on where you listen to the event:

*

*if in a controller or directive, then you'll have to remove it manually, else each time you'll instantiate the controller, a new event will be attached, and so handleSomeEvent will be called many times

*if in a service, then you do not need to remove it manually, as services are always singleton (note that in Angular service, factory, ... all end up being the same thing)

A: According to Angular documentation on $scope:

'$destroy()' must be called on a scope when it is desired for the scope and its child scopes to be permanently detached from the parent and thus stop participating in model change detection and listener notification by invoking.

Also

Removal also implies that the current scope is eligible for garbage collection.

So it seems when $destroy() is called all the watchers and listeners get removed and the object which represented the scope becomes eligible for garbage collection.
If we look at the destroy() source code we'll see a line :
forEach(this.$$listenerCount, bind(null, decrementListenerCount, this));

Which is supposed to remove all the listeners.
As mentioned by @glepretre it applies to the watchers and listeners in the controller. The same doc page listed above says that:

Note that, in AngularJS, there is also a $destroy jQuery event, which can be used to clean up DOM bindings before an element is removed from the DOM.

So if you have specific listeners in the directives you should listen to the $destroy event and do the necessary cleanup yourself

A: If the scope is in a controller, angular unbind for you. Else you can unbind your event by calling the returned function :
var myevent = $scope.$on('someEvents', handleSomeEvent);
myevent() ; // unbind the event

http://docs.angularjs.org/api/ng/function/angular.bind


text:
Q: Send data from aws api gateway to http endpoint in x-www-form-urlencoded format I have an AWS API gateway proxy method. If I post data to AWS API gateway, then AWS API gateway posts data to my PHP backend. I have this mapping template in API gateway:
{
    "body-json" : $input.json('$'),
    "context" : {
        "cognito-identity-id" : "$context.identity.cognitoIdentityId"
    }
}

The problem is that API gateway posts data in JSON format. And PHP does not understand JSON (content type application/json), $_POST array is empty. PHP understands application/x-www-form-urlencoded format. How to make AWS API gateway to send data in x-www-form-urlencoded format?

A: Silly question, but have you tried PHP's JSON Decode function?
    $json = '{
       "body-json" : $input.json(\'$\'),
       "context" : {
        "cognito-identity-id" : "$context.identity.cognitoIdentityId"
       }
     }';

$phpArray = json_decode($json, true);

Which will produce an associative PHP array from that json.

A: The Amazon API Gateway uses the following logic to select a mapping template:
When the Content-Type header is absent in the request, API Gateway assumes that its default value is application/json. For such a request, API Gateway uses application/json as the default key to select the mapping template, if one is defined. When no template matches this key, API Gateway passes the payload through unmapped if the passthroughBehavior property is set to WHEN_NO_MATCH or WHEN_NO_TEMPLATES.
When the Accept header is not specified in the request, API Gateway assumes that its default value is application/json. In this case, API Gateway selects an existing mapping template for application/json to map the response payload. If no template is defined for application/json, API Gateway selects the first existing template and uses it as the default to map the response payload. Similarly, API Gateway uses the first existing template when the specified Accept header value does not match any existing template key. If no template is defined, API Gateway simply passes the response payload through unmapped.
For example, suppose that an API has a application/json template defined for a request payload and has a application/xml template defined for the response payload. If the client sets the "Content-Type : application/json", and "Accept : application/xml" headers in the request, both the request and response payloads will be processed with the corresponding mapping templates. If the Accept:application/xml header is absent, the application/xml mapping template will be used to map the response payload. To return the response payload unmapped instead, you must set up an empty template for application/json.
Only the MIME type is used from the Accept and Content-Type headers when selecting a mapping template. For example, a header of "Content-Type: application/json; charset=UTF-8" will have a request template with the application/json key selected.
Source: http://docs.aws.amazon.com/apigateway/latest/developerguide/request-response-data-mappings.html#transforming-request-response-body


text:
Q: Best practices for ensuring up to date sequences after table import We perform weekly table moves between several schema using expdp and impdp. Some tables have sequences associated with the ID columns and I'd like to ensure that the sequences are always up to date on the destination table after a load.
Is the following sequence of events a safe and acceptable way of handling this?

*

*Backup sequence properties to a table

*Drop sequences

*Load tables (with metadata)

*Find which has the greatest last cached value, backup sequence table or new imported sequence.

*Update accordingly
Are there any pitfalls with this method, and if so are there tried and tested methods?

A: For sequences the best way is to copy the current value from dba|all|user_sequences.last_number. Fetching the current value from the sequence is not safe; it can have higher values in other instances of the database.
Also make sure that your app is not using sequences for ordering ....


text:
Q: Android Drawing bitmap and button on canvas by X Y Positions i'm new into android and i have some problems with my app. Any help will be appreciated :)
I have drawing bitmap on canvas by xpositon and ypostion by sensors (when i'm moving my phone, bitmaps are moving )
I need to create moving clickable button on center of my  bitmaps and when i click them i will go to next activity .
Bitmaps are drawing perfectly but idont know how to draw buttons on them, buttons that will be moving with my bitmap by the same values of x and y. How i can do that?
This is my piece of code:
    private void updateBall() {

        // Calculate new speed
        // xVelocity += (xAcceleration * frameTime);
        // yVelocity += (yAcceleration * frameTime);

        // Calc distance travelled in that time
        // float xS = (xVelocity/2)*frameTime;
        // float yS = (yVelocity/2)*frameTime;

        // Add to position negative due to sensor
        // readings being opposite to what we want!
        // xPosition -= xS;

        // ------------------------------- MOVING Y --------------------------------------------------

        by = (-IMG_H + ddy) / 2f;
        ay = by / 90f;

        float dy = (ay * zAcceleration + by);

        if (Math.abs(zAcceleration) < 90 && Math.abs(yAcceleration) > 100)
            yPosition -= (yPosition - dy) / 20.;
        else if (zAcceleration > 0) {
            if (yPosition > -IMG_H) {
                if (Math.abs(yAcceleration) > 100) {
                    dy = (ay * 90 + by);
                    yPosition -= (yPosition - dy) / 20.;
                } else {
                    yPosition = -IMG_H;
                }
            }

        } else {
            if (yPosition < IMG_H) {
                if (Math.abs(yAcceleration) > 100) {
                    dy = (-ay * 90 + by);
                    yPosition -= (yPosition - dy) / 20.;
                } else {
                    yPosition = ddy;
                }
            }
        }

        // block y
        yPosition = 0;

        // ------------------------------- MOVING X --------------------------------------------------

        // For understanding :)
        // ddx= 1280-(float)display.getWidth();

        ax = -IMG_W / (180f);// -2*xStart);
        bx = -ax * xStart;

        // xStart pozycja początkowa

        if (xAcceleration > xStart && xAcceleration <= 180 + xStart) {
            dx = (ax * xAcceleration + bx);
            if (dirr == false) {
                xPosition = dx;
                dirr = true;
            }

            xPosition -= (xPosition - dx) / 20.;
            xPosition1 = xPosition + IMG_W;
        } else {
            dx1 = (ax * (xAcceleration - 180f) + bx);
            if (dirr == true) {
                xPosition1 = dx1;
                dirr = false;
            }

            xPosition1 -= (xPosition1 - dx1) / 20.;
            xPosition = xPosition1 + IMG_W;

        }

        xPosition = 0;
        xPosition1 = 0;
        // xPosition=yPosition=150;
        /*
         * if (xPosition > xmax) { xPosition = xmax; } else if (xPosition < 0) {
         * xPosition = 0; }
         */
        /*
         * if (yPosition > ymax) { yPosition = ymax; } else if (yPosition < 0) {
         * yPosition = 0; }
         */

        // Print values
        Log.i("QLA", " x: " + xAcceleration + "   dx: " + dx + "    dx1: "+ dx1 + "  xpos: " + xPosition + " " + " xpos1: " + xPosition1);

    }

    // I've chosen to not implement this method
    public void onAccuracyChanged(Sensor arg0, int arg1) {
        // TODO Auto-generated method stub
    }

    @Override
    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    protected void onStop() {
        // Unregister the listener
        sensorManager.unregisterListener(this);
        super.onStop();
    }

    public class CustomDrawableView extends View {
        public CustomDrawableView(Context context) {
            super(context);
            Bitmap ball = BitmapFactory.decodeResource(getResources(),
                    R.drawable.test);
            final int dstWidth = 1280;
            final int dstHeight = 960;
            mBitmap = Bitmap.createScaledBitmap(ball, dstWidth, dstHeight, true);

            Bitmap ball1 = BitmapFactory.decodeResource(getResources(),
                    R.drawable.tt);
            final int dstWidth1 = 1280;
            final int dstHeight1 = 960;
            mBitmap1 = Bitmap.createScaledBitmap(ball1, dstWidth1, dstHeight1, true);
            // mWood = BitmapFactory.decodeResource(getResources(),
            // R.drawable.wood);

            /*
             * ImageButton star = (ImageButton) findViewById(R.id.imageButton1);
             * star.setOnClickListener(new View.OnClickListener() { public void
             * onClick(View view) { Intent myIntent = new
             * Intent(view.getContext(), Main.class);
             * startActivityForResult(myIntent, 0);
             * overridePendingTransition(R.anim.fade_in, R.anim.fade_out); }
             *
             * });
             */
            // ImageView ddss=star.getDrawable();

        }

        protected void onDraw(Canvas canvas) {
            final Bitmap bitmap = mBitmap;
            // canvas.drawBitmap(mWood, 0, 0, null);
            canvas.drawBitmap(bitmap, xPosition, yPosition, null);

            // ss.getChildAt(0).setX();

            final Bitmap bitmap1 = mBitmap1;
            // canvas.drawBitmap(mWood, 0, 0, null);
            canvas.drawBitmap(bitmap1, xPosition1, yPosition, null);

            invalidate();

        }
    }

// END of class
};

AND XML:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:id="@+id/layout">

  <FrameLayout android:id="@+id/preview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:visibility="visible"
    android:orientation="horizontal"
    >

   <Button

            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="sdgvgvgfcvcv"
            android:gravity="center"
            />

  </FrameLayout>

<ImageView
          android:id="@+id/imageView1"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:scaleType="centerCrop"
          android:contentDescription="@string/desc"
          android:adjustViewBounds="true"
          android:src="@drawable/vinetka"
          android:orientation="horizontal"/>

</AbsoluteLayout>

A: I would put your
CustomDrawableView

in a FrameLayout
and add the buttons to the FrameLayout then position your button with setX() setY()
or with a margin if your app needs to run pre API Level 11
Something like this:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:gravity="center_horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">

    <CustomDrawableView android:layout_height="fill_parent"
               android:layout_width="fill_parent"
              />

    <Button

            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="@string/myButtonText"
            android:gravity="center"
            />

</FrameLayout>

now your Button will get added over the CustomDrawableView and you can use it like a normal Button.

A: Ok, its finally working great thanks to "gabe" and this - link. You can always move whole relative layout inside absolute layout - Link
in my class variables i add :
    Button button;
    private int myNewX = 0;
    private int myNewY = 0;

on update function:
myNewX = (int)xAcceleration;
myNewY = (int)yAcceleration;

Button button = (Button)findViewById(R.id.button);
            AbsoluteLayout.LayoutParams absParams =
                (AbsoluteLayout.LayoutParams)button.getLayoutParams();
            absParams.x = myNewX;
            absParams.y = myNewY;
            button.setLayoutParams(absParams);

And XML File:

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <FrameLayout
        android:id="@+id/preview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal"
        android:visibility="visible" >

    </FrameLayout>

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:contentDescription="@string/desc"
        android:orientation="horizontal"
        android:scaleType="centerCrop"
        android:src="@drawable/vinetka" />

     <Button
      android:id="@+id/button"
      android:layout_width="188dp"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_x="130px"
        android:layout_y="390px"

/>

</AbsoluteLayout>

THANKS FOR HELP!


text:
Q: Where to place require and use statements in a php class I'm new to php and a program I'm creating is not working as expected. I'm struggling to find the error, so I want to make sure that I'm placing the require and use statement in the correct position. In the code sample below, are the require and use statement in the correct position? Or should it be within the class definition?
<?php

require 'abc.php';

use xyz;

class foo
{
  //or should I place both of them here?

  function bar ()

  {

  }
}
?>

A: Usually best practice is to have them outside of class. Require statements are loaded with auto-loading and namespaces and use-s are outside.
For example check out this modern framework: Nette: Compiler class. Browse it on github and you will see what I am talking about. Loader looks like this: Nette: Loader.


text:
Q: Centering plots in Jupyter-Lab using R kernel I'm using Jupyter-lab with R kernel and I would like to know how to center the plots I make. Here is how it looks by default :

I would like to make it like this :


text:
Q: Invoking Word for rtf to docx conversion I have a need to routinely programmatically convert *.rtf files into *.docx. Manually, this works just fine with Save As inside Word 2007 ... the resulting docx behaves just fine.  Programmatically, I can't get it to work.
What I tried is basically the following:
Fetch RTF from Word
... but in the reverse direction. Instead of opening *.docx and using SaveAs to *.rtf, I'm opening the *.rtf and using SaveAs to *.docx.  However, the resulting file won't open, and so evidently there's something I don't understand.  Is
wordApp.Documents.Open(@"D:\Bar\foo.rtf")

not a legit thing to do?
Any thoughts about how to do this would be appreciated.

A: You can try this code, it works for me
var wordApp = new Microsoft.Office.Interop.Word.Application();
var currentDoc = wordApp.Documents.Open(@"C:\TestDocument.rtf");
currentDoc.SaveAs(@"C:\TestDocument.doc", Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument97);

I got the same error when I tried to use wdFormatDocument or wdFormatDocumentDefault
EDIT: this is an update to the code, it converts it but u will get the error once then it never appeared again!!
var wordApp = new Microsoft.Office.Interop.Word.Application();
var currentDoc = wordApp.Documents.Open(@"C:\TestDocument.rtf");
currentDoc.SaveAs(@"C:\TestDocument", Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault);
currentDoc.Close();
wordApp.Quit();

A: Can you show the code where you are calling SaveAs? I am curious which Word.WdSaveFormat you are specifying. It sounds like it is saving the rtf data, but changing the extension to .docx.

A: Here is the code that does conversion. The code is almost the same as shown above, with some small (but important) difference - it is necessary to use references (not objects themselves):
Microsoft.Office.Interop.Word.Application _App = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document _Doc =  _App.Documents.Open("c:/xxx.rtf");

object _DocxFileName = "C:/xxx.docx";
Object FileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLDocument;

_Doc.SaveAs2(ref _DocxFileName, ref FileFormat);


text:
Q: Mockito when not returning expected value in different test methods I have two test methods where the method call should return different objects in the methods calls of each test method.
Mocked call -
Test Method 1 -
when(service.getCustomer(ArgumentMatchers.any(Customer.class))).thenAnswer(invocation -> Arrays.asList(customer1));
Test Method 2 -
when(service.getCustomer(ArgumentMatchers.any(Customer.class))).thenAnswer(invocation -> Arrays.asList(customer2));
service.getCustomer(Customer) when called in method called by test method returns same customer object every time in both test methods. Does mockito stores any cache of objects returned ?


text:
Q: Websockets Client not printing message -- Python The Connection is being established but no message is being printed to the terminal.
Here is my code.
import websocket, json

cc = 'btcusd'

interval = '1m'

socket = f'wss://stream.binance.com:9443/ws/{cc}@kline_{interval}'

print('This part of the code has been executed')

def on_open(ws):
  print("Opened")

def on_message(ws, message):
    print(message)

def on_close(ws):
    print("Connection Closed")

ws = websocket.WebSocketApp(socket, on_open=on_open, on_message=on_message, on_close=on_close)
ws.run_forever()


text:
Q: spring form tag is not resolving session variables We are migrating our application from spring 3 to spring 4. I now have a  problem wherein the session variables gets resolved when I use  c:out and not when I use form:form. I viewed a similar issue on another post which remained unanswered. But, I am now facing the same issue.
<%@ include file="/common/taglibs.jsp"%>
<c:forEach var="item" items="${yesNos}">
<c:out value="${item}"/>
</c:forEach>

<form:select path="blocked">
<form:option value="" label=""/>
<form:options items="${yesNos}" itemValue="id" itemLabel="${domainValueProperty}"/>
</form:select>

c:forEach is able to iterate on the list "yesNos".
form:options cannot seem to identify this list "yesNos" and throws an error

OptionsTag  - Type [java.lang.String] is not valid for option items

yesNos is a list of our POJO and has a corresponding PropertyEditor defined. I suspected PropertyEditor to be an issue but the below realization stumped me.
I also realized the form:form tag also shows an issue wherein the dynamic session variable passed to the action attribute does not get resolved and stays as ${} even on the generated HTML source.
JSP: formActionURL is of type String
<form:form action="${formActionURL}" commandName="pDSearch">

HTML source
<form id="pDSearch" action="${formActionURL}" method="post">

*

*I have the taglibs uri configured and it works well, since the tags are being processed.

*This worked with Spring 3.0.7 & servlet 2.3. Now, we are migrating to spring 4.0.6 & servlet 2.3.

*On the other post, the requester used servlet 2.5 and still faced the issue. Migrating to servlet 2.5 would be a huge impact on our application.

Below is the taglibs.jsp that is imported on the page
<%@ page language="java" errorPage="/error.jsp" pageEncoding="UTF-8" contentType="text/html; charset=utf-8" %>
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="security" %>
<%@ taglib uri="http://www.springmodules.org/tags/commons-validator" prefix="v" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://displaytag.sf.net/el" prefix="display" %>
<%@ taglib uri="http://struts-menu.sf.net/tag-el" prefix="menu" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://www.opensymphony.com/oscache" prefix="cache" %>
<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator"%>
<%@ taglib uri="http://www.opensymphony.com/sitemesh/page" prefix="page"%>

Greatly appreciate if someone could redirect me to a source where I can find answer to my issue. Do let me know if you need further information.

A: The way how EL works has changed during the transition Servlet 2.3 --> Servlet 2.4.
During Servlet 2.3, EL was supplied as part of JSTL 1.0. Since Servlet 2.4, EL was supplied as part of JSP 2.0, and EL was removed from JSTL 1.1.
Any Servlet 2.4+ compatible JSP tag library, will expect to find EL in JSP, not in JSTL anymore. In other words, when you still use a Servlet 2.4+ compatible JSP tag library on a Servlet 2.3 container, then EL expressions in all its tags will stop working, because it can't find EL in JSP.
So, when you want to use a Servlet 2.4+ compatible JSP tag library, like Spring 4+, which actually requires Servlet 2.5, then you really need to upgrade to exactly that minimum Servlet version.
See also:

*

*Difference between JSP EL, JSF EL and Unified EL


text:
Q: Constancy on large subsets Let $X$ be a smooth proper variety of dimension greater than one defined over a number field. Let $A_i$ be a sequence of pairwise disjoint finite closed subsets of $X$ indexed by natural numbers defined over number fields such that $|A_{i}| \rightarrow \infty$ as $i \rightarrow \infty$. Suppose that any closed subvariety $W \subset X$ with $\dim(W) < \dim(X)$ contains at most finitely many $A_i$'s. Is it possible to have a non-constant a rational function $f$ such that $f=c_{i}$ on $A_i$ for all $i$? Here $c_{i}$'s are constants.
It seems tempting to expect that the answer is no. If not, can we put some additional hypotheses on the density of these large subsets (or something relevant) to guarantee that $f$ is constant?

A: If $X$ is proper then $f$ is locally constant so it's possible to have non-constant $f$ iff $X$=$Y\cup Z$ such that $Y$ and $Z$ are each non-empty unions of connected components of $X$, $Y$ and $Z$ are disjoint, and each $A$$i$ is contained in $Y$ or is contained in $Z$.
I give 2 examples with $X$ = affine plane over ℚ such that $f$ exists in the first example and not in the second.
Let {$t$$i$: $i=1,2,3,...$} be a set of algebraic numbers such that degree ℚ($t$$i$)/ℚ($t$$j$:$j$ ≠ $i$) $\rightarrow \infty$ as $i\rightarrow \infty$.  (For example, take $t$$i$ = $p$$i$$1/p$$i$ where $p$$i$ is the $i$th prime.)  Set $P$1=($t$1, $t$2), $P$2=($t$3, $t$4),..., points of $X$.
First example: $A$1={$P$1}, $A$2={$P$2}, ... Any curve {$g(x,y)=0$} contains only finitely many $A$$i$ because the degree of each coordinate over the other coordinate is bounded by a function of the degree of $g$ and the degrees of the coefficients of $g$.  And, $f(x,y)=x$ is constant on each $A$$i$.
Second example: $A$1={$P$1,$P$2}, $A$2={$P$3,$P$4},... Any curve {$g(x,y)=0$} contains only finitely many $A$$i$, as in the first example.  There is no $f$ which is constant on each $A$$i$ because $f(P$$2i-1$) = $f(P$$2i$) bounds the degree of each coordinate of $P$$2i$ (resp. $P$$2i-1$) over the compositum of the other coordinate and the coordinates of $P$$2i-1$ (resp. $P$$2i$) by a function of the degree of $f$ and the degrees of the coefficients of $f$.


text:
Q: Why is my private route checkup always evaluating to false? I have a private route component in my react app
    import { Route } from 'react-router-dom';
import React from 'react';
import { Redirect } from 'react-router';

export default ({ component: Component, render: renderFn, authed, ...rest }) =>
  Component ? (
    <Route
      {...rest}
      render={props =>
        authed === true ? (
          <Component {...props} />
        ) : (
            <Redirect to={{ pathname: '/', state: { from: props.location } }} />
          )
      }
    />
  ) : (
    <Route {...rest} render={props => authed === true ? console.log(authed) : <Redirect to={{ pathname: '/', state: { from: props.location } }} /> } />
    );

Which works with the following routes
<PrivateRoute authed={this.state.isAuthenticated} path="/route1" render={props => <iframe frameBorder={0} src={constans.urlRoute1} className="iframe" />} />
<PrivateRoute authed={this.state.isAuthenticated} path='/register' component={RegisterPage} />

The problem im facing is that they always evaluate to false because my app.js doesnt have time to set the state of authentication, the router acts too fast.
This is how the resto of my auth process looks in the app.js
constructor(props) {
    super(props);

    console.log("PROPS APPJS")
    console.log(props)

    //checks if user is autheticated within the system in order to manage routes
    this.state = {
        isAuthenticated: false
    }

}

componentDidMount() {
    isAuthenticated().then((result) => {
        if (result === true) {
            this.setState({ isAuthenticated: true})
        } else {
            this.setState({ isAuthenticated: false})
        }
    });
}

How can I make the protected route await for componentDidMount() to set the proper value?

A: It looks like your isAuthenticated() method is asynchronous, so your component will always render before it is done. If you can make it synchronous, then do so and run it directly in the constructor.
If you cannot make it synchronous, then your only option is to block rendering until you have your result. You could do this by having a "isLoading" state that returns early from your render method if it is true. Then set it to false at the same time as you set your isAuthenticated state.

A: You can either not return anything before authentication check in your app.js or you can move the authentication logic into the private route handler and wait for it to finish and then decide.
The first option would be something like this:
constructor(props) {
    super(props);

    this.state = {
        authenticationChecked: false,
        isAuthenticated: false
    }

}

componentDidMount() {
    isAuthenticated().then((result) => {
        if (result === true) {
            this.setState({ isAuthenticated: true, authenticationChecked: true})
        } else {
            this.setState({ isAuthenticated: false, authenticationChecked: true})
        }
    });
}

render() {
    if (!this.state.authenticationChecked) return null; // Or some sort of loader ...
    // Render the app otherwise
}

@pgsandstrom's answer is also another way to handle the problem. But I usually rather avoid synchronous calls so I have the freedom to show a loader or ... while the function is working.


text:
Q: Reflection in SQLAlchemy doesn't work for MS SQL Server system tables? I'm trying to reflect system table in MS SQL Server database:
from sqlalchemy import engine, create_engine, MetaData, Table

meta = MetaData()

url = engine.url.URL(
    "mssql+pyodbc",
    username=credentials["username"],
    password=credentials["pswd"],
    host=credentials["host"],
    database=credentials["db"],
    query=dict(driver="ODBC Driver 13 for SQL Server")
)

e = create_engine(url)
conn = e.connect()
tt = Table("objects", meta, autoload=True, autoload_with=e, schema="sys")
for c in tt.columns:
    print(c.name)

At the end I get NoSuchTable error. I tried to reflect other system tables (sys.triggers, sys.sql_modules) - same results. With ordinary tables this code works normally, I can list columns and make other queries. Login which I use in my application has "db_owner" role, so it has enough permissions, and if I write something like this
for item in conn.execute("select * from sys.triggers"):
    print(item)

it works fine.
What am I doing wrong? Is there any other way to work with data from system tables, besides executing raw sql and wrapping results in dataclasses etc.?

A: I was trying to reflect system views in MS SQL Server database. After adding echo='debug' to engine, I realized that, SQL Alchemy searches table and view metadata from INFORMATION_SCHEMA in MSSQL.
The system tables and views are not listed in INFORMATION_SCHEMA.TABLES OR INFORMATION_SCHEMA.VIEWS.
(I'm using SQLAlchemy version 1.3.5.)

A: When you add echo='debug' to your engine you can see the steps it's going through when talking to the database. In my case it sends out a query consisting of a left join of all_col_comments on all_tab_cols. In this query you'll see it uses owner = <schema value>.
I found that the system tables are owned by 'SYS' so by setting the schema to 'SYS' it will be able to find the system table just fine. A small code example to clarify where to set the schema:
table = db.Table('USER_SOURCE', metadata, schema='SYS', autoload=True, autoload_with=engine)


text:
Q: bootstrap does not work in android studio hello everyone my name is danish I am a beginner web developer so I need to make an android app using the web now I use bootstrap in my android studio but that does not work please someone helps me how to use bootstrap in the android studio I create html css
and js file which is work properly but bootstrap is not working properly


text:
Q: How do I build only one JAR file with classifier? I'm using Maven 2 and maven-jar-plugin to build my jar.
I'd like to generate only a jar with a classifier. Is it possible?
In my example I'd like to generate only the myjar-another-1.0.jar but not myjar-1.0.jar.
After take a look at this question I tried to skip the default-jar. But this seems to work only with version 3 of Maven (haven't tried thou.
The parent is to do the
<modules>

Thanks all!
Here is the relevant piece of my pom.xml:
Also tried in the global configuration segment.
<project>
         <!-- Definition of the Parent (only an aggregator) -->
    <build>
      <plugins>
         <!-- <artifactId>maven-bundle-plugin</artifactId> -->
         <!-- surefire -->
         <!-- <artifactId>maven-source-plugin</artifactId> -->
         <plugin>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <classifier>another</classifier>
            </configuration>
            <executions>
                <execution>
                    <id>test-jar</id>
                    <goals>
                        <goal>test-jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
     </plugins>
   </build>

A: Just use it for the plugin element:
  <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <classifier>another</classifier>
        </configuration>
      </plugin>
  </plugins>


text:
Q: Crossed module classification theorem and $H^3(G; A)$ We are interested in "Crossed Module Classification Theorem (Two crossed modules with kernel $A$ and cokernel $G$ determined the same class in $H^3(G;A)$ if and only if they are equivalent.)".
We study the works of Charles A. Weibel "An Introduction To Homological Algebra", Saunders Mac Lane "Historical Note, Cohomolgy Groups $H^n(G;M)$" and Joseph J. Rotman "An Introduction to Homological Algebra". Weibel says:

Consider a $4$-term exact sequence with $A$ central in $N$; $0\to A\to N\to E\to G\to 1$ and choose a based section $\sigma : G \to E$ of $\pi$; as in the theory of factor sets, the map $[] : G\times G \to \ker\pi$ defined by $[g,h] = \sigma(g)\sigma(h)\sigma(gh)^{-1}$ satisfies a nonabelian cocycle condition $[f,g][fg,h] = \sigma(f)[g,h]\sigma(f)^{-1}[f,gh]$. We can lift each $[f,g]$ to an element $[[f,g]]$ of $N$.
Given a crossed module $N\to E$ we set $A = \ker\alpha$ and $G = \operatorname{coker}\alpha$; $G$ is a group because $\alpha(N)$ is normal in $E$, $A$ is in the center of $N$ and $G$ acts on $A$, so that $A$ is a $G$ module and we have the sequence $0\to A\to N\to E\to G\to 1$. Assuming that $N\to E$ is a crossed module, the failure of $[[f,g]]$ to satisfy the cocycle condition is given by the function $c : G\times G\times G \to A$ defined by $c(f,g,h)[[f,g]][[fg,h]] = \sigma(f)[[g,h]]\sigma(f)^{-1}[[f,gh]]$.

How can we check that $c$ is a $3$-cocycle, whose class in $H^3(G;A)$ is independent of choices of $\sigma$ and $[[f,g]]$? Can we define the function of $c$ explicitly?

A: The book partially titled Nonabelian Algebraic Topology (NAT) (pdf available) has an extensive treatment of crossed modules and their role in cohomology and in homotopy classification.
A main difference from  standard homological algebra texts is the use of crossed complexes and of free crossed resolutions of groups. In particular, some seemingly complicated cocycle conditions turn out to be related to a boundary rule in a standard free crossed complex; so the rule you give does, with the appropriate conventions, become $c\delta =0$.
Background is given in the exposition `Groupoids and crossed objects in algebraic topology',Homology, homotopy and applications, 1 (1999) 1-78, available here. This contains some calculations of the $k$-invariants  of some crossed modules.
Further calculations are available in the paper
G. Ellis and Le Van Luyen, "Homotopy 2-types of low order", available from the preprint list of Graham Ellis.


text:
Q: How to use button onclicklistener for recycleview item inside main activity I am facing this problem while working at an Android app: I have a recycleview and every item has a delete button. I know I can add the button onclicklistener of every row item inside the onBindViewHolder in the adapter, but I want it specifically to be used from inside the MainActivity, not the adapter. Here is a brief sketch of my recycleview:
sketch
Here is the code for my adapter:
public class EntryAdapter extends RecyclerView.Adapter<EntryAdapter.MyViewHolder> {

    private Context context;
    private CRUD db;
    private List<Entry> entryList;

    public class MyViewHolder extends RecyclerView.ViewHolder {

        ImageView type;
        ImageView person;
        TextView amount;
        TextView amount_ron;
        ImageButton deleteB, editB, payB;
        TextView description;
        TextView timestamp;
        TextView positionTxt, noHolderPositionTxt;
        LinearLayout containter;
        Typeface SR, SB, SL;

        MyViewHolder(View view) {
            super(view);

            this.SB = Typeface.createFromAsset(context.getAssets(), "fonts/sansation_bold.ttf");
            this.SR = Typeface.createFromAsset(context.getAssets(), "fonts/sansation_regular.ttf");
            this.SL = Typeface.createFromAsset(context.getAssets(), "fonts/sansation_light.ttf");
            containter = view.findViewById(R.id.item_container);
            type = view.findViewById(R.id.debt_type);
            person = view.findViewById(R.id.debt_person);
            amount = view.findViewById(R.id.entry_cost);
            amount.setTypeface(SR);
            amount_ron = view.findViewById(R.id.entry_cost_ron);
            amount_ron.setTypeface(SR);
            deleteB = view.findViewById(R.id.delete_button);
            editB = view.findViewById(R.id.edit_button);
            payB = view.findViewById(R.id.pay_button);
            description = view.findViewById(R.id.descriptionTxt);
            description.setTypeface(SL);
            timestamp = view.findViewById(R.id.timestamp);
            timestamp.setTypeface(SR);
            positionTxt = view.findViewById(R.id.position);
            noHolderPositionTxt = view.findViewById(R.id.positionnotwithholder);

            db = new CRUD(context);
        }
    }

    public EntryAdapter(Context context, List<Entry> entryList) {
        this.context = context;
        this.entryList = entryList;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_entry, parent, false);
        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {

        Entry entry = entryList.get(holder.getAdapterPosition());
        holder.positionTxt.setText(String.valueOf(holder.getAdapterPosition()));
        holder.noHolderPositionTxt.setText(String.valueOf(position));

        switch(entry.getType()){
            case "FOOD": holder.type.setImageResource(R.drawable.food);
                break;
            case "FLOWERS": holder.type.setImageResource(R.drawable.flowers);
                break;
            case "GROCERIES": holder.type.setImageResource(R.drawable.groceries);
                break;
            case "HOLIDAY": holder.type.setImageResource(R.drawable.holiday);
                break;
            case "PHARMACY": holder.type.setImageResource(R.drawable.pharmacy);
                break;
            case "BILLS": holder.type.setImageResource(R.drawable.bills);
                break;
            case "CLOTHES": holder.type.setImageResource(R.drawable.clothes);
                break;
            case "TRANSPORT": holder.type.setImageResource(R.drawable.transport);
                break;
            case "ITEMS": holder.type.setImageResource(R.drawable.items);
                break;
            case "OTHERS": holder.type.setImageResource(R.drawable.others);
                break;
        }
        switch (entry.getPerson()){
            case "ew": holder.person.setImageResource(R.drawable.crisu_to_radu_small);
                break;
            case "wr": holder.person.setImageResource(R.drawable.radu_to_crisu_big);
                break;
        }
        switch (entry.getIsPaid()){
            case "YES": holder.containter.setAlpha((float) 0.3);
                        holder.payB.setVisibility(View.GONE);
                        holder.deleteB.setVisibility(View.GONE);
                        holder.editB.setVisibility(View.GONE);
                break;
            case "NO":  holder.containter.setAlpha((float) 1);
                        holder.payB.setVisibility(View.VISIBLE);
                        holder.deleteB.setVisibility(View.VISIBLE);
                        holder.editB.setVisibility(View.VISIBLE);
                break;
        }
        holder.amount.setText(entry.getAmount());
        holder.description.setText(entry.getDescription());
        holder.timestamp.setText(formatDate(entry.getTimestamp()));
//                deleteEntry(holder.getAdapterPosition());
    }

    @Override
    public int getItemCount() {
        return entryList.size();
    }

    private void deleteEntry(int position) {
        db.deleteEntry(entryList.get(position));
        entryList.remove(position);
        notifyItemRemoved(position);
        notifyDataSetChanged();
        notifyItemRangeChanged(position, entryList.size());
    }

    private String formatDate(String dateStr) {
        try {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = fmt.parse(dateStr);
            @SuppressLint("SimpleDateFormat") SimpleDateFormat fmtOut = new SimpleDateFormat("MMM d, HH:mm");
            return fmtOut.format(date);
        } catch (ParseException ignored) {}

        return "";
    }
}

Here is my MainActivity:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fonts();

        recyclerView = findViewById(R.id.recycler_view);
        no_entry_message = findViewById(R.id.no_entry_message);
        no_entry_message.setTypeface(SL);
        title = findViewById(R.id.finance_title);
        title.setTypeface(SB);
        subtitle = findViewById(R.id.finance_subtitle);
        subtitle.setTypeface(SL);
        card_title = findViewById(R.id.total_title);
        card_title.setTypeface(SR);
        money_amount = findViewById(R.id.total_money);
        money_amount.setTypeface(SB);
        money_rom = findViewById(R.id.total_ron);
        money_rom.setTypeface(SB);
        total_calculation = findViewById(R.id.total_button);
        total_calculation.setTypeface(SR);
        total_container = findViewById(R.id.total_card_container);

        db = new CRUD(this);
        entryList.addAll(db.getAllEntries());

        fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isUpdateDilog = false;
                addEntryDialog(null, -1);
            }
        });

        mAdapter = new EntryAdapter(this, entryList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);
        emptyList();
    }
//    private void deleteEntry(int position) {
//
//        db.deleteEntry(entryList.get(position));
//        entryList.remove(position);
//        mAdapter.notifyItemRemoved(position);
//        emptyList();
//    }

So basically, every time I click on the delete button inside the recyclerview item, I want the onclick event to happen in the MainActivity and use the method deleteEntry(position) so I can delete the specific item from my local sqlite database.
Also, if I want to put a condition in onBindViewHolder from my adapter, how can I change (for example) the color of a textview from MainActivity right there?
UPDATE - WITH H.sanati's ANSWER
Thanks again for the answer, H.sanati. Here is all I changed:
Created this Interface:
public interface OnClickListener {
    void onClick(int position, String button_pressed);
}

The integer position will store my item position inside the list and the string will tell which of my 3 buttons was pressed.
Then inside my Recyclview Adapter:
@Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_entry, parent, false);

        final MyViewHolder holder = new MyViewHolder(itemView);
        holder.deleteB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity)context).onClick(holder.getAdapterPosition(), "DELETE_B");
            }
        });

        holder.editB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity)context).onClick(holder.getAdapterPosition(), "EDIT_B");
            }
        });

        holder.payB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity)context).onClick(holder.getAdapterPosition(), "PAY_B");
            }
        });

        return holder;
    }

Note that deleteB, editB and payB are all buttons that appear in every single list item. The string in the interface above tells which one of these was pressed.
Then in my MainActivity:
public class MainActivity extends AppCompatActivity implements OnClickListener {
@Override
    public void onClick(int item_position, String which_button_was_pressed) {
        switch (which_button_was_pressed)
        {
            case "DELETE_B":
                deleteEntry(item_position);
                Toast.makeText(this, "Delete button at position:" + item_position + "was pressed", Toast.LENGTH_SHORT).show();
                    break;
            case "EDIT_B":
                Toast.makeText(this, "Edit button at position:" + item_position + "was pressed", Toast.LENGTH_SHORT).show();
                break;
            case "PAY_B":
                Toast.makeText(this, "Pay button at position:" + item_position + "was pressed", Toast.LENGTH_SHORT).show();
                break;
        }

    }

Here there is a Toast massage to confirm the correct buttons were pressed and following, I'll be adding my methods for each case. Also I suggest that inside your methods in the MainActivity (let's say the the delete method, you can view it ballow) you should add the following lines marked with @@@ for an accurate list size and position update:
 private void deleteEntry(int position) {

            db.deleteEntry(entryList.get(position));
            entryList.remove(position);
      @@@   mAdapter.notifyItemRemoved(position);
      @@@   mAdapter.notifyDataSetChanged();
      @@@   mAdapter.notifyItemRangeChanged(position, entryList.size());
            emptyList();
        }

Hope this helps. Thanks!

A: at first, create an interface:
public interface OnClickListener {
    void onClick();
}

then implement this interface in your activity:
class MainActivity extends AppCompatActivity implements OnClickListener {
    @Override
    public void onClick() {
        //code
    }
}

do whatever you want in the onClick method after that call it in your recyclerview:
((MainActivity)context).onClick();

it's better to set your listeners in onCreateViewHolder to have a smooth scroll in recyclerview like this:
 @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_entry, parent, false);

        MyViewHolder holder = new MyViewHolder(view);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity)context).onClick();
            }
        });

        return holder;
    }


text:
Q: Powershell compare issue I have 2 variables that I'm trying to compare. $Variable1 contains 3 columns of data, $Variable2 contains 1 column of data.
I need to compare column1 of $Variable1 to $Variable2. If there is a match, I want to return the value (all columns) of $Variable1.
Initially, I've tried:
$Variable1 -match $Variable2 and it works, but it returns too much data and I just want an exact match.
So then I tried $Variable1 -eq $Variable2 and it doesn't return anything. But if I use $Variable1.Column1 -eq $Variable2, then it returns the exact data that I want. But here, the problem is that it only returns Column1 of $Variable1 and I want all the columns of $Variable1 for that particular row of data. What should I do here?

A: You can use Where-Object (alias where) in combination with an operator to achieve this result.
$variable1 | where column1 -in $variable2

You may also see the above written with the script block notation:
$variable1 | Where-Object { $_.column1 -in $variable2 }

This works when you want to filter a specific value against a list of values. If $variable2 is always a single value, you can use -eq instead. You must send the object with all the possible properties you need into the pipeline and then filter the object values as needed. If you limit your object to one column/property before filtering, you will only output a filtered version of that one column.

The scenario above assumes a data set similar to below:
$var1 = [pscustomobject]@{c1=1;c2=2;c3=3},
        [pscustomobject]@{c1=2;c2=4;c3=6},
        [pscustomobject]@{c1=1;c2=6;c3=9},
        [pscustomobject]@{c1=6;c2=12;c3=13}
$var1 # array of objects with 3 properties

c1 c2 c3
-- -- --
 1  2  3
 2  4  6
 1  6  9
 6 12 13

$var2 # array of data

1
2
3

$var1 | where c1 -in $var2

c1 c2 c3
-- -- --
 1  2  3
 2  4  6
 1  6  9


text:
Q: Non-autogenerated ContextMenu will not display I'm trying to create a context menu which will be able to add extra menu items, with an attached child menu, as required.
As it stands my code generates no errors and it will flow through the program as intended, but it doesn't display anything on screen.
I thought I might be missing the link between the ContextMenuStrip and the component it attaches to so I had a look at how the code is auto generated in the design view... however I have no access to the "Controls" object to do Control.Add(this.whatever) and it appears not to be part of the using System... collection.
I have left my testing for this commented out below.
The SuspendLayout and ResumeLayout methods are another thing I looked into after reading that you should call them before and after making changes to UI components. I am not sure if I am correctly using them as they appeared to do nothing, I'm unsure when they are actually required to be used.
Would appreciate being pointed towards what ever I have missed out on, thanks :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.IO;

namespace Context
{
class PopulateMenu
{
    private void PopulateSubMenu(string fileName, ContextMenuStrip parent, EventHandler onClickDelete, EventHandler onClickView)
    {
        try
        {
            Image delete = Properties.Resources.RO_Mx2_24_delete;
            Image view = Properties.Resources.OpenFolder1;

            parent.SuspendLayout();
            //Parent
            ToolStripMenuItem attachedFiles = new ToolStripMenuItem(fileName, Properties.Resources.NewDocumentHS);
            //Kids
            attachedFiles.DropDownItems.Add(new ToolStripMenuItem("View File", view, onClickView));

            //if (!hotfolder)
            //{
            attachedFiles.DropDownItems.Add(new ToolStripMenuItem("Delete File", delete, onClickDelete));
            //}
            //else
            //{
            //    attachedFiles.DropDownItems.Add(new ToolStripMenuItem("Remove File", delete, onClickDelete));
            //}

            // Attach kid to parent
            parent.Items.Add(attachedFiles);
            parent.ResumeLayout();
        }
        catch { Exception e; }
    }

    private void BuildHotMenu(List<FileInfo> files, ContextMenuStrip parent)
    {
        try
        {
            parent.SuspendLayout();
            parent.Items.Add(new ToolStripMenuItem("Hot Folder Files"));
            parent.Items.Add(new ToolStripSeparator());

            foreach (FileInfo fileInfo in files)
            {
                PopulateSubMenu(fileInfo.Name, parent, null, null);
            }
            parent.ResumeLayout();
        }
        catch { Exception e; }
    }

    private void BuildDropMenu(List<FileInfo> files, ContextMenuStrip parent)
    {
        try
        {
            parent.SuspendLayout();
            parent.Items.Add(new ToolStripMenuItem("Dropped Files"));
            parent.Items.Add(new ToolStripSeparator());

            foreach (FileInfo fileInfo in files)
            {
                PopulateSubMenu(fileInfo.Name, parent, null, null);
            }
            parent.ResumeLayout();
        }
        catch { Exception e; }
    }

    public void SummonContextMenu()
    {
        try
        {
            ContextMenuStrip attachedFilesWithMenu = new ContextMenuStrip();
            ////ContextMenu
            //attachedFilesWithMenu.Name = "attachFilesWithMenu";
            //attachedFilesWithMenu.Size = new Size(61, 4);

            //ToolStrip ToolStrip1 = new ToolStrip();
            ////ToolStrip
            //toolStrip1.ContextMenuStrip = attachedFilesWithMenu;
            //toolStrip1.Location = new Point(0, 0);
            //toolStrip1.Size = new Size(284, 25);
            //toolStrip1.Name = "toolStrip1";
            //toolStrip1.Text = "toolStrip1";

            //// Form2
            ////
            //AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            //AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            //ClientSize = new System.Drawing.Size(284, 262);
            //Controls.Add(this.toolStrip1);
            //ResumeLayout(false);
            //PerformLayout();

            //static directory for testing only
            ConfigurationInformation configurationInformation = new ConfigurationInformation();
            configurationInformation.HotFolderPath = "C:\\Users\\alexh\\HotFolder\\";

            //Store DirectoryInfo
            DirectoryInfo dirInfo = new DirectoryInfo(Environment.ExpandEnvironmentVariables(configurationInformation.HotFolderPath));
            //Create list to store file details
            List<FileInfo> hotFiles = new List<FileInfo>();

            foreach (FileInfo fileInfo in dirInfo.GetFiles())
            {
                hotFiles.Add(fileInfo);
            }
            BuildHotMenu(hotFiles, attachedFilesWithMenu);
            BuildDropMenu(hotFiles, attachedFilesWithMenu);
        }
        catch { Exception e; }
    }

    public PopulateMenu()
    {
    }
    //private System.Windows.Forms.ToolStrip toolStrip1;
    //private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
}

}

A: Well that was actually quite simple. You just have to do it from a Form.
//this.Literally = theAnswer;
this.ContextMenuStrip = myContextMenu;


text:
Q: Android FaceDetector Pose Always Returning Zero
Possible Duplicate:
Android FaceDetector.Face Euler angles are 0 all the time

I'm working with the Android FaceDetector and seem to have everything working well EXCEPT getting the "Pose" information for a Face. I've tried several different Bitmaps showing faces with varying orientations, but the EULER_X, EULER_Y and EULER_Z always come back as 0. Is there something I'm missing?  Thanks!


text:
Q: image not appearing on secondary tile Hi i'm trying to resize an image to show it in a secondary tile.My code works fine  but i don't know what i'm doing wrong because when the image is bigger than 1000*1000   the image is not shown in the secondary tile
this is my code  that i use to resize
//restablecemos el nuevo tamañao 100*100
            using (var sourceStream = await file.OpenAsync(FileAccessMode.Read))
            {
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);
                BitmapTransform transform = new BitmapTransform() { ScaledHeight =100, ScaledWidth= 100 };
                PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Rgba8,
                BitmapAlphaMode.Straight,
                transform,
                ExifOrientationMode.RespectExifOrientation,
                ColorManagementMode.DoNotColorManage);

                using (var destinationStream = await localfile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destinationStream);
                    encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, 100,100,96, 96, pixelData.DetachPixelData());
                    await encoder.FlushAsync();
                }
            }

and this is my code that i use to pin and show the secondary tile
  private async void btnpin(object sender, RoutedEventArgs e)
    {

        //mantenmos abierta el appbar
        this.miappbar.IsSticky = true;

        //obtenemos la imagen del .json y la mostramos en  la nota
        Uri smalllogo = new Uri(pequeniaImagen);

        //creamos el secondary tile
        SecondaryTile secondary = new SecondaryTile(logoSecondaryTileld, String.Format("{0} {1:d}",pageTitle.Text,Convert.ToDateTime(tvFecha.Text)),pageTitle.Text,logoSecondaryTileld, TileOptions.ShowNameOnLogo,smalllogo);
        secondary.DisplayName =pageTitle.Text;//nombre de la nota
        //obtenemos el color de fondo del secondary tile
        SolidColorBrush brush= Editor.returnColorfromString(Mcolor);
        secondary.BackgroundColor = brush.Color;
        //color del texto
        secondary.ForegroundText = ForegroundText.Dark;

        bool isPinned = await secondary.RequestCreateForSelectionAsync(detalles.GetElementRect((FrameworkElement)sender), Windows.UI.Popups.Placement.Below);
        //el usuario pinieo la nota
        if (isPinned)
        {
            //ocultamos el btn pin
            btnpin.Visibility = Visibility.Collapsed;
            //mostramos el btn unpin
            btnunpin.Visibility = Visibility.Visible;
            this.firstbord.Visibility = Visibility.Collapsed;

        }

        this.miappbar.IsSticky = false;

    }

does anybody knows the reason of this error?
i hope you can help me
thanks