问:
Dragging a table column using HTML5 and AngularJS
http://jsfiddle.net/asutosh/82qum/

```<code><div ng-app='myApp'>

 <div ng-controller="myCtrl">

<table border="4">
    <thead>
        <th ng-repeat="hd in heads">
            <div draganddrop drag="handleDrag()">{{hd}}</div>
        </th>
        </thead>
        <tr ng-repeat="row in myData">
        <td ng-repeat="hd in heads">
        {{row[hd]}}
        </td>
        </tr>

</table>
</div>
</code>```

Here is the JS:

```<code>  var myApp=angular.module('myApp',[]);
  myApp.controller('myCtrl',function($scope){
  $scope.handleDrag=function()
     {

     }

   $scope.heads=['name','age','company','tech'];

   $scope.myData=[{name:'Jay',age:27,company:'XYZ',tech:'Js'},
            { name:'Rayn',age:30,company:'XYZ',tech:'.net'}]
   });
    myApp.directive('draganddrop',function(){
    return{
    scope:{
        drag:'&'
    },
    link: function(scope, element) {
    // this gives us the native JS object
    var el = element[0];
     el.draggable=true;

    el.addEventListener(
        'dragstart',
        function(e) {

    e.dataTransfer.effectAllowed = 'move';

           // this.classList.add('drag');
            return false;
        },
        false
    );

    el.addEventListener(
        'dragend',
        function(e) {

            this.classList.remove('drag');
            return false;
        },
        false
    );
}
};

});
</code>```

In the above fiddle I want to create a table having column reordering, I am able to set the column header to draggable however while dragging only the header's image is getting dragged, I want the the image of the whole column should come as the dragging image, any suggestion on that will be helpful.

答:
This drag'n'drop library will do it for you:

https://github.com/lorenzofox3/lrDragNDrop

Just include it in your app, and make your  say this:

```<code><th  lr-drag-src="headers" lr-drop-target="headers" ng-repeat="hd in heads" >
</code>```

Body:
http://jsfiddle.net/asutosh/82qum/

{{hd}}

        {{row[hd]}}

Here is the JS:

  var myApp=angular.module('myApp',[]);
  myApp.controller('myCtrl',function($scope){
  $scope.handleDrag=function()
     {

     }

   $scope.heads=['name','age','company','tech'];

   $scope.myData=[{name:'Jay',age:27,company:'XYZ',tech:'Js'},
            { name:'Rayn',age:30,company:'XYZ',tech:'.net'}]
   });
    myApp.directive('draganddrop',function(){
    return{
    scope:{
        drag:'&'
    },
    link: function(scope, element) {
    // this gives us the native JS object
    var el = element[0];
     el.draggable=true;

    el.addEventListener(
        'dragstart',
        function(e) {

    e.dataTransfer.effectAllowed = 'move';

           // this.classList.add('drag');
            return false;
        },
        false
    );

    el.addEventListener(
        'dragend',
        function(e) {

            this.classList.remove('drag');
            return false;
        },
        false
    );
}
};

});

In the above fiddle I want to create a table having column reordering, I am able to set the column header to draggable however while dragging only the header's image is getting dragged, I want the the image of the whole column should come as the dragging image, any suggestion on that will be helpful.

Body:
This drag'n'drop library will do it for you:

https://github.com/lorenzofox3/lrDragNDrop

Just include it in your app, and make your <th> say this:

<th  lr-drag-src="headers" lr-drop-target="headers" ng-repeat="hd in heads" >


来源: stackexchange

问:
Delphi 7 GIF in picture Dialog
I am using Delphi 7 and the OpenPictureDialog to open / preview various images. This works fine when opening a bmp, jpg, etc.; however, if I try to do the same with a gif I get the following error. Anyone got any idea why or have a fix for it?

thanks

Colin

答:
Use this TGIFImage. This is the original unit which was donated to CodeGear in 2006. It supports Delphi7.

copy GifImage.pas to your project path (from gifimaged2010b.zip) ,
and add to your uses list ;

thats all

It will automatically add GIF in filters for openpicturedialog (**)

ContentLicense: CC BY-SA 2.5

Title: Delphi 7 GIF in picture Dialog

ContentLicense: CC BY-SA 3.0


问:
JAVA getResourceAsStream() real path string interpretation of a file
I am using NetBeans 8.0.2 (I know there already is v8.2 but it has a lot of bugs for me so I got back to v8.0.2) and I need a string path to my .obj file for a parameter attribute like this:

```<code>api.parameter("filename", "obj/someFile.obj");
</code>```

Above example worked in a previous version of my app where I had that .obj file placed in a folder called "obj" in the same directory as my .jar file, but now as I am trying to rather include it in the JAR itself with code:

```<code>api.parameter("filename", MyClass.class.getResourceAsStream("/someFile.obj").toString());
</code>```

...it is not working anymore as the path string interpretation is not a path to a file, it looks more like this:

```<code>java.io.BufferedInputStream@215d7ea7
</code>```

...where, of course, my code is expecting something like normal path string, I would said something in this pseudo-code manner:

```<code>api.parameter("filename", "<this.jar>/someFile.obj");
</code>```

So after a fiddling a bit around StackOverflow I've found pieces of code that I thought could actually enable me to directly place that path as a string:

```<code>URL jar = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
api.parameter("filename", jar + "/someFile.obj");
</code>```

But surprisingly although I checked several times if the file actually really exist in my built jar file (and yes, it is there in the root) it still gives me this error:

```<code>java.io.FileNotFoundException: file:\Z:\_JAVA_\MyProject_0_018\dist\bin\myjar.jar\someFile.obj <The filename, directory name, or volume label syntax is incorrect>
</code>```

And I am 100% sure the name of the file is correct, also its placement in the root of my jar file.

Or does it actually thinks that myjar.jar is a directory?

I am desperately trying to find a solution to this "path string" mess.

答:
Your protection domain's code source location likely returns not what you'd expect it to.

You should use getResource(name) directly, like this:

```<code>URL locator = MyClass.class.getResource("someFile.obj");
api.parameter("filename", locator.toString());
</code>```

Body:
I am using NetBeans 8.0.2 (I know there already is v8.2 but it has a lot of bugs for me so I got back to v8.0.2) and I need a string path to my .obj file for a parameter attribute like this:

api.parameter("filename", "obj/someFile.obj");

Above example worked in a previous version of my app where I had that .obj file placed in a folder called "obj" in the same directory as my .jar file, but now as I am trying to rather include it in the JAR itself with code:

api.parameter("filename", MyClass.class.getResourceAsStream("/someFile.obj").toString());

...it is not working anymore as the path string interpretation is not a path to a file, it looks more like this:

java.io.BufferedInputStream@215d7ea7

...where, of course, my code is expecting something like normal path string, I would said something in this pseudo-code manner:

api.parameter("filename", "<this.jar>/someFile.obj");

So after a fiddling a bit around StackOverflow I've found pieces of code that I thought could actually enable me to directly place that path as a string:

URL jar = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
api.parameter("filename", jar + "/someFile.obj");

But surprisingly although I checked several times if the file actually really exist in my built jar file (and yes, it is there in the root) it still gives me this error:

java.io.FileNotFoundException: file:\Z:\_JAVA_\MyProject_0_018\dist\bin\myjar.jar\someFile.obj <The filename, directory name, or volume label syntax is incorrect>

And I am 100% sure the name of the file is correct, also its placement in the root of my jar file.

Or does it actually thinks that myjar.jar is a directory?

I am desperately trying to find a solution to this "path string" mess.

Body:
Your protection domain's code source location likely returns not what you'd expect it to.

You should use getResource(name) directly, like this:

URL locator = MyClass.class.getResource("someFile.obj");
api.parameter("filename", locator.toString());


问:
Cannot get input number from a form in laravel 5.4
I am trying to input number in a form (laravel 5.4) but the code is not working.

I have tried different options but it is not working.

```<code><div class="col-md-4 col-md-offset-2">
{!! Form::open(array('route' => 'properties.store', 'data-parsley-validate' => '' , 'files' => true)) !!}
{{ Form::label('address', 'Address:') }}
{{ Form::text('address', null, array('class'=>'form-control', 'placeholder'=>'Street & Number')) }}

</div>

<div class="col-md-4">

{{ Form::label('price_paid', "Price Paid:") }}
{{ Form::number('fuel',null, ['class' => 'form-control']) }}

{{ Form::label('loan_ltv', "Loan to Value:") }}
{{ Form::input('number', 'amount', null, ['class' => 'form-control']) }}

{{ Form::label('rent', "Rent Achievable:") }}
{{ Form::number('name', 'value', ['class' => 'form-control']) }}

{{ Form::label('mortgage', "Mortgage Rate:") }}
{{ Form::number('name', 'value', ['class' => 'form-control']) }}

{{ Form::label('management_moe', "Management and Operating Expenses:") }}
{{ Form::number('name', 'value', ['class' => 'form-control']) }}

{{ Form::submit('Create Property Case', array('class' => 'btn btn-success btn-lg btn-block', 'style' => 'margin-top: 20px;')) }}
</div>
{!! Form::close() !!}
</div>
</code>```

I have tried different options I found here but it is not working.

```<code>public function store(Request $request)
{
    //validate the data
    $this->validate($request, array(
            'address' =>'max:255|nullable',
            'price_paid' => 'integer|nullable',
            'loan_ltv' => 'integer|nullable',
            'rent' => 'integer|nullable',
            'mortgage' => 'integer|nullable',
            'management_moe' => 'integer|nullable'
            ));
</code>```

When I submit the form, the only thing I see in the database is the street name and the street number. The rest of the rows has nulls.

I can manually input number in the database but I want to do it through the form. Can someone help me???

答:
This is the working code I use after a lot of research:

```<code>            {{ Form::label('price_paid', "Price Paid:") }}
            {{ Form::number('price_paid', null, ['class' => 'form-control']) }}

            {{ Form::label('loan_ltv', "Loan to Value:") }}
            {{ Form::number('loan_ltv', null, ['class' => 'form-control']) }}

            {{ Form::label('rent', "Rent Achievable:") }}
            {{ Form::number('rent', null, ['class' => 'form-control']) }}

            {{ Form::label('mortgage', "Mortgage Rate:") }}
            {{ Form::number('mortgage', null, ['class' => 'form-control']) }}

            {{ Form::label('management_moe', "Management and Operating Expenses:") }}
            {{ Form::number('management_moe', null, ['class' => 'form-control']) }}
</code>```

Body:
I am trying to input number in a form (laravel 5.4) but the code is not working.

I have tried different options but it is not working.

