问:
Inserting a Script into a PHP Variable
Im building a mailing contact form for my site. Its PHP.

I want to know my visitors Screen Width and Height so Ive tried adding the Scripts to my $variable =; But Ive had no luck. Every email sends the variable as etc rather using the code to give me a result.

```<code><head><style>
<?
$screenwidth = '<script type="text/javascript">document.write(screen.availWidth);</script>';
?>
</style></head>
<body>

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['submit']))

{
$ipadd = $_SERVER['REMOTE_ADDR'];
$agent = $_SERVER['HTTP_USER_AGENT'];
$screen = "$screenwidth";
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$mobile = $_POST['mob'];
$address = $_POST['addr'];
$formcontent="$name \n$mobile \n$address \r\nMessage: $message \r\nBrowser: $agent \nIP: $ipadd \n $screen \r\n";
$recipient = "";
$subject = $_POST['subject'];
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");

echo "<h3>Thank You!</h3><h4>Expect a response within 24 hours</h4>";
}
?>
</code>```

Not having any luck. Could someone let me know my error?
Cheers

答:
```<code><head>
    <style>
    </style>
</head>
<body>

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);

    if(isset($_POST['submit'])) {
        $ipadd = $_SERVER['REMOTE_ADDR'];
        $agent = $_SERVER['HTTP_USER_AGENT'];

        $screen = '<script type="text/javascript">document.write(screen.availWidth);</script>';
        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];
        $mobile = $_POST['mob'];
        $address = $_POST['addr'];
        $formcontent="$name \n$mobile \n$address \r\nMessage: $message \r\nBrowser:
        $agent \nIP: $ipadd \n $screen \r\n";
        $recipient = "";
        $subject = $_POST['subject'];
        $mailheader = "From: $email \r\n";
        mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
        echo "<h3>Thank You!</h3><h4>Expect a response within 24 hours</h4>";
    }
?>
</code>```

Title: Inserting a Script into a PHP Variable

Body:
Im building a mailing contact form for my site. Its PHP.

I want to know my visitors Screen Width and Height so Ive tried adding the Scripts to my $variable =; But Ive had no luck. Every email sends the variable as etc rather using the code to give me a result.

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['submit']))

{
$ipadd = $_SERVER['REMOTE_ADDR'];
$agent = $_SERVER['HTTP_USER_AGENT'];
$screen = "$screenwidth";
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$mobile = $_POST['mob'];
$address = $_POST['addr'];
$formcontent="$name \n$mobile \n$address \r\nMessage: $message \r\nBrowser: $agent \nIP: $ipadd \n $screen \r\n";
$recipient = "";
$subject = $_POST['subject'];
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");

echo "
Thank You!

Expect a response within 24 hours
";
}
?>

Not having any luck. Could someone let me know my error?
Cheers


来源: stackexchange

问:
Transfering Data From BigQuery Datasets to my Own Created BigQuery Table
I have a project in big query with its all datasets now I want to know how data is coming from firebase to those datasets, And I have created one new own table in bigquery. How can I push the data from any tables of dataset to my own created table?
This query contains all the fields of the dataset table which I want to in my own table.</p>

```<code>SELECT
user_dim.device_info.device_category
user_dim.device_info.mobile_brand_name

user_dim.device_info.mobile_model_name
user_dim.device_info.mobile_marketing_nam
FROM [in_mylo_pregnancy_baby_app_ANDROID.app_events]
</code>```

答:
Assuming that user_dim is an array, you can use a query such as this one. Make sure to include the #standardSQL.

```<code>#standardSQL
SELECT
  user_dim.device_info.device_category
  user_dim.device_info.mobile_brand_name
  user_dim.device_info.mobile_model_name
  user_dim.device_info.mobile_marketing_nam
FROM `in_mylo_pregnancy_baby_app_ANDROID.app_events`
CROSS JOIN UNNEST(user_dim) AS user_dim;
</code>```

Now all of the fields will be top level columns in the resulting table. If it is not an array, then just select those fields directly:

```<code>#standardSQL
SELECT
  user_dim.device_info.device_category
  user_dim.device_info.mobile_brand_name
  user_dim.device_info.mobile_model_name
  user_dim.device_info.mobile_marketing_nam
FROM `in_mylo_pregnancy_baby_app_ANDROID.app_events;
</code>```

Please stop trying to ask multiple questions, since that is not how StackOverflow works. See how to ask.

ContentLicense: CC BY-SA 3.0

Body:
I have a project in big query with its all datasets now I want to know how data is coming from firebase to those datasets, And I have created one new own table in bigquery. How can I push the data from any tables of dataset to my own created table?
This query contains all the fields of the dataset table which I want to in my own table.

SELECT
user_dim.device_info.device_category
user_dim.device_info.mobile_brand_name

user_dim.device_info.mobile_model_name
user_dim.device_info.mobile_marketing_nam
FROM [in_mylo_pregnancy_baby_app_ANDROID.app_events]

Body:
Assuming that user_dim is an array, you can use a query such as this one. Make sure to include the #standardSQL.

#standardSQL
SELECT
  user_dim.device_info.device_category
  user_dim.device_info.mobile_brand_name
  user_dim.device_info.mobile_model_name
  user_dim.device_info.mobile_marketing_nam
FROM `in_mylo_pregnancy_baby_app_ANDROID.app_events`
CROSS JOIN UNNEST(user_dim) AS user_dim;

Now all of the fields will be top level columns in the resulting table. If it is not an array, then just select those fields directly:

#standardSQL
SELECT
  user_dim.device_info.device_category
  user_dim.device_info.mobile_brand_name
  user_dim.device_info.mobile_model_name
  user_dim.device_info.mobile_marketing_nam
FROM `in_mylo_pregnancy_baby_app_ANDROID.app_events;

Please stop trying to ask multiple questions, since that is not how StackOverflow works. See how to ask.


问:
What is the difference between updated hook and watchers in VueJS?
I'm discovering VueJS and I don't understand exactly the differences between updated and watchers.

Updated hook

It is a lifecycle hook. According to the official documentation, it is triggered whenever data changes. So whenever a prop or a data is updated (the value, not only the pointer), updated is called.

Watchers

In the documentation, watchers are compared to computed properties. But in which cases would it be best to use updated instead of watchers ?

It seems that in both cases, DOM is not updated when the callback is called (nextTick() is required if we want to manipulate the changes in the DOM). The only difference I see is that watchers are only triggered when one precise property (or data) is updated where updated is always called.

I can't figure out what are the pros of updating whenever a data changes (updating) if we can be more accurate (watchers).

Here are my thoughts.

Thanks :)

答: The lifecycle hooks around update respond to changes in the DOM. Watchers respond to changes in the data. DOM changes are generally in response to data changes, but they might not be data owned by the component in question. One example where updated could be used is noticing that slot content has updated.

ContentLicense: CC BY-SA 4.0


问:
Angular2 Unit Test Not Using Mock Service
I am testing a very simple component that shows/hides the login/out buttons.

For this I am mocking my AuthService service as that relies AngularFire2.

The problem I am having is that is appears my mock service (Mock AuthService) isn't being provided in place of the actual AuthService.

In the test should show the Facebook login button, service.isAnonymous is expected to be undefined. In the actual service, it is. But in the mock service is is true. This test should fail.

Also, notice I am trying to call the method service.test(false);; in the mock service this method exists and is public. But I receive the error:

Property 'test' does not exist on type 'AuthService'.

This suggests that my mock service is not being provided.

You can see how I have tried two way to provide the mock service (one is commented out) in my test spec:

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

import { FacebookLoginComponent } from './facebook-login.component';
import { AuthService } from '../shared/auth.service';
import { MockAuthService } from '../shared/testing/auth.service';

describe('FacebookLoginComponent', () => {
  let authService: AuthService;
  let component: FacebookLoginComponent;
  let fixture: ComponentFixture<FacebookLoginComponent>;
  let debugElement: DebugElement;
  let htmlElement: HTMLElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ FacebookLoginComponent ],
      // providers: [{ provide: AuthService, useValue: MockAuthService }]
    })
      .compileComponents();

    TestBed.overrideComponent(FacebookLoginComponent, {
      set: {
        providers: [{ provide: AuthService, useClass: MockAuthService }]
      }
    })
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(FacebookLoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });

  it('should show the Facebook login button', inject([ AuthService ], (service: AuthService) => {
    expect(service.isAnonymous).toBeUndefined();

    debugElement = fixture.debugElement.query(By.css('button'));
    htmlElement = debugElement.nativeElement;

    service.test(false);

    expect(htmlElement.textContent).toBe('Facebook Login');
  }));

  it('should show the Logout button', () => {
    debugElement = fixture.debugElement.query(By.css('button'));
    htmlElement = debugElement.nativeElement;

    expect(htmlElement.textContent).toBe('Logout');
  });
});
</code>```

For completeness; here is my mock service, MockAuthService:

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

@Injectable()
export class MockAuthService {
  public authState: { isAnonymous: boolean, uid: string };

  constructor() {
    this.authState = { isAnonymous: true, uid: '0HjUd9owxPZ5kibvUCN6S2DgB4x1' };
  }

  // public get currentUser(): firebase.User {
  //   return this.authState ? this.authState : undefined;
  // }

  // public get currentUserObservable(): Observable<firebase.User> {
  //   return this.afAuth.authState;
  // }

  public get currentUid(): string {
    return this.authState ? this.authState.uid : undefined;
  }

  public get isAnonymous(): boolean {
    return this.authState ? this.authState.isAnonymous : false;
  }

  public get isAuthenticated(): boolean {
    return !!this.authState;
  }

  // public logout(): void {
  //   this.afAuth.auth.signOut();
  // }

  public test(isAnonymous: boolean) {
    this.authState.isAnonymous = isAnonymous;
  }
}
</code>```

I am at a loss as to how to provide the mock instead.

Update:

Based on answers and comments so far I have update my mock test spec. However, I am still having the same issue.

I get the error Property 'test' does not exist on type 'AuthService'.

This suggests it is still not substituting the mock for the actual authService service.

Furthermore, when I add:

```<code>public test(test: boolean): boolean {
  return test;
}
</code>```

To the actual service the test fails; but not because of the error above, but because it should — the expectations of the test are not met.

This is my updated spec:

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

import { FacebookLoginComponent } from './facebook-login.component';
import { AuthService } from '../shared/auth.service';
import { MockAuthService } from '../shared/testing/auth.service';

