text:
Q: RESTIFY: Error: socket hang up] code: 'ECONNRESET' on multiple requests I am implementing a node app, which brings in order details from BigCommerce.
Multiple calls are made to BigCommerce API asynchronously using Restify JsonClient.
It works fine for some calls but after that i gives error:  [Error: socket hang up] code: 'ECONNRESET', sslError: undefined, body: {}
I have tried turning off socket pooling ie by setting agent=false, but it still gives same error.
Following is code which makes call to BigCommerce API
makeRequest = function (url, params, headers, orderDetails, cb) {
                var options = {
              headers: headers
              };

                var client = restify.createJsonClient({
                    url: url
                });

                client.get(options, function(err, req, res, obj) {
                    if(err){
                        console.log(err);
                        cb(err,obj);
                    } else if(obj != null) {
                        var result = obj;
                        if(orderDetails == null) {
                            cb(null,result);
                        } else {
                            cb(null, result , orderDetails);
                        }
                    }
                });
            };

I get following error:
{ [Error: socket hang up] code: 'ECONNRESET', sslError: unde
fined, body: {} } Error: socket hang up
    at SecurePair.error (tls.js:993:23)
    at EncryptedStream.CryptoStream._done (tls.js:689:22)
    at CleartextStream.read [as _read] (tls.js:490:24)
    at CleartextStream.Readable.read (_stream_readable.js:320:10)
    at EncryptedStream.onCryptoStreamFinish (tls.js:301:47)
    at EncryptedStream.g (events.js:175:14)
    at EncryptedStream.EventEmitter.emit (events.js:117:20)
    at finishMaybe (_stream_writable.js:352:12)
    at endWritable (_stream_writable.js:359:3)
    at EncryptedStream.Writable.end (_stream_writable.js:337:5)
    at EncryptedStream.CryptoStream.end (tls.js:628:31)
    at Socket.onend (_stream_readable.js:483:10)

Why am i getting such error? How can i handle it?
Thanks

A: I just wanted to make sure that you're setting the agent setting in the right area.
Include the

"agent": false

