问:
How to send all the values of a dynamic input field to the action page and `echo` an `Ordered List` with the values?
In my form, I have made a dynamic text input field using jQuery and made it sortable using jQuery-UI. But the problem it, when I submit the form, only the last value of the form is sent to the action page.

How can I send all the values to the form action page and echo an Ordered List with the values?

Thanks in advance for your suggestions. Here is the snippet of the dynamic form:

    $(document).ready(function() {
       var fixHelperModified = function(e, div) {
             var $originals = div.children();
             var $helper = div.clone();
             $helper.children().each(function(index) {
                $(this).width($originals.eq(index).width())
             });
             return $helper;
          },
          updateIndex = function() {
             $('div.index').each(function(i) {
                $(this).html(i + 1);
             });
          };
       $("#add").sortable({
          helper: fixHelperModified,
          stop: updateIndex
       }).disableSelection();
       $("#addNew").click(function() {
          $('#add').append("

1.

<input type='text' class='form-control' name='members'>

<button class='delete btn btn-warning btn-xs'>Delete</button>

");
          updateIndex();
       });
       $("body").on('click', '#add .delete', function() {
          $(this).closest(".rem").remove();
          updateIndex();
       });
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<form method="post" id="members" class="form-horizontal" action="pritnPreview.php">
   <fieldset>
      <div class="form-group">
         <div class="col-sm-2">
            <label class="form-name">Members</label>
         </div>
         <div class="col-sm-8">
            <div class="row">
               <div id='add'>
                  <div class='row rem' id='move'>
                     <div class='col-md-1 index'>1. </div>
                     <div class='col-md-9'>
                        <input type='text' class='form-control' name='members'>
                     </div>
                     <div class='col-md-1'>
                        <button class='delete btn btn-warning btn-xs'>Delete</button>
                     </div>
                  </div>
               </div>
            </div>
            <div class="row">
               <div class="form-group">
                  <div class="col-md-2">
                     <button id='addNew' type="button" href="#">Add another</button>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form></code>```

The printPreview.php page:

```<code><?php
    if (!empty($_POST['cc'])) echo 'CC: ' . $cc;
    ?>
</code>```

答:
Change the name of the input to cc[] to save a array of values

```<code> name='cc[]'
</code>```

Body:
In my form, I have made a dynamic text input field using jQuery and made it sortable using jQuery-UI. But the problem it, when I submit the form, only the last value of the form is sent to the action page.

How can I send all the values to the form action page and echo an Ordered List with the values?

Thanks in advance for your suggestions. Here is the snippet of the dynamic form:

    $(document).ready(function() {
       var fixHelperModified = function(e, div) {
             var $originals = div.children();
             var $helper = div.clone();
             $helper.children().each(function(index) {
                $(this).width($originals.eq(index).width())
             });
             return $helper;
          },
          updateIndex = function() {
             $('div.index').each(function(i) {
                $(this).html(i + 1);
             });
          };
       $("#add").sortable({
          helper: fixHelperModified,
          stop: updateIndex
       }).disableSelection();
       $("#addNew").click(function() {
          $('#add').append("

1.

<input type='text' class='form-control' name='members'>

<button class='delete btn btn-warning btn-xs'>Delete</button>

");
          updateIndex();
       });
       $("body").on('click', '#add .delete', function() {
          $(this).closest(".rem").remove();
          updateIndex();
       });
    });

<form method="post" id="members" class="form-horizontal" action="pritnPreview.php">
   <fieldset>

            Members

1.

                        <input type='text' class='form-control' name='members'>

                        <button class='delete btn btn-warning btn-xs'>Delete</button>

                     <button id='addNew' type="button" href="#">Add another</button>

   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form>

The printPreview.php page:

<?php
    if (!empty($_POST['cc'])) echo 'CC: ' . $cc;
    ?>

Body:
Change the name of the input to cc[] to save a array of values

 name='cc[]'


来源: stackexchange

问:
Function with a -> a -> a possible in Haskell?
I am going through Haskell Programming book and an in exercise on page 140, the author states this:

A hypothetical function a->a->a has two possible implementations. Write both possible versions.

I am assuming a -> a -> a  would imply a function that takes two arguments (a and a) - (which does not makes sense to me and if I declare a function with two args as a, ghci rightly complains too) and returns a

I think I am missing something, what is it?

答:
The way to think about this problem, perhaps, is to imagine how much we do not know about your arguments a and a.

It is impossible, for instance, for us to say the following:

```<code>someFunc :: a -> a -> a
someFunc x y = x == y
</code>```

This won't typecheck because we don't even know if a is an instance of the typeclass Eq. In other words, we have no useful information about these a things except that they are the same type of thing (whatever that may be).

Consider the identity function:

```<code>ident :: a -> a
ident x = ...
</code>```

There is nothing this function can know about its sole argument x. There is, as a result, only one possible, valid result:

```<code>ident x = x
</code>```

Nothing else works because there's nothing else we can assume about our argument.

Now, in your case, you have two arguments which can be absolutely anything in the universe. There is no possible assertion we can make about any behaviors these two arguments can conform to. Thus, we can define our function in possibly two different ways:

```<code>someFunc1 :: a -> a -> a
someFunc1 x y = x
</code>```

OR

```<code>someFunc2 :: a -> a -> a
someFunc2 x y = y
</code>```

There is no other valid way to represent this function.

ContentLicense: CC BY-SA 3.0

Body:
The way to think about this problem, perhaps, is to imagine how much we do not know about your arguments a and a.

It is impossible, for instance, for us to say the following:

someFunc :: a -> a -> a
someFunc x y = x == y

This won't typecheck because we don't even know if a is an instance of the typeclass Eq. In other words, we have no useful information about these a things except that they are the same type of thing (whatever that may be).

Consider the identity function:

ident :: a -> a
ident x = ...

There is nothing this function can know about its sole argument x. There is, as a result, only one possible, valid result:

ident x = x

Nothing else works because there's nothing else we can assume about our argument.

Now, in your case, you have two arguments which can be absolutely anything in the universe. There is no possible assertion we can make about any behaviors these two arguments can conform to. Thus, we can define our function in possibly two different ways:

someFunc1 :: a -> a -> a
someFunc1 x y = x

OR

someFunc2 :: a -> a -> a
someFunc2 x y = y

There is no other valid way to represent this function.


问:
Sum the number of firms in one year
Suppose I have a dataframe as follows:

```<code>dt=structure(list(id = c(1L, 1L, 1L, 1L, 2L, 3L, 3L, 3L, 4L, 4L,
4L, 4L, 5L, 5L, 6L, 6L), year = c(2001L, 2002L, 2003L, 2004L,
2002L, 2002L, 2003L, 2004L, 2002L, 2003L, 2004L, 2005L, 2001L,
2002L, 2001L, 2002L)), .Names = c("firm", "year"), row.names = c(NA,
-16L), class = "data.frame")

dt
 firm year
1   1 2001
2   1 2002
3   1 2003
4   1 2004
5   2 2002
6   3 2002
7   3 2003
8   3 2004
9   4 2002
10  4 2003
11  4 2004
12  4 2005
13  5 2001
14  5 2002
15  6 2001
16  6 2002
</code>```

Now, I hope to sum the number of firms which have exited the market in one year. For example, I want a table like this:

```<code> resulttable
     All 2001 2002 2003 2004 2005
2001   3    0    2    0    1    0
2002   3    0    1    0    1    1
</code>```

The first row of resulttable means that 3 firms entered the market in year 2001 and 2 firms exited in 2003, 1 firm exited in year 2004. Thanks!

答:
Here is an option using dcast from data.table.  Convert the 'data.frame' to 'data.table' (setDT(dt)), grouped by 'firm' get the range of 'year' into two columns, dcast into 'wide' with drop = FALSE to avoid removing the unused levels and then sum the values in the row with Reduce

```<code>library(data.table)
dcast(setDT(dt)[, as.list(range(year)), firm], V1 ~ factor(V2, levels = unique(dt$year)),
          drop =FALSE)[, All := Reduce(`+` , .SD), .SDcols = -1][]
#      V1 2001 2002 2003 2004 2005 All
#1: 2001    0    2    0    1    0   3
#2: 2002    0    1    0    1    1   3
</code>```

Title: Sum the number of firms in one year

Body:
Suppose I have a dataframe as follows:

dt=structure(list(id = c(1L, 1L, 1L, 1L, 2L, 3L, 3L, 3L, 4L, 4L,
4L, 4L, 5L, 5L, 6L, 6L), year = c(2001L, 2002L, 2003L, 2004L,
2002L, 2002L, 2003L, 2004L, 2002L, 2003L, 2004L, 2005L, 2001L,
2002L, 2001L, 2002L)), .Names = c("firm", "year"), row.names = c(NA,
-16L), class = "data.frame")

dt
 firm year
1   1 2001
2   1 2002
3   1 2003
4   1 2004
5   2 2002
6   3 2002
7   3 2003
8   3 2004
9   4 2002
10  4 2003
11  4 2004
12  4 2005
13  5 2001
14  5 2002
15  6 2001
16  6 2002

Now, I hope to sum the number of firms which have exited the market in one year. For example, I want a table like this:

 resulttable
     All 2001 2002 2003 2004 2005
2001   3    0    2    0    1    0
2002   3    0    1    0    1    1

The first row of resulttable means that 3 firms entered the market in year 2001 and 2 firms exited in 2003, 1 firm exited in year 2004. Thanks!

Body:
Here is an option using dcast from data.table.  Convert the 'data.frame' to 'data.table' (setDT(dt)), grouped by 'firm' get the range of 'year' into two columns, dcast into 'wide' with drop = FALSE to avoid removing the unused levels and then sum the values in the row with Reduce

library(data.table)
dcast(setDT(dt)[, as.list(range(year)), firm], V1 ~ factor(V2, levels = unique(dt$year)),
          drop =FALSE)[, All := Reduce(`+` , .SD), .SDcols = -1][]
#      V1 2001 2002 2003 2004 2005 All
#1: 2001    0    2    0    1    0   3
#2: 2002    0    1    0    1    1   3


问:
How to rename package name
When I create a package long_term_streaming_monitor by paster

What should I do if I want to change long_term_streaming_monitor to long_term_monitor

What files should I change and how ?

Thanks

setup.py

```<code>from setuptools import setup, find_packages
import sys, os

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
NEWS = open(os.path.join(here, 'NEWS.txt')).read()

version = '0.3'

install_requires = [
    # List your project dependencies here.
    # For more details, see:
    # http://packages.python.org/distribute/setuptools.html#declaring-dependencies
]

setup(name='long_term_streaming_monitor/',
    version=version,
    description="",
    long_description=README + '\n\n' + NEWS,
    classifiers=[
      # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
    ],
    keywords='',
    url='',
    license='',
    packages=find_packages('src'),
    package_dir = {'': 'src'},include_package_data=True,
    zip_safe=False,
    install_requires=install_requires,
    entry_points={
        'console_scripts':
            ['long_term_streaming_monitor/=long_term_streaming_monitor:main']
    }
)
</code>```

Package tree view

```<code>├── [Mar 21 16:03]  HACKING.txt
├── [Mar 21 16:03]  MANIFEST.in
├── [Mar 21 16:03]  NEWS.txt
├── [Mar 21 16:03]  README.rst
├── [Mar 21 16:03]  bootstrap.py
├── [Mar 21 16:03]  buildout.cfg
├── [Mar 27 18:07]  docs
│   ├── [Mar 25 11:56]  Makefile
│   ├── [Mar 25 11:58]  _build
│   ├── [Mar 25 11:56]  _static
│   ├── [Mar 25 11:56]  _templates
│   ├── [Mar 25 11:56]  conf.py
│   ├── [Mar 25 11:55]  html
│   ├── [Mar 25 11:55]  index.rst
│   ├── [Mar 25 11:55]  long_term_streaming_monitor.rst
│   ├── [Mar 25 11:55]  long_term_streaming_monitor.tests.rst
│   ├── [Mar 25 11:56]  make.bat
│   ├── [Mar 25 11:55]  modules.rst
│   └── [Mar 25 11:58]  y.rst
├── [Mar 27 18:13]  setup.py
└── [Mar 27 18:13]  src
    ├── [Mar 27 18:13]  long_term_streaming_monitor
    └── [Mar  6 18:00]  long_term_streaming_monitor_.egg-info
</code>```

答:
rename long_term_streaming_monitor to long_term_monitor in setup.py

setup(name='long_term_streaming_monitor/', ..)

to

setup(name='long_term_monitor', ..)

Title: How to rename package name

Body:
When I create a package long_term_streaming_monitor by paster

What should I do if I want to change long_term_streaming_monitor to long_term_monitor

What files should I change and how ?

Thanks

setup.py

from setuptools import setup, find_packages
import sys, os

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
NEWS = open(os.path.join(here, 'NEWS.txt')).read()

version = '0.3'

install_requires = [
    # List your project dependencies here.
    # For more details, see:
    # http://packages.python.org/distribute/setuptools.html#declaring-dependencies
]

setup(name='long_term_streaming_monitor/',
    version=version,
    description="",
    long_description=README + '\n\n' + NEWS,
    classifiers=[
      # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
    ],
    keywords='',
    url='',
    license='',
    packages=find_packages('src'),
    package_dir = {'': 'src'},include_package_data=True,
    zip_safe=False,
    install_requires=install_requires,
    entry_points={
        'console_scripts':
            ['long_term_streaming_monitor/=long_term_streaming_monitor:main']
    }
)

Package tree view

├── [Mar 21 16:03]  HACKING.txt
├── [Mar 21 16:03]  MANIFEST.in
├── [Mar 21 16:03]  NEWS.txt
├── [Mar 21 16:03]  README.rst
├── [Mar 21 16:03]  bootstrap.py
├── [Mar 21 16:03]  buildout.cfg
├── [Mar 27 18:07]  docs
│   ├── [Mar 25 11:56]  Makefile
│   ├── [Mar 25 11:58]  _build
│   ├── [Mar 25 11:56]  _static
│   ├── [Mar 25 11:56]  _templates
│   ├── [Mar 25 11:56]  conf.py
│   ├── [Mar 25 11:55]  html
│   ├── [Mar 25 11:55]  index.rst
│   ├── [Mar 25 11:55]  long_term_streaming_monitor.rst
│   ├── [Mar 25 11:55]  long_term_streaming_monitor.tests.rst
│   ├── [Mar 25 11:56]  make.bat
│   ├── [Mar 25 11:55]  modules.rst
│   └── [Mar 25 11:58]  y.rst
├── [Mar 27 18:13]  setup.py
└── [Mar 27 18:13]  src
    ├── [Mar 27 18:13]  long_term_streaming_monitor
    └── [Mar  6 18:00]  long_term_streaming_monitor_.egg-info

ContentLicense: CC BY-SA 4.0


问:
Load a .gif (Image slow)
I've implemented Glide library, on my project, but the problem is that it lags a lot, the image is mooving super slow, I do not want to use a WebView (if I have to, it'd be the last option), but I'd like if anyone of you have implemented for example an Alert Dialog with a .gif or something, and know what is the perfect size to load a .gif please, let me know.

I put the code but it's not necessary, because it's just one line.

```<code>Glide.with(this).load(R.raw.test).into(ivGif);
</code>```

答:
Here if you want use Glide for load gif image:

```<code>Glide.with(context).load(myUrl)
                .thumbnail(Glide.with(context).load(R.drawable.myThumbnail))
                .fitCenter()
                .crossFade()
                .into(imageView);
</code>```

I'm suggest if you use Icon libs for load gif Image, because Icon libs load image better 2x times faster than Glide. But in terms of images quality Glide is better.
I post code use Icon libs for load gif image:

```<code> Ion.with(this).load(myUrl).withBitmap().asBitmap()
            .setCallback(new FutureCallback<Bitmap>() {
                @Override
                public void onCompleted(Exception e, Bitmap result) {
                    // do something with your bitmap
                }
            });
</code>```

Title: Load a .gif (Image slow)

Body:
I've implemented Glide library, on my project, but the problem is that it lags a lot, the image is mooving super slow, I do not want to use a WebView (if I have to, it'd be the last option), but I'd like if anyone of you have implemented for example an Alert Dialog with a .gif or something, and know what is the perfect size to load a .gif please, let me know.

I put the code but it's not necessary, because it's just one line.

Glide.with(this).load(R.raw.test).into(ivGif);

Body:
Here if you want use Glide for load gif image:

Glide.with(context).load(myUrl)
                .thumbnail(Glide.with(context).load(R.drawable.myThumbnail))
                .fitCenter()
                .crossFade()
                .into(imageView);

I'm suggest if you use Icon libs for load gif Image, because Icon libs load image better 2x times faster than Glide. But in terms of images quality Glide is better.
I post code use Icon libs for load gif image:

 Ion.with(this).load(myUrl).withBitmap().asBitmap()
            .setCallback(new FutureCallback<Bitmap>() {
                @Override
                public void onCompleted(Exception e, Bitmap result) {
                    // do something with your bitmap
                }
            });


问:
Metal shader types vertex and buffer best practice demonstrated in "ShaderTypes.h"
Here is the full shadertypes.h file. I am going to break it down into parts that I cant understand.

```<code>#ifndef ShaderTypes_h
#define ShaderTypes_h

//Part 1 Compiler flags
#ifdef __METAL_VERSION__
#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
#define NSInteger metal::int32_t
#else
#import <Foundation/Foundation.h>
#endif

#include <simd/simd.h>

//Part 2 buffer index
typedef NS_ENUM(NSInteger, BufferIndex)
{
    BufferIndexMeshPositions = 0,
    BufferIndexMeshGenerics  = 1,
    BufferIndexUniforms      = 2
};

//Part 3 vertex attribute and position
typedef NS_ENUM(NSInteger, VertexAttribute)
{
    VertexAttributePosition  = 0,
    VertexAttributeTexcoord  = 1,
};

//Part 4 texture index color
typedef NS_ENUM(NSInteger, TextureIndex)
{
    TextureIndexColor    = 0,
};

//Part 5 uniforms
typedef struct
{
    matrix_float4x4 projectionMatrix;
    matrix_float4x4 modelViewMatrix;
} Uniforms;

#endif /* ShaderTypes_h */
</code>```

Part 1

```<code>#ifdef __METAL_VERSION__
#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
#define NSInteger metal::int32_t
#else
#import <Foundation/Foundation.h>
#endif
//A bunch of definitions go after this
#endif
</code>```

My confusion is mostly why we are doing all of this code. It seems to be checking if the user has metal but then what is this NS_ENUM it is defining? Why is it defining a metal variable? While is foundation conditionally imported?

Part 2

```<code>typedef NS_ENUM(NSInteger, BufferIndex)
{
    BufferIndexMeshPositions = 0,
    BufferIndexMeshGenerics  = 1,
    BufferIndexUniforms      = 2
};
</code>```

Not exactly sure what this is doing especially since I cant find anyone referencing them explicitly anywhere.

Part 3

```<code>typedef NS_ENUM(NSInteger, VertexAttribute)
{
    VertexAttributePosition  = 0,
    VertexAttributeTexcoord  = 1,
};
</code>```

This one has a bit more of a clear usage because it is referenced in the .metal file

```<code>typedef struct
{
    float3 position [[attribute(VertexAttributePosition)]];
    float2 texCoord [[attribute(VertexAttributeTexcoord)]];
} Vertex;
</code>```

as well as in the attribute section of the vertex descriptor code

```<code>    mtlVertexDescriptor.attributes[VertexAttribute.position.rawValue].format = MTLVertexFormat.float3
mtlVertexDescriptor.attributes[VertexAttribute.position.rawValue].offset = 0
mtlVertexDescriptor.attributes[VertexAttribute.position.rawValue].bufferIndex = BufferIndex.meshPositions.rawValue
...
</code>```

Somehow it appears to be keeping track of indexes of the various elements rather like the buffer.

Part 4

This one I sort of get as it is referenced in the render here

```<code>renderEncoder.setFragmentTexture(colorMap, index: TextureIndex.color.rawValue)
</code>```

as well as the shader here

```<code>fragment float4 fragmentShader(..., texture2d<half> colorMap     [[ texture(TextureIndexColor) ]]){
</code>```

I sort of get this one (Minus the NSEnum part) however I dont get how it is good practice to do this for just one thing.

Part 5

This one is actually the only one I understand it looks like its a struct for all the uniform components which makes a lot of sense as it is storing the actual types of the uniforms allowing the shader to be exposed to the struct as well as the renderer.

I guess ultimately I am wondering why this approach was taken and why it is a suggested best practice by Apple. I suppose it sort of makes sense to do things this way except for the fact that metal appears to play better with objective-c even though it looks like swift.

答:
This is a header that's meant to be shared by Metal shader code and app code (either Objective-C or, via bridging, Swift). Having to share it between those two languages requires a bit of care.

The #ifdef __METAL_VERSION__ test determines which language it's being compiled in. For Metal, a couple of macros are defined. For Objective-C, it imports Foundation. (Foundation can't, of course, be imported when compiling Metal code.)

In their (Objective-)C headers, Apple routinely declare enums using the NS_ENUM() macro. That macro is defined within the Foundation headers, so it can be used when this header is being compiled into app code. It's not defined in the Metal headers, so this header needs to define it for itself if it wants to use it (as it does). The Foundation version of the macro is useful because it detects compiler capabilities to use typed enums if available and conventional enums if not. In this header, Apple is implementing that same macro for the Metal shader language. Since there's no question whether the compiler supports typed enums (it does), there's only one definition of the macro which takes advantage of that feature.

Later in the header, they plan on using the NSInteger type. That's defined by the Foundation headers for app code. Since they want to use the same code for Metal but that type isn't defined there, they need to define it in this header. They make a couple of weird choices, though. First, they use a macro instead of a typedef. Second, they define it to be equivalent to int32_t (in the metal namespace). That's weird because the app code is going to be 64-bit (Metal isn't available to 32-bit apps) causing NSInteger to be a 64-bit integer type (equivalent to int64_t). So, the two worlds are going to disagree about the size of NSInteger and therefore all of the enums based on it. That's kind of bad, but probably doesn't cause a real issue given the ways these enums are actually used.

It would probably have been better to simply base the enums on int, which is 32-bit in all Apple environments.

Parts 2, 3, and 4 are all similar. It's generally good practice to use "symbolic" constants rather than just magic numbers (i.e. integer literals within the code). It is less error-prone and improves readability. These parts are simply defining some such symbolic constants for use by the Metal code and app code to share. The fact that some of these names aren't used in the particular sample project you're examining suggests that Apple uses this same header for multiple sample projects, or something like that.

Body:
Here is the full shadertypes.h file. I am going to break it down into parts that I cant understand.

#ifndef ShaderTypes_h
#define ShaderTypes_h

//Part 1 Compiler flags
#ifdef __METAL_VERSION__
#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
#define NSInteger metal::int32_t
#else
#import <Foundation/Foundation.h>
#endif

#include <simd/simd.h>

//Part 2 buffer index
typedef NS_ENUM(NSInteger, BufferIndex)
{
    BufferIndexMeshPositions = 0,
    BufferIndexMeshGenerics  = 1,
    BufferIndexUniforms      = 2
};

//Part 3 vertex attribute and position
typedef NS_ENUM(NSInteger, VertexAttribute)
{
    VertexAttributePosition  = 0,
    VertexAttributeTexcoord  = 1,
};

//Part 4 texture index color
typedef NS_ENUM(NSInteger, TextureIndex)
{
    TextureIndexColor    = 0,
};

//Part 5 uniforms
typedef struct
{
    matrix_float4x4 projectionMatrix;
    matrix_float4x4 modelViewMatrix;
} Uniforms;

#endif /* ShaderTypes_h */

Part 1

#ifdef __METAL_VERSION__
#define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
#define NSInteger metal::int32_t
#else
#import <Foundation/Foundation.h>
#endif
//A bunch of definitions go after this
#endif

My confusion is mostly why we are doing all of this code. It seems to be checking if the user has metal but then what is this NS_ENUM it is defining? Why is it defining a metal variable? While is foundation conditionally imported?

Part 2

typedef NS_ENUM(NSInteger, BufferIndex)
{
    BufferIndexMeshPositions = 0,
    BufferIndexMeshGenerics  = 1,
    BufferIndexUniforms      = 2
};

Not exactly sure what this is doing especially since I cant find anyone referencing them explicitly anywhere.

Part 3

typedef NS_ENUM(NSInteger, VertexAttribute)
{
    VertexAttributePosition  = 0,
    VertexAttributeTexcoord  = 1,
};

This one has a bit more of a clear usage because it is referenced in the .metal file

typedef struct
{
    float3 position [[attribute(VertexAttributePosition)]];
    float2 texCoord [[attribute(VertexAttributeTexcoord)]];
} Vertex;

as well as in the attribute section of the vertex descriptor code

    mtlVertexDescriptor.attributes[VertexAttribute.position.rawValue].format = MTLVertexFormat.float3
mtlVertexDescriptor.attributes[VertexAttribute.position.rawValue].offset = 0
mtlVertexDescriptor.attributes[VertexAttribute.position.rawValue].bufferIndex = BufferIndex.meshPositions.rawValue
...

Somehow it appears to be keeping track of indexes of the various elements rather like the buffer.

Part 4

This one I sort of get as it is referenced in the render here

renderEncoder.setFragmentTexture(colorMap, index: TextureIndex.color.rawValue)

as well as the shader here

fragment float4 fragmentShader(..., texture2d<half> colorMap     [[ texture(TextureIndexColor) ]]){

I sort of get this one (Minus the NSEnum part) however I dont get how it is good practice to do this for just one thing.

Part 5

This one is actually the only one I understand it looks like its a struct for all the uniform components which makes a lot of sense as it is storing the actual types of the uniforms allowing the shader to be exposed to the struct as well as the renderer.

I guess ultimately I am wondering why this approach was taken and why it is a suggested best practice by Apple. I suppose it sort of makes sense to do things this way except for the fact that metal appears to play better with objective-c even though it looks like swift.


问:
Microsoft Excel
I have an excel sheet with Columns having the dates of a month. The entire column needs to be colored based on whether the date in the header cell is a weekday or weekend, I tried using the Weekday formula, but unable to get the work done.
Could anyone please guide me on this?

Image below shows the requirement.

答:
Simply use conditional formatting like this:

Basically, highlight the columns, from the Home tab, select 'Conditional Formatting' > 'New Rule' > 'Use a formula ...', use =WEEKDAY(A$1,2)>5 (A is the cell of the lighter cell from the highlighted range, $1 is the header row, the $ sign ensures that the condition always checks the 1st row), then select the formatting of your choice.

Repeat similar steps for weekdays, except this time the formula will be =WEEKDAY(A$1,2)<6 (or equivalent =WEEKDAY(A$1,2)<=5, etc) and the format will be different.

Title: Microsoft Excel


问:
Is try-catch like error handling possible in ASP Classic?
What options are there in ASP Classic for error handling?

For example:

I'm using the Mail.SendMail function but when switching on the testing server it doesn't work, which is normal. I want to test if mailing is possible, if not then continue and/or show a message.

Any ideas?

答:
There are two approaches, you can code in JScript or VBScript which do have the construct or you can fudge it in your code.

Using JScript you'd use the following type of construct:

```<code><script language="jscript" runat="server">
try  {
    tryStatements
}
catch(exception) {
    catchStatements
}
finally {
    finallyStatements
}
</script>
</code>```

In your ASP code you fudge it by using on error resume next at the point you'd have a try and checking err.Number at the point of a catch like:

<%
' Turn off error Handling
On Error Resume Next

'Code here that you want to catch errors from

' Error Handler
If Err.Number <> 0 Then
   ' Error Occurred - Trap it
   On Error Goto 0 ' Turn error handling back on for errors in your handling block
   ' Code to cope with the error here
End If
On Error Goto 0 ' Reset error handling.

%>
```

OwnerDisplayName: Sander Versluys

ContentLicense: CC BY-SA 2.5

Body:
There are two approaches, you can code in JScript or VBScript which do have the construct or you can fudge it in your code.

Using JScript you'd use the following type of construct:

<script language="jscript" runat="server">
try  {
    tryStatements
}
catch(exception) {
    catchStatements
}
finally {
    finallyStatements
}
</script>

In your ASP code you fudge it by using on error resume next at the point you'd have a try and checking err.Number at the point of a catch like:

<%
' Turn off error Handling
On Error Resume Next

'Code here that you want to catch errors from

' Error Handler
If Err.Number <> 0 Then
   ' Error Occurred - Trap it
   On Error Goto 0 ' Turn error handling back on for errors in your handling block
   ' Code to cope with the error here
End If
On Error Goto 0 ' Reset error handling.

%>

OwnerDisplayName: Wolfwyrd


问:
User Input Date Comparison in Javascript and moment.js
I'm trying to compare two user input dates which is not related to the current or today's date with moment.js. I want to display the color based on the date difference.Help me reach out.

Here is my code:

function compare() {
 var firstDate = moment($("#date1").val(), "MM-DD-YYYY");
  var secondDate = moment($("#date2").val(), "MM-DD-YYYY");

  console.log(firstDate.inspect(), secondDate.inspect());

  if (firstDate.isValid() && secondDate.isValid()) {
    // you need a validation before using diff function of momentjs
    var diff = Math.abs(firstDate.diff(secondDate, 'days'));
    console.log(diff);
    // you also need to remove all classes before adding new class
    $("#status").removeClass("redBg").removeClass("greenBg").removeClass("yellowBg");
    if (diff => 14) {
      $("#status").addClass('redBg');
    } else if (7 < diff =< 9) {
      $("#status").addClass('greenBg');
    } else if(diff >= 6) {
      $("#status").addClass('yellowBg');
    }
  } else {
    $("#status").addClass('yellowBg');
  }

    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.greenBg {
    background: green;
}

.yellowBg {
    background: yellow;
}

.redBg {
    background: red;
}</code>```

    <input type="text" id="date1" onchange=/>
<input type="text" id="date2" onchange='compare()'/>
<input  readonly type="text" id="status"/>

```

what is the mistake I have made?

答:
You should get the values with

```<code>document.getElementById('date1').value
</code>```

not with

```<code>"document.getElementById'date1'"
</code>```

the code should be:

```<code>var firstDate = moment(document.getElementById('date1').value, "MM-DD-YYYY");
var secondDate = moment(document.getElementById('date2').value, "MM-DD-YYYY");
</code>```

or better

```<code>var firstDate = moment($('$date1').val(), "MM-DD-YYYY");
var secondDate = moment($('$date2').val(), "MM-DD-YYYY");
</code>```

Edit

To make your code work, it needs to be like this:

function compare() {

  var firstDate = moment($("#date1").val(), "MM-DD-YYYY");
  var secondDate = moment($("#date2").val(), "MM-DD-YYYY");

  console.log(firstDate.inspect(), secondDate.inspect());

  if (firstDate.isValid() && secondDate.isValid()) {
    // you need a validation before using diff function of momentjs
    var diff = firstDate.diff(secondDate, 'days');
    console.log(diff);
    // you also need to remove all classes before adding new class
    $("#status").removeClass("redBg").removeClass("greenBg").removeClass("yellowBg");
    if (diff > 7) {
      $("#status").addClass('redBg');
    } else if (diff > 4) {
      $("#status").addClass('greenBg');
    } else {
      $("#status").addClass('yellowBg');
    }
  } else {
    $("#status").addClass('yellowBg');
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.greenBg {
  background: green;
}

.yellowBg {
  background: yellow;
}

.redBg {
  background: red;
}</code>```

  <input type="text" id="date1" />
  <input type="text" id="date2" />
  <input type="text" id="status" />
  <input type="button" id="click" value="check" onclick="compare()">

```
</div>
</div>
</p>

<p>Added a few debug statements to make you understand the code.</p>

<hr>

<p>Further edit: </p>

<p>without the button, you can use the <code>input</code> or <code>change</code> events of the textboxes:</p>

```<input type="text" id="date1" onchange='compare()' />
<input type="text" id="date2" onchange='compare()' />
```

Body:
I'm trying to compare two user input dates which is not related to the current or today's date with moment.js. I want to display the color based on the date difference.Help me reach out.

Here is my code:

function compare() {
 var firstDate = moment($("#date1").val(), "MM-DD-YYYY");
  var secondDate = moment($("#date2").val(), "MM-DD-YYYY");

  console.log(firstDate.inspect(), secondDate.inspect());

  if (firstDate.isValid() && secondDate.isValid()) {
    // you need a validation before using diff function of momentjs
    var diff = Math.abs(firstDate.diff(secondDate, 'days'));
    console.log(diff);
    // you also need to remove all classes before adding new class
    $("#status").removeClass("redBg").removeClass("greenBg").removeClass("yellowBg");
    if (diff => 14) {
      $("#status").addClass('redBg');
    } else if (7 < diff =< 9) {
      $("#status").addClass('greenBg');
    } else if(diff >= 6) {
      $("#status").addClass('yellowBg');
    }
  } else {
    $("#status").addClass('yellowBg');
  }

    });

.greenBg {
    background: green;
}

.yellowBg {
    background: yellow;
}

.redBg {
    background: red;
}

    <input type="text" id="date1" onchange=/>
<input type="text" id="date2" onchange='compare()'/>
<input  readonly type="text" id="status"/>

what is the mistake I have made?

Body:
You should get the values with

document.getElementById('date1').value

not with

"document.getElementById'date1'"

the code should be:

var firstDate = moment(document.getElementById('date1').value, "MM-DD-YYYY");
var secondDate = moment(document.getElementById('date2').value, "MM-DD-YYYY");

or better

var firstDate = moment($('$date1').val(), "MM-DD-YYYY");
var secondDate = moment($('$date2').val(), "MM-DD-YYYY");

Edit

To make your code work, it needs to be like this:

function compare() {

  var firstDate = moment($("#date1").val(), "MM-DD-YYYY");
  var secondDate = moment($("#date2").val(), "MM-DD-YYYY");

  console.log(firstDate.inspect(), secondDate.inspect());

  if (firstDate.isValid() && secondDate.isValid()) {
    // you need a validation before using diff function of momentjs
    var diff = firstDate.diff(secondDate, 'days');
    console.log(diff);
    // you also need to remove all classes before adding new class
    $("#status").removeClass("redBg").removeClass("greenBg").removeClass("yellowBg");
    if (diff > 7) {
      $("#status").addClass('redBg');
    } else if (diff > 4) {
      $("#status").addClass('greenBg');
    } else {
      $("#status").addClass('yellowBg');
    }
  } else {
    $("#status").addClass('yellowBg');
  }
}

.greenBg {
  background: green;
}

.yellowBg {
  background: yellow;
}

.redBg {
  background: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.js"></script>
<html>

<body>
  <input type="text" id="date1" />
  <input type="text" id="date2" />
  <input type="text" id="status" />
  <input type="button" id="click" value="check" onclick="compare()">
</body>

</html>

Added a few debug statements to make you understand the code.

Further edit:

without the button, you can use the input or change events of the textboxes:

<input type="text" id="date1" onchange='compare()' />
<input type="text" id="date2" onchange='compare()' />


问:
Angular4 *ngFor how to loop nested array using its key name
I have the following data sample:

for now i have two nested loop, but what i want to do is, Is it possible to loop through specific key, such as *ngFor="let key of myArray.functionalArea"

My current code is:

```<code><span *ngFor="let jobByField of countOfJobsByFields">
  <span  *ngFor="let jobByWorkType of countOfJobsByFields?.workType">
    <li (click)="searchByWorkType(jobByWorkType?._id)"><a>{{ jobByWorkType?._id }}<span class="badge badge-default pull-right item-plus-icon-custom-style">{{ jobByWorkType.total }}</span></a></li>
 </span>
</code>```

and for second key i have this:

```<code><span *ngFor="let jobByField of countOfJobsByFields">
  <span  *ngFor="let jobByFunctionalArea of countOfJobsByFields?.functionalArea">
    <li (click)="searchByFunctionalArea(jobByFunctionalArea?._id)"><a>{{ jobByWorkType?._id }}<span class="badge badge-default pull-right item-plus-icon-custom-style">{{ jobByFunctionalArea.total }}</span></a></li>
 </span>
</code>```

Note i can not use the same  for both because they are separate element in my html.

答:
Yes you can :</p>

```<code><span *ngFor="let jobByField of countOfJobsByFields">
    <ng-template *ngIf='jobByField.workType'>
        <span  *ngFor="let jobByWorkType of jobByField.workType">
            {{jobByWorkType._id}}
        </span>
    </ng-template>

    <ng-template *ngIf='jobByField.functionalArea'>
        <span  *ngFor="let jobByWorkType of jobByField.functionalArea">
            {{jobByWorkType._id}}
        </span>
    </ng-template>
</span>
</code>```

Body:
I have the following data sample:

for now i have two nested loop, but what i want to do is, Is it possible to loop through specific key, such as *ngFor="let key of myArray.functionalArea"

My current code is:

{{ jobByWorkType?._id }}{{ jobByWorkType.total }}

and for second key i have this:

{{ jobByWorkType?._id }}{{ jobByFunctionalArea.total }}

Note i can not use the same  for both because they are separate element in my html.

Body:
Yes you can :

<span *ngFor="let jobByField of countOfJobsByFields">
    <ng-template *ngIf='jobByField.workType'>
        <span  *ngFor="let jobByWorkType of jobByField.workType">
            {{jobByWorkType._id}}
        </span>
    </ng-template>

    <ng-template *ngIf='jobByField.functionalArea'>
        <span  *ngFor="let jobByWorkType of jobByField.functionalArea">
            {{jobByWorkType._id}}
        </span>
    </ng-template>
</span>


问:
DataTables fixed headers misaligned with columns in wide tables

Problem

When using the sScrollX, sScrollXInner and/or sScrollY to achieve a fixed header table with its inner content scrolling, the headers of the table go out of alignment with the rest of the body in Chrome and IE. Firefox, on the other hand, displays them perfectly.

Using the version 1.9.4, as far as I can tell, this issue only occurs when there is a lot of data with fluctuating widths, and with words that are very long/unwrappable combined in the same columns as small ones. Also, the table in question needs to be fairly wide.

All these factors are demonstrated in this fiddle:

Output

Chrome:

IE:

Firefox

Suggested Solutions

These solutions have been suggested before but have had no effect on my implementation. Owing to some of these suggestions, I setup a clean plain vanilla demo as I wanted to ensure that no other code was contributing to this effect.

turn-off/remove all my css

setTimeout( function () { oTable.fnAdjustColumnSizing(); }, 10 );

calling oTable.fnFilter( "x",0 ) and oTable.fnFilter( "",0 ) in that order

"sScrollXInner": "100%"

get rid of all widths

The only solution that I found to the misaligned headers was taking out sScrollX and sScrollY, but this can't be counted as a solution as you lose the fixed header/inner content scrolling functionality. So sadly it's a temporary hack, not a fix!

Note

To edit/play with the latest fiddle.

I have tried various combinations which can be observed in the revision history of the fiddle by using the link http://jsfiddle.net/pratik136/etL73/#REV# where 1 <= #REV# <= 12

History

StackO

This question has been asked before: jQuery Datatables Header Misaligned With Vertical Scrolling

but the vital difference is that the OP of that question mentioned that they were able to fix the issue if all CSS was removed, which is untrue in my case, and I have tried a few permutations, thus thought the question worthy of a repost.

External

This issue has also been flagged on the DataTables forum:

http://datatables.net/forums/discussion/7395/sscrolly-and-sscrollx-broken/p1

http://datatables.net/forums/discussion/7778/vertical-scrolling-messes-up-column-header-alignment#Item_1

http://datatables.net/forums/discussion/3835/width-columns-problem-in-chrome-safari/p1

My bug report: http://datatables.net/forums/discussion/12491/datatables-header-alignment-issue-refresh#Item_1

This issue has driven me nuts! Please contribute your thoughts!

答:
I have fixed the column issue bu using below concept</p>

```<code>$(".panel-title a").click(function(){
    setTimeout( function(){
           $('#tblSValidationFilerGrid').DataTable().search( '' ).draw();
        }, 10 );
})
</code>```

Body:
I have fixed the column issue bu using below concept

$(".panel-title a").click(function(){
    setTimeout( function(){
           $('#tblSValidationFilerGrid').DataTable().search( '' ).draw();
        }, 10 );
})


问:
IsProviderEnabled for GPS is not working
we have implemented a geobased app for Android, so we need to ensure GPS is enabled all the time. The problem is that

```<code>manager.isProviderEnabled( LocationManager.GPS_PROVIDER )
</code>```

is always returning false even if the GPS Provider is enabled, so our app is always showing the alert to change the GPS status or it is not working.

Do you know what is happening?

We are testing it with a Samsung Galaxy S and a HTC Wildfire device...
Thanks in advance.

答:
Sometimes your device settings is set to get the location using WiFi Networks not GPS system, so that the location would be opened but your app will return false when checking for the GPS_PROVIDER.

The proper solution to that is to check for both, GPS & Network:

if you want to check using Settings:

```<code>private boolean checkIfLocationOpened() {
    String provider = Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if (provider.contains("gps") || provider.contains("network"))
        return true;
    }
    // otherwise return false
    return false;
}
</code>```

and if you want to do it using the LocationManager:

```<code>private boolean checkIfLocationOpened() {
    final LocationManager manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) || manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
        return true;
    }
    // otherwise return false
    return false;
}
</code>```

You can find the complete details at my answer here.

Body:
we have implemented a geobased app for Android, so we need to ensure GPS is enabled all the time. The problem is that

manager.isProviderEnabled( LocationManager.GPS_PROVIDER )

is always returning false even if the GPS Provider is enabled, so our app is always showing the alert to change the GPS status or it is not working.

Do you know what is happening?

We are testing it with a Samsung Galaxy S and a HTC Wildfire device...
Thanks in advance.

Body:
Sometimes your device settings is set to get the location using WiFi Networks not GPS system, so that the location would be opened but your app will return false when checking for the GPS_PROVIDER.

The proper solution to that is to check for both, GPS & Network:

if you want to check using Settings:

private boolean checkIfLocationOpened() {
    String provider = Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if (provider.contains("gps") || provider.contains("network"))
        return true;
    }
    // otherwise return false
    return false;
}

and if you want to do it using the LocationManager:

private boolean checkIfLocationOpened() {
    final LocationManager manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) || manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
        return true;
    }
    // otherwise return false
    return false;
}

You can find the complete details at my answer here.


问:
Set focus on input text where ID not defined
I want to set focus each time on the textbox if alert message is prompted. How should I deal where I use that javascript function for multiple times. Here is my js code

```<code>function validateLandline(landfield) {
        var reg = /\d{5}([- ]*)\d{6}/;
        if (reg.test(landfield.value) == false) {
            jAlert('Kindly enter valid landline no', 'INFORMATION');
            return false;
            landfield.focus();
        }
        return true;
    }
</code>```

and textbox html

```<code><input type="text" id="txtStoreSiteL1" onchange="validateLandline(this);" maxlength="20" />
</code>```

答:
Based on the comments, I have created a small snippet below:

function validateEmail($email) {
  var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
  return emailReg.test($email);
}

$('input').on('input focusout', function() {
  $(this).removeClass('error');
  if (!validateEmail($(this).val())) {
    $(this).addClass('error').focus();
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.error {
  border: 2px solid #d00;
}</code>```

<input type="text" id="txtStoreSiteL1" maxlength="20" />
<input type="text" id="txtStoreSiteL2" maxlength="20" />```

Body:
I want to set focus each time on the textbox if alert message is prompted. How should I deal where I use that javascript function for multiple times. Here is my js code

function validateLandline(landfield) {
        var reg = /\d{5}([- ]*)\d{6}/;
        if (reg.test(landfield.value) == false) {
            jAlert('Kindly enter valid landline no', 'INFORMATION');
            return false;
            landfield.focus();
        }
        return true;
    }

and textbox html

<input type="text" id="txtStoreSiteL1" onchange="validateLandline(this);" maxlength="20" />

Body:
Based on the comments, I have created a small snippet below:

function validateEmail($email) {
  var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
  return emailReg.test($email);
}

$('input').on('input focusout', function() {
  $(this).removeClass('error');
  if (!validateEmail($(this).val())) {
    $(this).addClass('error').focus();
  }
});

.error {
  border: 2px solid #d00;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtStoreSiteL1" maxlength="20" />
<input type="text" id="txtStoreSiteL2" maxlength="20" />


问:
Django: How can I select objects with the same field values?
For example, I have a model like this:

```<code>Class Doggy(models.Model):
    name = models.CharField(u'Name', max_length = 40)
    color = models.CharField(u'Color', max_length = 20)
</code>```

How can i select doggies with the same color? Or with the same name :)

UPD. Of course, I don't know the name or the color. I want to.. kind of, group by their values.

UPD2. I'm trying to do something like that, but using Django:

```<code>SELECT *
FROM table
WHERE tablefield IN (
 SELECT tablefield
 FROM table
 GROUP BY tablefield
 HAVING (COUNT(tablefield ) > 1)
)
</code>```

UPD3. I'd like to do it via Django ORM, without having to iterate over the objects. I just want to get rows with duplicate values for one particular field.

答:
You can use itertools.groupby() for this:

```<code>import operator
import itertools
from django.db import models

def group_model_by_attr(model_class, attr_name):
    assert issubclass(model_class, models.Model), \
        "%s is not a Django model." % (model_class,)
    assert attr_name in [field.name for field in Event._meta.fields], \
        "The %s field doesn't exist on model %s" % (attr_name, model_class)

    all_instances = model_class.objects.all().order_by(attr_name)
    keyfunc = operator.attrgetter(attr_name)
    return [{k: list(g)} for k, g in itertools.groupby(all_instances, keyfunc)]

grouped_by_color = group_model_by_attr(Doggy, 'color')
grouped_by_name = group_model_by_attr(Doggy, 'name')
</code>```

grouped_by_color (for example) will be a list of dicts like [{'purple': [doggy1, doggy2], {'pink': [doggy3,]}] where doggy1,2, etc. are Doggy instances.

UPDATE:

From your update it looks like you just want a list of ids for each event type.  I tested this with 250k records in postgresql on my ubuntu laptop w/ a core 2 duo & 3gb of ram, and it took .35 seconds (the itertools.group_by took .72 seconds btw) to generate the dict. You mention that you have 900K records, so this should be fast enough.  If it's not it should be easy to cache/update as the records change.

```<code>from collections import defaultdict

doggies = Doggy.objects.values_list('color', 'id').order_by('color').iterator()
grouped_doggies_by_color = defaultdict(list)
for color, id in doggies:
    grouped_doggies_by_color[color].append(id)
</code>```

Body:
For example, I have a model like this:

Class Doggy(models.Model):
    name = models.CharField(u'Name', max_length = 40)
    color = models.CharField(u'Color', max_length = 20)

How can i select doggies with the same color? Or with the same name :)

UPD. Of course, I don't know the name or the color. I want to.. kind of, group by their values.

UPD2. I'm trying to do something like that, but using Django:

SELECT *
FROM table
WHERE tablefield IN (
 SELECT tablefield
 FROM table
 GROUP BY tablefield
 HAVING (COUNT(tablefield ) > 1)
)

UPD3. I'd like to do it via Django ORM, without having to iterate over the objects. I just want to get rows with duplicate values for one particular field.

Body:
You can use itertools.groupby() for this:

import operator
import itertools
from django.db import models

def group_model_by_attr(model_class, attr_name):
    assert issubclass(model_class, models.Model), \
        "%s is not a Django model." % (model_class,)
    assert attr_name in [field.name for field in Event._meta.fields], \
        "The %s field doesn't exist on model %s" % (attr_name, model_class)

    all_instances = model_class.objects.all().order_by(attr_name)
    keyfunc = operator.attrgetter(attr_name)
    return [{k: list(g)} for k, g in itertools.groupby(all_instances, keyfunc)]

grouped_by_color = group_model_by_attr(Doggy, 'color')
grouped_by_name = group_model_by_attr(Doggy, 'name')

grouped_by_color (for example) will be a list of dicts like [{'purple': [doggy1, doggy2], {'pink': [doggy3,]}] where doggy1,2, etc. are Doggy instances.

UPDATE:

From your update it looks like you just want a list of ids for each event type.  I tested this with 250k records in postgresql on my ubuntu laptop w/ a core 2 duo & 3gb of ram, and it took .35 seconds (the itertools.group_by took .72 seconds btw) to generate the dict. You mention that you have 900K records, so this should be fast enough.  If it's not it should be easy to cache/update as the records change.

from collections import defaultdict

doggies = Doggy.objects.values_list('color', 'id').order_by('color').iterator()
grouped_doggies_by_color = defaultdict(list)
for color, id in doggies:
    grouped_doggies_by_color[color].append(id)


问:
Applescript to capture window
I am trying to create an applescript to capture a window. The keyboard shortcut is cmd+shift+4 then space. I am not able to use this in applescript.

My code :

```<code>tell application "system events"
keystroke "21, 49" using {command down, shift down}
end tell
</code>```

It doesnt work. The problem with the scrip it using space bar. I need to hold cmd, shift & 4 and then press space bar.

答:
If all you want is to get to that point then use this:

tell application "System Events"

    key code 21 using {shift down, command down}

    delay 0.1

    key code 49

end tell

Title: Applescript to capture window

Body:
I am trying to create an applescript to capture a window. The keyboard shortcut is cmd+shift+4 then space. I am not able to use this in applescript.

My code :

tell application "system events"
keystroke "21, 49" using {command down, shift down}
end tell

It doesnt work. The problem with the scrip it using space bar. I need to hold cmd, shift & 4 and then press space bar.


问:
Finite loop in Go routine
I am trying to execute two or more go routine synchronously after finish the topic

goroutines order of execution

And I write some code to test the go routines' behaviour
(I treat it like a queue, BTW the go concurrency tutorial page not really help me)

```<code>package main

import (
        "fmt"
        "sync"
)

const size = 10
var vChan chan int = make(chan int, size)

func justSend(wg *sync.WaitGroup) {
        defer wg.Done()
        for i := 1; i <= 10; i++ {
                vChan <- i
        }
}

func justPrint(wg *sync.WaitGroup) {
        defer wg.Done()
        v := <- vChan
        fmt.Printf("%4d ", v);
}

func main() {
        wg := new(sync.WaitGroup)

        go func() {
                wg.Add(1)
                go justSend(wg)
                wg.Wait()
                wg.Add(size)
                go justPrint(wg)
                wg.Wait()
                close(vChan)
        }()
}
</code>```

But it print nothing, should we design a go routine always have a infinite loop in there or we can't get it work properly?

(The piece of code is prepared for my real problem on building multiple websocket connection and testing our API server's response, so...I think passing bunch of channel which has same type between different function is quite annoying, so I set it globally)

答: You have put goroutine in main and main function finishes before your go routine finishes. So either do not use goroutine in main or use some kind of boolean receiving channel at the end of main which gets true when goroutine completed.

Title: Finite loop in Go routine

Body:
I am trying to execute two or more go routine synchronously after finish the topic

goroutines order of execution

And I write some code to test the go routines' behaviour
(I treat it like a queue, BTW the go concurrency tutorial page not really help me)

package main

import (
        "fmt"
        "sync"
)

const size = 10
var vChan chan int = make(chan int, size)

func justSend(wg *sync.WaitGroup) {
        defer wg.Done()
        for i := 1; i <= 10; i++ {
                vChan <- i
        }
}

func justPrint(wg *sync.WaitGroup) {
        defer wg.Done()
        v := <- vChan
        fmt.Printf("%4d ", v);
}

func main() {
        wg := new(sync.WaitGroup)

        go func() {
                wg.Add(1)
                go justSend(wg)
                wg.Wait()
                wg.Add(size)
                go justPrint(wg)
                wg.Wait()
                close(vChan)
        }()
}

But it print nothing, should we design a go routine always have a infinite loop in there or we can't get it work properly?

(The piece of code is prepared for my real problem on building multiple websocket connection and testing our API server's response, so...I think passing bunch of channel which has same type between different function is quite annoying, so I set it globally)


问:
How to remove current Event Listener before adding new one
How do I remove current EventListener before adding new one to it? I have below code does a simple countdown:

```<code>var myTimer:Timer = new Timer(1000);
function countDown(dateToProcess):void
            {
               myTimer.addEventListener(TimerEvent.TIMER, countdownTimer);
               myTimer.start();

                function countdownTimer(e:Event):void
                {
                   //display dateToProcess.getTime() - today.getTime();
                   trace(myTimer.currentCounter);
                }

            }
</code>```

function countDown is called every X seconds and new datetoProcess value will be passed. However, every time when this function is called, a new TimerEvent.TIMER EventListener is added because the code told it to, is there anyway to remove the current Event Listener before adding new one?

I've tried:

```<code> if (myTimer.hasEventListener(TimerEvent.TIMER))
                        {
                            myTimer.stop();
                            myTimer.removeEventListener(TimerEvent.TIMER, countdown);

                            trace("remove");
                        }
</code>```

but doesn't seem to be working, it is still adding event Listener, I used trace(myTimer.currentcounter) and output like:
1
2
2
3
3
3
4
4
4
4
Anyone can help with this one please?

答:
Still not sure what you're after for, but here's one shot using the same Timer:

```<code>var myTimer:Timer = new Timer(1000,0);

function countDown(dateToProcess):void{
    myTimer.addEventListener(TimerEvent.TIMER, countdownTimer);
    myTimer.start();
}

function countdownTimer(e:TimerEvent):void{
    myTimer.stop();
    myTimer.removeEventListener(TimerEvent.TIMER, countdownTimer);
    trace(myTimer.currentCount);
}
</code>```

Or:

```<code>function countDown(dateToProcess):void{
    if(myTimer.hasEventListener(TimerEvent.TIMER)){
        myTimer.stop();
        myTimer.removeEventListener(TimerEvent.TIMER, countdownTimer);
    }
    myTimer.addEventListener(TimerEvent.TIMER, countdownTimer);
    myTimer.start();
}

function countdownTimer(e:TimerEvent):void{
    trace(myTimer.currentCount);
}
</code>```

So it works as you thought it would, you probably just had something in wrong place?

Body:
How do I remove current EventListener before adding new one to it? I have below code does a simple countdown:

var myTimer:Timer = new Timer(1000);
function countDown(dateToProcess):void
            {
               myTimer.addEventListener(TimerEvent.TIMER, countdownTimer);
               myTimer.start();

                function countdownTimer(e:Event):void
                {
                   //display dateToProcess.getTime() - today.getTime();
                   trace(myTimer.currentCounter);
                }

            }

function countDown is called every X seconds and new datetoProcess value will be passed. However, every time when this function is called, a new TimerEvent.TIMER EventListener is added because the code told it to, is there anyway to remove the current Event Listener before adding new one?

I've tried:

 if (myTimer.hasEventListener(TimerEvent.TIMER))
                        {
                            myTimer.stop();
                            myTimer.removeEventListener(TimerEvent.TIMER, countdown);

                            trace("remove");
                        }

but doesn't seem to be working, it is still adding event Listener, I used trace(myTimer.currentcounter) and output like:
1
2
2
3
3
3
4
4
4
4
Anyone can help with this one please?

Body:
Still not sure what you're after for, but here's one shot using the same Timer:

var myTimer:Timer = new Timer(1000,0);

function countDown(dateToProcess):void{
    myTimer.addEventListener(TimerEvent.TIMER, countdownTimer);
    myTimer.start();
}

function countdownTimer(e:TimerEvent):void{
    myTimer.stop();
    myTimer.removeEventListener(TimerEvent.TIMER, countdownTimer);
    trace(myTimer.currentCount);
}

Or:

function countDown(dateToProcess):void{
    if(myTimer.hasEventListener(TimerEvent.TIMER)){
        myTimer.stop();
        myTimer.removeEventListener(TimerEvent.TIMER, countdownTimer);
    }
    myTimer.addEventListener(TimerEvent.TIMER, countdownTimer);
    myTimer.start();
}

function countdownTimer(e:TimerEvent):void{
    trace(myTimer.currentCount);
}

So it works as you thought it would, you probably just had something in wrong place?


问:
Change Order on X-Axis for Matplotlib chart
I created a chart in matplotlib using python and the x-axis is the days of the week (Mon-Sun). When the data was plotted though, the x-axis is not arranged Mon-Sun.

Is there  way I can re-order the x-axis to have it be formatted this way?

or is there a way I can re-order the dataset? It is a csv file that is being read using the panda dataframe

Example Data: (lives in csv: './data/Days_Summary.csv')

```<code>Day         Value

 Monday      56
 Tuesday     23
 Wednesday   34
 Thursday     56
  Friday      58
 Saturday     70
  Sunday      43
</code>```

Code:

```<code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df=pd.read_csv('./data/Days_Summary.csv')
days_values=df.groupby(['day'])['day'].count().plot(kind='bar')
plt.xlabel('Day')
plt.ylabel('Values')
plt.show()
</code>```

答:
Use .loc to set the day order:

```<code>field = "Day"
day_order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
ax = df.set_index(field).loc[day_order].plot(kind="bar", legend=False)
ax.set_ylabel("Value")
</code>```

Note: Using groupby() and count() will not give you the values in the Value field, but will instead count the number of rows in each group.  In this case, you'll just get a count of 1 for each day. Hence this answer assumes that
you actually want to plot the values in Value for each day.

Body:
I created a chart in matplotlib using python and the x-axis is the days of the week (Mon-Sun). When the data was plotted though, the x-axis is not arranged Mon-Sun.

Is there  way I can re-order the x-axis to have it be formatted this way?

or is there a way I can re-order the dataset? It is a csv file that is being read using the panda dataframe

Example Data: (lives in csv: './data/Days_Summary.csv')

Day         Value

 Monday      56
 Tuesday     23
 Wednesday   34
 Thursday     56
  Friday      58
 Saturday     70
  Sunday      43

Code:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df=pd.read_csv('./data/Days_Summary.csv')
days_values=df.groupby(['day'])['day'].count().plot(kind='bar')
plt.xlabel('Day')
plt.ylabel('Values')
plt.show()

Body:
Use .loc to set the day order:

field = "Day"
day_order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
ax = df.set_index(field).loc[day_order].plot(kind="bar", legend=False)
ax.set_ylabel("Value")

Note: Using groupby() and count() will not give you the values in the Value field, but will instead count the number of rows in each group.  In this case, you'll just get a count of 1 for each day. Hence this answer assumes that
you actually want to plot the values in Value for each day.


问:
Get row which matched in each group
I am trying to make a sql query. I got some results from 2 tables below. Below results are good for me. Now I want those values which is present in each group. for example, A and B is present in each group(in each ID). so i want only A and B in result. and also i want make my query dynamic. Could anyone help?</p>

```<code>| ID | Value |
|----|-------|
|  1 |     A |
|  1 |     B |
|  1 |     C |
|  1 |     D |
|  2 |     A |
|  2 |     B |
|  2 |     C |
|  3 |     A |
|  3 |     B |
</code>```

答:
In the following query, I have placed your current query into a CTE for further use.  We can try selecting those values for which every ID in your current result appears.  This would imply that such values are associated with every ID.

```<code>WITH cte AS (
    -- your current query
)

SELECT Value
FROM cte
GROUP BY Value
HAVING COUNT(DISTINCT ID) = (SELECT COUNT(DISTINCT ID) FROM cte);
</code>```

Demo

Title: Get row which matched in each group

Body:
I am trying to make a sql query. I got some results from 2 tables below. Below results are good for me. Now I want those values which is present in each group. for example, A and B is present in each group(in each ID). so i want only A and B in result. and also i want make my query dynamic. Could anyone help?

| ID | Value |
|----|-------|
|  1 |     A |
|  1 |     B |
|  1 |     C |
|  1 |     D |
|  2 |     A |
|  2 |     B |
|  2 |     C |
|  3 |     A |
|  3 |     B |

Body:
In the following query, I have placed your current query into a CTE for further use.  We can try selecting those values for which every ID in your current result appears.  This would imply that such values are associated with every ID.

WITH cte AS (
    -- your current query
)

SELECT Value
FROM cte
GROUP BY Value
HAVING COUNT(DISTINCT ID) = (SELECT COUNT(DISTINCT ID) FROM cte);

Demo


问:
JMeter - can not assign password variable correctly
I set username and password from CSV file user:sysadmin, pass:"Pass@123456" but password is encrypted wrong upon request

```<code>User=sysadmin&Pass=Pass%40123456
</code>```

答:
The fact you see it as Pass@123456 doesn't necessarily mean that JMeter is sending wrong data, it might be either by intention due to string-based request representation in Raw form of request inspection in the View Results Tree listener or by accident (just a bug in it. You can check JMeter Issue Tracker to see whether similar issues were reported already)

In the mean time try switching to the HTTP tab of the View Results Tree listener:

Or double check what you're sending using a sniffer tool like Fiddler or Wireshark

But first of all I would recommend verifying your CSV data via Debug Sampler or temporarily switching to hard-coded (not parameterized) data to see if it resolves your issue.

Body:
I set username and password from CSV file user:sysadmin, pass:"Pass@123456" but password is encrypted wrong upon request

User=sysadmin&Pass=Pass%40123456


问:
react router basic example gives error Cannot resolve module 'history/lib/createBrowserHistory'
following react training documentation to learn basics of react-router but it failed on the very first example. below is my package.json info

```<code>    "dependencies": {
        "history": "^4.7.2",
        "react": "^0.14.7",
        "react-dom": "^0.14.7",
        "react-router": "^2.0.0"
    },
</code>```

and this is  relevant code in index.js file

```<code>    import { Router, Route, hashHistory } from 'react-router'

    render((
      <Router history={hashHistory}>
        <Route path="/" component={App}/>
      </Router>
    ), document.getElementById('app'))
</code>```

npm start outputs webpack: Compiled successfully.

but in broswer page opens with some random junk in URL http://localhost:8080/#/?_k=hrfoj1 and display nothing on browser

after searching the issue, came with other solution suggested that React Router is built on history.

so tried this

```<code>    import { Router, Route, IndexRoute} from 'react-router'

    import createBrowserHistory from 'history/lib/createBrowserHistory'
    const appHistory = createBrowserHistory()

    render((<Router history={appHistory} > ...</Router>),  document.getElementById('app'));
</code>```

but when run npm start  gives the error

Module not found: Error: Cannot resolve module
  'history/lib/createBrowserHistory' in
  /opt/react-router-tutorial/lessons/01-setting-up

so Please tell me what is the right solution

答:
The tutorial you are following is outdated. Basically, there are various types of router components (BrowserRouter, HashRouter, etc.) and they manage their history by themselves.

That is, if you are using react-router-dom. You see, react-router is now a core package which is used by both react-router-dom and react-router-native and you should install one of those (in this case, probably react-router-dom).

You can then change your code like this (assuming that the render function is coming from somewhere, presumably react-dom):

```<code>// notice the different package here
import { BrowserRouter, Route } from 'react-router-dom'

render((
  <BrowserRouter>
    <Route path="/" component={App}/>
  </BrowserRouter>
), document.getElementById('app'))
</code>```

Body:
following react training documentation to learn basics of react-router but it failed on the very first example. below is my package.json info

    "dependencies": {
        "history": "^4.7.2",
        "react": "^0.14.7",
        "react-dom": "^0.14.7",
        "react-router": "^2.0.0"
    },

and this is  relevant code in index.js file

    import { Router, Route, hashHistory } from 'react-router'

    render((
      <Router history={hashHistory}>
        <Route path="/" component={App}/>
      </Router>
    ), document.getElementById('app'))

npm start outputs webpack: Compiled successfully.

but in broswer page opens with some random junk in URL http://localhost:8080/#/?_k=hrfoj1 and display nothing on browser

after searching the issue, came with other solution suggested that React Router is built on history.

so tried this

    import { Router, Route, IndexRoute} from 'react-router'

    import createBrowserHistory from 'history/lib/createBrowserHistory'
    const appHistory = createBrowserHistory()

    render((<Router history={appHistory} > ...</Router>),  document.getElementById('app'));

but when run npm start  gives the error

Module not found: Error: Cannot resolve module
  'history/lib/createBrowserHistory' in
  /opt/react-router-tutorial/lessons/01-setting-up

so Please tell me what is the right solution

Body:
The tutorial you are following is outdated. Basically, there are various types of router components (BrowserRouter, HashRouter, etc.) and they manage their history by themselves.

That is, if you are using react-router-dom. You see, react-router is now a core package which is used by both react-router-dom and react-router-native and you should install one of those (in this case, probably react-router-dom).

You can then change your code like this (assuming that the render function is coming from somewhere, presumably react-dom):

// notice the different package here
import { BrowserRouter, Route } from 'react-router-dom'

render((
  <BrowserRouter>
    <Route path="/" component={App}/>
  </BrowserRouter>
), document.getElementById('app'))


问:
Differentiation between rectangle and square in image using opencv2 python
I'm learning how to recognize shapes that're within image provided. I'm able to recognize shape by number of edges present to the geometrical body. But now I'm wondering is there any way to differentiate between square and rectangle within image?
Here's my code. Currently I'm just drawing contours to the geometrical figures.

```<code>import cv2

raw_image = cv2.imread('test1.png')
cv2.imshow('Original Image', raw_image)
cv2.waitKey(0)

bilateral_filtered_image = cv2.bilateralFilter(raw_image, 5, 175, 175)
cv2.imshow('Bilateral', bilateral_filtered_image)
cv2.waitKey(0)

edge_detected_image = cv2.Canny(bilateral_filtered_image, 75, 200)
cv2.imshow('Edge', edge_detected_image)
cv2.waitKey(0)

_, contours, hierarchy = cv2.findContours(edge_detected_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

contour_list = []
for contour in contours:
    approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)
    area = cv2.contourArea(contour)
    if ((len(approx) >= 3)):
        contour_list.append(contour)

cv2.drawContours(raw_image, contour_list,  -1, (0,0,0), 2)
cv2.imshow('Objects Detected',raw_image)
cv2.waitKey(0)
</code>```

答:
The difference between a rectangle and a square is that a square has 4 equal sides making it a special rectangle. I learned this in kindergarden.

There are countless ways of identifying a square.

Its circumference always equals sqrt(area) hence its circularity is always 0.0625

The distance between all corners is either a or a
* sqrt(2)

The centroid has the same distance a / 2 to all 4 sides

...

You name it.

Body:
I'm learning how to recognize shapes that're within image provided. I'm able to recognize shape by number of edges present to the geometrical body. But now I'm wondering is there any way to differentiate between square and rectangle within image?
Here's my code. Currently I'm just drawing contours to the geometrical figures.

import cv2

raw_image = cv2.imread('test1.png')
cv2.imshow('Original Image', raw_image)
cv2.waitKey(0)

bilateral_filtered_image = cv2.bilateralFilter(raw_image, 5, 175, 175)
cv2.imshow('Bilateral', bilateral_filtered_image)
cv2.waitKey(0)

edge_detected_image = cv2.Canny(bilateral_filtered_image, 75, 200)
cv2.imshow('Edge', edge_detected_image)
cv2.waitKey(0)

_, contours, hierarchy = cv2.findContours(edge_detected_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

contour_list = []
for contour in contours:
    approx = cv2.approxPolyDP(contour,0.01*cv2.arcLength(contour,True),True)
    area = cv2.contourArea(contour)
    if ((len(approx) >= 3)):
        contour_list.append(contour)

cv2.drawContours(raw_image, contour_list,  -1, (0,0,0), 2)
cv2.imshow('Objects Detected',raw_image)
cv2.waitKey(0)


问:
How to perform feed forward propagation in CNN using Keras?
I want to perform feed forward propagation on CNN using Keras. I am trying to train CNN using my own optimizer, which I can't fit in the optimiser file of Keras. My optimiser in gradient free. I don't want any inbuilt to be used.</p>

答:
I found answer to this question. We just have to make model non trainable.</p>

```<code>import numpy as np
import keras

x = keras.layers.Input(shape=(3,))
y = keras.layers.Dense(5)(x)

model = keras.models.Model(x, y)
model.trainable = False
model.compile(optimizer='rmsprop', loss='mse')

x = np.random.random((10, 3))
y = np.random.random((10, 5))
model.fit(x, y, epochs=10)
</code>```

Body:
I found answer to this question. We just have to make model non trainable.

import numpy as np
import keras

x = keras.layers.Input(shape=(3,))
y = keras.layers.Dense(5)(x)

model = keras.models.Model(x, y)
model.trainable = False
model.compile(optimizer='rmsprop', loss='mse')

x = np.random.random((10, 3))
y = np.random.random((10, 5))
model.fit(x, y, epochs=10)


答:
Use This </p>

```<code>WITH CTE
AS
(
    SELECT
      Value,
  Cnt = COUNT(DISTINCT ID)
  FROM T1
  GROUP BY Value
)
SELECT
Value
FROM CTE
WHERE Cnt = (SELECT COUNT(DISTINCT ID) FROM T1)
</code>```

Title: Get row which matched in each group

Body:
Use This

WITH CTE
AS
(
    SELECT
      Value,
  Cnt = COUNT(DISTINCT ID)
  FROM T1
  GROUP BY Value
)
SELECT
Value
FROM CTE
WHERE Cnt = (SELECT COUNT(DISTINCT ID) FROM T1)


问:
angular-leaflet : draw control: GeoJSON of Circle and Point are same. How to differentiate?
I suppose to save the drawn shapes and on-demand it should load into the map. When I draw point and circle it gives same geoJSON. Type of both the shapes are point. I can't able to differentiate the difference. When I load the circle geoJSON to the map, it is loading as point.

demo

Checkout the console log from the screenshot.

Is't a bug or I'm doing something wrong?
Please advice.

答: GeoJSON doesn't support circles. It's doing the best it can with the point. I got around it by storing the radius as a property of the feature</p>


问:
Return excel file response in ASP.NET MVC
I am building a FileResult method which is supposed to return an excel file as a result.
Currently the method looks like this:

```<code>public ActionResult GetExcelFile(int id)
    {
        var entityPermission = AuthenticationManager.GetEntityPermission(PermissionEntity.Events, PermissionLevel.AllRecords);
        if (entityPermission == null || !entityPermission.AllowRead)
            return Json(new RequestResult(RequestCode.Unauthorized), JsonRequestBehavior.AllowGet);

        try
        {
            using (var serviceManager = new ServiceManager())
            {
                // Get object model
                var firstTableObj = serviceManager.GetDataForExcel(id);
                StringBuilder sb = new StringBuilder();
                sb.Append("<table border=`" + "1px" + "`b>");
                sb.Append("<tr>");
                // ... appending other strings and data
                sb.Append("</table>");

                // Return FileResult
                byte[] byteArray = Encoding.UTF8.GetBytes(sb.ToString());
                return File(new MemoryStream(byteArray, 0, byteArray.Length), "application/octet-stream", $"{firstTableObj.CurrentDate}.xlsx");
            }
        }
        catch (Exception ex)
        {
            return Json(new RequestResult(RequestCode.Server_Failure, ex.Message), JsonRequestBehavior.AllowGet);
        }
</code>```

Currently, when I send a request from Angular 2+ frontend, the request is being processed and returned, this is some of the header data:

```<code>Content-Disposition:attachment; filename=12.11.2017.xlsx, Content-Length:617, Content-Type:application/octet-stream
</code>```

However, the file is not being downloaded, the response body is just the html template in string format. What am I missing? I have seen some examples of returning excel files as a FileResult in MVC and they are not much different from mine. Changing the MIME to 'application/vnd.ms-excel' didn't help either. Also, as far as I am aware, there is no need to implement any file download logic in the client, it should work as is, that is a response from the server.
Will appreciate any hints on the subject.

P.S: I know that in general I should not load an entire file into memory, but this is currently for testing purposes (I know an approximate limit to returned file sizes) and will most surely be changed in the future development.

答:
You are not saving an xlsx file. You are saving an html file with xlsx extension.

You probably adjusted a sample found on the internet, but the initial extension was xls.

An html file with xls extension is not an Excel file either, but MS Excel knows to render the html file and displays the file into the spreadsheet. Still, with the recently MS Excel version a warning is raised that is an invalid file format.

If you need to save xlsx files, you need to search for an Excel library like OpenXML from Microsoft, EPPlus open source or EasyXLS commercial with 30-days trial.

Body:
I am building a FileResult method which is supposed to return an excel file as a result.
Currently the method looks like this:

public ActionResult GetExcelFile(int id)
    {
        var entityPermission = AuthenticationManager.GetEntityPermission(PermissionEntity.Events, PermissionLevel.AllRecords);
        if (entityPermission == null || !entityPermission.AllowRead)
            return Json(new RequestResult(RequestCode.Unauthorized), JsonRequestBehavior.AllowGet);

        try
        {
            using (var serviceManager = new ServiceManager())
            {
                // Get object model
                var firstTableObj = serviceManager.GetDataForExcel(id);
                StringBuilder sb = new StringBuilder();
                sb.Append("<table border=`" + "1px" + "`b>");
                sb.Append("
");
                // ... appending other strings and data
                sb.Append("
");

                // Return FileResult
                byte[] byteArray = Encoding.UTF8.GetBytes(sb.ToString());
                return File(new MemoryStream(byteArray, 0, byteArray.Length), "application/octet-stream", $"{firstTableObj.CurrentDate}.xlsx");
            }
        }
        catch (Exception ex)
        {
            return Json(new RequestResult(RequestCode.Server_Failure, ex.Message), JsonRequestBehavior.AllowGet);
        }

Currently, when I send a request from Angular 2+ frontend, the request is being processed and returned, this is some of the header data:

Content-Disposition:attachment; filename=12.11.2017.xlsx, Content-Length:617, Content-Type:application/octet-stream

However, the file is not being downloaded, the response body is just the html template in string format. What am I missing? I have seen some examples of returning excel files as a FileResult in MVC and they are not much different from mine. Changing the MIME to 'application/vnd.ms-excel' didn't help either. Also, as far as I am aware, there is no need to implement any file download logic in the client, it should work as is, that is a response from the server.
Will appreciate any hints on the subject.

P.S: I know that in general I should not load an entire file into memory, but this is currently for testing purposes (I know an approximate limit to returned file sizes) and will most surely be changed in the future development.


问:
How to get list of all music files from android phone
I created an app that scans music files on the mobile phone. It scans the music files if I scan the folder /sdcard/Music but it doesn't scan the mp3 file when I write /sdcard. It is working fine. But it is not working on some devices, the application crashes maybe because of that path not present on that phone what should I do?

CODE

```<code>public class SongsManager {

// SDCard Path
  String MEDIA_PATH = new String("/sdcard/Music");
 private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

// Constructor
public SongsManager() {

}

/**
 * Function to read all mp3 files from sdcard
 * and store the details in ArrayList
 */ public ArrayList<HashMap<String, String>> getPlayList(){
       File home = new File(MEDIA_PATH);

    if (home.listFiles(new FileExtensionFilter()).length > 0) {
        for (File file : home.listFiles(new FileExtensionFilter())) {
            HashMap<String, String> song = new HashMap<String, String>();
            song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
            song.put("songPath", file.getPath());
            // Adding each song to SongList
            songsList.add(song);
        }
    }
    // return songs list array
    return songsList;
}

class FileExtensionFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
        return (name.endsWith(".mp3") || name.endsWith(".MP3"));
    }
}
</code>```

}

答:
//Retrieve a list of Music files currently listed in the Media store DB via URI.

//Some audio may be explicitly marked as not being music

```<code>String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

String[] projection = {
    MediaStore.Audio.Media._ID,
    MediaStore.Audio.Media.ARTIST,
    MediaStore.Audio.Media.TITLE,
    MediaStore.Audio.Media.DATA,
    MediaStore.Audio.Media.DISPLAY_NAME,
    MediaStore.Audio.Media.DURATION
};

cursor = this.managedQuery(
    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
    projection,
    selection,
    null,
    null);

private List<String> songs = new ArrayList<String>();
while(cursor.moveToNext()){
    songs.add(cursor.getString(0) + "||" + cursor.getString(1) + "||" +   cursor.getString(2) + "||" +   cursor.getString(3) + "||" +  cursor.getString(4) + "||" +  cursor.getString(5));
}
</code>```

Body:
I created an app that scans music files on the mobile phone. It scans the music files if I scan the folder /sdcard/Music but it doesn't scan the mp3 file when I write /sdcard. It is working fine. But it is not working on some devices, the application crashes maybe because of that path not present on that phone what should I do?

CODE

public class SongsManager {

// SDCard Path
  String MEDIA_PATH = new String("/sdcard/Music");
 private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

// Constructor
public SongsManager() {

}

/**
 * Function to read all mp3 files from sdcard
 * and store the details in ArrayList
 */ public ArrayList<HashMap<String, String>> getPlayList(){
       File home = new File(MEDIA_PATH);

    if (home.listFiles(new FileExtensionFilter()).length > 0) {
        for (File file : home.listFiles(new FileExtensionFilter())) {
            HashMap<String, String> song = new HashMap<String, String>();
            song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
            song.put("songPath", file.getPath());
            // Adding each song to SongList
            songsList.add(song);
        }
    }
    // return songs list array
    return songsList;
}

class FileExtensionFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
        return (name.endsWith(".mp3") || name.endsWith(".MP3"));
    }
}

}

Body:
//Retrieve a list of Music files currently listed in the Media store DB via URI.

//Some audio may be explicitly marked as not being music

String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

String[] projection = {
    MediaStore.Audio.Media._ID,
    MediaStore.Audio.Media.ARTIST,
    MediaStore.Audio.Media.TITLE,
    MediaStore.Audio.Media.DATA,
    MediaStore.Audio.Media.DISPLAY_NAME,
    MediaStore.Audio.Media.DURATION
};

cursor = this.managedQuery(
    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
    projection,
    selection,
    null,
    null);

private List<String> songs = new ArrayList<String>();
while(cursor.moveToNext()){
    songs.add(cursor.getString(0) + "||" + cursor.getString(1) + "||" +   cursor.getString(2) + "||" +   cursor.getString(3) + "||" +  cursor.getString(4) + "||" +  cursor.getString(5));
}


问:
Fortran derived datatype used before defined
How to include the derived datatype (the type, not variable) between modules with use module, ONLY: statement?

More description: In my module1 I defined a derived datatype (let's call it my_datatype) and some data (let's call it my_data) of this datatype. In my module2 I need to use my_data. Since my module1 contains many procedures that module2 does not need, I want to use the ONLY statement to only include my_data. However, without including the datatype it will give me the error:

```<code>Derive datatype 'my_type' is used before defined at "type(my_type),intent(out)::A"
</code>```

It is obvious that module2 does not recognize my_datatype defined in module1 because I did not pass it. But what is the syntax to include a derived type in 'use module, only' statement? I am using Fortran 2003.

```<code>  module step1
  implicit none
     type my_type
        integer::id
        integer,dimension(2)::my_data
     end type my_type

     type(my_type)::A
  end module step1

  module step2
  use step1,only:A
  implicit none
  contains
     subroutine change_A(A)
        type(my_type),intent(inout)::A
        A%id = 1
        A%my_data(1) = 1
        A%my_data(2) = 2
     end subroutine change_A
  end module step2

  program test
  ! program is in a different folder
  use step1
  use step2
     implicit none
     call change_A(A)
  end program test
</code>```

答:
However, it is giving me error "derived datatype is used before it is defined". It looks like module2 does not recognize my_datatype defined in module1.

Well, yeah. Of course module2 does not recognize your datatype, because it's defined in module1 and in your 'use'-statement you say you only want to use the variable my_data. Simply include the datatype in the 'use'-statement, and it will be known in module2

Body:
How to include the derived datatype (the type, not variable) between modules with use module, ONLY: statement?

More description: In my module1 I defined a derived datatype (let's call it my_datatype) and some data (let's call it my_data) of this datatype. In my module2 I need to use my_data. Since my module1 contains many procedures that module2 does not need, I want to use the ONLY statement to only include my_data. However, without including the datatype it will give me the error:

Derive datatype 'my_type' is used before defined at "type(my_type),intent(out)::A"

It is obvious that module2 does not recognize my_datatype defined in module1 because I did not pass it. But what is the syntax to include a derived type in 'use module, only' statement? I am using Fortran 2003.

  module step1
  implicit none
     type my_type
        integer::id
        integer,dimension(2)::my_data
     end type my_type

     type(my_type)::A
  end module step1

  module step2
  use step1,only:A
  implicit none
  contains
     subroutine change_A(A)
        type(my_type),intent(inout)::A
        A%id = 1
        A%my_data(1) = 1
        A%my_data(2) = 2
     end subroutine change_A
  end module step2

  program test
  ! program is in a different folder
  use step1
  use step2
     implicit none
     call change_A(A)
  end program test


问:
PHP Parse URL - Domain returned as path when protocol prefix not present
I am trying to parse URL's in PHP where the input could be any of the following:

Code:

```<code>$info = parse_url('http://www.domainname.com/');
print_r($info);

$info = parse_url('www.domain.com');
print_r($info);

$info = parse_url('/test/');
print_r($info);

$info = parse_url('test.php');
print_r($info);
</code>```

Returns:

```<code>Array
(
    [scheme] => http
    [host] => www.domainname.com
    [path] => /
)
Array
(
    [path] => www.domain.com
)
Array
(
    [path] => /test/
)
Array
(
    [path] => test.php
)
</code>```

The problem you can see is the second example where the domain is returned as a path.

答:
To handle a URL in a way that preserves that it is was a schema-less URL, whilst also allowing a domain to be identified, use the following code.

```<code>if (!preg_match('/^([a-z][a-z0-9\-\.\+]*:)|(\/)/', $url)) {
    $url = '//' . $url;
}
</code>```

So this will apply "//" to beginning of the URL only if the URL does not have a valid scheme and does not begin with "/".

Some quick background on this:

The parser assumes (valid) characters before ":" is the schema, whilst characters following "//" is the domain.  To indicate the URL has both a scheme and domain, the two markers must be used consecutively, "://". For example

[scheme]:[path//path]

//[domain][/path]

[scheme]://[domain][/path]

[/path]

[path]

This is how PHP parses URLs with parse_url() but I couldn't say if it's to standard.

The rules for a valid scheme name is: alpha *( alpha | digit | "+" | "-" | "." )

Body:
I am trying to parse URL's in PHP where the input could be any of the following:

Code:

$info = parse_url('http://www.domainname.com/');
print_r($info);

$info = parse_url('www.domain.com');
print_r($info);

$info = parse_url('/test/');
print_r($info);

$info = parse_url('test.php');
print_r($info);

Returns:

Array
(
    [scheme] => http
    [host] => www.domainname.com
    [path] => /
)
Array
(
    [path] => www.domain.com
)
Array
(
    [path] => /test/
)
Array
(
    [path] => test.php
)

The problem you can see is the second example where the domain is returned as a path.

Body:
To handle a URL in a way that preserves that it is was a schema-less URL, whilst also allowing a domain to be identified, use the following code.

if (!preg_match('/^([a-z][a-z0-9\-\.\+]*:)|(\/)/', $url)) {
    $url = '//' . $url;
}

So this will apply "//" to beginning of the URL only if the URL does not have a valid scheme and does not begin with "/".

Some quick background on this:

The parser assumes (valid) characters before ":" is the schema, whilst characters following "//" is the domain.  To indicate the URL has both a scheme and domain, the two markers must be used consecutively, "://". For example

[scheme]:[path//path]

//[domain][/path]

[scheme]://[domain][/path]

[/path]

[path]

This is how PHP parses URLs with parse_url() but I couldn't say if it's to standard.

The rules for a valid scheme name is: alpha *( alpha | digit | "+" | "-" | "." )