Sunday, September 12, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


I keep getting this error while executing my application

Posted: 12 Sep 2021 08:43 AM PDT

enter image description hereExecution failed for task ':app:packageDebug'.

A failure occurred while executing com.android.build.gradle.tasks.PackageAndroidArtifact$IncrementalSplitterRunnable java.lang.RuntimeException: java.io.IOException: Incorrect function

How can I click this button using selenium?

Posted: 12 Sep 2021 08:43 AM PDT

<button name="main" type="submit" class="mainfont">  التسجيل</button>  

XPath: /html/body/table/tbody/tr[2]/td/table/tbody/tr/td/table[1]/tbody/tr/td[18]/font/button Full XPath: /html/body/table/tbody/tr[2]/td/table/tbody/tr/td/table[1]/tbody/tr/td[18]/font/button

How can I click this button in selenium? I have tried different methods but none worked, some notes:

  • There are different submit buttons called "main" with mainfont class
  • I tried using the XPath but the function also requires me to use the text inside the button, which is in arabic characters that split into two lines in python text editor, which ofcourse does not work as it needs to be in 1 line, but if I erase the space and make it into one code line, it won't work (probably because it is written in two lines in the HTML code?)

How Can I make my email signature shorter?

Posted: 12 Sep 2021 08:43 AM PDT

I have created an email signature generator using reactjs. Because I used canvas, I converted all elements of email signature to image in base64 format. So when I try to add email signatures to gmail, gmail gives an alert that says your email signature is too long. How Can I make my email signatures shorter so that gmail accepts it?

Kubernetes - Use flyway job to perform migrations on postgres database - Connection problems

Posted: 12 Sep 2021 08:43 AM PDT

The problem

Error photo

Flyway Job Error

I'm currently attempting to use flyway to perform migrations in postgres. I have a feeling the init scripts are unable to be found based on this error message. Not too sure what I'm missing as the init scripts worked when using docker containers.

Any help would be appreciated for solving this issue.

What I have tried:

  1. So far I have tried playing with the connection string inside the job to see if it was a connection problem.
  2. Then I tried using a config map with the init sql script inside to hopefully have the script visible for migrations. Didn't have too much luck with that approach. I have attached the example that I found for this approach. Migrations with ConfigMap for init sql scripts

I have some more research links that I found but they didn't quite fit or work with my problem and weren't as noteworthy or were outdated.

  1. Database migrations in Kubernetes with flyway video
  2. Continuous Database configuration with flyway

Code/Kubernetes setup

What follows is my current setup:

Side note: I am using kind to pull my docker images locally and create my clusters, I will attach my docker compose and docker files at the end.

Flyway Setup

I have Flyway as a Job in Kubernetes with this structure:

Flyway job file

apiVersion: batch/v1  kind: Job  metadata:    name: flyway-migration-job  spec:    template:      spec:        containers:        - name: flyway          image: flyway/flyway:6.3.1          command: ["flyway -url=jdbc:postgresql://postgres-master:5432/wallet -user=test_user -password=testuser1234  -connectRetries=60 migrate"]        restartPolicy: Never    backoffLimit: 1  

Postgres Setup

Postgres Deployment file:

This job is using postgres which I have created a deployment for using:

apiVersion: apps/v1  kind: Deployment  metadata:    name: postgres-master    labels:      app: postgres-master  spec:    replicas: 1    selector:      matchLabels:        app: postgres-master    template:      metadata:        labels:          app: postgres-master      spec:        containers:          - name: postgres-master            image: postgres:12            imagePullPolicy: IfNotPresent            ports:              - containerPort: 5432            env:              - name: POSTGRES_DB                value: wallet              - name: POSTGRES_USER                value: test_user              - name: POSTGRES_PASSWORD                value: testuser1234  

Postgres service file

I have then exposed the Postgres pod using this Postgres service:

apiVersion: v1  kind: Service  metadata:    name: postgres-master    labels:       app: postgres-master  spec:     type: NodePort    ports:      - protocol: TCP        port: 5432        targetPort: 5432    selector:       app: postgres-master  

Node setup

I also have a node deployment which connects to the database pod and I have confirmed that I have been able to connect to the database using hostname postgres-master(pod name), the above login details and port 5432.

Node deployment file

I've attached the node deployment file for completeness but it works.

apiVersion: apps/v1  kind: Deployment  metadata:    name: node-deployment    labels:      app: node-deployment  spec:    replicas: 3    selector:      matchLabels:        app: node-deployment    template:      metadata:        labels:          app: node-deployment      spec:        containers:          - name: node            image: wallet-api-20_web:latest            imagePullPolicy: IfNotPresent            ports:              - containerPort: 8080            env:              - name: PG_HOST                value: "postgres-master.default"  

Docker setup

Docker compose

Then I have my docker compose file which I use to build my images: Side not - All of the docker images worked together including migrations before I started adding Kubernetes.

version: '3.5'  services:    web:      build:        dockerfile: ./Dockerfile      container_name: wallet-api-web      depends_on:         - flyway      ports:         - "8080:8080"    postgres-db:      build:        dockerfile: ./utils/db.Dockerfile      container_name: postgres-db      environment:        POSTGRES_PASSWORD: testuser1234        POSTGRES_USER: test_user        POSTGRES_DB: wallet      image: postgres:12      ports:        - "5432:5432"      restart: always      flyway:      command: -url=jdbc:postgresql://db:5432/wallet -user=test_user -password=testuser1234  -connectRetries=60 migrate      container_name: flyway-migrations      depends_on:        - db      image: flyway/flyway:6.3.1      volumes:        - ${PWD}/migrations/sql:/flyway/sql  

