问:
NETWORK SERVICE user cannot read certificate windows server 2012
I have a local service running on my windows 2012 server machine. It is a azure service fabric cluster with one node, but this shouldn't matter for this problem.

The service runs under the "NETWORK SERVICE: user, and has code that accesses a certificate stored on local machine. The code that finds the certificate using X509Certificate2Collection.Find method.

The exception is:

Exception thrown: 'System.AggregateException' in mscorlib.dll

Additional information: Could not successfully acquire access token
  using thumbprints: 80CEA40A62FFA0116FCB40B7B5985ADCD3E5AC39

When I execute the same Find function with same parameters locally as admin user, it works.

I have tried explicitly granting the NETWORK SERVICE user read permission on the certificate, but this did not solve it.

I have also tried executing code locally under NETWORK SERVICE user context (not as deployed local service, but local executable code snippet) that gets a certificate, and this works, which is strange.

答:
I would think the issue is that the network service doesn't have access to the private key. I use the following code to set the permission, after importing the certificates to my own store with me having access to the private keys</p>

```<code>Import-PfxCertificate -CertStoreLocation Cert:\LocalMachine\My -FilePath "path to the pfx file"
$certs = Get-ChildItem -Path cert:\LocalMachine\My

Foreach ($cert in $certs)
{
 # Specify the user, the permissions and the permission type
 $permission = "Network Service","FullControl","Allow"
 $accessRule = New-Object -TypeName
 System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permission

 # Location of the machine related keys
 $keyPath = Join-Path -Path $env:ProgramData -ChildPath "\Microsoft\Crypto\RSA\MachineKeys"
 $keyName = $cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
 $keyFullPath = Join-Path -Path $keyPath -ChildPath $keyName

 # Get the current acl of the private key
 $acl = (Get-Item $keyFullPath).GetAccessControl('Access')

 # Add the new ace to the acl of the private key
 $acl.SetAccessRule($accessRule)

 # Write back the new acl
 Set-Acl -Path $keyFullPath -AclObject $acl -ErrorAction Stop

 # Observe the access rights currently assigned to this certificate.
 get-acl $keyFullPath| fl
 }
</code>```

Body:
I would think the issue is that the network service doesn't have access to the private key. I use the following code to set the permission, after importing the certificates to my own store with me having access to the private keys

Import-PfxCertificate -CertStoreLocation Cert:\LocalMachine\My -FilePath "path to the pfx file"
$certs = Get-ChildItem -Path cert:\LocalMachine\My

Foreach ($cert in $certs)
{
 # Specify the user, the permissions and the permission type
 $permission = "Network Service","FullControl","Allow"
 $accessRule = New-Object -TypeName
 System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permission

 # Location of the machine related keys
 $keyPath = Join-Path -Path $env:ProgramData -ChildPath "\Microsoft\Crypto\RSA\MachineKeys"
 $keyName = $cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
 $keyFullPath = Join-Path -Path $keyPath -ChildPath $keyName

 # Get the current acl of the private key
 $acl = (Get-Item $keyFullPath).GetAccessControl('Access')

 # Add the new ace to the acl of the private key
 $acl.SetAccessRule($accessRule)

 # Write back the new acl
 Set-Acl -Path $keyFullPath -AclObject $acl -ErrorAction Stop

 # Observe the access rights currently assigned to this certificate.
 get-acl $keyFullPath| fl
 }


来源: stackexchange

问:
Swift Audio Playback speed
I am developing a game where the main sprite is a spinning wheel. I would like to associate audio to the spinning wheel that changes pitch as the wheel slows down. When the wheel stops spinning I would like the sound effect to stop. Can someone point me in the right direction?

In my game scene I have the following code:

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    for touch in touches {
        let location = touch.location(in: self)
        //Start spinning the wheel
        if atPoint(location).name == "play_button" {
            player?.physicsBody?.angularVelocity = 0
            player?.rotatePlayer()

            //Click back button
        } else if atPoint(location).name == "back_button" {
            let play_scene = CharacterSelectScene(fileNamed: "CharacterSelect")
            play_scene?.scaleMode = .aspectFill
            self.view?.presentScene(play_scene!, transition: SKTransition.doorsOpenVertical(withDuration: 1))
        } else if atPoint(location).name == "settings_button" {
            let play_scene = SettingsScene(fileNamed: "SettingsScene")
            play_scene?.scaleMode = .aspectFill
            self.view?.presentScene(play_scene!, transition: SKTransition.doorsOpenVertical(withDuration: 1))
        }
    }
}