in your options.  (It's not set in the options in the code you pasted)
Per gfpacheco in the comments here: https://github.com/restify/node-restify/issues/485

By default NodeJS uses agents to keep the TCP connection open, so you can reuse it.
  The problem is that if the server is closed, or it closes your connection for whatever reason you get the ECONNRESET error.
To close the connection every time you just need to set agent: false in your client creation

I've tried this solution and it worked for me.
Other than that, the

"secureOptions": "constants.SSL_OP_NO_TLSv1_2"

solution posted here sounds like it could be the right path, since you're getting an sslError.

A: Maybe you are running into this issue https://github.com/joyent/node/issues/5360
TL;DR: You could try with latest node version and secureOptions: constants.SSL_OP_NO_TLSv1_2 added to your options.


text:
Q: Scaling reputation/badges by number of users I am not entirely sure how comparable reputation and badges are across Stack Exchange sites. Of course, an obvious concern is that if the reputation points needed to earn certain privileges are uniform across Stack Exchange sites, then sites with a lower number of people will unambiguously be less conducive to mobility.
If this is indeed the case, should the reputation points needed to ascend to a new privilege not be scaled by number of users on the sites?
Reputation is an increasing function of likes, which are in turn an increasing function of number of users. If this is not already the case, this should be taken into account!
For instance, a 10,000 reputation on the Economics site implies much more of an 'impact' as regards the number of users on the site as opposed to, say 10,000 on Mathematics. My point is simple- a user on the 90th percentile in the reputation distribution should have the same privileges across sites.

A: First, the Economics site is in "beta", so the requirements for privilieges are already lower than on fully established sites like Mathematics, to reflect the fact young sites need user-moderators quickly. If/when it graduates, people will have to work hard to re-earn them to the new standard.

If there are constantly-moving goalposts, you'd have to choose what happens in the many times users drop below the threshold for a privilege they earned as a result of other users earning rep. Either:

*

*Have people frequently lose privileges they earned while other users post good content, raising the average. Expect a lot of angry "Why can't I X anymore?" posts on meta, and a lot of users getting disillusioned because they can't keep up with what they can and can't do on each site.

*Have users never lose privileges, meaning some users have more privileges than other users who have more rep, because the latter users joined later when reaching the top percentiles was harder.

Both options sound very confusing.
Then there's the weird possible case of, a user who is just outside of the 90th percentile, slipping up into the 90th percentile not through earning it by actually doing anything, but because a flood of new users joined after a question went viral, lowering the average.

I also don't think it's possible to design a system that eliminates differences between sites. Even if we adjust for averages or percentiles, there will be different distributions and patterns. I think this introduces a lot of potential confusion and complication for not very much gain.
The most important case - very young Beta sites vs mature sites - is already coverred by the difference between beta sites and launched sites.

redpajama_set_name: RedPajamaStackExchange


text:
Q: useSelector only returning initial state I'm building a simple review app with react and redux toolkit.
Reviews are added via a form in AddReview.js, and I'm wanting to display these reviews in Venue.js.
When I submit a review in AddReview.js, the new review is added to state, as indicated in redux dev tools:

However when I try to pull that state from the store in Venue.js, I only get the initial state (the first two reviews), and not the state I've added via the submit form:

Can anyone suggest what's going wrong here?
Here's how I've set up my store:
store.js
import { configureStore } from "@reduxjs/toolkit";
import reviewReducer from '../features/venues/venueSlice'

export const store = configureStore({
    reducer:{
       reviews: reviewReducer
    }
})

Here's the slice managing venues/reviews:
venueSlice.js
import { createSlice } from "@reduxjs/toolkit";

const initialState = [
    {id:1, title: 'title 1',blurb: 'blurb 1'},
    {id:2, title: 'title 2',blurb: 'blurb 2'}
]

const venueSlice = createSlice({
    name: 'reviews',
    initialState,
    reducers: {
        ADD_REVIEW: (state,action) => {
            state.push(action.payload)
        }
    }
})

export const { ADD_REVIEW } = venueSlice.actions

export default venueSlice.reducer

And here's the Venue.js component where I want to render reviews:
import { useParams } from "react-router-dom";
import { useSelector } from "react-redux";

const Venue = () => {
    const { id } = useParams()

    const reviews = useSelector((state) => state.reviews)

    console.log(reviews)

    return (

            {reviews.map(item => (

{item.title}

            ))}

    )
}

export default Venue;

Form component  AddReview.js
import { useState } from "react"
import { useDispatch } from "react-redux"
import { ADD_REVIEW } from "./venueSlice"
import { nanoid } from "@reduxjs/toolkit"

const AddReview = () => {
    const [ {title,blurb}, setFormDetails ] = useState({title:'', blurb: ''})

    const dispatch = useDispatch()

    const handleChange = (e) => {
        const { name, value } = e.target
        setFormDetails(prevState => ({
            ...prevState,
            [name]: value
        }))
    }

    const handleSubmit = (e) => {
        console.log('it got here')
        e.preventDefault()
        if(title && blurb){
            dispatch(ADD_REVIEW({
                id: nanoid(),
                title,
                blurb
            }))
        // setFormDetails({title: '', blurb: ''})
        }
    }

    return(

            <form onSubmit={handleSubmit}>
                <input
                type = 'text'
                name = 'title'
                onChange={handleChange}
                />
                <input
                type = 'text'
                name = 'blurb'
                onChange={handleChange}
                />
                <button type = "submit">Submit</button>
            </form>

    )
}

export default AddReview;

A: I can notice that you pushing directly to the state, I can suggest to use variable in the state and then modify that variable.
Also I suggest to use concat instead of push. Where push will return the array length, concat will return the new array.
When your code in the reducer will looks like that:
import { createSlice } from "@reduxjs/toolkit";

const initialState = [
    reviews: [{id:1, title: 'title 1',blurb: 'blurb 1'},
             {id:2, title: 'title 2',blurb: 'blurb 2'}]
]

const venueSlice = createSlice({
    name: 'reviews',
    initialState,
    reducers: {
        ADD_REVIEW: (state,action) => {
            state.reviews = state.reviews.concat(action.payload);
        }
    }
})

export const { ADD_REVIEW } = venueSlice.actions

export default venueSlice.reducer

And then your selector will looks like that:
const reviews = useSelector((state) => state.reviews.reviews)

A: Your code seems to be fine. I don't see any reason why it shouldn't work.
I run your code on stackblitz react template and its working as expected.
Following is the link to the app:
stackblitz react-redux app
Link to the code:
Project files react-redux
if you are still unable to solve the problem, do create the sandbox version of your app with the issue to help further investigate.
Thanks

A: Expanding on @electroid answer (the solution he provided should fix your issue and here is why):
Redux toolkit docs mention on Rules of Reducers :

They are not allowed to modify the existing state. Instead, they must make immutable updates, by copying the existing state and making changes to the copied values.

and on Reducers and Immutable Updates :

One of the primary rules of Redux is that our reducers are never allowed to mutate the original / current state values!

And as mdn docs specify the push method changes the current array (so it mutates your state). You can read more about mutating the state in the second link link (Reducers and Immutable Updates).
If you really want to keep the state.reviews and avoid state.reviews.reviews you could also do something like this:
        ADD_REVIEW: (state,action) => {
            state = [...state, action.payload];
        }

But I wouldn't recommend something like this in a real app (it is avoided in all the examples you can find online). Some reason for this would be:

*

*It harder to work with, read and track the state when having an overall dynamic state instead of a state structure

*It leads to a lot of slices in a real app (creating a slices for an array without grouping the data)  which can also become hard to track and maintain.

*Usually you need a redux slice in multiple parts of the app (otherwise you can just use state). That data is usually bigger than just an array and not grouping the data properly on reducers can become very very confusing.

But I would definitely advise to use something else (not reviews.reviews). In your case I think something like state.venue.reviews
(so on store.js
...
export const store = configureStore({
    reducer:{
       venue: reviewReducer // reviewReducer should probably also be renamed to venueSlice or venueReducer
    }
})

So an option to avoid state.venue.reviews or state.reviews.reviews would be to export a selector from the venueSlice.js:
export const selectReviews = (state) => state.venue.reviews

and in your Venue.js component you can just use
const reviews = useSelector(selectReviews)

Exporting a selector is actually suggested by the redux toolkit tutorials as well (this link is for typescript but the same applies to javascript). Although this is optional.


text:
Q: Does a license allow or permit? In US English should I say

You have already activated more sites than your license allows

Or

You have already activated more sites than your license permits

A: In some degree, 'permits' sounds a wee bit more formal. Given the formality of the sentence, I would suggest 'permits'. But then again, you were specific about AmE, and a little digging showed that the use of 'allows' is more widespread in American literature.
This Google Ngram on 'license allows' vs 'license permits' clearly shows that the usage of 'allows' is far more extensive.

Note: The comparison has been done over books written in AmE.


text:
Q: Calculating Awk Output divide by mega=1048576 Hi Can someone please let me know how I can calculate the output field from this command to MB ?
The command below shows the 20 largest file in directory and sub directories
but I need to convert the output to MB. In my script I use an array.. But If you guys show me how to use awk to divide the output for this by mega=1048576
I would really appreciate it .. Please explain the options !!!
ls -1Rs | sed -e "s/^ *//" | grep "^[0-9]" | sort -nr | head -n20 | awk {'print $1'}

Thanks

A: You don't show any sample input or expected output so this is a guess but this MAY be what you want (assuming you cant follow all the other good advice about not parsing ls output and you don't have GNU awk for internal sorting):
ls -1Rs | awk '/^ *[0-9]/' | sort -nr | awk 'NR<21{print $1/1024}'

Note that you don't need all those other commands and pipes when you're already using awk.

A: ls -1Rs | sed -e "s/^ *//" | grep "^[0-9]" | sort -nr | head -n20 | awk {'print $1 / 1024'}     To turn it into MB - You have to divide it by 1024


text:
Q: Keep object in center when zooming? I've build my website using Wordpress (booo, i know) and I have a sticky menu (Menu from Elementor Pro, sticky header plugin from Sticky Menu (or Anything!) on Scroll) that always is showing on the top of the screen when you scroll.
To center this menu i've used custom CSS to the menu-element:
`
.center {
  margin: auto;
  width: 50%;
}

`
The problem is if i zoom in the browser, the menu gets off center the more i zoom. Until i refresh the page and it pops back in center.
Is there a way with CSS to keep the scaling and center of an object the whole time so it updates as i zoom. I want it always the same size, always in the center.
https://www.loom.com/share/fd55196094f942e98b800fcec7250228 Here is a videolink of the problem.
I've tried using:
`
.center {
  margin: auto;
  width: 50%;
}

`
It centers the block but when i zoom in or out, it jumps out of center until i refresh the page.
Website URL is https://visopro.se/


text:
Q: Google Tag Manager tags build up with page loads in Single Page Website I have a single page application linked to Google Tag Manager. I have a custom page load event setup so the tag fires when a "new page loads" (SPA page load).
However seeing that it is a SPA app the DOM doesn't reload completely on page load. My issue with this is that tags that fire on "page load" build up because the page isn't actually refreshed completely.
I was wondering if somebody had a good workflow for getting around this within Google Tag Manager?
An example is below.
URL:
mywebsite.com
Tags:
<script> console.log("my script"); </script>

URL 2:
mywebsite.com/about
Tags
<script> console.log("my script"); </script>
<script> console.log("my script"); </script>

URL 3:
mywebsite.com/work
Tags
<script> console.log("my script"); </script>
<script> console.log("my script"); </script>
<script> console.log("my script"); </script>

And so on depending on how many pages they visit.


text:
Q: c++ Access violation writing location 0x00000000 I have the following code:
In Client.cpp there is the constructor that is doing memory allocation for the array "conturi" of type ContBancar.
Client::Client(string nume, string prenume, string adresa)
{
    this->nume = nume;
    this->prenume = prenume;
    this->adresa = adresa;
    nrCont = 0;
    ContBancar** conturi = new ContBancar*[50];
}

Then there is a method that is adding a account in the "conturi" array:
void Client::adaugaCont(ContBancar* contNou)
{
    conturi[nrCont++] = contNou;
}

This is my code in Main.cpp:
ContBancar ron1 ("1.r", 0, Banca::RON);
Client ioana ("Pop", "Ioana", "Str Dorobantilor 3/4");
ioana.adaugaCont(&ron1);

But it gives me the access violation error at runtime, like the array 'conturi' has no memory allocated. I don't understand why, because the memory should be allocated in the constructor.
Could anyone help me with this?

A: Client::Client(string nume, string prenume, string adresa)
{
    this->nume = nume;
    this->prenume = prenume;
    this->adresa = adresa;
    nrCont = 0;
    //here is your problem!
    ContBancar** conturi = new ContBancar*[50];
}

You redefine conturi as a new array, with the pointer to it stored in the local scope of the constructor.
Change the line to:
conturi = new ContBancar*[50];

and you will then have the object's conturi pointer pointing to the allocated memory.
This will also solve the memory leak you have introduced.
(pointer to heap goes out of scope. memory on heap is leaked)
Or even better, use a std::vector.
In Class definition:
std::vector<ContBancar> conturi;

You don't have to manage the memory yourself with new and delete and you are not restricted to a fixed number of elements either.

A: You're declaring a new pointer variable with the following line:
ContBancar** conturi = new ContBancar*[50];

and the pointer variable will get destroyed at the end of the function call and leak memory leaving any other same-name member variable untouched.
You should rather use the member variable conturi(assuming you have one from the rest of the code):
Client::Client(string nume, string prenume, string adresa)
{
    this->nume = nume;
    this->prenume = prenume;
    this->adresa = adresa;
    nrCont = 0;
    conturi = new ContBancar*[50];
}

or you can use a std::vector<ContBancar> conturi member variable which might be easier to use and to deal with.
This is a simple reproducer to better understand the problem:
class Client {
public:
    int** conturi = 0;

    void function() {
        int** conturi = new int*[50];
    }
};

int main()
{
    Client obj;
    obj.function();
    if(obj.conturi == 0)
       std::cout << "this is still zero"; // This will get printed
}

Example


text:
Q: style not working when element created using PHP's "echo' '" I use PHP code to insert some elements in another PHP file, when the elements were originally created inside the calling PHP file style worked just fine, but when i replaced the code with an 'include(somephpfile.php)', elements were added the way i wanted them to but style didnt apply.
style doesn't apply to elements created this way:
echo '

';
    $query2 = "SELECT description FROM books WHERE bookno = '$temp';";
    $results = mysqli_query($db, $query2);
    $book = mysqli_fetch_array($results);
    echo $book[0];
    echo '

                Learn More

            <button class="myButtone">

              20. 00$
            </button>

';

but it applied when it was done this way:

            <button class="myButtone">

              20. 00$
            </button>


text:
Q: How to create a query for monthly total in MySQL? I have the following DB.
CREATE TABLE IF NOT EXISTS `omc_order` (
  `order_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `customer_id` int(10) unsigned NOT NULL,
  `total` decimal(10,2) NOT NULL,
  `order_date` datetime NOT NULL,
  `delivery_date` datetime NOT NULL,
  `payment_date` datetime NOT NULL,
  PRIMARY KEY (`order_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=32;

I want to create a statistic page to see total payment and total order monthly.
In one page I want to display something like this.
Month    Year    Total Order    Total Payment
Sep       09       800             760
Oct       09       670             876
Nov
...
...

Now I am not sure how to create query for this.
Could anyone give me some ideas how to approach this?

A: You can use the Mysql date and time functions to group the rows for each month and them sum them up. Something like this could be a starting point:
  SELECT monthname(payment_date) AS Month,
         year(payment_date) AS Year,
         sum(total) AS 'Total Order',
         sum(??) AS 'Total Payment'
    FROM omc_order
ORDER BY payment_date
GROUP BY month(payment_date),
         year(payment_date);

I'm not sure how you compute the values for Total Payment.
Edit: sum() is a MySQL function.

A: you need to Cast the datetime to a mount , then group by
SELECT SUM(foo), MONTH(mydate) DateOnly FROM a_table GROUP BY DateOnly;

see a close question :
MySQL/SQL: Group by date only on a Datetime column

A: The following should help you get started.
select sum(total) from omc_order group by month(order_date), year(order_date)


text:
Q: UITableView with read more button after the 120 character in the UILabel in objective c I have one tableview and inside on UILabel, 120 characters have to show there and after read more button, when we clicking on read more button cell want to expand as per the content of UILabel text. please help me to do this.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{
if(isReadMoreButtonTouched && [indexPath row]== indexOfReadMoreButton)

{
    NSLog(@"cccccccccccccccccccccc -------- %f",size.height);
    return size.height+52;;
}
else{
    return 120.0f;
}
}

here the size is the height of UILabel
- (CGFloat)getLabelHeight:(UILabel*)label
{
CGSize constraint = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);
CGSize size;

NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
CGSize boundingBox = [label.text boundingRectWithSize:constraint
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{NSFontAttributeName:label.font}
                                              context:context].size;

size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));

return size.height;
}

A: You have to substring label's string to 120 first and then assigning that 120 substring chars to label. When you tap more button, assign the full original length string to the label again, it will automatically grow cell height if you're using builtin dynamic height of cell for row.
Meanwhile you can also check this CollapsibleLabel.


text:
Q: Implement hashCode and equals method but class is final There is a class Message and it doesn't have hashCode and equals implementations. So I wanted to extend it and implement my own hashCode and equals method. Alas! This class is final. Is there a technique/hack/workaround that I can use to do this?
I want to avoid adding duplicated to Set. This is the reason.

A: In the case where you cannot extends the base class, another technique would be making a wrapper class, and delegating all the methods to the base class. This works good in this case because the base class is implementing a base interface:
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.UUID;

