问:
Is it worth pooling byte[] and char[] arrays or is it better to just create
My code does a lot of Input/Output and this often involves the creation of temporary arrays to hold bytes or chars of some size - i often use 4096. Im starting to wonder - without actual tests - to verify if it would be better to pool these arrays. My code would change to something like this

```<code>take array from pool
try {
   read from one inputStream
   write to another outputstream using array
} finally {
   return array to pool
}
</code>```

it is quicker to take or simply create a byte with 4096 which means some work is required to alloc mem on the heap, clear the 4096 bytes etc.

a pool seems simpler after all its probably just checking a list taking from the list and returning the array.

UPDATE
I wrote a small program that did two things, created arrays and used an apache commons pool. Both looped a lot of times (100*100*100) and created/took, filled array, then released. I added a few goes in the beginning to warm up the jit and ignored the results of those. Each run ran the create and pool forms a dozen times, alternating between the two.

There was little difference between the pool and create forms. However if i added a clear array to the callback that is fired by apache commons pool when an instance is returned to a pool, the pool became that much slower thanthe created form.

答:
You could consider using the java.nio.Buffer classes. For example, you could have something like this:

```<code>class ReadWorker {
    private ByteBuffer buffer = ByteBuffer.allocate(4096);

    public void work() {
        fillBufferWithData();
        buffer.flip();
        doSomethingWithData();
        buffer.clear();
    }
}
</code>```

Each call to work will clear the buffer ready for the next call but you won't be allocating/deallocating memory all the time. flip and clear are very fast operations.

Having one Buffer per worker will be easier than creating a pool with it's associated synchronisation fun-and-games.

EDIT: Note that I'm assuming you generate a fixed pool of workers so you're not creating new Buffer objects all the time.

If you can't have a fixed worker pool then you could consider creating a pool of Buffer objects rather than raw byte arrays. It depends on how you are using them.

Body:
My code does a lot of Input/Output and this often involves the creation of temporary arrays to hold bytes or chars of some size - i often use 4096. Im starting to wonder - without actual tests - to verify if it would be better to pool these arrays. My code would change to something like this

take array from pool
try {
   read from one inputStream
   write to another outputstream using array
} finally {
   return array to pool
}

it is quicker to take or simply create a byte with 4096 which means some work is required to alloc mem on the heap, clear the 4096 bytes etc.

a pool seems simpler after all its probably just checking a list taking from the list and returning the array.

UPDATE
I wrote a small program that did two things, created arrays and used an apache commons pool. Both looped a lot of times (100*100*100) and created/took, filled array, then released. I added a few goes in the beginning to warm up the jit and ignored the results of those. Each run ran the create and pool forms a dozen times, alternating between the two.

There was little difference between the pool and create forms. However if i added a clear array to the callback that is fired by apache commons pool when an instance is returned to a pool, the pool became that much slower thanthe created form.

Body:
You could consider using the java.nio.Buffer classes. For example, you could have something like this:

class ReadWorker {
    private ByteBuffer buffer = ByteBuffer.allocate(4096);

    public void work() {
        fillBufferWithData();
        buffer.flip();
        doSomethingWithData();
        buffer.clear();
    }
}

Each call to work will clear the buffer ready for the next call but you won't be allocating/deallocating memory all the time. flip and clear are very fast operations.

Having one Buffer per worker will be easier than creating a pool with it's associated synchronisation fun-and-games.

EDIT: Note that I'm assuming you generate a fixed pool of workers so you're not creating new Buffer objects all the time.

If you can't have a fixed worker pool then you could consider creating a pool of Buffer objects rather than raw byte arrays. It depends on how you are using them.


来源: stackexchange

答:
First, change your field named Group to something like Group_Name. GROUP is a reserved keyword, and if it is not causing you problems now it probably will later.

Second, you should ask yourself what you are really after. The following query should generate your desired result. It adds an additional condition where the IDs that are returned are the lowest numbered ID in each group.

```<code>SELECT * FROM products
WHERE sold = 0
      AND ID IN (SELECT MIN(ID) FROM products WHERE sold = 0 GROUP BY Group_Name)
</code>```

Why do you want that, though? That is not a normal desired end state. You should ask yourself why you care about the ID. It looks like your goal is to figure out which products have not sold anything. In that case, I would recommend this instead:

```<code>SELECT DISTINCT Group_Name, Name
FROM products
WHERE sold = 0
ORDER BY Group_Name, Name
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to select only one record of each category?

Body:
Products :
--------------------------------------------
|   ID   |   Group   |   Name   |   Sold   |
--------------------------------------------
|   1    |     A     |   Dell   |    0     |
--------------------------------------------
|   2    |     A     |   Dell   |    0     |
--------------------------------------------
|   3    |     B     |   Dell   |    1     |
--------------------------------------------
|   4    |     B     |   Dell   |    1     |
--------------------------------------------
|   5    |     C     |   Dell   |    0     |
--------------------------------------------
|   6    |     C     |   Dell   |    1     |
--------------------------------------------

Hi everyone, i have a table (products) stored in MySql with many records, for now i'm using this query SELECT * FROM products WHERE sold = 0, in results i get :

--------------------------------------------
|   ID   |   Group   |   Name   |   Sold   |
--------------------------------------------
|   1    |     A     |   Dell   |    0     |
--------------------------------------------
|   2    |     A     |   Dell   |    0     |
--------------------------------------------
|   5    |     C     |   Dell   |    0     |
--------------------------------------------

i want to get only one record from each group, so the results will be like :

--------------------------------------------
|   ID   |   Group   |   Name   |   Sold   |
--------------------------------------------
|   1    |     A     |   Dell   |    0     |
--------------------------------------------
|   5    |     C     |   Dell   |    0     |
--------------------------------------------

Body:
First, change your field named Group to something like Group_Name. GROUP is a reserved keyword, and if it is not causing you problems now it probably will later.

Second, you should ask yourself what you are really after. The following query should generate your desired result. It adds an additional condition where the IDs that are returned are the lowest numbered ID in each group.

SELECT * FROM products
WHERE sold = 0
      AND ID IN (SELECT MIN(ID) FROM products WHERE sold = 0 GROUP BY Group_Name)

Why do you want that, though? That is not a normal desired end state. You should ask yourself why you care about the ID. It looks like your goal is to figure out which products have not sold anything. In that case, I would recommend this instead:

SELECT DISTINCT Group_Name, Name
FROM products
WHERE sold = 0
ORDER BY Group_Name, Name


问:
OData services with Elastic search
I am new to OData services.I have written a query to retrieve the specific field with null values.I build the query in OData and pass it on to elastic search to retrieve data.But the query seems to be not working.</p>

```<code>The query is as follows:
$filter=assignedToEM eq  null.
I have also tried giving as: $filter=assignedToEM eq  'null'

The query has been built as :
{
 "from" : 0,
 "size" : 15,
 "query":{
       "bool" : {
           "must_not" : {
                    "term" : {
                        "assignedToEM" : "null"
                               }
                         }
                 }
          }
 }
In elastic search schema,The not_null value for assignedToEM is given as "_null_".

It would be really helpful if i get a solution for this as soon as possible.
Thanks.
</code>```

答:
Use Olastic - open source implementation of the OData services for Elasticsearch.

You can use sources as an example or get dependency from maven

Title: OData services with Elastic search

Body:
I am new to OData services.I have written a query to retrieve the specific field with null values.I build the query in OData and pass it on to elastic search to retrieve data.But the query seems to be not working.

The query is as follows:
$filter=assignedToEM eq  null.
I have also tried giving as: $filter=assignedToEM eq  'null'

The query has been built as :
{
 "from" : 0,
 "size" : 15,
 "query":{
       "bool" : {
           "must_not" : {
                    "term" : {
                        "assignedToEM" : "null"
                               }
                         }
                 }
          }
 }
In elastic search schema,The not_null value for assignedToEM is given as "_null_".

It would be really helpful if i get a solution for this as soon as possible.
Thanks.


问:
domPDF how to save a file without viewing ? LARAVEL
Below is my current code I want to store the pdf inmy files without view it . is it possible ? when user store the data for $bus object on db. I want to store below pdf on my local.</p>

```<code> $user = Festivals::where('id', $bus->id)->first();
        $pdf = PDF::loadView('user.view', compact('user'));
        $name = 'Ref_no' . $user->ref_no . '_' . date('m-d-Y') . '.pdf';
      return $pdf->download($name);
