问:
jaxb and xlink - friends or foes?
i want to build a rest service via cxf.
this is already done with only two objects "Earthpart" and "Earthquake".
when i call localhost/earthpars i get a xml list of the earthparts with the earthquakes.
but the earthquakeobject with more information {how heavy, how long, etc.} is only available with a xlink to localhost/earthquake/{id}
shortly: In localhost/earthpars is only the xlink to localhost/earthquake/{id}.

now the technical part:
to be honest the request was to use camel-cxf and jaxb to build a REST service. building xlinks with jaxb is possible with namespaces but thats obviously not the way to go! so the question is: is there any info about xlink in connection with jaxb anywhere or is that not the way to go for xlinks?

答:
You could use an XmlAdapter to convert the child object to an xlink representation.  For more information on XmlAdapter see:

http://bdoughan.blogspot.com/2010/07/xmladapter-jaxbs-secret-weapon.html

Title: jaxb and xlink - friends or foes?


来源: stackexchange

问:
Laravel access directly to json array in blade without using foreach statement
in this result:

```<code>LengthAwarePaginator {#251 ▼
  #total: 2
  #lastPage: 1
  #items: Collection {#246 ▼
    #items: array:2 [▼
      0 => ProductCategories {#247 ▼
        ...
        #attributes: array:6 [▼
          "id" => 1
          "category_name" => "test"
          "lang" => "fa"
          "images" => "{"images":{"original":"\/uploads\/post_images\/2017\/1512736029.jpeg","300":"\/uploads\/post_images\/2017\/300_1512736029.jpeg","600":"\/uploads\/post_images\/2017\/600_1512736029.jpeg","900":"\/uploads\/post_images\/2017\/900_1512736029.jpeg"},"thumbnail":"\/uploads\/post_images\/2017\/300_1512736029.jpeg"} ◀"
          "created_at" => "2017-12-08 10:47:56"
          "updated_at" => "2017-12-08 12:27:10"
        ]
        #original: array:6 [▼
          "id" => 1
          "category_name" => "test test"
          "lang" => "fa"
          "images" => "{"images":{"original":"\/uploads\/post_images\/2017\/1512736029.jpeg","300":"\/uploads\/post_images\/2017\/300_1512736029.jpeg","600":"\/uploads\/post_images\/2017\/600_1512736029.jpeg","900":"\/uploads\/post_images\/2017\/900_1512736029.jpeg"},"thumbnail":"\/uploads\/post_images\/2017\/300_1512736029.jpeg"} ◀"
          "created_at" => "2017-12-08 10:47:56"
          "updated_at" => "2017-12-08 12:27:10"
        ]
        ...
      }
      1 => ProductCategories {#248 ▶}
    ]
  }
</code>```

which i get from this query:

```<code>$categories = ProductCategories::paginate(10);
dd($categories);
</code>```

i'm trying to access to "images" column data such as thumbnail and 300 or etc, when i use foreach this data and show that on table i can't access to them, for example:

```<code>{{$categories->images->thumbnail}}
</code>```

but i get Undefined property error and i can't show that

答:
How about you just cast that field to an array ...

```<code>class ProductCategories ...
{
    protected $casts = [
        'images' => 'array',
    ];

    ...
 }

 @foreach ($categories as $category)
     {{ $category->images['thumb'] }}
 @endforeach
</code>```

Laravel 5.5 Docs - Eloquent - Mutators - Array and Json Casting

ContentLicense: CC BY-SA 3.0

Body:
in this result:

LengthAwarePaginator {#251 ▼
  #total: 2
  #lastPage: 1
  #items: Collection {#246 ▼
    #items: array:2 [▼
      0 => ProductCategories {#247 ▼
        ...
        #attributes: array:6 [▼
          "id" => 1
          "category_name" => "test"
          "lang" => "fa"
          "images" => "{"images":{"original":"\/uploads\/post_images\/2017\/1512736029.jpeg","300":"\/uploads\/post_images\/2017\/300_1512736029.jpeg","600":"\/uploads\/post_images\/2017\/600_1512736029.jpeg","900":"\/uploads\/post_images\/2017\/900_1512736029.jpeg"},"thumbnail":"\/uploads\/post_images\/2017\/300_1512736029.jpeg"} ◀"
          "created_at" => "2017-12-08 10:47:56"
          "updated_at" => "2017-12-08 12:27:10"
        ]
        #original: array:6 [▼
          "id" => 1
          "category_name" => "test test"
          "lang" => "fa"
          "images" => "{"images":{"original":"\/uploads\/post_images\/2017\/1512736029.jpeg","300":"\/uploads\/post_images\/2017\/300_1512736029.jpeg","600":"\/uploads\/post_images\/2017\/600_1512736029.jpeg","900":"\/uploads\/post_images\/2017\/900_1512736029.jpeg"},"thumbnail":"\/uploads\/post_images\/2017\/300_1512736029.jpeg"} ◀"
          "created_at" => "2017-12-08 10:47:56"
          "updated_at" => "2017-12-08 12:27:10"
        ]
        ...
      }
      1 => ProductCategories {#248 ▶}
    ]
  }

which i get from this query:

$categories = ProductCategories::paginate(10);
dd($categories);

i'm trying to access to "images" column data such as thumbnail and 300 or etc, when i use foreach this data and show that on table i can't access to them, for example:

{{$categories->images->thumbnail}}

but i get Undefined property error and i can't show that

Body:
How about you just cast that field to an array ...

class ProductCategories ...
{
    protected $casts = [
        'images' => 'array',
    ];

    ...
 }

 @foreach ($categories as $category)
     {{ $category->images['thumb'] }}
 @endforeach

Laravel 5.5 Docs - Eloquent - Mutators - Array and Json Casting


问:
Webpack not generating build.js
I moved my codebase to a dockerformat.

I have a docker-compose file with the command:
command: bash -c "rm -rf node_modules && npm install && npm run dev"

and everything works fine, I use rm -rf node_modules because it gives me some errors of missing packages (from my MAC). Doing that it just gets recreated and it works ok on localhost.

I've also added volumes, so when I change something in my code it gets reflected in my container, this also works fine (apart of the hot-reload, but that's not a big deal).

Now I usually just comment out the line: command: bash -c "rm -rf node_modules && npm install && npm run dev" on my docker-compose file and instead I add:
command: bash -c "rm -rf node_modules && npm install && npm run build" to build my bundle, so that in production I don't have node at all, however this gives me no results.

I'm not sure if it's a problem with volumes, i.e. it gets built in the container but I can't access it from my machine (which I don't think because changing code in my local machine does get reflected in my container) or it doesn't get built at all for some reason.

This is the output of command: bash -c "rm -rf node_modules && npm install && npm run build --verbose"

```<code>NODE     | npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules/fsevents):
NODE     | npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
NODE     |
NODE     | added 115 packages in 11.036s
NODE     | npm info it worked if it ends with ok
NODE     | npm verb cli [ '/usr/local/bin/node',
NODE     | npm verb cli   '/usr/local/bin/npm',
NODE     | npm verb cli   'run',
NODE     | npm verb cli   'build',
NODE     | npm verb cli   '--verbose' ]
NODE     | npm info using npm@5.5.1
NODE     | npm info using node@v9.2.0
NODE     | npm verb run-script [ 'prebuild', 'build', 'postbuild' ]
NODE     | npm info lifecycle frontend@1.0.0~prebuild: frontend@1.0.0
NODE     | npm info lifecycle frontend@1.0.0~build: frontend@1.0.0
NODE     |
NODE     | > frontend@1.0.0 build /code/client
NODE     | > cross-env NODE_ENV=production webpack --progress --hide-modules
NODE     |
NODE     | Hash: cda5e46c2c7f4ba2903b
NODE     | Version: webpack 3.9.1
NODE     | Time: 27298ms
NODE     |        Asset     Size  Chunks                    Chunk Names
NODE     |     build.js  1.29 MB       0  [emitted]  [big]  main
NODE     | build.js.map  7.65 MB       0  [emitted]         main
NODE     | npm verb lifecycle frontend@1.0.0~build: unsafe-perm in lifecycle true
NODE     | npm verb lifecycle frontend@1.0.0~build: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/code/client/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
NODE     | npm verb lifecycle frontend@1.0.0~build: CWD: /code/client
NODE     | npm info lifecycle frontend@1.0.0~postbuild: frontend@1.0.0
NODE     | npm verb exit [ 0, true ]
NODE     | npm info ok
</code>```

And my webpack conf file starts like this:

```<code>var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, '../static/dist/'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
</code>```

Which at least before worked fine since my app looks like this:

```<code>- manage.py
- static
  - dist
  - others
- client
  - webpack.config.js
</code>```

etc

Why nothing gets build in dist?

Update

I used exec to look inside the container. I can't find the build.js anywhere. I also run touch abc.txt inside /code/static/dist and it gets also created on my localhost, i.e. the volumes work fine.It must be a problem of webpack and not docker.

Update 2

I've also tried the full path like this, still nothing:

```<code>module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, '/code/static/dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
</code>```

Edit 3

I've tried to look for build.js I found these files, but I think that those are not my build.js:

```<code>root@0xxxxxx:/code# find . -name build.js
./client/node_modules/node-forge/nodejs/build.js
./client/node_modules/errno/build.js
./client/node_modules/vue-template-compiler/build.js
./client/node_modules/builtin-status-codes/build.js
./client/node_modules/webpack-dev-middleware/node_modules/mime/src/build.js
./client/node_modules/node-gyp/lib/build.js
./client/node_modules/node-sass/scripts/build.js
./client/node_modules/mime/build/build.js
./client/node_modules/npm/node_modules/node-gyp/lib/build.js
./client/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/node_modules/isarray/build/build.js
./client/node_modules/npm/lib/install/action/build.js
./client/node_modules/npm/lib/build.js
</code>```

答:
Try removing /dist/ from path. It works on my machine.

```<code>module.exports = {
    entry: './src/main.js',
    output: {
       path: path.resolve(__dirname, '../static'),
       publicPath: '/dist/',
       filename: 'build.js'
    },
</code>```