describe('FacebookLoginComponent', () => {
  let authService: AuthService;
  let component: FacebookLoginComponent;
  let fixture: ComponentFixture<FacebookLoginComponent>;
  let debugElement: DebugElement;
  let htmlElement: HTMLElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ FacebookLoginComponent ],
      providers: [{ provide: AuthService, useClass: MockAuthService }]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(FacebookLoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });

  it('should show the Facebook Login button', inject([ AuthService ], (service: AuthService) => {
    debugElement = fixture.debugElement.query(By.css('button'));
    htmlElement = debugElement.nativeElement;

    expect(htmlElement.textContent).toBe('Facebook Login');
  }));

  it('should show the Logout button', inject([ AuthService ], (service: AuthService) => {
    expect(service.isAnonymous).toBe(true);

    debugElement = fixture.debugElement.query(By.css('button'));
    htmlElement = debugElement.nativeElement;

    service.test(false);

    fixture.detectChanges();

    expect(htmlElement.textContent).toBe('Logout');
  }));
});
</code>```

答:
```<code>beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ FacebookLoginComponent ],
      // providers: [{ provide: AuthService, useValue: MockAuthService }]
    })
      .compileComponents();

    TestBed.overrideComponent(FacebookLoginComponent, {
      set: {
        providers: [{ provide: AuthService, useClass: MockAuthService }]
      }
    })
  }));
</code>```

There are two problems.
You don't need to override component's providers because you can provide them when configuring the TestBed.

I assume that you've started overriding the component because the initial configuration didn't work. It didn't work because you've used useValue instead of useClass.

```<code>  // providers: [{ provide: AuthService, useValue: MockAuthService }]
</code>```

This should do:

```<code>beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ FacebookLoginComponent ],
      providers: [{ provide: AuthService, useClass: MockAuthService }]
    }).compileComponents();
  }));
</code>```

EDIT:

When using inject function, you should use MockAuthService as a type. TypeScript should stop complaining.

```<code>inject([ AuthService ], (service: MockAuthService) => { /* ... */ });
</code>```

Body:
I am testing a very simple component that shows/hides the login/out buttons.

For this I am mocking my AuthService service as that relies AngularFire2.

The problem I am having is that is appears my mock service (Mock AuthService) isn't being provided in place of the actual AuthService.

In the test should show the Facebook login button, service.isAnonymous is expected to be undefined. In the actual service, it is. But in the mock service is is true. This test should fail.

Also, notice I am trying to call the method service.test(false);; in the mock service this method exists and is public. But I receive the error:

Property 'test' does not exist on type 'AuthService'.

This suggests that my mock service is not being provided.

You can see how I have tried two way to provide the mock service (one is commented out) in my test spec:

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

import { FacebookLoginComponent } from './facebook-login.component';
import { AuthService } from '../shared/auth.service';
import { MockAuthService } from '../shared/testing/auth.service';

describe('FacebookLoginComponent', () => {
  let authService: AuthService;
  let component: FacebookLoginComponent;
  let fixture: ComponentFixture<FacebookLoginComponent>;
  let debugElement: DebugElement;
  let htmlElement: HTMLElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ FacebookLoginComponent ],
      // providers: [{ provide: AuthService, useValue: MockAuthService }]
    })
      .compileComponents();

    TestBed.overrideComponent(FacebookLoginComponent, {
      set: {
        providers: [{ provide: AuthService, useClass: MockAuthService }]
      }
    })
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(FacebookLoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });

  it('should show the Facebook login button', inject([ AuthService ], (service: AuthService) => {
    expect(service.isAnonymous).toBeUndefined();

    debugElement = fixture.debugElement.query(By.css('button'));
    htmlElement = debugElement.nativeElement;

    service.test(false);

    expect(htmlElement.textContent).toBe('Facebook Login');
  }));

  it('should show the Logout button', () => {
    debugElement = fixture.debugElement.query(By.css('button'));
    htmlElement = debugElement.nativeElement;

    expect(htmlElement.textContent).toBe('Logout');
  });
});

For completeness; here is my mock service, MockAuthService:

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

@Injectable()
export class MockAuthService {
  public authState: { isAnonymous: boolean, uid: string };

  constructor() {
    this.authState = { isAnonymous: true, uid: '0HjUd9owxPZ5kibvUCN6S2DgB4x1' };
  }

  // public get currentUser(): firebase.User {
  //   return this.authState ? this.authState : undefined;
  // }

  // public get currentUserObservable(): Observable<firebase.User> {
  //   return this.afAuth.authState;
  // }

  public get currentUid(): string {
    return this.authState ? this.authState.uid : undefined;
  }

  public get isAnonymous(): boolean {
    return this.authState ? this.authState.isAnonymous : false;
  }

  public get isAuthenticated(): boolean {
    return !!this.authState;
  }

  // public logout(): void {
  //   this.afAuth.auth.signOut();
  // }

  public test(isAnonymous: boolean) {
    this.authState.isAnonymous = isAnonymous;
  }
}

I am at a loss as to how to provide the mock instead.

Update:

Based on answers and comments so far I have update my mock test spec. However, I am still having the same issue.

I get the error Property 'test' does not exist on type 'AuthService'.

This suggests it is still not substituting the mock for the actual authService service.

Furthermore, when I add:

public test(test: boolean): boolean {
  return test;
}

To the actual service the test fails; but not because of the error above, but because it should — the expectations of the test are not met.

This is my updated spec:

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

import { FacebookLoginComponent } from './facebook-login.component';
import { AuthService } from '../shared/auth.service';
import { MockAuthService } from '../shared/testing/auth.service';

describe('FacebookLoginComponent', () => {
  let authService: AuthService;
  let component: FacebookLoginComponent;
  let fixture: ComponentFixture<FacebookLoginComponent>;
  let debugElement: DebugElement;
  let htmlElement: HTMLElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ FacebookLoginComponent ],
      providers: [{ provide: AuthService, useClass: MockAuthService }]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(FacebookLoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });

  it('should show the Facebook Login button', inject([ AuthService ], (service: AuthService) => {
    debugElement = fixture.debugElement.query(By.css('button'));
    htmlElement = debugElement.nativeElement;

    expect(htmlElement.textContent).toBe('Facebook Login');
  }));

  it('should show the Logout button', inject([ AuthService ], (service: AuthService) => {
    expect(service.isAnonymous).toBe(true);

    debugElement = fixture.debugElement.query(By.css('button'));
    htmlElement = debugElement.nativeElement;

    service.test(false);

    fixture.detectChanges();

    expect(htmlElement.textContent).toBe('Logout');
  }));
});

Body:
beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ FacebookLoginComponent ],
      // providers: [{ provide: AuthService, useValue: MockAuthService }]
    })
      .compileComponents();

    TestBed.overrideComponent(FacebookLoginComponent, {
      set: {
        providers: [{ provide: AuthService, useClass: MockAuthService }]
      }
    })
  }));

There are two problems.
You don't need to override component's providers because you can provide them when configuring the TestBed.

I assume that you've started overriding the component because the initial configuration didn't work. It didn't work because you've used useValue instead of useClass.

  // providers: [{ provide: AuthService, useValue: MockAuthService }]

This should do:

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ FacebookLoginComponent ],
      providers: [{ provide: AuthService, useClass: MockAuthService }]
    }).compileComponents();
  }));

EDIT:

When using inject function, you should use MockAuthService as a type. TypeScript should stop complaining.

inject([ AuthService ], (service: MockAuthService) => { /* ... */ });


问:
Can I run rubygems in ironruby?
Is it currently possible with pre release of ironruby to run rubygems? It seems as if I have to set an environment variable to find them? </p>

答:
You've been able to run rubygems under IronRuby for quite a while now. Simply download and install the latest IronRuby from codeplex, and run igem on the command line

Original Answer:

I'm on that mailing list - to save you the digging, someone asked this a few weeks ago, and this was the answer

The answer (at this point) is no, you can't, but it doesn't seem like it'll be too far away.

PS: listen to curt. He's on the core team for ironruby. <3

OwnerDisplayName: Christi

ContentLicense: CC BY-SA 2.5

Title: Can I run rubygems in ironruby?

OwnerDisplayName: Orion Edwards


问:
WPF ActualWidth is zero
I have a user control which has a Canvas of height 100 and width 1920.

At the loading of the control, I go to an external source, download a text file and add TextBlocks to the Canvas. Then I want to create a marquee scrolling effect which should work just fine, except after I add the TextBlocks to the Canvas, I need to get their width for calculation purposes but the ActualWidth property is always zero.

Here is some code:

```<code>private readonly LinkedList<TextBlock> textBlocks = new LinkedList<TextBlock>();

public LocalNewsControl()
{
    Loaded += LocalNewsControlLoaded;
}

private void LocalNewsControlLoaded(object sender, RoutedEventArgs e)
{
    LoadDataContext();
}

private void LoadDataContext()
{
    DataContext = new NewsItemsViewModel((exception) => LoadNewsItems());
}

