问:
ReadOnlySequence – Slice to given SequencePosition + 1
I try to read some data from a ReadOnlySequence. The data are formatted as frames. Each frame is terminated by a NULL byte (octet 0).

My code searches for the end of a frame using ReadOnlySequence.PositionOf. When it finds a NULL byte, it will process all bytes up to the position of the NULL byte. After processing I would like to process the next frame by slicing the input and repeat the previous steps.
Since the frame ended before the NULL byte, the NULL byte would be part of the next sequence of bytes if I wouldn’t slice the input data again (start = 1).

Is there a way to slice a ReadOnlySequence with a SequencePosition + 1 item/byte as start value?

I tried to use SequencePosition.GetInteger + 1 as start value, but that does not work since GetInteger sometimes returns values larger then the length of the ReadOnlySequence. Slicing to the value returned by GetInteger results in the following exception: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. (Parameter 'start')

Minimal Reproducible Example

```<code>using System;
using System.Buffers;
using System.IO.Pipelines;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class Program
    {
        private static IDuplexPipe _pipe;

        public static async Task Main( String[] args )
        {
            var pipe = new Pipe();
            _pipe = new DuplexPipe( pipe.Reader, pipe.Writer );

            var firstMessage = Encoding.UTF8.GetBytes( "CONNECTED\nversion:1.1\nsession:2a840965\nserver:ActiveMQ-Artemis/2.8.0 ActiveMQ Artemis Messaging Engine\nheart-beat:10000,10000\n\n\0\n" );
            await _pipe.Output.WriteAsync( firstMessage );
            await _pipe.Output.FlushAsync();

            var secondMessage =
                Encoding.UTF8.GetBytes(
                    "\n\nMESSAGE\nsubscription:test-839c7766-0f38-4579-a3fc-74de35408536Sub1\ncontent-length:4\nmessage-id:2147486350\ndestination:/queue/TestQ\nexpires:1572278642017\nredelivered:false\npriority:5\npersistent:true\ntimestamp:1572278582050\ndestination-type:ANYCAST\nreceipt:2\ntest:test\nNMSXDeliveryMode:true\ntransformation:jms-byte\ntimestamp:1572278582017\n\nHello World\0\n" );
            await _pipe.Output.WriteAsync( secondMessage );
            await _pipe.Output.FlushAsync();

            var readResult = await _pipe.Input.ReadAsync();
            var buffer = readResult.Buffer;
            while ( TryParseFrame( ref buffer ) )
            {
                // ...
            }

            _pipe.Input.AdvanceTo( buffer.Start, buffer.End );

            Console.ReadLine();
        }

        private static Boolean TryParseFrame( ref ReadOnlySequence<Byte> inputBuffer )
        {
            var endOfFrame = inputBuffer.PositionOf( ByteConstants.Null );
            if ( endOfFrame == null )
                return false;

            var frameBuffer = inputBuffer.Slice( 0, endOfFrame.Value );
            // parse and process the frame...

            // This works....
            //inputBuffer = inputBuffer.Slice( frameBuffer.End );
            //inputBuffer = inputBuffer.Slice( 1 );

            // This does NOT.
            try
            {
                var end = frameBuffer.End.GetInteger();
                var length = inputBuffer.Length;
                Console.WriteLine( $" END: {end}, LENGTH: {length} " );
                inputBuffer = inputBuffer.Slice( end + 1 );
            }
            catch ( Exception ex )
            {
                Console.WriteLine( ex );
                // Make sure we can read the next frame...
                inputBuffer = inputBuffer.Slice( frameBuffer.End );
                inputBuffer = inputBuffer.Slice( 1 );
            }

            return true;
        }
    }

    public class DuplexPipe : IDuplexPipe
    {
        public DuplexPipe( PipeReader input, PipeWriter output )
        {
            Input = input;
            Output = output;
        }

        public PipeReader Input { get; }
        public PipeWriter Output { get; }
    }

    public static class ByteConstants
    {
        public const Byte HeaderDelimiter = 58;
        public const Byte LineFeed = 10;
        public const Byte Null = 0;
    }
}
</code>```

答:
I had a play with pipes recently, and quickly gave up on manipulating the SequencePosition constructs.

ReadOnlySequence exposes a GetPosition(Int64, SequencePosition) method, where the first argument is an offset (how far to read along) starting at the provided SequencePosition (in your case the position returned for the terminating null-byte).

Consider the following:

```<code>private static bool TryParseFrame(ref ReadOnlySequence<byte> inputBuffer)
{
    var endOfFrame = inputBuffer.PositionOf(ByteConstants.Null);
    if (endOfFrame == null)
        return false;

    // Get SequencePosition 1 place after endOfFrame
    var sliceEnd = inputBuffer.GetPosition(1, endOfFrame.Value);

    inputBuffer = inputBuffer.Slice(0, sliceEnd);

    return true;
}
</code>```

Not sure if the above is exactly what you're looking for, but hopefully GetPosition() is will help you out.

Disclaimer: I don't know what happens if your offset falls outside of the ReadOnlySequence, but I imagine you'd have problems when trying to slice the buffer. In your specific case, however, you already know that the byte is there.

Body:
I try to read some data from a ReadOnlySequence. The data are formatted as frames. Each frame is terminated by a NULL byte (octet 0).

My code searches for the end of a frame using ReadOnlySequence.PositionOf. When it finds a NULL byte, it will process all bytes up to the position of the NULL byte. After processing I would like to process the next frame by slicing the input and repeat the previous steps.
Since the frame ended before the NULL byte, the NULL byte would be part of the next sequence of bytes if I wouldn’t slice the input data again (start = 1).

Is there a way to slice a ReadOnlySequence with a SequencePosition + 1 item/byte as start value?

I tried to use SequencePosition.GetInteger + 1 as start value, but that does not work since GetInteger sometimes returns values larger then the length of the ReadOnlySequence. Slicing to the value returned by GetInteger results in the following exception: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. (Parameter 'start')

Minimal Reproducible Example

using System;
using System.Buffers;
using System.IO.Pipelines;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class Program
    {
        private static IDuplexPipe _pipe;

        public static async Task Main( String[] args )
        {
            var pipe = new Pipe();
            _pipe = new DuplexPipe( pipe.Reader, pipe.Writer );

            var firstMessage = Encoding.UTF8.GetBytes( "CONNECTED\nversion:1.1\nsession:2a840965\nserver:ActiveMQ-Artemis/2.8.0 ActiveMQ Artemis Messaging Engine\nheart-beat:10000,10000\n\n\0\n" );
            await _pipe.Output.WriteAsync( firstMessage );
            await _pipe.Output.FlushAsync();

            var secondMessage =
                Encoding.UTF8.GetBytes(
                    "\n\nMESSAGE\nsubscription:test-839c7766-0f38-4579-a3fc-74de35408536Sub1\ncontent-length:4\nmessage-id:2147486350\ndestination:/queue/TestQ\nexpires:1572278642017\nredelivered:false\npriority:5\npersistent:true\ntimestamp:1572278582050\ndestination-type:ANYCAST\nreceipt:2\ntest:test\nNMSXDeliveryMode:true\ntransformation:jms-byte\ntimestamp:1572278582017\n\nHello World\0\n" );
            await _pipe.Output.WriteAsync( secondMessage );
            await _pipe.Output.FlushAsync();

            var readResult = await _pipe.Input.ReadAsync();
            var buffer = readResult.Buffer;
            while ( TryParseFrame( ref buffer ) )
            {
                // ...
            }

            _pipe.Input.AdvanceTo( buffer.Start, buffer.End );

            Console.ReadLine();
        }

        private static Boolean TryParseFrame( ref ReadOnlySequence<Byte> inputBuffer )
        {
            var endOfFrame = inputBuffer.PositionOf( ByteConstants.Null );
            if ( endOfFrame == null )
                return false;

            var frameBuffer = inputBuffer.Slice( 0, endOfFrame.Value );
            // parse and process the frame...

            // This works....
            //inputBuffer = inputBuffer.Slice( frameBuffer.End );
            //inputBuffer = inputBuffer.Slice( 1 );

            // This does NOT.
            try
            {
                var end = frameBuffer.End.GetInteger();
                var length = inputBuffer.Length;
                Console.WriteLine( $" END: {end}, LENGTH: {length} " );
                inputBuffer = inputBuffer.Slice( end + 1 );
            }
            catch ( Exception ex )
            {
                Console.WriteLine( ex );
                // Make sure we can read the next frame...
                inputBuffer = inputBuffer.Slice( frameBuffer.End );
                inputBuffer = inputBuffer.Slice( 1 );
            }

            return true;
        }
    }

    public class DuplexPipe : IDuplexPipe
    {
        public DuplexPipe( PipeReader input, PipeWriter output )
        {
            Input = input;
            Output = output;
        }

        public PipeReader Input { get; }
        public PipeWriter Output { get; }
    }

    public static class ByteConstants
    {
        public const Byte HeaderDelimiter = 58;
        public const Byte LineFeed = 10;
        public const Byte Null = 0;
    }
}

Body:
I had a play with pipes recently, and quickly gave up on manipulating the SequencePosition constructs.

ReadOnlySequence exposes a GetPosition(Int64, SequencePosition) method, where the first argument is an offset (how far to read along) starting at the provided SequencePosition (in your case the position returned for the terminating null-byte).

Consider the following:

private static bool TryParseFrame(ref ReadOnlySequence<byte> inputBuffer)
{
    var endOfFrame = inputBuffer.PositionOf(ByteConstants.Null);
    if (endOfFrame == null)
        return false;

    // Get SequencePosition 1 place after endOfFrame
    var sliceEnd = inputBuffer.GetPosition(1, endOfFrame.Value);

    inputBuffer = inputBuffer.Slice(0, sliceEnd);

    return true;
}

Not sure if the above is exactly what you're looking for, but hopefully GetPosition() is will help you out.

Disclaimer: I don't know what happens if your offset falls outside of the ReadOnlySequence, but I imagine you'd have problems when trying to slice the buffer. In your specific case, however, you already know that the byte is there.


来源: stackexchange

问:
Flutter : Scrolled Stack Widget

I have some problem use stack with SingleChildScrollView. I want in the screen , my card with content overwrite the image. But the card still can be scrolled. How can i do this ?

