问:
Random number generator that returns unique entries in sorted order
I need a generator for many (up to one trillion, 10^12) unique random 64-bit numbers.
The generator needs to return the numbers in sorted order (Long.MIN_VALUE to Long.MAX_VALUE). The problem is that sorting $10^{12}$ numbers is slow. The use case is replicating a test that was run for BBHash (in the paper, 4.5 Indexing a trillion keys).

The straightforward solution is to create a set in memory, using a huge bit set or so
to ensure no duplicates are returned.
But that uses too much memory or I/O.
I'd like to use at most a few MB of internal state.

The generator should use a java.util.Random internally.
It should be as "fair" as possible (have the same statistical distribution as if generated otherwise). I would also like to have a version for 128-bit numbers (2 longs).

What I have so far is code to create a set in memory (Java code):

```<code>public static void main(String... args) {
    for(long x : randomSet(10, 0)) {
        System.out.println(x);
    }
}

static Iterable<Long> randomSet(int size, int seed) {
    Random r = new Random(seed);
    TreeSet<Long> set = new TreeSet<Long>();
    while (set.size() < size) {
        set.add(r.nextLong());
    }
    return set;
}

-8292973307042192125
-7423979211207825555
-6688467811848818630
-4962768465676381896
-2228689144322150137
-1083761183081836303
-279624296851435688
4437113781045784766
6146794652083548235
7105486291024734541
</code>```

The simplest (wrong) solution, which is not random, is to distribute the results evenly.
I don't think a solution along the line of "add a random gap" will work,
because it is slow, and the sum of such gaps, after 10^12, will not land where it should (well, maybe: remember how many numbers are left, then re-calculate the distribution...). I think the following should work, but is complex, and not sure what formulas to use: for each bit level,
recursively, calculating how many 0s / 1s will likely occur
(using the Binomial distribution or the approximation, the normal / Gaussian distribution, somehow).
Stop at some point (say, blocks of 1 million entries or less),
use the code above, for speed.
But maybe there is an elegant solution.
Maybe this is related to the Metropolis–Hastings algorithm, not sure.
I read "An Efficient Algorithm for Sequential Random Sampling",
but I think it is only for small n, and I find it hard to get to a simple algorithm from this.

Java code would be best, but C is fine (anyway at some point I might have to convert it to C / C++). I would like to not use too many libraries, to simplify porting.

答:
Let's call your universe of random values U. For starters, that's the range of 64-bit signed integers, so has 2 ^ 64 possible values. Let's call the total number of sorted random values you need to produce N, which you say is about a 10 ^ 12.

Decide up front how much is a reasonable amount of memory to use. Let's say your machine can allocate and use 1GB with no problems. That's 134,217,728 64-bit values. Call that A (array size).

N / A = 7450.58..., so round up to 7451 buckets, and adjust A to ceil(N/7451), which is 134,210,173. Calculate R (bucket range) = U/7451.

```<code>Loop over 7451 buckets (B):
    Generate 134,210,173 random values in the range (0..R),
    inserting them into the array as they are produced. Binary
    insertion should be reasonable (N*log(N), just like generating
    them all then sorting, but you can use the insertion to catch
    duplicates so you don't need extra memory or time for that).

    Output the bucket of values, adding (B*R) to each.
</code>```

You will have overshot N by a few; if that's critical, then randomly select as many buckets as needed and remove one value from each.

Body:
I need a generator for many (up to one trillion, 10^12) unique random 64-bit numbers.
The generator needs to return the numbers in sorted order (Long.MIN_VALUE to Long.MAX_VALUE). The problem is that sorting $10^{12}$ numbers is slow. The use case is replicating a test that was run for BBHash (in the paper, 4.5 Indexing a trillion keys).

The straightforward solution is to create a set in memory, using a huge bit set or so
to ensure no duplicates are returned.
But that uses too much memory or I/O.
I'd like to use at most a few MB of internal state.

The generator should use a java.util.Random internally.
It should be as "fair" as possible (have the same statistical distribution as if generated otherwise). I would also like to have a version for 128-bit numbers (2 longs).

What I have so far is code to create a set in memory (Java code):

public static void main(String... args) {
    for(long x : randomSet(10, 0)) {
        System.out.println(x);
    }
}

static Iterable<Long> randomSet(int size, int seed) {
    Random r = new Random(seed);
    TreeSet<Long> set = new TreeSet<Long>();
    while (set.size() < size) {
        set.add(r.nextLong());
    }
    return set;
}

-8292973307042192125
-7423979211207825555
-6688467811848818630
-4962768465676381896
-2228689144322150137
-1083761183081836303
-279624296851435688
4437113781045784766
6146794652083548235
7105486291024734541

The simplest (wrong) solution, which is not random, is to distribute the results evenly.
I don't think a solution along the line of "add a random gap" will work,
because it is slow, and the sum of such gaps, after 10^12, will not land where it should (well, maybe: remember how many numbers are left, then re-calculate the distribution...). I think the following should work, but is complex, and not sure what formulas to use: for each bit level,
recursively, calculating how many 0s / 1s will likely occur
(using the Binomial distribution or the approximation, the normal / Gaussian distribution, somehow).
Stop at some point (say, blocks of 1 million entries or less),
use the code above, for speed.
But maybe there is an elegant solution.
Maybe this is related to the Metropolis–Hastings algorithm, not sure.
I read "An Efficient Algorithm for Sequential Random Sampling",
but I think it is only for small n, and I find it hard to get to a simple algorithm from this.

Java code would be best, but C is fine (anyway at some point I might have to convert it to C / C++). I would like to not use too many libraries, to simplify porting.

Body:
Let's call your universe of random values U. For starters, that's the range of 64-bit signed integers, so has 2 ^ 64 possible values. Let's call the total number of sorted random values you need to produce N, which you say is about a 10 ^ 12.

Decide up front how much is a reasonable amount of memory to use. Let's say your machine can allocate and use 1GB with no problems. That's 134,217,728 64-bit values. Call that A (array size).

N / A = 7450.58..., so round up to 7451 buckets, and adjust A to ceil(N/7451), which is 134,210,173. Calculate R (bucket range) = U/7451.

