问:
ASP.NET Core MVC Error - Edit Delete Not Working
I reverse engineered a table from and exiting database. Then added a controller with all scaffolding for views and context. My table does not have a traditional primary key such as "Id" it has a complex key. However, I do have an Id column which is unique.

When the views got created, the set up was correct. I noticed that the out of the box "Edit, Details and Delete" had action links commented out. I removed the comments and pointed the Model items to the "Id" field.

My "Id" field is a guid but I don't think that is a problem. When I click the edit link on the view, I receive a page not found. Any help would be greatly appreciated.

```<code><h2>Index</h2>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Id)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Dark)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Lit)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Contra)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.CreateDate)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.CreateBy)
                </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Dark)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Lit)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Contra)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CreateDate)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CreateBy)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new {  id=item.Id }) |
                @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.Id })
            </td>
        </tr>
}
    </tbody>
</table>
</code>```

Here is my controller

```<code>public class RoutePartnersController : Controller

{
    private readonly TraderContext _context;

    public RoutePartnersController(TraderContext context)
    {
        _context = context;
    }

    // GET: RoutePartners
    public async Task<IActionResult> Index()
    {
        return View(await _context.RoutePartner.ToListAsync());
    }

    // GET: RoutePartners/Details/5
    public async Task<IActionResult> Details(Guid? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var routePartner = await _context.RoutePartner
            .SingleOrDefaultAsync(m => m.PartnerId == id);
        if (routePartner == null)
        {
            return NotFound();
        }

        return View(routePartner);
    }

    // GET: RoutePartners/Create
    public IActionResult Create()
    {
        return View();
    }

    // POST: RoutePartners/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,PartnerId,RouteCompany,RouteCode,Dark,Lit,Contra,CreateDate,CreateBy")] RoutePartner routePartner)
    {
        if (ModelState.IsValid)
        {
            routePartner.PartnerId = Guid.NewGuid();
            _context.Add(routePartner);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(routePartner);
    }

    // GET: RoutePartners/Edit/5
    public async Task<IActionResult> Edit(Guid? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var routePartner = await _context.RoutePartner.SingleOrDefaultAsync(m => m.PartnerId == id);
        if (routePartner == null)
        {
            return NotFound();
        }
        return View(routePartner);
    }

    // POST: RoutePartners/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(Guid id, [Bind("Id,PartnerId,RouteCompany,RouteCode,Dark,Lit,Contra,CreateDate,CreateBy")] RoutePartner routePartner)
    {
        if (id != routePartner.PartnerId)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(routePartner);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RoutePartnerExists(routePartner.PartnerId))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction("Index");
        }
        return View(routePartner);
    }

    // GET: RoutePartners/Delete/5
    public async Task<IActionResult> Delete(Guid? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var routePartner = await _context.RoutePartner
            .SingleOrDefaultAsync(m => m.PartnerId == id);
        if (routePartner == null)
        {
            return NotFound();
        }

        return View(routePartner);
    }

    // POST: RoutePartners/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(Guid id)
    {
        var routePartner = await _context.RoutePartner.SingleOrDefaultAsync(m => m.PartnerId == id);
        _context.RoutePartner.Remove(routePartner);
        await _context.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    private bool RoutePartnerExists(Guid id)
    {
        return _context.RoutePartner.Any(e => e.PartnerId == id);
    }
}
</code>```

答: Ok, I figured out what's wrong. I have a table with 7 columns. Column one is an "Id" column that we use to quickly identify a row. It is NOT the primary key. Columns 2, 3 and 4 are the primary key. Oddly when the scaffolding was generated, the primary key columns were NOT included in the view. This ultimately led to the views not working. Is this a VS 2017 bug?</p>

Body:
I reverse engineered a table from and exiting database. Then added a controller with all scaffolding for views and context. My table does not have a traditional primary key such as "Id" it has a complex key. However, I do have an Id column which is unique.

When the views got created, the set up was correct. I noticed that the out of the box "Edit, Details and Delete" had action links commented out. I removed the comments and pointed the Model items to the "Id" field.

My "Id" field is a guid but I don't think that is a problem. When I click the edit link on the view, I receive a page not found. Any help would be greatly appreciated.

Index

    Create New

                    @Html.DisplayNameFor(model => model.Id)

                    @Html.DisplayNameFor(model => model.Dark)

                    @Html.DisplayNameFor(model => model.Lit)

                    @Html.DisplayNameFor(model => model.Contra)

                    @Html.DisplayNameFor(model => model.CreateDate)

                    @Html.DisplayNameFor(model => model.CreateBy)

@foreach (var item in Model) {

                @Html.DisplayFor(modelItem => item.Id)

                @Html.DisplayFor(modelItem => item.Dark)

                @Html.DisplayFor(modelItem => item.Lit)

                @Html.DisplayFor(modelItem => item.Contra)

                @Html.DisplayFor(modelItem => item.CreateDate)

                @Html.DisplayFor(modelItem => item.CreateBy)

                @Html.ActionLink("Edit", "Edit", new {  id=item.Id }) |
                @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.Id })

}

Here is my controller

public class RoutePartnersController : Controller

{
    private readonly TraderContext _context;

    public RoutePartnersController(TraderContext context)
    {
        _context = context;
    }

    // GET: RoutePartners
    public async Task<IActionResult> Index()
    {
        return View(await _context.RoutePartner.ToListAsync());
    }

    // GET: RoutePartners/Details/5
    public async Task<IActionResult> Details(Guid? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var routePartner = await _context.RoutePartner
            .SingleOrDefaultAsync(m => m.PartnerId == id);
        if (routePartner == null)
        {
            return NotFound();
        }

        return View(routePartner);
    }

    // GET: RoutePartners/Create
    public IActionResult Create()
    {
        return View();
    }

    // POST: RoutePartners/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,PartnerId,RouteCompany,RouteCode,Dark,Lit,Contra,CreateDate,CreateBy")] RoutePartner routePartner)
    {
        if (ModelState.IsValid)
        {
            routePartner.PartnerId = Guid.NewGuid();
            _context.Add(routePartner);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(routePartner);
    }

    // GET: RoutePartners/Edit/5
    public async Task<IActionResult> Edit(Guid? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var routePartner = await _context.RoutePartner.SingleOrDefaultAsync(m => m.PartnerId == id);
        if (routePartner == null)
        {
            return NotFound();
        }
        return View(routePartner);
    }

    // POST: RoutePartners/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(Guid id, [Bind("Id,PartnerId,RouteCompany,RouteCode,Dark,Lit,Contra,CreateDate,CreateBy")] RoutePartner routePartner)
    {
        if (id != routePartner.PartnerId)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(routePartner);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RoutePartnerExists(routePartner.PartnerId))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction("Index");
        }
        return View(routePartner);
    }

    // GET: RoutePartners/Delete/5
    public async Task<IActionResult> Delete(Guid? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var routePartner = await _context.RoutePartner
            .SingleOrDefaultAsync(m => m.PartnerId == id);
        if (routePartner == null)
        {
            return NotFound();
        }

        return View(routePartner);
    }

    // POST: RoutePartners/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(Guid id)
    {
        var routePartner = await _context.RoutePartner.SingleOrDefaultAsync(m => m.PartnerId == id);
        _context.RoutePartner.Remove(routePartner);
        await _context.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    private bool RoutePartnerExists(Guid id)
    {
        return _context.RoutePartner.Any(e => e.PartnerId == id);
    }
}


来源: stackexchange

问:
Why does an attribute has a method?
I use pytorch define a Variable x, compute and get its gradient x.grad, meaning grad is an attribute of instance x. But, I can use x.grad.data.zero_() to set x.grad to zero meaning that data.zero_() is method of x.grad. Why does an attribute has a method? Thanks a lot.</p>

