问:
why main thread don't return response immediately when I call async method?
I have write a test code in a new web application as below:

```<code>    public ActionResult Index()
    {
        Logger.Write("start Index,threadId:" + System.Threading.Thread.CurrentThread.ManagedThreadId);
        MyMethodAsync(System.Web.HttpContext.Current.Request);//no await and has warning
        Logger.Write("end Index,threadId:" + System.Threading.Thread.CurrentThread.ManagedThreadId);
        return View();
    }

private async Task MyMethodAsync(HttpRequest request)
    {
        Logger.Write("start MyMethodAsync,threadId:" + System.Threading.Thread.CurrentThread.ManagedThreadId);
        await SomeMethodAsync(request);
        Logger.Write("end MyMethodAsync,threadId:" + System.Threading.Thread.CurrentThread.ManagedThreadId);
    }
</code>```

And here is the log:

2017-11-15 19:55:31.904 start Index,threadId:35

2017-11-15 19:55:31.919 start MyMethodAsync,threadId:35

2017-11-15 19:55:31.919 end Index,threadId:35

2017-11-15 19:55:53.324 end MyMethodAsync,threadId:46

The client brower will receive response at about 2017-11-15 19:55:32 and it accord with my understanding. In my actual project production environment,it writes the same log as above, However, the client brower received response in about 22 seconds later at about 2017-11-15 19:55:54. It seems that even the main thread complete the work, the main thread do not return the response until the new thread complete the work.

I have debug this problem serveral days. Could you help me please?

答:
async-await does not change the HTTP protocol. The request goes to the server, the server produces a response and sends it to the client.

It just changes how ASP.NET requests are processed by ASP.NET.

And it doesn't make the request handling faster. Quite the contrary.

But it does use more thread pool threads and makes the server more responsive under heavy load.

Body:
I have write a test code in a new web application as below:

    public ActionResult Index()
    {
        Logger.Write("start Index,threadId:" + System.Threading.Thread.CurrentThread.ManagedThreadId);
        MyMethodAsync(System.Web.HttpContext.Current.Request);//no await and has warning
        Logger.Write("end Index,threadId:" + System.Threading.Thread.CurrentThread.ManagedThreadId);
        return View();
    }

private async Task MyMethodAsync(HttpRequest request)
    {
        Logger.Write("start MyMethodAsync,threadId:" + System.Threading.Thread.CurrentThread.ManagedThreadId);
        await SomeMethodAsync(request);
        Logger.Write("end MyMethodAsync,threadId:" + System.Threading.Thread.CurrentThread.ManagedThreadId);
    }

And here is the log:

2017-11-15 19:55:31.904 start Index,threadId:35

2017-11-15 19:55:31.919 start MyMethodAsync,threadId:35

2017-11-15 19:55:31.919 end Index,threadId:35

2017-11-15 19:55:53.324 end MyMethodAsync,threadId:46

The client brower will receive response at about 2017-11-15 19:55:32 and it accord with my understanding. In my actual project production environment,it writes the same log as above, However, the client brower received response in about 22 seconds later at about 2017-11-15 19:55:54. It seems that even the main thread complete the work, the main thread do not return the response until the new thread complete the work.

I have debug this problem serveral days. Could you help me please?


来源: stackexchange

问:
mongoose nested arrays schema
I'm trying to create a schema for the following array:

```<code>const data = [ [ { name: 'AKA_A2',
      path: '/',
      expires: 1510762544.752427,
      size: 7 },
    { name: 'userInfo',
      path: '/',
      expires: 0,
      size: 82 },
    { name: 'userInfo',
      path: '/',
      expires: 0,
      size: 82 } ] ]
</code>```

This is the Schema that I've created:

```<code>import mongoose from 'mongoose';

const CookieSchema = mongoose.Schema(
  {
    name: String,
    path: String,
    expires: String,
    size: String
  }
)

const RunSchema = mongoose.Schema(
  {
    reports: {
      cookieSummary: [CookieSchema]
    }
  }
)

export default mongoose.model('Run', RunSchema);
</code>```

Then when I'm trying to update a document from this schema I get a null response and the document is not updated.

This is my code:

```<code>Run.findOneAndUpdate({_id: runId}, {$set: {'reports.cookieSummary': data}}, (err, doc) => {
  console.log(doc);
});
</code>```

My document looks like this:

```<code>{
    "_id": {
        "$oid": "5a0c5e86d4b737549e88d8cf"
    },
    "reports": {},
    "__v": 0
}
</code>```

答:
// In Previous Answer is not be cleared for your answer. You don't need to create two Schemas    </p>

```<code>import mongoose from 'mongoose';
const RunSchema = mongoose.Schema({
    reports: {
            cookieSummary: {
                  name: String,
                  path: String,
                  expires: String,
                  size: String
             }
        }
})

export default mongoose.model('Run', RunSchema);
</code>```

ContentLicense: CC BY-SA 3.0

Title: mongoose nested arrays schema

Body:
I'm trying to create a schema for the following array:

const data = [ [ { name: 'AKA_A2',
      path: '/',
      expires: 1510762544.752427,
      size: 7 },
    { name: 'userInfo',
      path: '/',
      expires: 0,
      size: 82 },
    { name: 'userInfo',
      path: '/',
      expires: 0,
      size: 82 } ] ]

This is the Schema that I've created:

import mongoose from 'mongoose';

const CookieSchema = mongoose.Schema(
  {
    name: String,
    path: String,
    expires: String,
    size: String
  }
)

const RunSchema = mongoose.Schema(
  {
    reports: {
      cookieSummary: [CookieSchema]
    }
  }
)

export default mongoose.model('Run', RunSchema);

Then when I'm trying to update a document from this schema I get a null response and the document is not updated.

This is my code:

Run.findOneAndUpdate({_id: runId}, {$set: {'reports.cookieSummary': data}}, (err, doc) => {
  console.log(doc);
});

My document looks like this:

{
    "_id": {
        "$oid": "5a0c5e86d4b737549e88d8cf"
    },
    "reports": {},
    "__v": 0
}

Body:
// In Previous Answer is not be cleared for your answer. You don't need to create two Schemas

import mongoose from 'mongoose';
const RunSchema = mongoose.Schema({
    reports: {
            cookieSummary: {
                  name: String,
                  path: String,
                  expires: String,
                  size: String
             }
        }
})

export default mongoose.model('Run', RunSchema);


问:
Basic javascript code on hidden field to stop simple bots signingup
I want to have a hidden field in my code as below, that bots will fill in when submitting it. But i want javascript code to look at that field only for a value and if there is a value, create an alert or hide the submit button so the bot cannot signup at all.

I just tailored a mailchimp form to use.

<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">

<form action="http://my.site/index.php/lists/ej8651mn51e/subscribe" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank">

Subscribe to our mailing list

* indicates required

 Email Address  *

 <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">

 First Name
 <input type="text" value="" name="FNAME" class="" id="mce-FNAME">

<input type="text" name="b_8705ce44717aeac8551b690ed_1b95a85a92" tabindex="-1" value="erg34t34t3">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

</form>

```

答:
It sounds to me like you are talking about using a honeypot technique to catch spam bots. But I think you are thinking about it slightly wrong. A bot with any level of sophistication should be able to submit a form without it having an explicit submit button. Further, a sophisticated spam bot will be able to bypass any client-side validation you attempt to perform prior to submitting the form, and will also likely ignore any seemingly meaningless alerts you present it.

Thus, you want to augment your client-side validation with server-side validation when using a honeypot. The idea is that a normal user won't enter anything into a hidden field, but a bot might, so if there is an unexpected value in it then the form submission is bogus.

If you are, however, stuck with client-side validation here are a few articles about implementing honeypots in JavaScript:

https://lukehollenback.me/avoiding-bots-without-a-captcha/

http://jennamolby.com/how-to-prevent-form-spam-by-using-the-honeypot-technique/


问:
If using Django-tenat-schemas how to flush database?
I am using django-tenant-schemas app to handle tenants and database related to various tenants. Now what I want to do is flush all the database so how can this be done? </p>

答:
I am working with https://github.com/tomturner/django-tenants, but this should also work for https://github.com/bernardopires/django-tenant-schemas.

When using multiple tenants/schemas, flush does not work anymore. When you use manage.py flush, the error tells you that there are foreign key constraints that are not met; and it suggests:

```<code>HINT:  Truncate table "<your table name>" at the same time, or use TRUNCATE ... CASCADE.
</code>```

Here is a management command (flush_cascade.py) which does that (I only tested with PostgreSQL`):

```<code>from django.core.management import call_command
from django.core.management.commands.flush import Command as FlushCommand
from django.db import transaction

class Command(FlushCommand):
    @transaction.atomic
    def handle(self, *args, **options):
        options['allow_cascade'] = True
        call_command('flush', *args, **options)
</code>```

Django's default flush command only sends TRUNCATE to the database. It doesn't add CASCADE because not all database backends support cascading statements.

Body:
I am working with https://github.com/tomturner/django-tenants, but this should also work for https://github.com/bernardopires/django-tenant-schemas.

When using multiple tenants/schemas, flush does not work anymore. When you use manage.py flush, the error tells you that there are foreign key constraints that are not met; and it suggests:

HINT:  Truncate table "<your table name>" at the same time, or use TRUNCATE ... CASCADE.

Here is a management command (flush_cascade.py) which does that (I only tested with PostgreSQL`):

from django.core.management import call_command
from django.core.management.commands.flush import Command as FlushCommand
from django.db import transaction

class Command(FlushCommand):
    @transaction.atomic
    def handle(self, *args, **options):
        options['allow_cascade'] = True
        call_command('flush', *args, **options)

Django's default flush command only sends TRUNCATE to the database. It doesn't add CASCADE because not all database backends support cascading statements.


问:
Why do I need to do `--set-upstream` all the time?
I create a new branch in Git:

```<code>git branch my_branch
</code>```

Push it:

```<code>git push origin my_branch
</code>```

Now say someone made some changes on the server and I want to pull from origin/my_branch. I do:

```<code>git pull
</code>```

But I get:

```<code>You asked me to pull without telling me which branch you
want to merge with, and 'branch.my_branch.merge' in
your configuration file does not tell me, either. Please
specify which branch you want to use on the command line and
try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) for details.

If you often merge with the same branch, you may want to
use something like the following in your configuration file:

    [branch "my_branch"]
    remote = <nickname>
    merge = <remote-ref>

    [remote "<nickname>"]
    url = <url>
    fetch = <refspec>