</code>```

答:
if $pdf is a DomPDF object, use its output() method to get pdf content as a string and simply put it in a file;

```<code>$content = $pdf->output();
file_put_contents('/path/to/your/file', $content);
</code>```

Body:
Below is my current code I want to store the pdf inmy files without view it . is it possible ? when user store the data for $bus object on db. I want to store below pdf on my local.

 $user = Festivals::where('id', $bus->id)->first();
        $pdf = PDF::loadView('user.view', compact('user'));
        $name = 'Ref_no' . $user->ref_no . '_' . date('m-d-Y') . '.pdf';
      return $pdf->download($name);

Body:
if $pdf is a DomPDF object, use its output() method to get pdf content as a string and simply put it in a file;

$content = $pdf->output();
file_put_contents('/path/to/your/file', $content);


问:
Convert string of dictionary to list with removal of single quotes
I have one string having dictionary, I want to convert it into a list, but unable to remove single quote while doing the same.

Can someone help me in figuring out what is missing here?

```<code>>>> a = '{"src_ports": [7] , "dst_ports": [8]}'
</code>```

What I want is following:

```<code>[{"src_ports": [7] , "dst_ports": [8]}]
</code>```

But what I get is following:

```<code>>>> a = [a]
>>> a
['{"src_ports": [7] , "dst_ports": [8]}']
</code>```

Edited:
With ast, order of dictionary elements gets changed, I need to keep it intact.

```<code>>>> import ast
>>> b = [ast.literal_eval(a)]
>>> b
[{'dst_ports': [8], 'src_ports': [7]}]
</code>```

答:
ast.literal_eval

```<code>>>> import ast
>>> [ast.literal_eval(a)]
[{'src_ports': [7], 'dst_ports': [8]}]
</code>```

json.loads

(Preserves order.)

```<code>>>> import collections
>>> import json
>>> [json.loads(a, object_pairs_hook=collections.OrderedDict)]
[OrderedDict([('src_ports', [7]), ('dst_ports', [8])])]
</code>```

Note that an OrderedDict is still a dictionary, so you can access its elements the same way you would a normal one.

Body:
I have one string having dictionary, I want to convert it into a list, but unable to remove single quote while doing the same.

Can someone help me in figuring out what is missing here?

>>> a = '{"src_ports": [7] , "dst_ports": [8]}'

What I want is following:

[{"src_ports": [7] , "dst_ports": [8]}]

But what I get is following:

>>> a = [a]
>>> a
['{"src_ports": [7] , "dst_ports": [8]}']

Edited:
With ast, order of dictionary elements gets changed, I need to keep it intact.

>>> import ast
>>> b = [ast.literal_eval(a)]
>>> b
[{'dst_ports': [8], 'src_ports': [7]}]

Body:
ast.literal_eval

>>> import ast
>>> [ast.literal_eval(a)]
[{'src_ports': [7], 'dst_ports': [8]}]

json.loads

(Preserves order.)

>>> import collections
>>> import json
>>> [json.loads(a, object_pairs_hook=collections.OrderedDict)]
[OrderedDict([('src_ports', [7]), ('dst_ports', [8])])]

Note that an OrderedDict is still a dictionary, so you can access its elements the same way you would a normal one.

ContentLicense: CC BY-SA 4.0


问:
ASP.NET Core Localization with help of SharedResources
Hi I have a question about the SharedResources file. It is glanced over in the tutorial here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization, and I'm not sure if I get it correctly.

I am supposed to create a SharedResources.cs class, but where should i put it and should it be empty or do I need to fill it with some data?

Same goes for the resource file, should I create a SharedResources.da.resx file and put all my shared strings there? Where should it go?

And when I use IHtmlLocalizer<SharedResources> do I just write @using and point it to the namespace where SharedResources.cs resides?

I tried putting SharedResources.cs and SharedResources.da.resx in the Resources folder and use it to change website language to Danish, but it does not work. Using dedicated Resource file like Index.da.resx and IViewLocalizer works fine, but IHtmlLocalizer<SharedResources> does not seem to work.

When I looked at the example project linked to at the bottom of the page I didn't find any place where SharedResources is used, it would be great if somebody updated it with an example of that.

Here's how I tried to do it:

Views/Home/Index.cshtml:

```<code>@using Funkipedia.Resources
@using Microsoft.AspNetCore.Mvc.Localization
@inject IHtmlLocalizer<Shared> SharedLocalizer
...
<p>@SharedLocalizer["Hei"]</p>
...
</code>```

At top of ConfigureServices in Startup.cs:

```<code>services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
  .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
  .AddDataAnnotationsLocalization();
</code>```

At top of Configure in Startup.cs:

```<code>var supportedCultures = new List<CultureInfo>
{
       new CultureInfo("nb-NO"),
       new CultureInfo("sv-SE"),
       new CultureInfo("da-DK")
};

app.UseRequestLocalization(new RequestLocalizationOptions
{
       DefaultRequestCulture = new RequestCulture("nb-NO"),
       SupportedCultures = supportedCultures,
       SupportedUICultures = supportedCultures
});
</code>```

Resources folder contains empty class called Shared.cs and Shared.da.resx which contains shared strings. Do I maybe need to change the name of it to SharedResources.cs and SharedResources.da.resx?

答:
I'd like to add the setup that's working for my team as well. It's based on the same principle as yours (of course), but I believe it allows some more flexibility on your files location, as it does not force you to put resource-related files in project root.

My understanding is that IStringLocalizer<T> has the concept of a placeholder Type, whose fullname will be converted into a relative path and used to find the actual resource file. To do this conversion, it also uses info from LocalizationOptions.ResourcesPath, if any.

Say you have:

// in ProjectRoot\Startup.cs

services.AddLocalization(opts =>
{
  opts.ResourcesPath = "Localized";
});

// in ProjectRoot\Area\Whatever\SomeClass.cs

namespace Com.Company.Project.Area.Whatever
{
  public class SomeClass
  {
    public SomeClass(IStringLocalizer<SomeClass> localizer)
    {
      // ...
    }
  }
}
```

<p>So here's what happens, step-by-step, just to give an idea:</p>

<ol>
<li><code>SomeClass</code> fullname: <code>Com.Company.Project.Area.Whatever.SomeClass</code></li>
<li>convert that to .resx file path: <code>Com\Company\Project\Area\Whatever\SomeClass.resx</code></li>
<li>prefix that with <code>ResourcesPath</code> content: <code>Localized\Com\Company\Project\Area\Whatever\SomeClass.resx</code> </li>
</ol>

<p>That's the actual path where resource file(s) will be looked up.</p>

<p>So, all in all, you can place your <code>SharedResources.cs</code> empty class wherever you want, as long as you replicate its fullname as a path under <code>ResourcesPath</code> folder under project root.</p>

<p>In the example:</p>

```\
--Area
  --Whatever
    --SomeClass.cs
--Localized
  --Com
    --Company
      --Project
        --Area
          --Whatever
            --SomeClass.resx
            --SomeClass.fr.resx
            --SomeClass.da.resx
```

Under the cover, that directory tree is needed because classes generated out of resx file will take their namespace from the directory tree, and also because string localizer will not strip root namespace when prefixing placeholder type with ResourcesPath.

Body:
Hi I have a question about the SharedResources file. It is glanced over in the tutorial here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization, and I'm not sure if I get it correctly.

I am supposed to create a SharedResources.cs class, but where should i put it and should it be empty or do I need to fill it with some data?

Same goes for the resource file, should I create a SharedResources.da.resx file and put all my shared strings there? Where should it go?

And when I use IHtmlLocalizer<SharedResources> do I just write @using and point it to the namespace where SharedResources.cs resides?

I tried putting SharedResources.cs and SharedResources.da.resx in the Resources folder and use it to change website language to Danish, but it does not work. Using dedicated Resource file like Index.da.resx and IViewLocalizer works fine, but IHtmlLocalizer<SharedResources> does not seem to work.

When I looked at the example project linked to at the bottom of the page I didn't find any place where SharedResources is used, it would be great if somebody updated it with an example of that.

Here's how I tried to do it:

Views/Home/Index.cshtml:

@using Funkipedia.Resources
@using Microsoft.AspNetCore.Mvc.Localization
@inject IHtmlLocalizer<Shared> SharedLocalizer
...

@SharedLocalizer["Hei"]

...

At top of ConfigureServices in Startup.cs:

services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
  .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
  .AddDataAnnotationsLocalization();

At top of Configure in Startup.cs:

var supportedCultures = new List<CultureInfo>
{
       new CultureInfo("nb-NO"),
       new CultureInfo("sv-SE"),
       new CultureInfo("da-DK")
};

app.UseRequestLocalization(new RequestLocalizationOptions
{
       DefaultRequestCulture = new RequestCulture("nb-NO"),
       SupportedCultures = supportedCultures,
       SupportedUICultures = supportedCultures
});

Resources folder contains empty class called Shared.cs and Shared.da.resx which contains shared strings. Do I maybe need to change the name of it to SharedResources.cs and SharedResources.da.resx?

Body:
I'd like to add the setup that's working for my team as well. It's based on the same principle as yours (of course), but I believe it allows some more flexibility on your files location, as it does not force you to put resource-related files in project root.

My understanding is that IStringLocalizer<T> has the concept of a placeholder Type, whose fullname will be converted into a relative path and used to find the actual resource file. To do this conversion, it also uses info from LocalizationOptions.ResourcesPath, if any.

Say you have:

// in ProjectRoot\Startup.cs

services.AddLocalization(opts =>
{
  opts.ResourcesPath = "Localized";
});

// in ProjectRoot\Area\Whatever\SomeClass.cs

namespace Com.Company.Project.Area.Whatever
{
  public class SomeClass
  {
    public SomeClass(IStringLocalizer<SomeClass> localizer)
    {
      // ...
    }
  }
}

So here's what happens, step-by-step, just to give an idea:

SomeClass fullname: Com.Company.Project.Area.Whatever.SomeClass

convert that to .resx file path: Com\Company\Project\Area\Whatever\SomeClass.resx

prefix that with ResourcesPath content: Localized\Com\Company\Project\Area\Whatever\SomeClass.resx

That's the actual path where resource file(s) will be looked up.

So, all in all, you can place your SharedResources.cs empty class wherever you want, as long as you replicate its fullname as a path under ResourcesPath folder under project root.

In the example:

\
--Area
  --Whatever
    --SomeClass.cs
--Localized
  --Com
    --Company
      --Project
        --Area
          --Whatever
            --SomeClass.resx
            --SomeClass.fr.resx
            --SomeClass.da.resx

Under the cover, that directory tree is needed because classes generated out of resx file will take their namespace from the directory tree, and also because string localizer will not strip root namespace when prefixing placeholder type with ResourcesPath.


