How to obfuscate react code using terser or uglify-js? When .JS file has tag in it?

I have tried both npm packages to obfuscate react code.
I tried below code is inside package.json in script object
“minify:js”: “uglifyjs ./src/folder1/folder2/filename.js -c -m -o ./Build/filename.js”
and i run npm run minify:js and got below error.
Parse error at ./src/folder1/folder2/filename.js:15,8
<IconButton
^
ERROR: Unexpected token: operator «<».

The filename.js file has html tag content in it. It reruns an HTML element <IconButton. Because of that, it is throwing an error.

I am providing the code
enter image description here

Opening popup window on different monitor in Chrome [closed]

I can’t believe the hassle I’m having trying to do this. What I need to do, is open up 12 popups on my PC – all opening a different page. Currently, I’m having to manually move 2 of them onto each screen every day. I want to be able to click my button, and programmatically move / set their location onto a different screen. I have 6 screens, all the same size. I found so many posts, and quite a few going back over 10 years:

`window.open` on the second monitor in Chrome

Surely this is possible? I have tried manually setting negative top/left, but all it does is move the position on the primary screen. I’m on Windows 11, using the latest Chrome (happy to move to Firefox if it helps!).

Troubleshooting Data Display Issues in a Flask Web Application

this code should process the user text or file it used to work successfully till I had an error and during the error I reloaded the web and it started to display this message (No recommendations to display) even though I fixed the error it still the same whenever I reloaded the web and it no more displays the boxes only the message no matter what

here is the fe code ,, I get the only message on terminal saying (INFO:root:GET request processed)

app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        text_data = request.form.get('text')
        file = request.files.get('file')
        response_data = {}
        error_message = None
        
        if text_data:
            logging.info('Processing text data')
            response_json = send_to_other_app({'text': text_data}, 'create_cv')
            if response_json is not None:
                recommendations = response_json['recommendations']
                recommendations_newlines = recommendations.replace("['", " ").replace("',", " ").replace("']", " ").replace("'", " ")
                recommendations_newlines = recommendations.replace("\n", "n")
                response_json['recommendations'] = recommendations_newlines
                response_data['text_response'] = response_json
                logging.info(f'response_json_0  : {response_json}')
            else:
                error_message = 'Failed to process text data due to an external service error.'
        
        elif file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            save_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(save_path)
            logging.info(f'File uploaded: {filename} to path: {save_path}')
            response_json = send_to_other_app({'file_path': save_path}, 'recommend')
            if response_json is not None:
                response_data['file_response'] = response_json
                logging.info(f'response_json_1 {response_json}')
            else:
                logging.info(f'response_json_2 {response_json}')
                error_message = 'Failed to process file due to an external service error.'
        
        if response_data:
            logging.info(f"Response data available: {response_data}")
            return render_template('recommendations.html', response=response_data)
        
        if not response_data and not error_message:
            logging.info("No response data available.")
            error_message = 'No text data or valid file provided for processing.'
        
        logging.error(error_message)
        return jsonify({'error': error_message}), 400

    # Handle GET request
    logging.info('GET request processed')
    return render_template('index.html')

here is the html code

    </style>
</head>
<body>
    <div class="container">
        {% if response %}
            {% if response.text_response %}
                <!-- CV Generated Box -->
                <div class="box">
                    <h2>CV Generated</h2>
                    <div class="content-box">
                        <pre>{{ response.text_response.created_cv }}</pre>
                    </div>
                </div>
        
                <!-- Recommendations Box -->
                <div class="box">
                    <h2>Recommendation</h2>
                    <div class="content-box">
                        <!-- Convert escaped newlines to HTML line breaks -->
                        <pre>{{ response.text_response.recommendations}}</pre>



                    </div>
                </div>
            {% endif %}
            {% if response.file_response %}
                <!-- File Response Box -->
                <div class="box">
                    <h2>Recommendation</h2>
                    <div class="content-box">
                        <pre>{{ response.file_response.recommendations }}</pre>
                    </div>
                </div>
            {% endif %}
        {% else %}
            <div class="no-recommendations">
                <p>No recommendations to display at the moment.</p>
            </div>
        {% endif %}
    </div>
</body>
</html>

How to collide the objects with wall Using AFrame and Javascript

How to collide with wall using and If possible in latest version of and If there is any reference to learn and Three.js. We are trying to work on how to attach the object to the wall in the latest version and Super hands with latest version.