override func didSimulatePhysics() {
    let speed = player?.physicsBody?.angularVelocity
    if (speed != CGFloat(0.0)) {
        if (speed! <= CGFloat(0.1)){
            finishedRotation = true
        }
    }
}
override func didFinishUpdate() {
    if (finishedRotation == true) {
        let play_scene = QuestionScene(fileNamed: "QuestionScene")
        play_scene?.scaleMode = .aspectFill
        self.view?.presentScene(play_scene!, transition: SKTransition.doorsOpenVertical(withDuration: 1))
    }
}
func didBegin(_ contact: SKPhysicsContact) {
    let defaults = UserDefaults.standard
    var firstBody = SKPhysicsBody()
    var secondBody = SKPhysicsBody()
    if (contact.bodyA.node?.name == "pin") {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    } else {
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }
    if (firstBody.node?.name == "pin" && secondBody.node?.name == "geography") {
        let set_topic = secondBody.node?.name
        defaults.set(set_topic, forKey: "Topic")
    } else if (firstBody.node?.name == "pin" && secondBody.node?.name == "maths") {
        let set_topic = secondBody.node?.name
        defaults.set(set_topic, forKey: "Topic")
    } else if (firstBody.node?.name == "pin" && secondBody.node?.name == "history") {
        let set_topic = secondBody.node?.name
        defaults.set(set_topic, forKey: "Topic")
    } else if (firstBody.node?.name == "pin" && secondBody.node?.name == "science") {
        let set_topic = secondBody.node?.name
        defaults.set(set_topic, forKey: "Topic")
    }
}
</code>```

The rotatePlayer method from the Player class is defined as below:

```<code>func rotatePlayer() {
    let random = GKRandomDistribution(lowestValue: 20, highestValue: 120)
    let r = random.nextInt()
    self.physicsBody?.angularVelocity = 0
    self.physicsBody?.angularVelocity = CGFloat(r)
    self.physicsBody?.angularDamping = 1.02

}
</code>```

答:
I have resolved the issue and the code is listed below:</p>

```<code>func playSound() {
    let url = Bundle.main.url(forResource: "clicker", withExtension: "m4a")!

    do {
        SoundEffect = try AVAudioPlayer(contentsOf: url)
        guard let players = SoundEffect else { return }

        players.prepareToPlay()
        players.play()
    } catch let error as NSError {
        print(error.description)
    }
}
func didEnd(_ contact: SKPhysicsContact) {

    let defaults = UserDefaults.standard
    var firstBody = SKPhysicsBody()
    var secondBody = SKPhysicsBody()
    if (contact.bodyA.node?.name == "pin") {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    } else {
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }
    if (firstBody.node?.name == "pin" && secondBody.node?.name == "geography") {
        let set_topic = secondBody.node?.name
        defaults.set(set_topic, forKey: "Topic")
        playSound()
    } else if (firstBody.node?.name == "pin" && secondBody.node?.name == "maths") {
        let set_topic = secondBody.node?.name
        defaults.set(set_topic, forKey: "Topic")
        playSound()
    } else if (firstBody.node?.name == "pin" && secondBody.node?.name == "history") {
        let set_topic = secondBody.node?.name
        defaults.set(set_topic, forKey: "Topic")
        playSound()
    } else if (firstBody.node?.name == "pin" && secondBody.node?.name == "science") {
        let set_topic = secondBody.node?.name
        defaults.set(set_topic, forKey: "Topic")
        playSound()
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Swift Audio Playback speed

Body:
I am developing a game where the main sprite is a spinning wheel. I would like to associate audio to the spinning wheel that changes pitch as the wheel slows down. When the wheel stops spinning I would like the sound effect to stop. Can someone point me in the right direction?

In my game scene I have the following code:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    for touch in touches {
        let location = touch.location(in: self)
        //Start spinning the wheel
        if atPoint(location).name == "play_button" {
            player?.physicsBody?.angularVelocity = 0
            player?.rotatePlayer()

            //Click back button
        } else if atPoint(location).name == "back_button" {
            let play_scene = CharacterSelectScene(fileNamed: "CharacterSelect")
            play_scene?.scaleMode = .aspectFill
            self.view?.presentScene(play_scene!, transition: SKTransition.doorsOpenVertical(withDuration: 1))
        } else if atPoint(location).name == "settings_button" {
            let play_scene = SettingsScene(fileNamed: "SettingsScene")
            play_scene?.scaleMode = .aspectFill
            self.view?.presentScene(play_scene!, transition: SKTransition.doorsOpenVertical(withDuration: 1))
        }
    }
}

override func didSimulatePhysics() {
    let speed = player?.physicsBody?.angularVelocity
    if (speed != CGFloat(0.0)) {
        if (speed! <= CGFloat(0.1)){
            finishedRotation = true
        }
    }
}
override func didFinishUpdate() {
    if (finishedRotation == true) {
        let play_scene = QuestionScene(fileNamed: "QuestionScene")
        play_scene?.scaleMode = .aspectFill
        self.view?.presentScene(play_scene!, transition: SKTransition.doorsOpenVertical(withDuration: 1))
    }
}
func didBegin(_ contact: SKPhysicsContact) {
    let defaults = UserDefaults.standard
    var firstBody = SKPhysicsBody()
    var secondBody = SKPhysicsBody()
    if (contact.bodyA.node?.name == "pin") {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    } else {
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }
    if (firstBody.node?.name == "pin" && secondBody.node?.name == "geography") {
        let set_topic = secondBody.node?.name
        defaults.set(set_topic, forKey: "Topic")
    } else if (firstBody.node?.name == "pin" && secondBody.node?.name == "maths") {
        let set_topic = secondBody.node?.name
        defaults.set(set_topic, forKey: "Topic")
    } else if (firstBody.node?.name == "pin" && secondBody.node?.name == "history") {
        let set_topic = secondBody.node?.name
        defaults.set(set_topic, forKey: "Topic")
    } else if (firstBody.node?.name == "pin" && secondBody.node?.name == "science") {
        let set_topic = secondBody.node?.name
        defaults.set(set_topic, forKey: "Topic")
    }
}

The rotatePlayer method from the Player class is defined as below:

func rotatePlayer() {
    let random = GKRandomDistribution(lowestValue: 20, highestValue: 120)
    let r = random.nextInt()
    self.physicsBody?.angularVelocity = 0
    self.physicsBody?.angularVelocity = CGFloat(r)
    self.physicsBody?.angularDamping = 1.02

}

Body:
I have resolved the issue and the code is listed below:

func playSound() {
    let url = Bundle.main.url(forResource: "clicker", withExtension: "m4a")!

    do {
        SoundEffect = try AVAudioPlayer(contentsOf: url)
        guard let players = SoundEffect else { return }

        players.prepareToPlay()
        players.play()
    } catch let error as NSError {
        print(error.description)
    }
}
func didEnd(_ contact: SKPhysicsContact) {

    let defaults = UserDefaults.standard
    var firstBody = SKPhysicsBody()
    var secondBody = SKPhysicsBody()
    if (contact.bodyA.node?.name == "pin") {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    } else {
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }
    if (firstBody.node?.name == "pin" && secondBody.node?.name == "geography") {
        let set_topic = secondBody.node?.name
        defaults.set(set_topic, forKey: "Topic")
        playSound()
    } else if (firstBody.node?.name == "pin" && secondBody.node?.name == "maths") {
        let set_topic = secondBody.node?.name
        defaults.set(set_topic, forKey: "Topic")
        playSound()
    } else if (firstBody.node?.name == "pin" && secondBody.node?.name == "history") {
        let set_topic = secondBody.node?.name
        defaults.set(set_topic, forKey: "Topic")
        playSound()
    } else if (firstBody.node?.name == "pin" && secondBody.node?.name == "science") {
        let set_topic = secondBody.node?.name
        defaults.set(set_topic, forKey: "Topic")
        playSound()
    }
}


问:
Is there any AdMob dummy id?
Is there any AdMob dummy ids for testing purpose?
Do I need to register app & get MY_AD_UNIT_ID? </p>

答:
For RewardedVideo you can use the following one :

```<code>private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/5224354917";
private static final String APP_ID = "ca-app-pub-3940256099942544~3347511713";
</code>```

how to use:

```<code>MobileAds.initialize(this, APP_ID);

mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
mRewardedVideoAd.loadAd(AD_UNIT_ID, new AdRequest.Builder().build());
</code>```

for showing

```<code> if (mRewardedVideoAd.isLoaded()) {
        mRewardedVideoAd.show();
  }
</code>```

Hope this will help many of us!

Title: Is there any AdMob dummy id?

Body:
For RewardedVideo you can use the following one :

private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/5224354917";
private static final String APP_ID = "ca-app-pub-3940256099942544~3347511713";

how to use:

MobileAds.initialize(this, APP_ID);

mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
mRewardedVideoAd.loadAd(AD_UNIT_ID, new AdRequest.Builder().build());

for showing

 if (mRewardedVideoAd.isLoaded()) {
        mRewardedVideoAd.show();
  }

Hope this will help many of us!


问:
Limiting objects in a SUM/COUNT without using a WHERE argument but requiring DISTINCT data
This may not be possible but worth a shot.

I have a very complex query and am trying to build a specific field. In short, some users have a date for ToS acceptance, other don't (yet) and I need to show both, but with the added complication that I need to have the dates of their logins after the ToS SUM'd. However, I don't want just the total logins, but the total distinct dates.

I can't add the argument t2.session >= t1.ToS in WHERE because that will eliminate the NULL ones I need to have

Here's a simplified view of the query:

```<code>SELECT t1.user,
     IF(t1.ToS IS NULL, NULL,COUNT(DISTINCT DATE_FORMAT(t2.sessionTime, '%Y-%m-%d'))) AS TotalLoginDates
FROM t1
JOIN t2 ON t1.id = t2.userId
</code>```

Not sure if my best option is a subquery, CASE, or other option.

Any help is appreciated, thanks.

EDIT: Some Inputs and desired outputs:

```t1
id | user         | ToS
1  | John Doe     | 2017-01-01 00:00:00
2  | Dave Smith   | 2017-02-01 06:00:00
3  | Alan Smithee | 2017-03-01 12:00:00
```

```
t2
sessionId | userId | sessionTime
1001      | 1      | 2017-01-01 00:01:00
1002      | 1      | 2017-01-05 03:17:45
1003      | 2      | 2016-12-15 15:27:34
1004      | 2      | 2017-03-15 16:67:12
1005      | 3      | 2017-04-02 12:00:00
1005      | 3      | 2017-04-02 13:15:00
```

```
Desired Output:
t1.user      | TotalLoginDates
John Doe     | 2
Dave Smith   | 1 (only one date after ToS)
Alan Smithee | 1 (2 logins on a single date)
```

答:
I am not sure exactly what you want to do, but this:

In short, some users have a date for ToS acceptance, other don't
  (yet) and I need to show both

suggests that you want a LEFT JOIN:

```<code>FROM t1 LEFT JOIN
     t2
     ON t1.id = t2.userId AND t2.session >= t1.ToS
</code>```

Body:
This may not be possible but worth a shot.

I have a very complex query and am trying to build a specific field. In short, some users have a date for ToS acceptance, other don't (yet) and I need to show both, but with the added complication that I need to have the dates of their logins after the ToS SUM'd. However, I don't want just the total logins, but the total distinct dates.

I can't add the argument t2.session >= t1.ToS in WHERE because that will eliminate the NULL ones I need to have

Here's a simplified view of the query:

SELECT t1.user,
     IF(t1.ToS IS NULL, NULL,COUNT(DISTINCT DATE_FORMAT(t2.sessionTime, '%Y-%m-%d'))) AS TotalLoginDates
FROM t1
JOIN t2 ON t1.id = t2.userId

Not sure if my best option is a subquery, CASE, or other option.

Any help is appreciated, thanks.

EDIT: Some Inputs and desired outputs:

t1
id | user         | ToS
1  | John Doe     | 2017-01-01 00:00:00
2  | Dave Smith   | 2017-02-01 06:00:00
3  | Alan Smithee | 2017-03-01 12:00:00

t2
sessionId | userId | sessionTime
1001      | 1      | 2017-01-01 00:01:00
1002      | 1      | 2017-01-05 03:17:45
1003      | 2      | 2016-12-15 15:27:34
1004      | 2      | 2017-03-15 16:67:12
1005      | 3      | 2017-04-02 12:00:00
1005      | 3      | 2017-04-02 13:15:00

Desired Output:
t1.user      | TotalLoginDates
John Doe     | 2
Dave Smith   | 1 (only one date after ToS)
Alan Smithee | 1 (2 logins on a single date)

Body:
I am not sure exactly what you want to do, but this:

In short, some users have a date for ToS acceptance, other don't
  (yet) and I need to show both

suggests that you want a LEFT JOIN:

FROM t1 LEFT JOIN
     t2
     ON t1.id = t2.userId AND t2.session >= t1.ToS


问:
DOM HTMLElement className property when the element has no class name set
When you have an HTML element with no class name set, what is the value of HTMLElement className property? My first thought was that it is undefined, but I found out that in FF it is just an empty string. My question is - can I rely on this behavior in all current and future browsers? Is that part of some specification or is it just another browser trick to avoid errors in badly written code?</p>

答:
It will always by default be an empty string (a DOMString specifically), and yes you can rely on it not being null/undefined.

Where it really matters is the getAttribute() definition:

Return Value DOMString

  The Attr value as a string, or the empty string if that attribute does not have a specified or default value.

...it's really just an attribute you're pulling back, so it's the same behavior in both cases, the interface just specifies those attributes.

ContentLicense: CC BY-SA 2.5


问:
Does storing Uploaded Files in Azure Web Applications FS harmpers multiples instaces deploy?
I heard a lot that Azure Web Applications uploaded content such as images or any files should be stored in Azure Storage service, not in the app File System.
But I would like to keep the solution simple and store those files into local file system.

Does storing images or any files on the application's local file system hampers somehow the application deployment with more than one instance?

答:
After researching a lot, I understand that, unlike Amazon Beanstalk, all instances of a Web App share the same file storage. despite of ecah apps runs into a different VM, they file system is the same.

The best way to think about it is that all the instances of your app map to the same network drive share that have your files.

when you spin up 2 or more instances the files in the file are using that same storage based file system even if you only have one instance.

You can see that easily by dropping a file (e.g. via FTP), and seeing it reflected instantly in all instances.

Sources: Microsoft, This question and this question


问:
is there a way of handling this Attribute value must be constant error?
I'm trying to invoke this method:

```<code>public Response getWithPathParam(@ApiParam(
        value = "Service group to check",
        allowableValues = ApiConstants.components,
        required = true )
</code>```

but want that allowableValues attribute will get a value that can be varying.

what I mean that I assuming allowableValues is a String.

I wondering if there is a way of reading a string from configuration and pass it into the attributes.

my attempt so far just led into the error of:

"Attribute value must be constant"

can you help please?

答:
Java prevents to accept any other annotation parameter other than a constant, so you need to change ApiConstants.components to be a fixed value, for example:

```<code>  class ApiConstants{
     public static final String[] CONSTANTS = {"VAL_1","VAL_2"};
  }
</code>```

If you still want to stay with dynamic configuration, then you need to handle it within the method itself.

Body:
I'm trying to invoke this method:

public Response getWithPathParam(@ApiParam(
        value = "Service group to check",
        allowableValues = ApiConstants.components,
        required = true )

but want that allowableValues attribute will get a value that can be varying.

what I mean that I assuming allowableValues is a String.

I wondering if there is a way of reading a string from configuration and pass it into the attributes.

my attempt so far just led into the error of:

"Attribute value must be constant"

can you help please?

Body:
Java prevents to accept any other annotation parameter other than a constant, so you need to change ApiConstants.components to be a fixed value, for example:

  class ApiConstants{
     public static final String[] CONSTANTS = {"VAL_1","VAL_2"};
  }

If you still want to stay with dynamic configuration, then you need to handle it within the method itself.


问:
Hibernate deletes occurring out of order
I have the following classes:

Category

```<code>@Entity
@Table(name = "category", schema = "customer")
public class Category extends CustomerOwned {
   ...
}
</code>```

CatalogueItem

```<code>@Entity
@Table(name = "catalogue_item", schema = "customer")
@EntityListeners(value = { CatalogueItemStatusListener.class })
public class CatalogueItem extends CatalogueOwned implements Statusable<CatalogueItem, CatalogueItemStatus> {
    ...
    @OneToMany(mappedBy = "catalogueItem", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<CatalogueItemCategory> categories;
    ...
}
</code>```

CatalogueItemCategory

```<code>@Entity
@Table(name = "catalogue_item_category", schema = "customer")
public class CatalogueItemCategory extends CatalogueItemOwned implements CategoryOwner {
    ...
    @ManyToOne
    @JoinColumn(name = "category_id", nullable = false, insertable = true, updatable = false)
    private Category category;
    ...
}
</code>```

We perform very few hard deletes in our application, but Categorys are hard deleted. CatalogueItemCategorys are also hard deleted.

I'm creating a service to allow someone to delete a Category and at the same time I check all Category dependencies and delete those too, so I'm doing this:

```<code>@Transactional
public DependentItemsResultResource delete(String categoryId, boolean force) {
    List<CatalogueItem> catalogueItems = catalogueItemRepository.getByCategory(getCustomerStringId(), categoryId);

    DependentItemsResultResource resultResource = new DependentItemsResultResource();
    resultResource.setDependentCatalogueItems(new SearchResponse().from(catalogueItems, CatalogueItemSummaryResource::new));

    if (!catalogueItems.isEmpty()) {
        if (!force) {
            resultResource.setDeleted(false);
            return resultResource;
        }

        catalogueItems.forEach(item -> {
            item.getCategories().removeIf(catalogueItemCategory -> categoryId.equals(catalogueItemCategory.getCategory().getStringId()));
            sendEvent(prepareEvent(new CatalogueItemUpdatedEvent(), item.getCatalogue().getStringId(), item.getStringId()));
        });
    }

    Category category = getCategory(categoryId);
    resultResource.setDeleted(true);
    categoryRepository.delete(category);

    CategoryDeletedEvent event = new CategoryDeletedEvent();
    event.setCategoryPath(category.getPath());
    sendEvent(prepareEvent(event, categoryId));
    return resultResource;
}
</code>```

This is causing the following exception:

```<code>Caused by: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FKLYKUEHJG9UL0LR36O5XDD3MLF: CUSTOMER.CATALOGUE_ITEM_CATEGORY FOREIGN KEY(CATEGORY_ID) REFERENCES CUSTOMER.CATEGORY(ID) (1)"; SQL statement:
delete from customer.category where id=? [23503-192]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:426)
    at org.h2.constraint.ConstraintReferential.checkRowRefTable(ConstraintReferential.java:443)
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:318)
    at org.h2.table.Table.fireConstraints(Table.java:967)
    at org.h2.table.Table.fireAfterRow(Table.java:985)
    at org.h2.command.dml.Delete.update(Delete.java:101)
    at org.h2.command.CommandContainer.update(CommandContainer.java:98)
    at org.h2.command.Command.executeUpdate(Command.java:258)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:160)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:146)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
    ... 109 common frames omitted
</code>```

I've tried replacing this bit:

```<code>item.getCategories().removeIf(catalogueItemCategory -> categoryId.equals(catalogueItemCategory.getCategory().getStringId()));
</code>```

with this:

```<code>item.getCategories().stream()
    .filter(catalogueItemCategory -> categoryId.equals(catalogueItemCategory.getCategory().getStringId()))
    .forEach(catalogueItemCategoryRepository::delete);
</code>```

but it's not making any difference. Hibernate is deleting the objects out of order. It should be deleting the CatalogueItemCategory objects before the Category objects, but it's not.

How do I get it to delete in the correct order?

Edit: missed this class which provides the parent of the CatalogueItemCategory:

```<code>@MappedSuperclass
public class CatalogueItemOwned extends Updateable {
    ...
    @ManyToOne
    @JoinColumn(name = "catalogue_item_id", nullable = false, insertable = true)
    private CatalogueItem catalogueItem;
    ...
}
</code>```

答:
I've solved this by explicitly deleting the category and all dependencies as follows:

```<code>@Transactional
public DependentItemsResultResource delete(String categoryId, boolean force) {
    List<CatalogueItem> catalogueItems = catalogueItemRepository.getByCategory(getCustomerStringId(), categoryId);

    DependentItemsResultResource resultResource = new DependentItemsResultResource();
    resultResource.setDependentCatalogueItems(new SearchResponse().from(catalogueItems, CatalogueItemSummaryResource::new));

    if (!catalogueItems.isEmpty()) {
        if (!force) {
            resultResource.setDeleted(false);
            return resultResource;
        }

        catalogueItems.forEach(item -> sendEvent(prepareEvent(
            new CatalogueItemUpdatedEvent(), item.getCatalogue().getStringId(), item.getStringId())));
    }

    Category category = getCategory(categoryId);
    resultResource.setDeleted(true);
    categoryRepository.deleteCatalogueItemCategoriesByCategory(category);
    categoryRepository.deleteCategory(category);

    CategoryDeletedEvent event = new CategoryDeletedEvent();
    event.setCategoryPath(category.getPath());
    sendEvent(prepareEvent(event, categoryId));
    return resultResource;
}
</code>```

The repo methods are:

```<code>@Modifying
@Query("delete from Category c where c = :category")
void deleteCategory(@Param("category") Category category);
</code>```

and

```<code>@Modifying
@Query("delete from CatalogueItemCategory where category = :category")
void deleteCatalogueItemCategoriesByCategory(@Param("category") Category category);
</code>```

Not the best, but also not the worst. Not using native deletes and it's still within the main transaction.

Body:
I have the following classes:

Category

@Entity
@Table(name = "category", schema = "customer")
public class Category extends CustomerOwned {
   ...
}

CatalogueItem

@Entity
@Table(name = "catalogue_item", schema = "customer")
@EntityListeners(value = { CatalogueItemStatusListener.class })
public class CatalogueItem extends CatalogueOwned implements Statusable<CatalogueItem, CatalogueItemStatus> {
    ...
    @OneToMany(mappedBy = "catalogueItem", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<CatalogueItemCategory> categories;
    ...
}

CatalogueItemCategory

@Entity
@Table(name = "catalogue_item_category", schema = "customer")
public class CatalogueItemCategory extends CatalogueItemOwned implements CategoryOwner {
    ...
    @ManyToOne
    @JoinColumn(name = "category_id", nullable = false, insertable = true, updatable = false)
    private Category category;
    ...
}

We perform very few hard deletes in our application, but Categorys are hard deleted. CatalogueItemCategorys are also hard deleted.

I'm creating a service to allow someone to delete a Category and at the same time I check all Category dependencies and delete those too, so I'm doing this:

@Transactional
public DependentItemsResultResource delete(String categoryId, boolean force) {
    List<CatalogueItem> catalogueItems = catalogueItemRepository.getByCategory(getCustomerStringId(), categoryId);

    DependentItemsResultResource resultResource = new DependentItemsResultResource();
    resultResource.setDependentCatalogueItems(new SearchResponse().from(catalogueItems, CatalogueItemSummaryResource::new));

    if (!catalogueItems.isEmpty()) {
        if (!force) {
            resultResource.setDeleted(false);
            return resultResource;
        }

        catalogueItems.forEach(item -> {
            item.getCategories().removeIf(catalogueItemCategory -> categoryId.equals(catalogueItemCategory.getCategory().getStringId()));
            sendEvent(prepareEvent(new CatalogueItemUpdatedEvent(), item.getCatalogue().getStringId(), item.getStringId()));
        });
    }

    Category category = getCategory(categoryId);
    resultResource.setDeleted(true);
    categoryRepository.delete(category);

    CategoryDeletedEvent event = new CategoryDeletedEvent();
    event.setCategoryPath(category.getPath());
    sendEvent(prepareEvent(event, categoryId));
    return resultResource;
}

This is causing the following exception:

Caused by: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FKLYKUEHJG9UL0LR36O5XDD3MLF: CUSTOMER.CATALOGUE_ITEM_CATEGORY FOREIGN KEY(CATEGORY_ID) REFERENCES CUSTOMER.CATEGORY(ID) (1)"; SQL statement:
delete from customer.category where id=? [23503-192]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:179)
    at org.h2.message.DbException.get(DbException.java:155)
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:426)
    at org.h2.constraint.ConstraintReferential.checkRowRefTable(ConstraintReferential.java:443)
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:318)
    at org.h2.table.Table.fireConstraints(Table.java:967)
    at org.h2.table.Table.fireAfterRow(Table.java:985)
    at org.h2.command.dml.Delete.update(Delete.java:101)
    at org.h2.command.CommandContainer.update(CommandContainer.java:98)
    at org.h2.command.Command.executeUpdate(Command.java:258)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:160)
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:146)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
    ... 109 common frames omitted

