Collage | #SDK | This library allows you to create a random collage of cards.

 by   jcmore2 Java Updated: 10 months ago - Current License: No License

Download this library from

Build Applications

kandi X-RAY | Collage REVIEW AND RATINGS

This library allows you to create a random collage of cards.

kandi-support
Support

  • Collage has a low active ecosystem.
  • It has 131 star(s) with 27 fork(s).
  • It had no major release in the last 12 months.
  • On average issues are closed in 1388 days.
  • It has a neutral sentiment in the developer community.

quality kandi
Quality

  • Collage has 7 bugs (0 blocker, 0 critical, 4 major, 3 minor) and 486 code smells.

security
Security

  • Collage has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • Collage code analysis shows 0 unresolved vulnerabilities.
  • There are 2 security hotspots that need review.

license
License

  • Collage does not have a standard license declared.
  • Check the repository for any license declaration and review the terms closely.
  • Without a license, all rights are reserved, and you cannot use the library in your applications.

build
Reuse

  • Collage releases are not available. You will need to build from source code and install.
  • Collage has no build file. You will be need to create the build yourself to build the component from source.
  • Collage saves you 2692 person hours of effort in developing the same functionality from scratch.
  • It has 5837 lines of code, 63 functions and 116 files with 0 % test coverage
  • It has low code complexity. Code complexity directly impacts maintainability of the code.
Top functions reviewed by kandi - BETA

kandi has reviewed Collage and discovered the below as its top functions. This is intended to give you an instant insight into Collage implemented functionality, and help decide if they suit your requirements.

  • Handles a touch event .
  • Handle touch event .
  • Set current view context .
  • Initializes the CollapseView .
  • Refreshes the views .
  • Compute render offset .
  • Create a new collage view .
  • region View
  • Initialize the view .
  • Initialize the border paint .

Collage Key Features

This library allows you to create a random collage of cards.

Collage examples and code snippets

  • default
  • How can make white background of the picture with texts in C++
  • How to make a fabricJS canvas draggable horizontally on mobile?
  • how to bypass text captcha using selininum
  • Problem with using different onClick events in one button component
  • Flutter custom image collage
  • C menu problem with a validating loop (to many prints)
  • How to display diffrent images using if function after pressing a button
  • apply a custom function on grouped dataframe n rows at a time
  • Gatsby images from markdown posts not displaying from graphql query
  • Clion : Process finished with exit code 139

default

Add library to your build.gradle:

```java

	    compile 'com.jcmore2.collage:collage:1.0.0'

```

Add CollageView in your xml


```xml

        <com.jcmore2.collage.CollageView
            android:id="@+id/collage"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="10dip" >
        </com.jcmore2.collage.CollageView>

```


Get CollageView in your activity, create a list of images (Bitmaps, Drawables, Resources)
and call 'createCollage'

```java

		CollageView collage = (CollageView) findViewById(R.id.collage);

		List<Integer> listRes = new ArrayList<Integer>();
		listRes.add(R.drawable.img1);
		listRes.add(R.drawable.img2);
		listRes.add(R.drawable.img3);
		listRes.add(R.drawable.img4);

		collage.createCollageResources(listRes);

```


* You can set Collage fixed

```java

		collage.setFixedCollage(true);

```

* or dynamic (default)

```java

		collage.setFixedCollage(false);


```


Credits & Contact
-----------------

Collage was created by jcmore2@gmail.com


License
-------

Collage is available under the Apache License, Version 2.0.

How can make white background of the picture with texts in C++

import cv2
import numpy as np

def get_white_image(img, crops):
    image_sizey, image_sizex, c = img.shape
    white_image = np.zeros([image_sizey, image_sizex, 3], dtype=np.uint8)
    white_image.fill(255)
    for crop in crops:
        white_image[crop[0]:crop[1], crop[2]:crop[3]] = img[crop[0]:crop[1], crop[2]:crop[3]]
    return white_image


image = cv2.imread("baldo.jpg")
cv2.imshow("image", image)
crops = []
crops.append([35, 80, 70, 140])
crops.append([85, 95, 50, 160])
crops.append([115, 145, 50, 90])
crops.append([220, 240, 80, 125])
result = get_white_image(image, crops=crops)
cv2.imshow("result", result)
cv2.waitKey(0)

How to make a fabricJS canvas draggable horizontally on mobile?

$('canvas').css('touch-action', 'manipulation');
(function(){
  var defaultOnTouchStartHandler = fabric.Canvas.prototype._onTouchStart;
  fabric.util.object.extend(fabric.Canvas.prototype, {
    _onTouchStart: function(e) {
      var target = this.findTarget(e);
      // if allowTouchScrolling is enabled, no object was at the
      // the touch position and we're not in drawing mode, then
      // let the event skip the fabricjs canvas and do default
      // behavior
      if (this.allowTouchScrolling && !target && !this.isDrawingMode) {
        // returning here should allow the event to propagate and be handled
        // normally by the browser
        return;
      }
      // otherwise call the default behavior
      defaultOnTouchStartHandler.call(this, e);
    }
  });
})();

how to bypass text captcha using selininum

# Execute a script in the browser
browser.execute_script("""

// Set the value of the input to the value of the CAPTCHA text
document.querySelector("#txtInput").value = document.querySelector("#txtCaptcha").value

""")

Problem with using different onClick events in one button component

<AppButton onClick={()=> {
  changeButtonName && changeButtonName();
  changeCycle && changeCycle();
 }}>
  {text}
</AppButton>
-----------------------
export const Button = ({text, changeButtonName, changeCycle}) => {

  return (
    <AppButton onClick={changeButtonName || changeCycle}>
      {text}
    </AppButton>
  );
};
export const Button = ({text, changeButtonName, changeCycle}) => {

  return (
    <AppButton
        onClick={() => {
          changeButtonName && changeButtonName();
          changeCycle && changeCycle();
        }
    }>
      {text}
    </AppButton>
  );
};
-----------------------
export const Button = ({text, changeButtonName, changeCycle}) => {

  return (
    <AppButton onClick={changeButtonName || changeCycle}>
      {text}
    </AppButton>
  );
};
export const Button = ({text, changeButtonName, changeCycle}) => {

  return (
    <AppButton
        onClick={() => {
          changeButtonName && changeButtonName();
          changeCycle && changeCycle();
        }
    }>
      {text}
    </AppButton>
  );
};
-----------------------
export const Button = ({text, changeButtonName, changeCycle, changeTheme, changeDisplay})
export const Button = ({text, clickHandler}) => {

  return (
    <AppButton onClick={clickHandler}>
      {text}
    </AppButton>
  );
};
-----------------------
export const Button = ({text, changeButtonName, changeCycle, changeTheme, changeDisplay})
export const Button = ({text, clickHandler}) => {

  return (
    <AppButton onClick={clickHandler}>
      {text}
    </AppButton>
  );
};

Flutter custom image collage

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: HomePage(),
    ),
  );
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ClipPath(
          clipper: CustomClipperImage(),
          child: Image.asset('images/abstract.jpg'),
        ),
      ),
    );
  }
}

class CustomClipperImage extends CustomClipper<Path> {
  @override
  getClip(Size size) {
    return Path()
      ..moveTo(size.width / 1, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.width)
      ..close();
  }