See git-config(1) for details.
</code>```

I learned that I can make it work with:

```<code>git branch --set-upstream my_branch origin/my_branch
</code>```

But why do I need to do this for every branch I create? Isn't it obvious that if I push my_branch into origin/my_branch, then I would want to pull origin/my_branch into my_branch? How can I make this the default behavior?

答:
This is my most common use for The Fuck.

```<code>$ git push
fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin master

$ fuck
git push --set-upstream origin master [enter/↑/↓/ctrl+c]
Counting objects: 9, done.
...
</code>```

Also, it's fun to type swear words in your terminal.

Body:
I create a new branch in Git:

git branch my_branch

Push it:

git push origin my_branch

Now say someone made some changes on the server and I want to pull from origin/my_branch. I do:

git pull

But I get:

You asked me to pull without telling me which branch you
want to merge with, and 'branch.my_branch.merge' in
your configuration file does not tell me, either. Please
specify which branch you want to use on the command line and
try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) for details.

If you often merge with the same branch, you may want to
use something like the following in your configuration file:

    [branch "my_branch"]
    remote = <nickname>
    merge = <remote-ref>

    [remote "<nickname>"]
    url = <url>
    fetch = <refspec>

See git-config(1) for details.

I learned that I can make it work with:

git branch --set-upstream my_branch origin/my_branch

But why do I need to do this for every branch I create? Isn't it obvious that if I push my_branch into origin/my_branch, then I would want to pull origin/my_branch into my_branch? How can I make this the default behavior?

Body:
This is my most common use for The Fuck.

$ git push
fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin master

$ fuck
git push --set-upstream origin master [enter/↑/↓/ctrl+c]
Counting objects: 9, done.
...

Also, it's fun to type swear words in your terminal.


问:
Questions about routing in Asp.net Core MVC 2
I can't wrap my mind around the routing mechanism in asp.net core MVC 2.

Here's what I have:

I already built a functioning page to add 'Materials' to a 'Application'.

The URL to call this page is:

    http://localhost:33333/AddMaterial/Index/57

which uses the default route:

```<code>routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}/{id?}"
);
</code>```

Whereby 57 is the application id, so that I know what 'Application' gets the new 'Material'. The Index Method in the controller looks like this, and works like expected:

```<code>[HttpGet] public IActionResult Index(string id)
{
    var model = GetModel(context, int.Parse(id));
    return View("Index", model);
}
</code>```

So far so good... Now here's my problem:

I want to use the same controller and view to also edit 'Materials'. But for that i'd need two parameters in Index(). I'd need:

```<code>string applicationId
string materialId
</code>```

as parameters.

So I added a new route:

```<code>routes.MapRoute(
    name: "whatImTryingToAchieve",
    template: "{controller}/{action}/{applicationId?}/{materialId?}"
);
</code>```

And of course I updated the controller:

```<code>public IActionResult Index(string applicationiId, string materialId)
{
    // Do stuff with materialId etc.
    // ...
    return View("Index", model);
 }
</code>```

I know that the routing system has a specific order. So I tried defining my new route before the default route. That didn't work.
I then tried to put it after the default route, which didn't work either.

I read through a lot of information about the routing system, but I didn't seem to find the answer to my simple question:

How can I add another, specific route?

Help would be much appreciated :)

EDIT: Attribute based routing as suggested by Igors Šutovs

Controller:

```<code>[Authorize(Roles = "Admins")]
[Route("AddMaterial")]
public class AddMaterialController : Controller
{
    //....

    [Route("AddMaterial/{applicationId}/{otherid}")] // Nope. Nothing.
    [HttpGet] public IActionResult Index(string applicationId, string otherid)
    {
        return View();
    }

    [Route("AddMaterial/Index/{applicationId}")]  // Didn't work.
    [Route("AddMaterial/{applicationId}")]        // Didn't work either...
    [HttpGet] public IActionResult Index(string applicationId)
    {
        return View();
    }
}
</code>```

So much for Attribute base routing.

答:
I will provide my subjective opinion on the essence of the described problem. It seems that the question could be rephrased as: "What is the correct ASP.NET Core way to design routes and resolve such situations with multiple parameters?"

TLDR: use Attribute-Based Routing

This is the new type of routing which was added in ASP.MVC 5. Since then the old routing mechanism has been regarded as "Conventional-Based". ASP.NET Core currently allows mixing of both. I will provide a detailed example of how to solve the described problem using the Attribute-Based Routing only because the new approach provides the following advantages:

Route information is moved closer to controller actions, hence code is easier to understand and troubleshoot

Controller names and their method are decoupled from route names

Moving on to the solution. Let's assume that we have 2 models: Application and Material. I would create 2 distinct controllers to manage each. From your example, I understand that the relationship between these domain entities is one-to-many e.g. one Application could have many Materials. This suggests the following routes:

```<code>GET: applications/{applicationId}
GET: applications/{applicationId}/materials/{materialId}
</code>```

...with a look back at principles of Restful Routing.

The ApplicationController would then look like this:

```<code>[Route("applications")]
public class ApplicationController
{
    [HttpGet("{applicationId}")]
    public IActionResult Index(string applicationId)
    {
        // return your view
    }
}
</code>```

While the MaterialController would look like this:

```<code>[Route("applications/{applicationId}/materials")]
public class MaterialController
{
    [HttpGet("{materialId}")]
    public IActionResult Index(string applicationId, string materialId)
    {
        // return your view
    }
}
</code>```

The call to UseMvc(..) extension method in Configure method of Startup.cs can now be simplified to just:

```<code>app.UseMvc();
</code>```

Hope you'll find it useful!

Body:
I can't wrap my mind around the routing mechanism in asp.net core MVC 2.

Here's what I have:

I already built a functioning page to add 'Materials' to a 'Application'.

The URL to call this page is:

    http://localhost:33333/AddMaterial/Index/57

which uses the default route:

routes.MapRoute(
    name: "default",
    template: "{controller=Home}/{action=Index}/{id?}"
);

Whereby 57 is the application id, so that I know what 'Application' gets the new 'Material'. The Index Method in the controller looks like this, and works like expected:

[HttpGet] public IActionResult Index(string id)
{
    var model = GetModel(context, int.Parse(id));
    return View("Index", model);
}

So far so good... Now here's my problem:

I want to use the same controller and view to also edit 'Materials'. But for that i'd need two parameters in Index(). I'd need:

string applicationId
string materialId

as parameters.

So I added a new route:

routes.MapRoute(
    name: "whatImTryingToAchieve",
    template: "{controller}/{action}/{applicationId?}/{materialId?}"
);

And of course I updated the controller:

public IActionResult Index(string applicationiId, string materialId)
{
    // Do stuff with materialId etc.
    // ...
    return View("Index", model);
 }

I know that the routing system has a specific order. So I tried defining my new route before the default route. That didn't work.
I then tried to put it after the default route, which didn't work either.

I read through a lot of information about the routing system, but I didn't seem to find the answer to my simple question:

How can I add another, specific route?

Help would be much appreciated :)

EDIT: Attribute based routing as suggested by Igors Šutovs

Controller:

[Authorize(Roles = "Admins")]
[Route("AddMaterial")]
public class AddMaterialController : Controller
{
    //....

    [Route("AddMaterial/{applicationId}/{otherid}")] // Nope. Nothing.
    [HttpGet] public IActionResult Index(string applicationId, string otherid)
    {
        return View();
    }

    [Route("AddMaterial/Index/{applicationId}")]  // Didn't work.
    [Route("AddMaterial/{applicationId}")]        // Didn't work either...
    [HttpGet] public IActionResult Index(string applicationId)
    {
        return View();
    }
}

So much for Attribute base routing.

Body:
I will provide my subjective opinion on the essence of the described problem. It seems that the question could be rephrased as: "What is the correct ASP.NET Core way to design routes and resolve such situations with multiple parameters?"

TLDR: use Attribute-Based Routing

This is the new type of routing which was added in ASP.MVC 5. Since then the old routing mechanism has been regarded as "Conventional-Based". ASP.NET Core currently allows mixing of both. I will provide a detailed example of how to solve the described problem using the Attribute-Based Routing only because the new approach provides the following advantages:

Route information is moved closer to controller actions, hence code is easier to understand and troubleshoot

Controller names and their method are decoupled from route names

Moving on to the solution. Let's assume that we have 2 models: Application and Material. I would create 2 distinct controllers to manage each. From your example, I understand that the relationship between these domain entities is one-to-many e.g. one Application could have many Materials. This suggests the following routes:

GET: applications/{applicationId}
GET: applications/{applicationId}/materials/{materialId}

...with a look back at principles of Restful Routing.

The ApplicationController would then look like this:

[Route("applications")]
public class ApplicationController
{
    [HttpGet("{applicationId}")]
    public IActionResult Index(string applicationId)
    {
        // return your view
    }
}

While the MaterialController would look like this:

[Route("applications/{applicationId}/materials")]
public class MaterialController
{
    [HttpGet("{materialId}")]
    public IActionResult Index(string applicationId, string materialId)
    {
        // return your view
    }
}

The call to UseMvc(..) extension method in Configure method of Startup.cs can now be simplified to just:

app.UseMvc();

Hope you'll find it useful!


问:
Git ignore deleted folders during a merge?
A developer has been working on some feature branch f1 that branched off of master.

Due to poor modularization of the repo (the system is modular, but lives in a monolithic repo) and other reasons, the developer decided to delete "a bunch of irrelevant stuff" (other modules unrelated to his feature) in the f1 branch. The feature unit-tests successfully, but the branch now contains all these deletions of entire other modules of the system.

What is the easiest, most painless way to merge f1 back into master while ignoring folder deletions? Assume some of the files modified in f1 were also modified in the evolution of master.

Additional Requirement
Work on the f1 branch may need to continue for a little while after the merge. I'm not quite sure how the answers proposed so far would impact that.

答:
I hope my git-fu is up to par.

Supposing that MERGE_SOURCE is the branch you want to merge from, here F1, and PRESERVED_PATHS is the list of paths that need to be revived:

```<code># Find out the commit from which F1 forked
MERGE_SPLIT_POINT=`git merge-base HEAD ${MERGE_SOURCE}`

# Rewrite the branch's history to unstage all changes
# (including removals) of the preserved paths
git filter-branch \
    --index-filter 'git reset ${MERGE_SPLIT_POINT} -- ${PRESERVED_PATHS}' \
    -- ${MERGE_SPLIT_POINT}..${MERGE_SOURCE}