I already try with this code , but my card cut off :

Source Code

```<code>class NewsScreenDetail extends StatelessWidget {
  static const routeNamed = '/news-screen-detail';
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DrysAppBar(
        appBar: AppBar(),
        scaffoldKey: _scaffoldKey,
        titleAppBar: Text('BERITA'),
        showDrawerMenu: false,
      ),
      body: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Stack(
              overflow: Overflow.visible,
              children: <Widget>[
                Container(
                  height: sizes.height(context) / 4,
                  decoration: BoxDecoration(
                    color: Colors.red,
                    image: DecorationImage(
                      fit: BoxFit.cover,
                      image: NetworkImage(
                          "https://homepages.cae.wisc.edu/~ece533/images/airplane.png"),
                    ),
                  ),
                ),
                Positioned(
                  left: 0,
                  right: 0,
                  top: sizes.width(context) / 3,
                  child: Card(
                    color: Colors.blue,
                    child: Text(
                      """
                  What is Lorem Ipsum?
                  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

                  Why do we use it?
                  It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

                  Where does it come from?
                  Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

                  The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.
                    """,
                    ),
                  ),
                )
              ],
            ),
          ],
        ),
      ),
    );
  }
}

</code>```

I'm try to adding property in Stack overflow:visible, but nothing happen

答:
I've modified your code to fit with what you seem to want, based on your question, examples and comment:</p>

```<code>class NewsScreenDetail extends StatelessWidget {
  static const routeNamed = '/news-screen-detail';
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Stack(
        overflow: Overflow.visible,
        children: <Widget>[
          Image.network("https://homepages.cae.wisc.edu/~ece533/images/airplane.png"),
          Container(
            margin: EdgeInsets.only(top: 200),
            child: Card(
              color: Colors.blue,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(
                  """
                  What is Lorem Ipsum?
                  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

                  Why do we use it?
                  It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

                  Where does it come from?
                  Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

                  The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.
                  """,
                  overflow: TextOverflow.visible,
                  softWrap: true,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Flutter : Scrolled Stack Widget

Body:
I have some problem use stack with SingleChildScrollView. I want in the screen , my card with content overwrite the image. But the card still can be scrolled. How can i do this ?

I already try with this code , but my card cut off :

Source Code

class NewsScreenDetail extends StatelessWidget {
  static const routeNamed = '/news-screen-detail';
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DrysAppBar(
        appBar: AppBar(),
        scaffoldKey: _scaffoldKey,
        titleAppBar: Text('BERITA'),
        showDrawerMenu: false,
      ),
      body: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Stack(
              overflow: Overflow.visible,
              children: <Widget>[
                Container(
                  height: sizes.height(context) / 4,
                  decoration: BoxDecoration(
                    color: Colors.red,
                    image: DecorationImage(
                      fit: BoxFit.cover,
                      image: NetworkImage(
                          "https://homepages.cae.wisc.edu/~ece533/images/airplane.png"),
                    ),
                  ),
                ),
                Positioned(
                  left: 0,
                  right: 0,
                  top: sizes.width(context) / 3,
                  child: Card(
                    color: Colors.blue,
                    child: Text(
                      """
                  What is Lorem Ipsum?
                  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

                  Why do we use it?
                  It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

                  Where does it come from?
                  Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

                  The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.
                    """,
                    ),
                  ),
                )
              ],
            ),
          ],
        ),
      ),
    );
  }
}

I'm try to adding property in Stack overflow:visible, but nothing happen

Body:
I've modified your code to fit with what you seem to want, based on your question, examples and comment:

class NewsScreenDetail extends StatelessWidget {
  static const routeNamed = '/news-screen-detail';
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Stack(
        overflow: Overflow.visible,
        children: <Widget>[
          Image.network("https://homepages.cae.wisc.edu/~ece533/images/airplane.png"),
          Container(
            margin: EdgeInsets.only(top: 200),
            child: Card(
              color: Colors.blue,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Text(
                  """
                  What is Lorem Ipsum?
                  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

                  Why do we use it?
                  It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

                  Where does it come from?
                  Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

                  The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.
                  """,
                  overflow: TextOverflow.visible,
                  softWrap: true,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}


问:
Is there any way to delete widget by its position in grid or delete row in this grid?
I need to have ability to create endless widgets by .addWidget (in grid, new widget - new row). I already have it. But im also need ability to delete widgets by his position. I tried this:

```<code>from PyQt5 import QtWidgets, QtGui
from PyQt5.QtCore import QTime, QTimer, QObject
from PyQt5.QtWidgets import QMainWindow, QApplication, QLCDNumber, QPushButton, QGridLayout, QLabel, QLineEdit, QTextEdit, QGroupBox
import sys
from somethingtestui import Ui_MainWindow

global selection
selection = 1

class mywindow(QtWidgets.QMainWindow):

def __init__(self):
    super(mywindow, self).__init__()
    self.ui = Ui_MainWindow()
    self.ui.setupUi(self)
    self.ui.pushButton.clicked.connect(self.add)

def add(self):
    global selection
    self.row = QTextEdit('')
    self.text3 = QPushButton('Delete row')
    self.ui.gridLayout.addWidget(self.row, selection, 0, 1, 1)
    self.ui.gridLayout.addWidget(self.text3, selection, 1, 1, 1)
    # global delf
    def delf():
        global selection
        selection = selection-1
        number = self.ui.gridLayout.itemAtPosition(selection,1)
        print(number)
        self.row.deleteLater()
        self.rrow = None
        self.text3.deleteLater()
        self.text3 = None
    self.text3.clicked.connect(delf)
    selection = selection+1
app = QtWidgets.QApplication([])
application = mywindow()
application.show()

sys.exit(app.exec())
</code>```

With it i can add many widgets. If there are one created widget i am free to delete it and repeat it. But if there are 2 or more created widget i can delete one of them, and after click button "Delete" in the other row it crash:

```<code>Traceback (most recent call last):
  File "E:\Programs\YandexDisk\Tempfiles\TournamentBot\testi22.py", line 31, in delf
    self.row.deleteLater()
RuntimeError: wrapped C/C++ object of type QTextEdit has been deleted
</code>```

答:
I found solution for myself </p>

```<code>from somethingtestui import Ui_MainWindow

global rowcnt
rowcnt = 1

class mywindow(QtWidgets.QMainWindow):

def __init__(self):
    super(mywindow, self).__init__()
    self.ui = Ui_MainWindow()
    self.ui.setupUi(self)
    self.ui.pushButton.clicked.connect(self.add)
    self.ui.gridLayout.setRowMinimumHeight(50,50)
    self.ui.gridLayout.setColumnMinimumWidth(50,50)

def add(self):
    global rowcnt
    self.row = QTextEdit('')
    self.delbtn = QPushButton('Delete row')
    self.ui.gridLayout.addWidget(self.row, rowcnt, 0, 1, 1)
    self.ui.gridLayout.addWidget(self.delbtn, rowcnt, 1, 1, 1)
    w = self.ui.gridLayout.itemAtPosition(rowcnt,1).widget()
    def delf(currow):
        global rowcnt
        rowcnt = rowcnt-1
        number = self.ui.gridLayout.itemAtPosition(currow,1).widget()
        number2 = self.ui.gridLayout.itemAtPosition(currow,0).widget()
        number.deleteLater()
        number2.deleteLater()
    w.clicked.connect(lambda: delf(mrowcnt))
    rowcnt = rowcnt+1
    mrowcnt = rowcnt-1
</code>```

Body:
I need to have ability to create endless widgets by .addWidget (in grid, new widget - new row). I already have it. But im also need ability to delete widgets by his position. I tried this:

from PyQt5 import QtWidgets, QtGui
from PyQt5.QtCore import QTime, QTimer, QObject
from PyQt5.QtWidgets import QMainWindow, QApplication, QLCDNumber, QPushButton, QGridLayout, QLabel, QLineEdit, QTextEdit, QGroupBox
import sys
from somethingtestui import Ui_MainWindow

global selection
selection = 1

class mywindow(QtWidgets.QMainWindow):

def __init__(self):
    super(mywindow, self).__init__()
    self.ui = Ui_MainWindow()
    self.ui.setupUi(self)
    self.ui.pushButton.clicked.connect(self.add)

def add(self):
    global selection
    self.row = QTextEdit('')
    self.text3 = QPushButton('Delete row')
    self.ui.gridLayout.addWidget(self.row, selection, 0, 1, 1)
    self.ui.gridLayout.addWidget(self.text3, selection, 1, 1, 1)
    # global delf
    def delf():
        global selection
        selection = selection-1
        number = self.ui.gridLayout.itemAtPosition(selection,1)
        print(number)
        self.row.deleteLater()
        self.rrow = None
        self.text3.deleteLater()
        self.text3 = None
    self.text3.clicked.connect(delf)
    selection = selection+1
app = QtWidgets.QApplication([])
application = mywindow()
application.show()

sys.exit(app.exec())

With it i can add many widgets. If there are one created widget i am free to delete it and repeat it. But if there are 2 or more created widget i can delete one of them, and after click button "Delete" in the other row it crash:

Traceback (most recent call last):
  File "E:\Programs\YandexDisk\Tempfiles\TournamentBot\testi22.py", line 31, in delf
    self.row.deleteLater()
RuntimeError: wrapped C/C++ object of type QTextEdit has been deleted

Body:
I found solution for myself

from somethingtestui import Ui_MainWindow

global rowcnt
rowcnt = 1

class mywindow(QtWidgets.QMainWindow):

def __init__(self):
    super(mywindow, self).__init__()
    self.ui = Ui_MainWindow()
    self.ui.setupUi(self)
    self.ui.pushButton.clicked.connect(self.add)
    self.ui.gridLayout.setRowMinimumHeight(50,50)
    self.ui.gridLayout.setColumnMinimumWidth(50,50)

def add(self):
    global rowcnt
    self.row = QTextEdit('')
    self.delbtn = QPushButton('Delete row')
    self.ui.gridLayout.addWidget(self.row, rowcnt, 0, 1, 1)
    self.ui.gridLayout.addWidget(self.delbtn, rowcnt, 1, 1, 1)
    w = self.ui.gridLayout.itemAtPosition(rowcnt,1).widget()
    def delf(currow):
        global rowcnt
        rowcnt = rowcnt-1
        number = self.ui.gridLayout.itemAtPosition(currow,1).widget()
        number2 = self.ui.gridLayout.itemAtPosition(currow,0).widget()
        number.deleteLater()
        number2.deleteLater()
    w.clicked.connect(lambda: delf(mrowcnt))
    rowcnt = rowcnt+1
    mrowcnt = rowcnt-1


问:
Notepad++ Explorer plugin
I'm currently using the notepad++ as my code editor..since it was so quick to start i'm pretty much like this..but i have a problem regarding the explorer plugin..i can't add the network drive so that i can access the shared document from other workstation. only the drive C and D showed up. How to show the network drive in the explorer plugin?</p>

答:
The explorer plugin won't show a mapped network drive, but the light explorer plugin will. Both of these are available in the plugin manager.

EDIT: I answered this extremely old question because it is the top Google result for this search, so it may as well have the correct answer.

ContentLicense: CC BY-SA 2.5

Title: Notepad++ Explorer plugin

ContentLicense: CC BY-SA 3.0


问:
How can I randomly capitalise letters in a string
I'm sorry if this has been asked before, but I can't seem to find the right answer.

I'm trying to create a random password generator using Javascript. I've set meself 4 basic requirements:

Must contain letters, numbers and special characters

Must be 14 characters

Must have upper and lower case lettering

Must log the result as a string

Here is what I have:

```<code>var characters = 'abcdefghijklmnoqrstuvwxyz0123456789?<>!"£$%^&*()-+./';
var results = '';
var length = characters.length;

