问:
Position transition not working in Edge
So i have an animation on an element, which changes background-color, and changes the bottom position from vertical center of parent to bottom.

I just did a test in Edge, and the background is working fine but the bottom transition isnt. It just changes instantly.

I do realize translate would probably work, but i'm interested in knowing wether positioning as in top, right, bottom, left does not work with transitions in Microsoft browsers? It works perfectly fine in Firefox, Chrome and Safari.

My CSS is shown below.

```<code>.heading-bg{
    display: table;
    width: 100%;
    margin-left: auto;
    margin-right: auto;
    position: absolute;
    bottom: calc(50% - 30px);

    -webkit-transition: bottom .5s ease-out, background-color .4s ease-out;
    -moz-transition: bottom .5s ease-out, background-color .4s ease-out;
    -ms-transition: bottom .5s ease-out, background-color .4s ease-out;
    -o-transition: bottom .5s ease-out, background-color .4s ease-out;
    transition: bottom .5s ease-out, background-color .4s ease-out;
}

.gallery-item:hover .heading-bg{
    bottom: 0px;
    background-color: rgba(0,0,0,0.7);

    -webkit-transition: bottom .6s ease-out, background-color .4s ease-out;
    -moz-transition: bottom .6s ease-out, background-color .4s ease-out;
    -ms-transition: bottom .6s ease-out, background-color .4s ease-out;
    -o-transition: bottom .6s ease-out, background-color .4s ease-out;
    transition: bottom .6s ease-out, background-color .4s ease-out;
}
</code>```

Markup:

```<code><div class="gallery-item">
    <a href="www.example.com">
        <div class="gallery-item-inner">
            <div class="heading-bg">
                <h3>Gallery name</h3>
            </div>
        </div>
    </a>
</div>
</code>```

.gallery-item has a  fixed height

答:
I had the same problem and managed to figure out what's wrong by comparing both our code.

Here's the part that Edge doesn't like:

```<code>bottom: calc(50% - 30px);
</code>```

It appears that Edge currently (EdgeHTML v14.14393) doesn't support transitions when used in conjunction with calc().

Title: Position transition not working in Edge

Body:
So i have an animation on an element, which changes background-color, and changes the bottom position from vertical center of parent to bottom.

I just did a test in Edge, and the background is working fine but the bottom transition isnt. It just changes instantly.

I do realize translate would probably work, but i'm interested in knowing wether positioning as in top, right, bottom, left does not work with transitions in Microsoft browsers? It works perfectly fine in Firefox, Chrome and Safari.

My CSS is shown below.

.heading-bg{
    display: table;
    width: 100%;
    margin-left: auto;
    margin-right: auto;
    position: absolute;
    bottom: calc(50% - 30px);

    -webkit-transition: bottom .5s ease-out, background-color .4s ease-out;
    -moz-transition: bottom .5s ease-out, background-color .4s ease-out;
    -ms-transition: bottom .5s ease-out, background-color .4s ease-out;
    -o-transition: bottom .5s ease-out, background-color .4s ease-out;
    transition: bottom .5s ease-out, background-color .4s ease-out;
}

.gallery-item:hover .heading-bg{
    bottom: 0px;
    background-color: rgba(0,0,0,0.7);

    -webkit-transition: bottom .6s ease-out, background-color .4s ease-out;
    -moz-transition: bottom .6s ease-out, background-color .4s ease-out;
    -ms-transition: bottom .6s ease-out, background-color .4s ease-out;
    -o-transition: bottom .6s ease-out, background-color .4s ease-out;
    transition: bottom .6s ease-out, background-color .4s ease-out;
}

Markup:

Gallery name

.gallery-item has a  fixed height

Body:
I had the same problem and managed to figure out what's wrong by comparing both our code.

Here's the part that Edge doesn't like:

bottom: calc(50% - 30px);

It appears that Edge currently (EdgeHTML v14.14393) doesn't support transitions when used in conjunction with calc().


来源: stackexchange

问:
PHP/Laravel Select text in brackets after certain number
We have a field in a database (of a Laravel 5.4 site) that has cells with data like this:

```<code>"123(Description of 123) 124(Description of 124) 125(Description of 125)"
</code>```

All in one long string. I need to output the bracketed text but only of the specified number. For example, pass the number 123 as a parameter and Description of 123 is returned.

I have the regex pattern to use with preg_match that extracts the data from the brackets:

```<code>$sTest = "247(text goes here)248(more here)";
preg_match("/\(([^\)]*)\)/", $sTest, $aMatches);
$sResult = $aMatches[1];
</code>```

But I don't know how to instruct PHP to read the specific brackets after a certain number.

Does anyone have any suggestions please?
Many thanks in advance!

答:
While redesigning the DB might look like a fix, a current work around is to pass the ID of the bracketed data as part of the regex pattern.

Consider this snippet:

```<code>$id = 248;
$sTest = "247(text goes here)248(more here)";
preg_match("/\b" . $id . "\(([^\)]*)\)/", $sTest, $aMatches);
$sResult = $aMatches[1];
echo $sResult;
</code>```

Here, \b is a word boundary to match a number as a whole word (so as not to match 1 in 21) and $id becomes part of the pattern (but since you only get the contents of the first capturing group with $aMatches[1], it is only used as context, and not part of  the extraction).

ContentLicense: CC BY-SA 3.0

Body:
We have a field in a database (of a Laravel 5.4 site) that has cells with data like this:

"123(Description of 123) 124(Description of 124) 125(Description of 125)"

All in one long string. I need to output the bracketed text but only of the specified number. For example, pass the number 123 as a parameter and Description of 123 is returned.

I have the regex pattern to use with preg_match that extracts the data from the brackets:

$sTest = "247(text goes here)248(more here)";
preg_match("/\(([^\)]*)\)/", $sTest, $aMatches);
$sResult = $aMatches[1];

But I don't know how to instruct PHP to read the specific brackets after a certain number.

Does anyone have any suggestions please?
Many thanks in advance!

Body:
While redesigning the DB might look like a fix, a current work around is to pass the ID of the bracketed data as part of the regex pattern.

Consider this snippet:

$id = 248;
$sTest = "247(text goes here)248(more here)";
preg_match("/\b" . $id . "\(([^\)]*)\)/", $sTest, $aMatches);
$sResult = $aMatches[1];
echo $sResult;

Here, \b is a word boundary to match a number as a whole word (so as not to match 1 in 21) and $id becomes part of the pattern (but since you only get the contents of the first capturing group with $aMatches[1], it is only used as context, and not part of  the extraction).


问:
CollectionView sizeForItemAtIndexPath never called
This is driving me crazy! I have a UICollectionViewController as shown below:

```<code>class PhrasesCompactCollectionViewController: UICollectionViewController
</code>```

The numberOfSections and cellForItemAt are being called but the sizeForItemAtIndexPath is never called. I am using the same exact code somewhere else and it fires correctly. I am using Xcode 8 Beta 6.

```<code>func collectionView(collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAtIndexPath indexPath:  NSIndexPath) -> CGSize {
    return CGSize(width: 120, height:120)
}
</code>```

答:
Swift 3

To set Cell Size of UICollectionView, you need to create and customise object of UICollectionViewFlowLayout. Customise the properties and set that layout object to the UICollectionView object.

Change cellheight and cell cellWidth objects according to your requirement (the cell hight and width you want).

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    let cellWidth : CGFloat = myCollectionView.frame.size.width / 4.0
    let cellheight : CGFloat = myCollectionView.frame.size.height - 2.0
    let cellSize = CGSize(width: cellWidth , height:cellheight)

    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .vertical //.horizontal
    layout.itemSize = cellSize
    layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
    layout.minimumLineSpacing = 1.0
    layout.minimumInteritemSpacing = 1.0
    myCollectionView.setCollectionViewLayout(layout, animated: true)

    myCollectionView.reloadData()
}
</code>```

Make Sure: if you added sizeForItemAt indexPath method then must REMOVE  the method...

Remove Below Method

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is driving me crazy! I have a UICollectionViewController as shown below:

class PhrasesCompactCollectionViewController: UICollectionViewController

The numberOfSections and cellForItemAt are being called but the sizeForItemAtIndexPath is never called. I am using the same exact code somewhere else and it fires correctly. I am using Xcode 8 Beta 6.

func collectionView(collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAtIndexPath indexPath:  NSIndexPath) -> CGSize {
    return CGSize(width: 120, height:120)
}

Body:
Swift 3

To set Cell Size of UICollectionView, you need to create and customise object of UICollectionViewFlowLayout. Customise the properties and set that layout object to the UICollectionView object.

Change cellheight and cell cellWidth objects according to your requirement (the cell hight and width you want).

override func viewDidLoad() {
    super.viewDidLoad()

    let cellWidth : CGFloat = myCollectionView.frame.size.width / 4.0
    let cellheight : CGFloat = myCollectionView.frame.size.height - 2.0
    let cellSize = CGSize(width: cellWidth , height:cellheight)

    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .vertical //.horizontal
    layout.itemSize = cellSize
    layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
    layout.minimumLineSpacing = 1.0
    layout.minimumInteritemSpacing = 1.0
    myCollectionView.setCollectionViewLayout(layout, animated: true)

    myCollectionView.reloadData()
}

Make Sure: if you added sizeForItemAt indexPath method then must REMOVE  the method...

Remove Below Method

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

}


问:
Contact form with MySQL sends Email when form is filled in
Im trying to make a contact form on my private portfolio site. The link between the contact form and the database is made. But now I would like to receive a Mail notification when someone sends in a filled in form.

thanks in advance

答:
You can simply use this:</p>

```<code>mail($to,$subject,$message,$headers);
</code>```

Body:
You can simply use this:

mail($to,$subject,$message,$headers);


问:
Insert date in a empty column of a file delimited with "|"
I have a file with four columns delimited by "|" as below

```<code>23414|test doc for me||
32322|test doc for you|2004_12_03|
13454|test doc for all||2010_11_01
</code>```

i am trying to insert current system date to the empty column's so that output should looks like as

```<code>23414|test doc for me|2018_04_03|2018_04_03
32322|test doc for you|2004_12_03|2018_04_03
13454|test doc for all|2018_04_03|2010_11_01
</code>```

below is the code which i am tried

```<code>for file in `ls -rlt Added_to_* | awk '{print $9}'`
do
now="$(date +'%Y/%m/%d')"
echo "Running for: $file"
awk -F'|' -v curr="$now" '{
if( $3=="" || $4=="" ){
     if ( $3=="" ) { print "$curr"}
     if ( $4=="" ) { print "$curr"}
}else
     do_something ;
}' $file
done
</code>```

答:
@hemu:@try:

```<code>awk -F"|" -v DATE=$(date +%Y"-"%m"-"%d) '!$3{$3=DATE} !$4{$4=DATE} 1' OFS="|"  Input_file
</code>```

Simply mentioning the field separator as | then creating a awk's variable which has a shell date command which gives values in YYYY-MM-DD formats. Then in awk I am checking if 3rd or 4th field is empty then making their values as DATE's value then mentioning 1 here will print the current(newly formed with value of $4 or $3 if they have been assigned with new values) line.

Body:
I have a file with four columns delimited by "|" as below

23414|test doc for me||
32322|test doc for you|2004_12_03|
13454|test doc for all||2010_11_01

i am trying to insert current system date to the empty column's so that output should looks like as

23414|test doc for me|2018_04_03|2018_04_03
32322|test doc for you|2004_12_03|2018_04_03
13454|test doc for all|2018_04_03|2010_11_01

below is the code which i am tried

for file in `ls -rlt Added_to_* | awk '{print $9}'`
do
now="$(date +'%Y/%m/%d')"
echo "Running for: $file"
awk -F'|' -v curr="$now" '{
if( $3=="" || $4=="" ){
     if ( $3=="" ) { print "$curr"}
     if ( $4=="" ) { print "$curr"}
}else
     do_something ;
}' $file
done

Body:
@hemu:@try:

awk -F"|" -v DATE=$(date +%Y"-"%m"-"%d) '!$3{$3=DATE} !$4{$4=DATE} 1' OFS="|"  Input_file

Simply mentioning the field separator as | then creating a awk's variable which has a shell date command which gives values in YYYY-MM-DD formats. Then in awk I am checking if 3rd or 4th field is empty then making their values as DATE's value then mentioning 1 here will print the current(newly formed with value of $4 or $3 if they have been assigned with new values) line.


问:
Is there an alternate/better way to do this simple logic in java?
I have a method, say method1(), that takes a while to run. During it's execution, if there is another call to method1(), it should be ignored. I have, roughly, something like this

```<code>    boolean mFlag = false;

    void method1()
    {
        if(!mFlag)
        {
           mFlag=true;

           // do Stuff

          mFlag=false;
        }
    }