问:
VueJS: what does an html attribute prefixed with a colon signify?
Example:

```<code><vue-select
  class="vue-select1"
  name="select1"
  :options="options1"
  :model.sync="result1"
></vue-select>
</code>```

What is the meaning the colon in front of :options and :model.sync here? I've searched all over the internet and can't find an answer anywhere.

Example seen here: https://github.com/Haixing-Hu/vue-select

答:
To add to thanksd's answer:

Those are dynamic attributes. Basically it means that Vue.js will let you set the value of those attributes to variables, and when the value of those variables updates, the value of those attributes will update as well.

Body:
Example:

<vue-select
  class="vue-select1"
  name="select1"
  :options="options1"
  :model.sync="result1"
></vue-select>

What is the meaning the colon in front of :options and :model.sync here? I've searched all over the internet and can't find an answer anywhere.

Example seen here: https://github.com/Haixing-Hu/vue-select


问:
Why is this except being called? - Python
I have a method that checks a JSON payload for JSON decoding errors, and KeyErrors. For some reason, the except statement with the KeyError is getting called, but then shows there was in fact, no KeyError as the object is None. Here is the code:

```<code>    try:
        test_data = simplejson.loads(self.raw_data) # Loads the data in a dict to test for the right fields
        test_data["test"]

    except simplejson.decoder.JSONDecodeError as jsonErr:
        print 'JSON Malform Error: ', jsonErr
        pass
        return False

    except KeyError as keyErr:
        print 'JSON Validation Error: ', keyErr
        pass
</code>```

答:
Looking through the traceback should tell you what module the exception was raised in. You might also want to consider using ipdb to manually step back and forth to debug future issues like this. Further more, you should inherit from Python's Exception class so you have more control over your own code by raising and excepting.

Utilizing Python's getattr and setattr functions help a lot too:

Using getattr on test_data will let you know when to raise your custom exception in the event that that None is returned.

ContentLicense: CC BY-SA 2.5

Body:
I have a method that checks a JSON payload for JSON decoding errors, and KeyErrors. For some reason, the except statement with the KeyError is getting called, but then shows there was in fact, no KeyError as the object is None. Here is the code:

    try:
        test_data = simplejson.loads(self.raw_data) # Loads the data in a dict to test for the right fields
        test_data["test"]

    except simplejson.decoder.JSONDecodeError as jsonErr:
        print 'JSON Malform Error: ', jsonErr
        pass
        return False

    except KeyError as keyErr:
        print 'JSON Validation Error: ', keyErr
        pass


问:
Change color for saturday and sunday date field in tree view odoo 9
Is it possible change color line for saturday and sunday date field in tree view?</p>

答:
Seems to be not possible with the latest version of Odoo. You could use the new decorations for that, but the python expression context doesn't have datetime or any other date library loaded into it anymore (i think the old colors possibility allowed datetime use).

Maybe it will be possible with Odoo 11 again.


问:
How to display two different type of images in SSRS report for a Boolean field
I am working on a SSRS report. I have a field called IsAllergic in database which could be 1, 0 or NULL. The business requirement is Yes and No side by side in report. If Yes then show a checked image infront of Yes and unchecked infront of No.
I have tried the following.
For the Yes checkbox under Use this image I use the below query:

```<code>=switch(Fields!IsAllergic .Value <> 1, "unchecked", Fields!IsAllergic .Value = 1, "checked")
</code>```

I have set the Visibility when the report initially run to "Show".

For the No checkbox under Use this image I use the below query:

```<code>=switch(Fields!IsAllergic Value <> 1, "checked", Fields!IsAllergic .Value = 1, "unchecked")
</code>```

For this checkbox also I have set the Visibility when the report initially run to "Show".

When I run the report I get the opposite result. Yes shows an unchecked checkbox image and No shows checked checkbox.
What am I missing here?
Been looking at this for hours and help is appreciated!

答:
I've just put together a quick sample to test and essentially what you are doing should be OK (except for the typos). However you can simplify it.

Step-by-step
I created a new report and added a new dataset. The dataset query is as follows (just to produce some sample data)

```<code>DECLARE @t TABLE (Name varchar(50), IsAllergic int)

INSERT INTO @t
VALUES
('Bob', 1),
('Dave', 0),
('Mike', NULL),
('Tony', 1),
('Rick', 0),
('Steve', NULL)
                                                                                SELECT * FROM @t
</code>```

Next I added two images, one was a box with a green check and one with the red cross but obviously swap these out for you checked and unchecked images.

Next I added a simple table with three columns, name in the first column and then images in the 2nd and 3rd columns.

The expressions for the image value properties is this...
For the YES column

```<code>=SWITCH(
Fields!IsAllergic.Value = 1, "checkboxchecked",
True, "checkboxcrossed"
)
</code>```

For the NO column

```<code>=SWITCH(
Fields!IsAllergic.Value = 1, "checkboxcrossed",
True, "checkboxchecked"
)
</code>```

By using SWITCH like this we are only really testing the first condition, the TRUE condition acts like an ELSE catching anything that fails the first condition, including NULLs.

The report design look something like this

That's it, no other properties were changed.
The output looks like this.

Body:
I am working on a SSRS report. I have a field called IsAllergic in database which could be 1, 0 or NULL. The business requirement is Yes and No side by side in report. If Yes then show a checked image infront of Yes and unchecked infront of No.
I have tried the following.
For the Yes checkbox under Use this image I use the below query:

=switch(Fields!IsAllergic .Value <> 1, "unchecked", Fields!IsAllergic .Value = 1, "checked")

I have set the Visibility when the report initially run to "Show".

For the No checkbox under Use this image I use the below query:

=switch(Fields!IsAllergic Value <> 1, "checked", Fields!IsAllergic .Value = 1, "unchecked")

For this checkbox also I have set the Visibility when the report initially run to "Show".

When I run the report I get the opposite result. Yes shows an unchecked checkbox image and No shows checked checkbox.
What am I missing here?
Been looking at this for hours and help is appreciated!

Body:
I've just put together a quick sample to test and essentially what you are doing should be OK (except for the typos). However you can simplify it.

Step-by-step
I created a new report and added a new dataset. The dataset query is as follows (just to produce some sample data)

DECLARE @t TABLE (Name varchar(50), IsAllergic int)

INSERT INTO @t
VALUES
('Bob', 1),
('Dave', 0),
('Mike', NULL),
('Tony', 1),
('Rick', 0),
('Steve', NULL)
                                                                                SELECT * FROM @t

Next I added two images, one was a box with a green check and one with the red cross but obviously swap these out for you checked and unchecked images.

Next I added a simple table with three columns, name in the first column and then images in the 2nd and 3rd columns.

The expressions for the image value properties is this...
For the YES column

=SWITCH(
Fields!IsAllergic.Value = 1, "checkboxchecked",
True, "checkboxcrossed"
)

For the NO column

=SWITCH(
Fields!IsAllergic.Value = 1, "checkboxcrossed",
True, "checkboxchecked"
)

By using SWITCH like this we are only really testing the first condition, the TRUE condition acts like an ELSE catching anything that fails the first condition, including NULLs.

The report design look something like this

That's it, no other properties were changed.
The output looks like this.


问:
how to pass variable with require() in PHP
I'm stuck trying to pass variables between 2 PHP files a.php and b.php  using require(). I learned that PHP variables have a single scope, which means that if a.php includes b.php, it can read its variables. However, I would like b.php to be able to read a variable from a.php with my current setup. For example, I can print out $msg if it is set in b.php but not a.php. Is there a simple way to do this?

a.php

```<code><?php

$msg = "Welcome NEW USER ! We can't wait for you to check out our books!";
require("connect.php");
require("b.php");
$table = "SELECT * FROM `login`";
if ($query_run=mysqli_query($cnn,$table)){

$username = $_POST['username'];
$pw = $_POST['password'];

$sql = "INSERT INTO login (username,password) VALUES ('{$username}','{$pw}')";

if($cnn->query($sql)===TRUE){echo "Query ran successfully";}
else{echo "Error: ".$sql."<br>".$cnn->error;}
}
else{die("table connection failed");}
$cnn.close();

?>
</code>```

b.php

```<code><?php
echo "<h1>".$msg."</h1>
<form action='' method='post'>
Username: <input type='text' name='username'><br>
Password: <input type='text' name='password'><br>
<input type='submit' name='submit'>
</form>
"

?>
</code>```

答:
No need to use of session.

if PHP file is included in other PHP file then variables also accessible in included PHP file.

Example

```<code><?php

$a = 1;
include 'filename.php';

?>
</code>```

Then $a is accessible in filename.php.
use echo in included file and test..

Let me know if you feel any issue.

Body:
I'm stuck trying to pass variables between 2 PHP files a.php and b.php  using require(). I learned that PHP variables have a single scope, which means that if a.php includes b.php, it can read its variables. However, I would like b.php to be able to read a variable from a.php with my current setup. For example, I can print out $msg if it is set in b.php but not a.php. Is there a simple way to do this?

a.php

<?php