function randomPassword() {

for (i=0; i<=13; i++) {
    var mix = characters.charAt(Math.floor(Math.random() * length));
    var newString = results += mix;
    }
    console.log(newString);
}

randomPassword();
</code>```

The code above passes all of my requirements apart from the upper and lower case letters. Is there a way to randomly capitalise some of the letters in my string? I've tried playing with .toUpperCase() in the same way I have to create my 'mix' variable, but I can't work out how to do it.

This isn't for any real life projects. I'm just using this as a way to try to learn Javascript, so any advice would be greatly appreciated :)

Thanks!

答:
your code is good and correct just make a simple improvement as mentioned below. you can achieve your goal.

var characters = 'abcdefghijklmnoqrstuvwxyz0123456789?<>!"£$%^&*()-+./';
     var results = '';
     var length = characters.length;

  function randomPassword() {
      var check = 2;
      for (i=0; i<=13; i++) {
        var mix = characters.charAt(Math.floor(Math.random() * length));
        if (mix.match(/[a-z]/i) && check>0) {
          mix =  mix.toUpperCase();
          check --;
        }
     var newString = results += mix;
    }
    console.log(newString);
   }
  randomPassword();```
</div>
</div>
</p>

```    var characters = 'abcdefghijklmnoqrstuvwxyz0123456789?<>!"£$%^&*()-+./';
     var results = '';
     var length = characters.length;

  function randomPassword() {
      var check = 2;
      for (i=0; i<=13; i++) {
        var mix = characters.charAt(Math.floor(Math.random() * length));
        if (mix.match(/[a-z]/i) && check>0) {
          mix =  mix.toUpperCase();
          check --;
        }
     var newString = results += mix;
    }
    console.log(newString);
   }
  randomPassword();
```

Body:
I'm sorry if this has been asked before, but I can't seem to find the right answer.

I'm trying to create a random password generator using Javascript. I've set meself 4 basic requirements:

Must contain letters, numbers and special characters

Must be 14 characters

Must have upper and lower case lettering

Must log the result as a string

Here is what I have:

var characters = 'abcdefghijklmnoqrstuvwxyz0123456789?<>!"£$%^&*()-+./';
var results = '';
var length = characters.length;

function randomPassword() {

for (i=0; i<=13; i++) {
    var mix = characters.charAt(Math.floor(Math.random() * length));
    var newString = results += mix;
    }
    console.log(newString);
}

randomPassword();

The code above passes all of my requirements apart from the upper and lower case letters. Is there a way to randomly capitalise some of the letters in my string? I've tried playing with .toUpperCase() in the same way I have to create my 'mix' variable, but I can't work out how to do it.

This isn't for any real life projects. I'm just using this as a way to try to learn Javascript, so any advice would be greatly appreciated :)

Thanks!

Body:
your code is good and correct just make a simple improvement as mentioned below. you can achieve your goal.

var characters = 'abcdefghijklmnoqrstuvwxyz0123456789?<>!"£$%^&*()-+./';
     var results = '';
     var length = characters.length;

  function randomPassword() {
      var check = 2;
      for (i=0; i<=13; i++) {
        var mix = characters.charAt(Math.floor(Math.random() * length));
        if (mix.match(/[a-z]/i) && check>0) {
          mix =  mix.toUpperCase();
          check --;
        }
     var newString = results += mix;
    }
    console.log(newString);
   }
  randomPassword();

    var characters = 'abcdefghijklmnoqrstuvwxyz0123456789?<>!"£$%^&*()-+./';
     var results = '';
     var length = characters.length;

  function randomPassword() {
      var check = 2;
      for (i=0; i<=13; i++) {
        var mix = characters.charAt(Math.floor(Math.random() * length));
        if (mix.match(/[a-z]/i) && check>0) {
          mix =  mix.toUpperCase();
          check --;
        }
     var newString = results += mix;
    }
    console.log(newString);
   }
  randomPassword();


问:
Mapping values from series over a column to replace nan values pandas
I have a DataFrame which has job numbers and the customer names associated with that job. There are instances where the job numbers have no customer name and therefore is null.
I have a separate series which has these job numbers as index and the missing customer names to replace the null values, based on the job numbers. I am not entirely sure how I would go about mapping this over the original DataFrame column.

This is the original DataFrame (df):

```<code>   Job Number  Customer
0    02123      Paul F
1    46456      nan
2    56823      Kevin T
3    62948      nan
</code>```

The series to replace the nan values:

```<code>Job Number
  46456     Kara L
  62948     Sabrina M
  Name: Customers, dtype: object
</code>```

The final output I need is:

```<code>   Job Number  Customer
0    02123      Paul F
1    46456      Kara L
2    56823      Kevin T
3    62948      Sabrina M
</code>```

I hope this makes sense. I have had a look at other answers such as using: df['Customer'] = df['Job Number'].map(customers) but that didn't work or test['Customer'] = df['Customer'].combine_first(df['Customer'].map(customers)).

I wasn't sure how to paste code into here so I have written out the df and series by hand.

Any help would be greatly appreciated.

答:
Here is necessary use map by column Job Number instead Customer:

```<code>df['Customer'] = df['Customer'].combine_first(df['Job Number'].map(customers))
print (df)
   Job Number   Customer
0        2123     Paul F
1       46456     Kara L
2       56823    Kevin T
3       62948  Sabrina M
</code>```

Detail:

```<code>print (df['Job Number'].map(customers))
0          NaN
1       Kara L
2          NaN
3    Sabrina M
Name: Job Number, dtype: object
</code>```

Body:
I have a DataFrame which has job numbers and the customer names associated with that job. There are instances where the job numbers have no customer name and therefore is null.
I have a separate series which has these job numbers as index and the missing customer names to replace the null values, based on the job numbers. I am not entirely sure how I would go about mapping this over the original DataFrame column.

This is the original DataFrame (df):

   Job Number  Customer
0    02123      Paul F
1    46456      nan
2    56823      Kevin T
3    62948      nan

The series to replace the nan values:

Job Number
  46456     Kara L
  62948     Sabrina M
  Name: Customers, dtype: object

The final output I need is:

   Job Number  Customer
0    02123      Paul F
1    46456      Kara L
2    56823      Kevin T
3    62948      Sabrina M

I hope this makes sense. I have had a look at other answers such as using: df['Customer'] = df['Job Number'].map(customers) but that didn't work or test['Customer'] = df['Customer'].combine_first(df['Customer'].map(customers)).

I wasn't sure how to paste code into here so I have written out the df and series by hand.

Any help would be greatly appreciated.

Body:
Here is necessary use map by column Job Number instead Customer:

df['Customer'] = df['Customer'].combine_first(df['Job Number'].map(customers))
print (df)
   Job Number   Customer
0        2123     Paul F
1       46456     Kara L
2       56823    Kevin T
3       62948  Sabrina M

Detail:

print (df['Job Number'].map(customers))
0          NaN
1       Kara L
2          NaN
3    Sabrina M
Name: Job Number, dtype: object


问:
Stuck at npm install at fechMetadata checking installable status
Suddently I can't install angular
I get stuck at the npm install command
"npm install -g @angular/cli"
It stays forever on  this "checking installable status".

my node version is 8.11.3 (yes I already tried to uninstall node and double checked to see it was really uninstalled) this was the version I had before and was working fine
my npm -v gives 5.6.0

then I run the angular command to install angular and it seems to freezing or very very very slow....

答:
In my case I had to wait for a few minutes and npm finally installed by package.
Also I suggest to use --verbose flag to see what's actually is going.


问:
create custom segmentControl
I'm trying to create a rather custom segmentControl. What is the easiest way to create such below. with just text and a border line the selected?

答: You can make fastens and offer tag to each of them,which will recognize which catch has been selected. Whenever a catch is set apart as chosen change the state to .selected with its image.</p>

Title: create custom segmentControl


问:
Fix "We're sorry HTTPS required " Keycloak login page
I was facing issue while logging into keycloak from external IP. As soon as i tried to login using administrative console I was presented with a message "We're sorry HTTPS required" . I search for almost all stackoverflow post but only one post was useful . </p>

答:
To disable the ssl requirement we can do so by using the below command:

java -cp /opt/keycloak-4.8.3.Final/modules/system/layers/base/com/h2database/h2/main/h2-1.4.193.jar org.h2.tools.Shell -url "jdbc:h2:/opt/keycloak-4.8.3.Final/standalone/data/keycloak" -user sa -password sa -sql "update REALM set ssl_required='NONE' where id = 'master'"
```

Make sure you stop the keycloak service first, so that you can update the table.

Body:
To disable the ssl requirement we can do so by using the below command:

java -cp /opt/keycloak-4.8.3.Final/modules/system/layers/base/com/h2database/h2/main/h2-1.4.193.jar org.h2.tools.Shell -url "jdbc:h2:/opt/keycloak-4.8.3.Final/standalone/data/keycloak" -user sa -password sa -sql "update REALM set ssl_required='NONE' where id = 'master'"

Make sure you stop the keycloak service first, so that you can update the table.


问:
To update rows in another table based on selected output from another table, but program only update top one row
I want to update multiple rows from table 'WORKTR' based on the selected rows from table 'BRTR'. Unfortunately, the program only update the WORKTR table based on the top one row from 'BRTR' table.

Here is my code:

```<code>      Button Back = (Button) findViewById(R.id.btn_back);
        Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                connectionClass = new ConnectionClass();
                Connection con = connectionClass.CONN();
                try {
                    final String PIC = lblname.getText().toString();
                    String dates = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).format(Calendar.getInstance().getTime());
                    String check = "Select * from BRTR where work_date='" + dates + "' and end_break is null";
                    Statement st = con.createStatement();

                    rs = st.executeQuery(check);

                    while (rs.next()) {
                        String PF_NO = rs.getString("PF_No");

                        String query2 = "Update WORKTR set status ='" + b_status + "' where Start_date='" + dates + "' and Pf_no='" + PF_NO + "' and Scan_by='" + PIC + "' and status='" + a_status + "'";

                        st.executeUpdate(query2);
                    }
                } catch (Exception ex)
                {

                }
                onBackPressed();
            }

        });
</code>```

Please help or notify if you see any mistakes from the codes above.

答:
Try using another statement since st.executeUpdate(query2); will close the ResultSet and you will get JdbcSQLException however you ignore all the exceptions on your code. You should at least put ex.printStackTrace() to your catch block so you can see what is going on.

Eventhough code-wise there are a lot to improve here, functionally this should work for you,

```<code>      Button Back = (Button) findViewById(R.id.btn_back);
    Back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            connectionClass = new ConnectionClass();
            Connection con = connectionClass.CONN();
            try {
                final String PIC = lblname.getText().toString();
                String dates = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).format(Calendar.getInstance().getTime());
                String check = "Select * from BRTR where work_date='" + dates + "' and end_break is null";
                Statement st = con.createStatement();

                rs = st.executeQuery(check);

                while (rs.next()) {
                    String PF_NO = rs.getString("PF_No");

                    String query2 = "Update WORKTR set status ='" + b_status + "' where Start_date='" + dates + "' and Pf_no='" + PF_NO + "' and Scan_by='" + PIC + "' and status='" + a_status + "'";

                    con.createStatement().executeUpdate(query2);
                }
            } catch (Exception ex)
            {
               ex.printStackTrace(); // now we can see what is going wrong
            }
            onBackPressed();
        }

    });
</code>```

Body:
I want to update multiple rows from table 'WORKTR' based on the selected rows from table 'BRTR'. Unfortunately, the program only update the WORKTR table based on the top one row from 'BRTR' table.

Here is my code:

      Button Back = (Button) findViewById(R.id.btn_back);
        Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                connectionClass = new ConnectionClass();
                Connection con = connectionClass.CONN();
                try {
                    final String PIC = lblname.getText().toString();
                    String dates = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).format(Calendar.getInstance().getTime());
                    String check = "Select * from BRTR where work_date='" + dates + "' and end_break is null";
                    Statement st = con.createStatement();

                    rs = st.executeQuery(check);

                    while (rs.next()) {
                        String PF_NO = rs.getString("PF_No");

                        String query2 = "Update WORKTR set status ='" + b_status + "' where Start_date='" + dates + "' and Pf_no='" + PF_NO + "' and Scan_by='" + PIC + "' and status='" + a_status + "'";

                        st.executeUpdate(query2);
                    }
                } catch (Exception ex)
                {

                }
                onBackPressed();
            }

        });

Please help or notify if you see any mistakes from the codes above.

Body:
Try using another statement since st.executeUpdate(query2); will close the ResultSet and you will get JdbcSQLException however you ignore all the exceptions on your code. You should at least put ex.printStackTrace() to your catch block so you can see what is going on.

Eventhough code-wise there are a lot to improve here, functionally this should work for you,

      Button Back = (Button) findViewById(R.id.btn_back);
    Back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            connectionClass = new ConnectionClass();
            Connection con = connectionClass.CONN();
            try {
                final String PIC = lblname.getText().toString();
                String dates = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).format(Calendar.getInstance().getTime());
                String check = "Select * from BRTR where work_date='" + dates + "' and end_break is null";
                Statement st = con.createStatement();

                rs = st.executeQuery(check);

                while (rs.next()) {
                    String PF_NO = rs.getString("PF_No");

                    String query2 = "Update WORKTR set status ='" + b_status + "' where Start_date='" + dates + "' and Pf_no='" + PF_NO + "' and Scan_by='" + PIC + "' and status='" + a_status + "'";

                    con.createStatement().executeUpdate(query2);
                }
            } catch (Exception ex)
            {
               ex.printStackTrace(); // now we can see what is going wrong
            }
            onBackPressed();
        }

    });


问:
http.client.InvalidURL: nonnumeric port: '//water-lined.net' Error?
I've been trying to make a script to check if a random website exists and then opens it if it does exist, but I keep getting a bunch of different errors. Here is my code:

```<code>import webbrowser
import time
import random
import http.client
from random_word import RandomWords
r=RandomWords()
while True:
    possible_things = random.choice([".com",".net"])
    WEB = "http://"+r.get_random_word()+possible_things
    c = http.client.HTTPConnection(WEB)
    if c.getresponse().status == 200:
        seconds = random.randint(5,20)
        print("Web site exists; Website: "+WEB+" ; Seconds: "+seconds)
        time.sleep(seconds)
        webbrowser.open(WEB)
        print("Finished countdown, re-looping...")
    else:
        print('Web site DOES NOT exists; Website: '+WEB+'; re-looping...')
</code>```

And here is the error:

```<code>Traceback (most recent call last):
  File "C:\Users\[REDACTED]\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 877, in _get_hostport
    port = int(host[i+1:])
ValueError: invalid literal for int() with base 10: '//water-lined.net'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "Troll.py", line 10, in <module>
    c = http.client.HTTPConnection(WEB)
  File "C:\Users\[REDACTED]\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 841, in __init__
    (self.host, self.port) = self._get_hostport(host, port)
  File "C:\Users\[REDACTED]\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 882, in _get_hostport
    raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
http.client.InvalidURL: nonnumeric port: '//water-lined.net'
</code>```

答:
```<code>WEB = "http://"+r.get_random_word()+possible_things
c = http.client.HTTPConnection(WEB)
</code>```

In the first of those lines you create an URL, beginning with http://
In the second one you pass it to a function that does not expect an URL, but rather a hostname with optional : and port number. Since your string contains a colon after 'http", 'http' will be assumed to be the host name and everything after the colon, ie '//something.tld' is interpreted as a port number - but it cannot be converted to an integer, hence error.

What you probably wanted to do is something along these lines:

```<code>host = r.get_random_word() + possible_things
WEB = 'http://' + host
c = http.client.HTTPConnection(host)
c.request('GET', '/')
resp = c.getresponse()
if resp.status == 200:
</code>```

etc.

Body:
I've been trying to make a script to check if a random website exists and then opens it if it does exist, but I keep getting a bunch of different errors. Here is my code:

import webbrowser
import time
import random
import http.client
from random_word import RandomWords
r=RandomWords()
while True:
    possible_things = random.choice([".com",".net"])
    WEB = "http://"+r.get_random_word()+possible_things
    c = http.client.HTTPConnection(WEB)
    if c.getresponse().status == 200:
        seconds = random.randint(5,20)
        print("Web site exists; Website: "+WEB+" ; Seconds: "+seconds)
        time.sleep(seconds)
        webbrowser.open(WEB)
        print("Finished countdown, re-looping...")
    else:
        print('Web site DOES NOT exists; Website: '+WEB+'; re-looping...')

And here is the error:

Traceback (most recent call last):
  File "C:\Users\[REDACTED]\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 877, in _get_hostport
    port = int(host[i+1:])
ValueError: invalid literal for int() with base 10: '//water-lined.net'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "Troll.py", line 10, in <module>
    c = http.client.HTTPConnection(WEB)
  File "C:\Users\[REDACTED]\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 841, in __init__
    (self.host, self.port) = self._get_hostport(host, port)
  File "C:\Users\[REDACTED]\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 882, in _get_hostport
    raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
http.client.InvalidURL: nonnumeric port: '//water-lined.net'

Body:
WEB = "http://"+r.get_random_word()+possible_things
c = http.client.HTTPConnection(WEB)

In the first of those lines you create an URL, beginning with http://
In the second one you pass it to a function that does not expect an URL, but rather a hostname with optional : and port number. Since your string contains a colon after 'http", 'http' will be assumed to be the host name and everything after the colon, ie '//something.tld' is interpreted as a port number - but it cannot be converted to an integer, hence error.

What you probably wanted to do is something along these lines:

host = r.get_random_word() + possible_things
WEB = 'http://' + host
c = http.client.HTTPConnection(host)
c.request('GET', '/')
resp = c.getresponse()
if resp.status == 200:

etc.


问:
Plot sample images over network graph
I am using Plotly to display a network graph and I'm trying to display sample images belonging to specific data points (each data point is a 64x64 luminosity map of a sculpture). I have two problems:

I'm using the datapoint coordinates to position the image, but they are not aligned. I tried to use xanchor/yanchor to fix it but it didn't work.

Although I'm plotting 100 images, only a few of them are actually visible. If I zoom in into the visualization I can see more of them but I want to force Plotly to show all of them. I tried with layer='above' but didn't work.

It would be great if there is a way to link the image with the actual data point but I don't know how to do it.

def plot_graph(G, plot_title, dataset, coordinates=None):

```<code>if coordinates == None:
    coordinates = nx.drawing.spring_layout(G, weight=None)

edge_x = []
edge_y = []
for edge in G.edges():
    x0, y0 = coordinates[edge[0]]
    x1, y1 = coordinates[edge[1]]
    edge_x.extend([x0, x1])
    edge_y.extend([y0, y1])

