VN:F [1.9.22_1171]
Rating: 9.3/10 (9 votes cast)

Random snippets of all sorts of code, mixed with a selection of help and advice.

How to avoid collision with the border or with each other by changing the heading i.e. rotate the object

5 Apr 2020, 8:55 am | Recent Questions - Stack Overflow

  • The task is actually, two cars moving, the cars must be able to avoidcollision with the border or with each other by changing the heading for example: rotate the object. **

    I got an error for this getRadius()

    import;import;import javafx.animation.KeyFrame;import javafx.animation.Timeline;import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.geometry.Bounds;import javafx.scene.Scene;import javafx.scene.image.Image;import javafx.scene.image.ImageView;import javafx.scene.layout.Pane;import javafx.scene.paint.Color;//import javafx.scene.shape.Circle;import javafx.stage.Stage;import javafx.util.Duration;

    public class Car extends Application {

    //public static Image car;public static Pane canvas;@Overridepublic void start(final Stage primaryStage) throws FileNotFoundException {    canvas = new Pane();    final Scene scene = new Scene(canvas, 800, 600);    scene.setFill(Color.LIGHTGREEN);    primaryStage.setTitle("Car");    primaryStage.setScene(scene);;    //export image    Image car1 = new Image(new FileInputStream("src/car2.png"));    Image car2 = new Image(new FileInputStream("src/car1.png"));    ImageView c1 = new ImageView(car1);    ImageView c2 = new ImageView(car2);    c1.setFitHeight(100);//Resize image    c1.setFitWidth(100);    c1.relocate(100,100);    c2.setFitHeight(100);//Resize image    c2.setFitWidth(100);    c2.relocate(600,100);    c2.setImage(car2);    c2.setVisible(true);    //add to stage    canvas.getChildren().add(c1);    canvas.getChildren().add(c2);    final Timeline loop = new Timeline(new KeyFrame(Duration.millis(10), new EventHandler<ActionEvent>() {        double deltaX = 3;        double deltaY = 3;        @Override        public void handle(final ActionEvent t) {            c1.setLayoutX(c1.getLayoutX() + deltaX);            c1.setLayoutY(c1.getLayoutY() + deltaY);            c2.setLayoutX(c2.getLayoutX() + deltaX);            c2.setLayoutY(c2.getLayoutY() + deltaY);            final Bounds bounds = canvas.getBoundsInLocal();            final boolean atRightBorder = c1.getLayoutX() >= (bounds.getMaxX() - c1.getRadius());            final boolean atLeftBorder = c1.getLayoutX() <= (bounds.getMinX() + c1.getRadius());            final boolean atBottomBorder = c1.getLayoutY() >= (bounds.getMaxY() - c1.getRadius());            final boolean atTopBorder = c1.getLayoutY() <= (bounds.getMinY() + c1.getRadius());            if (atRightBorder || atLeftBorder) {                deltaX *= -1;            }            if (atBottomBorder || atTopBorder) {                deltaY *= -1;            }        }    }));    loop.setCycleCount(Timeline.INDEFINITE);;}/** * @param args the command line arguments */public static void main(String[] args) {    launch(args);}


How can I use Access control npm for RBAC when Role, Action, Resource fetched from mongodb collection?

5 Apr 2020, 8:55 am | Recent Questions - Stack Overflow

I'm using Access Control npm package Access Control npm. Is there any way I can fetch Role, Action & Resource from mongodb collection and use it with this access control npm?

If you see in the figure below, I have defined one role.js file using this access control npm and another side I'm passing readOwn (action), profile (resource) to this role.js using middleware, I just want these two attribute from MongoDB collection based on user role, by this way I can make dynamic RBAC. How can I use these two attribute from table to middleware route?

please see this image

Xcode editor all code is cleared if file is deleted, how to turn this off?

5 Apr 2020, 8:55 am | Recent Questions - Stack Overflow

Unlike any other editor I've used before, once a file that is being edited gets deleted, the editor window will be cleared and your progress is lost forever, no undo history etc.

How can one do a setting to turn this off ?

I've looked at preferences but nothing that is obvious came to light. Also googling doesn't seem to get any results.

please help me with python problem : IndentationError: expected an indented block

5 Apr 2020, 8:54 am | Recent Questions - Stack Overflow

I am trying to write a program that prints a parallelogram.

# the required mehtoddef repeatChar(numRepeats, outputChar):#this function outputs the output char numRepeats timesoutput=""for i in range(numRepeats):output=output+outputCharreturn outputdef main():print("This program will output a prallelogram.")side=int(input("How long do you want wach side to be? "))char=input("Please enter the character you want it to be made of: ")output=""#loop to output the top trianglefor i in range(1,side+1):output=output+repeatChar(i, char)+"\n"#loop to output the bottom trianglefor i in range(1,side+1):#appnds the empty space i times and then appends the charoutput=output+repeatChar(i," ")+repeatChar((side-i), char)+"\n"print(output)main()

Handle Socket io when client is getting offline

5 Apr 2020, 8:54 am | Recent Questions - Stack Overflow

I am building a chat app, i use react-native in my client and node js in my server- for the chat app i use

All works great except when i simulate situation when i didn't receive internet connection.

Way to reproduce:

  1. connect to socket in the server
  2. cancel data in my phone
  3. disconnect event will call
  4. and after every time i get the internet connection again i send init event, because i must after the client disconnected


  1. cancel data in my phone, call disconnect event

  2. after doing that again- my server called disconnect event twice,after close the connection and open it again its called disconnect event 3 times and etc...

Excepted result:

cancel data in my phone call disconnect event just once, no matter how much time i will cancel data in my phone and connect again.

import express from "express";import http from "http";import ioServer from "";const app = express();const server = http.createServer(app);const io = ioServer(server);  let users: any = {};  io.on("connection", (socket: any) => {    socket.on("init", (userId: string) => {      console.log("initizalizeeee");      socket.userId = userId;      users[userId] = socket;    });    socket.on("message", (user) => {        if(users[])[].id).emit("message", {            ...message          });        else {          remoteNotification(message,;        }      });    });    socket.on("disconnect", (reason) => {      console.log(reason)      console.log("discoonectttt");      users[socket.userId] = null;    });  });});server.listen(port, () => console.log(`app listening on port ${port}!`));