# Regular merge with the resulting new branch
git merge ${MERGE_SOURCE}
</code>```

Body:
I hope my git-fu is up to par.

Supposing that MERGE_SOURCE is the branch you want to merge from, here F1, and PRESERVED_PATHS is the list of paths that need to be revived:

# Find out the commit from which F1 forked
MERGE_SPLIT_POINT=`git merge-base HEAD ${MERGE_SOURCE}`

# Rewrite the branch's history to unstage all changes
# (including removals) of the preserved paths
git filter-branch \
    --index-filter 'git reset ${MERGE_SPLIT_POINT} -- ${PRESERVED_PATHS}' \
    -- ${MERGE_SPLIT_POINT}..${MERGE_SOURCE}

# Regular merge with the resulting new branch
git merge ${MERGE_SOURCE}


问:
Google Maps Autocomplete Province
I am using Google Maps APIs guide for autocomplete:

https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform

but it seems it is not possible to detect Italy provinces.

For instance: typing an Italian address "Caronno Pertusella, VA, Italia", I'm not able to detect "VA".

I tried add and change parameters: https://developers.google.com/maps/documentation/javascript/geocoding

but I can not find province parameter.

答:
If you search for: "Caronno Pertusella VA, Italia" = without comma before VA, you will get it. Also "Caronno Pertusella VA, It" will work. After the city comma, autocomplete await the country or country code.

By the way, why do you not just choose one of the proposals of autocomplete? If you type in "Caronno " you get as proposal: "Caronno Pertusella Varese, Italia"

Title: Google Maps Autocomplete Province


问:
Not sending userAgent in header, Node.js console application
I'm just beginning to learn javascript and https requests.  I'm working in Visual Studio 2017, I created a blank javascript console app from the template and added the following code.

```<code>const https = require('https');

const options = {
    hostname: 'api.gdax.com',
    path: '/products/BTC-USD/stats',
    method: 'GET',
    agent: false
};

const req = https.request(options, (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);

    res.on('data', (d) => {
        process.stdout.write(d);
    });
});

req.on('error', (e) => {
    console.error(e);
});
req.end();
</code>```

The response I get from the server is

```<code>{"message":"User-Agent header is required."}
</code>```

When I navigate to https://api.gdax.com/products/BTC-USD/stats in my browser I get the correct response.  How come I can't do the same in a javascript console?

答:
That's because that specific API is blocking any request without the User-Agent header.

Just add the header, and it will work fine:

```<code>const https = require('https');

const options = {
  hostname: 'api.gdax.com',
  path: '/products/BTC-USD/stats',
  method: 'GET',
  agent: false,
  headers: {
    'User-Agent': 'something',
  },
};

const req = https.request(options, res => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', d => {
    process.stdout.write(d);
  });
});

req.on('error', e => {
  console.error(e);
});
req.end();
</code>```

Body:
I'm just beginning to learn javascript and https requests.  I'm working in Visual Studio 2017, I created a blank javascript console app from the template and added the following code.

const https = require('https');

const options = {
    hostname: 'api.gdax.com',
    path: '/products/BTC-USD/stats',
    method: 'GET',
    agent: false
};

const req = https.request(options, (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);

    res.on('data', (d) => {
        process.stdout.write(d);
    });
});

req.on('error', (e) => {
    console.error(e);
});
req.end();

The response I get from the server is

{"message":"User-Agent header is required."}

When I navigate to https://api.gdax.com/products/BTC-USD/stats in my browser I get the correct response.  How come I can't do the same in a javascript console?

Body:
That's because that specific API is blocking any request without the User-Agent header.

Just add the header, and it will work fine:

const https = require('https');

const options = {
  hostname: 'api.gdax.com',
  path: '/products/BTC-USD/stats',
  method: 'GET',
  agent: false,
  headers: {
    'User-Agent': 'something',
  },
};

const req = https.request(options, res => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', d => {
    process.stdout.write(d);
  });
});

req.on('error', e => {
  console.error(e);
});
req.end();


问:
PDF print to file path VBA
I have the below code I have researched and got to work in one of my workbooks. The idea of the code is to automatically print a sheet to PDF and save down in a directory of my choosing naming it the contents of a specific cell.

All works fine until I try to copy into a new workbook (I designed in a test workbook as not to corrupt the original)  then I get a

run time error 1004

and the ThisWorkbook.Sheets(Array("sheet 2")).Select is highlighted when I debug. Am I missing something simple? as the code works in the original workbook but not in if I paste into a new module in a new workbook?  Sorry i'm quite new to this!

```<code>sub PrintPDFRT()

Sheets("test").Activate
ActiveSheet.UsedRange.Select
Sheets("malbru1").Activate
ActiveSheet.UsedRange.Select
Sheets("sheet 2").Activate
Range("A1:j137").Select

ThisWorkbook.Sheets(Array("sheet 2")).Select
Selection.ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:="FIle path\" & Range("L7").Value, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False
 End Sub
</code>```

答:
Try it like this: (without Array)

```<code>sub PrintPDFRT()

WorkSheets("test").Activate
ActiveSheet.UsedRange.Select
WorkSheets("malbru1").Activate
ActiveSheet.UsedRange.Select
WorkSheets("sheet 2").Activate
Range("A1:j137").Select

ThisWorkbook.WorkSheets("sheet 2").ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:="FIle path\" & Range("L7").Value, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False
 End Sub
</code>```

Title: PDF print to file path VBA

Body:
I have the below code I have researched and got to work in one of my workbooks. The idea of the code is to automatically print a sheet to PDF and save down in a directory of my choosing naming it the contents of a specific cell.

All works fine until I try to copy into a new workbook (I designed in a test workbook as not to corrupt the original)  then I get a

run time error 1004

and the ThisWorkbook.Sheets(Array("sheet 2")).Select is highlighted when I debug. Am I missing something simple? as the code works in the original workbook but not in if I paste into a new module in a new workbook?  Sorry i'm quite new to this!

sub PrintPDFRT()

Sheets("test").Activate
ActiveSheet.UsedRange.Select
Sheets("malbru1").Activate
ActiveSheet.UsedRange.Select
Sheets("sheet 2").Activate
Range("A1:j137").Select

ThisWorkbook.Sheets(Array("sheet 2")).Select
Selection.ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:="FIle path\" & Range("L7").Value, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False
 End Sub

Body:
Try it like this: (without Array)

sub PrintPDFRT()

WorkSheets("test").Activate
ActiveSheet.UsedRange.Select
WorkSheets("malbru1").Activate
ActiveSheet.UsedRange.Select
WorkSheets("sheet 2").Activate
Range("A1:j137").Select

ThisWorkbook.WorkSheets("sheet 2").ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:="FIle path\" & Range("L7").Value, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False
 End Sub


问:
Adding row to dataframe with time stamp index
I'm trying to dynamically add a new row to a Pandas data frame. The index is a timestamp and I cannot figure out how to insert a new row without messing up the index. First part of the code creates the data frame:

```<code>data = {'time_stamp': ['2014-05-01 18:47:05.069', '2014-05-01 18:47:05.119', '2014-05-02 18:47:05.230',],
        'col_a': [34, 25, 26],
        'col_b' : [21,32,43]}
df = pd.DataFrame(data, columns = ['time_stamp', 'col_a', 'col_b'])
df['time_stamp'] = pd.to_datetime(df['time_stamp'], format="%Y-%m-%d %H:%M:%S.%f")
df.index = df['time_stamp'] # Make time_stamp the index
del df['time_stamp']        # Drop the initial time_stamp column
print df
</code>```

Result:

```<code>                             col_a  col_b
time_stamp
2014-05-01 18:47:05.069     34     21
2014-05-01 18:47:05.119     25     32
2014-05-02 18:47:05.230     26     43
</code>```

Trying to add a row with concat (same problem with append):

```<code>#Insert new row (corresponding to an incoming update message with a time stamp an a new value on col_a
ts = pd.to_datetime("2014-05-04 18:47:05.487", format="%Y-%m-%d %H:%M:%S.%f")
new_row = pd.DataFrame([[11]], columns = ["col_a"])
df = pd.concat([df, pd.DataFrame(new_row)], ignore_index=False)
print df
</code>```

Result:

```<code>                            col_a  col_b
2014-05-01 18:47:05.069000     34   21.0
2014-05-01 18:47:05.119000     25   32.0
2014-05-02 18:47:05.230000     26   43.0
0                              11    NaN
</code>```

If I extend "new_row" with a column called "time_frame" and a corresponding time stamp, it will create a new column called "time_stamp", rather than inserting a new value in the index column.

```<code>                            col_a  col_b              time_stamp
2014-05-01 18:47:05.069000     34   21.0                     NaT
2014-05-01 18:47:05.119000     25   32.0                     NaT
2014-05-02 18:47:05.230000     26   43.0                     NaT
0                              11    NaN 2014-05-04 18:47:05.487
</code>```

Any ideas would be greatly appreciated.

Body:
I'm trying to dynamically add a new row to a Pandas data frame. The index is a timestamp and I cannot figure out how to insert a new row without messing up the index. First part of the code creates the data frame:

data = {'time_stamp': ['2014-05-01 18:47:05.069', '2014-05-01 18:47:05.119', '2014-05-02 18:47:05.230',],
        'col_a': [34, 25, 26],
        'col_b' : [21,32,43]}
df = pd.DataFrame(data, columns = ['time_stamp', 'col_a', 'col_b'])
df['time_stamp'] = pd.to_datetime(df['time_stamp'], format="%Y-%m-%d %H:%M:%S.%f")
df.index = df['time_stamp'] # Make time_stamp the index
del df['time_stamp']        # Drop the initial time_stamp column
print df

Result:

                             col_a  col_b
time_stamp
2014-05-01 18:47:05.069     34     21
2014-05-01 18:47:05.119     25     32
2014-05-02 18:47:05.230     26     43

Trying to add a row with concat (same problem with append):

#Insert new row (corresponding to an incoming update message with a time stamp an a new value on col_a
ts = pd.to_datetime("2014-05-04 18:47:05.487", format="%Y-%m-%d %H:%M:%S.%f")
new_row = pd.DataFrame([[11]], columns = ["col_a"])
df = pd.concat([df, pd.DataFrame(new_row)], ignore_index=False)
print df

Result:

                            col_a  col_b
2014-05-01 18:47:05.069000     34   21.0
2014-05-01 18:47:05.119000     25   32.0
2014-05-02 18:47:05.230000     26   43.0
0                              11    NaN

If I extend "new_row" with a column called "time_frame" and a corresponding time stamp, it will create a new column called "time_stamp", rather than inserting a new value in the index column.

                            col_a  col_b              time_stamp
2014-05-01 18:47:05.069000     34   21.0                     NaT
2014-05-01 18:47:05.119000     25   32.0                     NaT
2014-05-02 18:47:05.230000     26   43.0                     NaT
0                              11    NaN 2014-05-04 18:47:05.487

Any ideas would be greatly appreciated.

Body:
Let's try using the index paramater in the pd.DataFrame construct.

ts = pd.to_datetime("2014-05-04 18:47:05.487", format="%Y-%m-%d %H:%M:%S.%f")
new_row = pd.DataFrame([[11]], columns = ["col_a"], index=[ts])
df1 = pd.concat([df, pd.DataFrame(new_row)], ignore_index=False)
print(df1)

Output:

                        col_a  col_b
2014-05-01 18:47:05.069     34   21.0
2014-05-01 18:47:05.119     25   32.0
2014-05-02 18:47:05.230     26   43.0
2014-05-04 18:47:05.487     11    NaN


问:
Given a string, how to iterate through many regexes to find a match?
Given a string, and a mapping of regexes to integers, I want to find out which integer the string maps to (assume the string will match exactly one of those regexes)

Is it inefficient to just iterate through the hash of regexes, trying each regex against the string, then outputting the value? Certainly I cannot explicitly enumerate all possible string => integer mappings, but it seems bad to try matching each regex in bunch of regexes.

答:
It depends on how complicated your regexes are. If you can put them in capture blocks and have the capture blocks map back to the integers that you need then you should be ok.

For instance:

```<code>(is).*(test)
</code>```

has two capture blocks. This will match:

```<code>This is a test
</code>```

The captures will be 1:is and 2:test

You can quickly try it on http://www.rubular.com/

Body:
It depends on how complicated your regexes are. If you can put them in capture blocks and have the capture blocks map back to the integers that you need then you should be ok.

For instance:

(is).*(test)

has two capture blocks. This will match:

This is a test

The captures will be 1:is and 2:test

You can quickly try it on http://www.rubular.com/

ContentLicense: CC BY-SA 2.5


问:
Case with multiple conditions in SQL Server 2014
I have a table 'FinancialTrans' which has many fields but only 3 of those fields concern me.

```<code>AcctID  TransTypeCode   DateOfTrans  Field 4  Field 5  Field 6....
123     TOLL            2016-06-06
123     TOLL            2016-06-02
123     TOLL            2016-04-28
123     PYMT            2016-03-11
123     TOLL            2015-12-22
123     TOLL            2015-12-22
</code>```

What I need:

I need to print a Flag when there are no TOLL or PYMT in the last 2 years.

So in plain logic:

```<code>(When TransTypeCode is 'TOLL' and the MAX(DateOfTrans) is more than 2 years ago)  AND
(When TransTypeCode is 'PYMT' and the MAX(DateOfTrans) is more than 2 years ago)
</code>```

So my code so far is:

```<code>select *,
(case when max(case when FT.TransTypeCode in ('TOLL', 'PYMT')
                    then FT.DateOfTrans
                    end)
      over (partition by FT.Acctid) >= dateadd(year, -2, getdate())
      then 0 else 1
      end) as MyFlag

