问:
Duplicate id key error with mongoDB E11000
I'm creating a todos app with MERN stack, and in an attempt to create personal todos for each user, I found this error:

```<code>MongoServerError: E11000 duplicate key error collection: Todos-APP.todos index: _id_ dup key: { _id: ObjectId('6201a648189af9a06ac75ca1') }
    at C:\Users\Administrador\Documents\GitHub\todos-app\server\node_modules\mongodb\lib\operations\insert.js:51:33
    at C:\Users\Administrador\Documents\GitHub\todos-app\server\node_modules\mongodb\lib\cmap\connection_pool.js:272:25
    at handleOperationResult (C:\Users\Administrador\Documents\GitHub\todos-app\server\node_modules\mongodb\lib\sdam\server.js:370:9)
    at MessageStream.messageHandler (C:\Users\Administrador\Documents\GitHub\todos-app\server\node_modules\mongodb\lib\cmap\connection.js:479:9)
    at MessageStream.emit (node:events:390:28)
    at processIncomingData (C:\Users\Administrador\Documents\GitHub\todos-app\server\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
    at MessageStream._write (C:\Users\Administrador\Documents\GitHub\todos-app\server\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10)
    at MessageStream.Writable.write (node:internal/streams/writable:334:10) {
  index: 0,
  code: 11000,
  keyPattern: { _id: 1 },
  keyValue: {
    _id: ObjectId {
      [Symbol(id)]: Buffer(12) [Uint8Array] [
         98,   1, 166,  72,  24,
        154, 249, 160, 106, 199,
         92, 161
      ]
    }
  }
}
</code>```

I have well-founded suspicions that the problem arises because in my Todo Schema, I have a field 'owner' which gets populated with the client's _id from MongoDB (the client that sent the request to create the new todo):

const mongoose = require('mongoose');

const TodoSchema = new mongoose.Schema({

    _id: {
        type: mongoose.Types.ObjectId,
        default: mongoose.Types.ObjectId()
    },
    owner: {
        type: mongoose.Types.ObjectId,
        ref: 'User'
    },
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    isCompleted: {
        type: Boolean,
        required: true
    }

});

module.exports = mongoose.model('Todo', TodoSchema);
```
<p>Now, this is how the server is handling the request:</p>
<pre class="lang-js prettyprint-override"><code>// Create Todo
router.post('/createTodo', async (req, res) => {
    const { ownerName, title, description, isCompleted } = req.body;

    if(!title || !description || isCompleted === null || ownerName === null) return res.status(400).send();

    const owner = await User.findOne({ username: ownerName }).exec();

    const existingTodo = await Todo.findOne({ owner: owner._id, title: title }).exec();

    if(existingTodo) return res.status(409).send();

    try {
        const todo = new Todo({
            owner: owner._id,
            title,
            description,
            isCompleted
        })

        todo.save();
        res.status(200).send();

    } catch (error) {
        console.error(`ERROR: ${error}`);
        res.status(409).end();
    }
});
</code>```

I'd like to add that I've noticed that once I log in, I can successfully create a new todo, but if I try to create another one within the same session, it throws that error, but if the session expires and I log in again, then I can create another new todo; just one todo per session.

答:
Try to remove explicitly adding _id to schema with value of mongoose.Types.ObjectId(). Remove these lines from schema definition.

_id: {
  type: mongoose.Types.ObjectId,
  default: mongoose.Types.ObjectId()
},
```

Mongo will create unique _id by default. To create ObjectId with Mongoose, I think you should use new mongoose.Types.ObjectId(). So maybe you are missing new keyword.

Body:
I'm creating a todos app with MERN stack, and in an attempt to create personal todos for each user, I found this error:

MongoServerError: E11000 duplicate key error collection: Todos-APP.todos index: _id_ dup key: { _id: ObjectId('6201a648189af9a06ac75ca1') }
    at C:\Users\Administrador\Documents\GitHub\todos-app\server\node_modules\mongodb\lib\operations\insert.js:51:33
    at C:\Users\Administrador\Documents\GitHub\todos-app\server\node_modules\mongodb\lib\cmap\connection_pool.js:272:25
    at handleOperationResult (C:\Users\Administrador\Documents\GitHub\todos-app\server\node_modules\mongodb\lib\sdam\server.js:370:9)
    at MessageStream.messageHandler (C:\Users\Administrador\Documents\GitHub\todos-app\server\node_modules\mongodb\lib\cmap\connection.js:479:9)
    at MessageStream.emit (node:events:390:28)
    at processIncomingData (C:\Users\Administrador\Documents\GitHub\todos-app\server\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
    at MessageStream._write (C:\Users\Administrador\Documents\GitHub\todos-app\server\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10)
    at MessageStream.Writable.write (node:internal/streams/writable:334:10) {
  index: 0,
  code: 11000,
  keyPattern: { _id: 1 },
  keyValue: {
    _id: ObjectId {
      [Symbol(id)]: Buffer(12) [Uint8Array] [
         98,   1, 166,  72,  24,
        154, 249, 160, 106, 199,
         92, 161
      ]
    }
  }
}

I have well-founded suspicions that the problem arises because in my Todo Schema, I have a field 'owner' which gets populated with the client's _id from MongoDB (the client that sent the request to create the new todo):

const mongoose = require('mongoose');

const TodoSchema = new mongoose.Schema({

    _id: {
        type: mongoose.Types.ObjectId,
        default: mongoose.Types.ObjectId()
    },
    owner: {
        type: mongoose.Types.ObjectId,
        ref: 'User'
    },
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    isCompleted: {
        type: Boolean,
        required: true
    }

});

module.exports = mongoose.model('Todo', TodoSchema);

Now, this is how the server is handling the request:

// Create Todo
router.post('/createTodo', async (req, res) => {
    const { ownerName, title, description, isCompleted } = req.body;

    if(!title || !description || isCompleted === null || ownerName === null) return res.status(400).send();

    const owner = await User.findOne({ username: ownerName }).exec();

    const existingTodo = await Todo.findOne({ owner: owner._id, title: title }).exec();

    if(existingTodo) return res.status(409).send();

    try {
        const todo = new Todo({
            owner: owner._id,
            title,
            description,
            isCompleted
        })

        todo.save();
        res.status(200).send();

    } catch (error) {
        console.error(`ERROR: ${error}`);
        res.status(409).end();
    }
});

I'd like to add that I've noticed that once I log in, I can successfully create a new todo, but if I try to create another one within the same session, it throws that error, but if the session expires and I log in again, then I can create another new todo; just one todo per session.

Body:
Try to remove explicitly adding _id to schema with value of mongoose.Types.ObjectId(). Remove these lines from schema definition.

_id: {
  type: mongoose.Types.ObjectId,
  default: mongoose.Types.ObjectId()
},

Mongo will create unique _id by default. To create ObjectId with Mongoose, I think you should use new mongoose.Types.ObjectId(). So maybe you are missing new keyword.


来源: stackexchange

问:
Remove all elements in a IList that contains any of the other List's elements
I have some strings in a IList as such:

IList - { "Apple", "Apple2" , Banana, Orange, "AppleBanana", Orange2, "Berries"};

I want to remove all of the elements that contains any elements from this list.
List - {"apple", "orange", "grape"}

I am expecting the IList to be returned as - {Banana, "Berries"}

```<code>            Food food1 = new Food();
            Fruits fruit1 = new Fruits();
            fruit1.Name = "Apple";
            food1.fruits.Add(fruit1);
            Fruits fruit2 = new Fruits();
            fruit1.Name = "Apple2";
            food1.fruits.Add(fruit2);
            Fruits fruit3 = new Fruits();
            fruit1.Name = "Banana";
            food1.fruits.Add(fruit3);
            Fruits fruit4 = new Fruits();
            fruit1.Name = "AppleBanana";
            food1.fruits.Add(fruit4);
            Fruits fruit5 = new Fruits();
            fruit1.Name = "Orange";
            food1.fruits.Add(fruit5);
            Fruits fruit6 = new Fruits();
            fruit1.Name = "Orange2";
            food1.fruits.Add(fruit6);
            Fruits fruit7 = new Fruits();
            fruit1.Name = "Berries";
            food1.fruits.Add(fruit7);
        }
        public class Food
        {
            public IList<Fruits> fruits;

            public Food()
            {
                fruits = new List<Fruits>();
            }
        }

        public class Fruits
        {
            public string Name;
        }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have some strings in a IList as such:

IList - { "Apple", "Apple2" , Banana, Orange, "AppleBanana", Orange2, "Berries"};

I want to remove all of the elements that contains any elements from this list.
List - {"apple", "orange", "grape"}

I am expecting the IList to be returned as - {Banana, "Berries"}

            Food food1 = new Food();
            Fruits fruit1 = new Fruits();
            fruit1.Name = "Apple";
            food1.fruits.Add(fruit1);
            Fruits fruit2 = new Fruits();
            fruit1.Name = "Apple2";
            food1.fruits.Add(fruit2);
            Fruits fruit3 = new Fruits();
            fruit1.Name = "Banana";
            food1.fruits.Add(fruit3);
            Fruits fruit4 = new Fruits();
            fruit1.Name = "AppleBanana";
            food1.fruits.Add(fruit4);
            Fruits fruit5 = new Fruits();
            fruit1.Name = "Orange";
            food1.fruits.Add(fruit5);
            Fruits fruit6 = new Fruits();
            fruit1.Name = "Orange2";
            food1.fruits.Add(fruit6);
            Fruits fruit7 = new Fruits();
            fruit1.Name = "Berries";
            food1.fruits.Add(fruit7);
        }
        public class Food
        {
            public IList<Fruits> fruits;

            public Food()
            {
                fruits = new List<Fruits>();
            }
        }

        public class Fruits
        {
            public string Name;
        }

Body: list1.Where(f=>list2.Contains(f)).ToList();


问:
ASP.NET Button click redirect to new page
I have created a Button programmatically.
I now want to redirect to a new aspx page on the click of this Button, such that we will enter into one of the methods of the new page (like page_load(), etc.)

Is this possible?

Eg:

```<code>Button oButton = new Button;
oButton.Text = "NextPage";
// Redirect to "Redirect.aspx" on click
</code>```

But I am not able to find an entry point in Redirect.aspx where I can do some changes to the UI components once we get redirected to "Redirect.aspx"

Regards,

Parag

答:
You need to handle Click event of oButton.

```<code>Button oButton = new Button();
 oButton.Text = "NextPage";
 oButton.Click += (sa, ea) =>
     {
         Response.Redirect("Redirect.aspx");
   };
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have created a Button programmatically.
I now want to redirect to a new aspx page on the click of this Button, such that we will enter into one of the methods of the new page (like page_load(), etc.)

Is this possible?

Eg:

Button oButton = new Button;
oButton.Text = "NextPage";
// Redirect to "Redirect.aspx" on click

But I am not able to find an entry point in Redirect.aspx where I can do some changes to the UI components once we get redirected to "Redirect.aspx"

Regards,

Parag

Body:
You need to handle Click event of oButton.

Button oButton = new Button();
 oButton.Text = "NextPage";
 oButton.Click += (sa, ea) =>
     {
         Response.Redirect("Redirect.aspx");
   };


问:
Problem using Mat-Dialog in a Service in Angular
I am having a problem trying to get mat-Dialog to work in a service. I can call the same code from my template with an onclick event but if i try to use the service this component consumes it fails with this error

TypeError: Cannot read properties of undefined (reading 'open')

Below is the code of the service which gets triggered when user try's to upload a file. It triggers it as expected and all works except i cant show the dialog box. Wondering if there is a certain way i have to do this in service vs a form ?

```<code>import {Inject, Injectable, OnDestroy} from '@angular/core';
import {environment} from '../../environments/environment';
import {switchMap, take, takeWhile} from 'rxjs/operators';
import {ModalImagePropertiesComponent} from '../modules/image-before-upload/modal-image-properties/modal-image-properties.component';
import {IUploadedImageProperties} from '../modules/uploaded-image-properties';
import {MAT_DIALOG_DATA, MatDialog, MatDialogRef} from '@angular/material/dialog';

