Cypress: Read from file and upload it again

I am trying to go through an number of tab-separated words in a file and check if the key is in the structure (json):
The json object looks like this:

[
  {
    "Name" : "Cypress Upload 1", 
    "Description" : "Cypress upload descrition 1"
  },
  {
    "Name" : "Cypress Upload 2",
    "Description" : "Cypress upload descrition 2"
  }
]

The code looks like this:

cy.readFile(uploadPathFile).then((jData) => {
      cy.log(jData[0].Name);
      const objLn = Object.keys(jData).length;
      cy.get('@LASTDOWNLOADEDFILE').then((downFile) => {
        cy.readFile(downFile as unknown as string).then((txt) => {
          const lines = (txt as string).split('t');
          for (let o = 0; o < objLn; o++) {
            for (let i = 0; i < lines.length; i++) {
              cy.log(`Key ${lines[i]}  ${jData[o].Name}`);
              if (jData[o].hasOwnProperty(lines[i])) {
                cy.log(`Found Key ${lines[i]}`);
              }
            }
          }
        });
      });
    });

The first log: gives me the correct value of the Name key at position 0

18 log  Cypress Upload 1

The second log lists me all the names from the tab separated file:

...
21 log Key "ID" Cypress Upload 1
22 log Key "Name" Cypress Upload 1
23 log Key "Synonym 1" Cypress Upload 1
...