from #temp_TableA A
INNER JOIN FinancialTrans FT ON A.AccountId = FT.AcctId
</code>```

But this code brings along all the other fields of the FinancialTrans table and joins each row for that account number with previous table. Hence, I get about 1200 duplicates for each account number.

Question:

 1. How do I NOT get 1200 duplicates for each account number?

 2. How do I get a column which gives a flag when the above two conditions are met.

答:
Use GROUP BY, so you get a single row for account, instead of row_number where you calculate something for every row.

```<code>SELECT A.AcctID,
       MAX(case when FT.TransTypeCode in ('TOLL', 'PYMT')
                 and FT.DateOfTrans >= dateadd(year, -2, getdate())
                then 1
                else 0
           end) as flag

FROM #temp_TableA A
INNER JOIN FinancialTrans FT ON A.AccountId = FT.AcctId
GROUP BY A.AcctID
</code>```

Body:
I have a table 'FinancialTrans' which has many fields but only 3 of those fields concern me.

AcctID  TransTypeCode   DateOfTrans  Field 4  Field 5  Field 6....
123     TOLL            2016-06-06
123     TOLL            2016-06-02
123     TOLL            2016-04-28
123     PYMT            2016-03-11
123     TOLL            2015-12-22
123     TOLL            2015-12-22

What I need:

I need to print a Flag when there are no TOLL or PYMT in the last 2 years.

So in plain logic:

(When TransTypeCode is 'TOLL' and the MAX(DateOfTrans) is more than 2 years ago)  AND
(When TransTypeCode is 'PYMT' and the MAX(DateOfTrans) is more than 2 years ago)

So my code so far is:

select *,
(case when max(case when FT.TransTypeCode in ('TOLL', 'PYMT')
                    then FT.DateOfTrans
                    end)
      over (partition by FT.Acctid) >= dateadd(year, -2, getdate())
      then 0 else 1
      end) as MyFlag

from #temp_TableA A
INNER JOIN FinancialTrans FT ON A.AccountId = FT.AcctId

But this code brings along all the other fields of the FinancialTrans table and joins each row for that account number with previous table. Hence, I get about 1200 duplicates for each account number.

Question:

 1. How do I NOT get 1200 duplicates for each account number?

 2. How do I get a column which gives a flag when the above two conditions are met.

Body:
Use GROUP BY, so you get a single row for account, instead of row_number where you calculate something for every row.

SELECT A.AcctID,
       MAX(case when FT.TransTypeCode in ('TOLL', 'PYMT')
                 and FT.DateOfTrans >= dateadd(year, -2, getdate())
                then 1
                else 0
           end) as flag

FROM #temp_TableA A
INNER JOIN FinancialTrans FT ON A.AccountId = FT.AcctId
GROUP BY A.AcctID


问:
C++ template argument deduction/substitution failed:
I am quite new to C++ and I am experiencing some of its features. In particular, I would like to implement a generic Divide and Conquer procedure that takes as parameter the 'functional code' to solve the problem. Actually what I have in mind is that 'Divide and Conquer' is a higher order function taking as parameters:

a function basecase() to test whether the we reached the base case

a function solvecase() to solve the base case

a function divide() to split the problem in two subproblems

a function conquer() that takes to partial solutions and builds one solution out of the two.

To do this, I used templates: in particular, type A is the type of the input problem, type B is the type of the output problem and type C will probably be a boolean (the result type of the test for base case).

There is also other stuff, like the use of async() to compute concurrently the solution, but this is not the focus of my question.

My question is: why do I get the following message when I compile, complaining about conflicting types ?

```<code>D&C.cpp: In function ‘int main(int, char**)’:
D&C.cpp:67:92: error: no matching function for call to ‘divideAndConquer(std::string&, main(int, char**)::__lambda4&, main(int, char**)::__lambda5&, main(int, char**)::__lambda6&, main(int, char**)::__lambda7&)’
     divideAndConquer(text, lambda_basecase, lambda_divide, lambda_conquer, lambda_solvecase);
                                                                                ^
D&C.cpp:67:92: note: candidate is:
D&C.cpp:10:3: note: template<class A, class B, class C> B divideAndConquer(A, C, A, B, B)
 B divideAndConquer(const A x, C basecase, A divide, B conquer, B solvecase)
   ^
D&C.cpp:10:3: note:   template argument deduction/substitution failed:
D&C.cpp:67:92: note:   deduced conflicting types for parameter ‘A’ (‘std::basic_string<char>’ and ‘main(int, char**)::__lambda5’)
     divideAndConquer(text, lambda_basecase, lambda_divide, lambda_conquer, lambda_solvecase);
</code>```

The Code is the following: basically the idea is to use the Divide and Conquer procedure to look for the instances of a target string into a text, but to be general enough to reuse this schema to solve also other problems (e.g. the Fibonacci numbers).

#include <iostream>
#include <thread>
#include <string>
#include <fstream>
#include <future>

using namespace std;

template <typename A, typename B, typename C>
B divideAndConquer(const A x, C basecase, A divide, B conquer, B solvecase)
{
    if (basecase(x))
    return solvecase(x);

    A probl1 = divide(x,1);
    A probl2 = divide(x, 2);

    auto sol1f = async(divideAndConquer, probl1, basecase, divide, conquer, solvecase);
    B sol2 = divideAndConquer(probl2, basecase, divide, conquer, solvecase);
    B sol1 = sol1f.get();

    return (conquer(sol1, sol2));
}

int splitOnWhitespaces(const string& text, int half, string direction){
    int i=half, N = text.length();
    if (direction.compare("forward")==0){
        while(text[i]!=' ' && text[i] != '\n' && i < N)
            i++;
    }
    else{
         while(text[i]!=' ' && text[i] != '\n' && i >= 0)
            i--;
    if (i<=0 || i==N)
        return -1;
    else
        return i;
    }
}

int main(int argc, char *argv[]){
    string text= "Nel mezzo del cammin di nostra vita mi ritrovai per una selva oscura, che la diritta via era smarrita.";
    string target = "nel";
    int base = 10;
    auto lambda_basecase = [base](string text){return text.length()<=base;};
    auto lambda_divide= [](string text, int subprobl){
         int half = text.length()/2;
         half = splitOnWhitespaces(text, half, "forward");
         if (half==-1)
            half = splitOnWhitespaces(text, half, "backward");
         if (half==-1)
             throw runtime_error("Error splitting the string: no whitespaces\n");
         return ((subprobl==1) ? string(text, 0, half) : string(text, half));
     };
    auto lambda_conquer = [](int count1, int count2){return count1+count2;};
    auto lambda_solvecase = [target](string baseText){
        int found = 0;
        int start = 0;
        int len = target.length();
        while(baseText.find(target, start)!=string::npos ){
            found++;
            int position = baseText.find(target, start);
            start = position + len + 1;
        }
        return found;
    };
    divideAndConquer(text, lambda_basecase, lambda_divide, lambda_conquer, lambda_solvecase);
    return 0;
}
```

I am studying template programming right now, so any help about this issue and any reference to (good) books or webpages explaining the matter would be appreciated.
Thank you in advance!

答:
First of all, a suggestion: give names to template type that are more useful (that suggest the use) than A, B, C, ...

So become more understandable that you have given the same type identifier to completely different things (A for std::string and for a lambda function; B for two different lambda types (and take in count that different lambda are ever different types; also when with the same signature) and for the return value (int, in your example)).

I propose the following version