$msg = "Welcome NEW USER ! We can't wait for you to check out our books!";
require("connect.php");
require("b.php");
$table = "SELECT * FROM `login`";
if ($query_run=mysqli_query($cnn,$table)){

$username = $_POST['username'];
$pw = $_POST['password'];

$sql = "INSERT INTO login (username,password) VALUES ('{$username}','{$pw}')";

if($cnn->query($sql)===TRUE){echo "Query ran successfully";}
else{echo "Error: ".$sql."
".$cnn->error;}
}
else{die("table connection failed");}
$cnn.close();

?>

b.php

<?php
echo "
".$msg."

<form action='' method='post'>
Username: <input type='text' name='username'>

Password: <input type='text' name='password'>

<input type='submit' name='submit'>
</form>
"

?>

Body:
No need to use of session.

if PHP file is included in other PHP file then variables also accessible in included PHP file.

Example

<?php

$a = 1;
include 'filename.php';

?>

Then $a is accessible in filename.php.
use echo in included file and test..

Let me know if you feel any issue.


问:
Treating numerical variables as text
I was not sure how to title this question, so I'll go straight to the code for you to see what I mean. Really new into this, so bear with me!

I have this code:

```<code>1   #include <cs50.h>
2   #include <stdio.h>
3   #include <string.h>
4
5   int main(int argc, string argv[])
6   {
7
8   if (argc!=2)
9   {
10     printf("error!! Usage: ./caesar k\n");
11     return 1;
12   }
13
14   printf("Plaintext: ");
15   string text=get_string();
16
17   char k=argv[1][0];
18   int n=strlen(text);
19
20
21   for (int i=0; i<n; i++)
22   {
23     if(text[i]>='a' && text[i]<='z')
24     {
25         printf("Cyphertext: %c\n", text[i]+k);
26     }
27   }
28   }
</code>```

What's its purpose?
Well, given a text, it adds k to every character. Which means that, for abc, and k=1, the output would be bcd; for abc and k=3, output would be def.

Now, it is imperative that k is given as a command line argument.

What do I want to do?
Just take k (which is a number), add it to every character of the input string text, and voilà.
Since every letter is a number in ASCII, adding a number can change the character, so... it should work. [I am still trying to figure out how ASCII works, and when do char show up like charcters and not numbers... but anyway].

What is going on?
First, I am having trouble declaring k as an int or char. In line 17, -and although k is a number(!)- the IDE forces me to declare a string or char*: if I declare k as int I receive an error; if I declare char I receive an error too, unless I declare it not only as k=argv[1] but as k=argv[1][0], as shown in the code above.

Second, executing the code above, this is the input/output (the name of the program is caesar):

```<code>$./caesar
error!! Usage: ./caesar k

$./caesar 1
Plaintext: a
Cyphertext: (nothing...)
</code>```

Third, given the error above, I changed the code in line 25 from this:

```<code>printf("Cyphertext: %c\n", text[i]+k);
</code>```

to this:

```<code>printf("Cyphertext: %s\n", text[i]+k);
</code>```

which returned this error message:

```<code>caesar.c:25:38: error: format specifies type 'char *' but the argument has
type 'int' [-Werror,-Wformat]
        printf("Cyphertext: %s", text[i]+k);
                            ~~   ^~~~~~~~~
                            %d`
</code>```

error message I do not understand, given that neither text nor k are int.

Anyway, changing %c to %s did not work, so I tried with %i instead:

```<code>printf("Cyphertext: %i\n", text[i]+k)
</code>```

which at least returned something:

```<code>$./caesar 1
Plaintext: a
Cyphertext: 146

$./caesar 5
Plaintext: a
Cyphertext: 150
</code>```

So, basically, it is adding k to 150 -which is 'û' in ASCII, so...(?).

And, finally, apart from the fact the program returns a number I do not understand, I thought I could make it show up like letters/non-numerical characters adding this:

```<code>printf("Cyphertext: %i\n", (char)text[i]+k);
</code>```

but it actually does not, the program returns exactly the same last output shown above.

So well, this is a much longer question than I expected, but I hope someone in here has the patence and proficency to answer it.

Thank you very much!

答:
Command line arguments are always passed in as strings.  Just because your program expects the first argument to look like a number doesn't necessarily mean that a number gets passed in.

So when you get the first character in the string via argv[1][0], you're not picking up the value 1 but the character 1.  Assuming ASCII is used for characters, this character has an ASCII value of 49.  So k in this case has the value 49.

You need to convert the argument to a number.  You can use the atoi function for this:

```<code>int k = atoi(argv[1]);
</code>```

Title: Treating numerical variables as text

Body:
I was not sure how to title this question, so I'll go straight to the code for you to see what I mean. Really new into this, so bear with me!

I have this code:

1   #include <cs50.h>
2   #include <stdio.h>
3   #include <string.h>
4
5   int main(int argc, string argv[])
6   {
7
8   if (argc!=2)
9   {
10     printf("error!! Usage: ./caesar k\n");
11     return 1;
12   }
13
14   printf("Plaintext: ");
15   string text=get_string();
16
17   char k=argv[1][0];
18   int n=strlen(text);
19
20
21   for (int i=0; i<n; i++)
22   {
23     if(text[i]>='a' && text[i]<='z')
24     {
25         printf("Cyphertext: %c\n", text[i]+k);
26     }
27   }
28   }

What's its purpose?
Well, given a text, it adds k to every character. Which means that, for abc, and k=1, the output would be bcd; for abc and k=3, output would be def.

Now, it is imperative that k is given as a command line argument.

What do I want to do?
Just take k (which is a number), add it to every character of the input string text, and voilà.
Since every letter is a number in ASCII, adding a number can change the character, so... it should work. [I am still trying to figure out how ASCII works, and when do char show up like charcters and not numbers... but anyway].

What is going on?
First, I am having trouble declaring k as an int or char. In line 17, -and although k is a number(!)- the IDE forces me to declare a string or char*: if I declare k as int I receive an error; if I declare char I receive an error too, unless I declare it not only as k=argv[1] but as k=argv[1][0], as shown in the code above.

Second, executing the code above, this is the input/output (the name of the program is caesar):

$./caesar
error!! Usage: ./caesar k

$./caesar 1
Plaintext: a
Cyphertext: (nothing...)

Third, given the error above, I changed the code in line 25 from this:

printf("Cyphertext: %c\n", text[i]+k);

to this:

printf("Cyphertext: %s\n", text[i]+k);

which returned this error message:

caesar.c:25:38: error: format specifies type 'char *' but the argument has
type 'int' [-Werror,-Wformat]
        printf("Cyphertext: %s", text[i]+k);
                            ~~   ^~~~~~~~~
                            %d`

error message I do not understand, given that neither text nor k are int.

Anyway, changing %c to %s did not work, so I tried with %i instead:

printf("Cyphertext: %i\n", text[i]+k)

which at least returned something:

$./caesar 1
Plaintext: a
Cyphertext: 146

$./caesar 5
Plaintext: a
Cyphertext: 150

So, basically, it is adding k to 150 -which is 'û' in ASCII, so...(?).

And, finally, apart from the fact the program returns a number I do not understand, I thought I could make it show up like letters/non-numerical characters adding this:

printf("Cyphertext: %i\n", (char)text[i]+k);

but it actually does not, the program returns exactly the same last output shown above.

So well, this is a much longer question than I expected, but I hope someone in here has the patence and proficency to answer it.

Thank you very much!

Body:
Command line arguments are always passed in as strings.  Just because your program expects the first argument to look like a number doesn't necessarily mean that a number gets passed in.

So when you get the first character in the string via argv[1][0], you're not picking up the value 1 but the character 1.  Assuming ASCII is used for characters, this character has an ASCII value of 49.  So k in this case has the value 49.

You need to convert the argument to a number.  You can use the atoi function for this:

int k = atoi(argv[1]);


问:
How to implement fair division(?) with buffer in javascript?
For the sake of explaining, imagine I have 101 entities. The entities are all people.

In the first entity, it has x amount of "potatoes", I want it to have y potatoes, for now I shall use 950 as an example, intentionally choosing a more awkward number than 1000 for testing.

```<code>var personOne = {
     ...
     potatoes: 100
}
</code>```

I have 100 more of these entities which may have any number of potatoes, but I set a constant buffer that at least 100 for the sake of example again - have to remain with each person.

This means for all of the entities that have over 100, I will be taking some from them - I want this to be shared proportionally across all of them, so that 850 aren't taken from the first two or three, but 10 or 5 taken from all those that are capable of providing such an amount.

Any ideas for an approach?

Optionally: I am using more properties than one "potatoes" property, but I plan on looping through each type and re-using the method that I find to each. I am unsure as to whether this could affect the answer.

Important / Simplified

The one entitiy is pulling "potatoes" from all of the other entities, they are not being distributed evenly across all of them - they are being taken to one entity. I just do not want to do it in a way that is not proportional across all other 100 entities.

This is more taxation than cake-cutting. I am struggling to google for or think of the correct name for the mathematical problem.

答:
Case 1. enough potatoes for everyone to have over 100 of them: put all potatoes together and divide evenly.

Case 2. Not enough potatoes for everyone to have 100. Sum the excess over 100 for those who have + sum all potatoes of those with less than 100, divide the collected potatoes between those with under 100.

(yes, case 2 will imply that some of those under 100 will end with less potatoes than they started. Not fair? Well, maybe you shouldn't protect the 1-percenters that much if there aren't enough potatoes for everybody :) But I digress)

Body:
For the sake of explaining, imagine I have 101 entities. The entities are all people.

In the first entity, it has x amount of "potatoes", I want it to have y potatoes, for now I shall use 950 as an example, intentionally choosing a more awkward number than 1000 for testing.

var personOne = {
     ...
     potatoes: 100
}

I have 100 more of these entities which may have any number of potatoes, but I set a constant buffer that at least 100 for the sake of example again - have to remain with each person.