Title: Webpack not generating build.js

Body:
I moved my codebase to a dockerformat.

I have a docker-compose file with the command:
command: bash -c "rm -rf node_modules && npm install && npm run dev"

and everything works fine, I use rm -rf node_modules because it gives me some errors of missing packages (from my MAC). Doing that it just gets recreated and it works ok on localhost.

I've also added volumes, so when I change something in my code it gets reflected in my container, this also works fine (apart of the hot-reload, but that's not a big deal).

Now I usually just comment out the line: command: bash -c "rm -rf node_modules && npm install && npm run dev" on my docker-compose file and instead I add:
command: bash -c "rm -rf node_modules && npm install && npm run build" to build my bundle, so that in production I don't have node at all, however this gives me no results.

I'm not sure if it's a problem with volumes, i.e. it gets built in the container but I can't access it from my machine (which I don't think because changing code in my local machine does get reflected in my container) or it doesn't get built at all for some reason.

This is the output of command: bash -c "rm -rf node_modules && npm install && npm run build --verbose"

NODE     | npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules/fsevents):
NODE     | npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
NODE     |
NODE     | added 115 packages in 11.036s
NODE     | npm info it worked if it ends with ok
NODE     | npm verb cli [ '/usr/local/bin/node',
NODE     | npm verb cli   '/usr/local/bin/npm',
NODE     | npm verb cli   'run',
NODE     | npm verb cli   'build',
NODE     | npm verb cli   '--verbose' ]
NODE     | npm info using npm@5.5.1
NODE     | npm info using node@v9.2.0
NODE     | npm verb run-script [ 'prebuild', 'build', 'postbuild' ]
NODE     | npm info lifecycle frontend@1.0.0~prebuild: frontend@1.0.0
NODE     | npm info lifecycle frontend@1.0.0~build: frontend@1.0.0
NODE     |
NODE     | > frontend@1.0.0 build /code/client
NODE     | > cross-env NODE_ENV=production webpack --progress --hide-modules
NODE     |
NODE     | Hash: cda5e46c2c7f4ba2903b
NODE     | Version: webpack 3.9.1
NODE     | Time: 27298ms
NODE     |        Asset     Size  Chunks                    Chunk Names
NODE     |     build.js  1.29 MB       0  [emitted]  [big]  main
NODE     | build.js.map  7.65 MB       0  [emitted]         main
NODE     | npm verb lifecycle frontend@1.0.0~build: unsafe-perm in lifecycle true
NODE     | npm verb lifecycle frontend@1.0.0~build: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/code/client/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
NODE     | npm verb lifecycle frontend@1.0.0~build: CWD: /code/client
NODE     | npm info lifecycle frontend@1.0.0~postbuild: frontend@1.0.0
NODE     | npm verb exit [ 0, true ]
NODE     | npm info ok

And my webpack conf file starts like this:

var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, '../static/dist/'),
    publicPath: '/dist/',
    filename: 'build.js'
  },

Which at least before worked fine since my app looks like this:

- manage.py
- static
  - dist
  - others
- client
  - webpack.config.js

etc

Why nothing gets build in dist?

Update

I used exec to look inside the container. I can't find the build.js anywhere. I also run touch abc.txt inside /code/static/dist and it gets also created on my localhost, i.e. the volumes work fine.It must be a problem of webpack and not docker.

Update 2

I've also tried the full path like this, still nothing:

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, '/code/static/dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },

Edit 3

I've tried to look for build.js I found these files, but I think that those are not my build.js:

root@0xxxxxx:/code# find . -name build.js
./client/node_modules/node-forge/nodejs/build.js
./client/node_modules/errno/build.js
./client/node_modules/vue-template-compiler/build.js
./client/node_modules/builtin-status-codes/build.js
./client/node_modules/webpack-dev-middleware/node_modules/mime/src/build.js
./client/node_modules/node-gyp/lib/build.js
./client/node_modules/node-sass/scripts/build.js
./client/node_modules/mime/build/build.js
./client/node_modules/npm/node_modules/node-gyp/lib/build.js
./client/node_modules/npm/node_modules/sorted-union-stream/node_modules/from2/node_modules/readable-stream/node_modules/isarray/build/build.js
./client/node_modules/npm/lib/install/action/build.js
./client/node_modules/npm/lib/build.js

Body:
Try removing /dist/ from path. It works on my machine.