{!! Form::open(array('route' => 'properties.store', 'data-parsley-validate' => '' , 'files' => true)) !!}
{{ Form::label('address', 'Address:') }}
{{ Form::text('address', null, array('class'=>'form-control', 'placeholder'=>'Street & Number')) }}

{{ Form::label('price_paid', "Price Paid:") }}
{{ Form::number('fuel',null, ['class' => 'form-control']) }}

{{ Form::label('loan_ltv', "Loan to Value:") }}
{{ Form::input('number', 'amount', null, ['class' => 'form-control']) }}

{{ Form::label('rent', "Rent Achievable:") }}
{{ Form::number('name', 'value', ['class' => 'form-control']) }}

{{ Form::label('mortgage', "Mortgage Rate:") }}
{{ Form::number('name', 'value', ['class' => 'form-control']) }}

{{ Form::label('management_moe', "Management and Operating Expenses:") }}
{{ Form::number('name', 'value', ['class' => 'form-control']) }}

{{ Form::submit('Create Property Case', array('class' => 'btn btn-success btn-lg btn-block', 'style' => 'margin-top: 20px;')) }}

{!! Form::close() !!}

I have tried different options I found here but it is not working.

public function store(Request $request)
{
    //validate the data
    $this->validate($request, array(
            'address' =>'max:255|nullable',
            'price_paid' => 'integer|nullable',
            'loan_ltv' => 'integer|nullable',
            'rent' => 'integer|nullable',
            'mortgage' => 'integer|nullable',
            'management_moe' => 'integer|nullable'
            ));

When I submit the form, the only thing I see in the database is the street name and the street number. The rest of the rows has nulls.

I can manually input number in the database but I want to do it through the form. Can someone help me???

Body:
This is the working code I use after a lot of research:

            {{ Form::label('price_paid', "Price Paid:") }}
            {{ Form::number('price_paid', null, ['class' => 'form-control']) }}

            {{ Form::label('loan_ltv', "Loan to Value:") }}
            {{ Form::number('loan_ltv', null, ['class' => 'form-control']) }}

            {{ Form::label('rent', "Rent Achievable:") }}
            {{ Form::number('rent', null, ['class' => 'form-control']) }}

            {{ Form::label('mortgage', "Mortgage Rate:") }}
            {{ Form::number('mortgage', null, ['class' => 'form-control']) }}

            {{ Form::label('management_moe', "Management and Operating Expenses:") }}
            {{ Form::number('management_moe', null, ['class' => 'form-control']) }}


问:
Vertical align UL to top of div
I have three ul's added to a footer within bootstrap columns inside a parent row element, and I've used vertical-align:top for a similar footer before, but can't use this here to align each ul to the top of the parent div. (It's added to footer > row > .col > ul)

Any ideas?

Codepen: https://codepen.io/nickwcook/pen/aJPGeJ.

HTML:

```<code><footer>
  <row>
    <div class="col col-sm-3">
      <ul>
        <li>Quick Menu</li>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Contact</a></li>
      </ul>
    </div>
    <div class="col col-sm-3">
      <ul>
        <li>Recent Posts</li>
        <li><a href="#">Post One</a></li>
        <li><a href="#">Post Two</a></li>
        <li><a href="#">Post Three</a></li>
      </ul>
    </div>
    <div class="col col-sm-3">
      <ul>
        <li>About</li>
        <li><a>Lorem ipsum dolor sit amet, vel decore vidisse an, id simul quaerendum usu. Et vis nemore mandamus. Ei pri dicit erroribus splendide. Alterum perfecto reprimique et nec, diam dolorum posidonium qui ei.</a></li>
      </ul>
    </div>
  </row>
  <row>
    <p>Developed by <a href="#">My Name</a></p>
  </row>
</footer>
</code>```

CSS

```<code>footer {
  width: 100%;
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  background: #212121;
  margin: 0;
  z-index: 99;
}

footer>row {
  display: flex;
  align-items: center;
  padding: 30px 5%;
}

footer>row:first-of-type {
  justify-content: space-between;
}

footer>row>.col {
  text-align: left;
}

footer>row>.col>ul>li:first-of-type {
  color: #fff;
  font-weight: 600;
  font-size: 12px;
}

footer>row>.col>ul {
  vertical-align: top;
  padding: 0;
}

footer>row>.col>ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

footer>row>.col ul>li {
  margin: 15px 0;
}

footer>row>.col ul>li>a {
  font-family: 'Open Sans', sans-serif;
  font-size: 11px;
  color: #a5a5a5;
}

footer>row>.col ul>li>a:hover {
  text-decoration: none;
  color: #fff;
}

footer>row:last-of-type {
  background: #1f1f1f;
  display: flex;
  justify-content: center;
}

footer>row:last-of-type>p,
footer>row:last-of-type>p>a {
  font-family: 'Open Sans', sans-serif;
}

footer>row:last-of-type>p {
  font-family: 'Open Sans', sans-serif;
  padding: 0;
  margin: 0;
  color: #747475;
  font-size: 11px;
}

footer>row:last-of-type>p>a {
  color: #a5a5a5;
  text-decoration: none;
}

footer>row:last-of-type>p>a:hover {
  color: #fff;
  text-decoration: none;
}
</code>```

答:
Since you're overriding the normal Bootstap row with flexbox, use the appropriate flexbox alignment..

```<code>footer > row
{
    display: flex;
    align-items: flex-start;
    padding: 30px 5%;
}
</code>```

https://codepen.io/anon/pen/peqKbj

Title: Vertical align UL to top of div

Body:
I have three ul's added to a footer within bootstrap columns inside a parent row element, and I've used vertical-align:top for a similar footer before, but can't use this here to align each ul to the top of the parent div. (It's added to footer > row > .col > ul)

Any ideas?

Codepen: https://codepen.io/nickwcook/pen/aJPGeJ.

HTML:

  <row>

Quick Menu

Home

About

Contact

Recent Posts

Post One

Post Two

Post Three

About

Lorem ipsum dolor sit amet, vel decore vidisse an, id simul quaerendum usu. Et vis nemore mandamus. Ei pri dicit erroribus splendide. Alterum perfecto reprimique et nec, diam dolorum posidonium qui ei.

  </row>
  <row>

Developed by My Name

  </row>

CSS

footer {
  width: 100%;
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  background: #212121;
  margin: 0;
  z-index: 99;
}

footer>row {
  display: flex;
  align-items: center;
  padding: 30px 5%;
}

footer>row:first-of-type {
  justify-content: space-between;
}

footer>row>.col {
  text-align: left;
}

footer>row>.col>ul>li:first-of-type {
  color: #fff;
  font-weight: 600;
  font-size: 12px;
}

footer>row>.col>ul {
  vertical-align: top;
  padding: 0;
}

footer>row>.col>ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

footer>row>.col ul>li {
  margin: 15px 0;
}

footer>row>.col ul>li>a {
  font-family: 'Open Sans', sans-serif;
  font-size: 11px;
  color: #a5a5a5;
}

footer>row>.col ul>li>a:hover {
  text-decoration: none;
  color: #fff;
}

footer>row:last-of-type {
  background: #1f1f1f;
  display: flex;
  justify-content: center;
}

footer>row:last-of-type>p,
footer>row:last-of-type>p>a {
  font-family: 'Open Sans', sans-serif;
}

footer>row:last-of-type>p {
  font-family: 'Open Sans', sans-serif;
  padding: 0;
  margin: 0;
  color: #747475;
  font-size: 11px;
}

footer>row:last-of-type>p>a {
  color: #a5a5a5;
  text-decoration: none;
}

footer>row:last-of-type>p>a:hover {
  color: #fff;
  text-decoration: none;
}

Body:
Since you're overriding the normal Bootstap row with flexbox, use the appropriate flexbox alignment..

footer > row
{
    display: flex;
    align-items: flex-start;
    padding: 30px 5%;
}

https://codepen.io/anon/pen/peqKbj


问:
How to access arguments between chained promise
I have the below code:

```<code>vm.testService.getUser(id, name)
.then((resultA) => {
    return vm.testService.getUserInfo(id, name);
})
.then(() => {
    // will process resultA from first .then
});
</code>```

I need to access resultA on the second .then.
Thanks in advance.

答:
You could store the result of the first callback in the external scope</p>

```<code>let result;
vm.testService.getUser(id, name)
.then((resultA) => {
    result = resultA;
    return vm.testService.getUserInfo(id, name);
})
.then(() => {
    // 'result' will now equal resultA
});
</code>```

Body:
I have the below code:

vm.testService.getUser(id, name)
.then((resultA) => {
    return vm.testService.getUserInfo(id, name);
})
.then(() => {
    // will process resultA from first .then
});

I need to access resultA on the second .then.
Thanks in advance.

Body:
You could store the result of the first callback in the external scope

let result;
vm.testService.getUser(id, name)
.then((resultA) => {
    result = resultA;
    return vm.testService.getUserInfo(id, name);
})
.then(() => {
    // 'result' will now equal resultA
});


问:
Can SagaData be manipulated before the saga handler fires using NServiceBus
Using NServiceBus (v6), is there a way to ensure that a property is set in the SagaData object before the Saga Handler for a message is fired?

Our environment is multi-tenant so I want to ensure that the correct CustomerId is used for db access etc.. and that developers don't forget to pull this value from the incoming message/message header.

For example given this saga data ...

```<code>public interface ICustomerSagaData : IContainSagaData
{
    Guid CustomerId { get; set; }
}

public class SomeProcessSagaData : ICustomerSagaData
{
    // IContainSagaData and other properties removed for brevity ...

    #region ICustomerSagaData properties

    public virtual Guid CustomerId { get; set; }

    #endregion
}
</code>```

... and the following Saga ...

```<code>public class  SomeProcessSagaSaga :
    Saga<SomeProcessSagaData>,
    IAmStartedByMessages<StartProcess>
{
    public async Task Handle(StartProcess message, IMessageHandlerContext context)
    {
        // How do I ensure that Data.CustomerId is already set at this point?

    }

    // ConfigureHowToFindSaga etc ...
}
</code>```

I initially tried inserting a behaviour into the pipeline e.g.

```<code>public class MyInvokeHandlerBehavior : Behavior<IInvokeHandlerContext>
{
    public override async Task Invoke(IInvokeHandlerContext context, Func<Task> next)
    {
        // Ideally I'd like to set the CustomerId here before the
        // Saga Handler is invoked but calls to ...
        //      context.Extensions.TryGet(out activeSagaInstance);
        // return a null activeSagaInstance

        await next().ConfigureAwait(false);

        // This is the only point I can get the saga data object but
        //  as mentioned above the hander has already been invoked
        ActiveSagaInstance activeSagaInstance;
        if (context.Extensions.TryGet(out activeSagaInstance))
        {
            var instance = activeSagaInstance.Instance.Entity as ICustomerSagaData;
            if (instance != null)
            {
                Guid customerId;
                if (Guid.TryParse(context.Headers["CustomerId"), out customerId))
                {
                    instance.CustomerId = customerId;
                }
            }
        }
    }
}
</code>```

