问:
Entity Framework 6: Is it safe to 'clear' resources of old migrations to reduce assembly size?
My database-project (EF6, code-first) has grown to a >15MB dll-file. This is mainly caused by the resources of all historical migrations.

As far as I understand from reading documentation, these old resources are not used.

Is it safe to remove the resources of these historical migrations (or replace with empty values), when leaving the last migration(s) unchanged?

答:
To answer my own question; the answer is: No, you cannot clear resources of old migrations.

I have set-up a test project with a number of migrations and experimented with it, but at a certain point it is no longer possible to apply certain migrations as the schema in the resource is required for additional information.

```<code>update-database -verbose
(..)
Applying explicit migration: 202005271522443_EnrollmentMigration.
System.Data.Entity.Migrations.Infrastructure.MigrationsException: The Foreign Key on table 'dbo.Enrollment' with columns 'CourseID' could not be created because the principal key columns could not be determined. Use the AddForeignKey fluent API to fully specify the Foreign Key.
   bij System.Data.Entity.Migrations.DbMigrator.FillInForeignKeyOperations(IEnumerable`1 operations, XDocument targetModel)
   bij System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
</code>```

Of course, I could try to decorate each FK, but for now I have decided to stop this experiment as it will probably lead to further problems related to missing schema information..

Body:
To answer my own question; the answer is: No, you cannot clear resources of old migrations.

I have set-up a test project with a number of migrations and experimented with it, but at a certain point it is no longer possible to apply certain migrations as the schema in the resource is required for additional information.

update-database -verbose
(..)
Applying explicit migration: 202005271522443_EnrollmentMigration.
System.Data.Entity.Migrations.Infrastructure.MigrationsException: The Foreign Key on table 'dbo.Enrollment' with columns 'CourseID' could not be created because the principal key columns could not be determined. Use the AddForeignKey fluent API to fully specify the Foreign Key.
   bij System.Data.Entity.Migrations.DbMigrator.FillInForeignKeyOperations(IEnumerable`1 operations, XDocument targetModel)
   bij System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)

Of course, I could try to decorate each FK, but for now I have decided to stop this experiment as it will probably lead to further problems related to missing schema information..


来源: stackexchange

问:
error java The method combinationSum(int[], int, List<Integer>) in the type Solution is not applicable for the arguments (int[], int, boolean)
///to get all values that addup to the target . error The method combinationSum(int[], int, List) in the type Solution is not
     applicable for the arguments (int[], int, boolean)

```<code>import java.util.*;
public class Solution {

    static List<Integer> b= new ArrayList<Integer>();
    static List<List<Integer>> c= new ArrayList<List<Integer>>();
    public static void combinationSum(int[] candidates, int target, List<Integer> b)
    {
        if(target==0)
        {
            c.add(b);
        }

        else {
        for(int i=0;i<candidates.length;i++)
        {

//          else
//          {
          //  if( target < 0 )
          //  {
                //b.remove( b.size() - 1 );
          //  }
            if(target>0)
            {
                //b.add(candidates[i]);
                combinationSum(candidates,target-candidates[i],b.add(candidates[i]));
                //b.remove( b.size() - 1 );
            }
            //}
        }
        }
        //return;
    }

    public static void main(String[] args)
    {
        int[] candidates= {2,3,5};
        int target=8;
        combinationSum(candidates,target,b);
        System.out.println(c);
    }
</code>```

答:
You can try this :

```<code>b.add(candidates[i]);
combinationSum(candidates,target-candidates[i],b));
</code>```

First add the candidates to b and then pass the list in the recursive call.

ContentLicense: CC BY-SA 4.0

Body:
///to get all values that addup to the target . error The method combinationSum(int[], int, List) in the type Solution is not
     applicable for the arguments (int[], int, boolean)

import java.util.*;
public class Solution {

    static List<Integer> b= new ArrayList<Integer>();
    static List<List<Integer>> c= new ArrayList<List<Integer>>();
    public static void combinationSum(int[] candidates, int target, List<Integer> b)
    {
        if(target==0)
        {
            c.add(b);
        }

        else {
        for(int i=0;i<candidates.length;i++)
        {

//          else
//          {
          //  if( target < 0 )
          //  {
                //b.remove( b.size() - 1 );
          //  }
            if(target>0)
            {
                //b.add(candidates[i]);
                combinationSum(candidates,target-candidates[i],b.add(candidates[i]));
                //b.remove( b.size() - 1 );
            }
            //}
        }
        }
        //return;
    }

    public static void main(String[] args)
    {
        int[] candidates= {2,3,5};
        int target=8;
        combinationSum(candidates,target,b);
        System.out.println(c);
    }

Body:
You can try this :

b.add(candidates[i]);
combinationSum(candidates,target-candidates[i],b));

First add the candidates to b and then pass the list in the recursive call.


问:
Force close all open popups from code
I want to cause all open popups (with StaysOpen == false) to close from code.  Basically I want to simulate the user clicking the mouse (which would close the popups) from code.

I don't need to actually simulate the click, I just need the resulting behavior.  I've thought about just going through the visual tree looking for popups and closing each one, but that doesn't seem like the cleanest approach.

Thanks in advance for any help or opinions.

答:
My previous answer was also not working all the time. It only worked when the Visual Studio debugger was attached to the process. What ended up working in any case is the following:</p>
```<code>Application.Current.Dispatcher.Invoke(() =>
{
    PresentationSource.CurrentSources.OfType<HwndSource>()
        .Select(h => h.RootVisual)
        .OfType<FrameworkElement>()
        .Select(f => f.Parent)
        .OfType<Popup>()
        .Where(popup => popup.IsOpen)
        .ToList()
        .ForEach(popup => popup.SetCurrentValue(Popup.IsOpenProperty, false));
});
</code>```

ContentLicense: CC BY-SA 2.5

Title: Force close all open popups from code

Body:
My previous answer was also not working all the time. It only worked when the Visual Studio debugger was attached to the process. What ended up working in any case is the following:

Application.Current.Dispatcher.Invoke(() =>
{
    PresentationSource.CurrentSources.OfType<HwndSource>()
        .Select(h => h.RootVisual)
        .OfType<FrameworkElement>()
        .Select(f => f.Parent)
        .OfType<Popup>()
        .Where(popup => popup.IsOpen)
        .ToList()
        .ForEach(popup => popup.SetCurrentValue(Popup.IsOpenProperty, false));
});


问:
I've tried to give a physicsBodyComponet to modelEntity, and It just falls deep down
On reality kit, I've tried to give a physicsBodyComponent to a modelEntity.

But as I put to modelEntity to real world, It just fall down.

Is there anyway to fix this?

答:
You need to create a floor mesh with a PhysicsBodyComponent:

let floor = ModelEntity(mesh: .generateBox(size: [1000, 0, 1000]), materials: [SimpleMaterial()])
floor.generateCollisionShapes(recursive: true)
if let collisionComponent = floor.components[CollisionComponent] as? CollisionComponent {
    floor.components[PhysicsBodyComponent] = PhysicsBodyComponent(shapes: collisionComponent.shapes, mass: 0, material: nil, mode: .static)
    floor.components[ModelComponent] = nil // make the floor invisible
}
scene?.addChild(floor)
```

<p>Then, when you load your entities, you also give them a <code>PhysicsBodyComponent</code> (and they need a non-zero <code>mass</code>, otherwise they will anyways fall through, which is what eluded me for a long time):</p>

<pre class="lang-swift prettyprint-override"><code>var loadModelCancellable: AnyCancellable? = nil
loadModelCancellable = Entity.loadModelAsync(named: modelUri)
  .sink(receiveCompletion: { _ in
      loadModelCancellable?.cancel()
  }, receiveValue: { entity in
      entity.generateCollisionShapes(recursive: true)

      if let collisionComponent = entity.components[CollisionComponent] as? CollisionComponent {
          entity.components[PhysicsBodyComponent] = PhysicsBodyComponent(shapes: collisionComponent.shapes, mass: 1, material: nil, mode: .dynamic)
      }

      scene.addChild(entity)
      loadModelCancellable?.cancel()
  })
</code>```

In the end, adding physics to my project had too many unintended consequences for what I was trying to do (just preventing models to overlap), like models pushing each other, and movements needing to be redone completely, ... So I didn't get further than this, but at least this should let you add physics to your models without them falling indefinitely from gravity.

Body:
You need to create a floor mesh with a PhysicsBodyComponent:

let floor = ModelEntity(mesh: .generateBox(size: [1000, 0, 1000]), materials: [SimpleMaterial()])
floor.generateCollisionShapes(recursive: true)
if let collisionComponent = floor.components[CollisionComponent] as? CollisionComponent {
    floor.components[PhysicsBodyComponent] = PhysicsBodyComponent(shapes: collisionComponent.shapes, mass: 0, material: nil, mode: .static)
    floor.components[ModelComponent] = nil // make the floor invisible
}
scene?.addChild(floor)

Then, when you load your entities, you also give them a PhysicsBodyComponent (and they need a non-zero mass, otherwise they will anyways fall through, which is what eluded me for a long time):

var loadModelCancellable: AnyCancellable? = nil
loadModelCancellable = Entity.loadModelAsync(named: modelUri)
  .sink(receiveCompletion: { _ in
      loadModelCancellable?.cancel()
  }, receiveValue: { entity in
      entity.generateCollisionShapes(recursive: true)

      if let collisionComponent = entity.components[CollisionComponent] as? CollisionComponent {
          entity.components[PhysicsBodyComponent] = PhysicsBodyComponent(shapes: collisionComponent.shapes, mass: 1, material: nil, mode: .dynamic)
      }

      scene.addChild(entity)
      loadModelCancellable?.cancel()
  })

In the end, adding physics to my project had too many unintended consequences for what I was trying to do (just preventing models to overlap), like models pushing each other, and movements needing to be redone completely, ... So I didn't get further than this, but at least this should let you add physics to your models without them falling indefinitely from gravity.


问:
Rewrite correlated subquery, Redshift throwing This type of correlated subquery pattern is not supported yet Error
I'm working on a query that needs to left join table A with table B on A.user_id=B.user_id and B.day is less than A.day but is closest to A.day.

Here's what I wrote:

```<code>Select A.user_id, A.date, b1.v1 from A
Left Join B as b1
on A.user_id=b1.user_id and b1.day=(Select max(day) from B as b2 where b2.user_id=A.user_id
and b2.day < A.day)
</code>```

I'm doing this in python using psycopg2 and it's returning error: This type of correlated subquery pattern is not supported yet.