public class WrappedMessage implements IMessage {
    private final IMessage message;

    public WrappedMessage(IMessage message) {
        this.message = message;
    }

    @Override
    public int hashCode() { // TODO add your own implementation
        return 4; // chosen by fair dice roll.
                  // guaranteed to be random.
    }

    @Override
    public boolean equals(Object obj) { // TODO add your own implementation
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        return true;
    }

    // Delegate all other methods:

    @Override
    public IMessage createCopy() {
        // this method is special as it returns an IMessage,
        // make sure to give back our wrapper instead
        return new WrappedMessage(message.createCopy());
    }

    @Override
    public byte[] getBody() {
        return message.getBody();
    }

    @Override
    public void setBody(byte[] body) {
        message.setBody(body);
    }

    @Override
    public String getContentType() {
        return message.getContentType();
    }

    @Override
    public void setContentType(String contentType) {
        message.setContentType(contentType);
    }

    @Override
    public String getCorrelationId() {
        return message.getCorrelationId();
    }

    @Override
    public void setCorrelationId(String correlationId) {
        message.setCorrelationId(correlationId);
    }

    @Override
    public String getDeadLetterSource() {
        return message.getDeadLetterSource();
    }

    @Override
    public long getDeliveryCount() {
        return message.getDeliveryCount();
    }

    @Override
    public Instant getEnqueuedTimeUtc() {
        return message.getEnqueuedTimeUtc();
    }

    @Override
    public Instant getExpiresAtUtc() {
        return message.getExpiresAtUtc();
    }

    @Override
    public String getLabel() {
        return message.getLabel();
    }

    @Override
    public void setLabel(String label) {
        message.setLabel(label);
    }

    @Override
    public UUID getLockToken() {
        return message.getLockToken();
    }

    @Override
    public Instant getLockedUntilUtc() {
        return message.getLockedUntilUtc();
    }

    @Override
    public void setLockedUntilUtc(Instant lockedUntilUtc) {
        message.setLockedUntilUtc(lockedUntilUtc);
    }

    @Override
    public MessageBody getMessageBody() {
        return message.getMessageBody();
    }

    @Override
    public void setMessageBody(MessageBody body) {
        message.setMessageBody(body);
    }

    @Override
    public String getMessageId() {
        return message.getMessageId();
    }

    @Override
    public void setMessageId(String messageId) {
        message.setMessageId(messageId);
    }

    @Override
    public String getPartitionKey() {
        return message.getPartitionKey();
    }

    @Override
    public void setPartitionKey(String partitionKey) {
        message.setPartitionKey(partitionKey);
    }

    @Override
    public Map<String, Object> getProperties() {
        return message.getProperties();
    }

    @Override
    public void setProperties(Map<String, Object> properties) {
        message.setProperties(properties);
    }

    @Override
    public String getReplyTo() {
        return message.getReplyTo();
    }

    @Override
    public void setReplyTo(String replyTo) {
        message.setReplyTo(replyTo);
    }

    @Override
    public String getReplyToSessionId() {
        return message.getReplyToSessionId();
    }

    @Override
    public void setReplyToSessionId(String replyToSessionId) {
        message.setReplyToSessionId(replyToSessionId);
    }

    @Override
    public Instant getScheduledEnqueueTimeUtc() {
        return message.getScheduledEnqueueTimeUtc();
    }

    @Override
    public void setScheduledEnqueueTimeUtc(Instant scheduledEnqueueTimeUtc) {
        message.setScheduledEnqueueTimeUtc(scheduledEnqueueTimeUtc);
    }

    @Override
    public Instant getScheduledEnqueuedTimeUtc() {
        return message.getScheduledEnqueuedTimeUtc();
    }

    @Override
    public void setScheduledEnqueuedTimeUtc(Instant scheduledEnqueueTimeUtc) {
        message.setScheduledEnqueuedTimeUtc(scheduledEnqueueTimeUtc);
    }

    @Override
    public long getSequenceNumber() {
        return message.getSequenceNumber();
    }

    @Override
    public String getSessionId() {
        return message.getSessionId();
    }

    @Override
    public void setSessionId(String sessionId) {
        message.setSessionId(sessionId);
    }

    @Override
    public Duration getTimeToLive() {
        return message.getTimeToLive();
    }

    @Override
    public void setTimeToLive(Duration timeToLive) {
        message.setTimeToLive(timeToLive);
    }

    @Override
    public String getTo() {
        return message.getTo();
    }

    @Override
    public void setTo(String to) {
        message.setTo(to);
    }

    @Override
    public String getViaPartitionKey() {
        return message.getViaPartitionKey();
    }

    @Override
    public void setViaPartitionKey(String partitionKey) {
        message.setViaPartitionKey(partitionKey);
    }
}


text: Q: Determine when a file has been dragged out of the window - Safari 6 OS X I'm currently able to determine when the user has dragged a file out of the browser window in every other browser, other than Safari on OS X.  All other browsers seem to provide some cues in the dragleave event.  For example, in Chrome, event.clientX and event.clientY are set to 0.  In Firefox, event.relatedTarget is null.  However, no such clues seem to exist in Safari on OS X.  Does anyone have any idea how I can can determine when a user has dragged a file out of the browser window (after dragging it into the window) on this browser?


text:
Q: regular expression to check file content type is .doc or not? When i use a file upload i use to check file contenttype with regular expressions... For ex
private bool IsImage(HttpPostedFile file)
    {
        if (file != null && Regex.IsMatch(file.ContentType, "image/\\S+") &&
          file.ContentLength > 0)
        {
            return true;
        }
        return false;
    }

This returns my file is an image or not... How to check it is a word(.doc/.docx) document or not using c#...

A: DOC's mimetype is:

*

*application/msword [official]

*application/doc

*appl/text

*application/vnd.msword

*application/vnd.ms-word

*application/winword

*application/word

*application/x-msw6

*application/x-msword

happy regex'ing
Edit:According to @Dan Diplo, you should also check for .docx's MIMEtypes

A: For example using Axarydax answer: (so no docx mime check)
List<String> wordMimeTypes = new List<String>();
wordMimeTypes.Add("application/msword");
wordMimeTypes.Add("application/doc");
wordMimeTypes.Add("appl/text");
wordMimeTypes.Add("application/vnd.msword");
wordMimeTypes.Add("application/vnd.ms-word");
wordMimeTypes.Add("application/winword");
wordMimeTypes.Add("application/word");
wordMimeTypes.Add("application/x-msw6");
wordMimeTypes.Add("application/x-msword");
//etc...etc...

if (wordMimeTypes.Contains(file.ContentType))
{
    //word document
}
else
{
    //not a word document
}

More readable than Regex because regex will become a pain in the ass when trying to make a expression for a dozen of mime types

A: if the content-type's are known (see Axarydax answer), why would you want to use regex?

A: Take a look at regexblid A library with regular expression.
Also good to know, regexbuddy can be used to validate and test regular expressions.

A: Gumbo is right, it might just be easier to check the file's extension.
Path.GetExtension(file.FileName)


text:
Q: How would I set up a docker container that runs an OS version of chrome and puppeteer? I am creating a node.js QR code reader. From experience, I have found that the most reliable and efficient reader is the built-in Chrome barcode detector API. Thus, I decided to build this application with a Puppeteer instance running Chrome. I successfully made the app pass in an image with a QR code to a Puppeteer browser instance, scan the QR code, and then return the result. It works as intended on my Mac. I packaged this functionality in an express app to make a scanning API. Currently, I am trying to deploy it on the web using a service that requires a docker container. However, I am struggling to make a Docker file that can runs the application.
I have tried installing Chrome in these three ways: 1, 2, 3. All of them have failed. Upon further searching, I discovered that Chrome supports the Barcode Detection API only on OS devices. Therefore, I need a way to ensure the docker container runs an OS version of Chrome.
If it is helpful, here is the function I am running with Puppeteer that works locally:
const puppeteer = require('puppeteer');

function scanQR = async (src) => {
  try {
    const browser = await puppeteer.launch({
      args: ['--no-sandbox', '--disable-setuid-sandbox'],
    });
    const page = await browser.newPage();
    await page.setJavaScriptEnabled(true);
    await page.setCacheEnabled(true);
    await page.goto('https://nimiq.github.io/qr-scanner/demo/');
    const barcodeDetectorPromise = page.evaluate(
      async (src) =>
        new Promise(async (resolve, reject) => {
          const image = new Image();

          image.src = src;

          // eslint-disable-next-line no-undef
          const barcodeReader = new BarcodeDetector({ formats: ['qr_code'] });

          await new Promise((resolve, reject) => (image.onload = resolve));

          resolve(await barcodeReader.detect(image));
        }),
      src
    );

    const timeoutPromise = new Promise((resolve, reject) => {
      setTimeout(() => resolve([]), 2000);
    });

    const result = await Promise.race([barcodeDetectorPromise, timeoutPromise]);

    await browser.close();

    return result;
  } catch {
    return [];
  }
};

The src is a link to an image with a QR code such as a base64URL whose image data includes a QR.


text:
Q: Failure when trying to deploy a model i am trying to load a model on pycharm saved for prediction but i am getting the below error
ModuleNotFoundError: No module named 'sklearn'
what could be the reason

A: The scikit-learn module is not installed in your python environment


text:
Q: Dynamically adding child views to a ScrollView I have a ScrollView which has a LinearLayout as a child and which contains all the other views that I shall be scrolling like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">
        <LinearLayout
            android:id="@+id/profile_fields_container"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/account_person_name_label" />

            <EditText
                android:id="@+id/person_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:minWidth="150dp"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="@string/account_person_emailId_label" />
            <EditText
                android:id="@+id/person_emailId"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:inputType="textEmailAddress"
                android:minWidth="150dp"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="@string/account_person_phoneNo_label" />
            <EditText
                android:id="@+id/person_phoneNo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:inputType="phone"
                android:maxLength="10"
                android:minWidth="150dp"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="@string/account_person_password_label" />
            <EditText
                android:id="@+id/password"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:minWidth="150dp"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="@string/account_person_retypePassword_label" />
            <EditText
                android:id="@+id/retype_password"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:minWidth="150dp"/>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="20dp">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/learner_tutor_status_label" />

                <android.support.v7.widget.AppCompatSpinner
                    android:id="@+id/learner_tutor_status_spinner"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>

            </LinearLayout>

        </LinearLayout>

    </ScrollView>

    <Button
        android:id="@+id/create_account"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/create_account_string"
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_weight="0"/>