I've tried replacing this bit:

item.getCategories().removeIf(catalogueItemCategory -> categoryId.equals(catalogueItemCategory.getCategory().getStringId()));

with this:

item.getCategories().stream()
    .filter(catalogueItemCategory -> categoryId.equals(catalogueItemCategory.getCategory().getStringId()))
    .forEach(catalogueItemCategoryRepository::delete);

but it's not making any difference. Hibernate is deleting the objects out of order. It should be deleting the CatalogueItemCategory objects before the Category objects, but it's not.

How do I get it to delete in the correct order?

Edit: missed this class which provides the parent of the CatalogueItemCategory:

@MappedSuperclass
public class CatalogueItemOwned extends Updateable {
    ...
    @ManyToOne
    @JoinColumn(name = "catalogue_item_id", nullable = false, insertable = true)
    private CatalogueItem catalogueItem;
    ...
}

Body:
I've solved this by explicitly deleting the category and all dependencies as follows:

@Transactional
public DependentItemsResultResource delete(String categoryId, boolean force) {
    List<CatalogueItem> catalogueItems = catalogueItemRepository.getByCategory(getCustomerStringId(), categoryId);

    DependentItemsResultResource resultResource = new DependentItemsResultResource();
    resultResource.setDependentCatalogueItems(new SearchResponse().from(catalogueItems, CatalogueItemSummaryResource::new));

    if (!catalogueItems.isEmpty()) {
        if (!force) {
            resultResource.setDeleted(false);
            return resultResource;
        }

        catalogueItems.forEach(item -> sendEvent(prepareEvent(
            new CatalogueItemUpdatedEvent(), item.getCatalogue().getStringId(), item.getStringId())));
    }

    Category category = getCategory(categoryId);
    resultResource.setDeleted(true);
    categoryRepository.deleteCatalogueItemCategoriesByCategory(category);
    categoryRepository.deleteCategory(category);

    CategoryDeletedEvent event = new CategoryDeletedEvent();
    event.setCategoryPath(category.getPath());
    sendEvent(prepareEvent(event, categoryId));
    return resultResource;
}

