问:
Python flask script not executing as expected
I'm trying to execute a function based on a button click via javascript.
I've copied a tutorial on how to do this, but nothing happens.

I've added a break point in the function that should be executed (background_process_test), but the program never executes the function.
What am I missing to get this simple tutorial working?
I'm running on a local machine with waitress.

python code:

```<code>from flask import Flask, render_template, request
from flask import jsonify
from waitress import serve

app = Flask(__name__)

#rendering the HTML page which has the button
@app.route('/json')
def json():
    return render_template('json.html')

#background process happening without any refreshing
@app.route('/background_process_test')
def background_process_test():
    print ("Hello")
    return ("nothing")

if __name__ == "__main__":
    app.debug = True

serve(app, host='0.0.0.0', port=8080) #WAITRESS!
</code>```

html code:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <!--<script src="/jquery/jquery-3.6.0.min.js"></script>-->
    <script src="{{url_for('static', filename='jquery-3.6.0.min.js')}}"></script>
    <script type=text/javascript>
            (function() {
                ('a#test').on('click', function(e) {
                    e.preventDefault()
                    $.getJSON('/background_process_test', function(data) {
                    //do nothing
                    })
                    return false;
                })
            })
    </script>
</head>

<body>
    <div class='container'>
        <h3>Test</h3>
            <form>
                <a href=# id=test><button class='btn btn-default'>Test</button></a>
            </form>

    </div>
</body>
</html>
</code>```

Update:
Network tab

答: i somehow deleted the '$' sign. It was giving an error due to spacing in visual studio. Setting the spacing right, solved the issue. Many thanks for pointing me in the right direction.</p>

Body:
I'm trying to execute a function based on a button click via javascript.
I've copied a tutorial on how to do this, but nothing happens.

I've added a break point in the function that should be executed (background_process_test), but the program never executes the function.
What am I missing to get this simple tutorial working?
I'm running on a local machine with waitress.

python code:

from flask import Flask, render_template, request
from flask import jsonify
from waitress import serve

app = Flask(__name__)

#rendering the HTML page which has the button
@app.route('/json')
def json():
    return render_template('json.html')

#background process happening without any refreshing
@app.route('/background_process_test')
def background_process_test():
    print ("Hello")
    return ("nothing")

if __name__ == "__main__":
    app.debug = True

serve(app, host='0.0.0.0', port=8080) #WAITRESS!

html code:

<!DOCTYPE html>

Test

            <form>
                <button class='btn btn-default'>Test</button>
            </form>

Update:
Network tab


来源: stackexchange

问:
strange char when use Python to convert from excel .xlsx to csv file
i used this to line of code
to convert excel file with xlsx extension to csv file
but when i have arabic char in excel file i got strange char like

Ø´ÙŠÙ… Ù„Ø§Ù„Ù†Ù‡Ø¶Ù‡ Ù„Ù„Ø§Ø³ØªØ«Ù…Ø§Ø± Ø°ªØ«Ù…Ø§Ø± Ø

```<code>data_xls = pd.read_excel(newFilename +'.xlsx' , dtype=str , index_col=None)

data_xls.to_csv('CSV ' +newFilename+'.csv', encoding='UTF-8' , index=False , header=True)

</code>```

any help please ?

答:
I have a solution and I did it with a small change in my code. I replaced encode='utf-8' with encode='utf-8-sig' and it works for me.

My new code:

data_xls = pd.read_excel(excelfilename+'.xlsx' , dtype=str , index_col=None)
data_xls.to_csv(newFilename+'.csv', encoding='utf-8-sig' , index=False , header=True)
```

ContentLicense: CC BY-SA 4.0

Body:
i used this to line of code
to convert excel file with xlsx extension to csv file
but when i have arabic char in excel file i got strange char like

Ø´ÙŠÙ… Ù„Ø§Ù„Ù†Ù‡Ø¶Ù‡ Ù„Ù„Ø§Ø³ØªØ«Ù…Ø§Ø± Ø°ªØ«Ù…Ø§Ø± Ø

data_xls = pd.read_excel(newFilename +'.xlsx' , dtype=str , index_col=None)

data_xls.to_csv('CSV ' +newFilename+'.csv', encoding='UTF-8' , index=False , header=True)

any help please ?