</LinearLayout>

Now, when I try to add another view inside the LinearLayout(which is inside the ScollView) at the end of it, dynamically, it does get added but half of it gets hidden underneath the Button(see the button with id @+id/create_account) and I am not able to scroll to it. It means that it doesn't get added to the ScrollView effectively.
This "other" view that I added dynamically is as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="10dp">

    <!--Type of Tutor-->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/type_of_tutor_label"
        android:textStyle="italic"/>
    <com.learncity.util.MultiSpinner
        android:id="@+id/type_of_tutor_spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Professor, Undergraduate, Freelancer..."/>

    <!--Subjects/Disciplines-->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/disciplines_label"
        android:textStyle="italic"
        android:layout_marginTop="10dp"/>
    <com.learncity.util.MultiSpinner
        android:id="@+id/subjects_taught_spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Physics, Maths, Computer Science..."/>

</LinearLayout>

Does anyone know how to make the dynamically added view as effectively "scrollable" ?
EDIT 1:
In case if anyone wants to know how this conditional view is being added dynamically, here is the edited version of the code:
void showConditionalTutorUI() {
        // Initialize the first time
        if(typeOfTutorMultiSpinner == null && subjectsICanTeachMultiSpinner == null){
            if(profileFieldsContainer == null){
                profileFieldsContainer = (ViewGroup)rootView.findViewById(R.id.profile_fields_container);
            }
            if(rootTutorConditionalLayout == null){
                rootTutorConditionalLayout = layoutInflater.inflate(
                        R.layout.layout_conditional_tutor_ui,
                        profileFieldsContainer,
                        false);
            }
            // Add the inflated layout to the last of the container
            profileFieldsContainer.addView(rootTutorConditionalLayout, profileFieldsContainer.getChildCount());

        isConditionalTutorUIVisible = true;
    }

EDIT 2:
Okay, here is the LayoutInspector's view of it:(The view that I am hovering over in the hierarchy(highlighted by a red border) is the one not being seen.)

A: Try to add android:fillViewport="true" and android:scrollbars="vertical" to your Scroll View.
  <ScrollView
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:fillViewport="true"
     android:scrollbars="vertical"
     android:layout_weight="1"/>


text:
Q: fixed header and scrollable body in table in html angular In Angular i have a table and it should be scrollable. But header should be fixed. but while scrolling header is not fixed. please help

A: Well, the requirement seems to be you want a scrollable table body. Not sure if angular could makes things different anyhow in this case.
Just to be sure, please see the fiddle at https://jsfiddle.net/hh6etg6s/ if this serves the purpose.
.tablediv {
  padding:20px;
}
table ,tr td{
    border:1px solid red
}
tbody {
    display:block;
    height:200px;
    overflow:auto;
}
thead, tbody tr {
    display:table;
    width:100%;
    table-layout:fixed;/* even columns width , fix width of table too*/
}
thead {
    width: calc( 100% - 1em )/* scrollbar is average 1em/16px width, remove it from thead width */
}
table {
    width:400px;
}

A: Have two instances of your table in your HTML in separate divs. In the top container, hide your body. In your bottom container hide your headers. Do this with visibility: collapse;
If you need to hide the scrollbars:
Hide Scroll Bars

A: Check out this post from angularjswiki:
https://www.angularjswiki.com/material/mat-table-fixed-sticky-header/
Taken from there:

In Angular, To create a mat-table with fixed header and scrollable body, we have to add sticky input to the matHeaderRowDef.


text:
Q: making simple blog reply quotes with php I've been struggling with this for hours
I need to convert this string
"> example quote /n"

to this

 example quote /n

so if I have a more than one quote ">" like this
">> example quote /n"

it would look like this

example quote

another example would be:
">>this is a great string /n > next quote"

 this is a great string

 next quote

This is my code so far
            // plain comment
            $text = "> we are here /n";

            // explode into array
            $single_quotes = explode("/n", $text);

            $renderedHtml = "";
            $quoteopeners = "";
            $quoteclosers = "";

            //make blockquote out of it
            foreach($single_quotes as $quote)
            {
                $number_of_quotes = substr_count($quote,'>');

                for($i = 0; $i < $number_of_quotes; $i++)
                {
                   $quoteopeners.= '
';
                   $quoteclosers.='
';
                }

                //replace all the '>' with spaces
                $quote = str_replace('>','', $quote);
                $quote = str_replace('/n','', $quote);

                $renderedHtml.= $quoteopeners.$quote.$quoteclosers;
            }

For some reason when I type
"> we are here /n "
it renders these random quotes at the end

 we are here

If you had a complete new solution to this problem it would be fine too

A: $quoteopeners and $quoteclosers are not initialized the right place. Try this :
<?php
 // plain comment
    $text = ">> we are here /n";

    // explode into array
    $single_quotes = explode("/n", $text);

    $renderedHtml = "";

    //make blockquote out of it
    foreach($single_quotes as $quote)
    {
        $number_of_quotes = substr_count($quote,'>');

        $quoteopeners = "";
        $quoteclosers = "";

        for($i = 0; $i < $number_of_quotes; $i++)
        {
           $quoteopeners.= '
';
           $quoteclosers.='
';
        }

        //replace all the '>' with spaces
        $quote = str_replace('>','', $quote);
        $quote = str_replace('/n','', $quote);

        $renderedHtml.= $quoteopeners.$quote.$quoteclosers;
    }

    echo $renderedHtml;
?>

A: You can do use preg_replace_callback() for this
<?php

 $str = preg_replace_callback(
            '/^(\>+) (\w+(\s+\w+)*)/',
            function ($matches) {
                return str_repeat("
", strlen($matches[1])) . $matches[2] . str_repeat("
", strlen($matches[1]));
            }, $string);
    echo $str;

For example;
//Output:
This is a simple quote

$string = "> This is a simple quote";

//Output:

This is a simple quote

$string = ">> This is a simple quote";

Live Preview
Useful sites

*

*http://www.phpliveregex.com/

*http://www.regexr.com/


text:
Q: How to access app.config from blueprint outside of request (Flask, pluggable views) I would like to be able to access app.config from a Pluggable View class
What i have:
flask app, pluggable views, blueprints
from flask import current_app

# using pluggable views
class Router(MethodView):

  # applying flask_login.login_required to all methods
  # in the current class
  decorators = [flask_login.login_required]

  def get(self, *args, **kwargs):
    pass

  def post(self, *args, **kwargs):
    pass

What i want:
(this does not work, as there's no app / request context, and current_app isn't set)
from flask import current_app

class Router(MethodView):

  # this does not work
  if current_app.config['LOGIN_REQUIRED']:
    decorators = [flask_login.login_required]

  def get(self, *args, **kwargs):
    pass

  def post(self, *args, **kwargs):
    pass

A: The problem is with your python code (as you might realize given it's 5 months later), not your flask code or flask.
When you set fields directly in a class like that, you're setting the static fields of the class. When a class is instatiated it 'inherits' the static fields. But they're not recalculated ever. To fix your problem with current_app not being set you can just do:
from flask import current_app

class Router(MethodView):

  def __init__(self):
    login_required = current_app.config['LOGIN_REQUIRED']
    # other logic etc

  def get(self, *args, **kwargs):
    pass

  def post(self, *args, **kwargs):
    pass

And if you wanted to make it so you can access login_required in get and post, you would just set self.login_required in the constructor instead, as that would initialize an instance variable.
But you still can't change the decorators like that in flask. The reason why is because it doesn't convert the decorators at request time, it converts them when you call .as_view on the pluggable view. As we can see in the source file flask/views.py:
class View(object):
  ...
  ...

      @classmethod
    def as_view(cls, name, *class_args, **class_kwargs):
        ...
        ...

        if cls.decorators:
            view.__name__ = name
            view.__module__ = cls.__module__
            for decorator in cls.decorators:
                view = decorator(view)
        ...
        ...
        return view

As you can see, it specifically accesses the static decorator list when it's converted into a view. So it doesn't matter what you do to it in the constructor, it has already created them.
If you need this functionality (I don't know why you'd need that in the first place?) then it would probably be best to implement it in your own decorator.


text:
Q: how to stop backspace from redirecting to a blank page? I am working on a JSP page and whenever i place the cursor on a disabled textbox and hit backspace on my keyboard i get a blank screen. How do I solve this problem?
I have already tried using the "readonly" attribute but the problem still persists.

A: You can control this behavior by calling event.preventDefault(); in-case of back button pressed using keydown event of the readOnly fields as following:
HTML:
<input type="text" id="search" readOnly />

jQuery:
jQuery('#search').bind('keydown', function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '8')
        event.preventDefault();
});

DEMO


text:
Q: Selenium TestNG Throw Exception get null pointer exception while Opening Chilld browser In above code at this line:
Set<String> statmentwindow = driver.getWindowHandles();

the compiler will throw an exception and the Test Case will be failed. Exception was like:
Cannot invoke "org.openqa.selenium.WebDriver.getWindowHandles()" because "Pages.FundsPage.driver" is null

Code trials:
public void fundClick() throws InterruptedException
    {
            btnfunds.click();
            Thread.sleep(2000);
            btnaddfunds.click();
            Thread.sleep(2000);
            Set<String> statmentwindow = driver.getWindowHandles();
            System.out.println(statmentwindow);
            String[] win2 =new String[10];
            Iterator<String> itr = statmentwindow.iterator();
            for (int i=0;i<statmentwindow.size();i++)
            {
                win2[i]=itr.next();
                System.out.println(win2[i]);
            }
            driver.switchTo().window(win2[1]);
            driver.close():
    }

A: I don't see you using the Pages.FundsPage.driver instance within the first two lines which are successfully executed within fundClick() method.
You were using btnfunds element. Hence when you try to access driver instance, you see the error:
org.openqa.selenium.WebDriver.getWindowHandles()" because "Pages.FundsPage.driver" is null


text:
Q: Why must I access a global variable through window? I have some JS in a file, and some JS on a page.
If I try to access my function via NucleusPreview, it can't be found
If I access it via window.NucleusPreview, it is found
Why is that?  Am I doing something wrong, or do I need to be explicit when accessing objects in window scope when in another function?
Update: I was creating NucleusPreview inside the onReady, but moved it so I think the window scope was a red herring.  The problem is that when calling it in onReady, gave it time to load the file, but when I moved it out I started calling it too early.
The JS in the the file is basically:
var NucleusPreview;

(function ($) {
    NucleusPreview = function NucleusPreview(source) {
        //ctor stuff
    };

    NucleusPreview.prototype.AdjustCaption = function AddCaption() {
        //caption stuff
    };
})(jQuery);

My JS on the page:
$('.nucleus-preview').each(function eachNucleusPreview(index, element) {
    var jElement = $(element),
        vidId = jElement.data('video-id'),
        np = new NucleusPreview($(element)); //Uncaught RefError: NucleusPreview is not defined

    _wq.push({
        id: vidId,
        onReady: function (video) {
            np.AdjustCaption();
        }
    });
});

A: As long as the first bit of code you provided is executed first and none of the code is executed prior to the DOM being loaded (you can put all of this code in a document.ready() callback to ensure that is the case), you should be able to. Run this code snippet and wait a moment, you will see that it works without qualifying window.
In the example below, I've placed all the code in a document.ready() callback (although that is not required for the code to run) to ensure that you don't try to access $('.nucleus-preview') before the DOM is ready.
Additionally, doing this will keep NucleusPreview out of the global scope in the first place, which is always a good idea.

// Always make sure the DOM is fully loaded prior to scanning for DOM elements.
// This can be done by placing all of your code in a "document.ready()` callback
// function as I'm doing here or by placing the code at the end of the HTML document,
// just before the close of the body ().
$(function(){

  // Now NucleusPreview is scoped to this function, which keeps it out of the
  // global scope and that's always good, so you don't pollute the window.
  var NucleusPreview;

  (function ($) {
    NucleusPreview = function NucleusPreview(source) {
        //ctor stuff
    };

    NucleusPreview.prototype.AdjustCaption = function AddCaption() {
        //caption stuff
    };
  })(jQuery);

  var _wq = [];  // Added to allow code to execute

  $('.nucleus-preview').each(function eachNucleusPreview(index, element) {
    var jElement = $(element),
        vidId = jElement.data('video-id'),
        np = new NucleusPreview($(element)); // <-- Works just fine!

    _wq.push({
        id: vidId,
        onReady: function (video) {
            np.AdjustCaption();
        }
    });
  });
});

console.log($('.nucleus-preview'));


text:
Q: template fragment caching doesn't seem to work for some custom template tags I've been implementing caching in my django application, and used per view caching via the cache API and template fragment caching.
On some of my pages I use a custom django template tag, this tag is provided via a third party developer, it takes some arguments in its template tags, and then make a request to a remote server, gets the response back over XML, and then renders the result in my page.
Great - I thought I could easily cache this using fragment caching, so I :
{% load cache %}
{% cache 500 request.user.username %}
{% load third party custom tags %}
{% expensive custom tag set that gets stuff from a third party server via xml %}
{{ some.stuff}}
{% endcache %}

Trouble is no matter what I do, the requests still get fired off to that remote server, it seems Django doesn't like to cache these custom template tags. I know memcached is working great, for other views and templates it all works just fine. Am I doing something that is incompatible with the fragment caching? Is there a way round it?

A: If the template fragment you're trying to cache can't be pickled, memcached won't be able to store it and will raise an exception. From what I can gather, exceptions generated when rendering Django templates are suppressed. Since your custom tag is doing HTTP requests, maybe socket objects (which can't be pickled) are getting stored to the template fragment somehow.
If this is the case, the only way around it I can think of would be to modify the custom tag to get rid of any leftover socket objects.

