How can I keep track of a variable in android app?

when user enter to the app he chose team 1 (Brazil)or team 2(Argentine) after that he chose yellow or red card then he chose a player after that in the first page it will show the player number and color of card.

enter image description here

My Question is How can keep track of the number of card and instead of showing player number I show how many either yellow or red card does team have .

CardActivity

public class CardActivity extends AppCompatActivity {

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

private void setCardData(int card) {
    SharedPreferences settings getApplicationContext().getSharedPreferences("MainThisApp", 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt("card", card);
    editor.apply();

    Intent intent = new Intent(this, Myapp.game.NumberActivity.class);
    startActivity(intent);
}

public void setRedCard(View view) {

    ((Variable) this.getApplication()).setSomeVariable("card_yellow");

    setCardData(0);
}

public void setYellowCard(View view) {

    ((Variable) this.getApplication()).setSomeVariable("card_red");

    setCardData(1);
}}

MainActivity

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SharedPreferences prefs = getApplicationContext().getSharedPreferences("MainThisApp", 0);
    int check = prefs.getInt("check", 0);

    String s = ((Variable) this.getApplication()).getSomeVariable();
    try{
        Integer number = Integer.valueOf(s);
        System.out.println(number);
    }
    catch (NumberFormatException ex){
        ex.printStackTrace();
    }

    if (check == 50) {
        TextView view = null;
        int country = prefs.getInt("country", -1);
        int card = prefs.getInt("card", -1);

        if (country == 0 & card == 0) {

            view = findViewById(R.id.textView4);
        }
        if (country == 0 & card == 1) {

            view = findViewById(R.id.textView3);
        }
        if (country == 1 & card == 0) {

            view = findViewById(R.id.textView2);

        }
        if (country == 1 & card == 1) {

            view = findViewById(R.id.textView);
        }
        view.setText(String.valueOf(prefs.getInt("number",1)));
    }

}

public void chooseBrasil(View view) {
    setCountryData(0);
}

private void setCountryData(int country) {
    SharedPreferences settings = getApplicationContext().getSharedPreferences("MainThisApp", 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt("country", country);
    editor.apply();
    Intent intent = new Intent(this, CardActivity.class);
    startActivity(intent);
}
public void chooseArgentine(View view) {
    setCountryData(1);
}

NumberActivity

public class NumberActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_number);
    }

private void setNumberData(int number) {
    SharedPreferences settings = getApplicationContext().getSharedPreferences("MainThisApp", 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putInt("number", number);
    editor.putInt("check", 50);
    editor.apply();
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);
}

public void setNumber1(View view) {
    setNumberData(1);
}

public void setNumber2(View view) {
    setNumberData(2);
}

public void setNumber3(View view) {
    setNumberData(3);
}

public void setNumber4(View view) {
    setNumberData(4);
}

public void setNumber5(View view) {
    setNumberData(5);
}

public void setNumber6(View view) {
    setNumberData(6);
}

public void setNumber7(View view) {
    setNumberData(7);
}

public void setNumber8(View view) {
    setNumberData(8);
}

Dark Mode Function

I created a dark mode function that allows me to use local storage to “save” the last selected preference the user chose by clicking on an icon even if they go to different pages within the site, refresh, close, etc. What I can’t figure out is how I can add an if statement so that the icon will also chance its “src” into a different png file when the “darkmode” is enabled and then switch back to another icon when it is disabled. If anyone could help me with this I would very much appreciate it.

let darkMode = localStorage.getItem('darkMode'); 

const darkModeToggle = document.querySelector('#dark-mode-toggle');

const enableDarkMode = () => {
  document.body.classList.add('darkmode');
  localStorage.setItem('darkMode', 'enabled');
}

const disableDarkMode = () => {
  document.body.classList.remove('darkmode');
  localStorage.setItem('darkMode', null);
}

if (darkMode === 'enabled') {
  enableDarkMode();
}