答:
Even in languages with distinct scalar and object types (like Java or C++), attributes can be objects (hopefully else OO wouldn't buy you much), so there's nothing wrong, unexpected or suprising in having an attribute that have methods.

When it comes to Python there's no scalar type and everything is an object (really everything, including modules, classes, methods and functions), it's hardly surprising that you found an attribute with a method.

ContentLicense: CC BY-SA 3.0

Title: Why does an attribute has a method?


问:
Insert a value into div parameter
I have a custom parameter in my div and I want to insert a value into this parameter using JS or JQuery.

```<code><div id='test' data-sku=""></div>
</code>```

Using JS or JQuery, how can I change/insert a value in data-sku?

答:
This will do the trick:

jQuery (Check out the documentation for more usage examples: http://api.jquery.com/attr/):

```<code>$('#test').attr('data-sku', 'my value')
</code>```

Vanilla JavaScript:

```<code>document.querySelector('#test').setAttribute('data-sku', 'my value')
</code>```

Title: Insert a value into div parameter

Body:
I have a custom parameter in my div and I want to insert a value into this parameter using JS or JQuery.

Using JS or JQuery, how can I change/insert a value in data-sku?

Body:
This will do the trick:

jQuery (Check out the documentation for more usage examples: http://api.jquery.com/attr/):

$('#test').attr('data-sku', 'my value')

Vanilla JavaScript:

document.querySelector('#test').setAttribute('data-sku', 'my value')


问:
RED Robot Editor - Is there anyway to execute multiple testsuites parallelly?
I have 7 testsuites that are specific to languages something like German, Finish, Italy etc., I would like to execute all at one time. Kindly provide me solution on this. Referred to many materials, but having confusions that how we should work with RED Editor.</p>

答:
In the recent releases of RED it is possible to use a custom script to launch robot from RED. The documentation shows some examples in the Launch Scripting section. In the section about launching using Gradle there is a nice Windows batch example.

This could be used to have RED launch Pabot to run several Robot sessions in parallel. This would allow you to achieve the parallelisation from RED you seek.

The Selenium Grid can help with this, but I'd consider it if the testing load needs to be spread across multiple machines. If only running locally, then pabot itself is sufficient.


问:
What's the difference between %i, %d and %D in C ? (printf)
I'm wondering what's the difference between %D, %d and %i in the printf function, because they all display integers, so why are there 3 formats to display integers? There must be a difference between these three formats?

Edit: I was also asking for %D, not only %i and %d.

答:
There is no difference between %d and %i, and as far as I can tell, %D isn't a thing (or at least, maybe it's a compiler-specific extension).

See http://en.cppreference.com/w/c/io/fprintf, or section 7.19.6.1 of the e.g. the C99 standard.


问:
PHP get XML rootNode content as String
How can i get the content of an XML as string?
I have a xml like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<section>
  <paragraph>some content</paragraph>
  <custom>some more content</custom>
</section>
</code>```

and i want the content of section as a string like this:

```<code>  <paragraph>some content</paragraph>
  <custom>some more content</custom>
</code>```

every doc i read so far only explains how to get  the content of a subnode but not of the root node.

答:
You can use xml parser for create an array and work with it. For example:

```<code><?php
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<section>
  <paragraph>some content</paragraph>
  <custom>some more content</custom>
</section>
XML;

$values = [];
$p = xml_parser_create();
xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($p, $xml, $values);
xml_parser_free($p);

var_dump($values);
</code>```

http://php.net/manual/en/ref.xml.php

Title: PHP get XML rootNode content as String

Body:
How can i get the content of an XML as string?
I have a xml like this:

<?xml version="1.0" encoding="utf-8"?>

  <paragraph>some content</paragraph>
  <custom>some more content</custom>

and i want the content of section as a string like this:

  <paragraph>some content</paragraph>
  <custom>some more content</custom>

every doc i read so far only explains how to get  the content of a subnode but not of the root node.

Body:
You can use xml parser for create an array and work with it. For example:

<?php
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<section>
  <paragraph>some content</paragraph>
  <custom>some more content</custom>
</section>
XML;

$values = [];
$p = xml_parser_create();
xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($p, $xml, $values);
xml_parser_free($p);

var_dump($values);

http://php.net/manual/en/ref.xml.php


问:
What improvements to do before deploying website?
I am currently working on my first small comercial projects in web development.

Performance is always crucial, so I would like to know what steps should I follow before putting my website on the server to make sure the performance is just the best it can be.

I have heard there are some tools which rename all variables in a project to one letter variables and also delete new line characters, so that only the minimum of data is sent via the Internet and that improves performance

I like to create smaller files as some modules and then put them in  index.php like this:

```<code><html>
  <head>
    <?php include index_head.php ?> // here
  </head>
  <body>
    <nav>
    <?php include index_nav.html ?> // and here
    </nav>
  // and so on...
</code>```

what that gives is of course you write the code once and then link it where you want... Does such use of include change performance?

Any other suggestions?

答:
Well developers take different steps to increase Performance of the website. You can find Ideal solutions for it but not a perfect one. Here is the list of some Ideal steps for boosting Up your Website Performance.

Minimize HTTP Requests.

Reduce server response time.

Enable compression.

Enable browser caching.

Minify Resources.

Optimize images.

Optimize CSS Delivery.

Prioritize above-the-fold content

Reduce the number of plugins you use on your site

Reduce redirects

For coding the best thing is create separate files and include them in your index file. Deployment is also the main part you need to see if your hosting is fast and robust enough to make your website up every time.

Body:
I am currently working on my first small comercial projects in web development.

Performance is always crucial, so I would like to know what steps should I follow before putting my website on the server to make sure the performance is just the best it can be.

I have heard there are some tools which rename all variables in a project to one letter variables and also delete new line characters, so that only the minimum of data is sent via the Internet and that improves performance

I like to create smaller files as some modules and then put them in  index.php like this:

    <?php include index_head.php ?> // here

    <?php include index_nav.html ?> // and here

  // and so on...

what that gives is of course you write the code once and then link it where you want... Does such use of include change performance?

Any other suggestions?


问:
Parse a file 2 lines at a time
Python beginner here. I have a file that looks like that (every field is \t separated):

```<code>chr1_1792868_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->S:225) ...
chr1_1792869_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->L:225) ...
chr2_19719_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_19811_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_20024_SNP  Bcin02g00005    NON_SYNONYMOUS  NON_SYNONYMOUS[C](gene:Bcin02g00005|transcript:Bcin02g00005.1|S->A:331)
chr2_20025_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)
</code>```

I would like to parse through the file and compare 2 lines at a time and compare a value between them.

So in this case, I woud like to compare the line 1 and 2, check if there is "SYNONYMOUS" in the 3rd field in each of them. If yes, I would do some thing, if no (this case) I move on to the 3rd and 4th line (where this time the comparison of the two "SYNONYMOUS" values be positive) and I would select the first value of the line to do some more thing (compare with another dictionnary).

I thought about doing something something like that:

```<code>with open ('file.txt') as mutmut_mutants:
    for line1 in mutmut_mutants:
        line2 = next(mutmut_mutants)
        print type(line1)
        print line2+ "line2"
</code>```

But the problem is that I am dealing with lines of string instead of element of list (on line/element in a big list). Dealing with a list seems easier than with strings/regex. I then thought of this:

```<code>with open ('file.txt') as mutmut_mutants:
    for i in csv.reader(mutmut_mutants, delimiter='\t'):
        for k,(l1, l2) in enumerate(zip(i[0::2], i[1::2])):
            print str(zip(i[0::2], i[1::2]))
</code>```

But I can't make it work (and I don't get the zip and the i[0::2] very clearly). What I'm trying to do is : compare lines 2 by 2, and if SYNONYMOUS in both lines get the first strings (chrX_XXXXX_SNP) of each line.

Any thought on how I should proceed?

答:
You have an iterator that produces 1 item at a time, which is the file object.

You need an iterator that wraps that one and generates 2 items at a time.

Here's a naive approach:

```<code>def even_by_two(incoming):
    while True:
        one = next(incoming)
        two = next(incoming)
        yield (one, two)
    # This will break on a StopIteration exception,
    # which is ok for a generator.
    # The odd item at the end will be silently missed.
</code>```

A demo:

```<code>with open('/etc/passwd') as f:
  for one, two in even_by_two(f):
    print ("one -> ", one)
    print ("two -> ", two)
</code>```

The problem, of course, is that if the number of lines is not even, the last line will be lost.

Here's a less naive approach that cuts the input iterator by chunks of given size; the last chunk can be smaller.

```<code>def by_n(how_much, incoming):
    while True: # We need a post-condition, got no do-while in Python.
        result = []
        count = 0
        # The `for` will advance the iterator, but not past its end.
        for value in incoming:
            result.append(value)
            count += 1
            if count >= how_much:
                break
        if result:
            yield result
        else:  # We got nothing from the iterator, it must be over.
            break