</code>```

This works. But I was wondering if there is a better way to do this preferably not involving any flags.

答:
Are you trying to guard against re-entry from the same thread or multiple threads accessing at the same time.

Assuming multi-threaded access, the light approach is to use java.util.concurrent.atomic. No  need for anything as "heavy" as a lock (provided there are not further requirements).

Assuming no-reentry from the same method:

```<code>private final AtomicBoolean inMethod = new AtomicBoolean();

void method1() {
    if (inMethod.compareAndSet(true, false)) { // Alternatively getAndSet
        try {
            // do Stuff
        } finally {
            inMethod.set(false); // Need to cover exception case!
        }
    }
}
</code>```

If you want to allow reentry within the same thread, then it gets messy enough to use locks:

```<code>private final AtomicReference<Thread> inMethod = new AtomicReference<Thread>();

void method1() {
    final Thread current = Thread.currentThread();
    final Thread old = inMethod.get();
    if (
        old == current || // We already have it.
        inMethod.compareAndSet(null, current) // Acquired it.
    ) {
        try {
            // do Stuff
        } finally {
            inMethod.set(old); // Could optimise for no change.
        }
    }
}
</code>```

Could use the Execute Around idiom for this.

ContentLicense: CC BY-SA 2.5

Body:
I have a method, say method1(), that takes a while to run. During it's execution, if there is another call to method1(), it should be ignored. I have, roughly, something like this

    boolean mFlag = false;

    void method1()
    {
        if(!mFlag)
        {
           mFlag=true;

           // do Stuff

          mFlag=false;
        }
    }

This works. But I was wondering if there is a better way to do this preferably not involving any flags.

Body:
Are you trying to guard against re-entry from the same thread or multiple threads accessing at the same time.

Assuming multi-threaded access, the light approach is to use java.util.concurrent.atomic. No  need for anything as "heavy" as a lock (provided there are not further requirements).

Assuming no-reentry from the same method:

private final AtomicBoolean inMethod = new AtomicBoolean();

void method1() {
    if (inMethod.compareAndSet(true, false)) { // Alternatively getAndSet
        try {
            // do Stuff
        } finally {
            inMethod.set(false); // Need to cover exception case!
        }
    }
}

If you want to allow reentry within the same thread, then it gets messy enough to use locks:

private final AtomicReference<Thread> inMethod = new AtomicReference<Thread>();

void method1() {
    final Thread current = Thread.currentThread();
    final Thread old = inMethod.get();
    if (
        old == current || // We already have it.
        inMethod.compareAndSet(null, current) // Acquired it.
    ) {
        try {
            // do Stuff
        } finally {
            inMethod.set(old); // Could optimise for no change.
        }
    }
}

Could use the Execute Around idiom for this.


问:
Angular NgModel two-way binding unit test
I'm attempting to test the two-way binding feature in Angular 2. I've also read through a few other answers but I still can't get the test to pass.

When the input field is updated, I would like to run a test that ensure the searchQuery property on the AppComponent class is the same as the value of the input field.

As mentioned, I've read a few other answers and as I've gone along included additional pieces of code. So what is there currently might not all be needed?

Component

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: '<input type="text" name="input" [(ngModel)]="searchQuery" (change)="onChange()" id="search">',
  styles: ['']
})
export class AppComponent {
    public searchQuery: string;

    onChange() {
        console.log(this.searchQuery);
    }

}
</code>```

Unit test

```<code>import { ComponentFixture, TestBed, async, fakeAsync, tick, ComponentFixtureAutoDetect } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

describe('AppComponent', () => {
  let comp: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ AppComponent ],
      providers: [],
      imports: [ FormsModule ],
      schemas: []
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    comp = fixture.componentInstance;
  });

  it('should create the app', fakeAsync(() => {
    const de = fixture.debugElement.query(By.css("#search"));
    const el = de.nativeElement;

    el.value = "My string";

    var event = new Event('input', {
      'bubbles': true,
      'cancelable': true
    });
    el.dispatchEvent(event);

    tick();

    fixture.detectChanges();

    expect(comp.searchQuery).toEqual("My string");
  }));
});
</code>```

If there is a better approach, I am of course happy to get any feedback around this.

答:
You have to run

```<code>fixture.detectChanges();
</code>```

before dispatching event to ensure that your control has initialized and registered onChange event

setUpControl function

```<code>// view -> model
dir.valueAccessor.registerOnChange(function (newValue) {
    dir.viewToModelUpdate(newValue);
    control.markAsDirty();
    control.setValue(newValue, { emitModelToViewChange: false });
});
</code>```

Plunker Example

See also

Angular2 NgModel not getting value in Jasmine test

Body:
I'm attempting to test the two-way binding feature in Angular 2. I've also read through a few other answers but I still can't get the test to pass.

When the input field is updated, I would like to run a test that ensure the searchQuery property on the AppComponent class is the same as the value of the input field.

As mentioned, I've read a few other answers and as I've gone along included additional pieces of code. So what is there currently might not all be needed?

Component

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: '<input type="text" name="input" [(ngModel)]="searchQuery" (change)="onChange()" id="search">',
  styles: ['']
})
export class AppComponent {
    public searchQuery: string;

    onChange() {
        console.log(this.searchQuery);
    }

}

Unit test

import { ComponentFixture, TestBed, async, fakeAsync, tick, ComponentFixtureAutoDetect } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

describe('AppComponent', () => {
  let comp: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ AppComponent ],
      providers: [],
      imports: [ FormsModule ],
      schemas: []
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    comp = fixture.componentInstance;
  });

  it('should create the app', fakeAsync(() => {
    const de = fixture.debugElement.query(By.css("#search"));
    const el = de.nativeElement;

    el.value = "My string";

    var event = new Event('input', {
      'bubbles': true,
      'cancelable': true
    });
    el.dispatchEvent(event);

    tick();

    fixture.detectChanges();

    expect(comp.searchQuery).toEqual("My string");
  }));
});

If there is a better approach, I am of course happy to get any feedback around this.

Body:
You have to run

fixture.detectChanges();

before dispatching event to ensure that your control has initialized and registered onChange event

setUpControl function

// view -> model
dir.valueAccessor.registerOnChange(function (newValue) {
    dir.viewToModelUpdate(newValue);
    control.markAsDirty();
    control.setValue(newValue, { emitModelToViewChange: false });
});

Plunker Example

See also

Angular2 NgModel not getting value in Jasmine test


问:
In a Scatter Plot, I'd like to Autofill an Axis
I am loading data from a text file that is a single column. I want to make a scatter plot with this data, but I only have one axis (the loaded data). For my other axis, I would like to just count up (i.e. 0,1,2,3,4,5,...) until I have a matching value for every value loaded in.

Thanks for any help in advance!

答:
Matplotlib automatically uses the index of the y data if no x data is given. So you could simply supply your data array to the plotting function,  pyplot.plot(data)

```<code>import io
import numpy as np
import matplotlib.pyplot as plt

csv = u"13.7\n12.4\n10.1\n7.4\n3.7\n9.4\n8.2"

a = np.loadtxt(io.StringIO(csv))
plt.plot(a, marker="o", ls="")

plt.xlabel("index")
plt.ylabel("data")

plt.show()
</code>```

Body:
Matplotlib automatically uses the index of the y data if no x data is given. So you could simply supply your data array to the plotting function,  pyplot.plot(data)

import io
import numpy as np
import matplotlib.pyplot as plt

csv = u"13.7\n12.4\n10.1\n7.4\n3.7\n9.4\n8.2"

a = np.loadtxt(io.StringIO(csv))
plt.plot(a, marker="o", ls="")

plt.xlabel("index")
plt.ylabel("data")

plt.show()


问:
Configuration for create-react-app after ejecting to build a component library
I started to build a component library that I want to publish on NPM (and reuse in other apps) by creating a React app using create-react-app. Unfortunately the create-react-app default configuration doesn't seem to support building such component libraries (see these issues). So it seems I have to eject.

Do you have some instructions what to configure after ejecting to make this a component library I can reuse in other apps (I guess some Webpack stuff)?

答:
Re-framing my comments into an answer.

Don't eject! CRA hides a lot of stuff under the hood and ejecting throws it up. It's relatively easier to just clone your src into another project with the tooling setup done.

And it's not very difficult to setup one yourself! Here's the things you will need to do:

Basic babel and webpack configuration so your code compiles.

Make sure React and React-DOM are added as external dependencies in your package.json file and added as alias in your webpack.config.js. (A thorough discussion is here.) This is important to ensure you ship the smallest bundles only. Also, React doesn't play well with multiple copies.