But it does not show the key found even though “Name” is there and jData[0].Name gives a value! Why is the line with “if (jData[o].hasOwnProperty(lines[i])) {” never true. I also tried “if (jData[o][lines[i]]) {

Luxon: get an array of offsets and untils (like we can in moment-timezone)

With the moment-timezone library I’m currently just retrieving the raw information for a particular timezone and then using that directly in my downstream code.

const zone = moment.tz.zone('Europe/London');

This is an object containing the following:

{
    "name":"Europe/London",
    "abbrs":["GMT","BST","GMT","BST", ...],
    "untils":[-1691964000000,-1680472800000,-1664143200000,-1650146400000, ...],
    "offsets":[0,-60,0,-60,0, ...],
    "population":10000000
}

The offsets and untils arrays are really all I need from moment… the rest I handle myself “manually” in the downstream code using the offsets and untils arrays (or actually just a small subset thereof)… without having to rely on moment as a dependency.

Is there an equivalent way to extract offsets and untils arrays in the luxon library?

Set custom dataTransfer with react-dnd

I am using the react-dnd library to handle drag and drop in React (with the multi back-end to have support for both desktop and mobile platforms) . I’m also using the Ace editor in my app.

The Ace editor accepts dragging and dropping text into the editor as long as the dataTransfer object of the event has {Text: thetexttopaste}.

I would like to generate this dataTransfer for the draggable items that I already handle with react-dnd. However, I can’t find a way to set this dataTransfer data, nor to access the native event.

Here’s the code where I declare my react-dnd draggable items:

export function AvailableBlock(props: AvailableBlockProps) {
    const {block} = props;

    const [collected, drag, dragPreview] = useDrag(() => ({
        type: 'available-block',
        item: {type: 'Text'}
    }))

    return (
        <div className="task-available-block" ref={drag}>
            <div className="task-available-block-name">
                {block.caption}
            </div>
        </div>
    );
}

Is there a way to do it?

How to prevent Chrome and Brave browsers from issuing a Browser notification after javascript removes an item from sessionStorage

As far as I can tell this browser behaviour is new.

I have searched using Google, Bing and Brave Search and can find no trace of the behaviour being documented.

When javascript computationally removes an item from sessionStorage, the browser drops a notification:

[Site] says:

[ItemName] Item removed from sessionStorage

User feedback reveals this notification hinders seamless UX.

One user reported waiting for several minutes before deleting the tab – she didn’t understand the message and she didn’t realise that she needed to press the “OK” button in the bottom right hand corner of the notification to make it go away and enable the page to finish loading.


Example:

sessionStorage.setItem('Test Key', 'Test Value');

setTimeout(() => sessionStorage.removeItem('Test Key'), 300);

/*

It doesn't look like StackSnippets will allow the javascript above.

*/

Is there a way to prevent the browser issuing a notification when javascript removes an item from sessionStorage ?


N.B. This is almost certainly a Blink issue.

I’ve noted that Firefox does not behave in the same manner as Chrome and Brave.

How to show wishlist items after adding items to wishlist without page refresh using ajax in Laravel?

I try to show the item in product page that it added to wishlist without reload but I can only remove wishlsit items in product page without reload using ajax ,so I can’t show items without reload and I want to show items that after adding items to wishlist without page refresh.

Product Page Blade

      @Extends('layouts.base')

    @section('content')

         @foreach($car_lists as $car_list)
           
          <li class="item odd cars_data">

        <div class="product-image"> <a href="{{route('car.detail', ['id' => $car_list->id])}}" title="">
    
    <!-- Begin responsive list slider  -->

           <div class="w-m-280px mb-12px mt-10px">

    <div class="list-slide-container">

    <div class="list-slide-items aspect-ratio-4-3 w-100">

    <div class="slide-items">


     @php
                              
   $images = explode('|', $car_list->images);

    @endphp

 @if($car_list->images)

@for($i = 0; $i < 4; $i++)
<div class="slide-items-list ">
    <div class="slide-items-image-wrapper">

    <img class="slide-items-image " src="{{asset('images')}}/{{$images[$i]}}" alt=""></div>
    <div class="slide-items-button"><i class="fas fa-circle"></i></div>

</div>

@endfor

@else

  <div class="slide-items-list ">
    <div class="slide-items-image-wrapper  ">

    <img class="slide-items-image" src="{{asset('images/car.png')}}" alt=""></div>
    <div class="slide-items-button"><i class="fas fa-circle"></i></div>

</div>

@endif


           </div>
       </div>
      </div>
    </div>

       </a> 


       </div>

          <div class="ratings">
            <div class="rating-box">
              <div style="width:50%" class="rating"></div>
            </div>
          </div>



          <div class="desc std">

            <p>There's no text!</p>

           
          </div>

          <div class="price-box">
           <div class="price-display"  style=" margin-left:2rem; margin-top: 3rem; font-size: 20px;  font-weight: 700; ">
            <hr>

              <span class="result_two"> {{number_format($car_list->price)}}</span> 

             <hr>
        </div>
          </div>
          
          <div class="actions action-button">
                    
         **<!-- add item to wishlist -->**

        @auth

        @php 

        $countWishlist = 0;

        @endphp


        @php

        $countWishlist = AppModelsWhislist::countWishlist($car_list['id'])

        @endphp
           

         <input type="hidden" name="car_id"  class="car_id" value="{{$car_list->id}}">
         
        
        <button class="button ajx-cart addwishlist  addToWhislist"  value="{{$car_list->id}}" type="button" style="background-color: lightgrey; cursor: pointer;">

            @if($countWishlist > 0)

               <i class="fas fa-heart"></i>

            @else

               <i class="far fa-heart"></i>
         
            @endif
                
            
              </button>

            @endauth
         
            <!-- end -->

        </div>
      </li>
      @endforeach

            <ul class="pagination">
               

{!! $car_lists->links('pagination') !!}

            </ul>
      

  <aside class="col-left sidebar col-sm-3 col-xs-12 col-sm-pull-9 wow bounceInUp animated"> 
 
      **<!-- This is my wishlist in product page that I' can't show items there without page refresh -->**

       @auth

       @php
      $wishlist = AppModelsWhislist::where('user_id', auth()->user()->id)- 
  >orderBy('created_at','DESC')->paginate(3, ['*'], 'wishlist_favorites');
    
    @endphp
    
    <div class="block block-list block-cart">
      <div class="block-title">My Favorites </div>
      <div class="block-content">
        <div class="summary">

          <p class="amount"><a href="#"> <span class="wishlist-count">0</span></a> </p>

         
        </div>
        @if($wishlist->count() > 0)
        <p class="block-subtitle">new favorites</p>
        @else
          <p class="block-subtitle"><img src="{{asset('assets/images/favourite.png')}}" width="30px"> No favorites! </p>
        @endif
        <ul id="cart-sidebar" class="mini-products-list">
          @if($wishlist->count() > 0)
          @foreach($wishlist as $item) 
          <li class="item wishlist_data">
            <div class="item-inner"> <a href="{{route('car.detail', ['id' => $item->cars->id])}}" class="product-image">

                @php
                              
             $wish_images = explode('|', $item->cars->images);

              @endphp

              @if($item->cars->images)
              @for($i = 0; $i < 1; $i++)
              <img src="{{asset('asset/images')}}/{{$wish_images[$i]}}" width="80" 
           alt="product">
              @endfor
              @else
                <img src="{{asset('assets/images/sports-car.png')}}" width="80" alt="product">
              @endif

            </a>
              <div class="product-details">
                 <input type="hidden" class="car_id" value="{{$item->cars->id}}">
                <div class="access"> <a href="#" class="btn-remove1 remove-whislist-item">Remove</a> 
                <a href="#" title="Edit item" class="btn-edit">
                <i class="icon-pencil"></i><span class="hidden">Edit item</span></a> </div>
                <!--access--> 
                
               <div style="margin-left: 10px;">
                <p class="product-name"><a href="{{route('car.detail', ['id' => $item->cars->id])}}"> 
               <span class="block-span-price">{{$item->cars->manufacturer}} {{$item->cars->model}} </span> 
                 </a></p>
                <hr>

                  <span class="price"><span class="block-span-price"> 
                  {{number_format($item->cars->price)}} 

                  </span>
                  </div>
              </div>
              <!--product-details-bottoms--> 
            </div>
          </li>

         @endforeach

            {{$wishlist->links('pagination2')}}
          @endif

         
        </ul>
      </div>
    </div>
    @endauth 

   <!-- end -->


  </aside>

@endsection

This is my ajax code below that I want to show items using ajax but how should I do? I tried many times to fix it but I couldn’t.

Ajax code

       $(document).ready(function () {

loadwishlist();

$('.addToWhislist').click(function (e){
    e.preventDefault();

    $.ajaxSetup({

        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }

    });

    var Click = $(this);
    var car_id = $(Click).closest('.cars_data').find('.car_id').val();

     var cars_id = $(Click).closest('.wishlist_data').find('.car_id').val();

    $.ajax({

        type: "POST",
        url: '/add-to-whislist',
        data: {
            'car_id': car_id,
            'cars_id': cars_id,
            
        },

        success: function(response){

            if (response.action == 'add') {


                $(Click).closest('.cars_data').find('.addwishlist').html('<i class="fas fa-heart"></i>');

                loadwishlist();

            }
            else if (response.action == 'remove') {

                $(Click).closest('.cars_data').find('.addwishlist').html('<i class="far fa-heart"></i>');
                loadwishlist();
            }
        
            loadwishlist();
            
        }

    });



});



function loadwishlist()
{
    $.ajax({

        type: "GET",
        url: '/load-cart-data',
        success: function(response){
            $('.wishlist-count').html('');
            $('.wishlist-count').html(response.count);
            
            
        }

    });
}


    $('.remove-whislist-item').click(function (e){
    e.preventDefault();

    $.ajaxSetup({

        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }

    });
    
    var Clickedthis = $(this);
    var car_id = $(Clickedthis).closest('.wishlist_data').find('.car_id').val();

    $.ajax({

        type: "POST",
        url: '/delete-whislist-item',
        data: {
            'car_id': car_id,
        },
        success: function(response){

            $(Clickedthis).closest('.wishlist_data').remove();
            loadwishlist();
        }

    });



});




});

