问:
R plot over a background image with coordinates
I have a factory layout in png format shown below.
And I have item moving activity data with coordinates ( starts from (0,0) and ends at (100,100)) like:

```<code>x y
0 4
2 5
4 100
</code>```

(0,4) means item showing in this position and I want to plot a dot. (0,100) indicates the lower-right endpoint.

I expected certain area has darker color if it visited more frequently.

How to plot the activity data into picture file with the right scale respected to the size of the pic?

答:
If you load the image into R as a raster image, you can plot it with the rasterImage function.

```<code>## Your data
PTS = read.table(text="x y
0 4
2 5
4 100",
header=TRUE)

library(png)
IM = readPNG(file.choose())
plot(NULL, xlim=c(0,100), ylim=c(0,100), axes=FALSE, xlab="", ylab="")
rasterImage(IM,0,0,100,100)
points(PTS[,2:1], pch=20, col="red")
</code>```

Notice that I used the y coordinates first, then the x's for the points function to match your statement "(0,100) indicates the lower-right endpoint."

If you want to show high traffic by darker color,  use a transparent color so that the depth of the color adds up. Your three points aren't enough to show that so I made up some other bogus data to illustrate this.

```<code>x = c(rnorm(400,40,10), rnorm(100,40,5))
y = 43 + rnorm(500,0,1)
plot(NULL, xlim=c(0,100), ylim=c(0,100), axes=FALSE, xlab="", ylab="")
rasterImage(IM,0,0,100,100)
points(y,x, pch=20, col="#33333322")
</code>```

Body:
I have a factory layout in png format shown below.
And I have item moving activity data with coordinates ( starts from (0,0) and ends at (100,100)) like:

x y
0 4
2 5
4 100

(0,4) means item showing in this position and I want to plot a dot. (0,100) indicates the lower-right endpoint.

I expected certain area has darker color if it visited more frequently.

How to plot the activity data into picture file with the right scale respected to the size of the pic?

Body:
If you load the image into R as a raster image, you can plot it with the rasterImage function.

## Your data
PTS = read.table(text="x y
0 4
2 5
4 100",
header=TRUE)

library(png)
IM = readPNG(file.choose())
plot(NULL, xlim=c(0,100), ylim=c(0,100), axes=FALSE, xlab="", ylab="")
rasterImage(IM,0,0,100,100)
points(PTS[,2:1], pch=20, col="red")

Notice that I used the y coordinates first, then the x's for the points function to match your statement "(0,100) indicates the lower-right endpoint."

If you want to show high traffic by darker color,  use a transparent color so that the depth of the color adds up. Your three points aren't enough to show that so I made up some other bogus data to illustrate this.

x = c(rnorm(400,40,10), rnorm(100,40,5))
y = 43 + rnorm(500,0,1)
plot(NULL, xlim=c(0,100), ylim=c(0,100), axes=FALSE, xlab="", ylab="")
rasterImage(IM,0,0,100,100)
points(y,x, pch=20, col="#33333322")


来源: stackexchange

问:
MongoDB: Shall I keep a global session all the time?
Here is a snippet of my DAO implementation:

```<code>type (
    User struct {
        Name string `json:"name" bson:"name"`
        ...
    }

    UserDAO struct {
        *mgo.Database
    }
)

func NewUserDAO() (*UserDAO, error) {
    session, err := mgo.Dial("mongodb://127.0.0.1:27017/test")
    if err != nil {
        return nil, err
    }

    return &UserDAO{session.DB("")}, nil
}

func (d *UserDAO) Insert(user User) error {
    return d.C("users").Insert(user)
}

func (d *CandleDAO) Find(name string) ([]User, error) {
    var result []User
    if err := d.C("users").Find(bson.M{"name": name)}).Sort("time").All(&result); err != nil {
        return nil, err
    }
    return result, nil
}

...

func (d *CandleDAO) Close() {
    d.Session.Close()
}
</code>```

And here is how I invoke it:

```<code>dao, err := dao.NewUserDAO()
if err != nil {
    Log.Error(err.Error())
    return
}

// close session... is this OK?
defer dao.Close()

users, err := dao.Find(&broker.Symbol{"BTC", "USD"}); if err != nil {
    Log.Error(err.Error())
    return
}

for i, user := range users {
    fmt.Printf("%d ==> %v\n", i, user)
}
</code>```

The code above works... and my question is simple: shall I keep a global mgo.Database instance or is it correct to always close the session when I'm finished and create a new one whenever I need?

答:
Per the main package docs:

New sessions are typically created by calling session.Copy on the
  initial session obtained at dial time. These new sessions will share
  the same cluster information and connection pool, and may be easily
  handed into other methods and functions for organizing logic. Every
  session created must have its Close method called at the end of its
  life time, so its resources may be put back in the pool or collected,
  depending on the case.

Meaning: at startup you should Dial and save that session, and for each call to NewUserDAO you should Clone the initial Session created with Dial.

ContentLicense: CC BY-SA 3.0

Body:
Here is a snippet of my DAO implementation:

type (
    User struct {
        Name string `json:"name" bson:"name"`
        ...
    }

    UserDAO struct {
        *mgo.Database
    }
)

func NewUserDAO() (*UserDAO, error) {
    session, err := mgo.Dial("mongodb://127.0.0.1:27017/test")
    if err != nil {
        return nil, err
    }

    return &UserDAO{session.DB("")}, nil
}

func (d *UserDAO) Insert(user User) error {
    return d.C("users").Insert(user)
}

func (d *CandleDAO) Find(name string) ([]User, error) {
    var result []User
    if err := d.C("users").Find(bson.M{"name": name)}).Sort("time").All(&result); err != nil {
        return nil, err
    }
    return result, nil
}

...

func (d *CandleDAO) Close() {
    d.Session.Close()
}

And here is how I invoke it:

dao, err := dao.NewUserDAO()
if err != nil {
    Log.Error(err.Error())
    return
}

// close session... is this OK?
defer dao.Close()

users, err := dao.Find(&broker.Symbol{"BTC", "USD"}); if err != nil {
    Log.Error(err.Error())
    return
}

for i, user := range users {
    fmt.Printf("%d ==> %v\n", i, user)
}

The code above works... and my question is simple: shall I keep a global mgo.Database instance or is it correct to always close the session when I'm finished and create a new one whenever I need?


问:
Match + offset in google sheets
Probably quite simple, but cannot get it together.

I simply want to match cell B2 with the range D2:D12. If there is an exact match, then pull the link next to the table with destinations, and give that value in A1.

Thanks so much for the help!

// Non-coder building chatbot backend in Google Sheets :)

Title: Match + offset in google sheets

Body:
Try A1:

=VLOOKUP(B2,D1:E15,2,0)


问:
How to change the same characters in a string to different values in python?
I'm trying to implement a basic converting program, changing stars to either  or  depending on if they are the first or second of a pair, but regardless of what I do my program changes all the stars to  or .

```<code>line = "*ju*bil*ee*"
star_counter = 0
new_line = line
    for character in line:
         if character is "*":
            star_counter += 1
            if star_counter%2 == 0:
                new_line = line.replace(character, "</em>")
            else:
                new_line = line.replace(character, "<em>")
</code>```

答:
You're already looping over the input string character by character, so just append to the output (your toggling of opening/closing em tags is ok).

```<code>line = "*ju*bil*ee*"
expected = "<em>ju</em>bil<em>ee</em>"
star_counter = 0
new_line = ""
for character in line:
  if character is "*":
    star_counter += 1
    if star_counter%2 == 0:
      new_line += "</em>"
    else:
      new_line += "<em>"
  else:
    new_line += character

assert new_line == expected
</code>```

Body:
I'm trying to implement a basic converting program, changing stars to either  or  depending on if they are the first or second of a pair, but regardless of what I do my program changes all the stars to  or .

line = "*ju*bil*ee*"
star_counter = 0
new_line = line
    for character in line:
         if character is "*":
            star_counter += 1
            if star_counter%2 == 0:
                new_line = line.replace(character, "")
            else:
                new_line = line.replace(character, "")

Body:
You're already looping over the input string character by character, so just append to the output (your toggling of opening/closing em tags is ok).

line = "*ju*bil*ee*"
expected = "<em>ju</em>bil<em>ee</em>"
star_counter = 0
new_line = ""
for character in line:
  if character is "*":
    star_counter += 1
    if star_counter%2 == 0:
      new_line += "</em>"
    else:
      new_line += "<em>"
  else:
    new_line += character

assert new_line == expected


问:
AWS: Setting up a kinesis stream from PostgreSQL to Redshift
In reference to my previous question, I got my boss to go ahead and let me set up a DMS from my existing postgres to our new redshift db for our analytics team.

The next issue that I am having, and after spending 3 days doing searching on this has provided nothing to help me with this.  My boss wants to use Kinesis to pull real-time data from our PG db to our RS db so our analytics team can pull data in real time from it.  I'm trying to get this configured and I'm running into nothing but headaches.

I have a Stream set up, Firehose set up to grab from our S3 bucket that I created called "postgres-stream-bucket", but I'm not sure how to get data to dump into it from PG, and then making sure that RS picks everything up and uses it, in real time.

However, if there are better options I would love to hear them, but it is imperative that we have real-time (or as close as possible) translated data.

答:
Amazon Kinesis Firehose is ideal if you have streaming data coming into your systems. It will collect the records, batch them and load them into Redshift. However, it is not an ideal solution for what you have described, where your source is a database rather than random streams of data.

Since you already have the Database Migration Service setup, you can continue to use it for continuous data replication between PostgreSQL and Redshift. This would be the simplest and most effective solution.


问:
Keras: Training loss decrases (accuracy increase) while validation loss increases (accuracy decrease)
I am working on a very sparse dataset with the point of predicting 6 classes.
I have tried working with a lot of models and architectures, but the problem remains the same.

When I start training, the acc for training will slowly start to increase and loss will decrease where as the validation will do the exact opposite.

I have really tried to deal with overfitting, and I simply cannot still believe that this is what is coursing this issue.

What have I tried

Transfer learning on VGG16:

exclude top layer and add dense layer with 256 units and 6 units softmax output layer

finetune the top CNN block