Optionally, do the same for any other heavier libraries, e.g. Material-UI, Bootstrap, Lodash etc.

In webpack's configuration, decide how you want your library exports should be? You should be good with UMD.

Add main (and optionally module) entries in your package.json to let npm imports know where the components should be imported from.

Publish it.

Done!

Or, you can simply clone one of these super thin component projects and put in your components there -

https://github.com/wangzuo/react-progress-label

https://github.com/aaronshaf/react-toggle

There are more complete starter-kits as well, but IMO it's important to first know the details yourself before you abstract them away. Once you are familiar with the process, you should try leveraging the kits too as they go much beyond the basics, like test integration, react-storybook support and great npm publishing support.

UPDATES:

The purpose of CRA is to allow quick experimentation and on-boarding to React development, without going through the (somewhat complicated to a beginner) tooling setup. The intended use case of CRA, as denoted by the "App" in the name, is the whole app, not a component. Although developing anything built on language features like ES6 takes some tooling, an app typically takes more setup than a component. E.g. you also need a server component which hosts the generated code. CRA does all this and more for you.

And if you are working on an app, you will eject when you want to take control of the server side of it. It adds value in that case as you will get the basic hosting code auto-generated by CRA during eject.

To address test needs, CRA also has Jest integration, which is a test runner having React specific features like snapshot testing. Again, setting it up manually with your build pipeline is a handful and CRA once again hides all of this complexity from you, so you can simply focus on writing the tests.


问:
Custom Sorting in .NET
I have designed a Class for Parent Child relationship

```<code>  class Category
  {
    public string CatName;
    public string CatId;
    public IList<Category> childCategory = new List<Category>();

    public  void addChildCat(Category childCat)
    {
      this.childCategory.Add(childCat);
    }

    public Category SortedCategory(Category cat)
    {
      // Should return the sorted cat i.e topmost parent
    }
}
</code>```

Here by Parent will not have Catname or CatId, it will have Child Categories which has CatName, CatId as well as another Child Category List and it goes till "N" categories

Here I need to get the Top Parent with all the child categories sorted by CatName. Any ideas How this can be achieved?

Is my class design GOOD?

答:
Instead of :

```<code>public string CatName;
public string CatId;
</code>```

I would do:

```<code> class Cat
 {
      public string Name { get; set; }
      public string Id { get; set; }
 }
</code>```

And instead of:

```<code>public Category SortedCategory(Category cat)
    {
      // Should return the sorted cat i.e topmost parent
    }
</code>```

I would do:

```<code> var category = new List<Cat>
                               {
                                   new Cat() {Name = "cat1", Id = "123"},
                                   new Cat() {Name = "cat2", Id = "124"},
                                   new Cat() {Name = "cat3", Id = "125"},
                                   new Cat() {Name = "cat4", Id = "126"}
                               };

category.Sort(( cat1, cat2) =>  ((Convert.ToInt32(cat1.Id) > Convert.ToInt32(cat2.Id)) ? 1 : 0) );
</code>```

Title: Custom Sorting in .NET

Body:
I have designed a Class for Parent Child relationship

  class Category
  {
    public string CatName;
    public string CatId;
    public IList<Category> childCategory = new List<Category>();

    public  void addChildCat(Category childCat)
    {
      this.childCategory.Add(childCat);
    }

    public Category SortedCategory(Category cat)
    {
      // Should return the sorted cat i.e topmost parent
    }
}

Here by Parent will not have Catname or CatId, it will have Child Categories which has CatName, CatId as well as another Child Category List and it goes till "N" categories

Here I need to get the Top Parent with all the child categories sorted by CatName. Any ideas How this can be achieved?

Is my class design GOOD?

Body:
Instead of :

public string CatName;
public string CatId;

I would do:

 class Cat
 {
      public string Name { get; set; }
      public string Id { get; set; }
 }

And instead of:

public Category SortedCategory(Category cat)
    {
      // Should return the sorted cat i.e topmost parent
    }

I would do:

 var category = new List<Cat>
                               {
                                   new Cat() {Name = "cat1", Id = "123"},
                                   new Cat() {Name = "cat2", Id = "124"},
                                   new Cat() {Name = "cat3", Id = "125"},
                                   new Cat() {Name = "cat4", Id = "126"}
                               };

category.Sort(( cat1, cat2) =>  ((Convert.ToInt32(cat1.Id) > Convert.ToInt32(cat2.Id)) ? 1 : 0) );


问:
Odoo 8 Many2many validate and delete lines
How I wanna check if the product_id of a new line added to the mrp.bom.line (Many2many) is equal to a fixed id ('=17'), which may never be added to a BoM. But I can't seem to do this cus he stores the new line as a "NewId", he only writes it to the database when I press the SAVE button. I understood that the NewId is some sort of ID saved in the cache. How can I delete this line when it is equal tot 17?</p>

```<code>@api.onchange('bom_line_ids')

def methodA(self):
     list = []
     fixed_list = [17]

     for i in self.bom_line_ids:
         list.append(i.product_id.id)

     for j in list:
        if j in fixed_list:

        HERE DELETE THIS MRP.BOM.LINE AND PRINT WARNING MESSAGE

        warning_message = "Product: " + self.env['product.template'].search([('id','=',j)]).name + " can't be added to the BoM.\n Please select another product."
            return { 'warning': {'title': 'Product error', 'message':warning_message} }
</code>```

答:
if you have fixed id to check then this code many help. and reduce execution time</p>

```<code>@api.onchange('bom_line_ids')
def methodA(self):
    fixed_product_id = 17
    is_found = False
    for bom_line in self.bom_line_ids:
        if bom_line.product_id.id == fixed_product_id:
            is_found =True
            bom_line.unlink()

    if is_found:
        warning_message = "Product: " + self.env['product.template'].search([('id','=',fixed_product_id)]) + " can't be added to the BoM.\n Please select another product."
        return { 'warning': {'title': 'Product error', 'message':warning_message} }
</code>```

Body:
How I wanna check if the product_id of a new line added to the mrp.bom.line (Many2many) is equal to a fixed id ('=17'), which may never be added to a BoM. But I can't seem to do this cus he stores the new line as a "NewId", he only writes it to the database when I press the SAVE button. I understood that the NewId is some sort of ID saved in the cache. How can I delete this line when it is equal tot 17?

@api.onchange('bom_line_ids')

def methodA(self):
     list = []
     fixed_list = [17]

     for i in self.bom_line_ids:
         list.append(i.product_id.id)

     for j in list:
        if j in fixed_list:

        HERE DELETE THIS MRP.BOM.LINE AND PRINT WARNING MESSAGE

        warning_message = "Product: " + self.env['product.template'].search([('id','=',j)]).name + " can't be added to the BoM.\n Please select another product."
            return { 'warning': {'title': 'Product error', 'message':warning_message} }

Body:
if you have fixed id to check then this code many help. and reduce execution time

@api.onchange('bom_line_ids')
def methodA(self):
    fixed_product_id = 17
    is_found = False
    for bom_line in self.bom_line_ids:
        if bom_line.product_id.id == fixed_product_id:
            is_found =True
            bom_line.unlink()

    if is_found:
        warning_message = "Product: " + self.env['product.template'].search([('id','=',fixed_product_id)]) + " can't be added to the BoM.\n Please select another product."
        return { 'warning': {'title': 'Product error', 'message':warning_message} }


问:
Getting Error Code -2147216615 in Task scheduler 2.0
I am using the Task Scheduler managed library available from https://taskscheduler.codeplex.com/.

I am trying to RegisterTask using the below code.

```<code>ts.RootFolder.RegisterTaskDefinition(Curr_Task.Name, Curr_Task.Definition, TaskCreation.CreateOrUpdate, str_username, str_password, TaskLogonType.Password);
</code>```

But exception is thrown in the above line.

Error Code : -2147216615
Error Msg : (10,8):StartBoundary:
Stack Trace as below :-

```<code>   at Microsoft.Win32.TaskScheduler.V2Interop.ITaskFolder.RegisterTaskDefinition(String Path, ITaskDefinition pDefinition, Int32 flags, Object UserId, Object password, TaskLogonType LogonType, Object sddl)
   at Microsoft.Win32.TaskScheduler.TaskFolder.RegisterTaskDefinition(String path, TaskDefinition definition, TaskCreation createType, String userId, String password, TaskLogonType logonType, String sddl) in D:\Jeet\Task Schedular API v2.5.22\Source Code\TaskService\TaskFolder.cs:line 424
   at SQScheduler.frmScheduleScenario.SetTriggerinTaskScheduler_New() in D:\Jeet\SQScheduler-branch_5.2\SQScheduler\Parameters\frmScheduleScenario.cs:line 1259
</code>```

NOTE : For the first time when I call the RegisterTaskDefinition it works fine. But after updating the trigger, when it is called again the exception is thrown.

Update: The XML is as below:-

```<code><?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2017-04-03T16:15:11.154+05:30</Date>
    <Description>Run parameters</Description>
  </RegistrationInfo>
  <Triggers>
    <TimeTrigger>
      <StartBoundary>2017-04-03T17:10:27.153</StartBoundary>
      <Enabled>true</Enabled>
    </TimeTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>FRSYMTRAX\JDoshi</UserId>
      <LogonType>Password</LogonType>
      <RunLevel>LeastPrivilege</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <Duration>PT10M</Duration>
      <WaitTimeout>PT1H</WaitTimeout>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT2H30M</ExecutionTimeLimit>
    <Priority>10</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>D:\Program Files (x86)\Symtrax\StarQuery\Debug\SQSRunTime.exe</Command>
      <Arguments>"C:\ProgramData\Symtrax\SQScheduler\My Scenarios\New API Scenarios\Test\Test FTP.xml" "9384bea0-0f56-4423-b6f5-f22f51bf2378"</Arguments>
    </Exec>
  </Actions>
</Task>
</code>```

Please suggest the changes required to get this working!!

答: The error code -2147216615 that you're getting, if you convert it to Hexadecimal is 0x80041319, which is listed as SCHED_E_MISSINGNODE, meaning that "The task XML is missing a required element or attribute". Without seeing the XML I can't know what the problem is, but hopefully you should be able to work it out from that.</p>

Body:
I am using the Task Scheduler managed library available from https://taskscheduler.codeplex.com/.

I am trying to RegisterTask using the below code.

ts.RootFolder.RegisterTaskDefinition(Curr_Task.Name, Curr_Task.Definition, TaskCreation.CreateOrUpdate, str_username, str_password, TaskLogonType.Password);

But exception is thrown in the above line.