The debug: true parameter to physics will produce wires around the bodies subject to physics, which makes it easier to understand the behavior of the scene. The rest is just placing the bodies and defining them as static or dynamic.
There are several ways of controlling movement in a world with physics. For example, bodies may receive impulse, and depending on the impulse vector, it will behave by gaining velocity, and maybe impacting other bodies.

To illustrate this, we will use some JavaScript to define a new Arame component, push, which will emulate “pushing” (giving some impulse) to the body. This will happen whenever the body collides with some other in the scene, and when that happens, it will get a “push”, always in the same direction and with the same intensity (that is, with the same impulse vector).

There are several ways of controlling movement in a world with physics. For example, bodies may receive impulse, and depending on the impulse vector, it will behave by gaining velocity, and maybe impacting other bodies.

To illustrate this, we will use some JavaScript to define a new Arame component, push, which will emulate “pushing” (giving some impulse) to the body. This will happen whenever the body collides with some other in the scene, and when that happens, it will get a “push”, always in the same direction and with the same intensity (that is, with the same impulse vector).

Unable to resolve dependency tree Error in react js while installing npm package

When I try to install react-sortable-tree npm package getting error like “unable to resolve dependency tree” and solution for this is given in that error message “Fix the upstream dependency conflict, or retry this command with –force or –legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution.”

What’s the right way to go about fixing this upstream dependency conflict? without using –force or –legacy-peer-deps how can I fix it?

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR! react@”^18.2.0″ from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@”^16.3.0″ from [email protected]
npm ERR! node_modules/react-sortable-tree
npm ERR! react-sortable-tree@”*” from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with –force or –legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!
npm ERR! For a full report see:
npm ERR! /Users/user/.npm/_logs/2024-04-25T05_31_59_043Z-eresolve-report.txt

npm ERR! A complete log of this run can be found in: /Users/user/.npm/_logs/2024-04-25T05_31_59_043Z-debug-0.log

In my package.json I have “react”: “^17.0.2”.

Issues with the floating bar given by chrome when i screen record in chrome from my react app

Hello I am expecting some kind of directions/solution here. I have a react web app which enable user to record screen and video. So i use JS getDisplayMedia() to get the screen recording. So for enhancing the experience I have a timer of 5 seconds shown before the recording starts . In this timer screen I had added a keydown listner to catch space and esc button. esc button will abandon the recording and space will pause the timer. Now I will come to my issue. When I use getDisplayMedia() the chrome will prompt a floating window asking what to share (window, tab, screen). and if I choose something there will be a floating bar shown in the bottom by chrome which says stop sharing or hide. If in the options I choose share my entire window then automatically the focus got to the floating bar below(stop sharing one) and my keydown listners won’t work until i click on the screen. So is there a way in which I can avoid the chrome focussing its floating bar. All other sharing options (screen, tab) it is not getting focussed.

Please don’t down vote the question, if you know some links please point me there or if you know a solution please tell me here. If you find the question irrelevant please let me know that also with some reason.

Sonarqube – Error Refactor this function to reduce its Cognitive Complexity from 18 to the 15 allowed – in javascript

I am getting this error :
30:9 error Refactor this function to reduce its Cognitive Complexity from 18 to the 15 allowed

Possible solutions I tried is like using if and then else if for the rest of the conditions.
Error will go but my code will not work as expected

How can I refactor the below code?

 workItemDetails.value.map((e: any) => {
        const existingData = touchPointRequests.filter((t) => +t.ticket_no === e.id);
        if (existingData.length && e.fields['System.State']) {
          this.updateBrandWebsiteState(existingData, e.fields['System.State']);
        }
        const existingGoLiveDate = new Date(new Date(existingData[0].go_live_date).toDateString());
        const newGoLiveDate = new Date(new Date(e.fields['Custom.GoLiveDate']).toDateString());
        const updateData: any = {};
        if (
          existingData.length &&
          e.fields['Custom.GoLiveDate'] &&
          newGoLiveDate.getTime() !== existingGoLiveDate.getTime()
        ) {
          const zonedDate = utcToZonedTime(new Date(e.fields['Custom.GoLiveDate']), 'Europe/Berlin');
          updateData.goLiveDate = zonedDate;
        }
        if (
          existingData.length &&
          e.fields['Microsoft.VSTS.Common.Priority'] &&
          AzurePriority[e.fields['Microsoft.VSTS.Common.Priority']] !== existingData[0].priority
        ) {
          updateData.priority = AzurePriority[e.fields['Microsoft.VSTS.Common.Priority']];
        }

        if (Object.keys(updateData).length) {
          this.touchPointRequestRepository.UpdateTouchPointRequestById(existingData[0].tpr_id, updateData);
        }
        if (
          existingData.length &&
          e.fields['Custom.PreviewLinks'] != undefined &&
          existingData[0].preview_link !== e.fields['Custom.PreviewLinks']
        ) {
          this.brandWebsiteRequestRepository.UpdateBrandWebsiteRequestByTPId(existingData[0].tpr_id, {
            previewLink: e.fields['Custom.PreviewLinks'],
          });
          this.sendPreviewLinkUpdateMail(existingData);
        }

        if (
          existingData.length &&
          e.fields['System.State'] === 'In Review' &&
          e.fields['Custom.PreviewLinks'] != undefined &&
          existingData[0].feedback_and_comments !== e.fields['Custom.PreviewLinks']
        ) {
          this.brandWebsiteRequestRepository.UpdateBrandWebsiteRequestByTPId(existingData[0].tpr_id, {
            feedbackAndComments: e.fields['Custom.PreviewLinks'],
          });
        }
      });