The repo methods are:

@Modifying
@Query("delete from Category c where c = :category")
void deleteCategory(@Param("category") Category category);

and

@Modifying
@Query("delete from CatalogueItemCategory where category = :category")
void deleteCatalogueItemCategoriesByCategory(@Param("category") Category category);

Not the best, but also not the worst. Not using native deletes and it's still within the main transaction.


问:
Can't center a View in an activity in XML (Android)
I have created a new (second) activity in my android app, and right now there is one view in the content_area_reduction.xml (EditText). The file looks like this:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.company.myname.appname.AreaReductionActivity"
    tools:showIn="@layout/activity_area_reduction">

        <EditText
            android:id="@+id/edit2"
            android:layout_width="200dip"
            android:layout_height="50dip"
            android:textAlignment="center"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"/>

</RelativeLayout>
</code>```

The problem is, the view appears on the left of the screen instead of center. How do I fix this issue? Will post more code if needed.

Thank you

答:
You can try this code </p>

```<code><EditText
    android:id="@+id/edit2"
    android:layout_width="200dp"
    android:layout_height="50dp"
    android:textAlignment="center"
    android:layout_centerInParent="true" />
</code>```

Body:
I have created a new (second) activity in my android app, and right now there is one view in the content_area_reduction.xml (EditText). The file looks like this:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.company.myname.appname.AreaReductionActivity"
    tools:showIn="@layout/activity_area_reduction">

        <EditText
            android:id="@+id/edit2"
            android:layout_width="200dip"
            android:layout_height="50dip"
            android:textAlignment="center"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"/>

</RelativeLayout>

The problem is, the view appears on the left of the screen instead of center. How do I fix this issue? Will post more code if needed.

Thank you

Body:
You can try this code

<EditText
    android:id="@+id/edit2"
    android:layout_width="200dp"
    android:layout_height="50dp"
    android:textAlignment="center"
    android:layout_centerInParent="true" />


问:
Css cut right side of an image
I have a div with a width of ~ 200px and a height of 145px, inside that div I place an Image which has a height of 145px but a width of 210px, how can I cut 10px from the right side of the Image so that the Image fits into the Content of the div?

答:
.container {
    width: 200px;
    height: 145px;
    overflow: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <img src="https://images-na.ssl-images-amazon.com/images/M/MV5BMzU5ODI0NDE4MF5BMl5BanBnXkFtZTYwMTE2MTI2._V1_SY154_SX210_AL_.jpg">
</div></code>```

Title: Css cut right side of an image

Body:
.container {
    width: 200px;
    height: 145px;
    overflow: hidden;
}

<div class="container">
  <img src="https://images-na.ssl-images-amazon.com/images/M/MV5BMzU5ODI0NDE4MF5BMl5BanBnXkFtZTYwMTE2MTI2._V1_SY154_SX210_AL_.jpg">
</div>


问:
Regex to capture everything up to (but not including the 1st space and hyphen)
Here is my samples string

```<code>Google Chrome-Helper -type=renderer -field-trial-handle=1
</code>```

But I want just Google Chrome-Helper

Ive tried: ^.*[ ][-] but captures up to the last parameter.

Example Here

答:
You need to use lazy dot matching and either use capturing or a lookahead:

```<code>^(.*?)\s+-
</code>```

(your value will be in Group 1) or

```<code>^.*?(?=\s+-)
</code>```

See the regex demo with capturing and with a lookahead.

Details:

^ - start of string anchor

.*?  - any 0+ chars other than a newline, as few as possible (i.e. the subsequent subpatterns are tried first, this one is skipped, the regex engine only comes back here if they fail to find a match)

(?=\s+-) -  a positive lookahead that requires 1+ whitespace and then a hyphen.

Body:
Here is my samples string

Google Chrome-Helper -type=renderer -field-trial-handle=1

But I want just Google Chrome-Helper

Ive tried: ^.*[ ][-] but captures up to the last parameter.

Example Here

Body:
You need to use lazy dot matching and either use capturing or a lookahead:

^(.*?)\s+-

(your value will be in Group 1) or

^.*?(?=\s+-)

See the regex demo with capturing and with a lookahead.

Details:

^ - start of string anchor

.*?  - any 0+ chars other than a newline, as few as possible (i.e. the subsequent subpatterns are tried first, this one is skipped, the regex engine only comes back here if they fail to find a match)

(?=\s+-) -  a positive lookahead that requires 1+ whitespace and then a hyphen.


问:
How do you make tooltip show up for longer in IE
i got the following

```<code><span id="pageLink" style="cursor:pointer;" onClick="...." title="<%=pHelper.getNameToolTip()%>">
</code>```

in firefox the tooltip stays there until the mouse is moved, but in IE it only stays there for about 5seconds and disappears.

is there a way to make it last longer?

答: Not sure if you're inclined to using jQuery, but there are many tooltip plugins that will provide the functionality you're looking for, along with some extras.</p>

Body:
i got the following

<span id="pageLink" style="cursor:pointer;" onClick="...." title="<%=pHelper.getNameToolTip()%>">

in firefox the tooltip stays there until the mouse is moved, but in IE it only stays there for about 5seconds and disappears.

is there a way to make it last longer?


问:
Issue getting exit code from jar
I have made a jar file which takes as parameter a string representing the path to an image file. After that I made a batch file which takes a string (path to a folder full of pictures), as a parameter. Then it starts the jar file in a loop giving to it the image files. The Problem is that it should return the errorlevel form the jar, yet it returns only 0. this is the batch file:

```<code>set arg1=%1
setlocal enabledelayedexpansion
for %%i in (%arg1%\*.*) do (java -jar %~dp0DrawingLinesBytedeco.jar "%%i"
set exitcode=%ERRORLEVEL%
call echo exit code %exitcode%)
</code>```

And this is a part of the java code:

```<code>if(horizontal > vertical) {
        System.out.println("The Image is horizontal");
        System.out.println("The Image is ok");
    }
else {
        System.out.println("The Image is vertical");
        System.out.println("The Image should turn");
        System.exit(1);
     }
</code>```

This is the output I get when I run it in the console

答:
Try this.</p>

```<code>set arg1=%1
goto MAIN

:JAVA
java -jar %~dp0DrawingLinesBytedeco.jar %1
set exitcode=%ERRORLEVEL%
call echo exit code %exitcode%
goto :EOF

:MAIN
for %%i in (%arg1%\*.*) do call :JAVA "%%i"
</code>```

Title: Issue getting exit code from jar

Body:
I have made a jar file which takes as parameter a string representing the path to an image file. After that I made a batch file which takes a string (path to a folder full of pictures), as a parameter. Then it starts the jar file in a loop giving to it the image files. The Problem is that it should return the errorlevel form the jar, yet it returns only 0. this is the batch file:

set arg1=%1
setlocal enabledelayedexpansion
for %%i in (%arg1%\*.*) do (java -jar %~dp0DrawingLinesBytedeco.jar "%%i"
set exitcode=%ERRORLEVEL%
call echo exit code %exitcode%)

And this is a part of the java code:

if(horizontal > vertical) {
        System.out.println("The Image is horizontal");
        System.out.println("The Image is ok");
    }
else {
        System.out.println("The Image is vertical");
        System.out.println("The Image should turn");
        System.exit(1);
     }

This is the output I get when I run it in the console

Body:
Try this.

set arg1=%1
goto MAIN

:JAVA
java -jar %~dp0DrawingLinesBytedeco.jar %1
set exitcode=%ERRORLEVEL%
call echo exit code %exitcode%
goto :EOF

:MAIN
for %%i in (%arg1%\*.*) do call :JAVA "%%i"


问:
How to conveniently hide elements selected using an adblocker via a userscript?
To block an element, one can use:

```<code>var adSidebar = document.getElementById('ads');
if (adSidebar) {
    adSidebar.parentNode.removeChild(adSidebar);
}
</code>```

But that's for one specific element, for one specific site. To do block multiple elements in multiple sites, the userscript must @include many times, and in each site it should list the elements many times. Say I have a list of adblocker filters, how to covert it into a single userscript conveniently?