Error Code : -2147216615
Error Msg : (10,8):StartBoundary:
Stack Trace as below :-

   at Microsoft.Win32.TaskScheduler.V2Interop.ITaskFolder.RegisterTaskDefinition(String Path, ITaskDefinition pDefinition, Int32 flags, Object UserId, Object password, TaskLogonType LogonType, Object sddl)
   at Microsoft.Win32.TaskScheduler.TaskFolder.RegisterTaskDefinition(String path, TaskDefinition definition, TaskCreation createType, String userId, String password, TaskLogonType logonType, String sddl) in D:\Jeet\Task Schedular API v2.5.22\Source Code\TaskService\TaskFolder.cs:line 424
   at SQScheduler.frmScheduleScenario.SetTriggerinTaskScheduler_New() in D:\Jeet\SQScheduler-branch_5.2\SQScheduler\Parameters\frmScheduleScenario.cs:line 1259

NOTE : For the first time when I call the RegisterTaskDefinition it works fine. But after updating the trigger, when it is called again the exception is thrown.

Update: The XML is as below:-

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2017-04-03T16:15:11.154+05:30</Date>
    <Description>Run parameters</Description>
  </RegistrationInfo>
  <Triggers>
    <TimeTrigger>
      <StartBoundary>2017-04-03T17:10:27.153</StartBoundary>
      <Enabled>true</Enabled>
    </TimeTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>FRSYMTRAX\JDoshi</UserId>
      <LogonType>Password</LogonType>
      <RunLevel>LeastPrivilege</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <Duration>PT10M</Duration>
      <WaitTimeout>PT1H</WaitTimeout>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT2H30M</ExecutionTimeLimit>
    <Priority>10</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>D:\Program Files (x86)\Symtrax\StarQuery\Debug\SQSRunTime.exe</Command>
      <Arguments>"C:\ProgramData\Symtrax\SQScheduler\My Scenarios\New API Scenarios\Test\Test FTP.xml" "9384bea0-0f56-4423-b6f5-f22f51bf2378"</Arguments>
    </Exec>
  </Actions>
</Task>

Please suggest the changes required to get this working!!


问:
Firebase 3.x issue: FIRUserInfo is an "undeclared identifier"
No matter what I try, FIRUserInfo is an undeclared identifier. I'm trying to migrate from Firebase 2.x to 3.x: somehow the recent changes on google/firebase server side broke my app's facebook auth integration.

I made sure my Podfile installs FirebaseAuth 3.0.2. I made sure my header does import @FirebaseAuth. I tried cleaning my build folder, restarting xcode etc.

In Xcode 7.3.1 I can command-click FIRUserInfo and it does indeed find the header file in the pod framework as expected. But it won't compile - the last line below fails with FIRUserInfo as undeclared identifier.

```<code>@import Firebase;
...
                [[FIRAuth auth] signInWithCredential:credential completion:^(FIRUser * _Nullable user, NSError * _Nullable error) {
                    if (error || user.providerData.count < 1) {
                        DDLogWarn(@"Firebase login after facebook failed: %@", error);
                        if( weakSelf.signInCompletionHandler ) {
                            weakSelf.signInCompletionHandler(false, false, nil);
                            weakSelf.signInCompletionHandler = nil;
                        }
                    } else {
                        FIRDatabaseReference *userRef = [[FIRDatabase database] reference];
                        userRef = [userRef child:[NSString stringWithFormat:@"users/%@", user.uid]];
                        FIRUserInfo *profile = user.providerData.firstObject;
</code>```

答:
i am new in ios and have same problem
use

```<code>#import <FirebaseAuth/FirebaseAuth.h>
</code>```

instead of

```<code>@import Firebase;
</code>```

may it help..

Body:
No matter what I try, FIRUserInfo is an undeclared identifier. I'm trying to migrate from Firebase 2.x to 3.x: somehow the recent changes on google/firebase server side broke my app's facebook auth integration.

I made sure my Podfile installs FirebaseAuth 3.0.2. I made sure my header does import @FirebaseAuth. I tried cleaning my build folder, restarting xcode etc.

In Xcode 7.3.1 I can command-click FIRUserInfo and it does indeed find the header file in the pod framework as expected. But it won't compile - the last line below fails with FIRUserInfo as undeclared identifier.