This means for all of the entities that have over 100, I will be taking some from them - I want this to be shared proportionally across all of them, so that 850 aren't taken from the first two or three, but 10 or 5 taken from all those that are capable of providing such an amount.

Any ideas for an approach?

Optionally: I am using more properties than one "potatoes" property, but I plan on looping through each type and re-using the method that I find to each. I am unsure as to whether this could affect the answer.

Important / Simplified

The one entitiy is pulling "potatoes" from all of the other entities, they are not being distributed evenly across all of them - they are being taken to one entity. I just do not want to do it in a way that is not proportional across all other 100 entities.

This is more taxation than cake-cutting. I am struggling to google for or think of the correct name for the mathematical problem.


问:
Assign a different macro per click of VBA Button
I have an excel button that hides columns "S-U" when I click it. I want to click the button a 2nd time and it hides columns "P-R" and etc. Can you manipulate an excel button per click?</p>

答:
If you only need to alternate between two options, e.g. like a toggle on off, then use a boolean:</p>

```<code>Public x As Boolean

Private Sub CommandButton1_Click()
If x Then MsgBox ("ON") Else MsgBox ("OFF")
x = Not x
End Sub
</code>```

Body:
If you only need to alternate between two options, e.g. like a toggle on off, then use a boolean:

Public x As Boolean

Private Sub CommandButton1_Click()
If x Then MsgBox ("ON") Else MsgBox ("OFF")
x = Not x
End Sub


问:
Replicate SQL row with same data but not defining all columns
Is it possible to do a SQL query where I can take let's say all columns form the row for user 'A' and copy them into row for user 'B' without defining the column names.

For an Example, this will not be against speed or intense data, but to help these tasks be functional instead of doing them redundantly over and over. The params for base user and target user would be the stored procedure params.

```<code>Declare @BaseUserId varchar(50),
    @TargetUserId varchar(50),
    @ColumnName varchar(100)

Declare columnNameCursor Cursor For SELECT c.name
        FROM sys.columns c
        WHERE c.object_id = OBJECT_ID('dbo.EmployeeMenuAccess')

--Opens the cursor now for loop reading
Open columnNameCursor

Fetch next From columnNameCursor into @ColumnName

While @@Fetch_Status=0 Begin
  update DocSS set @ColumnName = (select @ColumnName from DocSS where
  Username = @BaseUserId) where Username = @TargetUserID
  Fetch next From c into @ColumnName
End

Close columnNameCursor
Deallocate columnNameCursor
</code>```

Thanks in advance.

答:
```<code>CREATE TABLE Test
    (id int, name char(10))
;
INSERT INTO Test VALUES(1, 'first');
INSERT INTO Test VALUES(2, 'second');
BEGIN TRAN T1;
SELECT * INTO Temp FROM Test WHERE id = 1;
UPDATE Temp SET id = (SELECT MAX(id)+1 FROM Test);
INSERT INTO Test SELECT * FROM Temp;
DROP TABLE Temp;
COMMIT TRAN T1;
SELECT * FROM Test;
</code>```

Try this

Body:
Is it possible to do a SQL query where I can take let's say all columns form the row for user 'A' and copy them into row for user 'B' without defining the column names.

For an Example, this will not be against speed or intense data, but to help these tasks be functional instead of doing them redundantly over and over. The params for base user and target user would be the stored procedure params.

Declare @BaseUserId varchar(50),
    @TargetUserId varchar(50),
    @ColumnName varchar(100)

Declare columnNameCursor Cursor For SELECT c.name
        FROM sys.columns c
        WHERE c.object_id = OBJECT_ID('dbo.EmployeeMenuAccess')

--Opens the cursor now for loop reading
Open columnNameCursor

Fetch next From columnNameCursor into @ColumnName

While @@Fetch_Status=0 Begin
  update DocSS set @ColumnName = (select @ColumnName from DocSS where
  Username = @BaseUserId) where Username = @TargetUserID
  Fetch next From c into @ColumnName
End

Close columnNameCursor
Deallocate columnNameCursor

Thanks in advance.

Body:
CREATE TABLE Test
    (id int, name char(10))
;
INSERT INTO Test VALUES(1, 'first');
INSERT INTO Test VALUES(2, 'second');
BEGIN TRAN T1;
SELECT * INTO Temp FROM Test WHERE id = 1;
UPDATE Temp SET id = (SELECT MAX(id)+1 FROM Test);
INSERT INTO Test SELECT * FROM Temp;
DROP TABLE Temp;
COMMIT TRAN T1;
SELECT * FROM Test;

Try this


问:
Efficient way to count number of objects with certain characteristics in database
Please edit the title if you can think of a way to improve it.

I have a table that contains dozens of rows now, but will have hundreds in production and possibly thousands eventually. I need to count how many have certain characteristics, for example having an enum property set to a target enum.

For the sake of the question, we'll say I have in my model:

```<code>public enum Types { One, Two, Three, Four }
public Types Type = Types.One; // Or Two, etc.
</code>```

Currently, each time the index page -- which lists these entries -- is accessed, I enumerate(?) counters for One, Two, Three, Four and display them at the top of the page.

Current method:

- Loop through every object in the table, check its properties, and increment relevant counter(s) -- each time the list is loaded

Potential methods:

- Is LINQ any faster? i.e. db.MySet.Where(obj => obj.Type == Model.Types.One)

- Could I keep these counters in memory at all times? Not sure how to do that. If that's possible, a potential solution would be adding to these counters in the MyModelController.Create method.

答:
Potential methods:
  - Is LINQ any faster? i.e. db.MySet.Where(obj => obj.Type == Model.Types.One)

LINQ would be much much better and faster. Actually all work would do SQL Server - not your application and SQL Server is optimized for such tasks. And better LINQ-code for counting objects is db.MySet.Count(obj => obj.Type == Model.Types.One)

Could I keep these counters in memory at all times? Not sure how to do that. If that's possible, a potential solution would be adding to
  these counters in the MyModelController.Create method.

I am not sure what you mean, but you cannot keep something in controllers variables because controllers are created for each request and destroyed after request processing. You can persist these data in separate store but I think its unneeded complication.

Body:
Please edit the title if you can think of a way to improve it.

I have a table that contains dozens of rows now, but will have hundreds in production and possibly thousands eventually. I need to count how many have certain characteristics, for example having an enum property set to a target enum.

For the sake of the question, we'll say I have in my model:

public enum Types { One, Two, Three, Four }
public Types Type = Types.One; // Or Two, etc.

Currently, each time the index page -- which lists these entries -- is accessed, I enumerate(?) counters for One, Two, Three, Four and display them at the top of the page.

Current method:

- Loop through every object in the table, check its properties, and increment relevant counter(s) -- each time the list is loaded

Potential methods:

- Is LINQ any faster? i.e. db.MySet.Where(obj => obj.Type == Model.Types.One)

- Could I keep these counters in memory at all times? Not sure how to do that. If that's possible, a potential solution would be adding to these counters in the MyModelController.Create method.


问:
Cygwin with win10 (64 bit , parallels) does not working for gcc 32
I'd try to install gcc in win10  (64 bit , parallels)
It is working for 64 but not working for 32
-it is working like this

```<code>C:\Users\me\Desktop>gcc -m64 -o test64 testt.c
</code>```

-but it is not....

```<code>C:\Users\me\Desktop>gcc -m32 -o test32 testt.c
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc_s.dll.a when searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc_s.dll.a when searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc_s.dll.a when searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc_s.dll.a when searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../libcygwin.a when searching for -lcygwin
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../libcygwin.a when searching for -lcygwin
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../libcygwin.a when searching for -lcygwin
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lcygwin
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -ladvapi32
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lshell32
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -luser32
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lkernel32
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc_s.dll.a when searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc_s.dll.a when searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc_s.dll.a when searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc_s.dll.a when searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lgcc
collect2: error: ld returned 1 exit status
</code>```

how can I solve it?

答:
The gcc compiler of cygwin x86_64 is only for x86_64 so 64bit.

If you want to compile for cygwin x86, 32bit,  you need to install cygwin at 32 bit and its compiler.

If instead you want to compile for windows at 32bit, you need to install a cross compiler

```<code>mingw64-i686-gcc-core   GCC for Win32 (i686-w64-mingw32) toolchain (C, OpenMP)
</code>```

While for Windows 64 bit, the cross compiler

```<code>mingw64-x86_64-gcc-core GCC for Win64 toolchain (C, OpenMP)
</code>```

You will need also to install the relative libraries.
Full package list is available at

https://cygwin.com/packages/package_list.html

Body:
I'd try to install gcc in win10  (64 bit , parallels)
It is working for 64 but not working for 32
-it is working like this

C:\Users\me\Desktop>gcc -m64 -o test64 testt.c

-but it is not....

C:\Users\me\Desktop>gcc -m32 -o test32 testt.c
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc_s.dll.a when searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc_s.dll.a when searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc_s.dll.a when searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc_s.dll.a when searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../libcygwin.a when searching for -lcygwin
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../libcygwin.a when searching for -lcygwin
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../libcygwin.a when searching for -lcygwin
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lcygwin
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -ladvapi32
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lshell32
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -luser32
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lkernel32
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc_s.dll.a when searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc_s.dll.a when searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc_s.dll.a when searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc_s.dll.a when searching for -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lgcc_s
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0//libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-pc-cygwin/5.4.0/libgcc.a when searching for -lgcc
/usr/lib/gcc/x86_64-pc-cygwin/5.4.0/../../../../x86_64-pc-cygwin/bin/ld: cannot find -lgcc
collect2: error: ld returned 1 exit status