edge_trace = go.Scatter(x=edge_x,
                        y=edge_y,
                        line=dict(width=0.5, color='#888'),
                        hoverinfo='none',
                        mode='lines'
                        )

node_x = []
node_y = []
for node in G.nodes():
    x, y = coordinates[node]
    node_x.append(x)
    node_y.append(y)

colorbar_attrs = dict(thickness=15, title='KNN Density', xanchor='left', titleside='right')
marker_attrs = dict(showscale=True,
                    colorscale='YlGnBu',
                    reversescale=True,
                    color=[], size=10,
                    colorbar=colorbar_attrs,
                    line_width=2)

node_trace = go.Scatter(x=node_x, y=node_y, mode='markers', hoverinfo='text', marker=marker_attrs)

node_adjacencies = []
node_text = []

for node, adjacencies in enumerate(G.adjacency()):
    node_adjacencies.append(len(adjacencies[1]))
    node_text.append('K-Nearest Neighbors: '+str(len(adjacencies[1])))

node_trace.marker.color = node_adjacencies
node_trace.text = node_text
fig = go.Figure(data=[edge_trace, node_trace],
                layout=go.Layout(
                title='<br> {}'.format(plot_title),
                titlefont_size=18,
                showlegend=False,
                hovermode='closest',
                margin=dict(b=20,l=5,r=5,t=40),
                xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
                yaxis=dict(showgrid=False, zeroline=False, showticklabels=False))
                )

num_images = 100
num_faces = dataset.shape[0]
sample_images = np.random.choice(num_faces, num_images, replace=False)
greys = cm.get_cmap('Greys_r')

for index in sample_images:
    greyscale = np.apply_along_axis(greys, 0, dataset[index]).reshape((64, 64, 4))*255
    greyscale = greyscale.astype(np.uint8)
    im = pilim.fromarray(greyscale)
    fig.add_layout_image(dict(
        source=im,
        x=coordinates[index][0],
        y=coordinates[index][1],
        sizex=0.03,
        sizey=0.03,
        layer='above'
                         ))

return fig
</code>```

This is what I'm getting

答:
First pitch

Since you haven't provided a fully reproducible example, it's difficult to solve your problem directly. But I do have a suggestion building on the top example from plot.ly/python/network-graphs/ and using the image benze.png that's also used in other plotly examples. The image is stored multiple times in a list, so you should be able to replace those easily with references to other images. I'm grabbing the X, Y coordinates from fig['data'][1]['x'] and fig['data'][1]['y'] but that should be easily adjustable to other sources too.

Plot 1:

Plot 2: Zoomed in

Now, if I'm understanding your challenge correctly, this plot meets your requirements regarding all three criteria:

datapoints are aligned

all images are showing

images are aligned directly to all datapoints

Please don't hesitate to let me know how this works out for you!

Code:

```<code>import plotly.graph_objects as go
import networkx as nx

G = nx.random_geometric_graph(200, 0.125)

edge_x = []
edge_y = []
for edge in G.edges():
    x0, y0 = G.nodes[edge[0]]['pos']
    x1, y1 = G.nodes[edge[1]]['pos']
    edge_x.append(x0)
    edge_x.append(x1)
    edge_x.append(None)
    edge_y.append(y0)
    edge_y.append(y1)
    edge_y.append(None)

edge_trace = go.Scatter(
    x=edge_x, y=edge_y,
    line=dict(width=0.5, color='#888'),
    hoverinfo='none',
    mode='lines')

node_x = []
node_y = []
for node in G.nodes():
    x, y = G.nodes[node]['pos']
    node_x.append(x)
    node_y.append(y)

node_trace = go.Scatter(
    x=node_x, y=node_y,
    mode='markers',
    hoverinfo='text',
    marker=dict(
        showscale=True,
        colorscale='YlGnBu',
        reversescale=True,
        color=[],
        size=10,
        colorbar=dict(
            thickness=15,
            title='Node Connections',
            xanchor='left',
            titleside='right'
        ),
        line_width=2))

node_adjacencies = []
node_text = []
for node, adjacencies in enumerate(G.adjacency()):
    node_adjacencies.append(len(adjacencies[1]))
    node_text.append('# of connections: '+str(len(adjacencies[1])))

node_trace.marker.color = node_adjacencies
node_trace.text = node_text

fig = go.Figure(data=[edge_trace, node_trace])

# sample images
sample_images=["https://raw.githubusercontent.com/michaelbabyn/plot_data/master/benzene.png"]*len(fig['data'][1]['x'])
xVals = fig['data'][1]['x']
yVals = fig['data'][1]['y']

for i in range(0, len(xVals)):
    fig.add_layout_image(dict(
        source=sample_images[i],
        x=xVals[i],
        y=yVals[i],
        xref="x",
        yref="y",
        #sizex=0.03,
        #sizey=0.03,
        #layer='above'
        sizex=0.1,
        sizey=0.1,
        #sizing="stretch",
        opacity=0.5,
        layer="below"
    ))

fig.show()
</code>```

Title: Plot sample images over network graph

Body:
I am using Plotly to display a network graph and I'm trying to display sample images belonging to specific data points (each data point is a 64x64 luminosity map of a sculpture). I have two problems:

I'm using the datapoint coordinates to position the image, but they are not aligned. I tried to use xanchor/yanchor to fix it but it didn't work.

Although I'm plotting 100 images, only a few of them are actually visible. If I zoom in into the visualization I can see more of them but I want to force Plotly to show all of them. I tried with layer='above' but didn't work.

It would be great if there is a way to link the image with the actual data point but I don't know how to do it.

def plot_graph(G, plot_title, dataset, coordinates=None):

if coordinates == None:
    coordinates = nx.drawing.spring_layout(G, weight=None)

edge_x = []
edge_y = []
for edge in G.edges():
    x0, y0 = coordinates[edge[0]]
    x1, y1 = coordinates[edge[1]]
    edge_x.extend([x0, x1])
    edge_y.extend([y0, y1])

edge_trace = go.Scatter(x=edge_x,
                        y=edge_y,
                        line=dict(width=0.5, color='#888'),
                        hoverinfo='none',
                        mode='lines'
                        )

node_x = []
node_y = []
for node in G.nodes():
    x, y = coordinates[node]
    node_x.append(x)
    node_y.append(y)

colorbar_attrs = dict(thickness=15, title='KNN Density', xanchor='left', titleside='right')
marker_attrs = dict(showscale=True,
                    colorscale='YlGnBu',
                    reversescale=True,
                    color=[], size=10,
                    colorbar=colorbar_attrs,
                    line_width=2)

node_trace = go.Scatter(x=node_x, y=node_y, mode='markers', hoverinfo='text', marker=marker_attrs)

node_adjacencies = []
node_text = []

for node, adjacencies in enumerate(G.adjacency()):
    node_adjacencies.append(len(adjacencies[1]))
    node_text.append('K-Nearest Neighbors: '+str(len(adjacencies[1])))

node_trace.marker.color = node_adjacencies
node_trace.text = node_text
fig = go.Figure(data=[edge_trace, node_trace],
                layout=go.Layout(
                title='
 {}'.format(plot_title),
                titlefont_size=18,
                showlegend=False,
                hovermode='closest',
                margin=dict(b=20,l=5,r=5,t=40),
                xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
                yaxis=dict(showgrid=False, zeroline=False, showticklabels=False))
                )

num_images = 100
num_faces = dataset.shape[0]
sample_images = np.random.choice(num_faces, num_images, replace=False)
greys = cm.get_cmap('Greys_r')

for index in sample_images:
    greyscale = np.apply_along_axis(greys, 0, dataset[index]).reshape((64, 64, 4))*255
    greyscale = greyscale.astype(np.uint8)
    im = pilim.fromarray(greyscale)
    fig.add_layout_image(dict(
        source=im,
        x=coordinates[index][0],
        y=coordinates[index][1],
        sizex=0.03,
        sizey=0.03,
        layer='above'
                         ))

return fig

This is what I'm getting

Body:
First pitch

Since you haven't provided a fully reproducible example, it's difficult to solve your problem directly. But I do have a suggestion building on the top example from plot.ly/python/network-graphs/ and using the image benze.png that's also used in other plotly examples. The image is stored multiple times in a list, so you should be able to replace those easily with references to other images. I'm grabbing the X, Y coordinates from fig['data'][1]['x'] and fig['data'][1]['y'] but that should be easily adjustable to other sources too.

Plot 1:

Plot 2: Zoomed in

Now, if I'm understanding your challenge correctly, this plot meets your requirements regarding all three criteria:

datapoints are aligned

all images are showing

images are aligned directly to all datapoints

Please don't hesitate to let me know how this works out for you!

Code:

import plotly.graph_objects as go
import networkx as nx

G = nx.random_geometric_graph(200, 0.125)

edge_x = []
edge_y = []
for edge in G.edges():
    x0, y0 = G.nodes[edge[0]]['pos']
    x1, y1 = G.nodes[edge[1]]['pos']
    edge_x.append(x0)
    edge_x.append(x1)
    edge_x.append(None)
    edge_y.append(y0)
    edge_y.append(y1)
    edge_y.append(None)

edge_trace = go.Scatter(
    x=edge_x, y=edge_y,
    line=dict(width=0.5, color='#888'),
    hoverinfo='none',
    mode='lines')

node_x = []
node_y = []
for node in G.nodes():
    x, y = G.nodes[node]['pos']
    node_x.append(x)
    node_y.append(y)

node_trace = go.Scatter(
    x=node_x, y=node_y,
    mode='markers',
    hoverinfo='text',
    marker=dict(
        showscale=True,
        colorscale='YlGnBu',
        reversescale=True,
        color=[],
        size=10,
        colorbar=dict(
            thickness=15,
            title='Node Connections',
            xanchor='left',
            titleside='right'
        ),
        line_width=2))

node_adjacencies = []
node_text = []
for node, adjacencies in enumerate(G.adjacency()):
    node_adjacencies.append(len(adjacencies[1]))
    node_text.append('# of connections: '+str(len(adjacencies[1])))

node_trace.marker.color = node_adjacencies
node_trace.text = node_text

fig = go.Figure(data=[edge_trace, node_trace])

# sample images
sample_images=["https://raw.githubusercontent.com/michaelbabyn/plot_data/master/benzene.png"]*len(fig['data'][1]['x'])
xVals = fig['data'][1]['x']
yVals = fig['data'][1]['y']

for i in range(0, len(xVals)):
    fig.add_layout_image(dict(
        source=sample_images[i],
        x=xVals[i],
        y=yVals[i],
        xref="x",
        yref="y",
        #sizex=0.03,
        #sizey=0.03,
        #layer='above'
        sizex=0.1,
        sizey=0.1,
        #sizing="stretch",
        opacity=0.5,
        layer="below"
    ))

fig.show()


问:
Windows Batch file debugger?
Is there a program like Visual Studio that allows you to debug (dos) batch files?  What techniques could I use to debug?  Martin Brown answered a batch file question with a nice for / each loop.  I would love to see the values of the variables as they loop.

for /R A %i IN (*.jpg) DO xcopy %i B /M

答: Running Steps is like the IDE.  You get an 'Analyzer' which is the equivalent of a compiler.  It shows you errors and warnings in your code.  It has an integrated environment that allows you to step over, into, etc.  It even unrolls for loops which I find awesome.  Check it out at http://www.steppingsoftware.com.   It's helped me a lot.

Title: Windows Batch file debugger?


问:
SQL Tally up value based on the day of the week
Here is what my table looks like

```<code>ID | Date
------------
13  2013-03-21 00:00:00
13  2013-03-23 00:00:00
13  2013-03-24 00:00:00
25  2013-03-21 00:00:00
25  2013-03-22 00:00:00
25  2013-03-21 00:00:00
25  2013-03-23 00:00:00
25  2013-03-28 00:00:00
25  2013-03-21 00:00:00
82  2013-03-22 00:00:00
82  2013-03-22 00:00:00
I want it to output (combine sat & sun into 'weekend'). It'll combine all the Mondays, Tuesdays, Wednesdays, etc. and combine the values.