finetune the top 3-4 CNN blocks

To deal with overfitting I use heavy augmentation in Keras and dropout after the 256 dense layer with p=0.5.

Creating own CNN with VGG16-ish architecture:

including batch normalization wherever possible

L2 regularization on each CNN+dense layer

Dropout from anywhere between 0.5-0.8 after each CNN+dense+pooling layer

Heavy data augmentation in "on the fly" in Keras

Realising that perhaps I have too many free parameters:

decreasing the network to only contain 2 CNN blocks + dense + output.

dealing with overfitting in the same manner as above.

Without exception all training sessions are looking like this:
Training & Validation loss+accuracy

The last mentioned architecture looks like this:

```<code>    reg = 0.0001

    model = Sequential()

    model.add(Conv2D(8, (3, 3), input_shape=input_shape, padding='same',
            kernel_regularizer=regularizers.l2(reg)))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.7))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.5))

    model.add(Conv2D(16, (3, 3), input_shape=input_shape, padding='same',
            kernel_regularizer=regularizers.l2(reg)))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.7))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.5))

    model.add(Flatten())
    model.add(Dense(16, kernel_regularizer=regularizers.l2(reg)))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.5))

    model.add(Dense(6))
    model.add(Activation('softmax'))

    model.compile(loss='categorical_crossentropy', optimizer='SGD',metrics=['accuracy'])
</code>```

And the data is augmented by the generator in Keras and is loaded with flow_from_directory:

```<code>    train_datagen = ImageDataGenerator(rotation_range=10,
                                width_shift_range=0.05,
                                height_shift_range=0.05,
                                shear_range=0.05,
                                zoom_range=0.05,
                                rescale=1/255.,
                                fill_mode='nearest',
                                channel_shift_range=0.2*255)
    train_generator = train_datagen.flow_from_directory(
                train_data_dir,
                target_size=(img_width, img_height),
                batch_size=batch_size,
                shuffle = True,
                class_mode='categorical')

    validation_datagen = ImageDataGenerator(rescale=1/255.)
    validation_generator = validation_datagen.flow_from_directory(
                                            validation_data_dir,
                                            target_size=(img_width, img_height),
                                            batch_size=1,
                                            shuffle = True,
                                            class_mode='categorical')
</code>```

答:
IMHO, this is just normal situation for DL.  In Keras you can setup a callback that will save the best model (depending on evaluation metric that you provide), and callback that will stop training if model isn't improving.

See ModelCheckpoint & EarlyStopping callbacks respectively.

P.S. Sorry, maybe I misunderstood question - do you have validation loss decreasing form first step?

Body:
I am working on a very sparse dataset with the point of predicting 6 classes.
I have tried working with a lot of models and architectures, but the problem remains the same.

When I start training, the acc for training will slowly start to increase and loss will decrease where as the validation will do the exact opposite.

I have really tried to deal with overfitting, and I simply cannot still believe that this is what is coursing this issue.

What have I tried

Transfer learning on VGG16:

exclude top layer and add dense layer with 256 units and 6 units softmax output layer

finetune the top CNN block

finetune the top 3-4 CNN blocks

To deal with overfitting I use heavy augmentation in Keras and dropout after the 256 dense layer with p=0.5.

Creating own CNN with VGG16-ish architecture:

including batch normalization wherever possible

L2 regularization on each CNN+dense layer

Dropout from anywhere between 0.5-0.8 after each CNN+dense+pooling layer

Heavy data augmentation in "on the fly" in Keras

Realising that perhaps I have too many free parameters:

decreasing the network to only contain 2 CNN blocks + dense + output.

dealing with overfitting in the same manner as above.

Without exception all training sessions are looking like this:
Training & Validation loss+accuracy

The last mentioned architecture looks like this:

    reg = 0.0001

    model = Sequential()

    model.add(Conv2D(8, (3, 3), input_shape=input_shape, padding='same',
            kernel_regularizer=regularizers.l2(reg)))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.7))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.5))

    model.add(Conv2D(16, (3, 3), input_shape=input_shape, padding='same',
            kernel_regularizer=regularizers.l2(reg)))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.7))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.5))

    model.add(Flatten())
    model.add(Dense(16, kernel_regularizer=regularizers.l2(reg)))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.5))

    model.add(Dense(6))
    model.add(Activation('softmax'))

    model.compile(loss='categorical_crossentropy', optimizer='SGD',metrics=['accuracy'])

And the data is augmented by the generator in Keras and is loaded with flow_from_directory:

    train_datagen = ImageDataGenerator(rotation_range=10,
                                width_shift_range=0.05,
                                height_shift_range=0.05,
                                shear_range=0.05,
                                zoom_range=0.05,
                                rescale=1/255.,
                                fill_mode='nearest',
                                channel_shift_range=0.2*255)
    train_generator = train_datagen.flow_from_directory(
                train_data_dir,
                target_size=(img_width, img_height),
                batch_size=batch_size,
                shuffle = True,
                class_mode='categorical')

    validation_datagen = ImageDataGenerator(rescale=1/255.)
    validation_generator = validation_datagen.flow_from_directory(
                                            validation_data_dir,
                                            target_size=(img_width, img_height),
                                            batch_size=1,
                                            shuffle = True,
                                            class_mode='categorical')


问:
Firestore Getting documents id from collection
I'm trying to retrieve my documents with id but can't figure it out.

Currently I retrieve my documents like this :

```<code>const racesCollection: AngularFirestoreCollection<Races> = this.afs.collection('races');
return racesCollection.valueChanges();
</code>```

I do get my documents list perfectly, however there is no doc id with them.

How can I retrieve it for each document ?

答:
To obtain the id of the documents in a collection, you must use snapshotChanges()

    this.shirtCollection = afs.collection<Shirt>('shirts');
    // .snapshotChanges() returns a DocumentChangeAction[], which contains
    // a lot of information about "what happened" with each change. If you want to
    // get the data and the id use the map operator.
    this.shirts = this.shirtCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data() as Shirt;
        const id = a.payload.doc.id;
        return { id, ...data };
      });
    });
```

Documentation
https://github.com/angular/angularfire2/blob/7eb3e51022c7381dfc94ffb9e12555065f060639/docs/firestore/collections.md#example

Body:
I'm trying to retrieve my documents with id but can't figure it out.

Currently I retrieve my documents like this :

const racesCollection: AngularFirestoreCollection<Races> = this.afs.collection('races');
return racesCollection.valueChanges();

I do get my documents list perfectly, however there is no doc id with them.

How can I retrieve it for each document ?

Body:
To obtain the id of the documents in a collection, you must use snapshotChanges()

    this.shirtCollection = afs.collection<Shirt>('shirts');
    // .snapshotChanges() returns a DocumentChangeAction[], which contains
    // a lot of information about "what happened" with each change. If you want to
    // get the data and the id use the map operator.
    this.shirts = this.shirtCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data() as Shirt;
        const id = a.payload.doc.id;
        return { id, ...data };
      });
    });

Documentation
https://github.com/angular/angularfire2/blob/7eb3e51022c7381dfc94ffb9e12555065f060639/docs/firestore/collections.md#example

ContentLicense: CC BY-SA 4.0


问:
How can I view hidden characters in Notepad++?
I have a string that has been giving some of my code fits of rage and its got "extra" characters in it that I only stumbled upon by using the arrow keys to go through it.  I noticed that the cursor stayed in place in certain areas for an extra keystroke of the arrow key.  Using View >Show Symbols > Show All Characters still didnt seem to indicate anything there.  What kind of character could be there and is there a plugin for it?</p>

答:
The simplest way is to use the menu:

View->Show Symbol->Show all characters

It will show Tabs and EOL characters.

Here is an example of a VBS script that announces the current hour being viewed in Notepad++ on Win7.

Note that it is clear I used spaces to do the indents - not Tabs.

This is the base script I used in the Q&A about how to make Windows announce the time at the top of each hour:

https://superuser.com/questions/1268702/how-to-make-windows-speak-the-time-at-the-top-of-the-hour/1268703#1268703


问:
Historical and current size
I have a database which uses a Creation date field on all of the tables. How do i go about using row count and byte to get the size of tables and then get the size of the Db. Do i have to manually run a script to calculate for one table and then to the next. or can everything can be done once. </p>

<p>-- Any Suggestion would be appreciated </p>

答:
To get the current size (approximate size from InnoDB) for the tables in your database try this

```<code>SELECT TABLE_NAME, DATA_LENGTH+INDEX_LENGTH size
  FROM information_schema.TABLES
 WHERE TABLE_SCHEMA=DATABASE();
</code>```

If you want to guess the size a month ago (historical size) you can use the TABLES.AVG_ROW_LENGTH value, and a guesstimate of the number of rows you had back then. But that won't take index storage into account.

Title: Historical and current size

Body:
I have a database which uses a Creation date field on all of the tables. How do i go about using row count and byte to get the size of tables and then get the size of the Db. Do i have to manually run a script to calculate for one table and then to the next. or can everything can be done once.

-- Any Suggestion would be appreciated

Body:
To get the current size (approximate size from InnoDB) for the tables in your database try this

SELECT TABLE_NAME, DATA_LENGTH+INDEX_LENGTH size
  FROM information_schema.TABLES
 WHERE TABLE_SCHEMA=DATABASE();

If you want to guess the size a month ago (historical size) you can use the TABLES.AVG_ROW_LENGTH value, and a guesstimate of the number of rows you had back then. But that won't take index storage into account.


问:
A robust solution for FileSystemWatcher firing events multiple times
FileSystemWatcher events can fire multiple times. Not good if I need predictable behaviour from my code.

This is described in the MSDN documentation:

Common file system operations might raise more than one event. For
  example, when a file is moved from one directory to another, several
  OnChanged and some OnCreated and OnDeleted events might be raised.
  Moving a file is a complex operation that consists of multiple simple
  operations, therefore raising multiple events. Likewise, some
  applications (for example, antivirus software) might cause additional
  file system events that are detected by FileSystemWatcher.

Good use of NotifyFilters with particular events has helped but won't give me 100% confidence in the consistency.

Here's an example, recreating a Notepad write example (but I have experienced this with other write actions too):

```<code> public ExampleAttributesChangedFiringTwice(string demoFolderPath)
 {
     var watcher = new FileSystemWatcher()
     {
          Path = @"c:\temp",
          NotifyFilter = NotifyFilters.LastWrite,
          Filter = "*.txt"
      };

      watcher.Changed += OnChanged;
      watcher.EnableRaisingEvents = true;
  }

  private static void OnChanged(object source, FileSystemEventArgs e)
  {
      // This will fire twice if I edit a file in Notepad
  }