@Injectable({
  providedIn: 'root'
})
  constructor(
    private authService: AuthService,
    private http: HttpClient,
    public toasterService: ToasterService,
    @Inject(IgxOverlayService) private overlayService: IgxOverlayService,
    private dialog: MatDialog,
    //@Optional() @Inject(MAT_DIALOG_DATA) public data: any,
    private dialogRef: MatDialogRef<ModalImagePropertiesComponent>,

  ) {
  }
// New Upload Service
  initNewUploadEvents(): Object {
    const _froalaUploadService = this;
    console.log('Calling New Upload')
    return {
      'image.beforeUpload': function (images) {
        // make copies of the data passed in since they are lost after false is returned to froala from this callback
        const copies = {
          editor: this,  // {...editor}, // make full copy of editor object
          // e: {...e}, // make full copy of the event
          images: {...images}, // make full copy of the images
        };
        let imageBase64 = null;
        // create reader
        if (images.length) {
          // Create a File Reader.
          const reader = new FileReader();
          // Set the reader to insert images when they are loaded.
          reader.onload = (ev) => {
            imageBase64 = ev.target['result'];
          // console.log('file reader result ', imageBase64);
          };
          // Read image as base64.
          reader.readAsDataURL(images[0]);
        }

        _froalaUploadService.editorInstance = this;

            const modalInstance = {}
            // Splitting the name (filename) here and taking the first part which represents the name without the extension
            modalInstance.imageProperties = {
              filename: copies.images[0].name.split('.')[0],
              original_filename: copies.images[0].name,
              myFile: imageBase64,
              user_id: _froalaUploadService.userId,
            };

        const dialogRef = this.dialog.open(ModalImagePropertiesComponent,
          {
            data: row,
            disableClose: false, width: '600px', position: {
              top: '50px'
            },
          })

            console.log(modalInstance.imageProperties)

      },
</code>```

答:
I think the context of this gets lost in the function. But you are keeping reference in the local variable _froalaUploadService = this

const dialogRef = _froalaUploadService.dialog.open(ModalImagePropertiesComponent,
    {
      data: row,
      disableClose: false, width: '600px', position: {
      top: '50px'
    },
  });
```

Body:
I am having a problem trying to get mat-Dialog to work in a service. I can call the same code from my template with an onclick event but if i try to use the service this component consumes it fails with this error

TypeError: Cannot read properties of undefined (reading 'open')

Below is the code of the service which gets triggered when user try's to upload a file. It triggers it as expected and all works except i cant show the dialog box. Wondering if there is a certain way i have to do this in service vs a form ?

import {Inject, Injectable, OnDestroy} from '@angular/core';
import {environment} from '../../environments/environment';
import {switchMap, take, takeWhile} from 'rxjs/operators';
import {ModalImagePropertiesComponent} from '../modules/image-before-upload/modal-image-properties/modal-image-properties.component';
import {IUploadedImageProperties} from '../modules/uploaded-image-properties';
import {MAT_DIALOG_DATA, MatDialog, MatDialogRef} from '@angular/material/dialog';

@Injectable({
  providedIn: 'root'
})
  constructor(
    private authService: AuthService,
    private http: HttpClient,
    public toasterService: ToasterService,
    @Inject(IgxOverlayService) private overlayService: IgxOverlayService,
    private dialog: MatDialog,
    //@Optional() @Inject(MAT_DIALOG_DATA) public data: any,
    private dialogRef: MatDialogRef<ModalImagePropertiesComponent>,

  ) {
  }
// New Upload Service
  initNewUploadEvents(): Object {
    const _froalaUploadService = this;
    console.log('Calling New Upload')
    return {
      'image.beforeUpload': function (images) {
        // make copies of the data passed in since they are lost after false is returned to froala from this callback
        const copies = {
          editor: this,  // {...editor}, // make full copy of editor object
          // e: {...e}, // make full copy of the event
          images: {...images}, // make full copy of the images
        };
        let imageBase64 = null;
        // create reader
        if (images.length) {
          // Create a File Reader.
          const reader = new FileReader();
          // Set the reader to insert images when they are loaded.
          reader.onload = (ev) => {
            imageBase64 = ev.target['result'];
          // console.log('file reader result ', imageBase64);
          };
          // Read image as base64.
          reader.readAsDataURL(images[0]);
        }

        _froalaUploadService.editorInstance = this;

            const modalInstance = {}
            // Splitting the name (filename) here and taking the first part which represents the name without the extension
            modalInstance.imageProperties = {
              filename: copies.images[0].name.split('.')[0],
              original_filename: copies.images[0].name,
              myFile: imageBase64,
              user_id: _froalaUploadService.userId,
            };

        const dialogRef = this.dialog.open(ModalImagePropertiesComponent,
          {
            data: row,
            disableClose: false, width: '600px', position: {
              top: '50px'
            },
          })

            console.log(modalInstance.imageProperties)

      },


问:
C# Split a List in Columns
I am trying to split a List in C# and display the results in columns like this:

```<code>ID 1  ID 2
ID 3  ID 4
ID 5  ID 6
</code>```

Instead of displaying them like this:

```<code>ID 1
ID 2
ID 3
ID 4
ID 5
ID 6
</code>```

This is my list:

```<code>private List<ID> IDs = new List<ID>();
</code>```

And I'm trying to do something like this:

```<code>int chunkNumber = 1;
foreach (int[] chunk in Enumerable.Range(0, 8).Chunk(3))
{
    Console.WriteLine($"Chunk {chunkNumber++}:");
    foreach (int item in chunk)
    {
        Console.WriteLine($"    {item}");
    }

    Console.WriteLine();
}
</code>```

Any help on how to accomplish this?
Thanks

答:
You can index by steps of 2 with a for-loop

```<code>for (int i = 0; i < IDs.Count; i += 2)
{
    Console.WriteLine($"{IDs[i]}  {IDs[i+1]}");
}
</code>```

This will only work if the list has an even number of elements. To be able to handle odd-length lists, try something like this

```<code>for (int i = 0; i < IDs.Count; i += 2)
{
    if (i < IDs.Count - 1)
        Console.WriteLine($"{IDs[i]}  {IDs[i+1]}");
    else
        Console.WriteLine($"{IDs[i]}");
}
</code>```

Title: C# Split a List in Columns

Body:
I am trying to split a List in C# and display the results in columns like this:

ID 1  ID 2
ID 3  ID 4
ID 5  ID 6

Instead of displaying them like this:

ID 1
ID 2
ID 3
ID 4
ID 5
ID 6

This is my list:

private List<ID> IDs = new List<ID>();

And I'm trying to do something like this:

int chunkNumber = 1;
foreach (int[] chunk in Enumerable.Range(0, 8).Chunk(3))
{
    Console.WriteLine($"Chunk {chunkNumber++}:");
    foreach (int item in chunk)
    {
        Console.WriteLine($"    {item}");
    }

    Console.WriteLine();
}

Any help on how to accomplish this?
Thanks

Body:
You can index by steps of 2 with a for-loop

for (int i = 0; i < IDs.Count; i += 2)
{
    Console.WriteLine($"{IDs[i]}  {IDs[i+1]}");
}

This will only work if the list has an even number of elements. To be able to handle odd-length lists, try something like this

for (int i = 0; i < IDs.Count; i += 2)
{
    if (i < IDs.Count - 1)
        Console.WriteLine($"{IDs[i]}  {IDs[i+1]}");
    else
        Console.WriteLine($"{IDs[i]}");
}


问:
How can I create view more and make my word stand in same line?
I'm having an issues with css that my "Room Description" is splitting 2 line.

When I add white-space: nowrap it become like this:

Here is my code base:

```<code>  <span className="room-type mv-print-link">
    {this.props.waitlistRooms.map((room: any, i: any) => (
        <div>
        {this.props.waitlistRooms.length > 0 ? &&
          <span
            onClick={() => this.toggleRoomModal(resortId || "", room.roomPoolCode)}
            key={i}
          >
            <b>{"Room Description, "}</b>
          </span>
        )
        </div>
      ))}
</code>```

css file:

```<code>.room-type-container
    display: flex
    flex-direction: column
    margin-bottom: 15px
    .room-type
        display: flex
        flex-direction: row
        flex-shrink: 0
        width: 300px
</code>```

How can I achieve when there is more than 3 rooms and it will appear View More button? Thanks for helping me

答:
so the mechanic you want should work like this:

when you have only 3 (or any other default) rooms, just show them.
lets say you have a list of rooms, so something like:

{roomsList.map((room) => {room.name}: {room.description})}```
</div>
</div>
</p>
<p>now, if you have more than the default rooms number (3 in our case), you want to render also the rest, but out of the view. in order to accomplish this, you should do the follow:</p>
<ul>
<li>split your array in 2: first-3-items, rest-of-items.</li>
<li>render first array.</li>
<li>if the length of the second array is bigger than 0, render a 'View More' button using react-collapsible (which makes the collapsible behaviour you desire) and inside of it render the rest of the rooms.</li>
</ul>
<p>in a quick example it should look something like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//after splitting the array you will have:

const roomsArray1 = [{name:' roomA', description: 'niceA'},{name:' roomB', description: 'niceB'},{name:' roomC', description: 'niceC'}
const roomsArray2 = [{name:' roomD', description: 'niceD'},{name:' roomE', description: 'niceE'}];

{roomsArray1.map((room) => <span>{room.name}: {room.description})</span>}
{roomsArray2.length > 0 &&
  <Collapsible trigger="View More">
    {roomsArray2.map((room) => <span>{room.name}: {room.description})</span>}
  </Collapsible>
    </code>```

You can add styles as you like (spaces, colors, etc..)

By this, you will only show only part of the rooms, and by clicking the 'View More' button, more will appear.

Body:
I'm having an issues with css that my "Room Description" is splitting 2 line.

When I add white-space: nowrap it become like this:

Here is my code base:

    {this.props.waitlistRooms.map((room: any, i: any) => (

        {this.props.waitlistRooms.length > 0 ? &&
           this.toggleRoomModal(resortId || "", room.roomPoolCode)}
            key={i}
          >
            {"Room Description, "}

        )

      ))}

css file:

.room-type-container
    display: flex
    flex-direction: column
    margin-bottom: 15px
    .room-type
        display: flex
        flex-direction: row
        flex-shrink: 0
        width: 300px

How can I achieve when there is more than 3 rooms and it will appear View More button? Thanks for helping me

Body:
so the mechanic you want should work like this:

when you have only 3 (or any other default) rooms, just show them.
lets say you have a list of rooms, so something like:

{roomsList.map((room) => <span>{room.name}: {room.description})}

now, if you have more than the default rooms number (3 in our case), you want to render also the rest, but out of the view. in order to accomplish this, you should do the follow:

split your array in 2: first-3-items, rest-of-items.

render first array.

if the length of the second array is bigger than 0, render a 'View More' button using react-collapsible (which makes the collapsible behaviour you desire) and inside of it render the rest of the rooms.

in a quick example it should look something like this:

//after splitting the array you will have:

const roomsArray1 = [{name:' roomA', description: 'niceA'},{name:' roomB', description: 'niceB'},{name:' roomC', description: 'niceC'}
const roomsArray2 = [{name:' roomD', description: 'niceD'},{name:' roomE', description: 'niceE'}];

{roomsArray1.map((room) => <span>{room.name}: {room.description})</span>}
{roomsArray2.length > 0 &&
  <Collapsible trigger="View More">
    {roomsArray2.map((room) => <span>{room.name}: {room.description})</span>}
  </Collapsible>

You can add styles as you like (spaces, colors, etc..)

By this, you will only show only part of the rooms, and by clicking the 'View More' button, more will appear.


问:
Why is list count not working as I expect with nested lists?
I can count simple list but can not count list of lists.

```<code>list1 = ['R', 'E', 'R', 'E']
print(list1[0])
print(list1.count(list1[0]))
</code>```

My logic thinks if above is true below should be true, but I was wrong.

```<code>list1 = [['Z', 'R', 0], ['X', 'E', 1], ['Z', 'R', 3], ['X', 'E', 4]]
print(list1[0][1])
print(list1.count(list1[0][1]))
</code>```

Output

R
2
R
0
```

答:
A string is not equal to a list containing that string, so list1.count('R') won't find any matches in the second snippet.

You can use a list comprehension to extract the [1] element of each nested list, and then count the matches there.

```<code>print([x[1] for x in list1].count(list1[0][1]))
</code>```

Body:
I can count simple list but can not count list of lists.

list1 = ['R', 'E', 'R', 'E']
print(list1[0])
print(list1.count(list1[0]))

My logic thinks if above is true below should be true, but I was wrong.

list1 = [['Z', 'R', 0], ['X', 'E', 1], ['Z', 'R', 3], ['X', 'E', 4]]
print(list1[0][1])
print(list1.count(list1[0][1]))

Output

R
2
R
0

Body:
A string is not equal to a list containing that string, so list1.count('R') won't find any matches in the second snippet.

You can use a list comprehension to extract the [1] element of each nested list, and then count the matches there.

print([x[1] for x in list1].count(list1[0][1]))


问:
Cypress: Import tests into "./cypress/integration" from multiple npm dependencies?
I have a very large Cypress-based test suite, cy_tests_A_B_monolith, and the number of tests in ./cypress/integration folder is substantial.

I wish to partition these integration tests into their own npm module, and make them dependencies of a more manageable Cypress test suite.

From cy_tests_A_B_monolith

To cy_tests_A_B_manageable + dependencies cy_test_A + cy_test_B

Rough draft below. Uncertain how to import ./cypress/integration/*** tests to be a dependency into another Cypress test suite.

Much appreciated for suggestions, Thank you.

Rough Draft:

FROM monolith

Many integration tests + src custom commands...

npm cy_tests_A_B_monolith

```<code>├── cypress
│   ├── integration
│   │   ├── A
│   │   └── B
│   └── support
│       └── specs
│           ├── A
│           └── B
├── src
│   ├── A
│   |   └── commands
│   └── B
│       └── commands
</code>```

TO...

Partitioning monolith into a manageable test suite by maintaining subset of /cypress/integration of monolith test suite

npm cy_tests_A_B_manageable

```<code>├── cypress
│   ├── integration
│   │   ├── A << dependency imported cy_test_A ./cypress/integration/A
│   │   └── B << dependency imported cy_test_B ./cypress/integration/B
</code>```

npm cy_test_A

```<code>├── cypress
│   ├── integration
│   │   └── A
│   └── support
│       └── specs
│           └── A
├── src
│   └── A
│       └── commands
</code>```

npm cy_test_B

```<code>├── cypress
│   ├── integration
│   │   └── B
│   └── support
│       └── specs
│           └── B
├── src
│   └── B
│       └── commands
</code>```

答:
It's a little bit funky, but you can us the Module API in cy_tests_A_B_manageable to drive tests from other projects

/scripts/run-cypress.js

const cypress = require('cypress')

const testProjects = ['../cy_test_A', '../cy_test_B']

testProjects.forEach(project => {

  cypress.run({
    reporter: 'junit',
    browser: 'chrome',
    project,                // can specify the project root here
    config: {
      video: false,
    },
    env: {
      login_url: '/login',
      products_url: '/products',
    },
  })
})
```
<p>With <code>cypress open</code> it opens multiple runners, not ideal...</p>
<p>But can use <code>cypress.open(...)</code> with this folder setup</p>
```cypress-multi-project
  - cy_test_A
  - cy_test_B
  - cypress-run-other-project
```
<p><strong>cypress-multi-project/cypress.json</strong></p>
<pre class="lang-js prettyprint-override"><code>{
  "integrationFolder": "./",
  "testFiles": "**/*.spec.js"    // must uniquely suffix integration tests
}
</code>```

cypress-multi-project/cypress-run-other-project/scripts/run-cypress.js

const cypress = require('cypress')

cypress.open({
  reporter: 'junit',
  browser: 'chrome',
  project: '..',      // project is parent folder
  config: {
    video: true,
  },
  env: {
    login_url: '/login',
    products_url: '/products',
  },
})
```

Body:
I have a very large Cypress-based test suite, cy_tests_A_B_monolith, and the number of tests in ./cypress/integration folder is substantial.

I wish to partition these integration tests into their own npm module, and make them dependencies of a more manageable Cypress test suite.

From cy_tests_A_B_monolith

To cy_tests_A_B_manageable + dependencies cy_test_A + cy_test_B

Rough draft below. Uncertain how to import ./cypress/integration/*** tests to be a dependency into another Cypress test suite.

Much appreciated for suggestions, Thank you.

Rough Draft:

FROM monolith

Many integration tests + src custom commands...

npm cy_tests_A_B_monolith

├── cypress
│   ├── integration
│   │   ├── A
│   │   └── B
│   └── support
│       └── specs
│           ├── A
│           └── B
├── src
│   ├── A
│   |   └── commands
│   └── B
│       └── commands

TO...

Partitioning monolith into a manageable test suite by maintaining subset of /cypress/integration of monolith test suite

npm cy_tests_A_B_manageable

├── cypress
│   ├── integration
│   │   ├── A << dependency imported cy_test_A ./cypress/integration/A
│   │   └── B << dependency imported cy_test_B ./cypress/integration/B

npm cy_test_A

├── cypress
│   ├── integration
│   │   └── A
│   └── support
│       └── specs
│           └── A
├── src
│   └── A
│       └── commands

npm cy_test_B

├── cypress
│   ├── integration
│   │   └── B
│   └── support
│       └── specs
│           └── B
├── src
│   └── B
│       └── commands

Body:
It's a little bit funky, but you can us the Module API in cy_tests_A_B_manageable to drive tests from other projects

/scripts/run-cypress.js

const cypress = require('cypress')

const testProjects = ['../cy_test_A', '../cy_test_B']

testProjects.forEach(project => {

  cypress.run({
    reporter: 'junit',
    browser: 'chrome',
    project,                // can specify the project root here
    config: {
      video: false,
    },
    env: {
      login_url: '/login',
      products_url: '/products',
    },
  })
})

With cypress open it opens multiple runners, not ideal...

But can use cypress.open(...) with this folder setup

cypress-multi-project
  - cy_test_A
  - cy_test_B
  - cypress-run-other-project

cypress-multi-project/cypress.json

{
  "integrationFolder": "./",
  "testFiles": "**/*.spec.js"    // must uniquely suffix integration tests
}

cypress-multi-project/cypress-run-other-project/scripts/run-cypress.js

const cypress = require('cypress')

cypress.open({
  reporter: 'junit',
  browser: 'chrome',
  project: '..',      // project is parent folder
  config: {
    video: true,
  },
  env: {
    login_url: '/login',
    products_url: '/products',
  },
})


问:
Pandas transforming chronological rows to columns
I have a table of work experiences where each row represents a job in chronological order from the first job to the most recent job. For data science purposes I'm trying to create a new table based on this table that displays new job attributes and old job attributes on the same row. For example, the original table would be like:

uniqueID
personID
startdate
enddate
title
functions

1
A1
1/1/21
12/1/21
Analyst
data science

2
A1
1/1/22
12/1/22
Manager
admin

The new table would be something like this:

uniqueID
personID
new_title
new_function
old_title
old_function

1
A1
Analyst
data science
nan
nan

2
A1
Manager
admin
Analyst
data science

I tried to use some groupby variations but haven't been able to get this result.

答:
If I understand correctly, you're looking for a shift:

```<code>cols = ['title', 'functions']
df[['old_' + c for c in cols]] = df.groupby('personID')[cols].shift(1)
df = df.drop(['startdate', 'enddate'], axis=1).rename({c: 'new_' + c for c in cols}, axis=1)
</code>```

Output:

```<code>>>> df
   uniqueID personID new_title new_functions old_title old_functions
0         1       A1   Analyst  data science       NaN           NaN
1         2       A1   Manager         admin   Analyst  data science
</code>```

Body:
If I understand correctly, you're looking for a shift:

cols = ['title', 'functions']
df[['old_' + c for c in cols]] = df.groupby('personID')[cols].shift(1)
df = df.drop(['startdate', 'enddate'], axis=1).rename({c: 'new_' + c for c in cols}, axis=1)

Output:

>>> df
   uniqueID personID new_title new_functions old_title old_functions
0         1       A1   Analyst  data science       NaN           NaN
1         2       A1   Manager         admin   Analyst  data science


问:
How to target parents from elements with a class?
So, .search-chat-search-btn > form { } targets the form "inside" the element with class .search-chat-search-btn, but can I make it go the other way? As in, target the form that is outside .search-chat-search-btn?

```<code><form>
    <button class="search-chat-search-btn"></button>
</form>
</code>```

Apparently this is suppose to work, but it doesn't. Target every form that has a button.

```<code>form:has(> button) {
    display: inline;
    border: red 1px solid;
}
</code>```

https://developer.mozilla.org/en-US/docs/Web/CSS/:has

(but then I just realised it's only supported in Safari, development version?)

答:
As in, target the form that is outside .search-chat-search-btn?

Based on the question, I assume you want to select style all the form that not inside the .search-chat-search-btn, then you probably looking for css :not pseudo-class

Maybe you are looking for :not :

:not(.search-chat-search-btn) form{
  color:blue
}
.search-chat-search-btn form{
color:red
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='search-chat-search-btn'>
<form>Yes</form></div>
<form >Hello</form>
<form >Hello</form></code>```

Body:
So, .search-chat-search-btn > form { } targets the form "inside" the element with class .search-chat-search-btn, but can I make it go the other way? As in, target the form that is outside .search-chat-search-btn?

<form>
    <button class="search-chat-search-btn"></button>
</form>

Apparently this is suppose to work, but it doesn't. Target every form that has a button.

form:has(> button) {
    display: inline;
    border: red 1px solid;
}

https://developer.mozilla.org/en-US/docs/Web/CSS/:has

(but then I just realised it's only supported in Safari, development version?)

Body:
As in, target the form that is outside .search-chat-search-btn?

Based on the question, I assume you want to select style all the form that not inside the .search-chat-search-btn, then you probably looking for css :not pseudo-class

Maybe you are looking for :not :

:not(.search-chat-search-btn) form{
  color:blue
}
.search-chat-search-btn form{
color:red
}

<div class='search-chat-search-btn'>
<form>Yes</form></div>
<form >Hello</form>
<form >Hello</form>


问:
How to use AWS Cognito as a unified SSO?
I would like to have only one login screen, registration, profile and password recovery for all projects in my company. Basically a unified login or SSO.

So I made these screens using AWS Cognito and hosted them on the sso.mycompany.com domain and it's working fine.

But now I need to implement these screens in my other projects. How can I do this? I can't just copy the files, as this was done in Vue.js, and I would like to put these screens in projects done in Laravel, Wordpress, React, etc;

I thought of using an iframe loading sso.mycompany.com, but how do I return user data after login to the app that opened the iframe?

Basically that's it, I have authentication screens hosted on the sso.mycompany.com domain and I would like to use them on projectx.com, projecty.com, mycompany.com, etc.

答:
Here is one solution that might work for you and might give you some ideas on how you could put together a solution.  Unfortunately, Cognito out of the box doesn't come with a unified/universal login experience that you require.  It also doesn't come with a lot of other features you might see from the big IdP platforms, but that is another discussion for another time :) The whole foundation of this solution is based off of a single domain, cookies and JWTs(access token, id token and a refresh token). It will still work for your apps on other domains, but the experience for your end users will be a bit sub optimal compared to if all your apps were on the same domain.

Because an app like projectx.com sits on a different domain then sso.mycompany.com, you have to somehow get a access token over to projectx.com after the user logs in through mycompany.com.  You can simply just pass the access token through as a query param when you redirect the user back to projectx.com after a successful login on sso.mycompany.com.

I had a much longer answer with details, but stackoverflow won't let me post because it thinks my answer is spam??? Check my profile on how to contact me if you want the longer version with details.


问:
Developing a Video conferencing application where the participants should have a feature to show their video only to organizer using Microsoft TEAMS
I am trying to develop a Video Conferencing application using Microsoft Graph API for TEAMS.

My requirement for it is

Participant should be given an option to show his/her video only to organizer but not other participants in the meeting.

Could anyone please help me to know whether this is possible via Microsoft TEAMS API.

Thanks in advance.

答:
your requirements leave quite a bit to the imagination, but
I would recommend using a combination of Azure Communication Services and Teams.

Using the ACS part you can build a custom service that where you have the freedom and responsibility to build your own client.

You could build an ACS client that sets up a video-call with a ACS router

the Router ( another ACS Client) implements the logic which video stream to send where.

The router then can send the the selected streams ACS-Teams Interop to a Teams Meeting.

Note that you will need to build the (multi-tier) logic yourself, depending on the authentication/licensing of your clients, you will may incur charges for the use of the ACS service.


问:
Images not showing up in Github
I'm trying to upload my website in GitHub but the images won't show. I've tried a lot of the solutions posted here (changing path, changing png to PNG..) but nothing works?</p>
```<code>

<body>
  <div class="top-container">
    <img class="top-bird" src="C:/Users/hanah/OneDrive/Desktop/Web Development/CSS-My Site/seagull.png" alt="bird">
    <h1>I'm Hana</h1>
    <h2>A programmer</h2>
    <img class="bottom-bird" src="C:/Users/hanah/OneDrive/Desktop/Web Development/CSS-My Site/seagull.png" alt="bird">
    <img src="C:/Users/hanah/OneDrive/Desktop/Web Development/CSS-My Site/mountain.png" alt="mountain">

  </div>
  <div class="middle-container">
    <div class="profile">
      <img src="Hana profile-modified.PNG" alt="Hana Profile">
      <h2 class="hello2">Hello.</h2>
      <p class="hello">My name is Hana and I'm currently studying to become a Web Developer. I graduated in 2020 from UC Riverside with a Bachelor's in Art. I have always been interested in digital design and tech in general so I'm purusing HTML, CSS
        and
        Javascript at the moment and plan to learn other coding languages like Python and Java. In my free time I enjoy reading, art, and music.</p>
    </div>
    <hr class="hr">
    <div class="skills">
      <h2 class="myskills">My Skills.</h2>

      <div class="skill-row">
        <img class="art" src="C:/Users/hanah/OneDrive/Desktop/Web Development/CSS-My Site/art.png">
        <h3>Web Development</h3>
        <p>I love designing and coding websites for users to enjoy and am excited to expand my skill set.</p>
      </div>
      <div class="skill-row">
        <img class="web" src="C:/Users/hanah/OneDrive/Desktop/Web Development/CSS-My Site/coding.png" alt="art">
        <h3>Art</h3>
        <p>Whether it is digital design or traditional art, I enjoy it all and am eager to learn more.</p>

</body>

</html>

</code>```

答: The images you are trying to use with src= are on your local machine, when the website is loading its trying to access C:/Users/hanah.. but that doesnt exist on the sites server, thats the path of them on your own computer, try uploading the images with the site in their own folder and link them as "./images/seagull.png" or to imgur or online storage and link to them that way</p>

Title: Images not showing up in Github

Body:
I'm trying to upload my website in GitHub but the images won't show. I've tried a lot of the solutions posted here (changing path, changing png to PNG..) but nothing works?

I'm Hana

A programmer

Hello.

My name is Hana and I'm currently studying to become a Web Developer. I graduated in 2020 from UC Riverside with a Bachelor's in Art. I have always been interested in digital design and tech in general so I'm purusing HTML, CSS
        and
        Javascript at the moment and plan to learn other coding languages like Python and Java. In my free time I enjoy reading, art, and music.

My Skills.

Web Development

I love designing and coding websites for users to enjoy and am excited to expand my skill set.

Art

Whether it is digital design or traditional art, I enjoy it all and am eager to learn more.


问:
Python Function that Match a Given Template
Say I have a template and I have a dictionary containing words. I want to create a function that returns a list of words that match the given template. To illustrate this:

```<code>template = 'W**ER'
dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}

Desired output:
output_list = ['water', 'weber', 'waver']
</code>```

I'm not entirely sure how to create the function and I would totally appreciate any help. Thanks!

答:
Try to use regex:

import re
ptrn = re.compile("w..er")
list(filter(lambda key: re.match(ptrn, key), dictionary))
```

Body:
Say I have a template and I have a dictionary containing words. I want to create a function that returns a list of words that match the given template. To illustrate this:

template = 'W**ER'
dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}

Desired output:
output_list = ['water', 'weber', 'waver']

I'm not entirely sure how to create the function and I would totally appreciate any help. Thanks!


问:
Replace a set of html br elements with another in jQuery -- parsing HTML with jQuery
So here's my problem. I have a little third-party service on my site that generates a bunch of HTML from an RSS feed and sticks it in my webpage when the page is loaded. However, when it generates the HTML, it inserts a bunch of totally unnecessary break tags. Unfortunately, the source file that generates this code is on the third party's server and not mine, so I can't tweak it.

Thus, I'm trying to tweak the HTML right before the page is loaded by using a little jQuery inside the onLoad="" property in the body tag. However, I can't simply use something like $('br').remove(); because then there aren't ANY break tags, and I need one per each spot where there are currently three.

So ultimately, what I need to do is come up with a jQuery statement that replaces

```<code><br><br clear=all><br>
</code>```

with

```<code><br />
</code>```

I'm rather new to jQuery, but I couldn't seem to find anything that would help me do this. Any ideas?

Thanks in advance for any help!

答:
Why donn`t just replace the html of the RSS HTML container:</p>

```<code>  yourContainerElem.innerHTML =  yourContainerElem.innerHTML.replace(/<br><br clear=all><br>/gi, '<br />');
</code>```

Body:
So here's my problem. I have a little third-party service on my site that generates a bunch of HTML from an RSS feed and sticks it in my webpage when the page is loaded. However, when it generates the HTML, it inserts a bunch of totally unnecessary break tags. Unfortunately, the source file that generates this code is on the third party's server and not mine, so I can't tweak it.

Thus, I'm trying to tweak the HTML right before the page is loaded by using a little jQuery inside the onLoad="" property in the body tag. However, I can't simply use something like $('br').remove(); because then there aren't ANY break tags, and I need one per each spot where there are currently three.

So ultimately, what I need to do is come up with a jQuery statement that replaces

with

I'm rather new to jQuery, but I couldn't seem to find anything that would help me do this. Any ideas?

Thanks in advance for any help!

Body:
Why donn`t just replace the html of the RSS HTML container:

  yourContainerElem.innerHTML =  yourContainerElem.innerHTML.replace(/<br><br clear=all><br>/gi, '<br />');


问:
reduce ticks of matplotlib axis
I have a question. I would like to show on a plot a few values and dates.
but the axes are very full...
is there a possibility to display only a part of the values on the axes?
So a possibility to reduce the values to e.g. 5 ?

```<code>for kurs in kurs_daten[:20]:
       datum.append(kurs.split(",")[0])
       kurse.append(kurs.split(",")[1][:5])

print(kurse)
print(datum)

plt.plot(datum,kurse)
plt.xlabel("Datum")

plt.ylabel("Kurs")
plt.show()
</code>```

答:
You can rotate your labels on the x-axis

plt.xticks(rotation = 45)  will rotate 45 degrees

rotate 90 degrees for vertical

Title: reduce ticks of matplotlib axis

Body:
I have a question. I would like to show on a plot a few values and dates.
but the axes are very full...
is there a possibility to display only a part of the values on the axes?
So a possibility to reduce the values to e.g. 5 ?

for kurs in kurs_daten[:20]:
       datum.append(kurs.split(",")[0])
       kurse.append(kurs.split(",")[1][:5])

print(kurse)
print(datum)

plt.plot(datum,kurse)
plt.xlabel("Datum")

plt.ylabel("Kurs")
plt.show()


问:
Getting System.Web.Mvc.SelectListItem as options of DropDownList
I have a ViewBag.CategoryList which contains ViewBag.CategoryList = new SelectList(Category.GetCategories());

My View:

```
@Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DropDownListFor(model => model.Category, new SelectList(ViewBag.CategoryList), "Select Category", htmlAttributes: new {@class = "form-control"})
```

What I'm getting is <option>System.Web.Mvc.SelectListItem</option> instead of my strings. Debugger shows that the ViewBag does have a list of strings.

Edit:
Fixed it by replacing the view with:

```
@Html.DropDownListFor(model => model.Category, (IEnumerable)(ViewBag.CategoryList), "Select Category", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Category, "", new { @class = "text-danger" })
```

答:
actually give a select list instead of a string list from the controller.</p>
```<code>ViewBag.CategoryList = Category.GetCategories().Select(r => new SelectListItem()
            {
                Value = r,
                Text = r
            })
</code>```
```<code>@Html.DropDownListFor(model => model.Category, new SelectList(ViewBag.CategoryList, "Value", "Text"), "Select Category", htmlAttributes: new {@class = "form-control"})
</code>```

Body:
I have a ViewBag.CategoryList which contains ViewBag.CategoryList = new SelectList(Category.GetCategories());

My View:

@Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DropDownListFor(model => model.Category, new SelectList(ViewBag.CategoryList), "Select Category", htmlAttributes: new {@class = "form-control"})

What I'm getting is <option>System.Web.Mvc.SelectListItem</option> instead of my strings. Debugger shows that the ViewBag does have a list of strings.

Edit:
Fixed it by replacing the view with:

@Html.DropDownListFor(model => model.Category, (IEnumerable)(ViewBag.CategoryList), "Select Category", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Category, "", new { @class = "text-danger" })

Body:
actually give a select list instead of a string list from the controller.

ViewBag.CategoryList = Category.GetCategories().Select(r => new SelectListItem()
            {
                Value = r,
                Text = r
            })

@Html.DropDownListFor(model => model.Category, new SelectList(ViewBag.CategoryList, "Value", "Text"), "Select Category", htmlAttributes: new {@class = "form-control"})


问:
Why won't renderDT() return a table on my Shiny app?
I'm trying to create a function on my Shiny app which allows someone to upload a file. The uploaded file will always contain a column called "Index". I want the Shiny app to be able to take this Index (e.g. A0AVT1_Y44) and extract information to add three additional columns to the table: Protein_id (A0AVT1), Residue (Y), and Position (44). I've already created a successful function which does this. However, when I run this code and then renderDT(), no data table shows up even though there is no error message. Does anyone know what's happening?

Code:

```<code>library(dplyr)
library(viridis)
library(tidyverse)
library(rio)
library(shiny)

options(shiny.maxRequestSize = 30*1024^2)

ui <- fluidPage(
  titlePanel("File Upload"),
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Browse...",
                multiple = TRUE,
                accept = c("text/csv",
                           "text/tab-separated-values",
                           ".csv",
                           "text/tsv",
                           "text/comma-separated-values",
                           ".tsv")),
                placeholder = "No file selected",
      tags$hr(),
      radioButtons("disp", "Display",
                   choices = c(Head = "head",
                               All = "all"),
                   selected = "head")
    ),
    mainPanel(
      DT::dataTableOutput(outputId = "exp_df")
    )
  )
)

server <- function(input, output) {
  exp_df <- reactive({return(
    cbind(
      iris[input$file1],
      Residue = nv(),
      Position = nvar(),
      Protein_id = newvar())
  )
  })

  return(exp_df)

  nv <- reactive({
    exp_df[[gsub('[0-9]*','', sub(".*?_(.*?)$", "\\1",
</code>```

input$file1$Index))]]
})