day | total
--------------
Friday  2
Thursday 3
Weekend 3
</code>```

This is my query so far

```<code>SELECT
  CASE
    WHEN DATENAME(weekday, [date]) = 'Saturday' OR DATENAME(weekday, [date]) = 'Sunday' THEN 'Weekend'
    ELSE DATENAME(weekday, [date])
  END AS Day,
  COUNT(DISTINCT [id]) AS score

  FROM [table]

GROUP BY
  CASE
    WHEN DATENAME(weekday, [date]) = 'Saturday' OR DATENAME(weekday, [date]) = 'Sunday' THEN 'Weekend'
    ELSE DATENAME(weekday, [date])
  END
</code>```

Currently I can get my query to output this, but it seems like it isn't adding both thursdays or sat + sun.

```<code>Day | total
--------------
Friday 2
Thursday 2
Weekend 2
</code>```

答:
Appears like what you are actually after is a distinct count of the ID and date combined. Seems like the easiest way, therefore, would be to concatenate the 2 values to make a new unique value and COUNT those DISTINCT values:

```<code>SELECT CASE WHEN DATENAME(WEEKDAY, V.[Date]) IN ('Saturday','Sunday') THEN 'Weekend' ELSE DATENAME(WEEKDAY, V.[Date]) END AS [Weekday],
       COUNT(DISTINCT CONCAT(ID,[date]))
FROM (VALUES (13, CONVERT(datetime2(0),'2013-03-21T00:00:00')),
             (13, CONVERT(datetime2(0),'2013-03-23T00:00:00')),
             (13, CONVERT(datetime2(0),'2013-03-24T00:00:00')),
             (25, CONVERT(datetime2(0),'2013-03-21T00:00:00')),
             (25, CONVERT(datetime2(0),'2013-03-22T00:00:00')),
             (25, CONVERT(datetime2(0),'2013-03-21T00:00:00')),
             (25, CONVERT(datetime2(0),'2013-03-23T00:00:00')),
             (25, CONVERT(datetime2(0),'2013-03-28T00:00:00')),
             (25, CONVERT(datetime2(0),'2013-03-21T00:00:00')),
             (82, CONVERT(datetime2(0),'2013-03-22T00:00:00')),
             (82, CONVERT(datetime2(0),'2013-03-22T00:00:00'))) V (ID, [Date])
GROUP BY CASE WHEN DATENAME(WEEKDAY, V.[Date]) IN ('Saturday','Sunday') THEN 'Weekend' ELSE DATENAME(WEEKDAY, V.[Date]) END;
</code>```

Body:
Here is what my table looks like

ID | Date
------------
13  2013-03-21 00:00:00
13  2013-03-23 00:00:00
13  2013-03-24 00:00:00
25  2013-03-21 00:00:00
25  2013-03-22 00:00:00
25  2013-03-21 00:00:00
25  2013-03-23 00:00:00
25  2013-03-28 00:00:00
25  2013-03-21 00:00:00
82  2013-03-22 00:00:00
82  2013-03-22 00:00:00
I want it to output (combine sat & sun into 'weekend'). It'll combine all the Mondays, Tuesdays, Wednesdays, etc. and combine the values.

day | total
--------------
Friday  2
Thursday 3
Weekend 3

This is my query so far

SELECT
  CASE
    WHEN DATENAME(weekday, [date]) = 'Saturday' OR DATENAME(weekday, [date]) = 'Sunday' THEN 'Weekend'
    ELSE DATENAME(weekday, [date])
  END AS Day,
  COUNT(DISTINCT [id]) AS score

  FROM [table]

GROUP BY
  CASE
    WHEN DATENAME(weekday, [date]) = 'Saturday' OR DATENAME(weekday, [date]) = 'Sunday' THEN 'Weekend'
    ELSE DATENAME(weekday, [date])
  END

Currently I can get my query to output this, but it seems like it isn't adding both thursdays or sat + sun.

Day | total
--------------
Friday 2
Thursday 2
Weekend 2

Body:
Appears like what you are actually after is a distinct count of the ID and date combined. Seems like the easiest way, therefore, would be to concatenate the 2 values to make a new unique value and COUNT those DISTINCT values:

SELECT CASE WHEN DATENAME(WEEKDAY, V.[Date]) IN ('Saturday','Sunday') THEN 'Weekend' ELSE DATENAME(WEEKDAY, V.[Date]) END AS [Weekday],
       COUNT(DISTINCT CONCAT(ID,[date]))
FROM (VALUES (13, CONVERT(datetime2(0),'2013-03-21T00:00:00')),
             (13, CONVERT(datetime2(0),'2013-03-23T00:00:00')),
             (13, CONVERT(datetime2(0),'2013-03-24T00:00:00')),
             (25, CONVERT(datetime2(0),'2013-03-21T00:00:00')),
             (25, CONVERT(datetime2(0),'2013-03-22T00:00:00')),
             (25, CONVERT(datetime2(0),'2013-03-21T00:00:00')),
             (25, CONVERT(datetime2(0),'2013-03-23T00:00:00')),
             (25, CONVERT(datetime2(0),'2013-03-28T00:00:00')),
             (25, CONVERT(datetime2(0),'2013-03-21T00:00:00')),
             (82, CONVERT(datetime2(0),'2013-03-22T00:00:00')),
             (82, CONVERT(datetime2(0),'2013-03-22T00:00:00'))) V (ID, [Date])
GROUP BY CASE WHEN DATENAME(WEEKDAY, V.[Date]) IN ('Saturday','Sunday') THEN 'Weekend' ELSE DATENAME(WEEKDAY, V.[Date]) END;


问:
Rerun a ngSwitch
I have an angular application and in one component I need to display a video. Depending on the user settings, two different videos can be displayed: one in English and another in German. The user can change this setting in this same component. At the moment that's how I have made it:

```<code><div [ngSwitch]="lang">
      <video
        id="some-id"
        class="video-js"
        muted
        oncanplay="this.muted=true"
        autoplay
        controls
        controlsList="nodownload"
        disablepictureinpicture
        preload="auto"
        width="100%"
        height="100%"
      >
        <source *ngSwitchCase="'en'" src="https://linktoEnglishVideo" type="video/mp4" />
        <source *ngSwitchCase="'de'" src="linktoGermanVideo" type="video/mp4" />
        <source *ngSwitchDefault src="https://linktoEnglishVideo" type="video/mp4" />
      </video>
</div>
</code>```

The problem is that whenever I change the setting (the lang variable) the ngSwitch doesn't re-run and the video is not re-loaded, staying the same no matter what.

Is there a way to force it to rerun and get the right video?

答:
You're missing quote marks:</p>

```<code><source *ngSwitchCase="'en'" src="https://linktoEnglishVideo" type="video/mp4" />
</code>```

Title: Rerun a ngSwitch

Body:
I have an angular application and in one component I need to display a video. Depending on the user settings, two different videos can be displayed: one in English and another in German. The user can change this setting in this same component. At the moment that's how I have made it:

      <video
        id="some-id"
        class="video-js"
        muted
        oncanplay="this.muted=true"
        autoplay
        controls
        controlsList="nodownload"
        disablepictureinpicture
        preload="auto"
        width="100%"
        height="100%"
      >
        <source *ngSwitchCase="'en'" src="https://linktoEnglishVideo" type="video/mp4" />
        <source *ngSwitchCase="'de'" src="linktoGermanVideo" type="video/mp4" />
        <source *ngSwitchDefault src="https://linktoEnglishVideo" type="video/mp4" />
      </video>

The problem is that whenever I change the setting (the lang variable) the ngSwitch doesn't re-run and the video is not re-loaded, staying the same no matter what.

Is there a way to force it to rerun and get the right video?

Body:
You're missing quote marks:

<source *ngSwitchCase="'en'" src="https://linktoEnglishVideo" type="video/mp4" />


问:
How would you position a HTML element while having animations running
I have CSS animations running on an HTML element but I am unable to position the HTML element freely on the HTML page so, how would I do this?

I have tried using doing this in order to position the HTML element freely on the page.

```<code><div style="text-align: center;"><p class="animated flipInX">2</p></div>
</code>```

But it does not work.

/* GLOBAL STYLES */
    body {
      background: #011;
      padding-top: 5em;
      display: flex;
      justify-content: center;
    }

    /* DEMO-SPECIFIC STYLES */
    .typewriter h1 {
      color: #fff;
      font-family: Consolas,monaco,monospace;
      overflow: hidden; /* Ensures the content is not revealed until the animation */
      border-right: .15em solid orange; /* The typwriter cursor */
      white-space: nowrap; /* Keeps the content on a single line */
      margin: 0 auto; /* Gives that scrolling effect as the typing happens */
      letter-spacing: .15em; /* Adjust as needed */
      animation:
        typing 3.5s steps(30, end),
        blink-caret .5s step-end infinite;
    }

    /* The typing effect */
    @keyframes typing {
      from { width: 0 }
      to { width: 100% }
    }

    /* The typewriter cursor effect */
    @keyframes blink-caret {
      from, to { border-color: transparent }
      50% { border-color: white }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <div class="typewriter">
      <h1>1</h1>
    </div>
    <head>
      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css">
      <p class="animated flipInX">2</p>
    </head>
    </html></code>```