After 3 time i get-

discoonecttttping timeout5dfbhf42342389fdsc1bbfadiscoonecttttping timeoutundefineddiscoonecttttping timeoutundefined

I excepted -

    discoonectttt    ping timeout    5dfbhf42342389fdsc1bbfa

python histogram first and last data weird

5 Apr 2020, 8:54 am | Recent Questions - Stack Overflow

I'm trying to plot this graph in histogram but the graph is drawn not correct. I want the value to be centered on the xticks. I would like this to be done without using numpy nor pandas. How can I succeed?

res = [1,2,3,1,5,4,2,6,3,4,1,2,3,4,1,5,6,1,2,3,4,5] # range 1~6plt.figure(figsize=[4,4])plt.hist(x=res)plt.grid(axis='y', alpha=0.75)plt.xlabel('Value',fontsize=15)plt.ylabel('Frequency',fontsize=15)plt.xticks(fontsize=15)plt.yticks(fontsize=15)

enter image description here

express do not serving page, instead window browser show json

5 Apr 2020, 8:54 am | Recent Questions - Stack Overflow

I`m noobie programming. Currently i struggling to build some api to my buisness. Working with framework next.js and express backend, probably is not the best to use javascript on backend, but only in this language i can burn some code.

The href query in router triggering backend request to external api


const routeToPathSearchTermCat = () => {Router.push({pathname: "/kategoria/[searchTermCat]/[offset]",query: {searchTermCat: searchTermCat, offset: offset}},`/kategoria/${searchTermCat}/${offset}`)};

my folder sctructure:

--|pages--index.js--|[searchTermCat] (this is a folder)   --|[offset].js

my server.js:

server.get('/kategoria/:searchTermCat/:offset', async (request, response) => {const params = { searchTermCat: request.params.searchTermCat,                 offset: request.params.offset};const actualPage = "/kategoria"    try {    const url = `                  locale=pl_PL&search_parameters[words]=${request.params.searchTermCat}                 &search_parameters[limit]=${limit}&search_parameters[offset]=                 ${request.params.offset}`;           const fetchData = await fetch(url, {                             headers: {                                      "x-api-key": "XXXXXXXXXXXXXXXX",                                      "X-Product": "adobe-api/0.1.0",                                      "Content-Type": "application/json",                                      "Accept": "application/json"                                      }                                      });           const objectAdobeStock = await fetchData.json();                                    response.json(objectAdobeStock);                                    const totalObj = await objectAdobeStock.nb_results;                                    const adobeImages = await objectAdobeStock.files;  app.render(request, response, actualPage, params);} catch (error) {  console.log(error);}});

And last peace of code is [offset].js

Zdjateczka.getInitialProps = async ({request, query}) => {  const response = await fetch(                              `http://localhost:3000/kategoria/${query.searchTermCat}/${query.offset}`, {                              headers: {                                       "Content-Type": "application/json",                                       "Accept": "application/json"                                        }                                        });                  try {                      const json = await res.json();                                  return { total: json.nb_results, images: json.files, offset:                                           query.offset, searchTermCat: query.searchTermCa};                      } catch (error) {                        console.log(error)                                      }                      };export default withRouter(Zdjateczka);