问:
How to click all arrow buttons within a dynamic table on website?
On this website (https://www.tradingview.com/symbols/NASDAQ-TSLA/financials-income-statement/), there is a table with clickable arrows on some of the rows. I've been trying to use Python Selenium and 'driver.find_elements_by_xpath' to find the arrows (within the table only) and continue clicking on the arrows until all of the rows within table have been fully expanded before scraping, but have been struggling.

The xpath to some of these arrows shown below, but there are some hidden arrows, which will only become visible to click once the first arrow is clicked

```<code>//span[@class='arrow-jKD0Exn-']//*[name()='svg']
</code>```

答:
```<code>driver.maximize_window()
wait=WebDriverWait(driver,10)
driver.get('https://www.tradingview.com/symbols/NASDAQ-TSLA/financials-income-statement/')

wait.until(EC.element_to_be_clickable((By.XPATH,"//span[.='Accept']"))).click()
while True:
    try:
        wait.until(EC.element_to_be_clickable((By.XPATH,"//div[contains(@class,'titleWrap')]//span[contains(@class,'arrow') and not(contains(@class,'opened'))]//*[name()='svg']"))).click()
        time.sleep(1)
    except:
        break
</code>```

Open all the svgs that have that class and nested openings I think you want. It breaks when there are no more of that type.

Import:

```<code>from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
</code>```

Body:
On this website (https://www.tradingview.com/symbols/NASDAQ-TSLA/financials-income-statement/), there is a table with clickable arrows on some of the rows. I've been trying to use Python Selenium and 'driver.find_elements_by_xpath' to find the arrows (within the table only) and continue clicking on the arrows until all of the rows within table have been fully expanded before scraping, but have been struggling.

The xpath to some of these arrows shown below, but there are some hidden arrows, which will only become visible to click once the first arrow is clicked

//span[@class='arrow-jKD0Exn-']//*[name()='svg']

Body:
driver.maximize_window()
wait=WebDriverWait(driver,10)
driver.get('https://www.tradingview.com/symbols/NASDAQ-TSLA/financials-income-statement/')

wait.until(EC.element_to_be_clickable((By.XPATH,"//span[.='Accept']"))).click()
while True:
    try:
        wait.until(EC.element_to_be_clickable((By.XPATH,"//div[contains(@class,'titleWrap')]//span[contains(@class,'arrow') and not(contains(@class,'opened'))]//*[name()='svg']"))).click()
        time.sleep(1)
    except:
        break

Open all the svgs that have that class and nested openings I think you want. It breaks when there are no more of that type.

Import:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time


问:
how to get value of more than one text box in a loop
I have some text boxes in my page. I want to get all text box values in an array and insert in to table of database.

Is there any option to work by loop

答:
```<code>private void FindSelecedControl(Control control)
{
    if (control is TextBox)
    {
        TextBox txt = (TextBox)control;
        txt.Enabled = false;
    }
    else
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            FindSelecedControl(control.Controls[i]);
        }
    }
}

foreach (Control control1 in this.Form.Controls)
{
     FindSelecedControl(control1);
}
</code>```

ContentLicense: CC BY-SA 3.0


问:
Event is fired without any call to .next()
the problem i have is, every time the component VisOpComponent is initialized, the subscribed eventemitter gets fired without any call to .next(). i also added some console.log as shown below to show you that, despite the
subEvtEmitterOnVisualizeBtnClicked is not initialize but still the log statement in the event subscription can be called and it prints subEvtEmitterOnVisualizeBtnClicked called

please let me know why the event is getting fired without any invokation to .next() and how to fix it

VisOpComponent:

```<code>if(this.subEvtEmitterOnVisualizeBtnClicked) {
  if(this.subEvtEmitterOnVisualizeBtnClicked.closed){
    console.log("closed subEvtEmitterOnVisualizeBtnClicked")
  } else {
    console.log("NOT closed subEvtEmitterOnVisualizeBtnClicked")
  }
} else {
  console.log("subEvtEmitterOnVisualizeBtnClicked not initialized")
}

this.subEvtEmitterOnVisualizeBtnClicked = this._FromAwanti1ToVisOpService.getEmitterOnVisualizeButtonClicked().subscribe((param:number)=>{
  console.log("subEvtEmitterOnVisualizeBtnClicked called")
  this.visulizationOperationID = param
  this.submit()
})
</code>```

eventemitters:

```<code>import { Injectable } from '@angular/core';
import { Component, OnInit, EventEmitter, Output } from '@angular/core';
import { BehaviorSubject, Subject,ReplaySubject } from 'rxjs'

@Injectable({
  providedIn: 'root'
})
export class FromAwanti1ToVisOpOfAocAvghInterceptionService {

private emitterOnVisualizeButtonClicked:Subject<number> = new ReplaySubject<number>();

  constructor() { }

  public emitOnVisualizeButtonClicked(param) {
    this.emitterOnVisualizeButtonClicked.next(param)
  }
  public getEmitterOnVisualizeButtonClicked() {
    return this.emitterOnVisualizeButtonClicked.asObservable();
  }
</code>```

logs:

```<code>vis-op.component.ts:45 constructor
vis-op.component.ts:59 subEvtEmitterOnVisualizeBtnClicked not initialized
vis-op.component.ts:63 subEvtEmitterOnVisualizeBtnClicked called
</code>```

答:
If you are absolutely sure that emitOnVisualizeButtonClicked(param) never gets called to trigger that unwanted call on line 63 then you may want to check if you have more than one subscription happening - perhaps VisOpComponent got constructed before and there is no unsubscribe()?

Other reasoning would be the ReplaySubject itself. When a new subscription occurs, add it to the container and replay the values from the cache if any to the corresponding observer.

You could add an if guard

this.subEvtEmitterOnVisualizeBtnClicked = this._FromAwanti1ToVisOpService.getEmitterOnVisualizeButtonClicked().subscribe((param:number)=>{
  if (!param) return;
  console.log("subEvtEmitterOnVisualizeBtnClicked called")
  this.visulizationOperationID = param
  this.submit()
})
```

Also important to know that ReplaySubject still replays the cached values before sending the complete or the error error notification to new subsequent subscriptions.

Add an buffer size of one new ReplaySubject<number>(1). It can record and replay a whole series of values or one last value if we give (1).

Body:
the problem i have is, every time the component VisOpComponent is initialized, the subscribed eventemitter gets fired without any call to .next(). i also added some console.log as shown below to show you that, despite the
subEvtEmitterOnVisualizeBtnClicked is not initialize but still the log statement in the event subscription can be called and it prints subEvtEmitterOnVisualizeBtnClicked called

please let me know why the event is getting fired without any invokation to .next() and how to fix it

VisOpComponent:

if(this.subEvtEmitterOnVisualizeBtnClicked) {
  if(this.subEvtEmitterOnVisualizeBtnClicked.closed){
    console.log("closed subEvtEmitterOnVisualizeBtnClicked")
  } else {
    console.log("NOT closed subEvtEmitterOnVisualizeBtnClicked")
  }
} else {
  console.log("subEvtEmitterOnVisualizeBtnClicked not initialized")
}

this.subEvtEmitterOnVisualizeBtnClicked = this._FromAwanti1ToVisOpService.getEmitterOnVisualizeButtonClicked().subscribe((param:number)=>{
  console.log("subEvtEmitterOnVisualizeBtnClicked called")
  this.visulizationOperationID = param
  this.submit()
})

eventemitters:

import { Injectable } from '@angular/core';
import { Component, OnInit, EventEmitter, Output } from '@angular/core';
import { BehaviorSubject, Subject,ReplaySubject } from 'rxjs'

@Injectable({
  providedIn: 'root'
})
export class FromAwanti1ToVisOpOfAocAvghInterceptionService {

private emitterOnVisualizeButtonClicked:Subject<number> = new ReplaySubject<number>();

  constructor() { }

  public emitOnVisualizeButtonClicked(param) {
    this.emitterOnVisualizeButtonClicked.next(param)
  }
  public getEmitterOnVisualizeButtonClicked() {
    return this.emitterOnVisualizeButtonClicked.asObservable();
  }

logs:

vis-op.component.ts:45 constructor
vis-op.component.ts:59 subEvtEmitterOnVisualizeBtnClicked not initialized
vis-op.component.ts:63 subEvtEmitterOnVisualizeBtnClicked called

Body:
If you are absolutely sure that emitOnVisualizeButtonClicked(param) never gets called to trigger that unwanted call on line 63 then you may want to check if you have more than one subscription happening - perhaps VisOpComponent got constructed before and there is no unsubscribe()?

Other reasoning would be the ReplaySubject itself. When a new subscription occurs, add it to the container and replay the values from the cache if any to the corresponding observer.

You could add an if guard

this.subEvtEmitterOnVisualizeBtnClicked = this._FromAwanti1ToVisOpService.getEmitterOnVisualizeButtonClicked().subscribe((param:number)=>{
  if (!param) return;
  console.log("subEvtEmitterOnVisualizeBtnClicked called")
  this.visulizationOperationID = param
  this.submit()
})

Also important to know that ReplaySubject still replays the cached values before sending the complete or the error error notification to new subsequent subscriptions.

Add an buffer size of one new ReplaySubject<number>(1). It can record and replay a whole series of values or one last value if we give (1).


问:
Is the "lock" statement in C# time-consuming?
I have a method which has been called many times by other methods to hash data. Inside the method, some lock statements are used. Could you please let me know whether the lock statement is time-consuming and what is the best way to improve it.

P/S: I have been finding a way to avoid using the lock statement in this method.

答:
I landed here for a slightly different question.
In a piece of code that can be run as single threaded or multi threaded shoud I refactor the code to remove the lock statement (i.e. is the lock statement without parallelism costless)?

This is my test

```<code>class Program
{
    static void Main(string[] args)
    {
        var startingTime = DateTime.Now;
        (new Program()).LockMethod();
        Console.WriteLine("Elapsed {0}", (DateTime.Now - startingTime).TotalMilliseconds);
        Console.ReadLine();
    }

    private void LockMethod()
    {
        int a = 0;
        for (int i = 0; i < 10000000; i++)
        {
            lock (this)
            {
                a++; // costless operation
            }
        }
    }
}
</code>```

To be sure that this code is not optimized I decompiled it. No optimizations at all (a++ changed to ++a).

RESULT: 1Mln of not contended locks acquirements takes about 160ms that is about 15ns for acquire a not contended lock.

ContentLicense: CC BY-SA 2.5

Body:
I landed here for a slightly different question.
In a piece of code that can be run as single threaded or multi threaded shoud I refactor the code to remove the lock statement (i.e. is the lock statement without parallelism costless)?

This is my test

class Program
{
    static void Main(string[] args)
    {
        var startingTime = DateTime.Now;
        (new Program()).LockMethod();
        Console.WriteLine("Elapsed {0}", (DateTime.Now - startingTime).TotalMilliseconds);
        Console.ReadLine();
    }

    private void LockMethod()
    {
        int a = 0;
        for (int i = 0; i < 10000000; i++)
        {
            lock (this)
            {
                a++; // costless operation
            }
        }
    }
}

To be sure that this code is not optimized I decompiled it. No optimizations at all (a++ changed to ++a).

RESULT: 1Mln of not contended locks acquirements takes about 160ms that is about 15ns for acquire a not contended lock.


问:
How to restrict dropping draggable elements into a predefined div element?
I am using interact.js and I want to enable dropping of draggable objects inside a predefined div .dropzone, so that dropping outside .dropzone would be disabled. I introduced restriction: ".dropzone", drag: document.getElementById('dropzone'),, however it does not work properly.

I created this JFIDDLE to be more clear (I updated the link, because the old link was not correct).

JavaScript:

```<code>// target elements with the "draggable" class
interact('.draggable').draggable({
    inertia: true,
    restrict: {
      restriction: ".dropzone",
      drag: document.getElementById('dropzone'),
      endOnly: true,
      elementRect: {
        top: 0,
        left: 0,
        bottom: 1,
        right: 1
      }
    },
    autoScroll: true,
    onmove: function(event) {
      var target = event.target;
      var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx;
      var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

      target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';

      target.setAttribute('data-x', x);
      target.setAttribute('data-y', y);
    },
    onend: function(event) {
      console.log(event);
    }
  })
  .on('move', function(event) {
    var interaction = event.interaction;
    if (interaction.pointerIsDown && !interaction.interacting() && event.currentTarget.getAttribute('clonable') != 'false') {
      var original = event.currentTarget;
      var clone = event.currentTarget.cloneNode(true);
      var x = clone.offsetLeft;
      var y = clone.offsetTop;
      clone.setAttribute('clonable', 'false');
      clone.style.position = "absolute";
      clone.style.left = original.offsetLeft + "px";
      clone.style.top = original.offsetTop + "px";
      original.parentElement.appendChild(clone);
      interaction.start({
        name: 'drag'
      }, event.interactable, clone);
    }
  })
  .resizable({
    edges: {
      left: true,
      right: true,
      bottom: true,
      top: true
    }
  })
  .on('resizemove', function(event) {
    var target = event.target;
    x = (parseFloat(target.getAttribute('data-x')) || 0),
      y = (parseFloat(target.getAttribute('data-y')) || 0);

    // update the element's style
    target.style.width = event.rect.width + 'px';
    target.style.height = event.rect.height + 'px';

    // translate when resizing from top or left edges
    x += event.deltaRect.left;
    y += event.deltaRect.top;

    target.style.webkitTransform = target.style.transform =
      'translate(' + x + 'px,' + y + 'px)';

    target.setAttribute('data-x', x);
    target.setAttribute('data-y', y);
    //target.textContent = event.rect.width + '×' + event.rect.height;
  });

// enable draggables to be dropped into this
interact('.dropzone').dropzone({
  // Require a 50% element overlap for a drop to be possible
  overlap: 0.50,

  // listen for drop related events:

  ondropactivate: function(event) {
    // add active dropzone feedback
    event.target.classList.add('drop-active');
  },
  ondragenter: function(event) {
    var draggableElement = event.relatedTarget,
      dropzoneElement = event.target;

    // feedback the possibility of a drop
    dropzoneElement.classList.add('drop-target');
  },
  ondragleave: function(event) {
    // remove the drop feedback style
    event.target.classList.remove('drop-target');
  },
  ondrop: function(event) {
    //event.relatedTarget.textContent = 'Dropped';
  },
  ondropdeactivate: function(event) {
    // remove active dropzone feedback
    event.target.classList.remove('drop-active');
    event.target.classList.remove('drop-target');
  }
});

$(".dropzone").html("<img src='https://s-media-cache-ak0.pinimg.com/originals/fb/d5/55/fbd5556e0e364b31166bebfce433c14e.jpg'>");

function popupBaseDetails(div, e) {
  e.preventDefault();
  div.querySelector(".basepopup").classList.toggle("show");
}
</code>```

CSS:

```<code>.dropzone {
  background-color: #e9ebed;
  padding: 10px;
  width: 100%;
  height: 600px;
  overflow-y: scroll;
  border: dashed 4px transparent;
  float: left;
}

.drop-active {
  border-color: #aaa;
}

.drop-target {
  background-color: #3f5265;
  color: #FFF;
  border-color: #fff;
  border-style: solid;
}
</code>```

HTML:

```<code><div style="height:280px">
  <div id="dropzone" class="dropzone"></div>
</div>
</code>```

答:
You can use restriction modifiers for restricting draggable element to a dropzone:</p>
```<code>interact('.draggable').draggable({
    inertia: true,
    modifiers: [
      interact.modifiers.restrictRect({
        restriction: document.getElementById('dropzone'),
        endOnly: true
      })
    ],
    listeners: {
      start(event) {
        var interaction = event.interaction;
        if (event.currentTarget.getAttribute('clonable') != 'false') {
          var original = event.currentTarget;
          var clone = event.currentTarget.cloneNode(true);
          var x = clone.offsetLeft;
          var y = clone.offsetTop;
          clone.setAttribute('clonable', 'false');
          clone.style.position = "absolute";
          clone.style.left = original.offsetLeft + "px";
          clone.style.top = original.offsetTop + "px";
          original.parentElement.appendChild(clone);
          interaction.start({
            name: 'drag'
          }, event.interactable, clone);
        }
      },
      move(event) {
        var target = event.target;
        var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx;
        var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

        target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';

        target.setAttribute('data-x', x);
        target.setAttribute('data-y', y);
      }
    },
    autoScroll: true
  });
</code>```

Body:
I am using interact.js and I want to enable dropping of draggable objects inside a predefined div .dropzone, so that dropping outside .dropzone would be disabled. I introduced restriction: ".dropzone", drag: document.getElementById('dropzone'),, however it does not work properly.

I created this JFIDDLE to be more clear (I updated the link, because the old link was not correct).

JavaScript:

// target elements with the "draggable" class
interact('.draggable').draggable({
    inertia: true,
    restrict: {
      restriction: ".dropzone",
      drag: document.getElementById('dropzone'),
      endOnly: true,
      elementRect: {
        top: 0,
        left: 0,
        bottom: 1,
        right: 1
      }
    },
    autoScroll: true,
    onmove: function(event) {
      var target = event.target;
      var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx;
      var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

      target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';

      target.setAttribute('data-x', x);
      target.setAttribute('data-y', y);
    },
    onend: function(event) {
      console.log(event);
    }
  })
  .on('move', function(event) {
    var interaction = event.interaction;
    if (interaction.pointerIsDown && !interaction.interacting() && event.currentTarget.getAttribute('clonable') != 'false') {
      var original = event.currentTarget;
      var clone = event.currentTarget.cloneNode(true);
      var x = clone.offsetLeft;
      var y = clone.offsetTop;
      clone.setAttribute('clonable', 'false');
      clone.style.position = "absolute";
      clone.style.left = original.offsetLeft + "px";
      clone.style.top = original.offsetTop + "px";
      original.parentElement.appendChild(clone);
      interaction.start({
        name: 'drag'
      }, event.interactable, clone);
    }
  })
  .resizable({
    edges: {
      left: true,
      right: true,
      bottom: true,
      top: true
    }
  })
  .on('resizemove', function(event) {
    var target = event.target;
    x = (parseFloat(target.getAttribute('data-x')) || 0),
      y = (parseFloat(target.getAttribute('data-y')) || 0);

    // update the element's style
    target.style.width = event.rect.width + 'px';
    target.style.height = event.rect.height + 'px';

    // translate when resizing from top or left edges
    x += event.deltaRect.left;
    y += event.deltaRect.top;

    target.style.webkitTransform = target.style.transform =
      'translate(' + x + 'px,' + y + 'px)';

    target.setAttribute('data-x', x);
    target.setAttribute('data-y', y);
    //target.textContent = event.rect.width + '×' + event.rect.height;
  });

// enable draggables to be dropped into this
interact('.dropzone').dropzone({
  // Require a 50% element overlap for a drop to be possible
  overlap: 0.50,

  // listen for drop related events:

  ondropactivate: function(event) {
    // add active dropzone feedback
    event.target.classList.add('drop-active');
  },
  ondragenter: function(event) {
    var draggableElement = event.relatedTarget,
      dropzoneElement = event.target;

    // feedback the possibility of a drop
    dropzoneElement.classList.add('drop-target');
  },
  ondragleave: function(event) {
    // remove the drop feedback style
    event.target.classList.remove('drop-target');
  },
  ondrop: function(event) {
    //event.relatedTarget.textContent = 'Dropped';
  },
  ondropdeactivate: function(event) {
    // remove active dropzone feedback
    event.target.classList.remove('drop-active');
    event.target.classList.remove('drop-target');
  }
});

$(".dropzone").html("");

function popupBaseDetails(div, e) {
  e.preventDefault();
  div.querySelector(".basepopup").classList.toggle("show");
}

CSS:

.dropzone {
  background-color: #e9ebed;
  padding: 10px;
  width: 100%;
  height: 600px;
  overflow-y: scroll;
  border: dashed 4px transparent;
  float: left;
}

.drop-active {
  border-color: #aaa;
}

.drop-target {
  background-color: #3f5265;
  color: #FFF;
  border-color: #fff;
  border-style: solid;
}

HTML:

Body:
You can use restriction modifiers for restricting draggable element to a dropzone:

interact('.draggable').draggable({
    inertia: true,
    modifiers: [
      interact.modifiers.restrictRect({
        restriction: document.getElementById('dropzone'),
        endOnly: true
      })
    ],
    listeners: {
      start(event) {
        var interaction = event.interaction;
        if (event.currentTarget.getAttribute('clonable') != 'false') {
          var original = event.currentTarget;
          var clone = event.currentTarget.cloneNode(true);
          var x = clone.offsetLeft;
          var y = clone.offsetTop;
          clone.setAttribute('clonable', 'false');
          clone.style.position = "absolute";
          clone.style.left = original.offsetLeft + "px";
          clone.style.top = original.offsetTop + "px";
          original.parentElement.appendChild(clone);
          interaction.start({
            name: 'drag'
          }, event.interactable, clone);
        }
      },
      move(event) {
        var target = event.target;
        var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx;
        var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

        target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';

        target.setAttribute('data-x', x);
        target.setAttribute('data-y', y);
      }
    },
    autoScroll: true
  });


问:
How to stop ´enumerateChildNodesWithName("//*") ´ enumeration?
How do I stop this enumeration? I have the following code and Xcode complaining that I cannot assign a value to let constant. Stopping is probably a simple thing but I'm quite the noobie with Swift, so please bear with me.</p>

```<code>self.enumerateChildNodesWithName("//*") {
        spaceshipNode, stop in
        if (( spaceshipNode.name?.hasSuffix("ship") ) != nil) {
            for enemyNode in self.children {
                if (enemyNode.name == "enemy"){
                    if(enemyNode.containsPoint(spaceshipNode.position)){
                        self.gotoGameOverScene(spaceshipNode)
                        stop = true // Error: Cannot assign to value: 'stop' is a 'let' constant
                    }
                }
            }
        }
    }
</code>```

答: Apple's documentation suggests that we stop enumeration via stop.initialize(to: true).

Body:
How do I stop this enumeration? I have the following code and Xcode complaining that I cannot assign a value to let constant. Stopping is probably a simple thing but I'm quite the noobie with Swift, so please bear with me.

self.enumerateChildNodesWithName("//*") {
        spaceshipNode, stop in
        if (( spaceshipNode.name?.hasSuffix("ship") ) != nil) {
            for enemyNode in self.children {
                if (enemyNode.name == "enemy"){
                    if(enemyNode.containsPoint(spaceshipNode.position)){
                        self.gotoGameOverScene(spaceshipNode)
                        stop = true // Error: Cannot assign to value: 'stop' is a 'let' constant
                    }
                }
            }
        }
    }


问:
CSV does not load to Google BigQuery
So I made a program that'll get the schema from a table in a MySQL Server, create a table based on the said schema, and insert the data rows which are saved in a  CSV file in a Google Cloud Storage.

Code for getting the schema from MySQL:

foreach (string table in listOfTableNames)
   {
      MySqlCommand query = new MySqlCommand($"desc {table}", openedMySQLConnection);
      MySqlDataReader reader = query.ExecuteReader();

      DataTable dt = new DataTable(table);
      dt.Load(reader);
      reader.Close();
      object[][] result = dt.AsEnumerable().Select(x => x.ItemArray).ToArray();
      TableSchemas.Add(table, result);
   }
```
<hr />
<p>Google BigQuery table maker from schema looped per table:</p>
<pre class="lang-cs prettyprint-override"><code>var schemaBuilder = new TableSchemaBuilder();
foreach (var column in dictionaryOfSchemas[myTablename])
{
   string columnType = column[1].ToString().ToLower();
   schemaBuilder.Add(
      column[0].ToString(),
      columnType.Contains("varchar") ? BigQueryDbType.String :
         (columnType.Contains("int") ? BigQueryDbType.Int64 :
         (columnType.Contains("decimal") ? BigQueryDbType.Float64 :
         (columnType.Contains("timestamp") ? BigQueryDbType.DateTime :
         (columnType.Contains("datetime") ? BigQueryDbType.DateTime :
         (columnType.Contains("date") ? BigQueryDbType.Date :
         BigQueryDbType.String)))))
   );
}
TableSchema schema = schemaBuilder.Build();
BigQueryTable newTable = bigquery.GetDataset(myDataset).CreateTable(myTablename, schema);
</code>```

CSV to created GBQ table looped per table:

    bigquery.CreateLoadJob(
       $"gs://{myProjectIdString}/{myBucketNameString}/{myCSVFilename}",
       newTable.Reference,
       schema,
       new CreateLoadJobOptions()
       {
           SourceFormat = FileFormat.Csv,
           SkipLeadingRows = 1
       }
    ).PollUntilCompleted();
```

No error shows up after running the CreateLoadJob method.

Schema of the new table seems to be good and matches the CSV and the MySQL table:

Here's a sneak peak into the CSV file in Cloud Storage with some data redacted out:

But there's still no data in the table:

Am I doing something wrong? I'm still learning Google services so any help and insight would be appreciated. :)

答:
There are a few things wrong here, but it's mostly to do with the data rather than with the code itself.

In terms of code, when a job has completed, it may still have completed with errors. You can call ThrowOnAnyError() to observe that. You can get detailed errors via job.Resource.Status.Errors. (I believe the first of those detailed errors is the one in job.Resource.Status.ErrorResults.)

Once the correct storage URL is provided (which would be observed that way as well) you'll see errors like this, with the CSV file you provided:

Error while reading data, error message: CSV processing encountered too many errors, giving up. Rows: 1; errors: 1; max bad: 0; error percent: 0

Could not parse '06/12/2014' as DATE for field delivery_date (position 0) starting at location 95  with message 'Unable to parse'

At that point, the problem is in your CSV file. There are two issues here:

The date format is expected to be ISO-8601, e.g. "2014-06-12" rather than "06/12/2014" for example

The date/time format is expected to include seconds as well, so "2014-05-12 12:37:00" rather than "05/12/2014 12:37" for example

Hopefully you're able to run a preprocessing job to fix the data in your CSV file.

This is assuming that the schema you've created is correct, of course - we can't tell that from your post, but here's the schema that worked for me:

var schema = new TableSchemaBuilder
{
    { "delivery_date", BigQueryDbType.Date },
    { "delivery_hour", BigQueryDbType.Int64 },
    { "participant_id", BigQueryDbType.String },
    { "resource_id", BigQueryDbType.String },
    { "type_id", BigQueryDbType.String },
    { "price", BigQueryDbType.Numeric },
    { "date_posted", BigQueryDbType.DateTime },
    { "date_created", BigQueryDbType.DateTime }
}.Build();
```

Title: CSV does not load to Google BigQuery

Body:
So I made a program that'll get the schema from a table in a MySQL Server, create a table based on the said schema, and insert the data rows which are saved in a  CSV file in a Google Cloud Storage.

Code for getting the schema from MySQL:

foreach (string table in listOfTableNames)
   {
      MySqlCommand query = new MySqlCommand($"desc {table}", openedMySQLConnection);
      MySqlDataReader reader = query.ExecuteReader();

      DataTable dt = new DataTable(table);
      dt.Load(reader);
      reader.Close();
      object[][] result = dt.AsEnumerable().Select(x => x.ItemArray).ToArray();
      TableSchemas.Add(table, result);
   }

Google BigQuery table maker from schema looped per table:

var schemaBuilder = new TableSchemaBuilder();
foreach (var column in dictionaryOfSchemas[myTablename])
{
   string columnType = column[1].ToString().ToLower();
   schemaBuilder.Add(
      column[0].ToString(),
      columnType.Contains("varchar") ? BigQueryDbType.String :
         (columnType.Contains("int") ? BigQueryDbType.Int64 :
         (columnType.Contains("decimal") ? BigQueryDbType.Float64 :
         (columnType.Contains("timestamp") ? BigQueryDbType.DateTime :
         (columnType.Contains("datetime") ? BigQueryDbType.DateTime :
         (columnType.Contains("date") ? BigQueryDbType.Date :
         BigQueryDbType.String)))))
   );
}
TableSchema schema = schemaBuilder.Build();
BigQueryTable newTable = bigquery.GetDataset(myDataset).CreateTable(myTablename, schema);

CSV to created GBQ table looped per table:

    bigquery.CreateLoadJob(
       $"gs://{myProjectIdString}/{myBucketNameString}/{myCSVFilename}",
       newTable.Reference,
       schema,
       new CreateLoadJobOptions()
       {
           SourceFormat = FileFormat.Csv,
           SkipLeadingRows = 1
       }
    ).PollUntilCompleted();

No error shows up after running the CreateLoadJob method.

Schema of the new table seems to be good and matches the CSV and the MySQL table:

Here's a sneak peak into the CSV file in Cloud Storage with some data redacted out:

But there's still no data in the table:

Am I doing something wrong? I'm still learning Google services so any help and insight would be appreciated. :)


问:
Cloud Storage - No 'Access-Control-Allow-Origin' header is present on the requested resource for AngularJS view
According to Chrome dev tools, my requests to get my html partials have the origin header https://site-name-here.com and request header GET.

I have the following JSON file set to my bucket:

```<code>[
    {
      "origin": ["https://site-name-here.com"],
      "responseHeader": ["content-type"],
      "method": ["GET"],
      "maxAgeSeconds": 3600
    }
]
</code>```

However, whenever angular tries to get the view, I get the following error: XMLHttpRequest cannot load https://storage.googleapis.com/bucket-name/view-path.html?. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://site-name-here.com' is therefore not allowed access.

I am also serving javascript and css files from Cloud Storage, but they're working fine, I assume because CSS doesn't have CORS restrictions and I'm using $sceDelegateProvider.resourceUrlWhitelist() in Angular for the scripts?

Edit: Working now, I'm assuming something was cached and it was serving me an old version.

答:
The problem might not be from the CORS configuration but from other errors being masked by CORS error.

To rule out problems with your configuration, check the CORS configuration of your bucket with this command - gsutil cors get gs://BUCKET_NAME. If your configuration is visible, then it's definitely not a configuration issue.

On the other hand, CORS might be masking other 4xx or 5xx errors returned by Cloud storage. This is because errors returned by Cloud storage do not have the access control headers set.

To see the real 4xx and 5xx errors on your browser, Try to disable the CORS check. A lot of plugins can assist with disabling CORS on Chrome.

Body:
According to Chrome dev tools, my requests to get my html partials have the origin header https://site-name-here.com and request header GET.

I have the following JSON file set to my bucket:

[
    {
      "origin": ["https://site-name-here.com"],
      "responseHeader": ["content-type"],
      "method": ["GET"],
      "maxAgeSeconds": 3600
    }
]

However, whenever angular tries to get the view, I get the following error: XMLHttpRequest cannot load https://storage.googleapis.com/bucket-name/view-path.html?. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://site-name-here.com' is therefore not allowed access.

I am also serving javascript and css files from Cloud Storage, but they're working fine, I assume because CSS doesn't have CORS restrictions and I'm using $sceDelegateProvider.resourceUrlWhitelist() in Angular for the scripts?

Edit: Working now, I'm assuming something was cached and it was serving me an old version.


问:
PC freezes totally while accessing physical memory on Ubuntu 10.04(64-bit machine)
I am trying to access the physical memory of my PC using this program which uses mmap()-

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/mman.h>

#define FATAL do { fprintf(stderr, "Error at line %d, file %s (%d) [%s]\n", \
  __LINE__, __FILE__, errno, strerror(errno)); exit(1); } while(0)

#define MAP_SIZE 4096UL
#define MAP_MASK (MAP_SIZE - 1)

int main(int argc, char **argv) {
    int fd;
    void *map_base, *virt_addr;
    unsigned long read_result, writeval;
    off_t target;
    int access_type = 'w';

    if(argc < 2) {
        fprintf(stderr, "\nUsage:\t%s { address } [ type [ data ] ]\n"
            "\taddress : memory address to act upon\n"
            "\ttype    : access operation type : [b]yte, [h]alfword, [w]ord\n"
            "\tdata    : data to be written\n\n",
            argv[0]);
        exit(1);
    }
    target = strtoul(argv[1], 0, 0);

    if(argc > 2)
        access_type = tolower(argv[2][0]);

    if((fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1) FATAL;
    printf("/dev/mem opened.\n");
    fflush(stdout);

    /* Map one page */
    map_base = mmap(0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, target & ~MAP_MASK);
    if(map_base == (void *) -1) FATAL;
    printf("Memory mapped at address %p.\n", map_base);
    fflush(stdout);

    virt_addr = map_base + (target & MAP_MASK);
    switch(access_type) {
        case 'b':
            read_result = *((unsigned char *) virt_addr);
            break;
        case 'h':
            read_result = *((unsigned short *) virt_addr);
            break;
        case 'w':
            read_result = *((unsigned long *) virt_addr);
            break;
        default:
            fprintf(stderr, "Illegal data type '%c'.\n", access_type);
            exit(2);
    }
    printf("Value at address 0x%X (%p): 0x%X\n", target, virt_addr, read_result);
    fflush(stdout);

    if(argc > 3) {
        writeval = strtoul(argv[3], 0, 0);
        switch(access_type) {
            case 'b':
                *((unsigned char *) virt_addr) = writeval;
                read_result = *((unsigned char *) virt_addr);
                break;
            case 'h':
                *((unsigned short *) virt_addr) = writeval;
                read_result = *((unsigned short *) virt_addr);
                break;
            case 'w':
                *((unsigned long *) virt_addr) = writeval;
                read_result = *((unsigned long *) virt_addr);
                break;
        }
        printf("Written 0x%X; readback 0x%X\n", writeval, read_result);
        fflush(stdout);
    }

    if(munmap(map_base, MAP_SIZE) == -1) FATAL;
    close(fd);
    return 0;
}
</code>```

When I run this program as sudo ./a.out 0xfdff8000, my system simply hangs. Mouse, keyboard, display everything freeze! Restart is the only option. I checked for 0xfdff8000 in /proc/iomem. It corresponds to ICH HD audio. I am not sure what this means.
Also kmsg, dmesg and /var/log/messages are not throwing any hints!

答:
You should not be accessing physical memory directly. What is likely happening is that a page table entry is set up with that address that's a memory mapped pointer to a device. Reading from it without permission will crash the system as it will send the OS an interrupt error that it is not expecting.

Remember that physical addresses and virtual addresses are completely different. The addresses which your program reads are all virtual and I believe the only way to get the physical address (which you cannot access unless mapped) is to do a linear address conversion which is hardware dependent (for example x86 kernel function convert_ip_to_linear).

The likely crash cause is unsafe access because drivers usually run one ring level higher than userspace and you are causing an access violation trying to read that from userspace instead of driver level space.

Body:
I am trying to access the physical memory of my PC using this program which uses mmap()-

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/mman.h>

#define FATAL do { fprintf(stderr, "Error at line %d, file %s (%d) [%s]\n", \
  __LINE__, __FILE__, errno, strerror(errno)); exit(1); } while(0)