private void LoadNewsItems()
{
    var viewModel = (NewsItemsViewModel)DataContext;

    NewsCanvas.Children.Clear();
    textBlocks.Clear();

    foreach (var newsViewModel in viewModel.NewsItems)
    {
        var tb = new TextBlock
        {
            Text = newsViewModel.Headline,
            FontSize = 28,
            FontWeight = FontWeights.Normal,
            Foreground = Brushes.Black
        };

        NewsCanvas.Children.Add(tb);

        Canvas.SetTop(tb, 20);
        Canvas.SetLeft(tb, -999);

        textBlocks.AddLast(tb);
    }

    Dispatcher.BeginInvoke(new Action(() =>
    {
        var node = textBlocks.First;

        while (node != null)
        {
            if (node.Previous != null)
            {
                //THIS IS WHERE ActualWidth is always ZERO
                var left = Canvas.GetLeft(node.Previous.Value) + node.Previous.Value.ActualWidth + Gap;
                Canvas.SetLeft(node.Value, left);
            }
            else
                Canvas.SetLeft(node.Value, NewsCanvas.Width + Gap);

            node = node.Next;
        }
    }));
}
</code>```

答: Is there any particular reason for using Canvas for the layout of the TextBlocks? If not, you'd better use a StackPanel with Horizontal orientation, it will handle the layout math for you.

Title: WPF ActualWidth is zero

Body:
I have a user control which has a Canvas of height 100 and width 1920.

At the loading of the control, I go to an external source, download a text file and add TextBlocks to the Canvas. Then I want to create a marquee scrolling effect which should work just fine, except after I add the TextBlocks to the Canvas, I need to get their width for calculation purposes but the ActualWidth property is always zero.

Here is some code:

private readonly LinkedList<TextBlock> textBlocks = new LinkedList<TextBlock>();

public LocalNewsControl()
{
    Loaded += LocalNewsControlLoaded;
}

private void LocalNewsControlLoaded(object sender, RoutedEventArgs e)
{
    LoadDataContext();
}

private void LoadDataContext()
{
    DataContext = new NewsItemsViewModel((exception) => LoadNewsItems());
}

private void LoadNewsItems()
{
    var viewModel = (NewsItemsViewModel)DataContext;

    NewsCanvas.Children.Clear();
    textBlocks.Clear();

    foreach (var newsViewModel in viewModel.NewsItems)
    {
        var tb = new TextBlock
        {
            Text = newsViewModel.Headline,
            FontSize = 28,
            FontWeight = FontWeights.Normal,
            Foreground = Brushes.Black
        };

        NewsCanvas.Children.Add(tb);

        Canvas.SetTop(tb, 20);
        Canvas.SetLeft(tb, -999);

        textBlocks.AddLast(tb);
    }

    Dispatcher.BeginInvoke(new Action(() =>
    {
        var node = textBlocks.First;

        while (node != null)
        {
            if (node.Previous != null)
            {
                //THIS IS WHERE ActualWidth is always ZERO
                var left = Canvas.GetLeft(node.Previous.Value) + node.Previous.Value.ActualWidth + Gap;
                Canvas.SetLeft(node.Value, left);
            }
            else
                Canvas.SetLeft(node.Value, NewsCanvas.Width + Gap);

            node = node.Next;
        }
    }));
}


问:
No Thrift TDebugProtocol?
I'm setting up a Thrift server in Java, and I'm trying to set up a TDebugProtocol (mentioned in the Thrift documentation here), but there doesn't seem to be a TDebugProtocol.java file in the protocol folder of the Thrift library.

Does this protocol no longer exist?

答: Not all things are equally implemented in all parts of the library. Usually this is where the particular contributor stopped. TDebugProtocol is probably just one of the lesser used ones. But given the C++ version it should not be so hard to build a Java version from it.</p>

Title: No Thrift TDebugProtocol?


问:
Starting jupyterhub with docker
I am starting with docker and jupyterhub. I am following those instructions (https://hub.docker.com/r/jupyter/jupyterhub/). I can start jupyterhub, but I am struggling to start it with docker (dockerspawner
) and to user the oauth authentication with github. Can someone point some tutorial or give some help with this matter?</p>

答:
I really like the approach by https://github.com/minrk/jupyterhub-demo. It features a makefile approach incorporating a nice automation of the necessary steps. You can adjust the bash scripts to suit your own needs. Very nice that it works as good as out of the box.

Some more tips for dockerspawner are to be found here:
https://github.com/jupyterhub/dockerspawner#configuration

He also gave a presentation some time ago: https://www.youtube.com/watch?v=gSVvxOchT8Y

Title: Starting jupyterhub with docker


问:
How do I autocomplete search for usernames from database without using jQuery?
I've seen multiple exams for autocomplete using jQuery.

I've a list of usernames stored in my MySQL database. When the user types his username, I need to autocomplete from the data in the database with use of PHP, mySQL and AJAX (without use of jQuery). How do I do it?

答:
jQuery is mostly just a wrapper, to make commonly used JavaScript expressions easier. However, there is no magic functionality to it, you can - without any problem - use plain JavaScript.

Basically if you want to do it completely server sided (without any JS) you would get a rather bad user experience as a result of the database fetching.

The basic idea is that the client sends a request to the server, which in turn answers with a list of possible results and either lets the js locally adapt the view (the suggestions) or pushes the updated view directly to the client (not smooth).


问:
why combiner function is not executed in java-8 stream reduce operation?
I am trying to understand how the reduce method in streams work.

```<code>Stream.of(1,2,3,4,5,6,7).reduce(new ArrayList<>(),
(List<Integer> l, Integer a) -> {l.add(a);return l;},
(List<Integer> l1, List<Integer> l2) -> {
System.out.println("l1 is" + l1 + "l2 is " + l2);
l1.addAll(l2);
return l1;
}).forEach(System.out::println);
</code>```

The line System.out.println("l1 is" + l1 + "l2 is " + l2) never gets printed.
I can understand what is happening in (List<Integer> l, Integer a) -> {l.add(a);return l;}

Can some one please explain why it is not printed ?
The java docs say function for combining two values, which must be compatible with the accumulator function

Thanks,
Amar

答:
It's only being called when the stream is parallel. In that case, the stream values are split in half (recursively), each half is reduced to a list, and then the two lists must be combined together.

Note that reduction is not supposed to mutate the values (the lists, in this case) received as argument. It's supposed to return a new value. That's what a mutable reduction (i.e. collect()) is a much better choice in this case.

Body:
I am trying to understand how the reduce method in streams work.

Stream.of(1,2,3,4,5,6,7).reduce(new ArrayList<>(),
(List<Integer> l, Integer a) -> {l.add(a);return l;},
(List<Integer> l1, List<Integer> l2) -> {
System.out.println("l1 is" + l1 + "l2 is " + l2);
l1.addAll(l2);
return l1;
}).forEach(System.out::println);

The line System.out.println("l1 is" + l1 + "l2 is " + l2) never gets printed.
I can understand what is happening in (List<Integer> l, Integer a) -> {l.add(a);return l;}

Can some one please explain why it is not printed ?
The java docs say function for combining two values, which must be compatible with the accumulator function

Thanks,
Amar


问:
Change Html control in EditorforModel MVC
I am using EditorforModel for Login Page,
this my model

```<code>[Required]
    public int UserId
    {
        get; set;
    }
    [Required]
    [DataType(DataType.Password)]
    public string Password
    {
        get; set;
    }
    [HiddenInput]
    [ScaffoldColumn(false)]
    public string ReturnUrl
    {
        get; set;
    }
</code>```

This is my view:

```<code>    @model MVCIdentityLogin.Models.LogInModel
@{
    ViewBag.Title = "LogIn";
}

<h2>LogIn</h2>

@Html.ValidationSummary(true)

@using(Html.BeginForm())
{
    @Html.EditorForModel()
    <p>
        <button type="submit"> Log In</button>
    </p>
}
</code>```

my view as :
View
this view Userid input field has increase and decrease button. How to remove it?
I check this html that is

答:
just add this [DataType(DataType.Text)]
 attribute in Userid property
    like this</p>

```<code>[Required]
[DataType(DataType.Text)]
public int UserId
{
    get; set;
}
</code>```

Body:
I am using EditorforModel for Login Page,
this my model

[Required]
    public int UserId
    {
        get; set;
    }
    [Required]
    [DataType(DataType.Password)]
    public string Password
    {
        get; set;
    }
    [HiddenInput]
    [ScaffoldColumn(false)]
    public string ReturnUrl
    {
        get; set;
    }

This is my view:

    @model MVCIdentityLogin.Models.LogInModel
@{
    ViewBag.Title = "LogIn";
}

LogIn

@Html.ValidationSummary(true)

@using(Html.BeginForm())
{
    @Html.EditorForModel()

        <button type="submit"> Log In</button>

}

my view as :
View
this view Userid input field has increase and decrease button. How to remove it?
I check this html that is

Body:
just add this [DataType(DataType.Text)]
 attribute in Userid property
    like this

[Required]
[DataType(DataType.Text)]
public int UserId
{
    get; set;
}


问:
How do I pause the command window when launching an app?
When I launch an Android app via Ctrl+F11 on Eclipse, there are two black command windows (DOS-like) that appear briefly with some important messages in them. Obviously, I can't read what's in them in that brief moment.

Is there a way to pause/freeze them?

Update: @Mayra's answers below provided great tips but they did not solve the problem of pausing/freezing these windows. I know for sure that they contain information not in the Console and not in the logcat. So the question remains.

答: Unless an answer that describes step-by-step how to pause the command window when launching an android app from Eclipse (to the emulator) comes along, the accepted answer is: This cannot be done.


问:
Using stack to get parameters/array address for my procedure in assembly 8086
I have an assignment where I'm told to write a procedure and that there are 3 arrays' addresses that were given to me using the stack, but they don't tell me how they were placed in the stack. Is there a way for me to know how to retrieve those addresses inside of the procedure?</p>

答:
The first thing you need to know is what order the parameters are passed in. Without that, you'll be able to get the three values, but you won't know how to interpret them. But let's press on…

Because the 8086 is a 16-bit microprocessor, pointers are going to be 16 bits in length. In assembly language terms, this would be WORD sized, or 2 bytes.

Generally, when a caller wants to pass parameters to a function, it will PUSH them onto the stack before CALLing the function. So, here is an example of how I might push three WORD sized values onto the stack, and then call the foo function:

```<code>push  3
push  2
push  1
call  foo
add   sp, 6     ; clean up stack after call, adding 6 because we pushed 3 2-byte values
                ; (could also do POP+POP+POP, but that trashes a register and is slower)
</code>```

Pretty simple, right? Notice that I've apparently pushed the parameters in reverse order. This is so that, when they are retrieved in the foo function, they'll appear to be in the correct order (1, 2, 3). This is conventional when calling functions in assembly language, and it's what C compilers will always do when generating code to call a function, so you can assume (if not told otherwise) that this is how your parameters will be passed.

Now, on to your question—how does the foo function retrieve those parameters from the stack?

First, here's how the foo function will start (this is called the prologue code, and it's used at the top of basically every function that needs to interact with the stack):

```<code>foo:
    push  bp       ; save original value of BP
    mov   bp, sp   ; copy current value of SP (stack pointer) into BP (base pointer)
    ...
</code>```

To retrieve the first parameter (and, say, load it in AX), you would then do:

```<code>mov  ax, WORD PTR [bp+4]
</code>```

Why bp+4? Well, after the prologue code, bp contains a pointer to the top of the stack. What's on the stack? Consider the following diagram:

```<code>Low            |====================|
addresses      | Unused space       |
               |                    |
               |====================|    ← SP points here
   ↑           | Function's         |
   ↑           | local variables    |
   ↑           |                    |    ↑ BP - x
direction      |--------------------|    ← BP points here
of stack       | Original/saved BP  |    ↓ BP + x
growth         |--------------------|
   ↑           | Return pointer     |
   ↑           |--------------------|
   ↑           | Function's         |
               | parameters         |
               |                    |
               |====================|
               | Parent             |
               | function's data    |
               |====================|
               | Grandparent        |