```<code>  nvar <- reactive({
    exp_df[[gsub('[0-9.-]','', sub(".*?_(.*?)$","\\1",
</code>```

input$file1$Index))]]
})

```<code>  newvar <-reactive({
    exp_df[[sub("_\\D(\\d)+$","",sub(".*?_(.*?)$","\\1",
</code>```

input$file1$Index))]]
})

```<code>  output$exp_df <- DT::renderDT({
    exp_df()
    })
}

shinyApp(ui=ui, server=server)
</code>```

I then ran options(shiny.trace = TRUE) and received the following output:

runApp('~/BioInf Proj')

```<code>Listening on http://127.0.0.1:4700
SEND {"config":{"workerId":"","sessionId":"2a9472a1d0a0da6562eac28841de4ff2","user":null}}
RECV {"method":"init","data":{"file1:shiny.file":null,"disp":"head",".clientdata_output_exp_df_hidden":false,".clientdata_pixelratio":1,".clientdata_url_protocol":"http:",".clientdata_url_hostname":"127.0.0.1",".clientdata_url_port":"4700",".clientdata_url_pathname":"/",".clientdata_url_search":"",".clientdata_url_hash_initial":"",".clientdata_url_hash":"",".clientdata_singletons":""}}
SEND {"busy":"busy"}
SEND {"recalculating":{"name":"exp_df","status":"recalculating"}}
SEND {"recalculating":{"name":"exp_df","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":{"exp_df":{"message":"","call":"NULL","type":["shiny.silent.error","validation"]}},"values":{},"inputMessages":[]}
RECV {"method":"uploadInit","args":[[{"name":"pY_cml.csv","size":336901,"type":"application/vnd.ms-excel"}]],"tag":0}
SEND {"response":{"tag":0,"value":{"jobId":"3ad1ee2355d914f1b88e13e5","uploadUrl":"session/2a9472a1d0a0da6562eac28841de4ff2/upload/3ad1ee2355d914f1b88e13e5?w="}}}
RECV {"method":"uploadEnd","args":["3ad1ee2355d914f1b88e13e5","file1"],"tag":1}
SEND {"progress":{"type":"binding","message":{"id":"exp_df"}}}
SEND {"busy":"busy"}
SEND {"response":{"tag":1,"value":null}}
SEND {"recalculating":{"name":"exp_df","status":"recalculating"}}
SEND {"recalculating":{"name":"exp_df","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":{"exp_df":{"message":"","call":"NULL","type":["shiny.silent.error","validation"]}},"values":{},"inputMessages":[]}
</code>```