Wishlist Controller

  <?php

namespace AppHttpControllerscontents;

  use AppHttpControllersController;
  use IlluminateHttpRequest;
  use AppModelsWhislist;
   use IlluminateSupportFacadesAuth;
   use AppModelsCar;
    use AppModelsUser;

    class WishlistController extends Controller
    {

    public function add()
     {

    if (Auth::check()) {

        $car_id = request()->car_id;
        
       
       
        $wislist = Whislist::where('user_id',Auth::id())->get()->first();

        if (Whislist::where('user_id',Auth::id())->where('car_id', $car_id)->exists()) {
            $whish = Whislist::where('car_id', $car_id)->where('user_id',Auth::id())->first();
            $whish->delete();

              return response()->json(['action' => 'remove', 'status' => 'removed!']);
        }
     
        else{
             

           $whish = new Whislist();
        
             
             $whish->car_id = $car_id;
            $whish->user_id = Auth::id();
            $whish->save();
                 
           return response()->json(['action' => 'add','status' => 'saved']);
        
        }

    }

    
    else{
        return response()->json(['status' => "Login To Continue"]);
    }

    }

      public function deleteItem()
     {
    if (Auth::check()) {
        $cars_id = request()->input('car_id');
        if (Whislist::where('car_id',$cars_id)->where('user_id',Auth::id())->exists()) {
            $whish = Whislist::where('car_id',$cars_id)->where('user_id',Auth::id())->first();
            $whish->delete();

            return response()->json(['status' => "removed!"]);
        }
             }
    
    else{
        return response()->json(['status' => "Login To Continue"]);
    }
}





  
public function countWislist()
{
    $countwislist = Whislist::where('user_id',Auth::id())->count();
    return response()->json(['count' => $countwislist]);
}
 


}