@import Firebase;
...
                [[FIRAuth auth] signInWithCredential:credential completion:^(FIRUser * _Nullable user, NSError * _Nullable error) {
                    if (error || user.providerData.count < 1) {
                        DDLogWarn(@"Firebase login after facebook failed: %@", error);
                        if( weakSelf.signInCompletionHandler ) {
                            weakSelf.signInCompletionHandler(false, false, nil);
                            weakSelf.signInCompletionHandler = nil;
                        }
                    } else {
                        FIRDatabaseReference *userRef = [[FIRDatabase database] reference];
                        userRef = [userRef child:[NSString stringWithFormat:@"users/%@", user.uid]];
                        FIRUserInfo *profile = user.providerData.firstObject;

Body:
i am new in ios and have same problem
use

#import <FirebaseAuth/FirebaseAuth.h>

instead of

@import Firebase;

may it help..


问:
getting Warnings and console.error in each test cases in jest
I am using react native development and using jest for testing . and my cases my all are test cases passing but getting this error .</p>

```<code>console.error node_modules/react-native/Libraries/Core/ExceptionsManager.js:71

          Warning: Invalid argument supplied to oneOf, expected an instance of array.

        console.error node_modules/react-native/Libraries/Core/ExceptionsManager.js:71

          Warning: In next release empty section headers will be rendered. In this release you can use 'enableEmptySections' flag to render empty section headers.

        console.error node_modules/react-native/Libraries/Core/ExceptionsManager.js:71

          Warning: In next release empty section headers will be rendered. In this release you can use 'enableEmptySections' flag to render empty section headers

    in my all test cases
</code>```

答:
try this
enableEmptySections={true}</p>

Body:
I am using react native development and using jest for testing . and my cases my all are test cases passing but getting this error .

console.error node_modules/react-native/Libraries/Core/ExceptionsManager.js:71

          Warning: Invalid argument supplied to oneOf, expected an instance of array.

        console.error node_modules/react-native/Libraries/Core/ExceptionsManager.js:71

          Warning: In next release empty section headers will be rendered. In this release you can use 'enableEmptySections' flag to render empty section headers.

        console.error node_modules/react-native/Libraries/Core/ExceptionsManager.js:71

          Warning: In next release empty section headers will be rendered. In this release you can use 'enableEmptySections' flag to render empty section headers

    in my all test cases

Body:
try this
enableEmptySections={true}


问:
How to add a border radius invertedly?
I'm currently trying to achieve this:

But when  border-radius: 15px 15px 0 0 I get this:

答:
You can do using this :beforecss selector:

.box{
  background:red;
  width:50px;
  height:100px;
  border-radius:3px;
  position:relative;
  margin-top:30px;
}
.box:before{
  content:"";
  width:50px;
  height:30px;
  border-radius:100%;
  background:#fff;
  position: absolute;
  top: -17px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
</div></code>```

Title: How to add a border radius invertedly?

Body:
You can do using this :beforecss selector:

.box{
  background:red;
  width:50px;
  height:100px;
  border-radius:3px;
  position:relative;
  margin-top:30px;
}
.box:before{
  content:"";
  width:50px;
  height:30px;
  border-radius:100%;
  background:#fff;
  position: absolute;
  top: -17px;
}

<div class="box">
</div>


问:
How to change UICollectionViewCell size programmatically in Swift?
I have a UICollectionView with a segmented control to switch between data. But how do I change the UICollectionViewCell size properties programmatically ? then I can custom each style appropriately for each data type.

For example change the width to 520 points and height to 100. I am new to iOS development and am experienced with CSS :/

I know how to do it in Xcode (obviously) but do not know the correct methods to change it in swift. Any ideas or feedback is much appreciated (Y)

答:
Swift 3

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    let cellSize = CGSize(width:80 , height:80)

    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .vertical //.horizontal
    layout.itemSize = cellSize
    layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
    layout.minimumLineSpacing = 1.0
    layout.minimumInteritemSpacing = 1.0
    myCollectionView.setCollectionViewLayout(layout, animated: true)

    myCollectionView.reloadData()
}
</code>```

Body:
Swift 3

override func viewDidLoad() {
    super.viewDidLoad()

    let cellSize = CGSize(width:80 , height:80)

    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .vertical //.horizontal
    layout.itemSize = cellSize
    layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
    layout.minimumLineSpacing = 1.0
    layout.minimumInteritemSpacing = 1.0
    myCollectionView.setCollectionViewLayout(layout, animated: true)

    myCollectionView.reloadData()
}


问:
How can I put validation in the getter and setter methods in C#?
In C#, I can have a property without having the need to declare a private variable.
My VB6 code that looked like this

```<code>'local variable(s) to hold property value(s)
Private mvarPhoneNumber As String 'local copy
Public Property Let PhoneNumber(ByVal vData As String)
'used when assigning a value to the property, on the left side of an assignment.
'Syntax: X.PhoneNumber = 5
    mvarPhoneNumber = vData
End Property

Public Property Get PhoneNumber() As String
'used when retrieving value of a property, on the right side of an assignment.
'Syntax: Debug.Print X.PhoneNumber
    PhoneNumber = mvarPhoneNumber
End Property
</code>```

can now look like this.

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

How can I put validation in the getter and setter methods in C#?
I tried adding a validation like this.

```<code>public string PhoneNumber
        {
            get
            {
                return PhoneNumber;
            }
            set
            {
                if (value.Length <= 30)
                {
                    PhoneNumber = value;
                }
                else
                {
                    PhoneNumber = "EXCEEDS LENGTH";
                }
            }
        }
</code>```

The get part of this code won't compile.
Do I need to revert to using a private variable?

答:
Look here for several many alternatives:
Acessing the backing field in an auto property

But the short answer is Yes, you will have to have backing field for validations.

Body:
In C#, I can have a property without having the need to declare a private variable.
My VB6 code that looked like this

'local variable(s) to hold property value(s)
Private mvarPhoneNumber As String 'local copy
Public Property Let PhoneNumber(ByVal vData As String)
'used when assigning a value to the property, on the left side of an assignment.
'Syntax: X.PhoneNumber = 5
    mvarPhoneNumber = vData
End Property

Public Property Get PhoneNumber() As String
'used when retrieving value of a property, on the right side of an assignment.
'Syntax: Debug.Print X.PhoneNumber
    PhoneNumber = mvarPhoneNumber
End Property

can now look like this.

public string PhoneNumber{get;set;}

How can I put validation in the getter and setter methods in C#?
I tried adding a validation like this.

public string PhoneNumber
        {
            get
            {
                return PhoneNumber;
            }
            set
            {
                if (value.Length <= 30)
                {
                    PhoneNumber = value;
                }
                else
                {
                    PhoneNumber = "EXCEEDS LENGTH";
                }
            }
        }

The get part of this code won't compile.
Do I need to revert to using a private variable?


问:
align center and center tag are not working
i am trying to show pagination in center but its show on left side. i am also try center tag and align=center attributes but its not working....

Pagination show in the center of page

#pagination {
  margin: 40 40 0;
  float: left;
}
ul.tsc_pagination li a {
  border:solid 1px;
  border-radius:3px;
  -moz-border-radius:3px;
  -webkit-border-radius:3px;
  padding:6px 9px 6px 9px;
}
ul.tsc_pagination li {
  padding-bottom:1px;
}
ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current {
  color:#FFFFFF;
  box-shadow:0px 1px #EDEDED;
  -moz-box-shadow:0px 1px #EDEDED;
  -webkit-box-shadow:0px 1px #EDEDED;
}
ul.tsc_pagination {
  margin:4px 0;
  padding:0px;
  height:100%;
  overflow:hidden;
  font:12px 'Tahoma';
  list-style-type:none;
}
ul.tsc_pagination li {
  float:left;
  margin:0px;
  padding:0px;
  margin-left:5px;
}
ul.tsc_pagination li a {
  color:black;
  display:block;
  text-decoration:none;
  padding:7px 10px 7px 10px;
}
ul.tsc_pagination li a img {
  border:none;
}
ul.tsc_pagination li a {
  color:#0A7EC5;
  border-color:#8DC5E6;
  background:#F8FCFF;
}
ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current {
  text-shadow:0px 1px #388DBE;
  border-color:#3390CA;
  background:#58B0E7;
  background:-moz-linear-gradient(top, #B4F6FF 1px, #63D0FE 1px, #58B0E7);
  background:-webkit-gradient(linear, 0 0, 0 100%, color-stop(0.02, #B4F6FF), color-stop(0.02, #63D0FE), color-stop(1, #58B0E7));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="pagination">
  <ul class="tsc_pagination">
    <!-- Show pagination links -->
    <li></li>
    <li>1</li>
    <li>2</li>
    <li>Next</li>
    <li></li>
  </ul>
</div></code>```

you can see this

答:
try this one https://jsfiddle.net/g3643p4q/4/
only mansion </p>

```<code>ul.tsc_pagination li {
    display: inline-block;
    float: none;
    margin: 0 0 0 5px;
    padding: 0;
}
ul.tsc_pagination {
    font: 12px "Tahoma";
    height: 100%;
    list-style-type: none;
    margin: 0 auto;
    overflow: hidden;
    padding: 0;
    text-align: center;
}

#pagination {
    float: none;
}
</code>```

Body:
i am trying to show pagination in center but its show on left side. i am also try center tag and align=center attributes but its not working....

Pagination show in the center of page

#pagination {
  margin: 40 40 0;
  float: left;
}
ul.tsc_pagination li a {
  border:solid 1px;
  border-radius:3px;
  -moz-border-radius:3px;
  -webkit-border-radius:3px;
  padding:6px 9px 6px 9px;
}
ul.tsc_pagination li {
  padding-bottom:1px;
}
ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current {
  color:#FFFFFF;
  box-shadow:0px 1px #EDEDED;
  -moz-box-shadow:0px 1px #EDEDED;
  -webkit-box-shadow:0px 1px #EDEDED;
}
ul.tsc_pagination {
  margin:4px 0;
  padding:0px;
  height:100%;
  overflow:hidden;
  font:12px 'Tahoma';
  list-style-type:none;
}
ul.tsc_pagination li {
  float:left;
  margin:0px;
  padding:0px;
  margin-left:5px;
}
ul.tsc_pagination li a {
  color:black;
  display:block;
  text-decoration:none;
  padding:7px 10px 7px 10px;
}
ul.tsc_pagination li a img {
  border:none;
}
ul.tsc_pagination li a {
  color:#0A7EC5;
  border-color:#8DC5E6;
  background:#F8FCFF;
}
ul.tsc_pagination li a:hover,
ul.tsc_pagination li a.current {
  text-shadow:0px 1px #388DBE;
  border-color:#3390CA;
  background:#58B0E7;
  background:-moz-linear-gradient(top, #B4F6FF 1px, #63D0FE 1px, #58B0E7);
  background:-webkit-gradient(linear, 0 0, 0 100%, color-stop(0.02, #B4F6FF), color-stop(0.02, #63D0FE), color-stop(1, #58B0E7));
}

1

2

Next

you can see this

Body:
try this one https://jsfiddle.net/g3643p4q/4/
only mansion

ul.tsc_pagination li {
    display: inline-block;
    float: none;
    margin: 0 0 0 5px;
    padding: 0;
}
ul.tsc_pagination {
    font: 12px "Tahoma";
    height: 100%;
    list-style-type: none;
    margin: 0 auto;
    overflow: hidden;
    padding: 0;
    text-align: center;
}

#pagination {
    float: none;
}


问:
D3 JS: How to add transition to refresh a plot when the dataset x-scale changes?
Looking at this Histogram chart using d3 example I plugged in my data but it had some strange side effects e.g. after refreshing to a new dataset, some information from the previous dataset i.e. x-axis scale was retained. I tried deleting and appending a new x-axis etc but nothing worked.

This happened due to the fact that my datasets had completely different x-axis ranges and scales. The only way I found to make it work was to select the whole svg element, remove it and re-append everything anew. However, this doesn't make a pleasant transition for the user so I was wondering how can this be improved to make it refreshable using transitions as in the original example even when having datasets with different x-scales and ranges.

This was my last approach which is a bit harsh to the eye:

```<code>// delete old
d3.select("#" + divId).select("svg").remove();

// then recreate all new
</code>```

And this was my refresh attempt (integrated with AngularJS). Note how it has some common initialization and then if the SVG doesn't exist appends everything new otherwise tries to update it. I went bit by bit but can't see why the refresh doesn't remove all the previous dataset information of the x-axis scale:

```<code>var divId = $scope.histogramData.divId;
var color = $scope.histogramData.color;
var values = $scope.histogramData.data[$scope.histogramData.selected];
var svg = $scope.histogramData.svg;

// plot common initialization
var margin = {top: 40, right: 20, bottom: 20, left: 20},
    width = 450 - margin.left - margin.right,
    height = 370 - margin.top - margin.bottom;

var max = d3.max(values);
var min = d3.min(values);
var x = d3.scale.linear()
    .domain([min, max])
    .range([0, width]);

// generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
    .bins(x.ticks(10))
    (values);

var yMax = d3.max(data, function(d){ return d.length });
var yMin = d3.min(data, function(d){ return d.length });
var colorScale = d3.scale.linear()
    .domain([yMin, yMax])
    .range([d3.rgb(color).brighter(), d3.rgb(color).darker()]);

var y = d3.scale.linear()
    .domain([0, yMax])
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

// ===================================================================
// If the SVG doesn't exist then adds everything new
// ===================================================================
if (svg === undefined) {
    var svg = d3.select("#" + divId)
        .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    $scope.histogramData.svg = svg;

    var bar = svg.selectAll(".bar")
        .data(data)
        .enter()
        .append("g")
        .attr("class", "bar")
        .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

    bar.append("rect")
        .attr("x", 1)
        .attr("width", (x(data[0].dx) - x(0)) - 1)
        .attr("height", function(d) { return height - y(d.y); })
        .attr("fill", function(d) { return colorScale(d.y) });

    bar.append("text")
        .attr("dy", ".75em")
        .attr("y", -12)
        .attr("x", (x(data[0].dx) - x(0)) / 2)
        .attr("text-anchor", "middle")
        .text(function(d) { return formatCount(d.y); });

    var gTitle = svg.append("text")
        .attr("x", 0)
        .attr("y", 0 - (margin.top / 2))
        .attr("text-anchor", "left")
        .classed("label", true)
        .text($scope.histogramData.spec[selected]);
    $scope.histogramData.gTitle = gTitle;

    var gAxis = svg.append("g")
     .attr("class", "x axis")
     .attr("transform", "translate(0," + height + ")")
     .call(xAxis);
     $scope.histogramData.gAxis = gAxis;

} else {
    // ===================================================================
    // If the SVG does exist then tries refreshing
    // ===================================================================
    var bar = svg.selectAll(".bar").data(data);

    // remove object with data
    bar.exit().remove();

    bar.transition()
        .duration(1000)
        .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

    bar.select("rect")
        .transition()
        .duration(1000)
        .attr("height", function(d) { return height - y(d.y); })
        .attr("fill", function(d) { return colorScale(d.y) });

    bar.select("text")
        .transition()
        .duration(1000)
        .text(function(d) { return formatCount(d.y); });

    var gTitle = $scope.histogramData.gTitle;
    gTitle.transition()
          .duration(1000)
          .text($scope.histogramData.spec[selected]);

    var gAxis = $scope.histogramData.gAxis;
    gAxis.transition()
         .duration(1000)
         .call(xAxis);
}
</code>```

答: I would suggest to keep this d3 code inside one angularJS directive and keep a watch on the json which you are using to plot that graph. As soon as values are changing the directive will be called again and the graph will be plotted. Hope it helps. </p>

Body:
Looking at this Histogram chart using d3 example I plugged in my data but it had some strange side effects e.g. after refreshing to a new dataset, some information from the previous dataset i.e. x-axis scale was retained. I tried deleting and appending a new x-axis etc but nothing worked.

This happened due to the fact that my datasets had completely different x-axis ranges and scales. The only way I found to make it work was to select the whole svg element, remove it and re-append everything anew. However, this doesn't make a pleasant transition for the user so I was wondering how can this be improved to make it refreshable using transitions as in the original example even when having datasets with different x-scales and ranges.

This was my last approach which is a bit harsh to the eye:

// delete old
d3.select("#" + divId).select("svg").remove();

// then recreate all new

And this was my refresh attempt (integrated with AngularJS). Note how it has some common initialization and then if the SVG doesn't exist appends everything new otherwise tries to update it. I went bit by bit but can't see why the refresh doesn't remove all the previous dataset information of the x-axis scale:

var divId = $scope.histogramData.divId;
var color = $scope.histogramData.color;
var values = $scope.histogramData.data[$scope.histogramData.selected];
var svg = $scope.histogramData.svg;

// plot common initialization
var margin = {top: 40, right: 20, bottom: 20, left: 20},
    width = 450 - margin.left - margin.right,
    height = 370 - margin.top - margin.bottom;

var max = d3.max(values);
var min = d3.min(values);
var x = d3.scale.linear()
    .domain([min, max])
    .range([0, width]);

// generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
    .bins(x.ticks(10))
    (values);

var yMax = d3.max(data, function(d){ return d.length });
var yMin = d3.min(data, function(d){ return d.length });
var colorScale = d3.scale.linear()
    .domain([yMin, yMax])
    .range([d3.rgb(color).brighter(), d3.rgb(color).darker()]);

var y = d3.scale.linear()
    .domain([0, yMax])
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

// ===================================================================
// If the SVG doesn't exist then adds everything new
// ===================================================================
if (svg === undefined) {
    var svg = d3.select("#" + divId)
        .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    $scope.histogramData.svg = svg;

    var bar = svg.selectAll(".bar")
        .data(data)
        .enter()
        .append("g")
        .attr("class", "bar")
        .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

    bar.append("rect")
        .attr("x", 1)
        .attr("width", (x(data[0].dx) - x(0)) - 1)
        .attr("height", function(d) { return height - y(d.y); })
        .attr("fill", function(d) { return colorScale(d.y) });

    bar.append("text")
        .attr("dy", ".75em")
        .attr("y", -12)
        .attr("x", (x(data[0].dx) - x(0)) / 2)
        .attr("text-anchor", "middle")
        .text(function(d) { return formatCount(d.y); });

    var gTitle = svg.append("text")
        .attr("x", 0)
        .attr("y", 0 - (margin.top / 2))
        .attr("text-anchor", "left")
        .classed("label", true)
        .text($scope.histogramData.spec[selected]);
    $scope.histogramData.gTitle = gTitle;

    var gAxis = svg.append("g")
     .attr("class", "x axis")
     .attr("transform", "translate(0," + height + ")")
     .call(xAxis);
     $scope.histogramData.gAxis = gAxis;

} else {
    // ===================================================================
    // If the SVG does exist then tries refreshing
    // ===================================================================
    var bar = svg.selectAll(".bar").data(data);

    // remove object with data
    bar.exit().remove();

    bar.transition()
        .duration(1000)
        .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

    bar.select("rect")
        .transition()
        .duration(1000)
        .attr("height", function(d) { return height - y(d.y); })
        .attr("fill", function(d) { return colorScale(d.y) });

    bar.select("text")
        .transition()
        .duration(1000)
        .text(function(d) { return formatCount(d.y); });

    var gTitle = $scope.histogramData.gTitle;
    gTitle.transition()
          .duration(1000)
          .text($scope.histogramData.spec[selected]);

    var gAxis = $scope.histogramData.gAxis;
    gAxis.transition()
         .duration(1000)
         .call(xAxis);
}


问:
Open links from excel one by one to Internet Explorer
I have more than 100 links in Excel and I want to open them in Internet Explorer one by one. The computer assigned to me is somewhat slow that is why the links need to be opened in just one tab of Internet Explorer.

I want to:

1.Copy link from A1, paste it to Internet Explorer.

2.Wait until the page is fully loaded.

3.Copy link from A2, paste it to Internet Explorer (same tab, not opening a
    new tab).

4.Wait until the page is fully loaded.

5.Repeat steps until the last cell of "A" with links.

In the code below, I can navigate the link from A1. How can you loop it that it will navigate from cell 1 to cell X.

```<code>Sub OpenInAnotherBrowser()
Dim iePath As String
Dim browser As String
Dim URL As String

iePath = "C:\Program Files\Internet Explorer\iexplore.exe"

If Dir(iePath) = "" Then pathie = "C:\Program Files\Internet Explorer\iexplore.exe"

URL = ActiveSheet.Range("A1").Value

If Dir(iePath) = "" Then
    If MsgBox("IE Not Found, Open with default browser?", vbQuestion + vbYesNo) = vbYes Then
        Application.FollowHyperlink URL
        Exit Sub
    End If
End If

Shell """" & iePath & """" & URL, vbHide

End Sub
</code>```

答:
This code loops through the links in column A in sheet1. Look out for broken links and things like that as there are no check for those things in this code.</p>

```<code>Sub Main()

Dim IE As Object
Dim rngURL As Range
Dim rng As Range

' not perfect, but it is a quick way to keep VBA from looping through 1000000+ rows without using a bunch of ifs....
Set rngURL = Intersect(Sheet1.UsedRange, Sheet1.Columns("A"))

Set IE = CreateObject("internetexplorer.application")

IE.Visible = True

For Each rng In rngURL

    rng.Select

    If Trim(rng.Value) <> "" Then

        IE.Navigate Trim(rng.Value)

        Do While IE.ReadyState <> READYSTATE_COMPLETE
        Loop

        MsgBox IE.LocationURL ' This is just to slow things down a little bit

    End If

Next rng

IE.Quit

End Sub
</code>```

Body:
I have more than 100 links in Excel and I want to open them in Internet Explorer one by one. The computer assigned to me is somewhat slow that is why the links need to be opened in just one tab of Internet Explorer.

I want to:

1.Copy link from A1, paste it to Internet Explorer.

2.Wait until the page is fully loaded.

3.Copy link from A2, paste it to Internet Explorer (same tab, not opening a
    new tab).

4.Wait until the page is fully loaded.

5.Repeat steps until the last cell of "A" with links.

In the code below, I can navigate the link from A1. How can you loop it that it will navigate from cell 1 to cell X.

Sub OpenInAnotherBrowser()
Dim iePath As String
Dim browser As String
Dim URL As String

iePath = "C:\Program Files\Internet Explorer\iexplore.exe"

If Dir(iePath) = "" Then pathie = "C:\Program Files\Internet Explorer\iexplore.exe"

URL = ActiveSheet.Range("A1").Value

If Dir(iePath) = "" Then
    If MsgBox("IE Not Found, Open with default browser?", vbQuestion + vbYesNo) = vbYes Then
        Application.FollowHyperlink URL
        Exit Sub
    End If
End If

Shell """" & iePath & """" & URL, vbHide

End Sub

Body:
This code loops through the links in column A in sheet1. Look out for broken links and things like that as there are no check for those things in this code.

Sub Main()

Dim IE As Object
Dim rngURL As Range
Dim rng As Range

' not perfect, but it is a quick way to keep VBA from looping through 1000000+ rows without using a bunch of ifs....
Set rngURL = Intersect(Sheet1.UsedRange, Sheet1.Columns("A"))

Set IE = CreateObject("internetexplorer.application")

IE.Visible = True

For Each rng In rngURL

    rng.Select

    If Trim(rng.Value) <> "" Then

        IE.Navigate Trim(rng.Value)

        Do While IE.ReadyState <> READYSTATE_COMPLETE
        Loop

        MsgBox IE.LocationURL ' This is just to slow things down a little bit

    End If

Next rng

IE.Quit

End Sub


问:
angular material md-autocomplete dynamic loading issue
I'm using Angular Material component "md-autocomplete" in my project.

We are trying to render dynamic response that we are getting from "md-list" component's item-click's event call.

Issue: However, before the event call is invoked, md-autocomplete method is invoked.

My Requirement: Is there a way to invoke the event call before invoking md-autocomplete method.

Here we attached sample images, that show's you basic response what we need as output.

I tried below code, But it is not working. I need solution for the problem.

HTML Source Code:

md-list code

```<code><md-list>
    <div ng-repeat="object in ['object 1', 'object 2', 'object 3', 'object 4', 'object 5', 'object 6'] track by $index">
        <md-list-item class="md-2-line contact-item" ng-click="listItemClick($event, object)">
            <div class="md-list-item-text compact">
                <h3>Object data displayed here like object 1, object 2 and etc ...</h3>
            </div>
        </md-list-item>
    </div>
</md-list>
</code>```

md-autocomplete code :

```<code><md-autocomplete
        ng-disabled="isDisabled"
        md-no-cache="noCache"
        md-selected-item="selectedItem"
        md-search-text-change="searchTextChangeEvent(searchText)"
        md-search-text="searchText"
        md-selected-item-change="selectedItemChangeEvent(item)"
        md-items="item in search(searchText)"
        md-item-text="item.id"
        md-min-length="0"
        placeholder="Search by id ..."
        md-menu-class="autocomplete-custom-template">
        <md-item-template>
            <span class="item-title">
                {{id}}
            </span>
        </md-item-template>
</md-autocomplete>
</code>```

AngularJS Script Code :

```<code>(function() {

        var app = angular.module('module-name');

        var controller = function($scope, $rootScope,$http, $timeout, $q, $log) {

            var self = this;

            self.simulateQuery = false;
            self.isDisabled    = false;

            $rootScope.objectName = "object 1";

            self.response = loadValues($rootScope.objectName);
            self.search = search;
            self.selectedItemChangeEvent = selectedItemChangeEvent;
            self.searchTextChangeEvent = searchTextChangeEvent;

            // ******************************
            // Internal methods
            // ******************************

            /**
             * Search for repos... use $timeout to simulate
             * remote dataservice call.
             */
            function search (query) {

                var results = query ? self.response.filter( createQueryFilterFor(query) ) : self.response,
                  deferred;
                if (self.simulateQuery) {
                    deferred = $q.defer();
                    $timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
                    return deferred.promise;
                } else {
                    return results;
                }
            }

            function searchTextChangeEvent(text) {
              $log.info('Text changed to ' + text);
            }

            function selectedItemChangeEvent(item) {
                $log.info('Item changed to ' + JSON.stringify(item));
            }

            /**
             * Build `components` list of key/value pairs
             */
            function loadValues(name) {

                var dynamicData = '';

                if(name === "object 1") {
                    dynamicData = [{
                        "id": 1,
                        "name": "some name here"
                    },{
                        "id": 2,
                        "name": "some name here"
                    }];
                } else if(name === "object 2") {
                    dynamicData = [{
                        "id": 3,
                        "name": "some name here"
                    },{
                        "id": 4,
                        "name": "some name here"
                    }];
                } else if(name === "object 3") {
                    dynamicData = [{
                        "id": 5,
                        "name": "some name here"
                    },{
                        "id": 6,
                        "name": "some name here"
                    }];
                }

                return dynamicData.map( function (response) {
                    response.value = response.id.toLowerCase();
                    return response;
                });
            }

            /**
             * Create filter function for a query string
             */
            function createQueryFilterFor(query) {

              var lowercaseQuery = angular.lowercase(query);

              return function filterFn(item) {
                return (item.value.indexOf(lowercaseQuery) === 0);
              };
            }

            $scope.listItemClick = function(event, object) {

                $rootScope.objectName= object.someFiledName; // It will give md-list-item name (like object 1 or object 2 and etc ...)

                self.response = loadValues($rootScope.name);
            }
        };

        app.controller("controller", controller)
    }());
</code>```

答:
I have taken your code and created a plunkr demo. I tweaked it few places, please feel free to explore the code in plunkr. Now suggestions are loading according to object selected.

I think filter logic was not correct according to use case you mentioned here so I corrected createQueryFilterFor function logic. I made changes in md-item-template section too.

```<code>function createQueryFilterFor(query) {
      var lowercaseQuery = angular.lowercase(query);
      return function filterFn(item) {
        //below condition updated to match search id
        return (item.value.toString() === lowercaseQuery);
      };
    }
</code>```

see demo

Body:
I'm using Angular Material component "md-autocomplete" in my project.

We are trying to render dynamic response that we are getting from "md-list" component's item-click's event call.

Issue: However, before the event call is invoked, md-autocomplete method is invoked.

My Requirement: Is there a way to invoke the event call before invoking md-autocomplete method.

Here we attached sample images, that show's you basic response what we need as output.

I tried below code, But it is not working. I need solution for the problem.

HTML Source Code:

md-list code

<md-list>

        <md-list-item class="md-2-line contact-item" ng-click="listItemClick($event, object)">

Object data displayed here like object 1, object 2 and etc ...

        </md-list-item>

</md-list>

md-autocomplete code :

<md-autocomplete
        ng-disabled="isDisabled"
        md-no-cache="noCache"
        md-selected-item="selectedItem"
        md-search-text-change="searchTextChangeEvent(searchText)"
        md-search-text="searchText"
        md-selected-item-change="selectedItemChangeEvent(item)"
        md-items="item in search(searchText)"
        md-item-text="item.id"
        md-min-length="0"
        placeholder="Search by id ..."
        md-menu-class="autocomplete-custom-template">
        <md-item-template>

                {{id}}

        </md-item-template>
</md-autocomplete>

AngularJS Script Code :

(function() {

        var app = angular.module('module-name');

        var controller = function($scope, $rootScope,$http, $timeout, $q, $log) {

            var self = this;

            self.simulateQuery = false;
            self.isDisabled    = false;

            $rootScope.objectName = "object 1";

            self.response = loadValues($rootScope.objectName);
            self.search = search;
            self.selectedItemChangeEvent = selectedItemChangeEvent;
            self.searchTextChangeEvent = searchTextChangeEvent;

            // ******************************
            // Internal methods
            // ******************************

            /**
             * Search for repos... use $timeout to simulate
             * remote dataservice call.
             */
            function search (query) {

                var results = query ? self.response.filter( createQueryFilterFor(query) ) : self.response,
                  deferred;
                if (self.simulateQuery) {
                    deferred = $q.defer();
                    $timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
                    return deferred.promise;
                } else {
                    return results;
                }
            }

            function searchTextChangeEvent(text) {
              $log.info('Text changed to ' + text);
            }

            function selectedItemChangeEvent(item) {
                $log.info('Item changed to ' + JSON.stringify(item));
            }

            /**
             * Build `components` list of key/value pairs
             */
            function loadValues(name) {

                var dynamicData = '';

                if(name === "object 1") {
                    dynamicData = [{
                        "id": 1,
                        "name": "some name here"
                    },{
                        "id": 2,
                        "name": "some name here"
                    }];
                } else if(name === "object 2") {
                    dynamicData = [{
                        "id": 3,
                        "name": "some name here"
                    },{
                        "id": 4,
                        "name": "some name here"
                    }];
                } else if(name === "object 3") {
                    dynamicData = [{
                        "id": 5,
                        "name": "some name here"
                    },{
                        "id": 6,
                        "name": "some name here"
                    }];
                }

                return dynamicData.map( function (response) {
                    response.value = response.id.toLowerCase();
                    return response;
                });
            }

            /**
             * Create filter function for a query string
             */
            function createQueryFilterFor(query) {

              var lowercaseQuery = angular.lowercase(query);

              return function filterFn(item) {
                return (item.value.indexOf(lowercaseQuery) === 0);
              };
            }

            $scope.listItemClick = function(event, object) {

                $rootScope.objectName= object.someFiledName; // It will give md-list-item name (like object 1 or object 2 and etc ...)

                self.response = loadValues($rootScope.name);
            }
        };

        app.controller("controller", controller)
    }());

Body:
I have taken your code and created a plunkr demo. I tweaked it few places, please feel free to explore the code in plunkr. Now suggestions are loading according to object selected.

I think filter logic was not correct according to use case you mentioned here so I corrected createQueryFilterFor function logic. I made changes in md-item-template section too.

function createQueryFilterFor(query) {
      var lowercaseQuery = angular.lowercase(query);
      return function filterFn(item) {
        //below condition updated to match search id
        return (item.value.toString() === lowercaseQuery);
      };
    }

see demo


问:
Java: Subtract '0' from char to get an int... why does this work?
This works fine:

```<code>int foo = bar.charAt(1) - '0';
</code>```

Yet this doesn't - because bar.charAt(x) returns a char:

```<code>int foo = bar.charAt(1);
</code>```

It seems that subtracting '0' from the char is casting it to an integer.

Why, or how,  does subtracting the string '0' (or is it a char?) convert another char in to an integer?

答:
chars are converted to int implicitly:

```<code>   public static void main(String [] args) throws Exception {
     String bar = "abc";
     int foo = bar.charAt(1) - '0';
     int foob = bar.charAt(1);
     System.err.println("foo = " + foo + "   foob = " + foob);
   }
</code>```

output: foo = 50   foob = 98.

Maybe you put two int foo ... and this is because it didn't work?

Body:
This works fine:

int foo = bar.charAt(1) - '0';

Yet this doesn't - because bar.charAt(x) returns a char:

int foo = bar.charAt(1);

It seems that subtracting '0' from the char is casting it to an integer.

Why, or how,  does subtracting the string '0' (or is it a char?) convert another char in to an integer?

Body:
chars are converted to int implicitly:

   public static void main(String [] args) throws Exception {
     String bar = "abc";
     int foo = bar.charAt(1) - '0';
     int foob = bar.charAt(1);
     System.err.println("foo = " + foo + "   foob = " + foob);
   }

output: foo = 50   foob = 98.

Maybe you put two int foo ... and this is because it didn't work?


问:
Can't seem to put brackets around a join result in JavaScript
Using checkbox values to fill an array and then joining those elements I need to put brackets around the joined element to carry out a google place type request.

These are the checkboxes:

```<code><form id= "checkboxes">
<label> Types of Places</label>
 <link rel="stylesheet" type="text/css"  href="css/style.css">
    <input type="checkbox" name="cbox" value="woodland" class="places"/>
    <label for="woodland"><img src="../img/Woodland.jpg" /></label>
    <input type="checkbox" name="cbox" value="lodging" class="places"/>
    <label for="viewpoint"><img src="../img/Viewpoint.jpg" /></label>
    <input type="checkbox" name="cbox" value="restaurant" class="places"/>
    <label for="restaurant"><img src="../img/Restaurant.jpg" /></label>
    <input type="checkbox" name="cbox" value="museum" class="places" />
    <label for="historical"><img src="../img/Historical.jpg" /></label>
  </form>

</form>
</code>```

This is the code for getting the checkbox values into the array:

```<code>$(".places").change(function()
    {
        placeT = [];
        $(".places").each(function()
        {
            if( $(this).is(':checked') )
            {
                placeT.push($(this).val());
            }
        });
        alert( placeT );
    });
</code>```

This is the JavaScript for joining the elements and performing the place search:

```<code>function findPlaces(boxes,searchIndex) {

   var typeP = placeT.join('", "');

   var request = {
       bounds: boxes[searchIndex],
       types: typeP
   };

   //alert(request.bounds);
   service.radarSearch(request, function (results, status) {
   if (status != google.maps.places.PlacesServiceStatus.OK) {
     alert("Request["+searchIndex+"] failed: "+status);

   }
   // alert(results.length);
   document.getElementById('side_bar').innerHTML += "bounds["+searchIndex+"] returns "+results.length+" results<br>"
   for (var i = 0, result; result = results[i]; i++) {
     var marker = createMarker(result);
   }
   searchIndex++;
   if (searchIndex < boxes.length)
     findPlaces(boxes,searchIndex);
   });
}
</code>```

The final format for the types in the request needs to be ["museum", "restaurant"] for example. The search works fine as types: ["museum", "restaurant"] but I can't seem to place brackets around the typeP result. Any help is much appreciated!

答: Just pass the array like: var request = { bounds: boxes[searchIndex], types: placeT }; without using the join()</p>

Body:
Using checkbox values to fill an array and then joining those elements I need to put brackets around the joined element to carry out a google place type request.

These are the checkboxes:

<form id= "checkboxes">
 Types of Places
 <link rel="stylesheet" type="text/css"  href="css/style.css">
    <input type="checkbox" name="cbox" value="woodland" class="places"/>

    <input type="checkbox" name="cbox" value="lodging" class="places"/>

    <input type="checkbox" name="cbox" value="restaurant" class="places"/>

    <input type="checkbox" name="cbox" value="museum" class="places" />

  </form>

</form>

This is the code for getting the checkbox values into the array:

$(".places").change(function()
    {
        placeT = [];
        $(".places").each(function()
        {
            if( $(this).is(':checked') )
            {
                placeT.push($(this).val());
            }
        });
        alert( placeT );
    });

This is the JavaScript for joining the elements and performing the place search:

function findPlaces(boxes,searchIndex) {

   var typeP = placeT.join('", "');

   var request = {
       bounds: boxes[searchIndex],
       types: typeP
   };

   //alert(request.bounds);
   service.radarSearch(request, function (results, status) {
   if (status != google.maps.places.PlacesServiceStatus.OK) {
     alert("Request["+searchIndex+"] failed: "+status);

   }
   // alert(results.length);
   document.getElementById('side_bar').innerHTML += "bounds["+searchIndex+"] returns "+results.length+" results
"
   for (var i = 0, result; result = results[i]; i++) {
     var marker = createMarker(result);
   }
   searchIndex++;
   if (searchIndex < boxes.length)
     findPlaces(boxes,searchIndex);
   });
}

The final format for the types in the request needs to be ["museum", "restaurant"] for example. The search works fine as types: ["museum", "restaurant"] but I can't seem to place brackets around the typeP result. Any help is much appreciated!


问:
ERROR ITMS-90164/90046: Invalid Code Signing Entitlements
Note: I'm developing using Xamarin. Similar question posted in Xamarin Forum here

I'm creating an app called, say CompanyApp. Then I created an App ID for it com.Company.CompanyApp, along with Distribution Provisioning Profile that uses the corresponding App ID. I uploaded the binary and it worked perfectly fine.

Then I went on create a demo version of the app (basically the same app with small modification, so it's the same solution & project, just different bundle signing setting), CompanyAppDemo with a new App ID com.Company.CompanyAppDemo, along with a new Distribution Provisioning Profile that uses the new App ID. I updated the iOS Bundle Signing options to use the new Provisioning Profile and generated the IPA. But when I uploaded this to Application Loader, I got the following error:

[2015-01-23 16:08:21 SGT] ERROR: ERROR ITMS-90164: "Invalid Code
  Signing Entitlements. The entitlements in your app bundle signature do
  not match the ones that are contained in the provisioning profile.
  According to the provisioning profile, the bundle contains a key value
  that is not allowed: 'TEAMID.com.Company.CompanyApp' for the key
  'application-identifier' in 'Payload/CompanyApp.app/CompanyApp'"

[2015-01-23 16:08:21 SGT] ERROR: ERROR ITMS-90046: "Invalid Code
  Signing Entitlements. Your application bundle's signature contains
  code signing entitlements that are not supported on iOS. Specifically,
  value 'TEAMID.com.Company.CompanyApp' for key 'application-identifier'
  in 'Payload/CompanyApp.app/CompanyApp' is not supported. This value
  should be a string starting with your TEAMID, followed by a dot '.',
  followed by the bundle identifier."

I have been debugging for days to figure out to no avail.

I am wondering why when I signed with the new
profile, the error that Application Loader threw refer to the ID of the original TEAMID.com.Company.CompanyApp instead of TEAMID.com.Company.CompanyAppDemo? Is this a bug in Xamarin that pick up a wrong provisioning profile or am I missing something? You don't need different certificate for different app right?

Note that I have always refreshed the Provisioning Profile list in XCode > Preference before changing the iOS Build Signing option in Xamarin.

答: For me, the problem was a Entitlements.plist that was auto-added and was empty. Removed it from the Custom entitlements field and solved the problem.


问:
Nested promises while using Array.map, using Promise.all but still not working
I've been banging my head against a wall for some time now. I have some node code that pulls a bunch of googlecalendar events and then maps these onto a different object structure for use in my webapp... As part of this I need to match the users in the google calendar event with the users in my webapp's database. Here's the code:

```<code>router.post('/getCalendar', function(req,res) {
  // authentication
  var oauth2Client = getOAuthClient();
  var session = req.session;
  oauth2Client.setCredentials({
    access_token: req.user.google.token,
    refresh_token: req.user.google.refreshToken,
    expiry_date: true
  })

  var p = new Promise(function (resolve, reject) {
    // get the next 20 calendar events
    var calendar = google.calendar('v3');
      calendar.events.list({
        auth: oauth2Client,
        calendarId: 'primary',
        timeMin: (new Date()).toISOString(),
        maxResults: 20,
        singleEvents: true,
        orderBy: 'startTime'
      }, function(err, response) {
        if (err) console.log('err',err)
          // displays all the events
        if (response) console.log('response',response)
        if(response) {
          var events = response.items;
          resolve(events || err);
        }
    });

  }).then(function (data) {

    var newdata = data.map(function(item) {
      // create the new object structure and populate with some details
      newObj = {
          _id: item.id,
          _title: item.summary,
          group: [req.headers.group],
          fields: [],
          assignedTo: [],
          google: "calendar",
          googledata: item,
          _category: []
      }

      var extendedFields = {}

      // get the list of attendees
      attendees = item.attendees.map(function(user) {
        var attendee = user.email;
        return attendee;
      })

      // pulls the user information for each attendee using promises
      var promises = attendees.map(function(email) {
        return new Promise(function(resolve, reject) {

          // data is in a mongodb, using mongoose
          User.findOne({'google.email': email}).exec(function (err, user) {
            if (err) return resolve(null);
            resolve(user); //not using reject at all so the Promise.all shouldn't fail
          });
        })
      })

      Promise.all(promises)
        .then(function(value) {
          value.forEach(function(user) {
            if(promise !== null) {
              newObj.assignedTo.push(user);
            }
          });

          return newObj

      }).catch((error) => {console.log(error)})

  })

  res.json(newdata)
  })

});
</code>```

I am using Promise.all to wait till all the promises have resolved, but it seems to move onto the next item in the data array before completing the first. Any guidance would be welcome. Please let me know if more details are required.

Thank you.

答:
return promise of last Promise.all.

```<code>return Promise.all(promises)
    .then(function(value) {
      value.forEach(function(user) {
        // user !== null ?
        if(promise !== null) {
          newObj.assignedTo.push(user);
        }
      });

      return newObj
    })
    .catch((error) => {console.log(error)})
</code>```

use Promise.all on newdata.

```<code>Promise.all(newdata)
  .then(function (newObjs) {
    // newObjs is the Array of newObj in your code
    res.json(newObjs);
  })
  .catch(function (err) {
    console.log(err);
  });
</code>```

Body:
I've been banging my head against a wall for some time now. I have some node code that pulls a bunch of googlecalendar events and then maps these onto a different object structure for use in my webapp... As part of this I need to match the users in the google calendar event with the users in my webapp's database. Here's the code:

router.post('/getCalendar', function(req,res) {
  // authentication
  var oauth2Client = getOAuthClient();
  var session = req.session;
  oauth2Client.setCredentials({
    access_token: req.user.google.token,
    refresh_token: req.user.google.refreshToken,
    expiry_date: true
  })

  var p = new Promise(function (resolve, reject) {
    // get the next 20 calendar events
    var calendar = google.calendar('v3');
      calendar.events.list({
        auth: oauth2Client,
        calendarId: 'primary',
        timeMin: (new Date()).toISOString(),
        maxResults: 20,
        singleEvents: true,
        orderBy: 'startTime'
      }, function(err, response) {
        if (err) console.log('err',err)
          // displays all the events
        if (response) console.log('response',response)
        if(response) {
          var events = response.items;
          resolve(events || err);
        }
    });

  }).then(function (data) {

    var newdata = data.map(function(item) {
      // create the new object structure and populate with some details
      newObj = {
          _id: item.id,
          _title: item.summary,
          group: [req.headers.group],
          fields: [],
          assignedTo: [],
          google: "calendar",
          googledata: item,
          _category: []
      }

      var extendedFields = {}

      // get the list of attendees
      attendees = item.attendees.map(function(user) {
        var attendee = user.email;
        return attendee;
      })

      // pulls the user information for each attendee using promises
      var promises = attendees.map(function(email) {
        return new Promise(function(resolve, reject) {

          // data is in a mongodb, using mongoose
          User.findOne({'google.email': email}).exec(function (err, user) {
            if (err) return resolve(null);
            resolve(user); //not using reject at all so the Promise.all shouldn't fail
          });
        })
      })

      Promise.all(promises)
        .then(function(value) {
          value.forEach(function(user) {
            if(promise !== null) {
              newObj.assignedTo.push(user);
            }
          });

          return newObj

      }).catch((error) => {console.log(error)})

  })

  res.json(newdata)
  })

});

I am using Promise.all to wait till all the promises have resolved, but it seems to move onto the next item in the data array before completing the first. Any guidance would be welcome. Please let me know if more details are required.

Thank you.

Body:
return promise of last Promise.all.

return Promise.all(promises)
    .then(function(value) {
      value.forEach(function(user) {
        // user !== null ?
        if(promise !== null) {
          newObj.assignedTo.push(user);
        }
      });

      return newObj
    })
    .catch((error) => {console.log(error)})

use Promise.all on newdata.

Promise.all(newdata)
  .then(function (newObjs) {
    // newObjs is the Array of newObj in your code
    res.json(newObjs);
  })
  .catch(function (err) {
    console.log(err);
  });


问:
Displaying a Django query result in HTML - table, list, css divs?
I am working on an django application that will return what historically was a table of information:

```<code>ISSUE  DESCRIPTION  INITIATOR  INITIATEDDATE  ASSIGNEE  FORECASTDATE  STATUS  REMARKS
</code>```

That will be the entrance point for users to sort / filter, etc the list of issues.

The columns like ISSUE, DATES, NAMES are of relatively fixed width, but others can be a paragraph or more.

What is the best way to render this in HTML?  As HTML Tables, lists or with a lot of CSS spans/divs?

I eventually hope to make the issues list sortable or filterable with javascript as well.

答:
The whole argument made by the CSS purists is that you need to keep your code semantically relevant to the information it contains. What you need to show is tabular data and you use the
 tag to do that. The only "problem" with tables is when they are used to control the layout, like making your two column layout two s as opposed to two
s. In this case, however, tables would be adequate.

OwnerDisplayName: Technical Bard

Body:
I am working on an django application that will return what historically was a table of information:

ISSUE  DESCRIPTION  INITIATOR  INITIATEDDATE  ASSIGNEE  FORECASTDATE  STATUS  REMARKS

That will be the entrance point for users to sort / filter, etc the list of issues.

The columns like ISSUE, DATES, NAMES are of relatively fixed width, but others can be a paragraph or more.

What is the best way to render this in HTML?  As HTML Tables, lists or with a lot of CSS spans/divs?

I eventually hope to make the issues list sortable or filterable with javascript as well.

LastEditorDisplayName: Peter Hilton

Body: The whole argument made by the CSS purists is that you need to keep your code semantically relevant to the information it contains. What you need to show is tabular data and you use the <table> tag to do that. The only "problem" with tables is when they are used to control the layout, like making your two column layout two <td>s as opposed to two <div>s. In this case, however, tables would be adequate.

OwnerDisplayName: Paolo Bergantino


问:
How to create an in-between library?
I am looking for some information on how to achieve something with libraries in C++ and c#.
What I would like to know is how to approach the following problem:

C# application:    -has a window

C++ library:    -has a function called create_button(x,y), when

invoked, it will create a button on

the c# application's window. (if the
C# application is not running,

nothing will happen)

C++ application:    -dynamicaly links to the C++ library and calls the create_button()
function.

How would I approach this problem, I would be glad to hear some of your ideas.
The platform is windows. My question is, how would I let the C++ library communicate to the c# application to create a new button? Is it linked, sockets, ... I'm particulary thinking of GTK+ in linux, you link to the gtk+ library, but how does the library interface with GNOME to create a new window etc, something like that. I'm not interested in writing dlls and linking those to a c# application, I'm interested in creating an in-between library.

答: I can't think of any sane way to do what you want to do.  What I believe you should be doing is creating functions to do the drawing in the C# app and then exposing some messaging interface, such as a socket, that allows external apps to send messages that command the C# app to do what you tell it.  When the C# app receives messages of with message type DRAW_BUTTON, it draws the button, with whatever parameters were specified in the message it received.  </p>

Title: How to create an in-between library?