Finally my window browser shows me json object: "{"nb_results":1758274,"files":[{"id":303624505,"title":"Closeup portrait of funny ginger cat wearing sunglasses isolated on light cyan. Copyspace.","width":7407,"height":4167,"creator_name":"mark_ka","creator_id":205209796,"thumbnail_url":"", ...", and page is not render at all.

What i am doing wrong?

Efficient way to store received data if no internet connection available and push it when connection available in Raspberry Pi using Python

5 Apr 2020, 8:54 am | Recent Questions - Stack Overflow

I'm trying to make gateway using Raspberry Pi which needs to push data periodically but some times internet connection lost. Is there a way to store received data and push it when connection available?

PHP (int) 5 == 4?; How to make floating point comparisons in PHP and cast them to integers as needed

5 Apr 2020, 8:54 am | Recent Questions - Stack Overflow

I have the task of calculating the number of units in a building based on a fee the building pays. There is a fixed portion which can be one of a set number of values plus a variable amount per unit. If I have the fee, I can subtract the fixed portion, divide by the variable portion, and if it's a whole number I know that's the number of units in the building. The problem is when I compare the outcome to see if it's a whole number, I get a bizarre result.

(40.73-11.03)/5.94 == 5

Given the $baseWaterCharge of 40.73 there are 5 units. When I round the result and compare it to the unrounded result, they aren't equal because it's a floating point comparison. I've learned more about it here but that doesn't explain the following.

When I run the same formula and comparison for the fee 123.89 the result comes back as true, which is inconsistent for floating point approximations. Is that the result of some astrological event and the cpu of my computer? (123.89-11.03)/5.94 == 19 and 19==19 but 5!==5?

From the link above I decided that if I subtract the difference between the rounded and unrounded result, and the absolute value of the difference was less than a tolerable amount, then it should equate to true which works but when I cast the result as an integer for my subsequent processing I get the answer is 4.

return (int)(($baseWaterCharge-$value)/$perUnit);// equals 4 when really (40.73-11.03)/5.94 == 5

var_dump(($baseWaterCharge-$value)/$perUnit); // float 5var_dump(round(($baseWaterCharge-$value)/$perUnit)); float 5var_dump(round(($baseWaterCharge-$value)/$perUnit) == ($baseWaterCharge-$value)/$perUnit); //FALSE????

Below is the complete code if someone has some idea why it's doing this.

$fixed = array(11.03, 27.59, 55.17, 88.28, 176.55, 275.86, 551.72, 882.75, 1268.96);$perUnit = 5.94;foreach($fixed as $value){    var_dump($baseWaterCharge);    var_dump($perUnit);    var_dump(($baseWaterCharge-$value)/$perUnit);    var_dump(round(($baseWaterCharge-$value)/$perUnit));    var_dump(round(($baseWaterCharge-$value)/$perUnit) == ($baseWaterCharge-$value)/$perUnit);    $delta = abs((($baseWaterCharge-$value)/$perUnit) - round(($baseWaterCharge-$value)/$perUnit));    var_dump($delta);    var_dump((int)(($baseWaterCharge-$value)/$perUnit));    if($delta<.000001){        return (int)(($baseWaterCharge-$value)/$perUnit);    }}

I know in PHP I can cast it as a string and use it like an integer, but I'm terribly curious to know. It's 4:50am where I am, and I haven't slept yet, so please excuse any typos or nonsensical portions.

How to compare Software Architecture and Building Architecture?

5 Apr 2020, 8:54 am | Recent Questions - Stack Overflow

Software architecture is often compared to the architectureof buildings as a conceptual analogy. What are the strongand weak points of that analogy? What is thecorrespondence in buildings to software architecturestructures and views? To patterns?

Recent Questions - Stack Overflow