</code>```

Any suggestions for making this more resilient?

EDIT: meaning not repeating multiple actions when multiple events are triggered.

答:
An approach utilising MemoryCache as a buffer that will 'throttle' additional events.

A file event (Changed in this example) is triggered

The event is handled by OnChanged but instead of completing the desired action, it stores the event in MemoryCache
 with a 1 second expiration
 and a CacheItemPolicy callback setup to execute on expiration.

Note that I use AddOrGetExisting as an simple way to block any additional events firing within the cache period being added to the cache.

When it expires, the callback OnRemovedFromCache completes the behaviour intended for that file event

.

```<code>  class BlockAndDelayExample
{
    private readonly MemoryCache _memCache;
    private readonly CacheItemPolicy _cacheItemPolicy;
    private const int CacheTimeMilliseconds = 1000;

    public BlockAndDelayExample(string demoFolderPath)
    {
        _memCache = MemoryCache.Default;

        var watcher = new FileSystemWatcher()
        {
            Path = demoFolderPath,
            NotifyFilter = NotifyFilters.LastWrite,
            Filter = "*.txt"
        };

        _cacheItemPolicy = new CacheItemPolicy()
        {
            RemovedCallback = OnRemovedFromCache
        };

        watcher.Changed += OnChanged;
        watcher.EnableRaisingEvents = true;
    }

    // Add file event to cache for CacheTimeMilliseconds
    private void OnChanged(object source, FileSystemEventArgs e)
    {
        _cacheItemPolicy.AbsoluteExpiration =
            DateTimeOffset.Now.AddMilliseconds(CacheTimeMilliseconds);

        // Only add if it is not there already (swallow others)
        _memCache.AddOrGetExisting(e.Name, e, _cacheItemPolicy);
    }

    // Handle cache item expiring
    private void OnRemovedFromCache(CacheEntryRemovedArguments args)
    {
        if (args.RemovedReason != CacheEntryRemovedReason.Expired) return;

        // Now actually handle file event
        var e = (FileSystemEventArgs) args.CacheItem.Value;
    }
}
</code>```

Could easily extend to:

Check file lock on expiry from cache and if not available, put it back in the cache again (sometimes events fire so fast the file isn't ready for some operations). Preferable to using try/catch loops.

Key cache on file name + event type combined

Body:
FileSystemWatcher events can fire multiple times. Not good if I need predictable behaviour from my code.

This is described in the MSDN documentation:

Common file system operations might raise more than one event. For
  example, when a file is moved from one directory to another, several
  OnChanged and some OnCreated and OnDeleted events might be raised.
  Moving a file is a complex operation that consists of multiple simple
  operations, therefore raising multiple events. Likewise, some
  applications (for example, antivirus software) might cause additional
  file system events that are detected by FileSystemWatcher.

Good use of NotifyFilters with particular events has helped but won't give me 100% confidence in the consistency.

Here's an example, recreating a Notepad write example (but I have experienced this with other write actions too):

 public ExampleAttributesChangedFiringTwice(string demoFolderPath)
 {
     var watcher = new FileSystemWatcher()
     {
          Path = @"c:\temp",
          NotifyFilter = NotifyFilters.LastWrite,
          Filter = "*.txt"
      };

      watcher.Changed += OnChanged;
      watcher.EnableRaisingEvents = true;
  }

  private static void OnChanged(object source, FileSystemEventArgs e)
  {
      // This will fire twice if I edit a file in Notepad
  }

Any suggestions for making this more resilient?

EDIT: meaning not repeating multiple actions when multiple events are triggered.

Body:
An approach utilising MemoryCache as a buffer that will 'throttle' additional events.

A file event (Changed in this example) is triggered

The event is handled by OnChanged but instead of completing the desired action, it stores the event in MemoryCache
 with a 1 second expiration
 and a CacheItemPolicy callback setup to execute on expiration.

Note that I use AddOrGetExisting as an simple way to block any additional events firing within the cache period being added to the cache.

When it expires, the callback OnRemovedFromCache completes the behaviour intended for that file event

.

  class BlockAndDelayExample
{
    private readonly MemoryCache _memCache;
    private readonly CacheItemPolicy _cacheItemPolicy;
    private const int CacheTimeMilliseconds = 1000;

    public BlockAndDelayExample(string demoFolderPath)
    {
        _memCache = MemoryCache.Default;

        var watcher = new FileSystemWatcher()
        {
            Path = demoFolderPath,
            NotifyFilter = NotifyFilters.LastWrite,
            Filter = "*.txt"
        };

        _cacheItemPolicy = new CacheItemPolicy()
        {
            RemovedCallback = OnRemovedFromCache
        };

        watcher.Changed += OnChanged;
        watcher.EnableRaisingEvents = true;
    }

    // Add file event to cache for CacheTimeMilliseconds
    private void OnChanged(object source, FileSystemEventArgs e)
    {
        _cacheItemPolicy.AbsoluteExpiration =
            DateTimeOffset.Now.AddMilliseconds(CacheTimeMilliseconds);

        // Only add if it is not there already (swallow others)
        _memCache.AddOrGetExisting(e.Name, e, _cacheItemPolicy);
    }

    // Handle cache item expiring
    private void OnRemovedFromCache(CacheEntryRemovedArguments args)
    {
        if (args.RemovedReason != CacheEntryRemovedReason.Expired) return;

        // Now actually handle file event
        var e = (FileSystemEventArgs) args.CacheItem.Value;
    }
}

Could easily extend to:

Check file lock on expiry from cache and if not available, put it back in the cache again (sometimes events fire so fast the file isn't ready for some operations). Preferable to using try/catch loops.

Key cache on file name + event type combined


问:
python memory-profiler giving no attribute error with pickle load
I am trying to use memory_profiler but it is giving pickling error.
In my code I am loading a object from a pickle file and the code is working fine but when I am running it with memory profiler it gives "'module' object has no attribute" error. Any suggestions? </p>

答:
Use the import mechanism rather than invoking python -m memory_profiler, ie.

```<code>from memory_profiler import profile

@profile
def func():
    …
    data = pickle.load(open('myfile', 'rb'))
    …
</code>```

I’m not able to give a clear explanation of why that works.

Body:
Use the import mechanism rather than invoking python -m memory_profiler, ie.

from memory_profiler import profile

@profile
def func():
    …
    data = pickle.load(open('myfile', 'rb'))
    …

I’m not able to give a clear explanation of why that works.


问:
Memory Address showing? C++
Not really sure what's going on here, I'm using Clion as my IDE which I don't believe has anything to do with this but I figured I'd add that information. My confusion comes from a function that I wrote

```<code>int Arry()
{

int Mynumbers [5] = {10};

    std::cout << Mynumbers;
}
</code>```

something simple. It should be assigning 5 integers the value of 10. But when I print out Mynumbers I am shown the memory address. Why is this happening, I thought that was what calling pointers was for. Thank you for your time.

Sincerely,
Nicholas

答:
It is a bit complicated, and there are a few issues at play:

std::cout (actually, std::ostream, of which std::cout is an instance, does not have an overload of operator<< that understands plain arrays. It does have overloads that understand pointers.

In C++ (and C) an array name can be used as an expression in a place where a pointer is needed. When there is no better option, the array name will decay to a pointer. That is what makes the following legal: int a[10] = {}; int* p = a;.

The overload that takes a pointer prints it as a hexadecimal address, unless the pointer is of type char* or const char* (or wchar versions), in which case it treats it as a null terminated string.

This is what is happening here: because there isn't an operator<< overload that matches the array, it decays to the overload taking a pointer. And as it isn't a character type pointer, you see the hexadecimal address. You are seeing the equivalent of cout << &MyNumbers[0];.

Title: Memory Address showing? C++

Body:
Not really sure what's going on here, I'm using Clion as my IDE which I don't believe has anything to do with this but I figured I'd add that information. My confusion comes from a function that I wrote

int Arry()
{

int Mynumbers [5] = {10};

    std::cout << Mynumbers;
}

something simple. It should be assigning 5 integers the value of 10. But when I print out Mynumbers I am shown the memory address. Why is this happening, I thought that was what calling pointers was for. Thank you for your time.

Sincerely,
Nicholas


问:
How to know whether an Android foreground service was started by OS or some user action?
I have a requirement to keep a service running (which fetches latest location updates) regardless of whether my Android app is running or closed.

I have finally used a notification based foreground service for this purpose, and it does this job well unless and until the app is closed.
So what happens is:

when the app is running on UI or in the background, the service perfectly fetches the location.

when the app is closed, i.e. swiped off from recent apps, the service gets restarted somehow and fails to fetch location updates.

Now, I want to understand whether that service is started by my application or by the Android OS. Is there any way to figure out?

I tried the following, but the problem is that intent isn't always null when started by service.

```<code>public int onStartCommand(Intent intent, int flags, int startId) {

    Log.i(Constants.TAG + this.getClass().getSimpleName(), "Inside onStartCommand");

    if (null == intent) {

        Log.w(Constants.TAG, "Service was stopped and automatically restarted by the system.");
        BackgroundTaskHandler.startLocationMonitorServiceBySelf(this, 20 * 1000); // start after 20 sec
        Log.w(Constants.TAG, "Stopped self. Restarting again via alarm.");
        stopSelf();

    } else {
        // Other piece of code to setup location client
        // and configure notification intent
    }

    return START_STICKY;
}
</code>```

答:
Instead of checking if the intent is null, you can be more specific and check if the intent contains an extra set by your activity.

In your activity:

```<code>Intent intent = new Intent(mContext, YourService.class);
intent.putExtra("IntentFlag", "MainActivity");
</code>```

In your service:

```<code>if (intent.getStringExtra("IntentFlag").equals("MainActivity"))
{
    //Service started by activity
}
</code>```

Hope this helps!

Body:
I have a requirement to keep a service running (which fetches latest location updates) regardless of whether my Android app is running or closed.

I have finally used a notification based foreground service for this purpose, and it does this job well unless and until the app is closed.
So what happens is:

when the app is running on UI or in the background, the service perfectly fetches the location.

when the app is closed, i.e. swiped off from recent apps, the service gets restarted somehow and fails to fetch location updates.

Now, I want to understand whether that service is started by my application or by the Android OS. Is there any way to figure out?

I tried the following, but the problem is that intent isn't always null when started by service.

public int onStartCommand(Intent intent, int flags, int startId) {

    Log.i(Constants.TAG + this.getClass().getSimpleName(), "Inside onStartCommand");

    if (null == intent) {

        Log.w(Constants.TAG, "Service was stopped and automatically restarted by the system.");
        BackgroundTaskHandler.startLocationMonitorServiceBySelf(this, 20 * 1000); // start after 20 sec
        Log.w(Constants.TAG, "Stopped self. Restarting again via alarm.");
        stopSelf();

    } else {
        // Other piece of code to setup location client
        // and configure notification intent
    }

    return START_STICKY;
}

Body:
Instead of checking if the intent is null, you can be more specific and check if the intent contains an extra set by your activity.

In your activity:

Intent intent = new Intent(mContext, YourService.class);
intent.putExtra("IntentFlag", "MainActivity");

In your service:

if (intent.getStringExtra("IntentFlag").equals("MainActivity"))
{
    //Service started by activity
}

Hope this helps!


问:
Incompatible pointer types (double pointers)
In a function that asks a double pointer like this one:

```<code>#include <stdlib.h>