... but this only allows access to the SagaData instance after the handler has been fired.

答:
So to answer your question directly Data.CustomerId is not going to be set when you handle StartProcess messages. You will need to set that with the id coming off of the message.

```<code>public async Task Handle(StartProcess message, IMessageHandlerContext context)
{
    Data.CustomerId = message.CustomerId;
}
</code>```

That being said your sample above is missing a crucial piece which is the code for determining how a saga can be looked up for continuation of processing:

```<code>protected override void ConfigureHowToFindSaga(SagaPropertyMapper<SomeProcessSagaData> mapper)
{
    mapper.ConfigureMapping<StartProcess>(message => message.CustomerId)
        .ToSaga(sagaData => sagaData.CustomerId);
}
</code>```

Each time you send a message type that is handled by a saga you need to have the ConfigureHowToFindSaga() method configured so it can look up the previously started saga to continue processing with. So in essence you are going to start a new saga for every customerid you send with a StartProcess message. You can read more about it here: https://docs.particular.net/nservicebus/sagas/

So the real question now is do you really need to be using a saga at this point? The sample only seems to be handling one type of message so do you really need to be saving the state of CustomerId? The overhead of the saga isn't necessary in your sample and I believe a regular handler would be just fine based on the example above.

Body:
Using NServiceBus (v6), is there a way to ensure that a property is set in the SagaData object before the Saga Handler for a message is fired?

Our environment is multi-tenant so I want to ensure that the correct CustomerId is used for db access etc.. and that developers don't forget to pull this value from the incoming message/message header.

For example given this saga data ...

public interface ICustomerSagaData : IContainSagaData
{
    Guid CustomerId { get; set; }
}

public class SomeProcessSagaData : ICustomerSagaData
{
    // IContainSagaData and other properties removed for brevity ...

    #region ICustomerSagaData properties

    public virtual Guid CustomerId { get; set; }

    #endregion
}

... and the following Saga ...

public class  SomeProcessSagaSaga :
    Saga<SomeProcessSagaData>,
    IAmStartedByMessages<StartProcess>
{
    public async Task Handle(StartProcess message, IMessageHandlerContext context)
    {
        // How do I ensure that Data.CustomerId is already set at this point?

    }

    // ConfigureHowToFindSaga etc ...
}

I initially tried inserting a behaviour into the pipeline e.g.

public class MyInvokeHandlerBehavior : Behavior<IInvokeHandlerContext>
{
    public override async Task Invoke(IInvokeHandlerContext context, Func<Task> next)
    {
        // Ideally I'd like to set the CustomerId here before the
        // Saga Handler is invoked but calls to ...
        //      context.Extensions.TryGet(out activeSagaInstance);
        // return a null activeSagaInstance

        await next().ConfigureAwait(false);

        // This is the only point I can get the saga data object but
        //  as mentioned above the hander has already been invoked
        ActiveSagaInstance activeSagaInstance;
        if (context.Extensions.TryGet(out activeSagaInstance))
        {
            var instance = activeSagaInstance.Instance.Entity as ICustomerSagaData;
            if (instance != null)
            {
                Guid customerId;
                if (Guid.TryParse(context.Headers["CustomerId"), out customerId))
                {
                    instance.CustomerId = customerId;
                }
            }
        }
    }
}

... but this only allows access to the SagaData instance after the handler has been fired.

Body:
So to answer your question directly Data.CustomerId is not going to be set when you handle StartProcess messages. You will need to set that with the id coming off of the message.

public async Task Handle(StartProcess message, IMessageHandlerContext context)
{
    Data.CustomerId = message.CustomerId;
}

That being said your sample above is missing a crucial piece which is the code for determining how a saga can be looked up for continuation of processing:

protected override void ConfigureHowToFindSaga(SagaPropertyMapper<SomeProcessSagaData> mapper)
{
    mapper.ConfigureMapping<StartProcess>(message => message.CustomerId)
        .ToSaga(sagaData => sagaData.CustomerId);
}

Each time you send a message type that is handled by a saga you need to have the ConfigureHowToFindSaga() method configured so it can look up the previously started saga to continue processing with. So in essence you are going to start a new saga for every customerid you send with a StartProcess message. You can read more about it here: https://docs.particular.net/nservicebus/sagas/

So the real question now is do you really need to be using a saga at this point? The sample only seems to be handling one type of message so do you really need to be saving the state of CustomerId? The overhead of the saga isn't necessary in your sample and I believe a regular handler would be just fine based on the example above.


问:
Php get dates inside a string
I have a string like this:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean 2017-03-31 ligula eget dolor. Aenean massa. 2016-03-04 sociis natoque penatibus...

I would like to get all the dates inside the text... the format dates are always yyyy-mm-dd.

Any suggestions?

答:
Alright so what you have to do is figure out what you are trying to find, in your case yyyy-mm-dd.

So this would be it:

```<code>[0-9]{4}-[0-9]{2}-[0-9]{2}
</code>```

Title: Php get dates inside a string

Body:
Alright so what you have to do is figure out what you are trying to find, in your case yyyy-mm-dd.

So this would be it:

[0-9]{4}-[0-9]{2}-[0-9]{2}


问:
Eclipse is freezing itself before getting started
I've been trying to open Eclipse to start my work today, and it freezes everytime during load.

My Eclipse is Helios. Someone told me I should remove a file called .lock from .metadata folder, but still didn't work.

Does anyone have any idea of how do I "melt" this thing up?

ps: I opened it yesterday with no problems.

答: I believe something is wrong with your workspace. I typically remove current and create new one in such case. It usually takes up to 5 minutes (if I have to add 20 projects). In most cases it takes less.</p>


问:
Call moveRowAt method in didSelectRowAt?
Is there a way that you can call

```<code>func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to toIndexPath: IndexPath) {

   let affectedEvent = arrayMoved[fromIndexPath.row]
        arrayMoved.remove(at: fromIndexPath.row)
        arrayMoved.insert(affectedEvent, at: toIndexPath.row) }
</code>```

in

```<code>  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){}
</code>```

答:
tableView(_:moveRowAt:to:) is a delegate method, meaning it is a method that you should implement and let the system call you, not the other way around — normally you should not call a delegate method yourself.

If you want to tell the system to move a row, simply call moveRow(at:to:) of the table view, e.g.

```<code>func tableView(_ tableView: UITableView, didSelectRowAt ip: IndexPath) {
    tableView.moveRow(at: ip, to: IndexPath(row: 0, section: ip.section))
}
</code>```

After communicating with OP, want OP actually wants to reorder the model to push the selected item to the end. The typical way to do this is something like:

```<code>func tableView(_ tableView: UITableView, didSelectRowAt ip: IndexPath) {
    // update the model.
    model[ip.row].value = maxOfValue + 1
    sortModelAgain()

    // reload the model (note: no animation if using this)
    tableView.reloadData()
}
</code>```

or, if you'd like to manually keep the view and model in sync:

```<code>func tableView(_ tableView: UITableView, didSelectRowAt ip: IndexPath) {
    // update the model.
    model[ip.row].value = maxOfValue + 1
    sortModelAgain()

    // change the view to keep in sync of data.
    tableView.beginUpdates()
    let endRow = tableView.numberOfRows(inSection: ip.section) - 1
    tableView.moveRow(at: ip, to: IndexPath(row: endRow, section: ip.section))
    tableView.endUpdates()
}
</code>```

Body:
Is there a way that you can call

func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to toIndexPath: IndexPath) {

   let affectedEvent = arrayMoved[fromIndexPath.row]
        arrayMoved.remove(at: fromIndexPath.row)
        arrayMoved.insert(affectedEvent, at: toIndexPath.row) }

in

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){}

Body:
tableView(_:moveRowAt:to:) is a delegate method, meaning it is a method that you should implement and let the system call you, not the other way around — normally you should not call a delegate method yourself.

If you want to tell the system to move a row, simply call moveRow(at:to:) of the table view, e.g.

func tableView(_ tableView: UITableView, didSelectRowAt ip: IndexPath) {
    tableView.moveRow(at: ip, to: IndexPath(row: 0, section: ip.section))
}

After communicating with OP, want OP actually wants to reorder the model to push the selected item to the end. The typical way to do this is something like:

func tableView(_ tableView: UITableView, didSelectRowAt ip: IndexPath) {
    // update the model.
    model[ip.row].value = maxOfValue + 1
    sortModelAgain()

    // reload the model (note: no animation if using this)
    tableView.reloadData()
}

or, if you'd like to manually keep the view and model in sync:

func tableView(_ tableView: UITableView, didSelectRowAt ip: IndexPath) {
    // update the model.
    model[ip.row].value = maxOfValue + 1
    sortModelAgain()

    // change the view to keep in sync of data.
    tableView.beginUpdates()
    let endRow = tableView.numberOfRows(inSection: ip.section) - 1
    tableView.moveRow(at: ip, to: IndexPath(row: endRow, section: ip.section))
    tableView.endUpdates()
}


问:
I need IP addresses of LinkedIn
i have been directed by LinkedIn to this developer's blog. I want to give access to LinkedIn for certain users on a mobile network. This is why i would like first to know if they are static or dynamic, and if there is a predefined list which someone can share. </p>

答:
Is there a reason you cannot allow access the domain name?  E.g. www.linkedin.com (Or whatever domain the api is)

But, if you'd like to get the ip of a domain, you could use the ping command on windows cmd or linux/maxos bash, the output will be different depending on your system, but it should contain the numbered ip.

```<code>ping www.linkedin.com
</code>```

Title: I need IP addresses of LinkedIn

Body:
Is there a reason you cannot allow access the domain name?  E.g. www.linkedin.com (Or whatever domain the api is)

But, if you'd like to get the ip of a domain, you could use the ping command on windows cmd or linux/maxos bash, the output will be different depending on your system, but it should contain the numbered ip.

ping www.linkedin.com


答:
Try to use preg_match and regex expression:

```<code>$string = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean 2017-03-31 ligula eget dolor. Aenean massa. 2016-03-04 sociis natoque penatibus...";
$pattern = '/([0-9]{4}-[0-9]{2}-[0-9]{2})/';
preg_match_all($pattern, $string, $matches);
print_r($matches);
</code>```

To test regex, I suggest you to use https://regex101.com/

Title: Php get dates inside a string

Body:
I have a string like this:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean 2017-03-31 ligula eget dolor. Aenean massa. 2016-03-04 sociis natoque penatibus...

