问:
I want to remove redundant code and move in to a separate Jquery function
Here is the code I am trying to remove the redundant code and move the code to separate function.

```<code>        //Adding Infotypes to filter and checks whether any infotype option is selected
        if(this.$infoOptions.val() != null){
          var infotypelength = this.$infoOptions.val().length;
          var l=0,j;
          //Condition to check empty input type
          if( infotypelength > 0){
              var infotypeList = this.$infoOptions.val();
              for(j = 0; j < infotypelength; j++) {
                //It checks whether already option is selected and prevents adding to filter if its duplicate.
                if(($.inArray( $('#infoOptions').select2('data')[j].text, filterList)) == -1 ){
                  this.filter.push($('#infoOptions').select2('data')[j].text);
                  if(infotypeList[j].contains('_subgroup')){
                     var res = infotypeList[j].split("_");
                     this.aSubinfotype[l]=res[0];
                     l=l+1;
                  }
                  else
                   this.aInfotypes.push(infotypeList[j]);
                }
              }
           }
        }

        //Adding Countries to filter
        if(this.$countryOptions.val() != null){
          var geoLength = this.$countryOptions.val().length;
          //Condition to check empty input type
          if( geoLength > 0){
              var geoList = this.$countryOptions.val();
              var l=0;
              for(var j = 0; j < geoLength; j++) {
                if(($.inArray( $('#countryOptions').select2('data')[j].text, filterList)) == -1 ){
                    this.filter.push($('#countryOptions').select2('data')[j].text);
                    if(geoList[j].contains('_subgroup')){
                       var res = geoList[j].split("_");
                       this.aSubgeotype[l]=res[0];
                       l=l+1;
                    }
                    else
                     this.aGeography.push(geoList[j]);
                }
              }
           }
        }
</code>```

But I am facing problem in passing the variable and cached selectors in to other function. Can anyone help me with this?

答:
I don't know how is done your implementation but I really think that you can improve it, by the way, you can reduce your code in two way bit different :

```<code>var myFunction = function(option, filter, array, selector, subType) {
    if(option && option.val()){
        var optList = option.val();
        var optLength = optList.length;
        //Condition to check empty input type
        if( optLength > 0) {
            var l = 0;
            for(var j = 0; j < optLength; j++) {
                if( ($.inArray( selector.select2('data')[j].text, filterList)) == -1 ){
                    filter.push(selector.select2('data')[j].text);
                    if(optList[j].contains('_subgroup')){
                        var res = optList[j].split("_");
                        subType[l]=res[0];
                        l=l+1;
                    } else {
                        array.push(optList[j]);
                    }
                }
            }
        }
    }
}
</code>```

call : myFunction(this.$countryOptions, this.filter, this.aGeography, $('#countryOptions'), this.aSubgeotype)

```<code>// data = {option, filter, array, selector, subType}
var myFunction = function(data) {
    if(data.option && data.option.val()){
        var optList = data.option.val();
        var optLength = optList.length;
        //Condition to check empty input type
        if( optLength > 0) {
            var l = 0;
            for(var j = 0; j < optLength; j++) {
                if( ($.inArray( data.selector.select2('data')[j].text, filterList)) == -1 ){
                    data.filter.push(data.selector.select2('data')[j].text);
                    if(optList[j].contains('_subgroup')){
                        var res = optList[j].split("_");
                        data.subType[l]=res[0];
                        l=l+1;
                    } else {
                        data.array.push(optList[j]);
                    }
                }
            }
        }
    }
}
</code>```

call :

```<code>myFunction({
    option: this.$countryOptions,
    filter: this.filter,
    array: this.aGeography,
    selector: $('#countryOptions'),
    subType: this.aSubgeotype
});
</code>```

or

```<code>var data = {
    option: this.$countryOptions,
    filter: this.filter,
    array: this.aGeography,
    selector: $('#countryOptions'),
    subType: this.aSubgeotype
}
myFunction(data);
</code>```

The first way is to pass your data one by one, the second you pass your data into an json object.

Body:
Here is the code I am trying to remove the redundant code and move the code to separate function.

        //Adding Infotypes to filter and checks whether any infotype option is selected
        if(this.$infoOptions.val() != null){
          var infotypelength = this.$infoOptions.val().length;
          var l=0,j;
          //Condition to check empty input type
          if( infotypelength > 0){
              var infotypeList = this.$infoOptions.val();
              for(j = 0; j < infotypelength; j++) {
                //It checks whether already option is selected and prevents adding to filter if its duplicate.
                if(($.inArray( $('#infoOptions').select2('data')[j].text, filterList)) == -1 ){
                  this.filter.push($('#infoOptions').select2('data')[j].text);
                  if(infotypeList[j].contains('_subgroup')){
                     var res = infotypeList[j].split("_");
                     this.aSubinfotype[l]=res[0];
                     l=l+1;
                  }
                  else
                   this.aInfotypes.push(infotypeList[j]);
                }
              }
           }
        }

        //Adding Countries to filter
        if(this.$countryOptions.val() != null){
          var geoLength = this.$countryOptions.val().length;
          //Condition to check empty input type
          if( geoLength > 0){
              var geoList = this.$countryOptions.val();
              var l=0;
              for(var j = 0; j < geoLength; j++) {
                if(($.inArray( $('#countryOptions').select2('data')[j].text, filterList)) == -1 ){
                    this.filter.push($('#countryOptions').select2('data')[j].text);
                    if(geoList[j].contains('_subgroup')){
                       var res = geoList[j].split("_");
                       this.aSubgeotype[l]=res[0];
                       l=l+1;
                    }
                    else
                     this.aGeography.push(geoList[j]);
                }
              }
           }
        }

But I am facing problem in passing the variable and cached selectors in to other function. Can anyone help me with this?

Body:
I don't know how is done your implementation but I really think that you can improve it, by the way, you can reduce your code in two way bit different :

var myFunction = function(option, filter, array, selector, subType) {
    if(option && option.val()){
        var optList = option.val();
        var optLength = optList.length;
        //Condition to check empty input type
        if( optLength > 0) {
            var l = 0;
            for(var j = 0; j < optLength; j++) {
                if( ($.inArray( selector.select2('data')[j].text, filterList)) == -1 ){
                    filter.push(selector.select2('data')[j].text);
                    if(optList[j].contains('_subgroup')){
                        var res = optList[j].split("_");
                        subType[l]=res[0];
                        l=l+1;
                    } else {
                        array.push(optList[j]);
                    }
                }
            }
        }
    }
}

call : myFunction(this.$countryOptions, this.filter, this.aGeography, $('#countryOptions'), this.aSubgeotype)

// data = {option, filter, array, selector, subType}
var myFunction = function(data) {
    if(data.option && data.option.val()){
        var optList = data.option.val();
        var optLength = optList.length;
        //Condition to check empty input type
        if( optLength > 0) {
            var l = 0;
            for(var j = 0; j < optLength; j++) {
                if( ($.inArray( data.selector.select2('data')[j].text, filterList)) == -1 ){
                    data.filter.push(data.selector.select2('data')[j].text);
                    if(optList[j].contains('_subgroup')){
                        var res = optList[j].split("_");
                        data.subType[l]=res[0];
                        l=l+1;
                    } else {
                        data.array.push(optList[j]);
                    }
                }
            }
        }
    }
}

call :

myFunction({
    option: this.$countryOptions,
    filter: this.filter,
    array: this.aGeography,
    selector: $('#countryOptions'),
    subType: this.aSubgeotype
});

or

var data = {
    option: this.$countryOptions,
    filter: this.filter,
    array: this.aGeography,
    selector: $('#countryOptions'),
    subType: this.aSubgeotype
}
myFunction(data);

The first way is to pass your data one by one, the second you pass your data into an json object.


来源: stackexchange

问:
Redis optimal hash set entry size
I have some questions regarding the optimal entry size setting for Redis hash sets.

In this example memory-optimization they use 100 hash entries
per key but use hash-max-zipmap-entries 256 ?  Why not
hash-max-zipmap-entries 100 or 128?

On the redis website (above link) they used max hash entry size of
100, but in this post instagram, they mention 1000 entries. So
does this mean the optimal setting is a function of the product of
hash-max-zipmap-entries & hash-max-zipmap-value ?(ie in this case
Instagram has smaller hash-values than memory optimization example?)

Your comments/clarifications are much appreciated.

答:
The key is, from here:

manipulating the compact versions of these [ziplist] structures can become slow as they grow longer

and

[as ziplists grow longer] fetching/updating individual fields of a HASH, Redis will have to decode many individual entries, and CPU caches won’t be as effective

So to your questions

This page just shows an example and I doubt the author gave much thought to the exact values. In real life, IF you wanted to take advantage of ziplists, and you knew your number of entries per hash was <100, then setting it at 100, 128 or 256 would make no difference. hash-max-zipmap-entries is only the LIMIT over which you're telling Redis to change the encoding from ziplist to hash.

There may be some truth in your "product of hash-max-zipmap-entries & hash-max-zipmap-value" idea, but I'm speculating. More importantly, first you have to define "optimal" based on what you want to do.  If you want to do lots of HSET/HGETs in a large ziplist, it will be slower than if you used a hash.  But if you never get/update single fields only ever do HMSET/HGETALL on a key, large ziplists wouldn't slow you down. The Instagram 1000 was THEIR optimal number based on THEIR specific data, use cases, and Redis function call frequencies.

ContentLicense: CC BY-SA 3.0

Title: Redis optimal hash set entry size