A: Have you tried to use a different name for the cache fragment? There could be a problem with using request.user.username for a couple of reasons:

*

*If a user is not signed in,
request.user.username could be empty,
resulting in a non-named cache
fragment

*If a user is signed in, this will
call the 3rd party template tag at
least once for each user every 3
mintues
Maybe it's worth trying to rename the cache fragment name to test:
{% cache 500 customxml %}

I'd also try loading of the 3rd party template tag outside the cache tag like so:
{% load cache third_party_custom_tags %}
{% cache 500 request.user.username %}
{% expensive custom tag set that gets stuff from a third party server via xml %}
{{ some.stuff}}
{% endcache %}

What I'm not sure of is if the cache framework caches the results of a template tag. If that doesn't work, I'd take a look at what the template tag is doing under the hood and re-implement the template tag using Django's low-level cache.

A: I think the problem is the custom tag, as you suggested.
I disagree that the request.user.username is a problem, as the documentation for the subject actually gives that as an example, and I have used it with internal caching (number of posts, for instance), in testing, and it worked fine.
The low level cache is potentially useful, but I would take a look at your custom tag to see what wouldn't be caching.  Without the code it's hard to guess, but my guess would be something like the time, or some other variable, is being returned whic his causing it to force an update (if the XML pulls any data that changes Django may force an update, depending on other settings). I've had mixed results with Django's caching, so I would have a look at your XML feed(s) to see if it's causing anything to stop caching.

A: I don't think this has anything to do with the custom tag.
We endded up rewriting the Django caching tag because we needed more control than was possible with the one that was supplied. You might make a copy of it yourself and stick some debugging print statements into it. In particular, check the filename (assuming you are caching to files) and see what is being generated. It could be that it is changing when it shouldn't (for some unknown reason) and that would mean that it is always needing to re-render then enclosed block.
Look in django/templatetags/cache.py. It's only 63 lines of code.


text:
Q: UnExpected Method Call Assertion Error I am new to EasyMock and am struggling with the following issue that i am facing while running the test cases. The unit test is failing as "UnExpected Method Call execute" .Firstly Here is my application code:
class Filter {

Filter(FilterExecutor f) {
   filter = f;
}
static FilterExecutor filter;

void handle() {

   filter.execute(object);
}
//some logic here
};

class FilterExtension extends Filter {

FilterExtension(FilterExecutor f) {
   super(f);
}
void handle() {
   //some logic here
   super.handle();
}
}

Test cases :
class Tests {

FilterExecutor f;
@Override
public void Tests() {
  f=EasyMock.createMock(FilterExecutor.class);
}
@Test
public void test1 {

  EasyMock.expect(f.execute(object)).andReturn(Obj1);
  EasyMock.replay(f);
  FilterExtension test = new FilterExtension(f);
  test.handle();
  //Assert
}

@Test
public void test2 {

  //More or less similar to above
  EasyMock.expect(f.execute(object)).andReturn(Obj1);
  EasyMock.replay(f);
  FilterExtension test = new FilterExtension(f);
  test.handle();
}
}

If the above test cases are run individually then the tests are passing succssfully. If they are ran together then one of the test passes and other gives an assertion error ""UnExpected Method Call execute". And also if i add at the end of one test case "Filter.filter=null" then both the test cases are succeeding. Can somebody please explain me why this behavior is observed?

A: There are 2 problems I'm seeing here:

*

*The dependency is declared as static, but is then initialised in the constructors from a parameter.

*The object being passed to the execute(object) method is not being passed to the handle() method.

Problem 1 is a design issue ore than anything else. If you want to initialise the FilterExecutor each time you create a new Filter (or FilterExetnsion) then why not make it an instance variable? It's obviously inherently linked to a specific instance of the class, not the class itself.
Problem 2 is potentially a design issue, or could be about expectations within your tests. Within the method call test.handle() a call to filter.execute(object) is made. However, the object that is passed to execute is not provided by your test class. This means the object passed in filter.execute(object) is not the same object as you've told it to expect in EasyMock.expect(f.execute(object)).andReturn(Obj1);
There are two ways to solve this:

*

*A) Change your expectation to use a Capture.

*B) Change your handle method to take in the object, then provide that to the handle method call in you test.

For option A, See this good Stack Overflow post
I think the test methods would look a bit like this:
@Test
public void test1() {
    final Capture<Object> object = new Capture<Object>();
    EasyMock.expect(this.mockFilterExecutor.execute(EasyMock.capture(object))).andReturn(new Object());
    EasyMock.replay(this.mockFilterExecutor);
    final FilterExtension test = new FilterExtension(this.mockFilterExecutor);
    test.handle();

    final Object capturedObject = object.getValue();
    //Assert
}

For option B You could do something like the following, but obviously, this won't be viable if the object you provide to execute() can't be constructed or received from outside of the handle() method
Your handle method in the Filter class would look like this:
public void handle(final Object object) {
    this.filter.execute(object);
}

Your handle method in the FilterExtension class would look like this:
@Override
public void handle(final Object object) {
    super.handle(object);
}

And your test would look like this:
@Test
public void test1() {
    final Object object = new Object();
    EasyMock.expect(this.mockFilterExecutor.execute(object)).andReturn(object);
    EasyMock.replay(this.mockFilterExecutor);
    final FilterExtension test = new FilterExtension(this.mockFilterExecutor);
    test.handle(object);
    //Assert
}


text:
Q: Finding source of web performance issue We are trying to track down a performance issue on a asp.net solution on windows 2008.

*

*The error page that has no database access and very little logic takes 10 sec. Other pages over 70 seconds.

*Performance drops noticeably only at high load

*total memory usage is low 5 GB of 16 available

*W3wp.exe using 2.5 GB