I would like to get all the dates inside the text... the format dates are always yyyy-mm-dd.

Any suggestions?

Body:
Try to use preg_match and regex expression:

$string = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean 2017-03-31 ligula eget dolor. Aenean massa. 2016-03-04 sociis natoque penatibus...";
$pattern = '/([0-9]{4}-[0-9]{2}-[0-9]{2})/';
preg_match_all($pattern, $string, $matches);
print_r($matches);

To test regex, I suggest you to use https://regex101.com/


问:
SQL, OR AND STATEMENT
Does the AND Statement after the OR statement have the same logic as something similar to

```<code>where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
 and
  d.status = ('C')
 OR
  d.status IN ('R' ,'D')
     AND
    t.done_dt = DATEADD(month, -1, GETDATE())

where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
IF d.status  IN ('R','D')
  t.done_dt = DATEADD(month, -1, GETDATE())
 ELSE
  d.status = 'C'
</code>```

Which one is the correct way to format it?

I'm trying to display all d.status with the 'C' status. But only if the t.done_dt is the previous month, do I want to display d.status IN ('R', 'D')

答:
Because of Operator Precedence, and evaluates before or. So, you get something like this:

```<code>where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
 and
  d.status = ('C')
 OR
  (
    d.status IN ('R' ,'D')
     AND
    t.done_dt = DATEADD(month, -1, GETDATE())
  )
</code>```

That said, I like to use the parentheses explicitly so I don't have to think about it so hard.

Title: SQL, OR AND STATEMENT

Body:
Does the AND Statement after the OR statement have the same logic as something similar to

where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
 and
  d.status = ('C')
 OR
  d.status IN ('R' ,'D')
     AND
    t.done_dt = DATEADD(month, -1, GETDATE())

where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
IF d.status  IN ('R','D')
  t.done_dt = DATEADD(month, -1, GETDATE())
 ELSE
  d.status = 'C'

Which one is the correct way to format it?

I'm trying to display all d.status with the 'C' status. But only if the t.done_dt is the previous month, do I want to display d.status IN ('R', 'D')

Body:
Because of Operator Precedence, and evaluates before or. So, you get something like this:

where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
 and
  d.status = ('C')
 OR
  (
    d.status IN ('R' ,'D')
     AND
    t.done_dt = DATEADD(month, -1, GETDATE())
  )

That said, I like to use the parentheses explicitly so I don't have to think about it so hard.


问:
My android app crashes on launch, and the stack trace doesn't show anything
I'm new to android development, and I'm trying to build a simple note taking app.

I've decided to use Realm instead of SQLite, but I couldn't figure out how to connect everything on the DB to my RecyclerView, so I found an example on their GitHub about creating Adapters for RecyclerViews that display data from a Realm DB.

I copied most of the code and edited it to suit my app, but now it crashes on launch, and I have no idea what's causing it because the stack trace doesn't show anything.

I've uploaded the app to this repo on GitHub for people to check it out and tell me what might be wrong.

答: Basically you just have to add Realm.init(this); before the RealmConfiguration


问:
object reference not set to an instance of an object while registering bot
I created a simple Bot and its working fine in bot emulator.

I published this Bot into Microsoft azure and trying to registering my Bot with the Microsoft Bot Framework.

I am getting the following error.

object reference not set to an instance of an object.

Can anyone please help ?

答: According to this issue: https://github.com/Microsoft/BotBuilder/issues/1012 This error can occur if you do not put a url in the terms of use form field.</p>


问:
How can I restore the "default" button style
I have a save button, and when the user mouses over it, I change some styles - for example:

```<code>$('.saveButton').mouseover(function() {
   $(this).css("background-color", "red");
   $(this).parents('fieldset').css("border", "2px solid red");
});
</code>```

When the mouse leaves the button, I would like to restore the original:

```<code>$('.saveButton').mouseout(function() {
   $(this).css("background-color", "#EEE");
   $(this).parents('fieldset').css("border", "1px solid gray");
});
</code>```

However, leaving aside the matter of whether or not the default button background color is #EEE, when this code executes the button loses its rounded look, and has square corners.

Is it possible to do this?

答:
Yes, use a class and some css:

```<code>/* in style.css */
.over {
    border: 2px solid red;
}
.over .saveButton {
    background-color: red;
}
</code>```

Then just add/remove this class to the parent fieldset:

```<code>$('.saveButton').mouseover(function() {
     $(this).parents('fieldset').addClass('over');
}).mouseout(function() {
     $(this).parents('fieldset').removeClass('over');
});
</code>```

Removing the class will revert the button and the field state they were before that.

As a good practice - it is better to keep the presentation (how things look) in css and use javascript to switch between them - it's much easier to manage that way.

Body:
I have a save button, and when the user mouses over it, I change some styles - for example:

$('.saveButton').mouseover(function() {
   $(this).css("background-color", "red");
   $(this).parents('fieldset').css("border", "2px solid red");
});

When the mouse leaves the button, I would like to restore the original:

$('.saveButton').mouseout(function() {
   $(this).css("background-color", "#EEE");
   $(this).parents('fieldset').css("border", "1px solid gray");
});

However, leaving aside the matter of whether or not the default button background color is #EEE, when this code executes the button loses its rounded look, and has square corners.

Is it possible to do this?

Body:
Yes, use a class and some css:

/* in style.css */
.over {
    border: 2px solid red;
}
.over .saveButton {
    background-color: red;
}

Then just add/remove this class to the parent fieldset:

$('.saveButton').mouseover(function() {
     $(this).parents('fieldset').addClass('over');
}).mouseout(function() {
     $(this).parents('fieldset').removeClass('over');
});

Removing the class will revert the button and the field state they were before that.

As a good practice - it is better to keep the presentation (how things look) in css and use javascript to switch between them - it's much easier to manage that way.


问:
Having Trouble Replacing NA
I'm new to R and I'm using a data set from kaggle on bombing operations in WWII

I wanted to replace all the NA's in a column with "UKNOWN" but I get this