问:
How do I read double quotes(") or single quotes(') through command line into my perl program?
I am trying to use use arguments passed as command line arguments into my script, But while doing so the double quotes(") and single quotes(') vanishes.
for example on running the following:

```<code>#!usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my $argument_list = join(" ",@ARGV);

print "$argument\n";
</code>```

Upon running the above code:

```<code>perl test1.pl name1 "name2 and name3"
</code>```

I am getting the following output:

```<code>name1 name2 and name3
</code>```

Is there any way to include the double quotes along with the command line arguments so that the final argument is "name2 and name3" and not just name2 and name3 ?

I have tried using '\' to escape double quotes perl test1.pl name1 \"name2 and name3\" but it only makes it worse by considering "name2 as a separate argument and as a separate argument and name3" as another argument.

答:
Your code snippet is not working as the $argument is undefined. However I tried this updated and it works as you desired. See the output below:

```<code>#!/usr/bin/perl

use strict;
use warnings;
#use Data::Dumper;

my $argument_list = join(" ",@ARGV);

print "$argument_list\n";
</code>```

Here's the output:

```<code>$ perl test1.pl name1 \"name2 and name3\"
name1 "name2 and name3"
$ perl test1.pl name1 name2 and name3
name1 name2 and name3
</code>```

Body:
I am trying to use use arguments passed as command line arguments into my script, But while doing so the double quotes(") and single quotes(') vanishes.
for example on running the following:

#!usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my $argument_list = join(" ",@ARGV);

print "$argument\n";

Upon running the above code:

perl test1.pl name1 "name2 and name3"

I am getting the following output:

name1 name2 and name3

Is there any way to include the double quotes along with the command line arguments so that the final argument is "name2 and name3" and not just name2 and name3 ?

I have tried using '\' to escape double quotes perl test1.pl name1 \"name2 and name3\" but it only makes it worse by considering "name2 as a separate argument and as a separate argument and name3" as another argument.

Body:
Your code snippet is not working as the $argument is undefined. However I tried this updated and it works as you desired. See the output below:

#!/usr/bin/perl

use strict;
use warnings;
#use Data::Dumper;

my $argument_list = join(" ",@ARGV);

print "$argument_list\n";

Here's the output:

$ perl test1.pl name1 \"name2 and name3\"
name1 "name2 and name3"
$ perl test1.pl name1 name2 and name3
name1 name2 and name3


问:
Nhibernate query entity with enum property
I need to query the entity Person with enum property TargetBookingSystemType

```<code>public class Person : EntityWithTypedId<PersonCompositeId>
{
    public virtual string Key { get; set; }

    public virtual TargetBookingSystemType TargetBookingSystemType { get; set; }
}

 public class PersonMap : ClassMap<Person>
 {
     public PersonMap()
     {
        this.CompositeId(x => x.Id).KeyProperty(y => y.AccountName, "[AccountName]").KeyProperty(y => y.Domain, "[Domain]");
        this.Table("Person");
        this.Map(x => x.Key).Column("[Key]");
        this.Map(x => x.TargetBookingSystemType).Column("[TargetBookingSystemType]");//.CustomType<TargetBookingSystemType>();
     }
 }

public enum TargetBookingSystemType
    {
        GoogleCalendarAPIv3 = 1,
        MSExchange2007 = 2,
        MSExchange2010 = 3,
        MSExchange2013 = 4,
        MSOnline = 5
    }

CREATE TABLE [dbo].[Person](
    [Domain] [varchar](3) NOT NULL,
    [AccountName] [varchar](255) NOT NULL,
    [Key] [varchar](255) NOT NULL,
    [TargetBookingSystemType] [nvarchar](20) NULL
 )
</code>```

I know that a possible solution is to change the type of the property to string but how can I achieve that using NHibernate I can have the property as an enum and still get a successful query?

Tried CustomType() but with no luck getting an error Input string was not in a correct format.

please note that the query is working when I comment out the line with mapping of TargetBookingSystemType

EDIT:

I would like to have one call to DB and after that filtering the result based on the enum.
This is the method doing the query using NHibernate:

```<code>public IList<Domain.DomainObjects.Entities.Person> GetAllPersons()
        {
            IList<Domain.DomainObjects.Entities.Person> list = new List<Domain.DomainObjects.Entities.Person>();
            string queryString = "select MR from Person MR";
            return this.Session.CreateQuery(queryString).SetCacheable(true).SetCacheRegion("LongTerm").List<Domain.DomainObjects.Entities.Person>();
        }
</code>```

How can I get the enum property in the result aswell?

答:
There is not a solution when you need to query over entity with enum property and nvarchar column in DB.

The possible workarounds

Change the datatype of the property from enum to string and keep the nvarchar in DB.

```<code>public class Person : EntityWithTypedId<PersonCompositeId>
{
    public virtual string Key { get; set; }

    public virtual string TargetBookingSystemType { get; set; }
}
</code>```

OR

Keep the enum property in enum but change the column type from nvarchar to int as suggested. You also need to specify the CustomProperty<enumType>() in mapping class or xml.

```<code>CREATE TABLE [dbo].[Person](
    [Domain] [varchar](3) NOT NULL,
    [AccountName] [varchar](255) NOT NULL,
    [Key] [varchar](255) NOT NULL,
    [TargetBookingSystemType] [int] NULL )
</code>```

Body:
I need to query the entity Person with enum property TargetBookingSystemType

public class Person : EntityWithTypedId<PersonCompositeId>
{
    public virtual string Key { get; set; }

    public virtual TargetBookingSystemType TargetBookingSystemType { get; set; }
}

 public class PersonMap : ClassMap<Person>
 {
     public PersonMap()
     {
        this.CompositeId(x => x.Id).KeyProperty(y => y.AccountName, "[AccountName]").KeyProperty(y => y.Domain, "[Domain]");
        this.Table("Person");
        this.Map(x => x.Key).Column("[Key]");
        this.Map(x => x.TargetBookingSystemType).Column("[TargetBookingSystemType]");//.CustomType<TargetBookingSystemType>();
     }
 }

public enum TargetBookingSystemType
    {
        GoogleCalendarAPIv3 = 1,
        MSExchange2007 = 2,
        MSExchange2010 = 3,
        MSExchange2013 = 4,
        MSOnline = 5
    }

CREATE TABLE [dbo].[Person](
    [Domain] [varchar](3) NOT NULL,
    [AccountName] [varchar](255) NOT NULL,
    [Key] [varchar](255) NOT NULL,
    [TargetBookingSystemType] [nvarchar](20) NULL
 )

I know that a possible solution is to change the type of the property to string but how can I achieve that using NHibernate I can have the property as an enum and still get a successful query?

Tried CustomType() but with no luck getting an error Input string was not in a correct format.

please note that the query is working when I comment out the line with mapping of TargetBookingSystemType

EDIT:

I would like to have one call to DB and after that filtering the result based on the enum.
This is the method doing the query using NHibernate:

public IList<Domain.DomainObjects.Entities.Person> GetAllPersons()
        {
            IList<Domain.DomainObjects.Entities.Person> list = new List<Domain.DomainObjects.Entities.Person>();
            string queryString = "select MR from Person MR";
            return this.Session.CreateQuery(queryString).SetCacheable(true).SetCacheRegion("LongTerm").List<Domain.DomainObjects.Entities.Person>();
        }

How can I get the enum property in the result aswell?

Body:
There is not a solution when you need to query over entity with enum property and nvarchar column in DB.

The possible workarounds

Change the datatype of the property from enum to string and keep the nvarchar in DB.

public class Person : EntityWithTypedId<PersonCompositeId>
{
    public virtual string Key { get; set; }

    public virtual string TargetBookingSystemType { get; set; }
}

OR

Keep the enum property in enum but change the column type from nvarchar to int as suggested. You also need to specify the CustomProperty<enumType>() in mapping class or xml.

CREATE TABLE [dbo].[Person](
    [Domain] [varchar](3) NOT NULL,
    [AccountName] [varchar](255) NOT NULL,
    [Key] [varchar](255) NOT NULL,
    [TargetBookingSystemType] [int] NULL )


问:
How to define a sub-module in Python?
Python has a module named "os". It also has some other module named "os.path" which is categorized under the "os".

I can use "os.path" methods even if only import the "os" module.

```<code>import os

print(os.path.join("sdfs","x"))
</code>```

I wonder how can I define a sub-module like this?

答:
Use this structure:

```<code>/ Package
├── __init__.py
├── file.py
│
├─┐ subpackage
│ ├── __init__.py
│ └── file.py
│
└─┐ subpackage2
  ├── __init__.py
  └── file.py
</code>```

Note each subpackage has its own __init__.py file. This will make Package.subpackage behave like os.path, importation speaking (considering you do not import .subpackage under the main __init__ file of Package).

Title: How to define a sub-module in Python?

Body:
Python has a module named "os". It also has some other module named "os.path" which is categorized under the "os".

I can use "os.path" methods even if only import the "os" module.

import os

print(os.path.join("sdfs","x"))

I wonder how can I define a sub-module like this?

Body:
Use this structure:

/ Package
├── __init__.py
├── file.py
│
├─┐ subpackage
│ ├── __init__.py
│ └── file.py
│
└─┐ subpackage2
  ├── __init__.py
  └── file.py

Note each subpackage has its own __init__.py file. This will make Package.subpackage behave like os.path, importation speaking (considering you do not import .subpackage under the main __init__ file of Package).


问:
android on back pressed
```<code>@Override
public void onBackPressed(){
    if (back_pressed + 2000 > System.currentTimeMillis()){
        Homepage1.super.onBackPressed();
    }
    else{
        Toast.makeText(getBaseContext(), "Press once again to exit", Toast.LENGTH_SHORT).show();
        back_pressed = System.currentTimeMillis();
    }
}
</code>```

Error:(51, 42) error: ';' expected Error:Execution failed for task
  ':app:compileDebugJavaWithJavac'. Compilation failed; see the compiler
  error output for details.

答:
Put this method inside Activity class.

```<code>public class MyActivity extends AppCompatActivity {

    @Override
    public void onBackPressed() {
        if (back_pressed + 2000 > System.currentTimeMillis()){
                    Homepage1.super.onBackPressed();
                }
                else{
                    Toast.makeText(getBaseContext(), "Press once again to exit", Toast.LENGTH_SHORT).show();
                    back_pressed = System.currentTimeMillis();
                }
    }
}
</code>```

Title: android on back pressed

Body:
@Override
public void onBackPressed(){
    if (back_pressed + 2000 > System.currentTimeMillis()){
        Homepage1.super.onBackPressed();
    }
    else{
        Toast.makeText(getBaseContext(), "Press once again to exit", Toast.LENGTH_SHORT).show();
        back_pressed = System.currentTimeMillis();
    }
}

Error:(51, 42) error: ';' expected Error:Execution failed for task
  ':app:compileDebugJavaWithJavac'. Compilation failed; see the compiler
  error output for details.

Body:
Put this method inside Activity class.

public class MyActivity extends AppCompatActivity {

    @Override
    public void onBackPressed() {
        if (back_pressed + 2000 > System.currentTimeMillis()){
                    Homepage1.super.onBackPressed();
                }
                else{
                    Toast.makeText(getBaseContext(), "Press once again to exit", Toast.LENGTH_SHORT).show();
                    back_pressed = System.currentTimeMillis();
                }
    }
}


问:
Accessing data in a loop of text field with ColdFusion
I am fairly new to ColdFusion, and don't quite understand how variable access works. I've created a table that generates a number of text fields named condesc#i#, where i is the current index in a cfloop.

I then have a second loop, that attempts to access the contents of each field that has been created. I have attempted to make access using #condesc#i##, but with no success.

How should I go about getting the information from these fields?

答:
All variables are structures so you can access them like this:

```<code>form[ "condesc" & i ]
</code>```

And dynamically build the keys.

ContentLicense: CC BY-SA 2.5

Body:
All variables are structures so you can access them like this:

form[ "condesc" & i ]

And dynamically build the keys.


问:
Angular 4 - configuring systemjs
I am using systemjs as a module loader for the first time. I am also trying to use ng2-drag-drop plugin in my project. After installing it, I have imported the module in the model where I would like to use it, in my case that is the PostModule.

```<code>import { Ng2DragDropModule } from 'ng2-drag-drop';

@NgModule({
  imports: [PostRoutingModule, SharedModule, Ng2DragDropModule],
  declarations: [PostComponent],
  exports: [PostComponent],
  providers: [PostService]
})
export class PostModule { }
</code>```

And as it says in the docs, I have changed the systemjs config file:

```<code>declare var System: SystemJSLoader.System;

System.config(JSON.parse('<%= SYSTEM_CONFIG_DEV %>'));
System.config({
    map: {
        'ng2-drag-drop': 'node_modules/ng2-drag-drop'
    },
    packages: {
        'ng2-drag-drop':  { main: 'index.js',  defaultExtension: 'js' },
    }
});
</code>```

But, I get an error:

GET
  http://localhost:5555/node_modules/node_modules/ng2-drag-drop/index.js
  404 (Not Found) (anonymous)
  (SystemJS) XHR error (404 Not Found) loading
  http://localhost:5555/node_modules/node_modules/ng2-drag-drop/index.js

答:
Here is how you can configure it:</p>

```<code>System.config({
    paths: {
        'npm:': '/node_modules/'
    },

    map: {
        'ng2-drag-drop': 'npm:ng2-drag-drop'
    },

    packages: {
        'ng2-drag-drop': {
            main: 'index.js',
            defaultExtension: 'js'
        }

    }
</code>```

Title: Angular 4 - configuring systemjs

Body:
I am using systemjs as a module loader for the first time. I am also trying to use ng2-drag-drop plugin in my project. After installing it, I have imported the module in the model where I would like to use it, in my case that is the PostModule.

import { Ng2DragDropModule } from 'ng2-drag-drop';

@NgModule({
  imports: [PostRoutingModule, SharedModule, Ng2DragDropModule],
  declarations: [PostComponent],
  exports: [PostComponent],
  providers: [PostService]
})
export class PostModule { }

And as it says in the docs, I have changed the systemjs config file:

declare var System: SystemJSLoader.System;

System.config(JSON.parse('<%= SYSTEM_CONFIG_DEV %>'));
System.config({
    map: {
        'ng2-drag-drop': 'node_modules/ng2-drag-drop'
    },
    packages: {
        'ng2-drag-drop':  { main: 'index.js',  defaultExtension: 'js' },
    }
});

But, I get an error:

GET
  http://localhost:5555/node_modules/node_modules/ng2-drag-drop/index.js
  404 (Not Found) (anonymous)
  (SystemJS) XHR error (404 Not Found) loading
  http://localhost:5555/node_modules/node_modules/ng2-drag-drop/index.js

Body:
Here is how you can configure it:

System.config({
    paths: {
        'npm:': '/node_modules/'
    },

    map: {
        'ng2-drag-drop': 'npm:ng2-drag-drop'
    },

    packages: {
        'ng2-drag-drop': {
            main: 'index.js',
            defaultExtension: 'js'
        }

    }


问:
bootstrap-timepicker not displaying model values on load
I have the following element:

```<code><div class="input-group bootstrap-timepicker">
    <input type="text"
           class="form-control timepicker"
           name="start-time"
           ng-model="timeSegment[0]"/>
    <span data-toggle="timepicker" class="input-group-addon add-on btn btn-default">
       <i class="icon icon-time"></i>
    </span>
</div>
</code>```

It is contained in an ng-repeat that repeats this element multiple times. The above code snippet works perfectly, and correctly displays the correct model values when it is loaded, but uses a text box to enter time instead of timepickers. My model value 'timeSegment[0]' is a string in the format 'hh:mm a', for example '04:00 AM'.

However, as soon as I added the bs-timepicker attribute to the above elements (to allow time to be entered using timepickers instead of textbox):

```<code><div class="input-group bootstrap-timepicker">
        <input type="text"
               class="form-control timepicker"
               name="start-time"
               ng-model="timeSegment[0]"
               bs-timepicker/>
        <span data-toggle="timepicker" class="input-group-addon add-on btn btn-default">
           <i class="icon icon-time"></i>
        </span>
    </div>
</code>```

they showed a default time instead of the values from my model. It was picking up my model correctly, since it correctly iterated the right number of elements and showed the timepicker for them, just not the right value in the timepicker.

Whats also strange is that although the timepickers show a default time, as soon as I change one of them, the value is correctly updated in my model.

I thought it may be because time is my model is a string, and not a date, but even adding attributes described here http://mgcrea.github.io/angular-strap/#/timepickers, such as the following, made no difference. I also tried making my model a Date object, but again, no difference.

```<code>data-modelTimeFormat="hh:mm A"
data-timeType="string"
</code>```

答:
I ended up using a different timepicker, which works as expected:

https://angular-ui.github.io/bootstrap/

Body:
I have the following element:

    <input type="text"
           class="form-control timepicker"
           name="start-time"
           ng-model="timeSegment[0]"/>

It is contained in an ng-repeat that repeats this element multiple times. The above code snippet works perfectly, and correctly displays the correct model values when it is loaded, but uses a text box to enter time instead of timepickers. My model value 'timeSegment[0]' is a string in the format 'hh:mm a', for example '04:00 AM'.

However, as soon as I added the bs-timepicker attribute to the above elements (to allow time to be entered using timepickers instead of textbox):

        <input type="text"
               class="form-control timepicker"
               name="start-time"
               ng-model="timeSegment[0]"
               bs-timepicker/>

they showed a default time instead of the values from my model. It was picking up my model correctly, since it correctly iterated the right number of elements and showed the timepicker for them, just not the right value in the timepicker.

Whats also strange is that although the timepickers show a default time, as soon as I change one of them, the value is correctly updated in my model.

I thought it may be because time is my model is a string, and not a date, but even adding attributes described here http://mgcrea.github.io/angular-strap/#/timepickers, such as the following, made no difference. I also tried making my model a Date object, but again, no difference.

data-modelTimeFormat="hh:mm A"
data-timeType="string"


问:
Best Practice with WCF ChannelFactory and connection timeout
I am working on an winform application that will access a WCF service self-hosted as a windows service. I am using the ChannelFactory instead of the service reference. I have been successful in connecting and calling the WCF service. The issue is when I let the application remain idle for 20 minutes and then try to make another call. I receive the following error:

"The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:59.9489970'."

I am looking for the best practice on managing the connection. I currently have created a function called PrepareWCFConnection (see below) that checks state of the channel and the ChannelFactory. I call this method before I make any calls to the WCF services. Is there a better way of handling this?

```<code>     public bool PrepareWCFConnection()
    {
        if ((channelFactory == null) ||
            (channelFactory.State == CommunicationState.Faulted) ||
            (channelFactory.State != CommunicationState.Opened))
        {
            channelFactory = new ChannelFactory<IService1>(new NetTcpBinding(), endpointAddress);
        }

        if ((proxy == null) ||
            (((IClientChannel)proxy).State == CommunicationState.Faulted) ||
            (((IClientChannel)proxy).State != CommunicationState.Opened))
        {
            proxy = channelFactory.CreateChannel(endpointAddress);
            ((IClientChannel)proxy).Open();
        }

        return true;
    }
</code>```

答:
One pretty straight forward solution to reuse your channel, without polling or do fancy stuff it's just take care of the last call to your channel and check the wcfC.Binding.ReceiveTimeout in order to regenerate it if needed, something like:</p>

```<code>    TimeSpan timeSpan = DateTime.Now - LastCallTime;
    if (timeSpan.TotalSeconds > wcfC.Binding.ReceiveTimeout.TotalSeconds || wcfC.State != CommunicationState.Opened)
    {
       wcfC.Abort();
       wcfC = new WCFChannel();

    }
    LastCallTime = DateTime.Now;
</code>```

Body:
I am working on an winform application that will access a WCF service self-hosted as a windows service. I am using the ChannelFactory instead of the service reference. I have been successful in connecting and calling the WCF service. The issue is when I let the application remain idle for 20 minutes and then try to make another call. I receive the following error:

"The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:59.9489970'."

I am looking for the best practice on managing the connection. I currently have created a function called PrepareWCFConnection (see below) that checks state of the channel and the ChannelFactory. I call this method before I make any calls to the WCF services. Is there a better way of handling this?

     public bool PrepareWCFConnection()
    {
        if ((channelFactory == null) ||
            (channelFactory.State == CommunicationState.Faulted) ||
            (channelFactory.State != CommunicationState.Opened))
        {
            channelFactory = new ChannelFactory<IService1>(new NetTcpBinding(), endpointAddress);
        }

        if ((proxy == null) ||
            (((IClientChannel)proxy).State == CommunicationState.Faulted) ||
            (((IClientChannel)proxy).State != CommunicationState.Opened))
        {
            proxy = channelFactory.CreateChannel(endpointAddress);
            ((IClientChannel)proxy).Open();
        }

        return true;
    }

Body:
One pretty straight forward solution to reuse your channel, without polling or do fancy stuff it's just take care of the last call to your channel and check the wcfC.Binding.ReceiveTimeout in order to regenerate it if needed, something like:

    TimeSpan timeSpan = DateTime.Now - LastCallTime;
    if (timeSpan.TotalSeconds > wcfC.Binding.ReceiveTimeout.TotalSeconds || wcfC.State != CommunicationState.Opened)
    {
       wcfC.Abort();
       wcfC = new WCFChannel();

    }
    LastCallTime = DateTime.Now;


问:
PowerShell to form correctly formatted json for calendar entry
I am struggling to get PowerShell to form a correctly formatted json entry when creating a new Google Calendar entry.

A correctly configured json, that is accepted by GC is as follows:

```<code>'{"end": {"dateTime": "2017-06-07T15:00:00Z"},
 "start": {"dateTime": "2017-06-07T10:00:00Z"}
}'
</code>```

However, forming a json from a hashtable (so I can use a variable dateTime) does not form it correctly, example:

```<code>$body=@{
    start="2017-06-08T10:00:00Z"
    end="2017-06-08T12:00:00Z"}

$json = $body | ConvertTo-Json
</code>```

$json is returned as follows:

```<code>{
    "start":  "2017-06-08T10:00:00Z",
    "end":  "2017-06-08T12:00:00Z"
}
</code>```

This is not accepted by the Google Cal API, an when testing with the OAuth 2.0 Playground it returns the following error:

```<code>{
  "error": {
    "code": 400,
    "message": "Missing end time.",
    "errors": [
     {
        "domain": "global",
        "message": "Missing end time.",
        "reason": "required"
     }
   ]
 }
</code>```

Any ideas on how to use PowerShell to form a correctly formatted Start and End date?

Thanks :)

Body:
I am struggling to get PowerShell to form a correctly formatted json entry when creating a new Google Calendar entry.

A correctly configured json, that is accepted by GC is as follows:

'{"end": {"dateTime": "2017-06-07T15:00:00Z"},
 "start": {"dateTime": "2017-06-07T10:00:00Z"}
}'

However, forming a json from a hashtable (so I can use a variable dateTime) does not form it correctly, example:

$body=@{
    start="2017-06-08T10:00:00Z"
    end="2017-06-08T12:00:00Z"}

$json = $body | ConvertTo-Json

$json is returned as follows:

{
    "start":  "2017-06-08T10:00:00Z",
    "end":  "2017-06-08T12:00:00Z"
}

This is not accepted by the Google Cal API, an when testing with the OAuth 2.0 Playground it returns the following error:

{
  "error": {
    "code": 400,
    "message": "Missing end time.",
    "errors": [
     {
        "domain": "global",
        "message": "Missing end time.",
        "reason": "required"
     }
   ]
 }

Any ideas on how to use PowerShell to form a correctly formatted Start and End date?

Thanks :)

Body:
Using nesting:

$body=@{
 start=@{"datetime" = "2017-06-08T10:00:00Z"}
 end=@{"datetime" = "2017-06-08T12:00:00Z"}} | ConvertTo-Json

Outputs:

{
    "start":  {
                  "datetime":  "2017-06-08T10:00:00Z"
              },
    "end":  {
                "datetime":  "2017-06-08T12:00:00Z"
            }
}


问:
How to change JSON array to another format
Array has objects. Example is below;

```<code>  [{
    "Id": 1,
    "ParentId": -1,
    "Name": "Mobilya",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 1,
    "IsShowing": true
  },
  {
    "Id": 2,
    "ParentId": -1,
    "Name": "Televizyon",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 2,
    "IsShowing": true
  },
  {
    "Id": 16,
    "ParentId": 1,
    "Name": "Köşe Takımları",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 5,
    "IsShowing": true
  }]
</code>```

I want to change it to

```<code>  [{
    "id": 1,
    "label": "Mobilya",
    "clickableId": "ndMainCategory",
    "icon": "",
    "items": [{
              "id": 16,
              "label": "Köşe Takımları"
              }]
   },
   {
    "id": 2,
    "label": "Mobilya",
    "clickableId": "ndMainCategory",
    "icon": ""
   }]
</code>```

Here if ParentId is -1 it means it is main category.clickableId":"ndMainCategory" this is static for every main category.
    First array comes from api and I have to change it to another one but I couldn't do it . How can I do it.

Thanks

in advance;

答:
You can use reduce() method with recursion to create function that will return this result.

var data = [{"Id":1,"ParentId":-1,"Name":"Mobilya","Slug":"","Content":"","Icon":"","Code":"","Order":1,"IsShowing":true},{"Id":2,"ParentId":-1,"Name":"Televizyon","Slug":"","Content":"","Icon":"","Code":"","Order":2,"IsShowing":true},{"Id":16,"ParentId":1,"Name":"Köşe Takımları","Slug":"","Content":"","Icon":"","Code":"","Order":5,"IsShowing":true}]

function format(data, pid) {
  return data.reduce(function(r, e) {
    var obj
    if (pid == -1) obj = {id: e.Id,label: e.Name,clickableId: "ndMainCategory",icon: e.Icon}
    else obj = {id: e.Id,label: e.Name}

    if (e.ParentId == pid) {
      var children = format(data, e.Id)
      if (children.length) obj.items = children
      r.push(obj)
    }

    return r;
  }, [])
}

console.log(format(data, -1))```

Body:
Array has objects. Example is below;

  [{
    "Id": 1,
    "ParentId": -1,
    "Name": "Mobilya",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 1,
    "IsShowing": true
  },
  {
    "Id": 2,
    "ParentId": -1,
    "Name": "Televizyon",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 2,
    "IsShowing": true
  },
  {
    "Id": 16,
    "ParentId": 1,
    "Name": "Köşe Takımları",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 5,
    "IsShowing": true
  }]

I want to change it to

  [{
    "id": 1,
    "label": "Mobilya",
    "clickableId": "ndMainCategory",
    "icon": "",
    "items": [{
              "id": 16,
              "label": "Köşe Takımları"
              }]
   },
   {
    "id": 2,
    "label": "Mobilya",
    "clickableId": "ndMainCategory",
    "icon": ""
   }]

Here if ParentId is -1 it means it is main category.clickableId":"ndMainCategory" this is static for every main category.
    First array comes from api and I have to change it to another one but I couldn't do it . How can I do it.

Thanks

in advance;


问:
What method to override to know when the application exits from any screen
I have to do a clean up of some app generated files, when the application is completely closed. The close can happen from any screen. Which method or where should i override globally to caputure Menu Close event, rather than overriding onClose() on each screen of the application ?

And when the application is closed using Menu Close in the middle of the application, is onClose() called for each screen on the stack and are popped off the stack, or it just removes the application from memory ?

答:
I don't believe there's a method that does exactly what you want but I think you can get the behavior you want.  First off, based on the testing I've done the close menu item simply calls onClose() for the current screen.  The default close menu item does not close the entire application, it just closes one screen.

The closest method I can think of is deactivate(), this is called when the app is sent to the background but not when it's actually closed (i.e. this method will be called if you press the red "end call" button but not if you press close in the menu).  This would probably be overkill but what you could do is select "Auto-run on startup" and "Do not display the application icon on the BlackBerry home screen" in your BlackBerry App Descriptor.  This would make the app invisible to the user so that it's always in the background, to have an icon on the homescreen and display a GUI you would create an alternate entry point that will bring up the UI.  Then when the user selects the close menu item all it's really doing is sending the application to the background and you can put your cleanup code in deactivate().

A much better approach would be to just override onClose() in a parent class and then just make all of your screens inherit from that class.  You can put your cleanup code in there.  Or if you want the close menu item to close all screens override the makeMenu() method and add a MenuItem that will execute the appropriate cleanup code before calling System.exit().


问:
Rem-Based Layouts, Zooming on chrome is inconsistent, PX vs REM
I've been wracking my brain over this one, google searches don't really have much in the way of help or even documentation of this problem but it's greatly affecting my current conversion to a mobile-friendly design.

Everywhere I go, everyone's touting using rem-based layouts as the new gold standard, and on the surface the virtues of this approach seem ideal (full accesibility support for both reference pixel based scaling and font-size scaling to support many DPIs and many screen sizes / settings).

However I've run into a rather large snag, I'm finding that Chrome (and possibly all webkit browsers but I don't have a mac atm to test) don't seem to scale the same as the rest.

With the initial setup like this:

```<code>html { font-size: 62.5%; }
body { font-size: 1.6rem; }
</code>```

We should be able to set up all our measurements using 1/10th the pixel size in rems:

```<code>.my-element { height: 15rem; } /* 150px */
</code>```

I've created a simple example that illustrates my problem here: https://jsfiddle.net/gLkpz88q/2/embedded/result/

When you use Chrome and you scale this way out, notice how the layout stops scaling but the content continues.

Compare this to Firefox, IE11, Edge and you don't see this behavior at all, they all scale uniformly and continually.

Here's (Top-Left: Chrome, Top-Right: IE11, Bottom-Left: Edge, Bottom-Right: FireFox) side-by-side:

As you can see this has some terrible implications for layouts if the rem unit scales differently than everything else.

I'm not certain how to proceed with this scenario as it seems like WebKit/Chrome have decided to handle scaling completely differently and this calls in to question all the scaling scenarios going forward.

There's a number of articles advocating just using pixels as the CSS Reference Pixel takes care of mobile scaling rather well:

Just Use Pixels

R.I.P. Rem, Viva CSS Reference Pixel!

However these tend to ignore the font-scaling issue, citing it as an unlikely situation.

I did a quick look around at man big mobile friendly/friendlyish sites I could think of from large & successful companies and it seems most of them just use pixels for all their layout needs. (Google, Facebook, Wordpress, Twitter, Bootstrap 3, [and to some extent Bootstrap 4], MDN, and WebPlatform)

Is Chrome the new Standards-Busting IE? Or am I doing something horribly wrong? I'm tempted to just use pixels at this point for consistency.

答:
Don't use this CSS { font-size: 62.5%; } body { font-size: 1.6rem; } it causes more problems that it is worth, due to the fact that you will get different results on browsers that use different base font sizes. Just use this site to calculate the correct rem values. http://pxtoem.com/

This should give you consistent results.
https://jsfiddle.net/WizardCoder/gLkpz88q/3/

UPDATE
https://jsfiddle.net/WizardCoder/gLkpz88q/5/

Body:
I've been wracking my brain over this one, google searches don't really have much in the way of help or even documentation of this problem but it's greatly affecting my current conversion to a mobile-friendly design.

Everywhere I go, everyone's touting using rem-based layouts as the new gold standard, and on the surface the virtues of this approach seem ideal (full accesibility support for both reference pixel based scaling and font-size scaling to support many DPIs and many screen sizes / settings).

However I've run into a rather large snag, I'm finding that Chrome (and possibly all webkit browsers but I don't have a mac atm to test) don't seem to scale the same as the rest.

With the initial setup like this:

html { font-size: 62.5%; }
body { font-size: 1.6rem; }

We should be able to set up all our measurements using 1/10th the pixel size in rems:

.my-element { height: 15rem; } /* 150px */

I've created a simple example that illustrates my problem here: https://jsfiddle.net/gLkpz88q/2/embedded/result/

When you use Chrome and you scale this way out, notice how the layout stops scaling but the content continues.

Compare this to Firefox, IE11, Edge and you don't see this behavior at all, they all scale uniformly and continually.

Here's (Top-Left: Chrome, Top-Right: IE11, Bottom-Left: Edge, Bottom-Right: FireFox) side-by-side:

As you can see this has some terrible implications for layouts if the rem unit scales differently than everything else.

I'm not certain how to proceed with this scenario as it seems like WebKit/Chrome have decided to handle scaling completely differently and this calls in to question all the scaling scenarios going forward.

There's a number of articles advocating just using pixels as the CSS Reference Pixel takes care of mobile scaling rather well:

Just Use Pixels

R.I.P. Rem, Viva CSS Reference Pixel!

However these tend to ignore the font-scaling issue, citing it as an unlikely situation.

I did a quick look around at man big mobile friendly/friendlyish sites I could think of from large & successful companies and it seems most of them just use pixels for all their layout needs. (Google, Facebook, Wordpress, Twitter, Bootstrap 3, [and to some extent Bootstrap 4], MDN, and WebPlatform)

Is Chrome the new Standards-Busting IE? Or am I doing something horribly wrong? I'm tempted to just use pixels at this point for consistency.


问:
How to change Azure App Service to 64-bit
I have been having trouble making a request to my 64-bit ASP.NET Core API running on an Azure App Service. The error I get back is:

Unhandled Exception: System.BadImageFormatException: Could not load file or assembly '***.dll'. An attempt was made to load a program with an incorrect format.

I understand that this means there is a mismatch between the platform of the app (64-bit) and that of the environment it runs on. I just can't figure out how to change the App Service so it runs using 64-bit.

In the Application Settings in the Azure portal I have set Platform to 64-bit:

However when I check in Kudu, the runtime environment indicates that it's operating under win8-x86:

project.json

```<code>"buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true,
    "platform": "x64"
},

"runtimes": {
    "win10-x64": {}
}
</code>```

Some questions

How do I change the App Service to ensure it's running on a 64-bit platform?

Does it matter that the RID is win8... when my runtimes configuration in project.json specifies win10.... Presumably x86 vs x64 matters, but does it need to be the same version of windows too ie. win8 vs win10.

答:
TLDR; 64 bit .NET core processes using the .NET core runtime (as opposed to the .NET Framework runtime) are not yet supported on Azure but is planned to be coming in the future.

The following is from discussions I had with Microsoft Azure support.

The 64bit/32bit configuration on Azure portal (shown above in my screenshot), controls the IIS w3wp.exe process. The w3wp.exe process forwards requests to your NET core process. The configuration doesn't control the bitness of the .NET core process. It's a bit confusing, but explains why changing the Platform option in the screneshot above had no affect.

Based on the PATH environment variable setting of app service, dotnet.exe is mapped to the 32bit one, which is "D: \Program Files (x86)\dotnet\dotnet.exe". The 64bit runtime of .NET core is not pre-installed in app services, as a result, it is currently not available.

Microsoft is planning to add 64-bit support to .NET core applications running on the .NET core runtime in Azure but it depends on a future update of the .NET core tools chain. They gave me an estimated internal date but I promised I wouldn't share that publicly.

A workaround they gave me was to use the ASP.NET core (using .net framework) visual studio template, not the ASP.NET core (using .net core) one. That one loads the 64bit .Net framework runtime for your ASP.Net core web application. This will require a bit of migration work and I assume may not be possible for some projects.

Fortunately I was able to swap to 32 bit versions of some of my dependencies which meant the app worked in the Azure environment. Sadly this won't mean much to those that don't have this option, and I'm sure there are many.

Body:
I have been having trouble making a request to my 64-bit ASP.NET Core API running on an Azure App Service. The error I get back is:

Unhandled Exception: System.BadImageFormatException: Could not load file or assembly '***.dll'. An attempt was made to load a program with an incorrect format.

I understand that this means there is a mismatch between the platform of the app (64-bit) and that of the environment it runs on. I just can't figure out how to change the App Service so it runs using 64-bit.

In the Application Settings in the Azure portal I have set Platform to 64-bit:

However when I check in Kudu, the runtime environment indicates that it's operating under win8-x86:

project.json

"buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true,
    "platform": "x64"
},

"runtimes": {
    "win10-x64": {}
}

Some questions

How do I change the App Service to ensure it's running on a 64-bit platform?

Does it matter that the RID is win8... when my runtimes configuration in project.json specifies win10.... Presumably x86 vs x64 matters, but does it need to be the same version of windows too ie. win8 vs win10.


问:
Form control with angular.js
I have been playing about with angular and forms but I am having some trouble with the code below. I thought that it should add forenames to the ones already displayed by the ng-repeat whenever the form is submitted but the submit button appears to do nothing.

HTML:

```<code><!DOCTYPE html>
    <html lang="en" ng-app="file">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
        <script types="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
        <script types=text/javascript" src="formLoops.js"></script>
        <title>Title</title>
    </head>
    <body ng-controller="PersonalDetailsController as person">
        <p ng-repeat="info in person.details">{{info.forename}}</p>

    <form name="PersonalDetailsForm" ng-controller="DataEntryController as dataCtrl" ng-submit="addPerson(person)">
        <blockquote>
            <p>{{dataCtrl.person.forename}}</p>
            <p>{{dataCtrl.person.surname}}</p>
        </blockquote>

        <label>Forename:</label>
        <input ng-model="dataCtrl.person.forename"/>
        <label>Surname:</label>
        <input ng-model="dataCtrl.person.surname"/>
        <input type="submit" value="submit"/>

    </form>

    </body>
    </html>
</code>```

JS:

```<code>var app = angular.module("file", []);

app.controller("PersonalDetailsController", function() {
  this.details = personalDetails;
});

app.controller("DataEntryController", function() {
  this.person = {};
  this.addPerson = function(person) {
    person.personalDetails.push(this.person);
  };
});

var personalDetails = [{
    forename: "John",
    surname: "Doe"
  },
  {
    forename: "John",
    surname: "Smith"
  }
];
</code>```

答:
You will need to find a way of sharing data between controllers.
One of the ways is using an angular service.

Check out this plunk!
https://plnkr.co/edit/oimKIgCDKknwsmSWbUsT?p=preview

script.js

```<code>var app = angular.module("file", []);

app.controller("PersonalDetailsController", function(PersonService) {
this.details = PersonService.personalDetails;
});

app.controller("DataEntryController", function(PersonService) {
this.person = {};

this.addPerson = function(person) {
    PersonService.personalDetails.push(this.person);
};
});

app.service("PersonService", function() {
this.personalDetails = [{
    forename: "John",
    surname: "Doe"
}, {
    forename: "John",
    surname: "Smith"
}];
});
</code>```

index.html

```<code><!DOCTYPE html>
<html lang="en" ng-app="file">

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
    <script types="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <script types="text/javascript " src="script.js"></script>

    <title>Title</title>
</head>

<body ng-controller="PersonalDetailsController as person ">
    ```
            {{person | json}}
        ```
    <p ng-repeat="info in person.details ">{{info.forename}}</p>

    <form name="PersonalDetailsForm " ng-controller="DataEntryController as dataCtrl " ng-submit="dataCtrl.addPerson(dataCtrl.person) ">
        ```
            {{dataCtrl.person | json}}
        ```

        <label>Forename:</label>
        <input ng-model="dataCtrl.person.forename " />
        <label>Surname:</label>
        <input ng-model="dataCtrl.person.surname " />
        <input type="submit " value="submit " />

    </form>

</body>

</html>
</code>```

Title: Form control with angular.js

Body:
I have been playing about with angular and forms but I am having some trouble with the code below. I thought that it should add forenames to the ones already displayed by the ng-repeat whenever the form is submitted but the submit button appears to do nothing.

HTML:

<!DOCTYPE html>

        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="bootstrap.min.css" />

        <title>Title</title>

{{info.forename}}

    <form name="PersonalDetailsForm" ng-controller="DataEntryController as dataCtrl" ng-submit="addPerson(person)">

{{dataCtrl.person.forename}}

{{dataCtrl.person.surname}}

        Forename:
        <input ng-model="dataCtrl.person.forename"/>
        Surname:
        <input ng-model="dataCtrl.person.surname"/>
        <input type="submit" value="submit"/>

    </form>

JS:

var app = angular.module("file", []);

app.controller("PersonalDetailsController", function() {
  this.details = personalDetails;
});

app.controller("DataEntryController", function() {
  this.person = {};
  this.addPerson = function(person) {
    person.personalDetails.push(this.person);
  };
});

var personalDetails = [{
    forename: "John",
    surname: "Doe"
  },
  {
    forename: "John",
    surname: "Smith"
  }
];

Body:
You will need to find a way of sharing data between controllers.
One of the ways is using an angular service.

Check out this plunk!
https://plnkr.co/edit/oimKIgCDKknwsmSWbUsT?p=preview

script.js

var app = angular.module("file", []);

app.controller("PersonalDetailsController", function(PersonService) {
this.details = PersonService.personalDetails;
});

app.controller("DataEntryController", function(PersonService) {
this.person = {};

this.addPerson = function(person) {
    PersonService.personalDetails.push(this.person);
};
});

app.service("PersonService", function() {
this.personalDetails = [{
    forename: "John",
    surname: "Doe"
}, {
    forename: "John",
    surname: "Smith"
}];
});

index.html

<!DOCTYPE html>
<html lang="en" ng-app="file">

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
    <script types="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <script types="text/javascript " src="script.js"></script>

    <title>Title</title>
</head>

<body ng-controller="PersonalDetailsController as person ">
    <pre>
            {{person | json}}
        </pre>
    <p ng-repeat="info in person.details ">{{info.forename}}</p>

    <form name="PersonalDetailsForm " ng-controller="DataEntryController as dataCtrl " ng-submit="dataCtrl.addPerson(dataCtrl.person) ">
        <pre>
            {{dataCtrl.person | json}}
        </pre>

        <label>Forename:</label>
        <input ng-model="dataCtrl.person.forename " />
        <label>Surname:</label>
        <input ng-model="dataCtrl.person.surname " />
        <input type="submit " value="submit " />

    </form>

</body>

</html>


问:
Backbone Marionette - How to render CompositeView->CollectionView->ItemView
I am trying to render an events section in my Marionette application. I've taken the approach o fusing a composite view containing my CollectionView.

I'm thinking that the CompositeView will render CollectionView and then the CollectionView will render my list of ItemViews (events).

Currently, the CompositeView renders the CollectionView, but no ItemViews are instantiated or rendering.

This is my first Marrionette application. I am using node for the dep. management. Gulp to build, browserify, and babel. I followed this project to get everything going so far: https://github.com/thejameskyle/marionette-wires

Your help is greatly appreciated!! Thank you!

CompositeView

```<code>import {
  CompositeView
} from 'backbone.marionette';
import {
  CollectionView
} from 'backbone.marionette';
import {
  Collection
} from 'backbone';
import template from './events-template.hbs';
import EventsService from '../services/events-service';
import EventsView from './events-view';
import EventModel from '../models/events-model';
import EventsCollection from '../collections/events-collection';
export default CompositeView.extend({
  template: template,
  className: 'col-md-3 calendar',
  childViewContainer: "ul",
  model:EventModel,

  regions: {
    events: '.events-list',
  },
  initialize: function(){
    let self = this;
    EventsService.find().then(collection => {
      self.collection = collection;
      console.log('Events CompositeView '+self.collection);
      self.childView = new EventsView({collection:self.collection});
    });
  },

  setup(options = {}) {
    this.container = options.container;
    console.log("setup");
  },

  modelsChanged() {
    console.log('Events ModelChanged' + this.model);
  }
});
</code>```

Events-Template.hbs

```<code><section class="panel">
  <div class="panel-body">
    <div class="monthly-stats pink">
      <div class="clearfix">
        <h4 class="pull-left">Calendar</h4>
        <!-- Nav tabs -->
        <div class="btn-group pull-right stat-tab">
          <a href="#line-chart" class="btn stat-btn active" data-toggle="tab">Week</a>
          <a href="#bar-chart" class="btn stat-btn" data-toggle="tab">Month</a>
        </div>
      </div>
    </div>
    <div class="events-list">

    </div>
  </div>
</section>
</code>```

CollectionView

```<code>import {
  CollectionView
} from 'backbone.marionette';
import {
  Collection
} from 'backbone';
import EventView from './event-view';
export default CollectionView.extend({
  tagName: 'ul',
  childView: EventView,
  childViewContainer: '.events-list',

  getChildView: function(item) {
    console.log('ChildView' +item);
  },

  initialize: function() {
    console.log('EVENTs CollectionView '+this.collection);
    for(let val of this.collection.models) {
      console.log(val.attributes);
    }
  },
  onBeforeRender: function() {
    console.log('Before EVENT CollectionView '+this.collection);
  },
  collectionEvents: {
    all: 'render'
  },
  childEvents: {
    // This callback will be called whenever a child is rendered or emits a `render` event
    render: function() {
      console.log('A child view has been rendered.');
    }
  }
});
</code>```

ItemView //All logging in the itemView is just to see if anything is being called. Which it is not.

```<code>import {
  ItemView
} from 'backbone.marionette';
import {
  Collection
} from 'backbone';
import template from './event-template.hbs';

export default ItemView.extend({
  template: template,
  tagName:'div',
  className: 'col-md-3',
  attributes() {

  },
    onShow: function() {
      console.log('Single EVENT');
    },
  initialize: function(o) {
    console.log('init itemView');
  },
  show() {
    console.log("ITEM");
  },
  modelEvents: {
    all: 'render'
  },
  onBeforeRender() {
    console.log("EVENZT VIEW");
  },
  render() {
    console.log("EVENZT VIEW");

  },
  modelsChanged() {
    console.log('Events ModelChanged' + this.model);

  }
});
</code>```

Event-Template.hbs

```<code> <div class="alert alert-info clearfix">
      <span class="alert-icon"><i class="fa fa-envelope-o"></i></span>
      <div class="notification-info">
        <ul class="clearfix notification-meta">
          <li class="pull-left notification-sender"><span><a href="#">{{eventName}}</a></span></li>
        </ul>
        <p>
          <span>{{program}}</span><span>
        </p>
      </div>
    </div>
</code>```

答:
As @J. Titus already commented on, you could use either CompositeView or CollectionView.

I'd recommend using CollectionView since you only need a region for displaying the list model views.

The thing about your collection is that you never populate it in your code. When you create a new collection it's empty unless you specifically pass an array of models. So you need to call .fetch() or .reset() (I recommend the latter for first-time use and for getting a lot of models all at once).

Since in your collectionEvents you're capturing all the events and render it, the view should update itself when the models have been loaded.

Body:
I am trying to render an events section in my Marionette application. I've taken the approach o fusing a composite view containing my CollectionView.

I'm thinking that the CompositeView will render CollectionView and then the CollectionView will render my list of ItemViews (events).

Currently, the CompositeView renders the CollectionView, but no ItemViews are instantiated or rendering.

This is my first Marrionette application. I am using node for the dep. management. Gulp to build, browserify, and babel. I followed this project to get everything going so far: https://github.com/thejameskyle/marionette-wires

Your help is greatly appreciated!! Thank you!

CompositeView

import {
  CompositeView
} from 'backbone.marionette';
import {
  CollectionView
} from 'backbone.marionette';
import {
  Collection
} from 'backbone';
import template from './events-template.hbs';
import EventsService from '../services/events-service';
import EventsView from './events-view';
import EventModel from '../models/events-model';
import EventsCollection from '../collections/events-collection';
export default CompositeView.extend({
  template: template,
  className: 'col-md-3 calendar',
  childViewContainer: "ul",
  model:EventModel,

  regions: {
    events: '.events-list',
  },
  initialize: function(){
    let self = this;
    EventsService.find().then(collection => {
      self.collection = collection;
      console.log('Events CompositeView '+self.collection);
      self.childView = new EventsView({collection:self.collection});
    });
  },

  setup(options = {}) {
    this.container = options.container;
    console.log("setup");
  },

  modelsChanged() {
    console.log('Events ModelChanged' + this.model);
  }
});

Events-Template.hbs

Calendar

          Week
          Month

CollectionView

import {
  CollectionView
} from 'backbone.marionette';
import {
  Collection
} from 'backbone';
import EventView from './event-view';
export default CollectionView.extend({
  tagName: 'ul',
  childView: EventView,
  childViewContainer: '.events-list',

  getChildView: function(item) {
    console.log('ChildView' +item);
  },

  initialize: function() {
    console.log('EVENTs CollectionView '+this.collection);
    for(let val of this.collection.models) {
      console.log(val.attributes);
    }
  },
  onBeforeRender: function() {
    console.log('Before EVENT CollectionView '+this.collection);
  },
  collectionEvents: {
    all: 'render'
  },
  childEvents: {
    // This callback will be called whenever a child is rendered or emits a `render` event
    render: function() {
      console.log('A child view has been rendered.');
    }
  }
});

ItemView //All logging in the itemView is just to see if anything is being called. Which it is not.

import {
  ItemView
} from 'backbone.marionette';
import {
  Collection
} from 'backbone';
import template from './event-template.hbs';

export default ItemView.extend({
  template: template,
  tagName:'div',
  className: 'col-md-3',
  attributes() {

  },
    onShow: function() {
      console.log('Single EVENT');
    },
  initialize: function(o) {
    console.log('init itemView');
  },
  show() {
    console.log("ITEM");
  },
  modelEvents: {
    all: 'render'
  },
  onBeforeRender() {
    console.log("EVENZT VIEW");
  },
  render() {
    console.log("EVENZT VIEW");

  },
  modelsChanged() {
    console.log('Events ModelChanged' + this.model);

  }
});

Event-Template.hbs

{{eventName}}

          {{program}}


问:
Specifying Multiple targets for regression in TFLearn
How to specify multiple target_column in tflearn.data_utils.load_csv method.

According to Tflearn docs load_csv takes target_column as integer.

Tried passing my target_columns as a list in the load_csv method and as expected got a TypeError: 'list' object cannot be interpreted as an integer traceback.

Any solutions for this.
Thanks

答: That's not how regression works. You must have only one column as a target. That's why the tensorflow API only allows one column to be the target of regression, specified with an integer.


问:
making a query using COUNT
I want to have one table with many tables.
Before I put the Count(taskid), it works well.

```<code>private DataTable GetData() //get any data
{
    string connString = @"Data Source=aa.net;Initial Catalog=db_c;Persist Security Info=True;User ID=db_c_ExternalWriter;Password=aa";
    string query = "Select a.Name, b.Restaurant,  a.City, c.[Postal Code], a.[Open Date], a.POSSystem FROM Stores a, tblConcepts b, tblStates c WHERE a.ConceptID = b.Restaurantid AND  a.State = c.Stateid AND a.[Open Date] >= cast(cast(getdate() as date) as datetime";
   // string query2 = "SELECT Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' GROUP BY StoreID";
    using (SqlConnection con = new SqlConnection(connString))
    {
        using (SqlCommand comm = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                comm.Connection = con;
                sda.SelectCommand = comm;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }
}
</code>```

But when I add Count(taskid) it doesn't work.
 SELECT Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' GROUP BY StoreID; I want to add these queries, any ideas?

```<code>private DataTable GetData() //get any data
{
    string connString = @"Data Source=aa.net;Initial Catalog=db_c;Persist Security Info=True;User ID=db_c_ExternalWriter;Password=aa";
    string query = "Select a.Name, b.Restaurant,  a.City, c.[Postal Code], a.[Open Date], a.POSSystem, d.Count(Taskid) FROM Stores a, tblConcepts b, tblStates c, tblAssignedTasks d WHERE a.ConceptID = b.Restaurantid AND  a.State = c.Stateid AND a.[Open Date] >= cast(cast(getdate() as date) as datetime AND b.Restaurantid = d.StoreID AND  d.Complete = 'True' GROUP BY d.StoreID)";
   // string query2 = "SELECT Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' GROUP BY StoreID";
    using (SqlConnection con = new SqlConnection(connString))
    {
        using (SqlCommand comm = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                comm.Connection = con;
                sda.SelectCommand = comm;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }
}
</code>```

答:
Replace your sql Query with the below query,Hope it works fine.</p>

```<code>string query = "Select COUNT(Taskid) OVER() Taskid, a.Name, b.Restaurant,  a.City, c.[Postal Code], a.[Open Date], a.POSSystem, d.Count(Taskid) FROM Stores a, tblConcepts b, tblStates c, tblAssignedTasks d WHERE a.ConceptID = b.Restaurantid AND a.State = c.Stateid AND a.[Open Date] >= cast(cast(getdate() as date) as datetime AND b.Restaurantid = d.StoreID AND  d.Complete = 'True' GROUP BY d.StoreID)";
</code>```

Title: making a query using COUNT

Body:
I want to have one table with many tables.
Before I put the Count(taskid), it works well.

private DataTable GetData() //get any data
{
    string connString = @"Data Source=aa.net;Initial Catalog=db_c;Persist Security Info=True;User ID=db_c_ExternalWriter;Password=aa";
    string query = "Select a.Name, b.Restaurant,  a.City, c.[Postal Code], a.[Open Date], a.POSSystem FROM Stores a, tblConcepts b, tblStates c WHERE a.ConceptID = b.Restaurantid AND  a.State = c.Stateid AND a.[Open Date] >= cast(cast(getdate() as date) as datetime";
   // string query2 = "SELECT Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' GROUP BY StoreID";
    using (SqlConnection con = new SqlConnection(connString))
    {
        using (SqlCommand comm = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                comm.Connection = con;
                sda.SelectCommand = comm;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }
}

But when I add Count(taskid) it doesn't work.
 SELECT Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' GROUP BY StoreID; I want to add these queries, any ideas?

private DataTable GetData() //get any data
{
    string connString = @"Data Source=aa.net;Initial Catalog=db_c;Persist Security Info=True;User ID=db_c_ExternalWriter;Password=aa";
    string query = "Select a.Name, b.Restaurant,  a.City, c.[Postal Code], a.[Open Date], a.POSSystem, d.Count(Taskid) FROM Stores a, tblConcepts b, tblStates c, tblAssignedTasks d WHERE a.ConceptID = b.Restaurantid AND  a.State = c.Stateid AND a.[Open Date] >= cast(cast(getdate() as date) as datetime AND b.Restaurantid = d.StoreID AND  d.Complete = 'True' GROUP BY d.StoreID)";
   // string query2 = "SELECT Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' GROUP BY StoreID";
    using (SqlConnection con = new SqlConnection(connString))
    {
        using (SqlCommand comm = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                comm.Connection = con;
                sda.SelectCommand = comm;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }
}

Body:
Replace your sql Query with the below query,Hope it works fine.

string query = "Select COUNT(Taskid) OVER() Taskid, a.Name, b.Restaurant,  a.City, c.[Postal Code], a.[Open Date], a.POSSystem, d.Count(Taskid) FROM Stores a, tblConcepts b, tblStates c, tblAssignedTasks d WHERE a.ConceptID = b.Restaurantid AND a.State = c.Stateid AND a.[Open Date] >= cast(cast(getdate() as date) as datetime AND b.Restaurantid = d.StoreID AND  d.Complete = 'True' GROUP BY d.StoreID)";


问:
Group array of javascript objects based on value into there own sub array of objects
I have an array of Javascript objects like below.

```<code>        [{

            "email": "alex@test.com",
            "fn": "Alex",
            "sn": "McPherson",
            "phone": "01233xxxxx",
            "hours": "40",
            "rate": "20",
            "amount": "200",
            "vat": "60",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "mike@test.com",
            "fn": "Mike",
            "sn": "Mann",
            "phone": "01233xxxxx",
            "hours": "50",
            "rate": "70",
            "amount": "500",
            "vat": "90",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "fred@test.com",
            "fn": "Fred",
            "sn": "Frogg",
            "phone": "01233xxxxx",
            "hours": "80",
            "rate": "90",
            "amount": "800",
            "vat": "100",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "alex@test.com",
            "fn": "Alex",
            "sn": "McPherson",
            "phone": "01233xxxxx",
            "hours": "90",
            "rate": "30",
            "amount": "900",
            "vat": "120",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        }]
</code>```

What I ideally want is to group those of the same value (email) into there own sub array of objects i.e if you look at the array above you will see I have 2 entries for the same person Alex McPherson. What I want to do is the below if possible move and combine into a sub array and the same for any other value that exists more than once.

```<code>    [[{

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "40",
        "rate": "20",
        "amount": "200",
        "vat": "60",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    },{

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "90",
        "rate": "30",
        "amount": "900",
        "vat": "120",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }],
    [{

        "email": "mike@test.com",
        "fn": "Mike",
        "sn": "Mann",
        "phone": "01233xxxxx",
        "hours": "50",
        "rate": "70",
        "amount": "500",
        "vat": "90",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }],
    [{

        "email": "fred@test.com",
        "fn": "Fred",
        "sn": "Frogg",
        "phone": "01233xxxxx",
        "hours": "80",
        "rate": "90",
        "amount": "800",
        "vat": "100",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }]]
</code>```

I can't seem to get my head around resorting the array.

答:
You could use a closure over a hash table for the same email address and their items.

var data = [{ email: "alex@test.com", fn: "Alex", sn: "McPherson", phone: "01233xxxxx", hours: "40", rate: "20", amount: "200", vat: "60", agency: "test", start: "08/06/2017", end: "10/06/2017" }, { email: "mike@test.com", fn: "Mike", sn: "Mann", phone: "01233xxxxx", hours: "50", rate: "70", amount: "500", vat: "90", agency: "test", start: "08/06/2017", end: "10/06/2017" }, { email: "fred@test.com", fn: "Fred", sn: "Frogg", phone: "01233xxxxx", hours: "80", rate: "90", amount: "800", vat: "100", agency: "test", start: "08/06/2017", end: "10/06/2017" }, { email: "alex@test.com", fn: "Alex", sn: "McPherson", phone: "01233xxxxx", hours: "90", rate: "30", amount: "900", vat: "120", agency: "test", start: "08/06/2017", end: "10/06/2017" }],
    result = data.reduce(function (hash) {
        return function (r, o) {
            if (!hash[o.email]) {
                hash[o.email] = [];
                r.push(hash[o.email]);
            }
            hash[o.email].push(o)
            return r;
        };
    }(Object.create(null)), []);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have an array of Javascript objects like below.

        [{

            "email": "alex@test.com",
            "fn": "Alex",
            "sn": "McPherson",
            "phone": "01233xxxxx",
            "hours": "40",
            "rate": "20",
            "amount": "200",
            "vat": "60",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "mike@test.com",
            "fn": "Mike",
            "sn": "Mann",
            "phone": "01233xxxxx",
            "hours": "50",
            "rate": "70",
            "amount": "500",
            "vat": "90",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "fred@test.com",
            "fn": "Fred",
            "sn": "Frogg",
            "phone": "01233xxxxx",
            "hours": "80",
            "rate": "90",
            "amount": "800",
            "vat": "100",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "alex@test.com",
            "fn": "Alex",
            "sn": "McPherson",
            "phone": "01233xxxxx",
            "hours": "90",
            "rate": "30",
            "amount": "900",
            "vat": "120",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        }]

What I ideally want is to group those of the same value (email) into there own sub array of objects i.e if you look at the array above you will see I have 2 entries for the same person Alex McPherson. What I want to do is the below if possible move and combine into a sub array and the same for any other value that exists more than once.

    [[{

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "40",
        "rate": "20",
        "amount": "200",
        "vat": "60",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    },{

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "90",
        "rate": "30",
        "amount": "900",
        "vat": "120",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }],
    [{

        "email": "mike@test.com",
        "fn": "Mike",
        "sn": "Mann",
        "phone": "01233xxxxx",
        "hours": "50",
        "rate": "70",
        "amount": "500",
        "vat": "90",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }],
    [{

        "email": "fred@test.com",
        "fn": "Fred",
        "sn": "Frogg",
        "phone": "01233xxxxx",
        "hours": "80",
        "rate": "90",
        "amount": "800",
        "vat": "100",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }]]

I can't seem to get my head around resorting the array.

Body:
You could use a closure over a hash table for the same email address and their items.

var data = [{ email: "alex@test.com", fn: "Alex", sn: "McPherson", phone: "01233xxxxx", hours: "40", rate: "20", amount: "200", vat: "60", agency: "test", start: "08/06/2017", end: "10/06/2017" }, { email: "mike@test.com", fn: "Mike", sn: "Mann", phone: "01233xxxxx", hours: "50", rate: "70", amount: "500", vat: "90", agency: "test", start: "08/06/2017", end: "10/06/2017" }, { email: "fred@test.com", fn: "Fred", sn: "Frogg", phone: "01233xxxxx", hours: "80", rate: "90", amount: "800", vat: "100", agency: "test", start: "08/06/2017", end: "10/06/2017" }, { email: "alex@test.com", fn: "Alex", sn: "McPherson", phone: "01233xxxxx", hours: "90", rate: "30", amount: "900", vat: "120", agency: "test", start: "08/06/2017", end: "10/06/2017" }],
    result = data.reduce(function (hash) {
        return function (r, o) {
            if (!hash[o.email]) {
                hash[o.email] = [];
                r.push(hash[o.email]);
            }
            hash[o.email].push(o)
            return r;
        };
    }(Object.create(null)), []);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
AS3: How do I set a value of a class and prevent it from being changed?
Solution found thanks to everyone's answers. Check bottom of this post.

I am using MVC and the problem concerns my model. With my code I am creating a board which in turn creates tiles. Every tile on the board gets an X and a Y value. After this I want to prevent access to the setter to prevent myself from accidentally changing the value ever again.

I was thinking of using a constant instead of a variable, but it seems I have to define the value at the time of creation. In other words: const myConst:uint; myConst = 2; // does not work

Right now I have a work-around which I am not happy with. Surely there's a cleaner way. You can see my work-around below.

```<code>package myboardgame
{
 internal class Tile
 {
  private var _x:uint;
  private var _y:uint;

  private var _xLock:Boolean; // Makes sure that the X and Y values of a tile can only be set once to prevent errors
  private var _yLock:Boolean; //  " "

  internal function set x(x:uint):void
  { if(!_xLock) {_x = x; _xLock = true;} else { throw new Error("Trying to change the one-time write access X tile value")}}
  internal function get x():uint
  { return _x; }
 }
}
</code>```

Edit. The solution I went with:

```<code>package myboardgame
{
    internal class Tile
{
    private var _x:uint;
    private var _y:uint;

    public function Tile(x:uint, y:uint):void
    {
        _x = x;
        _y = y;
    }
    internal function get x():uint
    { return _x; }

    internal function get y():uint
    { return _y; }
}
}
</code>```

答:
I would use parameters in a constructor like this:

```<code>var Tile : Tile = new Tile(3,6);
</code>```

Or If you need a setter:

```<code>package
{
  public class Tile
  {
    private var _x : uint;
    private var _isSetX : Boolean;
    private var _y : uint;
    private var _isSetY : Boolean;

    public function set x(value : uint)
    {
      if (_isSetX)
        return;

      _x = value;

    }

   .......

  }
}
</code>```

Body:
Solution found thanks to everyone's answers. Check bottom of this post.

I am using MVC and the problem concerns my model. With my code I am creating a board which in turn creates tiles. Every tile on the board gets an X and a Y value. After this I want to prevent access to the setter to prevent myself from accidentally changing the value ever again.

I was thinking of using a constant instead of a variable, but it seems I have to define the value at the time of creation. In other words: const myConst:uint; myConst = 2; // does not work

Right now I have a work-around which I am not happy with. Surely there's a cleaner way. You can see my work-around below.

package myboardgame
{
 internal class Tile
 {
  private var _x:uint;
  private var _y:uint;

  private var _xLock:Boolean; // Makes sure that the X and Y values of a tile can only be set once to prevent errors
  private var _yLock:Boolean; //  " "

  internal function set x(x:uint):void
  { if(!_xLock) {_x = x; _xLock = true;} else { throw new Error("Trying to change the one-time write access X tile value")}}
  internal function get x():uint
  { return _x; }
 }
}

Edit. The solution I went with:

package myboardgame
{
    internal class Tile
{
    private var _x:uint;
    private var _y:uint;

    public function Tile(x:uint, y:uint):void
    {
        _x = x;
        _y = y;
    }
    internal function get x():uint
    { return _x; }

    internal function get y():uint
    { return _y; }
}
}

Body:
I would use parameters in a constructor like this:

var Tile : Tile = new Tile(3,6);

Or If you need a setter:

package
{
  public class Tile
  {
    private var _x : uint;
    private var _isSetX : Boolean;
    private var _y : uint;
    private var _isSetY : Boolean;

    public function set x(value : uint)
    {
      if (_isSetX)
        return;

      _x = value;

    }

   .......

  }
}


问:
Primefaces/jsf Media Tag to Play WebM Files in chrome browser
I would like to know what type of settings are required to play .webm media files using the PrimeFaces  tag.
My code looks like the following:

This works when I try to open the page in Microsoft Internet Explorer, but I am not able to see the video in Google Chrome.
I am looking for a way to embed videos using PrimeFaces that does not involve plugins.

My code looks like the following:

```<code><p:media style="margin: auto; display: block" id="part1Video"
rendered="true" player="windows" width="600" height="400"
value="C:\...\Part1_Intro_(new).webm"/>
</code>```

答:
I hope you meant the file is on the server, because I know no cases where the server need to play a video that exist in the client's own computer to the client itself.

Anyway you could try making a servlet to stream your webm

```<code>@WebServlet(name = "WebmViewer", urlPatterns = {"/WebmViewer"})
public class WebmViewer extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String path = request.getParameter("path");
            Path p = Paths.get(path);
            byte[] webmbytes = Files.readAllBytes(p);
            response.setContentType("video/webm");
            response.getOutputStream().write(webmbytes);
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
</code>```

The url would be something like

```<code>http://localhost:8080/WebApp/WebmViewer?path=F:\java\mp3\Loop.webm
</code>```

Then use quicktime to play it

```<code><p:media value="WebmViewer?path=F:\java\mp3\Loop.webm" player="quicktime"/>
</code>```

Body:
I hope you meant the file is on the server, because I know no cases where the server need to play a video that exist in the client's own computer to the client itself.

Anyway you could try making a servlet to stream your webm

@WebServlet(name = "WebmViewer", urlPatterns = {"/WebmViewer"})
public class WebmViewer extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String path = request.getParameter("path");
            Path p = Paths.get(path);
            byte[] webmbytes = Files.readAllBytes(p);
            response.setContentType("video/webm");
            response.getOutputStream().write(webmbytes);
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

The url would be something like

http://localhost:8080/WebApp/WebmViewer?path=F:\java\mp3\Loop.webm

Then use quicktime to play it

<p:media value="WebmViewer?path=F:\java\mp3\Loop.webm" player="quicktime"/>


问:
Java libraries for converting between character encodings
The problem I am looking to solve is converting between unicode storage types. As I understand it, one character in UTF-8 can be represented by 1 to 4 bytes of data whereas a character in UTF-16 can be represented in 1-2, two bytes blocks of data. This variable length means it's a pain to convert between the two and produce something that is sensible in the english language. </p>

<p>What I am looking for is a library that would let me specify a language or locale, and a storage mechanism (utf-8 etc.) and have it produce a more sensible result. Am I dreaming in the clouds?  </p>

答:
You can convert bytes in one encoding to a Java String via the constructor String(byte[], Charset). Supported character sets are listed in java.nio.charset.Charset.

You can then convert back to bytes with a different encoding with String.getBytes(CharSet).

For example:

```<code>byte[] bytesIn = ...;
String s = new String( bytesIn, Charset.forName( "UTF-8" );
byte[] bytesOut = s.getBytes( Charset.forName( "UTF-16" ))
</code>```

Body:
The problem I am looking to solve is converting between unicode storage types. As I understand it, one character in UTF-8 can be represented by 1 to 4 bytes of data whereas a character in UTF-16 can be represented in 1-2, two bytes blocks of data. This variable length means it's a pain to convert between the two and produce something that is sensible in the english language.

What I am looking for is a library that would let me specify a language or locale, and a storage mechanism (utf-8 etc.) and have it produce a more sensible result. Am I dreaming in the clouds?

Body:
You can convert bytes in one encoding to a Java String via the constructor String(byte[], Charset). Supported character sets are listed in java.nio.charset.Charset.

You can then convert back to bytes with a different encoding with String.getBytes(CharSet).

For example:

byte[] bytesIn = ...;
String s = new String( bytesIn, Charset.forName( "UTF-8" );
byte[] bytesOut = s.getBytes( Charset.forName( "UTF-16" ))


问:
My counter counts up instead of down
My counter is counting up instead of down? I like it to count down from 10 minutes and when hours is 0 and minutes is 0 and seconds is 0 I want it to remove the counter and it should go to another frame using gotoAndStop(2).</p>

```<code>var countdownTimer:Timer = new Timer(1000);

countdownTimer.addEventListener(TimerEvent.TIMER, updateTime);

countdownTimer.start();

var startTime:int = getTimer();

function updateTime(e:TimerEvent):void

{

// milliseconds passed
var timePassed:int = getTimer()-startTime;
var seconds:Number = Math.floor(timePassed / 1000);
var minutes:Number = Math.floor(seconds / 60);
var hours:Number = Math.floor(minutes / 60);

seconds %= 60;
minutes %= 60;
hours %= 24;

var sec:String = seconds.toString();
var min:String = minutes.toString();
var hrs:String = hours.toString();

if (sec.length < 2) {
    sec = "0" + sec;
}

//A zero will automatic be put to the right side og 1, so "1" will be "10"

if (min.length < 2) {
    min = "1" + min;
}

if (hrs.length < 2) {
    hrs = "0" + hrs;
}

var time:String = hrs + ":" + min + ":" + sec;

time_txt.text = time;
</code>```

答:
Like Organis said :) You need to substract the time passed from your 10 minutes.</p>

```<code>private var TOTAL_TIME:int = 10 * 60 * 1000; // 10 minutes or 600000 milliseconds

var timePassed:int = getTimer()-startTime;
var timeLeft:int = TOTAL_TIME - timePassed;

// use timeLeft for the display, not timePassed
var seconds:Number = Math.floor(timeLeft / 1000);
</code>```

Title: My counter counts up instead of down

Body:
My counter is counting up instead of down? I like it to count down from 10 minutes and when hours is 0 and minutes is 0 and seconds is 0 I want it to remove the counter and it should go to another frame using gotoAndStop(2).

var countdownTimer:Timer = new Timer(1000);

countdownTimer.addEventListener(TimerEvent.TIMER, updateTime);

countdownTimer.start();

var startTime:int = getTimer();

function updateTime(e:TimerEvent):void

{

// milliseconds passed
var timePassed:int = getTimer()-startTime;
var seconds:Number = Math.floor(timePassed / 1000);
var minutes:Number = Math.floor(seconds / 60);
var hours:Number = Math.floor(minutes / 60);

seconds %= 60;
minutes %= 60;
hours %= 24;

var sec:String = seconds.toString();
var min:String = minutes.toString();
var hrs:String = hours.toString();

if (sec.length < 2) {
    sec = "0" + sec;
}

//A zero will automatic be put to the right side og 1, so "1" will be "10"

if (min.length < 2) {
    min = "1" + min;
}

if (hrs.length < 2) {
    hrs = "0" + hrs;
}

var time:String = hrs + ":" + min + ":" + sec;

time_txt.text = time;

Body:
Like Organis said :) You need to substract the time passed from your 10 minutes.

private var TOTAL_TIME:int = 10 * 60 * 1000; // 10 minutes or 600000 milliseconds

var timePassed:int = getTimer()-startTime;
var timeLeft:int = TOTAL_TIME - timePassed;

// use timeLeft for the display, not timePassed
var seconds:Number = Math.floor(timeLeft / 1000);