darkModeToggle.addEventListener('click', () => {
  darkMode = localStorage.getItem('darkMode');
  
  if (darkMode !== 'enabled') {
    enableDarkMode();

  } else {  
    disableDarkMode(); 
  }
});

const scrollBtn = document.getElementById("scroll_up")

    scrollBtn.addEventListener("click", () => {
        document.documentElement.scrollTop= 0;
    });

How to send data from popup.js to content.js in a Chrome Extension

I am making a chrome extension that will auto fill a input on a page (the outlook subject line in this case), and I need to somehow pass the message that I get from the input on popup.js (the extension), into the content.js so that I can update the DOM on that page.

GitHub repo here

popup.html

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="container">
        <input type="text" id="message" name="message" placeholder="Enter a message..." class="message-input">
        <input type="submit" value="Set new message" id="message-btn" class="message-btn">
    </div>
</body>
<script src="popup.js"></script>

</html>

popup.js

let messageInput = document.getElementsByClassName('message-input')[0];
let updateMessageBtn = document.getElementById('message-btn');

updateMessageBtn.addEventListener('click', async(messageInput) => {
        // Query tab
    let queryOptions = { active: true, currentWindow: true };
    let tabs = await chrome.tabs.query(queryOptions);

    // Open up connection
    const port = chrome.tabs.connect(tabs[0].id, {
        name: "uiOps",
    });

        port.postMessage({
            message: messageInput.value
        });

            port.onMessage.addListener(function(msg) {
        if (msg.exists) {
            alert('Exists');
        } else {
            alert("Doesn't exist");
        }
    })
});

content.js

chrome.runtime.onConnect.addListener(function (port) {
  port.onMessage.addListener(function (msg) {
    if (port.name === "uiOps") {
      const idToQuery = msg.message;
      if (idToQuery) {
        port.postMessage({
          exists: true,
        });
      } else {
        port.postMessage({
          exists: false,
        });
      }
    }
  });
});

manifest.json

{
    "name": "Email Autofiller",
    "description": "Automatically fill email subject lines!",
    "version": "1.0",
    "manifest_version": 3,
    "permissions": ["storage", "activeTab", "scripting"],
    "action": {
        "default_popup": "popup.html",
        "default_icon": {
        "16": "/images/get_started16.png",
      "32": "/images/get_started32.png",
      "48": "/images/get_started48.png",
      "128": "/images/get_started128.png"
    }
    },
      "icons": {
    "16": "/images/get_started16.png",
    "32": "/images/get_started32.png",
    "48": "/images/get_started48.png",
    "128": "/images/get_started128.png"
  }
}

I’ve tried a ton of different things, including trying to use localstorage, which didn’t work. I think I’m on the right track, but the Google Chrome Extension docs are confusing me a little. Any help is appreciated – thanks!

Get file extention using only file name in javascript

I am creating a discord bot (irrelevent) that sends images into the chat. The user can type out the name of the image without needing to type the file extention. The problem is that the bot doesn’t know what the file extention is so it will crash if the picture is a .jpg and the program was expecting a .png. Is there a way to make the program not require a file extention to open the file?

let image = imageName;
message.channel.send({ files: [`media/stickers/${imageName}.png`] });

Can I fetch data from a json that is in dropbox

The goal is to store json files on an external server. I’m going to fetch data and show in my react native app. The files won’t be adjusted often. It’s a static data.

The first thing that came to mind is to keep those json files on some file hosting. But I was trying to explore the option of doing the same thing with dropbox.

The get_metadata request https://api.dropboxapi.com/2/files/get_metadata only provides metadata (obviously).

get_preview also won’t give me what I need.

Is there a way to store json files in dropbox and read them with react native?

In general should routes be placed before or after middleware?

Oddly, when I moved my middleware in front of my routes, my routes stopped working. I got no error, on the client or the server.

My fetch() calls seemingly disappeared.

However when I put the routes before my middleware, the routes begin to work again.

I’m refactoring code and have no idea why this is happening.

// load middleware
const middleware = require(__dirname +'/middleware');
app.use(middleware.session.session);
...