void    prueba(void **ap)
{
    *ap = NULL;
}
</code>```

compiled with the following main:

```<code>#include <stdlib.h>
#include <stdio.h>

void    prueba(void **ap);

int        main(void)
{
    char *str;

    str = (char *)malloc(sizeof(char) * 5);
    prueba(&str);
    if (str == NULL)
        printf("NULL");
    return (0);
}
</code>```

I get this warning with gcc:

```<code>main2.c:11:9: warning: incompatible pointer types passing 'char **' to parameter of type 'void **' [-Wincompatible-pointer-types]
        prueba(&str);
               ^~~~
main2.c:4:23: note: passing argument to parameter 'ap' here
void    prueba(void **ap);
</code>```

But if i do the same but with simple pointers, that is give a pointer to char to a function who asks for a void pointer, gcc compiles without warnings, for example, the following compiles right:
function:

```<code>#include <stdlib.h>

void    prueba(void *ap)
{
    ap = NULL;
}
</code>```

main:

```<code>#include <stdlib.h>
#include <stdio.h>

void    prueba(void *ap);

int        main(void)
{
    char *str;

    str = (char *)malloc(sizeof(char) * 5);
    prueba(str);
    if (str == NULL)
        printf("NULL");
    return (0);
}
</code>```

So my question is, why it works with simple pointers but it does not work with double pointers (or greater i guess)?

答:
According to the C Standard (6.3.2.3 Pointers)

1 A pointer to void may be converted to or from a pointer to any
  object type. A pointer to any object type may be converted to a
  pointer to void and back again; the result shall compare equal to the
  original pointer.

So in the second code snippet a pointer of the type char * is implicitly converted to the type void * though the function does not make sense because it deals with a copy of its argument and therefore does not changes the original pointer.

However the type void ** is not the same as the type void *. So the quote is not applicable for the type void ** and the compiler issues a diagnostic message because there is no implicit conversion from a pointer to any object type to a pointer of the type void **.

Body:
In a function that asks a double pointer like this one:

#include <stdlib.h>

void    prueba(void **ap)
{
    *ap = NULL;
}

compiled with the following main:

#include <stdlib.h>
#include <stdio.h>

void    prueba(void **ap);

int        main(void)
{
    char *str;

    str = (char *)malloc(sizeof(char) * 5);
    prueba(&str);
    if (str == NULL)
        printf("NULL");
    return (0);
}

I get this warning with gcc:

main2.c:11:9: warning: incompatible pointer types passing 'char **' to parameter of type 'void **' [-Wincompatible-pointer-types]
        prueba(&str);
               ^~~~
main2.c:4:23: note: passing argument to parameter 'ap' here
void    prueba(void **ap);

But if i do the same but with simple pointers, that is give a pointer to char to a function who asks for a void pointer, gcc compiles without warnings, for example, the following compiles right:
function:

#include <stdlib.h>

void    prueba(void *ap)
{
    ap = NULL;
}

main:

#include <stdlib.h>
#include <stdio.h>

void    prueba(void *ap);

int        main(void)
{
    char *str;

    str = (char *)malloc(sizeof(char) * 5);
    prueba(str);
    if (str == NULL)
        printf("NULL");
    return (0);
}

So my question is, why it works with simple pointers but it does not work with double pointers (or greater i guess)?


问:
split a word from string and save it in a variable
I've a question.
I have a string, like this:
hello, I am a string, -how are you?-.

And I want to put any text in - - sign in another variable and remove it from original string (in short: cut it!).

How can I do it? I should do it with preg_match or preg_split?

If you help me, I will grateful to you!

答:
I believe this is what you are looking for is along the lines of:

```<code>preg_match("/\-[\d,\w,\s]+-/gi",'blah blah -hello world-',$myvar)
</code>```

Now you can use $myvar. It'll return an array of results, so in this case you could use $myvar[0] and it'll return the first one -hello world-

ContentLicense: CC BY-SA 2.5

Body:
I believe this is what you are looking for is along the lines of:

preg_match("/\-[\d,\w,\s]+-/gi",'blah blah -hello world-',$myvar)

Now you can use $myvar. It'll return an array of results, so in this case you could use $myvar[0] and it'll return the first one -hello world-


问:
Flutter: Get the local position from the GestureDetector
I'm using the GestureDetector to get this events using:

```<code>onHorizontalDragStart: _onDragStart,
onHorizontalDragUpdate: _onDragUpdate,
</code>```

But how can I transform the global position into local? The child that is moved is a Container.

答:
You can use a RenderObject and then transform the global positions into a local one similar to this simple example:

```<code>import "package:flutter/material.dart";

class Test extends StatefulWidget {
  @override
  _TestState createState() => new _TestState();
}

class _TestState extends State<Test> {
  _onDragStart(BuildContext context, DragStartDetails start) {
    print(start.globalPosition.toString());
    RenderBox getBox = context.findRenderObject();
    var local = getBox.globalToLocal(start.globalPosition);
    print(local.dx.toString() + "|" + local.dy.toString());
  }

  _onDragUpdate(BuildContext context, DragUpdateDetails update) {
    //print(update.globalPosition.toString());
    RenderBox getBox = context.findRenderObject();
    var local = getBox.globalToLocal(update.globalPosition);
    //print(local.dx.toString() + "|" + local.dy.toString());
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new GestureDetector(
          child: new Text("Drag"),
          onHorizontalDragStart: (DragStartDetails start) =>
              _onDragStart(context, start),
          onHorizontalDragUpdate: (DragUpdateDetails update) =>
              _onDragUpdate(context, update),
        ),
      ),
    );
  }
}
</code>```

Body:
I'm using the GestureDetector to get this events using:

onHorizontalDragStart: _onDragStart,
onHorizontalDragUpdate: _onDragUpdate,

But how can I transform the global position into local? The child that is moved is a Container.

Body:
You can use a RenderObject and then transform the global positions into a local one similar to this simple example:

import "package:flutter/material.dart";

class Test extends StatefulWidget {
  @override
  _TestState createState() => new _TestState();
}

class _TestState extends State<Test> {
  _onDragStart(BuildContext context, DragStartDetails start) {
    print(start.globalPosition.toString());
    RenderBox getBox = context.findRenderObject();
    var local = getBox.globalToLocal(start.globalPosition);
    print(local.dx.toString() + "|" + local.dy.toString());
  }

  _onDragUpdate(BuildContext context, DragUpdateDetails update) {
    //print(update.globalPosition.toString());
    RenderBox getBox = context.findRenderObject();
    var local = getBox.globalToLocal(update.globalPosition);
    //print(local.dx.toString() + "|" + local.dy.toString());
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new GestureDetector(
          child: new Text("Drag"),
          onHorizontalDragStart: (DragStartDetails start) =>
              _onDragStart(context, start),
          onHorizontalDragUpdate: (DragUpdateDetails update) =>
              _onDragUpdate(context, update),
        ),
      ),
    );
  }
}


问:
Importing a single rxjs operator not working with react and webpack
I am using redux-observable for react app and webpack for bundling.

When I include a specific operator from rxjs like

```<code>import 'rxjs/add/operator/mapTo';
</code>```

it doesn't work and throws error

```<code>TypeError: action$.ofType(...).mapTo is not a function.
</code>```

But when I include complete rxjs library, it works

```<code>import 'rxjs';
</code>```

When importing specific operator, my js bundle does contain mapTo code but the methods are not getting included in Observable prototype.  I am using webpack for bundling. Do we have to do anything special for importing specific operator in webpack?

Code:

```<code>import { combineEpics } from 'redux-observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/mapTo';

const PING = 'PING';
const PONG = 'PONG';

const pingEpic = action$ => {
  const obser = action$.ofType(PING);
  return obser.mapTo({ type: PONG });
}