```<code>www.youtube.com###watch7-sidebar-contents
www.youtube.com##.yt-masthead-logo-container
www.facebook.com##._1uh-:nth-of-type(2)
www.facebook.com##._2t-e > ._4kny:nth-of-type(1)
www.facebook.com##._1uh-:nth-of-type(1)
www.facebook.com##._50tj._2t-a
www.facebook.com##._50ti._2s1y._5rmj._26aw._2t-a
www.facebook.com###u_0_0
www.facebook.com###fbDockChatBuddylistNub > .fbNubButton
</code>```

I would like to keep that list in one place, so that if a new element in a new website needs to be blocked, I just simply add the line from uBlock into the list.

答:
You can do this by creating a userscript that runs on all domains, parses a list of strings obtained from an ad blocker for the domain and query selector, see if it matches the window's domain and if the element(s) exist, then remove them if so. I've provided one way of doing so below:

```<code>// ==UserScript==
// @name         Custom element hider
// @namespace    https://zachsaucier.com/
// @version      0.1
// @description  To show how one can hide elements like an ad blocker using userscripts
// @author       Zach Saucier
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Set our list of sites and elements to block
    var blockList = [
        "www.youtube.com###watch7-sidebar-contents",
        "www.youtube.com##.yt-masthead-logo-container",
        "www.facebook.com##._1uh-:nth-of-type(2)",
        "www.facebook.com##._2t-e > ._4kny:nth-of-type(1)",
        "www.facebook.com##._1uh-:nth-of-type(1)",
        "www.facebook.com##._50tj._2t-a",
        "www.facebook.com##._50ti._2s1y._5rmj._26aw._2t-a",
        "www.facebook.com###u_0_0",
        "www.facebook.com###fbDockChatBuddylistNub > .fbNubButton"
    ];

    // Get the window's hostname
    var windowHostname = window.location.hostname;

    // Iterate through the blocklist, hiding elements as needed
    for(var i = 0; i < blockList.length; i++) {
        var entryParts = blockList[i].split('##');

        // Compare the hostnames; Only remove elements if they match
        if(windowHostname === entryParts[0]) {
            // Find the elements if they exists
            var matchedElements = document.querySelectorAll(entryParts[1]);

            // Actually remove the element(s) that match
            for(var j = 0; j < matchedElements.length; j++) {
                var matchedElem = matchedElements[j];

                matchedElem.parentNode.removeChild(matchedElem);
            }
        }
    }
})();
</code>```

Though I'm not sure why you would want to write a userscript to do this when the ad blocker itself can do this...

Body:
To block an element, one can use:

var adSidebar = document.getElementById('ads');
if (adSidebar) {
    adSidebar.parentNode.removeChild(adSidebar);
}

But that's for one specific element, for one specific site. To do block multiple elements in multiple sites, the userscript must @include many times, and in each site it should list the elements many times. Say I have a list of adblocker filters, how to covert it into a single userscript conveniently?

www.youtube.com###watch7-sidebar-contents
www.youtube.com##.yt-masthead-logo-container
www.facebook.com##._1uh-:nth-of-type(2)
www.facebook.com##._2t-e > ._4kny:nth-of-type(1)
www.facebook.com##._1uh-:nth-of-type(1)
www.facebook.com##._50tj._2t-a
www.facebook.com##._50ti._2s1y._5rmj._26aw._2t-a
www.facebook.com###u_0_0
www.facebook.com###fbDockChatBuddylistNub > .fbNubButton

I would like to keep that list in one place, so that if a new element in a new website needs to be blocked, I just simply add the line from uBlock into the list.

Body:
You can do this by creating a userscript that runs on all domains, parses a list of strings obtained from an ad blocker for the domain and query selector, see if it matches the window's domain and if the element(s) exist, then remove them if so. I've provided one way of doing so below:

// ==UserScript==
// @name         Custom element hider
// @namespace    https://zachsaucier.com/
// @version      0.1
// @description  To show how one can hide elements like an ad blocker using userscripts
// @author       Zach Saucier
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Set our list of sites and elements to block
    var blockList = [
        "www.youtube.com###watch7-sidebar-contents",
        "www.youtube.com##.yt-masthead-logo-container",
        "www.facebook.com##._1uh-:nth-of-type(2)",
        "www.facebook.com##._2t-e > ._4kny:nth-of-type(1)",
        "www.facebook.com##._1uh-:nth-of-type(1)",
        "www.facebook.com##._50tj._2t-a",
        "www.facebook.com##._50ti._2s1y._5rmj._26aw._2t-a",
        "www.facebook.com###u_0_0",
        "www.facebook.com###fbDockChatBuddylistNub > .fbNubButton"
    ];

    // Get the window's hostname
    var windowHostname = window.location.hostname;

    // Iterate through the blocklist, hiding elements as needed
    for(var i = 0; i < blockList.length; i++) {
        var entryParts = blockList[i].split('##');

        // Compare the hostnames; Only remove elements if they match
        if(windowHostname === entryParts[0]) {
            // Find the elements if they exists
            var matchedElements = document.querySelectorAll(entryParts[1]);

            // Actually remove the element(s) that match
            for(var j = 0; j < matchedElements.length; j++) {
                var matchedElem = matchedElements[j];

                matchedElem.parentNode.removeChild(matchedElem);
            }
        }
    }
})();

Though I'm not sure why you would want to write a userscript to do this when the ad blocker itself can do this...


问:
How do I convert "7-1-2014" to "07-01-2014" in MySQL Workbench?
I have already gone through part of the process to convert my text to a proper date:

7-jan -> 7-1 -> 7-1-2014
(note: dd-mm-yyyy)

However, I am now required to change the 7-1-2014 format to 07-01-2014 in order to change the text to a date.

Is there an easy way to do this?
Am not too experienced but have a basic understanding of queries and functions.

Body:
Try this:

SELECT STR_TO_DATE('7-1-2014', '%e-%m-%Y');
SELECT STR_TO_DATE('7-Jan-2014', '%e-%M-%Y');


问:
Reserved error (-1524)
I am upgrading some of my MS Access programs from 2003 to 2007 version. I have a variable stored "Public" in the main menu of a program. In another form, I write that variable to a record (the form is using unbound data). The VBA line "Rst![FieldName]=Forms![Main Menu].strUser" gives a RunTime error of 3000, Reserved error (-1524).

What the heck is going on???????

Thanks for any help given.

答:
I did have the same problem and after look the records in one table discover that one record had language changed and was all in Chinese alphabet.
After delete the record no more error.

Looks like, in my case, the error was generated because the primary key was used to link to another table. I did a check after and manage to identify one record in the other table that do not exist in the main table (record I deleted).

OwnerDisplayName: Bill Crowder

Title: Reserved error (-1524)


问:
how to create a dropdown list in iphone?
i did a view based application and it tat thr 3 buttons and when i click each different subviews are displayed for performing different actions.when i click 1st button it should show a textfield to enter the items---for this i should have a drop down list to list the items available so that user can select the items from there.if i use pickerview then how i should display it as it may occupy more screen space.and if there is any other method pls give me the code.

could anyone help me with clear codes to complete this task pls.

thanku

答:
Just a suggestion

Picker is a good component better than a dropdownlist. So when the textfield is touched show the picker along with a toolbar having buttons as cancel and done. That is the user can select an option from the picker and select done to show the selected item in the textfield and cancel to cancel the picker.

Since you specified space constraint. Normally hide the picker. When user touches the textfield show the picker and again if the user selects cancel or done button hide the picker. Check your conditions in the cancel and done button actions.


问:
Spring Boot Config at Git
I am following an blog :

https://github.com/jeroenbellen/blog-manage-and-reload-spring-properties

I am developing the services using spring boot and I want to change the config at run-time without application restart.

I have run the code mentioned in the above github repo.
What I am not able to understand how does the example-service knows about config-service. There is nothing in code which link them together.

Also, there is just one example service but I have 10s of such example service, how do I use just one config service for all example services

答:
First question

how does the example-service knows about config-service?

Short answer

Magic happen when you add spring-cloud-config-client dependency

Long answer from spring cloud documentation

Client Side Usage

To use these features in an application, just build it as a Spring
  Boot application that depends on spring-cloud-config-client (e.g. see
  the test cases for the config-client, or the sample app). The most
  convenient way to add the dependency is via a Spring Boot starter
  org.springframework.cloud:spring-cloud-starter-config. There is also a
  parent pom and BOM (spring-cloud-starter-parent) for Maven users and a
  Spring IO version management properties file for Gradle and Spring CLI
  users.

Second question

Also, there is just one example service but I have 10s of such example
  service, how do I use just one config service for all example services

You just have to add spring-cloud-config-client dependency to each service. All services will look for config-service on http://localhost:8888 8888 being the default port

Title: Spring Boot Config at Git


问:
C# Decimal to byte[] and back in C
I have a system that stores a decimal value on a Mifare card

The C# decimal value is converted to a byte array of 16 bytes using this code

```<code>MemoryStream memStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memStream);
try
{
  try
  {
     writer.Write(m_Value);
     tmp = memStream.ToArray();
  }
  finally
  {
     memStream.Close();
  }
}
finally
{
  writer.Close();
}
</code>```

which gives a 16byte representation.

Now we have a customer which needs to read and convert these 16 bytes back to a decimal number, but in C

How is this done ?

Can anyone find a definition/spec of the C# byte representation, i cannot

答:
It is not good idea to rely on internal implementation of System.Decimal as far as it is a subject of change.

It is mach better to use Decimal.GetBits(value) that is well documented.

Other question is how are you going to pass you values to unmanaged code. For example, if you are using pInvoke you just pass decimal argument to method and it will be automatically marshaled to native code (if you want specify memory representation you can use [MarshalAs(UnmanagedType.R8)] attribute).

As far as I know, C++ by default does not have decimal type.

However, if you really need memory representation of System.Decimal you can easily obtain it from source code:
Decimal.cs and Decimal.cpp.

Title: C# Decimal to byte[] and back in C

Body:
I have a system that stores a decimal value on a Mifare card

The C# decimal value is converted to a byte array of 16 bytes using this code