TextInput centered align vertically on iOS

Is there any way to center align the text inside the TextInput vertically on iOS? (not the TextInput itself, but its text)

The TextInput has multiline set to true.

I have tried using “textAlignVertical: center”, but it doesn’t work on iOS. I also need the input’s height to be dynamic.

(Please refer to my code below from when reading the section below)

What I’m trying to achieve is prevent the user from seeing any changes in the UI when the Text component transforms into a TextInput.

I’m not sure if my approach of center aligning the text vertically inside the TextInput will work as I expected. Besides, I can’t even find a way to achieve that. So, I’m welcome to hear any new creative ideas to approach this problem.

function TextBlock() {
  const [editing, setEditing] = React.useState(false)
  const [text, setText] = React.useState('')
  const props = {}
  if(!editing) props.onPress = () => setEditing(true)
  return (
    <Pressable {...props}>
      {
        editing ? (
          <TextInput style={styles.text} multiline={true} onBlur={() => setEditing(false)} value={text} onChangeText={t => setText(t)}/>
        ) : (
          <Text style={styles.text}>{text}</Text>
        )
      }
    </Pressable>
  )
}
const styles = StyleSheet.create({
  text: {
    fontSize: 14,
    paddingTop: 0,
    paddingBottom: 0,
    paddingRight: 0,
    paddingLeft: 0,
    lineHeight: 20,
    marginBottom: 0,
    marginTop: 0,
    marginLeft: 0,
    marginRight: 0,
    textAlignVertical: 'center',
  }
})

Express/Nodemailer – send info to browser after sending email

I’m vary new to express and I think I’m struggling with something what is not that hard…

I have a function sendEmail