export const epic$ = new BehaviorSubject(combineEpics(pingEpic));
export const createRootEpic = (action$, store) =>
epic$.mergeMap(epic =>
  epic(action$, store)
);
</code>```

Update:

mapTo method is available to BehaviorSubject object (epic$.mapTo is available) but not to ActionsObservable object (action$.mapTo is not a function).

答:
The issue is highly likely to be that you accidentally have two copies of RxJS. This can happen in several situations, but in your specific case it sounds highly likely to a recently reported issue in rxjs. That particular issue was fixed started in 5.5.1 (5.5.2 is now the latest).

Make sure you have RxJS 5.5.1 or above installed--you may need to remove your node_modules and reinstall to get a newer version locally if your semver range is broad. You can also triple check by looking at node_modules/rxjs/package.json the "version" field, usually at the bottom

Body:
I am using redux-observable for react app and webpack for bundling.

When I include a specific operator from rxjs like

import 'rxjs/add/operator/mapTo';

it doesn't work and throws error

TypeError: action$.ofType(...).mapTo is not a function.

But when I include complete rxjs library, it works

import 'rxjs';

When importing specific operator, my js bundle does contain mapTo code but the methods are not getting included in Observable prototype.  I am using webpack for bundling. Do we have to do anything special for importing specific operator in webpack?

Code:

import { combineEpics } from 'redux-observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/mapTo';

const PING = 'PING';
const PONG = 'PONG';

const pingEpic = action$ => {
  const obser = action$.ofType(PING);
  return obser.mapTo({ type: PONG });
}

export const epic$ = new BehaviorSubject(combineEpics(pingEpic));
export const createRootEpic = (action$, store) =>
epic$.mergeMap(epic =>
  epic(action$, store)
);

Update:

mapTo method is available to BehaviorSubject object (epic$.mapTo is available) but not to ActionsObservable object (action$.mapTo is not a function).


问:
MariaDB - my.cnf isn't in my server CentOs
I have been working with MariaDB and i don't know why there is no my.cnf. But the crazy thing is that:

Where it is suposed that the file should be, there is only the my.cnf.d, but the .cnf isn't.

If i write a new file called my.cnf and i copy from another server, it works.

I want to know why happen this?

PD: This is my instalation via yum:

```<code>sudo yum install MariaDB-server MariaDB-client
sudo systemctl start mariadb
mysql_secure_installation
</code>```

答:
Depending on the specific version there may be no my.cnf file. See MariaDB KB

MariaDB will use compiled defaults if there is no my.cnf to override them. You can use my.cnf.d as a starting point for that.

Body:
I have been working with MariaDB and i don't know why there is no my.cnf. But the crazy thing is that:

Where it is suposed that the file should be, there is only the my.cnf.d, but the .cnf isn't.

If i write a new file called my.cnf and i copy from another server, it works.

I want to know why happen this?

PD: This is my instalation via yum:

sudo yum install MariaDB-server MariaDB-client
sudo systemctl start mariadb
mysql_secure_installation


问:
Change Color of Controls FX PopOver Title
Would like to change the color of a controls FX PopOver title which is set to always be on. I would like to do this in CSS, where I have already changed the background color. I have tried a couple of different options under .popover.

This is an example with the CSS of the last thing I tried:

```<code>public class HelloPopOver extends Application {

    @Override
    public void start(Stage primaryStage) {

        //Build PopOver look and feel
        Label lblName = new Label("John Doe");
        Label lblStreet = new Label("123 Hello Street");
        Label lblCityStateZip = new Label("MadeUpCity, XX 55555");
        VBox vBox = new VBox(lblName, lblStreet, lblCityStateZip);
        //Create PopOver and add look and feel
        PopOver popOver = new PopOver(vBox);

        // I always want to see my header
        popOver.setHeaderAlwaysVisible(true);

        Label label = new Label("Mouse mouse over me");
        label.setOnMouseEntered(mouseEvent -> {
            popOver.show(label);
            ((Parent)popOver.getSkin().getNode()).getStylesheets().add(getClass().getResource("Style.css").toExternalForm());
        });

        StackPane root = new StackPane();
        root.getChildren().add(label);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
   }
}
</code>```

And the CSS:

```<code>.popover > .border {
    -fx-stroke-width: 0.5;
    -fx-fill: rgba(200,200,200, 1);
    -fx-text-fill: red; /* This doesn't work, but is what I am looking for */
}
.popover > .label {
    -fx-text-fill: red; /* This doesn't work, but is what I am looking for */
 }
</code>```

How can CSS change the title color to red?

答:
Here is a very rough example of how you can create your own header. I personally would use an AwesomeFontFx icon in place of the button. I would also center the header and add spacing. I used Text as the header. Text allows you to change its color.

```<code>import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Control;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import org.controlsfx.control.PopOver;

public class HelloPopOver extends Application {

    @Override
    public void start(Stage primaryStage) {

        //Build PopOver look and feel

        Label lblClosePopOver = new Label("x");
        Text lblHeader = new Text("Keyword info");
        lblHeader.setFill(Color.RED);
        HBox headerRoot = new HBox(lblClosePopOver, lblHeader);
        headerRoot.setMaxSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE);
        Label lblName = new Label("John Doe");
        Label lblStreet = new Label("123 Hello Street");
        Label lblCityStateZip = new Label("MadeUpCity, XX 55555");

        VBox infoHolder = new VBox(lblName, lblStreet, lblCityStateZip);
        VBox.setMargin(infoHolder, new Insets(7, 7, 7, 7));
        VBox subRoot = new VBox(new StackPane(headerRoot), infoHolder);
        AnchorPane popOverRoot = new AnchorPane(subRoot);

        //Create PopOver and add look and feel
         Label label = new Label("Mouse mouse over me");
        PopOver popOver = new PopOver(label);
        popOver.setContentNode(popOverRoot);
        lblClosePopOver.setOnMouseClicked((event)->{
            if(popOver.isShowing())
            {
                popOver.hide();
            }
        });
    // I always want to see my header
    //popOver.setHeaderAlwaysVisible(true);

        label.setOnMouseEntered(mouseEvent -> {
            popOver.show(label);
        });

    StackPane root = new StackPane();
    root.getChildren().add(label);

    Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
   }
}
</code>```

Body:
Would like to change the color of a controls FX PopOver title which is set to always be on. I would like to do this in CSS, where I have already changed the background color. I have tried a couple of different options under .popover.

This is an example with the CSS of the last thing I tried:

public class HelloPopOver extends Application {

    @Override
    public void start(Stage primaryStage) {

        //Build PopOver look and feel
        Label lblName = new Label("John Doe");
        Label lblStreet = new Label("123 Hello Street");
        Label lblCityStateZip = new Label("MadeUpCity, XX 55555");
        VBox vBox = new VBox(lblName, lblStreet, lblCityStateZip);
        //Create PopOver and add look and feel
        PopOver popOver = new PopOver(vBox);

        // I always want to see my header
        popOver.setHeaderAlwaysVisible(true);

        Label label = new Label("Mouse mouse over me");
        label.setOnMouseEntered(mouseEvent -> {
            popOver.show(label);
            ((Parent)popOver.getSkin().getNode()).getStylesheets().add(getClass().getResource("Style.css").toExternalForm());
        });

        StackPane root = new StackPane();
        root.getChildren().add(label);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
   }
}

And the CSS:

.popover > .border {
    -fx-stroke-width: 0.5;
    -fx-fill: rgba(200,200,200, 1);
    -fx-text-fill: red; /* This doesn't work, but is what I am looking for */
}
.popover > .label {
    -fx-text-fill: red; /* This doesn't work, but is what I am looking for */
 }

How can CSS change the title color to red?

Body:
Here is a very rough example of how you can create your own header. I personally would use an AwesomeFontFx icon in place of the button. I would also center the header and add spacing. I used Text as the header. Text allows you to change its color.

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Control;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import org.controlsfx.control.PopOver;

public class HelloPopOver extends Application {

    @Override
    public void start(Stage primaryStage) {

        //Build PopOver look and feel

        Label lblClosePopOver = new Label("x");
        Text lblHeader = new Text("Keyword info");
        lblHeader.setFill(Color.RED);
        HBox headerRoot = new HBox(lblClosePopOver, lblHeader);
        headerRoot.setMaxSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE);
        Label lblName = new Label("John Doe");
        Label lblStreet = new Label("123 Hello Street");
        Label lblCityStateZip = new Label("MadeUpCity, XX 55555");

        VBox infoHolder = new VBox(lblName, lblStreet, lblCityStateZip);
        VBox.setMargin(infoHolder, new Insets(7, 7, 7, 7));
        VBox subRoot = new VBox(new StackPane(headerRoot), infoHolder);
        AnchorPane popOverRoot = new AnchorPane(subRoot);

        //Create PopOver and add look and feel
         Label label = new Label("Mouse mouse over me");
        PopOver popOver = new PopOver(label);
        popOver.setContentNode(popOverRoot);
        lblClosePopOver.setOnMouseClicked((event)->{
            if(popOver.isShowing())
            {
                popOver.hide();
            }
        });
    // I always want to see my header
    //popOver.setHeaderAlwaysVisible(true);

        label.setOnMouseEntered(mouseEvent -> {
            popOver.show(label);
        });

    StackPane root = new StackPane();
    root.getChildren().add(label);

    Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
   }
}


问:
Update value in Kivy (Python) widget
I'd like to display numeric values coming from a sensor (Tinkerforge ambient light sensor) in Kivy widgets. Unfortunately the variable 'illuminance' doesn't seem to change at all and the widgets display '0'.'illuminance' seems to update nicely and gets printed on the console. What am I doing wrong?

```<code>import kivy
import random
from kivy.clock import Clock
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout

from tinkerforge.ip_connection import IPConnection
from tinkerforge.brick_dc import BrickDC
from tinkerforge.bricklet_ambient_light import BrickletAmbientLight

HOST = "localhost"          # Tinkerforge IP and port
PORT = 4223
UID = "uM9"             # sensor ID

illuminance = 0

ipcon = IPConnection()          # Create IP connection
al = BrickletAmbientLight(UID, ipcon)   # Create device object
ipcon.connect(HOST, PORT)       # Connect to brickd

class TimerTink:
    def tinker(self):
        illuminance = al.get_illuminance()  #read sensor value
        print(illuminance)

class TinkerApp(App):
    def build(self):
        main_layout = BoxLayout(padding=10, orientation="vertical")
        for i in range(2):
            h_layout = BoxLayout(padding=10)
            for i in range(2):
                lbl = Label(text=str(illuminance),)
                h_layout.add_widget(lbl)
            main_layout.add_widget(h_layout)
        event = Clock.schedule_interval(TimerTink.tinker, 1/2)
        return main_layout

if __name__ == "__main__":
    app = TinkerApp()
    app.run()