```<code>template <typename dataT, typename divT, typename conqT, typename baseT,
          typename solvT>
auto divideAndConquer (dataT const & x, baseT basecase, divT divide,
                       conqT conquer, solvT solvecase)
   -> decltype(solvecase(x))
 {
   using retT = decltype(solvecase(x));

   if ( basecase(x) )
      return solvecase(x);

   dataT const probl1 { divide(x, 1) };
   dataT const probl2 { divide(x, 2) };

   auto sol1f = async<retT(*)(dataT const &, baseT, divT, conqT, solvT)>
      (divideAndConquer, probl1, basecase, divide, conquer, solvecase);

   retT sol2 { divideAndConquer(probl2, basecase, divide, conquer,
                                solvecase) };
   retT sol1 { sol1f.get() };

   return conquer(sol1, sol2);
 }
</code>```

Body:
I am quite new to C++ and I am experiencing some of its features. In particular, I would like to implement a generic Divide and Conquer procedure that takes as parameter the 'functional code' to solve the problem. Actually what I have in mind is that 'Divide and Conquer' is a higher order function taking as parameters:

a function basecase() to test whether the we reached the base case

a function solvecase() to solve the base case

a function divide() to split the problem in two subproblems

a function conquer() that takes to partial solutions and builds one solution out of the two.

To do this, I used templates: in particular, type A is the type of the input problem, type B is the type of the output problem and type C will probably be a boolean (the result type of the test for base case).

There is also other stuff, like the use of async() to compute concurrently the solution, but this is not the focus of my question.

My question is: why do I get the following message when I compile, complaining about conflicting types ?

D&C.cpp: In function ‘int main(int, char**)’:
D&C.cpp:67:92: error: no matching function for call to ‘divideAndConquer(std::string&, main(int, char**)::__lambda4&, main(int, char**)::__lambda5&, main(int, char**)::__lambda6&, main(int, char**)::__lambda7&)’
     divideAndConquer(text, lambda_basecase, lambda_divide, lambda_conquer, lambda_solvecase);
                                                                                ^
D&C.cpp:67:92: note: candidate is:
D&C.cpp:10:3: note: template<class A, class B, class C> B divideAndConquer(A, C, A, B, B)
 B divideAndConquer(const A x, C basecase, A divide, B conquer, B solvecase)
   ^
D&C.cpp:10:3: note:   template argument deduction/substitution failed:
D&C.cpp:67:92: note:   deduced conflicting types for parameter ‘A’ (‘std::basic_string<char>’ and ‘main(int, char**)::__lambda5’)
     divideAndConquer(text, lambda_basecase, lambda_divide, lambda_conquer, lambda_solvecase);

The Code is the following: basically the idea is to use the Divide and Conquer procedure to look for the instances of a target string into a text, but to be general enough to reuse this schema to solve also other problems (e.g. the Fibonacci numbers).

#include <iostream>
#include <thread>
#include <string>
#include <fstream>
#include <future>

using namespace std;

template <typename A, typename B, typename C>
B divideAndConquer(const A x, C basecase, A divide, B conquer, B solvecase)
{
    if (basecase(x))
    return solvecase(x);

    A probl1 = divide(x,1);
    A probl2 = divide(x, 2);

    auto sol1f = async(divideAndConquer, probl1, basecase, divide, conquer, solvecase);
    B sol2 = divideAndConquer(probl2, basecase, divide, conquer, solvecase);
    B sol1 = sol1f.get();

    return (conquer(sol1, sol2));
}

int splitOnWhitespaces(const string& text, int half, string direction){
    int i=half, N = text.length();
    if (direction.compare("forward")==0){
        while(text[i]!=' ' && text[i] != '\n' && i < N)
            i++;
    }
    else{
         while(text[i]!=' ' && text[i] != '\n' && i >= 0)
            i--;
    if (i<=0 || i==N)
        return -1;
    else
        return i;
    }
}

int main(int argc, char *argv[]){
    string text= "Nel mezzo del cammin di nostra vita mi ritrovai per una selva oscura, che la diritta via era smarrita.";
    string target = "nel";
    int base = 10;
    auto lambda_basecase = [base](string text){return text.length()<=base;};
    auto lambda_divide= [](string text, int subprobl){
         int half = text.length()/2;
         half = splitOnWhitespaces(text, half, "forward");
         if (half==-1)
            half = splitOnWhitespaces(text, half, "backward");
         if (half==-1)
             throw runtime_error("Error splitting the string: no whitespaces\n");
         return ((subprobl==1) ? string(text, 0, half) : string(text, half));
     };
    auto lambda_conquer = [](int count1, int count2){return count1+count2;};
    auto lambda_solvecase = [target](string baseText){
        int found = 0;
        int start = 0;
        int len = target.length();
        while(baseText.find(target, start)!=string::npos ){
            found++;
            int position = baseText.find(target, start);
            start = position + len + 1;
        }
        return found;
    };
    divideAndConquer(text, lambda_basecase, lambda_divide, lambda_conquer, lambda_solvecase);
    return 0;
}

I am studying template programming right now, so any help about this issue and any reference to (good) books or webpages explaining the matter would be appreciated.
Thank you in advance!

Body:
First of all, a suggestion: give names to template type that are more useful (that suggest the use) than A, B, C, ...

So become more understandable that you have given the same type identifier to completely different things (A for std::string and for a lambda function; B for two different lambda types (and take in count that different lambda are ever different types; also when with the same signature) and for the return value (int, in your example)).

I propose the following version

template <typename dataT, typename divT, typename conqT, typename baseT,
          typename solvT>
auto divideAndConquer (dataT const & x, baseT basecase, divT divide,
                       conqT conquer, solvT solvecase)
   -> decltype(solvecase(x))
 {
   using retT = decltype(solvecase(x));

   if ( basecase(x) )
      return solvecase(x);

   dataT const probl1 { divide(x, 1) };
   dataT const probl2 { divide(x, 2) };

   auto sol1f = async<retT(*)(dataT const &, baseT, divT, conqT, solvT)>
      (divideAndConquer, probl1, basecase, divide, conquer, solvecase);

   retT sol2 { divideAndConquer(probl2, basecase, divide, conquer,
                                solvecase) };
   retT sol1 { sol1f.get() };

   return conquer(sol1, sol2);
 }


问:
How do I access a public page variable of the only page from the master page?
I have a page - only ONE page for the entire site:

```<code>using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class CMSPageViewer : System.Web.UI.Page
{
    public int myPageID;

    protected void Page_PreInit(object sender, EventArgs e)
    {
         // Get stuff from the database

         myPageID = 1;

         // Set the Page.MasterPageFile
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // Fill in the page contents
        // This looks for and fills in asp:ContentPlaceHolder controls based on ID
    }
}
</code>```

And the master page:

```<code>using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Standard_Page : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int myID = (this.Page as CMSPageViewer).myPageID;
    }
}
</code>```

How can I access ID from the MasterPage that is used?

Casting the page doesn't seem to work. I get the following error:

```<code>Compiler Error Message: CS0246: The type or namespace name 'CMSPageViewer' could not be found (are you missing a using directive or an assembly reference?)
</code>```

答:
In your master page use this:</p>

```<code>(this.Page as CMSPageViewer ).ID
</code>```

Body:
I have a page - only ONE page for the entire site:

using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class CMSPageViewer : System.Web.UI.Page
{
    public int myPageID;

    protected void Page_PreInit(object sender, EventArgs e)
    {
         // Get stuff from the database

         myPageID = 1;

         // Set the Page.MasterPageFile
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // Fill in the page contents
        // This looks for and fills in asp:ContentPlaceHolder controls based on ID
    }
}

And the master page:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Standard_Page : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int myID = (this.Page as CMSPageViewer).myPageID;
    }
}

How can I access ID from the MasterPage that is used?

Casting the page doesn't seem to work. I get the following error:

Compiler Error Message: CS0246: The type or namespace name 'CMSPageViewer' could not be found (are you missing a using directive or an assembly reference?)

Body:
In your master page use this:

(this.Page as CMSPageViewer ).ID


问:
Writing FILE* through pipe
I have two file open in two different processes. There's a pipe connecting the two. Is it possible to write directly from one file to another? Especially if the process reading doesn't know the size of the file it's trying to read?

I was hoping to do something like this

```<code>#define length 100
int main(){
  int frk = fork();
  int pip[2];
  pipe(pip);
  if (frk==0){ //child
    FILE* fp fopen("file1", "r");
    write(pip[1],fp,length);
  }
  else {
    FILE* fp fopen("file2", "w");
    read(pip[0],fp,length);
}
</code>```

答:
Is it possible to write directly from one file to another?

C does not provide any mechanism for that, and it seems like it would require specialized hardware support.  The standard I/O paradigm is that data get read from their source into memory or written from memory to their destination.  That pesky "memory" in the middle means copying from one file to another cannot be direct.

Of course, you can write a function or program that performs such a copy, hiding the details from you.  This is what the cp command does, after all,  but the C standard library does not contain a function for that purpose.

Especially if the process reading doesn't know the size of the file it's trying to read?

That bit isn't very important.  One simply reads and then writes (only) what one has read, repeating until there is nothing more to read.  "Nothing more to read" means that a read attempt indicates by its return value that the end of the file has been reached.

If you want one process to read one file and the other to write that data to another file, using a pipe to convey data between the two, then you need both processes to implement that pattern.  One reads from the source file and writes to the pipe, and the other reads from the pipe and writes to the destination file.

Special note: for the process reading from the pipe to detect EOF on that pipe, the other end has to be closed, in both processes.  After the fork, each process can and should close the pipe end that it doesn't intend to use.  The one using the write end then closes that end when it has nothing more to write to it.

Title: Writing FILE* through pipe

Body:
I have two file open in two different processes. There's a pipe connecting the two. Is it possible to write directly from one file to another? Especially if the process reading doesn't know the size of the file it's trying to read?

I was hoping to do something like this