Can someone help me rewrite this so it doesn't use correlated subquery?

答:
One way to do this can be:</p>

```<code>Select A.user_id, A.date, b1.v1, max(b1.day)
from A Left Join B as b1 on A.user_id=b1.user_id and b1.day < A.day
group by A.user_id, A.date, b1.v1;
</code>```

Body:
I'm working on a query that needs to left join table A with table B on A.user_id=B.user_id and B.day is less than A.day but is closest to A.day.

Here's what I wrote:

Select A.user_id, A.date, b1.v1 from A
Left Join B as b1
on A.user_id=b1.user_id and b1.day=(Select max(day) from B as b2 where b2.user_id=A.user_id
and b2.day < A.day)

I'm doing this in python using psycopg2 and it's returning error: This type of correlated subquery pattern is not supported yet.

Can someone help me rewrite this so it doesn't use correlated subquery?

Body:
One way to do this can be:

Select A.user_id, A.date, b1.v1, max(b1.day)
from A Left Join B as b1 on A.user_id=b1.user_id and b1.day < A.day
group by A.user_id, A.date, b1.v1;


问:
Check if a word is enclosed within quotes using javascript
I have a string like get(3,"No MATCH",obj). I want to check if the word MATCH is enclosed within quotes (either single quote or double quote). Here MATCH is enclosed within quotes, although not exactly as "MATCH", it is still a part of the text contained in quotes as "No MATCH".

I want to write a function which takes the word (MATCH) as argument and returns true if it is contained within quotes or false if not.

Following are some other input strings which needs to be checked by this
function:

* get(1101,"MATCH",obj) --> return true since MATCH is within quotes

* get(255,'NO MATCH',obj) --> return true since MATCH is a part of text contained within quotes

* get(1111,"" , MATCH) ---> return false since MATCH is not contained within quotes

答:
If you're trying to perform syntactic analysis you should consider using esprima

This is the AST returned by

esprima.parse(`get(1111,"" , MATCH)`);
```

```{
  "type": "Program",
  "body": [
    {
      "type": "ExpressionStatement",
      "expression": {
        "type": "CallExpression",
        "callee": {
          "type": "Identifier",
          "name": "get"
        },
        "arguments": [
          {
            "type": "Literal",
            "value": 1111,
            "raw": "1111"
          },
          {
            "type": "Literal",
            "value": "",
            "raw": "\"\""
          },
          {
            "type": "Identifier",
            "name": "MATCH"
          }
        ]
      }
    }
  ],
  "sourceType": "script"
}
```

<p>And here's for</p>

<pre class="lang-js prettyprint-override"><code>esprima.parse(`get(255,'NO MATCH',obj)`)
</code>```

```<code>{
  "type": "Program",
  "body": [
    {
      "type": "ExpressionStatement",
      "expression": {
        "type": "CallExpression",
        "callee": {
          "type": "Identifier",
          "name": "get"
        },
        "arguments": [
          {
            "type": "Literal",
            "value": 255,
            "raw": "255"
          },
          {
            "type": "Literal",
            "value": "NO MATCH",
            "raw": "'NO MATCH'"
          },
          {
            "type": "Identifier",
            "name": "obj"
          }
        ]
      }
    }
  ],
  "sourceType": "script"
}
</code>```

You can search a 'Literal' type which value includes 'MATCH'.

const matcher = code => {
  const ast = esprima.parse(code);
  const args = ast.body[0].expression.arguments;
  return args.some(({value, type}) =>
       type === 'Literal'
    && typeof value === 'string'
    && value.includes('MATCH'));
};

console.log(matcher(`get(1101,"MATCH",obj)`));
console.log(matcher(`get(255,'NO MATCH',obj)`));
console.log(matcher(`get(1111,"" , MATCH)`));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/esprima@~4.0/dist/esprima.js"></script></code>```

Body:
If you're trying to perform syntactic analysis you should consider using esprima

This is the AST returned by

esprima.parse(`get(1111,"" , MATCH)`);

{
  "type": "Program",
  "body": [
    {
      "type": "ExpressionStatement",
      "expression": {
        "type": "CallExpression",
        "callee": {
          "type": "Identifier",
          "name": "get"
        },
        "arguments": [
          {
            "type": "Literal",
            "value": 1111,
            "raw": "1111"
          },
          {
            "type": "Literal",
            "value": "",
            "raw": "\"\""
          },
          {
            "type": "Identifier",
            "name": "MATCH"
          }
        ]
      }
    }
  ],
  "sourceType": "script"
}

And here's for

esprima.parse(`get(255,'NO MATCH',obj)`)

{
  "type": "Program",
  "body": [
    {
      "type": "ExpressionStatement",
      "expression": {
        "type": "CallExpression",
        "callee": {
          "type": "Identifier",
          "name": "get"
        },
        "arguments": [
          {
            "type": "Literal",
            "value": 255,
            "raw": "255"
          },
          {
            "type": "Literal",
            "value": "NO MATCH",
            "raw": "'NO MATCH'"
          },
          {
            "type": "Identifier",
            "name": "obj"
          }
        ]
      }
    }
  ],
  "sourceType": "script"
}

You can search a 'Literal' type which value includes 'MATCH'.

const matcher = code => {
  const ast = esprima.parse(code);
  const args = ast.body[0].expression.arguments;
  return args.some(({value, type}) =>
       type === 'Literal'
    && typeof value === 'string'
    && value.includes('MATCH'));
};

console.log(matcher(`get(1101,"MATCH",obj)`));
console.log(matcher(`get(255,'NO MATCH',obj)`));
console.log(matcher(`get(1111,"" , MATCH)`));

<script src="https://unpkg.com/esprima@~4.0/dist/esprima.js"></script>


问:
Duplicating wordpress database for local environment using Laragon
I'm trying to create a local development environment to test website changes out in.  The web developers I'm working with have a gitlab repo of the website with auto DevOps where changes are pushed to the production/stage sever when commited.

I downloaded Laragon and was able to serve pages locally, then I cloned the gitlab repo into my root directory.

How do I get a copy of production website's database and then connect it to my local development environment with laragon?  I tried to duplicate the database on production with WP all-in-one migration but there are read/write restrictions.

I was advised the following:  "I would recommend copying the database onto your local MariaDB/MySQL server the Laragon provides. You'd need to get a dump of the database from the server using SSH command line tools and then you can use the phpMyAdmin interface provided by Laragon to upload the dump".

I wasn't able to SSH from the windows command line, but I could SSH into the server using Putty, however, how am I able to transfer the file to my local windows machine?  If I'm logged into my server wouldn't the file just be placed somewhere in the file system of the remote machine, so I wouldn't be able to use it with Laragon.

答:
If you are using Laragon Full, you have ssh/scp command in Laragon's Terminal. So you can get your-sql-dump from your remote server easily.

Here's how:

Open Laragon's Terminal:

Menu > Laragon > Terminal

Run this command:

```<code>scp user@your-remote-host:/path-to-your-sql-dump C:/laragon/tmp/your-sql-dump
</code>```

Import your sql-dump to your local database:

```<code>mysql -u root -p your-database < C:\laragon\tmp\your-sql-dump
</code>```

Reference: https://laragon.org/download/migrate-from-xampp.html

That's all.

Body:
If you are using Laragon Full, you have ssh/scp command in Laragon's Terminal. So you can get your-sql-dump from your remote server easily.

Here's how:

Open Laragon's Terminal:

Menu > Laragon > Terminal

Run this command:

scp user@your-remote-host:/path-to-your-sql-dump C:/laragon/tmp/your-sql-dump

Import your sql-dump to your local database:

mysql -u root -p your-database < C:\laragon\tmp\your-sql-dump

Reference: https://laragon.org/download/migrate-from-xampp.html

That's all.


问:
Git: force a pull to overwrite local changes
I would like my local branch to be identical to the remote one. When I pull from the remote one, I'm getting conflicts, and in this case I would like not to resolve them and just get the latest version from the remote branch.

To hard pull I use in my local branch:

```<code>git reset -- hard

git pull
</code>```

Nevertheless, when pulling I'm getting the error:

```<code>Automatic merge failed; fix conflicts and then commit the result.
</code>```

Why? How can I pull the remote branch with overwriting? I thought of a workaround to just delete my local branch and create a new one and then pull, but is there a better way?

答:
Try doing a git fetch to bring the (local) remote tracking branch up to date with the remote version, then hard reset your local branch to that:

```<code># from local
git fetch origin
git reset --hard origin/local
</code>```

As to why you are still getting merge conflicts even after a hard reset, this could be explained by a few things.  The general explanation would be that your local branch has commits which are not present in the remote version.  In that case, Git cannot simply fast-forward your local branch, and must resort to doing a merge instead, which can lead to conflicts.

Body:
I would like my local branch to be identical to the remote one. When I pull from the remote one, I'm getting conflicts, and in this case I would like not to resolve them and just get the latest version from the remote branch.

To hard pull I use in my local branch:

git reset -- hard

git pull

Nevertheless, when pulling I'm getting the error:

Automatic merge failed; fix conflicts and then commit the result.

Why? How can I pull the remote branch with overwriting? I thought of a workaround to just delete my local branch and create a new one and then pull, but is there a better way?

Body:
Try doing a git fetch to bring the (local) remote tracking branch up to date with the remote version, then hard reset your local branch to that:

# from local
git fetch origin
git reset --hard origin/local

As to why you are still getting merge conflicts even after a hard reset, this could be explained by a few things.  The general explanation would be that your local branch has commits which are not present in the remote version.  In that case, Git cannot simply fast-forward your local branch, and must resort to doing a merge instead, which can lead to conflicts.


问:
How do I get an element with a specific ID from getElementsByClassName?
EDIT: SOLVED. Thanks everyone!

I'm new to programming :D My code is below. Here is the deal: I have multiple buttons, but I want to make it so that the same thing would happen anytime any one of these buttons is clicked, but each button also has a specific value, and I also want that specific value to be printed out. My code goes through the document and looks at all the elements with "editButton" class, and correctly identifies all the buttons, but the problem is that no matter which button I press, I always get the value of the last button, because var id only gets assigned after the for loop finishes and is on the last element. I tried creating a global variable and assigning the value to it, but the result is the same. I tried ending the for loop before moving on to .done (function (data), but I got an error. Can someone help me out? Thanks!