Loop over 7451 buckets (B):
    Generate 134,210,173 random values in the range (0..R),
    inserting them into the array as they are produced. Binary
    insertion should be reasonable (N*log(N), just like generating
    them all then sorting, but you can use the insertion to catch
    duplicates so you don't need extra memory or time for that).

    Output the bucket of values, adding (B*R) to each.

You will have overshot N by a few; if that's critical, then randomly select as many buckets as needed and remove one value from each.


来源: stackexchange

问:
How to vary a Materialize modal based on trigger button?
I'm using the Materialize CSS and have a working modal for creating new model instances. When I click the edit button on an instance, I want to open the same modal only with the fields pre-populated.

In bootstrap I could accomplish this using

```<code>$('#exampleModal').on('show.bs.modal', function (event) {
    modal.find('.modal-body input').val('new value')
})
</code>```

This function doesn't appear to work using Materialize. Is there an equivalent function I can use instead?

答:
So this method is not available on the Materialize framework but they do have a callback available for modal open.

In the initialization of the model, you're able to add optional parameters. Instead of:

```<code>$(document).ready(function(){
    $('.modal').modal();
});
</code>```

you can add a modal open callback using:

```<code>$(document).ready(function(){
    $('.modal').modal({
        ready: function(modal, trigger) {
            alert("Modal Open");
        }
    });
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using the Materialize CSS and have a working modal for creating new model instances. When I click the edit button on an instance, I want to open the same modal only with the fields pre-populated.

In bootstrap I could accomplish this using

$('#exampleModal').on('show.bs.modal', function (event) {
    modal.find('.modal-body input').val('new value')
})

This function doesn't appear to work using Materialize. Is there an equivalent function I can use instead?

Body:
So this method is not available on the Materialize framework but they do have a callback available for modal open.

In the initialization of the model, you're able to add optional parameters. Instead of:

$(document).ready(function(){
    $('.modal').modal();
});

you can add a modal open callback using:

$(document).ready(function(){
    $('.modal').modal({
        ready: function(modal, trigger) {
            alert("Modal Open");
        }
    });
});


问:
Laravel Model Binding
I have issue with model binding in routes and controller. Here is my routes:

```<code>Route::group(['prefix'=>'services/devops/domain-names'], function () {
    Route::group(['middleware'=>'auth'], function () {
        Route::get('/editAutoRenew/{domainname}', 'EnomController@editAutoRenew');
    });
    Route::post('/', 'EnomController@checkDomainName');
});
</code>```

And here is function

```<code>public function editAutoRenew(DomainName $domainname)
{
    dd($domainname);
}
</code>```

But this gives me empty model. Why? How can I get my model?
I tried to route:list and there it shows {domainname}

答:
You get in argument integer type, not object. Try to rewrite your function with:

```<code>public function editAutoRenew($domainname)
{
    $domainnameObj = DomainName::findOrFail($domainname);
}
</code>```

When you use:

```<code>DomainName::first();
</code>```

You get all entries from your table domain_name, then command first() - get first of this records.

Title: Laravel Model Binding

Body:
I have issue with model binding in routes and controller. Here is my routes:

Route::group(['prefix'=>'services/devops/domain-names'], function () {
    Route::group(['middleware'=>'auth'], function () {
        Route::get('/editAutoRenew/{domainname}', 'EnomController@editAutoRenew');
    });
    Route::post('/', 'EnomController@checkDomainName');
});

And here is function

public function editAutoRenew(DomainName $domainname)
{
    dd($domainname);
}

But this gives me empty model. Why? How can I get my model?
I tried to route:list and there it shows {domainname}

Body:
You get in argument integer type, not object. Try to rewrite your function with:

public function editAutoRenew($domainname)
{
    $domainnameObj = DomainName::findOrFail($domainname);
}

When you use:

DomainName::first();

You get all entries from your table domain_name, then command first() - get first of this records.


问:
Reading a hash from a file on disk
Here is a hash that I save to a file to later be read.

```<code>my_hash = {-1 => 20, -2 => 30, -3 => 40}
File.open("my_file.txt", "w") { |f| f.write my_hash }
#how it looks opening the text file
{-1 => 20, -2 => 30, -3 => 40}
</code>```

When I go to read it, is where my problem is. (following code is separate from top)

```<code>my_hash = File.foreach("my_file.txt") { |f| print f }
p my_hash
#=> {-1 => 20, -2 => 30, -3 => 40}nil
</code>```

that nil messes up the rest of my code..not sure how to get rid of if. Just for clarity the rest of the code...

```<code>back_up_hash = {-1 => 20}
if my_hash.nil?
  my_hash = back_up_hash
end
</code>```

That little nil always makes my_hash equal to back_up_hash. I need that .nil? just in case the file is doesn't have the hash, otherwise the problem just gets pushed further down.

I also tried to read (slurp?..it's a small file) the file like this....

```<code>my_hash = File.read("my_file.txt") { |f| print f }
p my_hash
=> "{-1 => 20, -2 => 30, -3 => 40}"
# not sure how to get it out of string form...and I have searched for it.
</code>```

答:
I have had success with these 2 simple methods:

```<code>def create_json_copy
  File.open("db/json_records/stuff.json","w") do |f|
    f.write("#{@existing_data.to_json}")
  end
end

def read_json_copy
  @json = JSON.parse(File.read("db/json_records/stuff.json")).as_json.with_indifferent_access
  @json.each do |identifier,record|
    existing_record = Something.find_by(some_column: identifier)
    if !existing_record
      Something.create!(record.except(:id).except(:created_at).except(:updated_at))
    end
  end
end
</code>```

note: @existing_data is a Ruby Hash organised as { some_identifier: record_objet, ... } . I call .to_json on it before writing it to file and then when reading I JSON.parse it followed by .as_json, with_indifferent_access isn't really needed here so you can take it off as long as you substitute the symbols inside the excepts.

Title: Reading a hash from a file on disk

Body:
Here is a hash that I save to a file to later be read.

my_hash = {-1 => 20, -2 => 30, -3 => 40}
File.open("my_file.txt", "w") { |f| f.write my_hash }
#how it looks opening the text file
{-1 => 20, -2 => 30, -3 => 40}

When I go to read it, is where my problem is. (following code is separate from top)

my_hash = File.foreach("my_file.txt") { |f| print f }
p my_hash
#=> {-1 => 20, -2 => 30, -3 => 40}nil

that nil messes up the rest of my code..not sure how to get rid of if. Just for clarity the rest of the code...

back_up_hash = {-1 => 20}
if my_hash.nil?
  my_hash = back_up_hash
end

That little nil always makes my_hash equal to back_up_hash. I need that .nil? just in case the file is doesn't have the hash, otherwise the problem just gets pushed further down.

I also tried to read (slurp?..it's a small file) the file like this....

my_hash = File.read("my_file.txt") { |f| print f }
p my_hash
=> "{-1 => 20, -2 => 30, -3 => 40}"
# not sure how to get it out of string form...and I have searched for it.

Body:
I have had success with these 2 simple methods:

def create_json_copy
  File.open("db/json_records/stuff.json","w") do |f|
    f.write("#{@existing_data.to_json}")
  end
end

def read_json_copy
  @json = JSON.parse(File.read("db/json_records/stuff.json")).as_json.with_indifferent_access
  @json.each do |identifier,record|
    existing_record = Something.find_by(some_column: identifier)
    if !existing_record
      Something.create!(record.except(:id).except(:created_at).except(:updated_at))
    end
  end
end

note: @existing_data is a Ruby Hash organised as { some_identifier: record_objet, ... } . I call .to_json on it before writing it to file and then when reading I JSON.parse it followed by .as_json, with_indifferent_access isn't really needed here so you can take it off as long as you substitute the symbols inside the excepts.


问:
Force browser to reload the Javascript files
I am trying to achieve the below in ASP.NET MVC3 web application which uses razor.

1) In my Index.cshtml file, I have the below reference.

```<code><script src="/MySite/Scripts/Main.js"></script>
</code>```

2) I load my home page for the first time and a http request is made to fetch this file which returns 200.

3) Then, I made some changes to the Main.js and saved it.

4) Now I just reload the home page (please note that I am not refreshing the page) by going to the address bar and typing the home page url and pressing enter. At this point, I want the browser to fetch the updated Main.js file by making a http request again.

How can I achieve this? I don't want to use System.Web.Optimization bundling way. I knew that we can achieve this by changing the URL (appending version or some random number) everytime the file changes.

But the challenge here is the URL is hardcoded in my Index.cshtml file. Everytime when there is a change in Main.js file, how can I change that hardcoded URL in the Index.cshtml file?

Thanks,
Sathya.

答:
What I was trying to achieve is to invalidate browser cache as soon as my application javascript file (which already got cached in the browser) gets modified at the physical location. I understood that this is simply not achievable as no browsers are providing that support currently. To get around this below are the only two ways:
1)Use MVC bundling
2)Everytime the file is modified, modify the URL by just appending the version or any random number to the URL through querystring. This method is explained in the following URL - force browsers to get latest js and css files in asp.net application
But the disadvantage with the 2nd method is, if there are any external applications referring to your application's javascript file, the browser cache will still not be invalidated without refreshing the external application in browser.</p>

Body:
I am trying to achieve the below in ASP.NET MVC3 web application which uses razor.

1) In my Index.cshtml file, I have the below reference.

2) I load my home page for the first time and a http request is made to fetch this file which returns 200.

3) Then, I made some changes to the Main.js and saved it.

4) Now I just reload the home page (please note that I am not refreshing the page) by going to the address bar and typing the home page url and pressing enter. At this point, I want the browser to fetch the updated Main.js file by making a http request again.

How can I achieve this? I don't want to use System.Web.Optimization bundling way. I knew that we can achieve this by changing the URL (appending version or some random number) everytime the file changes.

But the challenge here is the URL is hardcoded in my Index.cshtml file. Everytime when there is a change in Main.js file, how can I change that hardcoded URL in the Index.cshtml file?

Thanks,
Sathya.


问:
What are the pros and cons of Dash by Plotly vs Jupyter Dashboards?
Dash by Plotly looks like a great way for a Python developer to create interactive web apps without having to learn Javascript and Front End Web development. Another great project with similar aims and scope is Jupyter Dashboards.

What are the pros and cons of each?

In particular in a multi-user deployment? I also found the Plotly documentation quite unclear on what exactly is Open Source and whether the data gets uploaded to them or if the plotting can be done offline? There are clearly two modes for the underlying Plotly library but what mode does Dash operate in?

答: Well for one jupyter dashboards are free, ploty dashboards I would assume use the ploty library, where as the jupyter dashboards can use what ever modules/libraries you want. I just finished making a jupyter dashboard today to aggregate information from all of our CI systems. It was incredibly easy and honestly kind of fun. Once you get one or two data sources figured out adding a new one or adding a new widget is easy along with adding control widgets.</p>


问:
Write output out of grep into a file on Linux?
```<code>find . -name "*.php" | xargs grep -i -n "searchstring" >output.txt
</code>```

Here I am trying to write data into a file which is not happening...

答: Looks fine to me.  What happens if you remove >output.txt?

ContentLicense: CC BY-SA 4.0

Body:
find . -name "*.php" | xargs grep -i -n "searchstring" >output.txt

Here I am trying to write data into a file which is not happening...

ContentLicense: CC BY-SA 2.5


问:
pandas join two dataframe based on Index
I am trying to join two dataframes based on Index values of dataframes however, my result produces NaN and followed by values with index values repeated.

```<code>print st
</code>```

results in (stored in data frame series and with only index as follows)

```<code>index
1499054400000
1499140800000
1499227200000
1499313600000
1499400000000
</code>```

Another dataframe is as follows

```<code>print dtest2
</code>```

This results in (same index as above)

```<code>                1
index
1499227200000   33.48
1499400000000   35.71
</code>```

I am trying to get the following when i merge two dataframes

Result desired

```<code>index            1
1499054400000    0.0
1499140800000    0.0
1499227200000    33.48
1499313600000    0.0
1499400000000    35.71
</code>```

However when i concatenate as follows

```<code>pd.concat([st,dtest2],ignore_index=False)
</code>```

I get the following

```<code>                1
index
1499054400000   NaN
1499140800000   NaN
1499227200000   NaN
1499313600000   NaN
1499400000000   NaN
1499227200000   33.48
1499400000000   35.71
</code>```

答:
use the merge function instead of concat</p>

```<code>pd.merge(st,dtest2,how='outer',left_index=True,right_index=True).fillna(0)
</code>```

Body:
I am trying to join two dataframes based on Index values of dataframes however, my result produces NaN and followed by values with index values repeated.

print st

results in (stored in data frame series and with only index as follows)

index
1499054400000
1499140800000
1499227200000
1499313600000
1499400000000

Another dataframe is as follows

print dtest2

This results in (same index as above)

                1
index
1499227200000   33.48
1499400000000   35.71

I am trying to get the following when i merge two dataframes

Result desired

index            1
1499054400000    0.0
1499140800000    0.0
1499227200000    33.48
1499313600000    0.0
1499400000000    35.71

However when i concatenate as follows

pd.concat([st,dtest2],ignore_index=False)

I get the following

                1
index
1499054400000   NaN
1499140800000   NaN
1499227200000   NaN
1499313600000   NaN
1499400000000   NaN
1499227200000   33.48
1499400000000   35.71

Body:
use the merge function instead of concat

pd.merge(st,dtest2,how='outer',left_index=True,right_index=True).fillna(0)


问:
STM32F103C8/CoIDE/ST-LinkV2 Can't update registers
I'm new to STM32, not to embedded development (experience with PIC, dsPIC, MSP430).

Environment

CooCox CoIDE

arm-none-eabi-gcc

ST-LINK V2 (have encountered same with Segger J-Link) over SWD

Problem Description

I am trying to write a basic library using direct register manipulations (STMCube HAL is cool, but I found I had to read the datasheet anyway, so register manipulation is preferred).  In essence, I'm just trying to blink an LED that is on the Blue Pill development board, which is pin C13.

I can compile, flash, and debug, but when I debug, the LED is not flashing and the registers aren't changing.  The register values themselves don't actually matter that much, so you shouldn't need to go out and check the datasheet.  I just need to be able to manipulate them!

Stepping through the debugger works just fine, and the variables watch window is also appropriately updated.

Things I've Tried

Although this isn't exhaustive (it has been several hours, so I may have forgotten to include a few), these are some of the things I have tried:

Changing the BOOTx pin configurations

Changing the debugger config (slow down, speed up, reset strategy).

Changing the debugger to SEGGER J-Link

Lock/Unlock GPIO pins

All have had same result.  I suspect that I may be missing something in CMSIS or a necessary include file, I just can't seem to find it.

Another point that I may be missing deals with oscillator setup.  As I understand it, there is a default configuration at startup that I don't have to worry about unless I want to change it.  Perhaps this is flawed?

Edit: Works with STM32CubeMX HAL

When I try a basic toggle using the STM32CUBEMX HAL, it works.  This makes me think that there is something fundamental that I am missing in the includes, project setup, oscillator setup... something?

Code

main.c

```<code>#include "gpio.h"

#define LED_PIN 13

int main(void)
{
    uint32_t i;

    // initialize the peripherals
    GPIO_init();
    GPIOC_setupOutput(LED_PIN, PUSH_PULL, PIN_SPEED_50MHz);

    while(1)
    {
        GPIOC_setPin(LED_PIN);
        for(i=0; i<4000000; i++);
        GPIOC_clearPin(LED_PIN);
        for(i=0; i<4000000; i++);
    }
}
</code>```

gpio.h

```<code>#ifndef _GPIO_H
#define _GPIO_H

#include <stdint.h>
#include <stdbool.h>

typedef enum{
    ANALOG=0b00, FLOATING=0b01, PULL_UP_PULL_DOWN=0b10
}InputPinMode;

typedef enum{
    PUSH_PULL=0b00, OPEN_DRAIN=0b01, AF_PUSH_PULL=0b10, AF_OPEN_DRAIN=0b11
}OutputPinMode;

typedef enum{
    PIN_SPEED_2MHz=0b10, PIN_SPEED_10MHz=0b01, PIN_SPEED_50MHz=0b11
}PinSpeed;

void GPIO_init(void);
void GPIOA_setupInput(uint8_t pinNumber, InputPinMode mode);
void GPIOC_setupInput(uint8_t pinNumber, InputPinMode mode);
void GPIOA_setupOutput(uint8_t pinNumber, OutputPinMode mode, PinSpeed speed);
void GPIOC_setupOutput(uint8_t pinNumber, OutputPinMode mode, PinSpeed speed);

bool GPIOA_readPin(uint8_t pinNumber);

void GPIOA_setPin(uint8_t pinNumber);
void GPIOC_setPin(uint8_t pinNumber);

void GPIOA_clearPin(uint8_t pinNumber);
void GPIOC_clearPin(uint8_t pinNumber);

#endif
</code>```

gpio.c

```<code>#include "stm32f1xx.h"
#include "gpio.h"

/**
 * @brief Initialize GPIO
 */
void GPIO_init(void){
    RCC->APB2ENR |= RCC_APB2ENR_IOPAEN;
    RCC->APB2ENR |= RCC_APB2ENR_IOPBEN;
    RCC->APB2ENR |= RCC_APB2ENR_IOPCEN;
    RCC->APB2ENR |= RCC_APB2ENR_IOPDEN;
    RCC->APB2ENR |= RCC_APB2ENR_IOPEEN;
}

/**
 * @brief Setup pin as an input
 * @param pinNumber the pin number
 * @param mode the input mode
 */
void GPIOA_setupInput(uint8_t pinNumber, InputPinMode mode){
    uint32_t pinNumberLocation, regValue;

    if(pinNumber < 8){
        pinNumberLocation = pinNumber << 2; // bit location
        regValue = (mode << 2) << pinNumberLocation;

        GPIOA->CRL &= ~(0b1111 << pinNumberLocation);   // clear the register
        GPIOA->CRL = regValue;
    }else{
        pinNumberLocation = (pinNumber - 8) << 2;   // bit location
        regValue = (mode << 2) << pinNumberLocation;

        GPIOA->CRH &= ~(0b1111 << pinNumberLocation);   // clear the register
        GPIOA->CRH = regValue;
    }
}

/**
 * @brief Setup port A pin as an output
 * @brief pinNumber the pin number
 * @brief mode the output mode
 * @brief speed the pin speed (lower results in less noise)
 */
void GPIOA_setupOutput(uint8_t pinNumber, OutputPinMode mode, PinSpeed speed){
    uint32_t pinNumberLocation, regValue;

    if(pinNumber < 8){
        pinNumberLocation = pinNumber << 2; // bit location
        regValue = ((mode << 2) << pinNumberLocation) + speed;

        GPIOA->CRL &= ~(0b1111 << pinNumberLocation);   // clear the register
        GPIOA->CRL |= regValue;
    }else{
        pinNumberLocation = (pinNumber - 8) << 2;   // bit location
        regValue = ((mode << 2) << pinNumberLocation) + speed;

        GPIOA->CRH &= ~(0b1111 << pinNumberLocation);   // clear the register
        GPIOA->CRH |= regValue;
    }
}

/**
 * @brief Setup port C pin as an output
 * @brief pinNumber the pin number
 * @brief mode the output mode
 * @brief speed the pin speed (lower results in less noise)
 */
void GPIOC_setupOutput(uint8_t pinNumber, OutputPinMode mode, PinSpeed speed){
    uint32_t pinNumberLocation, regValue;

    if(pinNumber < 8){
        pinNumberLocation = pinNumber << 2; // bit location
        regValue = ((mode << 2) << pinNumberLocation) + speed;

        GPIOC->CRL &= ~(0b1111 << pinNumberLocation);   // clear the register
        GPIOC->CRL |= regValue;
    }else{
        pinNumberLocation = (pinNumber - 8) << 2;   // bit location
        regValue = ((mode << 2) << pinNumberLocation) + speed;

        GPIOC->CRH &= ~(0b1111 << pinNumberLocation);   // clear the register
        GPIOC->CRH |= regValue;
    }
}

bool GPIOA_readPin(uint8_t pinNumber){
    uint16_t mask = 1 << pinNumber;

    if(GPIOA->IDR & mask)
        return true;
    else
        return false;
}

void GPIOA_setPin(uint8_t pinNumber){ GPIOA->BSRR = (1 << pinNumber);}
void GPIOC_setPin(uint8_t pinNumber){ GPIOC->BSRR = (1 << pinNumber);}

void GPIOA_clearPin(uint8_t pinNumber){ GPIOA->BSRR = ~(1 << (pinNumber + 16));}
void GPIOC_clearPin(uint8_t pinNumber){ GPIOC->BSRR = ~(1 << (pinNumber + 16));}
</code>```

答:
Your problem is trivial.

You just forgot to enable the the peripheral clock. all peripheral clocks in the Cortex micros are off by default. Please read the reference manual not the data sheet. Look for the "peripheral clock enable registers" and enable GPIO port in the proper one.

PS in your case RCC_APB2ENR

you do a lots of another serious mistakes in your code. I have no time to read in full but BSRR BRR registers are write only and you cant do any operations which incur reading (ie |= or &=). probably there is much more. Read RM more carefully. another mistake - you write to the reserved part of BRR. (upper 16 bits are reserved) If you even write to the correct half of the registe your &= ~() operation does something different than you think (abstracting from illegal read operation) - it does nothing. Actually you did not read and understand the RM  at all

So for the future:
Cortex micros to have an access to the peripheral registers - start their clock. Even EXTI (external interrupts) is the peripheral as well, and its clock has to be enabled.

Some peripherals have even more than one clock to enable (for example ADC in STM32F3xx where analog part has more than one clock option and it has to be enabled separately + digital part)

Body:
I'm new to STM32, not to embedded development (experience with PIC, dsPIC, MSP430).

Environment

CooCox CoIDE

arm-none-eabi-gcc

ST-LINK V2 (have encountered same with Segger J-Link) over SWD

Problem Description

I am trying to write a basic library using direct register manipulations (STMCube HAL is cool, but I found I had to read the datasheet anyway, so register manipulation is preferred).  In essence, I'm just trying to blink an LED that is on the Blue Pill development board, which is pin C13.

I can compile, flash, and debug, but when I debug, the LED is not flashing and the registers aren't changing.  The register values themselves don't actually matter that much, so you shouldn't need to go out and check the datasheet.  I just need to be able to manipulate them!

Stepping through the debugger works just fine, and the variables watch window is also appropriately updated.

Things I've Tried

Although this isn't exhaustive (it has been several hours, so I may have forgotten to include a few), these are some of the things I have tried:

Changing the BOOTx pin configurations

Changing the debugger config (slow down, speed up, reset strategy).

Changing the debugger to SEGGER J-Link

Lock/Unlock GPIO pins

All have had same result.  I suspect that I may be missing something in CMSIS or a necessary include file, I just can't seem to find it.

Another point that I may be missing deals with oscillator setup.  As I understand it, there is a default configuration at startup that I don't have to worry about unless I want to change it.  Perhaps this is flawed?

Edit: Works with STM32CubeMX HAL

When I try a basic toggle using the STM32CUBEMX HAL, it works.  This makes me think that there is something fundamental that I am missing in the includes, project setup, oscillator setup... something?

Code

main.c

#include "gpio.h"

#define LED_PIN 13

int main(void)
{
    uint32_t i;

    // initialize the peripherals
    GPIO_init();
    GPIOC_setupOutput(LED_PIN, PUSH_PULL, PIN_SPEED_50MHz);

    while(1)
    {
        GPIOC_setPin(LED_PIN);
        for(i=0; i<4000000; i++);
        GPIOC_clearPin(LED_PIN);
        for(i=0; i<4000000; i++);
    }
}

gpio.h

#ifndef _GPIO_H
#define _GPIO_H

#include <stdint.h>
#include <stdbool.h>

typedef enum{
    ANALOG=0b00, FLOATING=0b01, PULL_UP_PULL_DOWN=0b10
}InputPinMode;

typedef enum{
    PUSH_PULL=0b00, OPEN_DRAIN=0b01, AF_PUSH_PULL=0b10, AF_OPEN_DRAIN=0b11
}OutputPinMode;

typedef enum{
    PIN_SPEED_2MHz=0b10, PIN_SPEED_10MHz=0b01, PIN_SPEED_50MHz=0b11
}PinSpeed;

void GPIO_init(void);
void GPIOA_setupInput(uint8_t pinNumber, InputPinMode mode);
void GPIOC_setupInput(uint8_t pinNumber, InputPinMode mode);
void GPIOA_setupOutput(uint8_t pinNumber, OutputPinMode mode, PinSpeed speed);
void GPIOC_setupOutput(uint8_t pinNumber, OutputPinMode mode, PinSpeed speed);

bool GPIOA_readPin(uint8_t pinNumber);

void GPIOA_setPin(uint8_t pinNumber);
void GPIOC_setPin(uint8_t pinNumber);

void GPIOA_clearPin(uint8_t pinNumber);
void GPIOC_clearPin(uint8_t pinNumber);

#endif

gpio.c

#include "stm32f1xx.h"
#include "gpio.h"

/**
 * @brief Initialize GPIO
 */
void GPIO_init(void){
    RCC->APB2ENR |= RCC_APB2ENR_IOPAEN;
    RCC->APB2ENR |= RCC_APB2ENR_IOPBEN;
    RCC->APB2ENR |= RCC_APB2ENR_IOPCEN;
    RCC->APB2ENR |= RCC_APB2ENR_IOPDEN;
    RCC->APB2ENR |= RCC_APB2ENR_IOPEEN;
}

/**
 * @brief Setup pin as an input
 * @param pinNumber the pin number
 * @param mode the input mode
 */
void GPIOA_setupInput(uint8_t pinNumber, InputPinMode mode){
    uint32_t pinNumberLocation, regValue;

    if(pinNumber < 8){
        pinNumberLocation = pinNumber << 2; // bit location
        regValue = (mode << 2) << pinNumberLocation;

        GPIOA->CRL &= ~(0b1111 << pinNumberLocation);   // clear the register
        GPIOA->CRL = regValue;
    }else{
        pinNumberLocation = (pinNumber - 8) << 2;   // bit location
        regValue = (mode << 2) << pinNumberLocation;

        GPIOA->CRH &= ~(0b1111 << pinNumberLocation);   // clear the register
        GPIOA->CRH = regValue;
    }
}

/**
 * @brief Setup port A pin as an output
 * @brief pinNumber the pin number
 * @brief mode the output mode
 * @brief speed the pin speed (lower results in less noise)
 */
void GPIOA_setupOutput(uint8_t pinNumber, OutputPinMode mode, PinSpeed speed){
    uint32_t pinNumberLocation, regValue;

    if(pinNumber < 8){
        pinNumberLocation = pinNumber << 2; // bit location
        regValue = ((mode << 2) << pinNumberLocation) + speed;

        GPIOA->CRL &= ~(0b1111 << pinNumberLocation);   // clear the register
        GPIOA->CRL |= regValue;
    }else{
        pinNumberLocation = (pinNumber - 8) << 2;   // bit location
        regValue = ((mode << 2) << pinNumberLocation) + speed;

        GPIOA->CRH &= ~(0b1111 << pinNumberLocation);   // clear the register
        GPIOA->CRH |= regValue;
    }
}

/**
 * @brief Setup port C pin as an output
 * @brief pinNumber the pin number
 * @brief mode the output mode
 * @brief speed the pin speed (lower results in less noise)
 */
void GPIOC_setupOutput(uint8_t pinNumber, OutputPinMode mode, PinSpeed speed){
    uint32_t pinNumberLocation, regValue;

    if(pinNumber < 8){
        pinNumberLocation = pinNumber << 2; // bit location
        regValue = ((mode << 2) << pinNumberLocation) + speed;

        GPIOC->CRL &= ~(0b1111 << pinNumberLocation);   // clear the register
        GPIOC->CRL |= regValue;
    }else{
        pinNumberLocation = (pinNumber - 8) << 2;   // bit location
        regValue = ((mode << 2) << pinNumberLocation) + speed;

        GPIOC->CRH &= ~(0b1111 << pinNumberLocation);   // clear the register
        GPIOC->CRH |= regValue;
    }
}

bool GPIOA_readPin(uint8_t pinNumber){
    uint16_t mask = 1 << pinNumber;

    if(GPIOA->IDR & mask)
        return true;
    else
        return false;
}

void GPIOA_setPin(uint8_t pinNumber){ GPIOA->BSRR = (1 << pinNumber);}
void GPIOC_setPin(uint8_t pinNumber){ GPIOC->BSRR = (1 << pinNumber);}

void GPIOA_clearPin(uint8_t pinNumber){ GPIOA->BSRR = ~(1 << (pinNumber + 16));}
void GPIOC_clearPin(uint8_t pinNumber){ GPIOC->BSRR = ~(1 << (pinNumber + 16));}


问:
Filter nested collection not working as expected with Querydsl, Spring Data REST
Based on StoreRepository by @Oliver Gierke

If Store has a collection of products

/api/store?products.name=Sony%20Vaio

Returns Stores that has Sony Viao on it's products Good, But all products returned,
I need Only product with name Sony Viao.

```<code>public interface StoreRepository extends PagingAndSortingRepository<Store, String>,
    QueryDslPredicateExecutor<Store>, QuerydslBinderCustomizer<QStore> {

    default void customize(QuerydslBindings bindings, QStore store) {
        bindings.bind(store.products.any().first((path, value) -> path.equals(value));
    }
}
</code>```

Any help will be appreciated!

答:
I believe the problem is that you don't specify the property name inside product. Try this:</p>

```<code>bindings.bind(store.products.any().name).first((path, value) -> path.eq(value));
</code>```

Body:
Based on StoreRepository by @Oliver Gierke

If Store has a collection of products

/api/store?products.name=Sony%20Vaio

Returns Stores that has Sony Viao on it's products Good, But all products returned,
I need Only product with name Sony Viao.

public interface StoreRepository extends PagingAndSortingRepository<Store, String>,
    QueryDslPredicateExecutor<Store>, QuerydslBinderCustomizer<QStore> {

    default void customize(QuerydslBindings bindings, QStore store) {
        bindings.bind(store.products.any().first((path, value) -> path.equals(value));
    }
}

Any help will be appreciated!

Body:
I believe the problem is that you don't specify the property name inside product. Try this:

bindings.bind(store.products.any().name).first((path, value) -> path.eq(value));


问:
How to enable type checking for rules that require type checking on the command line?
Some rules require type checking. I don't understand from the documentation about  type checking what to do to run it on the command line.

If I run somethink like

```<code>tslint --project admin/tslint.json "project/**/*.ts{,x}"
</code>```

I get the error message

```<code>Invalid source file: project/main.ts. Ensure that the
files supplied to lint have a .ts, .tsx, .d.ts, .js or .jsx extension.
</code>```

The documentation says

When using the CLI, the --project flag will automatically create a
  program from the specified tsconfig.json file and enable rules that
  require the type checker.

But I don't see the program generated by tslint nor do I understand how to run it.

So, what are the steps to run tslint with type checking form the command line?

答:
The --project argument needs the typescript compiler tsc configuration file (typically tsconfig.json).

The --config argument gets the tslint configuration (typically tslint.json):

So, the full command line is:

```<code>tslint --config tslint.json --project tsconfig.json
</code>```

You don't have to specify the files on the command line -- they are found in the tsconfig.json file...

Body:
Some rules require type checking. I don't understand from the documentation about  type checking what to do to run it on the command line.

If I run somethink like

tslint --project admin/tslint.json "project/**/*.ts{,x}"

I get the error message

Invalid source file: project/main.ts. Ensure that the
files supplied to lint have a .ts, .tsx, .d.ts, .js or .jsx extension.

The documentation says

When using the CLI, the --project flag will automatically create a
  program from the specified tsconfig.json file and enable rules that
  require the type checker.

But I don't see the program generated by tslint nor do I understand how to run it.

So, what are the steps to run tslint with type checking form the command line?

Body:
The --project argument needs the typescript compiler tsc configuration file (typically tsconfig.json).

The --config argument gets the tslint configuration (typically tslint.json):

So, the full command line is:

tslint --config tslint.json --project tsconfig.json

You don't have to specify the files on the command line -- they are found in the tsconfig.json file...


问:
how to listen the change the value in textfield or textbox in j2me?
I want to store each character that is input from user. When user presses key, that key should store in any variable. When user presses other key, it must replace the value of variable with new character in textbox in j2me</p>

答:
yes you need to listen event ItemStateListener and then you can handle it in itemStateChanged(..) Here is full code

```<code>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hello;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
 * @author Jigar
 */
public class KeyEventListener extends MIDlet implements ItemStateListener{

    private boolean midletPaused = false;

    //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">
    private Form form;
    private TextField textField;
    //</editor-fold>

    /**
     * The KeyEventListener constructor.
     */
    public KeyEventListener() {
    }

    //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">
    /**
     * Initilizes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {
        // write pre-initialize user code here

        // write post-initialize user code here
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {
        // write pre-action user code here
        switchDisplayable(null, getForm());
        // write post-action user code here
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {
        // write pre-action user code here

        // write post-action user code here
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {
        // write pre-switch user code here
        Display display = getDisplay();
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }
        // write post-switch user code here
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: form ">
    /**
     * Returns an initiliazed instance of form component.
     * @return the initialized component instance
     */
    public Form getForm() {
        if (form == null) {
            // write pre-init user code here
            form = new Form("form", new Item[] { getTextField() });
            form.setItemStateListener(this);
        }
        return form;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: textField ">
    /**
     * Returns an initiliazed instance of textField component.
     * @return the initialized component instance
     */
    public TextField getTextField() {
        if (textField == null) {
            // write pre-init user code here
            textField = new TextField("textField", null, 32, TextField.ANY);

        }
        return textField;
    }
    //</editor-fold>

    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay () {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable (null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet ();
        } else {
            initialize ();
            startMIDlet ();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }

    public void itemStateChanged(Item item) {
        if(item.equals(getTextField())){
            System.out.println("KeyPressed :) ");
        }

    }

}
</code>```

Body:
yes you need to listen event ItemStateListener and then you can handle it in itemStateChanged(..) Here is full code

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hello;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
 * @author Jigar
 */
public class KeyEventListener extends MIDlet implements ItemStateListener{

    private boolean midletPaused = false;

    //<editor-fold defaultstate="collapsed" desc=" Generated Fields ">
    private Form form;
    private TextField textField;
    //</editor-fold>

    /**
     * The KeyEventListener constructor.
     */
    public KeyEventListener() {
    }

    //<editor-fold defaultstate="collapsed" desc=" Generated Methods ">
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">
    /**
     * Initilizes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {
        // write pre-initialize user code here

        // write post-initialize user code here
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {
        // write pre-action user code here
        switchDisplayable(null, getForm());
        // write post-action user code here
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {
        // write pre-action user code here

        // write post-action user code here
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {
        // write pre-switch user code here
        Display display = getDisplay();
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }
        // write post-switch user code here
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: form ">
    /**
     * Returns an initiliazed instance of form component.
     * @return the initialized component instance
     */
    public Form getForm() {
        if (form == null) {
            // write pre-init user code here
            form = new Form("form", new Item[] { getTextField() });
            form.setItemStateListener(this);
        }
        return form;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Generated Getter: textField ">
    /**
     * Returns an initiliazed instance of textField component.
     * @return the initialized component instance
     */
    public TextField getTextField() {
        if (textField == null) {
            // write pre-init user code here
            textField = new TextField("textField", null, 32, TextField.ANY);

        }
        return textField;
    }
    //</editor-fold>

    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay () {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable (null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet ();
        } else {
            initialize ();
            startMIDlet ();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }

    public void itemStateChanged(Item item) {
        if(item.equals(getTextField())){
            System.out.println("KeyPressed :) ");
        }

    }

}


答:
You can try following:

```<code>result = st.join(dtest2, how='outer').fillna(0)
print(result)
</code>```

Output:

```<code>                   1
  index
  1499054400000   0.00
  1499140800000   0.00
  1499227200000  33.48
  1499313600000   0.00
  1499400000000  35.71
</code>```

Or, left join would also give same result:

```<code>result = st.join(dtest2, how='left').fillna(0)
</code>```

Title: pandas join two dataframe based on Index

Body:
You can try following:

result = st.join(dtest2, how='outer').fillna(0)
print(result)

Output:

                   1
  index
  1499054400000   0.00
  1499140800000   0.00
  1499227200000  33.48
  1499313600000   0.00
  1499400000000  35.71

Or, left join would also give same result:

result = st.join(dtest2, how='left').fillna(0)


问:
Me.Close() not working in VB with WPF
I'm using VB with WPF and I am trying to close an application... the code I usually use ( Me.Close() ) is not working this time. The error it gave me was BC30545.. but it didn't help me understand the issue. Thanks for any solutions you all respond with.</p>

答:
The error code BC30545 corresponds with this message:

Property access must assign to the property or use it's value

Make sure you don't have another method/property/control with the same name (For example, a button on your form called "Close"

In the case of this example, you'd rename to something like CloseBtn so that it doesn't interfere.

Title: Me.Close() not working in VB with WPF


问:
Create Object using ObjectBuilder
Want to create objects using ObjectBuilder or ObjectBuilder2.

I do not want to use StructureMap

I was able to create the object having parameterless constructor using the code mentioned below.

```<code> public class ObjectFactory : BuilderBase<BuilderStage>
    {
        public static T BuildUp<T>()
        {
            var builder = new Builder();

            var locator = new Locator { { typeof(ILifetimeContainer), new LifetimeContainer() } };

            var buildUp = builder.BuildUp<T>(locator, null, null);
            return buildUp;
        }
</code>```

for creating object of customer you just call

ObjectFactory.BuildUp<Customer>

However this creates object of class which has no parameters, however I need to create object which are having constructor with parameters.

答:
Used the CreateNew Attribute class to build the object and that worked fine. Also used the SessionStateBindingStrategry so that the object could take session variables as parameters in the constructor. </p>

```<code>  public static T BuildUp<T>()
            {
                var locator = new Locator { { typeof(ILifetimeContainer), new LifetimeContainer() } };
//For accessing the session variables through StateValue<>
                 locator.Add(new DependencyResolutionLocatorKey(typeof(ISessionStateLocatorService), null), new SessionStateLocatorService());

                var builder = new Builder();

                var attribute = new CreateNewAttribute();
                IParameter parameter = attribute.CreateParameter(typeof (T));

                builder.Strategies.AddNew<SessionStateBindingStrategy>(BuilderStage.PreCreation);

                var builderContext =
                    new BuilderContext(builder.Strategies.MakeStrategyChain(),locator,builder.Policies);
                object value = parameter.GetValue(builderContext);

                return (T)value;
            }
</code>```

Title: Create Object using ObjectBuilder

Body:
Want to create objects using ObjectBuilder or ObjectBuilder2.

I do not want to use StructureMap

I was able to create the object having parameterless constructor using the code mentioned below.

 public class ObjectFactory : BuilderBase<BuilderStage>
    {
        public static T BuildUp<T>()
        {
            var builder = new Builder();

            var locator = new Locator { { typeof(ILifetimeContainer), new LifetimeContainer() } };

            var buildUp = builder.BuildUp<T>(locator, null, null);
            return buildUp;
        }

for creating object of customer you just call

ObjectFactory.BuildUp<Customer>

However this creates object of class which has no parameters, however I need to create object which are having constructor with parameters.

Body:
Used the CreateNew Attribute class to build the object and that worked fine. Also used the SessionStateBindingStrategry so that the object could take session variables as parameters in the constructor.

  public static T BuildUp<T>()
            {
                var locator = new Locator { { typeof(ILifetimeContainer), new LifetimeContainer() } };
//For accessing the session variables through StateValue<>
                 locator.Add(new DependencyResolutionLocatorKey(typeof(ISessionStateLocatorService), null), new SessionStateLocatorService());

                var builder = new Builder();

                var attribute = new CreateNewAttribute();
                IParameter parameter = attribute.CreateParameter(typeof (T));

                builder.Strategies.AddNew<SessionStateBindingStrategy>(BuilderStage.PreCreation);

                var builderContext =
                    new BuilderContext(builder.Strategies.MakeStrategyChain(),locator,builder.Policies);
                object value = parameter.GetValue(builderContext);

                return (T)value;
            }


问:
AWS SAM - Circular dependency between resources error
I followed this tutorial to setup an AWS Lambda function that is invoked upon an upload to S3 and populates DynamoDB.

I'm trying to achieve the same with AWS SAM for which I need to define a template.yaml file with the configuration information. I keep getting this error when deploying with Cloudformation -

```<code>Failed to create the changeset: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state Status: FAILED. Reason: Circular dependency between resources: [LambdaPerm]
</code>```

I could not find a lot of information on this so I'm struggling to debug. What's causing this error and how can I resolve this? Here's my template configuration -

```<code>AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  Gradebook:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: LambdaGradebookServerless
      Handler: serverless.LambdaGradebook
      Runtime: java8
      CodeUri: ./target/serverless-0.0.1-SNAPSHOT.jar
      Role: arn:aws:iam::xxxxxxxxxxxx:role/lambda-s3-execution-role
  LambdaPerm:
    Type: AWS::Lambda::Permission
    Properties:
      Action: lambda:InvokeFunction
      FunctionName:
        Ref: Gradebook
      Principal: s3.amazonaws.com
      SourceAccount:
        Ref: AWS::xxxxxxxxxxxx
      SourceArn:
        Fn::Join:
        - ':'
        - - arn
          - aws
          - s3
          - ''
          - ''
          - Ref: gradebookBucket
  gradebookBucket:
    Type: AWS::S3::Bucket
    Properties:
      Bucket: gradebook-lambda
      NotificationConfiguration:
        LambdaConfigurations:
        - Event: s3:ObjectCreated:*
          Function:
            Ref: Gradebook
</code>```

答: To avoid this circular dependency, create the S3 bucket and the Lambda function independently, then update the stack with an S3 notification configuration.</p>

Body:
I followed this tutorial to setup an AWS Lambda function that is invoked upon an upload to S3 and populates DynamoDB.

I'm trying to achieve the same with AWS SAM for which I need to define a template.yaml file with the configuration information. I keep getting this error when deploying with Cloudformation -

Failed to create the changeset: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state Status: FAILED. Reason: Circular dependency between resources: [LambdaPerm]

I could not find a lot of information on this so I'm struggling to debug. What's causing this error and how can I resolve this? Here's my template configuration -

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  Gradebook:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: LambdaGradebookServerless
      Handler: serverless.LambdaGradebook
      Runtime: java8
      CodeUri: ./target/serverless-0.0.1-SNAPSHOT.jar
      Role: arn:aws:iam::xxxxxxxxxxxx:role/lambda-s3-execution-role
  LambdaPerm:
    Type: AWS::Lambda::Permission
    Properties:
      Action: lambda:InvokeFunction
      FunctionName:
        Ref: Gradebook
      Principal: s3.amazonaws.com
      SourceAccount:
        Ref: AWS::xxxxxxxxxxxx
      SourceArn:
        Fn::Join:
        - ':'
        - - arn
          - aws
          - s3
          - ''
          - ''
          - Ref: gradebookBucket
  gradebookBucket:
    Type: AWS::S3::Bucket
    Properties:
      Bucket: gradebook-lambda
      NotificationConfiguration:
        LambdaConfigurations:
        - Event: s3:ObjectCreated:*
          Function:
            Ref: Gradebook


问:
Conditionally setting configs in ExtJS 6?
I have an Ext.Img that I would like to set the src config of based upon a condition. Is there a simple way to accomplish this? I am thinking something like

if(condition){ src: 'image1.png'} else { src: 'image2.png'}

but this obviously won't work. I've using some of the techniques mentioned in this thread, by adding a different image item based on the condition but all I get are errors or no items will be added to the parent panel.

答:
Javascript supports the so-called conditional (ternary) operator:

```<code>condition ? expr1 : expr2
</code>```

which in your example would be

```<code>src: condition?'image1.png':'image2.png'
</code>```

I use this regularly, e.g. to account for varying space requirements of the different themes:

```<code>width: Ext.is.Triton?200:180
</code>```

However, you have to make sure that the variables used in the condition are correctly defined at the time they are evaluated (this may be earlier than you think).

If you need conditions that are re-evaluated whenever the variables change, you have to look into ExtJS bindings.

Body:
Javascript supports the so-called conditional (ternary) operator:

condition ? expr1 : expr2

which in your example would be

src: condition?'image1.png':'image2.png'

I use this regularly, e.g. to account for varying space requirements of the different themes:

width: Ext.is.Triton?200:180

However, you have to make sure that the variables used in the condition are correctly defined at the time they are evaluated (this may be earlier than you think).

If you need conditions that are re-evaluated whenever the variables change, you have to look into ExtJS bindings.


问:
C++ Vector Sorts
I am working with a vector in Codefights for the "almostIncreasingSequence" challenge. Is there a way to track how many "steps" a sort method takes when so I can set a simple counter/flag to check against if the sort passes a predefined threshold?</p>

答:
Yes there is. You can use a custom comparison function with std::sort as follows:

```<code>#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> myVector { 2, 8, 5, 9, 3, 7, 1, 4, 6, 0 };

    int counter = 0;
    std::sort(myVector.begin(), myVector.end(), [&counter](int lhs, int rhs) {
        counter++;
        return lhs < rhs;
    });

    std::cout << "Steps: " << counter << std::endl;
    for(auto e : myVector)
        std::cout << e << ' ';
    std::cout << std::endl;

    return 0;
}
</code>```

Title: C++ Vector Sorts

Body:
Yes there is. You can use a custom comparison function with std::sort as follows:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> myVector { 2, 8, 5, 9, 3, 7, 1, 4, 6, 0 };

    int counter = 0;
    std::sort(myVector.begin(), myVector.end(), [&counter](int lhs, int rhs) {
        counter++;
        return lhs < rhs;
    });

    std::cout << "Steps: " << counter << std::endl;
    for(auto e : myVector)
        std::cout << e << ' ';
    std::cout << std::endl;

    return 0;
}


问:
error copy file that was created in C#
I have this problem when I try to copy a file that was created in C#:

"System.IO.IOException: 'The process can not access the file' d:\las.txt 'because it is being used in another process.'"

my code:

```
using System;

namespace modulo1
{
    class Program
    {
        static void Main(string[] args)
        {
           string folderName = @"c:\lasss";

           System.IO.Directory.CreateDirectory(folderName);

           string archivo = @"d:\las.txt";

           System.IO.File.Create(archivo);

            string dest = @"d:\soft";

           //here is the problem
            System.IO.File.Copy(archivo, dest, true);
        }
    }
}
```

How can i solve this problem???

答:
FIRST LETS SEE WHAT CAUSED THIS PROBLEM?

The error message is pretty clear: you're trying to access a file, and it's not accessible because another process (or even the same process) is doing something with it (and it didn't allow any sharing).

You need to include pattern  that will also ensure that the file won't be left open in case of exceptions (it may be the reason the file is in use: something went wrong, and no one closed it;).

When I said you need to implement pattern fortunately FileStream implements IDisposable, so it's easy to wrap all your code inside a using statement:

```<code>using (var fileStream = System.IO.File.Create(archive)) {
    // do your operations with your files in here
}
</code>```

Title: error copy file that was created in C#

Body:
I have this problem when I try to copy a file that was created in C#:

"System.IO.IOException: 'The process can not access the file' d:\las.txt 'because it is being used in another process.'"

my code:

using System;

namespace modulo1
{
    class Program
    {
        static void Main(string[] args)
        {
           string folderName = @"c:\lasss";

           System.IO.Directory.CreateDirectory(folderName);

           string archivo = @"d:\las.txt";

           System.IO.File.Create(archivo);

            string dest = @"d:\soft";

           //here is the problem
            System.IO.File.Copy(archivo, dest, true);
        }
    }
}

How can i solve this problem???

Body:
FIRST LETS SEE WHAT CAUSED THIS PROBLEM?

The error message is pretty clear: you're trying to access a file, and it's not accessible because another process (or even the same process) is doing something with it (and it didn't allow any sharing).

You need to include pattern  that will also ensure that the file won't be left open in case of exceptions (it may be the reason the file is in use: something went wrong, and no one closed it;).

When I said you need to implement pattern fortunately FileStream implements IDisposable, so it's easy to wrap all your code inside a using statement:

using (var fileStream = System.IO.File.Create(archive)) {
    // do your operations with your files in here
}


问:
Django queryset of related records, but only the max from the related table
Lets say I have two django models which are related. Groups, and People, who belong to a single group.

```<code>class Group(models.Model):
    name = models.CharField(max_length=100, null=True, blank=True)

class Person(models.Model):
    group = models.ForeignKey('Group', on_delete=models.CASCADE, related_name='group')
    name = models.CharField(max_length=100, null=True, blank=True)
    birthdate = models.DateTimeField(auto_now_add=True)
</code>```

What I would like to do, is return a queryset of the Person objects, which is composed of only those people with the greatest birthdate for each group. So if there are 5 'Groups' I want a queryset of 5 'Person' objects, determined by maxmium birthdate.

答:
Pls Try:

```<code>gruop_id = Group.objects.get(name='?').id
Person.objects.filter(group__id=gruop_id).order_by('birthdate').values()[:5]
</code>```

I may not have understood you. Maybe, You want the reverse.

```<code>Person.objects.filter(group__id=gruop_id).order_by('birthdate').values().reverse()[:5]
</code>```

Body:
Lets say I have two django models which are related. Groups, and People, who belong to a single group.

class Group(models.Model):
    name = models.CharField(max_length=100, null=True, blank=True)

class Person(models.Model):
    group = models.ForeignKey('Group', on_delete=models.CASCADE, related_name='group')
    name = models.CharField(max_length=100, null=True, blank=True)
    birthdate = models.DateTimeField(auto_now_add=True)

What I would like to do, is return a queryset of the Person objects, which is composed of only those people with the greatest birthdate for each group. So if there are 5 'Groups' I want a queryset of 5 'Person' objects, determined by maxmium birthdate.

Body:
Pls Try:

gruop_id = Group.objects.get(name='?').id
Person.objects.filter(group__id=gruop_id).order_by('birthdate').values()[:5]

I may not have understood you. Maybe, You want the reverse.

Person.objects.filter(group__id=gruop_id).order_by('birthdate').values().reverse()[:5]


问:
How to find a sibling GameObject by name; Unity2d c#
I am trying to develop a small 2D Unity platformer to learn to work with Unity's interface. I have been having an issue trying to make a gameobject track clones of an enemy and follow it. The function is to make it so when you hover on the enemy clone, it shows the enemy's health. But when I hover on the enemy, it tracks the position of the original enemy, not the clone. Both gameobjects have the same name. What I want is the GameObject HoverDataDisplay (as shown in the screenshot) to track its sibling, Enemy.

The current code that I have for the tracking script is as shown:

```<code>        private GameObject Enemy;

void Start() {

    Enemy = GameObject.Find ("Enemy");
}

void Update(){
    transform.position = new Vector3 (Enemy.transform.position.x - 0.57f, Enemy.transform.position.y + 1.5f, Enemy.transform.position.z);

}
</code>```

But the GameObject (HoverDataDisplay) Only follows the original enemy.

Thanks for your help!

答:
In Unity, you can use the forward slash "/" to find a Child of an Object. Since the name of the parents are different, you can easily find them like this:

```<code>GameObject.Find("EnemyObject/Enemy");
</code>```

And the second HoverDataDisplay:

```<code>GameObject.Find("EnemyObject(Clone)/Enemy");
</code>```

It's not really a good idea to let your GameObject use the default "Clone" name. You should rename it after instantiating it so that it will be easy to find. Only do this if you need to find the Object after instantiating it.

This script is attached to the HoverDataDisplay GameObject

You can actually get it's parent Object which is either EnemyObject or EnemyObject(Clone) with transform.parent then use the FindChild to find the enemy Object.

```<code>//First, Find the Parent Object which is either EnemyObject or EnemyObject(Clone)
Transform parent = transform.parent;

//Now, Find it's Enemy Object
GameObject enemy = parent.FindChild("Enemy").gameObject;
</code>```

I recommend you use this method instead of the first one I mentioned. The first one is mentioned so that you will know it can be done.

EDIT:

Transform.FindChild is now deprecated. You can use Transform.Find to do that same exact thing.

Body:
I am trying to develop a small 2D Unity platformer to learn to work with Unity's interface. I have been having an issue trying to make a gameobject track clones of an enemy and follow it. The function is to make it so when you hover on the enemy clone, it shows the enemy's health. But when I hover on the enemy, it tracks the position of the original enemy, not the clone. Both gameobjects have the same name. What I want is the GameObject HoverDataDisplay (as shown in the screenshot) to track its sibling, Enemy.

The current code that I have for the tracking script is as shown:

        private GameObject Enemy;

void Start() {

    Enemy = GameObject.Find ("Enemy");
}

void Update(){
    transform.position = new Vector3 (Enemy.transform.position.x - 0.57f, Enemy.transform.position.y + 1.5f, Enemy.transform.position.z);

}

But the GameObject (HoverDataDisplay) Only follows the original enemy.

Thanks for your help!

Body:
In Unity, you can use the forward slash "/" to find a Child of an Object. Since the name of the parents are different, you can easily find them like this:

GameObject.Find("EnemyObject/Enemy");

And the second HoverDataDisplay:

GameObject.Find("EnemyObject(Clone)/Enemy");

It's not really a good idea to let your GameObject use the default "Clone" name. You should rename it after instantiating it so that it will be easy to find. Only do this if you need to find the Object after instantiating it.

This script is attached to the HoverDataDisplay GameObject

You can actually get it's parent Object which is either EnemyObject or EnemyObject(Clone) with transform.parent then use the FindChild to find the enemy Object.

//First, Find the Parent Object which is either EnemyObject or EnemyObject(Clone)
Transform parent = transform.parent;

//Now, Find it's Enemy Object
GameObject enemy = parent.FindChild("Enemy").gameObject;

I recommend you use this method instead of the first one I mentioned. The first one is mentioned so that you will know it can be done.

EDIT:

Transform.FindChild is now deprecated. You can use Transform.Find to do that same exact thing.


问:
Webbased MySQL interface better that phpMyAdmin
Is there any webbased interface for MySQL better than phpMyAdmin? I use phpMyAdmin a lot but it is becoming a pain, especially it is slow sometimes.

I'd like to have deep export functionality like phpMyAdmin but more design features

答: As clients, the MySQL Query browser and Administrator are quite good. That has a number of different export facilities that are cool. If it needs to be web though, then you might be best sticking with the slow phpmyadmin.  </p>

OwnerDisplayName: Siamak

OwnerDisplayName: Amadiere


答:
How about appending results using >>?

```<code>find . -name "*.php" | xargs grep -i -n "searchstring" >> output.txt
</code>```

I haven't got a Linux box with me right now, so I'll try to improvize.

the xargs grep -i -n "searchstring" bothers me a bit.

Perhaps you meant xargs -I {} grep -i "searchstring" {}, or just xargs grep -i "searchstring"?

Since -n as grep's argument will give you only number lines, I doubt this is what you needed.

This way, your final code would be

```<code>find . -name "*.php" | xargs grep -i "searchstring" >> output.txt
</code>```

Title: Write output out of grep into a file on Linux?

Body:
find . -name "*.php" | xargs grep -i -n "searchstring" >output.txt

Here I am trying to write data into a file which is not happening...

Body:
How about appending results using >>?

find . -name "*.php" | xargs grep -i -n "searchstring" >> output.txt

I haven't got a Linux box with me right now, so I'll try to improvize.

the xargs grep -i -n "searchstring" bothers me a bit.

Perhaps you meant xargs -I {} grep -i "searchstring" {}, or just xargs grep -i "searchstring"?

Since -n as grep's argument will give you only number lines, I doubt this is what you needed.

This way, your final code would be

find . -name "*.php" | xargs grep -i "searchstring" >> output.txt


问:
React Apollo and Redux: Combine custom reducers with Apollo state
When using react-apollo with redux, data from the server is cached in the redux store under an apollo key:

```<code>{
    apollo: // results from Apollo queries
}
</code>```

After creating your own reducers and corresponding state tree, your store might look like this:

```<code>{
    apollo: { ... },
    ui: {
        selectedItem: 2;
        showItems: 6
    }
}
</code>```

Imagine that there is an action which changes the value of ui.selectedItem, and that this value is the index of an item buried somewhere in the apollo object.

With reducer composition, reducers for our ui state will rightly have no access to anything under the Apollo state.

In our component we can subscribe to changes on our ui state via mapStateToProps, and we can map Apollo results to props using the react-apollo GraphQL container (or @graphql decorator).

But how can we update our store with values that are computed from Apollo results and other state in our application?

For example, if apollo.item.list is an array of items, and ui.selectedItem is the index you want to target in that list - how could the store contain a value for:

```<code>apollo.item.list[ui.selectedItem]
</code>```

答:
You're right -- with reducer composition, each reducer should not have access to the rest of the state. The question is why would you even need your store to contain a separate value for apollo.item.list[ui.selectedItem].

Presumably you need this value to render the correct item inside your container. To calculate it, you just need an appropriate selector to call within mapStateToProps. Pass in the whole state, get the value you need. A simplified example:

```<code>const mapStateToProps = state => ({
  itemToShow: itemSelector(state)
})

const itemSelector = ({ apollo, ui }) => apollo.item.list[ui.selectedItem]
</code>```

You'll need to wrap your container in both the connect and graphql HOCs to make that work, although as far as I can tell, whether you wrap it in one or the other first doesn't seem to matter. You can also look into using reselect which is ideal for derived data like this.

Edit: Since Apollo's chunk of the store wasn't really designed to be used as described above, you may find it easier to break this up into two steps instead: First, assign ui.selectedItem to a prop in mapStateToProps. Then, if you wrap your container with the graphql HOC, you can reference that prop like so:

```<code>const mapStateToProps = state => ({ selectedItem });
const mapDataToProps = ({ ownProps: { selectedItem }, data }) => ({
  itemToShow: data.item.list[selectedItem]
});
const ContainerWithData = graphql(myQuery, { props: mapDataToProps })(MyContainer);

export default connect(mapStateToProps)(ContainerWithData);
</code>```

Or you could use apollo-react's compose for a cleaner approach.

Body:
When using react-apollo with redux, data from the server is cached in the redux store under an apollo key:

{
    apollo: // results from Apollo queries
}

After creating your own reducers and corresponding state tree, your store might look like this:

{
    apollo: { ... },
    ui: {
        selectedItem: 2;
        showItems: 6
    }
}

Imagine that there is an action which changes the value of ui.selectedItem, and that this value is the index of an item buried somewhere in the apollo object.

With reducer composition, reducers for our ui state will rightly have no access to anything under the Apollo state.

In our component we can subscribe to changes on our ui state via mapStateToProps, and we can map Apollo results to props using the react-apollo GraphQL container (or @graphql decorator).

But how can we update our store with values that are computed from Apollo results and other state in our application?

For example, if apollo.item.list is an array of items, and ui.selectedItem is the index you want to target in that list - how could the store contain a value for:

apollo.item.list[ui.selectedItem]

Body:
You're right -- with reducer composition, each reducer should not have access to the rest of the state. The question is why would you even need your store to contain a separate value for apollo.item.list[ui.selectedItem].

Presumably you need this value to render the correct item inside your container. To calculate it, you just need an appropriate selector to call within mapStateToProps. Pass in the whole state, get the value you need. A simplified example:

const mapStateToProps = state => ({
  itemToShow: itemSelector(state)
})

const itemSelector = ({ apollo, ui }) => apollo.item.list[ui.selectedItem]

You'll need to wrap your container in both the connect and graphql HOCs to make that work, although as far as I can tell, whether you wrap it in one or the other first doesn't seem to matter. You can also look into using reselect which is ideal for derived data like this.

Edit: Since Apollo's chunk of the store wasn't really designed to be used as described above, you may find it easier to break this up into two steps instead: First, assign ui.selectedItem to a prop in mapStateToProps. Then, if you wrap your container with the graphql HOC, you can reference that prop like so:

const mapStateToProps = state => ({ selectedItem });
const mapDataToProps = ({ ownProps: { selectedItem }, data }) => ({
  itemToShow: data.item.list[selectedItem]
});
const ContainerWithData = graphql(myQuery, { props: mapDataToProps })(MyContainer);

export default connect(mapStateToProps)(ContainerWithData);

Or you could use apollo-react's compose for a cleaner approach.


问:
Git for Windows: .bashrc or equivalent configuration files for Git Bash shell
I've just installed Git for Windows and am delighted to see that it installs Bash.

I want to customise the shell in the same way I can under Linux (e.g. set up aliases like ll for ls -l), but I can't seem to find .bashrc or equivalent configuration files.

What should I be editing?

答:
Sometimes the files are actually located at ~/. These are the steps I took to starting Zsh as the default terminal on Visual Studio Code/Windows 10.

cd ~/

vim .bashrc

Paste the following...

if test -t 1; then
exec zsh
fi

Save/close Vim.

Restart the terminal


问:
Angular2(v4.2.5) click event doesn't work inside *ngIF
I have the following problem in Angular: as I understand, *ngIf directive doesn't allow me to add event on nesting DOM's component.
 This is the code:

Template

```<code><div class="bf-search-field">
  <input #productSearch
         [(ngModel)]="term"
         (ngModelChange)="search()"
         (blur)="closeAutocomplete()"
         (focus)="activeAutocomplete()"
         autocomplete="off" type="search" id="search"
         placeholder="Search black friday deals"
  />
  <button class="bf-search-field__search-btn"></button>
</div>
<div  class="bf-search-hints">
   <!--use for not duplicate full term in autocomplete-->
      <ng-container *ngFor="let product of products | async">
        <div *ngIf="(term !== product.title) && autocomplete" (click)="update(product.title)"
             class="bf-search-hint" >
          {{ product.title }}
        </div>
      </ng-container>
</div>
</code>```

Component

```<code>/**
 * Created by lizarusi on 02.07.17.
 */
import {Component, OnInit, ViewChild, ElementRef} from '@angular/core';
import { ProductService } from '../shared/product.service'
import {Product} from '../shared/product.model';

import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';

import 'rxjs/add/observable/of';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';

@Component({
  selector: 'product-search',
  templateUrl: './product-search.component.html',
  styleUrls: ['./product-search.component.scss'],
  providers: [ProductService]
})

export class ProductSearchComponent implements OnInit {

  @ViewChild('productSearch') searchField: ElementRef;
  products: Observable<Product[]>;
  autocomplete = true;
  term = '';
  private searchTerms = new Subject<string>();
  constructor(private productService: ProductService) {};
  search(): void {
    console.log('term ' + this.term);
    this.searchTerms.next(this.term);
  }
  ngOnInit(): void {
    this.products = this.searchTerms
      .debounceTime(300)
      .distinctUntilChanged()
      .switchMap( term => this.productService.searchProducts(term))
      .catch((err) => {
          console.log(err);
          return Observable.of<Product[]>([]);
    });
  }
  closeAutocomplete(): void {
    this.autocomplete = false;
  }
  activeAutocomplete(): void {
    this.autocomplete = true;
    this.search();
  }
  update(value: string): void {
    console.log('asaa');
    this.term = value;
    this.searchField.nativeElement.focus();
  }
}
</code>```

In this case my (click) doesn't work. I suppose that it happens
because *ngIf removing my element from DOM and than creating it again, but event listeners wasn't assigned.

The question is: How can I use (click) inside/together with *ngIf? Or any other suggestions to figured this out.

答:
Update:

I looked through your code beyond the ngIf and ngFor and realized you were attempting to directly use your Observable in your ngFor instead of a Subscription to the Observable. The general idea is that after you observe your data you'll want to then push the data into a variable of the proper format. Check out this guide for more information: https://angular-2-training-book.rangle.io/handout/observables/using_observables.html

And specifically this part of the code:

```<code>  let subscription = this.data.subscribe(
      value => this.values.push(value),
      error => this.anyErrors = true,
      () => this.finished = true
  );
</code>```

In your case this.data will be this.products, and this.values will be a new variable. If you use this.finished, you can replace that as your conditional in the ngIf

Body:
I have the following problem in Angular: as I understand, *ngIf directive doesn't allow me to add event on nesting DOM's component.
 This is the code:

Template

  <input #productSearch
         [(ngModel)]="term"
         (ngModelChange)="search()"
         (blur)="closeAutocomplete()"
         (focus)="activeAutocomplete()"
         autocomplete="off" type="search" id="search"
         placeholder="Search black friday deals"
  />
  <button class="bf-search-field__search-btn"></button>

      <ng-container *ngFor="let product of products | async">

          {{ product.title }}

      </ng-container>

Component

/**
 * Created by lizarusi on 02.07.17.
 */
import {Component, OnInit, ViewChild, ElementRef} from '@angular/core';
import { ProductService } from '../shared/product.service'
import {Product} from '../shared/product.model';

import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';

import 'rxjs/add/observable/of';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';

@Component({
  selector: 'product-search',
  templateUrl: './product-search.component.html',
  styleUrls: ['./product-search.component.scss'],
  providers: [ProductService]
})

export class ProductSearchComponent implements OnInit {

  @ViewChild('productSearch') searchField: ElementRef;
  products: Observable<Product[]>;
  autocomplete = true;
  term = '';
  private searchTerms = new Subject<string>();
  constructor(private productService: ProductService) {};
  search(): void {
    console.log('term ' + this.term);
    this.searchTerms.next(this.term);
  }
  ngOnInit(): void {
    this.products = this.searchTerms
      .debounceTime(300)
      .distinctUntilChanged()
      .switchMap( term => this.productService.searchProducts(term))
      .catch((err) => {
          console.log(err);
          return Observable.of<Product[]>([]);
    });
  }
  closeAutocomplete(): void {
    this.autocomplete = false;
  }
  activeAutocomplete(): void {
    this.autocomplete = true;
    this.search();
  }
  update(value: string): void {
    console.log('asaa');
    this.term = value;
    this.searchField.nativeElement.focus();
  }
}

In this case my (click) doesn't work. I suppose that it happens
because *ngIf removing my element from DOM and than creating it again, but event listeners wasn't assigned.

The question is: How can I use (click) inside/together with *ngIf? Or any other suggestions to figured this out.

Body:
Update:

I looked through your code beyond the ngIf and ngFor and realized you were attempting to directly use your Observable in your ngFor instead of a Subscription to the Observable. The general idea is that after you observe your data you'll want to then push the data into a variable of the proper format. Check out this guide for more information: https://angular-2-training-book.rangle.io/handout/observables/using_observables.html

And specifically this part of the code:

  let subscription = this.data.subscribe(
      value => this.values.push(value),
      error => this.anyErrors = true,
      () => this.finished = true
  );

In your case this.data will be this.products, and this.values will be a new variable. If you use this.finished, you can replace that as your conditional in the ngIf


问:
How to extend 'resize' event?
I listen for a resize event, but I need to extend it, because I use it globally. I need to have some additional checks for passing before calling this event. How can I achieve this?

答:
I'm going to start off by saying I'm not exactly sure what you're asking for, but hopefully this will help a little. in JavaScript, you don't 'call' an event like resize. You listen for it, and when it fires, you do something.

For example, if (as I think you mean), you want to do something once the window has been resized and a few conditions have been met, try something like this:

```<code><html>
<body onresize = 'myFunction(condition1, condition2, condition3)'>
    <div id = 'content'>
        <!--your content here-->
    </div>
</body>
</code>```

and then for your JavaScript:

```<code>function myFunction(condition1, condition2, condition3){
    if(condition1 && condition2 && condition3){
        //code that will execute once resize event fires
        //and all three conditions have been met
        console.log("Resize event detected, all three conditions have been met");
        //your code here
    };
}
</code>```

Is this what you're looking for?

You could also try something like this:

```<code>function myFunction(cond1, cond2, cond3(){
    if(cond1 && cond2 && cond3){
        //code that will execute once resize event fires
        //and all three conditions have been met
        console.log("Resize event detected, all three conditions have been met");
        //your code here
    };
}
window.addEventListener("resize", myFunction(cond1, cond2, cond3);
</code>```

Title: How to extend 'resize' event?

Body:
I'm going to start off by saying I'm not exactly sure what you're asking for, but hopefully this will help a little. in JavaScript, you don't 'call' an event like resize. You listen for it, and when it fires, you do something.

For example, if (as I think you mean), you want to do something once the window has been resized and a few conditions have been met, try something like this:

<html>
<body onresize = 'myFunction(condition1, condition2, condition3)'>
    <div id = 'content'>
        <!--your content here-->
    </div>
</body>

and then for your JavaScript:

function myFunction(condition1, condition2, condition3){
    if(condition1 && condition2 && condition3){
        //code that will execute once resize event fires
        //and all three conditions have been met
        console.log("Resize event detected, all three conditions have been met");
        //your code here
    };
}

Is this what you're looking for?

You could also try something like this:

function myFunction(cond1, cond2, cond3(){
    if(cond1 && cond2 && cond3){
        //code that will execute once resize event fires
        //and all three conditions have been met
        console.log("Resize event detected, all three conditions have been met");
        //your code here
    };
}
window.addEventListener("resize", myFunction(cond1, cond2, cond3);