exports.sendEmail = async (req, res) => {
  const transport = nodemailer.createTransport({
    host: process.env.MAIL_HOST,
    port: process.env.MAIL_PORT,
    secure: false,
    auth: {
      user: process.env.MAIL_USER,
      pass: process.env.MAIL_PASSWORD,
    },
    tls: {
      rejectUnauthorized: false,
    },
  });

  await transport.sendMail(
    { body },
    (err, info) => {
      console.log(err);
      console.log(info);
// here is a problem
          if (err) {
           res.status(200).json({ msg: 'error' });
           throw err;
           } else {
             res.status(200).json({ msg: 'mesage  
             has been sent' });
           }
          ); 

This function works fine – email is send. But what I want to achieve is send info to browser with info ‘is sent’ or ‘error’.

In frontend I have this code:

await axios.all([
      axios.post(`${process.env.REACT_APP_DOMAIN}/api/send-email`, {
        data,
      }),
     
      axios
        .get(`${process.env.REACT_APP_DOMAIN}/api/send-email`)
        .then((res) => {
          console.log(res);
        }),
    ]);

axios.post works fine, but axios.get is not. The response I get doesn’t contain data I want.

Could anyone explain me how to send data I need to after email is sent?

Thanks.

How can I decrease a key of a state in React without knowing the key name? [duplicate]

I have the following state in React:

const [counter, setCounter] = useState({foo: 1, bar: 1});

and I have data like

const data = [{who: "foo", otherVal: "bla"}, {who: "bar", otherVal: "bla"}];

If I remove an object from the data array, I want to decrease the counter by 1 related to the who value of the deleted object.

If {who: "foo", otherVal: "bla"} gets removed, I want to decrease the foo key of the counter because who === "foo". But In my app I don’t know that foo is foo or bar is bar. I must use counter[data.who] somehow to update my state.

clearRect clearing the entire screen

i’m new to js and would like some help. I’m making a system where I’m taking the value of an input and inserting the typed text inside an image with canvas. I would like some help because when I have more than one input field, when using ctx.clearRect, it always clears the contents of the other input when typing the second input. Could someone help me?

My form

<form>
    <img style="display:none" src="images/facebook.jpg" crossorigin="anonymous" />
    <input type="text" id="vaga" />
    <input type="text" id="nome" />
    <button type="submit">Save</button>
</form>

My JS

    var canvas = document.getElementById('canvas'),
        ctx = canvas.getContext('2d');
    canvas.width = $('img').width();
    canvas.crossOrigin = "Anonymous";
    canvas.height = $('img').height();
    ctx.drawImage($('img').get(0), 0, 0);
    ctx.font = "36pt Verdana";

    $(document).on('input', '#vaga', function() {
        //redraw image
        ctx.clearRect(550, 80, 200, 20);
        ctx.drawImage($('img').get(0), 0, 0);
        //refill text
        ctx.font = "26pt 'Bebas Neue'";
        ctx.fillStyle = "black";
        ctx.textAlign = 'center';
        //ctx.fillText('center-aligned', x, 85);
        ctx.fillText($(this).val(), 550, 80);
    });

    $(document).on('input', '#nome', function() {
        //redraw image
        //ctx.clearRect(190, 180, 120, 120);
        ctx.drawImage($('img').get(0), 0, 0);
        //refill text
        ctx.font = "14pt 'Bebas Neue 400'";
        ctx.textAlign = 'left';
        ctx.fillStyle = "black";
        ctx.fillText($(this).val(), 190, 180);
    });

    $('button').click(function() {
        console.log(ctx.getImageData(50, 50, 100, 100));
    });

Thaks

Chrome Extension Create a Tab and inject content into it

Hi I’m trying to create a new tab in my background script, and inject a content script (for now its just a regular alert to check the code), but I cant manage to do that since
Content scripts cant be injected into nealy created tabs that follow the chrome-extensions:// scheme and the CSP blocks me if I try to use inline script.

So to conclude:
I’d like to create a new tab from a background script and inject content script into the newly created tab.

my manifest:

{
    "manifest_version": 3,
    "name": "OSINTisizer",
    "description": "OSINT any IP or URL",
    "version": "1.20",
    "icons": {
        "48": "images/logo_48.png",
        "128": "images/logo_128.png"
    },
    "background": {
        "service_worker": "background.js"
    },
    "content_scripts": [
        {
          "matches": ["https://*/report.html"],
          "js": ["report.js"]
        }
      ],
    "permissions": [
        "contextMenus",
        "background",
        "scripting",
        "tabs",
        "storage"
    ],
    "host_permissions": [
        "*://*/*"
    ]
}

My background.js code snippet that is relevant:

chrome.storage.local.set({ info: uniqeEmails }, function () {});
          chrome.tabs.create({ url: "report.html" });
        });
      });