>>> list(by_n(2, iter('abcdefg')))
[['a', 'b'], ['c', 'd'], ['e', 'f'], ['g']]
>>> list(by_n(5, iter('abcdefg')))
[['a', 'b', 'c', 'd', 'e'], ['f', 'g']]
</code>```

Note that the input must be a generator / iterator, e.g. a file, or a csv.reader. A simple list or a string won't work, hence iter(...) above that produces an iterator.

Title: Parse a file 2 lines at a time

Body:
Python beginner here. I have a file that looks like that (every field is \t separated):

chr1_1792868_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->S:225) ...
chr1_1792869_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->L:225) ...
chr2_19719_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_19811_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)  ...
chr2_20024_SNP  Bcin02g00005    NON_SYNONYMOUS  NON_SYNONYMOUS[C](gene:Bcin02g00005|transcript:Bcin02g00005.1|S->A:331)
chr2_20025_SNP  Bcin02g00005    SYNONYMOUS  SYNONYMOUS[A](gene:Bcin02g00005|transcript:Bcin02g00005.1)

I would like to parse through the file and compare 2 lines at a time and compare a value between them.

So in this case, I woud like to compare the line 1 and 2, check if there is "SYNONYMOUS" in the 3rd field in each of them. If yes, I would do some thing, if no (this case) I move on to the 3rd and 4th line (where this time the comparison of the two "SYNONYMOUS" values be positive) and I would select the first value of the line to do some more thing (compare with another dictionnary).

I thought about doing something something like that:

with open ('file.txt') as mutmut_mutants:
    for line1 in mutmut_mutants:
        line2 = next(mutmut_mutants)
        print type(line1)
        print line2+ "line2"

But the problem is that I am dealing with lines of string instead of element of list (on line/element in a big list). Dealing with a list seems easier than with strings/regex. I then thought of this:

with open ('file.txt') as mutmut_mutants:
    for i in csv.reader(mutmut_mutants, delimiter='\t'):
        for k,(l1, l2) in enumerate(zip(i[0::2], i[1::2])):
            print str(zip(i[0::2], i[1::2]))

But I can't make it work (and I don't get the zip and the i[0::2] very clearly). What I'm trying to do is : compare lines 2 by 2, and if SYNONYMOUS in both lines get the first strings (chrX_XXXXX_SNP) of each line.

Any thought on how I should proceed?

Body:
You have an iterator that produces 1 item at a time, which is the file object.

You need an iterator that wraps that one and generates 2 items at a time.

Here's a naive approach:

def even_by_two(incoming):
    while True:
        one = next(incoming)
        two = next(incoming)
        yield (one, two)
    # This will break on a StopIteration exception,
    # which is ok for a generator.
    # The odd item at the end will be silently missed.

A demo:

with open('/etc/passwd') as f:
  for one, two in even_by_two(f):
    print ("one -> ", one)
    print ("two -> ", two)

The problem, of course, is that if the number of lines is not even, the last line will be lost.

Here's a less naive approach that cuts the input iterator by chunks of given size; the last chunk can be smaller.

def by_n(how_much, incoming):
    while True: # We need a post-condition, got no do-while in Python.
        result = []
        count = 0
        # The `for` will advance the iterator, but not past its end.
        for value in incoming:
            result.append(value)
            count += 1
            if count >= how_much:
                break
        if result:
            yield result
        else:  # We got nothing from the iterator, it must be over.
            break

>>> list(by_n(2, iter('abcdefg')))
[['a', 'b'], ['c', 'd'], ['e', 'f'], ['g']]
>>> list(by_n(5, iter('abcdefg')))
[['a', 'b', 'c', 'd', 'e'], ['f', 'g']]

Note that the input must be a generator / iterator, e.g. a file, or a csv.reader. A simple list or a string won't work, hence iter(...) above that produces an iterator.


问:
What are useful parameters to store when tracking page views?
I want to implement a simple in-house table that tracks user page views on my website. Without targeting some specific hypothesis, what is useful data to store? Eventually I'll use it to build graphs or decision trees to better learn about our user base. This is static (no javascript).

Things I can think of:

URL accessed

HTTP refer[r]er

HTTP Accept Language

Browser-agent

Session id

User id (if logged in)

Time visited

答:
Sounds like a good start,

I'd be inclined to store visitor IP address, and derived from that via a geo ip lookup the location of the visitor.

Also you could consider reverse dns'ing the IP to get an idea of the isp you're user is on, you might never use it but then again it could be useful if you have a report of downstream caching causing problems.

ContentLicense: CC BY-SA 2.5


答:
you can use .attr() to set the value of a specific attribute of an element, like this:

```<code>$('#test').attr('data-sku', 'value');
</code>```

Title: Insert a value into div parameter

Body:
you can use .attr() to set the value of a specific attribute of an element, like this:

$('#test').attr('data-sku', 'value');


问:
How to bind checkBox to a boolean property?
I started using vaadin framework recently.

I have a Form which contains some textFields and a checkbox, my problem is all fields are binding with their properties expect checkbox ??.

This is the form :

```<code>public class ContactForm extends FormLayout {

private Button save = new Button("Save", this::save);
private Button delete = new Button("Delete", this::delete);
private Button cancel = new Button("Cancel", this::cancel);
private TextField firstName = new TextField("First name");
private TextField lastName = new TextField("Last name");
private TextField phone = new TextField("Phone");
private TextField email = new TextField("Email");
private DateField birthDate = new DateField("Birth date");
private CheckBox bookMarks = new CheckBox("BookMarks");

private Contact contact;

// Easily bind forms to beans and manage validation and buffering
private BeanFieldGroup<Contact> formFieldBindings;

public ContactForm() {
    configureComponents();
    buildLayout();
}

private void configureComponents() {...}

private void buildLayout() {...}

void edit(Contact contact) {

    this.contact = contact;
    if (contact != null) {
        // Bind the properties of the contact POJO to fields in this form
        formFieldBindings = BeanFieldGroup.bindFieldsBuffered(contact, this);

        delete.setVisible(contact.getId() != null);
    }

    setVisible(contact != null);
}

@Override
public AddressbookUI getUI() {
    return (AddressbookUI) super.getUI();
}}
</code>```

This is My class Contact :

```<code>public class Contact implements Serializable, Cloneable {

private Long id;

private String firstName = "";
private String lastName = "";
private String phone = "";
private String email = "";
private Date birthDate;
private Boolean bookMarks;

// getters and setters
...
}
</code>```

What am i doing wrong? Should I bind the checkbox field manually ?

答:
The solution is to add addValueChangeListener to the check box like this :

```<code>bookMarks.addValueChangeListener(event -> contact.setBookMarks(bookMarks.getValue()));
</code>```

Body:
I started using vaadin framework recently.

I have a Form which contains some textFields and a checkbox, my problem is all fields are binding with their properties expect checkbox ??.

This is the form :

public class ContactForm extends FormLayout {

private Button save = new Button("Save", this::save);
private Button delete = new Button("Delete", this::delete);
private Button cancel = new Button("Cancel", this::cancel);
private TextField firstName = new TextField("First name");
private TextField lastName = new TextField("Last name");
private TextField phone = new TextField("Phone");
private TextField email = new TextField("Email");
private DateField birthDate = new DateField("Birth date");
private CheckBox bookMarks = new CheckBox("BookMarks");

private Contact contact;

// Easily bind forms to beans and manage validation and buffering
private BeanFieldGroup<Contact> formFieldBindings;

public ContactForm() {
    configureComponents();
    buildLayout();
}

private void configureComponents() {...}

private void buildLayout() {...}

void edit(Contact contact) {

    this.contact = contact;
    if (contact != null) {
        // Bind the properties of the contact POJO to fields in this form
        formFieldBindings = BeanFieldGroup.bindFieldsBuffered(contact, this);

        delete.setVisible(contact.getId() != null);
    }

    setVisible(contact != null);
}

@Override
public AddressbookUI getUI() {
    return (AddressbookUI) super.getUI();
}}

This is My class Contact :

public class Contact implements Serializable, Cloneable {

private Long id;

private String firstName = "";
private String lastName = "";
private String phone = "";
private String email = "";
private Date birthDate;
private Boolean bookMarks;

// getters and setters
...
}

What am i doing wrong? Should I bind the checkbox field manually ?

Body:
The solution is to add addValueChangeListener to the check box like this :

bookMarks.addValueChangeListener(event -> contact.setBookMarks(bookMarks.getValue()));


问:
Picturebox location for X and Y is different then what is being entered in properties
I have 2 picture box's, a hero and an enemy. The hero seems to load fine at the location I specify in the properties of the PictureBox (0,0). However, the enemy picture box I want it to be set to location (90,90), which I do set it to that, but when I run the windows form - for some reason - it is showing the picture form is at location (60,58).

The hero PictureBox is the Green and the Enemy is Orange.

I am wanting to make a simple game and want to move the hero the exact size as the tile he is so that if you move the hero to where the enemy is they should stack up flat on top of each other. I have my form set to a full size of (300,300) and both picture boxes are a size of (30,30). So, they should be able to "move" 10 moves to the left and right - if they are set at a starting position of (0,0). I am not sure if it is my movement method that is messing me up but I also have zero ideas as to why the location of x and y are different when I tried to post it to console to debug this situation- instead of being 90,90 where I placed it on the form and in properties. Ideally I should be able to move 3 to the left and 3 down and be on top of the enemy but it's not at all correct.

Is there any reason why these are not the same? I will attach photos and my source code.

Starting Position

Hero Moving - They are not directly on top of each other but should be

Enemy Properties - to show size and location

Hero Properties - to show size and location

CODE

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Mirage
{
public partial class Form1 : Form
{
Random rand = new Random();

public Form1()
{
    InitializeComponent();
    Console.WriteLine("HERO STARTING LOCATION --- X = : {0} ---- Y = : {1}", pctrBxHero.Location.X, pctrBxHero.Location.Y);
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    using (Font myFont = new Font("Lucida", 10))
    {
        e.Graphics.DrawString("@", myFont, Brushes.Green, new Point(0, 0));
    }
}

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    int x = pctrBxHero.Location.X;
    int y = pctrBxHero.Location.Y;

    if (e.KeyCode == Keys.Right) x += 30;
    else if (e.KeyCode == Keys.Left) x -= 30;
    else if (e.KeyCode == Keys.Up) y -= 30;
    else if (e.KeyCode == Keys.Down) y += 30;

    pctrBxHero.Location = new Point(x, y);
    Console.WriteLine("HERO --- X = : {0} ---- Y = : {1}", x, y);
    Console.WriteLine("ENEMY --- X = : {0} ---- Y = : {1}", pctrBxEnemy.Location.X, pctrBxEnemy.Location.Y);
}

private void pictureBox2_Paint_1(object sender, PaintEventArgs e)
{

    using (Font myFont = new Font("Lucida", 10))
    {
        e.Graphics.DrawString("X", myFont, Brushes.Orange, new Point(0, 0));
    }
}
}
}
</code>```

答:
I'm unable to reproduce your problem in my example project.

Here's my output:

```<code>HERO --- X = : 30 ---- Y = : 0
ENEMY --- X = : 90 ---- Y = : 90
HERO --- X = : 60 ---- Y = : 0
ENEMY --- X = : 90 ---- Y = : 90
HERO --- X = : 90 ---- Y = : 0
ENEMY --- X = : 90 ---- Y = : 90
HERO --- X = : 90 ---- Y = : 30
ENEMY --- X = : 90 ---- Y = : 90
HERO --- X = : 90 ---- Y = : 60
ENEMY --- X = : 90 ---- Y = : 90
HERO --- X = : 90 ---- Y = : 90
ENEMY --- X = : 90 ---- Y = : 90
</code>```

With a screenshots at start and after moving:

The code I used:

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private Font fnt = new Font("Lucida", 10);

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        int x = pctrBxHero.Location.X;
        int y = pctrBxHero.Location.Y;

        if (e.KeyCode == Keys.Right) x += 30;
        else if (e.KeyCode == Keys.Left) x -= 30;
        else if (e.KeyCode == Keys.Up) y -= 30;
        else if (e.KeyCode == Keys.Down) y += 30;

        pctrBxHero.Location = new Point(x, y);

        Console.WriteLine("HERO --- X = : {0} ---- Y = : {1}", x, y);
        Console.WriteLine("ENEMY --- X = : {0} ---- Y = : {1}", pctrBxEnemy.Location.X, pctrBxEnemy.Location.Y);
    }

    private void pctrBxHero_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawString("@", fnt, Brushes.Green, new Point(0, 0));
    }

    private void pctrBxEnemy_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawString("X", fnt, Brushes.Orange, new Point(0, 0));
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        fnt.Dispose();
    }

}
</code>```

I notice that you have "pictureBox2_Paint_1", which means you renamed the PictureBox after wiring it up, and also that you possibly had two Paint() events at one point (since it added the "_1" on the end).  It's possible that you simply need to start over with fresh PictureBoxes; delete your existing ones, add new ones, rename them, then set their properties back up.  Finally, select each one, click on the "Lightning Bolt" icon to see their events, and re-wire up their Paint() events.

********** EDIT **********

Here's an alternate approach that may get around your scaling problem.  Get rid of the PictureBoxes altogether and DRAW both your Hero and Enemy in the Paint() event of your Form.  This could look something like:

```<code>public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
        sf.Alignment = StringAlignment.Center; // vertical center
        sf.LineAlignment = StringAlignment.Center; // horizontal center
    }

    private int boxSize = 30;
    private bool EnemyKilled = false;
    private Point pntHero = new Point(0, 0);
    private Point pntEnemy = new Point(3, 3);
    private Font fnt = new Font("Lucida", 10);
    private StringFormat sf = new StringFormat();

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Right) pntHero.Offset(1,0);
        else if (e.KeyCode == Keys.Left) pntHero.Offset(-1, 0);
        else if (e.KeyCode == Keys.Up) pntHero.Offset(0, -1);
        else if (e.KeyCode == Keys.Down) pntHero.Offset(0, 1);

        if (pntHero.Equals(pntEnemy))
        {
            EnemyKilled = true;
        }

        this.Invalidate();

        Console.WriteLine("HERO: " + pntHero.ToString());
        Console.WriteLine("ENEMY: " + pntEnemy.ToString());
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Rectangle rc;

        rc = new Rectangle(new Point(pntEnemy.X * boxSize, pntEnemy.Y * boxSize), new Size(boxSize, boxSize));
        e.Graphics.DrawRectangle(Pens.White, rc);
        e.Graphics.DrawString(EnemyKilled ? "X" : "O", fnt, Brushes.Orange, (RectangleF)rc, sf);

        rc = new Rectangle(new Point(pntHero.X * boxSize, pntHero.Y * boxSize), new Size(boxSize, boxSize));
        e.Graphics.DrawRectangle(Pens.White, rc);
        e.Graphics.DrawString("@", fnt, Brushes.Green, (RectangleF)rc, sf);
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        fnt.Dispose();
    }

}
</code>```

Body:
I have 2 picture box's, a hero and an enemy. The hero seems to load fine at the location I specify in the properties of the PictureBox (0,0). However, the enemy picture box I want it to be set to location (90,90), which I do set it to that, but when I run the windows form - for some reason - it is showing the picture form is at location (60,58).

The hero PictureBox is the Green and the Enemy is Orange.

I am wanting to make a simple game and want to move the hero the exact size as the tile he is so that if you move the hero to where the enemy is they should stack up flat on top of each other. I have my form set to a full size of (300,300) and both picture boxes are a size of (30,30). So, they should be able to "move" 10 moves to the left and right - if they are set at a starting position of (0,0). I am not sure if it is my movement method that is messing me up but I also have zero ideas as to why the location of x and y are different when I tried to post it to console to debug this situation- instead of being 90,90 where I placed it on the form and in properties. Ideally I should be able to move 3 to the left and 3 down and be on top of the enemy but it's not at all correct.

Is there any reason why these are not the same? I will attach photos and my source code.

Starting Position

Hero Moving - They are not directly on top of each other but should be

Enemy Properties - to show size and location

Hero Properties - to show size and location

CODE

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Mirage
{
public partial class Form1 : Form
{
Random rand = new Random();

public Form1()
{
    InitializeComponent();
    Console.WriteLine("HERO STARTING LOCATION --- X = : {0} ---- Y = : {1}", pctrBxHero.Location.X, pctrBxHero.Location.Y);
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    using (Font myFont = new Font("Lucida", 10))
    {
        e.Graphics.DrawString("@", myFont, Brushes.Green, new Point(0, 0));
    }
}

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    int x = pctrBxHero.Location.X;
    int y = pctrBxHero.Location.Y;

    if (e.KeyCode == Keys.Right) x += 30;
    else if (e.KeyCode == Keys.Left) x -= 30;
    else if (e.KeyCode == Keys.Up) y -= 30;
    else if (e.KeyCode == Keys.Down) y += 30;

    pctrBxHero.Location = new Point(x, y);
    Console.WriteLine("HERO --- X = : {0} ---- Y = : {1}", x, y);
    Console.WriteLine("ENEMY --- X = : {0} ---- Y = : {1}", pctrBxEnemy.Location.X, pctrBxEnemy.Location.Y);
}

private void pictureBox2_Paint_1(object sender, PaintEventArgs e)
{

    using (Font myFont = new Font("Lucida", 10))
    {
        e.Graphics.DrawString("X", myFont, Brushes.Orange, new Point(0, 0));
    }
}
}
}

Body:
I'm unable to reproduce your problem in my example project.

Here's my output:

HERO --- X = : 30 ---- Y = : 0
ENEMY --- X = : 90 ---- Y = : 90
HERO --- X = : 60 ---- Y = : 0
ENEMY --- X = : 90 ---- Y = : 90
HERO --- X = : 90 ---- Y = : 0
ENEMY --- X = : 90 ---- Y = : 90
HERO --- X = : 90 ---- Y = : 30
ENEMY --- X = : 90 ---- Y = : 90
HERO --- X = : 90 ---- Y = : 60
ENEMY --- X = : 90 ---- Y = : 90
HERO --- X = : 90 ---- Y = : 90
ENEMY --- X = : 90 ---- Y = : 90

With a screenshots at start and after moving:

The code I used:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private Font fnt = new Font("Lucida", 10);

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        int x = pctrBxHero.Location.X;
        int y = pctrBxHero.Location.Y;

        if (e.KeyCode == Keys.Right) x += 30;
        else if (e.KeyCode == Keys.Left) x -= 30;
        else if (e.KeyCode == Keys.Up) y -= 30;
        else if (e.KeyCode == Keys.Down) y += 30;

        pctrBxHero.Location = new Point(x, y);

        Console.WriteLine("HERO --- X = : {0} ---- Y = : {1}", x, y);
        Console.WriteLine("ENEMY --- X = : {0} ---- Y = : {1}", pctrBxEnemy.Location.X, pctrBxEnemy.Location.Y);
    }

    private void pctrBxHero_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawString("@", fnt, Brushes.Green, new Point(0, 0));
    }

    private void pctrBxEnemy_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawString("X", fnt, Brushes.Orange, new Point(0, 0));
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        fnt.Dispose();
    }

}

I notice that you have "pictureBox2_Paint_1", which means you renamed the PictureBox after wiring it up, and also that you possibly had two Paint() events at one point (since it added the "_1" on the end).  It's possible that you simply need to start over with fresh PictureBoxes; delete your existing ones, add new ones, rename them, then set their properties back up.  Finally, select each one, click on the "Lightning Bolt" icon to see their events, and re-wire up their Paint() events.

********** EDIT **********

Here's an alternate approach that may get around your scaling problem.  Get rid of the PictureBoxes altogether and DRAW both your Hero and Enemy in the Paint() event of your Form.  This could look something like:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
        sf.Alignment = StringAlignment.Center; // vertical center
        sf.LineAlignment = StringAlignment.Center; // horizontal center
    }

    private int boxSize = 30;
    private bool EnemyKilled = false;
    private Point pntHero = new Point(0, 0);
    private Point pntEnemy = new Point(3, 3);
    private Font fnt = new Font("Lucida", 10);
    private StringFormat sf = new StringFormat();

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Right) pntHero.Offset(1,0);
        else if (e.KeyCode == Keys.Left) pntHero.Offset(-1, 0);
        else if (e.KeyCode == Keys.Up) pntHero.Offset(0, -1);
        else if (e.KeyCode == Keys.Down) pntHero.Offset(0, 1);

        if (pntHero.Equals(pntEnemy))
        {
            EnemyKilled = true;
        }

        this.Invalidate();

        Console.WriteLine("HERO: " + pntHero.ToString());
        Console.WriteLine("ENEMY: " + pntEnemy.ToString());
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Rectangle rc;

        rc = new Rectangle(new Point(pntEnemy.X * boxSize, pntEnemy.Y * boxSize), new Size(boxSize, boxSize));
        e.Graphics.DrawRectangle(Pens.White, rc);
        e.Graphics.DrawString(EnemyKilled ? "X" : "O", fnt, Brushes.Orange, (RectangleF)rc, sf);

        rc = new Rectangle(new Point(pntHero.X * boxSize, pntHero.Y * boxSize), new Size(boxSize, boxSize));
        e.Graphics.DrawRectangle(Pens.White, rc);
        e.Graphics.DrawString("@", fnt, Brushes.Green, (RectangleF)rc, sf);
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        fnt.Dispose();
    }

}


问:
EventBus : Activity does not receive event when app is in the background
I'm using EventBus to communicate between Activity and Service.
Today I got a problem and don't know why.

I have Activity, Fragment and Service. All of them are working fine.

In Activity and Fragment I registered them to Receive events which delivered from Service

In Activity and Fragment, I un-register them when onDestroy() was called.

In normal cases, when Services delivers events, Fragment and Activity can receive those events and work well.

But when App is pushed on the background (by presses Home or Power button), only Fragment receives events which delivered from Service, and Activity does not receive them.

I did not do anything in onPause() both of Activity and Fragment.

Question:

Is there any explanation for that? And how can I make my Activity receives event like Fragment did when app is pushed on background?

答:
In EventBus version 3.0.0 you can use Sticky posts.

This way you can and should unregister EventBus on 'onStop()' to prevent memory leaks and still receive events when App come to foreground.

Post events this way:

```<code>EventBus.getDefault().postSticky(new MessageEvent("Hello everyone!"));
</code>```

Subscribe events with sticky flag, like this:

```<code>@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onEvent(MessageEvent event) {
    textField.setText(event.message);
}
</code>```

EventBus Documentation:
http://greenrobot.org/eventbus/documentation/configuration/sticky-events/

Body:
In EventBus version 3.0.0 you can use Sticky posts.

This way you can and should unregister EventBus on 'onStop()' to prevent memory leaks and still receive events when App come to foreground.

Post events this way:

EventBus.getDefault().postSticky(new MessageEvent("Hello everyone!"));

Subscribe events with sticky flag, like this:

@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onEvent(MessageEvent event) {
    textField.setText(event.message);
}

EventBus Documentation:
http://greenrobot.org/eventbus/documentation/configuration/sticky-events/


问:
importing jquery through webpack error - module not found: can't resolve jquery
I'm new to typescript and trying to learn it through online example and getting started tutorials, I'm following tutorial from
    https://www.codingforentrepreneurs.com/blog/typescript-setup-guide/
everything worked fine for me except when I tried to import jquery and tried to use it in my typescript file, it started giving error for module not found.
Following is my code chunks which I'm running:

my main.ts file is

```<code>import * as $ from 'jquery'
import {MustHaveCoffee} from './getcoffee'
class SweetSweetClass{
    constructor(){
        console.log("Even sweeter");
        $('body').css('background-color', 'red');//here error occures
    }
}
let basil = new SweetSweetClass();
let coffee = new MustHaveCoffee();
</code>```

webpack.config.js file is

```<code>var path = require('path');
module.exports = {
    entry: './main.ts',
    resolve: {
        extensions: ['.webpack.js', '.web.js', '.ts', '.js']
    },
    module:{
        loaders: [
            { test:/\.ts$/, loader: 'ts-loader' }
        ]
    },
    output:{
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
}
</code>```

my tsconfig.json file is

```<code>{
    "compilerOptions":{
        "module":"commonjs",
        "outDir":"dist/",
        "noImplicitAny":true,
        "removeComments":true,
        "preserveConstEnums":true
    },
    "include":[
        "./typings/*"
    ],
    "exclude":[
        "node_modules",
        "**/*.spec.ts"
    ]
}
</code>```

Following is error which I'm getting while running 'webapack' command

```<code>E:\learning-typescript-by-examples>webpack
ts-loader: Using typescript@2.4.1 and E:\learning-typescript-by-examples\tsconfig.json
Hash: 3a411aca489fbed8710d
Version: webpack 3.0.0
Time: 1659ms
Asset     Size  Chunks             Chunk Names
bundle.js  3.34 kB       0  [emitted]  main
[0] ./main.ts 402 bytes {0} [built]
[1] ./getcoffee.ts 235 bytes {0} [built]

ERROR in ./main.ts
Module not found: Error: Can't resolve 'jquery' in 'E:\learning-typescript-by-examples'
@ ./main.ts 3:8-25
</code>```

Also, I've added jquery as global module through typings by running

```<code>typings install dt~jquery --global --save
</code>```

and it worked correctly.
I followed every step mentioned it tutorial but started getting the stated error. May be I'm missing something but unable to figure it out. I've searched the problem and found some solution (like one here webpack Module not found: Error: Can't resolve 'jquery') but the solutions doesn't seems to be fit in my situation as I'm not using bower for dependency management etc. Any help would be highly appreciated.Thanks

UPDATE

I've added now jquery through using 'npm install --save-dev @types/jquery' and detailed error is following

```<code>ts-loader: Using typescript@2.4.1 and E:\learning-typescript-by-examples\tsconfig.json
Hash: d72ca1c2dd5c6319254c
Version: webpack 3.0.0
Time: 2233ms
Asset     Size  Chunks             Chunk Names
bundle.js  3.35 kB       0  [emitted]  main
[0] ./main.ts 410 bytes {0} [built] [2 errors]
[1] ./getcoffee.ts 235 bytes {0} [built]

ERROR in ./main.ts
(1,20): error TS2306: File 'E:/learning-typescript-by-examples/node_modules/@types/jquery/index.d.ts' is not a module.

ERROR in ./main.ts
(1,20): error TS6137: Cannot import type declaration files. Consider importing 'jquery' instead of '@types/jquery'.

ERROR in ./main.ts

Module not found: Error: Can't resolve '@types/jquery' in 'E:\learning-typescript-by-examples'

resolve '@types/jquery' in 'E:\learning-typescript-by-examples'

  Parsed request is a module

  using description file: E:\learning-typescript-by-examples\package.json (relative path: .)

    Field 'browser' doesn't contain a valid alias configuration

  after using description file: E:\learning-typescript-by-examples\package.json (relative path: .)

    resolve as module

      E:\node_modules doesn't exist or is not a directory
      looking for modules in E:\learning-typescript-by-examples\node_modules

        using description file: E:\learning-typescript-by-examples\package.json (relative path: ./node_modules)

          Field 'browser' doesn't contain a valid alias configuration
        after using description file: E:\learning-typescript-by-examples\package.json (relative path: ./node_modules)

          using description file: E:\learning-typescript-by-examples\node_modules\@types\jquery\package.json (relative path: .)
            no extension

              Field 'browser' doesn't contain a valid alias configuration

             E:\learning-typescript-by-examples\node_modules\@types\jquery is not a file
            .webpack.js

              Field 'browser' doesn't contain a valid alias configuration

              E:\learning-typescript-by-examples\node_modules\@types\jquery.webpack.js doesn't exist
            .web.js

              Field 'browser' doesn't contain a valid alias configuration

              E:\learning-typescript-by-examples\node_modules\@types\jquery.web.js doesn't exist
            .ts

              Field 'browser' doesn't contain a valid alias configuration

              E:\learning-typescript-by-examples\node_modules\@types\jquery.ts doesn't exist
            .js

              Field 'browser' doesn't contain a valid alias configuration

              E:\learning-typescript-by-examples\node_modules\@types\jquery.js doesn't exist
            as directory
              existing directory

                using path: E:\learning-typescript-by-examples\node_modules\@types\jquery\index

                  using description file: E:\learning-typescript-by-examples\node_modules\@types\jquery\package.json (relative path: ./index)
                    no extension

                      Field 'browser' doesn't contain a valid alias configuration

                      E:\learning-typescript-by-examples\node_modules\@types\jquery\index doesn't exist
                    .webpack.js

                      Field 'browser' doesn't contain a valid alias configuration

                      E:\learning-typescript-by-examples\node_modules\@types\jquery\index.webpack.js doesn't exist
                    .web.js

                      Field 'browser' doesn't contain a valid alias configuration
                      E:\learning-typescript-by-examples\node_modules\@types\jquery\index.web.js doesn't exist
                    .ts

                      Field 'browser' doesn't contain a valid alias configuration
                      E:\learning-typescript-by-examples\node_modules\@types\jquery\index.ts doesn't exist
                    .js

                      Field 'browser' doesn't contain a valid alias configuration
                      E:\learning-typescript-by-examples\node_modules\@types\jquery\index.js doesn't exist

[E:\node_modules]

[E:\learning-typescript-by-examples\node_modules\@types\jquery]

[E:\learning-typescript-by-examples\node_modules\@types\jquery.webpack.js]

[E:\learning-typescript-by-examples\node_modules\@types\jquery.web.js]

[E:\learning-typescript-by-examples\node_modules\@types\jquery.ts]

[E:\learning-typescript-by-examples\node_modules\@types\jquery.js]

[E:\learning-typescript-by-examples\node_modules\@types\jquery\index]

[E:\learning-typescript-by-examples\node_modules\@types\jquery\index.webpack.js]

[E:\learning-typescript-by-examples\node_modules\@types\jquery\index.web.js]

[E:\learning-typescript-by-examples\node_modules\@types\jquery\index.ts]

[E:\learning-typescript-by-examples\node_modules\@types\jquery\index.js]
@ ./main.ts 3:8-32
</code>```

答:
You're trying to import type definitions instead of the module itself. The error reflects that and suggests that you import jquery instead.

```<code>(1,20): error TS6137: Cannot import type declaration files. Consider importing 'jquery' instead of '@types/jquery'.
</code>```

The actual module is jquery, that means you need to import it as such.

```<code>import * as $ from 'jquery';
</code>```

Of course you need to have it installed first, which might have been your initial problem. You can install it with:

```<code>npm install --save jquery
</code>```

You might be wondering why you need two different packages to use jQuery. The reason is that jquery is a JavaScript module and TypeScript is generally not happy when it doesn't have any type information for a module and jquery doesn't provide them. You don't need the types to use the module, but you need to somehow satisfy the TypeScript compiler. Because it would be tedious to create your own type definitions, there are many type definitions for popular libraries that are made by the community. They can be found in the DefinitelyTyped repository and each of them is published to npm as @types/<package-name>.

The tutorial you're using suggests to use typings, but that is not used anymore since TypeScript 2.0 (see Deprecation Notice: Regarding TypeScript@2.0). The tutorial seems to be outdated, even at the time of the writing, and it doesn't really cover more (or in more detail) than the official webpack docs Webpack - TypeScript.

Body:
I'm new to typescript and trying to learn it through online example and getting started tutorials, I'm following tutorial from
    https://www.codingforentrepreneurs.com/blog/typescript-setup-guide/
everything worked fine for me except when I tried to import jquery and tried to use it in my typescript file, it started giving error for module not found.
Following is my code chunks which I'm running:

my main.ts file is

import * as $ from 'jquery'
import {MustHaveCoffee} from './getcoffee'
class SweetSweetClass{
    constructor(){
        console.log("Even sweeter");
        $('body').css('background-color', 'red');//here error occures
    }
}
let basil = new SweetSweetClass();
let coffee = new MustHaveCoffee();

webpack.config.js file is

var path = require('path');
module.exports = {
    entry: './main.ts',
    resolve: {
        extensions: ['.webpack.js', '.web.js', '.ts', '.js']
    },
    module:{
        loaders: [
            { test:/\.ts$/, loader: 'ts-loader' }
        ]
    },
    output:{
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
}

my tsconfig.json file is

{
    "compilerOptions":{
        "module":"commonjs",
        "outDir":"dist/",
        "noImplicitAny":true,
        "removeComments":true,
        "preserveConstEnums":true
    },
    "include":[
        "./typings/*"
    ],
    "exclude":[
        "node_modules",
        "**/*.spec.ts"
    ]
}

Following is error which I'm getting while running 'webapack' command

E:\learning-typescript-by-examples>webpack
ts-loader: Using typescript@2.4.1 and E:\learning-typescript-by-examples\tsconfig.json
Hash: 3a411aca489fbed8710d
Version: webpack 3.0.0
Time: 1659ms
Asset     Size  Chunks             Chunk Names
bundle.js  3.34 kB       0  [emitted]  main
[0] ./main.ts 402 bytes {0} [built]
[1] ./getcoffee.ts 235 bytes {0} [built]

ERROR in ./main.ts
Module not found: Error: Can't resolve 'jquery' in 'E:\learning-typescript-by-examples'
@ ./main.ts 3:8-25

Also, I've added jquery as global module through typings by running

typings install dt~jquery --global --save

and it worked correctly.
I followed every step mentioned it tutorial but started getting the stated error. May be I'm missing something but unable to figure it out. I've searched the problem and found some solution (like one here webpack Module not found: Error: Can't resolve 'jquery') but the solutions doesn't seems to be fit in my situation as I'm not using bower for dependency management etc. Any help would be highly appreciated.Thanks

UPDATE

I've added now jquery through using 'npm install --save-dev @types/jquery' and detailed error is following

ts-loader: Using typescript@2.4.1 and E:\learning-typescript-by-examples\tsconfig.json
Hash: d72ca1c2dd5c6319254c
Version: webpack 3.0.0
Time: 2233ms
Asset     Size  Chunks             Chunk Names
bundle.js  3.35 kB       0  [emitted]  main
[0] ./main.ts 410 bytes {0} [built] [2 errors]
[1] ./getcoffee.ts 235 bytes {0} [built]

ERROR in ./main.ts
(1,20): error TS2306: File 'E:/learning-typescript-by-examples/node_modules/@types/jquery/index.d.ts' is not a module.

ERROR in ./main.ts
(1,20): error TS6137: Cannot import type declaration files. Consider importing 'jquery' instead of '@types/jquery'.

ERROR in ./main.ts

Module not found: Error: Can't resolve '@types/jquery' in 'E:\learning-typescript-by-examples'

resolve '@types/jquery' in 'E:\learning-typescript-by-examples'

  Parsed request is a module

  using description file: E:\learning-typescript-by-examples\package.json (relative path: .)

    Field 'browser' doesn't contain a valid alias configuration

  after using description file: E:\learning-typescript-by-examples\package.json (relative path: .)

    resolve as module

      E:\node_modules doesn't exist or is not a directory
      looking for modules in E:\learning-typescript-by-examples\node_modules

        using description file: E:\learning-typescript-by-examples\package.json (relative path: ./node_modules)

          Field 'browser' doesn't contain a valid alias configuration
        after using description file: E:\learning-typescript-by-examples\package.json (relative path: ./node_modules)

          using description file: E:\learning-typescript-by-examples\node_modules\@types\jquery\package.json (relative path: .)
            no extension

              Field 'browser' doesn't contain a valid alias configuration

             E:\learning-typescript-by-examples\node_modules\@types\jquery is not a file
            .webpack.js

              Field 'browser' doesn't contain a valid alias configuration

              E:\learning-typescript-by-examples\node_modules\@types\jquery.webpack.js doesn't exist
            .web.js

              Field 'browser' doesn't contain a valid alias configuration

              E:\learning-typescript-by-examples\node_modules\@types\jquery.web.js doesn't exist
            .ts

              Field 'browser' doesn't contain a valid alias configuration

              E:\learning-typescript-by-examples\node_modules\@types\jquery.ts doesn't exist
            .js

              Field 'browser' doesn't contain a valid alias configuration

              E:\learning-typescript-by-examples\node_modules\@types\jquery.js doesn't exist
            as directory
              existing directory

                using path: E:\learning-typescript-by-examples\node_modules\@types\jquery\index

                  using description file: E:\learning-typescript-by-examples\node_modules\@types\jquery\package.json (relative path: ./index)
                    no extension

                      Field 'browser' doesn't contain a valid alias configuration

                      E:\learning-typescript-by-examples\node_modules\@types\jquery\index doesn't exist
                    .webpack.js

                      Field 'browser' doesn't contain a valid alias configuration

                      E:\learning-typescript-by-examples\node_modules\@types\jquery\index.webpack.js doesn't exist
                    .web.js

                      Field 'browser' doesn't contain a valid alias configuration
                      E:\learning-typescript-by-examples\node_modules\@types\jquery\index.web.js doesn't exist
                    .ts

                      Field 'browser' doesn't contain a valid alias configuration
                      E:\learning-typescript-by-examples\node_modules\@types\jquery\index.ts doesn't exist
                    .js

                      Field 'browser' doesn't contain a valid alias configuration
                      E:\learning-typescript-by-examples\node_modules\@types\jquery\index.js doesn't exist

[E:\node_modules]

[E:\learning-typescript-by-examples\node_modules\@types\jquery]

[E:\learning-typescript-by-examples\node_modules\@types\jquery.webpack.js]

[E:\learning-typescript-by-examples\node_modules\@types\jquery.web.js]

[E:\learning-typescript-by-examples\node_modules\@types\jquery.ts]

[E:\learning-typescript-by-examples\node_modules\@types\jquery.js]

[E:\learning-typescript-by-examples\node_modules\@types\jquery\index]

[E:\learning-typescript-by-examples\node_modules\@types\jquery\index.webpack.js]

[E:\learning-typescript-by-examples\node_modules\@types\jquery\index.web.js]

[E:\learning-typescript-by-examples\node_modules\@types\jquery\index.ts]

[E:\learning-typescript-by-examples\node_modules\@types\jquery\index.js]
@ ./main.ts 3:8-32

Body:
You're trying to import type definitions instead of the module itself. The error reflects that and suggests that you import jquery instead.

(1,20): error TS6137: Cannot import type declaration files. Consider importing 'jquery' instead of '@types/jquery'.

The actual module is jquery, that means you need to import it as such.

import * as $ from 'jquery';

Of course you need to have it installed first, which might have been your initial problem. You can install it with:

npm install --save jquery

You might be wondering why you need two different packages to use jQuery. The reason is that jquery is a JavaScript module and TypeScript is generally not happy when it doesn't have any type information for a module and jquery doesn't provide them. You don't need the types to use the module, but you need to somehow satisfy the TypeScript compiler. Because it would be tedious to create your own type definitions, there are many type definitions for popular libraries that are made by the community. They can be found in the DefinitelyTyped repository and each of them is published to npm as @types/<package-name>.

The tutorial you're using suggests to use typings, but that is not used anymore since TypeScript 2.0 (see Deprecation Notice: Regarding TypeScript@2.0). The tutorial seems to be outdated, even at the time of the writing, and it doesn't really cover more (or in more detail) than the official webpack docs Webpack - TypeScript.


问:
Can't Return String Array in VBA
I have been combing the internet for an answer to this and can't find anything. For the life of me, I can't return a string array from a function. I've tried as a variant as well, but all I get is syntax errors.</p>

```<code>Private Function set_device_list(ByVal deviceListSize As Integer) As Variant()

    Dim loopIndex As Integer
    loopIndex = 0

    Dim firstRow As Integer
    Dim lastRow As Integer
    Dim firstColumn As Integer
    Dim lastColumn As Integer

    firstRow = 2
    lastRow = 2
    firstColumn = 4
    lastColumn = 63

    Dim deviceStartIndex As String
    Dim deviceEndIndex As String

    Dim deviceList() As Variant
    ReDim deviceList(0 To (deviceListSize - 1))

    deviceStartIndex = Cells(firstRow, firstColumn)
    deviceEndIndex = Cells(lastRow, lastColumn)

    For i = firstColumn To lastColumn

        deviceList(loopIndex) = Cells(firstRow, i).Value

        loopIndex = loopIndex + 1
        Next i
    Return deviceList

End Function
</code>```

答:
Actually there is no actual "return" function in VBA.
What you can do is that you assign the result of the function to the variable.

For example:

```<code>Dim test As Integer
Dim dummy As Integer

Function do_something(parameter) As Integer
      For i = parameter to 5
            dummy = dummy + i
      Next i
do_something = dummy
End Function

Sub your_sub
    Dim test_var As Integer

    test_var = do_something(0)
End Sub
</code>```

I hope that you can understand what I'm trying to tell

Title: Can't Return String Array in VBA

Body:
I have been combing the internet for an answer to this and can't find anything. For the life of me, I can't return a string array from a function. I've tried as a variant as well, but all I get is syntax errors.

Private Function set_device_list(ByVal deviceListSize As Integer) As Variant()

    Dim loopIndex As Integer
    loopIndex = 0

    Dim firstRow As Integer
    Dim lastRow As Integer
    Dim firstColumn As Integer
    Dim lastColumn As Integer

    firstRow = 2
    lastRow = 2
    firstColumn = 4
    lastColumn = 63

    Dim deviceStartIndex As String
    Dim deviceEndIndex As String

    Dim deviceList() As Variant
    ReDim deviceList(0 To (deviceListSize - 1))

    deviceStartIndex = Cells(firstRow, firstColumn)
    deviceEndIndex = Cells(lastRow, lastColumn)

    For i = firstColumn To lastColumn

        deviceList(loopIndex) = Cells(firstRow, i).Value

        loopIndex = loopIndex + 1
        Next i
    Return deviceList

End Function

Body:
Actually there is no actual "return" function in VBA.
What you can do is that you assign the result of the function to the variable.

For example:

Dim test As Integer
Dim dummy As Integer

Function do_something(parameter) As Integer
      For i = parameter to 5
            dummy = dummy + i
      Next i
do_something = dummy
End Function

Sub your_sub
    Dim test_var As Integer

    test_var = do_something(0)
End Sub

I hope that you can understand what I'm trying to tell


问:
How can I access a constraint throughout my class not just where I set it?
So my first thought was to make it an instance property of the class, and then set it in one method and access it in another. This didn't really work as nicely as I hoped it would so I am wondering how I can set an identifier for a constraint so I can access it where ever I need to in my class? I am not using storyboards. So I cannot use outlets and set the identifier in the GUI.

```<code>iconOne.heightAnchor.constraint(equalToConstant: 25.0).isActive = true
</code>```

I want to be able to access the above constraint so I can later on update the constant what is the best way to go about this? If it is not identifiers please let me know as I open to any suggestions.

答:
The best way to do this is definitely a class-level variable. Declare it inside the class but not inside a function, like this:</p>

```<code>class SomeClass {
    var someConstraint: NSLayoutConstraint!
    [...]
</code>```

Body:
So my first thought was to make it an instance property of the class, and then set it in one method and access it in another. This didn't really work as nicely as I hoped it would so I am wondering how I can set an identifier for a constraint so I can access it where ever I need to in my class? I am not using storyboards. So I cannot use outlets and set the identifier in the GUI.

iconOne.heightAnchor.constraint(equalToConstant: 25.0).isActive = true

I want to be able to access the above constraint so I can later on update the constant what is the best way to go about this? If it is not identifiers please let me know as I open to any suggestions.

Body:
The best way to do this is definitely a class-level variable. Declare it inside the class but not inside a function, like this:

class SomeClass {
    var someConstraint: NSLayoutConstraint!
    [...]


问:
sencha architect production build : Uncaught TypeError: c is not a constructor
I am having Extjs6 App. I am using Sencha Architect for UI . When I am building web using build setting , testing build was getting following error after build is done and onclick of my index.html.

```<code>  Uncaught Error: [Ext.createByAlias] Unrecognized alias: interaction.itemhighlight
       at Ext.Inventory.instantiateByAlias (app.js:13520)
       at Object.factory (app.js:7711) at constructor.applyInteractions (app.js:213699)
       at constructor.setter [as setInteractions] (app.js:9056)
       at constructor.addItemHighlight (app.js:206608)
       at constructor.updateTooltip (app.js:206589)
       at constructor.setter [as setTooltip] (app.js:9062)
</code>```

Please help me to resolve this error.

Regards

答:
I had a similar issue, the problem seems to be that sencha is not importing the library when is creating the production or testing builds, you should add the library you are missing in "requires" section of the view that uses it in this case i think the library is 'Ext.chart.interactions.ItemHighlight' after this all your builds should work properly because sencha now knows that it needs this library in the build.
Sorry for my english, hope it helps.

Body:
I am having Extjs6 App. I am using Sencha Architect for UI . When I am building web using build setting , testing build was getting following error after build is done and onclick of my index.html.

  Uncaught Error: [Ext.createByAlias] Unrecognized alias: interaction.itemhighlight
       at Ext.Inventory.instantiateByAlias (app.js:13520)
       at Object.factory (app.js:7711) at constructor.applyInteractions (app.js:213699)
       at constructor.setter [as setInteractions] (app.js:9056)
       at constructor.addItemHighlight (app.js:206608)
       at constructor.updateTooltip (app.js:206589)
       at constructor.setter [as setTooltip] (app.js:9062)

Please help me to resolve this error.

Regards


问:
How can I allow multiple users to access/edit a microsoft access database?
Now I know right off the bat that Microsoft access isn't the ideal client for multiple users accessing it but it's the only one I've got right now. I have built a small program as a sort of inventory management system. There are currently three users that will be using it regularly and at the same time. One issue I am running into with this is that sometimes the database will not be accessible and will give an error stating that the file is already in use by "so and so" user. The other issue is that I'm getting a similar error every now and then where it states "The database has been placed in a state by user  on machine  that prevents it from being opened or locked". I am connecting to the database through an ACE OLEDB connection using the line below

```<code>con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Tool & Cutter Grinding\Tool Cutter Database.accdb;Persist Security Info = False"
</code>```

I have also changed some of the settings in the actual access database such as:

Enable all macros

Add the folder the database is in to the trusted locations list

Confirm that the database is set to open in shared mode by default

I don't know if there is something small I've missed or a setting I need to change but as of yet, the problem is still persisting.

Below is an example of how I am using the database. I am using string based SQL commands but am not too familiar with DataSet/DataTable/etc. items, so I may be doing something incorrectly.

```<code> 'close connection from any previous session
    con.Close()

    'clear dataset so as not to append data
    ds.Clear()

    'Select SQL query that selects ALL records from a table
    Dim str As String = "SELECT * FROM " & "[" & table & "]" & ""
    con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Tool & Cutter Grinding\Tool Cutter Database.accdb;Persist Security Info = False"

    'use try catch statement to open the connection
    Try
        con.Open()
    Catch ex As Exception
        MsgBox(Convert.ToString(ex))
    End Try

    'use try catch statement to add a table (dt) to the dataset (ds) in order to store values
    Try
        ds.Tables.Add(dt)
    Catch ex As Exception

    End Try

    'create new dataadapter object using the sql string from above and the connection created above
    da = New OleDbDataAdapter(str, con)

    'create new command builder in order to excecute the SELECT SQL statement using the dataadapter created (da)
    'specify prefix and suffix for cb
    Dim cb = New OleDbCommandBuilder(da) With {
        .QuotePrefix = "[",
        .QuoteSuffix = "]"
    }

    'use try catch statement to fill the datatable (dt) using the dataadapter (da)
    Try
        da.Fill(dt)
    Catch ex As Exception
        MsgBox(Convert.ToString(ex))
    End Try

    'set the datasource of the datagridview to the datatable
    dgv.DataSource = dt.DefaultView

    'close the connection to the database
    con.Close()
</code>```

答: Go to your Back-End Access DB file. File > Options > Client Settings. For your Use Case No Locks should be fine, but Edited record setting will work as well if you need it

Body:
Now I know right off the bat that Microsoft access isn't the ideal client for multiple users accessing it but it's the only one I've got right now. I have built a small program as a sort of inventory management system. There are currently three users that will be using it regularly and at the same time. One issue I am running into with this is that sometimes the database will not be accessible and will give an error stating that the file is already in use by "so and so" user. The other issue is that I'm getting a similar error every now and then where it states "The database has been placed in a state by user  on machine  that prevents it from being opened or locked". I am connecting to the database through an ACE OLEDB connection using the line below

con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Tool & Cutter Grinding\Tool Cutter Database.accdb;Persist Security Info = False"

I have also changed some of the settings in the actual access database such as:

Enable all macros

Add the folder the database is in to the trusted locations list

Confirm that the database is set to open in shared mode by default

I don't know if there is something small I've missed or a setting I need to change but as of yet, the problem is still persisting.

Below is an example of how I am using the database. I am using string based SQL commands but am not too familiar with DataSet/DataTable/etc. items, so I may be doing something incorrectly.

 'close connection from any previous session
    con.Close()

    'clear dataset so as not to append data
    ds.Clear()

    'Select SQL query that selects ALL records from a table
    Dim str As String = "SELECT * FROM " & "[" & table & "]" & ""
    con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=P:\Tool & Cutter Grinding\Tool Cutter Database.accdb;Persist Security Info = False"

    'use try catch statement to open the connection
    Try
        con.Open()
    Catch ex As Exception
        MsgBox(Convert.ToString(ex))
    End Try

    'use try catch statement to add a table (dt) to the dataset (ds) in order to store values
    Try
        ds.Tables.Add(dt)
    Catch ex As Exception

    End Try

    'create new dataadapter object using the sql string from above and the connection created above
    da = New OleDbDataAdapter(str, con)

    'create new command builder in order to excecute the SELECT SQL statement using the dataadapter created (da)
    'specify prefix and suffix for cb
    Dim cb = New OleDbCommandBuilder(da) With {
        .QuotePrefix = "[",
        .QuoteSuffix = "]"
    }

    'use try catch statement to fill the datatable (dt) using the dataadapter (da)
    Try
        da.Fill(dt)
    Catch ex As Exception
        MsgBox(Convert.ToString(ex))
    End Try

    'set the datasource of the datagridview to the datatable
    dgv.DataSource = dt.DefaultView

    'close the connection to the database
    con.Close()


问:
Splitting configuration in Grails 3
I'm currently in the process of migrating existing grails 2.5.x applications to grails 3.1.

What I really liked in the previous grails versions was the possibility to modularize my config files over multiple files with the grails.config.locations option, like:

```<code>Config.groovy
App.groovy
Logging.groovy
SpringSecurity.groovy
Quartz.groovy
...
</code>```

As grails 3 is now based on spring boot, it uses a different configuration approach. But I couldn't figure a way to load my configuration from multiple files.

I've read about the spring.config.location option in spring, but it doesn't seem to do what I want. It seems to search for the application.groovy/application.yml in a different location, but that doesn't bring me back my splitted configuration files.

And I also do not like the fact that this option has to be set as an environment parameter. The application should just work without configuring extra environment variables or parameters.

That leads to my questions:

Is it possible to bring back the configuration possibilities of the previous grails versions?

Are there other methods in grails or spring boot to implement similar functionality?

答:
There is now a Grails 3 plugin that mimics the way configuration files were handled in Grails 2:

http://plugins.grails.org/plugin/grails/external-config

Title: Splitting configuration in Grails 3

Body:
I'm currently in the process of migrating existing grails 2.5.x applications to grails 3.1.

What I really liked in the previous grails versions was the possibility to modularize my config files over multiple files with the grails.config.locations option, like:

Config.groovy
App.groovy
Logging.groovy
SpringSecurity.groovy
Quartz.groovy
...

As grails 3 is now based on spring boot, it uses a different configuration approach. But I couldn't figure a way to load my configuration from multiple files.

I've read about the spring.config.location option in spring, but it doesn't seem to do what I want. It seems to search for the application.groovy/application.yml in a different location, but that doesn't bring me back my splitted configuration files.

And I also do not like the fact that this option has to be set as an environment parameter. The application should just work without configuring extra environment variables or parameters.

That leads to my questions:

Is it possible to bring back the configuration possibilities of the previous grails versions?

Are there other methods in grails or spring boot to implement similar functionality?


问:
QML adding labels dynamically
Allright, i'm trying to make a kind of messenger using qml. i have a textarea and a send button. when send button is clicked the text inside the textarea will be displayed somewhere on the screen. but any other changes in text area will change the context of label. i tried using createObject(...) but it didn't help. is there any other way for creating labels (or any other component) dynamically?</p>

```<code>import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
import QtQuick.Controls.Material 2.1
ApplicationWindow {

    visible: true
    width: 640
    height: 480
    property var xPosition : 500
    property var yPosition: 200
    title: qsTr("server")
    Rectangle{
        width: parent.width
        height: parent.height

        Button{
            id: sentButton
            width: parent.width / 14
            x: parent.height + 112
            y: parent.width - 200
            Material.accent: Material.Blue
            Material.background: Material.DeepOrange
            Text {
                id: name
                text: qsTr("Send")
                color: "white"
                x:parent.width / 4
                y:parent.height / 4
            }
            onClicked: {
                //add label with the context of textarea

            }
        }

        Rectangle{
            id:back
            height: sentButton.height
            width: parent.width - sentButton.width
            x:0
            y: 435
            color: "white"
            border.width: 0.5

            TextArea{
                id:search
                placeholderText: qsTr("Search")
                x:7
                width: parent.width - 25
                background: null
            }

        }
    }

}
</code>```

答:
Instead of creating Label manually, I would add a row to a model (like ListModel) and display it with a ListView.

The ListView will instantiate a delegate for each row of the model, it's cleaner than doing it manually. Plus you get the scrolling behaviour for free.

Example here :

```<code>import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
import QtQuick.Controls.Material 2.1

ApplicationWindow {

    visible: true
    width: 640
    height: 480
    Material.accent: Material.DeepOrange

    ListModel {
        id: messageModel
    }

    ColumnLayout {
        anchors { fill: parent; margins: 8 }
        spacing: 16
        ListView {
            Layout.fillWidth: true; Layout.fillHeight: true
            model: messageModel
            delegate: ItemDelegate { text: model.message }
        }
        RowLayout {
            spacing: 16
            Layout.fillWidth: true; Layout.fillHeight: false
            TextField {
                id: textField
                Layout.fillWidth: true; Layout.fillHeight: true
            }
            Button {
                Material.foreground: "white"; Material.background: Material.DeepOrange
                Layout.fillHeight: true
                text: "Send"
                onClicked: {
                    messageModel.append({message: textField.text});
                    textField.text = "";
                }
            }
        }
    }
}
</code>```

Here, the Button will append a new row to the ListModel with the TextField's text as the message role.
Then the ListView instantiates for each row of the model a ItemDelegate displaying the message role.

Title: QML adding labels dynamically

Body:
Allright, i'm trying to make a kind of messenger using qml. i have a textarea and a send button. when send button is clicked the text inside the textarea will be displayed somewhere on the screen. but any other changes in text area will change the context of label. i tried using createObject(...) but it didn't help. is there any other way for creating labels (or any other component) dynamically?

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
import QtQuick.Controls.Material 2.1
ApplicationWindow {

    visible: true
    width: 640
    height: 480
    property var xPosition : 500
    property var yPosition: 200
    title: qsTr("server")
    Rectangle{
        width: parent.width
        height: parent.height

        Button{
            id: sentButton
            width: parent.width / 14
            x: parent.height + 112
            y: parent.width - 200
            Material.accent: Material.Blue
            Material.background: Material.DeepOrange
            Text {
                id: name
                text: qsTr("Send")
                color: "white"
                x:parent.width / 4
                y:parent.height / 4
            }
            onClicked: {
                //add label with the context of textarea

            }
        }

        Rectangle{
            id:back
            height: sentButton.height
            width: parent.width - sentButton.width
            x:0
            y: 435
            color: "white"
            border.width: 0.5

            TextArea{
                id:search
                placeholderText: qsTr("Search")
                x:7
                width: parent.width - 25
                background: null
            }

        }
    }

}

Body:
Instead of creating Label manually, I would add a row to a model (like ListModel) and display it with a ListView.

The ListView will instantiate a delegate for each row of the model, it's cleaner than doing it manually. Plus you get the scrolling behaviour for free.

Example here :

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
import QtQuick.Controls.Material 2.1

ApplicationWindow {

    visible: true
    width: 640
    height: 480
    Material.accent: Material.DeepOrange

    ListModel {
        id: messageModel
    }

    ColumnLayout {
        anchors { fill: parent; margins: 8 }
        spacing: 16
        ListView {
            Layout.fillWidth: true; Layout.fillHeight: true
            model: messageModel
            delegate: ItemDelegate { text: model.message }
        }
        RowLayout {
            spacing: 16
            Layout.fillWidth: true; Layout.fillHeight: false
            TextField {
                id: textField
                Layout.fillWidth: true; Layout.fillHeight: true
            }
            Button {
                Material.foreground: "white"; Material.background: Material.DeepOrange
                Layout.fillHeight: true
                text: "Send"
                onClicked: {
                    messageModel.append({message: textField.text});
                    textField.text = "";
                }
            }
        }
    }
}

Here, the Button will append a new row to the ListModel with the TextField's text as the message role.
Then the ListView instantiates for each row of the model a ItemDelegate displaying the message role.


问:
Where is the webpack.config.js in angular-cli new project?
I'm looking into webpack and also angular-cli, and even though angular-cli is supposed to use webpack, I can't see any webpack.config.js file when I create a new project with ng new

Does anybody know how does this work in angular-cli?

答: You can use $ ng eject to generate webpack.config.js in the root folder of your project.


问:
Disable error reporting entirely in Laravel production?
I would like to disable error reporting entirely on production, because we have some very old code we still need to fix but for now does work (yes I don't like it either). We cannot fix everything in a few days, so we need to just supress the warnings and exceptions like we always did.

The real problem is that it already throws an exception on a simple lazy bug like (because var is not defined)

```<code>if(!$var) {
     // do whatever
}
</code>```

tried

APP_DEBUG=false

APP_LOG_LEVEL=emergency

```<code>display_errors(false);
set_error_handler(null);
set_exception_handler(null);
</code>```

But it still shows an ErrorException

Undefined variable: script_name_vars_def

edit: The code works like this

web.php

```<code>Route::any('/someroute', 'somecontroller@controllerFunc');
</code>```

somecontroller.php

```<code>public controllerFunc() {
    ob_start();
    require '/old_index.php';
    $html = ob_get_clean();

    return response($html);
}
</code>```

This way we use Laravel routing without having to rewrite the old code immediately.

I know I can fix this warning very easy, but there are many, many more of these errors and we need to use Laravel routing now. Fix the problems later.

ideas

Use some wildcard in $dontReport.

Use a @ suppression at the right place

Can it be http://php.net/manual/en/scream.examples-simple.php

edit to explain after which steps middleware didn't work

1) create midddleware

```<code>php artisan make:middleware SuppressExceptions
</code>```

2) Write it

SuppressExceptions.php

```<code>public function handle($request, Closure $next)
{
    error_reporting(0);
    return $next($request);
}
</code>```

3) Register

laravel/app/Http/Kernel.php

```<code>protected $middlewareGroups = [
   'web' => [
       \App\Http\Middleware\SuppressExceptions::class,
],
</code>```

答:
If the problem is that you are seeing the 'Whoops something went wrong' page, you could fix that with the answer @alepeino wrote:

https://stackoverflow.com/a/44862789/2777970

But I'd change the render method to:

```<code>public function render($request, Exception $exception)
{
    if (!config('app.debug')) {
        error_reporting(0);

        return response('nothing', 500);
    }

    return parent::render($request, $exception);
}
</code>```

This render method (the parent) is the one that builds and returns the html for the "Whoops" page, so if you overwrite it, you should be cool.

To change de debug config, check if your config/app.php has the debug options using the ENV value APP_DEBUG, and on your production .env, check it's set to false (APP_DEBUG=false).

Body:
I would like to disable error reporting entirely on production, because we have some very old code we still need to fix but for now does work (yes I don't like it either). We cannot fix everything in a few days, so we need to just supress the warnings and exceptions like we always did.

The real problem is that it already throws an exception on a simple lazy bug like (because var is not defined)

if(!$var) {
     // do whatever
}

tried

APP_DEBUG=false

APP_LOG_LEVEL=emergency

display_errors(false);
set_error_handler(null);
set_exception_handler(null);

But it still shows an ErrorException

Undefined variable: script_name_vars_def

edit: The code works like this

web.php

Route::any('/someroute', 'somecontroller@controllerFunc');

somecontroller.php

public controllerFunc() {
    ob_start();
    require '/old_index.php';
    $html = ob_get_clean();

    return response($html);
}

This way we use Laravel routing without having to rewrite the old code immediately.

I know I can fix this warning very easy, but there are many, many more of these errors and we need to use Laravel routing now. Fix the problems later.

ideas

Use some wildcard in $dontReport.

Use a @ suppression at the right place

Can it be http://php.net/manual/en/scream.examples-simple.php

edit to explain after which steps middleware didn't work

1) create midddleware

php artisan make:middleware SuppressExceptions

2) Write it

SuppressExceptions.php

public function handle($request, Closure $next)
{
    error_reporting(0);
    return $next($request);
}

3) Register

laravel/app/Http/Kernel.php

protected $middlewareGroups = [
   'web' => [
       \App\Http\Middleware\SuppressExceptions::class,
],

Body:
If the problem is that you are seeing the 'Whoops something went wrong' page, you could fix that with the answer @alepeino wrote:

https://stackoverflow.com/a/44862789/2777970

But I'd change the render method to:

public function render($request, Exception $exception)
{
    if (!config('app.debug')) {
        error_reporting(0);

        return response('nothing', 500);
    }

    return parent::render($request, $exception);
}

This render method (the parent) is the one that builds and returns the html for the "Whoops" page, so if you overwrite it, you should be cool.

To change de debug config, check if your config/app.php has the debug options using the ENV value APP_DEBUG, and on your production .env, check it's set to false (APP_DEBUG=false).


问:
Why are my actionErrors and fieldErrors displayed with braces []?
Once the pages have captured errors within my Struts 2 application the errors are displayed correctly from my resource bundles however they are always displayed with a braces [].

For example:

```<code>[first name must not be empty]
</code>```

These are displayed through the tags:

```<code><s:actionerror />

<s:iterator value="fieldErrors">
   <s:property value="value" />
</s:iterator>
</code>```

These come through the Action-validation.xml and setting a addFieldError() through the validation method

Is this something to do with my theme being set to simple ? I can't see anything in documentation or anything through other posts.

答:
Without default xhtml theme it would render objects as it's printed toString(), i.e. formatting an array with brackets.

Render field errors if they exists the specific layout of the
  rendering depends on the theme itself. Empty (null or blank string)
  errors will not be printed. The field error strings will be html
  escaped by default.

The code to display errors should look like

```<code><s:if test="hasFieldErrors()">
   <div class="errors">
      <s:fielderror />
   </div>
</s:if>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Once the pages have captured errors within my Struts 2 application the errors are displayed correctly from my resource bundles however they are always displayed with a braces [].

For example:

[first name must not be empty]

These are displayed through the tags:

<s:actionerror />

<s:iterator value="fieldErrors">
   <s:property value="value" />
</s:iterator>

These come through the Action-validation.xml and setting a addFieldError() through the validation method

Is this something to do with my theme being set to simple ? I can't see anything in documentation or anything through other posts.

Body:
Without default xhtml theme it would render objects as it's printed toString(), i.e. formatting an array with brackets.

Render field errors if they exists the specific layout of the
  rendering depends on the theme itself. Empty (null or blank string)
  errors will not be printed. The field error strings will be html
  escaped by default.

The code to display errors should look like

<s:if test="hasFieldErrors()">
   <div class="errors">
      <s:fielderror />
   </div>
</s:if>