</code>```

Finally it's working, thanks to @YOSHI 's suggestions:

```<code>import kivy
import random
from kivy.clock import Clock
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout

from tinkerforge.ip_connection import IPConnection
from tinkerforge.brick_dc import BrickDC
from tinkerforge.bricklet_ambient_light import BrickletAmbientLight

HOST = "localhost"          # Tinkerforge IP and port
PORT = 4223
UID = "uM9"             # sensor ID

illuminance = 0

ipcon = IPConnection()          # Create IP connection
al = BrickletAmbientLight(UID, ipcon)   # Create device object
ipcon.connect(HOST, PORT)       # Connect to brickd

class TinkerApp(App):

    def build(self):
        i = 0
        main_layout = BoxLayout(padding=10, orientation="vertical")
        h_layout = FloatLayout(size=(300,300))
        self.label = Label(text=str(illuminance),pos=(i*100, i*100),size_hint = (.1,.1))
        h_layout.add_widget(self.label)
        main_layout.add_widget(h_layout)
        Clock.schedule_interval(self.timer, 0.1)

        return main_layout

    def timer(self, dt):
        illuminance = al.get_illuminance()  #read sensor value
        self.label.text = str(illuminance)
        print(str(illuminance))

if __name__ == "__main__":
    app = TinkerApp()
    app.run()
</code>```

答:
The function 'tinker' in the TimeTink class takes 2 arguments: self and dt

```<code>def tinker(self,dt):
    illuminance = al.get_illuminance()  #read sensor value
    print(illuminance)
</code>```

or you change the line where you call the method to sth. like this:

```<code>event = Clock.schedule_interval(lambda dt: TimerTink.tinker, 1/2)
</code>```

for more info visit the doc for kivy.clock.

Edit: (maybe this works)

```<code>import kivy
import random
from kivy.clock import Clock
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout

from tinkerforge.ip_connection import IPConnection
from tinkerforge.brick_dc import BrickDC
from tinkerforge.bricklet_ambient_light import BrickletAmbientLight

HOST = "localhost"          # Tinkerforge IP and port
PORT = 4223
UID = "uM9"             # sensor ID

illuminance = 0

ipcon = IPConnection()          # Create IP connection
al = BrickletAmbientLight(UID, ipcon)   # Create device object
ipcon.connect(HOST, PORT)       # Connect to brickd

main_layout = BoxLayout(padding=10, orientation="vertical")
for i in range(2):
    h_layout = BoxLayout(padding=10)
    for i in range(2):
        lbl = Label(text=str(illuminance),)
        h_layout.add_widget(lbl)
    main_layout.add_widget(h_layout)
def tinker(self):
    illuminance = al.get_illuminance()  #read sensor value
    lbl.text = str(illuminance)
    print(illuminance)

class TinkerApp(App):
    def build(self):
        event = Clock.schedule_interval(tinker, 1/2)
        return main_layout

if __name__ == "__main__":
    app = TinkerApp()
    app.run()
</code>```

Title: Update value in Kivy (Python) widget

Body:
I'd like to display numeric values coming from a sensor (Tinkerforge ambient light sensor) in Kivy widgets. Unfortunately the variable 'illuminance' doesn't seem to change at all and the widgets display '0'.'illuminance' seems to update nicely and gets printed on the console. What am I doing wrong?

import kivy
import random
from kivy.clock import Clock
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout

from tinkerforge.ip_connection import IPConnection
from tinkerforge.brick_dc import BrickDC
from tinkerforge.bricklet_ambient_light import BrickletAmbientLight

HOST = "localhost"          # Tinkerforge IP and port
PORT = 4223
UID = "uM9"             # sensor ID

illuminance = 0

ipcon = IPConnection()          # Create IP connection
al = BrickletAmbientLight(UID, ipcon)   # Create device object
ipcon.connect(HOST, PORT)       # Connect to brickd

class TimerTink:
    def tinker(self):
        illuminance = al.get_illuminance()  #read sensor value
        print(illuminance)

class TinkerApp(App):
    def build(self):
        main_layout = BoxLayout(padding=10, orientation="vertical")
        for i in range(2):
            h_layout = BoxLayout(padding=10)
            for i in range(2):
                lbl = Label(text=str(illuminance),)
                h_layout.add_widget(lbl)
            main_layout.add_widget(h_layout)
        event = Clock.schedule_interval(TimerTink.tinker, 1/2)
        return main_layout

if __name__ == "__main__":
    app = TinkerApp()
    app.run()

Finally it's working, thanks to @YOSHI 's suggestions:

import kivy
import random
from kivy.clock import Clock
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout

from tinkerforge.ip_connection import IPConnection
from tinkerforge.brick_dc import BrickDC
from tinkerforge.bricklet_ambient_light import BrickletAmbientLight

HOST = "localhost"          # Tinkerforge IP and port
PORT = 4223
UID = "uM9"             # sensor ID

illuminance = 0

ipcon = IPConnection()          # Create IP connection
al = BrickletAmbientLight(UID, ipcon)   # Create device object
ipcon.connect(HOST, PORT)       # Connect to brickd

class TinkerApp(App):

    def build(self):
        i = 0
        main_layout = BoxLayout(padding=10, orientation="vertical")
        h_layout = FloatLayout(size=(300,300))
        self.label = Label(text=str(illuminance),pos=(i*100, i*100),size_hint = (.1,.1))
        h_layout.add_widget(self.label)
        main_layout.add_widget(h_layout)
        Clock.schedule_interval(self.timer, 0.1)

        return main_layout

    def timer(self, dt):
        illuminance = al.get_illuminance()  #read sensor value
        self.label.text = str(illuminance)
        print(str(illuminance))

if __name__ == "__main__":
    app = TinkerApp()
    app.run()

Body:
The function 'tinker' in the TimeTink class takes 2 arguments: self and dt

def tinker(self,dt):
    illuminance = al.get_illuminance()  #read sensor value
    print(illuminance)

or you change the line where you call the method to sth. like this:

event = Clock.schedule_interval(lambda dt: TimerTink.tinker, 1/2)

for more info visit the doc for kivy.clock.

Edit: (maybe this works)

import kivy
import random
from kivy.clock import Clock
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout

from tinkerforge.ip_connection import IPConnection
from tinkerforge.brick_dc import BrickDC
from tinkerforge.bricklet_ambient_light import BrickletAmbientLight

HOST = "localhost"          # Tinkerforge IP and port
PORT = 4223
UID = "uM9"             # sensor ID

illuminance = 0

ipcon = IPConnection()          # Create IP connection
al = BrickletAmbientLight(UID, ipcon)   # Create device object
ipcon.connect(HOST, PORT)       # Connect to brickd

main_layout = BoxLayout(padding=10, orientation="vertical")
for i in range(2):
    h_layout = BoxLayout(padding=10)
    for i in range(2):
        lbl = Label(text=str(illuminance),)
        h_layout.add_widget(lbl)
    main_layout.add_widget(h_layout)
def tinker(self):
    illuminance = al.get_illuminance()  #read sensor value
    lbl.text = str(illuminance)
    print(illuminance)

class TinkerApp(App):
    def build(self):
        event = Clock.schedule_interval(tinker, 1/2)
        return main_layout

if __name__ == "__main__":
    app = TinkerApp()
    app.run()


问:
Hibernate query to get server time without converting to local timezone
I've searched high and low for an answer to this and I've found nothing. Note (before someone refers me to a similar, but unhelpful question) that I'm NOT STORING ANY DATES/TIMES IN THE DATABASE.

Background

I have a Postgres database that's running on a server somewhere. I have a Java back end that queries the database using Hibernate. The database server and the Java back end (Tomcat server) are running on separate systems, and can be in different timezones.

The server needs to perform some cleanup tasks at a specific time (which can be configured by the user) - for example, delete entries older than x days every day at noon. I'm trying to run a query on the server to get the current server time. The problem is that either hibernate or the JVM is converting the time from the time on the database server to the local time on the server running Tomcat.

Example

I have a database server (Postgres) on a server using Central Time (UTC-6). I have my back end server (Java/Tomcat) using GMT (UTC+0). I have a query that I can run to get the current time (SELECT now()). Let's say that the current time on the database server is 12:00:00. If I run the query from the back end server on the database server using pgAdmin, it returns the correct time (12:00:00). If I run the same query using Hibernate, it converts it to GMT (18:00:00).

Question

Is there a query that I can run from the back end server (Java/Tomcat) that will get the current time from the database server without converting it? Alternatively, is there something that I can do to the time that's returned so that I can convert it back to the time on the database server?

答:
Time on Tomcat server is 18:00 then below sql would return 12:00...</p>

```<code>select current_timestamp - (interval '6' hour)
</code>```

Body:
Time on Tomcat server is 18:00 then below sql would return 12:00...

select current_timestamp - (interval '6' hour)


问:
Search the RadListBox using JQuery
I am trying to search the RadListBox containing more than 150 items. I am populating the RadListBox with an ICollection.  I have a RadListBox and a textbox. I have a KeyUp() event on the textbox which fires the below code upon entering the search criteria and I should be able to see all the items in the RadListBox matching the search criteria.
Below coe works fine if the number of items in the RadListBox is small (< 50).  Performance is bad as the no. items i nthe RadListBox grows (>100)

Is there anyway I could optimize the search criteria? Also, currentlly, the matched items are selected in the RadListbOX, But I want the only the matched items to show up in the RadListBox and the rest of the items to be hidden. is it possible using the JQuery? Please advise. I appreciate any sample codeing on this. Thanks!

```<code> $(document).ready(function () {
            $('#ctl00_ContentMain_txtLearnersNotInGrp_text').keyup(function () {
                var item;
                var search;
                var availableUserList
                availableUserList = $find("<%= AvailableUsers.ClientID %>"); //Get RadList

                search = $(this).val(); //get textBox value

                                if (search.length > 3) {
                                    for (var i = 0; i < availableUserList ._children.get_count(); i++) {
                                        if (availableUserList .getItem(i).get_text().toLowerCase().match(search.toLowerCase())) {
                                            availableUserList .getItem(i).select();

                                        }
                                        else {
                                            availableUserList .getItem(i).unselect();
                                        }
                                    }
                                }
                                else {
                                    availableUserList .clearSelection();
                                    availableUserList .selectedIndex = -1;
                                }
            });
        });