答:
To position things anywhere on the screen, likely means you also want to be able to use any part of the screen even if there were items all over the page. Best way to do this is to use the position css property. so on whatever you want to move around, write a css class or id to it like this;

```<code>position: absolute;
z-index: 1;
top: 0px;
left: 200px;
</code>```

Here is a link I played with the example you gave. https://jsfiddle.net/cphutx78/

Let me know if it hel

Body:
I have CSS animations running on an HTML element but I am unable to position the HTML element freely on the HTML page so, how would I do this?

I have tried using doing this in order to position the HTML element freely on the page.

2

But it does not work.

/* GLOBAL STYLES */
    body {
      background: #011;
      padding-top: 5em;
      display: flex;
      justify-content: center;
    }

    /* DEMO-SPECIFIC STYLES */
    .typewriter h1 {
      color: #fff;
      font-family: Consolas,monaco,monospace;
      overflow: hidden; /* Ensures the content is not revealed until the animation */
      border-right: .15em solid orange; /* The typwriter cursor */
      white-space: nowrap; /* Keeps the content on a single line */
      margin: 0 auto; /* Gives that scrolling effect as the typing happens */
      letter-spacing: .15em; /* Adjust as needed */
      animation:
        typing 3.5s steps(30, end),
        blink-caret .5s step-end infinite;
    }

    /* The typing effect */
    @keyframes typing {
      from { width: 0 }
      to { width: 100% }
    }

    /* The typewriter cursor effect */
    @keyframes blink-caret {
      from, to { border-color: transparent }
      50% { border-color: white }
    }

    <link rel="stylesheet" type="text/css" href="styles.css">

1

      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css">

2

Body:
To position things anywhere on the screen, likely means you also want to be able to use any part of the screen even if there were items all over the page. Best way to do this is to use the position css property. so on whatever you want to move around, write a css class or id to it like this;

position: absolute;
z-index: 1;
top: 0px;
left: 200px;

Here is a link I played with the example you gave. https://jsfiddle.net/cphutx78/

Let me know if it hel


问:
Is there a way to match a specific pattern within curly braces multiple times using regex?
I use an older language that doesn't have any prebuilt syntax highlighters.

Although notepad++ has user defined language features there are some cases that aren't supported. For these cases I use a python script that applies syntax highlighting using regex.

My current issue I have run into is using regex to find patterns within curly braces. The pattern I'm trying to match is [A-Za-z_]\w* .
So basically, a variable name. However I would like to match only instances that occur within double curly braces.

In the following string I would like to match both instances of TimeStamps and Descending and nothing else.
Test Test2'{{TimeStamps(Descending(1))(7:8)}}/{{TimeStamps(Descending(1))(1:4)}} - '

I have tried variations of this (?<={{)([A-Za-z_]\w*)*(?=[0-9\(\)\:]*}}), however it feels like I'm over complicating it for myself.

Any help is appreciated. Thanks in advance.

答:
You may use

```<code>\b[A-Za-z_]\w*(?=(?:(?!{{|}}).)*}})
</code>```

See the regex demo

Details

\b - a word boundary

[A-Za-z_] - an ASCII letter or _

\w* - any 0 or more word chars (letters, digits or  _)

(?=(?:(?!{{|}}).)*}}) - a positive lookahead that requires

(?:(?!{{|}}).)* - any char, 0 or more occurrences, other than line break chars, that does not start a {{ or }} substring (it is a tempered greedy token)

}} - a }} substring.

Body:
You may use

\b[A-Za-z_]\w*(?=(?:(?!{{|}}).)*}})

See the regex demo

Details

\b - a word boundary

[A-Za-z_] - an ASCII letter or _

\w* - any 0 or more word chars (letters, digits or  _)

(?=(?:(?!{{|}}).)*}}) - a positive lookahead that requires

(?:(?!{{|}}).)* - any char, 0 or more occurrences, other than line break chars, that does not start a {{ or }} substring (it is a tempered greedy token)

}} - a }} substring.


问:
What is the correct way to bind a DataGrid to XML in MVVM?
I would like to bind a DataGrid to an XML file, that can be updated / changed via two-way binding.

Currently, the source doesn't change when updated.

I have attempted to build it using the following code:

XAML

```<code><DataGrid Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding CFCCDataView.DataView, UpdateSourceTrigger=PropertyChanged}"/>
</code>```

ViewModel

```<code>public XMLCFCCTranslationList CFCCDataView { get; set; }

public VM()
{
CFCCDataView = new XMLCFCCTranslationList();
}

</code>```

Model

```<code>    class XMLCFCCTranslationList : INotifyPropertyChanged
    {
        private void RaisePropertyChanged(string prop)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
        }
        public event PropertyChangedEventHandler PropertyChanged;

        private DataView _dataView;
        public DataView DataView
        {
            get => _dataView;
            set
            {
                if (_dataView == value) return;
                _dataView = value;
                RaisePropertyChanged("DataView");
            }
        }
        public XMLCFCCTranslationList()
        {
            var dataSet = new DataSet();
            dataSet.ReadXml(@"c:\file.xml");
            var cfccDataView = new DataView(dataSet.Tables[0]);
            DataView = cfccDataView;
        }
    }
</code>```

XML

```<code><?xml version="1.0" encoding="utf-8" ?>
<Translation xmlns="">
 <CFCCTranslation CFCC="A10" FUNC_CLASS="1" SPEED_CAT="5"  />
 <CFCCTranslation CFCC="A20" FUNC_CLASS="2" SPEED_CAT="5"  />
 <CFCCTranslation CFCC="A30" FUNC_CLASS="3" SPEED_CAT="5"  />
 <CFCCTranslation CFCC="A40" FUNC_CLASS="4" SPEED_CAT="5"  />
 <CFCCTranslation CFCC="A50" FUNC_CLASS="5" SPEED_CAT="5"  />
 <CFCCTranslation CFCC="A71" FUNC_CLASS="6" SPEED_CAT="5"  />
 <CFCCTranslation CFCC="B10" FUNC_CLASS="7" SPEED_CAT="5"  />
</Translation>
</code>```

答:
You should add DataCntext to view for it knew from where take data,

In your xaml.cs:

```<code>   public partial class MainWindow : Window
{
    private readonly ViewModel viewModel = new ViewModel();
    public MainWindow()
    {
        DataContext = viewModel;
        InitializeComponent();
    }
}
</code>```

Body:
I would like to bind a DataGrid to an XML file, that can be updated / changed via two-way binding.

Currently, the source doesn't change when updated.

I have attempted to build it using the following code:

XAML

<DataGrid Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding CFCCDataView.DataView, UpdateSourceTrigger=PropertyChanged}"/>

ViewModel

public XMLCFCCTranslationList CFCCDataView { get; set; }

public VM()
{
CFCCDataView = new XMLCFCCTranslationList();
}

Model

    class XMLCFCCTranslationList : INotifyPropertyChanged
    {
        private void RaisePropertyChanged(string prop)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
        }
        public event PropertyChangedEventHandler PropertyChanged;

        private DataView _dataView;
        public DataView DataView
        {
            get => _dataView;
            set
            {
                if (_dataView == value) return;
                _dataView = value;
                RaisePropertyChanged("DataView");
            }
        }
        public XMLCFCCTranslationList()
        {
            var dataSet = new DataSet();
            dataSet.ReadXml(@"c:\file.xml");
            var cfccDataView = new DataView(dataSet.Tables[0]);
            DataView = cfccDataView;
        }
    }

XML

<?xml version="1.0" encoding="utf-8" ?>
<Translation xmlns="">
 <CFCCTranslation CFCC="A10" FUNC_CLASS="1" SPEED_CAT="5"  />
 <CFCCTranslation CFCC="A20" FUNC_CLASS="2" SPEED_CAT="5"  />
 <CFCCTranslation CFCC="A30" FUNC_CLASS="3" SPEED_CAT="5"  />
 <CFCCTranslation CFCC="A40" FUNC_CLASS="4" SPEED_CAT="5"  />
 <CFCCTranslation CFCC="A50" FUNC_CLASS="5" SPEED_CAT="5"  />
 <CFCCTranslation CFCC="A71" FUNC_CLASS="6" SPEED_CAT="5"  />
 <CFCCTranslation CFCC="B10" FUNC_CLASS="7" SPEED_CAT="5"  />
</Translation>

Body:
You should add DataCntext to view for it knew from where take data,

In your xaml.cs:

   public partial class MainWindow : Window
{
    private readonly ViewModel viewModel = new ViewModel();
    public MainWindow()
    {
        DataContext = viewModel;
        InitializeComponent();
    }
}


问:
Laravel: save image in database
I am trying to store an image in my images table that is related to the articles table

When I do this the following error appears:

Indirect modification of overloaded property App\Article::$thumbnail has no effect.

My Article Model:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $fillable = [
        'title', 'exerpt', 'body'
    ];

    public function author()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function tags()
    {
        return $this->belongsToMany(Tag::class);
    }

    public function thumbnail()
    {
        return $this->hasOne(Image::class);
    }
}
</code>```

My Image Model:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    public function article()
    {
        return $this->belongsTo(Article::class);
    }
}
</code>```

And the store method in my ArticleController:

```<code>public function store(Request $request)
    {
        $article = new Article($this->validateArticle($request));

        //hardcoded for now
        $article->user_id = 1;

        $thumbnail = '';

        $destinationPath = storage_path('app/public/thumbnails');

        $file = $request->thumbnail;

        $fileName = $file->clientExtension();

        $file->move($destinationPath, $fileName);

        $article->thumbnail->title = $file;

        $article->save();

        $article->tags()->attach(request('tags'));

        return redirect(route('articles'));
    }
</code>```

答:
Related to your Laravel version, this may works for you:</p>

```<code>$article = new Article( $this->validateArticle( $request ) );
$article->user_id = 1;
$article->save();
$article->tags()->attach( request( 'tags' ) );

if( $request->hasFile( 'thumbnail' ) ) {
    $destinationPath = storage_path( 'app/public/thumbnails' );
    $file = $request->thumbnail;
    $fileName = time() . '.'.$file->clientExtension();
    $file->move( $destinationPath, $fileName );

    $image = new Image;
    $image->title = $fileName;
    $image->article_id = $article->id;
    $image->save();
}
</code>```

Title: Laravel: save image in database

Body:
I am trying to store an image in my images table that is related to the articles table

When I do this the following error appears:

Indirect modification of overloaded property App\Article::$thumbnail has no effect.

My Article Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $fillable = [
        'title', 'exerpt', 'body'
    ];

    public function author()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function tags()
    {
        return $this->belongsToMany(Tag::class);
    }

    public function thumbnail()
    {
        return $this->hasOne(Image::class);
    }
}

My Image Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    public function article()
    {
        return $this->belongsTo(Article::class);
    }
}

And the store method in my ArticleController:

public function store(Request $request)
    {
        $article = new Article($this->validateArticle($request));

        //hardcoded for now
        $article->user_id = 1;

        $thumbnail = '';

        $destinationPath = storage_path('app/public/thumbnails');

        $file = $request->thumbnail;

        $fileName = $file->clientExtension();

        $file->move($destinationPath, $fileName);

        $article->thumbnail->title = $file;

        $article->save();

        $article->tags()->attach(request('tags'));

        return redirect(route('articles'));
    }

Body:
Related to your Laravel version, this may works for you:

$article = new Article( $this->validateArticle( $request ) );
$article->user_id = 1;
$article->save();
$article->tags()->attach( request( 'tags' ) );

if( $request->hasFile( 'thumbnail' ) ) {
    $destinationPath = storage_path( 'app/public/thumbnails' );
    $file = $request->thumbnail;
    $fileName = time() . '.'.$file->clientExtension();
    $file->move( $destinationPath, $fileName );

    $image = new Image;
    $image->title = $fileName;
    $image->article_id = $article->id;
    $image->save();
}


问:
Url query parameters becoming visibly encoded upon redirect - Symfony 2
I am attempting to persist my query parameters when redirecting to a new path with Symfony2, however the method I am using appears to show encoded query parameters in the URL...

```<code>return $this->redirect(
    $this->generateUrl(
        'my_page_name',
        [
            'myVar' => $myVar,
            $request->query->all()
            // I have also tried $request->getQueryString() with the same result...
        ]
    )
);
</code>```

When sending an URL with query params such as

my-domain.com/some-page?var1=test&var2=test

I can visibly see the URL change in the browser on redirect to something resembling

my-domain.com/some-page?0var1%3Dtest%26var2%3Dtest

My question here is...

1) Does this affect the actual URL being navigated to
2) Is there any way in which I can stop this and keep the URL looking as it was entered?

答:
It is encoding request parameters because you are passing whole array as parameter which in terms gets serialized, to avoid that you need to pass each parameter individually. This can be achieved by merging arrays.

So solution would look like :

```<code>return $this->redirect(
    $this->generateUrl(
        'my_page_name',
        array_merge(
            array(
                'myVar' => $myVar,
                'myVar2' => $myVar2
            ),
            $request->query->all()
      )
    )
);
</code>```

Body:
I am attempting to persist my query parameters when redirecting to a new path with Symfony2, however the method I am using appears to show encoded query parameters in the URL...

return $this->redirect(
    $this->generateUrl(
        'my_page_name',
        [
            'myVar' => $myVar,
            $request->query->all()
            // I have also tried $request->getQueryString() with the same result...
        ]
    )
);

When sending an URL with query params such as

my-domain.com/some-page?var1=test&var2=test

I can visibly see the URL change in the browser on redirect to something resembling

my-domain.com/some-page?0var1%3Dtest%26var2%3Dtest

My question here is...

1) Does this affect the actual URL being navigated to
2) Is there any way in which I can stop this and keep the URL looking as it was entered?

Body:
It is encoding request parameters because you are passing whole array as parameter which in terms gets serialized, to avoid that you need to pass each parameter individually. This can be achieved by merging arrays.

So solution would look like :

return $this->redirect(
    $this->generateUrl(
        'my_page_name',
        array_merge(
            array(
                'myVar' => $myVar,
                'myVar2' => $myVar2
            ),
            $request->query->all()
      )
    )
);


问:
Maven deploy: deployment should fail if artifact already exists
If I configure my pom.xml as below:

```<code>        <plugin>
            <artifactId>maven-deploy-plugin</artifactId>
            <version>2.8.1</version>
            <executions>
                <execution>
                    <id>default-deploy</id>
                    <phase>deploy</phase>
                    <goals>
                        <goal>deploy</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <serverId>nexus</serverId>
                <nexusUrl>https://nexus/</nexusUrl>
                <skipStaging>false</skipStaging>
            </configuration>
        </plugin>
</code>```

Then what happens is that on executing mvn deploy -this will deploy projectName-1.0-20180323.065217-1.jar on Nexus and the next deployment will have projectName-1.0-20180323.065217-2.jar deployed on nexus.

Is it possible to check if the snapshot version (in this case 1.0) is already present in nexus repo (and it gives a fail message that the version cannot be deployed).

The deployed version should be named as projectName-1.0.jar instead of projectName-1.0-20180323.065217-1.jar

答:
The mvn deploy will fail if the artifact to be uploaded is already in the repository

Note: only if you upload as a "RELEASE", not a "SNAPSHOT".

Your build could check first if that release version exists:

mvn dependency:get -Dartifact=g:a:v -o -DrepoUrl=file://path/to/your/repo

Body:
If I configure my pom.xml as below:

        <plugin>
            <artifactId>maven-deploy-plugin</artifactId>
            <version>2.8.1</version>
            <executions>
                <execution>
                    <id>default-deploy</id>
                    <phase>deploy</phase>
                    <goals>
                        <goal>deploy</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <serverId>nexus</serverId>
                <nexusUrl>https://nexus/</nexusUrl>
                <skipStaging>false</skipStaging>
            </configuration>
        </plugin>

Then what happens is that on executing mvn deploy -this will deploy projectName-1.0-20180323.065217-1.jar on Nexus and the next deployment will have projectName-1.0-20180323.065217-2.jar deployed on nexus.

Is it possible to check if the snapshot version (in this case 1.0) is already present in nexus repo (and it gives a fail message that the version cannot be deployed).

The deployed version should be named as projectName-1.0.jar instead of projectName-1.0-20180323.065217-1.jar


问:
install System.Net.Http to .net framework 4.0 project
I need use AuthenticationHeaderValue for getting token

```<code>var token = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}")));
</code>```

so I have to install System.Net.Http package but when I install it via package manager console it give that error
what should I do?
what is AuthenticationHeaderValue alternative?

Could not install package 'System.Net.Http 4.0.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.0', but the package does not contain any assembly  references or content files that are compatible with that framework.

答: Install System.Net.http version which is compatible to your .Net Framework</p>

Body:
I need use AuthenticationHeaderValue for getting token

var token = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}")));

so I have to install System.Net.Http package but when I install it via package manager console it give that error
what should I do?
what is AuthenticationHeaderValue alternative?

Could not install package 'System.Net.Http 4.0.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.0', but the package does not contain any assembly  references or content files that are compatible with that framework.


问:
How to set custom date programmatically using ng bootstrap & angular 6?
Here I am trying to set a date programmatically using ng-bootstrap date picker

I tried some thing like this putting the custom date

```<code>this.model= {
  "year": 2018,
  "month": 8,
  "day": 15
}
</code>```

I know it is not efficient way and there is one issue is that after selecting the giving the date picker is not navigating to that particular month.

Suppose If I choose 2nd jan 2018 then also it is staying in the current month it is not moving to jan. How can i solve these issues?

Below is my code & stack blitz link

.ts code

```<code>model: NgbDateStruct;
  date: {year: number, month: number};
  constructor(private calendar: NgbCalendar){

  }

   selectToday() {
    this.model = this.calendar.getToday();
  }

  select(){
    this.model= {
  "year": 2018,
  "month": 8,
  "day": 15
}
</code>```

.html file

```<code><ngb-datepicker #dp [(ngModel)]="model" (navigate)="date = $event.next"></ngb-datepicker>
</code>```

答:
Create NgbDate instance by,

```<code>date = new NgbDate(2020,19,2);
</code>```

make this date as ngModel;

See https://ng-bootstrap.github.io/#/components/datepicker/api#NgbDate

Body:
Here I am trying to set a date programmatically using ng-bootstrap date picker

I tried some thing like this putting the custom date

this.model= {
  "year": 2018,
  "month": 8,
  "day": 15
}

I know it is not efficient way and there is one issue is that after selecting the giving the date picker is not navigating to that particular month.

Suppose If I choose 2nd jan 2018 then also it is staying in the current month it is not moving to jan. How can i solve these issues?

Below is my code & stack blitz link

.ts code

model: NgbDateStruct;
  date: {year: number, month: number};
  constructor(private calendar: NgbCalendar){

  }

   selectToday() {
    this.model = this.calendar.getToday();
  }

  select(){
    this.model= {
  "year": 2018,
  "month": 8,
  "day": 15
}

.html file

<ngb-datepicker #dp [(ngModel)]="model" (navigate)="date = $event.next"></ngb-datepicker>

Body:
Create NgbDate instance by,

date = new NgbDate(2020,19,2);

make this date as ngModel;

See https://ng-bootstrap.github.io/#/components/datepicker/api#NgbDate