MemoryStream memStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memStream);
try
{
  try
  {
     writer.Write(m_Value);
     tmp = memStream.ToArray();
  }
  finally
  {
     memStream.Close();
  }
}
finally
{
  writer.Close();
}

which gives a 16byte representation.

Now we have a customer which needs to read and convert these 16 bytes back to a decimal number, but in C

How is this done ?

Can anyone find a definition/spec of the C# byte representation, i cannot


问:
Spring JPA @query image
I need to get image saved in postgresql database using custom query in repository.
Currently i save image to database as byte[] with mime-type, file name and also create 2 thumbnail image in the same row.
For Http GET request i need to display the image, but i am required to create a qustom query so that if i want to get original image i query for that and dont load thumbnails or file name that are stored in the same table row in database.

MyFile entity:

```<code>@Entity
private String name;
private String mimeType;
private byte[] content;
private byte[] thumbnailSm;
private byte[] thumbnailMd;
// getters & setters
</code>```

Repository:

```<code>@Component
public interface MyFileRepository extends JpaRepository<MyFile, Long> {}
</code>```

Currently what i did in controller to get image from db:

```<code>    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public void getFile(@PathVariable Long id, HttpServletResponse response) throws IOException{
    MyFile myFile = myFileRepository.findOne(id);
    response.setContentType(myFile.getMimetype());
    response.getOutputStream().write(myFile.getContent());
    response.getOutputStream().close();
}
</code>```

The problem is that it loads all the content from database (thumbnails, name etc) when i only need original image.

I try to create a custom query in repository and the sql statement that i try to use is:

```<code>@Query(value = "SELECT content FROM file WHERE id=:id")
</code>```

Also tried the statement, don't really know what is the difference:

```<code>@Query(value = "SELECT f.content FROM file f WHERE f.id=:id")
</code>```

I get bytes from database but i can't seem to figure out how to send them from repository interface method to controller so i can display image.
I tried to use something like:

```<code>byte[] findFileById(@Param("id") Long id);
</code>```

and:

```<code>ResponseEntity<byte[]> findFileById(@Param("id") Long id);
</code>```

So my question is, after sql query gets bytes for image from db, how can i create a sql query method to get only image from db without also loading other content (thumbnails, name etc)?
Sorry if my explanation is confusing.

答:
Got it to work like i want by doing a sql query and setting the fields i dont want to load as null:</p>

```<code>@Query(value = "SELECT id, name, mime_type, content, null as thumbnail_sm, null as thumbnail_md FROM file WHERE id=:id", nativeQuery = true)
MyFile findContentById(@Param("id")Long id);
</code>```

Title: Spring JPA @query image

Body:
I need to get image saved in postgresql database using custom query in repository.
Currently i save image to database as byte[] with mime-type, file name and also create 2 thumbnail image in the same row.
For Http GET request i need to display the image, but i am required to create a qustom query so that if i want to get original image i query for that and dont load thumbnails or file name that are stored in the same table row in database.

MyFile entity:

@Entity
private String name;
private String mimeType;
private byte[] content;
private byte[] thumbnailSm;
private byte[] thumbnailMd;
// getters & setters

Repository:

@Component
public interface MyFileRepository extends JpaRepository<MyFile, Long> {}

Currently what i did in controller to get image from db:

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public void getFile(@PathVariable Long id, HttpServletResponse response) throws IOException{
    MyFile myFile = myFileRepository.findOne(id);
    response.setContentType(myFile.getMimetype());
    response.getOutputStream().write(myFile.getContent());
    response.getOutputStream().close();
}

The problem is that it loads all the content from database (thumbnails, name etc) when i only need original image.

I try to create a custom query in repository and the sql statement that i try to use is:

@Query(value = "SELECT content FROM file WHERE id=:id")

Also tried the statement, don't really know what is the difference:

@Query(value = "SELECT f.content FROM file f WHERE f.id=:id")

I get bytes from database but i can't seem to figure out how to send them from repository interface method to controller so i can display image.
I tried to use something like:

byte[] findFileById(@Param("id") Long id);

and:

ResponseEntity<byte[]> findFileById(@Param("id") Long id);

So my question is, after sql query gets bytes for image from db, how can i create a sql query method to get only image from db without also loading other content (thumbnails, name etc)?
Sorry if my explanation is confusing.

Body:
Got it to work like i want by doing a sql query and setting the fields i dont want to load as null:

@Query(value = "SELECT id, name, mime_type, content, null as thumbnail_sm, null as thumbnail_md FROM file WHERE id=:id", nativeQuery = true)
MyFile findContentById(@Param("id")Long id);