High           | function's data    |
addresses      |====================|
</code>```

From that diagram, you can see that:

BP+0 == the original value of BP that you saved in the foo function's prologue by pushing it onto the top of the stack (push bp)

BP+2 == the return pointer (implicitly pushed by CALL, and which will implicitly be used by RET when foo ends)

BP+4 == the first parameter that was passed to the foo function by its caller on the stack

BP+6 == the second parameter

etc.

Again, because you're on the 16-bit 8086, all of these values are WORD sized, so they are each 2 bytes long.

The "function's local variables" section would be used (negative offsets from bp) if you had allocated space on the stack to store some local variables inside of the foo function. But we'll ignore that in this answer for simplicity purposes.

So, let's put it all together and look at a possible implementation for foo:

```<code>foo:
    push  bp                     ; save original value of BP
    mov   bp, sp                 ; set base pointer to top of stack
    mov   ax, WORD PTR [bp+4]    ; get first parameter
    mov   bx, WORD PTR [bp+6]    ; get second parameter
    mov   cx, WORD PTR [bp+8]    ; get third parameter
    ; do something interesting
    leave
    ret
</code>```

Notice the epilogue code that appears there after doing something "interesting"—in particular, the LEAVE instruction. This reverses the prologue code that we saw earlier. LEAVE is equivalent to:

```<code>mov  sp, bp
pop  bp
</code>```

but fewer bytes, so it's commonly used as an optimization on the 8086 (not on newer processors, though, because it's slower than the expanded form on at least the 386 and later).

And that's how you access parameters from the stack!

One more thing, though. You said that these parameters are pointers (addresses), so you need to make sure that you understand how to dereference pointers in assembly language. When we loaded the registers earlier, what we loaded were pointers. If you want to get the first element of the first array, you would do:

```<code>mov  bx, WORD PTR [bp+4]      ; get first parameter (pointer to array)
mov  ax, WORD PTR [bx]        ; dereference pointer to array,
                              ;   putting value of first element in BX
</code>```

Note that in 16-bit mode, you are heavily restricted to certain addressing modes. The only registers that you can use to access memory are BP, BX, SI, and DI. That is why we had to put the stack pointer in BP (instead of using it directly from SP), and why in this last example, I loaded the pointer into BX so I could load from [BX].

Body:
The first thing you need to know is what order the parameters are passed in. Without that, you'll be able to get the three values, but you won't know how to interpret them. But let's press on…

Because the 8086 is a 16-bit microprocessor, pointers are going to be 16 bits in length. In assembly language terms, this would be WORD sized, or 2 bytes.

Generally, when a caller wants to pass parameters to a function, it will PUSH them onto the stack before CALLing the function. So, here is an example of how I might push three WORD sized values onto the stack, and then call the foo function:

push  3
push  2
push  1
call  foo
add   sp, 6     ; clean up stack after call, adding 6 because we pushed 3 2-byte values
                ; (could also do POP+POP+POP, but that trashes a register and is slower)

Pretty simple, right? Notice that I've apparently pushed the parameters in reverse order. This is so that, when they are retrieved in the foo function, they'll appear to be in the correct order (1, 2, 3). This is conventional when calling functions in assembly language, and it's what C compilers will always do when generating code to call a function, so you can assume (if not told otherwise) that this is how your parameters will be passed.

Now, on to your question—how does the foo function retrieve those parameters from the stack?

First, here's how the foo function will start (this is called the prologue code, and it's used at the top of basically every function that needs to interact with the stack):

foo:
    push  bp       ; save original value of BP
    mov   bp, sp   ; copy current value of SP (stack pointer) into BP (base pointer)
    ...

To retrieve the first parameter (and, say, load it in AX), you would then do:

mov  ax, WORD PTR [bp+4]

Why bp+4? Well, after the prologue code, bp contains a pointer to the top of the stack. What's on the stack? Consider the following diagram:

Low            |====================|
addresses      | Unused space       |
               |                    |
               |====================|    ← SP points here
   ↑           | Function's         |
   ↑           | local variables    |
   ↑           |                    |    ↑ BP - x
direction      |--------------------|    ← BP points here
of stack       | Original/saved BP  |    ↓ BP + x
growth         |--------------------|
   ↑           | Return pointer     |
   ↑           |--------------------|
   ↑           | Function's         |
               | parameters         |
               |                    |
               |====================|
               | Parent             |
               | function's data    |
               |====================|
               | Grandparent        |
High           | function's data    |
addresses      |====================|

From that diagram, you can see that:

BP+0 == the original value of BP that you saved in the foo function's prologue by pushing it onto the top of the stack (push bp)

BP+2 == the return pointer (implicitly pushed by CALL, and which will implicitly be used by RET when foo ends)

BP+4 == the first parameter that was passed to the foo function by its caller on the stack

BP+6 == the second parameter

etc.

Again, because you're on the 16-bit 8086, all of these values are WORD sized, so they are each 2 bytes long.

The "function's local variables" section would be used (negative offsets from bp) if you had allocated space on the stack to store some local variables inside of the foo function. But we'll ignore that in this answer for simplicity purposes.

So, let's put it all together and look at a possible implementation for foo:

foo:
    push  bp                     ; save original value of BP
    mov   bp, sp                 ; set base pointer to top of stack
    mov   ax, WORD PTR [bp+4]    ; get first parameter
    mov   bx, WORD PTR [bp+6]    ; get second parameter
    mov   cx, WORD PTR [bp+8]    ; get third parameter
    ; do something interesting
    leave
    ret

Notice the epilogue code that appears there after doing something "interesting"—in particular, the LEAVE instruction. This reverses the prologue code that we saw earlier. LEAVE is equivalent to:

mov  sp, bp
pop  bp

but fewer bytes, so it's commonly used as an optimization on the 8086 (not on newer processors, though, because it's slower than the expanded form on at least the 386 and later).

And that's how you access parameters from the stack!

One more thing, though. You said that these parameters are pointers (addresses), so you need to make sure that you understand how to dereference pointers in assembly language. When we loaded the registers earlier, what we loaded were pointers. If you want to get the first element of the first array, you would do:

mov  bx, WORD PTR [bp+4]      ; get first parameter (pointer to array)
mov  ax, WORD PTR [bx]        ; dereference pointer to array,
                              ;   putting value of first element in BX

Note that in 16-bit mode, you are heavily restricted to certain addressing modes. The only registers that you can use to access memory are BP, BX, SI, and DI. That is why we had to put the stack pointer in BP (instead of using it directly from SP), and why in this last example, I loaded the pointer into BX so I could load from [BX].


问:
Ruby/ RoR - String Hash to Integer Hash
I have an Hash  @answers = params[:Answers].to_hash;

<%= debug @answers %> outs

```<code>---
"1": "2"
"7": "3"
"6": "4"
"4": "0"
</code>```

Need to make the @answers to one like below

@ans = {1 => 2, 7 => 3, 6 => 4, 4 => 0}
<%= debug @answers %> outs

```<code>---
1: 2
7: 3
6: 4
4: 0
</code>```

答:
Black magic wizard reporting in:</p>

```<code>answers = {"1" => "2", "3" => "4"}
Hash[*answers.to_a.flatten.map(&:to_i)] # => {1=>2, 3=>4}
</code>```

Title: Ruby/ RoR - String Hash to Integer Hash

Body:
I have an Hash  @answers = params[:Answers].to_hash;

<%= debug @answers %> outs

---
"1": "2"
"7": "3"
"6": "4"
"4": "0"

Need to make the @answers to one like below

@ans = {1 => 2, 7 => 3, 6 => 4, 4 => 0}
<%= debug @answers %> outs

---
1: 2
7: 3
6: 4
4: 0

Body:
Black magic wizard reporting in:

answers = {"1" => "2", "3" => "4"}
Hash[*answers.to_a.flatten.map(&:to_i)] # => {1=>2, 3=>4}


问:
How can I manipulate MySQL fulltext search relevance to make one field more 'valuable' than another?
Suppose I have two columns, keywords and content. I have a fulltext index across both. I want a row with foo in the keywords to have more relevance than a row with foo in the content. What do I need to do to cause MySQL to weight the matches in keywords higher than those in content?

I'm using the "match against" syntax.

SOLUTION:

Was able to make this work in the following manner:

```<code>SELECT *,
CASE when Keywords like '%watermelon%' then 1 else 0 END as keywordmatch,
CASE when Content like '%watermelon%' then 1 else 0 END as contentmatch,
MATCH (Title, Keywords, Content) AGAINST ('watermelon') AS relevance
FROM about_data
WHERE MATCH(Title, Keywords, Content) AGAINST ('watermelon' IN BOOLEAN MODE)
HAVING relevance > 0
ORDER by keywordmatch desc, contentmatch desc, relevance desc
</code>```

答:
Simpler version using only 2 fulltext indexes (credits taken from @mintywalker):

```<code>SELECT id,
   MATCH (`content_ft`) AGAINST ('keyword*' IN BOOLEAN MODE) AS relevance1,
   MATCH (`title_ft`) AGAINST ('keyword*' IN BOOLEAN MODE) AS relevance2
FROM search_table
HAVING (relevance1 + relevance2) > 0
ORDER BY (relevance1 * 1.5) + (relevance2) DESC
LIMIT 0, 1000;
</code>```

This will search both full indexed columns against the keyword and select matched relevance into two separate columns. We will exclude items with no match (relevance1 and relevance2 are both zero) and reorder results by increased weight of content_ft column. We don't need composite fulltext index.

OwnerDisplayName: Buzz

Body:
Suppose I have two columns, keywords and content. I have a fulltext index across both. I want a row with foo in the keywords to have more relevance than a row with foo in the content. What do I need to do to cause MySQL to weight the matches in keywords higher than those in content?

I'm using the "match against" syntax.

SOLUTION:

Was able to make this work in the following manner:

SELECT *,
CASE when Keywords like '%watermelon%' then 1 else 0 END as keywordmatch,
CASE when Content like '%watermelon%' then 1 else 0 END as contentmatch,
MATCH (Title, Keywords, Content) AGAINST ('watermelon') AS relevance
FROM about_data
WHERE MATCH(Title, Keywords, Content) AGAINST ('watermelon' IN BOOLEAN MODE)
HAVING relevance > 0
ORDER by keywordmatch desc, contentmatch desc, relevance desc

LastEditorDisplayName: Buzz

Body:
Simpler version using only 2 fulltext indexes (credits taken from @mintywalker):

SELECT id,
   MATCH (`content_ft`) AGAINST ('keyword*' IN BOOLEAN MODE) AS relevance1,
   MATCH (`title_ft`) AGAINST ('keyword*' IN BOOLEAN MODE) AS relevance2
FROM search_table
HAVING (relevance1 + relevance2) > 0
ORDER BY (relevance1 * 1.5) + (relevance2) DESC
LIMIT 0, 1000;

This will search both full indexed columns against the keyword and select matched relevance into two separate columns. We will exclude items with no match (relevance1 and relevance2 are both zero) and reorder results by increased weight of content_ft column. We don't need composite fulltext index.


问:
div where i can add Forms and others in HTML
I am starting to learn Web Development from scratch other than using drag and drop Hence i wanted to ask something like this , As a newbie.

Now this takes the code to the Left hand side of the screen for navigation works fine here.

```<code><html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Home</title>
</head>
 <link rel="stylesheet" type="text/css" href="style.css">