答:
If you read the file first and then use just the Index column, it works fine.  Try this</p>
```<code>library(dplyr)
library(viridis)
library(tidyverse)
#library(rio)
library(shiny)

options(shiny.maxRequestSize = 30*1024^2)

ui <- fluidPage(
  titlePanel("File Upload"),
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Browse...",
                multiple = TRUE,
                accept = c("text/csv",
                           "text/tab-separated-values",
                           ".csv",
                           "text/tsv",
                           "text/comma-separated-values",
                           ".tsv")),
      placeholder = "No file selected",
      tags$hr(),
      radioButtons("disp", "Display",
                   choices = c(Head = "head",
                               All = "all"),
                   selected = "head")
    ),
    mainPanel(
      DT::dataTableOutput(outputId = "exp_df")
    )
  )
)

server <- function(input, output) {
  mydf <- eventReactive(input$file1,{
        infile <- input$file1
        req(infile)
        return(read.csv(infile$datapath, header=TRUE, sep=','))
  })

  exp_dff <- reactive({
    req(mydf(),newvar(),nv(),nvar())
    return(
    cbind(
      mydf(),
      Residue = nv(),
      Position = nvar(),
      Protein_id = newvar())
  )
  })

  nv <- reactive({
    req(mydf())
    eI <- mydf()$Index
    gsub('[0-9]*','', sub(".*?_(.*?)$", "\\1",eI))
    #exp_df[[gsub('[0-9]*','', sub(".*?_(.*?)$", "\\1",input$file1$Index))]]
  })

  nvar <- reactive({
    req(mydf())
    eI <- mydf()$Index
    gsub('[A-Z.-]','', sub(".*?_(.*?)$","\\1", eI))
    #exp_df[[gsub('[0-9.-]','', sub(".*?_(.*?)$","\\1", input$file1$Index))]]
  })

  newvar <-reactive({
    req(mydf())
    eI <- mydf()$Index
    sub("(.*?)_(.*?)$","\\1",eI)
    #exp_df[[sub("_\\D(\\d)+$","",sub(".*?_(.*?)$","\\1",input$file1$Index))]]
  })

  output$exp_df <- DT::renderDT({
    exp_dff()
  })
}

shinyApp(ui=ui, server=server)
</code>```