*several Connection_Dropped DefaultAppPool in the httperr file

*ca. 1500 connections, Asp.net queue length is 10000

*CPU usage is low

Anyone have an idea what I could check next?
Edit
I have now used VS 2010 to run a performance test against it in a test virtual server.
I ran 200 users with a stepped build up and no wait time.
The interesting thing was that the page time continued to increase even after the max number of users was reached. There did not appear to be any memory leaks, memory usage is flat. Time taken per page goes from 0.1 to 30.0 seconds.
All pages increase, the one that increases most is a get of the login page, no database access just a forms auth check to see if the user is logged in.

A: Upon reading your numbers (always answering too fast, am I?) I agree that you should probably profile the server-side first. See What Are Some Good .NET Profilers?

I suggest you use

*

*google chrome

It has excellent profiling tools (under developer tools, Ctrl-Shift-I on my installation). I peruse

*

*network

*profiles

*timeline

charts for the information.
Also, there is the more highlevel Y-Slow extension to Firefox. It is developed/used by yahoo and gives some rather to the point advice out of the box.
If you prefer Firefox, the Firebug extension comes pretty close to the Google developer tools

A: Ah. Wha about you just look it up?
Attach a profiler, make a profiling run, find out where the CPU spends itÄs time.
There are plenty of profilers around that offer 14 day free trials.
I wouldsay ou need more CPU - find out why ;)


text:
Q: ArrayList Selection Sort I am trying to do a selection sort with the years on an ArrayList of movies, and with this code, I get the years in the right descending order, but the titles and studio names do not correspond with the year in the output. How can I get the titles, studio names, and years to be together?
ArrayList:
ArrayList<Movie3> myMovies = new ArrayList<Movie3>();
myMovies.add(new Movie3("The Muppets Take Manhattan", 2001, "Columbia Tristar"));
myMovies.add(new Movie3("Mulan Special Edition", 2004, "Disney"));
myMovies.add(new Movie3("Shrek 2", 2004, "Dreamworks"));
myMovies.add(new Movie3("The Incredibles", 2004, "Pixar"));
myMovies.add(new Movie3("Nanny McPhee", 2006, "Universal"));
myMovies.add(new Movie3("The Curse of the Were-Rabbit", 2006, "Aardman"));
myMovies.add(new Movie3("Ice Age", 2002, "20th Century Fox"));
myMovies.add(new Movie3("Lilo & Stitch", 2002, "Disney"));
myMovies.add(new Movie3("Robots", 2005, "20th Century Fox"));
myMovies.add(new Movie3("Monsters Inc.", 2001, "Pixar"));

Sorting:
    int i, k, posmin;
    int temp;
    for (i = b.size()-1; i >= 0; i--) {
        posmin = 0;
        for (k=0; k <= i; k++) {
            if (b.get(k).getYear() <= b.get(posmin).getYear()) posmin = k;
        }
        temp = b.get(i).getYear();
        b.get(i).setTitle(b.get(posmin).getTitle());
        b.get(i).setYear(b.get(posmin).getYear());
        b.get(i).setStudio(b.get(posmin).getStudio());

        b.get(posmin).setYear(temp);
    }

EDIT: This is the code I based it off of - it sorts the titles, and it works perfectly fine.
            int i, k, posmax;
            String temp;
            for (i = b.size()-1; i >= 0; i--) {
                posmax = 0;
                for (k=0; k <= i; k++) {
                    if (b.get(k).getTitle().compareTo(b.get(posmax).getTitle()) < 0) posmax = k;
                }
                temp = b.get(i).getTitle();
                b.get(i).setTitle(b.get(posmax).getTitle());
                b.get(i).setYear(b.get(posmax).getYear());
                b.get(i).setStudio(b.get(posmax).getStudio());

                b.get(posmax).setTitle(temp);
            }

A: Quick fix: You need to swap all data in the Object, not only the year.
For example, when the 2nd round in your sorting algorithm, you will result in swapping Movie3("The Muppets Take Manhattan", 2001, "Columbia Tristar") and new Movie3("Robots", 2005, "20th Century Fox"). Because you only swap the years (set all data to the last but only set year back to the unordered list), so it will end with Movie3("The Muppets Take Manhattan", 2005, "Columbia Tristar") and Movie3("The Muppets Take Manhattan", 2001, "Columbia Tristar"). Therefore, your Robots movie is disappeared.
Better solution: You can swap the reference instead of set all data in the Object.
Since there are references stored in the ArrayList, you can just swap those references to swap them.
Movie3 tmp = b.get(i);
b.set(i, b.get(posmin));
b.set(posmin, tmp);

It would be better in this case.

A: If you want the whole triple to be sorted, you have to save the values for "title" and "studio" too and not only the one for "year" - otherwise these values are lost.
You can achieve that by creating two more temporary variables (in the example below: tempTitle and tempStudio).
Notice, that I renamed your "temp" into "tempYear for a better overview.
int i, k, posmin;
    int tempYear;
    String tempTitle, tempStudio;
    for (i = b.size()-1; i >= 0; i--) {
        posmin = 0;
        for (k=0; k <= i; k++) {
            if (b.get(k).getYear() <= b.get(posmin).getYear()) posmin = k;
        }
        tempYear = b.get(i).getYear();
        tempTitle = b.get(i).getTitle();
        tempStudio = b.get(i).getStudio();

        b.get(i).setYear(b.get(posmin).getYear());
        b.get(posmin).setYear(tempYear);

        b.get(i).setTitle(b.get(posmin).getTitle());
        b.get(posmin).setTitle(tempTitle);

        b.get(i).setStudio(b.get(posmin).getStudio());
        b.get(posmin).setStudio(tempStudio);

    }

A: A much better way of doing this would be to create a comparator and pass it to the Collections.sort(..) function.
Say, your Movie3 looks something like this.
public static class Movie3 {
    public Movie3(String title, int year, String studio) {
        this.title = title;
        this.year = year;
        this.studio = studio;
    }

    public String toString() {
        return title + " (" + year + ") [" + studio + "]";
    }

    String title;
    int year;
    String studio;
}

This is how you could declare a comparator and pass it to the sort function. Run this on your current ArrayList with any changes you deem required.
Comparator<Movie3> comp = new Comparator<Movie3>() {
    @Override
    public int compare(Movie3 a, Movie3 b) {
        // compare names
        if(a.title.compareTo(b.title) != 0)
            return -1*(a.title.compareTo(b.title));

        // same name, compare years
        if(a.year < b.year)
            return 1;
        else if(a.year > b.year)
            return -1;

        // same name, year, compare studio
        return -1*(a.studio.compareTo(b.studio));
    }
};
List<Movie3> list = new ArrayList<Movie3>();
Collections.sort(list, comp);

For your myMovies list, this is what it should output:
[The Muppets Take Manhattan (2001) [Columbia Tristar], The Incredibles (2004) [Pixar], The Curse of the Were-Rabbit (2006) [Aardman], Shrek 2 (2004) [Dreamworks], Robots (2005) [20th Century Fox], Nanny McPhee (2006) [Universal], Mulan Special Edition (2004) [Disney], Monsters Inc. (2001) [Pixar], Lilo & Stitch (2002) [Disney], Ice Age (2002) [20th Century Fox]]


text:
Q: Is the future continuous correct here? "I'll be studying there for a year" Is the following sentence correct? Why it's not in the future simple form.

I'm going to London. I'll be studying there for a year.

Can anyone explain its grammar?


text:
Q: tkinter clear txt box before writing to it I have the following code which not working way i thought it would, but i am only beginner. can someone please explain how i can get the txt to clear before entering the next. at moment if i type hi i get right response but i want that to clear before get next response.
import tkinter

def show_data():
    txtBox = ent.get()

    if txtBox == ("hi" or "hello"):
        txt.delete(0.0, END)
        txt.insert(0.0, sentense)
    elif txtBox == ("i am good"):
        txt.delete(0.0, END)
        txt.insert(0.0, sentense1)
    else:
        txt.delete(0.0, END)
        txt.insert(0.0, sentence3)

window = tkinter.Tk()
window.configure(background="#18e0d9")
window.title("Project One")
window.geometry("300x300")

sentense = ("Hi! How are you?")
sentense1 = ("I'm glad to hear it")
sentence3 = ("i dont understand")

photo = tkinter.PhotoImage(file = 'title.gif')

w = tkinter.Label(window, image=photo)

lblInst = tkinter.Label(window, text="HOW CAN I HELP YOU TODAY?",
fg="#383a39", bg="#18e0d9", font="bolder")

ent = tkinter.Entry(window, width=38)
btn = tkinter.Button(window, text="submit", fg="#ffffff", bg="#383a39", command=show_data)
txt = tkinter.Text(window, width=29, height=6, bg="#18e0d9")

txt.pack(side="bottom", pady=15)
w.pack()
lblInst.pack(pady=5)
ent.pack(pady=5)
btn.pack(pady=5)

window.mainloop()

A: Use the syntax correctly as in:
text = tkinter.Text()
text.insert('1.0', 'template') # add template from the start point
text.delete('1.0', 'end') # delete from start to end, entirely


text:
Q: UEFI Installation Ubuntu Unavailable. I have an AlienWare 15 R3.
I made a Ubuntu installation media using Universal USB installer.
For some reason I can't get the option to install Ubuntu/Kubuntu in UEFI mode in boot list although legacy option is available .
I have windows installed in UEFI and want Linux to work in UEFI side by side.
Here is what I have tried so far.

*

*Disabling secure boot.

*Switching partition type of media from NTFS to FAT32

*Disable and Enable Legacy Support when bios is on UEFI mode.

Anyone have any idea how to fix this?

A: To boot in EFI mode, an external boot medium needs to have an EFI-mode boot loader (EFI/BOOT/bootx64.efi) on a filesystem that the firmware can read. The symptoms you describe are consistent with this not being the case. Two causes are common:

*