<body>

<div align="center">
    <table border="0" width="93%">
        <tr>
            <td> </td>
        </tr>
        <tr>
            <td><h1>Test</h1></td>
        </tr>
        <tr>
            <td> </td>
        </tr>
        <tr>
            <td>
            <div class="left">
            <ul class="nav">
            <li class="selected"><a href="#">Home</a></li>
             <li><a href="#">About</a></li>
            </ul>
            </div>
            <div class ="center">
            </div>
            </td>
        </tr>
    </table>
    <p> </div>

</body>

</html>
</code>```

CSS

```<code>@charset "utf8";
/*CSS Document*/

*{
    padding:0px;
    margin :0px;
}

h1{
    font-family : arial, sans-serif;
    font-weight:400;
    height:60px;
    width:100%
    background-color:black;
    line-height:60px;
    color: white;
}

div{
    width:250px;
    height:666px;
    background:#1a1a1a;

}

div a{
    text-decoration:none;
    color:white;
    padding: 20px;
    padding-right:100px;
}

div ul li{
    list-style-type:none;
    display:block;
    padding:15px;
    border-bottom: 1px solid #CCC;
}

div ul li:hover{
    background:#bfbfbf;
    transition:linear all 0.40s;
    margin-left:10px;
}

div ul li a:hover{
    color:black;
}

.selected{
    background:white;
}

.selected a{
    color:black;
}
</code>```

答: Give margin: 0 auto, then position: absolute and finally left: 0, right: 0 to your class.</p>

Body:
I am starting to learn Web Development from scratch other than using drag and drop Hence i wanted to ask something like this , As a newbie.

Now this takes the code to the Left hand side of the screen for navigation works fine here.

<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Home</title>

 <link rel="stylesheet" type="text/css" href="style.css">

Test

Home

About

CSS

@charset "utf8";
/*CSS Document*/

*{
    padding:0px;
    margin :0px;
}

h1{
    font-family : arial, sans-serif;
    font-weight:400;
    height:60px;
    width:100%
    background-color:black;
    line-height:60px;
    color: white;
}

div{
    width:250px;
    height:666px;
    background:#1a1a1a;

}

div a{
    text-decoration:none;
    color:white;
    padding: 20px;
    padding-right:100px;
}

div ul li{
    list-style-type:none;
    display:block;
    padding:15px;
    border-bottom: 1px solid #CCC;
}

div ul li:hover{
    background:#bfbfbf;
    transition:linear all 0.40s;
    margin-left:10px;
}

div ul li a:hover{
    color:black;
}

.selected{
    background:white;
}

.selected a{
    color:black;
}


问:
Append parameter in url on multiple checkbox group click
I want to rewrite url parameters values on checkbox click, similar to LinkedIn Advance search.

  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3>Filter recepies:</h3>

<div>
<p>Select vegetables</p>
<label><input type="checkbox" id="vegetables[]" value="potato"> Potato</label><br>
<label><input type="checkbox" id="vegetables[]" value="onion"> Onion</label><br>
<label><input type="checkbox" id="vegetables[]" value="tomato"> Tomato</label><br>
</div>

<div>
<p>Select seasoning</p>
<label><input type="checkbox" id="seasoning[]" value="salt"> Salt</label><br>
<label><input type="checkbox" id="seasoning[]" value="pepper"> Pepper</label><br>
<label><input type="checkbox" id="seasoning[]" value="chilli"> Chilli Flakes</label><br>
</div></code>```

My Desired Result

Click1: when I click Potato from  vegitable my URL should look like

example.com?vegitables=potato

Click2: when I click Onion from  vegitable my URL should look like

example.com?vegitables=potato,onion

Click3: when I click salt from  seasoning my URL should look like

example.com?vegitables=potato,onion&seasoning=salt

Click4: when I click pepper from  seasoning my URL should look like

example.com?vegitables=potato,onion&seasoning=salt,pepper

答:
Here is what you can do