  @override
  bool shouldReclip(CustomClipper oldClipper) {
    return false;
  }
}
import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: HomePage(),
    ),
  );
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width * .8;
    final height = width * .7;
    return Scaffold(
      body: Container(
        color: Colors.black54,
        child: Center(
          child: Stack(
            children: [
              CustomPaint(
                painter: MyPainter(),
                child: Container(width: width, height: height),
              ),
              ClipPath(
                clipper: CustomClipperImage(),
                child: Transform.scale(
                  scale: 3,
                  child: Image.asset('images/abstract.jpg',
                      width: width, height: height),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class CustomClipperImage extends CustomClipper<Path> {
  @override
  getClip(Size size) {
    return Path()
      ..moveTo(size.width, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.height)
      ..close();
  }

  @override
  bool shouldReclip(CustomClipper oldClipper) {
    return false;
  }
}

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final path = Path()
      ..moveTo(size.width, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.height)
      ..close();
    final paint = Paint()
      ..color = Colors.white
      ..strokeWidth = 8.0
      ..style = PaintingStyle.stroke;
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: HomePage(),
    ),
  );
}

class HomePage extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final _width = MediaQuery.of(context).size.width * .8;
    final _height = _width * .6;
    final _zoom = useState<double>(1.0);
    final _previousZoom = useState<double>(1.0);
    final _offset = useState<Offset>(Offset.zero);
    final _previousOffset = useState<Offset>(Offset.zero);
    final _startingFocalPoint = useState<Offset>(Offset.zero);
    return Scaffold(
      body: Container(
        color: Colors.black54,
        child: Center(
          child: GestureDetector(
            onScaleStart: (details) {
              _startingFocalPoint.value = details.localFocalPoint;
              _previousOffset.value = _offset.value;
              _previousZoom.value = _zoom.value;
            },
            onScaleUpdate: (details) {
              _zoom.value = _previousZoom.value * details.scale;
              final Offset normalizedOffset =
                  (_startingFocalPoint.value - _previousOffset.value) /
                      _previousZoom.value;
              _offset.value =
                  details.localFocalPoint - normalizedOffset * _zoom.value;
            },
            child: Stack(
              children: [
                CustomPaint(
                  painter: MyPainter(),
                  child: Container(width: _width, height: _height),
                ),
                ClipPath(
                  clipper: CustomClipperImage(),
                  child: Transform(
                    transform: Matrix4.identity()
                      ..translate(_offset.value.dx, _offset.value.dy)
                      ..scale(_zoom.value),
                    // ..rotateZ(_rotation.value),
                    child: Image.asset('images/milkyway.jpg',
                        width: _width, height: _height),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class CustomClipperImage extends CustomClipper<Path> {
  @override
  getClip(Size size) {
    return Path()
      ..moveTo(size.width, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.height)
      ..close();
  }

  @override
  bool shouldReclip(CustomClipper oldClipper) {
    return false;
  }
}

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final path = Path()
      ..moveTo(size.width, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.height)
      ..close();
    final paint = Paint()
      ..color = Colors.white
      ..strokeWidth = 8.0
      ..style = PaintingStyle.stroke;
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
-----------------------
import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: HomePage(),
    ),
  );
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ClipPath(
          clipper: CustomClipperImage(),
          child: Image.asset('images/abstract.jpg'),
        ),
      ),
    );
  }
}

class CustomClipperImage extends CustomClipper<Path> {
  @override
  getClip(Size size) {
    return Path()
      ..moveTo(size.width / 1, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.width)
      ..close();
  }

  @override
  bool shouldReclip(CustomClipper oldClipper) {
    return false;
  }
}
import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: HomePage(),
    ),
  );
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width * .8;
    final height = width * .7;
    return Scaffold(
      body: Container(
        color: Colors.black54,
        child: Center(
          child: Stack(
            children: [
              CustomPaint(
                painter: MyPainter(),
                child: Container(width: width, height: height),
              ),
              ClipPath(
                clipper: CustomClipperImage(),
                child: Transform.scale(
                  scale: 3,
                  child: Image.asset('images/abstract.jpg',
                      width: width, height: height),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class CustomClipperImage extends CustomClipper<Path> {
  @override
  getClip(Size size) {
    return Path()
      ..moveTo(size.width, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.height)
      ..close();
  }

  @override
  bool shouldReclip(CustomClipper oldClipper) {
    return false;
  }
}

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final path = Path()
      ..moveTo(size.width, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.height)
      ..close();
    final paint = Paint()
      ..color = Colors.white
      ..strokeWidth = 8.0
      ..style = PaintingStyle.stroke;
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: HomePage(),
    ),
  );
}

class HomePage extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final _width = MediaQuery.of(context).size.width * .8;
    final _height = _width * .6;
    final _zoom = useState<double>(1.0);
    final _previousZoom = useState<double>(1.0);
    final _offset = useState<Offset>(Offset.zero);
    final _previousOffset = useState<Offset>(Offset.zero);
    final _startingFocalPoint = useState<Offset>(Offset.zero);
    return Scaffold(
      body: Container(
        color: Colors.black54,
        child: Center(
          child: GestureDetector(
            onScaleStart: (details) {
              _startingFocalPoint.value = details.localFocalPoint;
              _previousOffset.value = _offset.value;
              _previousZoom.value = _zoom.value;
            },
            onScaleUpdate: (details) {
              _zoom.value = _previousZoom.value * details.scale;
              final Offset normalizedOffset =
                  (_startingFocalPoint.value - _previousOffset.value) /
                      _previousZoom.value;
              _offset.value =
                  details.localFocalPoint - normalizedOffset * _zoom.value;
            },
            child: Stack(
              children: [
                CustomPaint(
                  painter: MyPainter(),
                  child: Container(width: _width, height: _height),
                ),
                ClipPath(
                  clipper: CustomClipperImage(),
                  child: Transform(
                    transform: Matrix4.identity()
                      ..translate(_offset.value.dx, _offset.value.dy)
                      ..scale(_zoom.value),
                    // ..rotateZ(_rotation.value),
                    child: Image.asset('images/milkyway.jpg',
                        width: _width, height: _height),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class CustomClipperImage extends CustomClipper<Path> {
  @override
  getClip(Size size) {
    return Path()
      ..moveTo(size.width, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.height)
      ..close();
  }

  @override
  bool shouldReclip(CustomClipper oldClipper) {
    return false;
  }
}

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final path = Path()
      ..moveTo(size.width, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.height)
      ..close();
    final paint = Paint()
      ..color = Colors.white
      ..strokeWidth = 8.0
      ..style = PaintingStyle.stroke;
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
-----------------------
import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: HomePage(),
    ),
  );
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ClipPath(
          clipper: CustomClipperImage(),
          child: Image.asset('images/abstract.jpg'),
        ),
      ),
    );
  }
}

class CustomClipperImage extends CustomClipper<Path> {
  @override
  getClip(Size size) {
    return Path()
      ..moveTo(size.width / 1, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.width)
      ..close();
  }

  @override
  bool shouldReclip(CustomClipper oldClipper) {
    return false;
  }
}
import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: HomePage(),
    ),
  );
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width * .8;
    final height = width * .7;
    return Scaffold(
      body: Container(
        color: Colors.black54,
        child: Center(
          child: Stack(
            children: [
              CustomPaint(
                painter: MyPainter(),
                child: Container(width: width, height: height),
              ),
              ClipPath(
                clipper: CustomClipperImage(),
                child: Transform.scale(
                  scale: 3,
                  child: Image.asset('images/abstract.jpg',
                      width: width, height: height),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class CustomClipperImage extends CustomClipper<Path> {
  @override
  getClip(Size size) {
    return Path()
      ..moveTo(size.width, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.height)
      ..close();
  }

  @override
  bool shouldReclip(CustomClipper oldClipper) {
    return false;
  }
}

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final path = Path()
      ..moveTo(size.width, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.height)
      ..close();
    final paint = Paint()
      ..color = Colors.white
      ..strokeWidth = 8.0
      ..style = PaintingStyle.stroke;
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: HomePage(),
    ),
  );
}

class HomePage extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final _width = MediaQuery.of(context).size.width * .8;
    final _height = _width * .6;
    final _zoom = useState<double>(1.0);
    final _previousZoom = useState<double>(1.0);
    final _offset = useState<Offset>(Offset.zero);
    final _previousOffset = useState<Offset>(Offset.zero);
    final _startingFocalPoint = useState<Offset>(Offset.zero);
    return Scaffold(
      body: Container(
        color: Colors.black54,
        child: Center(
          child: GestureDetector(
            onScaleStart: (details) {
              _startingFocalPoint.value = details.localFocalPoint;
              _previousOffset.value = _offset.value;
              _previousZoom.value = _zoom.value;
            },
            onScaleUpdate: (details) {
              _zoom.value = _previousZoom.value * details.scale;
              final Offset normalizedOffset =
                  (_startingFocalPoint.value - _previousOffset.value) /
                      _previousZoom.value;
              _offset.value =
                  details.localFocalPoint - normalizedOffset * _zoom.value;
            },
            child: Stack(
              children: [
                CustomPaint(
                  painter: MyPainter(),
                  child: Container(width: _width, height: _height),
                ),
                ClipPath(
                  clipper: CustomClipperImage(),
                  child: Transform(
                    transform: Matrix4.identity()
                      ..translate(_offset.value.dx, _offset.value.dy)
                      ..scale(_zoom.value),
                    // ..rotateZ(_rotation.value),
                    child: Image.asset('images/milkyway.jpg',
                        width: _width, height: _height),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class CustomClipperImage extends CustomClipper<Path> {
  @override
  getClip(Size size) {
    return Path()
      ..moveTo(size.width, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.height)
      ..close();
  }

  @override
  bool shouldReclip(CustomClipper oldClipper) {
    return false;
  }
}

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final path = Path()
      ..moveTo(size.width, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.height)
      ..close();
    final paint = Paint()
      ..color = Colors.white
      ..strokeWidth = 8.0
      ..style = PaintingStyle.stroke;
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

C menu problem with a validating loop (to many prints)

int c;
while(( c = getchar()) != '\n' && c != EOF){}

How to display diffrent images using if function after pressing a button

document.getElementById('b').addEventListener('click', randomNumber);
document.getElementById('b').addEventListener('click', randomNumber);

function randomNumber() {
  let number = Math.floor((Math.random() * 6) + 1);

  if (number == 1) {
    document.getElementById('img1').src = "image/dice1.jpg";
  } else if (number == 2) {
    document.getElementById('img1').src = "image/dice2.jpg";
  } else if (number == 3) {
    document.getElementById("img1").src = "image/dice3.jpg"
  } else if (number == 4) {
    document.getElementById("img1").src = "image/dice4.jpg";
  } else if (number == 5) {
    document.getElementById("img1").src = "image/dice5.jpg";
  } else if (number == 6) {
    document.getElementById("img1").src = "image/dice6.jpg";
  }

}
<head>
  <title></title>

</head>

<body>
  <p id="number"> </p>
  <img id="img1"></img>
  <button id="b"> Yes </button>
  <button onclick="Num2button()">No</button>
</body>
-----------------------
document.getElementById('b').addEventListener('click', randomNumber);
document.getElementById('b').addEventListener('click', randomNumber);

function randomNumber() {
  let number = Math.floor((Math.random() * 6) + 1);

  if (number == 1) {
    document.getElementById('img1').src = "image/dice1.jpg";
  } else if (number == 2) {
    document.getElementById('img1').src = "image/dice2.jpg";
  } else if (number == 3) {
    document.getElementById("img1").src = "image/dice3.jpg"
  } else if (number == 4) {
    document.getElementById("img1").src = "image/dice4.jpg";
  } else if (number == 5) {
    document.getElementById("img1").src = "image/dice5.jpg";
  } else if (number == 6) {
    document.getElementById("img1").src = "image/dice6.jpg";
  }

}
<head>
  <title></title>

</head>

<body>
  <p id="number"> </p>
  <img id="img1"></img>
  <button id="b"> Yes </button>
  <button onclick="Num2button()">No</button>
</body>
-----------------------
document.getElementById('b').addEventListener('click', randomNumber);
document.getElementById('b').addEventListener('click', randomNumber);

function randomNumber() {
  let number = Math.floor((Math.random() * 6) + 1);

  if (number == 1) {
    document.getElementById('img1').src = "image/dice1.jpg";
  } else if (number == 2) {
    document.getElementById('img1').src = "image/dice2.jpg";
  } else if (number == 3) {
    document.getElementById("img1").src = "image/dice3.jpg"
  } else if (number == 4) {
    document.getElementById("img1").src = "image/dice4.jpg";
  } else if (number == 5) {
    document.getElementById("img1").src = "image/dice5.jpg";
  } else if (number == 6) {
    document.getElementById("img1").src = "image/dice6.jpg";
  }

}
<head>
  <title></title>

</head>

<body>
  <p id="number"> </p>
  <img id="img1"></img>
  <button id="b"> Yes </button>
  <button onclick="Num2button()">No</button>
</body>
-----------------------
let images = [
    'https://via.placeholder.com/10',
    'https://via.placeholder.com/20',
    'https://via.placeholder.com/30',
    'https://via.placeholder.com/40',
    'https://via.placeholder.com/50',
]

function setRandomImage() {
    let index = Math.floor(Math.random() * images.length);
    document.getElementById('img').src = images[index];
    document.getElementById('num').innerHTML = index + 1;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
var images = [
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
]
function setRandomImage() {
    let index = Math.floor(Math.random() * images.length) + 1;
    document.getElementById('img').src  = images[index - 1] + '/' + index + '0';
    document.getElementById('num').innerHTML = index;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
function setRandomImage() {
    let rand = Math.floor(Math.random() * 6) + 1;
    document.getElementById('img').src  = 'https://via.placeholder.com/' + rand + '0';
    document.getElementById('num').innerHTML = rand;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
-----------------------
let images = [
    'https://via.placeholder.com/10',
    'https://via.placeholder.com/20',
    'https://via.placeholder.com/30',
    'https://via.placeholder.com/40',
    'https://via.placeholder.com/50',
]

function setRandomImage() {
    let index = Math.floor(Math.random() * images.length);
    document.getElementById('img').src = images[index];
    document.getElementById('num').innerHTML = index + 1;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
var images = [
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
]
function setRandomImage() {
    let index = Math.floor(Math.random() * images.length) + 1;
    document.getElementById('img').src  = images[index - 1] + '/' + index + '0';
    document.getElementById('num').innerHTML = index;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
function setRandomImage() {
    let rand = Math.floor(Math.random() * 6) + 1;
    document.getElementById('img').src  = 'https://via.placeholder.com/' + rand + '0';
    document.getElementById('num').innerHTML = rand;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
-----------------------
let images = [
    'https://via.placeholder.com/10',
    'https://via.placeholder.com/20',
    'https://via.placeholder.com/30',
    'https://via.placeholder.com/40',
    'https://via.placeholder.com/50',
]

function setRandomImage() {
    let index = Math.floor(Math.random() * images.length);
    document.getElementById('img').src = images[index];
    document.getElementById('num').innerHTML = index + 1;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
var images = [
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
]
function setRandomImage() {
    let index = Math.floor(Math.random() * images.length) + 1;
    document.getElementById('img').src  = images[index - 1] + '/' + index + '0';
    document.getElementById('num').innerHTML = index;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
function setRandomImage() {
    let rand = Math.floor(Math.random() * 6) + 1;
    document.getElementById('img').src  = 'https://via.placeholder.com/' + rand + '0';
    document.getElementById('num').innerHTML = rand;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
-----------------------
let images = [
    'https://via.placeholder.com/10',
    'https://via.placeholder.com/20',
    'https://via.placeholder.com/30',
    'https://via.placeholder.com/40',
    'https://via.placeholder.com/50',
]

function setRandomImage() {
    let index = Math.floor(Math.random() * images.length);
    document.getElementById('img').src = images[index];
    document.getElementById('num').innerHTML = index + 1;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
var images = [
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
]
function setRandomImage() {
    let index = Math.floor(Math.random() * images.length) + 1;
    document.getElementById('img').src  = images[index - 1] + '/' + index + '0';
    document.getElementById('num').innerHTML = index;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
function setRandomImage() {
    let rand = Math.floor(Math.random() * 6) + 1;
    document.getElementById('img').src  = 'https://via.placeholder.com/' + rand + '0';
    document.getElementById('num').innerHTML = rand;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
-----------------------
let images = [
    'https://via.placeholder.com/10',
    'https://via.placeholder.com/20',
    'https://via.placeholder.com/30',
    'https://via.placeholder.com/40',
    'https://via.placeholder.com/50',
]

function setRandomImage() {
    let index = Math.floor(Math.random() * images.length);
    document.getElementById('img').src = images[index];
    document.getElementById('num').innerHTML = index + 1;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
var images = [
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
]
function setRandomImage() {
    let index = Math.floor(Math.random() * images.length) + 1;
    document.getElementById('img').src  = images[index - 1] + '/' + index + '0';
    document.getElementById('num').innerHTML = index;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
function setRandomImage() {
    let rand = Math.floor(Math.random() * 6) + 1;
    document.getElementById('img').src  = 'https://via.placeholder.com/' + rand + '0';
    document.getElementById('num').innerHTML = rand;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
-----------------------
let images = [
    'https://via.placeholder.com/10',
    'https://via.placeholder.com/20',
    'https://via.placeholder.com/30',
    'https://via.placeholder.com/40',
    'https://via.placeholder.com/50',
]

function setRandomImage() {
    let index = Math.floor(Math.random() * images.length);
    document.getElementById('img').src = images[index];
    document.getElementById('num').innerHTML = index + 1;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
var images = [
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
    'https://via.placeholder.com',
]
function setRandomImage() {
    let index = Math.floor(Math.random() * images.length) + 1;
    document.getElementById('img').src  = images[index - 1] + '/' + index + '0';
    document.getElementById('num').innerHTML = index;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>
function setRandomImage() {
    let rand = Math.floor(Math.random() * 6) + 1;
    document.getElementById('img').src  = 'https://via.placeholder.com/' + rand + '0';
    document.getElementById('num').innerHTML = rand;
}
<img id="img"></img>
<p id="num"></p>
<button onclick="setRandomImage()">Yes</button>
<button>No</button>

apply a custom function on grouped dataframe n rows at a time

library(dplyr)
library(purrr)
library(slider)

N <- 10

Collage <- function(country,strain,subgroupnumber,data) {
  cat(paste('Processing:',country,'-',strain,'/',subgroupnumber),'\n')
  cat(paste(nrow(data) , ' files to read \n'))
  cat(paste(data$png_file,collapse=' ; '),'\n')
  cat('\n')
}

res <- df %>% group_by(country,strain) %>% 
  group_walk(~{
    group <- .y
    subgroups <- slider::slide(.x,.f=~.x,.step = N ,.after = N-1)
    # Remove empty elements
    subgroups <- subgroups[lengths(subgroups) != 0]
    
    # Run wished function on each subgroup
    subgroups %>% iwalk(~{
      Collage(group[1],group[2],.y,.x)
  })

})

Processing: UK - Covid_123 / 1 
10  files to read 
A_UK_1_lp21_pmn1__1.png ; A_UK_1_xno9_pmn1__1.png ; A_UK_2.14.3_lp21_pmn1__1.png ; A_UK_2.14.3_xno9_pmn1__1.png ; A_UK_2.2_lp21_zn78__1.png ; A_UK_2.2_xno9_zn78__1.png ; A_UK_2.3_lp21_pmn1__1.png ; A_UK_2.3_xno9_pmn1__1.png ; A_UK_2.4_lp21_yun7__1.png ; A_UK_2.8.1_lp21_pmn1__1.png 

Processing: UK - Covid_123 / 2 
9  files to read 
A_UK_2.8.1_xno9_pmn1__1.png ; A_UK_2.8.2_lp21_pmn1__1.png ; A_UK_2.8.2_xno9_pmn1__1.png ; B_UK_2.1_lp21_pmn1__1.png ; B_UK_2.1_xno9_pmn1__1.png ; B_UK_2.14.1_lp21_pmn1__1.png ; B_UK_2.14.1_xno9_pmn1__1.png ; B_UK_2.14.2_lp21_pmn1__1.png ; B_UK_2.14.2_xno9_pmn1__1.png 

Processing: UK - Covid_125 / 1 
10  files to read 
A_UK_2.14.3_lp21_pmn1__1.png ; A_UK_2.14.3_xno9_pmn1__1.png ; A_UK_2.2_lp21_zn78__1.png ; A_UK_2.2_xno9_zn78__1.png ; A_UK_2.3_lp21_pmn1__1.png ; A_UK_2.3_xno9_pmn1__1.png ; A_UK_2.4_lp21_yun7__1.png ; A_UK_2.8.1_lp21_pmn1__1.png ; A_UK_2.8.1_xno9_pmn1__1.png ; A_UK_2.8.2_lp21_pmn1__1.png 

Processing: UK - Covid_125 / 2 
5  files to read 
A_UK_2.8.2_xno9_pmn1__1.png ; B_UK_2.14.1_lp21_pmn1__1.png ; B_UK_2.14.1_xno9_pmn1__1.png ; B_UK_2.14.2_lp21_pmn1__1.png ; B_UK_2.14.2_xno9_pmn1__1.png 

Processing: UK - Covid_127 / 1 
10  files to read 
A_UK_2.2_lp21_zn78__1.png ; A_UK_2.2_xno9_zn78__1.png ; A_UK_2.3_lp21_pmn1__1.png ; A_UK_2.3_xno9_pmn1__1.png ; A_UK_2.4_lp21_yun7__1.png ; A_UK_2.9.1_lp21_yun7__1.png ; B_UK_2.12.1_lp21_yun7__1.png ; B_UK_2.12.2_lp21_yun7__1.png ; B_UK_2.7.1_lp21_pmn1__1.png ; B_UK_2.7.1_xno9_pmn1__1.png 

Processing: UK - Covid_127 / 2 
7  files to read 
B_UK_2.7.4_lp21_yun7__1.png ; B_UK_2.9.2_lp21_yun7__1.png ; A_UK_2.4_lp21_yun7__1.png ; A_UK_2.5.4_lp21_pmn1__1.png ; A_UK_2.5.4_xno9_pmn1__1.png ; A_UK_2.6.4_lp21_yun7__1.png ; B_UK_2.5.3_lp21_yun7__1.png 

Processing: UK - Covid_128 / 1 
1  files to read 
A_UK_2.4_lp21_yun7__1.png 
              1

Gatsby images from markdown posts not displaying from graphql query

---
path: "/create-a-blog-with-react-and-sanity"
date: "2021-01-10"
title: "Create a blog with React and Sanity"
description: "Create a technical blog built with React, TailwindCSS, and Sanity then deploy it using Github and Netlify"
category: "React"
author: "Nikki Peel"
authorImage: /gatsby-blog/images/selfie.png
image: /gatsby-blog/images/sanity-blog-collage.jpg
---
---
path: "/create-a-blog-with-react-and-sanity"
date: "2021-01-10"
title: "Create a blog with React and Sanity"
description: "Create a technical blog built with React, TailwindCSS, and Sanity then deploy it using Github and Netlify"
category: "React"
author: "Nikki Peel"
authorImage: ../../images/selfie.png
image: ../../sanity-blog-collage.jpg
---
`gatsby-plugin-sharp`,
{
  resolve: `gatsby-transformer-remark`,
  options: {
    plugins: [
      {
        resolve: `gatsby-remark-images`,
        options: {
          maxWidth: 800,
        },
      },
    ],
  },
},
-----------------------
---
path: "/create-a-blog-with-react-and-sanity"
date: "2021-01-10"
title: "Create a blog with React and Sanity"
description: "Create a technical blog built with React, TailwindCSS, and Sanity then deploy it using Github and Netlify"
category: "React"
author: "Nikki Peel"
authorImage: /gatsby-blog/images/selfie.png
image: /gatsby-blog/images/sanity-blog-collage.jpg
---
---
path: "/create-a-blog-with-react-and-sanity"
date: "2021-01-10"
title: "Create a blog with React and Sanity"
description: "Create a technical blog built with React, TailwindCSS, and Sanity then deploy it using Github and Netlify"
category: "React"
author: "Nikki Peel"
authorImage: ../../images/selfie.png
image: ../../sanity-blog-collage.jpg
---
`gatsby-plugin-sharp`,
{
  resolve: `gatsby-transformer-remark`,
  options: {
    plugins: [
      {
        resolve: `gatsby-remark-images`,
        options: {
          maxWidth: 800,
        },
      },
    ],
  },
},
-----------------------
---
path: "/create-a-blog-with-react-and-sanity"
date: "2021-01-10"
title: "Create a blog with React and Sanity"
description: "Create a technical blog built with React, TailwindCSS, and Sanity then deploy it using Github and Netlify"
category: "React"
author: "Nikki Peel"
authorImage: /gatsby-blog/images/selfie.png
image: /gatsby-blog/images/sanity-blog-collage.jpg
---
---
path: "/create-a-blog-with-react-and-sanity"
date: "2021-01-10"
title: "Create a blog with React and Sanity"
description: "Create a technical blog built with React, TailwindCSS, and Sanity then deploy it using Github and Netlify"
category: "React"
author: "Nikki Peel"
authorImage: ../../images/selfie.png
image: ../../sanity-blog-collage.jpg
---
`gatsby-plugin-sharp`,
{
  resolve: `gatsby-transformer-remark`,
  options: {
    plugins: [
      {
        resolve: `gatsby-remark-images`,
        options: {
          maxWidth: 800,
        },
      },
    ],
  },
},
-----------------------
---
path: "/post-three"
date: "2020-11-23"
title: "My Third Gatsby Post"
description: "This is my third markdown post with gatsby"
category: "Tailwind"
author: "Nikki Peel"
authorImage: https://i.imgur.com/qyIekvV.png
image: https://i.imgur.com/lKnOCsT.jpg
---

Clion : Process finished with exit code 139

Tree *root;
void add(char c)
{
    root->data = c;
}
int main()
{
    cout<<2;
    add('a'); // <---
    return 0;
}
root = new Tree();
-----------------------
Tree *root;
void add(char c)
{
    root->data = c;
}
int main()
{
    cout<<2;
    add('a'); // <---
    return 0;
}
root = new Tree();

COMMUNITY DISCUSSIONS

Top Trending Discussions on Collage
  • why python show file not found error during run time?
  • c code to compare two binary files runs on windows but won't run on Linux
  • How can make white background of the picture with texts in C++
  • How to make a fabricJS canvas draggable horizontally on mobile?
  • how to bypass text captcha using selininum
  • Problem with using different onClick events in one button component
  • some data from nodejs is not inserting in mongodb?
  • Flutter custom image collage
  • C menu problem with a validating loop (to many prints)
  • How to display diffrent images using if function after pressing a button
Top Trending Discussions on Collage

QUESTION

why python show file not found error during run time?

Asked 2021-May-18 at 07:42

I am write a code for collage maker using python and place 2 picture in same folder in which code file exist but when I run a code this error shown: FileNotFoundError: [Errno 2] No such file or directory: 'background.jpg' and my line of code is:

img1 = Image.open("background.jpg")
img2 = Image.open('Awais.jpg')

My Question is how I handle this error?

ANSWER

Answered 2021-May-18 at 07:42

You would be getting this error because even though you have placed the code and the image in the same directory/folder , the path from where you're running the code matter as that's the working directory for the program.

The best here would be to either use absolute path or make use of os.path.dirname(__file__) and other utilities to fetch the directory where the code file is and use it to reference the image paths.

Source https://stackoverflow.com/questions/67581848

QUESTION

c code to compare two binary files runs on windows but won't run on Linux

Asked 2021-May-15 at 17:43

I wrote a c code on visual studio to compare binary file to search a know virus in other binary file.
the code is running on my windows PC perfectly however it won't compile on the Linux test of my collage.

the code receive a folder containing the files and the file of the virus


this is the code adjusted for Linux that i sent to the test

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#define SLASH "/"  

#define FIFTH 0.2
#define NORMAL '0'
#define PARAMS 3
#define MAX 200
#define WELCOME_MES "Welcome to my Virus Scan!\n\nFolder to scan: "
#define FLOG_WELCOME "Anti-virus began! Welcome!\n\nFolder to scan:\n"
#define COMP_MES "Scan Completed.\nSee log path for results: antiVirus_log.txt"
#define INF_LAST "INFECTED (LAST 20%%)"
#define INF_FIRST "INFECTED (FIRST 20%%)"
#define INF "INFECTED"

int search_virus(char word[], char virus[], char name[], int finish_point, int sigLen, int starting_point);
char welcome_op(char directory_name[], char virus_name[], FILE* log);
int is_directory(const char* path);
int fast_or_regular(FILE* file, FILE* virus, char name[], char option, FILE* log);


int main(int argc, char** argv)
{
    char full_path[MAX] = "";
    char option = ' '; 
    FILE* fLog = fopen("antiVirus_log.txt", "w");
    if (!fLog)
    {
        return 0;
    }
    FILE* virusSig = fopen(argv[2], "rb");// **** 2
    if (!virusSig)
    {
        return 0;
    }

    if (argc != PARAMS)
    {
        return 0;
    }
    
    struct dirent* struct_lab;
    DIR* ptr_lab = opendir(argv[1]);
    if (!ptr_lab)
    {
        printf("Couldn't open the directory!");
        return 0;
    }
    else
    {
        option = welcome_op(argv[1], argv[2], fLog);

        while ((struct_lab = readdir(ptr_lab)) != NULL)//enter dir
        {
            
            if (!is_directory(struct_lab->d_name))
            {
                strcpy(full_path, argv[1]);//add name of the direcotry
                strcat(full_path, SLASH);// add slash
                strcat(full_path, struct_lab->d_name);// add the file name

                FILE* check_file = fopen(full_path, "rb");// open
                if (check_file)
                {
                    fast_or_regular(check_file, virusSig, full_path, option, fLog);
                    fclose(check_file);
                }

            }

        }
        closedir(ptr_lab);
    }
    
    fclose(fLog);
    printf("%s", COMP_MES);
    fclose(virusSig);

    getchar();
    return(0);
}
/*
* prints the welcome message and ask the user to choose quick or normal scan
* input: directory_name: the name of the directory, virus name: virus file name, logL: writes the action there
* output: 0 if normal, anything else quick
*/
char welcome_op(char* directory_name, char* virus_name, FILE* log)
{
    char op = ' ';
    printf("%s%s\nVirus signature: %s\nPress 0 for normal scan or any other key for a quick scan: ", WELCOME_MES, directory_name, virus_name);
    fprintf(log, "%s%s\nVirus signature:\n%s", FLOG_WELCOME, directory_name, virus_name);
    fflush(stdin);
    op = getchar();
    printf("\nscanning began...\nThis process may take several minutes...\n");
    (op == 1) ? fprintf(log, "\n\nScanning option:\nQuick scan\n\nResults:\n") : fprintf(log, "\n\nScanning option:\nRegular scan\n\nResults:\n");
    return(op);
}
/*
* check if its directory
* input: path to the file
* output: 0 if not directory, 1 if is directory
*/

int is_directory(const char* path)
{
    struct stat statbuf;
    if (stat(path, &statbuf) != 0)
        return 0;
    return S_ISDIR(statbuf.st_mode);
}

/*
*send it 1 time full scan if option = 0 (regular) or split the file to 3 parts, 0-20%, 80-100%, 20-80%.
* copy the binary file into a string and send it to a func to scan it.
* if found it prints INFECTED and write it in log file.
* else print CLEAN and writes it in log file.
* input: file - the file we scanning, virus: virus's signiture, name: name of the file, option: quick or normal, log: file where we write the actions
* output: 0, just to finish the operation.
*/
int fast_or_regular(FILE* file, FILE* virus, char name[], char option, FILE* log)
{
    int start = 0, fifth_of_len = 0, fourth_len = 0;

    fseek(file, 0, SEEK_END);
    long len = ftell(file);
    rewind(file);
    char* word = (char*)malloc(len);
    fread(word, 1, len, file);//binary file into string

    fseek(virus, 0, SEEK_END);
    long lenSig = ftell(virus);
    rewind(virus);
    char* sig = (char*)malloc(lenSig);
    fread(sig, 1, lenSig, virus);//binary file into string

    if (option == '0')//normal
    {
        if (search_virus(word, sig, name, len, lenSig, start))
        {
            fprintf(log, "%s - INFECTED!\n", name);
        }
        else
        {
            fprintf(log, "%s - clean\n", name);
        }
        free(sig);
        free(word);
        return(0);
    }
    else//quick
    {
        fifth_of_len = len * FIFTH;
        fourth_len = fifth_of_len * 4;
        if (search_virus(word, sig, name, fifth_of_len, lenSig, start))//0-20
        {
            fprintf(log, "%s - %s\n", name, INF_FIRST);
            free(sig);
            free(word);
            return(0);
        }
        else if (search_virus(word, sig, name, len, lenSig, fourth_len))//80-100
        {
            fprintf(log, "%s - %s\n", name, INF_LAST);
            free(sig);
            free(word);
            return(0);
        }
        else if (search_virus(word, sig, name, fifth_of_len, lenSig, fourth_len))//20-80
        {
            fprintf(log, "%s - INFECTED\n", name);
            free(sig);
            free(word);
            return(0);
        }

    }
    fprintf(log, "%s - clean\n", name);//clean
    free(sig);
    free(word);
    return 0;
}
/*
* compare between the file and the virus signiture
* runs on the file untill it equal to the first symbol of the signiture, then runs on both add 1 to the counter
* if counter = len of sig returns same. else its different
* input: word: the word, virus: virus signiture to camper with, name: name of the file, finish_point: where to stop, starting_point: where to start
* output: 1 if same, 0 if not.
*/
int search_virus(char word[], char virus[], char name[], int finish_point, int sigLen, int starting_point)
{
    long i = 0, j = 0, same = 0;
    for (i = starting_point; i < finish_point; i++)//run on the word
    {
        if (word[i] == virus[0])
        {
            same = 1;
            for (j = 1; j < sigLen; j++)//run on the virus sig
            {
                if (word[i + j] == virus[j])
                {
                    same++;
                }
                else
                {
                    break;
                }
            }
        }

        if (same == sigLen)
        {
            return(1);
        }
    }
    return(0);
}



this is the code I run on windows, I add the dirent.h library to open the folder directory

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "dirent.h"
#define SLASH "\\"  

#define FIFTH 0.2
#define NORMAL '0'
#define PARAMS 3
#define MAX 200
#define WELCOME_MES "Welcome to my Virus Scan!\n\nFolder to scan: "
#define FLOG_WELCOME "Anti-virus began! Welcome!\n\nFolder to scan:\n"
#define COMP_MES "Scan Completed.\nSee log path for results: antiVirus_log.txt"
#define INF_LAST "INFECTED (LAST 20%%)"
#define INF_FIRST "INFECTED (FIRST 20%%)"
#define INF "INFECTED"

int search_virus(char word[], char virus[], char name[], int finish_point, int sigLen, int starting_point);
char welcome_op(char directory_name[], char virus_name[], FILE* log);
int is_directory(const char* path);
int fast_or_regular(FILE* file, FILE* virus, char name[], char option, FILE* log);


int main(int argc, char** argv)
{
    char full_path[MAX] = "";
    char option = ' '; //עבור בחירת מצב מהיר או רגיל
    FILE* fLog = fopen("antiVirus_log.txt", "w");
    if (!fLog)
    {
        return 0;
    }
    FILE* virusSig = fopen(argv[2], "rb");// **** 2
    if (!virusSig)
    {
        return 0;
    }

    if (argc != PARAMS)
    {
        return;
    }
    struct dirent* struct_lab;
    DIR* ptr_lab = opendir(argv[1]);
    if (!ptr_lab)
    {
        printf("Couldn't open the directory!");
        return 0;
    }
    else
    {
        option = welcome_op(argv[1], argv[2], fLog);

        while ((struct_lab = readdir(ptr_lab)) != NULL)//enter dir
        {
            if (!is_directory(struct_lab->d_name))
            {
                strcpy(full_path, argv[1]);//add name of the direcotry
                strcat(full_path, SLASH);// add slash
                strcat(full_path, struct_lab->d_name);// add the file name

                FILE* check_file = fopen(full_path, "rb");// open
                if (check_file)
                {
                    fast_or_regular(check_file, virusSig, full_path, option, fLog);
                    fclose(check_file);
                }

            }

        }
        closedir(ptr_lab);
    }
    fclose(fLog);
    FILE* fLog = fopen("antiVirus_log.txt", "r");
    printf("%s", COMP_MES);
    fclose(virusSig);

    getchar();
    return(0);
}
/*
* prints the welcome message and ask the user to choose quick or normal scan
* input: directory_name: the name of the directory, virus name: virus file name, logL: writes the action there
* output: 0 if normal, anything else quick
*/
char welcome_op(char* directory_name, char* virus_name, FILE* log)
{
    char op = ' ';
    printf("%s%s\nVirus signature: %s\nPress 0 for normal scan or any other key for a quick scan: ", WELCOME_MES, directory_name, virus_name);
    fprintf(log, "%s%s\nVirus signature:\n%s", FLOG_WELCOME, directory_name, virus_name);
    op = getch();
    printf("\nscanning began...\nThis process may take several minutes...\n");
    (op == 1) ? fprintf(log, "\n\nScanning option:\nQuick scan\n\nResults:\n") : fprintf(log, "\n\nScanning option:\nRegular scan\n\nResults:\n");
    return(op);
}

/*
* check if its directory
* input: path to the file
* output: 0 if not directory, 1 if is directory
*/
int is_directory(const char* path)
{
    struct stat statbuf;
    if (stat(path, &statbuf) != 0)
        return 0;
    return S_ISDIR(statbuf.st_mode);
}

/*
*send it 1 time full scan if option = 0 (regular) or split the file to 3 parts, 0-20%, 80-100%, 20-80%.
* copy the binary file into a string and send it to a func to scan it.
* if found it prints INFECTED and write it in log file.
* else print CLEAN and writes it in log file.
* input: file - the file we scanning, virus: virus's signiture, name: name of the file, option: quick or normal, log: file where we write the actions
* output: 0, just to finish the operation.
*/
int fast_or_regular(FILE* file, FILE* virus, char name[], char option, FILE* log)
{
    int start = 0, fifth_of_len = 0, fourth_len = 0;

    fseek(file, 0, SEEK_END);
    long len = ftell(file);
    rewind(file);
    char* word = (char*)malloc(len);
    fread(word, 1, len, file);//binary file into string

    fseek(virus, 0, SEEK_END);
    long lenSig = ftell(virus);
    rewind(virus);
    char* sig = (char*)malloc(virus);
    fread(sig, 1, lenSig, virus);//binary file into string

    if (option == '0')//normal
    {
        if (search_virus(word, sig, name, len, lenSig, start))
        {
            fprintf(log, "%s - INFECTED!\n", name);

        }
        else
        {
            fprintf(log, "%s - clean\n", name);
        }
        free(sig);
        free(word);
        return(0);
    }
    else//quick
    {
        fifth_of_len = len * FIFTH;
        fourth_len = fifth_of_len * 4;
        if (search_virus(word, sig, name, fifth_of_len, lenSig, start))//0-20
        {
            fprintf(log, "%s - %s\n", name, INF_FIRST);
            free(sig);
            free(word);
            return(0);
        }
        else if (search_virus(word, sig, name, len, lenSig, fourth_len))//80-100
        {
            fprintf(log, "%s - %s\n", name, INF_LAST);
            free(sig);
            free(word);
            return(0);
        }
        else if (search_virus(word, sig, name, fifth_of_len, lenSig, fourth_len))//20-80
        {
            fprintf(log, "%s - INFECTED\n", name);
            free(sig);
            free(word);
            return(0);
        }

    }
    fprintf(log, "%s - clean\n", name);//clean
    free(sig);
    free(word);
    return 0;
}
/*
* compare between the file and the virus signiture
* runs on the file untill it equal to the first symbol of the signiture, then runs on both add 1 to the counter
* if counter = len of sig returns same. else its different
* input: word: the word, virus: virus signiture to camper with, name: name of the file, finish_point: where to stop, starting_point: where to start
* output: 1 if same, 0 if not.
*/
int search_virus(char word[], char virus[], char name[], int finish_point, int sigLen, int starting_point)
{
    long i = 0, j = 0, same = 0;
    for (i = starting_point; i < finish_point; i++)//run on the word
    {
        if (word[i] == virus[0])
        {
            same = 1;
            for (j = 1; j < sigLen; j++)//run on the virus sig
            {
                if (word[i + j] == virus[j])
                {
                    same++;
                }
                else
                {
                    break;
                }
            }
        }

        if (same == sigLen)
        {
            return(1);
        }
    }
    return(0);
}

ANSWER

Answered 2021-May-15 at 17:43

Pasting your code into godbolt quickly reveals the problem. struct stat isn't defined. For linux, you need to #include <sys/types.h> and #include <sys/stat.h> for struct stat. Pay attention to the remaining warning(s).

Source https://stackoverflow.com/questions/67549395

QUESTION

How can make white background of the picture with texts in C++

Asked 2021-Apr-26 at 14:11

I want to crop the text on a 1280x720 image and put the text back on a 1280x720 white image. I want the places outside the writings to be white.

Actually, I cropped all the texts in the picture and made a collage, but the size of the texts changes, I don't want this.

I want the position and size of the text in the picture not to change.

How can I do this in Opencv? c++ or python

etc

enter image description here

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/opencv_modules.hpp>

#include <cmath>
#include <fstream>

using namespace std;
using namespace cv;

Mat detect_text(Mat input) {
    Mat large = input;
    Mat rgb;
    // downsample and use it for processing
    pyrDown(large, rgb);
    Mat small;
    cvtColor(rgb, small, COLOR_BGR2GRAY);
    // morphological gradient
    Mat grad;
    Mat morphKernel = getStructuringElement(MORPH_ELLIPSE, Size(3, 3));
    morphologyEx(small, grad, MORPH_GRADIENT, morphKernel);
    // binarize
    Mat bw;
    threshold(grad, bw, 0.0, 255.0, THRESH_BINARY | THRESH_OTSU);
    // connect horizontally oriented regions
    Mat connected;
    morphKernel = getStructuringElement(MORPH_RECT, Size(9, 1));
    morphologyEx(bw, connected, MORPH_CLOSE, morphKernel);
    // find contours
    Mat mask = Mat::zeros(bw.size(), CV_8UC1);
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;
    findContours(connected, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE,
                 Point(0, 0));
    // filter contours
    cv::Mat croppedImage;

    Mat temp_Image(input.size(), CV_8UC3, Scalar(255, 255, 255));

    for(int idx = 0; idx >= 0; idx = hierarchy[idx][0]) {
        Rect rect = boundingRect(contours[idx]);
        Mat maskROI(mask, rect);

        maskROI = Scalar(0, 0, 0);
        // fill the contour
        drawContours(mask, contours, idx, Scalar(255, 255, 255), FILLED);
        // ratio of non-zero pixels in the filled region
        double r = (double)countNonZero(maskROI) / (rect.width * rect.height);

        // assume at least 45% of the area is filled if it contains text
        if(r > 0.45 &&
           (rect.height > 8 && rect.width > 8) // constraints on region size
           // these two conditions alone are not very robust. better to use
           // something
           // like the number of significant peaks in a horizontal projection as a
           // third condition
        ) {
            rect.x = rect.x;
            rect.y = rect.y;
            rect.height = rect.height + 10;
            rect.width = rect.width + 10;

            rectangle(rgb, rect, Scalar(0, 255, 0), 2);
            croppedImage = rgb(rect);

            //
            //  to put cropped texts in tem_image
            //
            // imwrite(string("test_text_contours.jpg"), temp_image);
        }
    }
    // imwrite(string("test_text_contours.jpg"), croppedImage);

    return croppedImage;
}

int main(int argc, char *argv[])
{
    Mat img = cv.imread("1.jpg");
    detect_text(img);
    return 0;
}

ANSWER

Answered 2021-Apr-26 at 14:11

here is the python code:

import cv2
import numpy as np

def get_white_image(img, crops):
    image_sizey, image_sizex, c = img.shape
    white_image = np.zeros([image_sizey, image_sizex, 3], dtype=np.uint8)
    white_image.fill(255)
    for crop in crops:
        white_image[crop[0]:crop[1], crop[2]:crop[3]] = img[crop[0]:crop[1], crop[2]:crop[3]]
    return white_image


image = cv2.imread("baldo.jpg")
cv2.imshow("image", image)
crops = []
crops.append([35, 80, 70, 140])
crops.append([85, 95, 50, 160])
crops.append([115, 145, 50, 90])
crops.append([220, 240, 80, 125])
result = get_white_image(image, crops=crops)
cv2.imshow("result", result)
cv2.waitKey(0)

Here is results: Image and white image

Source https://stackoverflow.com/questions/67268109

QUESTION

How to make a fabricJS canvas draggable horizontally on mobile?

Asked 2021-Mar-16 at 14:56

I am trying to create a canvas that is wider than my mobile screen, users can drag right and left to see the rest of the canvas. But for some reason dragging does not work from inside the canvas.

If I below it (outside the canvas) the page can be dragged left and right, but not inside the canvas. How can I fix that?

Ideally I just want a scrollbar inside the canvas so people can drag left and right on mobile, whilst it doesn't increase the entire page width.

I tried setting overflow:scroll on the canvas but I still couldn't drag it. I also added pointer-events: none;, this allows dragging while focused in the canvas but drags the whole page, not just inside the canvas.

What can I do?

Snippet:

<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <base href="//printzelf.nl/new/">
    <title>Image test</title>
    <link rel="stylesheet" href="https://unpkg.com/tippy.js@6/animations/scale-subtle.css"/>
    <link rel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
  </head>
  <body>
    <style media="screen">
    .tippy-box {
      width: 100%!important;
      text-align: center;
      background-color: #fff!important;
      color: #fff!important;
      box-shadow: 3px 2px 15px 6px rgb(0 0 0 / 10%);
      border-radius: 5px;
    }
    .darktext {
      color: #383838;
      font-family: Panton;
      font-size: 15px;
    }
    body .tippy-arrow {
      color: #fff!important;
    }

    .tippy-content{
      padding:0px;
    }

    .tooltipwrap{
      display: flex;
      flex-direction: row-reverse;
    }

    .tooltipinfo{
      text-align: left;
      padding: 0px 0px 15px 15px;
      display: flex;
      flex-direction: column;
    }

    .tooltipinfo h2{
      margin-top: 15px;
      margin-bottom: 0px;
      font-weight: 800;
      font-family: Panton;
      font-size: 22px;
    }

    .tooltipinfo .sub{
      color: #b0b0b0;
      font-weight: 600;
    }

    .tooltipinfo .subbottom{
      background-color:#439fdd;
      display: inline-block;
      position: relative;
      color: #fff;
      padding: 3px 5px;
      border-radius: 5px;
      width: max-content;
      margin-top: 5px;
      font-size: 18px;
    }

    .tooltipwrap img{
      height: 220px;
      width: 190px;
      object-fit: cover;
      border-radius: 0px 5px 5px 0px;
      padding-left: 15px;
    }

    body{
      margin: 0px;
    }

    .canvastip{
      background-color: #009fe3;
      border:3px solid #ccc;
    }

    .canvastip:hover{
      background-color: #009fe3;
      border: 3px solid #FFF;
      border-radius: 18px;
      box-shadow: 0 0 2px #888;
    }
    </style>
    <img id="background" src="https://printzelf.nl/new/assets/images/custom/WOONKAMER.jpg" alt="" style="display:none;">
    <div class="canvas-container" style="pointer-events: none;width: 100%; height: 500px; position: relative; user-select: none;">
      <canvas id="c" width="100%" height="500" class="lower-canvas" style="pointer-events: none;position: absolute; width: 100%; height: 500px; left: 0px; top: 0px;user-select: none;"></canvas>
    </div>
    <h2 style="margin-top:200px;">Test</h2>
    <span id="cirkel1" class="canvastip" style="border-radius:100%;width: 25px;height:25px;position:absolute;cursor:pointer;">
      <div class="tooltipcontentcanvas1 tooltipcontentcanvas darktext" style="position:relative;">
        <div class="tooltipwrap">
          <img src="assets/images/tooltipimg.png" alt="Gordijnen">
          <div class="tooltipinfo">
            <h2>Gordijnen</h2>
            <span class="sub">Print je eigen gordijnen.</span>
            <span class="subbottom">v.a. <b>€18,-</b> p/m<sup>2</sup></span>
          </div>
        </div>
      </div>
    </span>
    <span id="cirkel2" class="canvastip" style="border-radius:100%;width: 25px;height:25px;position:absolute;cursor:pointer;">
      <div class="tooltipcontentcanvas2 tooltipcontentcanvas darktext" style="position:relative;">
        <div class="tooltipwrap">
          <img src="cms/images/canvas/woonkamer/tooltip/vitragegordijnen.jpg" alt="Vitragegordijnen">
          <div class="tooltipinfo">
            <h2>Vitrage gordijnen</h2>
            <span class="sub">Print je eigen gordijnen.</span>
            <span class="subbottom">v.a. <b>€18,-</b> p/m<sup>2</sup></span>
          </div>
        </div>
      </div>
    </span>
    <span id="cirkel3" class="canvastip" style="border-radius:100%;width: 25px;height:25px;position:absolute;cursor:pointer;">
      <div class="tooltipcontentcanvas3 tooltipcontentcanvas darktext" style="position:relative;">
        <div class="tooltipwrap">
          <img src="cms/images/canvas/woonkamer/tooltip/fotoblok.jpg" alt="Fotoblok">
          <div class="tooltipinfo">
            <h2>Fotoblok</h2>
            <span class="sub">Print je eigen gordijnen.</span>
            <span class="subbottom">v.a. <b>€18,-</b> p/m<sup>2</sup></span>
          </div>
        </div>
      </div>
    </span>
    <span id="cirkel4" class="canvastip" style="border-radius:100%;width: 25px;height:25px;position:absolute;cursor:pointer;">
      <div class="tooltipcontentcanvas4 tooltipcontentcanvas darktext" style="position:relative;">
        <div class="tooltipwrap">
          <img src="cms/images/canvas/woonkamer/tooltip/fotopaneel.jpg" alt="Fotopaneel">
          <div class="tooltipinfo">
            <h2>Fotopaneel</h2>
            <span class="sub">Print je eigen gordijnen.</span>
            <span class="subbottom">v.a. <b>€18,-</b> p/m<sup>2</sup></span>
          </div>
        </div>
      </div>
    </span>
    <span id="cirkel5" class="canvastip" style="border-radius:100%;width: 25px;height:25px;position:absolute;cursor:pointer;">
      <div class="tooltipcontentcanvas5 tooltipcontentcanvas darktext" style="position:relative;">
        <div class="tooltipwrap">
          <img src="cms/images/canvas/woonkamer/tooltip/zitzak.jpg" alt="Zitzak">
          <div class="tooltipinfo">
            <h2>Zitzak</h2>
            <span class="sub">Print je eigen gordijnen.</span>
            <span class="subbottom">v.a. <b>€18,-</b> p/m<sup>2</sup></span>
          </div>
        </div>
      </div>
    </span>
    <span id="cirkel6" class="canvastip" style="border-radius:100%;width: 25px;height:25px;position:absolute;cursor:pointer;">
      <div class="tooltipcontentcanvas6 tooltipcontentcanvas darktext" style="position:relative;">
        <div class="tooltipwrap">
          <img src="cms/images/canvas/woonkamer/tooltip/kussens.jpg" alt="Kussens">
          <div class="tooltipinfo">
            <h2>Kussens</h2>
            <span class="sub">Print je eigen gordijnen.</span>
            <span class="subbottom">v.a. <b>€18,-</b> p/m<sup>2</sup></span>
          </div>
        </div>
      </div>
    </span>
    <span id="cirkel7" class="canvastip" style="border-radius:100%;width: 25px;height:25px;position:absolute;cursor:pointer;">
      <div class="tooltipcontentcanvas7 tooltipcontentcanvas darktext" style="position:relative;">
        <div class="tooltipwrap">
          <img src="cms/images/canvas/woonkamer/tooltip/tafelkleed.jpg" alt="Salontafelkleed">
          <div class="tooltipinfo">
            <h2>Salontafelkleed</h2>
            <span class="sub">Print je eigen gordijnen.</span>
            <span class="subbottom">v.a. <b>€18,-</b> p/m<sup>2</sup></span>
          </div>
        </div>
      </div>
    </span>
    <span id="cirkel8" class="canvastip" style="border-radius:100%;width: 25px;height:25px;position:absolute;cursor:pointer;">
      <div class="tooltipcontentcanvas8 tooltipcontentcanvas darktext" style="position:relative;">
        <div class="tooltipwrap">
          <img src="cms/images/canvas/woonkamer/tooltip/hexagonfotocollage.jpg" alt="Hexagon collage">
          <div class="tooltipinfo">
            <h2>Hexagon Fotocollage</h2>
            <span class="sub">Print je eigen gordijnen.</span>
            <span class="subbottom">v.a. <b>€18,-</b> p/m<sup>2</sup></span>
          </div>
        </div>
      </div>
    </span>
    <span id="cirkel9" class="canvastip" style="border-radius:100%;width: 25px;height:25px;position:absolute;cursor:pointer;">
      <div class="tooltipcontentcanvas9 tooltipcontentcanvas darktext" style="position:relative;">
        <div class="tooltipwrap">
          <img src="cms/images/canvas/woonkamer/tooltip/3dletters.jpg" alt="3D letters">
          <div class="tooltipinfo">
            <h2>3D Letters</h2>
            <span class="sub">Print je eigen gordijnen.</span>
            <span class="subbottom">v.a. <b>€18,-</b> p/m<sup>2</sup></span>
          </div>
        </div>
      </div>
    </span>
    <span id="cirkel10" class="canvastip" style="border-radius:100%;width: 25px;height:25px;position:absolute;cursor:pointer;">
      <div class="tooltipcontentcanvas10 tooltipcontentcanvas darktext" style="position:relative;">
        <div class="tooltipwrap">
          <img src="cms/images/canvas/woonkamer/tooltip/tafelkleed2.jpg" alt="Tafelkleed 2">
          <div class="tooltipinfo">
            <h2>Tafelkleed</h2>
            <span class="sub">Print je eigen gordijnen.</span>
            <span class="subbottom">v.a. <b>€18,-</b> p/m<sup>2</sup></span>
          </div>
        </div>
      </div>
    </span>
    <span id="cirkel11" class="canvastip" style="border-radius:100%;width: 25px;height:25px;position:absolute;cursor:pointer;">
      <div class="tooltipcontentcanvas11 tooltipcontentcanvas darktext" style="position:relative;">
        <div class="tooltipwrap">
          <img src="cms/images/canvas/woonkamer/tooltip/rolgordijn.jpg" alt="Rolgordijn">
          <div class="tooltipinfo">
            <h2>Rolgordijn</h2>
            <span class="sub">Print je eigen gordijnen.</span>
            <span class="subbottom">v.a. <b>€18,-</b> p/m<sup>2</sup></span>
          </div>
        </div>
      </div>
    </span>
    <span id="cirkel12" class="canvastip" style="border-radius:100%;width: 25px;height:25px;position:absolute;cursor:pointer;">
      <div class="tooltipcontentcanvas12 tooltipcontentcanvas darktext" style="position:relative;">
        <div class="tooltipwrap">
          <img src="cms/images/canvas/woonkamer/tooltip/raamsticker.jpg" alt="Raamsticker">
          <div class="tooltipinfo">
            <h2>Raamsticker</h2>
            <span class="sub">Print je eigen gordijnen.</span>
            <span class="subbottom">v.a. <b>€18,-</b> p/m<sup>2</sup></span>
          </div>
        </div>
      </div>
    </span>
    <span id="cirkel13" class="canvastip" style="border-radius:100%;width: 25px;height:25px;position:absolute;cursor:pointer;">
      <div class="tooltipcontentcanvas13 tooltipcontentcanvas darktext" style="position:relative;">
        <div class="tooltipwrap">
          <img src="cms/images/canvas/woonkamer/tooltip/textielwand.jpg" alt="Textielwand">
          <div class="tooltipinfo">
            <h2>Textielwand</h2>
            <span class="sub">Print je eigen gordijnen.</span>
            <span class="subbottom">v.a. <b>€18,-</b> p/m<sup>2</sup></span>
          </div>
        </div>
      </div>
    </span>
    <span id="cirkel14" class="canvastip" style="border-radius:100%;width: 25px;height:25px;position:absolute;cursor:pointer;">
      <div class="tooltipcontentcanvas14 tooltipcontentcanvas darktext" style="position:relative;">
        <div class="tooltipwrap">
          <img src="cms/images/canvas/woonkamer/tooltip/fotoopplexiglas.jpg" alt="Foto op plexiglas">
          <div class="tooltipinfo">
            <h2>Foto op plexiglas</h2>
            <span class="sub">Print je eigen gordijnen.</span>
            <span class="subbottom">v.a. <b>€18,-</b> p/m<sup>2</sup></span>
          </div>
        </div>
      </div>
    </span>
    <span id="cirkel15" class="canvastip" style="border-radius:100%;width: 25px;height:25px;position:absolute;cursor:pointer;">
      <div class="tooltipcontentcanvas15 tooltipcontentcanvas darktext" style="position:relative;">
        <div class="tooltipwrap">
          <img src="cms/images/canvas/woonkamer/tooltip/fotooprvs.jpg" alt="Foto op RVS">
          <div class="tooltipinfo">
            <h2>Foto op RVS</h2>
            <span class="sub">Print je eigen gordijnen.</span>
            <span class="subbottom">v.a. <b>€18,-</b> p/m<sup>2</sup></span>
          </div>
        </div>
      </div>
    </span>
  <!-- Popper JS -->
  <script src="assets/js/popper.min.js"></script>
  <script src="https://unpkg.com/tippy.js@6"></script>
  <script type="text/javascript" src="assets/js/fabric.js"></script>
  <script type="text/javascript">
  (function() {
     function reRender(){
            var myImg = document.querySelector("#background");
            var realWidth = window.innerWidth;
            var realHeight = myImg.naturalHeight;
            var source = document.getElementById('background').src;
            var canvas = new fabric.Canvas('c');
            canvas.hoverCursor = 'pointer';
            canvas.selection = false;
            canvas.setDimensions({
                    allowTouchScrolling: true,
                    width: realWidth,
                    height: realHeight
            });
            var img = new Image();
            // use a load callback to add image to canvas.
            img.src = 'https://printzelf.nl/new/assets/images/custom/WOONKAMER.jpg';
            fabric.Object.NUM_FRACTION_DIGITS = 10;
            fabric.Image.fromURL(source, function(img) {
                img.scaleToWidth(canvas.width);
                canvas.setBackgroundImage(img);
                canvas.requestRenderAll();
        });

        var scaleToWidth = window.innerWidth / myImg.width;

        // alert (scaleToWidth)
        const hotspots = [{
                        top: (140* scaleToWidth),
                        left: (720* scaleToWidth),
                        radius: 10,
                        fill: '#009fe3',
                        id: 'cirkel1',
                        hoverCursor: 'pointer',
                        selectable: false,
                        imgtop: 71,
                        imgleft: 236,
                        imgheight: 335,
                        imgwidth: 514,
                        placement: 'right',
                        tooltipid: 'cirkel1',
                        imgUrl: 'https://printzelf.nl/new/cms/images/canvas/woonkamer/gordijnen.jpg'
                },
                {
                        top: (160* scaleToWidth),
                        left: (640* scaleToWidth),
                        radius: 10,
                        fill: '#009fe3',
                        id: 'cirkel2',
                        hoverCursor: 'pointer',
                        selectable: false,
                        imgtop: 82,
                        imgleft: 351,
                        imgheight: 313,
                        imgwidth: 337,
                        placement: 'right',
                        tooltipid: 'cirkel2',
                        imgUrl: 'https://printzelf.nl/new/cms/images/canvas/woonkamer/voile.jpg'
                },
                {
                        top: (350* scaleToWidth),
                        left: (120* scaleToWidth),
                        radius: 10,
                        fill: '#009fe3',
                        id: 'cirkel3',
                        hoverCursor: 'pointer',
                        selectable: false,
                        imgtop: 293,
                        imgleft: 21,
                        placement: 'right',
                        imgheight: 81,
                        imgwidth: 107,
                        imgUrl: 'https://printzelf.nl/new/cms/images/canvas/woonkamer/fotoblok.jpg'
                },
                {
                        top: (275* scaleToWidth),
                        left: (165* scaleToWidth),
                        radius: 10,
                        fill: '#009fe3',
                        id: 'cirkel4',
                        hoverCursor: 'pointer',
                        selectable: false,
                        imgtop: 283,
                        imgleft: 127,
                        placement: 'right',
                        imgheight: 60,
                        imgwidth: 57,
                        imgUrl: 'https://printzelf.nl/new/cms/images/canvas/woonkamer/fotopaneel.jpg'
                },
                {
                        top: (430* scaleToWidth),
                        left: (600* scaleToWidth),
                        radius: 10,
                        fill: '#009fe3',
                        id: 'cirkel5',
                        hoverCursor: 'pointer',
                        selectable: false,
                        imgtop: 365,
                        imgleft: 227,
                        placement: 'right',
                        imgheight: 185,
                        imgwidth: 396,
                        imgUrl: 'https://printzelf.nl/new/cms/images/canvas/woonkamer/zitzak.jpg'
                },
                {
                        top: (320* scaleToWidth),
                        left: (760* scaleToWidth),
                        radius: 10,
                        fill: '#009fe3',
                        id: 'cirkel6',
                        hoverCursor: 'pointer',
                        selectable: false,
                        imgtop: 287,
                        imgleft: 785,
                        placement: 'left',
                        imgheight: 60,
                        imgwidth: 75,
                        imgUrl: 'https://printzelf.nl/new/cms/images/canvas/woonkamer/kussens.jpg'
                },
                {
                        top: (360* scaleToWidth),
                        left: (660* scaleToWidth),
                        radius: 10,
                        fill: '#009fe3',
                        id: 'cirkel7',
                        hoverCursor: 'pointer',
                        selectable: false,
                        imgtop: 309,
                        imgleft: 554,
                        placement: 'right',
                        imgheight: 82,
                        imgwidth: 138,
                        imgUrl: 'https://printzelf.nl/new/cms/images/canvas/woonkamer/tafelkleed.jpg'
                },
                {
                        top: (200* scaleToWidth),
                        left: (970* scaleToWidth),
                        radius: 10,
                        fill: '#009fe3',
                        id: 'cirkel8',
                        hoverCursor: 'pointer',
                        selectable: false,
                        imgtop: 162,
                        imgleft: 843,
                        placement: 'right',
                        imgheight: 102,
                        imgwidth: 129,
                        imgUrl: 'https://printzelf.nl/new/cms/images/canvas/woonkamer/hexagoncollage.jpg'
                },
                {
                        top: (140* scaleToWidth),
                        left: (1020* scaleToWidth),
                        radius: 10,
                        fill: '#009fe3',
                        id: 'cirkel9',
                        hoverCursor: 'pointer',
                        selectable: false,
                        imgtop: 150,
                        imgleft: 1033,
                        placement: 'left',
                        imgheight: 81,
                        imgwidth: 121,
                        imgUrl: 'https://printzelf.nl/new/cms/images/canvas/woonkamer/3dletters.jpg'
                },
                {
                        top: (380* scaleToWidth),
                        left: (1290* scaleToWidth),
                        radius: 10,
                        fill: '#009fe3',
                        id: 'cirkel10',
                        hoverCursor: 'pointer',
                        selectable: false,
                        imgtop: 331,
                        imgleft: 1288,
                        placement: 'left',
                        imgheight: 102,
                        imgwidth: 324,
                        imgUrl: 'https://printzelf.nl/new/cms/images/canvas/woonkamer/tafelkleed2.jpg'
                },
                {
                        top: (180* scaleToWidth),
                        left: (1795* scaleToWidth),
                        radius: 10,
                        fill: '#009fe3',
                        id: 'cirkel11',
                        hoverCursor: 'pointer',
                        selectable: false,
                        imgtop: 55,
                        imgleft: 1807,
                        placement: 'left',
                        imgheight: 173,
                        imgwidth: 152,
                        imgUrl: 'https://printzelf.nl/new/cms/images/canvas/woonkamer/rolgordijn.jpg'
                },
                {
                        top: (278* scaleToWidth),
                        left: (1809* scaleToWidth),
                        radius: 10,
                        fill: '#009fe3',
                        id: 'cirkel12',
                        hoverCursor: 'pointer',
                        selectable: false,
                        imgtop: 245,
                        imgleft: 1823,
                        placement: 'left',
                        imgheight: 173,
                        imgwidth: 152,
                        imgUrl: 'https://printzelf.nl/new/cms/images/canvas/woonkamer/raamsticker.jpg'
                },
                {
                        top: (200* scaleToWidth),
                        left: (1365* scaleToWidth),
                        radius: 10,
                        fill: '#009fe3',
                        id: 'cirkel13',
                        hoverCursor: 'pointer',
                        selectable: false,
                        imgtop: 82,
                        imgleft: 1333,
                        placement: 'left',
                        imgheight: 331,
                        imgwidth: 468,
                        imgUrl: 'https://printzelf.nl/new/cms/images/canvas/woonkamer/textielwand.jpg'
                },
                {
                        top: (255* scaleToWidth),
                        left: (1165* scaleToWidth),
                        radius: 10,
                        fill: '#009fe3',
                        id: 'cirkel14',
                        hoverCursor: 'pointer',
                        selectable: false,
                        imgtop: 156,
                        imgleft: 1165,
                        placement: 'left',
                        imgheight: 116,
                        imgwidth: 54,
                        imgUrl: 'https://printzelf.nl/new/cms/images/canvas/woonkamer/fotoopplexiglas.jpg'
                },
                {
                        top: (159* scaleToWidth),
                        left: (1219* scaleToWidth),
                        radius: 10,
                        fill: '#009fe3',
                        id: 'cirkel15',
                        hoverCursor: 'pointer',
                        selectable: false,
                        imgtop: 164,
                        imgleft: 1215,
                        placement: 'left',
                        imgheight: 116,
                        imgwidth: 468,
                        imgUrl: 'https://printzelf.nl/new/cms/images/canvas/woonkamer/fotooprvs.jpg'
                }
        ];

        const loadedImages = [];

        for (let [idx, props] of hotspots.entries()) {
                let c = new fabric.Circle(props);
                c.class = 'hotspot';
                c.name = 'hotspot-' + idx;
                canvas.add(c);
        }

        fabric.Canvas.prototype.getAbsoluteCoords = function(object) {
                return {
                        left: object.left + this._offset.left,
                        top: object.top + this._offset.top
                };
        }

        var btnWidth = 40,
                btnHeight = 40;

        function positionBtn(obj, index) {
                var absCoords = canvas.getAbsoluteCoords(obj);
                var element = document.getElementById('cirkel' + index);
                element.style.left = (absCoords.left - btnWidth / 10) + 'px';
                element.style.top = (absCoords.top - btnHeight / 10) + 'px';
        }

        canvas.getObjects().forEach(function(ho, index) {
                positionBtn(ho, index + 1);
        });

        $(".canvastip").each(function(i) {
                tippy(this, {
                        theme: 'blue',
                        allowHTML: true,
                        placement: 'right',
                        animation: 'scale-subtle',
                        interactive: true,
                        // popperOptions: {
                        //  strategy: 'fixed',
                        //  modifiers: [
                        //      {
                        //          name: 'flip',
                        //          options: {
                        //              fallbackPlacements: ['bottom', 'bottom'],
                        //          },
                        //      },
                        //      {
                        //          name: 'preventOverflow',
                        //          options: {
                        //              altAxis: true,
                        //              tether: false,
                        //          },
                        //      },
                        //  ],
                        // },
                        onShow(instance) {
                                canvas.getObjects().forEach(function(ho, index) {
                                        if (ho.class && ho.class === 'hotspot') {
                                                if (instance.id == index + 1) {
                                                        // check if image was previously loaded
                                                        if (loadedImages.indexOf(ho.name) < 0) {
                                                                // image is not in the array
                                                                // so it needs to be loaded
                                                                // prepare the image properties
                                                                let imgProps = {
                                                                        width: ho.imgwidth,
                                                                        height: ho.imgheight,
                                                                        left: ho.imgleft* scaleToWidth,
                                                                        top: ho.imgtop* scaleToWidth,
                                                                        scaleX: 1* scaleToWidth,
                                                                        scaleY: 1* scaleToWidth,
                                                                        selectable: false,
                                                                        id: 'img-' + ho.name,
                                                                        hoverCursor: "default",
                                                                };
                                                                instance.setProps({placement: ho.placement})
                                                                var printzelfImg = new Image();
                                                                printzelfImg.onload = function(img) {
                                                                        var printzelf = new fabric.Image(printzelfImg, imgProps);
                                                                        printzelf.trippyHotspotImage = true;
                                                                        canvas.add(printzelf);
                                                                };
                                                                printzelfImg.src = ho.imgUrl;
                                                                // update the `loadedImages` array
                                                                loadedImages.push(ho.name);
                                                        } else {
                                                                for (const o of canvas.getObjects()) {
                                                                        if (o.id && o.id === 'img-' + ho.name) {
                                                                                o.visible = true;
                                                                                break;
                                                                        }
                                                                }
                                                                canvas.renderAll();
                                                        }
                                                }
                                        }
                                });
                        },
                        onHide(instance) {
                                for (const o of canvas.getObjects()) {
                                        if (o.trippyHotspotImage) {
                                                o.visible = false;
                                        }
                                }
                                canvas.renderAll();
                        },
                        content: function(reference) {
                                return reference.querySelector('.tooltipcontentcanvas' + (i + 1));
                        }
                });
        });
     }
     window.addEventListener('resize', reRender, false);
     reRender();
  })();
  </script>
  </body>
</html>

The 'test' beneath it should always be visible, so dragging/scrolling should only happen inside the canvas.

Codepen of my canvas: https://codepen.io/twan2020/pen/mdOoGMz

ANSWER

Answered 2021-Mar-16 at 14:56

I fixed it with the following code:

$('canvas').css('touch-action', 'manipulation');
(function(){
  var defaultOnTouchStartHandler = fabric.Canvas.prototype._onTouchStart;
  fabric.util.object.extend(fabric.Canvas.prototype, {
    _onTouchStart: function(e) {
      var target = this.findTarget(e);
      // if allowTouchScrolling is enabled, no object was at the
      // the touch position and we're not in drawing mode, then
      // let the event skip the fabricjs canvas and do default
      // behavior
      if (this.allowTouchScrolling && !target && !this.isDrawingMode) {
        // returning here should allow the event to propagate and be handled
        // normally by the browser
        return;
      }
      // otherwise call the default behavior
      defaultOnTouchStartHandler.call(this, e);
    }
  });
})();

According to the fabric js github page, the line: allowTouchScrolling: true is currently not working.

Placing above code at the top of my script tag (above the initialization of the fabric canvas) fixed it.

Source https://stackoverflow.com/questions/66566257

QUESTION

how to bypass text captcha using selininum

Asked 2021-Mar-13 at 10:54

enter image description here

The website i am trying to bypass is http://results.jntuh.ac.in/ using selenium with python on pi3 need it for collage project, is there any way o can bypass text captcha , i can copy the text from catch and paste it in the textbox !

ANSWER

Answered 2021-Mar-13 at 10:54

You can pair the .execute_script() method with a JavaScript snippet which will do it for you. This works by getting the value of the input CAPTCHA, then setting it to the value of the input field.

# Execute a script in the browser
browser.execute_script("""

// Set the value of the input to the value of the CAPTCHA text
document.querySelector("#txtInput").value = document.querySelector("#txtCaptcha").value

""")

Source https://stackoverflow.com/questions/66612419

QUESTION

Problem with using different onClick events in one button component

Asked 2021-Mar-10 at 20:42

I wanted to make my components as reusable as it possible but when I started adding events the problems occured. I am using one button component in a lot of places in my app and I just change its name. It worked fine when I passed one onClick event to it (to change menu button name) but when I wanted to do the same with another button (to change cycle name) and when I passed second onClick event to the same button component the menu button stopped working. I tried to find solution but found only different topics. I know I could make a wrapper around the button and make onClick on the wrapper, but I think I am doing something wrong and there must be more elegant way to handle this.

Button component

export const Button = ({text, changeButtonName, changeCycle}) => {

  return (
    <AppButton onClick={changeButtonName, changeCycle}>
      {text}
    </AppButton>
  );
};

Navbar component where cycle and menuu buttons are placed

export const Navbar = () => {

  const menuButton = 'Menu';
  const closeButton = 'Zamknij';

  const [menuButtonName, setMenuButtonName] = useState(menuButton);

  const changeButtonName = () => {
    menuButtonName === menuButton ? setMenuButtonName(closeButton) : setMenuButtonName(menuButton);
  }

  const interiorButton = 'Interior →';
  const structuralCollageButton = 'Structural Collage →';

  const [cycleButtonName, setCycleButtonName] = useState(interiorButton);

  const changeCycle = () => {
    cycleButtonName === interiorButton ? setCycleButtonName(structuralCollageButton) : setCycleButtonName(interiorButton);
  }

  return (
    <Nav>
      <AuthorWrapper>
        <AuthorName>
          Michał Król
        </AuthorName>
        <AuthorPseudonym>
          Structuralist
        </AuthorPseudonym>
      </AuthorWrapper>
      <CycleButtonWrapper >
        <Button text={cycleButtonName} changeCycle={changeCycle} />
      </CycleButtonWrapper>
      <MenuButtonWrapper>
        <Button text={menuButtonName} changeButtonName={changeButtonName} />
      </MenuButtonWrapper>
    </Nav>
   )
}

ANSWER

Answered 2021-Mar-10 at 20:28

update your code like

<AppButton onClick={()=> {
  changeButtonName && changeButtonName();
  changeCycle && changeCycle();
 }}>
  {text}
</AppButton>

Source https://stackoverflow.com/questions/66571835

QUESTION

some data from nodejs is not inserting in mongodb?

Asked 2021-Mar-07 at 18:39

So, this is the post request for my register route using express.js. I am printing the newUser object to console. It prints all the information i.e. name, collage, address, encrypted password but it didn't prints the phone to console why? and also only phone number is not inerting in mongodb database.

    app.post("/register", function(req,res){
    
    const newUser=new User({
        name:req.body.fname,
        phone:req.body.ffphone,
        email:req.body.femail,
        callege:req.body.fcallege,
        password:req.body.fpassword
        
    });
    
    console.log(newUser);
    
    newUser.save(function(err){
        if(err){
            console.log(err);
        }else{
            res.send("<h1>Registration done</h1>");
        }
    });            
   

})

It only prints this output to console:

{
  callege: 'MIT',
  _id: 60450bd602c55639309f93a1,
  name: 'user1',
  email: 'abc@gmail.com',
  password: '123456'
}

why it didn't showing phone attribute? Though I am taking right input from html form.

ANSWER

Answered 2021-Mar-07 at 18:39

Check your Schema for your User model. You probably forgot to add the phone field to it.

Fields that are not included in the schema will not be inserted into the document, which could be why your phone number is not appearing.

Source https://stackoverflow.com/questions/66519273

QUESTION

Flutter custom image collage

Asked 2021-Mar-04 at 12:07

I would like to be able to build collages and for that I tried using CustomPaint to draw the shape and then filling that shape with an image. This is what I tried:

  Container(
    height: 300,
    width: 300,
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(10.0),
      border: Border.all(color: Colors.white, width: 5),
    ),
    child: CustomPaint(
      painter: DrawTriangleShape(color: Colors.blue),
      child: Image.asset('assets/images/exampleImage.jpg'),
    ),
  ),

And my DrawTriangleShape:

class DrawTriangleShape extends CustomPainter {
  Paint painter;

  DrawTriangleShape({color: Colors}) {
    painter = Paint()
      ..color = color
      ..style = PaintingStyle.fill;
  }

  @override
  void paint(Canvas canvas, Size size) {
    var path = Path();

    path.moveTo(size.width / 1, 0);
    path.lineTo(0, size.height);
    path.lineTo(size.height, size.width);
    path.close();

    canvas.drawPath(path, painter);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}

The outcome:

enter image description here

As you can see it is not really the desired outcome as the image is not filling the shape. I didn't find anything on this. Is it even possible? And if not, what would be the best approach to build collages with custom shapes?

Let me know if you need more info!

ANSWER

Answered 2021-Mar-04 at 12:07

Instead of a CustomPaint, use a ClipPath widget.

Using the same path as your CustomPaint:

enter image description here

Full source code

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: HomePage(),
    ),
  );
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ClipPath(
          clipper: CustomClipperImage(),
          child: Image.asset('images/abstract.jpg'),
        ),
      ),
    );
  }
}

class CustomClipperImage extends CustomClipper<Path> {
  @override
  getClip(Size size) {
    return Path()
      ..moveTo(size.width / 1, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.width)
      ..close();
  }

  @override
  bool shouldReclip(CustomClipper oldClipper) {
    return false;
  }
}

Additional example with a white border and scaling the image.

enter image description here

Full source code

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: HomePage(),
    ),
  );
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width * .8;
    final height = width * .7;
    return Scaffold(
      body: Container(
        color: Colors.black54,
        child: Center(
          child: Stack(
            children: [
              CustomPaint(
                painter: MyPainter(),
                child: Container(width: width, height: height),
              ),
              ClipPath(
                clipper: CustomClipperImage(),
                child: Transform.scale(
                  scale: 3,
                  child: Image.asset('images/abstract.jpg',
                      width: width, height: height),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class CustomClipperImage extends CustomClipper<Path> {
  @override
  getClip(Size size) {
    return Path()
      ..moveTo(size.width, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.height)
      ..close();
  }

  @override
  bool shouldReclip(CustomClipper oldClipper) {
    return false;
  }
}

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final path = Path()
      ..moveTo(size.width, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.height)
      ..close();
    final paint = Paint()
      ..color = Colors.white
      ..strokeWidth = 8.0
      ..style = PaintingStyle.stroke;
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

Solution with zoom and pan on the image

Using a GestureDetector to detect the change of scale and localFocalPoint. And then using a Matrix4 to Transform our Image.asset:

enter image description here

Full source code:

import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: HomePage(),
    ),
  );
}

class HomePage extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final _width = MediaQuery.of(context).size.width * .8;
    final _height = _width * .6;
    final _zoom = useState<double>(1.0);
    final _previousZoom = useState<double>(1.0);
    final _offset = useState<Offset>(Offset.zero);
    final _previousOffset = useState<Offset>(Offset.zero);
    final _startingFocalPoint = useState<Offset>(Offset.zero);
    return Scaffold(
      body: Container(
        color: Colors.black54,
        child: Center(
          child: GestureDetector(
            onScaleStart: (details) {
              _startingFocalPoint.value = details.localFocalPoint;
              _previousOffset.value = _offset.value;
              _previousZoom.value = _zoom.value;
            },
            onScaleUpdate: (details) {
              _zoom.value = _previousZoom.value * details.scale;
              final Offset normalizedOffset =
                  (_startingFocalPoint.value - _previousOffset.value) /
                      _previousZoom.value;
              _offset.value =
                  details.localFocalPoint - normalizedOffset * _zoom.value;
            },
            child: Stack(
              children: [
                CustomPaint(
                  painter: MyPainter(),
                  child: Container(width: _width, height: _height),
                ),
                ClipPath(
                  clipper: CustomClipperImage(),
                  child: Transform(
                    transform: Matrix4.identity()
                      ..translate(_offset.value.dx, _offset.value.dy)
                      ..scale(_zoom.value),
                    // ..rotateZ(_rotation.value),
                    child: Image.asset('images/milkyway.jpg',
                        width: _width, height: _height),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class CustomClipperImage extends CustomClipper<Path> {
  @override
  getClip(Size size) {
    return Path()
      ..moveTo(size.width, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.height)
      ..close();
  }

  @override
  bool shouldReclip(CustomClipper oldClipper) {
    return false;
  }
}

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final path = Path()
      ..moveTo(size.width, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.height, size.height)
      ..close();
    final paint = Paint()
      ..color = Colors.white
      ..strokeWidth = 8.0
      ..style = PaintingStyle.stroke;
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

Source https://stackoverflow.com/questions/66407482

QUESTION

C menu problem with a validating loop (to many prints)

Asked 2021-Feb-06 at 18:02

I'm working on a menu with a partner (we're collage students) and are unable to solve a bug where some conditions are met the loop prints the menu more times than it needs to. there is all so the problem i met with when i want to get a negative number into a char variable which i fixed with "(short)input<1" though i think the should be a more memory efficient way to do so.

the code:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>


char main() {
    char choice;
    printf("what would you like to do? use number keys to make a choice.\n");
    printf("Database System Menu:\n1. Add person\n2. Search a person\n3. Search Parents\n4. Delete a person\n5. Get generation\n6. Print database\n7. Search by name\n8. Quit\n");
    scanf("%c", &choice);
    while ((short)choice<1 || (short)choice>8) {
        printf("elegal coice use 1 through 8 keys.\n");
        scanf("%c", &choice);
    }
    if ((short)choice >= 1&&(short)choice < 8) {
        return choice;
    }
    else return '\0';
}

option 2 that we tried:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
    char input = '0';
    while (input != '8')
    {
        printf("Database System Menu:\n");
        printf("1. Add person\n");
        printf("2. Search a person\n");
        printf("3. Search Parents\n");
        printf("4. Delete a person\n");
        printf("5. Get generation\n");
        printf("6. Print database \n");
        printf("7. Search by name\n");
        printf("8. Quit\n");
        scanf("%c", &input);
        if ((short)input < 1 || input >'8')
        {
            printf("Invalid input\n");

        }


    }
}

ANSWER

Answered 2021-Feb-06 at 18:02

The %c specifier as you know gets exactly one character from the standard input, but when you input a character you press Enter causing a newline character to be added to the input buffer, so you'll have two characters in stdin, the loop runs twice, the second being caused by that newline character.


Approach #1:

To discard blank characters such as \n, simply use a space before the specifier, i.e. replace scanf("%c", &input); with scanf(" %c", &input);, mind the space before the %c specifier. The problem that remains is that the loop will cycle as many times as there are characters in the input buffer e.g. if you input asdf the loop will still cycle four times instead of just one.

The negative number question is related to the above, a negative input will need at least 2 characters, so in there lies the problem, the loop will run 3 times for an input of -9, 2 times for the 2 characters and a third time for the \n (if you haven't fixed the \n issue).


Approach #2: (better)

To discard all characters in stdin you can use something like:

int c;
while(( c = getchar()) != '\n' && c != EOF){}

After the scanf.

With this second approach you can solve not only the \n problem but also discard any extra characters you input, e.g. let's say you input 8asds, the 8 will be parsed but all the other characters will be discarded avoiding unwanted extra loops.


Note that a more robust way to do this is to use fgets to parse the input string, and if you need to convert it to a numerical value, use strtoll, don't use atoi it's an unsafe function.


input < 1 looks like it's a typo, you may have meant input < '1'.

Source https://stackoverflow.com/questions/66077888

QUESTION

How to display diffrent images using if function after pressing a button

Asked 2021-Feb-04 at 19:00

For my collage assignment i need to create a html webpage where if you press the button yes it displays a number and a corresponding image. i have figured out how to create the random number but cannot get the corresponding image to show up when the button in pressed. i am very new to this and any help would be appreciated

This is the java script

function randomNumber() {
  var ranNumgen = Math.floor((Math.random() * 6) + 1);
}

console.log("randomNumber");
if ("number" == 1) {
  document.getElementById('img1').src = "image/dice1.jpg";
} else if ("number" == 2) {
  document.getElementById('img1').src = "image/dice2.jpg";
} else if ("number" == 3) {
  document.getElementById("img1").src = "image/dice3.jpg"
} else if ("number" == 4) {
  document.getElementById("img1").src = "image/dice4.jpg";
} else if ("number" == 5) {
  document.getElementById("img1").src = "image/dice5.jpg";
} else if ("number" == 6) {
  document.getElementById("img1").src = "image/dice6.jpg";
}
<head>
  <title></title>
  <button id="b" onclick="ranNumgen()"> Yes </button>
  <button onclick="Num2button()">No</button>
</head>

<body>
  <p id="number"> </p>


And this is all my code 

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <button id="b" onclick="ranNumgen()">   Yes </button>
    <button onclick="Num2button()">No</button>
</head>
<body>
    <p id="number"> </p>

    <script type="text/javascript">

        function randomNumber() {
        var ranNumgen = Math.floor((Math.random() *6) +1);      
}
    
    console.log("randomNumber");
    if ("number" ==1 ) {
        document.getElementById('img1').src ="image/dice1.jpg";
    }

   else if ("number" ==2) {
    document.getElementById('img1').src ="image/dice2.jpg";
   }
   else if ("number"==3) {
    document.getElementById("img1").src="image/dice3.jpg"
   } 
   else if ("number"==4) {
document.getElementById("img1").src="image/dice4.jpg";
   }
   else if ("number"==5) {
        document.getElementById("img1").src="image/dice5.jpg";
   }
   else if ("number"==6) {
        document.getElementById("img1").src="image/dice6.jpg";
   }

        function Num2button() {
        var button2 = "Are you sure"
        alert(button2);
            }


    </script>
    




</body>
                    
</html>

ANSWER

Answered 2021-Feb-04 at 18:03

You can put your logic to assign the picture in your randomNumber function, the best would be to rename it to something like generateRandomPicture.

Then you need an element with the id you have specified and also I would recommend that you use an eventListener instead of doing the inline scripting.

You can add .addEventListener() to your element.

document.getElementById('b').addEventListener('click', randomNumber);

document.getElementById('b').addEventListener('click', randomNumber);

function randomNumber() {
  let number = Math.floor((Math.random() * 6) + 1);

  if (number == 1) {
    document.getElementById('img1').src = "image/dice1.jpg";
  } else if (number == 2) {
    document.getElementById('img1').src = "image/dice2.jpg";
  } else if (number == 3) {
    document.getElementById("img1").src = "image/dice3.jpg"
  } else if (number == 4) {
    document.getElementById("img1").src = "image/dice4.jpg";
  } else if (number == 5) {
    document.getElementById("img1").src = "image/dice5.jpg";
  } else if (number == 6) {
    document.getElementById("img1").src = "image/dice6.jpg";
  }

}
<head>
  <title></title>

</head>

<body>
  <p id="number"> </p>
  <img id="img1"></img>
  <button id="b"> Yes </button>
  <button onclick="Num2button()">No</button>
</body>

Source https://stackoverflow.com/questions/66051098

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

VULNERABILITIES

No vulnerabilities reported

INSTALL Collage

You can use Collage like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the Collage component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

SUPPORT

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

Implement Collage faster with kandi.

  • Use the support, quality, security, license, reuse scores and reviewed functions to confirm the fit for your project.
  • Use the, Q & A, Installation and Support guides to implement faster.

Discover Millions of Libraries and
Pre-built Use Cases on kandi