*No EFI boot files -- Some programs for creating bootable USB media from Ubuntu's .iso files omit the EFI-mode boot loader entirely, or put the EFI boot loader in a non-standard location. This is true of Pen Drive Linux (aka YUMI and one or two other names), for instance. Others require that particular options be set before they'll create EFI-bootable media. See my notes on a few programs for more details.

*Quirky incompatibilities -- Sometimes a boot medium works fine on one computer but not on another. This can be because there's something odd about the boot medium that's fine with some computers but not with others or because of a bug in the firmware.

In both cases, the solution usually involves creating the boot medium with another tool, although sometimes adjusting options in the tool you're using may do the trick. As you mentioned NTFS and FAT, be aware that all EFIs support FAT boot media, but I have yet to encounter one that supports NTFS. (I've seen a small number of posts that claim NTFS support in particular computers, but I have yet to see evidence backing up these claims.) Thus, you should stick with FAT, if the tool gives you an option. (Furthermore, FAT32 is more reliable on some older computers than is FAT16 or FAT12, so using FAT32 may be helpful.)
Based on my own experience and online reports, Rufus is one of the more reliable and flexible tools for this task, but the last I checked it was Windows-only. In Ubuntu, dd seems to be pretty reliable, although some computers dislike the Frankenstein's Monster format that a dd copy of the .iso file to a USB flash drive creates, so in some cases you may need to use something else.

A: Try using gparted and once the app is open select device and select gpt instead of mbr.  GPT only works with UEFI and mbr works with BIOS.
Then, create your partitions.  Gparted will format NTFS is so desired.
BR,
Miriam


text:
Q: Post vote casts disappear after scrolling Steps to reproduce:

*

*Open any post and long tap on the score to view vote casts:

*Scroll page to hide score section from the screen completely:

*Scroll back and see that votes disappeared and only total score is displayed:

*

*App Version: 1.6.5.3

*Device: iPad Air 2 (Wi-Fi)

*OS Version: Version 10.3.1 (Build 14E304)