How to use the Livewire component nested in a livewire form

I have a form which has dynamic selects, I want to separate these selects into another livewire component, so as not to reprogram them in each form, but I don’t know how to validate them and obtain their values from the parent livewire component, how could I do the selects component to use them in other livewire forms?

I have read the documentation and it can be bound with the parent component, but it only allows one property and in these selects I have 3 properties (Country, State and City) these are the selects:

                    <div class="col-4">
                    <x-adminlte-input type="text" wire:model.live='employeeForm.employee_code' name="employeeForm.employee_code" label="Codigo de empleado" />
                </div>
                <div class="col-4">
                    <x-adminlte-select wire:model.live='employeeForm.team_id' name="employeeForm.team_id" label="Equipo:">
                        <x-adminlte-options :options='$employeeForm->teams' empty-option="Seleciona un equipo..." />
                    </x-adminlte-select>
                </div>
                <div class="col-4">
                    <x-adminlte-select wire:model.live='employeeForm.company_id' name="employeeForm.company_id" label="Empresa:">
                        <x-adminlte-options :options='$employeeForm->companies' empty-option="Seleciona una empresa..." />
                    </x-adminlte-select>
                </div>

My component code:

class CreateEmployeeForm extends Component
{
public EmployeeForm $employeeForm;

public $age = 0;

public function mount()
{
    $this->employeeForm->init();
}

public function updatedEmployeeFormCountryId($value)
{
    $this->employeeForm->updateStates($value);
}
public function updatedEmployeeFormstateId($value)
{
    $this->employeeForm->updateCities($value);
}
public function updatedEmployeeFormBirthDate($value)
{
    $this->age = Carbon::parse($value)->diff(now())->y;
}
public function updatedEmployeeFormCompanyId($value)
{
    $this->employeeForm->updateCompanyAssigment($value);
}
public function updatedEmployeeFormDepartamentId($value)
{
    $this->employeeForm->updateJobPositions($value);
}
public function save()
{
    $this->employeeForm->store();
}
public function render()
{
    return view('livewire.create-employee-form');
}
}

My EmployeeForm Code:

    public function updateStates($citySelectedId)
{
    $this->states = Country::find($citySelectedId)?->states()->get()->pluck('name', 'id')->all();
    $this->reset(['state_id', 'city_id']);
}

public function updateCities($stateSelectedId)
{
    $this->cities = State::find($stateSelectedId)?->cities()->get()->pluck('name', 'id')->all();
    $this->reset(['city_id']);
}

public function updateCompanyAssigment($companySelectedId)
{
    $company = app(CompanyRepository::class)->find($companySelectedId);
    $this->departaments = $company?->departaments()->get()->pluck('name', 'id')->all();
    $this->areas = $company?->areas()->get()->pluck('name', 'id')->all();
    $this->payRolls = $company?->payRolles()->get()->pluck('code', 'id')->all();
    $this->reset(['area_id', 'payroll_id', 'departanment_id']);
}

public function updateJobPositions($departamentSelectedId)
{
    $this->jobPositions = Departament::find($departamentSelectedId)?->jobPositions()->get()->pluck('name', 'id')->all();
}

chrome extension how download file user

I have an extension that has added a button to a page. How to make sure that after clicking the button, a file is downloaded from the site/extension folders, the image is allowed in the extension extension, and when you click the download button, it goes in the browser

Didn’t find any information at all, didn’t try anything

Is there a way to see if website is static or dynamic programatically