// load routes
const routes = require(__dirname + '/routes');
app.use('/articles', routes.articles);
...

Heroku not finding endpoint with Express

So I created this local host app I am trying to deploy to Heroku with express and for some reason it works on localhost but not on the Heroku API, getting 502, if someone could help that would be awesome!

app.listen(process.env.PORT || 3000, () => console.log('listening at 3000'));
app.use(express.static('public'));
app.use(express.json({ limit: '5mb' }));
const database = new Datastore('database.db');
database.loadDatabase();
app.get('/api', (request, response) => {
database.find({}, (err, data) => {
if (err) {
  response.end();
  return;
}
response.json(data);
});
});

Wondering why this occurring to be honest, deployed many apps with the same setup and never had it happen like this. The package.json has all the proper NPM packages aswell

is there a way to filter this request with mongoose?

I need to make a query of all products but only with the category status in true,
The model of my products is something like this:

const ProductSchema = Schema({
name : {type: String},
category: {type: Schema.Types.ObjectId, ref: 'Category'}
})

Normally I would just make a query and then a filter for the products with category.status === true, but the thing is that I’m using pagination and due to the filter my page of 15 products ends up with fewer products than 15 obviously because of the filter, so I really don’t know if I can make the filter with a population in the query, maybe something like this:

const query = await Product.find().populate('category', 'name status')
.select(['-cost']).where('category.status')
.equals(true).skip(0).limit(15)

but sadly it doesnt work, is there a way to do it or should i give up?

Storing JSON objects in the postgreSQL using parameterized query

I am having problems with saving JSON objects in the database using parameterized queries. I am using postman to send this object on red.body
enter image description here

On my server side I havet his code:

queryController.createQuery = (req, res, next) => {
  const { info }= req.body;
  const sqlQuery = 'INSERT INTO test (info) VALUES ($1) RETURNING *';
  db.query(sqlQuery, info)
  .then(result => {
    console.log(result);
    if (result) res.locals.message = "Saved the query successfully";
    next();
  })
  .catch(err => {
    return next({
      log: `queryController.createQuery: ERROR: ${typeof err === 'object' ? JSON.stringify(err) : err}`,
      message: { err: 'Error occurred in queryController.createQuery. Check server log for more details.'},
    })
  })

Why is that I still get this error: enter image description here

throw new TypeError('Client was passed a null or undefined query')
      ^

TypeError: Client was passed a null or undefined query

Here is my table schema:

CREATE TABLE test (
    id serial NOT NULL PRIMARY KEY,
    info json NOT NULL
);

How do I format $1 correctly to get it accept it as JSON file. Thank you.

FastAPI rejecting POST request from javascript code but not from a 3rd party request application (insomnia)

When I use insomnia to send a post request I get a 200 code and everything works just fine, but when I send a fetch request through javascript, I get a 405 ‘method not allowed error’, even though I’ve allowed post requests from the server side.
(Server side code uses python).

Server side code

from pydantic import BaseModel
from typing import Optional
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = ["*"]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["POST", "GET"],
    allow_headers=["*"],
)

class data_format(BaseModel):                                                           
    comment_id : int
    username : str
    comment_body : Optional[str] = None

@app.post('/post/submit_post')
async def sumbit_post(somename_3: data_format):
    comment_id = somename_3.comment_id
    username = somename_3.username
    comment_body = somename_3.comment_body
    # add_table_data(comment_id, username, comment_body)                //Unrelated code
    return {
        'Response': 'Submission received',
        'Data' : somename_3
    }

JS code

var payload = {
    "comment_id" : 4,
    "username" : "yo mum",
    "comment_body": "go to sleep"
};
fetch("/post/submit_post",
{
    method: "POST",
    body: JSON.stringify(payload),

    headers: {
        'Content-Type': 'application/json'
    }
})
.then(function(res){ return res.json(); })
.then(function(data){ alert( JSON.stringify( data ) ) })

The error

enter image description here

What should I do to get around this error?
Thanks in advance.

Proxied Browser Requests with Cookies through a node server