#define length 100
int main(){
  int frk = fork();
  int pip[2];
  pipe(pip);
  if (frk==0){ //child
    FILE* fp fopen("file1", "r");
    write(pip[1],fp,length);
  }
  else {
    FILE* fp fopen("file2", "w");
    read(pip[0],fp,length);
}


问:
Make electron app smaller?
I just recently built an electron app and packaged it using electron-packager. The .exe file is 55,000kb and the rest of the folder is quite bulky as well. Is there any way to take down the size of this application at all?</p>

答:
A somewhat helpful post from that github thread suggests removing unnecessary node modules via electron-packager. It also offers a bit more explanation on why files are so large.

You can zip your app and if you're using electron-packager you can ignore some node modules that you don't need when the app is running, this makes it a bit smaller. For instance I have a 37MB zipped Electron app (Note Windows version is much larger as it contains a copy of Git). But Electron will always have a large part of Chrome in it so there is only so much that can be done. Electron itself right now is ~33MB.

Title: Make electron app smaller?


问:
R - Better organize program workflow and processes using functions
I am working on a data mining project which is currently composed of several script.

What I would like to do is to better organize the processes executed in each script by using functions.

One of the many example can be the following:

in the script dedicated to clustering I apply a filter for outliers

```<code>library(dplyr)

myDF <-
        myDF %>%
        filter(distance > 680) %>%
        filter(time > 120) %>%
        filter(speed > 5)
</code>```

What I am looking for is the possibility of "wrapping" this process inside a small "node". In my mind, the thing closest to an Enterprise Miner node in R is a function. Therefore:

```<code>outlier_filter <- function() {
            myDF %>%
            filter(distance > 680) %>%
            filter(time > 120) %>%
            filter(speed > 5)
}
</code>```

However, when I run:

```<code>outlier_filter
</code>```

It simply prints the code on the console. Instead I would like it to apply act like a node to filter the outliers from the DF.

I am open to other suggestions, however, the main point is that by simply executing a work, I want it to apply its effect to the data frame I am working on.

Another example could be the "node"/function create_features which when run, executes the code to add the new variables to my dataframe.

Hope I was clear, Thank you.

答:
You are just printing the function, you probably want to call it using outlier_filter()

However, this could only work by using side effects. Usually this is not something you want, a solution could be:

```<code>outlier_filter <- function(df) {
  df %>%
    filter(distance > 680) %>%
    filter(time > 120) %>%
    filter(speed > 5) %>%
    return()
}
</code>```

You can call the function using myDF <- outlier_function(myDF)

Body:
I am working on a data mining project which is currently composed of several script.

What I would like to do is to better organize the processes executed in each script by using functions.

One of the many example can be the following:

in the script dedicated to clustering I apply a filter for outliers

library(dplyr)

myDF <-
        myDF %>%
        filter(distance > 680) %>%
        filter(time > 120) %>%
        filter(speed > 5)

What I am looking for is the possibility of "wrapping" this process inside a small "node". In my mind, the thing closest to an Enterprise Miner node in R is a function. Therefore:

outlier_filter <- function() {
            myDF %>%
            filter(distance > 680) %>%
            filter(time > 120) %>%
            filter(speed > 5)
}

However, when I run:

outlier_filter

It simply prints the code on the console. Instead I would like it to apply act like a node to filter the outliers from the DF.

I am open to other suggestions, however, the main point is that by simply executing a work, I want it to apply its effect to the data frame I am working on.

Another example could be the "node"/function create_features which when run, executes the code to add the new variables to my dataframe.

Hope I was clear, Thank you.

Body:
You are just printing the function, you probably want to call it using outlier_filter()

However, this could only work by using side effects. Usually this is not something you want, a solution could be:

outlier_filter <- function(df) {
  df %>%
    filter(distance > 680) %>%
    filter(time > 120) %>%
    filter(speed > 5) %>%
    return()
}

You can call the function using myDF <- outlier_function(myDF)


问:
Can't Export Symbol and Color of CATIA points
This is my first post asking for help with code I've written, please ask for clarification if you need it!
   I am trying to export point data from CATIA V5. Currently I have a macro which takes user selection of a Geometric Set of points and exports position but I also want to export the symbol type and color.
   The CATIA given example code shows how to access visual properties as VisProperties with one item selected and I've tried to adapt that to take my automation bodies. My question is, how do I export color and symbol type from automation bodies? Here is what I have so far:

```<code>Language="VBSCRIPT"

Sub CATMain()

Dim oPartDoc As Part
On Error Resume Next
Set oPartDoc = CATIA.ActiveDocument.Part
If Err.Number <> 0 Then
Message = MsgBox("Sorry, This script works with a CATPart as Active
document", vbCritical, "Error")
Exit Sub
End If

    ' What do want to select

    Dim EnableSelectionFor(0)
    EnableSelectionFor(0) = "HybridBody"

    ' Reset the Selection

    Set sSEL = CATIA.ActiveDocument.Selection
    sSEL.Clear

 ' Define Selection

    MsgBox "Please Select the Geometrical Set that contains Points"

    UserSelection = sSEL.SelectElement2(EnableSelectionFor,  "Please select
another Geometrical Set", False)
    ' Evaluation if the selectio is correct or not
    If UserSelection <> "Normal" Then
        MsgBox "Error with the selection"
        Exit Sub
Else
Set ohybridbody = sSEL.Item(1).Value

    MsgBox "The Geometrical Set selected is : " & ohybridbody.Name

    End If
'//Defining collection arrays

ReDim acoord(2)
Dim symbol
Dim r, g, b

'//initializing symbol and color collection arrays, may be wrong?

symbol=CLng(0)
r=CLng(0)
g=CLng(0)
b=CLng(0)

'---------------------------------------------------------------------------
-----
'   The location of the result file
'---------------------------------------------------------------------------
-----
Dim filename As String

filename = CATIA.FileSelectionBox("Where do you want to save the result
file", "*.txt", CatFileSelectionModeSave)

Set Datos = CATIA.FileSystem.CreateFile(filename & ".txt" , True)

Set ostream = Datos.OpenAsTextStream("ForAppending")

ostream.Write ("Points Extraction from " & oPartDoc.Name & ".CATPart" &
Chr(10))
ostream.Write (" "& Chr(10))
ostream.Write ("The selected Geometrical Set was : " & ohybridbody.Name &
Chr(10))
ostream.Write (" "& Chr(10))

'////Selection of points within geometrical set
Set oshapes = ohybridbody.HybridShapes

'///this part may be wrong
Set visproperties1=oshapes.VisProperties

'///Loop to run on each point in geometrical set
For i = 1 To oshapes.Count
oshapes.Item(i).GetCoordinates acoord

'////Trying to access visual properties , def wrong here
visproperties1.Item(i).GetSymbolType symbol
visproperties1.Item(i).GetRealColor r, g, b

'/////Writing to file

Set reference1 = oshapes.Item(i)

ostream.Write (reference1.Name & Chr(0009) & acoord(0) & Chr(0009) &
acoord(1) & Chr(0009) & acoord(2) & Chr(0009) & symbol & Chr(0009) & r &
Chr(0009) & g & Chr(0009) & b & Chr(0009) & Chr(10))

Next

ostream.Close

MsgBox  "Points Exported :" & (i-1) & "x" & Chr(10) & Chr(10) & "Please
Check the following file for result : " &  chr(10) &  chr(10) & filename &
chr(10)&  chr(10) & "Process finished"

End Sub
</code>```

答:
VisProperties is a property of the Selection object.

So what you need to do is after your initial selection, put all the point objects into selection one by one to get the information.

So, taking up from after you select the geometrical set, something like this:

```<code>Set ohybridbody = sSEL.Item(1).Value

'clear the selection
sSel.Clear

for i = 1 to oHybridBody.HybridShapes.Count
    Set obj = oHybridBody.HybridShapes.Item(i)
    obj.GetCoordiates coords
    sSel.Add obj
    sSel.VisProperties.GetSymbolType symbol
    sSel.VisProperties.GetRealColor r, g, b
    ....  output your results....
    sSel.Clear
Next
</code>```

This assumes that all you have are points in your geometrical set. If not you have to filter each object in the HybridShapes collection for points only.

Body:
This is my first post asking for help with code I've written, please ask for clarification if you need it!
   I am trying to export point data from CATIA V5. Currently I have a macro which takes user selection of a Geometric Set of points and exports position but I also want to export the symbol type and color.
   The CATIA given example code shows how to access visual properties as VisProperties with one item selected and I've tried to adapt that to take my automation bodies. My question is, how do I export color and symbol type from automation bodies? Here is what I have so far:

Language="VBSCRIPT"

Sub CATMain()

Dim oPartDoc As Part
On Error Resume Next
Set oPartDoc = CATIA.ActiveDocument.Part
If Err.Number <> 0 Then
Message = MsgBox("Sorry, This script works with a CATPart as Active
document", vbCritical, "Error")
Exit Sub
End If

    ' What do want to select

    Dim EnableSelectionFor(0)
    EnableSelectionFor(0) = "HybridBody"

    ' Reset the Selection

    Set sSEL = CATIA.ActiveDocument.Selection
    sSEL.Clear

 ' Define Selection

    MsgBox "Please Select the Geometrical Set that contains Points"

    UserSelection = sSEL.SelectElement2(EnableSelectionFor,  "Please select
another Geometrical Set", False)
    ' Evaluation if the selectio is correct or not
    If UserSelection <> "Normal" Then
        MsgBox "Error with the selection"
        Exit Sub
Else
Set ohybridbody = sSEL.Item(1).Value

    MsgBox "The Geometrical Set selected is : " & ohybridbody.Name

    End If
'//Defining collection arrays

ReDim acoord(2)
Dim symbol
Dim r, g, b

'//initializing symbol and color collection arrays, may be wrong?

symbol=CLng(0)
r=CLng(0)
g=CLng(0)
b=CLng(0)

'---------------------------------------------------------------------------
-----
'   The location of the result file
'---------------------------------------------------------------------------
-----
Dim filename As String

filename = CATIA.FileSelectionBox("Where do you want to save the result
file", "*.txt", CatFileSelectionModeSave)

Set Datos = CATIA.FileSystem.CreateFile(filename & ".txt" , True)

Set ostream = Datos.OpenAsTextStream("ForAppending")

ostream.Write ("Points Extraction from " & oPartDoc.Name & ".CATPart" &
Chr(10))
ostream.Write (" "& Chr(10))
ostream.Write ("The selected Geometrical Set was : " & ohybridbody.Name &
Chr(10))
ostream.Write (" "& Chr(10))

'////Selection of points within geometrical set
Set oshapes = ohybridbody.HybridShapes

'///this part may be wrong
Set visproperties1=oshapes.VisProperties

'///Loop to run on each point in geometrical set
For i = 1 To oshapes.Count
oshapes.Item(i).GetCoordinates acoord

'////Trying to access visual properties , def wrong here
visproperties1.Item(i).GetSymbolType symbol
visproperties1.Item(i).GetRealColor r, g, b

'/////Writing to file

Set reference1 = oshapes.Item(i)

ostream.Write (reference1.Name & Chr(0009) & acoord(0) & Chr(0009) &
acoord(1) & Chr(0009) & acoord(2) & Chr(0009) & symbol & Chr(0009) & r &
Chr(0009) & g & Chr(0009) & b & Chr(0009) & Chr(10))

Next

ostream.Close

MsgBox  "Points Exported :" & (i-1) & "x" & Chr(10) & Chr(10) & "Please
Check the following file for result : " &  chr(10) &  chr(10) & filename &
chr(10)&  chr(10) & "Process finished"

End Sub

Body:
VisProperties is a property of the Selection object.

So what you need to do is after your initial selection, put all the point objects into selection one by one to get the information.

So, taking up from after you select the geometrical set, something like this:

Set ohybridbody = sSEL.Item(1).Value

'clear the selection
sSel.Clear

for i = 1 to oHybridBody.HybridShapes.Count
    Set obj = oHybridBody.HybridShapes.Item(i)
    obj.GetCoordiates coords
    sSel.Add obj
    sSel.VisProperties.GetSymbolType symbol
    sSel.VisProperties.GetRealColor r, g, b
    ....  output your results....
    sSel.Clear
Next

This assumes that all you have are points in your geometrical set. If not you have to filter each object in the HybridShapes collection for points only.


问:
SQL-Calculate percentages from database table values
Im trying to calculate the percentages of selected fields from tables. Within the fields that data is numeric but I want to show the percentage value. Please help.</p>

```<code>    private void btnpics_Click(object sender, EventArgs e)
    {
        try
        {
            myCon.Open();
            string queryString = "SELECT FoodType.Description,FoodType.Calories, FoodType.Carbohydrate, FoodType.Fat, FoodType.Protein FROM [FoodType], [Meal] WHERE (Meal.UserID =" + userid.Text + ") AND (Meal.MealDate =" + date.Text + ");";
            MessageBox.Show(queryString);
            loadDataGrid(queryString);
        }
        catch (Exception ex) { MessageBox.Show(ex.Message); }
    }
</code>```

答:
Same Concept in MSSQL</p>

```<code>SELECT
  FoodType.Description,
  FoodType.Calories,
  FoodType.Carbohydrate,
  FoodType.Fat,
  FoodType.Protein,
  FoodType.Calories / A.SumCalories * 100 AS CaloriesPercentage,
  FoodType.Carbohydrate / A.SumCarbohydrate * 100 AS CarbohydratePercentage,
  FoodType.Fat / A.SumCalories * 100 AS FatPercentage,
  FoodType.Protein / A.SumProtein * 100 AS ProteinPercentage
FROM [FoodType]
JOIN [Meal] ON FoodType.ID = Meal.FoodTypeID --Not sure on your table schema here.
JOIN
(
  SELECT
    FoodType.Description,
    SUM(FoodType.Calories) AS SumCalories,
    SUM(FoodType.Carbohydrate) AS SumCarbohydrate,
    SUM(FoodType.Fat) AS SumFat,
    SUM(FoodType.Protein) AS SumProtein
  FROM [FoodType],[Meal]
  WHERE (Meal.UserID =" + userid.Text + ") AND (Meal.MealDate =" + date.Text + ")
  GROUP BY FoodType.Description
) A ON FoodType.Description = A.Description --You should use FoodTypeID if it exists
WHERE (Meal.UserID =" + userid.Text + ") AND (Meal.MealDate =" + date.Text + ")
</code>```

Body:
Im trying to calculate the percentages of selected fields from tables. Within the fields that data is numeric but I want to show the percentage value. Please help.

    private void btnpics_Click(object sender, EventArgs e)
    {
        try
        {
            myCon.Open();
            string queryString = "SELECT FoodType.Description,FoodType.Calories, FoodType.Carbohydrate, FoodType.Fat, FoodType.Protein FROM [FoodType], [Meal] WHERE (Meal.UserID =" + userid.Text + ") AND (Meal.MealDate =" + date.Text + ");";
            MessageBox.Show(queryString);
            loadDataGrid(queryString);
        }
        catch (Exception ex) { MessageBox.Show(ex.Message); }
    }

Body:
Same Concept in MSSQL

SELECT
  FoodType.Description,
  FoodType.Calories,
  FoodType.Carbohydrate,
  FoodType.Fat,
  FoodType.Protein,
  FoodType.Calories / A.SumCalories * 100 AS CaloriesPercentage,
  FoodType.Carbohydrate / A.SumCarbohydrate * 100 AS CarbohydratePercentage,
  FoodType.Fat / A.SumCalories * 100 AS FatPercentage,
  FoodType.Protein / A.SumProtein * 100 AS ProteinPercentage
FROM [FoodType]
JOIN [Meal] ON FoodType.ID = Meal.FoodTypeID --Not sure on your table schema here.
JOIN
(
  SELECT
    FoodType.Description,
    SUM(FoodType.Calories) AS SumCalories,
    SUM(FoodType.Carbohydrate) AS SumCarbohydrate,
    SUM(FoodType.Fat) AS SumFat,
    SUM(FoodType.Protein) AS SumProtein
  FROM [FoodType],[Meal]
  WHERE (Meal.UserID =" + userid.Text + ") AND (Meal.MealDate =" + date.Text + ")
  GROUP BY FoodType.Description
) A ON FoodType.Description = A.Description --You should use FoodTypeID if it exists
WHERE (Meal.UserID =" + userid.Text + ") AND (Meal.MealDate =" + date.Text + ")


问:
When should you use a mutex over a channel?
For the past few weeks I've been wrestling with one (not-so) simple question:

When is it best to use a sync.Mutex and, conversely, when is it best use a chan?

It seems that for a lot of problems either strategy is interchangeable with the other - and that's just the problem!

Take this video found in the Golang documentation. Below, I've taken the liberty to dictate the code in the playground and also translate it to a sync.Mutex equivalent.

Is there a certain problem - encountered in the real world - that warrants the use of one other?

Notes:

I am a huge fan of this use of chan and struggle to think of a more elegant implementation using sync.Mutex.

It's worth noting that the chan implementation does more work in the same time (reaches 12)*

Playgrounds:

Chan implementation

Mutex implementation

Ping/pong with chan:

```<code>package main

import (
    "fmt"
    "time"
)

type Ball struct { hits int }

func main() {
    table := make(chan *Ball)
    go player("ping", table)
    go player("pong", table)

    table <- new(Ball)
    time.Sleep(1 * time.Second)
    <-table
}

func player(name string, table chan *Ball) {
    for {
        ball := <-table
        ball.hits++
        fmt.Println(name, ball.hits)
        time.Sleep(100 * time.Millisecond)
        table <- ball
    }
}
</code>```

Ping/pong with sync.Mutex:

```<code>package main

import (
    "fmt"
    "time"
    "sync"
)

type Ball struct { hits int }

var m =  sync.Mutex{}

func main() {
    ball := new(Ball)
    go player("ping", ball)
    go player("pong", ball)

    time.Sleep(1 * time.Second)
}

func player(name string, ball *Ball) {
    for {
        m.Lock()
        ball.hits++
        fmt.Println(name, ball.hits)
        time.Sleep(100 * time.Millisecond)
        m.Unlock()

    }
}
</code>```

答:
In most cases prefer channels, in some sync.Mutex, (and pay attention to sync/atomic and sync.Once too):

Use channels if you need to:

limit concurrent tasks number (e.g. number of running goroutines) using buffered channel capacity (and length)

transferring ownership of an object (one and only one goroutine writes to it while no other goroutines reading it)

coordination, synchronization, sending signals, and data.

Use primitives if:

guarding internal state of a struct (with e.g. sync.Mutex)

performance critical (algorithm and use case dependent, not a general rule)

Note: Concurrent safe coding needs more care and slow careful timing analysis - I've seen subtle concurrent bugs in production codes, which is not easy to detect - even with the Go race detector.

Micro-benchmark

To make it clear, imagine we need a one second counter, so in the following examples we count for a second then print the counter value to see how fast it counts:

```<code>No |         Count |       Method
------------------------------------------------------
 1 |     17_729_027 | Using sync.RWMutex for increment
 2 |     12_180_741 | Using channel for increment
 3 |    106_743_095 | Using channel for timer
 4 |    104_178_671 | Using time.AfterFunc and channel sync
</code>```

Note: go version go1.13.5 linux/amd64

Codes:

1 - Using sync.RWMutex for increment:

```<code>package main

import (
    "sync"
    "time"
)

func main() {
    var i rwm
    go func() {
        for {
            i.inc() // free running counter
        }
    }()
    time.Sleep(1 * time.Second)
    println(i.read()) // sampling the counter
}

type rwm struct {
    sync.RWMutex
    i int
}

func (l *rwm) inc() {
    l.Lock()
    defer l.Unlock()
    l.i++
}
func (l *rwm) read() int {
    l.RLock()
    defer l.RUnlock()
    return l.i
}
</code>```

2 - Using channel for increment:

```<code>package main

import (
    "time"
)

func main() {
    ch := make(chan int, 1)
    ch <- 1
    timeout := time.NewTimer(1 * time.Second)
loop:
    for {
        select {
        case <-timeout.C:
            timeout.Stop()
            break loop
        default:
            ch <- 1 + <-ch
        }
    }

    println(<-ch)
}
</code>```

3 - Using channel for timer:

```<code>package main

import "time"

func main() {
    ch := make(chan int)
    go func() {
        timeout := time.NewTimer(1 * time.Second)
        defer timeout.Stop()
        i := 1
        for {
            select {
            case <-timeout.C:
                ch <- i
                return
            default:
                i++
            }
        }
    }()

    println(<-ch)
}
</code>```

4 - Using time.AfterFunc and channel sync:

```<code>package main

import (
    "fmt"
    "time"
)

func main() {
    d := 1 * time.Second
    i := uint64(0)
    ch := make(chan struct{})

    time.AfterFunc(d, func() {
        close(ch)
    })

loop:
    for {
        select {
        case <-ch:
            break loop
        default:
            i++
        }
    }

    fmt.Println(i) // 104_178_671
}

</code>```

Body:
For the past few weeks I've been wrestling with one (not-so) simple question:

When is it best to use a sync.Mutex and, conversely, when is it best use a chan?

It seems that for a lot of problems either strategy is interchangeable with the other - and that's just the problem!

Take this video found in the Golang documentation. Below, I've taken the liberty to dictate the code in the playground and also translate it to a sync.Mutex equivalent.

Is there a certain problem - encountered in the real world - that warrants the use of one other?

Notes:

I am a huge fan of this use of chan and struggle to think of a more elegant implementation using sync.Mutex.

It's worth noting that the chan implementation does more work in the same time (reaches 12)*

Playgrounds:

Chan implementation

Mutex implementation

Ping/pong with chan:

package main

import (
    "fmt"
    "time"
)

type Ball struct { hits int }

func main() {
    table := make(chan *Ball)
    go player("ping", table)
    go player("pong", table)

    table <- new(Ball)
    time.Sleep(1 * time.Second)
    <-table
}

func player(name string, table chan *Ball) {
    for {
        ball := <-table
        ball.hits++
        fmt.Println(name, ball.hits)
        time.Sleep(100 * time.Millisecond)
        table <- ball
    }
}

Ping/pong with sync.Mutex:

package main

import (
    "fmt"
    "time"
    "sync"
)

type Ball struct { hits int }

var m =  sync.Mutex{}

func main() {
    ball := new(Ball)
    go player("ping", ball)
    go player("pong", ball)

    time.Sleep(1 * time.Second)
}

func player(name string, ball *Ball) {
    for {
        m.Lock()
        ball.hits++
        fmt.Println(name, ball.hits)
        time.Sleep(100 * time.Millisecond)
        m.Unlock()

    }
}

Body:
In most cases prefer channels, in some sync.Mutex, (and pay attention to sync/atomic and sync.Once too):

Use channels if you need to:

limit concurrent tasks number (e.g. number of running goroutines) using buffered channel capacity (and length)

transferring ownership of an object (one and only one goroutine writes to it while no other goroutines reading it)

coordination, synchronization, sending signals, and data.

Use primitives if:

guarding internal state of a struct (with e.g. sync.Mutex)

performance critical (algorithm and use case dependent, not a general rule)

Note: Concurrent safe coding needs more care and slow careful timing analysis - I've seen subtle concurrent bugs in production codes, which is not easy to detect - even with the Go race detector.

Micro-benchmark

To make it clear, imagine we need a one second counter, so in the following examples we count for a second then print the counter value to see how fast it counts:

No |         Count |       Method
------------------------------------------------------
 1 |     17_729_027 | Using sync.RWMutex for increment
 2 |     12_180_741 | Using channel for increment
 3 |    106_743_095 | Using channel for timer
 4 |    104_178_671 | Using time.AfterFunc and channel sync

Note: go version go1.13.5 linux/amd64

Codes:

1 - Using sync.RWMutex for increment:

package main

import (
    "sync"
    "time"
)

func main() {
    var i rwm
    go func() {
        for {
            i.inc() // free running counter
        }
    }()
    time.Sleep(1 * time.Second)
    println(i.read()) // sampling the counter
}

type rwm struct {
    sync.RWMutex
    i int
}

func (l *rwm) inc() {
    l.Lock()
    defer l.Unlock()
    l.i++
}
func (l *rwm) read() int {
    l.RLock()
    defer l.RUnlock()
    return l.i
}

2 - Using channel for increment:

package main

import (
    "time"
)

func main() {
    ch := make(chan int, 1)
    ch <- 1
    timeout := time.NewTimer(1 * time.Second)
loop:
    for {
        select {
        case <-timeout.C:
            timeout.Stop()
            break loop
        default:
            ch <- 1 + <-ch
        }
    }

    println(<-ch)
}

3 - Using channel for timer:

package main

import "time"

func main() {
    ch := make(chan int)
    go func() {
        timeout := time.NewTimer(1 * time.Second)
        defer timeout.Stop()
        i := 1
        for {
            select {
            case <-timeout.C:
                ch <- i
                return
            default:
                i++
            }
        }
    }()

    println(<-ch)
}

4 - Using time.AfterFunc and channel sync:

package main

import (
    "fmt"
    "time"
)

func main() {
    d := 1 * time.Second
    i := uint64(0)
    ch := make(chan struct{})

    time.AfterFunc(d, func() {
        close(ch)
    })

loop:
    for {
        select {
        case <-ch:
            break loop
        default:
            i++
        }
    }

    fmt.Println(i) // 104_178_671
}

ContentLicense: CC BY-SA 4.0


问:
Change text color of a specific column for QTreeView
I have widget that inherits from QTreeView, and I want to change the text color, but only for a specific column. Currently I set the stylesheet, so the entire row changes the text color to red when the item is selected.

```<code>QTreeView::item:selected {color: red}
</code>```

I want to change only the color of the first column when the item is selected. I know how to change the colour for specific columns (using ForegroundRole on the model and checking the index column), but I don't know how to do check if the index is selected in the model.

答:
You can use a delegate for that:</p>

```<code>class MyDelegate : public QStyledItemDelegate {
public:
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
        if (option.state & QStyle::State_Selected) {
            QStyleOptionViewItem optCopy = option;
            optCopy.palette.setColor(QPalette::Foreground, Qt::red);
        }
        QStyledItemDelegate::paint(painter, optCopy, index);
    }
}

myTreeWidget->setItemDelegateForColumn(0, new MyDelegate);
</code>```

Body:
I have widget that inherits from QTreeView, and I want to change the text color, but only for a specific column. Currently I set the stylesheet, so the entire row changes the text color to red when the item is selected.

QTreeView::item:selected {color: red}

I want to change only the color of the first column when the item is selected. I know how to change the colour for specific columns (using ForegroundRole on the model and checking the index column), but I don't know how to do check if the index is selected in the model.

Body:
You can use a delegate for that:

class MyDelegate : public QStyledItemDelegate {
public:
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
        if (option.state & QStyle::State_Selected) {
            QStyleOptionViewItem optCopy = option;
            optCopy.palette.setColor(QPalette::Foreground, Qt::red);
        }
        QStyledItemDelegate::paint(painter, optCopy, index);
    }
}

myTreeWidget->setItemDelegateForColumn(0, new MyDelegate);


问:
Java Error: NullPointerException due to missing Constructor(s)
I'm trying to access a method within another class, but I already have some constructors in said class which is throwing up an error when I try to create an instance in another class.

EDIT: I know I need to fill in a constructor, but I don't know what to put in it. Do I create another JFrame in the ArrayControl class or what?

This is the error I get when I run it:

```<code>Exception in thread "main" java.lang.NullPointerException
at Position.ArrayControl.updatePosition(ArrayControl.java:10)
at Display.Display.<init>(Display.java:39)
at Main.Game.<init>(Game.java:19)
at Main.Launch.main(Launch.java:6)
</code>```

This is where the error happens:

```<code>public class ArrayControl{
 Display display = new Display(); // Error here asking for a JFrame or String, int, int

public void updatePosition(String name, int x, int y){
    display.updateGrid(name, x, y, display.getGrid());
    }
}
</code>```

The "Display" class I'm trying to access:

```<code>public class Display {
public JPanel panel = new JPanel();
public ArrayControl arrayC = new ArrayControl();
public JFrame frame;
JLabel[][] grid= new JLabel[5][5];

public JFrame getFrame() {
    return frame;
}

public Display(JFrame frame){
    this.frame = frame;
}

private String title;
private int width, height;
Color sky = new Color(137, 182, 255);
Color enemyPortal = new Color(154, 91, 193);

//Creating a display function that takes in a title, the width (pixels) and height (pixels)
public Display(String title, int width, int height){
    this.title = title;
    this.width = width;
    this.height = height;

    createDisplay();
    arrayC.updatePosition("Test", 2, 3);
}
</code>```

I realise this may be a silly question and the answer is glaring me in the face, but all help is appreciated.
Thank you.

答:
You created a constructor

public Display(JFrame frame){
    this.frame = frame;
}

but didn't fill in the constructor (JFrame) when creating an display object.

Body:
I'm trying to access a method within another class, but I already have some constructors in said class which is throwing up an error when I try to create an instance in another class.

EDIT: I know I need to fill in a constructor, but I don't know what to put in it. Do I create another JFrame in the ArrayControl class or what?

This is the error I get when I run it:

Exception in thread "main" java.lang.NullPointerException
at Position.ArrayControl.updatePosition(ArrayControl.java:10)
at Display.Display.<init>(Display.java:39)
at Main.Game.<init>(Game.java:19)
at Main.Launch.main(Launch.java:6)

This is where the error happens:

public class ArrayControl{
 Display display = new Display(); // Error here asking for a JFrame or String, int, int

public void updatePosition(String name, int x, int y){
    display.updateGrid(name, x, y, display.getGrid());
    }
}

The "Display" class I'm trying to access:

public class Display {
public JPanel panel = new JPanel();
public ArrayControl arrayC = new ArrayControl();
public JFrame frame;
JLabel[][] grid= new JLabel[5][5];

public JFrame getFrame() {
    return frame;
}

public Display(JFrame frame){
    this.frame = frame;
}

private String title;
private int width, height;
Color sky = new Color(137, 182, 255);
Color enemyPortal = new Color(154, 91, 193);

//Creating a display function that takes in a title, the width (pixels) and height (pixels)
public Display(String title, int width, int height){
    this.title = title;
    this.width = width;
    this.height = height;

    createDisplay();
    arrayC.updatePosition("Test", 2, 3);
}

I realise this may be a silly question and the answer is glaring me in the face, but all help is appreciated.
Thank you.


答: You are calling arrayC.updatePosition from Display's constructor, at which point arrayC.display is still null, because the instance that it is supposed to be assigned to is, well, still under construction.

Title: Java Error: NullPointerException due to missing Constructor(s)


问:
Always eager load association with entity
Is it possible to always eager load an association when an entity is loaded. For example

```<code>class Book
  has_many :chapters
end

class Chapters
  belongs_to :book
end

book = Book.find_by_title('Moby Dick')
</code>```

I know that you can eager load in the call to find ie. book = Book.find_by_title( 'Moby Dick', :include => :chapters) but in this case I know that any time I find a book I always want the chapters eager loaded without needing to remember the :include => parameter.

答:
You can include a "default_scope" in your model.

For Rails 4:

```<code>class Book
  has_many :chapters
  default_scope { includes(:chapters) }
end
</code>```

For Rails 3:

```<code>class Book
  has_many :chapters
  default_scope includes(:chapters)
end
</code>```

For Rails 2:

```<code>class Book
  has_many :chapters
  default_scope :include => :chapters
end
</code>```

Body:
Is it possible to always eager load an association when an entity is loaded. For example

class Book
  has_many :chapters
end

class Chapters
  belongs_to :book
end

book = Book.find_by_title('Moby Dick')

I know that you can eager load in the call to find ie. book = Book.find_by_title( 'Moby Dick', :include => :chapters) but in this case I know that any time I find a book I always want the chapters eager loaded without needing to remember the :include => parameter.

Body:
You can include a "default_scope" in your model.

For Rails 4:

class Book
  has_many :chapters
  default_scope { includes(:chapters) }
end

For Rails 3:

class Book
  has_many :chapters
  default_scope includes(:chapters)
end

For Rails 2:

class Book
  has_many :chapters
  default_scope :include => :chapters
end