I am creating scraping API and yesterday I bumped into a dilemma. When using puppeteer I saw that it takes a long time for certain request to be made and after asking it turned out that there is no need to use puppeteer for static content. For static content cheerio is more appropriate. But then immediately another question arised – if cheerio is better for static websites and puppeteer is better for dynamic websites, is there a way to see programatically if website is dynamic or static and based on that use the appropriate scraping tool. And will this slow the performance of the API? I won’t include any code because it doesn’t seem appropriate.
Thank you all in advance!

Getting error “validateDOMNesting(…): cannot appear as a descendant of .”

Here’s my code


const ReadMore = ({children}) => {
    const text = children;
    const [isReadMore, setIsReadMore] = useState(true);
    const toggleReadMore = () => {
        setIsReadMore(!isReadMore);
    };
    return (
        <>
          <p className={`text ${!isReadMore ? "expanded" : ""}`}>
              {isReadMore  ? text[0] : text}
              <span
                  onClick={toggleReadMore}
                  className={`read-or-hide ${!isReadMore ? "expanded" : ""}`}
                  style={{ color: "#00ADB5", cursor: 'pointer'}}
              >  
                  {isReadMore ? "Position Activities" : " show less"}
              </span>
          </p>
        </>
    );
  };
  
  export default function Experience() {
    
    return (
      <>
        <div className='main_div_experience_section'>
          <div className='experience_h1'>
            <span className='text-6xl font-bold text-white'>
              Experience
            </span>
          </div>
          <div className='parent_section'>
            <div className='rectangle'>
              <div className='grid'>
                <div className='col1'>
                  <div className='years_experience'><p>Sep 2023 - Present</p></div>
                </div>
                <div className='col2'>
                  <div className='text_company'>
                    <div className='grouper_name_and_logo'>
                      <div className='img_div_experience'>
                          <a href="home">
                            <img src={Nymbus} alt="" className='company_img_experience' href="home"/>
                          </a>
                      </div>
                      <h1 className='role_experience text-gray-400 text-xl font-normal'>
                        Full Stack Developer - asdfasdf
                      </h1>
                    </div>
                    <ReadMore>
                      <div className={`role_explanation_experience`}>
                        <ul>
                          <p className='my_p_experience'>Daily Activities:</p>
                          <li>SOMETHING</li>
                          <li>SOMETHING</li>
                          <li>SOMETHING</li>
                          <li>SOMETHING</li>
                          <li>SOMETHING</li>
                          <li>SOMETHING</li>
                          <li>SOMETHING</li>
                          <li>SOMETHING</li>
                          <p className='following_p_experience'>Achievements:</p>
                          <li>SOMETHING</li>
                          <li>SOMETHING</li>
                        </ul>
                      </div>
                    </ReadMore>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </>
    )
  }

The function ReadMore is basically a read more section that can increase or decrease by clicking on the <p> tag. However, I’ve been getting the warning “Warning: validateDOMNesting(…): <ul> cannot appear as a descendant of <p>.” and I’d like to fix that.

Furthermore, I’d like to add the functionality to add a transition for my ReadMore function, but I just can’t get it to work, I’ve been thinking is because of the warning (maybe?)

I’d pretty much appreciate your help or recommendations.

I’ve tried

  • Modified ReadMore function
  • Added CSS for transition functionality

I have large stream(4 gb) write from multiple blob, how do I copy that stream to download folder by node js fs

class cfilewriter{    
    constructor(name){
        this.tempname = this.uuidv4() + '.bin';
        this.stream = null;
        this.name = name;
        fs.unlink(this.name);        
        this.stream = fs.createWriteStream(this.tempname, {'flags':'a'});        
    }
    write(dt){        
        this.stream.write(dt, (err, data) => {
            // finish renaming file
            if(err) throw err;
            alert("write ok !");
            this.close();
        });
    }
    uuidv4() {
        return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, c =>
          (+c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> +c / 4).toString(16)
        );
    }
    close(){                
        this.stream.end(()=>{
            // finish closing file
            console.log("finish close file");
            fs.rename(this.tempname, this.name, () => {
                // finish renaming file
                console.log("complete save");
            });
        });
    }
}

var gfile = null;
function save2file(blob){
    var reader = new FileReader();  
    var name = blob.name;    
    reader.onload = function () { // here we save variable 'file' in closure      
        console.log(this.result);
        var arrayBuffer=this.result;
        const buffer = mbuffer.Buffer.from(arrayBuffer);
        if (gfile==null) gfile = new cfilewriter(name);
        gfile.write(buffer);
        //gfile.close();
        
    }     
    reader.readAsArrayBuffer(blob);
}