Postgres Dockerfile

Here is my dockerfile for postgres:

FROM postgres:13    ENV POSTGRES_DB wallet  

Node dockerfile

FROM node:15  ENV NODE_ENV=production    WORKDIR /app    # Copying the package json first enables caching.  COPY ["package.json", "package-lock.json*", "./"]    RUN npm install --production    COPY . .     RUN npm run build    ENTRYPOINT npm run start  

Flyway Migration scripts

This is the only migration script I have and it was working before moving to Kubernetes.

CREATE TABLE transaction_events (      transaction_version int,      transaction_type VARCHAR(200),      coins int,      transaction_id VARCHAR(500),      wallet_id VARCHAR(500)  )  

Any help would be appreciated, I have a feeling this might be something small I am missing.

If anymore information is required please let me know.

Feel free to add any questions as well and I will do my best to provide further context.

Thank you.

Centre bars in barplots if category is missing in hue

Posted: 12 Sep 2021 08:42 AM PDT

If one uses hue in seaborn's barplot and one of the categories is missing, it leads to this strange effect of "empty columns" where seaborn plots nothing at the place where it expects the hue to be (see below at the second position, Fri; or in the second picture). How can one centre such cases so that it is at the place of the tick? In the first case, it would be in the middle of the orange bar, in the second it would remove the empty space between the blue and green and place the tick in the middle of the green bar. Thanks.

import seaborn    tips = sns.load_dataset("tips")  tips.loc[(tips["sex"]=="Male")&(tips["day"]=="Fri"), "total_bill"]=np.nan    sns.barplot(x="day", y="total_bill", hue="sex", data=tips)    sns.barplot(x="sex", y="total_bill", hue="day", data=tips)  

two categories

enter image description here

Side note, it is unrelated to this post.

Unable to verify captcha while sign up in Github

Posted: 12 Sep 2021 08:42 AM PDT

I've tried both the spiral galaxy puzzle and voice code. Even though I answered it right, a notification says unable to verify captcha. (I've tried it multiple times. Still the same result) Help, please. Thanks in advance.

How to show data to table html from json nested loop array in php

Posted: 12 Sep 2021 08:42 AM PDT

First of all, sorry I'm newcomer with PHP and I have searched to learn what I am trying to do but could not find any solution. My question may seem simple to an expert developer. If it hurts any expert programmers ego, please do not close because any kind programmer can see and help me. Thanks.

I have json data from curl http request, that I change to array:

array(6) {    ["page"]=>    int(2)    ["per_page"]=>    int(6)    ["total"]=>    int(12)    ["total_pages"]=>    int(2)    ["data"]=>    array(6) {      [0]=>      array(5) {        ["id"]=>        int(7)        ["email"]=>        string(24) "michael.lawson@reqres.in"        ["first_name"]=>        string(7) "Michael"        ["last_name"]=>        string(6) "Lawson"        ["avatar"]=>        string(39) "https://reqres.in/img/faces/7-image.jpg"      }      [1]=>      array(5) {        ["id"]=>        int(8)        ["email"]=>        string(26) "lindsay.ferguson@reqres.in"        ["first_name"]=>        string(7) "Lindsay"        ["last_name"]=>        string(8) "Ferguson"        ["avatar"]=>        string(39) "https://reqres.in/img/faces/8-image.jpg"      }      [2]=>      array(5) {        ["id"]=>        int(9)        ["email"]=>        string(22) "tobias.funke@reqres.in"        ["first_name"]=>        string(6) "Tobias"        ["last_name"]=>        string(5) "Funke"        ["avatar"]=>        string(39) "https://reqres.in/img/faces/9-image.jpg"      }      [3]=>      array(5) {        ["id"]=>        int(10)        ["email"]=>        string(22) "byron.fields@reqres.in"        ["first_name"]=>        string(5) "Byron"        ["last_name"]=>        string(6) "Fields"        ["avatar"]=>        string(40) "https://reqres.in/img/faces/10-image.jpg"      }      [4]=>      array(5) {        ["id"]=>        int(11)        ["email"]=>        string(24) "george.edwards@reqres.in"        ["first_name"]=>        string(6) "George"        ["last_name"]=>        string(7) "Edwards"        ["avatar"]=>        string(40) "https://reqres.in/img/faces/11-image.jpg"      }      [5]=>      array(5) {        ["id"]=>        int(12)        ["email"]=>        string(23) "rachel.howell@reqres.in"        ["first_name"]=>        string(6) "Rachel"        ["last_name"]=>        string(6) "Howell"        ["avatar"]=>        string(40) "https://reqres.in/img/faces/12-image.jpg"      }    }    ["support"]=>    array(2) {      ["url"]=>      string(34) "https://reqres.in/#support-heading"      ["text"]=>      string(72) "To keep ReqRes free, contributions towards server costs are appreciated!"    }  }  

I want to add this data to table in html, when I try to store the data, I cant get the true method to store the data. This is my html:

<table>          <thead>              <tr>                  <th>No</th>                  <th>Nama Depan</th>                  <th>Nama Belakang</th>                  <th>ID</th>                  <th>Foto</th>              </tr>          </thead>          <tbody>              <?php foreach ($profile as $pro) { ?>                  <?php $no = 1; ?>              <tr>                  <td><?= $no++; ?></td>                  <td><?= $profile['data'][0]['first_name'] ?></td>                  <td><?= $profile['data'][0]['last_name'] ?></td>                  <td><?= $profile['data'][0]['id'] ?></td>                  <td><?= $profile['data'][0]['avatar'] ?></td>              </tr>              <?php } ?>          </tbody>      </table>  

How to store the data correctly from my nested array?

Universal Signal in C++

Posted: 12 Sep 2021 08:42 AM PDT

I want to bind a signa in my C++ code, which I suppose to call on every crash, so is there any signal in C++ which can be use in this way.

C++ signal in /usr/include/bits/signum.h

How to make revenue $0 for months prior to decrease in SQL?

Posted: 12 Sep 2021 08:42 AM PDT

I have the following data:

client_id balance_month balance
100000000 September 1,2021 12:00 AM $400
100000000 August 1,2021 12:00 AM $100
100000000 July 1,2021 12:00 AM $200
100000000 June 1,2021 12:00 AM $300
200000000 September 1,2021 12:00 AM $99
200000000 August 1,2021 12:00 AM $100
200000000 July 1,2021 12:00 AM $100
200000000 June 1,2021 12:00 AM $100

What is the most efficient way to make all prior months prior to the most recent month with a decrease in balance have $0 such that:

client_id balance_month balance
100000000 September 1,2021 12:00 AM $400
100000000 August 1,2021 12:00 AM $100
100000000 July 1,2021 12:00 AM $0
100000000 June 1,2021 12:00 AM $0
200000000 September 1,2021 12:00 AM $99
200000000 August 1,2021 12:00 AM $0
200000000 July 1,2021 12:00 AM $0
200000000 June 1,2021 12:00 AM $0

React Typescript Error: Invariant failed: You should not use <withRouter(App) /> outside a <Router>

Posted: 12 Sep 2021 08:41 AM PDT

I was developing an App where I use Firebase as an Authentication system of the App, an when I try to implement the routes of the app, I start to get the above title error.

I'm using withRouter funtion, to encapsulate my App component.

So the code of my App.tsx file is the following:

import React, { FC, useEffect } from "react";  import { useDispatch, useSelector } from "react-redux";  import {    Route,    Switch,    useHistory,    withRouter,    BrowserRouter as Router,  } from "react-router-dom";  import "./App.css";    import Header from "./components/sections/Header";  import SignUp from "./components/pages/SignUp";  import SignIn from "./components/pages/SignIn";  import ForgotPassword from "./components/pages/ForgotPassword";  import Homepage from "./components/pages/Homepage";  import Dashboard from "./components/pages/Dashboard";  import PrivateRoute from "./components/auth/PrivateRoute";  import PublicRoute from "./components/auth/PublicRoute";  import Loader from "./components/UI/Loader";  import firebase from "./firebase/config";  import {    getUserById,    setLoading,    setNeedVerification,  } from "./store/actions/authActions";  import { RootState } from "./store";    const App: FC = () => {    const dispatch = useDispatch();    const { loading } = useSelector((state: RootState) => state.auth);    let history = useHistory();    // Check if user exists    // App.tsx    useEffect(() => {      dispatch(setLoading(true));      const unsubscribe = firebase.auth().onAuthStateChanged(async (user) => {        if (user) {          await dispatch(getUserById(user.uid));          if (user.emailVerified) {            history.push("/homepage");          } else {            history.push("/signin");            dispatch(setNeedVerification());          }        }        dispatch(setLoading(false));      });        return () => {        unsubscribe();      };    });      if (loading) {      return <Loader />;    }      function Routes() {      return (        <Switch>          <PublicRoute path="/signup" component={SignUp} exact />          <PublicRoute path="/signin" component={SignIn} exact />          <PublicRoute path="/forgot-password" component={ForgotPassword} exact />          <PrivateRoute path="/dashboard" component={Dashboard} exact />          <PublicRoute path="/homepage" component={Homepage} exact />        </Switch>      );    }      return (      <Router>        <Header />        <Routes />      </Router>    );  };    export default withRouter(App);    

`So I think that have to be realated with the configuration of Route library into the main component of the app.

What I missing??

Take thankss in advance !

Spring data elastic nested relation between document

Posted: 12 Sep 2021 08:41 AM PDT

I have a simple springboot app with three entities with one to many relation ,That I want to save them as document using elasticsearch ,reading the documentation i choose the nested object mapping here's my entities :

    Category --*> product --*> reviews         @Data      @Builder      @Document(indexName = "product-store")      public class Category {          private UUID id ;          private String name ;          private String description ;          @Field(type = FieldType.Nested, includeInParent = true)          private List<Product> products ;      }    @Data  @Builder  @ToString  @Document(indexName = "product-store")  public class Product  {        @Id      private UUID id ;      private String name ;      private String description ;      private String ImageUrl ;      private Double price;        @Field(type = FieldType.Nested, includeInParent = true)      private List<ProductExperience> productExperience ;  }    @Data  @Builder  @Document(indexName = "product-store")  public class ProductExperience {      @Id      private UUID id ;      private String reviewTitle;      private String reviewBody;      private int rate ;  }  

I'm working with spring data elastic I create a repository for each entity ,I'm little confused what order should in save the three entities so they will be saved in the same elastic document :

Is this the correct order using the repositories :

  1. create and save category
  2. create and save product it list of categories
  3. update the product with review

awaitMap() unresolved reference - GoogleMaps in Compose

Posted: 12 Sep 2021 08:41 AM PDT

Column(                  modifier = Modifier                      .height(220.dp)                      .fillMaxWidth(),                  verticalArrangement = Arrangement.Top              ) {                    AndroidView({ mapView }) { mapView ->                      CoroutineScope(Dispatchers.Main).launch {                          val map = mapView.awaitMap()                          // val location = objMap.latLng                          val location = LatLng(-35.016, 143.321)                          // map.user                          map.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 5f))                            val markerOptions = MarkerOptions()                              .position(location)                          map.addMarker(markerOptions)                        }                  }                }  

I'm trying to integrate maps using compose. I'm not sure why I can't find a reference to awaitMap() I already add dependencies as below:

    implementation 'com.google.android.libraries.maps:maps:3.1.0-beta'      implementation '"com.google.maps.android:maps-v3-ktx:2.2.0'      implementation 'com.android.volley:volley:1.2.1'  

Thank you in advance for your advice/suggetion.

How To Redirect from One Component When a Button is Clicked to Other Component in React?

Posted: 12 Sep 2021 08:41 AM PDT

Hi Guys I am a Newbie in ReactJS. I am Making a Project of Movie Booking Website. I am Done with HomePage. When Button Book is clicked Under the Movie Card i Have to Redirect the user to a new Page with a grid of Seats and Movie Details. For Movie Details, I Am Using the card itself. When Book is clicked i want to Display Card But when i click Book Button Nothing Happens. I Have Tried It Using Link from React-Router-DOM. Here Are The Codes: Apps.js:

import './App.css';  import React,{Component} from 'react';  import Navbar from "./components/Navbar/Navbar";  import Movies from "./components/Movies";  import "bootstrap/dist/css/bootstrap.min.css";  import Cards from './components/Cards';  import { Route } from 'react-router';  import { BrowserRouter } from 'react-router-dom';  class App extends Component {    render(){      return (        <BrowserRouter>          <switch>          <Navbar/>          <Cards/>            <Route path="/navbar">              <Navbar/>            </Route>            <Route path="/booking" exact>              <Cards/>            </Route>          </switch>        </BrowserRouter>      );    }  }    export default App;      export default App;  

Cards.js:

import React from 'react';  import { Link } from 'react-router-dom';  import './Card.css';  function Cards(){      return (        <div class="row row-cols-1 row-cols-md-2 g-4">        <div class="col">          <div class="card">      <div class="card-header">        <h2>Movie-name</h2>        </div>        <img src="https://reactjsexample.com/content/images/2020/01/React-MovieCards-1.jpg" class="card-thumbnail" alt=""/>      <div class="card-body">        <p className="text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>                <div class="d-grid gap-2 col-4 mx-auto">        <Link to="/booking"><button type="button" >Book</button></Link>        </div>        </div>    </div>    </div>      <div class="col">          <div class="card">      <div class="card-header">        <h2>Movie-name</h2>        </div>                <img src="https://reactjsexample.com/content/images/2020/01/React-MovieCards-1.jpg" class="img-thumbnail" alt=""/>      <div class="card-body">        <p className="text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>        <div class="d-grid gap-2 col-4 mx-auto">        <Link to="/booking"><button type="button" >Book</button></Link>        </div>      </div>    </div>    </div>        </div>      );  }    export default Cards;  

Component not updating after fireEvent.click

Posted: 12 Sep 2021 08:41 AM PDT

I'm new with Jest and testing-library. I have a NavbarContainer component that renders one button or another depending of a variable (menuOpen) that it's being changed with a function. I have already checked that the variable changes its value after the fireEvent, however, it seems as the component it's not updating. What am I doing wrong?

Here there is my component

export const NavbarContainer = ({functionality, menuOpen, activeLink}) => {      return (          <div className="navbar-container">              { menuOpen && <Navbar functionality={functionality} activeLink={activeLink}/> }              { menuOpen && <Button text="navbar.back" functionality={functionality}></Button> }              { !menuOpen && <Button text="navbar.menu" functionality={functionality} modificator="back"></Button> }          </div>      );  };  

Here are the values and functions I am passing to NavbarContainer component

    const [menuOpen, setMenuOpen] = useState(false);      const [activeLink, setActiveLink] = useState("");      const openMenu = (link) => {          setMenuOpen(!menuOpen);          setActiveLink(link.toString());      };  

Here are my tests

  describe("NavbarContainer", () => {      i18n.changeLanguage('cimode');      let component;      let menuOpen = true;      const openMenu = () => {          menuOpen = !menuOpen;      };      beforeEach(() => {          component = render(              <BrowserRouter basename="/">                  <NavbarContainer menuOpen={menuOpen} functionality={openMenu} activeLink=""/>              </BrowserRouter>                        );      });      it("after click the menu button is shown", async () => {          const backButton = component.queryByText("navbar.back");          await fireEvent.click(backButton);          const menuButton = await component.queryByText("navbar.menu");          expect(menuButton).toBeInTheDocument();      });  });  

If a file was found more than once in subfolders - delete all using batch script

Posted: 12 Sep 2021 08:43 AM PDT

The system I'm working on looks like this:

D:\TargetFolder\Subfolder1   D:\TargetFolder\Subfolder2\Subfolder3  

There is a file called "Settings.txt" that could exist in each of these folders. what I want is the following:

  • If the file was found more than once in the targeted folder and all of its subfolders then delete all of them.

  • If the file was found just once in the targeted folder and all of its subfolders then continue on with the script.

  • If the file doesn't exist then continue on with the script.

The final script could possibly be something like this:

IF exist "D:\TargetFolder\*Settings.txt" (goto delete) else goto continue  :delete  del *Settings.txt /f /q  :continue  exit  

I hope, I explained my question correctly. Thanks in advance.

How to center div vertically in other div

Posted: 12 Sep 2021 08:42 AM PDT

In my code I have section element with a background image and I want to put a div element over that like thisenter image description here

But I dont know how to put that text over the image. It just sticks over it: Here is my html and css:

* {    background-color: black;    font-family: Helvetica;    color: seashell;    opacity: 0.9;    font-size: 22px;      }    #mission {    margin: 0 auto;    width: 1200px;    height: 700px;    background-image: url(https://content.codecademy.com/courses/freelance-1/unit-4/img-mission-background.jpg);    background-repeat: no-repeat;  }    #mission div {    background-color: black;    text-align: center;      }
<section id="mission">    <div>      <h2>Our Mission</h2>      <h4>Handpicked, Artisanally Curated, Free Range, Sustainable, Small Batch, Fair Trade, Organic Tea</h4>    </div>   </section>

Inconsistent encoding of persian text/characters

Posted: 12 Sep 2021 08:41 AM PDT

I am new to R and trying to clean my dataset. some of my variables are strings (but not in English, my string variable are in the Persian language). yesterday when I used table function the persian language was supported and it gave a table with its value in persian but today it doesn't work and it return in a strange format (ªÙ†Ø¯ Ùˆ پرسشنامه تکمیل نشده است به همین دلیل Ù\u0081قط ایتم هایی Ú©Ù‡ پاسخ داده اند ثبت گردید ). how can I solve this problem?

Automate MailMerge Filling from one Excel button into a Word Template

Posted: 12 Sep 2021 08:41 AM PDT

I have an Excel Summary with multiple macros to create documents and i created a button to do all that with one click (pdf, excel etc.). The only remaining document i need to do outside Excel is a label document in word format which i have a template for (precise format with one pic on the top and few paragraphs with text in specific position). In one sheet of the Excel Summary i created a format table ready to be used as data entry for mailmerge into the Word template. I looked in the internet to find a way to automate these mailmerge fields with an Excel macro and i found this useful topic: Executing Word Mail Merge

I wanted to know if is possible to fill the word template with the mailmerge fields in the right place (pic attached).

Here the label with mailmerge fields, then i set print settings on 2 labels per pages

How Propagation REQUIRED works in spring boot?

Posted: 12 Sep 2021 08:43 AM PDT

I am just trying to understand the transaction propagation in spring: using jpa, postgres, validators and web starter in my project. Propogation REQUIRED says:

  • when one of these logical transactions is rolled back, all the logical transactions of the current physical transaction are rolled back.

  • but when I am throwing exception in insertUserKumar() it should not persist data in database as per documentation but its getting persisted.

  • my properties are below defined

logging.level.sql=debug  spring.datasource.generate_unique_name=false    spring.datasource.url=jdbc:postgresql://localhost:5432/postgres  spring.datasource.username=dummy  spring.datasource.password=dummy  spring.jpa.properties.hibernate.format_sql=true  spring.jpa.hibernate.ddl-auto=update    spring.datasource.hikari.auto-commit=false  spring.jpa.properties.hibernate.connection.provider_disables_autocommit=true  
  • some will say you might have missed @EnableTransactionManagement I tried it with or without that. but two records are getting persisted into database. Can anyone help me?
@Slf4j  @Component  @RequiredArgsConstructor  public class AppRunner implements CommandLineRunner {      private final UserRepository userRepository;        @Override      public void run(String... args) throws Exception {          insertUserBunty();// this transaction should fail but its getting persisted      }        @Transactional(propagation = Propagation.REQUIRED)      void insertUserBunty() {          User bunty = new User(null, "Bunty");          userRepository.save(bunty);          insertUserKumar();      }        @Transactional(propagation = Propagation.REQUIRED)      void insertUserKumar() {          User kumar = new User(null, "Kumar");          userRepository.save(kumar);          throw new RuntimeException("This will rollback both insert Bunty and Kumar");      }  }  

When the button is a picture, the text also has a prescribed size and spacing. How to make the text appear in the middle of the picture through CSS?

Posted: 12 Sep 2021 08:41 AM PDT

I have a question feel troubled CSS settings need everyone's help -

requirements are as follows: a picture of a button, the picture has a text design draft marked above the button is the size of the picture must be 200px width of the text must be 26px text In the middle of the picture, the upper and lower spacing between the picture and the picture is 8px. The example shown in the figure below needs to be achieved.

But I can't do it anyway. I hope you can provide some solutions to let me know how to deal with this kind of demand. Thank you Everyoneenter image description here

.btn{      display: inline-block;      width: 200px;      height: 100px;      background-image: url('https://upload.cc/i1/2021/09/12/IX7D1d.png');      background-size: cover;      background-repeat: no-repeat;      background-position: center center;      background-size: 140%;  }    .txt{      font-size: 26px;      text-align: center;      padding: 16px;  }
<a class="btn" href="javascript:;">      <p class="txt">send</p>  </a>

Program working fine for relatively smaller numbers but goes haywire for very large numbers

Posted: 12 Sep 2021 08:42 AM PDT

I was working on a problem which asked to compute the smallest number of notes to give an amount input by the user. NOTE: The only allowed denominations were 1, 2, 5, 10, 50, and 100.

THE ISSUE: My code works fine for smaller values like 3000, 4000, etc. but gives the wrong answer for really large numbers like 1234554875687.

Why is this so and what is the solution to that?

#include<stdio.h>  int main (void)  {   int money, _100, r100, _50, r50, _10, r10, _5, r5, _2, r2, _1;            printf("Enter the amount of money you wanna have but will never get : ");      scanf("%d", &money);         _100 = money/100;             r100 = money % 100;           _50 = r100/50;                r50 = r100 % 50;              _10 = r50/10;                  r10 = r50 % 10;                _5 = r10/5;                   r5 = r10 % 5;                 _2 = r5/2;                    r2 = r5 % 2;                  _1 = r2/1;                      printf("No of notes required of 100 are %d\n", _100);      printf("No of notes required of 50 are %d\n", _50);      printf("No of notes required of 10 are %d\n", _10);      printf("No of notes required of 5 are %d\n", _5);      printf("No of notes required of 2 are %d\n", _2);      printf("No of notes required of 1 are %d\n", _1);        return 0;  }  

Error: argument 1 must be pygame.Surface, not function when blit an image

Posted: 12 Sep 2021 08:42 AM PDT

I have managed to blit a few images onto pygame but one of the blits is not working:

def rock():      global rock, rockx, rocky, spawned, rocks, run      rng = random.randint(1, chanse)      pick = random.choice(rocks)            print(rng)            if rockx < 0:          spawned = False            if rng < 2 and spawned == False:          spawned = True                    win.blit(pick, rockx, rocky)            elif spawned == True:          win.blit(pick, rockx, rocky)      

Full code:

import pygame  import time  import random  pygame.init()  pygame.font.init()    main_font = pygame.font.SysFont('comicsnas', 50)  finescore = 0  width = 800  ground = 602  spawned = False  rockx = width  rocky = ground  score = 0  chanse = 100  power = -12  gchange = 0.5  ground = 602  gravity = 0    pygame.display.set_caption('Car Jumpper')    height = 800  fps = 60  car = pygame.image.load('/home/pi/Pygames/carjumper/car-removebg-preview.png')  car_mask = pygame.mask.from_surface(car)  bg = pygame.image.load('/home/pi/Pygames/carjumper/BlueSky.png')  rock1 = pygame.image.load('/home/pi/Pygames/carjumper/rock1-removebg-preview.png')  rock2 = pygame.image.load('/home/pi/Pygames/carjumper/rock2-removebg-preview.png')  rock3 = pygame.image.load('/home/pi/Pygames/carjumper/rock3-removebg-preview.png')    rock1_mask = pygame.mask.from_surface(rock1)  rock2_mask = pygame.mask.from_surface(rock2)  rock3_mask = pygame.mask.from_surface(rock3)      rocks = [ rock1_mask, rock2_mask, rock3_mask]    win = pygame.display.set_mode((width, height))    run = True    def colision():      global run, rock_mask, car_mask, rock2_mask, rock2_mask        result = rock1_mask.overlap(car_mask)      if result:          run = False      else:          pass            result = rock3_mask.overlap(car_mask)      if result:          run = False      else:          pass                result = rock3_mask.overlap(car_mask)       if result:          run = False      else:          pass        def rock():      global rock, rockx, rocky, spawned, rocks, run      rng = random.randint(1, chanse)      pick = random.choice(rocks)            print(rng)            if rockx < 0:          spawned = False            if rng < 2 and spawned == False:          spawned = True                    win.blit(rock, rockx, rocky)            elif spawned == True:          win.blit(pick, rockx, rocky)              def printscore():      global finescore      finescore += 0.1       score = round(finescore)      score_label = main_font.render("Score: {score}".format(score=score), 1, (0, 0, 0))      win.blit(score_label, (10, 10))    def main():      print('Startting...')      global finescore, width, ground, run, rockx, rocky, win          gravity = 0      clock = pygame.time.Clock()      clock.tick(fps)      x = 250      y = 400      jump = False      width = 800      height = 800      black = 0, 0, 0      red = 255, 0, 0      run = True                        while run:          space = False          finescore += 0.2          win.blit(bg, (0, 0))          win.blit(car, (x, y))          printscore()          rockx += 2          rocky += 2                    pygame.display.flip()          gravity += gchange          y += gravity          rock()          for event in pygame.event.get():              if event.type == pygame.KEYDOWN:                  if event.key == pygame.K_SPACE and y > ground:                      jump = True                      space = True            if space == False:              jump = False                                if jump == False:              if y > ground:                      gravity = (gchange * -1)                                          elif jump== True:              gravity = power              y += gravity                              if event.type == pygame.QUIT:              run = False            main()  

This error occurs in the line win.blit(pick(rockx, rocky)).

Merge two txt files as columns in Windows

Posted: 12 Sep 2021 08:42 AM PDT

I need to be able to merge as separate columns files with millions of lines. I tried using the suggested code here:

@echo off  set f1=1.txt  set f2=2.txt  set outfile=mix.txt  type nul>%outfile%  (      for /f "delims=" %%a in (%f1%) do (          setlocal enabledelayedexpansion          set /p line=          echo(%%a!line!>>%outfile%          endlocal      )  )<%f2%    pause  

Concatenate 2 txt files line by line using Batch

But when I run it with non-ASCII (Greek) text I get a weird output and the encoding in result file changes from UTF-8 to Windows-1253 with corrupt Greek characters (despite all files involved, including the batch file, being UTF-8). Also, I get no separator (I want it to be tab).

Example input

file1

Agenda  

file2

Διάταξη των εργασιών  

Output

AgendaΞ"ιάταξη των ΞµΟΞ³Ξ±ΟƒΞΉΟŽΞ½  

Desired Output

Agenda[TAB]Διάταξη των εργασιών  

How to make a TextInputEditText unfocused by default in android?

Posted: 12 Sep 2021 08:43 AM PDT

I have created a Registration form and I wish for no text field to gain focus automatically when the activity starts. I have tried to add to all of my text fields but it is not working.

android:focusedByDefault="false"  

XML Output

        <com.google.android.material.textfield.TextInputLayout          android:id="@+id/bio"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:layout_marginVertical="3dp"          style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense">            <com.google.android.material.textfield.TextInputEditText              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:hint="Bio"              android:inputType="textLongMessage"              android:minLines="3"              android:transitionName="logo_username"              android:focusedByDefault="false"/>      </com.google.android.material.textfield.TextInputLayout>        <com.google.android.material.textfield.TextInputLayout          android:id="@+id/password"          android:layout_width="match_parent"          android:layout_height="wrap_content"          app:passwordToggleEnabled="true"          android:layout_marginVertical="3dp"          style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"          app:counterEnabled="true"          app:counterMaxLength="10">            <com.google.android.material.textfield.TextInputEditText              android:layout_width="match_parent"              android:layout_height="wrap_content"              android:inputType="textPassword"              android:hint="Password"              android:transitionName="logo_username"              android:focusedByDefault="false"/>      </com.google.android.material.textfield.TextInputLayout>        <Button          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:text="LOGIN"          android:textColor="@color/white"          android:background="@color/black"          android:transitionName="logo_button"          android:focusedByDefault="true"/>      

Is there a formula in google sheets where it picks one option out of many to assign to a cell?

Posted: 12 Sep 2021 08:42 AM PDT

I have a column full of models of cars, a column next to it that assigns the correct car type (hatchback, pick up, etc) to the car model.

In the third column, I have more than 1000 car models which need to have these car types associated with them. Is there a formula that can help me do this? I tried nested Ifs but there are around 45 car models so this is a bit inefficient I thought.

How do I display the numbers 0 to 10 in react native without repetition each time I click on the output?

Posted: 12 Sep 2021 08:42 AM PDT

I want the numbers 0 to 10 to be repeated only once and then start counting from 0 to 10 again.

enter image description here

import React, {Component} from 'react';    import {    StyleSheet,    Text,    View,    StatusBar,    SafeAreaView,    TouchableOpacity,  } from 'react-native';    import Ionicons from 'react-native-vector-icons/Ionicons';    export class CertificationScreen extends Component{    constructor(props) {      super(props);    }        render() {      const count = 0;      return (      <SafeAreaView style={styles.container}>        <StatusBar barStyle="light-content" />            <View style={styles.item}>            <TouchableOpacity onPress={() => this.props.navigation.navigate('Forms', {itemId: count + 1 })}>              <Ionicons style={styles.icons} name="arrow-back" size={24} color="#0064FE" />              <Text style={{fontSize: 24}}>Text</Text>              </TouchableOpacity>            </View>      </SafeAreaView>    );}  }  

I researched a lot, but I could not solve this problem. please guide me.

Yes, this is exactly what I want, to add a number by tapping TouchableOpacity. And send this data to my class component via props (itemId). But after making changes, I get this error: Too many re-renders. React limits the number of renders to prevent an infinite loop. Do you know a better way I can use it?

import React from 'react';  import {    StyleSheet,    Text,    View,    StatusBar,    SafeAreaView,    TouchableOpacity,  } from 'react-native';  import Ionicons from 'react-native-vector-icons/Ionicons';    export function CertificationScreen() {    let [counter, setCounter] = React.useState();         if (counter < 10) {        setCounter(counter += 1);          } else {          setCounter(0);        }      return (      <SafeAreaView style={styles.container}>        <StatusBar barStyle="light-content" />            <View style={styles.item}>            <TouchableOpacity onPress={() => this.props.navigation.navigate('Forms', {itemId: setCounter })}>              <Ionicons style={styles.icons} name="arrow-back" size={24} color="#0064FE" />              <Text style={{fontSize: 24}}>Text</Text>              </TouchableOpacity>            </View>      </SafeAreaView>    );     }  

enter image description here

Unable to run smallest windows service in Python

Posted: 12 Sep 2021 08:42 AM PDT

According to this answer I created a smallest Windows service in Python.

Then I ran successfully:

python.exe smallest_service.py install  

and

python.exe smallest_service.py start  

with error message

Starting service SmallestPythonService

Error starting service: The service did not respond to the start or control request in a timely fashion.

My Python version is Python 3.9.6

pip freeze  pypiwin32==223  pywin32 @ file:///C:/Users/me/Downloads/pywin32-301-cp39-cp39-win_amd64.whl  

How can I fix it?

Count nodes within k distance of marked nodes in grid

Posted: 12 Sep 2021 08:42 AM PDT

I am attempting to solve a coding challenge however my solution is not very performant, I'm looking for advice or suggestions on how I can improve my algorithm.

The puzzle is as follows:

You are given a grid of cells that represents an orchard, each cell can be either an empty spot (0) or a fruit tree (1). A farmer wishes to know how many empty spots there are within the orchard that are within k distance from all fruit trees.

Distance is counted using taxicab geometry, for example:

k = 1    [1, 0]  [0, 0]    the answer is 2 as only the bottom right spot is >k distance from all trees.  

My solution goes something like this:

  1. loop over grid and store all tree positions
  2. BFS from the first tree position and store all empty spots until we reach a neighbour that is beyond k distance
  3. BFS from the next tree position and store the intersection of empty spots
  4. Repeat step 3 until we have iterated over all tree positions
  5. Return the number of empty spots remaining after all intersections

I have found that for large grids with large values of k, my algorithm becomes very slow as I end up checking every spot in the grid multiple times. After doing some research, I found some solutions for similar problems that suggest taking the two most extreme target nodes and then only comparing distance to them:

However this does not work for my challenge given certain inputs like below:

k = 4    [0, 0, 0, 1]  [0, 1, 0, 0]  [0, 0, 0, 0]  [1, 0, 0, 0]  [0, 0, 0, 0]  

Using the extreme nodes approach, the bottom right empty spot is counted even though it is 5 distance away from the middle tree.

Could anyone point me towards a more efficient approach? I am still very new to these types of problems so I am finding it hard to see the next step I should take.

how to clear warnings in node js while using mongoose

Posted: 12 Sep 2021 08:42 AM PDT

I'm having a doubt

in The Web Developer Bootcamp course from section 29,304 module  (node:15807) Warning: Accessing non-existent property 'count' of module exports inside circular dependency    (Use node --trace-warnings ... to show where the warning was created)    (node:15807) Warning: Accessing non-existent property 'findOne' of module exports inside circular dependency    (node:15807) Warning: Accessing non-existent property 'remove' of module exports inside circular dependency    (node:15807) Warning: Accessing non-existent property 'updateOne' of module exports inside circular dependency  

I'm getting the above warnings when I use mongoose. How to clear them?

enter image description here

Dart SDK is not configured

Posted: 12 Sep 2021 08:42 AM PDT

I installed Flutter and set up Android Studio. Then I cloned an example of flutter on GitHub (https://github.com/flutter/flutter) and launched it in Android Studio, but it warns me "Dart SDK is not configured", this happened to my co-worker as well. But if I create a new project in Android Studio, no problem at all.

What I have done:

  1. Installed Flutter

  2. Installed Android Studio, along with Flutter plugin including Dart plugin

  3. Flutter run in command line works fine, all five tests passed. (See below)

[✓] Flutter (on Mac OS X 10.13.3 17D47, locale en-US, channel dev) • Flutter version 0.0.22 at /Users/katelyn/flutter • Framework revision 3001b3307d (7 days ago), 2018-01-30 11:37:15 -0800 • Engine revision 8f2d72b183 • Tools Dart version 2.0.0-dev.16.0 • Engine Dart version 2.0.0-edge.7af4db0ea091dddca6b2da851e6dda8d7f9467e8

[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3) • Android SDK at /Users/katelyn/Library/Android/sdk • Android NDK location not configured (optional; useful for native profiling support) • Platform android-27, build-tools 27.0.3 • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-915-b08)

[✓] iOS toolchain - develop for iOS devices (Xcode 9.2) • Xcode at /Applications/Xcode.app/Contents/Developer • Xcode 9.2, Build version 9C40b • ios-deploy 1.9.2 • CocoaPods version 1.4.0

[✓] Android Studio (version 3.0) • Android Studio at /Applications/Android Studio.app/Contents • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-915-b08)

[✓] Connected devices • Android SDK built for x86 • emulator-5554 • android-x86 • Android 7.1.1 (API 25) (emulator)

Last week, I can run their example thru command line (in that dir),

flutter run   

but now I it shows some errors with Gradle.

Launching lib/main.dart on Android SDK built for x86 in debug mode... Initializing gradle... 0.7s Resolving dependencies...

  • Error running Gradle: Exit code 1 from: /Users/katelyn/AndroidStudioProjects/flutter/examples/flutter_gallery/android/gradlew app:properties:

FAILURE: Build failed with an exception.

  • Where: Build file '/Users/katelyn/AndroidStudioProjects/flutter/examples/flutter_gallery/android/app/build.gradle' line: 20

  • What went wrong: A problem occurred evaluating project ':app'. 3

  • Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

  • Get more help at https://help.gradle.org

BUILD FAILED in 0s

Please review your Gradle project setup in the android/ folder.

No comments:

Post a Comment