What I am trying to achieve is displaying html content to a user from another server (external server That I do not own) that is normally accessed through a browser.

To get the right html to display to the user, cookies related to that server’s domain must be provided.

APPROACH 1:

Easiest approach I tried is using an iframe. And of course, I got the usual CSP error from the chrome console:

Refused to frame ‘{{URL}}’ because an ancestor violates the following Content Security Policy directive: “frame-ancestors ‘self’ {{ACCEPTED DOMAINS}}”.

APPROACH 2:

I made a local proxy server in node.js and tried to setup a proxied request in browser axios:

axios.get("{{URL to external server}}", { proxy: { host: "localhost", port: 5050 }});

I quickly realized that axios proxy is a node only feature per this issue.

CONCLUSION:

I can’t find a way to make a GET request to get html in a browser to a cookie protected and CSP protected server/domain. If I am able to display html in the first place, I can probably use the same system to show a login page to update the user’s cookies. Just a heads up I am using react / node.js.

If you know of a better approach that completely scraps away my code or uses a different technology, please share!

Thank you in advance.

How do i count a data that includes another data in sequelize?

So i was trying to get a record about car dealers who successfully sold a specific car, sorted from how much the dealer successfully sold that car so the dealer that successfully sold the most of that specific car will appear first. The problem is that in the end i also need to group the car id, which makes the counting innacurrate. Can anyone please help me solve this problem where i can just get the record without needing to group the car id as well?

Here is my code:

const data = await models.Car.findAll({
      paranoid: false,
      attributes: [[Sequelize.fn('COUNT', Sequelize.col('userId')), 'carsCount'], 'userId'],
      where: { brandId, groupModelId, status: 2 },
      include: [
        {
          model: models.User,
          as: 'user',
          required: true,
          duplicating: false,
          attributes: ['name', 'phone', 'email'],
          include: [
            {
              model: models.UserAddress,
              as: 'userAddress'
            }
          ]
        }
      ],
      group: ['userId', 'user.id'],
      offset,
      limit
    })

Thank you in advance and sorry if my English is not perfect

Handling django form views using ajax

I am looking for more elegant way to solve this problem. Say I have say two buttons x, y in main.html:

<input class= "btn-check", name = "options", id="x">
<label class="btn btn-lg btn-info", for="x">x</label>
    
<input class= "btn-check", name = "options", id="y">
<label class="btn btn-lg btn-success", for="y">y</label>

What I want to do is after the button is clicked, I will do something in python and so in django views I will create a view function for each of the buttons (my current implementation):

def funcX(request):
    booleanX = doSomethingforX()
    return JsonResponse({"success": booleanX})

def funcY(request):
    booleanY = doSomethingforY()
    return JsonResponse({"success": booleanY})

and the ajax calls would be:

$("[id='x']").on("click", function(e){
    e.preventDefault();
    
    $.ajax({
        type:"GET",
        url: "{% url 'funcX' %}",           
        success: function(response){
            if(response.success == true){
                //Do something
            }
        }       
    })
});

The ajax call will be the same for button Y.

Now, I was wondering if it is possible to do this with forms?
Say the html becomes:

<form method="POST", class="form-group", id="post-form">
    <input type="submit", value="x", class= "btn-check", name = "options", id="x">
    <label class="btn btn-lg btn-info", for="x">x</label>

    <input type="submit", value="y", class= "btn-check", name = "options", id="y">
    <label class="btn btn-lg btn-success", for="y">y</label>

</form>

Then in django views I have a view for the main.html. This way it saves a lot of views written in django.

def main(request):
    
    if request.method == "POST" and request.POST["options"] == "x":
        booleanX = doSomethingforX()
        return JsonResponse({"success": booleanX})
    
    if request.method == "POST" and request.POST["options"] == "y":
        booleanY = doSomethingforY()
        return JsonResponse({"success": booleanY)})
    return render(request, "main.html")

Now the problem is I don’t know how to write the ajax calls to receive from views and get the JsonResponse return for X and Y respectively…

Any ideas?