how can I solve it?

Body:
The gcc compiler of cygwin x86_64 is only for x86_64 so 64bit.

If you want to compile for cygwin x86, 32bit,  you need to install cygwin at 32 bit and its compiler.

If instead you want to compile for windows at 32bit, you need to install a cross compiler

mingw64-i686-gcc-core   GCC for Win32 (i686-w64-mingw32) toolchain (C, OpenMP)

While for Windows 64 bit, the cross compiler

mingw64-x86_64-gcc-core GCC for Win64 toolchain (C, OpenMP)

You will need also to install the relative libraries.
Full package list is available at

https://cygwin.com/packages/package_list.html


问:
File reading & counting & sorting by hours in Python
I'm new to Python & here is my question

Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008
Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.

Link of the file:

http://www.pythonlearn.com/code/mbox-short.txt

This is my code:

```<code>name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)

counts = dict()
for line in handle:
    if not line.startswith ("From "):continue
    #words = line.split()

    col = line.find(':')
    coll = col - 2
    print coll

    #zero = line.find('0')
    #one = line.find('1')
    #b = line[ zero or one : col ]
    #print b
    #hour = words[5:6]
    #print hour

    #for line in hour:
     #   hr = line.split(':')
      #  x = hr[1]

    for x in coll:
        counts[x] = counts.get(x,0) + 1

        for key, value in sorted(counts.items()):
            print key, value
</code>```

My first try was with list splitting(Comments) and it didn't work as it considered the 0 & the 1 as the first & the second letter not the numbers
second one was with line find (:) which is partially worked with minutes not with hours as required!!

First question

Why when I write line.find(:), it takes automatically the 2 numbers after?

Second question

Why when I run the program now, it gives an error
TypeError: 'int' object is not iterable on line 26 ??

Third question

Why it considered 0 & 1 as first & second letters of the line not  0 & 1 numbers

Finally
If possible please solve me this problem with a little of explanation please (with the same codes to keep my learning sequence)

Thank you...

答:
First question
  Why when I write line.find(:), it takes automatically the 2 numbers
  after?

str.find() return the first index of the character that you want to find. If your string is "From 00:00:00", it returns 7 as the first ':' is at index 7.

Second question
  Why when I run the program now, it gives an error TypeError: 'int'
  object is not iterable on line 26 ??

As have said above, it returns an int, which you cannot iterate

Third question

Why it considered 0 & 1 as first & second letters of the line not 0 &
  1 numbers

I don't really understand what do you mean here. Anyway, as I understand, you try to find the first index which '0' or '1' occurs and assume that the first letter of hour? What about 8-11pm(start with 2)?

Finally If possible please solve me this problem with a little of
  explanation please (with the same codes to keep my learning sequence)

Sure, it will be like this:

```<code>for line in f:
    if not line.startswith("From "): continue

    first_colon_index = line.find(":")
    if first_colon_index == -1: # there is no ':'
        continue
    first_char_hour_index = first_colon_index - 2

    # string slicing
    # [a:b] get string from index a to b
    hour = line[first_char_hour_index:first_char_hour_index+2]

    hour_int = int(hour)

    # if key exist, increase by 1. If not, set to 1
    if hour_int in count:
         count[hour_int] += 1
    else:
         count[hour_int] = 1
# print hour & count, in sorting order
for hour in sorted(count):
   print hour, count[hour]
</code>```

The part about string slicing can be confusing, you can read more about it at Python docs.

And you have to sure that: in the line, there is no other ":" or this method will fail as the first ":" will not be the one between hour and minute.

To make sure it works, it's better to use Regex. Something like:

```<code>for line in f:
    if not line.startswith("From"): continue

    match = re.search(r'^From.*?([0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2})', line)
    if match:
        time = match.group(1) # hh:mm:ss
        hh = int(time.split(":")[0])
        # if key exist, increase by 1. If not, set to 1
        if hh in count:
             count[hh] += 1
        else:
             count[hh] = 1
# print hour & count, in sorting order
for hour in sorted(count):
   print hour, count[hour]
</code>```

Body:
I'm new to Python & here is my question

Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008
Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.

Link of the file:

http://www.pythonlearn.com/code/mbox-short.txt

This is my code:

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)

counts = dict()
for line in handle:
    if not line.startswith ("From "):continue
    #words = line.split()

    col = line.find(':')
    coll = col - 2
    print coll

    #zero = line.find('0')
    #one = line.find('1')
    #b = line[ zero or one : col ]
    #print b
    #hour = words[5:6]
    #print hour

    #for line in hour:
     #   hr = line.split(':')
      #  x = hr[1]

    for x in coll:
        counts[x] = counts.get(x,0) + 1

        for key, value in sorted(counts.items()):
            print key, value

My first try was with list splitting(Comments) and it didn't work as it considered the 0 & the 1 as the first & the second letter not the numbers
second one was with line find (:) which is partially worked with minutes not with hours as required!!

First question

Why when I write line.find(:), it takes automatically the 2 numbers after?

Second question

Why when I run the program now, it gives an error
TypeError: 'int' object is not iterable on line 26 ??

Third question

Why it considered 0 & 1 as first & second letters of the line not  0 & 1 numbers

Finally
If possible please solve me this problem with a little of explanation please (with the same codes to keep my learning sequence)

Thank you...

Body:
First question
  Why when I write line.find(:), it takes automatically the 2 numbers
  after?

str.find() return the first index of the character that you want to find. If your string is "From 00:00:00", it returns 7 as the first ':' is at index 7.

Second question
  Why when I run the program now, it gives an error TypeError: 'int'
  object is not iterable on line 26 ??

As have said above, it returns an int, which you cannot iterate

Third question

Why it considered 0 & 1 as first & second letters of the line not 0 &
  1 numbers

I don't really understand what do you mean here. Anyway, as I understand, you try to find the first index which '0' or '1' occurs and assume that the first letter of hour? What about 8-11pm(start with 2)?

Finally If possible please solve me this problem with a little of
  explanation please (with the same codes to keep my learning sequence)

Sure, it will be like this:

for line in f:
    if not line.startswith("From "): continue

    first_colon_index = line.find(":")
    if first_colon_index == -1: # there is no ':'
        continue
    first_char_hour_index = first_colon_index - 2

    # string slicing
    # [a:b] get string from index a to b
    hour = line[first_char_hour_index:first_char_hour_index+2]

    hour_int = int(hour)

    # if key exist, increase by 1. If not, set to 1
    if hour_int in count:
         count[hour_int] += 1
    else:
         count[hour_int] = 1
# print hour & count, in sorting order
for hour in sorted(count):
   print hour, count[hour]

The part about string slicing can be confusing, you can read more about it at Python docs.

And you have to sure that: in the line, there is no other ":" or this method will fail as the first ":" will not be the one between hour and minute.

To make sure it works, it's better to use Regex. Something like:

for line in f:
    if not line.startswith("From"): continue

    match = re.search(r'^From.*?([0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2})', line)
    if match:
        time = match.group(1) # hh:mm:ss
        hh = int(time.split(":")[0])
        # if key exist, increase by 1. If not, set to 1
        if hh in count:
             count[hh] += 1
        else:
             count[hh] = 1
# print hour & count, in sorting order
for hour in sorted(count):
   print hour, count[hour]


问:
Neither constructor nor onFinishInflate called for custom view
I have a custom view (which extends GLSurfaceView) I'm trying to use in my app. The xml layout that uses it appears to be being loaded correctly (attributes I set for the view are applied), but neither the view's constructor nor the onFinishInflate method are being called for the class.  I should also add that I'm new to the android platform so this is probably a stupid mistake.

Here is my main.xml

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

```<code>#<!-- Status Bar -->
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0"
    android:background="@drawable/status_bkg">

    #<!-- Location label -->
    <TextView
        android:text="Location"
        android:textColor="#FFFFFF"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    #<!-- Date/Time label -->
    <TextView
        android:text="Date and Time"
        android:textColor="#FFFFFF"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="right"  />
</LinearLayout>

#<!-- ChartView -->
<View class="com.xxx.yyy.ChartView" android:id="@+id/chartView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00FF00"
    android:layout_weight="1">
</View>
</code>```

The ChartView is the custom GLSurfaceView.  This layout is loaded and the ChartView has a green background as specified. However, none of my setup (in code) happens for it.  I've tried placing it in the two constructors and in the onFinishInflate methods, but they inexplicably don't get called.  I've verified that the class name is correct (the xxx.yyy are just to hide the company in this post.

I've also tried a different form of the xml reference

```<code>    <com.xxx.yyy.ChartView android:id="@+id/chartView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00FF00"
    android:layout_weight="1"/>
</code>```

But this dies when loading the Activity says that the constructor

ChartView(Context context, AttributeSet attrs)

doesn't exist (although it is certainly in my code).

Anyone got any tips on what could be going on?

答:
I finally figured this out.  I had defined my constructor (the one not getting called) as:

```<code>public ChartView( MyActivity context, AttributeSet attrs )
{
    super( context, attrs );
….
}
</code>```

However, it started working when I changed the constructor to be:

```<code>public ChartView( Context context, AttributeSet attrs )
{
    super( context, attrs );
….
}
</code>```

Given that MyActivity extends Activity (which extends Context), this is perfectly valid code and I believe it should work (it certainly compiles).  It would seem there is an error in the reflection the system is using in locating this method.

Body:
I have a custom view (which extends GLSurfaceView) I'm trying to use in my app. The xml layout that uses it appears to be being loaded correctly (attributes I set for the view are applied), but neither the view's constructor nor the onFinishInflate method are being called for the class.  I should also add that I'm new to the android platform so this is probably a stupid mistake.