$(document).ready(function () {
  $('input[type=checkbox]').click(function (e) {
  var seasoning = '', tempArray = [];
  $('input[name="vegetables[]"]:checked').each(function(){
      tempArray.push($(this).val());
  })
  if(tempArray.length !== 0){
     seasoning+='vegetables='+tempArray.toString();
     tempArray = [];
  }

  $('input[name="seasoning[]"]:checked').each(function(){
      tempArray.push($(this).val());
  })
  if(tempArray.length !== 0){
     seasoning+='&seasoning='+tempArray.toString();
  }

 // window.location ='example.com?seasoning='+seasoning;
 console.log('example.com?'+seasoning);

  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p>Select vegetables</p>
<label><input type="checkbox" name="vegetables[]" value="potato"> Potato</label><br>
<label><input type="checkbox" name="vegetables[]" value="onion"> Onion</label><br>
<label><input type="checkbox" name="vegetables[]" value="tomato"> Tomato</label><br>
</div>

<div>
<p>Select seasoning</p>
<label><input type="checkbox" name="seasoning[]" value="salt"> Salt</label><br>
<label><input type="checkbox" name="seasoning[]" value="pepper"> Pepper</label><br>
<label><input type="checkbox" name="seasoning[]" value="chilli"> Chilli Flakes</label><br>
</div></code>```

For simplicity and further edit here is the link to working JSFIDDLE

Body:
I want to rewrite url parameters values on checkbox click, similar to LinkedIn Advance search.

Filter recepies:

Select vegetables

<input type="checkbox" id="vegetables[]" value="potato"> Potato

<input type="checkbox" id="vegetables[]" value="onion"> Onion

<input type="checkbox" id="vegetables[]" value="tomato"> Tomato

Select seasoning

<input type="checkbox" id="seasoning[]" value="salt"> Salt

<input type="checkbox" id="seasoning[]" value="pepper"> Pepper

<input type="checkbox" id="seasoning[]" value="chilli"> Chilli Flakes

My Desired Result

Click1: when I click Potato from  vegitable my URL should look like

example.com?vegitables=potato

Click2: when I click Onion from  vegitable my URL should look like

example.com?vegitables=potato,onion

Click3: when I click salt from  seasoning my URL should look like

example.com?vegitables=potato,onion&seasoning=salt

Click4: when I click pepper from  seasoning my URL should look like

example.com?vegitables=potato,onion&seasoning=salt,pepper

Body:
Here is what you can do

$(document).ready(function () {
  $('input[type=checkbox]').click(function (e) {
  var seasoning = '', tempArray = [];
  $('input[name="vegetables[]"]:checked').each(function(){
      tempArray.push($(this).val());
  })
  if(tempArray.length !== 0){
     seasoning+='vegetables='+tempArray.toString();
     tempArray = [];
  }

  $('input[name="seasoning[]"]:checked').each(function(){
      tempArray.push($(this).val());
  })
  if(tempArray.length !== 0){
     seasoning+='&seasoning='+tempArray.toString();
  }

 // window.location ='example.com?seasoning='+seasoning;
 console.log('example.com?'+seasoning);

  });

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p>Select vegetables</p>
<label><input type="checkbox" name="vegetables[]" value="potato"> Potato</label><br>
<label><input type="checkbox" name="vegetables[]" value="onion"> Onion</label><br>
<label><input type="checkbox" name="vegetables[]" value="tomato"> Tomato</label><br>
</div>

<div>
<p>Select seasoning</p>
<label><input type="checkbox" name="seasoning[]" value="salt"> Salt</label><br>
<label><input type="checkbox" name="seasoning[]" value="pepper"> Pepper</label><br>
<label><input type="checkbox" name="seasoning[]" value="chilli"> Chilli Flakes</label><br>
</div>

For simplicity and further edit here is the link to working JSFIDDLE


问:
Disabled all the records book button in gridview1 whose name column values is sumit?

I have TextBox1 whose Default text is Sumit and a gridview with records and button field in each row ..

On Page load event

I want if textbox1 text is Sumit .... then all the records in gridview1 whose name column values is sumit .... then that rows Book button will be disabled and rest of all will be remain as it is in Enableed form ...

i m using Visual Studio 2008 with vb

Is this coding is right : ?

```<code>Protected Sub GridView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.DataBound
        For Each myRow As GridViewRow In GridView1.Rows
            'Find the checkbox
            Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
            If lab1.Text = "Sumit" Then
                'Find the Delete linkbutton and hide it
                Dim deleteButton As Button = DirectCast(myRow.FindControl("Button1"), Button)
                deleteButton.Enabled = False
            End If
        Next
    End Sub
</code>```

But this coding doesn't disabled the button .... in rows whose name field is Sumit

答: In the grid view item data bound eventhandler, set button.Enabled = false if "name" in the dataitem is sumit.</p>

Body:
I have TextBox1 whose Default text is Sumit and a gridview with records and button field in each row ..

On Page load event

I want if textbox1 text is Sumit .... then all the records in gridview1 whose name column values is sumit .... then that rows Book button will be disabled and rest of all will be remain as it is in Enableed form ...

i m using Visual Studio 2008 with vb

Is this coding is right : ?

Protected Sub GridView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.DataBound
        For Each myRow As GridViewRow In GridView1.Rows
            'Find the checkbox
            Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
            If lab1.Text = "Sumit" Then
                'Find the Delete linkbutton and hide it
                Dim deleteButton As Button = DirectCast(myRow.FindControl("Button1"), Button)
                deleteButton.Enabled = False
            End If
        Next
    End Sub

But this coding doesn't disabled the button .... in rows whose name field is Sumit


问:
MySQL: why is "1+1" treated as "1" in this query?
All of the following queries return the row with ID == 1, why is that?

SELECT * FROM `my_table` WHERE `ID` = "1"
SELECT * FROM `my_table` WHERE `ID` = "1+1"
SELECT * FROM `my_table` WHERE `ID` = "1 WTF"

答:
When MySql performs a comparison it will do a data type conversion when the data types of the two compared values are not the same. In this case ID is numerical, and you compare it with a string. So MySql will convert the string to number. It does this by reading the digits at the start of the string, stopping as soon as it no longer understands it as a number.

In all three examples you provided that number is 1.

You can read about this in the MySql documentation: "Type Conversion in Expression Evaluation"


问:
Label For radio buttons does not work in popup created using jquery modal popup
THis sounds more like an html issue than jquery and I hope someone could help me with this.

I have a hidden div containing radio buttons which has Label For tag. This works great on the page (I tested by removing hidden property from the div), but when I pull that div content out of on the modal popup created using jquery my Label For does not work on a popup. It seems when I click on the label from my modal window it clicks the appropriate radio on parent page but not the one on modal window.

Thanks for your help.

答:
I added a span tag next to the input with a class="text"</p>

```<code>            <label>
                <input type="radio" name="rr"  />
                <span class="text"> </span>
            </label>
</code>```

Body:
I added a span tag next to the input with a class="text"

            <label>
                <input type="radio" name="rr"  />
                <span class="text">&nbsp;</span>
            </label>


问:
Force cropper to always be either full width or full height
I have been using cropper js.

I am resizing the cropper based on input values(integer). For example A and B.

So when user enters A = 200 and B = 240. The cropper calculates the aspect ratio and shows the cropper. Is there a option or some kind of hack to force the cropper to either force it to fill the width or height based on the ratio?

If i was unclear in my question see images below.
First there is an incorrect image where i got spaces on both sides and at the top and bottom.
Incorrect

This image is correct:
Correct
So at the correct image the user shouldn't be able to make it smaller, and if the the ratio get's below 1 in ratio it should fill the height instead of width.

Do someone have a good soultion on this?

答:
I figured it out!
If someone looking for the answer, what i did -->
Set following options to cropper:

viewMode: 2 (not necessarily 2, but needs to be more than 0).

cropBoxMovable: true. (Could only change the cropBox by my inputs.)

dragMode: 'none'. Otherwise the user could drag a new cropBox.

cropBoxResizable: false. OtherWise user could drag in the corners in of crfopbox and change size.


问:
PGP key signature from stranger
I received a signature to my key by an unknown person. How should I react?

Signing GPG keys should be a trusty way to declare the real link between key and owner but in this case a person I do not know declared to know me and to have verified the validity of my key.

That's not the case.

Can I remove/block/tag someone's signature to my key?

答:
Can I remove/block/tag someone's signature to my key?

Unfortunately not, that's not possible with the design of OpenPGP and the way the keyservers work.

The other person's signature on your key doesn't actually mean anything - certainly not a two-way relationship.

I understand you might be worried that people think it means more than it does.

How should I react?

Is the unknown person a well-known evil person you don't want to be associated with in any way?

If not I wouldn't worry about it.

You've highlighted one of the many confusing or broken things about the web of trust. The technical principle is fine, but in reality few people understand it well enough to know what it's saying.

The plus side is that people aren't likely to read much into your mysterious signer.

Other reasons people don't use web-of-trust

it reveals something about who you email, and when you met them (at a key signing party, for example)

it allows anyone to attach an arbitrary comment to your key (by generating a new key, filling out the UID field and signing & pushing your key.)

it's unclear what a signature means, to the extent that some people actually write signature policies to describe what verification they do.

My personal approach

This is my approach which doesn't involve the web of trust.

Treat the keyservers as a free but untrustworthy way of hosting your public key.

Share your fingerprint widely: in email signatures, social media, website, business card, Signal

Refer to your key by fingerprint, rather than by a URL to a keyserver

Always fetch keys with your software by fingerprint, then you get fingerprint-checking for free: e.g. gpg --recv-keys 'A999 B749 8D1A 8DC4 73E5  3C92 309F 635D AD1B 5517'

Don't search the keyservers by name or email. The keys listed could belong to anyone.

Forget short IDs exist. Use long IDs only if you can't use fingerprint.

Title: PGP key signature from stranger


问:
Databinding multiple records to a single vertical-column table in asp.net gridview
I fetch data by using a selectmethod and it works fine , the problem is that I don't want a new table for each record inserted. I'd like a new column to be added to the existing table. Something like the picture below

```<code><asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

    <asp:GridView ID="FormView1" runat="server" ShowHeader="False" ItemType="MieleRepresentative.SteamBoiler" SelectMethod="GetSteamBoilerModels" RenderOuterTable="false" AutoGenerateColumns="False">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>

                <table class="table-striped table-bordered">
                    <tr style="background-color: thistle!important;">
                        <td style="font-weight: bold;">Model</td>
                        <td><%# Eval("Model")%></td>
                    </tr>

                    <tr>
                        <td style="font-weight: bold">WorkingPressureLimit</td>
                        <td><%# Eval("WorkingPressureLimit")%></td>
                    </tr>
                    <tr>
                        <td style="font-weight: bold">TestPressureLimit</td>
                        <td><%# Eval("TestPressureLimit")%></td>
                    </tr>
                    <tr>
                        <td style="font-weight: bold">Electrical</td>
                        <td><%# Eval("Electrical")%></td>
                    </tr>
                    <tr>
                        <td style="font-weight: bold">Diameter</td>
                        <td><%# Eval("Diameter")%></td>
                    </tr>
                    <tr>
                        <td style="font-weight: bold">Height</td>
                        <td><%# Eval("Height")%></td>
                    </tr>
                    <tr>
                        <td style="font-weight: bold">Weight</td>
                        <td><%# Eval("Weight")%></td>
                    </tr>

                </table>
            </ItemTemplate>

        </asp:TemplateField>

    </Columns>
</asp:GridView>
</code>```

```<code>       public IQueryable<SteamBoiler> GetSteamBoilerModels([QueryString("productID")] Guid productId)
    {

        var _mieleDbEntities = new MieleDBEntities();

        return _mieleDbEntities.SteamBoilers.Where(boiler => boiler.FKProduct == productId);
    }
</code>```

答:
If you want a table with an undefined number of columns (one for each record selected), probabily GridView is not your best bet.

In my opinion you should build dynamically your table in .aspx page in this way:

```<code><% var steamBoilersList = GetSteamBoilerModels(...params...); %>
<table>
    <!-- first row -->
    <tr>
        <% foreach (var singleSteamBoiler in steamBoilersList) { %>
        <td>
            <%= singleSteamBoiler.FIELD1 %>
        </td>
    </tr>

    <!-- second row and so on -->
    <tr>
        <% foreach (var singleSteamBoiler in steamBoilersList) { %>
        <td>
            <%= singleSteamBoiler.FIELD2 %>
        </td>
    </tr>
</table>
</code>```

Body:
I fetch data by using a selectmethod and it works fine , the problem is that I don't want a new table for each record inserted. I'd like a new column to be added to the existing table. Something like the picture below

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

    <asp:GridView ID="FormView1" runat="server" ShowHeader="False" ItemType="MieleRepresentative.SteamBoiler" SelectMethod="GetSteamBoilerModels" RenderOuterTable="false" AutoGenerateColumns="False">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>

                        Model
                        <%# Eval("Model")%>

                        WorkingPressureLimit
                        <%# Eval("WorkingPressureLimit")%>

                        TestPressureLimit
                        <%# Eval("TestPressureLimit")%>

                        Electrical
                        <%# Eval("Electrical")%>

                        Diameter
                        <%# Eval("Diameter")%>

                        Height
                        <%# Eval("Height")%>

                        Weight
                        <%# Eval("Weight")%>

            </ItemTemplate>

        </asp:TemplateField>

    </Columns>
</asp:GridView>

       public IQueryable<SteamBoiler> GetSteamBoilerModels([QueryString("productID")] Guid productId)
    {

        var _mieleDbEntities = new MieleDBEntities();

        return _mieleDbEntities.SteamBoilers.Where(boiler => boiler.FKProduct == productId);
    }

Body:
If you want a table with an undefined number of columns (one for each record selected), probabily GridView is not your best bet.

In my opinion you should build dynamically your table in .aspx page in this way:

<% var steamBoilersList = GetSteamBoilerModels(...params...); %>
<table>
    <!-- first row -->
    <tr>
        <% foreach (var singleSteamBoiler in steamBoilersList) { %>
        <td>
            <%= singleSteamBoiler.FIELD1 %>
        </td>
    </tr>

    <!-- second row and so on -->
    <tr>
        <% foreach (var singleSteamBoiler in steamBoilersList) { %>
        <td>
            <%= singleSteamBoiler.FIELD2 %>
        </td>
    </tr>
</table>


问:
How do you rename a MongoDB database?
There's a typo in my MongoDB database name and I'm looking to rename the database.

I can copy and delete like so...

```<code>db.copyDatabase('old_name', 'new_name');
use old_name
db.dropDatabase();
</code>```

Is there a command to rename a database?

答:
NOTE: Hopefully this changed in the latest version.

You cannot copy data between a MongoDB 4.0 mongod instance (regardless
  of the FCV value) and a MongoDB 3.4 and earlier mongod instance.
  https://docs.mongodb.com/v4.0/reference/method/db.copyDatabase/

ALERT: Hey folks just be careful while copying the database, if you don't want to mess up the different collections under single database.

The following shows you how to rename

```<code>> show dbs;
testing
games
movies
</code>```

To rename you use the following syntax

```<code>db.copyDatabase("old db name","new db name")
</code>```

Example:

```<code>db.copyDatabase('testing','newTesting')
</code>```

Now you can safely delete the old db by the following way

```<code>use testing;

db.dropDatabase(); //Here the db **testing** is deleted successfully
</code>```

Now just think what happens if you try renaming the new database name with existing database name

Example:

```<code>db.copyDatabase('testing','movies');
</code>```

So in this context all the collections (tables) of testing will be copied to movies database.

Title: How do you rename a MongoDB database?

Body:
There's a typo in my MongoDB database name and I'm looking to rename the database.

I can copy and delete like so...

db.copyDatabase('old_name', 'new_name');
use old_name
db.dropDatabase();

Is there a command to rename a database?

Body:
NOTE: Hopefully this changed in the latest version.

You cannot copy data between a MongoDB 4.0 mongod instance (regardless
  of the FCV value) and a MongoDB 3.4 and earlier mongod instance.
  https://docs.mongodb.com/v4.0/reference/method/db.copyDatabase/

ALERT: Hey folks just be careful while copying the database, if you don't want to mess up the different collections under single database.

The following shows you how to rename

> show dbs;
testing
games
movies

To rename you use the following syntax

db.copyDatabase("old db name","new db name")

Example:

db.copyDatabase('testing','newTesting')

Now you can safely delete the old db by the following way

use testing;

db.dropDatabase(); //Here the db **testing** is deleted successfully

Now just think what happens if you try renaming the new database name with existing database name

Example:

db.copyDatabase('testing','movies');

So in this context all the collections (tables) of testing will be copied to movies database.


问:
What does compute_gradients return in tensorflow
```<code>mean_sqr = tf.reduce_mean(tf.pow(y_ - y, 2))
optimizer = tf.train.AdamOptimizer(LEARNING_RATE)
gradients, variables = zip(*optimizer.compute_gradients(mean_sqr))
opt = optimizer.apply_gradients(list(zip(gradients, variables)))

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

for j in range(TRAINING_EPOCHS):
    sess.run(opt, feed_dict={x: batch_xs, y_: batch_xs})
</code>```

I don't clearly understand what compute_gradients returns? Does it return sum(dy/dx) for a given x values assigned by batch_xs, and update gradient in apply_gradients function such as :

theta <- theta - LEARNING_RATE*1/m*gradients?

Or does it already return average of gradients that is summed for each x values in a given batch such as sum(dy/dx)*1/m, m is defined as batch_size?

答:
compute_gradients(a,b) returns d[ sum a ]/db. So in your case this returns d mean_sq / d theta, where theta is set of all variables. There is no "dx" in this equation, you are not computing gradients wrt. inputs. So what happens with batch dimension? You remove it yourself in the definition of mean_sq:

```<code>mean_sqr = tf.reduce_mean(tf.pow(y_ - y, 2))
</code>```

thus (I am assuming y is 1D for simplicity)

```<code>d[ mean_sqr ] / d theta = d[ 1/M SUM_i=1^M (pred(x_i), y_i)^2 ] / d theta
                        = 1/M SUM_i=1^M d[ (pred(x_i), y_i)^2 ] / d theta
</code>```

so you are in control of whether it sums over batch, takes the mean or does something different, if you would define mean_sqr to use reduce_sum instead of a reduce_mean, gradients would be the sum over the batch and so on.

On the other hand apply_gradients simply "applies the gradients", the exact rule for application is optimiser dependent, for GradientDescentOptimizer it would be

```<code>theta <- theta - learning_rate * gradients(theta)
</code>```

For Adam that you are using the equation is more complex of course.

Note however that tf.gradients is more like "backprop" than true gradient in mathematical sense - meaning that it depends on the graph dependencies and does not recognise dependences which are in "opposite" direction.

Body:
mean_sqr = tf.reduce_mean(tf.pow(y_ - y, 2))
optimizer = tf.train.AdamOptimizer(LEARNING_RATE)
gradients, variables = zip(*optimizer.compute_gradients(mean_sqr))
opt = optimizer.apply_gradients(list(zip(gradients, variables)))

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

for j in range(TRAINING_EPOCHS):
    sess.run(opt, feed_dict={x: batch_xs, y_: batch_xs})

I don't clearly understand what compute_gradients returns? Does it return sum(dy/dx) for a given x values assigned by batch_xs, and update gradient in apply_gradients function such as :

theta <- theta - LEARNING_RATE*1/m*gradients?

Or does it already return average of gradients that is summed for each x values in a given batch such as sum(dy/dx)*1/m, m is defined as batch_size?

Body:
compute_gradients(a,b) returns d[ sum a ]/db. So in your case this returns d mean_sq / d theta, where theta is set of all variables. There is no "dx" in this equation, you are not computing gradients wrt. inputs. So what happens with batch dimension? You remove it yourself in the definition of mean_sq:

mean_sqr = tf.reduce_mean(tf.pow(y_ - y, 2))

thus (I am assuming y is 1D for simplicity)

d[ mean_sqr ] / d theta = d[ 1/M SUM_i=1^M (pred(x_i), y_i)^2 ] / d theta
                        = 1/M SUM_i=1^M d[ (pred(x_i), y_i)^2 ] / d theta

so you are in control of whether it sums over batch, takes the mean or does something different, if you would define mean_sqr to use reduce_sum instead of a reduce_mean, gradients would be the sum over the batch and so on.

On the other hand apply_gradients simply "applies the gradients", the exact rule for application is optimiser dependent, for GradientDescentOptimizer it would be

theta <- theta - learning_rate * gradients(theta)

For Adam that you are using the equation is more complex of course.

Note however that tf.gradients is more like "backprop" than true gradient in mathematical sense - meaning that it depends on the graph dependencies and does not recognise dependences which are in "opposite" direction.


问:
Vagrant doesn't read Homestead.yaml
I've been trying to sync a folder between my computer and a Homestead VM run using Vagrant. My guess is that Vagrant isn't reading my Homestead.yaml file as no change is reflected in the VM.

I've tried the following:

Tried reloading, halting with provision after editing the file as mentioned here

Checked for tabs and ensured that there are 2 spaces in my yaml file

Rechecked the paths of the mounted folders. Tried variations like /home/abhirath/Desktop/Laravel_Recipes and ~/Desktop/Laravel_Recipes

Destroyed and recreated the VM

Read random tutorials like this

SSH'd into my VM. I don't see any folder there

I changed the memory from 2048 to 512 in the Homestead.yaml file and checked the RAM in my VM using sudo cat /proc/meminfo | grep MemTotal and it still shows 2048 MB

vagrant up with debug mode enabled. I couldn't find anything relevant in the debug logs

contents of ~/.homestead

after.sh

aliases

Homestead.yaml

Vagrantfile

Homestead.yaml

```<code>---
ip: "192.168.10.10"
memory: 512
cpus: 1
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: ~/Desktop/Laravel_Recipes
      to: /home/vagrant/Laravel_Recipes

sites:
    - map: recipes.dev
      to: /home/vagrant/Laravel_Recipes/public

databases:
    - homestead

# blackfire:
#     - id: foo
#       token: bar
#       client-id: foo
#       client-token: bar

# ports:
#     - send: 50000
#       to: 5000
#     - send: 7777
#       to: 777
#       protocol: udp
</code>```

答: The problem is that the Vagrantfile created with init.sh during the aliases phase is trying to be written to .homestead If you have that directory it will be created and you can copy it to the ~/Homestead directory and vagrant will work properly. Otherwise you can copy the Vagrantfile from ~/Homestead/resources/localized to ~/Homestead</p>

Title: Vagrant doesn't read Homestead.yaml

Body:
I've been trying to sync a folder between my computer and a Homestead VM run using Vagrant. My guess is that Vagrant isn't reading my Homestead.yaml file as no change is reflected in the VM.

I've tried the following:

Tried reloading, halting with provision after editing the file as mentioned here

Checked for tabs and ensured that there are 2 spaces in my yaml file

Rechecked the paths of the mounted folders. Tried variations like /home/abhirath/Desktop/Laravel_Recipes and ~/Desktop/Laravel_Recipes

Destroyed and recreated the VM

Read random tutorials like this

SSH'd into my VM. I don't see any folder there

I changed the memory from 2048 to 512 in the Homestead.yaml file and checked the RAM in my VM using sudo cat /proc/meminfo | grep MemTotal and it still shows 2048 MB

vagrant up with debug mode enabled. I couldn't find anything relevant in the debug logs

contents of ~/.homestead

after.sh

aliases

Homestead.yaml

Vagrantfile

Homestead.yaml

---
ip: "192.168.10.10"
memory: 512
cpus: 1
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: ~/Desktop/Laravel_Recipes
      to: /home/vagrant/Laravel_Recipes

sites:
    - map: recipes.dev
      to: /home/vagrant/Laravel_Recipes/public

databases:
    - homestead

# blackfire:
#     - id: foo
#       token: bar
#       client-id: foo
#       client-token: bar

# ports:
#     - send: 50000
#       to: 5000
#     - send: 7777
#       to: 777
#       protocol: udp


问:
Global hotkey with WIN32 API?
I've been able to set local hotkeys like this

```<code> RegisterHotKey(hwndDlg, 100, MOD_ALT | MOD_CONTROL, 'S');
</code>```

How can I set the hotkey to be global? I want it to be there even when my window is hidden.

答:
First you define one or more constants for your hotkeys

```<code>#define HOTKEY1 1000
#define HOTKEY2 1002
</code>```

Then you register these hot keys

```<code>RegisterHotKey(NULL, HOTKEY1, MOD_ALT + MOD_SHIFT, 0x53); // ALT+SHIFT+s
RegisterHotKey(NULL, HOTKEY2, MOD_ALT + MOD_SHIFT, 0x51); // ALT+SHIFT+q
</code>```

Finally in the main event loop you monitor these hot keys and respond to them:

if (msg.message == HOTKEY1)
{
switch (LOWORD(msg.wParam))
{
case HOTKEY1:
// do such and such
break;
case HOTKEY2:
// do such and such
break;
}
}

Title: Global hotkey with WIN32 API?

Body:
I've been able to set local hotkeys like this

 RegisterHotKey(hwndDlg, 100, MOD_ALT | MOD_CONTROL, 'S');

How can I set the hotkey to be global? I want it to be there even when my window is hidden.

Body:
First you define one or more constants for your hotkeys

#define HOTKEY1 1000
#define HOTKEY2 1002

Then you register these hot keys

RegisterHotKey(NULL, HOTKEY1, MOD_ALT + MOD_SHIFT, 0x53); // ALT+SHIFT+s
RegisterHotKey(NULL, HOTKEY2, MOD_ALT + MOD_SHIFT, 0x51); // ALT+SHIFT+q

Finally in the main event loop you monitor these hot keys and respond to them:

if (msg.message == HOTKEY1)
{
switch (LOWORD(msg.wParam))
{
case HOTKEY1:
// do such and such
break;
case HOTKEY2:
// do such and such
break;
}
}


问:
why combiner function is not executed in java-8 stream reduce operation?
I am trying to understand how the reduce method in streams work.

```<code>Stream.of(1,2,3,4,5,6,7).reduce(new ArrayList<>(),
(List<Integer> l, Integer a) -> {l.add(a);return l;},
(List<Integer> l1, List<Integer> l2) -> {
System.out.println("l1 is" + l1 + "l2 is " + l2);
l1.addAll(l2);
return l1;
}).forEach(System.out::println);
</code>```

The line System.out.println("l1 is" + l1 + "l2 is " + l2) never gets printed.
I can understand what is happening in (List<Integer> l, Integer a) -> {l.add(a);return l;}

Can some one please explain why it is not printed ?
The java docs say function for combining two values, which must be compatible with the accumulator function

Thanks,
Amar

答:
It has described in java.util.stream package summary as below:

```<code><U> U reduce(U identity,
          BiFunction<U, ? super T, U> accumulator,
          BinaryOperator<U> combiner);
</code>```

The combiner function combines two partial results to produce a new partial result. (The combiner is necessary in parallel reductions, where the input is partitioned, a partial accumulation computed for each partition, and then the partial results are combined to produce a final result.)

the "necessary" imply if your stream is empty or contains only single element in the stream, the combiner also never be called in a parallel stream.

So if you want to see "l1 is" + l1 + "l2 is " + l2 is printed, you should run it in a parallel stream, for example:

```<code>//                       v--- make the stream run in parallel
Stream.of(1,2,3,4,5,6,7).parallel().reduce(...).forEach(System.out::println);
</code>```

Body:
I am trying to understand how the reduce method in streams work.

Stream.of(1,2,3,4,5,6,7).reduce(new ArrayList<>(),
(List<Integer> l, Integer a) -> {l.add(a);return l;},
(List<Integer> l1, List<Integer> l2) -> {
System.out.println("l1 is" + l1 + "l2 is " + l2);
l1.addAll(l2);
return l1;
}).forEach(System.out::println);

The line System.out.println("l1 is" + l1 + "l2 is " + l2) never gets printed.
I can understand what is happening in (List<Integer> l, Integer a) -> {l.add(a);return l;}

Can some one please explain why it is not printed ?
The java docs say function for combining two values, which must be compatible with the accumulator function

Thanks,
Amar

Body:
It has described in java.util.stream package summary as below:

<U> U reduce(U identity,
          BiFunction<U, ? super T, U> accumulator,
          BinaryOperator<U> combiner);

The combiner function combines two partial results to produce a new partial result. (The combiner is necessary in parallel reductions, where the input is partitioned, a partial accumulation computed for each partition, and then the partial results are combined to produce a final result.)

the "necessary" imply if your stream is empty or contains only single element in the stream, the combiner also never be called in a parallel stream.

So if you want to see "l1 is" + l1 + "l2 is " + l2 is printed, you should run it in a parallel stream, for example:

//                       v--- make the stream run in parallel
Stream.of(1,2,3,4,5,6,7).parallel().reduce(...).forEach(System.out::println);


问:
AWS/S3 ACLs & CloudFront
tl;dr - Is there a robust S3 ACL management tool, possibly for use with CloudFront?

I'm working on a personal private content distribution (via CloudFront) but obviously the AWS Console is severely lacking in this regard.

I know there are a handful of S3 clients out there, but none of them really do much for advanced ACL.  To avoid having to use the AWS cli tools or to write wrappers for the API for everything (this is for configuring long-term systems, not for anything that would need to be done programmatically), I'm looking for one that has the best ACL support.

OR, if anyone has suggestions for managing CloudFront and custom ACLs (specifically for adding canonical user IDs/OriginAccessIdentities to buckets), I'm totally open to that too.

On a side note, the AWS docs mention the following:

Once you have a private content distribution, you must grant your CloudFront origin access identity read access to the private content. You do this by modifying the Amazon S3 ACL on each of the objects (not on the bucket).

which seems, er, exceptionally hard to maintain for a system that could potentially be used as swap (sic) storage for protected assets and modified on a regular basis (tens+ of times per day).  Am I misreading that, or is it really intended to be that static and explicit?

答: Cyberduck for Mac & Windows supports ACL editing. Refer to http://trac.cyberduck.ch/wiki/help/en/howto/s3.</p>

Title: AWS/S3 ACLs & CloudFront


问:
Sorting an an ArrayList of Objects in Java
I have an object that holds an int value, a String, and a double. Instances of that object are stored in an ArrayList. I want to print that object now but I want to first sort the ArrayList by the String values. I am having a hard time conceptualizing how I'd do that through something like a selection sort. Any help would be grateful!

Here is what I thought you were suppose to do, but that didn't seem to work.

```<code>public static void sSortStrings(ArrayList<Student> list) { //Selection sort
     int count1;
     int count2;
     int largest;
     String temp;
     for (count1 = 0; count1 < list.size() - 1; count1++) {
      largest = 0;
      for (count2 = largest + 1; count2 < list.size() - count1; count2++) {
       if (list[largest].compareTo(list[count2]) < 0) {
        largest = count2;
       }
      }
      temp = list[list.size() - 1 - count1];
      list[list.size() - 1 - count1] = list[largest];
      list[largest] = temp;
     }
    }
</code>```

Just to throw in there my professor had included this in the source code, but I'm not sure if I should be calling it instead of the compare to method

```<code>public boolean nameComesBefore(Student other) {
    return name.compareToIgnoreCase(other.name) < 0;
}
</code>```

答:
Assuming the Student class has getter for the String property.
Then all you need to do to sort the list is
 list.sort(Comparator.comparing(Student::getName))

This will sort the given list by student's name.
For more options check javadoc for List.sort() and Comparator.

Body:
I have an object that holds an int value, a String, and a double. Instances of that object are stored in an ArrayList. I want to print that object now but I want to first sort the ArrayList by the String values. I am having a hard time conceptualizing how I'd do that through something like a selection sort. Any help would be grateful!

Here is what I thought you were suppose to do, but that didn't seem to work.

public static void sSortStrings(ArrayList<Student> list) { //Selection sort
     int count1;
     int count2;
     int largest;
     String temp;
     for (count1 = 0; count1 < list.size() - 1; count1++) {
      largest = 0;
      for (count2 = largest + 1; count2 < list.size() - count1; count2++) {
       if (list[largest].compareTo(list[count2]) < 0) {
        largest = count2;
       }
      }
      temp = list[list.size() - 1 - count1];
      list[list.size() - 1 - count1] = list[largest];
      list[largest] = temp;
     }
    }

Just to throw in there my professor had included this in the source code, but I'm not sure if I should be calling it instead of the compare to method

public boolean nameComesBefore(Student other) {
    return name.compareToIgnoreCase(other.name) < 0;
}


问:
How can I traverse/iterate an STL map?
I want to traverse an STL map. I don't want to use its key. I don't care about the ordering, I just look for a way to access all elements it contains. How can I do this?</p>

答:
You can iterate map by using auto iterator.

Code Snippet:

```<code>#include<bits/stdc++.h>
using namespace std;

int main()
{
      ios::sync_with_stdio(false);
      map<string, int> mp;

      mp["a"]=500;
      mp["b"]=200;
      mp["d"]=300;
      mp["c"]=400;

      for(auto it=mp.begin(); it != mp.end(); it++)
      {
         cout<<it->first <<" : "<<it->second<<endl;
      }
      return 0;
}
</code>```

Title: How can I traverse/iterate an STL map?

Body:
You can iterate map by using auto iterator.

Code Snippet:

#include<bits/stdc++.h>
using namespace std;

int main()
{
      ios::sync_with_stdio(false);
      map<string, int> mp;

      mp["a"]=500;
      mp["b"]=200;
      mp["d"]=300;
      mp["c"]=400;

      for(auto it=mp.begin(); it != mp.end(); it++)
      {
         cout<<it->first <<" : "<<it->second<<endl;
      }
      return 0;
}


问:
Zenity --progress return string and return code (POSIX shell)
I am trying to call a shell function and while this function processes, a zenity progress dialog should be displayed.
However, I want the echo'ed string from that function to be stored in a variable for further processing, as well as the return code of that function.

And all of this in POSIX shell.

My current approach is like this:

```<code>output="$( compress "${input}" |  \
    zenity --progress \
    --pulsate \
    --title="Compressing files" \
    --text="Scanning mail logs..." \
    --percentage=0 \
)";

if [ "$?" != "0" ]; then
    echo "${output}"
    exit 1
fi
</code>```

The progress dialog shows up, however, $output is empty at the end.

Any idea how to get the output of the compress function?

答:
You can create a subshell and run commands in there. The only caveat is that the commands executed after the progress dialog is finished aren't allowed to write to standard output. Otherwise you get an I/O error.

In your case this would look like this:

```<code>(
    output="$(compress "${input}")"

    if [ "$?" != "0" ]; then
        #echo "${output}" <- this would result in an I/O error because the pipe is closed
        # write to somewhere else, maybe standard error like so:
        echo "${output}" >&2
        exit 1
    fi
) | \
    zenity --progress \
    --pulsate \
    --title="Compressing files" \
    --text="Scanning mail logs..." \
    --percentage=0
</code>```

I used this to create a small "GUI" wrapper to sha256sum, like so:

```<code>(
  HASH=$(sha256sum "$1")
  # send EOF to end the zenity progress dialog
  exec 1>&-
  zenity --title="sha256sum" --info --text="$HASH" --no-wrap
) | zenity --progress  --title="sha256sum" --pulsate --auto-close --no-cancel
</code>```

Body:
I am trying to call a shell function and while this function processes, a zenity progress dialog should be displayed.
However, I want the echo'ed string from that function to be stored in a variable for further processing, as well as the return code of that function.

And all of this in POSIX shell.

My current approach is like this:

output="$( compress "${input}" |  \
    zenity --progress \
    --pulsate \
    --title="Compressing files" \
    --text="Scanning mail logs..." \
    --percentage=0 \
)";

if [ "$?" != "0" ]; then
    echo "${output}"
    exit 1
fi

The progress dialog shows up, however, $output is empty at the end.

Any idea how to get the output of the compress function?

Body:
You can create a subshell and run commands in there. The only caveat is that the commands executed after the progress dialog is finished aren't allowed to write to standard output. Otherwise you get an I/O error.

In your case this would look like this:

(
    output="$(compress "${input}")"

    if [ "$?" != "0" ]; then
        #echo "${output}" <- this would result in an I/O error because the pipe is closed
        # write to somewhere else, maybe standard error like so:
        echo "${output}" >&2
        exit 1
    fi
) | \
    zenity --progress \
    --pulsate \
    --title="Compressing files" \
    --text="Scanning mail logs..." \
    --percentage=0

I used this to create a small "GUI" wrapper to sha256sum, like so:

(
  HASH=$(sha256sum "$1")
  # send EOF to end the zenity progress dialog
  exec 1>&-
  zenity --title="sha256sum" --info --text="$HASH" --no-wrap
) | zenity --progress  --title="sha256sum" --pulsate --auto-close --no-cancel