Body:
I'm trying to create a function on my Shiny app which allows someone to upload a file. The uploaded file will always contain a column called "Index". I want the Shiny app to be able to take this Index (e.g. A0AVT1_Y44) and extract information to add three additional columns to the table: Protein_id (A0AVT1), Residue (Y), and Position (44). I've already created a successful function which does this. However, when I run this code and then renderDT(), no data table shows up even though there is no error message. Does anyone know what's happening?

Code:

library(dplyr)
library(viridis)
library(tidyverse)
library(rio)
library(shiny)

options(shiny.maxRequestSize = 30*1024^2)

ui <- fluidPage(
  titlePanel("File Upload"),
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Browse...",
                multiple = TRUE,
                accept = c("text/csv",
                           "text/tab-separated-values",
                           ".csv",
                           "text/tsv",
                           "text/comma-separated-values",
                           ".tsv")),
                placeholder = "No file selected",
      tags$hr(),
      radioButtons("disp", "Display",
                   choices = c(Head = "head",
                               All = "all"),
                   selected = "head")
    ),
    mainPanel(
      DT::dataTableOutput(outputId = "exp_df")
    )
  )
)

server <- function(input, output) {
  exp_df <- reactive({return(
    cbind(
      iris[input$file1],
      Residue = nv(),
      Position = nvar(),
      Protein_id = newvar())
  )
  })

  return(exp_df)

  nv <- reactive({
    exp_df[[gsub('[0-9]*','', sub(".*?_(.*?)$", "\\1",

input$file1$Index))]]
})

  nvar <- reactive({
    exp_df[[gsub('[0-9.-]','', sub(".*?_(.*?)$","\\1",

input$file1$Index))]]
})

  newvar <-reactive({
    exp_df[[sub("_\\D(\\d)+$","",sub(".*?_(.*?)$","\\1",

input$file1$Index))]]
})

  output$exp_df <- DT::renderDT({
    exp_df()
    })
}

shinyApp(ui=ui, server=server)

I then ran options(shiny.trace = TRUE) and received the following output:

runApp('~/BioInf Proj')

Listening on http://127.0.0.1:4700
SEND {"config":{"workerId":"","sessionId":"2a9472a1d0a0da6562eac28841de4ff2","user":null}}
RECV {"method":"init","data":{"file1:shiny.file":null,"disp":"head",".clientdata_output_exp_df_hidden":false,".clientdata_pixelratio":1,".clientdata_url_protocol":"http:",".clientdata_url_hostname":"127.0.0.1",".clientdata_url_port":"4700",".clientdata_url_pathname":"/",".clientdata_url_search":"",".clientdata_url_hash_initial":"",".clientdata_url_hash":"",".clientdata_singletons":""}}
SEND {"busy":"busy"}
SEND {"recalculating":{"name":"exp_df","status":"recalculating"}}
SEND {"recalculating":{"name":"exp_df","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":{"exp_df":{"message":"","call":"NULL","type":["shiny.silent.error","validation"]}},"values":{},"inputMessages":[]}
RECV {"method":"uploadInit","args":[[{"name":"pY_cml.csv","size":336901,"type":"application/vnd.ms-excel"}]],"tag":0}
SEND {"response":{"tag":0,"value":{"jobId":"3ad1ee2355d914f1b88e13e5","uploadUrl":"session/2a9472a1d0a0da6562eac28841de4ff2/upload/3ad1ee2355d914f1b88e13e5?w="}}}
RECV {"method":"uploadEnd","args":["3ad1ee2355d914f1b88e13e5","file1"],"tag":1}
SEND {"progress":{"type":"binding","message":{"id":"exp_df"}}}
SEND {"busy":"busy"}
SEND {"response":{"tag":1,"value":null}}
SEND {"recalculating":{"name":"exp_df","status":"recalculating"}}
SEND {"recalculating":{"name":"exp_df","status":"recalculated"}}
SEND {"busy":"idle"}
SEND {"errors":{"exp_df":{"message":"","call":"NULL","type":["shiny.silent.error","validation"]}},"values":{},"inputMessages":[]}

Body:
If you read the file first and then use just the Index column, it works fine.  Try this

library(dplyr)
library(viridis)
library(tidyverse)
#library(rio)
library(shiny)

options(shiny.maxRequestSize = 30*1024^2)

ui <- fluidPage(
  titlePanel("File Upload"),
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Browse...",
                multiple = TRUE,
                accept = c("text/csv",
                           "text/tab-separated-values",
                           ".csv",
                           "text/tsv",
                           "text/comma-separated-values",
                           ".tsv")),
      placeholder = "No file selected",
      tags$hr(),
      radioButtons("disp", "Display",
                   choices = c(Head = "head",
                               All = "all"),
                   selected = "head")
    ),
    mainPanel(
      DT::dataTableOutput(outputId = "exp_df")
    )
  )
)