#define MAP_SIZE 4096UL
#define MAP_MASK (MAP_SIZE - 1)

int main(int argc, char **argv) {
    int fd;
    void *map_base, *virt_addr;
    unsigned long read_result, writeval;
    off_t target;
    int access_type = 'w';

    if(argc < 2) {
        fprintf(stderr, "\nUsage:\t%s { address } [ type [ data ] ]\n"
            "\taddress : memory address to act upon\n"
            "\ttype    : access operation type : [b]yte, [h]alfword, [w]ord\n"
            "\tdata    : data to be written\n\n",
            argv[0]);
        exit(1);
    }
    target = strtoul(argv[1], 0, 0);

    if(argc > 2)
        access_type = tolower(argv[2][0]);

    if((fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1) FATAL;
    printf("/dev/mem opened.\n");
    fflush(stdout);

    /* Map one page */
    map_base = mmap(0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, target & ~MAP_MASK);
    if(map_base == (void *) -1) FATAL;
    printf("Memory mapped at address %p.\n", map_base);
    fflush(stdout);

    virt_addr = map_base + (target & MAP_MASK);
    switch(access_type) {
        case 'b':
            read_result = *((unsigned char *) virt_addr);
            break;
        case 'h':
            read_result = *((unsigned short *) virt_addr);
            break;
        case 'w':
            read_result = *((unsigned long *) virt_addr);
            break;
        default:
            fprintf(stderr, "Illegal data type '%c'.\n", access_type);
            exit(2);
    }
    printf("Value at address 0x%X (%p): 0x%X\n", target, virt_addr, read_result);
    fflush(stdout);

    if(argc > 3) {
        writeval = strtoul(argv[3], 0, 0);
        switch(access_type) {
            case 'b':
                *((unsigned char *) virt_addr) = writeval;
                read_result = *((unsigned char *) virt_addr);
                break;
            case 'h':
                *((unsigned short *) virt_addr) = writeval;
                read_result = *((unsigned short *) virt_addr);
                break;
            case 'w':
                *((unsigned long *) virt_addr) = writeval;
                read_result = *((unsigned long *) virt_addr);
                break;
        }
        printf("Written 0x%X; readback 0x%X\n", writeval, read_result);
        fflush(stdout);
    }

    if(munmap(map_base, MAP_SIZE) == -1) FATAL;
    close(fd);
    return 0;
}

When I run this program as sudo ./a.out 0xfdff8000, my system simply hangs. Mouse, keyboard, display everything freeze! Restart is the only option. I checked for 0xfdff8000 in /proc/iomem. It corresponds to ICH HD audio. I am not sure what this means.
Also kmsg, dmesg and /var/log/messages are not throwing any hints!


问:
Volume is already exclusively attached to one node and can't be attached to another
I have a pretty simple Kubernetes pod. I want a stateful set and want the following process:

I want to have an initcontainer download and uncompress a tarball from s3 into a volume mounted to the initcontainer

I want to mount that volume to my main container to be used

```<code>apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: app
  namespace: test
  labels:
    name: app
spec:
  serviceName: app
  replicas: 1
  selector:
    matchLabels:
      app: app
  template:
    metadata:
      labels:
        app: app
    spec:
      initContainers:
      - name: preparing
        image: alpine:3.8
        imagePullPolicy: IfNotPresent
        command:
          - "sh"
          - "-c"
          - |
            echo "Downloading data"
            wget https://s3.amazonaws.com/.........
            tar -xvzf xxxx-........ -C /root/
        volumeMounts:
        - name: node-volume
          mountPath: /root/data/

      containers:
      - name: main-container
        image: ecr.us-west-2.amazonaws.com/image/:latest
        imagePullPolicy: Always

        volumeMounts:
        - name: node-volume
          mountPath: /root/data/

  volumeClaimTemplates:
  - metadata:
      name: node-volume
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: gp2-b
      resources:
        requests:
          storage: 80Gi
</code>```

I continue to get the following error:

At first I run this and I can see the logs flowing of my tarball being downloaded by the initcontainer. About half way done it terminates and gives me the following error:

```<code>Multi-Attach error for volume "pvc-faedc8" Volume is
already exclusively attached to one node and can't be
attached to another
</code>```

答: I had the same issue right now and the problem was, that the node on which the pod is usually running on was down and another one took over (which didn't work as expected for whatever reason). Had the "node down" scenario a few times before already and it never caused any issues. Couldn't get the StatefulSet and Deployment back up and running without booting the node that was down. But as soon as the node was up and running again the StatefulSet and Deployment immediately came back to life as well.</p>

Body:
I have a pretty simple Kubernetes pod. I want a stateful set and want the following process:

I want to have an initcontainer download and uncompress a tarball from s3 into a volume mounted to the initcontainer

I want to mount that volume to my main container to be used

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: app
  namespace: test
  labels:
    name: app
spec:
  serviceName: app
  replicas: 1
  selector:
    matchLabels:
      app: app
  template:
    metadata:
      labels:
        app: app
    spec:
      initContainers:
      - name: preparing
        image: alpine:3.8
        imagePullPolicy: IfNotPresent
        command:
          - "sh"
          - "-c"
          - |
            echo "Downloading data"
            wget https://s3.amazonaws.com/.........
            tar -xvzf xxxx-........ -C /root/
        volumeMounts:
        - name: node-volume
          mountPath: /root/data/

      containers:
      - name: main-container
        image: ecr.us-west-2.amazonaws.com/image/:latest
        imagePullPolicy: Always

        volumeMounts:
        - name: node-volume
          mountPath: /root/data/

  volumeClaimTemplates:
  - metadata:
      name: node-volume
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: gp2-b
      resources:
        requests:
          storage: 80Gi

I continue to get the following error:

At first I run this and I can see the logs flowing of my tarball being downloaded by the initcontainer. About half way done it terminates and gives me the following error:

Multi-Attach error for volume "pvc-faedc8" Volume is
already exclusively attached to one node and can't be
attached to another


问:
MotionLayout jump to end ConstraintSet programmatically
There is an option to jump to end ConstraintSet in XML in MotionLayout.

```<code><Transition
    app:autoTransition="jumpToEnd"
    motion:constraintSetEnd="@+id/constraintStart"
    motion:constraintSetStart="@+id/constraintEnd"
    motion:duration="300" />
</code>```

Can this be done programmatically?

答: Use the setProgress to 1f method did take effect ,but I can not receive the onTransitionCompleted event in TransitionListener</p>

Body:
There is an option to jump to end ConstraintSet in XML in MotionLayout.

<Transition
    app:autoTransition="jumpToEnd"
    motion:constraintSetEnd="@+id/constraintStart"
    motion:constraintSetStart="@+id/constraintEnd"
    motion:duration="300" />

Can this be done programmatically?


问:
Program took more time than expected error
Below is a program to reverse a doubly linked list in gfg.

When I try to submit, I get the following error

Your program took more time than expected. Time Limit Exceeded
Expected Time Limit 0.00sec.

Can anyone tell me how to decrease my program's time?

Code

```<code>public static Node reverseDLL(Node  head)
{
   Node p,cur;
   p=head;
   cur=head.next;

   while(cur!=null)
   {
       if(cur.next==null)
       {
           p.next=cur.next;
           cur.next=head;
           head.prev=cur;

           head=cur;
           break;
       }

       p.next=cur.next;
       cur.next.prev=p;

       cur.next=head;
       head.prev=cur;

       head=cur;
       cur=p.next;
   }
   return head;

}
</code>```

答:
Your code is not correct:

The prev member of the (original) tail node is not set correctly. It is not set in the if block, but in the previous iteration, where it got its value with cur.next.prev=p, which is setting it to the (original) head node. This creates an infinite loop in the data structure. In the end, none of the prev links is null. It might be that the testing framework keeps following those prev links in circles until a time out happens.

Also, the function assumes that head is not null. This may not be guaranteed.

There are also too many assignments happening. With a doubly linked list it is quite simple: just swap the value of next and prev in every node:

```<code>public static Node reverseDLL(Node  head)
{
    if (head == null) {
        return null;
    }
    Node next = head.next;
    while (next != null) {
        head.next = head.prev;
        head.prev = next;
        head = next;
        next = head.next;
    }
    head.next = head.prev;
    head.prev = null;
    return head;
}
</code>```

Body:
Below is a program to reverse a doubly linked list in gfg.

When I try to submit, I get the following error

Your program took more time than expected. Time Limit Exceeded
Expected Time Limit 0.00sec.

Can anyone tell me how to decrease my program's time?

Code

public static Node reverseDLL(Node  head)
{
   Node p,cur;
   p=head;
   cur=head.next;

   while(cur!=null)
   {
       if(cur.next==null)
       {
           p.next=cur.next;
           cur.next=head;
           head.prev=cur;

           head=cur;
           break;
       }

       p.next=cur.next;
       cur.next.prev=p;

       cur.next=head;
       head.prev=cur;

       head=cur;
       cur=p.next;
   }
   return head;

}

Body:
Your code is not correct:

The prev member of the (original) tail node is not set correctly. It is not set in the if block, but in the previous iteration, where it got its value with cur.next.prev=p, which is setting it to the (original) head node. This creates an infinite loop in the data structure. In the end, none of the prev links is null. It might be that the testing framework keeps following those prev links in circles until a time out happens.

Also, the function assumes that head is not null. This may not be guaranteed.

There are also too many assignments happening. With a doubly linked list it is quite simple: just swap the value of next and prev in every node:

public static Node reverseDLL(Node  head)
{
    if (head == null) {
        return null;
    }
    Node next = head.next;
    while (next != null) {
        head.next = head.prev;
        head.prev = next;
        head = next;
        next = head.next;
    }
    head.next = head.prev;
    head.prev = null;
    return head;
}


问:
How to 1). put a div , 2). render a component without Route inside <Routes> with React Router in v6 React?
I want to put a div inside <Routes>  and also Render a <Topbar /> and <Sidebar /> component inside <Routes> without <Route> tag for them.