Here is my main.xml

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

#
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0"
    android:background="@drawable/status_bkg">

    #
    <TextView
        android:text="Location"
        android:textColor="#FFFFFF"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    #
    <TextView
        android:text="Date and Time"
        android:textColor="#FFFFFF"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="right"  />
</LinearLayout>

#
<View class="com.xxx.yyy.ChartView" android:id="@+id/chartView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00FF00"
    android:layout_weight="1">
</View>

The ChartView is the custom GLSurfaceView.  This layout is loaded and the ChartView has a green background as specified. However, none of my setup (in code) happens for it.  I've tried placing it in the two constructors and in the onFinishInflate methods, but they inexplicably don't get called.  I've verified that the class name is correct (the xxx.yyy are just to hide the company in this post.

I've also tried a different form of the xml reference

    <com.xxx.yyy.ChartView android:id="@+id/chartView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00FF00"
    android:layout_weight="1"/>

But this dies when loading the Activity says that the constructor

ChartView(Context context, AttributeSet attrs)

doesn't exist (although it is certainly in my code).

Anyone got any tips on what could be going on?

Body:
I finally figured this out.  I had defined my constructor (the one not getting called) as:

public ChartView( MyActivity context, AttributeSet attrs )
{
    super( context, attrs );
….
}

However, it started working when I changed the constructor to be:

public ChartView( Context context, AttributeSet attrs )
{
    super( context, attrs );
….
}

Given that MyActivity extends Activity (which extends Context), this is perfectly valid code and I believe it should work (it certainly compiles).  It would seem there is an error in the reflection the system is using in locating this method.


问:
pdf2svg leads to blurry images
I'm trying to convert a pdf figure to svg so I can edit some details with Inkscape. The problem I have is that the import changes slightly through some sort of smoothing.

In particular, this is the original figure:

And this is the figure after converting to SVG

This is the output of pdf2svg, which is exactly the same I get if I use Inkscape directly.

I attach a link where you can get both files.

https://www.dropbox.com/s/domxcc8pncyouy6/images.tar.gz?dl=0

Do you know a workaround to this issue?

答:
Without seeing the SVG it is hard to tell for sure.  However it looks like the "heat map" portion of your PDF/SVG may be a low resolution bitmap that is being enlarged in the page.

By default, SVG renderers will use interpolation when enlarging an image.  This gives the image a smoothed/blurry look at large scales.

You could try locating the <image> element in your SVG and adding the attribute image-rendering="pixelated" to the <image> tag.  Some browsers support that option and will scale the image using the nearest-neighbour scaling method.

Otherwise you may need to extract the image from the PDF or SVG; resample it at a higher (eg. 4x or 8x) resolution; then reinsert it back into the file.

Find the image in the SVG file (<image id="image5" .../>

Extract the Base64 encoded image from the DataURI. And decode it using a Base64 decoder.

Multiply the image resolution using an editor, cusch as Photoshop or Gimp.

Encode the file back to Base64

Update that <image> element with the new Base64.

Title: pdf2svg leads to blurry images


答: Be careful when using the colon in HTMLbecause selecting the attribute in CSS and JQueryhas a different meaning with a colon.  In CSS and JQuery, a colon signifies a pseudo-selector, which is different from v-bind;

Title: VueJS: what does an html attribute prefixed with a colon signify?

Body:
Example:

<vue-select
  class="vue-select1"
  name="select1"
  :options="options1"
  :model.sync="result1"
></vue-select>

What is the meaning the colon in front of :options and :model.sync here? I've searched all over the internet and can't find an answer anywhere.

Example seen here: https://github.com/Haixing-Hu/vue-select


问:
Iframe mobile responsivness
I have a page and I wanted more than one slide show on the same page but that proves slightly difficult with JavaScript variables so I decide to make each slide show an iframe. This works rather well however now the responsiveness of the iframe is causing issues. The slides within the Iframe are div elements that will stack based on screen size. The issue is now that the Iframe does not get longer. I have tried:

```<code><iframe src="Web.html"  height="100%" frameborder="1" marginheight="0" marginwidth="0" scrolling="no"></iframe>
</code>```

except that doesn't make the iframe long enough even before resizing. My question is, how do I make the Iframe as tall as the page is, and the page will be resizing?

答:
Try Bootstarp Responsive embed.

```

Here is like: http://getbootstrap.com/components/#responsive-embed

Title: Iframe mobile responsivness

Body:
I have a page and I wanted more than one slide show on the same page but that proves slightly difficult with JavaScript variables so I decide to make each slide show an iframe. This works rather well however now the responsiveness of the iframe is causing issues. The slides within the Iframe are div elements that will stack based on screen size. The issue is now that the Iframe does not get longer. I have tried:

except that doesn't make the iframe long enough even before resizing. My question is, how do I make the Iframe as tall as the page is, and the page will be resizing?

Body:
Try Bootstarp Responsive embed.

<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="..."></iframe>
</div>

Here is like: http://getbootstrap.com/components/#responsive-embed


问:
Is it possible to define a one-off user control in the ASPX codebehind?
One of my big beefs with ASP.NET is that it makes it difficult to organize the controls of a page beyond excessive amounts of prefixing IDs. I have gone to great and complicated lengths in the past to try to alleviate this, but I would like a solution that is easier to implement. So, I'm wondering:

Is it possible to define a user control in the codebehind of a .aspx, and then use it in the .aspx? I'm thinking probably not... I can't get it to work.

答:
No. You must create a user control in it's own .ascx file.

Though if you wish wish to create a web control, you can define that in whichever .cs/.vb file you want. Though for the sake of your coworkers being able to find your code, I might suggest it live in it's own file anyways.

NOTE: I would question the validity of "it difficult to organize the controls of a page beyond excessive amounts of prefixing IDs". This is what templated controls (repeater, datalist, etc) are for. They will implement INamingContainer and thus will enable you to name controls with the same name, but different scope. There's some good info here...


问:
Keras model.summary() result - Understanding the # of Parameters
I have a simple NN model for detecting hand-written digits from a 28x28px image written in python using Keras (Theano backend):

```<code>model0 = Sequential()

#number of epochs to train for
nb_epoch = 12
#amount of data each iteration in an epoch sees
batch_size = 128

model0.add(Flatten(input_shape=(1, img_rows, img_cols)))
model0.add(Dense(nb_classes))
model0.add(Activation('softmax'))
model0.compile(loss='categorical_crossentropy',
         optimizer='sgd',
         metrics=['accuracy'])

model0.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,
      verbose=1, validation_data=(X_test, Y_test))

score = model0.evaluate(X_test, Y_test, verbose=0)

print('Test score:', score[0])
print('Test accuracy:', score[1])
</code>```

This runs well and I get ~90% accuracy. I then perform the following command to get a summary of my network's structure by doing print(model0.summary()). This outputs the following:

```<code>Layer (type)         Output Shape   Param #     Connected to
=====================================================================
flatten_1 (Flatten)   (None, 784)     0           flatten_input_1[0][0]
dense_1 (Dense)     (None, 10)       7850        flatten_1[0][0]
activation_1        (None, 10)          0           dense_1[0][0]
======================================================================
Total params: 7850
</code>```

I don't understand how they get to 7850 total params and what that actually means?

答:
The "none" in the shape means it does not have a pre-defined number. For example, it can be the batch size you use during training, and you want to make it flexible by not assigning any value to it so that you can change your batch size. The model will infer the shape from the context of the layers.

To get nodes connected to each layer, you can do the following:

```<code>for layer in model.layers:
    print(layer.name, layer.inbound_nodes, layer.outbound_nodes)
</code>```

Body:
I have a simple NN model for detecting hand-written digits from a 28x28px image written in python using Keras (Theano backend):

model0 = Sequential()

#number of epochs to train for
nb_epoch = 12
#amount of data each iteration in an epoch sees
batch_size = 128

model0.add(Flatten(input_shape=(1, img_rows, img_cols)))
model0.add(Dense(nb_classes))
model0.add(Activation('softmax'))
model0.compile(loss='categorical_crossentropy',
         optimizer='sgd',
         metrics=['accuracy'])

model0.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,
      verbose=1, validation_data=(X_test, Y_test))

score = model0.evaluate(X_test, Y_test, verbose=0)

print('Test score:', score[0])
print('Test accuracy:', score[1])

This runs well and I get ~90% accuracy. I then perform the following command to get a summary of my network's structure by doing print(model0.summary()). This outputs the following:

Layer (type)         Output Shape   Param #     Connected to
=====================================================================
flatten_1 (Flatten)   (None, 784)     0           flatten_input_1[0][0]
dense_1 (Dense)     (None, 10)       7850        flatten_1[0][0]
activation_1        (None, 10)          0           dense_1[0][0]
======================================================================
Total params: 7850

I don't understand how they get to 7850 total params and what that actually means?

Body:
The "none" in the shape means it does not have a pre-defined number. For example, it can be the batch size you use during training, and you want to make it flexible by not assigning any value to it so that you can change your batch size. The model will infer the shape from the context of the layers.

To get nodes connected to each layer, you can do the following:

for layer in model.layers:
    print(layer.name, layer.inbound_nodes, layer.outbound_nodes)


问:
How to responsively set width of button according to the width of the image using CSS
Here is what I have currently with the code below. I'm trying to have the button span the width of the responsive image on resize. Right now it shrinks almost half its size when resizing instead of staying align with the image. This may be a jQuery question, I'm not entirely sure.

HTML

```<code><div class="container">
        <div class="row">
            <div class="img-box col-lg-12 text-center">
                <button type="button" class="btn btn-lg btn-primary" onclick="window.location='beginReservation.php'">Book Seat Now</button><br>
                <img class="bg img-responsive img-center" src="images/homepage.jpg" alt="Book Seat">
            </div>
         </div>
     </div>