$(document).ready(function() {
  var anchors = document.getElementsByClassName('editButton');
  for (var i = 0; i < anchors.length; i++) {
    var anchor = anchors[i];
    anchor.onclick = function() {
      $.ajax({
        method: "GET",
        url: "/testedit.php",
      }).done(function(data) {
        var id = anchor.value;

        /* from result create a string of data and append to the div */

        var result = data;
        var string = '
ID is ' + id + '

';

        $("#records").html(string);
      });
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="records"></div></code>```

答:
Actually, instead of doing a huge for loop to add onclick events to your buttons, one of the best ways to do this is to listen to each button with editButton class on click() event then use $(this) which refers to the exact clicked button. After that, you can use each individual button to do whatever you want.

So your final code should be something like this:

$(document).ready(function() {
  $('.editButton').click(function() {
  console.log('innerHTML is:', $(this).html())
  console.log('id is:', $(this).attr('id'))
    $.ajax({
      method: "GET",
      url: "/testedit.php",
    }).done(function(data) {
      var id = $(this).value;

      /* from result create a string of data and append to the div */

      var result = data;
      var string = '
ID is ' + id + '

';

      $("#records").html(string);
    });
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="records">
  <button class="editButton" id="firstButton">button 1</button>
  <button class="editButton" id="secondButton">button 2</button>
  <button class="editButton" id="thirdButton">button 3</button>
  <button class="editButton" id="fourthButton">button 4</button>
</div></code>```

Body:
Actually, instead of doing a huge for loop to add onclick events to your buttons, one of the best ways to do this is to listen to each button with editButton class on click() event then use $(this) which refers to the exact clicked button. After that, you can use each individual button to do whatever you want.

So your final code should be something like this:

$(document).ready(function() {
  $('.editButton').click(function() {
  console.log('innerHTML is:', $(this).html())
  console.log('id is:', $(this).attr('id'))
    $.ajax({
      method: "GET",
      url: "/testedit.php",
    }).done(function(data) {
      var id = $(this).value;

      /* from result create a string of data and append to the div */

      var result = data;
      var string = '<p>ID is ' + id + '</p><br>';

      $("#records").html(string);
    });
  })
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="records">
  <button class="editButton" id="firstButton">button 1</button>
  <button class="editButton" id="secondButton">button 2</button>
  <button class="editButton" id="thirdButton">button 3</button>
  <button class="editButton" id="fourthButton">button 4</button>
</div>


问:
Node.js MongoDB crashes on Client.close()
I am using latest Mongodb 3.5.7 with Node.js and Express,

What I do is I call an async function when an API is being called and the code is as following  :

async function insert(data) {

        try {
             const connection = await client.connect();
             db =client.db(dbName);
             const insertion  = await db.collection('inserts').insertOne(data);
             //console.log(await client.close());
             await console.log('finished waiting promises');
             await client.close();
        } catch (err) {
            console.log(err.stack);
            return Promise.reject('false');
        }
        return new Promise(resolve =>{

            resolve();
        })
}
```

<p>`
In fact the first API Call works so well and successfully inserts the data into db , the issue starts with the second try which brings this error </p>

<p>I also tried promises in separated functions with every command ( connect - insert -close ) with call back promise and await for each one to be done. </p>

<p>As well tried calling connecting function which i created.then(setdbname).then(insert).then(closedb) ...</p>

```
the options [servers] is not supported
the options [caseTranslate] is not supported
the options [dbName] is not supported
the options [credentials] is not supported

MongoError: topology was destroyed
    at executeWriteOperation (C:\Users\raymo\Documents\Ticket\node_modules\mongodb\lib\core\topologies\replset.js:1188:21)
    at ReplSet.insert (C:\Users\raymo\Documents\Ticket\node_modules\mongodb\lib\core\topologies\replset.js:1257:3)
    at ReplSet.insert (C:\Users\raymo\Documents\Ticket\node_modules\mongodb\lib\topologies\topology_base.js:322:25)
    at insertDocuments (C:\Users\raymo\Documents\Ticket\node_modules\mongodb\lib\operations\common_functions.js:259:19)
    at InsertOneOperation.execute (C:\Users\raymo\Documents\Ticket\node_modules\mongodb\lib\operations\insert_one.js:26:5)
    at C:\Users\raymo\Documents\Ticket\node_modules\mongodb\lib\operations\execute_operation.js:98:26
    at new Promise (<anonymous>)
    at executeOperation (C:\Users\raymo\Documents\Ticket\node_modules\mongodb\lib\operations\execute_operation.js:91:10)
    at Collection.insertOne (C:\Users\raymo\Documents\Ticket\node_modules\mongodb\lib\collection.js:516:10)
    at Object.insert (C:\Users\raymo\Documents\Ticket\routes\Handlers\DatabaseHandler.js:68:63)
```

as well I tried downgrading to mongo v. 3.4.0

I tried normal Callback functions and it works. but i need to upgrade and work with promises and await/async
Please suggest edits if my question is not clear.

答:
client.close() closes the current db connection, including all the child db instances as stated in the documentation. This means that once you've called it, the current mongo client can no longer be used. You'd need to create an entirely new MongoClient and call connect() on it.

But - you should not do this, there's no need to manually create/close the connection for every database operation.

Just keep your connection instance after doing const connection = await client.connect(); and reuse/share it for your other operations. MongoClient already handles connection pooling for you.

Body:
I am using latest Mongodb 3.5.7 with Node.js and Express,

What I do is I call an async function when an API is being called and the code is as following  :

async function insert(data) {

        try {
             const connection = await client.connect();
             db =client.db(dbName);
             const insertion  = await db.collection('inserts').insertOne(data);
             //console.log(await client.close());
             await console.log('finished waiting promises');
             await client.close();
        } catch (err) {
            console.log(err.stack);
            return Promise.reject('false');
        }
        return new Promise(resolve =>{

            resolve();
        })
}

`
In fact the first API Call works so well and successfully inserts the data into db , the issue starts with the second try which brings this error

I also tried promises in separated functions with every command ( connect - insert -close ) with call back promise and await for each one to be done.

As well tried calling connecting function which i created.then(setdbname).then(insert).then(closedb) ...

the options [servers] is not supported
the options [caseTranslate] is not supported
the options [dbName] is not supported
the options [credentials] is not supported

MongoError: topology was destroyed
    at executeWriteOperation (C:\Users\raymo\Documents\Ticket\node_modules\mongodb\lib\core\topologies\replset.js:1188:21)
    at ReplSet.insert (C:\Users\raymo\Documents\Ticket\node_modules\mongodb\lib\core\topologies\replset.js:1257:3)
    at ReplSet.insert (C:\Users\raymo\Documents\Ticket\node_modules\mongodb\lib\topologies\topology_base.js:322:25)
    at insertDocuments (C:\Users\raymo\Documents\Ticket\node_modules\mongodb\lib\operations\common_functions.js:259:19)
    at InsertOneOperation.execute (C:\Users\raymo\Documents\Ticket\node_modules\mongodb\lib\operations\insert_one.js:26:5)
    at C:\Users\raymo\Documents\Ticket\node_modules\mongodb\lib\operations\execute_operation.js:98:26
    at new Promise (<anonymous>)
    at executeOperation (C:\Users\raymo\Documents\Ticket\node_modules\mongodb\lib\operations\execute_operation.js:91:10)
    at Collection.insertOne (C:\Users\raymo\Documents\Ticket\node_modules\mongodb\lib\collection.js:516:10)
    at Object.insert (C:\Users\raymo\Documents\Ticket\routes\Handlers\DatabaseHandler.js:68:63)

as well I tried downgrading to mongo v. 3.4.0

I tried normal Callback functions and it works. but i need to upgrade and work with promises and await/async
Please suggest edits if my question is not clear.


问:
Complex action on Django menu
I have a small app for a local hockey league, I wanted to know if it was possible to write an action on the admin of the games, so that when I check 2 games, it exchanges the teams that are about to play.

Example team A vs team B -- team C vs team D, if I swap this with the action menu it should be team C vs team B -- team A vs Team D

Thats the general idea... anyone has any suggestion? or ideas on how to achieve this!

Thank you all!

答:
You have to define a method like this:

```<code>def exchange_team(modeladmin, request, queryset):
    if queryset.count() == 2:
        #your interchange code...
</code>```

And reference it in your admin class:

```<code>class TeamAdmin(admin.ModelAdmin):
    ...
    actions = ['exchange_team']

admin.register(Team, TeamAdmin)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Complex action on Django menu

Body:
You have to define a method like this:

def exchange_team(modeladmin, request, queryset):
    if queryset.count() == 2:
        #your interchange code...

And reference it in your admin class:

class TeamAdmin(admin.ModelAdmin):
    ...
    actions = ['exchange_team']

admin.register(Team, TeamAdmin)


问:
Need only parent domain from a URL in dnsmasq.log file
I want to fetch website names visited by connected LAN clients from dnsmasq.log file. So far i have been able to get this done.

```<code>cat /tmp/dnsmasq.log | grep query | egrep -v 'AAA|SRV|PTR' |  awk '{print $1" "$2" "$3","$8","$6}'
</code>```

May 29 12:00:17,127.0.0.1,ftp.box.com

May 29 12:00:33,10.0.0.41,2.android.pool.ntp.org

I need output as

May 29 12:00:17,127.0.0.1,box.com

May 29 12:00:33,10.0.0.41,ntp.org

I need just the parent domain name in the output. Please help.

Thanks

答:
Could you please try following, written and tested with shown samples.Considering that you need last 2 elements of your url.

```<code>awk 'BEGIN{FS=OFS=","} {num=split($NF,array,".");$NF=array[num-1]"."array[num]} 1' Input_file
</code>```

Explanation: Adding detailed explanation.

```<code>awk '                                ##Starting awk program from here.
BEGIN{                               ##Starting BEGIN section of this awk program from here.
  FS=OFS=","                         ##Setting field separator and output field separator as comma here.
}
{
  num=split($NF,array,".")           ##Splitting last field and metioning . as separator.
  $NF=array[num-1]"."array[num]      ##Setting last column value as 2nd last element DOT and last element of array here.
}
1                                    ##1 will print lines here.
'  Input_file                        ##Mentioning Input_file name here.
</code>```

Body:
I want to fetch website names visited by connected LAN clients from dnsmasq.log file. So far i have been able to get this done.

cat /tmp/dnsmasq.log | grep query | egrep -v 'AAA|SRV|PTR' |  awk '{print $1" "$2" "$3","$8","$6}'

May 29 12:00:17,127.0.0.1,ftp.box.com

May 29 12:00:33,10.0.0.41,2.android.pool.ntp.org

I need output as

May 29 12:00:17,127.0.0.1,box.com

May 29 12:00:33,10.0.0.41,ntp.org

I need just the parent domain name in the output. Please help.

Thanks

Body:
Could you please try following, written and tested with shown samples.Considering that you need last 2 elements of your url.

awk 'BEGIN{FS=OFS=","} {num=split($NF,array,".");$NF=array[num-1]"."array[num]} 1' Input_file

Explanation: Adding detailed explanation.

awk '                                ##Starting awk program from here.
BEGIN{                               ##Starting BEGIN section of this awk program from here.
  FS=OFS=","                         ##Setting field separator and output field separator as comma here.
}
{
  num=split($NF,array,".")           ##Splitting last field and metioning . as separator.
  $NF=array[num-1]"."array[num]      ##Setting last column value as 2nd last element DOT and last element of array here.
}
1                                    ##1 will print lines here.
'  Input_file                        ##Mentioning Input_file name here.


问:
Swift default AlertViewController breaking constraints
I am trying to use a default AlertViewController with style .actionSheet. For some reason, the alert causes a constraint error. As long as the alertController is not triggered (displayed) through a button, there are no constraint errors on the whole view. Could it be that this is a bug of Xcode?

The exact error I get looks like this:

```<code>2019-04-12 15:33:29.584076+0200 Appname[4688:39368] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x6000025a1e50 UIView:0x7f88fcf6ce60.width == - 16   (active)>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x6000025a1e50 UIView:0x7f88fcf6ce60.width == - 16   (active)>

</code>```

This is the code I use:

```<code>@objc func changeProfileImageTapped(){
        print("ChangeProfileImageButton tapped!")
        let alert = UIAlertController(title: "Change your profile image", message: nil, preferredStyle: .actionSheet)

        alert.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: nil))
        alert.addAction(UIAlertAction(title: "Online Stock Library", style: .default, handler: nil))
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        alert.view.tintColor = ColorCodes.logoPrimaryColor

        self.present(alert, animated: true)
    }
</code>```

As you can see, it is very basic. That's why I am very confused about the strange behavior I get as this default implementation should not cause any errors, right?

Although, through breaking the constraints, the alert displays properly on all screen sizes I would be really thankful for any help I get.

答:
Safe Solution

You should not remove the constraint because it is used in the future with a correct value.

As an alternative, you can change its constant to a positive value:

```<code>class PXAlertController: UIAlertController {
    override func viewDidLoad() {
        super.viewDidLoad()

        for subview in self.view.subviews {
            for constraint in subview.constraints {
                if constraint.firstAttribute == .width && constraint.constant == -16 {
                    constraint.constant = 10 // Any positive value
                }
            }
        }
    }
}
</code>```

And then to initialize your controller use:

```<code>let controller = PXAlertController(title: "Title", message: "Message", preferredStyle: .actionSheet)
</code>```

Body:
I am trying to use a default AlertViewController with style .actionSheet. For some reason, the alert causes a constraint error. As long as the alertController is not triggered (displayed) through a button, there are no constraint errors on the whole view. Could it be that this is a bug of Xcode?

The exact error I get looks like this:

2019-04-12 15:33:29.584076+0200 Appname[4688:39368] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x6000025a1e50 UIView:0x7f88fcf6ce60.width == - 16   (active)>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x6000025a1e50 UIView:0x7f88fcf6ce60.width == - 16   (active)>

This is the code I use:

@objc func changeProfileImageTapped(){
        print("ChangeProfileImageButton tapped!")
        let alert = UIAlertController(title: "Change your profile image", message: nil, preferredStyle: .actionSheet)

        alert.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: nil))
        alert.addAction(UIAlertAction(title: "Online Stock Library", style: .default, handler: nil))
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        alert.view.tintColor = ColorCodes.logoPrimaryColor

        self.present(alert, animated: true)
    }

As you can see, it is very basic. That's why I am very confused about the strange behavior I get as this default implementation should not cause any errors, right?

Although, through breaking the constraints, the alert displays properly on all screen sizes I would be really thankful for any help I get.

Body:
Safe Solution

You should not remove the constraint because it is used in the future with a correct value.

As an alternative, you can change its constant to a positive value:

class PXAlertController: UIAlertController {
    override func viewDidLoad() {
        super.viewDidLoad()

        for subview in self.view.subviews {
            for constraint in subview.constraints {
                if constraint.firstAttribute == .width && constraint.constant == -16 {
                    constraint.constant = 10 // Any positive value
                }
            }
        }
    }
}

And then to initialize your controller use:

let controller = PXAlertController(title: "Title", message: "Message", preferredStyle: .actionSheet)


问:
CodingBat : LoneSum optimization
I have completed this exercise on codingbat successfully, but I want to know is there a better/faster or more elegant solution?

Given 3 int values, a b c, returns their sum. However, if one of the values is the same as another of the values, it does not count towards the sum.

loneSum(1, 2, 3) → 6
loneSum(3, 2, 3) → 2
loneSum(3, 3, 3) → 0

```<code>public int loneSum(int a, int b, int c)
{
    int sum = a + b + c;
    if ( a == b) { sum = sum - a - b; }
    if ( a == c) { sum = sum - a - c; }
    if( b == c) { sum = sum - b - c; }
    if (( a == b ) && (b==c)) { sum = 0; }
    return sum;
}
</code>```

答:
Please see the below function :

```<code>def su(a,b,c):
    total=0
    for x in (a,b,c):
        if x==(x+1):
            y=0
        else:
            y=1
            total+=x*y
    return total
print(su(3,2,3))
</code>```

Title: CodingBat : LoneSum optimization

Body:
I have completed this exercise on codingbat successfully, but I want to know is there a better/faster or more elegant solution?

Given 3 int values, a b c, returns their sum. However, if one of the values is the same as another of the values, it does not count towards the sum.

loneSum(1, 2, 3) → 6
loneSum(3, 2, 3) → 2
loneSum(3, 3, 3) → 0

public int loneSum(int a, int b, int c)
{
    int sum = a + b + c;
    if ( a == b) { sum = sum - a - b; }
    if ( a == c) { sum = sum - a - c; }
    if( b == c) { sum = sum - b - c; }
    if (( a == b ) && (b==c)) { sum = 0; }
    return sum;
}

Body:
Please see the below function :

def su(a,b,c):
    total=0
    for x in (a,b,c):
        if x==(x+1):
            y=0
        else:
            y=1
            total+=x*y
    return total
print(su(3,2,3))


问:
Redirect for default case in React using Switch and BrowserRouter
This is my current App.js file in react. What I am trying to achieve is everytime a link of the first switch is accessed, i do not want the navbar to be shown, but otherwise, the navbar has to be visible. I do not have a default case, so I am stuck. If this may help anyone, if the user is already logged in, accessing login/logout directly redirects you to home and if he is not logged in, accessing any other page redirects you to the login page. It would be very helpful if you have a workaround.

```<code><BrowserRouter>
  <Switch>
    <Route path='/user/register' component={Register} />
    <Route path='/user/login' component={Login} />
    <Route path='/user/logout' component={Logout} />
    <Navbar />
  </Switch>
  <Switch>
    <Route path='/note/new' component={NewNote} />
    <Route path='/list/new' component={NewList} />
    <Route path='/note/:noteid' component={NoteDetail} />
    <Route path='/list/:listid' component={ListDetail} />
    <Route path='/home' component={Home} />
    <Route path='/archive' component={Archive} />
    <Route path='/note' component={Note} />
    <Route path='/list' component={List} />
    <Route path='/trash' component={Trash} />
  </Switch>
</BrowserRouter>
</code>```

Thanks

答:
Switch isn't a conventional programming "switch" statement, there isn't a "default" case. It simply returns the first matching Route or Redirect child component. As written though, if none of the /user/XXX paths match it will (should) render the Navbar (maybe depends on react-router-dom version).

In your case it may be better to render the Navbar on a Route, outside the Switch, and specify what paths it can match, i.e. exclude the /user path.

```<code><BrowserRouter>
  <Route
    path={['/home', '/archive', '/note', '/list', '/trash']}
    component={Navbar}
  />
  <Switch>
    <Route path='/user/register' component={Register} />
    <Route path='/user/login' component={Login} />
    <Route path='/user/logout' component={Logout} />
    <Route path='/note/new' component={NewNote} />
    <Route path='/list/new' component={NewList} />
    <Route path='/note/:noteid' component={NoteDetail} />
    <Route path='/list/:listid' component={ListDetail} />
    <Route path='/home' component={Home} />
    <Route path='/archive' component={Archive} />
    <Route path='/note' component={Note} />
    <Route path='/list' component={List} />
    <Route path='/trash' component={Trash} />
  </Switch>
</BrowserRouter>
</code>```

Body:
This is my current App.js file in react. What I am trying to achieve is everytime a link of the first switch is accessed, i do not want the navbar to be shown, but otherwise, the navbar has to be visible. I do not have a default case, so I am stuck. If this may help anyone, if the user is already logged in, accessing login/logout directly redirects you to home and if he is not logged in, accessing any other page redirects you to the login page. It would be very helpful if you have a workaround.

<BrowserRouter>
  <Switch>
    <Route path='/user/register' component={Register} />
    <Route path='/user/login' component={Login} />
    <Route path='/user/logout' component={Logout} />
    <Navbar />
  </Switch>
  <Switch>
    <Route path='/note/new' component={NewNote} />
    <Route path='/list/new' component={NewList} />
    <Route path='/note/:noteid' component={NoteDetail} />
    <Route path='/list/:listid' component={ListDetail} />
    <Route path='/home' component={Home} />
    <Route path='/archive' component={Archive} />
    <Route path='/note' component={Note} />
    <Route path='/list' component={List} />
    <Route path='/trash' component={Trash} />
  </Switch>
</BrowserRouter>

Thanks

Body:
Switch isn't a conventional programming "switch" statement, there isn't a "default" case. It simply returns the first matching Route or Redirect child component. As written though, if none of the /user/XXX paths match it will (should) render the Navbar (maybe depends on react-router-dom version).

In your case it may be better to render the Navbar on a Route, outside the Switch, and specify what paths it can match, i.e. exclude the /user path.

<BrowserRouter>
  <Route
    path={['/home', '/archive', '/note', '/list', '/trash']}
    component={Navbar}
  />
  <Switch>
    <Route path='/user/register' component={Register} />
    <Route path='/user/login' component={Login} />
    <Route path='/user/logout' component={Logout} />
    <Route path='/note/new' component={NewNote} />
    <Route path='/list/new' component={NewList} />
    <Route path='/note/:noteid' component={NoteDetail} />
    <Route path='/list/:listid' component={ListDetail} />
    <Route path='/home' component={Home} />
    <Route path='/archive' component={Archive} />
    <Route path='/note' component={Note} />
    <Route path='/list' component={List} />
    <Route path='/trash' component={Trash} />
  </Switch>
</BrowserRouter>


答:
You need to look in to JavaScript closures and how they work to solve this.
When you add event listeners inside a for loop you need to be careful in JS. When you click the button, for loop is already executed and you will have only the last i value on every button press. You can use IIFE pattern, let keyword to solve this.

One simple way to resolve this issue is listed below.

```<code><div id="records"></div>

<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>

<script type="text/javascript">
  $(document).ready(function(){
    var anchors = document.getElementsByClassName('editButton');
    for(var i = 0; i < anchors.length; i++) {

            //Wrap the function with an IIFE and send i value to the event listener

            (function(anchor){

             anchor.onclick = function() {
               $.ajax({
                  method: "GET",
                  url: "/testedit.php",
               }).done(function( data ) {
                  var id = anchor.value;

                  /* from result create a string of data and append to the div */

                  var result= data;
                  var string='<p>ID is '+id+'</p><br>';

                  $("#records").html(string);
              });
            }

           })(anchors[i]);

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

You can read more about this in JavaScript closure inside loops – simple practical example

Title: How do I get an element with a specific ID from getElementsByClassName?

Body:
EDIT: SOLVED. Thanks everyone!

I'm new to programming :D My code is below. Here is the deal: I have multiple buttons, but I want to make it so that the same thing would happen anytime any one of these buttons is clicked, but each button also has a specific value, and I also want that specific value to be printed out. My code goes through the document and looks at all the elements with "editButton" class, and correctly identifies all the buttons, but the problem is that no matter which button I press, I always get the value of the last button, because var id only gets assigned after the for loop finishes and is on the last element. I tried creating a global variable and assigning the value to it, but the result is the same. I tried ending the for loop before moving on to .done (function (data), but I got an error. Can someone help me out? Thanks!

$(document).ready(function() {
  var anchors = document.getElementsByClassName('editButton');
  for (var i = 0; i < anchors.length; i++) {
    var anchor = anchors[i];
    anchor.onclick = function() {
      $.ajax({
        method: "GET",
        url: "/testedit.php",
      }).done(function(data) {
        var id = anchor.value;

        /* from result create a string of data and append to the div */

        var result = data;
        var string = '
ID is ' + id + '

';

        $("#records").html(string);
      });
    }
  }
});

Body:
You need to look in to JavaScript closures and how they work to solve this.
When you add event listeners inside a for loop you need to be careful in JS. When you click the button, for loop is already executed and you will have only the last i value on every button press. You can use IIFE pattern, let keyword to solve this.

One simple way to resolve this issue is listed below.

<div id="records"></div>

<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>

<script type="text/javascript">
  $(document).ready(function(){
    var anchors = document.getElementsByClassName('editButton');
    for(var i = 0; i < anchors.length; i++) {

            //Wrap the function with an IIFE and send i value to the event listener

            (function(anchor){

             anchor.onclick = function() {
               $.ajax({
                  method: "GET",
                  url: "/testedit.php",
               }).done(function( data ) {
                  var id = anchor.value;

                  /* from result create a string of data and append to the div */

                  var result= data;
                  var string='<p>ID is '+id+'</p><br>';

                  $("#records").html(string);
              });
            }

           })(anchors[i]);

        }
    }
});

You can read more about this in JavaScript closure inside loops – simple practical example


问:
Multiple text formats in unordered list
I'm trying to bold a single word within a sentence in an unordered list bullet (in PPT). Is this possible? Putting a combination of fpar/ftext objects into the str_list within unordered_list throws an error. Thanks in advance.

EDIT, adding example of what I mean:

example

答:
You may try the following, which works for me:</p>

```<code>library(officer)
doc <- read_pptx()

ul <- unordered_list(
  level_list = c(1, 2, 2, 3, 3, 1),
  str_list = c("Level1", "Level2", "Level2", "Level3", "Level3", "Level1"),
  style = list(fp_text(color = "red", bold = TRUE, font.size = 25),
               fp_text(color = "blue", bold = TRUE, font.size = 25)
               fp_text(color = "yellow", bold = TRUE, font.size = 25)
               fp_text(color = "red", bold = TRUE, font.size = 25)
               fp_text(color = "blue", bold = TRUE, font.size = 25)
               fp_text(color = "yellow", bold = TRUE, font.size = 25)))

doc <- add_slide(doc)
doc <- ph_with(x = doc, value = ul, location = ph_location_type(type = "body") )

print(doc, target = "ph_with_ul.pptx")
</code>```

Title: Multiple text formats in unordered list

Body:
You may try the following, which works for me:

library(officer)
doc <- read_pptx()

ul <- unordered_list(
  level_list = c(1, 2, 2, 3, 3, 1),
  str_list = c("Level1", "Level2", "Level2", "Level3", "Level3", "Level1"),
  style = list(fp_text(color = "red", bold = TRUE, font.size = 25),
               fp_text(color = "blue", bold = TRUE, font.size = 25)
               fp_text(color = "yellow", bold = TRUE, font.size = 25)
               fp_text(color = "red", bold = TRUE, font.size = 25)
               fp_text(color = "blue", bold = TRUE, font.size = 25)
               fp_text(color = "yellow", bold = TRUE, font.size = 25)))

doc <- add_slide(doc)
doc <- ph_with(x = doc, value = ul, location = ph_location_type(type = "body") )

print(doc, target = "ph_with_ul.pptx")


答:
save the button with button = this when run the onclick function and use it

```<code> $(document).ready(function(){
 var anchors = document.getElementsByClassName('editButton');
   for(var i = 0; i < anchors.length; i++) {
     var button;
     var anchor = anchors[i];
     anchor.onclick = function() {
       button = this;
       $.ajax({
         method: "GET",
         url: "/testedit.php",
       }).done(function( data ) {

         /* from result create a string of data and append to the div */

         var result= data;
         var string='<p>ID is '+ button.value +'</p><br>';

         $("#records").html(string);
       });
     }
   }
});
</code>```

https://jsfiddle.net/x02srmg6/

Body:
save the button with button = this when run the onclick function and use it

 $(document).ready(function(){
 var anchors = document.getElementsByClassName('editButton');
   for(var i = 0; i < anchors.length; i++) {
     var button;
     var anchor = anchors[i];
     anchor.onclick = function() {
       button = this;
       $.ajax({
         method: "GET",
         url: "/testedit.php",
       }).done(function( data ) {

         /* from result create a string of data and append to the div */

         var result= data;
         var string='<p>ID is '+ button.value +'</p><br>';

         $("#records").html(string);
       });
     }
   }
});

https://jsfiddle.net/x02srmg6/


问:
PowerApps Tool Installer fails for self-hosted agents
I configured a self-hosted agent from which to do my Dynamics 365 app builds/deployments.

However, I seem to be missing something, as the PowerApps Tool installer fails:

```<code>Starting: PowerApps Tool Installer
==============================================================================
Task         : PowerApps Tool Installer
Description  : PowerApps Tool Installer
Version      : 0.3.4
Author       : Microsoft
Help         : [More Info](https://aka.ms/buildtoolsdoc)
==============================================================================
Installing PS module Microsoft.Xrm.OnlineManagementAPI - 1.2.0.1 ...
Installing PS module Microsoft.PowerApps.Administration.PowerShell - 2.0.61 ...
Installing PS module Microsoft.Xrm.Tooling.PackageDeployment.Powershell - 3.3.0.882 ...
Installing PS module Microsoft.PowerApps.Checker.PowerShell - 1.0.12 ...

Name                           Version          Source           Summary
----                           -------          ------           -------
nuget                          2.8.5.208        https://onege... NuGet provider for the OneGet meta-package manager
##[error]The package source "nuget.org" is available.
Installing nuget pkg Microsoft.CrmSdk.CoreTools - 9.1.0.39 ...
##[error]For the search term and package name "Microsoft.CrmSdk.CoreTools" no corresponding package was found. Use Get-PackageSource to display all available registered package sources.
Finishing: PowerApps Tool Installer
</code>```

(had to translate the error message from German, so they might differ a bit)

Using Microsoft-hosted agents, the task succeeds.
I'm a beginner when it comes to this stuff, so can someone ELI5 what I'm missing?

Regards,
Tom

答:
PowerApps Tool Installer fails for self-hosted agents

According to the error message, it seem the nuget.exe could not find the package Microsoft.CrmSdk.CoreTools from the nuget.org.  And it is still the old version 2.8.5.208.

To resolve this issue, please try to download a new version of nuget.exe, save it in your local machine where your self-hosted agents installed.

Then set the local path of NuGet.exe into your path environment variable, check this document for some more details.

Besides, open the nuget.config in the path:

```<code>C:\Users\<UserName>\AppData\Roaming\NuGet\NuGet.Config
</code>```

Update the package scource:

```<code> <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </packageSources>
</code>```

Hope this helps.

Body:
I configured a self-hosted agent from which to do my Dynamics 365 app builds/deployments.

However, I seem to be missing something, as the PowerApps Tool installer fails:

Starting: PowerApps Tool Installer
==============================================================================
Task         : PowerApps Tool Installer
Description  : PowerApps Tool Installer
Version      : 0.3.4
Author       : Microsoft
Help         : [More Info](https://aka.ms/buildtoolsdoc)
==============================================================================
Installing PS module Microsoft.Xrm.OnlineManagementAPI - 1.2.0.1 ...
Installing PS module Microsoft.PowerApps.Administration.PowerShell - 2.0.61 ...
Installing PS module Microsoft.Xrm.Tooling.PackageDeployment.Powershell - 3.3.0.882 ...
Installing PS module Microsoft.PowerApps.Checker.PowerShell - 1.0.12 ...

Name                           Version          Source           Summary
----                           -------          ------           -------
nuget                          2.8.5.208        https://onege... NuGet provider for the OneGet meta-package manager
##[error]The package source "nuget.org" is available.
Installing nuget pkg Microsoft.CrmSdk.CoreTools - 9.1.0.39 ...
##[error]For the search term and package name "Microsoft.CrmSdk.CoreTools" no corresponding package was found. Use Get-PackageSource to display all available registered package sources.
Finishing: PowerApps Tool Installer

(had to translate the error message from German, so they might differ a bit)

Using Microsoft-hosted agents, the task succeeds.
I'm a beginner when it comes to this stuff, so can someone ELI5 what I'm missing?

Regards,
Tom

Body:
PowerApps Tool Installer fails for self-hosted agents

According to the error message, it seem the nuget.exe could not find the package Microsoft.CrmSdk.CoreTools from the nuget.org.  And it is still the old version 2.8.5.208.

To resolve this issue, please try to download a new version of nuget.exe, save it in your local machine where your self-hosted agents installed.

Then set the local path of NuGet.exe into your path environment variable, check this document for some more details.

Besides, open the nuget.config in the path:

C:\Users\<UserName>\AppData\Roaming\NuGet\NuGet.Config

Update the package scource:

 <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </packageSources>

Hope this helps.


问:
Is there a simple way to map a texture to a different "UV" system in python?
I really don't know if "UV's" is the right word as i'm from the world of Unity and am trying to write some stuff in python. What i'm trying to do is to take a picture of a human (from webcam) take the placement of their landmarks/key features and alter a second image (of a different person) to make their key features in the same place whilst morphing / warping the parts of their skin that are within the face to fit the position of the first input image (webcam)'s landmarks. After i do that I need to put the face back on the non-webcam input. (i'm sorry for how much that made me sound like a serial killer, stretching and cutting faces) I know that probably didn't make any sense but I want it to look like this.

I have the face landmark and cutting done with DLIB and OpenCV but i need a way to find a way to take these "cut" face chunks and stretch them "dynamically". What I mean by dynamically is that you don't just put a mask on by linearly re-sizing it on 1 or 2 axises. You can select a point of the mask and change that, I wanna do that but my mask is my cut chunk and the point is a section of that chunk that needs to change for the chunk to comply with the position of the generated landmarks. I know this is a very hard topic to think about and if you guys need any clarification just ask. My code:

```<code>import cv2
import numpy as np
import dlib

cap = cv2.VideoCapture(0)

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

while True:
    _, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = detector(gray)
    for face in faces:
        x1 = face.left()
        y1 = face.top()
        x2 = face.right()
        y2 = face.bottom()
        cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 3)

        landmarks = predictor(gray, face)

        for n in range(0, 68):
            x = landmarks.part(n).x
            y = landmarks.part(n).y
            cv2.circle(frame, (x, y), 4, (255, 0, 0), -1)

    cv2.imshow("Frame", frame)

    key = cv2.waitKey(1)
    if key == 27:
        break

</code>```

EDIT: No i'm not a serial killer

答: If you need to deform source image like a rubber sheet using 2 sets of keypoints, you need to use thin plate spline (TPS), or, better, piecewice affine transformation like here. The last one is more similar to texture rasterization methods (triangle to triangle texture transform). </p>

Body:
I really don't know if "UV's" is the right word as i'm from the world of Unity and am trying to write some stuff in python. What i'm trying to do is to take a picture of a human (from webcam) take the placement of their landmarks/key features and alter a second image (of a different person) to make their key features in the same place whilst morphing / warping the parts of their skin that are within the face to fit the position of the first input image (webcam)'s landmarks. After i do that I need to put the face back on the non-webcam input. (i'm sorry for how much that made me sound like a serial killer, stretching and cutting faces) I know that probably didn't make any sense but I want it to look like this.

I have the face landmark and cutting done with DLIB and OpenCV but i need a way to find a way to take these "cut" face chunks and stretch them "dynamically". What I mean by dynamically is that you don't just put a mask on by linearly re-sizing it on 1 or 2 axises. You can select a point of the mask and change that, I wanna do that but my mask is my cut chunk and the point is a section of that chunk that needs to change for the chunk to comply with the position of the generated landmarks. I know this is a very hard topic to think about and if you guys need any clarification just ask. My code:

import cv2
import numpy as np
import dlib

cap = cv2.VideoCapture(0)

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

while True:
    _, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = detector(gray)
    for face in faces:
        x1 = face.left()
        y1 = face.top()
        x2 = face.right()
        y2 = face.bottom()
        cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 3)

        landmarks = predictor(gray, face)

        for n in range(0, 68):
            x = landmarks.part(n).x
            y = landmarks.part(n).y
            cv2.circle(frame, (x, y), 4, (255, 0, 0), -1)

    cv2.imshow("Frame", frame)

    key = cv2.waitKey(1)
    if key == 27:
        break

EDIT: No i'm not a serial killer


问:
Restrict Range in Android DatePicker Custom Dialog
I have a custom linear layout which has DatePicker and TimePicker widgets in it. This is used as DateTime picker. I want to restrict the DatePicker by way of setMaxDate() and setMinDate(). I have done:

```<code>dp.setMaxDate(new DateTime().minusDays(1).getMillis());
dp.setMinDate(new DateTime().minusDays(30).getMillis());
</code>```

The dates beyond this range are actually grayed out when the dialog appears. But I can still select a grayed date. I have stumbled upon this. But, what is the work around for a custom layout with datepicker in it?

答:
The Material Components Library provides the MaterialDatePicker.

You can use a DateValidator to restrict the selections.

In particular you can use the built-in validators:

DateValidatorPointForward  that enables dates from a given point forward

DateValidatorPointBackward that enables only dates before a given point.

Something like:

```<code>MaterialDatePicker.Builder<Pair<Long, Long>> builderRange = MaterialDatePicker.Builder.dateRangePicker();
CalendarConstraints.Builder constraintsBuilderRange = new CalendarConstraints.Builder();

//....define min and max for example with LocalDateTime and ZonedDateTime or Calendar

CalendarConstraints.DateValidator dateValidatorMin = DateValidatorPointForward.from(min.getTimeInMillis());
CalendarConstraints.DateValidator dateValidatorMax = DateValidatorPointBackward.before(max.getTimeInMillis());

ArrayList<CalendarConstraints.DateValidator> listValidators =
            new ArrayList<CalendarConstraints.DateValidator>();
listValidators.add(dateValidatorMin);
listValidators.add(dateValidatorMax);
CalendarConstraints.DateValidator validators = CompositeDateValidator.allOf(listValidators);
constraintsBuilderRange.setValidator(validators);

builderRange.setCalendarConstraints(constraintsBuilderRange.build());
MaterialDatePicker<Pair<Long, Long>> pickerRange = builderRange.build();
pickerRange.show(getSupportFragmentManager(), pickerRange.toString());
</code>```

Body:
I have a custom linear layout which has DatePicker and TimePicker widgets in it. This is used as DateTime picker. I want to restrict the DatePicker by way of setMaxDate() and setMinDate(). I have done:

dp.setMaxDate(new DateTime().minusDays(1).getMillis());
dp.setMinDate(new DateTime().minusDays(30).getMillis());

The dates beyond this range are actually grayed out when the dialog appears. But I can still select a grayed date. I have stumbled upon this. But, what is the work around for a custom layout with datepicker in it?

Body:
The Material Components Library provides the MaterialDatePicker.

You can use a DateValidator to restrict the selections.

In particular you can use the built-in validators:

DateValidatorPointForward  that enables dates from a given point forward

DateValidatorPointBackward that enables only dates before a given point.

Something like:

MaterialDatePicker.Builder<Pair<Long, Long>> builderRange = MaterialDatePicker.Builder.dateRangePicker();
CalendarConstraints.Builder constraintsBuilderRange = new CalendarConstraints.Builder();

//....define min and max for example with LocalDateTime and ZonedDateTime or Calendar

CalendarConstraints.DateValidator dateValidatorMin = DateValidatorPointForward.from(min.getTimeInMillis());
CalendarConstraints.DateValidator dateValidatorMax = DateValidatorPointBackward.before(max.getTimeInMillis());

ArrayList<CalendarConstraints.DateValidator> listValidators =
            new ArrayList<CalendarConstraints.DateValidator>();
listValidators.add(dateValidatorMin);
listValidators.add(dateValidatorMax);
CalendarConstraints.DateValidator validators = CompositeDateValidator.allOf(listValidators);
constraintsBuilderRange.setValidator(validators);

builderRange.setCalendarConstraints(constraintsBuilderRange.build());
MaterialDatePicker<Pair<Long, Long>> pickerRange = builderRange.build();
pickerRange.show(getSupportFragmentManager(), pickerRange.toString());


问:
Read only replica on a different server using SQL Server 2019
What options exist through SQL Server or vendor tools including AWS that would allow me to take an existing SQL Server with multiple databases and create a read only replica of a different very large (multiple terabyte) database on that same server?

Our requirement is the databases need to live on the same server and we want to stay on SQL Server.

Linked Servers cause performance concerns when executing complex joins and distributed always on appears to require all databases on source database to be replicated.

Example:

```<code>**Server A**
DB1
DB2
DB3
DB4
DB5 *(replicated read only version)*

**Server B**
DB5 *(source, 1tb+)*
</code>```

What option am I missing?

答:
We have had a scenario similar to this at my company.

Transactional Replication can solve this, but getting it up and running is the hard part.  Taking the snapshot needed to start the replication locks up the source database fairly hard.

The solution we found was to take a backup of the source database (DB5 on Server B), and restore it on the target server (DB5 on Server A).  Then (via some public, but less well known commands), you attach the replication to that newly restored copy of DB5.  This way all changes since the backup was made, and all ongoing changes are replicated to the read only copy.

That way you can keep DB5 running fine on Server B, and have a read only replication copy on Server A.

If you need the actual commands I may be able to go dig them up.

Body:
What options exist through SQL Server or vendor tools including AWS that would allow me to take an existing SQL Server with multiple databases and create a read only replica of a different very large (multiple terabyte) database on that same server?

Our requirement is the databases need to live on the same server and we want to stay on SQL Server.

Linked Servers cause performance concerns when executing complex joins and distributed always on appears to require all databases on source database to be replicated.

Example:

**Server A**
DB1
DB2
DB3
DB4
DB5 *(replicated read only version)*

**Server B**
DB5 *(source, 1tb+)*

What option am I missing?


问:
Adding Outlook appointment using ASP.Net
I am creating an ASP.Net MVC project where users will add Outlook appointments to other users calendars. I other words; I wish for a user of my web app to be able to add an appointment directly in another persons calendar. This means sending it via email with no need for the receiver to accept it. It should be as if the receiver actually created it himself in Outlook.

Is this even possible to do?

The web app is hosted outside the customers network.

Best regards
Pål Eilertsen

答:
You can create an ICS file that the user can double click and store the appointment. If multiple users, it can be sent to others. If you can get access to their exchange server (sounds like you can't), as SLaks asked, you can use something like this (http://goo.gl/G2nrd). If you have no access to Exchange directly, the ICS file format will allow the user to add the appointment.

If you want an example of an ics file (other than a Google search), sign up for a Microsoft event and click the "add to outlook" button. The fortunate thing about this methodology is it can also work with other mail/calendar applications that use the format.


问:
How to get branch specific build status with embeddable build status plugin in Jenkins
I am using the "Embeddable build status" plugin for Jenkins.

I cannot get the build status of a specific branch working, it always shows "not run" status.

I am using the unprotected link:

[![Build Status](http://ec2-34-251-244-92.eu-west-1.compute.amazonaws.com/jenkins/buildStatus/icon?job=vuffeli_api)](http://ec2-34-251-244-92.eu-west-1.compute.amazonaws.com/jenkins/job/vuffeli_api/)

I have given Anonymous viewstatus permissions on jobs globally.
This works fine but as soon as I add the branch information it stops working.
I have tried the following combinations and am at a loss.

http://ec2-34-251-244-92.eu-west-1.compute.amazonaws.com/jenkins/buildStatus/icon?job=vuffeli_api%2Fmaster)

http://ec2-34-251-244-92.eu-west-1.compute.amazonaws.com/jenkins/buildStatus/icon?job=vuffeli_api%252Fmaster

http://ec2-34-251-244-92.eu-west-1.compute.amazonaws.com/jenkins/buildStatus/icon?job=vuffeli_api%2Forigin%252Fmaster

http://ec2-34-251-244-92.eu-west-1.compute.amazonaws.com/jenkins/buildStatus/icon?job=vuffeli_api%2Fvuffeli_api%252Fmaster

I was expecting the badge to show the status of the master branch but it is grey and displays "not run"

EDIT 27-05-2019

A temporary solution has been to have multiple projects in jenkins that filter what branches trigger builds and then show a status for projects that only build and test specific branches.

答:
I have not found a better solution than to have statuses displayed for all relevant branches and I have since stopped using jenkins and started using Azure pipelines instead.
If any of you find a solution please submit the answer but for now I will consider this closed.</p>


问:
NuGet Package Manager Console Default Project dropdown is empty
I recently upgraded to Visual Studio 2012 RTM Ultimate from MSDN.  I'm using EF Code First Migrations to build my database in my app, and I recently added a new entity and want to scaffold the migration for it.

To do this, you need to open the Package Manage Console window in VS, and type add-migration "some name here".  This will scaffold any changes to your database since the last time it was updated.

 The Problem

This issue did not occur on VS 2012 RC

The problem I'm encountering is the "Default Project" dropdown in the Package Manager Console is not populated, despite having several projects in my solution.  The default project that is used when I just type the command above is the wrong project (my migrations are in another project).  I get the following error when I do this:

No migrations configuration type was found in the assembly 'ProjectA'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).

What I've Tried

I have tried setting the correct project (ProjectB) as the startup project, only to get this error:

Could not load assembly 'ProjectA'. (If you are using Code First Migrations inside Visual Studio this can happen if the startUp project for your solution does not reference the project that contains your migrations. You can either change the startUp project for your solution or use the -StartUpProjectName parameter.)

The Question

How can I manually specify which project migrations are added to, or force the Default Project dropdown to populate?

答: You can select the projects under the Solution explorer .Then it showed up on package manager console . It worked for me</p>


问:
symfony 3.4 : forms : Use Data Transformers
trying to use data transformer, I have an error when loadding my html form

In my formType class

```<code>use Doctrine\ORM\EntityManagerInterface;

class PmpType extends AbstractType
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }
}
</code>```

in my app\config\services.yml

```<code>services:
# default configuration for services in *this* file
 _defaults:
    # automatically injects dependencies in your services
    autowire: true
    # automatically registers your services as commands, event subscribers, etc.
    autoconfigure: true
    # this means you cannot fetch services directly from the container via $container->get()
    # if you need to do this, you can override this setting on individual services
    public: true
</code>```

but I received this error

```<code>Type error: Too few arguments to function myApp\Bundle\Form\PmpType::__construct(), 0 passed in \vendor\symfony\symfony\src\Symfony\Component\Form\FormRegistry.php on line 92 and exactly 1 expected
</code>```

What do I miss

Thx for hepl

答:
OK
I don't understand why but I have toset the service for my class :
in service.yml, I add

```<code>    seims_pmp.pmptype:
      class: SEISM\PmpIG56Bundle\Form\PmpType
      arguments: ["@doctrine.orm.entity_manager"]
      tags: [form.type]
</code>```

and now it's working

Body:
trying to use data transformer, I have an error when loadding my html form

In my formType class

use Doctrine\ORM\EntityManagerInterface;

class PmpType extends AbstractType
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }
}

in my app\config\services.yml

services:
# default configuration for services in *this* file
 _defaults:
    # automatically injects dependencies in your services
    autowire: true
    # automatically registers your services as commands, event subscribers, etc.
    autoconfigure: true
    # this means you cannot fetch services directly from the container via $container->get()
    # if you need to do this, you can override this setting on individual services
    public: true

but I received this error

Type error: Too few arguments to function myApp\Bundle\Form\PmpType::__construct(), 0 passed in \vendor\symfony\symfony\src\Symfony\Component\Form\FormRegistry.php on line 92 and exactly 1 expected

What do I miss

Thx for hepl

Body:
OK
I don't understand why but I have toset the service for my class :
in service.yml, I add

    seims_pmp.pmptype:
      class: SEISM\PmpIG56Bundle\Form\PmpType
      arguments: ["@doctrine.orm.entity_manager"]
      tags: [form.type]

and now it's working


问:
Will the same value trigger the event in LiveDate?
The Code A and Image A is from the artical LiveData with SnackBar, Navigation and other events (the SingleLiveEvent case).

The author told me "Trigger the event by setting a new Event as a new value", I think it should be "Trigger the event by setting a new Event as any value", right?

For example,

Step 1: The user clicks the button in  master Activity with the code  userClicksOnButton("StartDetails") , the Details Activity will start.

Step 2: The user presses back, coming back to the master activity

Step 3:  The user clicks the button in  master Activity with the code  userClicksOnButton("StartDetails") again, the Details Activity will start again.

Is it right?

Code A

```<code>class ListViewModel : ViewModel {
    private val _navigateToDetails = MutableLiveData<Event<String>>()

    val navigateToDetails : LiveData<Event<String>>
        get() = _navigateToDetails

    fun userClicksOnButton(itemId: String) {
        _navigateToDetails.value = Event(itemId)  // Trigger the event by setting a new Event as a new value
    }
}

open class Event<out T>(private val content: T) {

    var hasBeenHandled = false
        private set // Allow external read but not write

    /**
     * Returns the content and prevents its use again.
     */
    fun getContentIfNotHandled(): T? {
        return if (hasBeenHandled) {
            null
        } else {
            hasBeenHandled = true
            content
        }
    }

    /**
     * Returns the content, even if it's already been handled.
     */
    fun peekContent(): T = content
}

myViewModel.navigateToDetails.observe(this, Observer {
    it.getContentIfNotHandled()?.let { // Only proceed if the event has never been handled
        startActivity(DetailsActivity...)
    }
})
</code>```

Image A

答:
You're having two different constraints on the data.

The LiveData emits every update to active observers, but the event itself is stateful. Thus a new event is required as a new LiveData value. The itemId could be any value, but the comment doesn't refer to it.

Trigger the event by setting a new Event as [a new] value

Body:
The Code A and Image A is from the artical LiveData with SnackBar, Navigation and other events (the SingleLiveEvent case).

The author told me "Trigger the event by setting a new Event as a new value", I think it should be "Trigger the event by setting a new Event as any value", right?

For example,

Step 1: The user clicks the button in  master Activity with the code  userClicksOnButton("StartDetails") , the Details Activity will start.

Step 2: The user presses back, coming back to the master activity

Step 3:  The user clicks the button in  master Activity with the code  userClicksOnButton("StartDetails") again, the Details Activity will start again.

Is it right?

Code A

class ListViewModel : ViewModel {
    private val _navigateToDetails = MutableLiveData<Event<String>>()

    val navigateToDetails : LiveData<Event<String>>
        get() = _navigateToDetails

    fun userClicksOnButton(itemId: String) {
        _navigateToDetails.value = Event(itemId)  // Trigger the event by setting a new Event as a new value
    }
}

open class Event<out T>(private val content: T) {

    var hasBeenHandled = false
        private set // Allow external read but not write

    /**
     * Returns the content and prevents its use again.
     */
    fun getContentIfNotHandled(): T? {
        return if (hasBeenHandled) {
            null
        } else {
            hasBeenHandled = true
            content
        }
    }

    /**
     * Returns the content, even if it's already been handled.
     */
    fun peekContent(): T = content
}

myViewModel.navigateToDetails.observe(this, Observer {
    it.getContentIfNotHandled()?.let { // Only proceed if the event has never been handled
        startActivity(DetailsActivity...)
    }
})

Image A


问:
C++: Access private member vector of structs from other class
from a similiar question here
I tried the solution

```<code>class A {
 ...
  public:

    // Give read-only access to vec_A
    const std::vector<DataStruct> & getVector() const {
        return vec_A;
    }
};
</code>```

but always get error: 'DataStruct' was not declared in this scope.
DataStruct and vec_A are defined in private section , below public section, in same class.

Please, could someone help me.

Regards,
Thomas

答: You are trying to create a vector out of the Datatype "DataStruct". Are you sure that you wrote the Class/or implemented it? It could be only a variable. You know that you actually have to put a Datatype in it like int,bool,string. It defines what datatype the specific variables in the vector are made of.</p>

Body:
from a similiar question here
I tried the solution

class A {
 ...
  public:

    // Give read-only access to vec_A
    const std::vector<DataStruct> & getVector() const {
        return vec_A;
    }
};

but always get error: 'DataStruct' was not declared in this scope.
DataStruct and vec_A are defined in private section , below public section, in same class.

Please, could someone help me.

Regards,
Thomas


问:
How do I get an element with a specific ID from getElementsByClassName?
EDIT: SOLVED. Thanks everyone!

I'm new to programming :D My code is below. Here is the deal: I have multiple buttons, but I want to make it so that the same thing would happen anytime any one of these buttons is clicked, but each button also has a specific value, and I also want that specific value to be printed out. My code goes through the document and looks at all the elements with "editButton" class, and correctly identifies all the buttons, but the problem is that no matter which button I press, I always get the value of the last button, because var id only gets assigned after the for loop finishes and is on the last element. I tried creating a global variable and assigning the value to it, but the result is the same. I tried ending the for loop before moving on to .done (function (data), but I got an error. Can someone help me out? Thanks!

$(document).ready(function() {
  var anchors = document.getElementsByClassName('editButton');
  for (var i = 0; i < anchors.length; i++) {
    var anchor = anchors[i];
    anchor.onclick = function() {
      $.ajax({
        method: "GET",
        url: "/testedit.php",
      }).done(function(data) {
        var id = anchor.value;

        /* from result create a string of data and append to the div */

        var result = data;
        var string = '
ID is ' + id + '

';

        $("#records").html(string);
      });
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="records"></div></code>```

答:
In your code..

```<code> var id = anchor.value;
</code>```

could be

```<code> var id = anchor.id;
</code>```

but I recommend you to use event delegation

If you have a html like this

```<code><div id="buttonArea">
  <a class="editButton" id="1"/>
  <a class="editButton" id="2"/>
  <a class="editButton" id="3"/>
  .......(so many buttons)
</div>
</code>```

you can code like below.

```<code>$(document).ready(function(){
  $('#buttonArea').on('click', 'a.editButton', function (event) {
    var anchor = event.currentTarget;
    $.ajax({
      method: "GET",
      url: "/testedit.php",
    })
    .done(function(data) {
      var id = anchor.id;

      /* from result create a string of data and append to the div */

      var result= data;
      var string='<p>ID is '+id+'</p><br>';

      $("#records").html(string);
    });
}
</code>```

Body:
In your code..

 var id = anchor.value;

could be

 var id = anchor.id;

but I recommend you to use event delegation

If you have a html like this

<div id="buttonArea">
  <a class="editButton" id="1"/>
  <a class="editButton" id="2"/>
  <a class="editButton" id="3"/>
  .......(so many buttons)
</div>

you can code like below.

$(document).ready(function(){
  $('#buttonArea').on('click', 'a.editButton', function (event) {
    var anchor = event.currentTarget;
    $.ajax({
      method: "GET",
      url: "/testedit.php",
    })
    .done(function(data) {
      var id = anchor.id;

      /* from result create a string of data and append to the div */

      var result= data;
      var string='<p>ID is '+id+'</p><br>';

      $("#records").html(string);
    });
}


问:
$selected$ only used once in custom visual studio c# snippet
My custom snippet only include $selected$ once. How can I use $selected$ multiple times?

Snippet:

```<code><?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <SnippetTypes>
        <SnippetType>SurroundsWith</SnippetType>
      </SnippetTypes>
      <Title>Creates a collection using ICollection from the selected entity</Title>
      <Author>Stein Lundbeck</Author>
      <Description>Select entity and the snippet implements ICollection with the selected entity</Description>
      <Shortcut>icoll</Shortcut>
      <Keywords>
        <Keyword>C#</Keyword>
        <Keyword>Collection</Keyword>
        <Keyword>Entity</Keyword>
      </Keywords>
    </Header>
    <Snippet>
    <Imports>
        <Import>
          <Namespace>System.Collections.Generic</Namespace>
        </Import>
        <Import>
          <Namespace>System.Collections.ObjectModel</Namespace>
        </Import>
    </Imports>
    <Declarations>
        <Literal Editable="true">
            <ID>Name</ID>
            <ToolTip>Name of variable</ToolTip>
            <Default>myVar</Default>
        </Literal>
    </Declarations>
        <Code Language="csharp" Delimiter="$" Kind="file">
            <![CDATA[ICollection<$selected$> $Name$ = new Collection<$selected$>();

            $end$]]>
        </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>
</code>```

Output:

```<code>using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Test
{
    class MyClass
    {
        ICollection<int> myVar = new Collection<>();
    }
}
</code>```

The Collection<> is missing the value from $selected$

答:
Check this MSDN reference for the Code Snippets Schema

"You may not use either $end$ or $selected$ more than once in a code snippet."

Body:
My custom snippet only include $selected$ once. How can I use $selected$ multiple times?

Snippet:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">

      <SnippetTypes>
        <SnippetType>SurroundsWith</SnippetType>
      </SnippetTypes>
      <Title>Creates a collection using ICollection from the selected entity</Title>
      <Author>Stein Lundbeck</Author>
      <Description>Select entity and the snippet implements ICollection with the selected entity</Description>
      <Shortcut>icoll</Shortcut>
      <Keywords>
        <Keyword>C#</Keyword>
        <Keyword>Collection</Keyword>
        <Keyword>Entity</Keyword>
      </Keywords>

    <Snippet>
    <Imports>
        <Import>
          <Namespace>System.Collections.Generic</Namespace>
        </Import>
        <Import>
          <Namespace>System.Collections.ObjectModel</Namespace>
        </Import>
    </Imports>
    <Declarations>
        <Literal Editable="true">
            <ID>Name</ID>
            <ToolTip>Name of variable</ToolTip>
            <Default>myVar</Default>
        </Literal>
    </Declarations>

            <![CDATA[ICollection<$selected$> $Name$ = new Collection<$selected$>();

            $end$]]>

    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Output:

using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Test
{
    class MyClass
    {
        ICollection<int> myVar = new Collection<>();
    }
}

The Collection<> is missing the value from $selected$


问:
Kafka with spark streaming issue: Cannot read data from topic with existing data
I am trying to read from a Kafka broker with spark streaming but I am facing some issues.

```<code>def spark_streaming_from_STABLE_kafka_topic():
    conf = SparkConf().setMaster("spark://antonis-dell:7077").setAppName("Kafka_Spark")
    sc = SparkContext(conf=conf)
    sc.setLogLevel("WARN")
    ssc = StreamingContext(sc, 2)

    topic = "stable_topic"
    kvs = KafkaUtils.createDirectStream(ssc,
                                    [topic],
                                    {"metadata.broker.list": "my-broker",
                                    "auto.offset.reset": "smallest"},
                                    keyDecoder=lambda x: x,
                                    valueDecoder=lambda x: x
                                    )

    lines = kvs.window(2, 2).map(lambda x: x[1])
    lines.pprint()
    return ssc

if __name__ == "__main__":
    ssc = StreamingContext.getOrCreate('/home/antonis/Desktop/tmp/checkpoint_v06', lambda: spark_streaming_from_STABLE_kafka_topic())
    ssc.start()
    ssc.awaitTermination()
</code>```

Above code does no fetch anything except empty batches:

```<code>-------------------------------------------
Time: 2020-05-29 09:32:38
-------------------------------------------

-------------------------------------------
Time: 2020-05-29 09:32:40
-------------------------------------------
</code>```

Topic stable_topic contains a fixed size of data. It does not change.
I have another topic that receives data every second. If I use this topic instead of stable_topic and remove the "auto.offset.reset": "smallest" then the code fetches data.

I assume that there is something wrong with {"auto.offset.reset": "smallest"} but I cannot figure it out.

Does anyone now what I am doing wrong?

答:
In later versions, smallest was replaced by earliest. Make sure you check the documentation of the version you are using.

Also, the auto.offset.reset configuration will not get into effect, if the Consumer Group has already been consuming some data from the topic stable_topic. Therefore, you might consider changing the group.id in your streaming job.

If you are assigning a new group.id, make sure to set the auto.offset.reset to smalles (or earliest in newer versions).

Body:
I am trying to read from a Kafka broker with spark streaming but I am facing some issues.

def spark_streaming_from_STABLE_kafka_topic():
    conf = SparkConf().setMaster("spark://antonis-dell:7077").setAppName("Kafka_Spark")
    sc = SparkContext(conf=conf)
    sc.setLogLevel("WARN")
    ssc = StreamingContext(sc, 2)

    topic = "stable_topic"
    kvs = KafkaUtils.createDirectStream(ssc,
                                    [topic],
                                    {"metadata.broker.list": "my-broker",
                                    "auto.offset.reset": "smallest"},
                                    keyDecoder=lambda x: x,
                                    valueDecoder=lambda x: x
                                    )

    lines = kvs.window(2, 2).map(lambda x: x[1])
    lines.pprint()
    return ssc

if __name__ == "__main__":
    ssc = StreamingContext.getOrCreate('/home/antonis/Desktop/tmp/checkpoint_v06', lambda: spark_streaming_from_STABLE_kafka_topic())
    ssc.start()
    ssc.awaitTermination()

Above code does no fetch anything except empty batches:

-------------------------------------------
Time: 2020-05-29 09:32:38
-------------------------------------------

-------------------------------------------
Time: 2020-05-29 09:32:40
-------------------------------------------

Topic stable_topic contains a fixed size of data. It does not change.
I have another topic that receives data every second. If I use this topic instead of stable_topic and remove the "auto.offset.reset": "smallest" then the code fetches data.

I assume that there is something wrong with {"auto.offset.reset": "smallest"} but I cannot figure it out.

Does anyone now what I am doing wrong?


问:
Memory Leak in C#
Is it ever possible in a managed system to leak memory when you make sure that all handles, things that implement IDispose are disposed?

Would there be cases where some variables are left out?

答:
Delegates can result in unintuitive memory leaks.

Whenever you create a delegate from an instance method, a reference to that instance is stored "in" that delegate.

Additionally, if you combine multiple delegates into a multicast delegate, you have one big blob of references to numerous objects that are kept from being garbage collected as long as that multicast delegate is being used somewhere.

OwnerDisplayName: Joan Venge

Title: Memory Leak in C#

LastEditorDisplayName: strager

OwnerDisplayName: SealedSun


问:
Dependency Injection in every aspect of a spring app?
I am taking a look into Spring as a web framework, however I am needing a bit of help getting my head around DI.

The concept of objects getting constructed in the container on run time is such a new concept.

I am just wondering how this will reflect in a big application, would I have some modules doing work that are more highly coupled or should every object be initialised at runtime?

It all seems a little intensive to me, I mean say for example I have a CSV file data mining application that removes the data per row - each rows data is encapsulated in one of my own CSVRow objects for processing or whatever. These objects are instantiated whenever an Excel file maybe uploaded to the server. I don't know how many I will need to create?

I seem to be getting a bit lost, any clarity, an overview or some guidance would be much appreciated.

Thanks in advance!

答:
I'll try to put it simply:

use dependency injection for stateless classes that have logic (business logic, persistence logic, front-end logic)

use new for value objects