module.exports = {
    entry: './src/main.js',
    output: {
       path: path.resolve(__dirname, '../static'),
       publicPath: '/dist/',
       filename: 'build.js'
    },


问:
In JShell, how to import classpath from a Maven project
I have a local Maven project under development. How can I launch jshell with the project class path with all the dependencies, so that I can test project or dependency classes inside JShell.

答:
I wrote a simple shell script put in the execution search path:

Shell script file: mshell (for *inux)

```<code>mvn dependency:build-classpath -DincludeTypes=jar -Dmdep.outputFile=.cp.txt
jshell --class-path `cat .cp.txt`:target/classes
</code>```

Shell script file: mshell (for Windows cmd.exe)

```<code>mvn dependency:build-classpath -DincludeTypes=jar -Dmdep.outputFile=.cp.txt
for /F %i in (.cp.txt) do jshell --class-path "%i;target/classes"
</code>```

Then in the maven project directory (for multi-module project, make sure in the module directory instead of parent directory), run:

```<code>$ cd $MAVEN_PROJECT_HOME   #make sure module folder for multi-module project
$ mshell
</code>```

gist link

Thanks Jay for pointing out -DincludeTypes=jar maven option.

Body:
I wrote a simple shell script put in the execution search path:

Shell script file: mshell (for *inux)

mvn dependency:build-classpath -DincludeTypes=jar -Dmdep.outputFile=.cp.txt
jshell --class-path `cat .cp.txt`:target/classes

Shell script file: mshell (for Windows cmd.exe)

mvn dependency:build-classpath -DincludeTypes=jar -Dmdep.outputFile=.cp.txt
for /F %i in (.cp.txt) do jshell --class-path "%i;target/classes"

Then in the maven project directory (for multi-module project, make sure in the module directory instead of parent directory), run:

$ cd $MAVEN_PROJECT_HOME   #make sure module folder for multi-module project
$ mshell

gist link

Thanks Jay for pointing out -DincludeTypes=jar maven option.

ContentLicense: CC BY-SA 4.0


问:
Coach a newbie through basic WPF? (I Do Not Grok It.)
Question is as it sounds. No matter how hard and how often I try to understand WPF, I feel like I'm hitting my head against a wall. I like Winforms, where everything makes sense.

As an example, I'm trying to write a simple app that will allow me to lay out a bunch of 2-D paths (represented by polylines) and drag their vertices around, and have the vertex information synchronised with a presenter (that is, I suppose, a ViewModel)

So the problem is thus:

Make the window recognise an instance of IExtendedObjectPresenter as a data source;

From a collection of IExtendedObject, draw one polyline for each IExtendedObject;

For each vertex in the extended object, represented by the collection IExtendedObject.Points, place a polyline vertex at the specified co-ordinates.

The IDE is giving me no help at all here. None of the many properties available in XAML sound meaningful to me. Because so much seems to be done implicitly, there is no obvious place to just tell the window what to do.

Before I get slated and told to RTFM, I would like to re-emphasise that I have researched the basic concepts of WPF a great many times. I know no more about it than I did when it was first released. It seems totally inpenetrable. Examples given for one type of behaviour are not in any way applicable to an even slightly different kind of behaviour, so you're back to square one. I'm hoping that repetition and targeted exampes might switch a light on in my head at some point.

答:
I sympathize with you.  Really understanding WPF takes a long time and it can be very frustrating to accomplish the simplest of things.  But diving into a problem that is not easy for experts is only asking for trouble.  You need to tackle simpler tasks and read a lot of code until things start to make sense.  Donald Knuth says you don't really know the material until you do the exercises.

I solved your problem and I admit there are a lot of advance concepts in doing this cleanly and tacking on MVVM makes it that much harder.  For what it's worth, here is a zero code-behind solution to your problem that is in the spirit of MVVM.

Here is the XAML:

```<code><Grid>
    <Grid.Resources>
        <local:PolylineCollection x:Key="sampleData">
            <local:Polyline>
                <local:Coordinate X="50" Y="50"/>
                <local:Coordinate X="100" Y="100"/>
                <local:Coordinate X="50" Y="150"/>
            </local:Polyline>
        </local:PolylineCollection>
    </Grid.Resources>
    <Grid DataContext="{StaticResource sampleData}">
        <ItemsControl ItemsSource="{Binding Segments}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Line X1="{Binding Start.X}" Y1="{Binding Start.Y}" X2="{Binding End.X}" Y2="{Binding End.Y}" Stroke="Black" StrokeThickness="2"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
        <ItemsControl ItemsSource="{Binding ControlPoints}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemContainerStyle>
                <Style TargetType="ContentPresenter">
                    <Setter Property="Canvas.Left" Value="{Binding X}"/>
                    <Setter Property="Canvas.Top" Value="{Binding Y}"/>
                </Style>
            </ItemsControl.ItemContainerStyle>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Ellipse Margin="-10,-10,0,0" Width="20" Height="20" Stroke="DarkBlue" Fill="Transparent">
                        <i:Interaction.Behaviors>
                            <local:ControlPointBehavior/>
                        </i:Interaction.Behaviors>
                    </Ellipse>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
</Grid>
</code>```

and here are the supporting classes:

```<code>public class Coordinate : INotifyPropertyChanged
{
    private double x;
    private double y;

    public double X
    {
        get { return x; }
        set { x = value; OnPropertyChanged("X", "Point"); }
    }
    public double Y
    {
        get { return y; }
        set { y = value; OnPropertyChanged("Y", "Point"); }
    }
    public Point Point
    {
        get { return new Point(x, y); }
        set { x = value.X; y = value.Y; OnPropertyChanged("X", "Y", "Point"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(params string[] propertyNames)
    {
        foreach (var propertyName in propertyNames)
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class Polyline : List<Coordinate>
{
}

public class Segment
{
    public Coordinate Start { get; set; }
    public Coordinate End { get; set; }
}

public class PolylineCollection : List<Polyline>
{
    public IEnumerable<Segment> Segments
    {
        get
        {
            foreach (var polyline in this)
            {
                var last = polyline.FirstOrDefault();
                foreach (var coordinate in polyline.Skip(1))
                {
                    yield return new Segment { Start = last, End = coordinate };
                    last = coordinate;
                }
            }
        }
    }

    public IEnumerable<Coordinate> ControlPoints
    {
        get
        {
            foreach (var polyline in this)
            {
                foreach (var coordinate in polyline)
                    yield return coordinate;
            }
        }
    }
}

public class ControlPointBehavior : Behavior<FrameworkElement>
{
    private bool mouseDown;
    private Vector delta;

    protected override void OnAttached()
    {
        var canvas = AssociatedObject.Parent as Canvas;
        AssociatedObject.MouseLeftButtonDown += (s, e) =>
        {
            mouseDown = true;
            var mousePosition = e.GetPosition(canvas);
            var elementPosition = (AssociatedObject.DataContext as Coordinate).Point;
            delta = elementPosition - mousePosition;
            AssociatedObject.CaptureMouse();
        };
        AssociatedObject.MouseMove += (s, e) =>
        {
            if (!mouseDown) return;
            var mousePosition = e.GetPosition(canvas);
            var elementPosition = mousePosition + delta;
            (AssociatedObject.DataContext as Coordinate).Point = elementPosition;
        };
        AssociatedObject.MouseLeftButtonUp += (s, e) =>
        {
            mouseDown = false;
            AssociatedObject.ReleaseMouseCapture();
        };
    }
}
</code>```

This solution uses behaviors, which are ideal for implementing interactivity with MVVM.

If you are not familiar with behaviors, Install the Expression Blend 4 SDK and add this namespaces:

```<code>xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
</code>```

and add System.Windows.Interactivity to your project.

ContentLicense: CC BY-SA 2.5

Body:
I sympathize with you.  Really understanding WPF takes a long time and it can be very frustrating to accomplish the simplest of things.  But diving into a problem that is not easy for experts is only asking for trouble.  You need to tackle simpler tasks and read a lot of code until things start to make sense.  Donald Knuth says you don't really know the material until you do the exercises.

I solved your problem and I admit there are a lot of advance concepts in doing this cleanly and tacking on MVVM makes it that much harder.  For what it's worth, here is a zero code-behind solution to your problem that is in the spirit of MVVM.

Here is the XAML:

<Grid>
    <Grid.Resources>
        <local:PolylineCollection x:Key="sampleData">
            <local:Polyline>
                <local:Coordinate X="50" Y="50"/>
                <local:Coordinate X="100" Y="100"/>
                <local:Coordinate X="50" Y="150"/>
            </local:Polyline>
        </local:PolylineCollection>
    </Grid.Resources>
    <Grid DataContext="{StaticResource sampleData}">
        <ItemsControl ItemsSource="{Binding Segments}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Line X1="{Binding Start.X}" Y1="{Binding Start.Y}" X2="{Binding End.X}" Y2="{Binding End.Y}" Stroke="Black" StrokeThickness="2"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
        <ItemsControl ItemsSource="{Binding ControlPoints}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemContainerStyle>
                <Style TargetType="ContentPresenter">
                    <Setter Property="Canvas.Left" Value="{Binding X}"/>
                    <Setter Property="Canvas.Top" Value="{Binding Y}"/>
                </Style>
            </ItemsControl.ItemContainerStyle>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Ellipse Margin="-10,-10,0,0" Width="20" Height="20" Stroke="DarkBlue" Fill="Transparent">
                        <i:Interaction.Behaviors>
                            <local:ControlPointBehavior/>
                        </i:Interaction.Behaviors>
                    </Ellipse>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
</Grid>

and here are the supporting classes:

public class Coordinate : INotifyPropertyChanged
{
    private double x;
    private double y;

    public double X
    {
        get { return x; }
        set { x = value; OnPropertyChanged("X", "Point"); }
    }
    public double Y
    {
        get { return y; }
        set { y = value; OnPropertyChanged("Y", "Point"); }
    }
    public Point Point
    {
        get { return new Point(x, y); }
        set { x = value.X; y = value.Y; OnPropertyChanged("X", "Y", "Point"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(params string[] propertyNames)
    {
        foreach (var propertyName in propertyNames)
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class Polyline : List<Coordinate>
{
}

public class Segment
{
    public Coordinate Start { get; set; }
    public Coordinate End { get; set; }
}

public class PolylineCollection : List<Polyline>
{
    public IEnumerable<Segment> Segments
    {
        get
        {
            foreach (var polyline in this)
            {
                var last = polyline.FirstOrDefault();
                foreach (var coordinate in polyline.Skip(1))
                {
                    yield return new Segment { Start = last, End = coordinate };
                    last = coordinate;
                }
            }
        }
    }

    public IEnumerable<Coordinate> ControlPoints
    {
        get
        {
            foreach (var polyline in this)
            {
                foreach (var coordinate in polyline)
                    yield return coordinate;
            }
        }
    }
}

public class ControlPointBehavior : Behavior<FrameworkElement>
{
    private bool mouseDown;
    private Vector delta;

    protected override void OnAttached()
    {
        var canvas = AssociatedObject.Parent as Canvas;
        AssociatedObject.MouseLeftButtonDown += (s, e) =>
        {
            mouseDown = true;
            var mousePosition = e.GetPosition(canvas);
            var elementPosition = (AssociatedObject.DataContext as Coordinate).Point;
            delta = elementPosition - mousePosition;
            AssociatedObject.CaptureMouse();
        };
        AssociatedObject.MouseMove += (s, e) =>
        {
            if (!mouseDown) return;
            var mousePosition = e.GetPosition(canvas);
            var elementPosition = mousePosition + delta;
            (AssociatedObject.DataContext as Coordinate).Point = elementPosition;
        };
        AssociatedObject.MouseLeftButtonUp += (s, e) =>
        {
            mouseDown = false;
            AssociatedObject.ReleaseMouseCapture();
        };
    }
}

This solution uses behaviors, which are ideal for implementing interactivity with MVVM.

If you are not familiar with behaviors, Install the Expression Blend 4 SDK and add this namespaces:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

and add System.Windows.Interactivity to your project.


问:
Mock or simulate Message Queue (JMS)
There is a message(text), which format and content i definitely know.

For now,class in Java,that parses and reads this message from file,is implemented.

In real world, this message will come from Message Queue.

For now I should simulate, mock or generate Message Queue on my local PC for testing purposes.

Java spec(java jms):

```<code>JMS provider: A messaging system that implements the JMS specification.
JMS clients: Java applications that send and receive messages.
Messages: Objects that are used to communicate information between JMS clients.
</code>```

Concerning this specification, i need JMS provider.

JMS client-it's my class that reads message.

Message itself i know.

So the question is how to start message queue?

How can i simulate it programmaticaly from Java code? Can i mock it somehow?

Thanks.

答:
To test an application in isolation when the real production JMS provider is not available you can use one of:

JMS mock:

When testing your applications you can simulate the non-existing dependencies using test doubles. You can use a JMS mock which will simulate the behaviour of a real JMS provider. API simulation tools will allow you to create JMS mocks (just choose a tool that supports JMS, for example Traffic Parrot). Using a JMS mock will allow you for a high level of flexibility during testing. You will be able to test typical production-like test scenarios but also hypothetical situations by setting up your mock to return almost any type of message. You will also be able to simulate different types of errors, which is often hard to do with real JMS providers. Have a look at this introduction video to JMS service virtualization for ActiveMq (service virtualization is a different name for a mock) or this one for IBM MQ. Note, these videos are from Traffic Parrot, but the principle described there will apply to any tool you choose.

JMS provider test instance:

You can run a JMS provider on your laptop or in one of your test environments and connect your application to it instead of the production provider. When you use open source providers in production like ActiveMQ or RabbitMQ, it should be easy to run one of them on your laptop as well because they are lightweight and free. For IBM Websphere MQ, you can use the free IBM MQ for Developers.

JMS class mock:

You can use Mockito in unit tests to mock interactions with JMS classes. This solution comes with all the trade-offs of unit testing. For more information on those see testing pyramid.

If you would like to black box test your application, use one of the solutions I have described above.

Title: Mock or simulate Message Queue (JMS)

Body:
There is a message(text), which format and content i definitely know.

For now,class in Java,that parses and reads this message from file,is implemented.

In real world, this message will come from Message Queue.

For now I should simulate, mock or generate Message Queue on my local PC for testing purposes.

Java spec(java jms):

JMS provider: A messaging system that implements the JMS specification.
JMS clients: Java applications that send and receive messages.
Messages: Objects that are used to communicate information between JMS clients.

Concerning this specification, i need JMS provider.

JMS client-it's my class that reads message.

Message itself i know.

So the question is how to start message queue?

How can i simulate it programmaticaly from Java code? Can i mock it somehow?

Thanks.


问:
xcode: class is not key value coding-compliant
I'm currently working myself through this tutorial:
https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/ConnectTheUIToCode.html#//apple_ref/doc/uid/TP40015214-CH22-SW1
After creating the function for the button(at ~2/3 on the page) I tried running the code and got the Exception:

```<code>2017-12-08 11:24:31.343183+0100 FoodTracker[2159:154603] ***

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<FoodTracker.ViewController 0x7fea6f406820> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key setDefaultLabelText.'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000109d7512b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x00000001060fcf41 objc_exception_throw + 48
    2   CoreFoundation                      0x0000000109d75079 -[NSException raise] + 9
    3   Foundation                          0x0000000105b1ba63 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 292
    4   UIKit                               0x0000000106b39117 -[UIViewController setValue:forKey:] + 87
    5   UIKit                               0x0000000106e2ac2d -[UIRuntimeOutletConnection connect] + 109
    6   CoreFoundation                      0x0000000109d183cd -[NSArray makeObjectsPerformSelector:] + 317
    7   UIKit                               0x0000000106e295e3 -[UINib instantiateWithOwner:options:] + 1856
    8   UIKit                               0x0000000106b403ff -[UIViewController _loadViewFromNibNamed:bundle:] + 383
    9   UIKit                               0x0000000106b40d2b -[UIViewController loadView] + 177
    10  UIKit                               0x0000000106b4105c -[UIViewController loadViewIfRequired] + 195
    11  UIKit                               0x0000000106b418b9 -[UIViewController view] + 27
    12  UIKit                               0x0000000106a0c7cf -[UIWindow addRootViewControllerViewIfPossible] + 122
    13  UIKit                               0x0000000106a0ced7 -[UIWindow _setHidden:forced:] + 294
    14  UIKit                               0x0000000106a1fe54 -[UIWindow makeKeyAndVisible] + 42
    15  UIKit                               0x00000001069928b8 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4737
    16  UIKit                               0x0000000106997aeb -[UIApplication _runWithMainScene:transitionContext:completion:] + 1720
    17  UIKit                               0x0000000106d616f8 __111-[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:]_block_invoke + 924
    18  UIKit                               0x00000001071374c8 +[_UICanvas _enqueuePostSettingUpdateTransactionBlock:] + 153
    19  UIKit                               0x0000000106d612f1 -[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:] + 249
    20  UIKit                               0x0000000106d61b6b -[__UICanvasLifecycleMonitor_Compatability activateEventsOnly:withContext:completion:] + 696
    21  UIKit                               0x00000001076dfa69 __82-[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:]_block_invoke + 262
    22  UIKit                               0x00000001076df922 -[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:] + 444
    23  UIKit                               0x00000001073bc9c8 __125-[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:]_block_invoke + 221
    24  UIKit                               0x00000001075bbb06 _performActionsWithDelayForTransitionContext + 100
    25  UIKit                               0x00000001073bc88b -[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:] + 231
    26  UIKit                               0x0000000107136b25 -[_UICanvas scene:didUpdateWithDiff:transitionContext:completion:] + 392
    27  UIKit                               0x000000010699636a -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 523
    28  UIKit                               0x0000000106f71605 -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 369
    29  FrontBoardServices                  0x000000010bc38cc0 -[FBSSceneImpl _didCreateWithTransitionContext:completion:] + 338
    30  FrontBoardServices                  0x000000010bc417b5 __56-[FBSWorkspace client:handleCreateScene:withCompletion:]_block_invoke_2 + 235
    31  libdispatch.dylib                   0x000000010ae9733d _dispatch_client_callout + 8
    32  libdispatch.dylib                   0x000000010ae9c9f3 _dispatch_block_invoke_direct + 592
    33  FrontBoardServices                  0x000000010bc6d498 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
    34  FrontBoardServices                  0x000000010bc6d14e -[FBSSerialQueue _performNext] + 464
    35  FrontBoardServices                  0x000000010bc6d6bd -[FBSSerialQueue _performNextFromRunLoopSource] + 45
    36  CoreFoundation                      0x0000000109d18101 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    37  CoreFoundation                      0x0000000109db7f71 __CFRunLoopDoSource0 + 81
    38  CoreFoundation                      0x0000000109cfca19 __CFRunLoopDoSources0 + 185
    39  CoreFoundation                      0x0000000109cfbfff __CFRunLoopRun + 1279
    40  CoreFoundation                      0x0000000109cfb889 CFRunLoopRunSpecific + 409
    41  GraphicsServices                    0x000000010c5019c6 GSEventRunModal + 62
    42  UIKit                               0x00000001069995d6 UIApplicationMain + 159
    43  FoodTracker                         0x00000001057e7b67 main + 55
    44  libdyld.dylib                       0x000000010af13d81 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
</code>```

Here is my Code:

And the connections inspector of the button:

答:
Check your connection to @IBAction with this steps below:

In the storyboard:

In your view controller:

Updated:

In your case, you should remove connection in Reference Outlets because you connect it to the label outlet.

Body:
I'm currently working myself through this tutorial:
https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/ConnectTheUIToCode.html#//apple_ref/doc/uid/TP40015214-CH22-SW1
After creating the function for the button(at ~2/3 on the page) I tried running the code and got the Exception:

2017-12-08 11:24:31.343183+0100 FoodTracker[2159:154603] ***

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<FoodTracker.ViewController 0x7fea6f406820> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key setDefaultLabelText.'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000109d7512b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x00000001060fcf41 objc_exception_throw + 48
    2   CoreFoundation                      0x0000000109d75079 -[NSException raise] + 9
    3   Foundation                          0x0000000105b1ba63 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 292
    4   UIKit                               0x0000000106b39117 -[UIViewController setValue:forKey:] + 87
    5   UIKit                               0x0000000106e2ac2d -[UIRuntimeOutletConnection connect] + 109
    6   CoreFoundation                      0x0000000109d183cd -[NSArray makeObjectsPerformSelector:] + 317
    7   UIKit                               0x0000000106e295e3 -[UINib instantiateWithOwner:options:] + 1856
    8   UIKit                               0x0000000106b403ff -[UIViewController _loadViewFromNibNamed:bundle:] + 383
    9   UIKit                               0x0000000106b40d2b -[UIViewController loadView] + 177
    10  UIKit                               0x0000000106b4105c -[UIViewController loadViewIfRequired] + 195
    11  UIKit                               0x0000000106b418b9 -[UIViewController view] + 27
    12  UIKit                               0x0000000106a0c7cf -[UIWindow addRootViewControllerViewIfPossible] + 122
    13  UIKit                               0x0000000106a0ced7 -[UIWindow _setHidden:forced:] + 294
    14  UIKit                               0x0000000106a1fe54 -[UIWindow makeKeyAndVisible] + 42
    15  UIKit                               0x00000001069928b8 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4737
    16  UIKit                               0x0000000106997aeb -[UIApplication _runWithMainScene:transitionContext:completion:] + 1720
    17  UIKit                               0x0000000106d616f8 __111-[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:]_block_invoke + 924
    18  UIKit                               0x00000001071374c8 +[_UICanvas _enqueuePostSettingUpdateTransactionBlock:] + 153
    19  UIKit                               0x0000000106d612f1 -[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:] + 249
    20  UIKit                               0x0000000106d61b6b -[__UICanvasLifecycleMonitor_Compatability activateEventsOnly:withContext:completion:] + 696
    21  UIKit                               0x00000001076dfa69 __82-[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:]_block_invoke + 262
    22  UIKit                               0x00000001076df922 -[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:] + 444
    23  UIKit                               0x00000001073bc9c8 __125-[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:]_block_invoke + 221
    24  UIKit                               0x00000001075bbb06 _performActionsWithDelayForTransitionContext + 100
    25  UIKit                               0x00000001073bc88b -[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:] + 231
    26  UIKit                               0x0000000107136b25 -[_UICanvas scene:didUpdateWithDiff:transitionContext:completion:] + 392
    27  UIKit                               0x000000010699636a -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 523
    28  UIKit                               0x0000000106f71605 -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 369
    29  FrontBoardServices                  0x000000010bc38cc0 -[FBSSceneImpl _didCreateWithTransitionContext:completion:] + 338
    30  FrontBoardServices                  0x000000010bc417b5 __56-[FBSWorkspace client:handleCreateScene:withCompletion:]_block_invoke_2 + 235
    31  libdispatch.dylib                   0x000000010ae9733d _dispatch_client_callout + 8
    32  libdispatch.dylib                   0x000000010ae9c9f3 _dispatch_block_invoke_direct + 592
    33  FrontBoardServices                  0x000000010bc6d498 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
    34  FrontBoardServices                  0x000000010bc6d14e -[FBSSerialQueue _performNext] + 464
    35  FrontBoardServices                  0x000000010bc6d6bd -[FBSSerialQueue _performNextFromRunLoopSource] + 45
    36  CoreFoundation                      0x0000000109d18101 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    37  CoreFoundation                      0x0000000109db7f71 __CFRunLoopDoSource0 + 81
    38  CoreFoundation                      0x0000000109cfca19 __CFRunLoopDoSources0 + 185
    39  CoreFoundation                      0x0000000109cfbfff __CFRunLoopRun + 1279
    40  CoreFoundation                      0x0000000109cfb889 CFRunLoopRunSpecific + 409
    41  GraphicsServices                    0x000000010c5019c6 GSEventRunModal + 62
    42  UIKit                               0x00000001069995d6 UIApplicationMain + 159
    43  FoodTracker                         0x00000001057e7b67 main + 55
    44  libdyld.dylib                       0x000000010af13d81 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

Here is my Code:

And the connections inspector of the button:


问:
Log4net not logging on Azure Webapp
For a web service, I have log4net configured and working fine locally but not when the webapp is deployed on Azure Webapp. The directory is created but there is nothing logged at the file..

Here is my config:

```<code><log4net>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
  <file value="log/sms.log" />
  <appendToFile value="true" />
  <maximumFileSize value="10MB" />
  <maxSizeRollBackups value="10" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %level - %message%newline" />
  </layout>
</appender>
<logger name="TheLogger">
  <appender-ref ref="RollingFile" />
</logger>
</code>```

Within my AssemblyInfo.cs I have:

```<code>[assembly: XmlConfigurator(Watch = true)]
</code>```

At the Startup class i have :

```<code>public static ILog Logger { get; private set; }

    public void Configuration(IAppBuilder appBuilder)
    {
        Logger = LogManager.GetLogger("TheLogger");
        Logger.Info("Application start...");
    }
</code>```

Clearly my configuration is being picked up because in my log file is written the hour/date format and also Application start... but not the logging information.
What am i missing?

答:
Make sure you don't forget to add the root configuration.
Are compiling for Debug and deploying in Azure in Release mode?

```<code><log4net>
  <root>
    <level value="INFO" />
    <appender-ref ref="RollingFile" />
  </root>
  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
   <!-- ... -->
  </appender>
</log4net>
</code>```

Title: Log4net not logging on Azure Webapp

Body:
For a web service, I have log4net configured and working fine locally but not when the webapp is deployed on Azure Webapp. The directory is created but there is nothing logged at the file..

Here is my config:

<log4net>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
  <file value="log/sms.log" />
  <appendToFile value="true" />
  <maximumFileSize value="10MB" />
  <maxSizeRollBackups value="10" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %level - %message%newline" />
  </layout>
</appender>
<logger name="TheLogger">
  <appender-ref ref="RollingFile" />
</logger>

Within my AssemblyInfo.cs I have:

[assembly: XmlConfigurator(Watch = true)]

At the Startup class i have :

public static ILog Logger { get; private set; }

    public void Configuration(IAppBuilder appBuilder)
    {
        Logger = LogManager.GetLogger("TheLogger");
        Logger.Info("Application start...");
    }

Clearly my configuration is being picked up because in my log file is written the hour/date format and also Application start... but not the logging information.
What am i missing?

Body:
Make sure you don't forget to add the root configuration.
Are compiling for Debug and deploying in Azure in Release mode?

<log4net>
  <root>
    <level value="INFO" />
    <appender-ref ref="RollingFile" />
  </root>
  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
   <!-- ... -->
  </appender>
</log4net>


问:
Basic Python imports question
If I have a src directory setup like this:

```<code>main.py
pkg1:
    __init__.py
    util.py
pkg2:
    __init__.py
    test.py
</code>```

Can you tell me the best way to import pkg1.util from main.py and from test.py?

Thanks! (If I need to have another __init__.py file in the root directory, let me know?)

答:
Since you mention that this is Python 3, you do not have to add the following to your .py files.  I would still though because it helps backwards portability if some poor sod who's stuck on Python 2 needs to use your code:

```<code>from __future__ import absolute_import
</code>```

Given that you are using Python 3, or that you're using Python 2 and have included the above line, here is your answer:

From main.py:

```<code>import pkg1.util as util
</code>```

from test.py you would use one of two ways depending on whether you considered pkg1 and pkg2 to be things that would always deployed together in the same way in relation to each other, or whether they will instead always be each deployed semi-independently at the top level.  If the first, you would do this:

```<code>from ..pkg1 import util
</code>```

and if it's the second option, this:

```<code>import pkg1.util as util
</code>```

This implies, of course, that you are always running Python from the directory in which main.py is, or that that directory is in PYTHONPATH or ends up in sys.path for some reason (like being the main Python site-packages directory for example).

Title: Basic Python imports question

Body:
If I have a src directory setup like this:

main.py
pkg1:
    __init__.py
    util.py
pkg2:
    __init__.py
    test.py

Can you tell me the best way to import pkg1.util from main.py and from test.py?

Thanks! (If I need to have another __init__.py file in the root directory, let me know?)

Body:
Since you mention that this is Python 3, you do not have to add the following to your .py files.  I would still though because it helps backwards portability if some poor sod who's stuck on Python 2 needs to use your code:

from __future__ import absolute_import

Given that you are using Python 3, or that you're using Python 2 and have included the above line, here is your answer:

From main.py:

import pkg1.util as util

from test.py you would use one of two ways depending on whether you considered pkg1 and pkg2 to be things that would always deployed together in the same way in relation to each other, or whether they will instead always be each deployed semi-independently at the top level.  If the first, you would do this:

from ..pkg1 import util

and if it's the second option, this:

import pkg1.util as util

This implies, of course, that you are always running Python from the directory in which main.py is, or that that directory is in PYTHONPATH or ends up in sys.path for some reason (like being the main Python site-packages directory for example).


问:
Repeat audio file, and stop when the task changed
I want to repeat to play audio file which says "Searching" every 1 minute. How can i implement it, to stop this file, when the CASE_STATUS_SEARCHING will change to other? I used TIMER and SOUNDPOOL :

```<code>public class Player {
private static SoundPool soundPool;
private static int searching;
final Timer timer = new Timer();

public void searching () {
    timer.schedule(new TimerTask() {
                       @Override
                       public void run() {
                           soundPool.play(searching, 1.0f, 1.0f, 1, 0, 1.0f);
                       }
                   }, 60000);
}
</code>```

//and I start thread here :

```<code>public class Locator BroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive (Context context, Intent intent) {
final String action = intent.getAction();

switch (newStatus) {
    case STATUS_SEARCHING:
                        stateStr = getString(R.string.Scanning);
                        tvStatus.setText(R.string.Scanning);
                        Player.searching();
                        break;
}
</code>```

答:
I solved it on my own with little help from stackoverflow.

```<code>public void playStillSearching() {

    if (handler == null) {
            handler = new Handler();
            handler.postDelayed(runnable = new Runnable() {
                @Override
                public void run() {
                    soundPool.play(stillSearching, 1.0f, 1.0f, 1, 0, 1.0f);
                    handler.postDelayed(this, 3000);
                }
            }, 3000);
    }
}

public void stopSpeak() {

    if (handler != null) {
        handler.removeCallbacks(runnable);
    }
}
</code>```

than i implement those to my events.

Body:
I want to repeat to play audio file which says "Searching" every 1 minute. How can i implement it, to stop this file, when the CASE_STATUS_SEARCHING will change to other? I used TIMER and SOUNDPOOL :

public class Player {
private static SoundPool soundPool;
private static int searching;
final Timer timer = new Timer();

public void searching () {
    timer.schedule(new TimerTask() {
                       @Override
                       public void run() {
                           soundPool.play(searching, 1.0f, 1.0f, 1, 0, 1.0f);
                       }
                   }, 60000);
}

//and I start thread here :

public class Locator BroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive (Context context, Intent intent) {
final String action = intent.getAction();

switch (newStatus) {
    case STATUS_SEARCHING:
                        stateStr = getString(R.string.Scanning);
                        tvStatus.setText(R.string.Scanning);
                        Player.searching();
                        break;
}

Body:
I solved it on my own with little help from stackoverflow.

public void playStillSearching() {

    if (handler == null) {
            handler = new Handler();
            handler.postDelayed(runnable = new Runnable() {
                @Override
                public void run() {
                    soundPool.play(stillSearching, 1.0f, 1.0f, 1, 0, 1.0f);
                    handler.postDelayed(this, 3000);
                }
            }, 3000);
    }
}

public void stopSpeak() {

    if (handler != null) {
        handler.removeCallbacks(runnable);
    }
}

than i implement those to my events.


问:
Xib file as a Custom TableView Cell crashes
I am using Xib file as a custom Tableview Cell. But everytime i run my application, it crashes. I get this crash logs which i posted below

* Assertion failure in -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3600.7.47/UITableView.m:6730
  2017-12-04 17:23:16.070 iCommander[2489:135476] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
  *** First throw call stack:
  (
      0   CoreFoundation                      0x00000001035f6b0b exceptionPreprocess + 171
      1   libobjc.A.dylib                     0x000000010305b141 objc_exception_throw + 48
      2   CoreFoundation                      0x00000001035facf2 +[NSException raise:format:arguments:] + 98
      3   Foundation                          0x0000000102bf5536 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 193
      4   UIKit                               0x00000001042eae45 -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:] + 241
      5   iCommander                          0x0000000101e6b43f _TFC10iCommander25CommentsHistoryController9tableViewfTCSo11UITableView12cellForRowAtV10Foundation9IndexPath_CSo15UITableViewCell + 303
      6   iCommander                          0x0000000101e6ba07 _TToFC10iCommander25CommentsHistoryController9tableViewfTCSo11UITableView12cellForRowAtV10Foundation9IndexPath_CSo15UITableViewCell + 87
      7   UIKit                               0x00000001042fdab2 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 750
      8   UIKit                               0x00000001042fdcf8 -[UITableView _createPreparedCellForGlobalRow:willDisplay:] + 74
      9   UIKit                               0x00000001042d2639 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2845
      10  UIKit                               0x0000000104306ccc -[UITableView _performWithCachedTraitCollection:] + 111
      11  UIKit                               0x00000001042ede7a -[UITableView layoutSubviews] + 233
      12  UIKit                               0x000000010425455b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1268
      13  QuartzCore                          0x0000000102429904 -[CALayer layoutSublayers] + 146
      14  QuartzCore                          0x000000010241d526 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 370
      15  QuartzCore                          0x000000010241d3a0 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
      16  QuartzCore                          0x00000001023ace92 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
      17  QuartzCore                          0x00000001023d9130 _ZN2CA11Transaction6commitEv + 468
      18  QuartzCore                          0x00000001023d9b37 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 115
      19  CoreFoundation                      0x000000010359c717 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 23
      20  CoreFoundation                      0x000000010359c687 __CFRunLoopDoObservers + 391
      21  CoreFoundation                      0x0000000103581720 __CFRunLoopRun + 1200
      22  CoreFoundation                      0x0000000103581016 CFRunLoopRunSpecific + 406
      23  GraphicsServices                    0x00000001091e1a24 GSEventRunModal + 62
      24  UIKit                               0x0000000104191134 UIApplicationMain + 159
      25  iCommander                          0x0000000101e13ea7 main + 55
      26  libdyld.dylib                       0x000000010743e65d start + 1
      27  ???                                 0x0000000000000001 0x0 + 1
  )
  libc++abi.dylib: terminating with uncaught exception of type NSException

Please help. Thanks in advance.

答:
IN Swift 3

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = Bundle.main.loadNibNamed("XibName", owner: self, options: nil)?.first as! XibName

 return cell

    }
</code>```

Body:
IN Swift 3

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = Bundle.main.loadNibNamed("XibName", owner: self, options: nil)?.first as! XibName

 return cell

    }


问:
Is there a way to configure router forwarding in a wireless network?
I'm running a web server on my laptop and using a service called no-ip to couple
the domain with my IP.

The problem is that the IP recognized is the router's IP.

Usually I use wireless networks so I can't configure port forwarding from a specific router.
Is there a way to configure a router remotely?

Another question: after forwarding configuration, will I be recognized on the internet by my PC's IP?

答:
You can configure most routers using a web browser by navigating to an address like 192.168.1.1 or 192.168.0.1 (it depends on the router, really). Then you can do port forwarding and things like that (if you have administrator access to the router, of course).

As for your external ip, it should always remain to be the ip of your router...

EDIT:

If you keep switching routers by moving around, your IP will keep changing -- I'm not sure if the no-ip service you have will work very well with that


问:
Compress JPG image into RequestBody without creating a File
I want to send a JPG file to my server with a size limit fixed to 500KB. This file should never be written to the phone storage (it contains confidential data).

My input is a byte array returned from the camera.

For now this is what I am doing

```<code>public Observable<User> uploadPicture(byte[] pictureBytes) {
    RequestBody pictureFormatted = RequestBody.create(MediaType.parse("image/*"), pictureBytes);
    MultipartBody.Part picturePart = MultipartBody.Part.createFormData("confidentialPicture", "confidentialPicture.jpg", pictureFormatted);

    return api.uploadPicture(picturePart);
}
</code>```

How can I create my RequestBody with this size constraint ? I am ok with scaling down the image quality.

答:
This can be achieved using a bitmap

I just had to use a Bitmap with a ByteArrayOutputStream to compress my picture, but I could not find a way to get a precise size in output.

```<code>public static byte[] compressCapture(byte[] capture, int maxSizeKB) {

    // This should be different based on the original capture size
    int compression = 12;

    Bitmap bitmap  = BitmapFactory.decodeByteArray(capture, 0, capture.length);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, compression, outputStream);
    return outputStream.toByteArray();
}

public Observable<User> uploadPicture(byte[] pictureBytes) {
    RequestBody pictureFormatted = RequestBody.create(MediaType.parse("image/*"), compressCapture(pictureBytes, 500));
    MultipartBody.Part.createFormData("confidentialPicture", "confidentialPicture.jpg", pictureFormatted);

    return api.uploadPicture(picturePart);
}
</code>```

Body:
I want to send a JPG file to my server with a size limit fixed to 500KB. This file should never be written to the phone storage (it contains confidential data).

My input is a byte array returned from the camera.

For now this is what I am doing

public Observable<User> uploadPicture(byte[] pictureBytes) {
    RequestBody pictureFormatted = RequestBody.create(MediaType.parse("image/*"), pictureBytes);
    MultipartBody.Part picturePart = MultipartBody.Part.createFormData("confidentialPicture", "confidentialPicture.jpg", pictureFormatted);

    return api.uploadPicture(picturePart);
}

How can I create my RequestBody with this size constraint ? I am ok with scaling down the image quality.

Body:
This can be achieved using a bitmap

I just had to use a Bitmap with a ByteArrayOutputStream to compress my picture, but I could not find a way to get a precise size in output.

public static byte[] compressCapture(byte[] capture, int maxSizeKB) {

    // This should be different based on the original capture size
    int compression = 12;

    Bitmap bitmap  = BitmapFactory.decodeByteArray(capture, 0, capture.length);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, compression, outputStream);
    return outputStream.toByteArray();
}

public Observable<User> uploadPicture(byte[] pictureBytes) {
    RequestBody pictureFormatted = RequestBody.create(MediaType.parse("image/*"), compressCapture(pictureBytes, 500));
    MultipartBody.Part.createFormData("confidentialPicture", "confidentialPicture.jpg", pictureFormatted);

    return api.uploadPicture(picturePart);
}


问:
Glassfish 5 not working with Intellij 2017 2.4
I am new to Intellij ide and i'm having issues running Glassfish 5 or any previous version on Intellij 2017 2.4.

After selecting New Project > Java Enterprise > Web Application i had to specify the application server, to which i selected the folder of glassfish 5, jdk is set to 1.8 and java ee to 7. So far so good, no errors and the project gets created. Then i have a greyed "play" icon next to GlassFish 5.0.0 in the upper right of the corner that says that i have to configure it, i click Edit Configurations and the Run/Debug Configurations opens up
Everything seems fine and when i click the "play" green button to start the server and run the project i have projectName:war exploded under Deployment and

```<code>[2017-09-26 08:47:57,836] Artifact testfornew:war exploded: Waiting for server connection to start artifact deployment...
Detected server admin port: 4848
Detected server http port: 8080
Exception in thread "main" java.lang.NullPointerException
at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.initializeServiceLocator(AbstractModulesRegistryImpl.java:152)
at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.newServiceLocator(AbstractModulesRegistryImpl.java:144)
at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.createServiceLocator(AbstractModulesRegistryImpl.java:218)
at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.createServiceLocator(AbstractModulesRegistryImpl.java:224)
at com.sun.enterprise.module.single.StaticModulesRegistry.createServiceLocator(StaticModulesRegistry.java:88)
at com.sun.enterprise.admin.cli.CLIContainer.getServiceLocator(CLIContainer.java:217)
at com.sun.enterprise.admin.cli.CLIContainer.getLocalCommand(CLIContainer.java:255)
at com.sun.enterprise.admin.cli.CLICommand.getCommand(CLICommand.java:231)
at com.sun.enterprise.admin.cli.AdminMain.executeCommand(AdminMain.java:371)
at com.sun.enterprise.admin.cli.AdminMain.doMain(AdminMain.java:306)
at org.glassfish.admin.cli.AsadminMain.main(AsadminMain.java:57)
</code>```

Under output. Coming from Netbeans setting glassfish up was pretty straightforward, i've checked a couple of solutions online including this but they don't seem to work for me.

答: In my case JDK 1.8.0_152 must be installed, path and java_home variables have to be configured AND JDK 9.X must be uninstalled. Without uninstall, the error persist.</p>

Body:
I am new to Intellij ide and i'm having issues running Glassfish 5 or any previous version on Intellij 2017 2.4.

After selecting New Project > Java Enterprise > Web Application i had to specify the application server, to which i selected the folder of glassfish 5, jdk is set to 1.8 and java ee to 7. So far so good, no errors and the project gets created. Then i have a greyed "play" icon next to GlassFish 5.0.0 in the upper right of the corner that says that i have to configure it, i click Edit Configurations and the Run/Debug Configurations opens up
Everything seems fine and when i click the "play" green button to start the server and run the project i have projectName:war exploded under Deployment and

[2017-09-26 08:47:57,836] Artifact testfornew:war exploded: Waiting for server connection to start artifact deployment...
Detected server admin port: 4848
Detected server http port: 8080
Exception in thread "main" java.lang.NullPointerException
at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.initializeServiceLocator(AbstractModulesRegistryImpl.java:152)
at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.newServiceLocator(AbstractModulesRegistryImpl.java:144)
at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.createServiceLocator(AbstractModulesRegistryImpl.java:218)
at com.sun.enterprise.module.common_impl.AbstractModulesRegistryImpl.createServiceLocator(AbstractModulesRegistryImpl.java:224)
at com.sun.enterprise.module.single.StaticModulesRegistry.createServiceLocator(StaticModulesRegistry.java:88)
at com.sun.enterprise.admin.cli.CLIContainer.getServiceLocator(CLIContainer.java:217)
at com.sun.enterprise.admin.cli.CLIContainer.getLocalCommand(CLIContainer.java:255)
at com.sun.enterprise.admin.cli.CLICommand.getCommand(CLICommand.java:231)
at com.sun.enterprise.admin.cli.AdminMain.executeCommand(AdminMain.java:371)
at com.sun.enterprise.admin.cli.AdminMain.doMain(AdminMain.java:306)
at org.glassfish.admin.cli.AsadminMain.main(AsadminMain.java:57)

Under output. Coming from Netbeans setting glassfish up was pretty straightforward, i've checked a couple of solutions online including this but they don't seem to work for me.


问:
Jersey - Unit testing resource with spring-injected service
My question is similar to this one.

Setting:
I have a GreetingResource which has a Autowired GreetingService to handle GET requests:

```<code>@Path("greetings")
public class GreetingResource
{

@Autowired
private GreetingService service;

@GET
@Produces(MediaType.TEXT_PLAIN_VALUE)
public String getHello()
{
    try
    {
        return service.greet("world");
    }
    catch(SQLException e)
    {
        System.out.println("Request failed (500)");
        e.printStackTrace();
        return null;
    }
}
}
</code>```

Problem: In my unit test I get
    org.springframework.beans.factory.NoSuchBeanDefinitionException:

```<code>No qualifying bean of type 'demo.rest.jersey.spring.GreetingService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1466)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1097)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059)
    at org.glassfish.jersey.server.spring.AutowiredInjectResolver.getBeanFromSpringContext(AutowiredInjectResolver.java:104)
    at org.glassfish.jersey.server.spring.AutowiredInjectResolver.resolve(AutowiredInjectResolver.java:96)
</code>```

Unit test class: In order to unit test this I have a testContext.xml which acts as application context for unit tests. It creates just one bean, namely the TestConfig:

```<code>@Configuration
public class TestConfig
{
    @Bean
    @Primary
    public GreetingService greetingService() throws SQLException
    {
        GreetingService service = Mockito.mock(GreetingService.class);
        when(service.greet(anyString())).thenReturn("Hello");
        return service;
    }
}
</code>```

The testContext.xml should be loaded by the unit test and hence the correct beans created:

```<code>public class Test_GreetingResource extends JerseyTest
{
    @Override
    protected TestContainerFactory getTestContainerFactory()
    {
        return new GrizzlyWebTestContainerFactory();
    }

    @Override
    protected DeploymentContext configureDeployment(){
        return ServletDeploymentContext
                .forServlet(new ServletContainer(new TestApp()))
                .addListener(ContextLoaderListener.class)
                .contextParam("contextConfigLocation", "classpath:testContext.xml")
                .build();
    }

    @Test
    public void doTest() throws SQLException
    {
        String response = target("greetings").request().get(String.class);
        assertEquals("response incorrect", "Hello", response);
        System.out.println(response);
    }
}
</code>```

Notes: The TestApp simply registers the GreetingResource

```<code>public class TestApp extends ResourceConfig
{
    public TestApp()
    {
        register(GreetingResource.class);
        packages("demo.rest.jersey.spring");
    }
}
</code>```

Here is also the testContext.xml that I mentioned above:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="testConfig" class="demo.rest.jersey.spring.TestConfig"></bean>
</beans>
</code>```

Additional question: If the GreetingService mock is created as a bean, can I somehow alter the mock behaviour? I.e. right now I specify in the TestConfig what response the mock should give but I might want to alter that behaviour from test to test.

Thanks for the help!

答:
I followed this answer and injected the GreetingService into the constructor of GreetingResource.

Then it's just

```<code>public class Test_GreetingResource extends JerseyTest
{
    @Mock
    private GreetingService service;

    @Override
    public ResourceConfig configure()
    {
        MockitoAnnotations.initMocks(this);
        return new ResourceConfig()
            .register(new GreetingResource(service));
    }

    @Test
    public void testMockedGreetingService()
    {
        try {
            when(service.greet(anyString())).thenReturn("Hello there");
        } catch (SQLException e) {
            fail("service cannot greet");
        }

        Response response = target("greetings")
                .request(MediaType.TEXT_PLAIN).get();

        String msg = response.readEntity(String.class);
        System.out.println("Message: " + msg);

        response.close();
    }
}
</code>```

Body:
My question is similar to this one.

Setting:
I have a GreetingResource which has a Autowired GreetingService to handle GET requests:

@Path("greetings")
public class GreetingResource
{

@Autowired
private GreetingService service;

@GET
@Produces(MediaType.TEXT_PLAIN_VALUE)
public String getHello()
{
    try
    {
        return service.greet("world");
    }
    catch(SQLException e)
    {
        System.out.println("Request failed (500)");
        e.printStackTrace();
        return null;
    }
}
}

Problem: In my unit test I get
    org.springframework.beans.factory.NoSuchBeanDefinitionException:

No qualifying bean of type 'demo.rest.jersey.spring.GreetingService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1466)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1097)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059)
    at org.glassfish.jersey.server.spring.AutowiredInjectResolver.getBeanFromSpringContext(AutowiredInjectResolver.java:104)
    at org.glassfish.jersey.server.spring.AutowiredInjectResolver.resolve(AutowiredInjectResolver.java:96)

Unit test class: In order to unit test this I have a testContext.xml which acts as application context for unit tests. It creates just one bean, namely the TestConfig:

@Configuration
public class TestConfig
{
    @Bean
    @Primary
    public GreetingService greetingService() throws SQLException
    {
        GreetingService service = Mockito.mock(GreetingService.class);
        when(service.greet(anyString())).thenReturn("Hello");
        return service;
    }
}

The testContext.xml should be loaded by the unit test and hence the correct beans created:

public class Test_GreetingResource extends JerseyTest
{
    @Override
    protected TestContainerFactory getTestContainerFactory()
    {
        return new GrizzlyWebTestContainerFactory();
    }

    @Override
    protected DeploymentContext configureDeployment(){
        return ServletDeploymentContext
                .forServlet(new ServletContainer(new TestApp()))
                .addListener(ContextLoaderListener.class)
                .contextParam("contextConfigLocation", "classpath:testContext.xml")
                .build();
    }

    @Test
    public void doTest() throws SQLException
    {
        String response = target("greetings").request().get(String.class);
        assertEquals("response incorrect", "Hello", response);
        System.out.println(response);
    }
}

Notes: The TestApp simply registers the GreetingResource

public class TestApp extends ResourceConfig
{
    public TestApp()
    {
        register(GreetingResource.class);
        packages("demo.rest.jersey.spring");
    }
}

Here is also the testContext.xml that I mentioned above:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="testConfig" class="demo.rest.jersey.spring.TestConfig"></bean>
</beans>

Additional question: If the GreetingService mock is created as a bean, can I somehow alter the mock behaviour? I.e. right now I specify in the TestConfig what response the mock should give but I might want to alter that behaviour from test to test.

Thanks for the help!

Body:
I followed this answer and injected the GreetingService into the constructor of GreetingResource.

Then it's just

public class Test_GreetingResource extends JerseyTest
{
    @Mock
    private GreetingService service;

    @Override
    public ResourceConfig configure()
    {
        MockitoAnnotations.initMocks(this);
        return new ResourceConfig()
            .register(new GreetingResource(service));
    }

    @Test
    public void testMockedGreetingService()
    {
        try {
            when(service.greet(anyString())).thenReturn("Hello there");
        } catch (SQLException e) {
            fail("service cannot greet");
        }

        Response response = target("greetings")
                .request(MediaType.TEXT_PLAIN).get();

        String msg = response.readEntity(String.class);
        System.out.println("Message: " + msg);

        response.close();
    }
}


问:
css, flex-direction, sticky element
I'm working with flex and two modes to change the flex-direction:

```<code>@mixin for-medium-up {
@media (min-width: 670px) { @content; }
}
@mixin for-large-up {
@media (min-width: 880px) { @content; }
}
</code>```

In the first mode (min-width: 880px), I want to have a sticky element on the right-hand side as follows:

the sticky element is defined as follows:

```<code>.sticky {
position: -webkit-sticky;
position: -moz-sticky;
position: -ms-sticky;
position: -o-sticky;
position: sticky;
}
</code>```

In the second mode (min-width: 670px), I want to have it as follows:

where the sticky element is sticky in the first mode, it does not stick in the second one.

here is the Demo

答:
The answer isn't quite as simple as attaching something to the parent element.

I've modified your demo and made some simplifications for clarity but I believe it achieves your intended goal.

Modified Demo

Consider the case where the elements are side-by-side...

The default value of align-items for flex box items is stretch (see MDN Docs). This means that the .view element grows in size to fill the full height, meaning that it never has the opportunity to become "stuck". This can be addressed by using align-self: flex start or by explicity setting the height, e.g. height: 100px.

If you un-comment line 10 and comment-out line 11, you'll see the issue.

Hope this helps.

Title: css, flex-direction, sticky element

Body:
I'm working with flex and two modes to change the flex-direction:

@mixin for-medium-up {
@media (min-width: 670px) { @content; }
}
@mixin for-large-up {
@media (min-width: 880px) { @content; }
}

In the first mode (min-width: 880px), I want to have a sticky element on the right-hand side as follows:

the sticky element is defined as follows:

.sticky {
position: -webkit-sticky;
position: -moz-sticky;
position: -ms-sticky;
position: -o-sticky;
position: sticky;
}

In the second mode (min-width: 670px), I want to have it as follows:

where the sticky element is sticky in the first mode, it does not stick in the second one.

here is the Demo


问:
In Javafx when a window is opened how can i set it so that the user isnt able to open the same window again?

I tried a lot but just couldn't find any solution. At the moment the opened window(popup window) is always on top but the user can still access the main window. That's how it should be, but it shouldn't be possible to open the same popup window again.
</p>

```<code>    Stage stage = new Stage();
    stage.setTitle(panelTitle);
    stage.setScene(new Scene(root));
    stage.initModality(Modality.WINDOW_MODAL);
    stage.setAlwaysOnTop(true);
    stage.showAndWait();
</code>```

<p>
Thank you in advance!
</p>

答:
An alternative solution to creating a new one each time is to create one and just setup and show.

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

    private final Stage popup = new Stage();

    @Override
    public void start(Stage stage) throws Exception {

        BorderPane root = new BorderPane();
        root.setPrefWidth(400);
        root.setPrefHeight(200);

        Button button = new Button("ClickMePopup");

        root.setCenter(button);

        button.setOnAction(
                event -> {
                    if (!popup.isShowing()) {
                        // you dont set modality because after the stage is set to visible second time it will throw an exception.
                        // Again depends on what you need.
                        // popup.initModality(Modality.WINDOW_MODAL);

                        // this focuses the popup and main window is not clickable
                        // popup.initOwner(stage);

                        VBox dialogVbox = new VBox(20);
                        dialogVbox.getChildren().add(new Text("Some Dialog"));
                        Scene dialogScene = new Scene(dialogVbox, 300, 200);
                        popup.setScene(dialogScene);

                        // you can actually put all above into the method called initPopup() or whatever, do it once, and just show it here or just bind the property to the button.

                        popup.show();
                    }
                });

        Scene scene = new Scene(root);

        stage.setTitle("Stack");
        stage.setScene(scene);
        stage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }

}
</code>```

Or disable the button when clicked, but if your popup is not driven by the button or can be opened from other places the first idea would be a bit better in my opinion. Depends on what you need.

Or just create your own class and Springify it.

Body:
I tried a lot but just couldn't find any solution. At the moment the opened window(popup window) is always on top but the user can still access the main window. That's how it should be, but it shouldn't be possible to open the same popup window again.

    Stage stage = new Stage();
    stage.setTitle(panelTitle);
    stage.setScene(new Scene(root));
    stage.initModality(Modality.WINDOW_MODAL);
    stage.setAlwaysOnTop(true);
    stage.showAndWait();

Thank you in advance!

Body:
An alternative solution to creating a new one each time is to create one and just setup and show.

public class Stack extends Application {

    private final Stage popup = new Stage();

    @Override
    public void start(Stage stage) throws Exception {

        BorderPane root = new BorderPane();
        root.setPrefWidth(400);
        root.setPrefHeight(200);

        Button button = new Button("ClickMePopup");

        root.setCenter(button);

        button.setOnAction(
                event -> {
                    if (!popup.isShowing()) {
                        // you dont set modality because after the stage is set to visible second time it will throw an exception.
                        // Again depends on what you need.
                        // popup.initModality(Modality.WINDOW_MODAL);

                        // this focuses the popup and main window is not clickable
                        // popup.initOwner(stage);

                        VBox dialogVbox = new VBox(20);
                        dialogVbox.getChildren().add(new Text("Some Dialog"));
                        Scene dialogScene = new Scene(dialogVbox, 300, 200);
                        popup.setScene(dialogScene);

                        // you can actually put all above into the method called initPopup() or whatever, do it once, and just show it here or just bind the property to the button.

                        popup.show();
                    }
                });

        Scene scene = new Scene(root);

        stage.setTitle("Stack");
        stage.setScene(scene);
        stage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }

}

Or disable the button when clicked, but if your popup is not driven by the button or can be opened from other places the first idea would be a bit better in my opinion. Depends on what you need.

Or just create your own class and Springify it.


问:
PowerShell Get Users Email Address To Exchange
Trying to do an auto ligation hold script using an ad synced group up to Azure. Would anyone be able to help with the below?

I'm trying to get all my users from the MsolGroup by doing a return of the MsolGroupMembers, I would like to return the users then from that I need to get their UPN/Email Address so I can pipe it into an exchange online command to turn litigation hold on for each of them users from the group.

```<code>Import-Module MSOnline
$user="removed"

$file = "removed"

$password = Get-Content $File | ConvertTo-SecureString

$cred = New-Object System.Management.Automation.PsCredential($user,$password)

Connect-MsolService -Credential $cred
$UserCredential = Get-Credential -Credential $cred

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session

$usersOfGroup = Get-MsolGroupMember -GroupObjectId removedID -All

foreach ($user in $usersOfGroup)
{
    $mailbox = Get-Mailbox $user.EmailAddress

    Write-Output $mailbox

    if ($mailbox.LitigationHoldEnabled -eq $false -and $mailbox.RecipientTypeDetails -eq "UserMailbox")
    {
        Write-Output "Current mailbox: " $mailbox.UserPrincipalName
        Set-Mailbox -Identity $mailbox.UserPrincipalName -LitigationHoldEnabled $true -LitigationHoldDuration 2555 -WarningAction SilentlyContinue
    }
}

Remove-PSSession $Session
</code>```

答:
This should do the trick.</p>

```<code>    #Useful Microsoft documentation
    #https://technet.microsoft.com/en-us/library/dn767952(v=exchg.160).aspx

    #Connect to Exchange Online
    Import-Module MSOnline
    $O365Cred = Get-Credential
    $O365Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.outlook.com/powershell" -Credential $O365Cred -Authentication Basic -AllowRedirection
    Import-PSSession $O365Session -AllowClobber
    Connect-MsolService -Credential $O365Cred

    #Filter mailboxes for the HR Department, pipe to the set litigation command for 365 days
   Get-Recipient -RecipientTypeDetails UserMailbox -ResultSize unlimited -Filter 'Department -eq "HR"' | Set-Mailbox -LitigationHoldEnabled $true -LitigationHoldDuration 365
    Remove-PSSession -Id $O365Session.Id
</code>```

Body:
Trying to do an auto ligation hold script using an ad synced group up to Azure. Would anyone be able to help with the below?

I'm trying to get all my users from the MsolGroup by doing a return of the MsolGroupMembers, I would like to return the users then from that I need to get their UPN/Email Address so I can pipe it into an exchange online command to turn litigation hold on for each of them users from the group.

Import-Module MSOnline
$user="removed"

$file = "removed"

$password = Get-Content $File | ConvertTo-SecureString

$cred = New-Object System.Management.Automation.PsCredential($user,$password)

Connect-MsolService -Credential $cred
$UserCredential = Get-Credential -Credential $cred

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session

$usersOfGroup = Get-MsolGroupMember -GroupObjectId removedID -All

foreach ($user in $usersOfGroup)
{
    $mailbox = Get-Mailbox $user.EmailAddress

    Write-Output $mailbox

    if ($mailbox.LitigationHoldEnabled -eq $false -and $mailbox.RecipientTypeDetails -eq "UserMailbox")
    {
        Write-Output "Current mailbox: " $mailbox.UserPrincipalName
        Set-Mailbox -Identity $mailbox.UserPrincipalName -LitigationHoldEnabled $true -LitigationHoldDuration 2555 -WarningAction SilentlyContinue
    }
}

Remove-PSSession $Session

Body:
This should do the trick.

    #Useful Microsoft documentation
    #https://technet.microsoft.com/en-us/library/dn767952(v=exchg.160).aspx

    #Connect to Exchange Online
    Import-Module MSOnline
    $O365Cred = Get-Credential
    $O365Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.outlook.com/powershell" -Credential $O365Cred -Authentication Basic -AllowRedirection
    Import-PSSession $O365Session -AllowClobber
    Connect-MsolService -Credential $O365Cred

    #Filter mailboxes for the HR Department, pipe to the set litigation command for 365 days
   Get-Recipient -RecipientTypeDetails UserMailbox -ResultSize unlimited -Filter 'Department -eq "HR"' | Set-Mailbox -LitigationHoldEnabled $true -LitigationHoldDuration 365
    Remove-PSSession -Id $O365Session.Id


问:
Removing an event handler by setting null is not working in Firefox 3.6
I was experimenting this code. It worked well in Chrome but not in Firefox 3.6</p>
```<code><body onmousedown="return false" oncontextmenu="return false">
<p>once there lived</p>
<div style='color:red; height: 300px; width:100%;'>
hehe</div>

<script>
/*
window.setTimeout( function() {
     document.body.onmousedown = function() { return true; }
     document.body.oncontextmenu = function() { return true; }
     document.onmousedown = function() { return true; }
     document.oncontextmenu = function() { return true; }
     alert('ready to check');
},5000)
*/

window.setTimeout( function() {
     document.body.onmousedown = null;
     document.body.oncontextmenu = null;
     document.onmousedown = null;
     document.oncontextmenu = null;
     alert('ready to check');
},5000)

</script>
</body>
</code>```

答: In Gecko-based browsers  maps to window.onmousedown, not document.onmousedown or document.body.onmousedown. On other elements the mousedown element maps to the mousedown property as expected.

Body:
I was experimenting this code. It worked well in Chrome but not in Firefox 3.6

once there lived

hehe

Body: In Gecko-based browsers <body onmousedown> maps to window.onmousedown, not document.onmousedown or document.body.onmousedown. On other elements the mousedown element maps to the mousedown property as expected.


问:
exceptions throw or catch and try
I'm trying to learn java and I have a little problem with understanding how exceptions work.

When do we need to use throw after a condition?
As an example

```<code>public Ex(String name, String prenom, int age) throws exceptionex  {
    if (name.length() < 3 && prenom.length() < 3 && age < 1) throw new exceptionex();

        this.age = age;
        this.name = name;
        this.prenom = prenom;

}
</code>```

excepetionex is an empty class which extends Exception.

And what is the difference between the previous example and this one?

```<code>public Ex(String name, String prenom, int age)   {
    if (name.length() < 3 && prenom.length() < 3 && age < 1)
        try {
            throw new exceptionex();
        } catch (exceptionex e) {
            e.printStackTrace();
        }

        this.age = age;
        this.name = name;
        this.prenom = prenom;

}
</code>```

And what does printstackTrace exactly do?

Do we always need to create another class if we wanted to customise an exception (exeptionex here ) or we can just use (throw new Exception)?

I googled my questions but i didn't find an answer which i can understand maybe because I'm new or because English is not my native language I need a simple explanation as much as possible please.

答:
what is the diffrence between the past example and this one !

The first one stops you creating an instance of Ex if that condition is met.

The second one prints something to stderr, and then creates the instance anyway.

Note that you don't need to throw an exception to print its stack trace:

```<code>new exexception().printStackTrace();
</code>```

does the same as the try/catch in the second example.

And what does printstackTrace exactly does

Your first stop should be Javadoc:

Prints this throwable and its backtrace to the standard error stream. This method prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err. The first line of output contains the result of the toString() method for this object. Remaining lines represent data previously recorded by the method fillInStackTrace()...

It goes on. Read it, and ask a specific question about what you don't understand.

Do we always need to create another class if we wanted to customise an exception (exeptionex here ) or we can just use (throw new Exception)!

You don't always need a new exception type. Effective Java 2nd Ed Item 60 advises to "Favor the use of standard exceptions".

Note that you basically never want to throw Exception itself (and you rarely should catch it).

Title: exceptions throw or catch and try

Body:
I'm trying to learn java and I have a little problem with understanding how exceptions work.

When do we need to use throw after a condition?
As an example

public Ex(String name, String prenom, int age) throws exceptionex  {
    if (name.length() < 3 && prenom.length() < 3 && age < 1) throw new exceptionex();

        this.age = age;
        this.name = name;
        this.prenom = prenom;

}

excepetionex is an empty class which extends Exception.

And what is the difference between the previous example and this one?

public Ex(String name, String prenom, int age)   {
    if (name.length() < 3 && prenom.length() < 3 && age < 1)
        try {
            throw new exceptionex();
        } catch (exceptionex e) {
            e.printStackTrace();
        }

        this.age = age;
        this.name = name;
        this.prenom = prenom;

}

And what does printstackTrace exactly do?

Do we always need to create another class if we wanted to customise an exception (exeptionex here ) or we can just use (throw new Exception)?

I googled my questions but i didn't find an answer which i can understand maybe because I'm new or because English is not my native language I need a simple explanation as much as possible please.

Body:
what is the diffrence between the past example and this one !

The first one stops you creating an instance of Ex if that condition is met.

The second one prints something to stderr, and then creates the instance anyway.

Note that you don't need to throw an exception to print its stack trace:

new exexception().printStackTrace();

does the same as the try/catch in the second example.

And what does printstackTrace exactly does

Your first stop should be Javadoc:

Prints this throwable and its backtrace to the standard error stream. This method prints a stack trace for this Throwable object on the error output stream that is the value of the field System.err. The first line of output contains the result of the toString() method for this object. Remaining lines represent data previously recorded by the method fillInStackTrace()...

It goes on. Read it, and ask a specific question about what you don't understand.

Do we always need to create another class if we wanted to customise an exception (exeptionex here ) or we can just use (throw new Exception)!

You don't always need a new exception type. Effective Java 2nd Ed Item 60 advises to "Favor the use of standard exceptions".

Note that you basically never want to throw Exception itself (and you rarely should catch it).