server <- function(input, output) {
  mydf <- eventReactive(input$file1,{
        infile <- input$file1
        req(infile)
        return(read.csv(infile$datapath, header=TRUE, sep=','))
  })

  exp_dff <- reactive({
    req(mydf(),newvar(),nv(),nvar())
    return(
    cbind(
      mydf(),
      Residue = nv(),
      Position = nvar(),
      Protein_id = newvar())
  )
  })

  nv <- reactive({
    req(mydf())
    eI <- mydf()$Index
    gsub('[0-9]*','', sub(".*?_(.*?)$", "\\1",eI))
    #exp_df[[gsub('[0-9]*','', sub(".*?_(.*?)$", "\\1",input$file1$Index))]]
  })

  nvar <- reactive({
    req(mydf())
    eI <- mydf()$Index
    gsub('[A-Z.-]','', sub(".*?_(.*?)$","\\1", eI))
    #exp_df[[gsub('[0-9.-]','', sub(".*?_(.*?)$","\\1", input$file1$Index))]]
  })

  newvar <-reactive({
    req(mydf())
    eI <- mydf()$Index
    sub("(.*?)_(.*?)$","\\1",eI)
    #exp_df[[sub("_\\D(\\d)+$","",sub(".*?_(.*?)$","\\1",input$file1$Index))]]
  })

  output$exp_df <- DT::renderDT({
    exp_dff()
  })
}

shinyApp(ui=ui, server=server)


问:
-bash: cfssl: command not found
When I tried to install cfssl with this command:

```<code>go get -u github.com/cloudflare/cfssl/cmd/cfssl
</code>```

I received following output:

```<code># github.com/cloudflare/cfssl/crypto/pkcs7
go_packages/src/github.com/cloudflare/cfssl/crypto/pkcs7/pkcs7.go:141: pkcs7.ContentType.String undefined (type asn1.ObjectIdentifier has no field or method String)
# github.com/cloudflare/cfssl/helpers/derhelpers
go_packages/src/github.com/cloudflare/cfssl/helpers/derhelpers/derhelpers.go:16: undefined: crypto.Signer
# github.com/cloudflare/cfssl/csr
go_packages/src/github.com/cloudflare/cfssl/csr/csr.go:191: undefined: x509.CertificateRequest
go_packages/src/github.com/cloudflare/cfssl/csr/csr.go:204: undefined: x509.CreateCertificateRequest
# golang.org/x/crypto/ocsp
go_packages/src/golang.org/x/crypto/ocsp/ocsp.go:494: undefined: crypto.Signer
# github.com/cloudflare/cf-tls/tls
go_packages/src/github.com/cloudflare/cf-tls/tls/handshake_client.go:431: undefined: crypto.Signer
</code>```

I really have no clue whether this is harmful or not and has something to do with the usage of this tool. However when I try to use it, I receive this error:

```<code>-bash: cfssl: Command not found.
</code>```

I never used go but I wanted to use this tool. Do you guys know why this is not working as expected?

Edit

output of go env

```<code>GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/ubuntu/go"
GORACE=""
GOROOT="/usr/lib/go"
GOTOOLDIR="/usr/lib/go/pkg/tool/linux_amd64"
TERM="dumb"
CC="gcc"
GOGCCFLAGS="-g -O2 -fPIC -m64 -pthread"
CXX="g++"
CGO_ENABLED="1"
</code>```

output of go version

```<code>go version go1.2.1 linux/amd64
</code>```

I really don't know why this is the case because I installed this version.

答:
You can use these commmand to install cfssl and cfssljson on last version. You need only have wget commmand installed on your OS and type these cmd:

```<code>yum -y -q install wget
VERSION=$(curl --silent "https://api.github.com/repos/cloudflare/cfssl/releases/latest" | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/')
VNUMBER=${VERSION#"v"}
wget https://github.com/cloudflare/cfssl/releases/download/${VERSION}/cfssl_${VNUMBER}_linux_amd64 -O cfssl
wget https://github.com/cloudflare/cfssl/releases/download/${VERSION}/cfssljson_${VNUMBER}_linux_amd64 -O cfssljson
chmod +x cfssl
chmod +x cfssljson
mv cfssl /usr/local/bin
mv cfssljson /usr/local/bin
</code>```

Title: -bash: cfssl: command not found

Body:
When I tried to install cfssl with this command:

go get -u github.com/cloudflare/cfssl/cmd/cfssl

I received following output:

# github.com/cloudflare/cfssl/crypto/pkcs7
go_packages/src/github.com/cloudflare/cfssl/crypto/pkcs7/pkcs7.go:141: pkcs7.ContentType.String undefined (type asn1.ObjectIdentifier has no field or method String)
# github.com/cloudflare/cfssl/helpers/derhelpers
go_packages/src/github.com/cloudflare/cfssl/helpers/derhelpers/derhelpers.go:16: undefined: crypto.Signer
# github.com/cloudflare/cfssl/csr
go_packages/src/github.com/cloudflare/cfssl/csr/csr.go:191: undefined: x509.CertificateRequest
go_packages/src/github.com/cloudflare/cfssl/csr/csr.go:204: undefined: x509.CreateCertificateRequest
# golang.org/x/crypto/ocsp
go_packages/src/golang.org/x/crypto/ocsp/ocsp.go:494: undefined: crypto.Signer
# github.com/cloudflare/cf-tls/tls
go_packages/src/github.com/cloudflare/cf-tls/tls/handshake_client.go:431: undefined: crypto.Signer

I really have no clue whether this is harmful or not and has something to do with the usage of this tool. However when I try to use it, I receive this error:

-bash: cfssl: Command not found.

I never used go but I wanted to use this tool. Do you guys know why this is not working as expected?

Edit

output of go env

GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/ubuntu/go"
GORACE=""
GOROOT="/usr/lib/go"
GOTOOLDIR="/usr/lib/go/pkg/tool/linux_amd64"
TERM="dumb"
CC="gcc"
GOGCCFLAGS="-g -O2 -fPIC -m64 -pthread"
CXX="g++"
CGO_ENABLED="1"

output of go version

go version go1.2.1 linux/amd64

I really don't know why this is the case because I installed this version.

Body:
You can use these commmand to install cfssl and cfssljson on last version. You need only have wget commmand installed on your OS and type these cmd:

yum -y -q install wget
VERSION=$(curl --silent "https://api.github.com/repos/cloudflare/cfssl/releases/latest" | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/')
VNUMBER=${VERSION#"v"}
wget https://github.com/cloudflare/cfssl/releases/download/${VERSION}/cfssl_${VNUMBER}_linux_amd64 -O cfssl
wget https://github.com/cloudflare/cfssl/releases/download/${VERSION}/cfssljson_${VNUMBER}_linux_amd64 -O cfssljson
chmod +x cfssl
chmod +x cfssljson
mv cfssl /usr/local/bin
mv cfssljson /usr/local/bin


问:
What does it mean ( i & (1<<j)) in second condition?
C++ code. In this code, I got confused while I read the code. As you can see (i & (j<<1)) in that condition does it mean an odd number? Please let me know (i & (j<<1)) what does it mean is and how does it work?</p>
```<code>void solve()
{
    int n, l, r, x;
    cin >> n >> l >> r >> x;

    int a[1000];

    for(int i=0; i<n; i++)
    cin >> a[i];

    int ans=0;

    for(int i=0; i< (1<<n); i++)
    {
        if(__builtin_popcount(i) >= 2)
        {
            int mx=0;
            int mn=INT_MAX;

            int sum=0;

            for(int j=0; j<n; j++)
            {
                if(i & (1<<j)) /// What does it mean ??
                {
                    sum+=a[j];

                    mx=max(mx, a[j]);
                    mn=min(mn, a[j]);
                }
            }

            if(l <= sum && sum<=r && mx-mn>=x)
            ans++;
        }
    }

    cout << ans << '\n';
}
</code>```

答:
```<code>if(i & (1<<j))
</code>```

means "if the binary representation of i has its j'th (lowest) bit turned on".

That's because:

<< is the left-shift operator.

The binary representation of (1<<j) has its j'th lowest bit turned on, and no other bits.

& is the bitwise-AND operator, so (1<<j) is used like a mask.

Caveat: n must be low enough so that (1<<j) doesn't exceed the number of bits in an int (which depends on the platform)... otherwise bad things may happen.

Body:
C++ code. In this code, I got confused while I read the code. As you can see (i & (j<<1)) in that condition does it mean an odd number? Please let me know (i & (j<<1)) what does it mean is and how does it work?

void solve()
{
    int n, l, r, x;
    cin >> n >> l >> r >> x;

    int a[1000];

    for(int i=0; i<n; i++)
    cin >> a[i];

    int ans=0;

    for(int i=0; i< (1<<n); i++)
    {
        if(__builtin_popcount(i) >= 2)
        {
            int mx=0;
            int mn=INT_MAX;

            int sum=0;

            for(int j=0; j<n; j++)
            {
                if(i & (1<<j)) /// What does it mean ??
                {
                    sum+=a[j];

                    mx=max(mx, a[j]);
                    mn=min(mn, a[j]);
                }
            }

            if(l <= sum && sum<=r && mx-mn>=x)
            ans++;
        }
    }

    cout << ans << '\n';
}

Body:
if(i & (1<<j))

means "if the binary representation of i has its j'th (lowest) bit turned on".

That's because:

<< is the left-shift operator.

The binary representation of (1<<j) has its j'th lowest bit turned on, and no other bits.

& is the bitwise-AND operator, so (1<<j) is used like a mask.

Caveat: n must be low enough so that (1<<j) doesn't exceed the number of bits in an int (which depends on the platform)... otherwise bad things may happen.


问:
How to use `deriving` in Idris?
I'm trying to deriving Show, Eq, Ord etc in Idris, but none of the following trials works:

trail #1:

```<code>data Expr =
      Lit Int
    | Neg Expr
    | Add Expr Expr
    deriving (Show)
</code>```

got:

```<code>deriving.idr:5:15-18:
  |
5 |     deriving (Show)
  |               ~~~~
When checking type of Main.Add:
Type mismatch between
        Type -> Type (Type of Show)
and
        Type (Expected type)
</code>```

trail #2:

```<code>data Expr =
      Lit Int
    | Neg Expr
    | Add Expr Expr
    deriving (Show _)
</code>```

got:

```<code>*deriving> Lit 1
Lit 1 : Expr
*deriving> Add (Lit 1) (Lit 1)
(input):Can't infer argument ty to Add, Can't infer argument deriving to Add
</code>```

trail #3:

```<code>data Expr =
      Lit Int
    | Neg Expr
    | Add Expr Expr
    deriving (Show Expr)
</code>```

got:

```<code>*deriving> Lit 1
Lit 1 : Expr
*deriving> Add (Lit 1) (Lit 1)
(input):Can't infer argument deriving to Add
</code>```

I have searched the keyword deriving on http://docs.idris-lang.org/ and google,  and even in the idris-dev repo under test/ directory, but there is no demo for the usage of deriving in idris. Anyone can help?

答: You can use Stefan Hoeck's idris2-sop library to generate implementations with elaborator reflection.</p>

Title: How to use `deriving` in Idris?

Body:
I'm trying to deriving Show, Eq, Ord etc in Idris, but none of the following trials works:

trail #1:

data Expr =
      Lit Int
    | Neg Expr
    | Add Expr Expr
    deriving (Show)

got:

deriving.idr:5:15-18:
  |
5 |     deriving (Show)
  |               ~~~~
When checking type of Main.Add:
Type mismatch between
        Type -> Type (Type of Show)
and
        Type (Expected type)

trail #2:

data Expr =
      Lit Int
    | Neg Expr
    | Add Expr Expr
    deriving (Show _)

got:

*deriving> Lit 1
Lit 1 : Expr
*deriving> Add (Lit 1) (Lit 1)
(input):Can't infer argument ty to Add, Can't infer argument deriving to Add

trail #3:

data Expr =
      Lit Int
    | Neg Expr
    | Add Expr Expr
    deriving (Show Expr)

got:

*deriving> Lit 1
Lit 1 : Expr
*deriving> Add (Lit 1) (Lit 1)
(input):Can't infer argument deriving to Add

I have searched the keyword deriving on http://docs.idris-lang.org/ and google,  and even in the idris-dev repo under test/ directory, but there is no demo for the usage of deriving in idris. Anyone can help?


问:
why do bindAll in backbone.js views?
In backbone's todo demo the code has a few spots where _.bindAll(this,...) is used. Specifically it's used in the initialize function of both views. As far as I can tell it's necessary to do the following:

```<code>this.$('.todo-content').text(content);
</code>```

But why would one want to do the above, when one can do:

```<code>$('.todo-content').text(content);
</code>```

?

答:
As of Backbone 0.5.2, it's no longer necessary to use _.bindAll(this...) in your views to set the context of the "bind" callback functions, as you can now pass a 3rd argument to bind() that will set the context (i.e. "this") of the callback.

For example:

```<code>var MyView = Backbone.View.extend({
  initialize: function(){
    this.model.bind('change', this.render, this);
  },
  render: function(){
    // "this" is correctly set to the instance of MyView
  }
});
</code>```

Title: why do bindAll in backbone.js views?

Body:
In backbone's todo demo the code has a few spots where _.bindAll(this,...) is used. Specifically it's used in the initialize function of both views. As far as I can tell it's necessary to do the following:

this.$('.todo-content').text(content);

But why would one want to do the above, when one can do:

$('.todo-content').text(content);

?

Body:
As of Backbone 0.5.2, it's no longer necessary to use _.bindAll(this...) in your views to set the context of the "bind" callback functions, as you can now pass a 3rd argument to bind() that will set the context (i.e. "this") of the callback.

For example:

var MyView = Backbone.View.extend({
  initialize: function(){
    this.model.bind('change', this.render, this);
  },
  render: function(){
    // "this" is correctly set to the instance of MyView
  }
});


问:
npm Install error- node modules but no package-lock.json
I'm getting an error with my npm install and would love some help/advice.

```<code>ELIFECYCLE
ENOENT
spawn bash
yorkie@2.0.0 install `node bin/install.js`
spawn bash ENOENT
Failed at the yorkie@2.0.0 install script
This is probably not a problem with npm. There is likely additional logging output above.
</code>```

My node path is set in my environmental variables. My node version is 10.24.1 and npm version is 6.4.1
I am using nvm for windows to manage versions.
Whenever I run npm install I get this error, and node modules is created, but package-lock is not.
I have deleted node modules and ran npm cache clear with no success.

Any tips appreciated!

答:
Try and run the following command.

```<code>npm install --registry=https://registry.npm.taobao.org
</code>```

If that doesn't work, see the following Issues page on GitHub.

yorkie@2.0.0 error

EDIT: Just noticed, you should update your Node.js version. It is on v10 and the current LTS version (at the time posted) is v16. This is just a suggestion, although it might solve your issue.

Body:
I'm getting an error with my npm install and would love some help/advice.

ELIFECYCLE
ENOENT
spawn bash
yorkie@2.0.0 install `node bin/install.js`
spawn bash ENOENT
Failed at the yorkie@2.0.0 install script
This is probably not a problem with npm. There is likely additional logging output above.

My node path is set in my environmental variables. My node version is 10.24.1 and npm version is 6.4.1
I am using nvm for windows to manage versions.
Whenever I run npm install I get this error, and node modules is created, but package-lock is not.
I have deleted node modules and ran npm cache clear with no success.

Any tips appreciated!

Body:
Try and run the following command.

npm install --registry=https://registry.npm.taobao.org

If that doesn't work, see the following Issues page on GitHub.

yorkie@2.0.0 error

EDIT: Just noticed, you should update your Node.js version. It is on v10 and the current LTS version (at the time posted) is v16. This is just a suggestion, although it might solve your issue.


问:
How do you create a toggle button?
I want to create a toggle button in html using css. I want it so that when you click on it  , it stays pushed in and than when you click it on it again it pops out.

If theres no way of doing it just using css. Is there a way to do it using jQuery?

答:
The following approach relies on html-css only, no js of any kind is needed.

The css and the HTML snippet is as simple as this:

#mycbid
{
  display:none;
}

#mycbid:checked + #mylabelid
{
  background: grey;
  border: inset;
}

#mylabelid
{
  background: lightgray;
  border: outset;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="mycbid">
  <label for="mycbid" id="mylabelid">Text of the label</label></code>```

Explication:

Under the hood the checkbox will not be displayed but still it can be set as checked or unchecked so it will be possible to use it more or less as usual.

When the checkbox is checked its status "triggers" the css rules under #mycbid:checked + #mylabelid and the label will be styled accordingly with it. This css selector is in fact the key of everything: in fact it selects the sibling of the checkbox (that is the label it self). The label redirects the click to the checkbox thanks to the for attribute, even if the checkbox is not shown.

When the checkbox is not checked its status "triggers" the css rules under #mylabelid and the label will be styled accordingly with it.

Of course it is possible to style the label in may different ways.

OwnerDisplayName: Donny V

ContentLicense: CC BY-SA 2.5

Title: How do you create a toggle button?

Body:
The following approach relies on html-css only, no js of any kind is needed.

The css and the HTML snippet is as simple as this:

#mycbid
{
  display:none;
}

#mycbid:checked + #mylabelid
{
  background: grey;
  border: inset;
}

#mylabelid
{
  background: lightgray;
  border: outset;
}

<input type="checkbox" id="mycbid">
  <label for="mycbid" id="mylabelid">Text of the label</label>

Explication:

Under the hood the checkbox will not be displayed but still it can be set as checked or unchecked so it will be possible to use it more or less as usual.

When the checkbox is checked its status "triggers" the css rules under #mycbid:checked + #mylabelid and the label will be styled accordingly with it. This css selector is in fact the key of everything: in fact it selects the sibling of the checkbox (that is the label it self). The label redirects the click to the checkbox thanks to the for attribute, even if the checkbox is not shown.

When the checkbox is not checked its status "triggers" the css rules under #mylabelid and the label will be styled accordingly with it.

Of course it is possible to style the label in may different ways.


问:
Suppress validation errors in ASP.NET Core's automatic 400 response
Although the automatic 400 response is useful, I don't want to send validation errors to the client.

This is the response body:

```<code>{
  "errors": {
    "username": [
      "'username' must not be empty."
    ],
    ...more errors
  },
  "title": "One or more validation errors occurred",
  "status": 400,
  "traceId": "xxx:yyy"
}
</code>```

But what I want is the default, without the errors:

```<code>{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "Bad Request",
  "status": 400,
  "traceId": "xxx:yyy"
}
</code>```

I thought all I needed to do was set

```<code>options.SuppressUseValidationProblemDetailsForInvalidModelStateResponses = true;
</code>```

...but that doesn't do anything.

I don't want to disable this feature, I just want to suppress validation errors. How do I do that?

BTW, I am using a workaround, by creating the response body manually, but I'd prefer to avoid this:

```<code>services.Configure<ApiBehaviorOptions>(apiBehaviorOptions => {
  apiBehaviorOptions.InvalidModelStateResponseFactory = actionContext => {
    var pd    = new ProblemDetails();
    pd.Type   = apiBehaviorOptions.ClientErrorMapping[400].Link;
    pd.Title  = apiBehaviorOptions.ClientErrorMapping[400].Title;
    pd.Status = 400;
    pd.Extensions.Add("traceId", actionContext.HttpContext.TraceIdentifier);
    return new BadRequestObjectResult(pd);
  };
});
</code>```

答:
The problem with ProblemDetails is that it is the default response for the StatusCodeResult with ths StatusCode greater or equal to 400.  https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.statuscoderesult?view=aspnetcore-6.0

The following action generates a response with ProblemDetails if the status is greater or equal 400.

```<code>[HttpGet("raw/{status}")]
public IActionResult GetRawStatus(int status)
{
    return StatusCode(status);
}
</code>```

To suppress the default ProblemDetails response body you can have an empty ObjectResult with the status.

The example below generates an response without ProblemDetails for any status code.

```<code>    [HttpGet("object/{status}")]
    public IActionResult GetObjectStatus(int status)
    {
        return new ObjectResult(null) { StatusCode = status };
    }
</code>```

Body:
Although the automatic 400 response is useful, I don't want to send validation errors to the client.

This is the response body:

{
  "errors": {
    "username": [
      "'username' must not be empty."
    ],
    ...more errors
  },
  "title": "One or more validation errors occurred",
  "status": 400,
  "traceId": "xxx:yyy"
}

But what I want is the default, without the errors:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "Bad Request",
  "status": 400,
  "traceId": "xxx:yyy"
}

I thought all I needed to do was set

options.SuppressUseValidationProblemDetailsForInvalidModelStateResponses = true;

...but that doesn't do anything.

I don't want to disable this feature, I just want to suppress validation errors. How do I do that?

BTW, I am using a workaround, by creating the response body manually, but I'd prefer to avoid this:

services.Configure<ApiBehaviorOptions>(apiBehaviorOptions => {
  apiBehaviorOptions.InvalidModelStateResponseFactory = actionContext => {
    var pd    = new ProblemDetails();
    pd.Type   = apiBehaviorOptions.ClientErrorMapping[400].Link;
    pd.Title  = apiBehaviorOptions.ClientErrorMapping[400].Title;
    pd.Status = 400;
    pd.Extensions.Add("traceId", actionContext.HttpContext.TraceIdentifier);
    return new BadRequestObjectResult(pd);
  };
});

Body:
The problem with ProblemDetails is that it is the default response for the StatusCodeResult with ths StatusCode greater or equal to 400.  https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.statuscoderesult?view=aspnetcore-6.0

The following action generates a response with ProblemDetails if the status is greater or equal 400.

[HttpGet("raw/{status}")]
public IActionResult GetRawStatus(int status)
{
    return StatusCode(status);
}

To suppress the default ProblemDetails response body you can have an empty ObjectResult with the status.

The example below generates an response without ProblemDetails for any status code.

    [HttpGet("object/{status}")]
    public IActionResult GetObjectStatus(int status)
    {
        return new ObjectResult(null) { StatusCode = status };
    }


问:
Site integrated with discord
I was just wondering, how can I post to a website (in this case a dashboard) with information from a discord server? For example, the number of members, number of admins, all the people with information like name, the chat history and so on? I’m new to this genre of things (only discord to site integration, Js is fine for me :) )

Btw I will post a GitHub page if everything works so you can have the source code and tweaking it for your server!

Thank you in advance and I hope someone will explain me how to do that and what I have to use!

答:
If you want to display this on the frontend which is connected using a backend I would use fetch/axios to call the Guild API EndPoint https://discord.com/developers/docs/resources/guild#get-guild
The Function can be

```<code>    return axios.get<PartialGuild>(`https://discord.com/api/v9/guilds/${serverId}?with_counts=true`, {
      headers: {
        Authorization: `Bot ${process.env.DISCORD_BOT_TOKEN}`,
      },
    });
</code>```

If you don't use typescript you can remove the <PartialGuild> as its used to typecast. The Partial Guild is helpful as you can set the object to items you only need and return that back to the front-end.

Make Aprox memberCount & Presence count optional as they are only returned if with_counts=true

```<code>export type PartialGuild = {
  id: string;
  name: string;
  icon: string;
  owner: boolean;
  permissions: string;
  features: string[];
 approximate_member_count?: number;
 approximate_presence_count?: number;
};
</code>```

If you don't have a backend where you can fetch this and only have a front-end + Discord Bot you could setup a websocket where the dashboard communicates directly with the front-end (this wouldn't be a recommended idea and a back-end would be more suitable for this). However I assume you have a backend because the front-end should only display this information to people who have been authorized.

You can repeat the process for other information from different EndPoints (check out the rest of the docs)
https://discord.com/developers/docs/resources/guild#list-guild-members
this will fetch guild members for a specified guild and with this you can filter the users by roles.

Title: Site integrated with discord

Body:
If you want to display this on the frontend which is connected using a backend I would use fetch/axios to call the Guild API EndPoint https://discord.com/developers/docs/resources/guild#get-guild
The Function can be

    return axios.get<PartialGuild>(`https://discord.com/api/v9/guilds/${serverId}?with_counts=true`, {
      headers: {
        Authorization: `Bot ${process.env.DISCORD_BOT_TOKEN}`,
      },
    });

If you don't use typescript you can remove the <PartialGuild> as its used to typecast. The Partial Guild is helpful as you can set the object to items you only need and return that back to the front-end.

Make Aprox memberCount & Presence count optional as they are only returned if with_counts=true

export type PartialGuild = {
  id: string;
  name: string;
  icon: string;
  owner: boolean;
  permissions: string;
  features: string[];
 approximate_member_count?: number;
 approximate_presence_count?: number;
};

If you don't have a backend where you can fetch this and only have a front-end + Discord Bot you could setup a websocket where the dashboard communicates directly with the front-end (this wouldn't be a recommended idea and a back-end would be more suitable for this). However I assume you have a backend because the front-end should only display this information to people who have been authorized.