问:
Python - Interpolation of plots
For my evaluation, I have used gnuplot to plot data from two separate csv files (found in this link: https://drive.google.com/open?id=0B2Iv8dfU4fTUZGV6X1Bvb3c4TWs) with a different number of rows which generates the following graph.

These data seem to have no common timestamp (the first column) in both csv files and yet gnuplot seems to fit the plotting as shown above.

Here is the gnuplot script that I use to generate my plot.

```<code># ###### GNU Plot

set style data lines
set terminal postscript eps enhanced color "Times" 20

set output "output.eps"

set title "Actual vs. Estimated Comparison"

set style line 99 linetype 1 linecolor rgb "#999999" lw 2
#set border 1 back ls 11
set key right top
set key box linestyle 50
set key width -2
set xrange [0:10]
set key spacing 1.2
#set nokey

set grid xtics ytics mytics
#set size 2
#set size ratio 0.4

#show timestamp
set xlabel "Time [Seconds]"
set ylabel "Segments"

set style line 1 lc rgb "#ff0000" lt 1 pi 0 pt 4 lw 4 ps 0

plot  "estimated.csv" using ($1):2 with lines title "Estimated", "actual.csv" using ($1):2 with lines title "Actual";
</code>```

I wanted to interpolate my green line into the grid where my pink line is defined, then compare the two. Here is my initial approach

```<code>#!/usr/bin/env python
import sys

import numpy as np
from shapely.geometry import LineString
#-------------------------------------------------------------------------------
def load_data(fname):
    return LineString(np.genfromtxt(fname, delimiter = ','))
#-------------------------------------------------------------------------------
lines = list(map(load_data, sys.argv[1:]))

for g in lines[0].intersection(lines[1]):
    if g.geom_type != 'Point':
        continue
    print('%f,%f' % (g.x, g.y))
Then in Gnuplot, one can invoke it directly:

set terminal pngcairo
set output 'fig.png'

set datafile separator comma
set yr [0:700]
set xr [0:10]

set xtics 0,2,10
set ytics 0,100,700

set grid

set xlabel "Time [seconds]"
set ylabel "Segments"

plot \
    'estimated.csv' w l lc rgb 'dark-blue' t 'Estimated', \
    'actual.csv' w l lc rgb 'green' t 'Actual', \
    '<python filter.py estimated.csv actual.csv' w p lc rgb 'red' ps 0.5 pt 7 t ''
</code>```

which gives us the following plot

I wrote the filtered points to another file (filtered_points.csv found in this link:https://drive.google.com/open?id=0B2Iv8dfU4fTUSHVOMzYySjVzZWc) from this script. However, the filtered points are less than 10% of the actual dataset (which is the ground truth).

Is there any way where we can interpolate the two lines by ignoring the pink high peaks above the green plot using python? Gnuplot doesn't seem to be the best tool for this. If the pink line doesn't touch the green line (i.e. if it is way below the green line), I want to take the values of the closest green line so that it will be a one-to-one correspondence (or very close) with the actual dataset. I want to return the interpolated values for the green line in the pink line grid so that we can compare both lines since they have the same array size.

答:
Getting the same data size in terms of an interpolation is pretty simple by numpy.interp(). For me, this code works:

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

names = ['actual.csv','estimated.csv']
#-------------------------------------------------------------------------------
def load_data(fname):
    return np.genfromtxt(fname, delimiter = ',')
#-------------------------------------------------------------------------------

data = [load_data(name) for name in names]
actual_data = data[0]
estimated_data = data[1]
interpolated_estimation = np.interp(estimated_data[:,0],actual_data[:,0],actual_data[:,1])

plt.figure()
plt.plot(actual_data[:,0],actual_data[:,1], label='actual')
plt.plot(estimated_data[:,0],estimated_data[:,1], label='estimated')
plt.plot(estimated_data[:,0],interpolated_estimation, label='interpolated')
plt.legend()
plt.show(block=True)
</code>```

After this interpolation interpolated_estimation has the same size as the x axis of actual_data, as the plot suggests. The slicing is a bit confusing but I tried to use your function and make the plot calls as clear as possible.

To save to a file and plot like suggested I changed the code to:

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

names = ['actual.csv','estimated.csv']
#-------------------------------------------------------------------------------
def load_data(fname):
    return np.genfromtxt(fname, delimiter = ',')
#-------------------------------------------------------------------------------

data = [load_data(name) for name in names]
actual_data = data[0]
estimated_data = data[1]
interpolated_estimation = np.interp(estimated_data[:,0],actual_data[:,0],actual_data[:,1])

plt.figure()
plt.plot(actual_data[:,0],actual_data[:,1], label='actual')
#plt.plot(estimated_data[:,0],estimated_data[:,1], label='estimated')
plt.plot(estimated_data[:,0],interpolated_estimation, label='interpolated')
np.savetxt('interpolated.csv',
       np.vstack((estimated_data[:,0],interpolated_estimation)).T,
       delimiter=',', fmt='%10.5f') #saves data to filedata to file
plt.legend()
plt.title('Actual vs. Interpolated')
plt.xlim(0,10)
plt.ylim(0,500)
plt.xlabel('Time [Seconds]')
plt.ylabel('Segments')
plt.grid()
plt.show(block=True)
</code>```

This produces the following output:

Title: Python - Interpolation of plots

Body:
For my evaluation, I have used gnuplot to plot data from two separate csv files (found in this link: https://drive.google.com/open?id=0B2Iv8dfU4fTUZGV6X1Bvb3c4TWs) with a different number of rows which generates the following graph.

These data seem to have no common timestamp (the first column) in both csv files and yet gnuplot seems to fit the plotting as shown above.

Here is the gnuplot script that I use to generate my plot.

# ###### GNU Plot

set style data lines
set terminal postscript eps enhanced color "Times" 20

set output "output.eps"

set title "Actual vs. Estimated Comparison"

set style line 99 linetype 1 linecolor rgb "#999999" lw 2
#set border 1 back ls 11
set key right top
set key box linestyle 50
set key width -2
set xrange [0:10]
set key spacing 1.2
#set nokey

set grid xtics ytics mytics
#set size 2
#set size ratio 0.4

#show timestamp
set xlabel "Time [Seconds]"
set ylabel "Segments"

set style line 1 lc rgb "#ff0000" lt 1 pi 0 pt 4 lw 4 ps 0

plot  "estimated.csv" using ($1):2 with lines title "Estimated", "actual.csv" using ($1):2 with lines title "Actual";

I wanted to interpolate my green line into the grid where my pink line is defined, then compare the two. Here is my initial approach

#!/usr/bin/env python
import sys

import numpy as np
from shapely.geometry import LineString
#-------------------------------------------------------------------------------
def load_data(fname):
    return LineString(np.genfromtxt(fname, delimiter = ','))
#-------------------------------------------------------------------------------
lines = list(map(load_data, sys.argv[1:]))

for g in lines[0].intersection(lines[1]):
    if g.geom_type != 'Point':
        continue
    print('%f,%f' % (g.x, g.y))
Then in Gnuplot, one can invoke it directly:

set terminal pngcairo
set output 'fig.png'

set datafile separator comma
set yr [0:700]
set xr [0:10]

set xtics 0,2,10
set ytics 0,100,700

set grid

set xlabel "Time [seconds]"
set ylabel "Segments"

plot \
    'estimated.csv' w l lc rgb 'dark-blue' t 'Estimated', \
    'actual.csv' w l lc rgb 'green' t 'Actual', \
    '<python filter.py estimated.csv actual.csv' w p lc rgb 'red' ps 0.5 pt 7 t ''

which gives us the following plot

I wrote the filtered points to another file (filtered_points.csv found in this link:https://drive.google.com/open?id=0B2Iv8dfU4fTUSHVOMzYySjVzZWc) from this script. However, the filtered points are less than 10% of the actual dataset (which is the ground truth).

Is there any way where we can interpolate the two lines by ignoring the pink high peaks above the green plot using python? Gnuplot doesn't seem to be the best tool for this. If the pink line doesn't touch the green line (i.e. if it is way below the green line), I want to take the values of the closest green line so that it will be a one-to-one correspondence (or very close) with the actual dataset. I want to return the interpolated values for the green line in the pink line grid so that we can compare both lines since they have the same array size.

Body:
Getting the same data size in terms of an interpolation is pretty simple by numpy.interp(). For me, this code works:

import numpy as np
import matplotlib.pyplot as plt

names = ['actual.csv','estimated.csv']
#-------------------------------------------------------------------------------
def load_data(fname):
    return np.genfromtxt(fname, delimiter = ',')
#-------------------------------------------------------------------------------

data = [load_data(name) for name in names]
actual_data = data[0]
estimated_data = data[1]
interpolated_estimation = np.interp(estimated_data[:,0],actual_data[:,0],actual_data[:,1])

plt.figure()
plt.plot(actual_data[:,0],actual_data[:,1], label='actual')
plt.plot(estimated_data[:,0],estimated_data[:,1], label='estimated')
plt.plot(estimated_data[:,0],interpolated_estimation, label='interpolated')
plt.legend()
plt.show(block=True)

After this interpolation interpolated_estimation has the same size as the x axis of actual_data, as the plot suggests. The slicing is a bit confusing but I tried to use your function and make the plot calls as clear as possible.

To save to a file and plot like suggested I changed the code to:

import numpy as np
import matplotlib.pyplot as plt

names = ['actual.csv','estimated.csv']
#-------------------------------------------------------------------------------
def load_data(fname):
    return np.genfromtxt(fname, delimiter = ',')
#-------------------------------------------------------------------------------

data = [load_data(name) for name in names]
actual_data = data[0]
estimated_data = data[1]
interpolated_estimation = np.interp(estimated_data[:,0],actual_data[:,0],actual_data[:,1])

plt.figure()
plt.plot(actual_data[:,0],actual_data[:,1], label='actual')
#plt.plot(estimated_data[:,0],estimated_data[:,1], label='estimated')
plt.plot(estimated_data[:,0],interpolated_estimation, label='interpolated')
np.savetxt('interpolated.csv',
       np.vstack((estimated_data[:,0],interpolated_estimation)).T,
       delimiter=',', fmt='%10.5f') #saves data to filedata to file
plt.legend()
plt.title('Actual vs. Interpolated')
plt.xlim(0,10)
plt.ylim(0,500)
plt.xlabel('Time [Seconds]')
plt.ylabel('Segments')
plt.grid()
plt.show(block=True)

This produces the following output:


问:
VarBinary vs Image SQL Server Data Type to Store Binary Data?
I need to store binary files to the SQL Server Database. Which is the better Data Type out of Varbinary and Image?</p>

答: varbinary(max) is the way to go (introduced in SQL Server 2005)

OwnerDisplayName: Yoann. B

OwnerDisplayName: SQLMenace


问:
Formatting Macro doesnt work on all worksheets
Below is part of my code that deals with formatting the output generated. So, to put it concisely, my macro pulls data from various sources, compares them and generates statistics like Market variance and catch-up etc. in multiple worksheets. What I need it to do is a format a range of cells as "Percentage" in all worksheets. What's happening is that the formatting only applies itself in the first worksheet generated and not in the subsequent worksheets. The part of code that formats into "comma" works fine on all sheets but not percentage.
I'm not really sure what the problem is. I've tried tweaking but with no success. I'm really pressed for time and need this to work as soon as possible, so I apologize in advance if this question exists already.
PFB code snippet:

```<code>ActiveWorkbook.Sheets.Select
Range(Cells(100, 2), Cells(142, MarketRangeColumn + 10)).Select
Selection.Style = "Comma"
Selection.numberformat = "_(* #,##0.0_);_(* (#,##0.0);_(* ""-""??_);_(@_)"
Selection.numberformat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(@_)"
Range(Cells(143, 2), Cells(146, MarketRangeColumn + 10)).Select
Selection.Style = "Percent"
</code>```

Thanks in advance guys!

答:
When you select all the sheets like that the code has no way to determine which sheet you want the code to run on (though your approach is logical VBA just doesn't work like that, in fact nearly all programming languages require you to specify the object you want to use), so it uses the first in the selection.

Use a for loop to move through the sheets. Also, you don't need to select something to act on it and you can use a With block to shorten the code a bit:

```<code>For s = 1 To Sheets.Count

    With Sheets(s).Range(Cells(100, 2), Cells(142, MarketRangeColumn + 10))
        .Style = "Comma"
        .NumberFormat = "_(* #,##0.0_);_(* (#,##0.0);_(* ""-""??_);_(@_)"
        .NumberFormat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(@_)"
    End With

    Sheets(s).Range(Cells(143, 2), Cells(146, MarketRangeColumn + 10)).Style = "Percent"

Next s
</code>```

Body:
Below is part of my code that deals with formatting the output generated. So, to put it concisely, my macro pulls data from various sources, compares them and generates statistics like Market variance and catch-up etc. in multiple worksheets. What I need it to do is a format a range of cells as "Percentage" in all worksheets. What's happening is that the formatting only applies itself in the first worksheet generated and not in the subsequent worksheets. The part of code that formats into "comma" works fine on all sheets but not percentage.
I'm not really sure what the problem is. I've tried tweaking but with no success. I'm really pressed for time and need this to work as soon as possible, so I apologize in advance if this question exists already.
PFB code snippet:

ActiveWorkbook.Sheets.Select
Range(Cells(100, 2), Cells(142, MarketRangeColumn + 10)).Select
Selection.Style = "Comma"
Selection.numberformat = "_(* #,##0.0_);_(* (#,##0.0);_(* ""-""??_);_(@_)"
Selection.numberformat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(@_)"
Range(Cells(143, 2), Cells(146, MarketRangeColumn + 10)).Select
Selection.Style = "Percent"

Thanks in advance guys!

Body:
When you select all the sheets like that the code has no way to determine which sheet you want the code to run on (though your approach is logical VBA just doesn't work like that, in fact nearly all programming languages require you to specify the object you want to use), so it uses the first in the selection.

Use a for loop to move through the sheets. Also, you don't need to select something to act on it and you can use a With block to shorten the code a bit:

For s = 1 To Sheets.Count

    With Sheets(s).Range(Cells(100, 2), Cells(142, MarketRangeColumn + 10))
        .Style = "Comma"
        .NumberFormat = "_(* #,##0.0_);_(* (#,##0.0);_(* ""-""??_);_(@_)"
        .NumberFormat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(@_)"
    End With

    Sheets(s).Range(Cells(143, 2), Cells(146, MarketRangeColumn + 10)).Style = "Percent"

Next s


问:
asyncio as_yielded from async generators
I'm looking to be able to yield from a number of async coroutines. Asyncio's as_completed is kind of close to what I'm looking for (i.e. I want any of the coroutines to be able to yield at any time back to the caller and then continue), but that only seems to allow regular coroutines with a single return.

Here's what I have so far:

```<code>import asyncio

async def test(id_):
    print(f'{id_} sleeping')
    await asyncio.sleep(id_)
    return id_

async def test_gen(id_):
    count = 0
    while True:
        print(f'{id_} sleeping')
        await asyncio.sleep(id_)
        yield id_
        count += 1
        if count > 5:
            return

async def main():
    runs = [test(i) for i in range(3)]

    for i in asyncio.as_completed(runs):
        i = await i
        print(f'{i} yielded')

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()
</code>```

Replacing runs = [test(i) for i in range(3)] with runs = [test_gen(i) for i in range(3)] and for for i in asyncio.as_completed(runs) to iterate on each yield is what I'm after.

Is this possible to express in Python and are there any third party maybe that give you more options then the standard library for coroutine process flow?

Thanks

答:
You can use aiostream.stream.merge:

```<code>from aiostream import stream

async def main():
    runs = [test_gen(i) for i in range(3)]
    async for x in stream.merge(*runs):
        print(f'{x} yielded')
</code>```

Run it in a safe context to make sure the generators are cleaned up properly after the iteration:

```<code>async def main():
    runs = [test_gen(i) for i in range(3)]
    merged = stream.merge(*runs)
    async with merged.stream() as streamer:
        async for x in streamer:
            print(f'{x} yielded')
</code>```

Or make it more compact using pipes:

```<code>from aiostream import stream, pipe

async def main():
    runs = [test_gen(i) for i in range(3)]
    await (stream.merge(*runs) | pipe.print('{} yielded'))
</code>```

More examples in the documentation.

Adressing @nirvana-msu comment

It is possible to identify the generator that yielded a given value by preparing sources accordingly:

```<code>async def main():
    runs = [test_gen(i) for i in range(3)]
    sources = [stream.map(xs, lambda x: (i, x)) for i, xs in enumerate(runs)]
    async for i, x in stream.merge(*sources):
        print(f'ID {i}: {x}')
</code>```

Body:
I'm looking to be able to yield from a number of async coroutines. Asyncio's as_completed is kind of close to what I'm looking for (i.e. I want any of the coroutines to be able to yield at any time back to the caller and then continue), but that only seems to allow regular coroutines with a single return.

Here's what I have so far:

import asyncio

async def test(id_):
    print(f'{id_} sleeping')
    await asyncio.sleep(id_)
    return id_

async def test_gen(id_):
    count = 0
    while True:
        print(f'{id_} sleeping')
        await asyncio.sleep(id_)
        yield id_
        count += 1
        if count > 5:
            return

async def main():
    runs = [test(i) for i in range(3)]

    for i in asyncio.as_completed(runs):
        i = await i
        print(f'{i} yielded')

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()

Replacing runs = [test(i) for i in range(3)] with runs = [test_gen(i) for i in range(3)] and for for i in asyncio.as_completed(runs) to iterate on each yield is what I'm after.

Is this possible to express in Python and are there any third party maybe that give you more options then the standard library for coroutine process flow?

Thanks

Body:
You can use aiostream.stream.merge:

from aiostream import stream

async def main():
    runs = [test_gen(i) for i in range(3)]
    async for x in stream.merge(*runs):
        print(f'{x} yielded')

Run it in a safe context to make sure the generators are cleaned up properly after the iteration:

async def main():
    runs = [test_gen(i) for i in range(3)]
    merged = stream.merge(*runs)
    async with merged.stream() as streamer:
        async for x in streamer:
            print(f'{x} yielded')

Or make it more compact using pipes:

from aiostream import stream, pipe

async def main():
    runs = [test_gen(i) for i in range(3)]
    await (stream.merge(*runs) | pipe.print('{} yielded'))

More examples in the documentation.

Adressing @nirvana-msu comment

It is possible to identify the generator that yielded a given value by preparing sources accordingly:

async def main():
    runs = [test_gen(i) for i in range(3)]
    sources = [stream.map(xs, lambda x: (i, x)) for i, xs in enumerate(runs)]
    async for i, x in stream.merge(*sources):
        print(f'ID {i}: {x}')


问:
R get all rows that have at least one number in each decade from 0 to 99
Having the following matrix:

```<code>     [,1] [,2] [,3] [,4]  [,5]  [,6]  [,7]  [,8]  [,9]  [,10]  [,11]  [,12]
[1,]   23   14   17   10     2     6    90    45    56     25     11      9
[2,]    1   15   18   21    32    46    55    50    61     73     81     93
[3,]   56   19   98   23    42     7     8    25    61     54     22     38
</code>```

I want to get only the rows that have at least 1 number in each of 10 decades from 1 to 99
 So the result must be:

```<code>[1] False
[2] True
[3] False
</code>```

Finally we get only [2] that satisfies the condition. Can you please provide an R language function which can generate this result?

Regards,
Dimitris

Body:
Having the following matrix:

     [,1] [,2] [,3] [,4]  [,5]  [,6]  [,7]  [,8]  [,9]  [,10]  [,11]  [,12]
[1,]   23   14   17   10     2     6    90    45    56     25     11      9
[2,]    1   15   18   21    32    46    55    50    61     73     81     93
[3,]   56   19   98   23    42     7     8    25    61     54     22     38

I want to get only the rows that have at least 1 number in each of 10 decades from 1 to 99
 So the result must be:

[1] False
[2] True
[3] False

Finally we get only [2] that satisfies the condition. Can you please provide an R language function which can generate this result?

Regards,
Dimitris

Body:
We can do

apply(m1, 1, function(x) length(unique(x %/%10))==10)
#[1] FALSE  TRUE FALSE

data

m1 <- structure(c(23, 1, 6, 14, 15, 19, 17, 18, 98, 10, 21, 23, 2,
32, 42, 6, 46, 7, 90, 35, 8, 45, 50, 25, 56, 61, 61, 25, 73,
54, 11, 81, 22, 9, 93, 38), .Dim = c(3L, 12L))


问:
Android, Random created list content opening a new activity
Good day, i have a question about android that my teacher couldn't answer and i couldn't really find an answer.

Example Program: Shopping List

I Want to create a program where i can press a button and create a new list with whatever name i choose, for example List A then i press it again, List B and so on, until that point it's quite easy, my doubt is how can i create with that push of a button a new List that opens an activity with that given name with a specific template, for example i press List A and it opens an activity for List A with the same template for List B but without the content the data being shared by lists or me having to create the list manualy on the code.

答:
You can use extras for that.
From the activity where you are in the beginning you create a new Intent like this:

```<code>Intent intent = new Intent(NameOfFirstActivity.this, NameOfListActivity.class);
</code>```

Then you can put an extra to that intent:

```<code>intent.putExtra("listname", "ListA");
</code>```

After that you start the activity:

```<code>startActivity(intent);
</code>```

On the second activity you can get the extra you put in by calling this:

```<code>String listname = getIntent().getStringExtra("listname");
</code>```

Then you can check what the listname is and then display different data for list A and list B.

Note: When you put an extra and when you get it you have to use the same String as the name. In this case the extra name is "listname" but you can use everything else too.

Body:
You can use extras for that.
From the activity where you are in the beginning you create a new Intent like this:

Intent intent = new Intent(NameOfFirstActivity.this, NameOfListActivity.class);

Then you can put an extra to that intent:

intent.putExtra("listname", "ListA");

After that you start the activity:

startActivity(intent);

On the second activity you can get the extra you put in by calling this:

String listname = getIntent().getStringExtra("listname");

Then you can check what the listname is and then display different data for list A and list B.

Note: When you put an extra and when you get it you have to use the same String as the name. In this case the extra name is "listname" but you can use everything else too.


问:
Why does cancelling a DetailsView update as part of a wizard clear the form?
I want to make sure an item in DetailsView2 is equal to 0 before committing any changes in DetailsView1 to the DB. But I just want to report an error and allow the user to continue editing. Currently, clicking "Update" in DetailsView1 clears the page.

Here's the code behind:

```<code>protected void DetailsView1_Updating(object sender, DetailsViewUpdateEventArgs e)
{
    if (DetailsView2.Rows[0].Cells[1].Text != "0")
    {
        DetailsView2.Rows[1].Cells[1].Visible = true;  // Display error message
        e.Cancel = true;
    }
}
</code>```

Here's the frontend:

```<code><asp:DetailsView
    ID="DetailsView1"
    runat="server"
    AutoGenerateRows="False"
    DataSourceID="ObjectDataSource1"
    DefaultMode="Edit"
    OnItemUpdating="DetailsView1_Updating">
    ...
</code>```

Both these DetailViews are part of a wizard, but I'm not certain that makes any difference.

答:
Turns out there was a listener on the ItemCommand event clearing the ID of the object the form was designed to edit. Since that ID gets overwritten anyway when a new object is selected in the wizard, I simply removed that logic. Now data stays in place after validation so that it can be fixed if validation fails.

For what it's worth, I found the errant event handler by setting a break point on every method in the codebehind and just watching the command flow.

Body:
I want to make sure an item in DetailsView2 is equal to 0 before committing any changes in DetailsView1 to the DB. But I just want to report an error and allow the user to continue editing. Currently, clicking "Update" in DetailsView1 clears the page.

Here's the code behind:

protected void DetailsView1_Updating(object sender, DetailsViewUpdateEventArgs e)
{
    if (DetailsView2.Rows[0].Cells[1].Text != "0")
    {
        DetailsView2.Rows[1].Cells[1].Visible = true;  // Display error message
        e.Cancel = true;
    }
}

Here's the frontend:

<asp:DetailsView
    ID="DetailsView1"
    runat="server"
    AutoGenerateRows="False"
    DataSourceID="ObjectDataSource1"
    DefaultMode="Edit"
    OnItemUpdating="DetailsView1_Updating">
    ...

Both these DetailViews are part of a wizard, but I'm not certain that makes any difference.


问:
WinPE with Powershell GUI boot into iso-files
I have created a USB-drive with WinPE and I created a Powershell script with GUI which is automatically loaded. It has a button to open CMD, a reboot and a shutdown button.

I want to be able to run Memtest from my menu, by booting its ISO file.

I have added the Imdrive to my WinPE and I am able to mount the ISO but I don´t know how to run it?

答:
As Memtest boots its own version of Linux you'll need to use a boot manager to be able to boot multiple OS's as you can't run Linux within WinPE.

Something like rEFInd would make this easier for you (small tutorial on using rEFInd).

Personally, I would just use Hirens BootCD as it will already contain everything you'd ever need.