text:
Q: EmberJS Handelbars compiler not working I'm trying to compile a template myself in a Ember View. (which I know isn't the best solution). When I use the standard Handlebars.compile everything works ok, but I want to use the EmberJS helpers (e.g. linkTo), but for some strange reason this isn't working. Does somebody know what I'm doing wrong?
This is working fine:
var menuitem = Handlebars.compile("
{{label}}
");
this.menu.prepend( menuitem( {label:"Homepage"} ) );

This isn't:
var menuitem = Ember.Handlebars.compile("
{{label}}
");
this.menu.prepend( menuitem( {label:"Homepage"} ) );

A: Are you loading the full Handlebars library or just the runtime version of it. Usually Ember comes with just the handlebars-runtime.js. Make sure you have full version. Handlebars.Compile is not included in the runtime version.


text:
Q: response using httpwebrequest and uri problems I'm trying to test if a website is up or down and I ran into some problems.
First I know if I'm to test the status of the server it's possible to do it with a simple piece of code like:
If My.Computer.Network.Ping(TextBox1.Text) Then
        TextBox2.Text = "Online"
    Else
        TextBox2.Text = "Offline"
    End If

But i refuse to do so since Pings are not always a reliable method of determining if an external web server is up.
So i try to work this out using this code:
Try
        Dim fr As System.Net.HttpWebRequest
        Dim targetURI As New Uri(TextBox1.Text)
        fr = DirectCast(System.Net.HttpWebRequest.Create(targetURI), System.Net.HttpWebRequest)
        If (fr.GetResponse().ContentLength > 0) Then
            TextBox2.Text = "Website appears to exist!"
        Else
            TextBox2.Text = "Website appears to have no content at all!"
        End If
    Catch ex As System.Net.WebException
        TextBox2.Text = "Cannot connect - website not responding!"

End Try

That code works. But the problem is if I type http://google.com in the TextBox1 and try to get server status then sometimes it shows up as "Website appears to have no content at all!" even when http://google.com is online and have contents. Not just for google but for other sites as well.
I have two question regarding this code.

*

*Why does it tells me that "Website appears to have no content at all!" even when http://google.com or any other site is online and have contents?

*Suppose i type in just google.com or any site without http:// or https:// in TextBox1 it gives me an error saying invalid URI format. Is there anyway I could automatically add http:// or https:// to the beginning of the url entered in TextBox1?
I know I can add this to the above code to do that:
Dim baseAddressx As String = "http://"
Dim targetURI As New Uri(baseAddressx & TextBox1.Text)

but what if I type http://google.com when the code it self adds http:// that will make a problem. Any better way to achieve that?

A: What I think you should do is that you should read the Status Code of the response, not the content length. It can be read as follows:
HttpWebResponse res = (HttpWebResponse)fr.GetResponse();
int statusCode = (int)response.StatusCode
if(statusCode == 200)
//Website is up else.
You may create enums to have a good understanding of it. And respond in various ways to the user based on which value you get.
Hope that helps.
Sorry I am no expert in VB. I know C#, I hope you can convert this to VB easily. See here.


text:
Q: How does OCaml manage float addition? In Java, if you do 0.2 + 0.01, you will get 0.21000000000000002
This is due to IEEE 754.
However, in OCaml, if you do 0.2 +. 0.01, then you get the correct result 0.21.
I think OCaml also obeys IEEE 754 for floats, why OCaml can give correct result while Java cannot?

A: OCaml, for the type that it calls float, uses the double type of the underlying C/Unix platform, which is usually defined by that platform as IEEE 754's binary64 format.
In OCaml, the conversion to decimal is done in the old-fashioned way, with a fixed number of digits (camlspotter has already dug up the format, which is %.12g, with the same meaning in OCaml that this format has in C).
Among modern languages (Java, Javascript, Ruby), the fashion is to convert to decimal by emitting exactly as many digits required for the decimal representation to convert back to the original floating-point number if converted back in the other direction. So in Java 0.21 is printed for and only for the double nearest to 0.21, which is not the rational 21/100 as this number is not exactly representable as a binary floating-point number.
One method is not better than the other. They both have surprising side-effects for the unwarned developer. In particular, the Java conversion method has lead to many "Why does the value of my float change when I convert it to double?" questions on StackOverflow (Answer: it doesn't, but (double)0.1f is printed with many additional digits after 0.100000 because the type double contains more values than float).
Anyway, both OCaml and Java compute the same floating-point number for 0.2 + 0.01, because they both closely follow IEEE 754. They just print them differently. OCaml prints a fixed number of digits that does not go far enough to show that the number is neither 21/100 nor the double-precision floating-point representation closest to 21/100. Java prints enough digits to show that the number is not the closest to 21/100.

A: I guess you looked that by printing the floating point number, but except if you use a lossless representation like this one never rely on that to infer properties of your floating point calculations. Rather do:
# 0.21 = 0.2 +. 0.01;;
- : bool = false
# 0.21000000000000002 = 0.2 +. 0.01;;
- : bool = true

A: Which one is "correct" in this case? From the view of the floating point arithmetics, Java is correct here. Anyway,
The values in OCaml toplevel is printed by genprintval.ml and there float values are printed by print_float, which uses string_of_float. Its definition is in pervasives.ml:
let string_of_float f = valid_float_lexem (format_float "%.12g" f)

As you see here the floats are printed using the printf format "%.12g". Things smaller than 10^{-12} are simply discarded. That's why you see the "incorrect" answer 0.21. If you upsize the precision, you have the same output as Java:
# Printf.sprintf "%.20g" (0.2 +. 0.01);;
- : string = "0.21000000000000002"


text:
Q: HTTPS switches to HTTP I login to a webpage using http:// I get redirected by javascript to  https://. This opens a login page under https.  After logging on successfully the next page is in http again. Why didn't the next page open with https as well. I am using JETTY as web server.

A: Are you posting your login form to http://mysite.com/login.php?
If so, I'd recommend using a relative link (e.g. <form action="login.php" method="POST">)

A: Encryption is usually only used when transferring sensitive data such as usernames and passwords (or your online bank account).
For an otherwise public website like StackOverflow it's impractical to use HTTPS for anything other than the login credentials because if every logged in user at StackOverflow would use HTTPS for every page-view the site could be too expensive to run because encryption is resource heavy which means it would require more hardware.
The server-side software could work something like this at the login page:

*

*User goes to login page http://mysite.com/login

*Login page is displayed. The HTML form points to https://mysite.com

*User types username/password and submits the form over an encrypted session

*User lands on "Login successful" page which redirects to the unencrypted http://mysite.com/

HTTP supports redirects in the header using the Location command:
Location: http://www.example.org/
Content-Type: text/html
Content-Length: 174

Hope this helps!


text:
Q: Webpack load different index file by default I am using webpack with HtmlWebpackPlugin plugin.
Let's say I have a file foo/index.js and if I import it as import { foo } from './foo' it works.
But I need to configure webpack such that if I have file foo/index.web.js and import { foo } from './foo' webpack should load index.web.js first.
Load order should be

*

*index.web.js

*index.js (if index.web.js not found)

A: This should be only a matter of adding .web.js as an extension in webpack resolve configuration before the .js
module.exports = {
  //...
  resolve: {
    extensions: ['.web.js', '.js', '.json'],
  },
};

https://webpack.js.org/configuration/resolve/
In fact create-react-app does this by default (with the .web.js)


text:
Q: Custom sort with custom ResultScriptWebPart I know in 2010 there was a way how to add custom sorting by Managed Property, it was obtaining data provider in overriden method and than just set the sort property and direction. However in 2013 I didnt find a way how to add custom sorting in code, i mean like inheriting the ResultsScriptWebPart. I found out event called BeforeserializeToContent which gives me DataProviderScriptWebPart and here Iam able to customize the query at least. So question is how to customize the sort order? Thanks.
P.S.: Not using querystring, thanks

A: so I found solution. There is property called DefaultAvailableSorts:ComplexResultSort[] and is marked as virtual, so just overriding it and providing custom array will do the job.


text:
Q: "A number of programs" vs. "several programs" I am always confused between "a number of programs" and "several programs" for saying "many programs". Google Ngrams show that both are widely used terms. Could someone tell me which one should be used when?

A: They both mean that more than one thing is involved, but...

*

*several indicates a small number: "more than a few; an indefinite small number". It falls somewhere between "a few" or "some", and "quite a few".

*a number of tends to imply more uncertainty, or at least flexibility, about the exact number involved. In other words, you see it in places where the count really does not matter:

Problems may be subdivided in any of a number of ways...
...suggested a number of ingenious ways that...

But if you put quite in front of it... "quite a number of" means that the count really does matter, and you are asserting that there are a lot.


text:
Q: execute php script upon new google voice text Right now, I have a working PHP script that will pull all my new Google voice texts to perform certain actions. Currently, I have to manually execute the PHP script via computer. More often than not, I am on the road and I need instant changes made to my site. I would like to know how to automatically execute the script as each new text comes in. The goal is to be able to text my Google voice account which will then update my site based on the particular codes I text.
I have thought about meta tag set interval or crontab, but rather than setting an interval of seconds/minutes, I would like to prevent unnecessary calls to the script. Could repeated requests to my Google Voice account flag anyone at Google?
Also, all of the texts can be forwarded to an email. Not sure is it would be easier to begin a script from an email client. If so, please advise.
Like I said the PHP script is already written and working. I just need help determining how to call the script only when a new text or email is received.
Cell -> Google Voice -> PHP -> Website

A: Gearman http://gearman.org/ could do the trick.
It has multy language API so you can just create a worker in php and every time job comes in gearman would call worker to do the job.

A: You can execute php scripts either using curl or running console commands using
php.net/manual/en/function.shell-exec.php
OR
php.net/manual/en/function.exec.php


text:
Q: Deserializando JSON em PHP Boa tarde, estou com algumas dúvidas no PHP. Tenho um arquivo PHP responsável apenas por apresentar um CPF no formato JSON, e com outro arquivo estou tentando consumir esses dados para apresentar na tela.
Arquivo de consumo cpf.php apresenta os dados dessa forma:
[{"id":"1","cpf":"098712321321","score":"400",]

Estou tentando fazer um foreach nesse JSON para imprimir os dados mas está dando um erro.
Arquivo de consulta,serasaService.php:

    <title>Api</title>

    <?php
    $json_file = file_get_contents("http://localhost/motora-proj/cpf.php");
    $json_str = json_decode($json_file, true);
    ?>

                <?php
                foreach ($json_str as $e => $key) {
                    ?>
                    <?php echo $e; ?>
                <?php
                }
                ?>

                <?php
                foreach ($json_str as $e => $key) {
                    ?>
                    <?php echo $key; ?>
                <?php
                }
                ?>

Erro que está sendo apresentado:

Warning: Invalid argument supplied for foreach() in
/opt/lampp/htdocs/motora-proj/serasaService.php on line 17
Warning: Invalid argument supplied for foreach() in
/opt/lampp/htdocs/motora-proj/serasaService.php on line 28

Podem me ajudar por gentileza? Obrigado!

A: O formato desse JSON está errado, deveria ser assim:
{"id":"1","cpf":"09871204922","score":"400"}

como ele está com o formato errado, o json_decode está retornando NULL, é importante fazer um tratamento de erros antes do foreach, como está usando php, pode usar o is_array() em uma condicional antes do foreach

    <title>Api</title>

    <?php
      $json_file  = file_get_contents( 'http://localhost/motora-proj/cpf.php' );
      $json_str   = json_decode( $json_file, true );
    ?>

    <?php if ( is_array( $json_str ) || is_object( $json_str ) ): ?>

          <?php foreach ( $json_str as $e => $key ): ?>
            <?php echo $e; ?>
          <?php endforeach; ?>

          <?php foreach ( $json_str as $e => $key ): ?>
            <?php echo $key; ?>
          <?php endforeach; ?>

    <?php else: ?>

    <?php endif ?>

A: Seu JSON está mal formado e são duas as possibilidades de reparo para ele.
1 - [{"id":"1","cpf":"09871204922","score":"400"}]
2 - {"id":"1","cpf":"09871204922","score":"400"}
No primeiro caso o JSON representa uma array cujo os elementos são objetos.
No segundo caso o JSON representa apenas um objeto.
Para cada um dos casos é necessário uma abordagem diferente.
Primeiro caso:
Para responder vou simplificar o seu código removendo as tags de HTML, mantendo o código em PHP com uma diferença o JSON vai ser colocado inline e impresso:
<?php
    $json_file = '[{"id":"1","cpf":"09871204922","score":"400"}]';
    $json_str = json_decode($json_file, true);
    print_r($json_str);
?>

resultando em:
Array
(
    [0] => Array
        (
            [id] => 1
            [cpf] => 09871204922
            [score] => 400
        )

)

Significando que objeto decodificado é uma array cujo o primeiro elemento também é um array. Nesse caso deve-se iterar pelo array mais externo para buscar as chaves e valores do elemento interno:
<?php
    //Aumentado a complexidade do JSON
    $json_file = '[{"id":"1","cpf":"09871204922","score":"400"},{"id":"2","cpf":"09848269111","score":"250"}]';
    $json_str = json_decode($json_file, true);
    foreach($json_str as $item){
      foreach ($item as $key => $value) {
        echo $key . " ". $value . PHP_EOL;
      }
    }
?>

Que vai resultar em:
id 1
cpf 09871204922
score 400
id 2
cpf 09848269111
score 250

Fazendo o reparo do seu código para o primeiro caso:

    <title>Api</title>

    <?php
    $json_file = '[{"id":"1","cpf":"09871204922","score":"400"},{"id":"2","cpf":"09848269111","score":"250"}]';
    //file_get_contents("http://localhost/motora-proj/cpf.php");
    $json_str = json_decode($json_file, true);
    ?>

                <?php
                  foreach ($json_str[0] as $e => $key) {
                    ?>
                    <?php echo $e; ?>
                <?php
                }
                ?>

                <?php
                foreach($json_str as $item){
                  ?>

                <?php foreach ($item as $e => $key) {
                    ?>
                    <?php echo $key; ?>
                <?php
                }
                ?>
<?php
                }
                ?>

Irá resultar em:

    <title>Api</title>

                                    id
                                    cpf
                                    score

                                    1
                                    09871204922
                                    400

                                    2
                                    09848269111
                                    250

Segundo caso:
No segundo caso o JSON representa apenas um objeto sendo mais fácil iterar sobre suas propriedades bastando iterar diretamente sobre o objeto:
<?php
    $json_file = '{"id":"1","cpf":"09871204922","score":"400"}';
    $json_str = json_decode($json_file, true);
    print_r($json_str);
?>

Resultando em:
Array
(
    [id] => 1
    [cpf] => 09871204922
    [score] => 400
)

Bastando iterar diretamente sobre o objeto:
<?php
    //Nesse caso não tem como aumentar a complexidade do objeto sem refatorar o código
    $json_file = '{"id":"1","cpf":"09871204922","score":"400"}';
    $json_str = json_decode($json_file, true);
    foreach ($json_str as $key => $value) {
      echo $key . " ". $value . PHP_EOL;
    }
?>

Resultado em:
id 1
cpf 09871204922
score 400

Fazendo o reparo para esse segundo caso ao código da pergunta:

    <title>Api</title>

    <?php
    $json_file = '{"id":"1","cpf":"09871204922","score":"400"}';
    //file_get_contents("http://localhost/motora-proj/cpf.php");
    $json_str = json_decode($json_file, true);
    ?>

                <?php
                foreach ($json_str as $e => $key) {
                    ?>
                    <?php echo $e; ?>
                <?php
                }
                ?>

                <?php
                foreach ($json_str as $e => $key) {
                    ?>
                    <?php echo $key; ?>
                <?php
                }
                ?>

Que irá resultar em:

    <title>Api</title>

                                    id
                                    cpf
                                    score

                                    1
                                    09871204922
                                    400


text:
Q: Value not being stored in realtime database firebase I was creating a signup page in android studio and connected it to firebase but the problem is it doesn't show me the password in   Realtime database when I sign up(although the Email gets stored in authentication)
this is my signup code
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.example.deliveryapp.Models.Users;
import com.example.deliveryapp.databinding.ActivitySignUpBinding;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;

public class SignUp extends AppCompatActivity {
    ActivitySignUpBinding binding;
    private FirebaseAuth mAuth;
    FirebaseDatabase database;
    ProgressDialog progressdialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding=ActivitySignUpBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        mAuth = FirebaseAuth.getInstance();
        database=FirebaseDatabase.getInstance();
        progressdialog=new ProgressDialog(SignUp.this);
        progressdialog.setTitle("Creating Account");
        progressdialog.setMessage("pls wait while we create your account");
        binding.SignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressdialog.show();
                mAuth.createUserWithEmailAndPassword(binding.Email.getText().toString()
                        ,binding.Password.getText().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull  Task<AuthResult> task) {
                        progressdialog.dismiss();
                        if (task.isSuccessful()) {
                            Users user=new Users(binding.Username.getText().toString(),binding.Email.getText().toString(),binding.Password.getText().toString());
                            Toast.makeText(SignUp.this, "Account created", Toast.LENGTH_SHORT).show();
                            String id=task.getResult().getUser().getUid();
                            database.getReference().child("Users").child(id).setValue(user);
                        }
                        else {
                            Toast.makeText(SignUp.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                        }

                    }
                });
            }
        });

    }
}

and the users class is this
public Users(String username, String mail, String password) {
        this.Username = username;
        this.mail = mail;
        this.Password = password;
    }

and these are my dependencies
dependencies {

    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'com.google.firebase:firebase-auth:21.0.1'
    implementation 'com.google.firebase:firebase-database:20.0.0'
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    implementation platform('com.google.firebase:firebase-bom:28.1.0')
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.android.gms:play-services-location:18.0.0'

}

My app runs normally without any error being thrown in logcat