</code>```

答:
Check this link out. RadListBox sorting. If that link is unavailable. This is the code.

I am directly quoting the developer who wrote the following code

Up and Down Arrow Usage: If the user uses the up and down arrows to go
  through a filtered list, it may appear to not work because the up and
  down arrow will potentially be "stopping" on hidden items.

Clearing the Filter after a Transfer: I opted to clear the filtered
  list and the filter after a transfer is made.  Otherwise, if the user
  transfers the item back while your listbox is filtered, you'll need to
  re-filter.  Also, that item may not match the filter criteria and seem
  to disappear to the user.

```<code>body
{
    font-family: Trebuchet MS, Sans-Serif;
}

.listBoxHeaders
{
    color:Green;
    font-weight:bold;
}

.RadListBox span.rlbText em
{
    background-color: #E5E5E5;
    font-weight: bold;
    font-style: normal;
}

.rbClear
{
    background-image: url(images/clear.png);
    background-position: center;
    background-repeat: no-repeat;
}

ASP.NET Markup:
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
<Scripts>
    <%--Needed for JavaScript IntelliSense in VS2010--%>
    <%--For VS2008 replace RadScriptManager with ScriptManager--%>
    <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
    <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
    <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
</Scripts>
</telerik:RadScriptManager>
<telerik:RadCodeBlock runat="server" >
<script type="text/javascript">

    function filterList()
    {
        var listbox = $find("<%= rlbAvailable.ClientID %>");
        var textbox = $find('<%= tbAvailableFilter.ClientID %>');

        clearListEmphasis(listbox);
        createMatchingList(listbox, textbox.get_textBoxValue());
    }

    // Remove emphasis from matching text in ListBox
    function clearListEmphasis(listbox)
    {
        var re = new RegExp("</{0,1}em>", "gi");
        var items = listbox.get_items();
        var itemText;

        items.forEach
        (
            function (item)
            {
                itemText = item.get_text();
                item.set_text(itemText.replace(re, ""));
            }
        )
    }

    // Emphasize matching text in ListBox and hide non-matching items
    function createMatchingList(listbox, filterText)
    {
        if (filterText != "")
        {
            filterText = escapeRegExCharacters(filterText);

            var items = listbox.get_items();
            var re = new RegExp(filterText, "i");

            items.forEach
            (
                function (item)
                {
                    var itemText = item.get_text();

                    if (itemText.match(re))
                    {
                        item.set_text(itemText.replace(re, "<em>" + itemText.match(re) + "</em>"));
                        item.set_visible(true);
                    }
                    else
                    {
                        item.set_visible(false);
                    }
                }
            )
        }
        else
        {
            var items = listbox.get_items();

            items.forEach
            (
                function (item)
                {
                    item.set_visible(true);
                }
            )
        }
    }

    function rlbAvailable_OnClientTransferring(sender, eventArgs)
    {
        // Transferred items retain the emphasized text, so it needs to be cleared.
        clearListEmphasis(sender);
        // Clear the list. Optional, but prevents follow up situation.
        clearFilterText();
        createMatchingList(sender, "");
    }

    function rbtnClear_OnClientClicking(sender, eventArgs)
    {
        clearFilterText();

        var listbox = $find("<%= rlbAvailable.ClientID %>");

        clearListEmphasis(listbox);
        createMatchingList(listbox, "");
    }

    // Clears the text from the filter.
    function clearFilterText()
    {
        var textbox = $find('<%= tbAvailableFilter.ClientID %>');
        textbox.clear();
    }

    // Escapes RegEx character classes and shorthand characters
    function escapeRegExCharacters(text)
    {
        return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    }

</script>
</telerik:RadCodeBlock>
<div style="margin-bottom: 10px;">
<telerik:RadButton ID="btnSave" runat="server"
    Text="Save"
    onclick="btnSave_Click">
    <Icon PrimaryIconCssClass="rbSave" />
</telerik:RadButton>
</div>
<div class="listBoxHeaders">
    <span style="margin-left:50px;">
        Available States
    </span>
    <span style="margin-left:136px;">
        Chosen States
    </span>
</div>
<div>
    <table style="position:relative;left:-3px;margin-bottom:2px;">
        <tr>
            <td>
                <telerik:RadTextBox ID="tbAvailableFilter" runat="server"
                    Width="187px"
                    EmptyMessage="Search States..."
                    autocomplete="off"
                    onkeyup="filterList();" />
            </td>
            <td>
                <telerik:RadButton ID="rbtnClear" runat="server"
                    Width="22px"
                    AutoPostBack="false"
                    OnClientClicking="rbtnClear_OnClientClicking">
                    <Icon PrimaryIconCssClass="rbClear" />
                </telerik:RadButton>
            </td>
        </tr>
    </table>
</div>
<telerik:RadListBox ID="rlbAvailable" runat="server"
    Height="250px"
    Width="250px"
    AllowTransfer="true"
    AllowTransferOnDoubleClick="true"
    TransferToID="rlbChosen"
    EnableDragAndDrop="true"
    OnClientTransferring="rlbAvailable_OnClientTransferring"
    ButtonSettings-ShowTransferAll="false"/>
<telerik:RadListBox ID="rlbChosen" runat="server"
    Height="250px"
    Width="250px"
    EnableDragAndDrop="true"
    AllowReorder="true"/>
<br /><br />
<strong>States I've Lived In:</strong>
<asp:Repeater ID="rptStates" runat="server">
    <ItemTemplate>
        <div><%# Eval("Text") %></div>
    </ItemTemplate>
</asp:Repeater>

C#
using System;

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            rlbAvailable.LoadContentFile("states.xml");
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        rptStates.DataSource = rlbChosen.Items;
        rptStates.DataBind();
    }

}
</code>```

Title: Search the RadListBox using JQuery

Body:
I am trying to search the RadListBox containing more than 150 items. I am populating the RadListBox with an ICollection.  I have a RadListBox and a textbox. I have a KeyUp() event on the textbox which fires the below code upon entering the search criteria and I should be able to see all the items in the RadListBox matching the search criteria.
Below coe works fine if the number of items in the RadListBox is small (< 50).  Performance is bad as the no. items i nthe RadListBox grows (>100)

Is there anyway I could optimize the search criteria? Also, currentlly, the matched items are selected in the RadListbOX, But I want the only the matched items to show up in the RadListBox and the rest of the items to be hidden. is it possible using the JQuery? Please advise. I appreciate any sample codeing on this. Thanks!

 $(document).ready(function () {
            $('#ctl00_ContentMain_txtLearnersNotInGrp_text').keyup(function () {
                var item;
                var search;
                var availableUserList
                availableUserList = $find("<%= AvailableUsers.ClientID %>"); //Get RadList

                search = $(this).val(); //get textBox value

                                if (search.length > 3) {
                                    for (var i = 0; i < availableUserList ._children.get_count(); i++) {
                                        if (availableUserList .getItem(i).get_text().toLowerCase().match(search.toLowerCase())) {
                                            availableUserList .getItem(i).select();

                                        }
                                        else {
                                            availableUserList .getItem(i).unselect();
                                        }
                                    }
                                }
                                else {
                                    availableUserList .clearSelection();
                                    availableUserList .selectedIndex = -1;
                                }
            });
        });

Body:
Check this link out. RadListBox sorting. If that link is unavailable. This is the code.

I am directly quoting the developer who wrote the following code

Up and Down Arrow Usage: If the user uses the up and down arrows to go
  through a filtered list, it may appear to not work because the up and
  down arrow will potentially be "stopping" on hidden items.

Clearing the Filter after a Transfer: I opted to clear the filtered
  list and the filter after a transfer is made.  Otherwise, if the user
  transfers the item back while your listbox is filtered, you'll need to
  re-filter.  Also, that item may not match the filter criteria and seem
  to disappear to the user.

body
{
    font-family: Trebuchet MS, Sans-Serif;
}

.listBoxHeaders
{
    color:Green;
    font-weight:bold;
}

.RadListBox span.rlbText em
{
    background-color: #E5E5E5;
    font-weight: bold;
    font-style: normal;
}

.rbClear
{
    background-image: url(images/clear.png);
    background-position: center;
    background-repeat: no-repeat;
}

ASP.NET Markup:
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
<Scripts>
    <%--Needed for JavaScript IntelliSense in VS2010--%>
    <%--For VS2008 replace RadScriptManager with ScriptManager--%>
    <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
    <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
    <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
</Scripts>
</telerik:RadScriptManager>
<telerik:RadCodeBlock runat="server" >
<script type="text/javascript">

    function filterList()
    {
        var listbox = $find("<%= rlbAvailable.ClientID %>");
        var textbox = $find('<%= tbAvailableFilter.ClientID %>');

        clearListEmphasis(listbox);
        createMatchingList(listbox, textbox.get_textBoxValue());
    }

    // Remove emphasis from matching text in ListBox
    function clearListEmphasis(listbox)
    {
        var re = new RegExp("</{0,1}em>", "gi");
        var items = listbox.get_items();
        var itemText;

        items.forEach
        (
            function (item)
            {
                itemText = item.get_text();
                item.set_text(itemText.replace(re, ""));
            }
        )
    }

    // Emphasize matching text in ListBox and hide non-matching items
    function createMatchingList(listbox, filterText)
    {
        if (filterText != "")
        {
            filterText = escapeRegExCharacters(filterText);

            var items = listbox.get_items();
            var re = new RegExp(filterText, "i");

            items.forEach
            (
                function (item)
                {
                    var itemText = item.get_text();

                    if (itemText.match(re))
                    {
                        item.set_text(itemText.replace(re, "<em>" + itemText.match(re) + "</em>"));
                        item.set_visible(true);
                    }
                    else
                    {
                        item.set_visible(false);
                    }
                }
            )
        }
        else
        {
            var items = listbox.get_items();

            items.forEach
            (
                function (item)
                {
                    item.set_visible(true);
                }
            )
        }
    }

    function rlbAvailable_OnClientTransferring(sender, eventArgs)
    {
        // Transferred items retain the emphasized text, so it needs to be cleared.
        clearListEmphasis(sender);
        // Clear the list. Optional, but prevents follow up situation.
        clearFilterText();
        createMatchingList(sender, "");
    }

    function rbtnClear_OnClientClicking(sender, eventArgs)
    {
        clearFilterText();

        var listbox = $find("<%= rlbAvailable.ClientID %>");

        clearListEmphasis(listbox);
        createMatchingList(listbox, "");
    }

    // Clears the text from the filter.
    function clearFilterText()
    {
        var textbox = $find('<%= tbAvailableFilter.ClientID %>');
        textbox.clear();
    }

    // Escapes RegEx character classes and shorthand characters
    function escapeRegExCharacters(text)
    {
        return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    }

</script>
</telerik:RadCodeBlock>
<div style="margin-bottom: 10px;">
<telerik:RadButton ID="btnSave" runat="server"
    Text="Save"
    onclick="btnSave_Click">
    <Icon PrimaryIconCssClass="rbSave" />
</telerik:RadButton>
</div>
<div class="listBoxHeaders">
    <span style="margin-left:50px;">
        Available States
    </span>
    <span style="margin-left:136px;">
        Chosen States
    </span>
</div>
<div>
    <table style="position:relative;left:-3px;margin-bottom:2px;">
        <tr>
            <td>
                <telerik:RadTextBox ID="tbAvailableFilter" runat="server"
                    Width="187px"
                    EmptyMessage="Search States..."
                    autocomplete="off"
                    onkeyup="filterList();" />
            </td>
            <td>
                <telerik:RadButton ID="rbtnClear" runat="server"
                    Width="22px"
                    AutoPostBack="false"
                    OnClientClicking="rbtnClear_OnClientClicking">
                    <Icon PrimaryIconCssClass="rbClear" />
                </telerik:RadButton>
            </td>
        </tr>
    </table>
</div>
<telerik:RadListBox ID="rlbAvailable" runat="server"
    Height="250px"
    Width="250px"
    AllowTransfer="true"
    AllowTransferOnDoubleClick="true"
    TransferToID="rlbChosen"
    EnableDragAndDrop="true"
    OnClientTransferring="rlbAvailable_OnClientTransferring"
    ButtonSettings-ShowTransferAll="false"/>
<telerik:RadListBox ID="rlbChosen" runat="server"
    Height="250px"
    Width="250px"
    EnableDragAndDrop="true"
    AllowReorder="true"/>
<br /><br />
<strong>States I've Lived In:</strong>
<asp:Repeater ID="rptStates" runat="server">
    <ItemTemplate>
        <div><%# Eval("Text") %></div>
    </ItemTemplate>
</asp:Repeater>

C#
using System;

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            rlbAvailable.LoadContentFile("states.xml");
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        rptStates.DataSource = rlbChosen.Items;
        rptStates.DataBind();
    }

}


问:
SQL2008: MSOLAP & SSRS Class not registered error with certain dimension
Our product leverages Analysis Services combined with Reporting Services, we recently made some changed to add compatability for SQL2008. Everything works great except with certain dimensions, drillthroughs or measures added to a report we suddenly get this following error:

Server: The operation has been
  cancelled. Errors in the high-level
  relational engine. A connection could
  not be made to the data source with
  the DataSourceID of 'Adventure Works
  DW', Name of 'Adventure Works DW'. OLE
  DB error: OLE DB or ODBC error: Class
  not registered.

Any ideas?

答:
Found the issue.

SQL2008 doesn't come with the SQL Native Client provider which my cube was using to retreive data from the datawarehouse.

Solution:

Change the provider to SQL OLE DB Provider instead.

You can use XMLA if you so wish:

```<code><Object>
    <DatabaseID>Adventure Works DW</DatabaseID>
    <DataSourceID>Adventure Works DW</DataSourceID>
  </Object>
  <ObjectDefinition>
    <DataSource xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="RelationalDataSource">
      <ID>Adventure Works DW</ID>
      <Name>Adventure Works DW</Name>
      <ConnectionString>Provider=SQLOLEDB.1;Data Source=s;Persist Security Info=False;Integrated Security=SSPI;Initial Catalog=AdventureWorksDWDW</ConnectionString>
      <ImpersonationInfo>
        <ImpersonationMode>ImpersonateServiceAccount</ImpersonationMode>
      </ImpersonationInfo>
      <Timeout>PT0S</Timeout>
    </DataSource>
  </ObjectDefinition>