```<code>Warning message:
In `[<-.factor`(`*tmp*`, is.na(operations[,"theater.of.operations"]),  :
invalid factor level, NA generated
</code>```

This is how I tried to do it

```<code>operations[, "theater.of.operations"][is.na(operations[, "theater.of.operations"])] <- "UNKNOWN"
</code>```

How else should I try to do this?

答:
To convert NA (which is not of string type) to a string such as "UNKNOWN" you need to cast your dataframe column to a string as follows.

```<code>operations$theater.of.operations <- as.character(operations$theater.of.operations)
</code>```

The critical element being the function as.character() which casts to your required character variable type.

Title: Having Trouble Replacing NA

Body:
I'm new to R and I'm using a data set from kaggle on bombing operations in WWII

I wanted to replace all the NA's in a column with "UKNOWN" but I get this

Warning message:
In `[<-.factor`(`*tmp*`, is.na(operations[,"theater.of.operations"]),  :
invalid factor level, NA generated

This is how I tried to do it

operations[, "theater.of.operations"][is.na(operations[, "theater.of.operations"])] <- "UNKNOWN"

How else should I try to do this?

Body:
To convert NA (which is not of string type) to a string such as "UNKNOWN" you need to cast your dataframe column to a string as follows.

operations$theater.of.operations <- as.character(operations$theater.of.operations)

The critical element being the function as.character() which casts to your required character variable type.


问:
How can i download only latest file by Get-AzureStorageBlobContent
I Have written this code. How can i download only latest file?</p>

```<code>$container_name = 'packageitems'
$destination_path = 'C:\pstest'
$connection_string = 'DefaultEndpointsProtocol=https;AccountName=[REPLACEWITHACCOUNTNAME];AccountKey=[REPLACEWITHACCOUNTKEY]'

$storage_account = New-AzureStorageContext -ConnectionString $connection_string

$blobs = Get-AzureStorageBlob -Container $container_name -Context $storage_account

foreach ($blob in $blobs)
{
    New-Item -ItemType Directory -Force -Path $destination_path

    Get-AzureStorageBlobContent `
    -Container $container_name -Blob $blob.Name -Destination $destination_path `
    -Context $storage_account

}
</code>```

答:
Try this code:

```<code>$container_name = 'packageitems'
$destination_path = 'C:\pstest'
$connection_string = 'DefaultEndpointsProtocol=https;AccountName=[REPLACEWITHACCOUNTNAME];AccountKey=[REPLACEWITHACCOUNTKEY]'
$storage_account = New-AzureStorageContext -ConnectionString $connection_string
# Get the blobs list and then sort them by last modified date descending
$blobs = Get-AzureStorageBlob -Container $container_name -Context $storage_account  | sort @{expression="LastModified";Descending=$true}
# First blob in that list would be the last modified.
$latestBlob = $blobs[0]
# Just download that blob
Get-AzureStorageBlobContent `
    -Container $container_name -Blob $latestBlob.Name -Destination $destination_path `
    -Context $storage_account
</code>```

What the code above does is lists the blobs and then sorts them in descending order based on the last modified date. The 1st element in the array will be the latest blob. It then downloads this blob.

Body:
I Have written this code. How can i download only latest file?

$container_name = 'packageitems'
$destination_path = 'C:\pstest'
$connection_string = 'DefaultEndpointsProtocol=https;AccountName=[REPLACEWITHACCOUNTNAME];AccountKey=[REPLACEWITHACCOUNTKEY]'

$storage_account = New-AzureStorageContext -ConnectionString $connection_string

$blobs = Get-AzureStorageBlob -Container $container_name -Context $storage_account

foreach ($blob in $blobs)
{
    New-Item -ItemType Directory -Force -Path $destination_path

    Get-AzureStorageBlobContent `
    -Container $container_name -Blob $blob.Name -Destination $destination_path `
    -Context $storage_account

}

Body:
Try this code:

$container_name = 'packageitems'
$destination_path = 'C:\pstest'
$connection_string = 'DefaultEndpointsProtocol=https;AccountName=[REPLACEWITHACCOUNTNAME];AccountKey=[REPLACEWITHACCOUNTKEY]'
$storage_account = New-AzureStorageContext -ConnectionString $connection_string
# Get the blobs list and then sort them by last modified date descending
$blobs = Get-AzureStorageBlob -Container $container_name -Context $storage_account  | sort @{expression="LastModified";Descending=$true}
# First blob in that list would be the last modified.
$latestBlob = $blobs[0]
# Just download that blob
Get-AzureStorageBlobContent `
    -Container $container_name -Blob $latestBlob.Name -Destination $destination_path `
    -Context $storage_account

What the code above does is lists the blobs and then sorts them in descending order based on the last modified date. The 1st element in the array will be the latest blob. It then downloads this blob.


问:
Makefile from one source Directory trying to access a cpp file from other Directory
I've an issue with object creation for a cpp files residing in 2 different directories as show below:

```<code>- Project-xyz
  - Hello
    - Hello.cpp
  - World
    - Main.cpp
    - World.cpp
    - Makefile
</code>```

For better clarity here is how the code looks (just a dummy code).

hello/Hello.h

```<code>#ifndef HELLO_H
#define HELLO_H

void HelloPrint();

#endif // HELLO_H
</code>```

hello/Hell.cpp

```<code>#include <iostream>
#include "Hello.h"

void HelloPrint()
{
  std::cout <<"Hello" << std::endl;
}
</code>```

world/World.h

```<code> #ifndef WORLD_H
 #define WORLD_H

 void WorldPrint();

 #endif // WORLD_H
</code>```

world/World.cpp

```<code>#include <iostream>
#include "World.h"

void WorldPrint()
{
 std::cout <<"World!" << std::endl;
}
</code>```

world/Makefile
Using a makefile given in here. Which is working fine. But it doesn't create any obj files.

```<code># set non-optional compiler flags here
CXXFLAGS += -std=c++11 -Wall -Wextra -pedantic-errors

# set non-optional preprocessor flags here
# eg. project specific include directories
CPPFLAGS +=

# find cpp files in subdirectories
SOURCES := $(shell find . -name '*.cpp')
SOURCES += $(shell find ../hello -name '*.cpp')

# find headers
HEADERS := $(shell find . -name '*.h')

OUTPUT := HelloWorld

# Everything depends on the output
all: $(OUTPUT)

# The output depends on sources and headers
$(OUTPUT): $(SOURCES) $(HEADERS)
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $(OUTPUT) $(SOURCES)

clean:
     $(RM) $(OUTPUT)
</code>```

I'm  looking at a solution which uses the makefile which generates the obj files in specific directory as shown here.

Now I'm trying to generate the obj files for hello/hello.cpp file in world/objdir/hello.o using the Below make file. Which is not working.
How to get it working?

world/Makefile

```<code>GCC=g++
CPPFLAGS=-c -Wall
LDFLAGS=
OBJDIR=objdir
OBJ=$(addprefix $(OBJDIR)/, $(patsubst %.cpp, %.o, $(wildcard *.cpp)))
TARGET=HelloWorld

.PHONY: all clean

all: $(OBJDIR) $(TARGET)

$(OBJDIR):
    mkdir $(OBJDIR)

$(OBJDIR)/%.o: %.cpp
    $(GCC) $(CPPFLAGS) -c $< -o $@
$(TARGET): $(OBJ)
    $(GCC) $(LDFLAGS) -o $@ $^
clean:
    @rm -f $(TARGET) $(wildcard *.o)
    @rm -rf $(OBJDIR)
</code>```

When i try to run the make it throws the following error.

```<code>g++ -c -Wall -c main.cpp ../hello/Hello.cpp -o objdir/main.o
g++: fatal error: cannot specify -o with -c, -S or -E with multiple files
compilation terminated.
make: *** [objdir/main.o] Error 4
</code>```

It is not able to generate the obj files for the hello/Hello.cpp file and hence throwing this error.

Any help from the makefile Masters is appreciated! :)

答:
It's weird that you want to access directories above current dir, since you cannot make files with names contain ..

You need this to compile multiple files with similar names, for example: in World directory you may have another file named Hello/Hello.cpp, then you have to compile both ../Hello/Hello.cpp and Hello/Hello.cpp. Although they are two different files, there is no way to produce object files with different names. You might replace .. with something like UPPERDIRECTORY but then if you have another file to compile with name UPPERDIRECTORY/Hello/Hello.cpp, you're screwed...

Anyway, here's a "temporary fix":

```<code>CXX=g++
CPPFLAGS=-Wall
LDFLAGS=
OBJDIR=objdir
TARGET=HelloWorld

# PLACE ALL NEEDED DIRECTORIES HERE
# List of directories that contains all needed cpp files
MODULES=. ../Hello

# Get all cpp source file names
SRCS=$(foreach module, $(MODULES), $(wildcard $(module)/*.cpp))   #*/weird SO comment syntax

# Convert them to object file names + $(OBJDIR) prefix
OBJS=$(SRCS:%.cpp=$(OBJDIR)/%.o)

# Get all directories of $(OBJS) so we can create object files with same name
# but locate in different dirs, for example:
#             Hello.cpp -> objdir/Hello.o                      (need to create objdir/)
#       Hello/Hello.cpp -> objdir/Hello/Hello.o                (need to create objdir/Hello/)
#    ../Hello/Hello.cpp -> objdir/UPPERDIRECTORY/Hello/Hello.o (need to create objdir/UPPERDIRECTORY/Hello/)
ALL_OBJ_DIRS=$(subst ..,UPPERDIRECTORY, $(sort $(dir $(OBJS))))

.PHONY: all clean

all: $(TARGET)

# Rule to make all needed object directories
$(ALL_OBJ_DIRS):
    @mkdir -p $@

# Rule to make object files
$(OBJDIR)/%.o: %.cpp | $(ALL_OBJ_DIRS)
# We need to replace .. with UPPERDIRECTORY in .o (output) path,
# but keep .cpp (input) path as it is
    $(CXX) -c $(CPPFLAGS) $< -o $(subst ..,UPPERDIRECTORY,$@)

# Rule to make target file
$(TARGET): $(OBJS)
# We need to replace .. with UPPERDIRECTORY in all $(OBJS) paths
    $(CXX) $(subst ..,UPPERDIRECTORY,$^) $(LDFLAGS) -o $@

clean:
    @rm -f $(TARGET)
    @rm -rf $(OBJDIR)
</code>```

If I were you, I would place Makefile on top of all cpp files to avoid ..

```<code>project/
  src/
    Makefile
    Hello/
      Hello.h
      Hello.cpp
    World/
      World.h
      World.cpp
      main.cpp
</code>```

Edit: you can replace / with _ in object file names so now you can include .. in your object file names:

```<code>GCC=g++
CPPFLAGS=-Wall
LDFLAGS=
OBJDIR=obj
TARGET=HelloWorld

# Modules: directories that contains all needed cpp files
MODULES=. ../Hello
# Get all cpp source file names
SRCS_WITHCURRENTDIR=$(foreach module, $(MODULES), $(wildcard $(module)/*.cpp))   #*/weird SO comment syntax
SRCS=$(SRCS_WITHCURRENTDIR:./%=%) # remove ./
# Convert them to object file names + $(OBJDIR) prefix
OBJS=$(SRCS:%.cpp=$(OBJDIR)/%.o)
OBJ_PREFIX=OBJ

.PHONY: all clean

all: $(OBJDIR) $(TARGET)

$(OBJDIR):
    @mkdir -p $@

$(OBJDIR)/%.o: %.cpp
    $(GCC) -c $(CPPFLAGS) $< -o $(addprefix $(OBJDIR)/$(OBJ_PREFIX),$(subst /,_,$(patsubst $(OBJDIR)/%,%,$@)))

$(TARGET): $(OBJS)
    $(GCC) $(addprefix $(OBJDIR)/$(OBJ_PREFIX),$(subst /,_,$(patsubst $(OBJDIR)/%,%,$^))) $(LDFLAGS) -o $@

clean:
    @rm -f $(TARGET)
    @rm -rf $(OBJDIR)
</code>```

make clean all gives

```<code>g++ -c -Wall main.cpp -o obj/OBJmain.o
g++ -c -Wall World.cpp -o obj/OBJWorld.o
g++ -c -Wall ../Hello/Hello.cpp -o obj/OBJ.._Hello_Hello.o
g++ obj/OBJmain.o obj/OBJWorld.o obj/OBJ.._Hello_Hello.o  -o HelloWorld
</code>```

3 object files in obj/: OBJmain.o, OBJWorld.o, OBJ.._Hello_Hello.o

Body:
I've an issue with object creation for a cpp files residing in 2 different directories as show below:

- Project-xyz
  - Hello
    - Hello.cpp
  - World
    - Main.cpp
    - World.cpp
    - Makefile

For better clarity here is how the code looks (just a dummy code).

hello/Hello.h

#ifndef HELLO_H
#define HELLO_H

void HelloPrint();

#endif // HELLO_H

hello/Hell.cpp

#include <iostream>
#include "Hello.h"

void HelloPrint()
{
  std::cout <<"Hello" << std::endl;
}

world/World.h

 #ifndef WORLD_H
 #define WORLD_H

 void WorldPrint();

 #endif // WORLD_H

world/World.cpp

#include <iostream>
#include "World.h"

void WorldPrint()
{
 std::cout <<"World!" << std::endl;
}

world/Makefile
Using a makefile given in here. Which is working fine. But it doesn't create any obj files.

# set non-optional compiler flags here
CXXFLAGS += -std=c++11 -Wall -Wextra -pedantic-errors

# set non-optional preprocessor flags here
# eg. project specific include directories
CPPFLAGS +=

# find cpp files in subdirectories
SOURCES := $(shell find . -name '*.cpp')
SOURCES += $(shell find ../hello -name '*.cpp')

# find headers
HEADERS := $(shell find . -name '*.h')

OUTPUT := HelloWorld

# Everything depends on the output
all: $(OUTPUT)

# The output depends on sources and headers
$(OUTPUT): $(SOURCES) $(HEADERS)
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $(OUTPUT) $(SOURCES)

clean:
     $(RM) $(OUTPUT)

I'm  looking at a solution which uses the makefile which generates the obj files in specific directory as shown here.

Now I'm trying to generate the obj files for hello/hello.cpp file in world/objdir/hello.o using the Below make file. Which is not working.
How to get it working?

world/Makefile

GCC=g++
CPPFLAGS=-c -Wall
LDFLAGS=
OBJDIR=objdir
OBJ=$(addprefix $(OBJDIR)/, $(patsubst %.cpp, %.o, $(wildcard *.cpp)))
TARGET=HelloWorld

.PHONY: all clean

all: $(OBJDIR) $(TARGET)

$(OBJDIR):
    mkdir $(OBJDIR)

$(OBJDIR)/%.o: %.cpp
    $(GCC) $(CPPFLAGS) -c $< -o $@
$(TARGET): $(OBJ)
    $(GCC) $(LDFLAGS) -o $@ $^
clean:
    @rm -f $(TARGET) $(wildcard *.o)
    @rm -rf $(OBJDIR)

When i try to run the make it throws the following error.

g++ -c -Wall -c main.cpp ../hello/Hello.cpp -o objdir/main.o
g++: fatal error: cannot specify -o with -c, -S or -E with multiple files
compilation terminated.
make: *** [objdir/main.o] Error 4

It is not able to generate the obj files for the hello/Hello.cpp file and hence throwing this error.

Any help from the makefile Masters is appreciated! :)