</code>```

CSS

```<code>   .img-box {
     background: white;
     margin-bottom: 20px;
     padding: 0px;
     display:inline-block;
    }

    .btn {
      background: rgb(179,0,14);
      border: rgb(179,0,14);
      padding: 0.5% 32.75%;
      border-radius: 0px;
      margin:0 auto;
    }

   .bg {
     margin:0 auto;
   }
</code>```

答: Remove  display:inline-block from this class .img-box{}

Body:
Here is what I have currently with the code below. I'm trying to have the button span the width of the responsive image on resize. Right now it shrinks almost half its size when resizing instead of staying align with the image. This may be a jQuery question, I'm not entirely sure.

HTML

                <button type="button" class="btn btn-lg btn-primary" onclick="window.location='beginReservation.php'">Book Seat Now</button>

CSS

   .img-box {
     background: white;
     margin-bottom: 20px;
     padding: 0px;
     display:inline-block;
    }

    .btn {
      background: rgb(179,0,14);
      border: rgb(179,0,14);
      padding: 0.5% 32.75%;
      border-radius: 0px;
      margin:0 auto;
    }

   .bg {
     margin:0 auto;
   }


问:
Colorbar for each row in ImageGrid
Disclaimer:  I am very inexperienced using matplotlib and python in general.

Here is the figure I'm trying to make:

Using GridSpec works well for laying out the plots, but when I try to include a colorbar on the right of each row, it changes the size of the corresponding subplot.  This seems to be a well known and unavoidable problem with GridSpec.  So at the advice of this question: Matplotlib 2 Subplots, 1 Colorbar
I've decided to remake the whole plot using ImageGrid. Unfortunately the documentation only lists  the options cbar_mode=[None|single|each] whereas I want 1 colobar per row.  Is there a way to do this inside a single ImageGrid? or will I have to make 2 grids and deal with the nightmare of alignment.

What about the 5th plot at the bottom? Is there a way to include that in the image grid somehow?

The only way I can see this working is to somehow nest two ImageGrids into a GridSpec in a 1x3 column.  this seems overly complicated and difficult so I don't want to build that script until I know its the right way to go.

Thanks for any help/advice!

答:
Ok I figured it out.  It seems ImageGrid uses subplot somehow inside it.  So I was able to generate the following plot using something like

```<code>TopGrid = ImageGrid( fig, 311,
                nrows_ncols=(1,2),
                axes_pad=0,
                share_all=True,
                cbar_location="right",
                cbar_mode="single",
                cbar_size="3%",
                cbar_pad=0.0,
                cbar_set_cax=True
                )
<Plotting commands for the top row of plots and colorbar>

BotGrid = ImageGrid( fig, 312,
                nrows_ncols=(1,2),
                axes_pad=0,
                share_all=True,
                cbar_location="right",
                cbar_mode="single",
                cbar_size="3%",
                cbar_pad=0.0,
                )
<Plotting commands for bottom row . . .>
StemPlot = plt.subplot(313)
<plotting commands for bottom stem plot>
</code>```

EDIT:  the whitespace in the color plots is intentional, not some artifact from adding the colorbars

Title: Colorbar for each row in ImageGrid

Body:
Ok I figured it out.  It seems ImageGrid uses subplot somehow inside it.  So I was able to generate the following plot using something like

TopGrid = ImageGrid( fig, 311,
                nrows_ncols=(1,2),
                axes_pad=0,
                share_all=True,
                cbar_location="right",
                cbar_mode="single",
                cbar_size="3%",
                cbar_pad=0.0,
                cbar_set_cax=True
                )
<Plotting commands for the top row of plots and colorbar>

BotGrid = ImageGrid( fig, 312,
                nrows_ncols=(1,2),
                axes_pad=0,
                share_all=True,
                cbar_location="right",
                cbar_mode="single",
                cbar_size="3%",
                cbar_pad=0.0,
                )
<Plotting commands for bottom row . . .>
StemPlot = plt.subplot(313)
<plotting commands for bottom stem plot>

EDIT:  the whitespace in the color plots is intentional, not some artifact from adding the colorbars


问:
What is the difference between a sequence point and operator precedence?
Consider the classical sequence point example:

```<code>i = i++;
</code>```

The C and C++ standards state that the behavior of the above expression is undefined because the = operator is not associated with a sequence point.

What confuses me is that ++ has a higher precedence than = and so, the above expression, based on precedence, must evaluate i++ first and then do the assignment. Thus, if we start with i = 0, we should always end up with i = 0 (or i = 1, if the expression was i = ++i) and not undefined behavior. What am I missing?

答:
Operator precedence and order of evaluation are two different things. Let's have a look at them one by one:

Operator precedence rule: In an expression operands bound tighter to the operators having higher precedence.

For example

```<code>int a = 5;
int b = 10;
int c = 2;
int d;

d = a + b * c;
</code>```

In the expression a + b * c, precedence of * is higher than that of + and therefore, b and c will bind to * and expression will be parsed as a + (b * c).

Order of evaluation rule: It describes how operands will be evaluated in an expression. In the statement

```<code> d = a>5 ? a : ++a;
</code>```

a is guaranteed to be evaluated before evaluation of ++b or c.

But for the expression a + (b * c), though * has higher precedence than that of +, it is not guaranteed that a will be evaluated either before or after b or c and not even b and c ordered for their evaluation. Even a, b and c can evaluate in any order.

The simple rule is that: operator precedence is independent from order of evaluation and vice versa.

In the expression i = i++, higher precedence of ++ just tells the compiler to bind i with ++ operator and that's it. It says nothing about order of evaluation of the operands or which side effect (the one by = operator or one by ++) should take place first. Compiler is free to do anything.

Let's rename the i at left of assignment be il and at the right of assignment (in the expression i++) be ir, then the expression be like

```<code>il = ir++     // Note that suffix l and r are used for the sake of clarity.
              // Both il and ir represents the same object.
</code>```

Now compiler is free to evaluate the expression il = ir++ either as

```<code>temp = ir;      // i = 0
ir = ir + 1;    // i = 1   side effect by ++ before assignment
il = temp;      // i = 0   result is 0
</code>```

or

```<code>temp = ir;      // i = 0
il = temp;      // i = 0   side effect by assignment before ++
ir = ir + 1;    // i = 1   result is 1
</code>```

resulting in two different results 0 and 1 which depends on the sequence of side effects by assignment and ++ and hence invokes UB.

Body:
Consider the classical sequence point example:

i = i++;

The C and C++ standards state that the behavior of the above expression is undefined because the = operator is not associated with a sequence point.

What confuses me is that ++ has a higher precedence than = and so, the above expression, based on precedence, must evaluate i++ first and then do the assignment. Thus, if we start with i = 0, we should always end up with i = 0 (or i = 1, if the expression was i = ++i) and not undefined behavior. What am I missing?

Body:
Operator precedence and order of evaluation are two different things. Let's have a look at them one by one:

Operator precedence rule: In an expression operands bound tighter to the operators having higher precedence.

For example

int a = 5;
int b = 10;
int c = 2;
int d;

d = a + b * c;

In the expression a + b * c, precedence of * is higher than that of + and therefore, b and c will bind to * and expression will be parsed as a + (b * c).

Order of evaluation rule: It describes how operands will be evaluated in an expression. In the statement

 d = a>5 ? a : ++a;

a is guaranteed to be evaluated before evaluation of ++b or c.

But for the expression a + (b * c), though * has higher precedence than that of +, it is not guaranteed that a will be evaluated either before or after b or c and not even b and c ordered for their evaluation. Even a, b and c can evaluate in any order.

The simple rule is that: operator precedence is independent from order of evaluation and vice versa.

In the expression i = i++, higher precedence of ++ just tells the compiler to bind i with ++ operator and that's it. It says nothing about order of evaluation of the operands or which side effect (the one by = operator or one by ++) should take place first. Compiler is free to do anything.

Let's rename the i at left of assignment be il and at the right of assignment (in the expression i++) be ir, then the expression be like

il = ir++     // Note that suffix l and r are used for the sake of clarity.
              // Both il and ir represents the same object.

Now compiler is free to evaluate the expression il = ir++ either as

temp = ir;      // i = 0
ir = ir + 1;    // i = 1   side effect by ++ before assignment
il = temp;      // i = 0   result is 0

or

temp = ir;      // i = 0
il = temp;      // i = 0   side effect by assignment before ++
ir = ir + 1;    // i = 1   result is 1

resulting in two different results 0 and 1 which depends on the sequence of side effects by assignment and ++ and hence invokes UB.


问:
Everything now is XML - but programming is still done with some legacy files obeying complicated syntax
Why is this ? Gcc is now providing a "C-to-XML" conversion since XML is more easily parsed.

Couldn't we benefit if our source code was XML?

Of course, nobody want's to edit XML files manually - but that's what IDEs are made for.

Would some programming language with less syntax (LISP, Smalltalk) better map to XML?

答:
```<code> <comment>
 <statement-of-argument>
    I don't think everything is XML.
 </statement-of-argument>
 <p>
    You still see plenty of plain text and other forms of encoding.
    I think you're just being <pejorative>silly</pejorative>.
    Or perhaps imagining things.
 </p>
 </comment>
</code>```