问:
Add item to a list in a dict
I have a program that works as intended:

```<code>import os
import hashlib
from pprint import pprint

def md5(fname):
    hash_md5 = hashlib.md5()
    with open(fname, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

lst = []
for dirpath, dirnames, filenames in os.walk('d:\\python\\exercism.io'):
    d = {dirpath: filenames}
    for filename in filenames:
        d[filename] = [os.stat(dirpath).st_mtime, md5(dirpath + '\\' + filename)]
        # d[filename] = [os.stat(dirpath).st_mtime]
        # d[filename] = [md5(dirpath + '\\' + filename)]
    lst.append(d)

pprint(lst)
</code>```

My question is this:

If I get rid of this line:

```<code>        d[filename] = [os.stat(dirpath).st_mtime, md5(dirpath + '\\' + filename)]
</code>```

and try to use the two commented out lines (with a modification -- see below) it fails.

1)  Either commented out line works by themselves.  I get a key: value pair in which the value is a list.

I then want to add the value of the second commented out line to the list.

I was trying this:

```<code>        d[filename][1] = md5(dirpath + '\\' + filename)
</code>```

but I get an index out of range error.  The first element of the list
should be item [0], the second should be [1].

Partial output:

```<code>[{'ceasar_cipher.py': [1512494094.5630972, '844e069c90ebdb3e1e5f5dd56da2ac2e'],
  'd:\\python\\exercism.io': ['ceasar_cipher.py',
                              'difference_of_squares.py',
                              'gigasecond.py',
                              'grains_in_python.py',
                              'hamming-compare.py',
                              'isogram.py',
                              'leap_year.py',
                              'rna_transcription.py',
                              'run_length_encoding.py'],
</code>```

Note the key: 'ceasar_cipher.py' has a value which is a two element list.

I want to construct the exact same output with the two commented out lines
versus the single line I am using now (just so I can, not that I should). My concern is simply what am I doing wrong.

答:
You need to append to your list:

```<code>d[filename] = [os.stat(dirpath).st_mtime]
d[filename].append(md5(dirpath + '\\' + filename))
</code>```

to get the same effect. There is no item at index 1 yet. You need to create it, for example with append().

Title: Add item to a list in a dict

Body:
I have a program that works as intended:

import os
import hashlib
from pprint import pprint

def md5(fname):
    hash_md5 = hashlib.md5()
    with open(fname, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

lst = []
for dirpath, dirnames, filenames in os.walk('d:\\python\\exercism.io'):
    d = {dirpath: filenames}
    for filename in filenames:
        d[filename] = [os.stat(dirpath).st_mtime, md5(dirpath + '\\' + filename)]
        # d[filename] = [os.stat(dirpath).st_mtime]
        # d[filename] = [md5(dirpath + '\\' + filename)]
    lst.append(d)

pprint(lst)

My question is this:

If I get rid of this line:

        d[filename] = [os.stat(dirpath).st_mtime, md5(dirpath + '\\' + filename)]

and try to use the two commented out lines (with a modification -- see below) it fails.

1)  Either commented out line works by themselves.  I get a key: value pair in which the value is a list.

I then want to add the value of the second commented out line to the list.

I was trying this:

        d[filename][1] = md5(dirpath + '\\' + filename)

but I get an index out of range error.  The first element of the list
should be item [0], the second should be [1].

Partial output:

[{'ceasar_cipher.py': [1512494094.5630972, '844e069c90ebdb3e1e5f5dd56da2ac2e'],
  'd:\\python\\exercism.io': ['ceasar_cipher.py',
                              'difference_of_squares.py',
                              'gigasecond.py',
                              'grains_in_python.py',
                              'hamming-compare.py',
                              'isogram.py',
                              'leap_year.py',
                              'rna_transcription.py',
                              'run_length_encoding.py'],

Note the key: 'ceasar_cipher.py' has a value which is a two element list.

I want to construct the exact same output with the two commented out lines
versus the single line I am using now (just so I can, not that I should). My concern is simply what am I doing wrong.

Body:
You need to append to your list:

d[filename] = [os.stat(dirpath).st_mtime]
d[filename].append(md5(dirpath + '\\' + filename))

to get the same effect. There is no item at index 1 yet. You need to create it, for example with append().


来源: stackexchange

问:
Scala cake pattern and multiproject
In common-project I have this:

```<code>trait DBProvider
trait DBTableNamesProvider
trait DefaultDBProvider extends DBProvider
trait DefaultTableNames extends  DBTableNamesProvider

trait MyService extends DBProvider with DBTableNamesProvider

object MyService {
  def apply() = new MyService with DefaultDBProvider with DefaultTableNames {}
}
</code>```

In projectA which has a reference to common-project as a jar I wish to construct MyService

projectA (has dependency on common-project):

```<code>object MyOtherApp {
  trait MyOtherTableName extends DBTableNamesProvider
  val MyCustomService = MyService() with MyOtherTableName // will not compile how to reuse the module's MyService() with another implementation of one of the traits?
}
</code>```

The above will not compile I cannot just call MyService() construction and override some of the dependencies.

The above is what I wish to do, I wish to override from a different project the factory construction of MyService() apply with my own implementation of MyProjectATableNames is that possible in scala? if not what is the recommended way without code repetition?

答:
```<code> val MyCustomService = new MyService() with MyOtherTableName
</code>```

should work

If you want to also inherit from the DefaultDBProvider and DefaultTableNames, you would have to either list them explicitly as well:

```<code>val MyCustomService = new MyService() with MyOtherTableName with DefaultDBProvider with DefaultTableNames
</code>```

or create an intermediate trait in the common library:

```<code>trait DefaultService extends MyService with DefaultDBProvider with DefaultTableNames
</code>```

ContentLicense: CC BY-SA 3.0

Title: Scala cake pattern and multiproject

Body:
In common-project I have this:

trait DBProvider
trait DBTableNamesProvider
trait DefaultDBProvider extends DBProvider
trait DefaultTableNames extends  DBTableNamesProvider

trait MyService extends DBProvider with DBTableNamesProvider

object MyService {
  def apply() = new MyService with DefaultDBProvider with DefaultTableNames {}
}

In projectA which has a reference to common-project as a jar I wish to construct MyService

projectA (has dependency on common-project):

object MyOtherApp {
  trait MyOtherTableName extends DBTableNamesProvider
  val MyCustomService = MyService() with MyOtherTableName // will not compile how to reuse the module's MyService() with another implementation of one of the traits?
}

The above will not compile I cannot just call MyService() construction and override some of the dependencies.

The above is what I wish to do, I wish to override from a different project the factory construction of MyService() apply with my own implementation of MyProjectATableNames is that possible in scala? if not what is the recommended way without code repetition?

Body:
 val MyCustomService = new MyService() with MyOtherTableName

should work

If you want to also inherit from the DefaultDBProvider and DefaultTableNames, you would have to either list them explicitly as well:

val MyCustomService = new MyService() with MyOtherTableName with DefaultDBProvider with DefaultTableNames

or create an intermediate trait in the common library:

trait DefaultService extends MyService with DefaultDBProvider with DefaultTableNames


问:
spring data mongodb 1.8.x - GridFS collection name in XML
is possible modify collection name of gridfs target in configuration XML? Default name is "fs.files"

this is a configuration file:

```<code>    <mongo:repositories base-package="it.marcoberri.repositories" />

    <mongo:mongo host="${mongo.db.server}" port="${mongo.db.port}" />

    <mongo:db-factory dbname="${mongo.db.name}" mongo-ref="mongo"
        id="mongoDbFactory" />

    <mongo:mapping-converter id="converter" />

    <bean class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
        <constructor-arg ref="mongoDbFactory" />
        <constructor-arg ref="converter" />
    </bean>

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="mongo" />
        <constructor-arg name="databaseName" value="${mongo.db.name}" />
    </bean>

</beans>
</code>```

答:
Should be:

```<code>  <bean class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
        <constructor-arg ref="mongoDbFactory" />
        <constructor-arg ref="converter" />
        <constructor-arg name="bucket" value="NameOsTheFsCollection" />
  </bean>
</code>```

If you have more than one collection of Gridfs type and want to have different names for each one, you must declare one GridFsTemplate for each, using this approach.

Body:
is possible modify collection name of gridfs target in configuration XML? Default name is "fs.files"

this is a configuration file:

    <mongo:repositories base-package="it.marcoberri.repositories" />

    <mongo:mongo host="${mongo.db.server}" port="${mongo.db.port}" />

    <mongo:db-factory dbname="${mongo.db.name}" mongo-ref="mongo"
        id="mongoDbFactory" />

    <mongo:mapping-converter id="converter" />

    <bean class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
        <constructor-arg ref="mongoDbFactory" />
        <constructor-arg ref="converter" />
    </bean>

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="mongo" />
        <constructor-arg name="databaseName" value="${mongo.db.name}" />
    </bean>

</beans>

Body:
Should be:

  <bean class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
        <constructor-arg ref="mongoDbFactory" />
        <constructor-arg ref="converter" />
        <constructor-arg name="bucket" value="NameOsTheFsCollection" />
  </bean>

If you have more than one collection of Gridfs type and want to have different names for each one, you must declare one GridFsTemplate for each, using this approach.


问:
SQL add a counter row
I'd like to add a counter to my website.

I am currently using php and mysql.

An example would be a total count of people who logged in my website.

The structure would look like this

```<code>|Total User Logins|
|                1|
</code>```

If a user logs in though, I'd like to do this

```<code>|Total User Logins|
|                2|
</code>```

How would I do this? At the moment it only creates a new row, which is not what I am after.

This is what I tried to do:

```<code>mysql_query(" UPDATE `Statistics` SET `Success`= `Success` + 1 WHERE 1 ");
</code>```

^ this works on the phpmyadmin panel. But does not work on the php script.

Thanks

答:
You need to be more specific in the WHERE clause, as to the specific column that is to be updated. That's why your code failed you and is creating a new row each time.

I.e.:

```<code>mysql_query(" UPDATE `Statistics` SET `Success`= `Success` + 1 WHERE column_x = 'y' ");
</code>```

Side note: column_x could be User as per what you posted for column names. I didn't see one called Success. The y is an example also. Use the value from the given row you wish to update.

This is purely an example, given you seem to have left out some important details.

By the way, the api you're using is quite old. It is recommended that you move over to either the mysqli_ or PDO api as soon as possible and preferably with a prepared statement. This will help safeguard against a possible SQL injection should user input be involved or any other method such as an href through a GET method.

Title: SQL add a counter row

Body:
I'd like to add a counter to my website.

I am currently using php and mysql.

An example would be a total count of people who logged in my website.

The structure would look like this

|Total User Logins|
|                1|

If a user logs in though, I'd like to do this

|Total User Logins|
|                2|

How would I do this? At the moment it only creates a new row, which is not what I am after.

This is what I tried to do:

mysql_query(" UPDATE `Statistics` SET `Success`= `Success` + 1 WHERE 1 ");

^ this works on the phpmyadmin panel. But does not work on the php script.

Thanks

Body:
You need to be more specific in the WHERE clause, as to the specific column that is to be updated. That's why your code failed you and is creating a new row each time.

I.e.:

mysql_query(" UPDATE `Statistics` SET `Success`= `Success` + 1 WHERE column_x = 'y' ");

Side note: column_x could be User as per what you posted for column names. I didn't see one called Success. The y is an example also. Use the value from the given row you wish to update.

This is purely an example, given you seem to have left out some important details.

By the way, the api you're using is quite old. It is recommended that you move over to either the mysqli_ or PDO api as soon as possible and preferably with a prepared statement. This will help safeguard against a possible SQL injection should user input be involved or any other method such as an href through a GET method.


问:
UIButton appearance also sets keyboard buttons
While I was trying to clean up some code I wanted to use appearances of views. But the UIButton troubles me. I tried the following:

```<code>[[UIButton appearanceWhenContainedInInstancesOfClasses:@[[UIViewController class]]] setBackgroundColor:[UIColor redColor]];
[[UIButton appearanceWhenContainedInInstancesOfClasses:@[[UIViewController class]]] setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
</code>```

This works like expected and all my buttons turned red with blue colour (in my project I used other colours). I noticed the buttons in the navigation bar also turned, which is something I rather not have so adding this line fixed this first problem:

```<code>[[UIButton appearanceWhenContainedInInstancesOfClasses:@[[UINavigationBar class], [UIViewController class]]] setBackgroundColor:[UIColor clearColor]];
</code>```

But these aren't the only buttons. The keyboard buttons (the undo, redo and paste) on the iPad also have other appearances than default. Is there any way I can fix this? Also, is there a list of appearances that I can use safely without 'breaking' other views (like in this case the keyboard buttons)? I am not talking about a list off all appearances as I have found this here.

The idea was to select only the buttons in my UIViewController (which contains also the navigation bar) but apparently the keyboard is also child of the UIViewController. I hope there is a way without the need of adding custom views or wrappers around the buttons.

答:
Create MyBaseViewController as a subclass to UIViewController, with an empty implementation. Change all of your viewControllers to inherit from MyBaseViewController. Change your calls to appearanceWhenContainedInInstancesOfClasses method to reference MyBaseViewController.

Your current code will affect all instances of UIViewController, including those embedded in Foundation or UIKit. By using your own base class, you are in effect creating a filter that isolates your viewControllers from the others.

Body:
While I was trying to clean up some code I wanted to use appearances of views. But the UIButton troubles me. I tried the following:

[[UIButton appearanceWhenContainedInInstancesOfClasses:@[[UIViewController class]]] setBackgroundColor:[UIColor redColor]];
[[UIButton appearanceWhenContainedInInstancesOfClasses:@[[UIViewController class]]] setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];

This works like expected and all my buttons turned red with blue colour (in my project I used other colours). I noticed the buttons in the navigation bar also turned, which is something I rather not have so adding this line fixed this first problem:

[[UIButton appearanceWhenContainedInInstancesOfClasses:@[[UINavigationBar class], [UIViewController class]]] setBackgroundColor:[UIColor clearColor]];

But these aren't the only buttons. The keyboard buttons (the undo, redo and paste) on the iPad also have other appearances than default. Is there any way I can fix this? Also, is there a list of appearances that I can use safely without 'breaking' other views (like in this case the keyboard buttons)? I am not talking about a list off all appearances as I have found this here.

The idea was to select only the buttons in my UIViewController (which contains also the navigation bar) but apparently the keyboard is also child of the UIViewController. I hope there is a way without the need of adding custom views or wrappers around the buttons.


问:
How to know if data was persisted during database transaction after method returning?
I have a method written in a Grails service, which processes a lot of data.

I noticed that, sometimes, the method returns success but the data is not persisted to the database.

I debugged it, following all the data till the end of the method and everything is fine, however data is not persisted.

The following image demonstrates the what I just explained. You can see the end of the method, in which a Map object is filled with persistent object metadata. Even you can see the console which contains the printend Hibertate SQL

How can I detect whether a rollback mechanism is thrown after successful method returning?

This is my connection properties for Oracle 12c database. Others configurations are Grails defaults

```<code>dataSource.pooled=true
hibernate.jdbc.use_get_generated_keys=true
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=false
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
dataSource.driverClassName=oracle.jdbc.driver.OracleDriver
dataSource.dialect=org.hibernate.dialect.OracleDialect

dataSource.url=jdbc:oracle:thin:@172.16.1.20:1521:db
dataSource.username=<USER>
dataSource.password=<PASS>
hibernate.default_schema=<SCHEMA>
</code>```

The service is anotated as @Transactional

```<code>@Transactional
class SincronizacionService {

}
</code>```

Any Idea?

答:
When using GORM's save method, also use failOnError:true. By default, save method silently fails. However, if you use failOnError:true, it will throw an exception if the data is not persisted.

If you do not want to stop the program when the data fails to save, you can use the try-catch block to log data that failed to save and let the algorithm continue to do it work.

Hope that helps.

Body:
I have a method written in a Grails service, which processes a lot of data.

I noticed that, sometimes, the method returns success but the data is not persisted to the database.

I debugged it, following all the data till the end of the method and everything is fine, however data is not persisted.

The following image demonstrates the what I just explained. You can see the end of the method, in which a Map object is filled with persistent object metadata. Even you can see the console which contains the printend Hibertate SQL

How can I detect whether a rollback mechanism is thrown after successful method returning?

This is my connection properties for Oracle 12c database. Others configurations are Grails defaults

dataSource.pooled=true
hibernate.jdbc.use_get_generated_keys=true
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=false
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
dataSource.driverClassName=oracle.jdbc.driver.OracleDriver
dataSource.dialect=org.hibernate.dialect.OracleDialect

dataSource.url=jdbc:oracle:thin:@172.16.1.20:1521:db
dataSource.username=<USER>
dataSource.password=<PASS>
hibernate.default_schema=<SCHEMA>

The service is anotated as @Transactional

@Transactional
class SincronizacionService {

}

Any Idea?


问:
Search field and button
I have a search field and a button beside. It works totally fine and everything. But on mobile when you type in something and click on the phones keyboard "search" it goes to 404 error. But when i type in something and click on the "search button" it works. I just want to also to be able to click "search" on the phones keyboard without it going to 404.

This is my search field and button:

```<code><div id="search" class="search" style="margin-left: 20px;">
<input class="form-control" type="text" placeholder="Hvad leder du efter?.." name="search" value="<?php if(isset($search)) echo $search; ?>" />
<button type="submit" class="button-search"></button>
</code>```

I just dont understand why the "search button" works and not the "search" on phone keyboard

答:
Insert an additional hidden submit into the form.</p>

```<code><input type="submit" style="display: none"/>
</code>```

Title: Search field and button

Body:
I have a search field and a button beside. It works totally fine and everything. But on mobile when you type in something and click on the phones keyboard "search" it goes to 404 error. But when i type in something and click on the "search button" it works. I just want to also to be able to click "search" on the phones keyboard without it going to 404.

This is my search field and button:

<input class="form-control" type="text" placeholder="Hvad leder du efter?.." name="search" value="<?php if(isset($search)) echo $search; ?>" />
<button type="submit" class="button-search"></button>

I just dont understand why the "search button" works and not the "search" on phone keyboard

Body:
Insert an additional hidden submit into the form.

<input type="submit" style="display: none"/>


问:
WPF Manipulation in Windows 8.1
Can anyone provide a few links to examples of how to do Manipulation in Windows 8.1, please?

I see many examples online of how to do it for Windows 7, but it doesn't work for me on my Windows 8.1 machine (with touchscreen).  I'm using VS Studio Community v15.  Here's the example that I've been trying:

https://www.tutorialspoint.com/wpf/wpf_multi_touch.htm

Using either the mouse or fingers doesn't make anything happen at all - no movement, no scaling, no rotation, etc.

P.S., I'm doing my project in VB, not C#.

For example,

```<code><Window x:Class = "WpfManipulation1.MainWindow"
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
   xmlns:local = "clr-namespace:WpfManipulation1"
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604">

    <Window.Resources>
        <MatrixTransform x:Key = "InitialMatrixTransform">
            <MatrixTransform.Matrix>
                <Matrix OffsetX = "200" OffsetY = "200"/>
            </MatrixTransform.Matrix>
        </MatrixTransform>
    </Window.Resources>

    <Canvas>
        <Rectangle Name = "manRect" Width = "321" Height = "241"
         RenderTransform = "{StaticResource InitialMatrixTransform}"
         IsManipulationEnabled = "true" Canvas.Left = "-70" Canvas.Top = "-170">
            <Rectangle.Fill>
                <ImageBrush ImageSource = "ManipImage.JPG"/>
            </Rectangle.Fill>
        </Rectangle>
        <Image Source="ManipImage.jpg" ManipulationMode="All" ManipulationDelta="UIElement_OnManipulationDelta" />
    </Canvas>

</Window>
</code>```

Partial success with...
XAML:

```<code><Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfManipulation2"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Image Source="ManipImage.jpg" IsManipulationEnabled="True" ManipulationDelta="OnManipulationDelta" />
    </Grid>
</Window>
</code>```

VB Code-Behind:

```<code>Imports System.Windows.UIElement

Class MainWindow

    Private Sub OnManipulationDelta(ByVal sender As Object, ByVal e As ManipulationDeltaEventArgs)
        Dim transformGroup = GetTransformGroup(sender)
        Dim translateTransform = transformGroup.Children.OfType(Of TranslateTransform).First
        Dim rotateTransform = transformGroup.Children.OfType(Of RotateTransform).First
        Dim scaleTransform = transformGroup.Children.OfType(Of ScaleTransform).First
        translateTransform.X = (translateTransform.X + e.DeltaManipulation.Translation.X)
        translateTransform.Y = (translateTransform.Y + e.DeltaManipulation.Translation.Y)
        rotateTransform.Angle = (rotateTransform.Angle + e.DeltaManipulation.Rotation)
        scaleTransform.ScaleY = (scaleTransform.ScaleY * e.DeltaManipulation.Scale.Y)
        scaleTransform.ScaleX = (scaleTransform.ScaleX * e.DeltaManipulation.Scale.X)
    End Sub

    Private Function GetTransformGroup(ByVal sender As Object) As TransformGroup
        Dim element = CType(sender, UIElement)
        element.RenderTransformOrigin = New Point(0.5, 0.5)
        Dim transformGroup = CType(element.RenderTransform, TransformGroup)
        If (transformGroup Is Nothing) Then
            transformGroup = New TransformGroup
            transformGroup.Children.Add(New TranslateTransform)
            transformGroup.Children.Add(New ScaleTransform)
            transformGroup.Children.Add(New RotateTransform)
            element.RenderTransform = transformGroup
        End If

        Return transformGroup
    End Function

End Class
</code>```

Error on line "Dim transformGroup = CType(element.RenderTransform, TransformGroup)": System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Media.MatrixTransform' to type 'System.Windows.Media.TransformGroup'.'

Here's the result of implementing the advice provided.

XAML:

```<code><Window x:Class="WpfTutorialSamples.Common_interface_controls.ToolbarSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ToolbarSample"
        Top="50" Left="50" Height="500" Width="700">
    <Window.CommandBindings>
        <CommandBinding Command="New" CanExecute="CommonCommandBinding_CanExecute" />
        <CommandBinding Command="Open" CanExecute="CommonCommandBinding_CanExecute" />
        <CommandBinding Command="Save" CanExecute="CommonCommandBinding_CanExecute" />
    </Window.CommandBindings>
    <Window.Resources>
        <MatrixTransform x:Key = "InitialMatrixTransform">
            <MatrixTransform.Matrix>
                <Matrix OffsetX = "0" OffsetY = "0"/>
            </MatrixTransform.Matrix>
        </MatrixTransform>
    </Window.Resources>
    <Grid x:Name="grid_MainWindow" Margin="0,0,0,0">
        <DockPanel>
            <ToolBarTray x:Name="myToolBarTray" DockPanel.Dock="Top" Panel.ZIndex="1">
                <!--
                <ToolBar>
                    <Button Command="New" Content="New" />
                    <Button Command="Open" Content="Open" />
                    <Button Command="Save" Content="Save" />
                </ToolBar>
                <ToolBar>
                    <Button Command="Cut" Content="Cut" />
                    <Button Command="Copy" Content="Copy" />
                    <Button Command="Paste" Content="Paste" />
                </ToolBar>
                -->
                <ToolBar x:Name="myToolBar" Height="30">
                    <Button Name="button_HideWindows" Content="Un/Hide" />
                    <Button Name="button_ClearWindows" Content="Clear" />
                    <Button Name="button_ResetMatrix" Content="Reset" />
                </ToolBar>
            </ToolBarTray>
            <!-- <TextBox AcceptsReturn="True" /> -->
            <!-- <Canvas x:Name="canvas_Main"/> -->
            <Canvas x:Name="canvas_Main" Background="LightPink" >
                <!--
                <Rectangle Name = "manRect" Width = "300" Height = "300"
                           HorizontalAlignment="Left"
                           VerticalAlignment="Top"
                           Margin="0,0,0,0"
                IsManipulationEnabled="True" ManipulationDelta="Window_ManipulationDelta"
                RenderTransform = "{StaticResource InitialMatrixTransform}"
                >
                    <Rectangle.Fill>
                        <SolidColorBrush Color="LightBlue" />
                    </Rectangle.Fill>
                </Rectangle>
                -->
                <Canvas Name = "manRect" Width = "300" Height = "300"
                           HorizontalAlignment="Left"
                           VerticalAlignment="Top"
                           Margin="0,0,0,0"
                IsManipulationEnabled="True" ManipulationDelta="Window_ManipulationDelta"
                RenderTransform = "{StaticResource InitialMatrixTransform}"
                        Background="LightBlue"
                >
                </Canvas>
                <Label x:Name="label_ZoomIn" Content="ZIn" Canvas.Left="330" Canvas.Top="370" Background="LightSkyBlue"/>
                <Label x:Name="label_ZoomOut" Content="ZOut" Canvas.Left="330" Canvas.Top="400" Background="LightSkyBlue"/>
            </Canvas>
        </DockPanel>

        <StackPanel x:Name="stackpanel_NW" Background="LightYellow" HorizontalAlignment="Left" Margin="0,30,0,0" VerticalAlignment="Top"  Height="100" Width="300">
            <Grid x:Name="grid_NW">
                <TextBox x:Name="textbox_NW" Background="LightYellow" BorderThickness="0" AcceptsReturn="True" Height="90" Width="290" Margin="5,5,5,5" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" />
            </Grid>
        </StackPanel>
        <StackPanel x:Name="stackpanel_NE" Background="LightYellow" HorizontalAlignment="Right" Margin="0,30,0,0" VerticalAlignment="Top"  Height="300" Width="300">
            <Grid x:Name="grid_NE">
                <TextBox x:Name="textbox_NE" Background="LightYellow" BorderThickness="0" AcceptsReturn="True" Height="290" Width="290" Margin="5,5,5,5" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" />
            </Grid>
        </StackPanel>
        <StackPanel x:Name="stackpanel_SW" Background="LightYellow" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Bottom"  Height="100" Width="300">
            <Grid x:Name="grid_SW">
                <TextBox x:Name="textbox_SW" Background="LightYellow" BorderThickness="0" AcceptsReturn="True" Height="90" Width="290" Margin="5,5,5,5" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" />
            </Grid>
        </StackPanel>
        <StackPanel x:Name="stackpanel_SE" Background="LightYellow" HorizontalAlignment="Right" Margin="0,0,0,0" VerticalAlignment="Bottom"  Height="100" Width="300">
            <Grid x:Name="grid_SE">
                <TextBox x:Name="textbox_SE" Background="LightYellow" BorderThickness="0" AcceptsReturn="True" Height="90" Width="290" Margin="5,5,5,5" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" />
            </Grid>
        </StackPanel>

    </Grid>
</Window>
</code>```

Code-Behind (VB):

```<code>'Reference: http://www.wpf-tutorial.com/common-interface-controls/toolbar-control/

Imports System
Imports System.Windows
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Shapes

Namespace WpfTutorialSamples.Common_interface_controls

    Public Class ToolbarSample
        Inherits Window

        Dim CausedByCode As Boolean
        Dim ZoomFactor As Double = 0.1
        Dim ZoomMax As Double = 4.95
        Dim ZoomMin As Double = 0.05
        Dim NumberOfLevels As Integer = 6
        Dim NumberOfCellsPerLevel As Integer = 2
        Dim LvlBuffer As Double = 0.02
        Dim CellBuffer As Double = 0.05
        Dim LvlContainerColor As Brush = Brushes.LightGreen
        Dim CellContainerColor As Brush = Brushes.LightYellow
        Dim LvlDividerColor As Brush = Brushes.Red

        Public Sub New()
            MyBase.New
            InitializeComponent()
        End Sub

        Private Sub MainWindow_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized
            'HideWindows(False, New StackPanel() {stackpanel_NW, stackpanel_SE, stackpanel_SW})
            HideWindows(True, New StackPanel() {}) 'all
        End Sub

        Private Sub MainWindow_Loaded(sender As Object, e As EventArgs) Handles Me.Loaded
            'add dividers
            For a = 1 To (NumberOfLevels - 1)
                Dim top As Double = a * (manRect.Height / NumberOfLevels)
                Dim LvlDivider As New Canvas
                LvlDivider.Background = LvlDividerColor
                LvlDivider.Width = manRect.Width
                LvlDivider.Height = 0.25
                manRect.Children.Add(LvlDivider)
                Canvas.SetLeft(LvlDivider, 0)
                Canvas.SetTop(LvlDivider, top)
            Next
            'add levels
            For a = 0 To (NumberOfLevels - 1)
                Dim LvlWidth As Double = manRect.Width
                Dim LvlHeight As Double = manRect.Height / NumberOfLevels
                Dim LvlTop As Double = (a * LvlHeight) + (LvlBuffer * LvlHeight)
                Dim LvlBottom As Double = LvlHeight - (2 * LvlBuffer * LvlHeight)
                Dim LvlContainer As New Canvas
                LvlContainer.Background = LvlContainerColor
                LvlContainer.Width = LvlWidth
                LvlContainer.Height = LvlBottom
                manRect.Children.Add(LvlContainer)
                Canvas.SetLeft(LvlContainer, 0)
                Canvas.SetTop(LvlContainer, LvlTop)
                'add cells
                For b = 0 To (NumberOfCellsPerLevel - 1)
                    Dim CellWidth As Double = LvlWidth / NumberOfCellsPerLevel
                    Dim CellWidthBuffered As Double = CellWidth - (2 * CellBuffer * CellWidth)
                    Dim CellHeight As Double = LvlBottom
                    Dim CellTop As Double = (CellBuffer * CellHeight)
                    Dim CellBottom As Double = CellHeight - (2 * CellBuffer * CellHeight)
                    Dim CellLeft As Double = (b * CellWidth) + (CellBuffer * CellWidth)
                    Dim CellContainer As New Canvas
                    CellContainer.Background = CellContainerColor
                    CellContainer.Width = CellWidthBuffered
                    CellContainer.Height = CellBottom
                    LvlContainer.Children.Add(CellContainer)
                    Canvas.SetLeft(CellContainer, CellLeft)
                    Canvas.SetTop(CellContainer, CellTop)
                Next
            Next
            '
            ResetMatrix_Click(button_ResetMatrix, Nothing)
        End Sub

        Private Sub CommonCommandBinding_CanExecute(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs)
            e.CanExecute = True
        End Sub

        Private Sub HideWindows_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles button_HideWindows.Click
            HideWindows(False, New StackPanel() {stackpanel_NE, stackpanel_NW, stackpanel_SE, stackpanel_SW})
        End Sub

        Private Sub ClearWindows_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles button_ClearWindows.Click
            ClearWindows(New StackPanel() {stackpanel_NE, stackpanel_NW, stackpanel_SE, stackpanel_SW})
        End Sub

        Private Sub HideWindows(ByVal Hide As Boolean, StackPanels() As StackPanel)
            If StackPanels.Length = 0 Then
                HideWindows(False, New StackPanel() {stackpanel_NE, stackpanel_NW, stackpanel_SE, stackpanel_SW})
            Else
                For Each s In StackPanels
                    If StackPanels.Length = 4 Then
                        s.Visibility = IIf((s.Visibility = Visibility.Hidden), Visibility.Visible, Visibility.Hidden)
                    Else
                        s.Visibility = IIf(Hide, Visibility.Visible, Visibility.Hidden)
                    End If
                Next
            End If
        End Sub

        Private Sub ClearWindows(StackPanels() As StackPanel)
            For Each s In StackPanels
                Dim g As Grid = (From a In s.Children Where a.GetType = GetType(Grid)
                                 Select TryCast(a, Grid)).FirstOrDefault
                Dim t As TextBox = (From a In g.Children Where a.GetType = GetType(TextBox)
                                    Select TryCast(a, TextBox)).FirstOrDefault
                If s.Visibility = Visibility.Visible Then t.Clear()
            Next
        End Sub

        Private Sub ResetMatrix_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles button_ResetMatrix.Click
            'CenterAboutPoint(New Point(150, 150), e) 'top-left
            CenterAboutPoint(New Point(Me.Width / 2, (Me.Height / 2) - myToolBar.Height), False, False, False, e) 'middle of window
        End Sub

        Private Sub label_ZoomIn_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles label_ZoomIn.MouseDown
            CenterAboutPoint(New Point(Me.Width / 2, (Me.Height / 2) - myToolBar.Height), True, True, False, e)
        End Sub

        Private Sub label_ZoomOut_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles label_ZoomOut.MouseDown
            CenterAboutPoint(New Point(Me.Width / 2, (Me.Height / 2) - myToolBar.Height), True, False, False, e)
        End Sub

        Private Sub CenterAboutPoint(ByVal p As Point, ByVal JustZoom As Boolean, ByVal ZoomDir As Boolean, ByVal JustTranslate As Boolean, ByVal e As RoutedEventArgs)

            'Dim rectToMove As Rectangle = CType(manRect, Rectangle)
            Dim rectToMove As Canvas = CType(manRect, Canvas)
            Dim rectsMatrix As Matrix = CType(rectToMove.RenderTransform, MatrixTransform).Matrix
            Dim ZoomLevel As Double = rectsMatrix.M11
            Dim transform = TransformToVisual(manRect)
            'textbox_NE.Text = "zoom: " & ZoomLevel & ", width: " & manRect.Width & ", height: " & manRect.Height

            Dim elemPosTopLeft = manRect.TranslatePoint(New Point(0, 0), canvas_Main)
            'textbox_NE.AppendText(vbCrLf & "elemPosTopLeft: " & elemPosTopLeft.ToString)

            Dim elemPosBottomRight = manRect.TranslatePoint(New Point(manRect.ActualWidth, manRect.ActualHeight), canvas_Main)
            'textbox_NE.AppendText(vbCrLf & "elemPosBottomRight: " & elemPosBottomRight.ToString)

            Dim elemPosWidth = (elemPosBottomRight.X - elemPosTopLeft.X) '* -ZoomLevel
            'textbox_NE.AppendText(vbCrLf & "elemPosWidth: " & elemPosWidth.ToString)

            Dim elemPosHeight = (elemPosBottomRight.Y - elemPosTopLeft.Y) '* -ZoomLevel
            'textbox_NE.AppendText(vbCrLf & "elemPosHeight: " & elemPosHeight.ToString)

            Dim elemPosLeft = elemPosTopLeft.X
            'textbox_NE.AppendText(vbCrLf & "elemPosLeft: " & elemPosLeft.ToString)

            Dim elemPosTop = elemPosTopLeft.Y
            'textbox_NE.AppendText(vbCrLf & "elemPosTop: " & elemPosTop.ToString)

            Dim elemPosBottom = elemPosBottomRight.Y
            'textbox_NE.AppendText(vbCrLf & "elemPosBottom: " & elemPosBottom.ToString)

            Dim elemPosRight = elemPosBottomRight.X
            'textbox_NE.AppendText(vbCrLf & "elemPosRight: " & elemPosRight.ToString)

            Dim elemPosCenterX = elemPosLeft + (elemPosWidth / 2)
            'textbox_NE.AppendText(vbCrLf & "elemPosCenterX: " & elemPosCenterX.ToString)

            Dim elemPosCenterY = elemPosTop + (elemPosHeight / 2)
            'textbox_NE.AppendText(vbCrLf & "elemPosCenterY: " & elemPosCenterY.ToString)

            'offsets from point
            Dim elemPosLeftOffset = p.X - elemPosCenterX
            'textbox_NE.AppendText(vbCrLf & "elemPosLeftOffset: " & elemPosLeftOffset.ToString)

            Dim elemPosTopOffset = p.Y - elemPosCenterY
            'textbox_NE.AppendText(vbCrLf & "elemPosTopOffset: " & elemPosTopOffset.ToString)

            'scale
            If JustTranslate = False Then
                If JustZoom = False Then
                    If ZoomLevel <> 1 Then
                        rectsMatrix.ScaleAt((1 / ZoomLevel), (1 / ZoomLevel), elemPosCenterX, elemPosCenterY)
                    End If
                Else
                    Dim NewZoomLevel = IIf(ZoomDir = True, (1 + ZoomFactor), (1 - ZoomFactor))
                    'textbox_NE.AppendText(vbCrLf & "NewZoomLevel: " & NewZoomLevel.ToString)
                    If ((ZoomLevel * NewZoomLevel) >= ZoomMin) And ((ZoomLevel * NewZoomLevel) <= ZoomMax) Then
                        rectsMatrix.ScaleAt(NewZoomLevel, NewZoomLevel, elemPosCenterX, elemPosCenterY)
                    End If
                End If
            End If

            'translate
            If JustZoom = False Then
                rectsMatrix.Translate(elemPosLeftOffset, elemPosTopOffset)
            End If
            'transform
            rectToMove.RenderTransform = New MatrixTransform(rectsMatrix)
            If Not IsNothing(e) Then e.Handled = True
        End Sub

        Private Sub Window_ManipulationStarting(ByVal sender As Object, ByVal e As ManipulationStartingEventArgs)
            e.ManipulationContainer = Me
            e.Handled = True
        End Sub

        Private Sub Window_ManipulationDelta(ByVal sender As Object, ByVal e As ManipulationDeltaEventArgs)
            'Reference: https://www.tutorialspoint.com/wpf/wpf_multi_touch.htm
            'Dim rectToMove As Rectangle = CType(e.OriginalSource, Rectangle)
            Dim rectToMove As Canvas = CType(e.OriginalSource, Canvas)
            Dim rectsMatrix As Matrix = CType(rectToMove.RenderTransform, MatrixTransform).Matrix
            Dim ZoomLevel As Double = rectsMatrix.M11
            'scale
            Dim scale As Double = (e.DeltaManipulation.Scale.X + e.DeltaManipulation.Scale.Y) / 2
            rectsMatrix.ScaleAtPrepend(scale, scale, e.ManipulationOrigin.X, e.ManipulationOrigin.Y)
            'translate
            If CausedByCode = False AndAlso (Math.Abs(e.DeltaManipulation.Translation.X) > 1 Or Math.Abs(e.DeltaManipulation.Translation.Y) > 1) Then
                rectsMatrix.Translate(e.DeltaManipulation.Translation.X, e.DeltaManipulation.Translation.Y)
                CausedByCode = True
            Else
                CausedByCode = False
            End If
            'apply transformation
            If (rectsMatrix.M11 >= ZoomMin) And (rectsMatrix.M11 <= ZoomMax) Then
                rectToMove.RenderTransform = New MatrixTransform(rectsMatrix)
            End If
            Dim containingRect As Rect = New Rect(CType(e.ManipulationContainer, FrameworkElement).RenderSize)
            Dim shapeBounds As Rect = rectToMove.RenderTransform.TransformBounds(New Rect(rectToMove.RenderSize))
            If (e.IsInertial AndAlso Not containingRect.Contains(shapeBounds)) Then
                e.Complete()
            End If

            e.Handled = True
        End Sub

        Private Sub Window_InertiaStarting(ByVal sender As Object, ByVal e As ManipulationInertiaStartingEventArgs)
            e.TranslationBehavior.DesiredDeceleration = (10 * (96 / (1000 * 1000))) 'inches per second squared
            e.ExpansionBehavior.DesiredDeceleration = (0.1 * (96 / (1000 * 1000))) 'inches per second squared
            e.RotationBehavior.DesiredDeceleration = (720 / (1000 * 1000)) 'degrees per second squared
            e.Handled = True
        End Sub

    End Class

End Namespace
</code>```

The program works great, although there is an issue when making long drags of the matrix after it has been scaled down...it might be due to inertia.

答:
The following allows basic manipulations on a specified image:

XAML

```<code><Image Source="https://placehold.it/200x200" IsManipulationEnabled="True" ManipulationDelta="OnManipulationDelta" />
</code>```

Code-Behind (C#)

```<code>private void OnManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
    var transformGroup = GetTransformGroup(sender);
    var translateTransform = transformGroup.Children.OfType<TranslateTransform>().First();
    var rotateTransform = transformGroup.Children.OfType<RotateTransform>().First();
    var scaleTransform = transformGroup.Children.OfType<ScaleTransform>().First();

    translateTransform.X += e.DeltaManipulation.Translation.X;
    translateTransform.Y += e.DeltaManipulation.Translation.Y;
    rotateTransform.Angle += e.DeltaManipulation.Rotation;
    scaleTransform.ScaleY *= e.DeltaManipulation.Scale.Y;
    scaleTransform.ScaleX *= e.DeltaManipulation.Scale.X;
}

private TransformGroup GetTransformGroup(object sender)
{
    var element = sender as UIElement;

    element.RenderTransformOrigin = new Point(.5, .5);

    var transformGroup = element.RenderTransform as TransformGroup;

    if (transformGroup == null)
    {
        transformGroup = new TransformGroup();
        transformGroup.Children.Add(new TranslateTransform());
        transformGroup.Children.Add(new ScaleTransform());
        transformGroup.Children.Add(new RotateTransform());

        element.RenderTransform = transformGroup;
    }

    return transformGroup;
}
</code>```

Title: WPF Manipulation in Windows 8.1

Body:
Can anyone provide a few links to examples of how to do Manipulation in Windows 8.1, please?

I see many examples online of how to do it for Windows 7, but it doesn't work for me on my Windows 8.1 machine (with touchscreen).  I'm using VS Studio Community v15.  Here's the example that I've been trying:

https://www.tutorialspoint.com/wpf/wpf_multi_touch.htm

Using either the mouse or fingers doesn't make anything happen at all - no movement, no scaling, no rotation, etc.

P.S., I'm doing my project in VB, not C#.

For example,

<Window x:Class = "WpfManipulation1.MainWindow"
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
   xmlns:local = "clr-namespace:WpfManipulation1"
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604">

    <Window.Resources>
        <MatrixTransform x:Key = "InitialMatrixTransform">
            <MatrixTransform.Matrix>
                <Matrix OffsetX = "200" OffsetY = "200"/>
            </MatrixTransform.Matrix>
        </MatrixTransform>
    </Window.Resources>

    <Canvas>
        <Rectangle Name = "manRect" Width = "321" Height = "241"
         RenderTransform = "{StaticResource InitialMatrixTransform}"
         IsManipulationEnabled = "true" Canvas.Left = "-70" Canvas.Top = "-170">
            <Rectangle.Fill>
                <ImageBrush ImageSource = "ManipImage.JPG"/>
            </Rectangle.Fill>
        </Rectangle>
        <Image Source="ManipImage.jpg" ManipulationMode="All" ManipulationDelta="UIElement_OnManipulationDelta" />
    </Canvas>

</Window>

Partial success with...
XAML:

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfManipulation2"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Image Source="ManipImage.jpg" IsManipulationEnabled="True" ManipulationDelta="OnManipulationDelta" />
    </Grid>
</Window>

VB Code-Behind:

Imports System.Windows.UIElement

Class MainWindow

    Private Sub OnManipulationDelta(ByVal sender As Object, ByVal e As ManipulationDeltaEventArgs)
        Dim transformGroup = GetTransformGroup(sender)
        Dim translateTransform = transformGroup.Children.OfType(Of TranslateTransform).First
        Dim rotateTransform = transformGroup.Children.OfType(Of RotateTransform).First
        Dim scaleTransform = transformGroup.Children.OfType(Of ScaleTransform).First
        translateTransform.X = (translateTransform.X + e.DeltaManipulation.Translation.X)
        translateTransform.Y = (translateTransform.Y + e.DeltaManipulation.Translation.Y)
        rotateTransform.Angle = (rotateTransform.Angle + e.DeltaManipulation.Rotation)
        scaleTransform.ScaleY = (scaleTransform.ScaleY * e.DeltaManipulation.Scale.Y)
        scaleTransform.ScaleX = (scaleTransform.ScaleX * e.DeltaManipulation.Scale.X)
    End Sub

    Private Function GetTransformGroup(ByVal sender As Object) As TransformGroup
        Dim element = CType(sender, UIElement)
        element.RenderTransformOrigin = New Point(0.5, 0.5)
        Dim transformGroup = CType(element.RenderTransform, TransformGroup)
        If (transformGroup Is Nothing) Then
            transformGroup = New TransformGroup
            transformGroup.Children.Add(New TranslateTransform)
            transformGroup.Children.Add(New ScaleTransform)
            transformGroup.Children.Add(New RotateTransform)
            element.RenderTransform = transformGroup
        End If

        Return transformGroup
    End Function

End Class

Error on line "Dim transformGroup = CType(element.RenderTransform, TransformGroup)": System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Media.MatrixTransform' to type 'System.Windows.Media.TransformGroup'.'

Here's the result of implementing the advice provided.

XAML:

<Window x:Class="WpfTutorialSamples.Common_interface_controls.ToolbarSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ToolbarSample"
        Top="50" Left="50" Height="500" Width="700">
    <Window.CommandBindings>
        <CommandBinding Command="New" CanExecute="CommonCommandBinding_CanExecute" />
        <CommandBinding Command="Open" CanExecute="CommonCommandBinding_CanExecute" />
        <CommandBinding Command="Save" CanExecute="CommonCommandBinding_CanExecute" />
    </Window.CommandBindings>
    <Window.Resources>
        <MatrixTransform x:Key = "InitialMatrixTransform">
            <MatrixTransform.Matrix>
                <Matrix OffsetX = "0" OffsetY = "0"/>
            </MatrixTransform.Matrix>
        </MatrixTransform>
    </Window.Resources>
    <Grid x:Name="grid_MainWindow" Margin="0,0,0,0">
        <DockPanel>
            <ToolBarTray x:Name="myToolBarTray" DockPanel.Dock="Top" Panel.ZIndex="1">

                <ToolBar x:Name="myToolBar" Height="30">
                    <Button Name="button_HideWindows" Content="Un/Hide" />
                    <Button Name="button_ClearWindows" Content="Clear" />
                    <Button Name="button_ResetMatrix" Content="Reset" />
                </ToolBar>
            </ToolBarTray>

            <Canvas x:Name="canvas_Main" Background="LightPink" >

                <Canvas Name = "manRect" Width = "300" Height = "300"
                           HorizontalAlignment="Left"
                           VerticalAlignment="Top"
                           Margin="0,0,0,0"
                IsManipulationEnabled="True" ManipulationDelta="Window_ManipulationDelta"
                RenderTransform = "{StaticResource InitialMatrixTransform}"
                        Background="LightBlue"
                >
                </Canvas>

            </Canvas>
        </DockPanel>

        <StackPanel x:Name="stackpanel_NW" Background="LightYellow" HorizontalAlignment="Left" Margin="0,30,0,0" VerticalAlignment="Top"  Height="100" Width="300">
            <Grid x:Name="grid_NW">
                <TextBox x:Name="textbox_NW" Background="LightYellow" BorderThickness="0" AcceptsReturn="True" Height="90" Width="290" Margin="5,5,5,5" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" />
            </Grid>
        </StackPanel>
        <StackPanel x:Name="stackpanel_NE" Background="LightYellow" HorizontalAlignment="Right" Margin="0,30,0,0" VerticalAlignment="Top"  Height="300" Width="300">
            <Grid x:Name="grid_NE">
                <TextBox x:Name="textbox_NE" Background="LightYellow" BorderThickness="0" AcceptsReturn="True" Height="290" Width="290" Margin="5,5,5,5" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" />
            </Grid>
        </StackPanel>
        <StackPanel x:Name="stackpanel_SW" Background="LightYellow" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Bottom"  Height="100" Width="300">
            <Grid x:Name="grid_SW">
                <TextBox x:Name="textbox_SW" Background="LightYellow" BorderThickness="0" AcceptsReturn="True" Height="90" Width="290" Margin="5,5,5,5" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" />
            </Grid>
        </StackPanel>
        <StackPanel x:Name="stackpanel_SE" Background="LightYellow" HorizontalAlignment="Right" Margin="0,0,0,0" VerticalAlignment="Bottom"  Height="100" Width="300">
            <Grid x:Name="grid_SE">
                <TextBox x:Name="textbox_SE" Background="LightYellow" BorderThickness="0" AcceptsReturn="True" Height="90" Width="290" Margin="5,5,5,5" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" />
            </Grid>
        </StackPanel>

    </Grid>
</Window>

Code-Behind (VB):

'Reference: http://www.wpf-tutorial.com/common-interface-controls/toolbar-control/

Imports System
Imports System.Windows
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Shapes

Namespace WpfTutorialSamples.Common_interface_controls

    Public Class ToolbarSample
        Inherits Window

        Dim CausedByCode As Boolean
        Dim ZoomFactor As Double = 0.1
        Dim ZoomMax As Double = 4.95
        Dim ZoomMin As Double = 0.05
        Dim NumberOfLevels As Integer = 6
        Dim NumberOfCellsPerLevel As Integer = 2
        Dim LvlBuffer As Double = 0.02
        Dim CellBuffer As Double = 0.05
        Dim LvlContainerColor As Brush = Brushes.LightGreen
        Dim CellContainerColor As Brush = Brushes.LightYellow
        Dim LvlDividerColor As Brush = Brushes.Red

        Public Sub New()
            MyBase.New
            InitializeComponent()
        End Sub

        Private Sub MainWindow_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized
            'HideWindows(False, New StackPanel() {stackpanel_NW, stackpanel_SE, stackpanel_SW})
            HideWindows(True, New StackPanel() {}) 'all
        End Sub

        Private Sub MainWindow_Loaded(sender As Object, e As EventArgs) Handles Me.Loaded
            'add dividers
            For a = 1 To (NumberOfLevels - 1)
                Dim top As Double = a * (manRect.Height / NumberOfLevels)
                Dim LvlDivider As New Canvas
                LvlDivider.Background = LvlDividerColor
                LvlDivider.Width = manRect.Width
                LvlDivider.Height = 0.25
                manRect.Children.Add(LvlDivider)
                Canvas.SetLeft(LvlDivider, 0)
                Canvas.SetTop(LvlDivider, top)
            Next
            'add levels
            For a = 0 To (NumberOfLevels - 1)
                Dim LvlWidth As Double = manRect.Width
                Dim LvlHeight As Double = manRect.Height / NumberOfLevels
                Dim LvlTop As Double = (a * LvlHeight) + (LvlBuffer * LvlHeight)
                Dim LvlBottom As Double = LvlHeight - (2 * LvlBuffer * LvlHeight)
                Dim LvlContainer As New Canvas
                LvlContainer.Background = LvlContainerColor
                LvlContainer.Width = LvlWidth
                LvlContainer.Height = LvlBottom
                manRect.Children.Add(LvlContainer)
                Canvas.SetLeft(LvlContainer, 0)
                Canvas.SetTop(LvlContainer, LvlTop)
                'add cells
                For b = 0 To (NumberOfCellsPerLevel - 1)
                    Dim CellWidth As Double = LvlWidth / NumberOfCellsPerLevel
                    Dim CellWidthBuffered As Double = CellWidth - (2 * CellBuffer * CellWidth)
                    Dim CellHeight As Double = LvlBottom
                    Dim CellTop As Double = (CellBuffer * CellHeight)
                    Dim CellBottom As Double = CellHeight - (2 * CellBuffer * CellHeight)
                    Dim CellLeft As Double = (b * CellWidth) + (CellBuffer * CellWidth)
                    Dim CellContainer As New Canvas
                    CellContainer.Background = CellContainerColor
                    CellContainer.Width = CellWidthBuffered
                    CellContainer.Height = CellBottom
                    LvlContainer.Children.Add(CellContainer)
                    Canvas.SetLeft(CellContainer, CellLeft)
                    Canvas.SetTop(CellContainer, CellTop)
                Next
            Next
            '
            ResetMatrix_Click(button_ResetMatrix, Nothing)
        End Sub

        Private Sub CommonCommandBinding_CanExecute(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs)
            e.CanExecute = True
        End Sub

        Private Sub HideWindows_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles button_HideWindows.Click
            HideWindows(False, New StackPanel() {stackpanel_NE, stackpanel_NW, stackpanel_SE, stackpanel_SW})
        End Sub

        Private Sub ClearWindows_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles button_ClearWindows.Click
            ClearWindows(New StackPanel() {stackpanel_NE, stackpanel_NW, stackpanel_SE, stackpanel_SW})
        End Sub

        Private Sub HideWindows(ByVal Hide As Boolean, StackPanels() As StackPanel)
            If StackPanels.Length = 0 Then
                HideWindows(False, New StackPanel() {stackpanel_NE, stackpanel_NW, stackpanel_SE, stackpanel_SW})
            Else
                For Each s In StackPanels
                    If StackPanels.Length = 4 Then
                        s.Visibility = IIf((s.Visibility = Visibility.Hidden), Visibility.Visible, Visibility.Hidden)
                    Else
                        s.Visibility = IIf(Hide, Visibility.Visible, Visibility.Hidden)
                    End If
                Next
            End If
        End Sub

        Private Sub ClearWindows(StackPanels() As StackPanel)
            For Each s In StackPanels
                Dim g As Grid = (From a In s.Children Where a.GetType = GetType(Grid)
                                 Select TryCast(a, Grid)).FirstOrDefault
                Dim t As TextBox = (From a In g.Children Where a.GetType = GetType(TextBox)
                                    Select TryCast(a, TextBox)).FirstOrDefault
                If s.Visibility = Visibility.Visible Then t.Clear()
            Next
        End Sub

        Private Sub ResetMatrix_Click(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles button_ResetMatrix.Click
            'CenterAboutPoint(New Point(150, 150), e) 'top-left
            CenterAboutPoint(New Point(Me.Width / 2, (Me.Height / 2) - myToolBar.Height), False, False, False, e) 'middle of window
        End Sub

        Private Sub label_ZoomIn_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles label_ZoomIn.MouseDown
            CenterAboutPoint(New Point(Me.Width / 2, (Me.Height / 2) - myToolBar.Height), True, True, False, e)
        End Sub

        Private Sub label_ZoomOut_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles label_ZoomOut.MouseDown
            CenterAboutPoint(New Point(Me.Width / 2, (Me.Height / 2) - myToolBar.Height), True, False, False, e)
        End Sub

        Private Sub CenterAboutPoint(ByVal p As Point, ByVal JustZoom As Boolean, ByVal ZoomDir As Boolean, ByVal JustTranslate As Boolean, ByVal e As RoutedEventArgs)

            'Dim rectToMove As Rectangle = CType(manRect, Rectangle)
            Dim rectToMove As Canvas = CType(manRect, Canvas)
            Dim rectsMatrix As Matrix = CType(rectToMove.RenderTransform, MatrixTransform).Matrix
            Dim ZoomLevel As Double = rectsMatrix.M11
            Dim transform = TransformToVisual(manRect)
            'textbox_NE.Text = "zoom: " & ZoomLevel & ", width: " & manRect.Width & ", height: " & manRect.Height

            Dim elemPosTopLeft = manRect.TranslatePoint(New Point(0, 0), canvas_Main)
            'textbox_NE.AppendText(vbCrLf & "elemPosTopLeft: " & elemPosTopLeft.ToString)

            Dim elemPosBottomRight = manRect.TranslatePoint(New Point(manRect.ActualWidth, manRect.ActualHeight), canvas_Main)
            'textbox_NE.AppendText(vbCrLf & "elemPosBottomRight: " & elemPosBottomRight.ToString)

            Dim elemPosWidth = (elemPosBottomRight.X - elemPosTopLeft.X) '* -ZoomLevel
            'textbox_NE.AppendText(vbCrLf & "elemPosWidth: " & elemPosWidth.ToString)

            Dim elemPosHeight = (elemPosBottomRight.Y - elemPosTopLeft.Y) '* -ZoomLevel
            'textbox_NE.AppendText(vbCrLf & "elemPosHeight: " & elemPosHeight.ToString)

            Dim elemPosLeft = elemPosTopLeft.X
            'textbox_NE.AppendText(vbCrLf & "elemPosLeft: " & elemPosLeft.ToString)

            Dim elemPosTop = elemPosTopLeft.Y
            'textbox_NE.AppendText(vbCrLf & "elemPosTop: " & elemPosTop.ToString)

            Dim elemPosBottom = elemPosBottomRight.Y
            'textbox_NE.AppendText(vbCrLf & "elemPosBottom: " & elemPosBottom.ToString)

            Dim elemPosRight = elemPosBottomRight.X
            'textbox_NE.AppendText(vbCrLf & "elemPosRight: " & elemPosRight.ToString)

            Dim elemPosCenterX = elemPosLeft + (elemPosWidth / 2)
            'textbox_NE.AppendText(vbCrLf & "elemPosCenterX: " & elemPosCenterX.ToString)

            Dim elemPosCenterY = elemPosTop + (elemPosHeight / 2)
            'textbox_NE.AppendText(vbCrLf & "elemPosCenterY: " & elemPosCenterY.ToString)

            'offsets from point
            Dim elemPosLeftOffset = p.X - elemPosCenterX
            'textbox_NE.AppendText(vbCrLf & "elemPosLeftOffset: " & elemPosLeftOffset.ToString)

            Dim elemPosTopOffset = p.Y - elemPosCenterY
            'textbox_NE.AppendText(vbCrLf & "elemPosTopOffset: " & elemPosTopOffset.ToString)

            'scale
            If JustTranslate = False Then
                If JustZoom = False Then
                    If ZoomLevel <> 1 Then
                        rectsMatrix.ScaleAt((1 / ZoomLevel), (1 / ZoomLevel), elemPosCenterX, elemPosCenterY)
                    End If
                Else
                    Dim NewZoomLevel = IIf(ZoomDir = True, (1 + ZoomFactor), (1 - ZoomFactor))
                    'textbox_NE.AppendText(vbCrLf & "NewZoomLevel: " & NewZoomLevel.ToString)
                    If ((ZoomLevel * NewZoomLevel) >= ZoomMin) And ((ZoomLevel * NewZoomLevel) <= ZoomMax) Then
                        rectsMatrix.ScaleAt(NewZoomLevel, NewZoomLevel, elemPosCenterX, elemPosCenterY)
                    End If
                End If
            End If

            'translate
            If JustZoom = False Then
                rectsMatrix.Translate(elemPosLeftOffset, elemPosTopOffset)
            End If
            'transform
            rectToMove.RenderTransform = New MatrixTransform(rectsMatrix)
            If Not IsNothing(e) Then e.Handled = True
        End Sub

        Private Sub Window_ManipulationStarting(ByVal sender As Object, ByVal e As ManipulationStartingEventArgs)
            e.ManipulationContainer = Me
            e.Handled = True
        End Sub

        Private Sub Window_ManipulationDelta(ByVal sender As Object, ByVal e As ManipulationDeltaEventArgs)
            'Reference: https://www.tutorialspoint.com/wpf/wpf_multi_touch.htm
            'Dim rectToMove As Rectangle = CType(e.OriginalSource, Rectangle)
            Dim rectToMove As Canvas = CType(e.OriginalSource, Canvas)
            Dim rectsMatrix As Matrix = CType(rectToMove.RenderTransform, MatrixTransform).Matrix
            Dim ZoomLevel As Double = rectsMatrix.M11
            'scale
            Dim scale As Double = (e.DeltaManipulation.Scale.X + e.DeltaManipulation.Scale.Y) / 2
            rectsMatrix.ScaleAtPrepend(scale, scale, e.ManipulationOrigin.X, e.ManipulationOrigin.Y)
            'translate
            If CausedByCode = False AndAlso (Math.Abs(e.DeltaManipulation.Translation.X) > 1 Or Math.Abs(e.DeltaManipulation.Translation.Y) > 1) Then
                rectsMatrix.Translate(e.DeltaManipulation.Translation.X, e.DeltaManipulation.Translation.Y)
                CausedByCode = True
            Else
                CausedByCode = False
            End If
            'apply transformation
            If (rectsMatrix.M11 >= ZoomMin) And (rectsMatrix.M11 <= ZoomMax) Then
                rectToMove.RenderTransform = New MatrixTransform(rectsMatrix)
            End If
            Dim containingRect As Rect = New Rect(CType(e.ManipulationContainer, FrameworkElement).RenderSize)
            Dim shapeBounds As Rect = rectToMove.RenderTransform.TransformBounds(New Rect(rectToMove.RenderSize))
            If (e.IsInertial AndAlso Not containingRect.Contains(shapeBounds)) Then
                e.Complete()
            End If

            e.Handled = True
        End Sub

        Private Sub Window_InertiaStarting(ByVal sender As Object, ByVal e As ManipulationInertiaStartingEventArgs)
            e.TranslationBehavior.DesiredDeceleration = (10 * (96 / (1000 * 1000))) 'inches per second squared
            e.ExpansionBehavior.DesiredDeceleration = (0.1 * (96 / (1000 * 1000))) 'inches per second squared
            e.RotationBehavior.DesiredDeceleration = (720 / (1000 * 1000)) 'degrees per second squared
            e.Handled = True
        End Sub

    End Class

End Namespace

The program works great, although there is an issue when making long drags of the matrix after it has been scaled down...it might be due to inertia.

Body:
The following allows basic manipulations on a specified image:

XAML

<Image Source="https://placehold.it/200x200" IsManipulationEnabled="True" ManipulationDelta="OnManipulationDelta" />

Code-Behind (C#)

private void OnManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
    var transformGroup = GetTransformGroup(sender);
    var translateTransform = transformGroup.Children.OfType<TranslateTransform>().First();
    var rotateTransform = transformGroup.Children.OfType<RotateTransform>().First();
    var scaleTransform = transformGroup.Children.OfType<ScaleTransform>().First();

    translateTransform.X += e.DeltaManipulation.Translation.X;
    translateTransform.Y += e.DeltaManipulation.Translation.Y;
    rotateTransform.Angle += e.DeltaManipulation.Rotation;
    scaleTransform.ScaleY *= e.DeltaManipulation.Scale.Y;
    scaleTransform.ScaleX *= e.DeltaManipulation.Scale.X;
}

private TransformGroup GetTransformGroup(object sender)
{
    var element = sender as UIElement;

    element.RenderTransformOrigin = new Point(.5, .5);

    var transformGroup = element.RenderTransform as TransformGroup;

    if (transformGroup == null)
    {
        transformGroup = new TransformGroup();
        transformGroup.Children.Add(new TranslateTransform());
        transformGroup.Children.Add(new ScaleTransform());
        transformGroup.Children.Add(new RotateTransform());

        element.RenderTransform = transformGroup;
    }

    return transformGroup;
}


问:
PHP preg_replace shortening a string
So I've got this php code:

```<code>$text = preg_replace("/(\s)http:\/\/([\S]+?)(\s)/i" ,
"$1[url=\"http://$2\"]http://$2[/url]$3" , " $text ");
</code>```

I guess it's replacing http://xyz.xyz.xyz kind of strings into [url=http://xyz.xyz.xyz]http://xyz.xyz.xyz[/url] inside of a given text (in my case it's a postparser for my forum) right?

now what I'm trying to do is, to limit the stringlength of the http://xyz.xyz.xyz-string that comes inside the [url=http://xyz.xyz.xyz] http://xyz.xyz.xyz <-- this string [/url]
because sometimes users post very long links and those are messing up my forum design and look very ugly anyway.

is there a way I could realize that in php, while keeping the 1. http link like it is so it still links correct?

big thanks in advance! :)

答:
Use preg_replace_callback so that you have more control over the replacement. (e.g. use $2 in [url=...] and use a shorten version of $2 in the text.

```<code>function replace_links($matches) {

    $url = $matches[2];
    $short_url = preg_replace('~^([^/]*)/(.{14})(.{3,})(.{18})$~', '$1/$2...$4', $url);

    return $matches[1] . '[url="http://' . $url . '"]http://' . $short_url . '[/url]' . $matches[3];

}

$text = preg_replace_callback("/(\s)http:\/\/([\S]+?)(\s)/i", 'replace_links', " $text ");
</code>```

(Codepad)

You can see that I use another preg_replace for transforming a very long URL to a short one. I cut it in the middle, while fully preserving the domain name, but you may use any cutting pattern you want.

ContentLicense: CC BY-SA 2.5

Title: PHP preg_replace shortening a string

Body:
So I've got this php code:

$text = preg_replace("/(\s)http:\/\/([\S]+?)(\s)/i" ,
"$1[url=\"http://$2\"]http://$2[/url]$3" , " $text ");

I guess it's replacing http://xyz.xyz.xyz kind of strings into [url=http://xyz.xyz.xyz]http://xyz.xyz.xyz[/url] inside of a given text (in my case it's a postparser for my forum) right?

now what I'm trying to do is, to limit the stringlength of the http://xyz.xyz.xyz-string that comes inside the [url=http://xyz.xyz.xyz] http://xyz.xyz.xyz <-- this string [/url]
because sometimes users post very long links and those are messing up my forum design and look very ugly anyway.

is there a way I could realize that in php, while keeping the 1. http link like it is so it still links correct?

big thanks in advance! :)

Body:
Use preg_replace_callback so that you have more control over the replacement. (e.g. use $2 in [url=...] and use a shorten version of $2 in the text.

function replace_links($matches) {

    $url = $matches[2];
    $short_url = preg_replace('~^([^/]*)/(.{14})(.{3,})(.{18})$~', '$1/$2...$4', $url);

    return $matches[1] . '[url="http://' . $url . '"]http://' . $short_url . '[/url]' . $matches[3];

}

$text = preg_replace_callback("/(\s)http:\/\/([\S]+?)(\s)/i", 'replace_links', " $text ");

(Codepad)

You can see that I use another preg_replace for transforming a very long URL to a short one. I cut it in the middle, while fully preserving the domain name, but you may use any cutting pattern you want.


问:
Dpylr's recode function multiple-to-1 R
I would like an easier way to recode vectors. Specifically I'm wondering if there is a way to pass vectors to a function like dplyr's recode. I understand the basics of quasiquotation but don't quite get how to incorporate the =.

```<code>library(tidyverse)

vec1 <- rep(LETTERS[1:7],7)

#standard way
vec2 <- recode(vec1,
               "A" = "Value1",
               "B" = "Value2",
               "C" = "Value3",
               "D" = "Value4",
               "E" = "Value5",
               "F" = "Value6",
               "G" = "Value7"
               )

vec3 <- recode(vec1,
               "A" = "Value1",
               "B" = "Value1",
               "C" = "Value2",
               "D" = "Value2",
               .default = "Value other"
               )
</code>```

I'd like to do the following

```<code>vec3 <- some.function(vec1,
               c("A", "B") = "Value1",
               c("C", "D") = "Value2",
               .default = "Value other"
               )
</code>```

I have a solution but can't figure out how to incorporate a function with ... and =

```<code>do.call(dplyr::recode,
        c(list(vec1),
        setNames(rep("Value1",length(val1)), val1),
        setNames(rep("Value2",length(val2)), val2)))
</code>```

I also have figured out a way to pass two vectors and rename all the variables.

```<code>recode.by.vectors <- function(x, current.names, new.names){
  do.call(dplyr::recode, c(list(x), setNames(new.names, current.names)))
}
</code>```

Lastly, I'm aware of a base solution.

```<code>vec3 <- vec1
val1 <- c("A", "B")
val2 <- c("C", "D")
vec3[vec1 %in% val1] <- "Value1"
vec3[vec1 %in% val2] <- "Value2"
vec3[!vec1 %in% c(val1,val1)] <- "Value other"
</code>```

but am unaware to how in incorporate the assignment carried out here into a function.

答:
We can use case_when from the dplyr package.

```<code>library(dplyr)

vec1 <- rep(LETTERS[1:7],7)

vec2 <- case_when(
    vec1 %in% c("A", "B")    ~ "Value1",
    vec1 %in% c("C", "D")    ~ "Value2",
    TRUE                     ~ "Value other"
  )
head(vec2)
# [1] "Value1"      "Value1"      "Value2"      "Value2"      "Value other" "Value other"
</code>```

Title: Dpylr's recode function multiple-to-1 R

Body:
I would like an easier way to recode vectors. Specifically I'm wondering if there is a way to pass vectors to a function like dplyr's recode. I understand the basics of quasiquotation but don't quite get how to incorporate the =.

library(tidyverse)

vec1 <- rep(LETTERS[1:7],7)

#standard way
vec2 <- recode(vec1,
               "A" = "Value1",
               "B" = "Value2",
               "C" = "Value3",
               "D" = "Value4",
               "E" = "Value5",
               "F" = "Value6",
               "G" = "Value7"
               )

vec3 <- recode(vec1,
               "A" = "Value1",
               "B" = "Value1",
               "C" = "Value2",
               "D" = "Value2",
               .default = "Value other"
               )

I'd like to do the following

vec3 <- some.function(vec1,
               c("A", "B") = "Value1",
               c("C", "D") = "Value2",
               .default = "Value other"
               )

I have a solution but can't figure out how to incorporate a function with ... and =

do.call(dplyr::recode,
        c(list(vec1),
        setNames(rep("Value1",length(val1)), val1),
        setNames(rep("Value2",length(val2)), val2)))

I also have figured out a way to pass two vectors and rename all the variables.

recode.by.vectors <- function(x, current.names, new.names){
  do.call(dplyr::recode, c(list(x), setNames(new.names, current.names)))
}

Lastly, I'm aware of a base solution.

vec3 <- vec1
val1 <- c("A", "B")
val2 <- c("C", "D")
vec3[vec1 %in% val1] <- "Value1"
vec3[vec1 %in% val2] <- "Value2"
vec3[!vec1 %in% c(val1,val1)] <- "Value other"

but am unaware to how in incorporate the assignment carried out here into a function.

Body:
We can use case_when from the dplyr package.

library(dplyr)

vec1 <- rep(LETTERS[1:7],7)

vec2 <- case_when(
    vec1 %in% c("A", "B")    ~ "Value1",
    vec1 %in% c("C", "D")    ~ "Value2",
    TRUE                     ~ "Value other"
  )
head(vec2)
# [1] "Value1"      "Value1"      "Value2"      "Value2"      "Value other" "Value other"


问:
Function to update a photo in ContactsContract
I try to update a photo in ContactsContract with a function who take the id of the contact and the uri of the picture but it seem it's not working (and my function return true).

I really don't understand because the code look good.

It seem it's working when the contact have already a photo...

This is my function :

```<code>boolean updatePhoto(String idStr, String uri){
        if (uri != null) {
            ArrayList<ContentProviderOperation> ops = new ArrayList<>();

            File imgFile = new File(uri.replace("file://", ""));
            if (imgFile.exists()) {

                Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                myBitmap.compress(Bitmap.CompressFormat.JPEG, 75, stream);
                ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                        .withSelection(ContactsContract.Data.CONTACT_ID + " = ?" + " AND " + ContactsContract.Data.MIMETYPE + "=?",
                                new String[]{idStr, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE})
                        .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, stream.toByteArray())
                        .build());

                try {
                    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
                } catch(Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }
        }
        return true;
    }
</code>```

答:
Your code only works if the contact already has a photo because your using ContentProviderOperation.newUpdate, if the contact doesn't have a photo you'll need to use ContentProviderOperation.newInsert.

You need to first query the contact to see if it has a photo, and then update/insert the new photo:

```<code>private boolean hasPhoto(long contactId) {
    Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
    InputStream input = Contacts.openContactPhotoInputStream(getContentResolver(), uri);
    if (input == null) {
        return false;
    }
    Bitmap photo = BitmapFactory.decodeStream(input);
    return (photo != null);
}

private long getRawId(long contactId) {
    String selection = RawContacts.CONTACT_ID + "='" + contactId + "'";
    Cursor cur = contentResolver.query(RawContacts.CONTENT_URI, new String[]{ RawContacts._ID }, selection, null, null);
    try {
        if (cur.moveToNext()) {
            return cur.getLong(0);
        }
    } finally {
        cur.close();
    }
    return 0;
}

private boolean updatePhoto(long contactId, String uri) {
    if (uri == null) {
        // do nothing?
        return false;
    }

    ContentProviderOperation.Builder builder;
    if (hasPhoto(contactId)) {
        builder = ContentProviderOperation.newUpdate(Data.CONTENT_URI);
        builder.withSelection(Data.CONTACT_ID + " = ?" + " AND " + Data.MIMETYPE + "=?",
                    new String[]{ String.valueOf(contactId), Photo.CONTENT_ITEM_TYPE});
    } else {
        long rawId = getRawId(contactId);
        builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
        builder.withValue(Data.RAW_CONTACT_ID, rawId);
    }

    builder.withValue(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE);
    builder.withValue(Data.IS_SUPER_PRIMARY, 1);
    builder.withValue(Data.IS_PRIMARY, 1);

    byte[] photo = getPhotoAsByteArray(uri); // to simplify the answer's code
    builder.withValue(Photo.PHOTO, photo);

    try {
        ArrayList<ContentProviderOperation> ops = new ArrayList<>();
        ops.add(builder.build());
        getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
    } catch(Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}
</code>```

Body:
I try to update a photo in ContactsContract with a function who take the id of the contact and the uri of the picture but it seem it's not working (and my function return true).

I really don't understand because the code look good.

It seem it's working when the contact have already a photo...

This is my function :

boolean updatePhoto(String idStr, String uri){
        if (uri != null) {
            ArrayList<ContentProviderOperation> ops = new ArrayList<>();

            File imgFile = new File(uri.replace("file://", ""));
            if (imgFile.exists()) {

                Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                myBitmap.compress(Bitmap.CompressFormat.JPEG, 75, stream);
                ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                        .withSelection(ContactsContract.Data.CONTACT_ID + " = ?" + " AND " + ContactsContract.Data.MIMETYPE + "=?",
                                new String[]{idStr, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE})
                        .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, stream.toByteArray())
                        .build());

                try {
                    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
                } catch(Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }
        }
        return true;
    }

Body:
Your code only works if the contact already has a photo because your using ContentProviderOperation.newUpdate, if the contact doesn't have a photo you'll need to use ContentProviderOperation.newInsert.

You need to first query the contact to see if it has a photo, and then update/insert the new photo:

private boolean hasPhoto(long contactId) {
    Uri uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
    InputStream input = Contacts.openContactPhotoInputStream(getContentResolver(), uri);
    if (input == null) {
        return false;
    }
    Bitmap photo = BitmapFactory.decodeStream(input);
    return (photo != null);
}

private long getRawId(long contactId) {
    String selection = RawContacts.CONTACT_ID + "='" + contactId + "'";
    Cursor cur = contentResolver.query(RawContacts.CONTENT_URI, new String[]{ RawContacts._ID }, selection, null, null);
    try {
        if (cur.moveToNext()) {
            return cur.getLong(0);
        }
    } finally {
        cur.close();
    }
    return 0;
}

private boolean updatePhoto(long contactId, String uri) {
    if (uri == null) {
        // do nothing?
        return false;
    }

    ContentProviderOperation.Builder builder;
    if (hasPhoto(contactId)) {
        builder = ContentProviderOperation.newUpdate(Data.CONTENT_URI);
        builder.withSelection(Data.CONTACT_ID + " = ?" + " AND " + Data.MIMETYPE + "=?",
                    new String[]{ String.valueOf(contactId), Photo.CONTENT_ITEM_TYPE});
    } else {
        long rawId = getRawId(contactId);
        builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
        builder.withValue(Data.RAW_CONTACT_ID, rawId);
    }

    builder.withValue(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE);
    builder.withValue(Data.IS_SUPER_PRIMARY, 1);
    builder.withValue(Data.IS_PRIMARY, 1);

    byte[] photo = getPhotoAsByteArray(uri); // to simplify the answer's code
    builder.withValue(Photo.PHOTO, photo);

    try {
        ArrayList<ContentProviderOperation> ops = new ArrayList<>();
        ops.add(builder.build());
        getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
    } catch(Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}


问:
jquery - iframe access denied in IE on some pages
I'm the author of printThis, a jquery plugin for printing.

https://github.com/jasonday/printThis

I have a user that has brought up an issue, that I have been unable to crack and unfortunately, I am unable to share the page (privacy concerns).

On the user's site, the issue presents on some pages in IE, but not others. The print is failing to happen, as the iframe remains empty.

The error in IE is within jQuery:

```<code>contents: function (a) {
            return f.nodeName(a,
                "iframe") ? a.contentDocument || a.contentWindow.document : f.makeArray(a.childNodes)
        }
</code>```

Using logging, I was able to determine it was failing around this line:

```<code>var $doc = $("#" + strFrameName).contents();
</code>```

But again, this only happens on some pages and I have been unable to recreate in any instance outside of this user's site.

My question: Is there a better approach here? or a method to make the $doc object more bulletproof?

```<code>// -----------------------------------------------------------------------
// printThis v1.1
// Printing plug-in for jQuery
//
// Resources (based on) :
//              jPrintArea: http://plugins.jquery.com/project/jPrintArea
//              jqPrint: https://github.com/permanenttourist/jquery.jqprint
//              Ben Nadal: http://www.bennadel.com/blog/1591-Ask-Ben-Print-Part-Of-A-Web-Page-With-jQuery.htm
//
// Dual licensed under the MIT and GPL licenses:
//              http://www.opensource.org/licenses/mit-license.php
//              http://www.gnu.org/licenses/gpl.html
//
// (c) Jason Day 2012
//
// Usage:
//
// $("#mySelector").printThis({
//      debug: false, //show the iframe for debugging
//      importCSS: true, // import page CSS
//      printContainer: true, // grab outer container as well as the contents of the selector
//      loadCSS: "path/to/my.css" //path to additional css file
//  });
//
// Notes:
//  - the loadCSS option does not need @media print
//------------------------------------------------------------------------

(function($) {
    var opt;

    $.fn.printThis = function (options) {
        opt = $.extend({}, $.fn.printThis.defaults, options);

        var $element = (this instanceof jQuery) ? this : $(this);

    // if Opera, open a new tab
        if ($.browser.opera)
        {
            var tab = window.open("","Print Preview");
            tab.document.open();

        }
    // add dynamic iframe to DOM
        else
        {
        var strFrameName = ("printThis-" + (new Date()).getTime());

            var $iframe = $("<iframe id='" + strFrameName +"' src='about:blank'/>");

            if (!opt.debug) { $iframe.css({ position: "absolute", width: "0px", height: "0px", left: "-600px", top: "-600px" }); }

            $iframe.appendTo("body");

        }
    // allow iframe to fully render before action
    setTimeout ( function () {

        if ($.browser.opera)
            {
        var $doc = tab.document;
        } else
        {
        var $doc = $("#" + strFrameName).contents();
        }

        // import page css
        if (opt.importCSS)
        {
                $("link[rel=stylesheet]").each(function(){
                var href = $(this).attr('href');
                if(href){
                        var media = $(this).attr('media') || 'all';
                        $doc.find("head").append("<link type='text/css' rel='stylesheet' href='" + href + "' media='"+media+"'>");
                    }
        });
        }

        // add another stylesheet
        if (opt.loadCSS)
        {
        $doc.find("head").append("<link type='text/css' rel='stylesheet' href='" + opt.loadCSS + "'>");

        }

        //add title of the page
        if (opt.titlePage)
        {
        $doc.find("head").append('<title>'+opt.titlePage+'</title>');
        }
        //grab outer container
        if (opt.printContainer) { $doc.find("body").append($element.outer()); }
        else { $element.each( function() { $doc.find("body").append($(this).html()); }); }

        //$doc.close();
        // print
        ($.browser.opera ? tab : $iframe[0].contentWindow).focus();
        setTimeout( function() { ($.browser.opera ? tab : $iframe[0].contentWindow).print(); if (tab) { tab.close(); } }, 1000);

        //removed iframe after 60 seconds
        setTimeout(
        function(){
        $iframe.remove();
        },
        (60 * 1000)
        );
    }, 333 );
    }

    $.fn.printThis.defaults = {
        debug: false, //show the iframe for debugging
        importCSS: true, // import page CSS
        printContainer: true, // grab outer container as well as the contents of the selector
        loadCSS: "", //path to additional css file
        titlePage: "" //add title to print page
    };

    jQuery.fn.outer = function() {
      return $($('<div></div>').html(this.clone())).html();
    }
})(jQuery);
</code>```

UPDATE

Issue to due to document.domain

This type of page has document.domain set and IE does not inherit document.domain from the parent.

To fix that portion, I changed the iframe creation to standard javascript and set the source to write document.domain on iframe creation.

```<code>    var printI= document.createElement('iframe');

    printI.name = "printIframe";

    printI.id = strFrameName;

    document.body.appendChild(printI);

    printI.src = "javascript:document.write('<head><script>document.domain=\"mydomain.com\";</script></head><body></body>')";

   var $iframe = $("#" + strFrameName);
</code>```

So this fixes the access denied, however now the frame won't print. I've tried a lot of different methods for accessing the object, however none of them are working.

A) how would you access the frame in this scenario (i've tried most of the methods outlined on SO) to get IE to recognize and print

or

B) can anyone think of a better way to get the document.domain into the iframe on creation with jQuery? (can't be afterwards, as the access denied issue will come up)

答:
This answer has already been stated in the original question UPDATE, but I wanted add a more succinct answer to the original question related to getting around the SCRIPT70 Permission denied error (I ran into this on IE11/Win7 with JQuery 3.2.1).

Instead of $('').appendTo($('body'))

Do this:

```<code>var $iframe = $('<iframe .../>');
document.body.appendChild($iframe[0]);
</code>```

Answer taken from here: https://bugs.jquery.com/ticket/13936#comment:28

Body:
I'm the author of printThis, a jquery plugin for printing.

https://github.com/jasonday/printThis

I have a user that has brought up an issue, that I have been unable to crack and unfortunately, I am unable to share the page (privacy concerns).

On the user's site, the issue presents on some pages in IE, but not others. The print is failing to happen, as the iframe remains empty.

The error in IE is within jQuery:

contents: function (a) {
            return f.nodeName(a,
                "iframe") ? a.contentDocument || a.contentWindow.document : f.makeArray(a.childNodes)
        }

Using logging, I was able to determine it was failing around this line:

var $doc = $("#" + strFrameName).contents();

But again, this only happens on some pages and I have been unable to recreate in any instance outside of this user's site.

My question: Is there a better approach here? or a method to make the $doc object more bulletproof?

// -----------------------------------------------------------------------
// printThis v1.1
// Printing plug-in for jQuery
//
// Resources (based on) :
//              jPrintArea: http://plugins.jquery.com/project/jPrintArea
//              jqPrint: https://github.com/permanenttourist/jquery.jqprint
//              Ben Nadal: http://www.bennadel.com/blog/1591-Ask-Ben-Print-Part-Of-A-Web-Page-With-jQuery.htm
//
// Dual licensed under the MIT and GPL licenses:
//              http://www.opensource.org/licenses/mit-license.php
//              http://www.gnu.org/licenses/gpl.html
//
// (c) Jason Day 2012
//
// Usage:
//
// $("#mySelector").printThis({
//      debug: false, //show the iframe for debugging
//      importCSS: true, // import page CSS
//      printContainer: true, // grab outer container as well as the contents of the selector
//      loadCSS: "path/to/my.css" //path to additional css file
//  });
//
// Notes:
//  - the loadCSS option does not need @media print
//------------------------------------------------------------------------

(function($) {
    var opt;

    $.fn.printThis = function (options) {
        opt = $.extend({}, $.fn.printThis.defaults, options);

        var $element = (this instanceof jQuery) ? this : $(this);

    // if Opera, open a new tab
        if ($.browser.opera)
        {
            var tab = window.open("","Print Preview");
            tab.document.open();

        }
    // add dynamic iframe to DOM
        else
        {
        var strFrameName = ("printThis-" + (new Date()).getTime());

            var $iframe = $("");

            if (!opt.debug) { $iframe.css({ position: "absolute", width: "0px", height: "0px", left: "-600px", top: "-600px" }); }

            $iframe.appendTo("body");

        }
    // allow iframe to fully render before action
    setTimeout ( function () {

        if ($.browser.opera)
            {
        var $doc = tab.document;
        } else
        {
        var $doc = $("#" + strFrameName).contents();
        }

        // import page css
        if (opt.importCSS)
        {
                $("link[rel=stylesheet]").each(function(){
                var href = $(this).attr('href');
                if(href){
                        var media = $(this).attr('media') || 'all';
                        $doc.find("head").append("<link type='text/css' rel='stylesheet' href='" + href + "' media='"+media+"'>");
                    }
        });
        }

        // add another stylesheet
        if (opt.loadCSS)
        {
        $doc.find("head").append("<link type='text/css' rel='stylesheet' href='" + opt.loadCSS + "'>");

        }

        //add title of the page
        if (opt.titlePage)
        {
        $doc.find("head").append('<title>'+opt.titlePage+'</title>');
        }
        //grab outer container
        if (opt.printContainer) { $doc.find("body").append($element.outer()); }
        else { $element.each( function() { $doc.find("body").append($(this).html()); }); }

        //$doc.close();
        // print
        ($.browser.opera ? tab : $iframe[0].contentWindow).focus();
        setTimeout( function() { ($.browser.opera ? tab : $iframe[0].contentWindow).print(); if (tab) { tab.close(); } }, 1000);

        //removed iframe after 60 seconds
        setTimeout(
        function(){
        $iframe.remove();
        },
        (60 * 1000)
        );
    }, 333 );
    }

    $.fn.printThis.defaults = {
        debug: false, //show the iframe for debugging
        importCSS: true, // import page CSS
        printContainer: true, // grab outer container as well as the contents of the selector
        loadCSS: "", //path to additional css file
        titlePage: "" //add title to print page
    };

    jQuery.fn.outer = function() {
      return $($('

').html(this.clone())).html();
    }
})(jQuery);

UPDATE

Issue to due to document.domain

This type of page has document.domain set and IE does not inherit document.domain from the parent.

To fix that portion, I changed the iframe creation to standard javascript and set the source to write document.domain on iframe creation.

    var printI= document.createElement('iframe');

    printI.name = "printIframe";

    printI.id = strFrameName;

    document.body.appendChild(printI);

    printI.src = "javascript:document.write('')";

   var $iframe = $("#" + strFrameName);

So this fixes the access denied, however now the frame won't print. I've tried a lot of different methods for accessing the object, however none of them are working.

A) how would you access the frame in this scenario (i've tried most of the methods outlined on SO) to get IE to recognize and print

or

B) can anyone think of a better way to get the document.domain into the iframe on creation with jQuery? (can't be afterwards, as the access denied issue will come up)

Body:
This answer has already been stated in the original question UPDATE, but I wanted add a more succinct answer to the original question related to getting around the SCRIPT70 Permission denied error (I ran into this on IE11/Win7 with JQuery 3.2.1).

Instead of $('<iframe .../>').appendTo($('body'))

Do this:

var $iframe = $('<iframe .../>');
document.body.appendChild($iframe[0]);

Answer taken from here: https://bugs.jquery.com/ticket/13936#comment:28


问:
SQL-PHP error solution
Evening community,

I stuck at one problem, which I can't find solution for. I would appreciate if you could give me a piece of your advice.
In brief, I wrote the following function in a php-file:

```<code>public function getCurrencyReal(){

    $sql = "SELECT currency_real FROM currency WHERE currency_id = '4' limit 1";

    $query = $this->db->query($sql);

    $currency_real = $query;

    return $currency_real->row;
}
</code>```

After that I added the following code in another php file, that should generate XML-list:

```<code>$currency_real = $model_module_xmlcreator -> getCurrencyReal();
</code>```

and

```<code>$out .= "<test>" . $currency_real . "</test>";
</code>```

As a result I've received the following thing:

, saying "Array".

I've realized that I'm asking for an array even though I want to get info only from one field and I actually need a string. So I changed the code a bit to

```<code>$currency_real = json_encode($query);

return $currency_real;
</code>```

and my next output was

I believe that I miss something simple, but I can't find what (the output should be just "33.00"). Pardon me if the question is silly, I've started studying PHP not much time ago.

All best

答:
just change this line

$out .= "<test>" . $currency_real->rows[0]->currency_real . "</test>";

or

$out .= "<test>" . $currency_real->row->currency_real . "</test>";

and don't use json_encode

Title: SQL-PHP error solution

Body:
Evening community,

I stuck at one problem, which I can't find solution for. I would appreciate if you could give me a piece of your advice.
In brief, I wrote the following function in a php-file:

public function getCurrencyReal(){

    $sql = "SELECT currency_real FROM currency WHERE currency_id = '4' limit 1";

    $query = $this->db->query($sql);

    $currency_real = $query;

    return $currency_real->row;
}

After that I added the following code in another php file, that should generate XML-list:

$currency_real = $model_module_xmlcreator -> getCurrencyReal();

and

$out .= "<test>" . $currency_real . "</test>";

As a result I've received the following thing:

, saying "Array".

I've realized that I'm asking for an array even though I want to get info only from one field and I actually need a string. So I changed the code a bit to

$currency_real = json_encode($query);

return $currency_real;

and my next output was

I believe that I miss something simple, but I can't find what (the output should be just "33.00"). Pardon me if the question is silly, I've started studying PHP not much time ago.

All best