My code is as follows:-

```<code>const App = () => {
  return (
    <Router>
      <Routes>
        <Route path="login" element={<Login />} />
        <Topbar />
        <div className="container">
          <Sidebar />
          <Route path="/" element={<Home />} />
          <Route path="users" element={<UserList />} />
        </div>
      </Routes>
    </Router>
  );
};
</code>```

I want to implement <Topbar /> and <Sidebar /> for all the routes.
But for an exception of login Page (Topbar and Sidebar should not be shown on the login page).
That's why I had put login Route at the top of Topbar and Sidebar.

The console is showing error as:

Uncaught Error: [Topbar] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

How to implement this functionality?

答:
Change your routes like below,

you need to check whether user is logged in or not, if user logged in use Tobbar, Sidebar etc, otherwise just return login route

```<code>  const App = () => {
  const [isLogin, setIsLogin] = useState(false)

   return (
    <Router>
    <Routes>
   { isLogin ? <Topbar />
     <div className="container">
       <Sidebar />
      <Route path="/" element={<Home />} />
      <Route path="users" element={<UserList />} />
    </div> : <Route path="login" element={<Login />} />

  </Routes>
  </Router>
);
};
</code>```

Body:
I want to put a div inside <Routes>  and also Render a <Topbar /> and <Sidebar /> component inside <Routes> without <Route> tag for them.

My code is as follows:-

const App = () => {
  return (
    <Router>
      <Routes>
        <Route path="login" element={<Login />} />
        <Topbar />

          <Sidebar />
          <Route path="/" element={<Home />} />
          <Route path="users" element={<UserList />} />

      </Routes>
    </Router>
  );
};

I want to implement <Topbar /> and <Sidebar /> for all the routes.
But for an exception of login Page (Topbar and Sidebar should not be shown on the login page).
That's why I had put login Route at the top of Topbar and Sidebar.

The console is showing error as:

Uncaught Error: [Topbar] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

How to implement this functionality?

Body:
Change your routes like below,

you need to check whether user is logged in or not, if user logged in use Tobbar, Sidebar etc, otherwise just return login route

  const App = () => {
  const [isLogin, setIsLogin] = useState(false)

   return (
    <Router>
    <Routes>
   { isLogin ? <Topbar />
     <div className="container">
       <Sidebar />
      <Route path="/" element={<Home />} />
      <Route path="users" element={<UserList />} />
    </div> : <Route path="login" element={<Login />} />

  </Routes>
  </Router>
);
};