</Alter>
</code>```

OwnerDisplayName: Rob Stevenson-Leggett

LastEditorDisplayName: Fabian Steeg

Body:
Found the issue.

SQL2008 doesn't come with the SQL Native Client provider which my cube was using to retreive data from the datawarehouse.

Solution:

Change the provider to SQL OLE DB Provider instead.

You can use XMLA if you so wish:

<Object>
    <DatabaseID>Adventure Works DW</DatabaseID>
    <DataSourceID>Adventure Works DW</DataSourceID>
  </Object>
  <ObjectDefinition>
    <DataSource xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="RelationalDataSource">
      <ID>Adventure Works DW</ID>
      <Name>Adventure Works DW</Name>
      <ConnectionString>Provider=SQLOLEDB.1;Data Source=s;Persist Security Info=False;Integrated Security=SSPI;Initial Catalog=AdventureWorksDWDW</ConnectionString>
      <ImpersonationInfo>
        <ImpersonationMode>ImpersonateServiceAccount</ImpersonationMode>
      </ImpersonationInfo>
      <Timeout>PT0S</Timeout>
    </DataSource>
  </ObjectDefinition>
</Alter>


问:
Can I make a constructor that deserializes a string version of my object?
I'm serializing and deserializing an object (TComponent descendant) using the example in the ComponentToString section in the Delphi help file.  This is so I can store the object in a VARCHAR field in the database.

When I need to instantiate a new instance of my class from a string stored in the database, can I do that using a constructor of the form CreateFromString(AOwner: TComponent; AData: String)?  Or do I have to use a non-class method that returns an instance of my component class?

If I can use the constructor version, how to I "map" the return value of ReadComponent to the "self" that is being created by the constructor?

Here's the deserialization example from the help file:

```<code>function StringToComponentProc(Value: string): TComponent;
var
  StrStream:TStringStream;
  BinStream: TMemoryStream;
begin
  StrStream := TStringStream.Create(Value);
  try
    BinStream := TMemoryStream.Create;
    try
      ObjectTextToBinary(StrStream, BinStream);
      BinStream.Seek(0, soFromBeginning);
      Result:= BinStream.ReadComponent(nil);
    finally
      BinStream.Free;
    end;
  finally
    StrStream.Free;
  end;
end;
</code>```

答:
In general, yes, you can make a constructor deserialize a string and use that information to initialize the new instance. A trivial example of that would be a class with a single Integer field. Pass a string to the constructor and have the constructor call StrToInt and initialize the field with the result.

But if the only function you have for deserialization is one that also creates the instance, then you cannot use that from the constructor because then you'll end up with two instances when you only wanted one. There's no way for a constructor to say, "Never mind; don't construct an instance after all. I already got one somewhere else."

However, that's not the situation you're in. As you should know, TStream.ReadComponent allows you to create the instance yourself. It only instantiates the class if you haven't already given it an instance to use. You should be able to write your constructor like this:

```<code>constructor TLarryComponent.CreateFromString(const AData: string);
var
  StrStream, BinStream: TStream;
begin
  Create(nil);
  StrStream := TStringStream.Create(AData);
  try
    BinStream := TMemoryStream.Create;
    try
      ObjectTextToBinary(StrStream, BinStream);
      BinStream.Position := 0;
      BinStream.ReadComponent(Self);
    finally
      BinStream.Free;
    end;
  finally
    StrStream.Free;
  end;
end;
</code>```

There we're passing the current object, designated by Self, to ReadComponent. The stream will ignore the class name stored in the stream and assume that the current object is of the correct class.

Body:
I'm serializing and deserializing an object (TComponent descendant) using the example in the ComponentToString section in the Delphi help file.  This is so I can store the object in a VARCHAR field in the database.

When I need to instantiate a new instance of my class from a string stored in the database, can I do that using a constructor of the form CreateFromString(AOwner: TComponent; AData: String)?  Or do I have to use a non-class method that returns an instance of my component class?

If I can use the constructor version, how to I "map" the return value of ReadComponent to the "self" that is being created by the constructor?

Here's the deserialization example from the help file:

function StringToComponentProc(Value: string): TComponent;
var
  StrStream:TStringStream;
  BinStream: TMemoryStream;
begin
  StrStream := TStringStream.Create(Value);
  try
    BinStream := TMemoryStream.Create;
    try
      ObjectTextToBinary(StrStream, BinStream);
      BinStream.Seek(0, soFromBeginning);
      Result:= BinStream.ReadComponent(nil);
    finally
      BinStream.Free;
    end;
  finally
    StrStream.Free;
  end;
end;

Body:
In general, yes, you can make a constructor deserialize a string and use that information to initialize the new instance. A trivial example of that would be a class with a single Integer field. Pass a string to the constructor and have the constructor call StrToInt and initialize the field with the result.

But if the only function you have for deserialization is one that also creates the instance, then you cannot use that from the constructor because then you'll end up with two instances when you only wanted one. There's no way for a constructor to say, "Never mind; don't construct an instance after all. I already got one somewhere else."

However, that's not the situation you're in. As you should know, TStream.ReadComponent allows you to create the instance yourself. It only instantiates the class if you haven't already given it an instance to use. You should be able to write your constructor like this:

constructor TLarryComponent.CreateFromString(const AData: string);
var
  StrStream, BinStream: TStream;
begin
  Create(nil);
  StrStream := TStringStream.Create(AData);
  try
    BinStream := TMemoryStream.Create;
    try
      ObjectTextToBinary(StrStream, BinStream);
      BinStream.Position := 0;
      BinStream.ReadComponent(Self);
    finally
      BinStream.Free;
    end;
  finally
    StrStream.Free;
  end;
end;

There we're passing the current object, designated by Self, to ReadComponent. The stream will ignore the class name stored in the stream and assume that the current object is of the correct class.