moongose query for finding qunique document

json : {
       data:{
            base:"Id",
           },
        res:{
           message:"sddg"
           }
     }

i want to find if a particular record already exist on the basis of base unique attribute using moongose in mogodb database, but unable to do so.
my approach is

model.findOne({data:{base:”Id”});

Fetch api call in onclick event triggering every alternate run and not every time

I am calling the fetch api call on a onclick event of the submit button after upload change event is performed… I observed that the fetch is not working every alternate hit but the function loadperson( in which fetch is called) is working as the alert in it is showing.
on every alternate hit it sends the payload as expected.
also while running in debug mode its running fine on every hit and payload is being sent perfectly.

is there any reasonsolution to the scenario.

for example :–

first run -no api hit….. second payload – api hit sucessfull …..third run -no api hit….. fourth payload – api hit sucessfull

<!DOCTYPE html>
<html lang="en">

<head>
    <title>File upload</title>
</head>

<body>
    <form id="Form">
        <input type="file" />
        <button type="submit" id="smtbtn" onclick = "hj()" >Submit</button>
    </form>
    <script>
        var base64;
        function loadPersons(a) {
//alert("submit started");
            fetch("http://localhost:8081/api", {
mode: "no-cors",
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    "data": a
                })
            });
alert("submit successful.");
        };
function hj() {
loadPersons(base64)
};
        const fileInput = document.querySelector("input");
        fileInput.addEventListener("change", (e) => {
            const file = e.target.files[0];
            const reader = new FileReader();
            reader.onloadend = () => {
                console.log(reader.result);
                base64 = reader.result;
            };
            reader.readAsDataURL(file);
        });
    </script>
</body>

</html>

How to disable error/warning overlay in webpack-dev-server 3.11.2

I want to disable the error overlay in development but it seems that configuration overlay: false is ignored with [email protected]

Reproduction

serverConfig here configuration set with overlay: false :

{
  disableHostCheck: true,
  compress: true,
  clientLogLevel: 'none',
  contentBase: '/home/dka/workspace/github.com/pass-culture/pass-culture-app-native/public',
  contentBasePublicPath: '/',
  watchContentBase: true,
  hot: true,
  transportMode: 'ws',
  injectClient: false,
  sockHost: undefined,
  sockPath: undefined,
  sockPort: undefined,
  publicPath: '',
  quiet: true,
  watchOptions: {
    ignored: /^(?!/home/dka/workspace/github.com/pass-culture/pass-culture-app-native/src/).+/node_modules//g
  },
  https: false,
  host: '0.0.0.0',
  overlay: false,
  historyApiFallback: { disableDotRule: true, index: '/' },
  public: '192.168.1.102',
  proxy: {
    '/native': {
      target: 'https://backend.testing.passculture.team',
      changeOrigin: true
    },
    '/saml': {
      target: 'https://backend.testing.passculture.team',
      changeOrigin: true
    }
  },
  before: [Function: before],
  after: [Function: after]
}

Expected Behavior

It should disable the overlay as explained here and here

Seems related to https://github.com/electron-userland/electron-forge/issues/2413 / https://github.com/webpack/webpack-dev-server/issues/4111

Debugging JavaScript Uncaught SyntaxError: Unexpected token ‘;’ [closed]

I have a problem with the last line. Does someone know how to fix this code?
The “console” says: Uncaught SyntaxError: Unexpected token ‘;’.
Thanks

var userDatabase = [
    {
        username: "Admin",
        password: "4444",
    }
];

var newsfeed = [
    {
        username: "Max",
        timeline: "Good Morning!",
    },
    {
        username: "Alex",
        timeline: "Have a cool day!",
    }
];

var signUpName = prompt("Enter Username");
var signUpPassword = prompt("Enter Password");

function login(a, b) {
    if (a === userDatabase[0].username && b === userDatabase[0].password) {
        console.log(newsfeed);
        } else {
            alert("Wrong Details");
        }
}
    
function login(signUpName, signUpPassword);