Body:
It's weird that you want to access directories above current dir, since you cannot make files with names contain ..

You need this to compile multiple files with similar names, for example: in World directory you may have another file named Hello/Hello.cpp, then you have to compile both ../Hello/Hello.cpp and Hello/Hello.cpp. Although they are two different files, there is no way to produce object files with different names. You might replace .. with something like UPPERDIRECTORY but then if you have another file to compile with name UPPERDIRECTORY/Hello/Hello.cpp, you're screwed...

Anyway, here's a "temporary fix":

CXX=g++
CPPFLAGS=-Wall
LDFLAGS=
OBJDIR=objdir
TARGET=HelloWorld

# PLACE ALL NEEDED DIRECTORIES HERE
# List of directories that contains all needed cpp files
MODULES=. ../Hello

# Get all cpp source file names
SRCS=$(foreach module, $(MODULES), $(wildcard $(module)/*.cpp))   #*/weird SO comment syntax

# Convert them to object file names + $(OBJDIR) prefix
OBJS=$(SRCS:%.cpp=$(OBJDIR)/%.o)

# Get all directories of $(OBJS) so we can create object files with same name
# but locate in different dirs, for example:
#             Hello.cpp -> objdir/Hello.o                      (need to create objdir/)
#       Hello/Hello.cpp -> objdir/Hello/Hello.o                (need to create objdir/Hello/)
#    ../Hello/Hello.cpp -> objdir/UPPERDIRECTORY/Hello/Hello.o (need to create objdir/UPPERDIRECTORY/Hello/)
ALL_OBJ_DIRS=$(subst ..,UPPERDIRECTORY, $(sort $(dir $(OBJS))))

.PHONY: all clean

all: $(TARGET)

# Rule to make all needed object directories
$(ALL_OBJ_DIRS):
    @mkdir -p $@

# Rule to make object files
$(OBJDIR)/%.o: %.cpp | $(ALL_OBJ_DIRS)
# We need to replace .. with UPPERDIRECTORY in .o (output) path,
# but keep .cpp (input) path as it is
    $(CXX) -c $(CPPFLAGS) $< -o $(subst ..,UPPERDIRECTORY,$@)

# Rule to make target file
$(TARGET): $(OBJS)
# We need to replace .. with UPPERDIRECTORY in all $(OBJS) paths
    $(CXX) $(subst ..,UPPERDIRECTORY,$^) $(LDFLAGS) -o $@

clean:
    @rm -f $(TARGET)
    @rm -rf $(OBJDIR)

If I were you, I would place Makefile on top of all cpp files to avoid ..

project/
  src/
    Makefile
    Hello/
      Hello.h
      Hello.cpp
    World/
      World.h
      World.cpp
      main.cpp

Edit: you can replace / with _ in object file names so now you can include .. in your object file names:

GCC=g++
CPPFLAGS=-Wall
LDFLAGS=
OBJDIR=obj
TARGET=HelloWorld

# Modules: directories that contains all needed cpp files
MODULES=. ../Hello
# Get all cpp source file names
SRCS_WITHCURRENTDIR=$(foreach module, $(MODULES), $(wildcard $(module)/*.cpp))   #*/weird SO comment syntax
SRCS=$(SRCS_WITHCURRENTDIR:./%=%) # remove ./
# Convert them to object file names + $(OBJDIR) prefix
OBJS=$(SRCS:%.cpp=$(OBJDIR)/%.o)
OBJ_PREFIX=OBJ

.PHONY: all clean

all: $(OBJDIR) $(TARGET)

$(OBJDIR):
    @mkdir -p $@

$(OBJDIR)/%.o: %.cpp
    $(GCC) -c $(CPPFLAGS) $< -o $(addprefix $(OBJDIR)/$(OBJ_PREFIX),$(subst /,_,$(patsubst $(OBJDIR)/%,%,$@)))

$(TARGET): $(OBJS)
    $(GCC) $(addprefix $(OBJDIR)/$(OBJ_PREFIX),$(subst /,_,$(patsubst $(OBJDIR)/%,%,$^))) $(LDFLAGS) -o $@

clean:
    @rm -f $(TARGET)
    @rm -rf $(OBJDIR)

make clean all gives

g++ -c -Wall main.cpp -o obj/OBJmain.o
g++ -c -Wall World.cpp -o obj/OBJWorld.o
g++ -c -Wall ../Hello/Hello.cpp -o obj/OBJ.._Hello_Hello.o
g++ obj/OBJmain.o obj/OBJWorld.o obj/OBJ.._Hello_Hello.o  -o HelloWorld

3 object files in obj/: OBJmain.o, OBJWorld.o, OBJ.._Hello_Hello.o


问:
breezejs : configuring service for CORS
I can access my web api service using a standard jquery ajax call:

```<code>$.ajax('http://service/method', {
contentType: 'application/json',
type: 'GET',
xhrFields: {
    withCredentials: true
  }
})
</code>```

On the server side the webconfig file is configured as such:

```<code> <customHeaders>
    <clear/>
    <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
    <add name="Access-Control-Allow-Origin" value="http://localhost:1502" />
    <add name="Access-Control-Allow-Headers" value="Content-Type,X-Requested-With, Authorization" />
    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>
</code>```

For now, I'm trying to reach the service from a local website running on port 1502.

However, when using breeze, I don't see how I can specify the withCredential parameter, and as a result I get a 401 error.

答:
I tried the above method and it does not seem to be working as of BreezeJS 1.6.3.

However, I was able to get it to work with a slight change. Here is my working code:

```<code>// set credentials on
var ajaxAdapter = breeze.config.getAdapterInstance('ajax');
ajaxAdapter.defaultSettings = {
    withCredentials: true
};
</code>```

Title: breezejs : configuring service for CORS

Body:
I can access my web api service using a standard jquery ajax call:

$.ajax('http://service/method', {
contentType: 'application/json',
type: 'GET',
xhrFields: {
    withCredentials: true
  }
})

On the server side the webconfig file is configured as such:

 <customHeaders>
    <clear/>
    <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
    <add name="Access-Control-Allow-Origin" value="http://localhost:1502" />
    <add name="Access-Control-Allow-Headers" value="Content-Type,X-Requested-With, Authorization" />
    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>

For now, I'm trying to reach the service from a local website running on port 1502.

However, when using breeze, I don't see how I can specify the withCredential parameter, and as a result I get a 401 error.

Body:
I tried the above method and it does not seem to be working as of BreezeJS 1.6.3.

However, I was able to get it to work with a slight change. Here is my working code:

// set credentials on
var ajaxAdapter = breeze.config.getAdapterInstance('ajax');
ajaxAdapter.defaultSettings = {
    withCredentials: true
};


问:
Moodle event observer not triggered in local plugin
I have created a plugin at this location moodle/local/redirectafterlogin with the following structure :

```<code>redirectafterlogin/
├── db
│   ├── classes
│   │   └── observer.php
│   └── events
│       └── events.php
└── version.php
</code>```

version.php:

```<code>defined('MOODLE_INTERNAL') || die();

$plugin->version = 20170333;
$plugin->requires = 2015111000;
$plugin->component = 'local_redirectafterlogin';
</code>```

events.php:

```<code>defined('MOODLE_INTERNAL') || die();

    $observers = array(
        array(
            'eventname' => 'core\event\user_loggedin',
            'callback' => 'local_redirectafterlogin_observer::user_loggedin',
        ),
        array(
            'eventname' => 'core\event\user_loggedout',
            'callback' => 'local_redirectafterlogin_observer::user_loggedin',
        ),
    );
</code>```

observer.php:

```<code>class local_redirectafterlogin_observer
{
    public static function user_loggedin(core\event\base $event)
    {
        $event_data = $event->get_data();
        var_dump($event_data);
        die();
    }
}
</code>```

Cached has been cleared a lot of time and version number has been bumped too but the callback is never called!

What's wrong, why does the callback is not triggered?

How can I debug events (is there a way in Moodle to see dispatched events)?

答: I made the experience that var_dump or output do stdout gets not trigggert. As quick "debug" i use file_put_contents to a temp logfile</p>

Body:
I have created a plugin at this location moodle/local/redirectafterlogin with the following structure :

redirectafterlogin/
├── db
│   ├── classes
│   │   └── observer.php
│   └── events
│       └── events.php
└── version.php

version.php:

defined('MOODLE_INTERNAL') || die();

$plugin->version = 20170333;
$plugin->requires = 2015111000;
$plugin->component = 'local_redirectafterlogin';

events.php:

defined('MOODLE_INTERNAL') || die();

    $observers = array(
        array(
            'eventname' => 'core\event\user_loggedin',
            'callback' => 'local_redirectafterlogin_observer::user_loggedin',
        ),
        array(
            'eventname' => 'core\event\user_loggedout',
            'callback' => 'local_redirectafterlogin_observer::user_loggedin',
        ),
    );

observer.php:

class local_redirectafterlogin_observer
{
    public static function user_loggedin(core\event\base $event)
    {
        $event_data = $event->get_data();
        var_dump($event_data);
        die();
    }
}

Cached has been cleared a lot of time and version number has been bumped too but the callback is never called!

What's wrong, why does the callback is not triggered?

How can I debug events (is there a way in Moodle to see dispatched events)?


问:
Calculating an Avg in SQL excluding the current row
I have a DB where certain records are tagged with an ID and I want create a view that contains the Average of all those records with the same ID, EXCLUDING the current record.  For example, if my data looks like this:

```<code>ROW - ID - Value
1     1    20
2     1    30
3     1    40
4     2    60
5     2    80
6     2    40
7     3    50
8     3    20
9     3    40
</code>```

My view needs to calculate the average of every row with the same ID, EXCLUDING the row it's on, so my output would look something like this:

```<code>ROW - ID - Value AVG
1     1    20    35
2     1    30    30
3     1    40    25
4     2    60    60
5     2    80    50
6     2    40    70
7     3    50    30
8     3    20    55
9     3    40    35
</code>```

So, in the case of row 3, it's extracted rows 1 and 2, as they have the same ID and given me the avg of their values - 25.

I'm gone round the houses on this for a while now, but can't seem to nail it.  Any help would be appreciated.

答:
```<code>SELECT t1.gid, AVG(t2.value)
FROM table1 as t1 INNER JOIN
  table1 as t2 ON (t1.gid != t2.gid)
GROUP BY t1.gid;
</code>```

Basically, join the table to itself on your condition and then group the results based on the first table's key.

This solution should work regardless of what database system you are usimg; there may be minor syntax details to change.

A table like this:

```<code>ID | Value
1  | 4
2  | 6
3  | 5
</code>```

Becomes (when joined):

```<code>t1.ID | t2.ID | t1.Value | t2.Value
1     | 2     | 4        | 6
1     | 3     | 4        | 5
2     | 1     | 6        | 4
2     | 3     | 6        | 5
3     | 1     | 5        | 4
3     | 2     | 5        | 6
</code>```

And, then the aggregate of the grouped rows yields the wanted values.

Body:
I have a DB where certain records are tagged with an ID and I want create a view that contains the Average of all those records with the same ID, EXCLUDING the current record.  For example, if my data looks like this:

ROW - ID - Value
1     1    20
2     1    30
3     1    40
4     2    60
5     2    80
6     2    40
7     3    50
8     3    20
9     3    40

My view needs to calculate the average of every row with the same ID, EXCLUDING the row it's on, so my output would look something like this:

ROW - ID - Value AVG
1     1    20    35
2     1    30    30
3     1    40    25
4     2    60    60
5     2    80    50
6     2    40    70
7     3    50    30
8     3    20    55
9     3    40    35

So, in the case of row 3, it's extracted rows 1 and 2, as they have the same ID and given me the avg of their values - 25.

I'm gone round the houses on this for a while now, but can't seem to nail it.  Any help would be appreciated.

Body:
SELECT t1.gid, AVG(t2.value)
FROM table1 as t1 INNER JOIN
  table1 as t2 ON (t1.gid != t2.gid)
GROUP BY t1.gid;

Basically, join the table to itself on your condition and then group the results based on the first table's key.

This solution should work regardless of what database system you are usimg; there may be minor syntax details to change.

A table like this:

ID | Value
1  | 4
2  | 6
3  | 5

Becomes (when joined):

t1.ID | t2.ID | t1.Value | t2.Value
1     | 2     | 4        | 6
1     | 3     | 4        | 5
2     | 1     | 6        | 4
2     | 3     | 6        | 5
3     | 1     | 5        | 4
3     | 2     | 5        | 6

And, then the aggregate of the grouped rows yields the wanted values.


问:
Need help parsing a specific type of page
Ok so just for reference I will be using the liquipedia API to parse this text area
my question is how when i have a line like |title4=Nearby Cast Range       |value4=500 parse that into a key value hash like {"Neraby Cast Range" => "500"}

Thank you

答:
You can use Regexp to parse an individual line.

line = "|title4=Nearby Cast Range       |value4=500"

pattern = /\|title4=(.*)\|value4=(.*)/
matches = pattern.match(line)
title = matches[1].strip
value = matches[2].strip

myHash = {}
myHash[title] = value

#> puts myHash
#> {"Nearby Cast Range"=>"500"}
```

<hr>

<p><strong>UPDATE:</strong></p>

<p>For any number after the <code>title</code> or <code>value</code> fields, you could add <code>\d*</code> to the regular expression:</p>

```pattern = /\|title\d*=(.*)\|value\d*=(.*)/
```

That will work for title0, title4, title123, etc.

Body:
You can use Regexp to parse an individual line.

line = "|title4=Nearby Cast Range       |value4=500"

pattern = /\|title4=(.*)\|value4=(.*)/
matches = pattern.match(line)
title = matches[1].strip
value = matches[2].strip

myHash = {}
myHash[title] = value

#> puts myHash
#> {"Nearby Cast Range"=>"500"}

UPDATE:

For any number after the title or value fields, you could add \d* to the regular expression:

pattern = /\|title\d*=(.*)\|value\d*=(.*)/

That will work for title0, title4, title123, etc.


问:
get index of boolean values in pandas - python
```<code>a=pd.DataFrame({'a1':[1,2,3,4],'a2':[5,6,7,8]})
c=pd.DataFrame({'c1':[True,False,True,True],'c2':[True,False,False,True]})
</code>```

How can I get the index of the elements in columns a1 and a2 which are True in columns c1 and c2 respectively?

The index of a1 should be [0,2,3] and the index of a2 [0,3]. The result could be a list of indexes like [[0,2,3],[0,3]].

答:
It isn't clear what you want exactly.

This is an approach using stack

```<code>a.stack().index[c.stack().values].to_series()

0  a1    (0, a1)
   a2    (0, a2)
2  a1    (2, a1)
3  a1    (3, a1)
   a2    (3, a2)
dtype: object
</code>```

If you want just the list of index values

```<code>a.index.values[c.values.any(1)]

array([0, 2, 3])
</code>```

Body:
a=pd.DataFrame({'a1':[1,2,3,4],'a2':[5,6,7,8]})
c=pd.DataFrame({'c1':[True,False,True,True],'c2':[True,False,False,True]})

How can I get the index of the elements in columns a1 and a2 which are True in columns c1 and c2 respectively?

The index of a1 should be [0,2,3] and the index of a2 [0,3]. The result could be a list of indexes like [[0,2,3],[0,3]].

Body:
It isn't clear what you want exactly.

This is an approach using stack

a.stack().index[c.stack().values].to_series()

0  a1    (0, a1)
   a2    (0, a2)
2  a1    (2, a1)
3  a1    (3, a1)
   a2    (3, a2)
dtype: object

If you want just the list of index values

a.index.values[c.values.any(1)]

array([0, 2, 3])


问:
Why does hibernate permit the update of a parent table although update="false" is provided to the many-to-one relationship?
I created a simple case for testing and I don't get the expected behavior.
I am interested why hibernate chooses to update the parent table (Country) although I provide update="false" attribute to the many-to-one relationship (in the Address.hbm.xml)?

The DDLs:

```<code>CREATE TABLE Country (
  `id` smallint NOT NULL auto_increment,
  `name` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) TYPE=InnoDB AUTO_INCREMENT=0;
CREATE TABLE Address (
  `id` bigint NOT NULL auto_increment,
  `firstName` varchar(100) NOT NULL,
  `lastName` varchar(100) NOT NULL,
  `countryId` smallint NOT NULL,
  PRIMARY KEY (`id`),
  FOREIGN KEY (countryId)
   REFERENCES Country(id)
   ON UPDATE CASCADE ON DELETE RESTRICT
) TYPE=InnoDB AUTO_INCREMENT=0;
</code>```

The hibernate xmls:

```<code><class name="Country" table="Country" lazy="false">
    <id name="id" column="id" type="integer">
        <generator class="native" />
    </id>
    <property name="name" type="string" not-null="true" length="100"/>
</class>
<class name="Address" table="Address" >
    <id name="id" column="id" type="long" unsaved-value="-1">
        <generator class="native" />
    </id>
    <property name="addressFirstName" column="firstName" type="string" not-null="true" length="100"/>
    <property name="addressLastName" column="lastName" type="string" not-null="true" length="100"/>
    <!-- Country is parent table, Address is child table (holds the FK countryId).
        From MySQL:
        CASCADE: Update the row from the parent table and automatically update the matching rows in the child table.
        RESTRICT: Rejects the delete operation for the parent table.
        From hibernate:
        1. cascade (optional): specifies which operations should be cascaded from the parent object to the associated object.
        2. update, insert (optional - defaults to true): specifies that the mapped columns should be included in SQL UPDATE
        and/or INSERT statements. Setting both to false allows a pure "derived" association whose value is initialized
        from another property that maps to the same column(s), or by a trigger or other application.
     -->
    <many-to-one name="country" class="Country" column="countryId"
        not-null="true" cascade="persist,merge,save-update"  update="false" />
    <many-to-one name="state" class="State" column="stateId"
        cascade="persist,merge,save-update" update="false" />
</class>
</code>```

My Country table has one row (id=1):

```<code>INSERT INTO Country (name) VALUES ("United States");
</code>```

If I do following:

```<code>Country country = getCountryFrom("US");
Address address = new Address();
address.setAddressFirstName("Deksa");
address.setAddressLastName("Jakim");
country.setName("Slovenia");
address.setCountry(country);
address.setId(-1);
saveAddress(address);
session.saveOrUpdate(address);
</code>```

I expect that I have one new row inserted in the Address table, but I also get an update on the Country table - the only row, the name of the country becomes Slovenia, instead of staying United States (expected behavior <= update="false"):

```<code>Hibernate: select country0_.id as id6_, country0_.name as name6_ from Country country0_ where country0_.stringId='US'
Hibernate: insert into Address (firstName, lastName, countryId) values (?, ?, ?)
Hibernate: update Country set name=? where id=?
</code>```

So why does hibernate update the parent table when instructed not to?

Kind regards,

Despot

Edit: Shortly after writing this post I realized that I am confusing the DB's cascade with the hibernate's cascade and that solved all my problems.

The thing is the following: Hibernate clearly says:

update, insert (optional - defaults to
  true): specifies that the mapped
  columns should be included in SQL
  UPDATE  and/or INSERT statements.
  Setting both to false allows a pure
  "derived" association whose value is
  initialized from another property that
  maps to the same column(s), or by a
  trigger or other application.

. This means that when using update="false" on the country property (on the countryId), I say to hibernate you cannot do UPDATE Address SET firstName="x", lastName="y", countryId=123 where condition; Only do an update without the countryId.

Than I saw that the DB's ON UPDATE CASCADE refers to the parent table (Country) - if the Country was updated, than update the child table (the countryId column in Address table). Contrary to what I thought hibernate's update would do, I realized that by providing cascade="save-update", I say to hibebernate, whatever values you have for the Country object in the Address object update them in it's own Country table. So the solution was to have cascade="persist,merge" without the save-update part!

答:
Setting update = "false" on country property doesn't allow you to update the corresponding countryId field, i.e. to choose another Country for particular Address.

If you want to disable chaning of the name of existing Country, you need to specify update = "false" on the corresponding property:

```<code><class name="Country" table="Country" lazy="false">
    ...
    <property name="name" type="string" not-null="true" length="100" update = "false" />
</class>
</code>```

Body:
I created a simple case for testing and I don't get the expected behavior.
I am interested why hibernate chooses to update the parent table (Country) although I provide update="false" attribute to the many-to-one relationship (in the Address.hbm.xml)?

The DDLs:

CREATE TABLE Country (
  `id` smallint NOT NULL auto_increment,
  `name` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) TYPE=InnoDB AUTO_INCREMENT=0;
CREATE TABLE Address (
  `id` bigint NOT NULL auto_increment,
  `firstName` varchar(100) NOT NULL,
  `lastName` varchar(100) NOT NULL,
  `countryId` smallint NOT NULL,
  PRIMARY KEY (`id`),
  FOREIGN KEY (countryId)
   REFERENCES Country(id)
   ON UPDATE CASCADE ON DELETE RESTRICT
) TYPE=InnoDB AUTO_INCREMENT=0;

The hibernate xmls:

<class name="Country" table="Country" lazy="false">
    <id name="id" column="id" type="integer">
        <generator class="native" />
    </id>
    <property name="name" type="string" not-null="true" length="100"/>
</class>
<class name="Address" table="Address" >
    <id name="id" column="id" type="long" unsaved-value="-1">
        <generator class="native" />
    </id>
    <property name="addressFirstName" column="firstName" type="string" not-null="true" length="100"/>
    <property name="addressLastName" column="lastName" type="string" not-null="true" length="100"/>

    <many-to-one name="country" class="Country" column="countryId"
        not-null="true" cascade="persist,merge,save-update"  update="false" />
    <many-to-one name="state" class="State" column="stateId"
        cascade="persist,merge,save-update" update="false" />
</class>

My Country table has one row (id=1):

INSERT INTO Country (name) VALUES ("United States");

If I do following:

Country country = getCountryFrom("US");
Address address = new Address();
address.setAddressFirstName("Deksa");
address.setAddressLastName("Jakim");
country.setName("Slovenia");
address.setCountry(country);
address.setId(-1);
saveAddress(address);
session.saveOrUpdate(address);

I expect that I have one new row inserted in the Address table, but I also get an update on the Country table - the only row, the name of the country becomes Slovenia, instead of staying United States (expected behavior <= update="false"):

Hibernate: select country0_.id as id6_, country0_.name as name6_ from Country country0_ where country0_.stringId='US'
Hibernate: insert into Address (firstName, lastName, countryId) values (?, ?, ?)
Hibernate: update Country set name=? where id=?

So why does hibernate update the parent table when instructed not to?

Kind regards,

Despot

Edit: Shortly after writing this post I realized that I am confusing the DB's cascade with the hibernate's cascade and that solved all my problems.

The thing is the following: Hibernate clearly says:

update, insert (optional - defaults to
  true): specifies that the mapped
  columns should be included in SQL
  UPDATE  and/or INSERT statements.
  Setting both to false allows a pure
  "derived" association whose value is
  initialized from another property that
  maps to the same column(s), or by a
  trigger or other application.

. This means that when using update="false" on the country property (on the countryId), I say to hibernate you cannot do UPDATE Address SET firstName="x", lastName="y", countryId=123 where condition; Only do an update without the countryId.

Than I saw that the DB's ON UPDATE CASCADE refers to the parent table (Country) - if the Country was updated, than update the child table (the countryId column in Address table). Contrary to what I thought hibernate's update would do, I realized that by providing cascade="save-update", I say to hibebernate, whatever values you have for the Country object in the Address object update them in it's own Country table. So the solution was to have cascade="persist,merge" without the save-update part!

Body:
Setting update = "false" on country property doesn't allow you to update the corresponding countryId field, i.e. to choose another Country for particular Address.

If you want to disable chaning of the name of existing Country, you need to specify update = "false" on the corresponding property:

<class name="Country" table="Country" lazy="false">
    ...
    <property name="name" type="string" not-null="true" length="100" update = "false" />
</class>


问:
CSS grid & Sass
The CSS working group member Rachel Andrews mentioned in a conference video that Sass is compatible with the new CSS grid spec.  With that, does anyone know the syntax for spacing the "ASCII art" on grid-template-areas for Sass?  I've since checked the Sass documentation and couldn't find anything (yet).  The errors I get involve spacing.  Appreciate any pointers in the community.  If not, back to .css until then (:  Thanks...

.wrapper
    grid-template-areas: header
                         nav
                         image
                         lead
                         cta //errors occur here with ASCII art grid areas for CSS grid

.header-area
  grid-area: header

.nav-area
  grid-area: nav

.image
  grid-area: image

.lead
  grid-area: lead

.cta
  grid-area: cta```

答:
Grid template areas must be quoted. Each row is a single string:

```<code>  grid-template-areas: "header header"
                       "main   sidebar"
                       "footer footer"
</code>```

full working demo here

edit The above example no longer works, I think due to changes in newer versions of Sass. It cannot handle the multi-line expression (issue here). Each grid row must be defined all in the same line:

```<code>.grid
  display: grid
  grid-template-areas: "header header" "main sidebar" "footer footer"
  grid-gap: 1em
</code>```

The linked demo on codepen has been updated to match. If you use the SCSS syntax (with braces & semi-colons), there isn’t this limitation.

Title: CSS grid & Sass

Body:
Grid template areas must be quoted. Each row is a single string:

  grid-template-areas: "header header"
                       "main   sidebar"
                       "footer footer"

full working demo here

edit The above example no longer works, I think due to changes in newer versions of Sass. It cannot handle the multi-line expression (issue here). Each grid row must be defined all in the same line:

.grid
  display: grid
  grid-template-areas: "header header" "main sidebar" "footer footer"
  grid-gap: 1em

The linked demo on codepen has been updated to match. If you use the SCSS syntax (with braces & semi-colons), there isn’t this limitation.


答:
A DictReader does not seem appropriate to me here, as your data is not organized with each column having a meaning, but rather each line having a name and some arbitrary data.

Are you trying to get a map where map['fbbh-b-an86'] would give you the first line of points ? If so this should do the trick:

```<code>import csv
map = {}
with open(data_points, 'rb') as csvfile:
  reader = csv.reader(csvfile, delimiter=' ')
  for row in reader:
    name = row[0]
    map[name] = row[1:]
print map
</code>```

Title: Store txt with inconsistent column number into a table

Body:
I have this txt files which contains data points stored as such:

fbbh-b-an86 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 110 110 110 110 110 110 110 110 110 110 110 110 110 110 110 110 110 110 110 110 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 138 138 138 138 138 138 138 138 138 138 138 138 138 138 71 71 71 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 71 71 71 71 71 71 71 71 71 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 138 138 138 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 1 1 1 1 1 1 1 1 1 1 1 38 38 38 38 38 38 38 38 38 16 16 16 16 32 32 32 32 32 32 32 32 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 84 84 84 84 84 136 136 136 136 136 136 136 123 123 123 123 123 123 123 1 1 1 1 1 1 1 1 50 50 50 50 50 50 50 50 50 50 50 50 50 50 115 115 115 115 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
fbbh-b-an87 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 42 42 42 42 42 92 92 92 92 92 92 116 116 116 116 116 116 116 47 47 47 47 47 47 47 47 110 110 110 110 110 110 110 110 110 110 110 110 110 110 110 110 110 110 110 68 68 68 68 68 68 68 80 80 80 111 111 111 111 114 114 114 114 114 114 114 114 123 123 123 123 123 123 123 123 123 123 123 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 107 107 107 107 107 107 107 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
fbbh-b-an88 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 66 66 66 108 108 108 108 108 108 108 108 108 52 52 52 52 111 111 111 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 114 114 114 114 114 114 114 114 114 114 114 114 114 114 114 114 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 71 50 50 50 50 50 50 35 35 35 35 35 35 35 35 35 35 35 35 35 35 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 55 55 55 55 55 55 55 55 55 55 1 1 1 1 1 1 1 1 1 1 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 54 54 54 54 54 54 54 54 54 54 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 28 127 127 127 127 127 127 127 1 1 1 1 1 1 1 1 138 138 138 138 138 138 138 138 138 138 68 68 68 108 108 108 108 108 108 108 108 108 108 108 108 108 108 108 108 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 99 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

The name at the beginning is a name associated to the data point, and the numbers are the data points.  The number of data points depends on the name, so the number of columns aren't the same.

I need to store these sets data points in a certain order in a numpy array, in which i though storing it in a map would make life easier, as i just would need to make a lookup based on the name to find get the set of data points i need.  But how do i do that with such a file..

I tried something like this:

import csv

data = open(data_points,"rb")
dict = csv.DictReader(data,delimiter=" ")

but this resulted in None appearing and each entry not being able to look up based on the name..

{'': None, '115': None, '38': None, '16': None, 'fbbh-b-an86': 'fbbh-b-an87', '32': None, '50': None, '1': None, '123': None, '110': '110', '71': None, '138': '107', '84': None, '136': None}
{'': '1', '115': '29', '38': '1', '16': '1', 'fbbh-b-an86': 'fbbh-b-an88', '32': '1', '50': '29', '1': '1', '123': '55', '110': '101', '71': '35', '138': '114', None: ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '54', '54', '54', '54', '54', '54', '54', '54', '54', '54', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '127', '127', '127', '127', '127', '127', '127', '1', '1', '1', '1', '1', '1', '1', '1', '138', '138', '138', '138', '138', '138', '138', '138', '138', '138', '68', '68', '68', '108', '108', '108', '108', '108', '108', '108', '108', '108', '108', '108', '108', '108', '108', '108', '108', '99', '99', '99', '99', '99', '99', '99', '99', '99', '99', '99', '99', '99', '99', '99', '99', '99', '99', '99', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', ''], '84': '42', '136': '42'}
{'': '32', '115': '38', '38': '74', '16': '71', 'fbbh-b-an86': 'fbbh-b-an89', '32': '71', '50': '38', '1': '32', '123': '1', '110': '24', '71': '71', '138': '1', None: ['32', '32', '32', '32', '32', '16', '16', '16', '16', '16', '16', '16', '16', '16', '84', '84', '84', '136', '136', '136', '136', '136', '123', '123', '123', '1', '1', '1', '1', '1', '1', '1', '1', '30', '30', '30', '30', '30', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '71', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '110', '110', '110', '110', '110', '110', '110', '110', '110', '110', '110', '110', '110', '110', '110', '110', '110', '110', '110', '44', '44', '44', '44', '128', '128', '128', '128', '128', '16', '16', '16', '92', '92', '92', '92', '92', '116', '116', '116', '116', '71', '71', '71', '71', '71', '90', '90', '90', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '91', '91', '91', '91', '91', '91', '91', '91', '91', '91', '91', '91', '91', '54', '54', '54', '54', '54', '54', '54', '54', '54', '54', '68', '68', '68', '68', '56', '56', '56', '56', '56', '116', '116', '116', '116', '116', '116', '116', '116', '116', '116', '71', '71', '71', '71', '90', '90', '90', '90', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '28', '91', '91', '91', '91', '91', '91', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', ''], '84': '71', '136': '1'}

Body:
A DictReader does not seem appropriate to me here, as your data is not organized with each column having a meaning, but rather each line having a name and some arbitrary data.

Are you trying to get a map where map['fbbh-b-an86'] would give you the first line of points ? If so this should do the trick:

import csv
map = {}
with open(data_points, 'rb') as csvfile:
  reader = csv.reader(csvfile, delimiter=' ')
  for row in reader:
    name = row[0]
    map[name] = row[1:]
print map