You can repeat the process for other information from different EndPoints (check out the rest of the docs)
https://discord.com/developers/docs/resources/guild#list-guild-members
this will fetch guild members for a specified guild and with this you can filter the users by roles.


答:
You can use regular expression to find a matched keys with the templete.

My code find all the matched keys, and it is case-insensitive code, as follows:

import re

dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}

output = []
for key in dictionary.keys():
    matched = re.match("[Ww]+..[Ee]+[Rr]+$", key) # case-insensitive, 5 letters
    if matched:
        output.append(key)

print(output)
#['water', 'weber', 'waver']
```

For more information about regular expressions with examples, you can see: https://docs.python.org/3/library/re.html

Title: Python Function that Match a Given Template

Body:
Say I have a template and I have a dictionary containing words. I want to create a function that returns a list of words that match the given template. To illustrate this:

template = 'W**ER'
dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}

Desired output:
output_list = ['water', 'weber', 'waver']

I'm not entirely sure how to create the function and I would totally appreciate any help. Thanks!

Body:
You can use regular expression to find a matched keys with the templete.

My code find all the matched keys, and it is case-insensitive code, as follows:

import re

dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}

output = []
for key in dictionary.keys():
    matched = re.match("[Ww]+..[Ee]+[Rr]+$", key) # case-insensitive, 5 letters
    if matched:
        output.append(key)

print(output)
#['water', 'weber', 'waver']

For more information about regular expressions with examples, you can see: https://docs.python.org/3/library/re.html


问:
copy line from a txt file and replace it in another txt file at specific number line using PowerShell
I'm relatively new to PowerShell. I would like to be able to copy a text line from a list file and paste it on another text file at specific number line.

I have the first step copy specific number line and need the second steppaste at specific number line:

```<code>Get-Content C:\Temp\Megateo\Hash.txt -TotalCount 121 | Select-Object -Skip 1 -First 1 > C:\Temp\Megateo\Monin.txt
</code>```

答:
You would need to provide a bit more details on where (index) you want to insert the line from the other file, but to show you one way to approach the problem slicing the index of your content file. Let's say we have test.txt which looks like this:

```<code>text text text text text text
text text text text text text
insert line below here
text text text text text text
text text text text text text
</code>```

And we want to insert hello world! below insert line below here, here is how you could do it:

```<code>$toInsert = 'hello world!'
$content = Get-Content ./test.txt
$index = $content.IndexOf('insert line below here')

$newContent = @(
    $content[0..$index++]
    $toInsert
    $content[$index..($content.Count - 1)]
)

$newContent | Out-File path/to/newfile....
</code>```

Now if we inspect $newContent:

```<code>PS /> $newContent

text text text text text text
text text text text text text
insert line below here
hello world!
text text text text text text
text text text text text text
</code>```

Body:
I'm relatively new to PowerShell. I would like to be able to copy a text line from a list file and paste it on another text file at specific number line.

I have the first step copy specific number line and need the second steppaste at specific number line:

Get-Content C:\Temp\Megateo\Hash.txt -TotalCount 121 | Select-Object -Skip 1 -First 1 > C:\Temp\Megateo\Monin.txt

Body:
You would need to provide a bit more details on where (index) you want to insert the line from the other file, but to show you one way to approach the problem slicing the index of your content file. Let's say we have test.txt which looks like this:

text text text text text text
text text text text text text
insert line below here
text text text text text text
text text text text text text

And we want to insert hello world! below insert line below here, here is how you could do it:

$toInsert = 'hello world!'
$content = Get-Content ./test.txt
$index = $content.IndexOf('insert line below here')

$newContent = @(
    $content[0..$index++]
    $toInsert
    $content[$index..($content.Count - 1)]
)

$newContent | Out-File path/to/newfile....

Now if we inspect $newContent:

PS /> $newContent

text text text text text text
text text text text text text
insert line below here
hello world!
text text text text text text
text text text text text text


问:
problem with the if statement
i m parsing a json file.the logic goes like this, if there is no data in the variable named boy.it got to enter the if loop and if there is data it got to enter the else part.but the problem is even if the variable boy is empty(which shows  empty in the console) the loop still enters the else part..cud u guys help me out..below is the code..

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
NSDictionary *boy=[url objectAtIndex:indexPath.row];
NSLog(@"the boy value:%@",boy);
if (boy == NULL)
{
Secondetailview *detailViewController1 = [[Secondetailview alloc] initWithItem:boy];
[self.navigationController pushViewController:detailViewController1 animated:YES];
[detailViewController1 release];
}else
{
    FirstViewDetail *detailViewController = [[FirstViewDetail alloc] initWithItem:boy];

    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}
</code>```

}

答:
Modify your if condition as below and see if that works.</p>

```<code>((boy == NULL) || ([boy count] == 0))
</code>```

Title: problem with the if statement

Body:
i m parsing a json file.the logic goes like this, if there is no data in the variable named boy.it got to enter the if loop and if there is data it got to enter the else part.but the problem is even if the variable boy is empty(which shows  empty in the console) the loop still enters the else part..cud u guys help me out..below is the code..

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
NSDictionary *boy=[url objectAtIndex:indexPath.row];
NSLog(@"the boy value:%@",boy);
if (boy == NULL)
{
Secondetailview *detailViewController1 = [[Secondetailview alloc] initWithItem:boy];
[self.navigationController pushViewController:detailViewController1 animated:YES];
[detailViewController1 release];
}else
{
    FirstViewDetail *detailViewController = [[FirstViewDetail alloc] initWithItem:boy];

    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}

}

Body:
Modify your if condition as below and see if that works.

((boy == NULL) || ([boy count] == 0))


问:
how to copy to clipboard text between h2 tags in selenium python
what i try to do here is get email code for verification. so I log in to the email, select and copy the 6 digits code from the email and paste it to the other tab. everything is done except i can not double click to select the 6 digit code and copy it to clipboard. the code is between h2 tag and nothing else, like this: 639094 where 639094 is actually the code which i need to be copied. how can i find the code element or whatever and copy it? here is a screen shot of the email and the chrome inspect element if anything helps.

this is the code that I use to copy the code:

```<code>codeID = driver.find_element(By.XPATH,
'//table[@class="main"]//tr//td//p//h2').text

ActionChains = ActionChains(driver)
ActionChains.double_click(codeID).perform()
time.sleep(2)
codeID.send_keys(Keys.CONTROL + 'c')
text = pyperclip.paste()
print(text)
</code>```

screen shot

答:
Hey i will analyse this problem with you
For the first part :

try to take that XPath you have and past it in the Xpath helper (google chrome extension)
=> If you find that element , than the problem in your code
=> if you don’t than the element is already in a frame or in a table
The solution is to change your drive to the new frame and relocate the element inside the frame
Exemple :

iframe_xpath = driver.find_element_by_xpath('//iframe')

driver.switch_to.frame('iframe_xpath')
Now try to relocate the element starting from the iframe

For the second part :
You say it’s a table so you need to mention the /td[i] and /tr[j] value where the number is located so you can get it
Exemple

```<code>d = driver.find_element_by_xpath( "//tr[i]/td[j]").text
</code>```

I hope that’s help

Body:
what i try to do here is get email code for verification. so I log in to the email, select and copy the 6 digits code from the email and paste it to the other tab. everything is done except i can not double click to select the 6 digit code and copy it to clipboard. the code is between h2 tag and nothing else, like this: 639094 where 639094 is actually the code which i need to be copied. how can i find the code element or whatever and copy it? here is a screen shot of the email and the chrome inspect element if anything helps.

this is the code that I use to copy the code:

codeID = driver.find_element(By.XPATH,
'//table[@class="main"]//tr//td//p//h2').text

ActionChains = ActionChains(driver)
ActionChains.double_click(codeID).perform()
time.sleep(2)
codeID.send_keys(Keys.CONTROL + 'c')
text = pyperclip.paste()
print(text)

screen shot

Body:
Hey i will analyse this problem with you
For the first part :

try to take that XPath you have and past it in the Xpath helper (google chrome extension)
=> If you find that element , than the problem in your code
=> if you don’t than the element is already in a frame or in a table
The solution is to change your drive to the new frame and relocate the element inside the frame
Exemple :

iframe_xpath = driver.find_element_by_xpath('//iframe')

driver.switch_to.frame('iframe_xpath')
Now try to relocate the element starting from the iframe

For the second part :
You say it’s a table so you need to mention the /td[i] and /tr[j] value where the number is located so you can get it
Exemple

d = driver.find_element_by_xpath( "//tr[i]/td[j]").text

I hope that’s help


问:
Google Vision API normalize image
I'm using Google Vison API with PHP.

I want to analyze image and extract table data from it.

The image will not always be aligned or in the same size.

I've got reference image which I'm looking for words that I know will always be there and then I'm trying to compare to the current image and fix positions

For each word I've got the bounds(top left, top right, bottom right, bottom left)

I've draw the bounds of the words.
reference image => red,
current image => green

Next I've compared the top red and green rectangles and shift them all based on the differences.
adjusted image => cyan.

The top one is correct because he was the reference. the others just shift but the distance between them are not correct.

What is the best practice to normalize the image based on reference image.

Thanks.

答:
The API returns the height and width: https://cloud.google.com/vision/docs/reference/rest/v1/AnnotateImageResponse#page

You could use those numbers and the numbers from your golden image to know how much to shift the boxes.

Title: Google Vision API normalize image