this code demo download large file (4gb) to stream .
but i dont know how i copy that stream to download folder.

detail:

  1. function save2file , read blob only demo to write stream.
  2. class cfilewwrite used to write stream, save to download.
  3. this code work , but file dont save in download folder.

everyone help me, i dont have experience in javascript, nodejs. thanks !

Javascript Textarea prevent Alt gr + key combinations on KeyDown/KeyUp events itself

In my text area im using onKeydown event to listen to characters typed by user.
I need to prevent Alt gr + key combination values (ē, r̥, ṭ,…) to avoid accented keys in my text area.

if (event.code === 'AltRight')  {
      console.log('Prevent Accent letters');
      event.preventDefault();
    }

(or)

if (event.code === 17 || event.code === 18)  {
      console.log('Prevent Accent letters');
      event.preventDefault();
    }

Nothing worked. They are entering these if condition but still the accent text is getting printed in my textarea. How can this be prevented

Promise.allSettled doesn’t execute

I have 2 promises and i want to make something after both finish, but it doesn’t seem to run

I have this

console.log(loadFilesPromise);
console.log(getBucketAccessPromise);

console.log(111111111);
Promise.allSettled([getBucketAccessPromise, loadFilesPromise])
    .then(results => {
        console.log('FINISH ALL');
        console.log(results);
        this.$store.commit('setLoadingBucket', false);
    })
    .catch(error => {
        console.log('asdasdasdasdasdasdasd');
        reject(error)
    });
console.log(2222222222);

This is the loadFilesPromise

loadFilesPromise = this.loadFiles()

#... this function is inside methods in Vue.js framework
async loadFiles() {
    return api.getDir({
        to: '',
    })
        .then(ret => {
            console.log('Promise loadFilesPromise');
            # more code

#... in another part
getDir(params) {
    return new Promise((resolve, reject) => {
        axios.post('getdir', {
                dir: params.dir,

And this is the getBucketAccessPromise

let getBucketAccessPromise =  new Promise((resolve, reject) => {
                axios.post('getBucketAccess', {
                    username: '_self_'
                })
                .then(res => {
                    console.log('Promise 2');
                    # more code

and the output is

Promise {<pending>}
[[Prototype]]: Promisecatch: ƒ catch()constructor: .....
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined # the undefined result is expected

Promise {<pending>}
[[Prototype]]: Promisecatch: ƒ catch()constructor: .....
[[PromiseState]]: "pending"
[[PromiseResult]]: undefined # the undefined result is expected

111111111
# the FINISH ALL log should be here
2222222222
Promise 1
Promise 2

This is confusing for me, Promise.allSettled should be wait for both promises, but instead this acts like it’s not there

Async Constant Call Ignoring Fetch Request

I’ve bene trying to figure out why an async fetch request gets absolutely ignored in my reactjs app. Basically, I am calling integrate() which, if generates a successful status result from its internal call, then awaits the result of a secondary async const call fetchOtherStuff()

Integrate is executing without issues, however for some reason Chrome is entirely ignoring the fetch request within fetchOtherStuff.

I know for a fact it is being called, as THIS WILL LOG logs every time. However there is no record of a network request being made and, predictably, THIS WILL NOT LOG does not log.

No console errors, no network requests, almost like it just aborts the call (as well as any other awaited constants below fetchOtherStuff()

Has anyone encountered this before? I don’t see anything on S.O.

(Calling await integrate() somewhere)

const integrate = async () => {
  const URL = 'https://whatever-endpoint.com';
  try {
    const response = await fetch(URL, {
      method: "GET",
      headers: {
          "Content-Type": "application/json"
      },
      credentials: 'include'
      });

      const responseData = await response.json();
      if (response.status === 200) {
        await fetchOtherStuff();
      }
   } catch (error) {
       return {status:500, body: 'Server Error, Please Try Again'}
      }
    }


  const fetchOtherStuff = async () =>{
  return new Promise(async (resolve,reject)=>{
    try {
      console.log("THIS WILL LOG")
      const orgCodes = await fetch(`https://endpoint-whatever.com`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json"
        },
        credentials: 'include'
      }); 
      const result = await orgCodes.json();
      console.log("THIS WILL NOT LOG ", result)
      setDomainNotReadyCodes(result)
      resolve(result)               
    } catch (error) {
     reject(error)
    }
  })
}