问:
How to remove css transitions without delay?
I want a transition a css property smoothly then I want immediate change in css property value and then I want to attach the transition back again. To better understand see the following example:

if ($(".marquee").height() < $(".marquee-content").outerHeight(true)) {
  $(".marquee-content").clone().appendTo($(".marquee-wrapper"));
}
$('.marquee-wrapper').css("transition", "transform 3s linear");
$('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");

setInterval(function() {

  $('.marquee-wrapper').css("transition", "none");
  $('.marquee-wrapper').css("transform", "translateY(100px)"); //This should Immediately change translateY to 100px without smooth transition. But this doesn't happen without adding a delay before the below written line

  // Its weird why javascript engine executes the below line before executing this line

  $('.marquee-wrapper').css("transition", "transform 3s linear");
  $('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");

}, 3000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.marquee {
  margin: auto;
  width: 600px;
  height: 200px;
  overflow: auto;
}

.marquee-wrapper {
  transform: translateY(0);
}

.marquee-content {
  margin: 0;
  padding: 30px 0;
}</code>```

      Updates: Update (8 Mar 2016): Now plugin have new option: startVisible The marquee will be visible in the start if set to true. Thanks to @nuke-ellington ðŸ‘ Update (24 Jan 2014): Note: people who been asking me how to use this plugin with content being
      loaded with Ajax, please read notes about this update. New methods added, so now after you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq
      = $('.marquee').marquee();, then you can pause, resume, togglepause, resume) and desestroy destroy toggle(pause, resume) and destroy toggle(pause, resume) and destroy methods e.g to remove the marquee plugin from your element simply use $mq.marquee('destroy');.
      Similarly you can use pause the marquee any time using $mq.marquee('pause');.

```
</div>
</div>
</p>

<p>As you can see in the setInterval I first set transition to none then translateY to 100px. Now in principle this should suddenly translate the div to 100px but this doesn't happen before moving div to 100px javascript engine executes the next line and reassign transition. In the below example I have given a 100ms delay before reassigning the transition and it works:  </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>if ($(".marquee").height() < $(".marquee-content").outerHeight(true)) {
  $(".marquee-content").clone().appendTo($(".marquee-wrapper"));
}
$('.marquee-wrapper').css("transition", "transform 3s linear");
$('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");

setInterval(function() {

  $('.marquee-wrapper').css("transition", "none");
  $('.marquee-wrapper').css("transform", "translateY(100px)"); //This  Immedeately change translateY to 100px without smooth transition now

  setTimeout(function(){
      $('.marquee-wrapper').css("transition", "transform 3s linear");
      $('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");
  },100);
}, 3000);</code>```

.marquee {
  margin: auto;
  width: 600px;
  height: 200px;
  overflow: auto;
}

.marquee-wrapper {
  transform: translateY(0);
}

.marquee-content {
  margin: 0;
  padding: 30px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="marquee">
  <div class="marquee-wrapper">
    <div class="marquee-content">
      Updates: Update (8 Mar 2016): Now plugin have new option: startVisible The marquee will be visible in the start if set to true. Thanks to @nuke-ellington ðŸ‘ Update (24 Jan 2014): Note: people who been asking me how to use this plugin with content being
      loaded with Ajax, please read notes about this update. New methods added, so now after you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq
      = $('.marquee').marquee();, then you can pause, resume, togglepause, resume) and desestroy destroy toggle(pause, resume) and destroy toggle(pause, resume) and destroy methods e.g to remove the marquee plugin from your element simply use $mq.marquee('destroy');.
      Similarly you can use pause the marquee any time using $mq.marquee('pause');.
    </div>
  </div>
</section></code>```

My questions are:

How do I stop javscript engine to reassign transition property before making changing translate property, without any delay?

Why does javscript engine excutes a forthcoming line($('.marquee-wrapper').css("transition", "transform 3s linear");) in script before the current line($('.marquee-wrapper').css("transform", "translateY(100px)");)

答:
I think that there are some great answers here telling you why it does work, but if you want a more browser supported animation, use jQuery animations.

```<code>$wrap = $(".marquee-wrapper")
$con = $(".marquee-content");
cHeight = $con.outerHeight(true)

if ($(".marquee").height() < cHeight) {
  $con.clone().appendTo( $wrap );
}

function animate() {
  $wrap.animate({
    top: "-=" + cHeight
  }, 3000, "linear", function() {
    $(this).css("top", "0");
    animate();
  });
}

animate();
</code>```

//Cache values
$wrap = $(".marquee-wrapper")
$con = $(".marquee-content");
cHeight = $con.outerHeight(true)

if ($(".marquee").height() < cHeight) {
  $con.clone().appendTo( $wrap );
}

function animate() {
  $wrap.animate({
    top: "-=" + cHeight //minus height from the value of top
  },
  3000, // milisecs of animations length
  "linear", // type of animations
  function() { //function to run after animation is complete
    $(this).css("top", "0");
    animate();
  });
}

animate(); //Run function in the beginning```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.marquee {
  margin: auto;
  width: 600px;
  height: 200px;
  overflow: auto;
  position: relative;
}

.marquee-wrapper {  position: absolute;  }

.marquee-content {
  margin: 0;
  padding: 30px 0;
}</code>```

      Updates: Update (8 Mar 2016): Now plugin have new option: startVisible The marquee will be visible in the start if set to true. Thanks to @nuke-ellington ðŸ‘ Update (24 Jan 2014): Note: people who been asking me how to use this plugin with content being
      loaded with Ajax, please read notes about this update. New methods added, so now after you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq
      = $('.marquee').marquee();, then you can pause, resume, togglepause, resume) and desestroy destroy toggle(pause, resume) and destroy toggle(pause, resume) and destroy methods e.g to remove the marquee plugin from your element simply use $mq.marquee('destroy');.
      Similarly you can use pause the marquee any time using $mq.marquee('pause');.

```

JSfiddle

Body:
I want a transition a css property smoothly then I want immediate change in css property value and then I want to attach the transition back again. To better understand see the following example:

if ($(".marquee").height() < $(".marquee-content").outerHeight(true)) {
  $(".marquee-content").clone().appendTo($(".marquee-wrapper"));
}
$('.marquee-wrapper').css("transition", "transform 3s linear");
$('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");

setInterval(function() {

  $('.marquee-wrapper').css("transition", "none");
  $('.marquee-wrapper').css("transform", "translateY(100px)"); //This should Immediately change translateY to 100px without smooth transition. But this doesn't happen without adding a delay before the below written line

  // Its weird why javascript engine executes the below line before executing this line

  $('.marquee-wrapper').css("transition", "transform 3s linear");
  $('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");

}, 3000);

.marquee {
  margin: auto;
  width: 600px;
  height: 200px;
  overflow: auto;
}

.marquee-wrapper {
  transform: translateY(0);
}

.marquee-content {
  margin: 0;
  padding: 30px 0;
}

      Updates: Update (8 Mar 2016): Now plugin have new option: startVisible The marquee will be visible in the start if set to true. Thanks to @nuke-ellington ðŸ‘ Update (24 Jan 2014): Note: people who been asking me how to use this plugin with content being
      loaded with Ajax, please read notes about this update. New methods added, so now after you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq
      = $('.marquee').marquee();, then you can pause, resume, togglepause, resume) and desestroy destroy toggle(pause, resume) and destroy toggle(pause, resume) and destroy methods e.g to remove the marquee plugin from your element simply use $mq.marquee('destroy');.
      Similarly you can use pause the marquee any time using $mq.marquee('pause');.

As you can see in the setInterval I first set transition to none then translateY to 100px. Now in principle this should suddenly translate the div to 100px but this doesn't happen before moving div to 100px javascript engine executes the next line and reassign transition. In the below example I have given a 100ms delay before reassigning the transition and it works:

if ($(".marquee").height() < $(".marquee-content").outerHeight(true)) {
  $(".marquee-content").clone().appendTo($(".marquee-wrapper"));
}
$('.marquee-wrapper').css("transition", "transform 3s linear");
$('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");

setInterval(function() {

  $('.marquee-wrapper').css("transition", "none");
  $('.marquee-wrapper').css("transform", "translateY(100px)"); //This  Immedeately change translateY to 100px without smooth transition now

  setTimeout(function(){
      $('.marquee-wrapper').css("transition", "transform 3s linear");
      $('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");
  },100);
}, 3000);

.marquee {
  margin: auto;
  width: 600px;
  height: 200px;
  overflow: auto;
}

.marquee-wrapper {
  transform: translateY(0);
}

.marquee-content {
  margin: 0;
  padding: 30px 0;
}

      Updates: Update (8 Mar 2016): Now plugin have new option: startVisible The marquee will be visible in the start if set to true. Thanks to @nuke-ellington ðŸ‘ Update (24 Jan 2014): Note: people who been asking me how to use this plugin with content being
      loaded with Ajax, please read notes about this update. New methods added, so now after you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq
      = $('.marquee').marquee();, then you can pause, resume, togglepause, resume) and desestroy destroy toggle(pause, resume) and destroy toggle(pause, resume) and destroy methods e.g to remove the marquee plugin from your element simply use $mq.marquee('destroy');.
      Similarly you can use pause the marquee any time using $mq.marquee('pause');.

My questions are:

How do I stop javscript engine to reassign transition property before making changing translate property, without any delay?

Why does javscript engine excutes a forthcoming line($('.marquee-wrapper').css("transition", "transform 3s linear");) in script before the current line($('.marquee-wrapper').css("transform", "translateY(100px)");)

Body:
I think that there are some great answers here telling you why it does work, but if you want a more browser supported animation, use jQuery animations.

$wrap = $(".marquee-wrapper")
$con = $(".marquee-content");
cHeight = $con.outerHeight(true)

if ($(".marquee").height() < cHeight) {
  $con.clone().appendTo( $wrap );
}

function animate() {
  $wrap.animate({
    top: "-=" + cHeight
  }, 3000, "linear", function() {
    $(this).css("top", "0");
    animate();
  });
}

animate();

//Cache values
$wrap = $(".marquee-wrapper")
$con = $(".marquee-content");
cHeight = $con.outerHeight(true)

if ($(".marquee").height() < cHeight) {
  $con.clone().appendTo( $wrap );
}

function animate() {
  $wrap.animate({
    top: "-=" + cHeight //minus height from the value of top
  },
  3000, // milisecs of animations length
  "linear", // type of animations
  function() { //function to run after animation is complete
    $(this).css("top", "0");
    animate();
  });
}

animate(); //Run function in the beginning

.marquee {
  margin: auto;
  width: 600px;
  height: 200px;
  overflow: auto;
  position: relative;
}

.marquee-wrapper {  position: absolute;  }

.marquee-content {
  margin: 0;
  padding: 30px 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="marquee">
  <div class="marquee-wrapper">
    <div class="marquee-content">
      Updates: Update (8 Mar 2016): Now plugin have new option: startVisible The marquee will be visible in the start if set to true. Thanks to @nuke-ellington ðŸ‘ Update (24 Jan 2014): Note: people who been asking me how to use this plugin with content being
      loaded with Ajax, please read notes about this update. New methods added, so now after you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq
      = $('.marquee').marquee();, then you can pause, resume, togglepause, resume) and desestroy destroy toggle(pause, resume) and destroy toggle(pause, resume) and destroy methods e.g to remove the marquee plugin from your element simply use $mq.marquee('destroy');.
      Similarly you can use pause the marquee any time using $mq.marquee('pause');.
    </div>
  </div>
</section>

JSfiddle


来源: stackexchange

问:
No File was submitted while trying to make a POST. Django Rest Framework
I'm trying to make a "POST", but the problem is that I get a "no file was submitted error" and I don't know why.

in my models.py

I don't have "icon" in PersonalDetail

PersonalDetailSample

```<code>class PersonalDetailSample(models.Model):
    ...
    icon = models.FileField(_('icon'), db_index=True, null=True, blank=True, upload_to='files/')
    ...
</code>```

serializers.py

```<code>class PersonalDetailSerializer(serializers.ModelSerializer):
    ...
    icon = serializers.FileField(source='details_sample.icon')
    ...

    class Meta:
        model = PersonalDetail
        fields = (
            ..., 'icon', ...
        )
</code>```

and in my views.py

```<code>def perform_create(self, serializer):
    preview_text, preview_name = personal_details.find_text_name(serializer.validated_data)
    serializer.save(user_id=self.request.user,
                    details_sample=serializer.validated_data['details_sample'],
                    content=serializer.validated_data['content'],
                    preview_name=preview_name)
</code>```

The post I would like to do:

```<code>{
    "checked":true,
    "content": {
        "text_field_1": {
            "size":"small",
            "text":"My userdefined Title",
            "title":"Title"
        },
        "text_field_2": {
            "size":"big",
            "text":"I don't have inspiration",
            "title":"Nachricht"
        }
    },
    "details_sample":27,
    "preview_user_title": "This is my User Title"
}
</code>```

And I get this error: (400 Bad Request)

{
    "icon": [
      "No file was submitted."
    ]
  }

And I don't know why...

Maybe someone had the same trouble.

答:
Try using required=False on serializer, or if you don't need to write at all on the file using the rest api use read_only=True.

required=False option http://www.django-rest-framework.org/api-guide/fields/#required

```<code>class PersonalDetailSerializer(serializers.ModelSerializer):
    ...
    icon = serializers.FileField(source='details_sample.icon', required=False)
    ...

    class Meta:
        model = PersonalDetail
        fields = (
            ..., 'icon', ...
        )
</code>```

OR read_only option
http://www.django-rest-framework.org/api-guide/fields/#read_only

```<code>class PersonalDetailSerializer(serializers.ModelSerializer):
    ...
    icon = serializers.FileField(source='details_sample.icon', read_only=True)
    ...

    class Meta:
        model = PersonalDetail
        fields = (
            ..., 'icon', ...
        )
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to make a "POST", but the problem is that I get a "no file was submitted error" and I don't know why.

in my models.py

I don't have "icon" in PersonalDetail

PersonalDetailSample

class PersonalDetailSample(models.Model):
    ...
    icon = models.FileField(_('icon'), db_index=True, null=True, blank=True, upload_to='files/')
    ...

serializers.py

class PersonalDetailSerializer(serializers.ModelSerializer):
    ...
    icon = serializers.FileField(source='details_sample.icon')
    ...

    class Meta:
        model = PersonalDetail
        fields = (
            ..., 'icon', ...
        )

and in my views.py

def perform_create(self, serializer):
    preview_text, preview_name = personal_details.find_text_name(serializer.validated_data)
    serializer.save(user_id=self.request.user,
                    details_sample=serializer.validated_data['details_sample'],
                    content=serializer.validated_data['content'],
                    preview_name=preview_name)

The post I would like to do:

{
    "checked":true,
    "content": {
        "text_field_1": {
            "size":"small",
            "text":"My userdefined Title",
            "title":"Title"
        },
        "text_field_2": {
            "size":"big",
            "text":"I don't have inspiration",
            "title":"Nachricht"
        }
    },
    "details_sample":27,
    "preview_user_title": "This is my User Title"
}

And I get this error: (400 Bad Request)

{
    "icon": [
      "No file was submitted."
    ]
  }

And I don't know why...

Maybe someone had the same trouble.

Body:
Try using required=False on serializer, or if you don't need to write at all on the file using the rest api use read_only=True.

required=False option http://www.django-rest-framework.org/api-guide/fields/#required

class PersonalDetailSerializer(serializers.ModelSerializer):
    ...
    icon = serializers.FileField(source='details_sample.icon', required=False)
    ...

    class Meta:
        model = PersonalDetail
        fields = (
            ..., 'icon', ...
        )

OR read_only option
http://www.django-rest-framework.org/api-guide/fields/#read_only

class PersonalDetailSerializer(serializers.ModelSerializer):
    ...
    icon = serializers.FileField(source='details_sample.icon', read_only=True)
    ...

    class Meta:
        model = PersonalDetail
        fields = (
            ..., 'icon', ...
        )


问:
Delegation with value types in Swift?
In my application I use to delegation: Controller C use delegation D1 with a model item named M1 and M1 use delegation with another model item called M2.

Everything is fine when M1 invoke delegate method from C.

```<code>C ---> M1
<----- delegation : OK
</code>```

Everything is fine when M2 invoke delegate method from M1.

```<code>M1 ---> M2
<------ delegation : OK
</code>```

But when M2 invoke delegate method from M1 that in turn invoke delegate method from C this does not work.

```<code>C ---> M1 ---> M2
       <------ delegation
<------ delegation
</code>```

Debugger revealed that value for delegate in M1 is nil as it should be C.

Update

```<code>protocol TestOneDelegate:class {

    func testMethodOne(message:String)

}

protocol TestTwoDelegate {

    func testMethodTwo(message:String)

}

//
struct M2 {

    var delegate:TestTwoDelegate?

    func testOperation() {
        delegate?.testMethodTwo(message:"From M2" )
    }
}

struct M1:TestTwoDelegate {

    weak var delegate:TestOneDelegate?
    var m2:M2

    init() {
        m2 = M2()
        m2.delegate = self
    }

    mutating func testOperation() {
        delegate?.testMethodOne(message: "From M1 - Start")

        // BREAKPOINT 1
        m2.testOperation()

        delegate?.testMethodOne(message: "From M1 - End")

    }

    /// Implementation of TestTwoDelegate
    func testMethodTwo(message:String) {

        // BREAKPOINT 2
        print ("M1 get message from M2: " + message)
        delegate?.testMethodOne(message: message + " via M1")
    }

}

class TestControler:UIViewController,TestOneDelegate {

    var m1:M1!

    required init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)

        m1 = M1()
        m1.delegate = self
        m1.testOperation()
    }

    /// Implementation of TestOneDelegate
    func testMethodOne(message:String) {
        print ("Controller get following message from M1: " + message)
    }

}
</code>```

Expected results:

```<code>Controller get following message from M1: From M1 - Start
M1 get message from M2: From M2
Controller get following message from M1: From M2 via M1
Controller get following message from M1: From M1 - End
</code>```

Obtained results:

```<code>Controller get following message from M1: From M1 - Start
M1 get message from M2: From M2
Controller get following message from M1: From M1 - End
</code>```

There is the From M2 via M1 missing...

Stop on 'BREAKPOINT 1', delegate have a value.

Stop on 'BREAKPOINT 2', delegate is nil.

Am I missing something?

答:
The answer was given by @OOper

With value types assignment create a copy of the instance. So in M1.init(), m2.delegate = self create a copy of the instance then assign it to m2.delegate. Thus any modification done to the instance of M1 is not reflected to m2.delegate and m2.delegateis nil.

Part related to Classes and Structures of The Swift Programming Language quote:

As a general guideline, consider creating a structure when one or more of these conditions apply:

  ...

  - Any properties stored by the structure are themselves value types, which would also be expected to be copied rather than referenced.

So best answer to this question is to use class instead of struct when delegation is needed.

For curiosity purpose here follows two answers to the initial problem still using struct. Be aware these solutions only work in the scope of this example. If controller access properties of m1 then problems may comes.

Let's say testMethodTwo now modify m1 properties:

```<code>func testMethodTwo(message:String) {

    // Properties are modify here
    // BREAKPOINT 2
    print ("M1 get message from M2: " + message)
    delegate?.testMethodOne(message: message + " via M1")
}
</code>```

Then when it's method testMethodOne is invoke controller won't see these modifications on m1 as they occured on a distinct copy of m1.

1. Initialize with delegate

```<code>struct M1:TestTwoDelegate {

    var m2 = M2()
    weak var delegate:TestOneDelegate?

    init(delegate:TestOneDelegate) {
        self.delegate = delegate
        m2.delegate = self
    }
</code>```

2. Propagate update

```<code>struct M1:TestTwoDelegate {

    var m2 = M2()

    weak var delegate:TestOneDelegate? {
        didSet {
            m2.delegate = self
        }
    }
</code>```

Title: Delegation with value types in Swift?

Body:
In my application I use to delegation: Controller C use delegation D1 with a model item named M1 and M1 use delegation with another model item called M2.

Everything is fine when M1 invoke delegate method from C.

C ---> M1
<----- delegation : OK

Everything is fine when M2 invoke delegate method from M1.

M1 ---> M2
<------ delegation : OK

But when M2 invoke delegate method from M1 that in turn invoke delegate method from C this does not work.

C ---> M1 ---> M2
       <------ delegation
<------ delegation

Debugger revealed that value for delegate in M1 is nil as it should be C.

Update

protocol TestOneDelegate:class {

    func testMethodOne(message:String)

}

protocol TestTwoDelegate {

    func testMethodTwo(message:String)

}

//
struct M2 {

    var delegate:TestTwoDelegate?

    func testOperation() {
        delegate?.testMethodTwo(message:"From M2" )
    }
}

struct M1:TestTwoDelegate {

    weak var delegate:TestOneDelegate?
    var m2:M2

    init() {
        m2 = M2()
        m2.delegate = self
    }

    mutating func testOperation() {
        delegate?.testMethodOne(message: "From M1 - Start")

        // BREAKPOINT 1
        m2.testOperation()

        delegate?.testMethodOne(message: "From M1 - End")

    }

    /// Implementation of TestTwoDelegate
    func testMethodTwo(message:String) {

        // BREAKPOINT 2
        print ("M1 get message from M2: " + message)
        delegate?.testMethodOne(message: message + " via M1")
    }

}

class TestControler:UIViewController,TestOneDelegate {

    var m1:M1!

    required init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)

        m1 = M1()
        m1.delegate = self
        m1.testOperation()
    }

    /// Implementation of TestOneDelegate
    func testMethodOne(message:String) {
        print ("Controller get following message from M1: " + message)
    }

}

Expected results:

Controller get following message from M1: From M1 - Start
M1 get message from M2: From M2
Controller get following message from M1: From M2 via M1
Controller get following message from M1: From M1 - End

Obtained results:

Controller get following message from M1: From M1 - Start
M1 get message from M2: From M2
Controller get following message from M1: From M1 - End

There is the From M2 via M1 missing...

Stop on 'BREAKPOINT 1', delegate have a value.

Stop on 'BREAKPOINT 2', delegate is nil.

Am I missing something?

Body:
The answer was given by @OOper

With value types assignment create a copy of the instance. So in M1.init(), m2.delegate = self create a copy of the instance then assign it to m2.delegate. Thus any modification done to the instance of M1 is not reflected to m2.delegate and m2.delegateis nil.

Part related to Classes and Structures of The Swift Programming Language quote:

As a general guideline, consider creating a structure when one or more of these conditions apply:

  ...

  - Any properties stored by the structure are themselves value types, which would also be expected to be copied rather than referenced.

So best answer to this question is to use class instead of struct when delegation is needed.

For curiosity purpose here follows two answers to the initial problem still using struct. Be aware these solutions only work in the scope of this example. If controller access properties of m1 then problems may comes.

Let's say testMethodTwo now modify m1 properties:

func testMethodTwo(message:String) {

    // Properties are modify here
    // BREAKPOINT 2
    print ("M1 get message from M2: " + message)
    delegate?.testMethodOne(message: message + " via M1")
}

Then when it's method testMethodOne is invoke controller won't see these modifications on m1 as they occured on a distinct copy of m1.

1. Initialize with delegate

struct M1:TestTwoDelegate {

    var m2 = M2()
    weak var delegate:TestOneDelegate?

    init(delegate:TestOneDelegate) {
        self.delegate = delegate
        m2.delegate = self
    }

2. Propagate update

struct M1:TestTwoDelegate {

    var m2 = M2()

    weak var delegate:TestOneDelegate? {
        didSet {
            m2.delegate = self
        }
    }


问:
removing folder via regex in htaccess
While I'm good with many things scripting and programming, the one thing I never really got into is regex.

I'm tweaking a third party script that uses the url structure of site.com/username/p/seo-friendly-link. I want it to be site.com/username/seo-friendly-link instead

its .htaccess file has

```<code>RewriteRule ^([A-Za-z0-9_-]+)/p/(.*)$ ./dir/pages/post.php?user=$1&pid=$2
RewriteRule ^p/(.*)$ ./dir/pages/post.php?pid=$1
</code>```

when I remove /p as

```<code>RewriteRule ^([A-Za-z0-9_-]+)/(.*)$ ./dir/pages/post.php?user=$1&pid=$2
</code>```

I see it the error in the apache logs as

```<code>[error] [client ::1] Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.
</code>```

I've tried adding the L to the end of the unmodified rule and it still gives the same error.

I want to learn regex, but I feel like this particular example isn't that noob friendly and it'd instead led to more confusion.

can someone explain what those two lines do, how to get what I need or why it's not as simple as it seems?

答:
Not an expert in .htaccess configuration rules, but as far the regex is concerned the problem seems to be that ^([A-Za-z0-9_-]+)/(.*)$ covers too many possible matches because of the last (.*) group which literally matches anything.

In other words, ^([A-Za-z0-9_-]+)/(.*)$ matches both username/p/seo-friendly-link and username/seo-friendly-link. It will also match the target part dir/pages/post.php?user=$1&pid=$2, probably leading to the infinite redirects.

To restrict the regex, you should exclude the / from the second group. So instead of (.*), use [^/]* where [^/] defines a character class that matches any character except /:

```<code>RewriteRule ^([A-Za-z0-9_-]+)/([^/]*)$ ./dir/pages/post.php?user=$1&pid=$2
</code>```

Title: removing folder via regex in htaccess

Body:
While I'm good with many things scripting and programming, the one thing I never really got into is regex.

I'm tweaking a third party script that uses the url structure of site.com/username/p/seo-friendly-link. I want it to be site.com/username/seo-friendly-link instead

its .htaccess file has

RewriteRule ^([A-Za-z0-9_-]+)/p/(.*)$ ./dir/pages/post.php?user=$1&pid=$2
RewriteRule ^p/(.*)$ ./dir/pages/post.php?pid=$1

when I remove /p as

RewriteRule ^([A-Za-z0-9_-]+)/(.*)$ ./dir/pages/post.php?user=$1&pid=$2

I see it the error in the apache logs as

[error] [client ::1] Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

I've tried adding the L to the end of the unmodified rule and it still gives the same error.

I want to learn regex, but I feel like this particular example isn't that noob friendly and it'd instead led to more confusion.

can someone explain what those two lines do, how to get what I need or why it's not as simple as it seems?

Body:
Not an expert in .htaccess configuration rules, but as far the regex is concerned the problem seems to be that ^([A-Za-z0-9_-]+)/(.*)$ covers too many possible matches because of the last (.*) group which literally matches anything.

In other words, ^([A-Za-z0-9_-]+)/(.*)$ matches both username/p/seo-friendly-link and username/seo-friendly-link. It will also match the target part dir/pages/post.php?user=$1&pid=$2, probably leading to the infinite redirects.

To restrict the regex, you should exclude the / from the second group. So instead of (.*), use [^/]* where [^/] defines a character class that matches any character except /:

RewriteRule ^([A-Za-z0-9_-]+)/([^/]*)$ ./dir/pages/post.php?user=$1&pid=$2


问:
Pass all state values to child component
I have a legacy application which passes a JSON to create a multi-page form. I'm trying to create a common multi-page form component in which we can just past a json to generate a form.

The application uses a buildFormState which sets the state in the parent component as:

```<code>constructor(props) {
  super(props);
  this.state = this.buildFormState();
}

 buildFormState() {
let state = SCREENS.reduce(function(o, s) {
    let _s = s.fields.reduce(function(_o, _f) {
        _o[_f.name] = _f.type == 'checkbox'  ? [] : '';
        return _o;
    }, {});
    return Object.assign(o, _s);
}, {});
state.current_screen = 0;
return state;
}
</code>```

And this is my call to my MultiPageForm component:

```<code><MultiStepForm SCREENS = {SCREENS} current_screen = {this.state.current_screen} state = {this.state} submitState={this.submitState.bind(this)} uploadPhoto={this.uploadPhoto.bind(this)} completeForm={this.completeForm.bind(this)} />
</code>```

And my constructor in the MultiStepForm Component is:

```<code>constructor(props) {
super(props);
// this.state = this.props;
this.state = this.props.state;
this.SCREENS = this.props.SCREENS
}
</code>```

But it doesn't pass the state properly as some things get passed while others don't. Is there a way I can pass everything properly without having to individually assign it in the child component?

答:
You can pass all the state like this:

```<code><MultiStepForm {...this.state} />
</code>```

If you don't want to split it and instead send it as an object:

```<code><MultiStepForm childState={this.state} />
</code>```

The use of state string as a prop name should not be a problem, still, it is better to avoid it.

Body:
I have a legacy application which passes a JSON to create a multi-page form. I'm trying to create a common multi-page form component in which we can just past a json to generate a form.

The application uses a buildFormState which sets the state in the parent component as:

constructor(props) {
  super(props);
  this.state = this.buildFormState();
}

 buildFormState() {
let state = SCREENS.reduce(function(o, s) {
    let _s = s.fields.reduce(function(_o, _f) {
        _o[_f.name] = _f.type == 'checkbox'  ? [] : '';
        return _o;
    }, {});
    return Object.assign(o, _s);
}, {});
state.current_screen = 0;
return state;
}

And this is my call to my MultiPageForm component:

<MultiStepForm SCREENS = {SCREENS} current_screen = {this.state.current_screen} state = {this.state} submitState={this.submitState.bind(this)} uploadPhoto={this.uploadPhoto.bind(this)} completeForm={this.completeForm.bind(this)} />

And my constructor in the MultiStepForm Component is:

constructor(props) {
super(props);
// this.state = this.props;
this.state = this.props.state;
this.SCREENS = this.props.SCREENS
}

But it doesn't pass the state properly as some things get passed while others don't. Is there a way I can pass everything properly without having to individually assign it in the child component?

Body:
You can pass all the state like this:

<MultiStepForm {...this.state} />

If you don't want to split it and instead send it as an object:

<MultiStepForm childState={this.state} />

The use of state string as a prop name should not be a problem, still, it is better to avoid it.


问:
How can I find a key in a map based on a pattern matching in java?
I want to find keys in a map with a pattern matching.

```<code>Ex:-
    Map<String, String> map = new HashMap<String, String>();
    map.put("address1", "test test test");
    map.put("address2", "aaaaaaaaaaa");
    map.put("fullname", "bla bla");
</code>```

From above map, I want to get the values of keys which has prefix of "address". So as in this example output should be the first two results ("address1" and "address2").

How can I achieve this dynamically?

答:
I came across a similar need and attempted implementing a POC for such a data structure. I came to the conclusion its much more practical to partition data in some manner :)

However, if you really have your mind set on implementing something like that you would need a structure more similar to a trie tree. Here is what I got (my apologies since the code is in Scala but it can easily be adapted and if you put your mind to it you can probably finish it and make it useable)

```<code>    package component.datastructure

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

class RegExpLookup[T] {

  private val root = new mutable.HashMap[Char, Node]

  def put(key: String, value: T): Unit = {
    addNode(key.toCharArray, 0, root, value)
    println(root.toString)
  }

  private def addNode(key: Array[Char], charIdx: Int,
                      currentRoot: mutable.Map[Char, Node], value: T): Unit = {
    if (charIdx < key.length - 1) {
      if (currentRoot.contains(key(charIdx))) {
        addNode(key, charIdx + 1, currentRoot(key(charIdx)).nodeRoot, value)
      } else {
        val node = Node(null, new mutable.HashMap[Char, Node])
        currentRoot.put(key(charIdx), node)
        addNode(key, charIdx + 1, node.nodeRoot, value)
      }
    } else {
      currentRoot.put(key(charIdx), Node(value, null))
    }
  }

  private def getAll(lastNode: Node, buffer: ArrayBuffer[T]): Unit = {
    if (lastNode.value != null)
      buffer.append(lastNode.value.asInstanceOf[T])
    if (lastNode.nodeRoot != null)
      lastNode.nodeRoot.values.foreach(e => {
        getAll(e, buffer)

      })

  }

  def get(key: String): Iterable[T] = {
    val t = findLastNode(key.toCharArray, 0, root)
    println("getting from " + root)
    val isLast = t._2
    if (isLast) {
      val v = t._1.value
      if (v != null)
        return List(v.asInstanceOf[T])
      else
        return null
    } else {
      val buffer = new ArrayBuffer[T]()
      getAll(t._1, buffer)
      return buffer.toList
    }
  }

  private def findLastNode(key: Array[Char], charIdx: Int,
                           root: mutable.Map[Char, Node]): (Node, Boolean) = {
    if (charIdx < key.length - 2 && (key(charIdx + 1) != '*')) {
      return (root(key(charIdx)), false)
    } else if (charIdx < key.length - 1) {
      return findLastNode(key, charIdx + 1, root(key(charIdx)).nodeRoot)
    } else
      return (root(key(charIdx)), true)
  }
}

case class Node(value: Any, private[datastructure] val nodeRoot: mutable.HashMap[Char, Node]) {

}
</code>```

Basically the idea is we look up every character in a subsequent map the complexity would now be the length of the key. Which, really, should be an acceptable limitation since compilation of a reg ex is likely O(N) anyways. Also in cases where you have shorter keys and many entries would yield much better performance then iterating over all the keys. If you swap the mutable.HashMap with some kind of own implementation with clever hashing and take advantage of the fact that a character is really an int, and in case of ASCII strings (which will likely be the key) actually a short. It would also be more difficult if you're looking up some more complex expression then something*, but still likely doable.

edit: a test

```<code>class MySpec extends PlaySpec {

  val map = new RegExpLookup[String]()

  "RegExpLookup" should {

    "put a bunch of values and get all matching ones" in {
      map.put("abc1", "123")
      map.put("abc2", "456")
      map.put("abc3", "789")
      val result = map.get("abc*")
      println(result)
      val s = result.toSet
      assert(s.contains("123"))
      assert(s.contains("456"))
      assert(s.contains("789"))
    }

    "put a single value and get it by exact key" in {
      map.put("abc", "xyz")
      val result = map.get("abc")
      println(result)
      assert(result.head.equals("xyz"))
    }
  }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to find keys in a map with a pattern matching.

Ex:-
    Map<String, String> map = new HashMap<String, String>();
    map.put("address1", "test test test");
    map.put("address2", "aaaaaaaaaaa");
    map.put("fullname", "bla bla");

From above map, I want to get the values of keys which has prefix of "address". So as in this example output should be the first two results ("address1" and "address2").

How can I achieve this dynamically?

Body:
I came across a similar need and attempted implementing a POC for such a data structure. I came to the conclusion its much more practical to partition data in some manner :)

However, if you really have your mind set on implementing something like that you would need a structure more similar to a trie tree. Here is what I got (my apologies since the code is in Scala but it can easily be adapted and if you put your mind to it you can probably finish it and make it useable)

    package component.datastructure

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

class RegExpLookup[T] {

  private val root = new mutable.HashMap[Char, Node]

  def put(key: String, value: T): Unit = {
    addNode(key.toCharArray, 0, root, value)
    println(root.toString)
  }

  private def addNode(key: Array[Char], charIdx: Int,
                      currentRoot: mutable.Map[Char, Node], value: T): Unit = {
    if (charIdx < key.length - 1) {
      if (currentRoot.contains(key(charIdx))) {
        addNode(key, charIdx + 1, currentRoot(key(charIdx)).nodeRoot, value)
      } else {
        val node = Node(null, new mutable.HashMap[Char, Node])
        currentRoot.put(key(charIdx), node)
        addNode(key, charIdx + 1, node.nodeRoot, value)
      }
    } else {
      currentRoot.put(key(charIdx), Node(value, null))
    }
  }

  private def getAll(lastNode: Node, buffer: ArrayBuffer[T]): Unit = {
    if (lastNode.value != null)
      buffer.append(lastNode.value.asInstanceOf[T])
    if (lastNode.nodeRoot != null)
      lastNode.nodeRoot.values.foreach(e => {
        getAll(e, buffer)

      })

  }

  def get(key: String): Iterable[T] = {
    val t = findLastNode(key.toCharArray, 0, root)
    println("getting from " + root)
    val isLast = t._2
    if (isLast) {
      val v = t._1.value
      if (v != null)
        return List(v.asInstanceOf[T])
      else
        return null
    } else {
      val buffer = new ArrayBuffer[T]()
      getAll(t._1, buffer)
      return buffer.toList
    }
  }

  private def findLastNode(key: Array[Char], charIdx: Int,
                           root: mutable.Map[Char, Node]): (Node, Boolean) = {
    if (charIdx < key.length - 2 && (key(charIdx + 1) != '*')) {
      return (root(key(charIdx)), false)
    } else if (charIdx < key.length - 1) {
      return findLastNode(key, charIdx + 1, root(key(charIdx)).nodeRoot)
    } else
      return (root(key(charIdx)), true)
  }
}

case class Node(value: Any, private[datastructure] val nodeRoot: mutable.HashMap[Char, Node]) {

}

Basically the idea is we look up every character in a subsequent map the complexity would now be the length of the key. Which, really, should be an acceptable limitation since compilation of a reg ex is likely O(N) anyways. Also in cases where you have shorter keys and many entries would yield much better performance then iterating over all the keys. If you swap the mutable.HashMap with some kind of own implementation with clever hashing and take advantage of the fact that a character is really an int, and in case of ASCII strings (which will likely be the key) actually a short. It would also be more difficult if you're looking up some more complex expression then something*, but still likely doable.

edit: a test

class MySpec extends PlaySpec {

  val map = new RegExpLookup[String]()

  "RegExpLookup" should {

    "put a bunch of values and get all matching ones" in {
      map.put("abc1", "123")
      map.put("abc2", "456")
      map.put("abc3", "789")
      val result = map.get("abc*")
      println(result)
      val s = result.toSet
      assert(s.contains("123"))
      assert(s.contains("456"))
      assert(s.contains("789"))
    }

    "put a single value and get it by exact key" in {
      map.put("abc", "xyz")
      val result = map.get("abc")
      println(result)
      assert(result.head.equals("xyz"))
    }
  }

}


问:
Mongoose Geospatial Query find all User Spheres which include a given point
Im trying to find the right way to query the given scenario.

I have a bunch of user with a location latlng and a user defined radius.
And i have a point of interest with an location latlng.
Now i want to find all users their spheres including the latlng of the point of interest.

I provide you how query in the moment but this is obviously wrong.

Schema:

```<code>    const POISchema = new mongoose.Schema({
                                   poi_uuid: {type: String, required: true},
                                   category_uuid: {type: Number, required: true},
                                   category: {type: String, ref: 'SubCategory'},
                                   activity: {type: String, required: false},
                                   infos: {type: String, required: false},
                                   location: {
                                               coordinates: {type: [Number], index: '2d', required: false, default: []}
                                              }
                                           }, {usePushEach: true});

    const UserSchema = new mongoose.Schema({
                                   user_uuid: {type: String, required: true},
                                   helper_radius: {type: Number, required: true},
                                   address: {
                                               coordinates: {type: [Number], index: '2d', required: false, default: []}
                                             }
                                          }, {usePushEach: true});
</code>```

Query:

```<code>User.find()
                    .and([
                        {
                            latlng: {
                                $near: [parseFloat(obj.coordinates[0]), parseFloat(obj.coordinates[1])],
                                $maxDistance: parseFloat(20 / 111.2)
                            }
                        },
                        {'_id': {'$ne': obj._id}},
                        {'categories': obj.category_uuid}
                    ])
                    .exec(function (err, users) {
                        if (err) {
                            console.log(err);
                            return res.send(500, JSON.stringify(err))
                        }
                        return res.send({users: users})
                    })
</code>```

I know that i may have to use $geoWithin or $geoIntersects. But i really don't know how and i read like everything i could find. I even don't find how to declare a schema field with mongoose for a 2d sphere with an defined radius. Maybe somebody can point me in the right direction or has some helpful links.

答:
I think you're looking for something like this:</p>

```<code>var poi; // this is the point of interest for which I want to find the users nearby
User.aggregate(
    [
        { "$geoNear": {
            "near": poi.location.coordinates,
            "distanceField": "distance"
        }},
        { "$redact": {
            "$cond": {
                "if": { "$lt": [ "$distance", "$helper_radius" ] },
                "then": "$$KEEP",
                "else": "$$PRUNE"
            }
        }}
    ],
    function(err,results) {
       // read the response
    }
);
</code>```

Body:
Im trying to find the right way to query the given scenario.

I have a bunch of user with a location latlng and a user defined radius.
And i have a point of interest with an location latlng.
Now i want to find all users their spheres including the latlng of the point of interest.

I provide you how query in the moment but this is obviously wrong.

Schema:

    const POISchema = new mongoose.Schema({
                                   poi_uuid: {type: String, required: true},
                                   category_uuid: {type: Number, required: true},
                                   category: {type: String, ref: 'SubCategory'},
                                   activity: {type: String, required: false},
                                   infos: {type: String, required: false},
                                   location: {
                                               coordinates: {type: [Number], index: '2d', required: false, default: []}
                                              }
                                           }, {usePushEach: true});

    const UserSchema = new mongoose.Schema({
                                   user_uuid: {type: String, required: true},
                                   helper_radius: {type: Number, required: true},
                                   address: {
                                               coordinates: {type: [Number], index: '2d', required: false, default: []}
                                             }
                                          }, {usePushEach: true});

Query:

User.find()
                    .and([
                        {
                            latlng: {
                                $near: [parseFloat(obj.coordinates[0]), parseFloat(obj.coordinates[1])],
                                $maxDistance: parseFloat(20 / 111.2)
                            }
                        },
                        {'_id': {'$ne': obj._id}},
                        {'categories': obj.category_uuid}
                    ])
                    .exec(function (err, users) {
                        if (err) {
                            console.log(err);
                            return res.send(500, JSON.stringify(err))
                        }
                        return res.send({users: users})
                    })

I know that i may have to use $geoWithin or $geoIntersects. But i really don't know how and i read like everything i could find. I even don't find how to declare a schema field with mongoose for a 2d sphere with an defined radius. Maybe somebody can point me in the right direction or has some helpful links.

Body:
I think you're looking for something like this:

var poi; // this is the point of interest for which I want to find the users nearby
User.aggregate(
    [
        { "$geoNear": {
            "near": poi.location.coordinates,
            "distanceField": "distance"
        }},
        { "$redact": {
            "$cond": {
                "if": { "$lt": [ "$distance", "$helper_radius" ] },
                "then": "$$KEEP",
                "else": "$$PRUNE"
            }
        }}
    ],
    function(err,results) {
       // read the response
    }
);


问:
asyncio function not defined python 3.6
Ive been having trouble with this for a little while now. When declaring a async function like:

```<code>async def init(loop):
</code>```

and then I call the function it returns a:

```<code>NameError: name 'init' is not defined
</code>```

Here is how the code all looks:

```<code>class Server:

    def __init__(self, port):
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
        loop = asyncio.get_event_loop()
        server = loop.run_until_complete(init(loop))

        print("Serving on {}".format(server.sockets[0].getsockname()))
        try:
            loop.run_forever()
        except KeyboardInterrupt:
            print("\rclosing the server")
            pass

        server.close()
        loop.run_until_complete(server.wait_closed())
        loop.close()

    async def init(loop):
        server = await loop.create_server(handle_request, '127.0.0.1', 8881)
        return server

    async def handle_request():
</code>```

Any direction that you could point me in would be helpful.
Thanks!

答:
Seems like def init() is inside your class.  Move it out of the class by unindenting it:

```<code>class Server:

    def __init__(self, port):
        #....
        loop.close()

    # IT SHOULD NOT BE HERE
#IT SHOULD BE HERE!!!
async def init(loop):
    server = await loop.create_server(handle_request, '127.0.0.1', 8881)
    return server
</code>```

Title: asyncio function not defined python 3.6

Body:
Ive been having trouble with this for a little while now. When declaring a async function like:

async def init(loop):

and then I call the function it returns a:

NameError: name 'init' is not defined

Here is how the code all looks:

class Server:

    def __init__(self, port):
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
        loop = asyncio.get_event_loop()
        server = loop.run_until_complete(init(loop))

        print("Serving on {}".format(server.sockets[0].getsockname()))
        try:
            loop.run_forever()
        except KeyboardInterrupt:
            print("\rclosing the server")
            pass

        server.close()
        loop.run_until_complete(server.wait_closed())
        loop.close()

    async def init(loop):
        server = await loop.create_server(handle_request, '127.0.0.1', 8881)
        return server

    async def handle_request():

Any direction that you could point me in would be helpful.
Thanks!

Body:
Seems like def init() is inside your class.  Move it out of the class by unindenting it:

class Server:

    def __init__(self, port):
        #....
        loop.close()

    # IT SHOULD NOT BE HERE
#IT SHOULD BE HERE!!!
async def init(loop):
    server = await loop.create_server(handle_request, '127.0.0.1', 8881)
    return server


问:
Environment variable used by CMake to detect Visual C++ compiler tools for Ninja
I have Mingw64 GCC 6.3.0 (always in PATH) and Visual C++ compiler tools from Visual Studio 2017 RTM (not in PATH).

If I run cmake . -G "MinGW Makefiles", GCC 6.3.0 will be selected.

If I run cmake . -G "Ninja", GCC 6.3.0 will be selected.

My Visual C++ compiler tools is none standard, I only keep the parts I need and delete the rest (like MSBuild, IDE etc.). I use my own batch script to set up PATH, INCLUDE and LIB (works just fine).

If I run this batch script and run cmake ., MSVC will be selected and build with NMake.

With the same environment, cmake . -G "Ninja", GCC 6.3.0 is selected instead of MSVC.

So my question is, how to tell CMake I want to use MSVC + Ninja rather than GCC + Ninja when both are in PATH? Any environment variable I should set?

答:
You can also use the inverted approach and exclude all compilers you don't want with CMAKE_IGNORE_PATH. It takes a list of paths to ignore, but be aware that it needs to be an exact string match. The advantage would be that you can declare those directly from the command line.

So what I did is to take the path from the compiler found but "not to be taken" into CMAKE_IGNORE_PATH.

And on my system there were actually three GCC compilers in my PATH (just make sure to start from an empty binary output directory with each try):

```<code>> cmake -G"Ninja" ..
...
-- Check for working C compiler: C:/MinGW/bin/cc.exe
...
</code>```

```<code>> cmake -DCMAKE_IGNORE_PATH="C:/MinGW/bin" -G"Ninja" ..
...
-- Check for working C compiler: C:/Strawberry/c/bin/gcc.exe
...
</code>```

```<code>> cmake -DCMAKE_IGNORE_PATH="C:/MinGW/bin;C:/Strawberry/c/bin" -G"Ninja" ..
...
-- Check for working C compiler: C:/Program Files (x86)/LLVM/bin/clang.exe
...
</code>```

```<code>> cmake -DCMAKE_IGNORE_PATH="C:/MinGW/bin;C:/Strawberry/c/bin;C:/Program Files (x86)/LLVM/bin" -G"Ninja" ..
...
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/cl.exe
...
</code>```

Body:
You can also use the inverted approach and exclude all compilers you don't want with CMAKE_IGNORE_PATH. It takes a list of paths to ignore, but be aware that it needs to be an exact string match. The advantage would be that you can declare those directly from the command line.

So what I did is to take the path from the compiler found but "not to be taken" into CMAKE_IGNORE_PATH.

And on my system there were actually three GCC compilers in my PATH (just make sure to start from an empty binary output directory with each try):

> cmake -G"Ninja" ..
...
-- Check for working C compiler: C:/MinGW/bin/cc.exe
...

> cmake -DCMAKE_IGNORE_PATH="C:/MinGW/bin" -G"Ninja" ..
...
-- Check for working C compiler: C:/Strawberry/c/bin/gcc.exe
...

> cmake -DCMAKE_IGNORE_PATH="C:/MinGW/bin;C:/Strawberry/c/bin" -G"Ninja" ..
...
-- Check for working C compiler: C:/Program Files (x86)/LLVM/bin/clang.exe
...

> cmake -DCMAKE_IGNORE_PATH="C:/MinGW/bin;C:/Strawberry/c/bin;C:/Program Files (x86)/LLVM/bin" -G"Ninja" ..
...
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/cl.exe
...


问:
PL/SQL ORACLE FUNCTION
I want to make function to count my all ID.
But my function does not work. Do not know why ?
I am using Oracle SQL Developer.</p>

```<code>CREATE FUNCTION policz(wartosc as NUMBER)
RETURN INT
IS
ile INT
BEGIN
SELECT COUNT(Id) INTO ile FROM t_dane
RETURN ILE;
end;
</code>```

答:
You have some issues in your code:

```<code>CREATE OR REPLACE FUNCTION policz(wartosc NUMBER)
    RETURN INT IS
    ile                                     INT;
BEGIN
    SELECT COUNT(Id) INTO ile FROM t_dane;

    RETURN ILE;
END;
</code>```

Also, the wartosc parameter is unuseful: you never use it.

Title: PL/SQL ORACLE FUNCTION

Body:
I want to make function to count my all ID.
But my function does not work. Do not know why ?
I am using Oracle SQL Developer.

CREATE FUNCTION policz(wartosc as NUMBER)
RETURN INT
IS
ile INT
BEGIN
SELECT COUNT(Id) INTO ile FROM t_dane
RETURN ILE;
end;

Body:
You have some issues in your code:

CREATE OR REPLACE FUNCTION policz(wartosc NUMBER)
    RETURN INT IS
    ile                                     INT;
BEGIN
    SELECT COUNT(Id) INTO ile FROM t_dane;

    RETURN ILE;
END;

Also, the wartosc parameter is unuseful: you never use it.


问:
How to create a table with variable number of columns in itext7?
I'm trying to create a table that may have one to six columns, depending upon the data. If a column doesn't have any entries in any of the rows, the column should not be shown. So, one document may show the name, building and email columns and the next may show the name, email, telephone and office columns. For example, the empty columns outlined in pink should not be shown:

The only way I've found to create a table is to define the columns in the constructor. I tried setting the column width to zero but that didn't achieve the desired outcome. Can columns be added/removed after a table object is created?

C#

```<code>    Table table = new Table( new UnitValue[]
    {
        new UnitValue( UnitValue.PERCENT, 20F ),
        new UnitValue( UnitValue.PERCENT, columns.ContainsKey("Building") ? 20F : 0F ),
        new UnitValue( UnitValue.PERCENT, columns.ContainsKey("Email") ? 15F : 0F ),
        new UnitValue( UnitValue.PERCENT, columns.ContainsKey("Telephone") ? 10F : 0F ),
        new UnitValue( UnitValue.PERCENT, columns.ContainsKey("Office") ? 10F : 0F ),
        new UnitValue( UnitValue.PERCENT, columns.ContainsKey("Note") ? 25F : 0F )
    }, true );
</code>```

答:
The iText team is slowly and methodically deprecating all the popular ways of setting up the columns in a Table! I suspect a conspiracy, but can't prove it ;-)

On a more serious note, it would be nice to know the philosophy behind some of these recent decisions. Are there plans for a super suite of tidy new APIs to handle this issue? Should we wait for some good news, or start complaining now?

With regard to Jim's issue, he is stuck between a rock and a hard place. Alexey is correct that the UnitValues should be set-up before the Table is ever created, but this code still assumes that columns get expanded to fill the available space. This is the way the old float-based Table constructor worked, and that has just been deprecated. This begs the question of how percentage column widths are treated, and that is neither documented nor guaranteed to remain the same in future releases. If I create a table with two columns, each of 25%, perhaps I want half the table to be blank. I don't see that it's iText's job to re-interpret my values, or try to "fix" them if I've made a mistake.

This is a well-known computing problem, and the common way to handle it is to allow a sentinel value in the list of column-widths which means "whatever's left". Then a percent array like say { 10%, -1, 10% } means two narrow columns either side of one 80% one. In Jim's case he knows how wide some of his columns need to be, but not the overall width, so he would do, say, 20% for Name, 10% for Number and -1 for the others, so they would get equal shares of whatever was left.

Body:
I'm trying to create a table that may have one to six columns, depending upon the data. If a column doesn't have any entries in any of the rows, the column should not be shown. So, one document may show the name, building and email columns and the next may show the name, email, telephone and office columns. For example, the empty columns outlined in pink should not be shown:

The only way I've found to create a table is to define the columns in the constructor. I tried setting the column width to zero but that didn't achieve the desired outcome. Can columns be added/removed after a table object is created?

C#

    Table table = new Table( new UnitValue[]
    {
        new UnitValue( UnitValue.PERCENT, 20F ),
        new UnitValue( UnitValue.PERCENT, columns.ContainsKey("Building") ? 20F : 0F ),
        new UnitValue( UnitValue.PERCENT, columns.ContainsKey("Email") ? 15F : 0F ),
        new UnitValue( UnitValue.PERCENT, columns.ContainsKey("Telephone") ? 10F : 0F ),
        new UnitValue( UnitValue.PERCENT, columns.ContainsKey("Office") ? 10F : 0F ),
        new UnitValue( UnitValue.PERCENT, columns.ContainsKey("Note") ? 25F : 0F )
    }, true );


问:
How to Access Vue-Loader Components in an HTML File
I would like to use the modular style and file format of Vue Loader (i.e., where I have a template section, script section and style section in each .vue file).

What I can't figure out how to do (or if it is even possible to do) is use my custom templates in an html file.

For instance, in the App.vue file I can use the following code:

```<code><template>
  <div id="app">
    <message>Hello there</message>
  </div>
</template>
</code>```

This will work to display a custom message component on the home page.

What I would like to do instead is use my custom components in html files.  For instance, in the index.html file to use the following code:

```<code>  <div id="app">
    <message>Hello there</message>
  </div>
</code>```

Any idea how I can do this?  Thanks.

NOTE:  I am new to Vue Loader and semi-new to Vue (so I apologize in advance if the answer to this question is obvious).

答:
Actually you can do this easily by:

register your component :

```<code>Vue.component('message', {
    template: '<div>A custom component!</div>'
});
</code>```

then comment the render function in your Vue instance like so:

```<code>new Vue({
  el: '#app',
  // render: h => h(App)
})
</code>```

after that you will be able to render your message Tag like this:

```<code><div id="app">
      <message></message>
</div>
</code>```

Edit :
if you don't want to use this way you can define it in your view instance:

```<code>new Vue({
  el: '#app',
  // render: h => h(App)
  components: {
    message: {
     template: `
    <h1>Hello World</h1>
        `
    }
  }
})
</code>```

Body:
I would like to use the modular style and file format of Vue Loader (i.e., where I have a template section, script section and style section in each .vue file).

What I can't figure out how to do (or if it is even possible to do) is use my custom templates in an html file.

For instance, in the App.vue file I can use the following code:

<template>

    <message>Hello there</message>

</template>

This will work to display a custom message component on the home page.

What I would like to do instead is use my custom components in html files.  For instance, in the index.html file to use the following code:

    <message>Hello there</message>

Any idea how I can do this?  Thanks.

NOTE:  I am new to Vue Loader and semi-new to Vue (so I apologize in advance if the answer to this question is obvious).

Body:
Actually you can do this easily by:

register your component :

Vue.component('message', {
    template: '<div>A custom component!</div>'
});

then comment the render function in your Vue instance like so:

new Vue({
  el: '#app',
  // render: h => h(App)
})

after that you will be able to render your message Tag like this:

<div id="app">
      <message></message>
</div>

Edit :
if you don't want to use this way you can define it in your view instance:

new Vue({
  el: '#app',
  // render: h => h(App)
  components: {
    message: {
     template: `
    <h1>Hello World</h1>
        `
    }
  }
})


问:
how to write a function in bash_profile
how can we write a simple regular function which i can put in my bashprofile
which can be used to secure console to any host i want.

but my secure console has to go through a jump host. that is the issue.

```<code>function func_name () {
 ssh jumphostname;
 sc $hostname # from jump host secure console to another host given as input from terminal
}
</code>```

this function only making to login in to jump host but not to secureconsole in to another host from there.

-bash-4.1$func_name host.me.com
should give me console to host.me.com via jumphost

is function for this not possible?
do i have to write a script?

答:
I would write this

```<code>con.sole() {
    if ! ssh -T jumphostname true; then
        printf 'Jump host "%s" not available.\n' jumphostname >&2
        return 1
    fi
    sc "$@"
}
</code>```

The square brace isn't part of the if statement syntax. It is a separate command, the same as test.

Title: how to write a function in bash_profile

Body:
how can we write a simple regular function which i can put in my bashprofile
which can be used to secure console to any host i want.

but my secure console has to go through a jump host. that is the issue.

function func_name () {
 ssh jumphostname;
 sc $hostname # from jump host secure console to another host given as input from terminal
}

this function only making to login in to jump host but not to secureconsole in to another host from there.

-bash-4.1$func_name host.me.com
should give me console to host.me.com via jumphost

is function for this not possible?
do i have to write a script?

Body:
I would write this

con.sole() {
    if ! ssh -T jumphostname true; then
        printf 'Jump host "%s" not available.\n' jumphostname >&2
        return 1
    fi
    sc "$@"
}

The square brace isn't part of the if statement syntax. It is a separate command, the same as test.


问:
Not calling notifyDataSetChanged() but data changing anyway? Lifecycle of RecyclerView and Adapter?
So my problem seem to be the opposite of everything else that I've come across around here.

I have the following piece of code:

RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    MyAdapter adapter = new MyAdapter(this);
    recyclerView.setAdapter(adapter);
    adapter.buildModels();
```

So I first set the adapter to the Recycler view, and then I build the models. There is, therefore, a brief moment in time where getItemCount() in the adapter is 0.
I never call notifyDataSetChanged() anywhere, but after calling buildModels() the adapter starts displaying the models. I've seen a couple of observers going on in the source code of RecyclerView.

To try to test how this works, I also added a method "adapter.addOneMoreItem()" right after adapter.buildModels(), and the adapter also knows how to display the new item.

So question: when exactly is notifyDataSetChanged() needed? What's the use case?
Anyone knows the exact lifecycle of the RecyclerView and Adapter?

Comments:
MyAdapter is a regular Adapter ->
public class MyAdapter extends RecyclerView.Adapter< RecyclerView.ViewHolder > {}

答:
RecyclerView.Adapter can be "observed" by other classes. When you'call RecyclerView.setAdapter(), it's calls registerAdapterDataObserver() of adapter. So, adapter knows that you entered new data.

Here is the source code or RecyclerView: https://android.googlesource.com/platform/frameworks/support/+/refs/heads/master/v7/recyclerview/src/android/support/v7/widget/RecyclerView.java

Body:
So my problem seem to be the opposite of everything else that I've come across around here.

I have the following piece of code:

RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    MyAdapter adapter = new MyAdapter(this);
    recyclerView.setAdapter(adapter);
    adapter.buildModels();

So I first set the adapter to the Recycler view, and then I build the models. There is, therefore, a brief moment in time where getItemCount() in the adapter is 0.
I never call notifyDataSetChanged() anywhere, but after calling buildModels() the adapter starts displaying the models. I've seen a couple of observers going on in the source code of RecyclerView.

To try to test how this works, I also added a method "adapter.addOneMoreItem()" right after adapter.buildModels(), and the adapter also knows how to display the new item.

So question: when exactly is notifyDataSetChanged() needed? What's the use case?
Anyone knows the exact lifecycle of the RecyclerView and Adapter?

Comments:
MyAdapter is a regular Adapter ->
public class MyAdapter extends RecyclerView.Adapter< RecyclerView.ViewHolder > {}


问:
Get Duplicates in List and Edit Item
I need to get any items in a list that already exist and edit BOTH items to include a duplicate property.

I've attempted to get duplicates by doing:

```<code>var duplicates = LIST.Select((t, i) => new { Index = i, Text = t }).GroupBy(g => g.Text.PROPERTYTOSEARCGBY).Where(g => g.Count() > 1);
</code>```

However this returns me the property that is duplicated when however I need to get index of both of the records so that I can edit them using:

```<code>LIST[index1].FlaggedData = true;
LIST[index2].FlaggedData = true;
etc...
</code>```

How can I get the index of BOTH duplicate or multiple records?

答:
The variable duplicates is an IGrouping that can be iterated.  Each element in the enumeration will be an anonymous type that you defined to have 2 properties: Index and Text.

```<code>foreach (var grouping in duplicates)
{
    // This will contain the value that was grouped by:
    // - grouping.Key

    foreach (var pair in grouping)
    {
        // These properties are available
        //  - pair.Index
        //  - pair.Text

        // set the FlaggedData property
        pair.Text.FlaggedData = true;
    }
}
</code>```

Title: Get Duplicates in List and Edit Item

Body:
I need to get any items in a list that already exist and edit BOTH items to include a duplicate property.

I've attempted to get duplicates by doing:

var duplicates = LIST.Select((t, i) => new { Index = i, Text = t }).GroupBy(g => g.Text.PROPERTYTOSEARCGBY).Where(g => g.Count() > 1);

However this returns me the property that is duplicated when however I need to get index of both of the records so that I can edit them using:

LIST[index1].FlaggedData = true;
LIST[index2].FlaggedData = true;
etc...

How can I get the index of BOTH duplicate or multiple records?

Body:
The variable duplicates is an IGrouping that can be iterated.  Each element in the enumeration will be an anonymous type that you defined to have 2 properties: Index and Text.

foreach (var grouping in duplicates)
{
    // This will contain the value that was grouped by:
    // - grouping.Key

    foreach (var pair in grouping)
    {
        // These properties are available
        //  - pair.Index
        //  - pair.Text

        // set the FlaggedData property
        pair.Text.FlaggedData = true;
    }
}


问:
How does Git compute SHA hashes so quickly?
I know git is fast but I have only recently found how fast it really can be.

In one of my projects, I am trying to compute SHA-256 hashes of a huge file (82 MB with 850k rows) and it took over a minute to compute it (includes hashing and a couple of other small operations).

Even with SHA-1, it took me 30+ seconds while git seems to be doing it in just a second or two.

I am computing the hash in Scala using java's Security API by combining all the lines of the file.

```<code>val lines = Source.fromFile(filePath, "UTF-8").getLines().toList
MessageDigest.getInstance("SHA-256")
.digest(lines.mkString("\n").getBytes).map("%02x".format(_)).mkString
</code>```

So, how does Git do it so quickly, or rather the more important question, why is my method so slow?

Edit: For those not familiar with scala syntax, lines will have all the lines of the file in a List and mkString method returns a string of all the elements in the list combined with the given separator.

答:
Reposting my earlier comment (extended).

What you do is:

Read bytes

Convert them to characters

Split the character stream to lines

Store those lines into a list

Again concatenate those lines into a string

Take its bytes again

Compute hash of those bytes

Steps 2-6 seem unnecessary. I would recommend to read bytes from your initial FileInputStream in chunks (for example, of 4k) and feed them to the MessageDigest for update. That would just perform steps 1 and 7.

```<code>InputStream is = new FileInputStream(fileName);
byte[] buffer = new byte[4096];
while (true) {
    int read = is.read(buffer);
    if (read < 0) {
        break;
    }
    md.update(buffer, 0, read);
}
is.close(); // better be done in finally
</code>```

As for sha1 performance, here is what I got for time sha1sum <file> where file is 179Mb:

```<code>real    0m0.607s
user    0m0.588s
sys 0m0.016s
</code>```

Body:
I know git is fast but I have only recently found how fast it really can be.

In one of my projects, I am trying to compute SHA-256 hashes of a huge file (82 MB with 850k rows) and it took over a minute to compute it (includes hashing and a couple of other small operations).

Even with SHA-1, it took me 30+ seconds while git seems to be doing it in just a second or two.

I am computing the hash in Scala using java's Security API by combining all the lines of the file.

val lines = Source.fromFile(filePath, "UTF-8").getLines().toList
MessageDigest.getInstance("SHA-256")
.digest(lines.mkString("\n").getBytes).map("%02x".format(_)).mkString

So, how does Git do it so quickly, or rather the more important question, why is my method so slow?

Edit: For those not familiar with scala syntax, lines will have all the lines of the file in a List and mkString method returns a string of all the elements in the list combined with the given separator.

Body:
Reposting my earlier comment (extended).

What you do is:

Read bytes

Convert them to characters

Split the character stream to lines

Store those lines into a list

Again concatenate those lines into a string

Take its bytes again

Compute hash of those bytes

Steps 2-6 seem unnecessary. I would recommend to read bytes from your initial FileInputStream in chunks (for example, of 4k) and feed them to the MessageDigest for update. That would just perform steps 1 and 7.

InputStream is = new FileInputStream(fileName);
byte[] buffer = new byte[4096];
while (true) {
    int read = is.read(buffer);
    if (read < 0) {
        break;
    }
    md.update(buffer, 0, read);
}
is.close(); // better be done in finally

As for sha1 performance, here is what I got for time sha1sum <file> where file is 179Mb:

real    0m0.607s
user    0m0.588s
sys 0m0.016s


问:
QuickFix - 'ObjectDisposedException' error on NewOrderSingle
I'm working on FxPro Ctrader broker (FIX 4.4) and I'm trying to make an FixApi  in C# using QuickFix/n library (1.7.0.0).

I stucked at 'NewOrderSingle':
  After successful logon I'm trying to make an order:

```<code>class TradeConnection : MessageCracker, IApplication
{
  public void OnLogon(SessionID sessionID)
    {
       Write.Info("Account TRADE successful logged " + sessionID);
       sendOrder();
    }

  public void sendOrder()
    {
       NewOrderSingle oc = new NewOrderSingle();
       ClOrdID ID = new ClOrdID("1408479");
       Symbol symb = new Symbol("1");
       Side side = new Side('1');
       OrderQty lots = new OrderQty(1000);
       OrdType type = new OrdType('1');
       TransactTime TransactTime = new TransactTime(DateTime.Now);
       TimeInForce TimeInForce = new TimeInForce('3');
       oc.SetField(ID);
       oc.SetField(symb);
       oc.SetField(side);
       oc.SetField(lots);
       oc.SetField(type);
       oc.SetField(TimeInForce);
       send(oc);
     }

  public void send(QuickFix.Message message)
    {
      Session.SendToTarget(message, sessionID);
    }
}
</code>```

Unfortunately it isn't working and I get error:

A first chance exception of type 'System.ObjectDisposedException' occurred in System.dll

Same error appears @

RequestForPositions and OrderStatusRequest

On same account in api that uses NetworkStream rather than QuickFix lib it works fine.

答:
Problem solved.
Forgot to set field TransactTime which counterparty required:</p>

```<code>oc.SetField(TransactTime);
</code>```

Body:
I'm working on FxPro Ctrader broker (FIX 4.4) and I'm trying to make an FixApi  in C# using QuickFix/n library (1.7.0.0).

I stucked at 'NewOrderSingle':
  After successful logon I'm trying to make an order:

class TradeConnection : MessageCracker, IApplication
{
  public void OnLogon(SessionID sessionID)
    {
       Write.Info("Account TRADE successful logged " + sessionID);
       sendOrder();
    }

  public void sendOrder()
    {
       NewOrderSingle oc = new NewOrderSingle();
       ClOrdID ID = new ClOrdID("1408479");
       Symbol symb = new Symbol("1");
       Side side = new Side('1');
       OrderQty lots = new OrderQty(1000);
       OrdType type = new OrdType('1');
       TransactTime TransactTime = new TransactTime(DateTime.Now);
       TimeInForce TimeInForce = new TimeInForce('3');
       oc.SetField(ID);
       oc.SetField(symb);
       oc.SetField(side);
       oc.SetField(lots);
       oc.SetField(type);
       oc.SetField(TimeInForce);
       send(oc);
     }

  public void send(QuickFix.Message message)
    {
      Session.SendToTarget(message, sessionID);
    }
}

Unfortunately it isn't working and I get error:

A first chance exception of type 'System.ObjectDisposedException' occurred in System.dll

Same error appears @

RequestForPositions and OrderStatusRequest

On same account in api that uses NetworkStream rather than QuickFix lib it works fine.

Body:
Problem solved.
Forgot to set field TransactTime which counterparty required:

oc.SetField(TransactTime);


问:
Add class to this element outside of parent div with jQuery
I'm trying to target a specific parent of an element and then add a class to it with jQuery. Example:

$('.disable-link').click(function(e) {
  $(this).hide();
  $(this).parents('.item').find('.title').addClass('disabled');

  e.preventDefault();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="item">
  <div class="title">Thing 1</div>
</div>
<div>
  Click to Disable Thing 1
</div>
<div class="item">
  <div class="title">Thing 2</div>
</div>
<div>
  Click to Disable Thing 2
</div>
<div class="item">
  <div class="title">Thing 3</div>
</div>
<div>
  Click to Disable Thing 3
</div></code>```

I thought that by using .parents('.item') it would go all the way up the chain to that specific item class with this and target that specific one, but for some reason it's not.

I've tried using parent().parent().find('.title') but that ends up adding the disabled class to all of the titles and not just the one.
I have a feeling that it something simple, but I can't wrap my head around the specific inheritance.

答:
The elements with class .item are not a parents of .disable-link elements so you should target the parent div first then get the previous .item using the .prev() method like:

```<code>$('.disable-link').click(function(e) {
    $(this).hide();
    $(this).parents('div').prev('.item').find('.title').addClass('disabled');

    e.preventDefault();
});
</code>```

Hope this helps.

$('.disable-link').click(function(e) {
  e.preventDefault();

  $(this).hide();
  $(this).parents('div').prev('.item').find('.title').addClass('disabled');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.disabled{
   background-color: grey;
}</code>```

Thing 1

  Click to Disable Thing 1

Thing 2

  Click to Disable Thing 2

Thing 3

  Click to Disable Thing 3

```

Body:
I'm trying to target a specific parent of an element and then add a class to it with jQuery. Example:

$('.disable-link').click(function(e) {
  $(this).hide();
  $(this).parents('.item').find('.title').addClass('disabled');

  e.preventDefault();
});

Thing 1

  Click to Disable Thing 1

Thing 2

  Click to Disable Thing 2

Thing 3

  Click to Disable Thing 3

I thought that by using .parents('.item') it would go all the way up the chain to that specific item class with this and target that specific one, but for some reason it's not.

I've tried using parent().parent().find('.title') but that ends up adding the disabled class to all of the titles and not just the one.
I have a feeling that it something simple, but I can't wrap my head around the specific inheritance.

Body:
The elements with class .item are not a parents of .disable-link elements so you should target the parent div first then get the previous .item using the .prev() method like:

$('.disable-link').click(function(e) {
    $(this).hide();
    $(this).parents('div').prev('.item').find('.title').addClass('disabled');

    e.preventDefault();
});

Hope this helps.

$('.disable-link').click(function(e) {
  e.preventDefault();

  $(this).hide();
  $(this).parents('div').prev('.item').find('.title').addClass('disabled');
});

.disabled{
   background-color: grey;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="item">
  <div class="title">Thing 1</div>
</div>
<div>
  <a class="disable-link" href="#">Click to Disable Thing 1</a>
</div>
<div class="item">
  <div class="title">Thing 2</div>
</div>
<div>
  <a class="disable-link" href="#">Click to Disable Thing 2</a>
</div>
<div class="item">
  <div class="title">Thing 3</div>
</div>
<div>
  <a class="disable-link" href="#">Click to Disable Thing 3</a>
</div>


问:
Why is this Objective-C code leaking memory?
Why does this leak?

The arrayOfPerformances is a NSMutableArray, (nonatomic, retain) property that is synthesized.

The currentPerformanceObject is a Performance *, (nonatomic, retain) property that is synthesized.

Performance is a custom class

```<code>if(self.arrayOfPerformances == nil)
    {
        self.arrayOfPerformances = [[NSMutableArray alloc]init];
    }

    [self.arrayOfPerformances addObject:currentPerformanceObject];
    [currentPerformanceObject release];
    currentPerformanceObject = nil;
</code>```

答:
This line is the culprit:

```<code>self.arrayOfPerformances = [[NSMutableArray alloc]init];
</code>```

The retain count is 1 after the alloc/init.  Setting the value via the arrayOfPerformances property setter increments the retain count again (because it's a retain property).

ContentLicense: CC BY-SA 2.5

Body:
Why does this leak?

The arrayOfPerformances is a NSMutableArray, (nonatomic, retain) property that is synthesized.

The currentPerformanceObject is a Performance *, (nonatomic, retain) property that is synthesized.

Performance is a custom class

if(self.arrayOfPerformances == nil)
    {
        self.arrayOfPerformances = [[NSMutableArray alloc]init];
    }

    [self.arrayOfPerformances addObject:currentPerformanceObject];
    [currentPerformanceObject release];
    currentPerformanceObject = nil;

Body:
This line is the culprit:

self.arrayOfPerformances = [[NSMutableArray alloc]init];

The retain count is 1 after the alloc/init.  Setting the value via the arrayOfPerformances property setter increments the retain count again (because it's a retain property).


问:
Command echo executes before read
I wrote this code:
   read NAME | echo "$NAME"
Unexpectedly, command echo executes before read, in this case it shows an empty line and then waits for me to enter the text. Does anyone know what to do if I want read to execute first?

答:
Bash, in a way, interprets your entire line of code all at once - it isn't as linear as it appears. The way you have it with | , you are telling bash to send the output of 'read' to be the input of 'echo'. Because 'read' has no output and echo has no input, bash does the following:

send output ' ' to echo

echo ' '

wait for input

Based on your description, I gather you may want something more like:

```<code>read NAME ; echo "$NAME"
</code>```

The ; is like saying first command "and then" second command. $ read foo ; echo $foo is the same as:

```<code>$ read foo
$ echo $foo
</code>```

Similarly, as pointed out by Hunter McMillen and iamauser, && essentially will get the same results. &&, however, tells bash to execute the command following only if the command preceding was successful, while ; is unconditional - it will execute regardless of the success of the preceding command. Another conditional way to do it is with ||, which is like an "or" statement meaning the command following will execute only if the preceding command is UN-successful.

Title: Command echo executes before read

Body:
Bash, in a way, interprets your entire line of code all at once - it isn't as linear as it appears. The way you have it with | , you are telling bash to send the output of 'read' to be the input of 'echo'. Because 'read' has no output and echo has no input, bash does the following:

send output ' ' to echo

echo ' '

wait for input

Based on your description, I gather you may want something more like:

read NAME ; echo "$NAME"

The ; is like saying first command "and then" second command. $ read foo ; echo $foo is the same as:

$ read foo
$ echo $foo

Similarly, as pointed out by Hunter McMillen and iamauser, && essentially will get the same results. &&, however, tells bash to execute the command following only if the command preceding was successful, while ; is unconditional - it will execute regardless of the success of the preceding command. Another conditional way to do it is with ||, which is like an "or" statement meaning the command following will execute only if the preceding command is UN-successful.


问:
Named placeholders in string formatting
In Python, when formatting string, I can fill placeholders by name rather than by position, like that:

```<code>print "There's an incorrect value '%(value)s' in column # %(column)d" % \
  { 'value': x, 'column': y }
</code>```

I wonder if that is possible in Java (hopefully, without external libraries)?

答:
I am the author of a small library that does exactly what you want:

```<code>Student student = new Student("Andrei", 30, "Male");

String studStr = template("#{id}\tName: #{st.getName}, Age: #{st.getAge}, Gender: #{st.getGender}")
                    .arg("id", 10)
                    .arg("st", student)
                    .format();
System.out.println(studStr);
</code>```

Or you can chain the arguments:

```<code>String result = template("#{x} + #{y} = #{z}")
                    .args("x", 5, "y", 10, "z", 15)
                    .format();
System.out.println(result);

// Output: "5 + 10 = 15"
</code>```

Title: Named placeholders in string formatting

Body:
In Python, when formatting string, I can fill placeholders by name rather than by position, like that:

print "There's an incorrect value '%(value)s' in column # %(column)d" % \
  { 'value': x, 'column': y }

I wonder if that is possible in Java (hopefully, without external libraries)?

Body:
I am the author of a small library that does exactly what you want:

Student student = new Student("Andrei", 30, "Male");

String studStr = template("#{id}\tName: #{st.getName}, Age: #{st.getAge}, Gender: #{st.getGender}")
                    .arg("id", 10)
                    .arg("st", student)
                    .format();
System.out.println(studStr);

Or you can chain the arguments:

String result = template("#{x} + #{y} = #{z}")
                    .args("x", 5, "y", 10, "z", 15)
                    .format();
System.out.println(result);

// Output: "5 + 10 = 15"


答:
Git undoubtedly is faster, but 30 seconds for SHA-1 is not so great.

So I ran a test in java:

```<code>public static void main(String[] args) throws Exception{
    long startTime = System.currentTimeMillis();

    byte[] bytes = createSha1(new File("src\\main\\resources\\200mb_file.zip"));
    System.out.println(new String(bytes));

    long endTime = System.currentTimeMillis();
    long duration = (endTime - startTime);
    System.out.format("Duration: %dms\n", duration);
}

private static byte[] createSha1(File file) throws Exception  {
    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    InputStream fis = new FileInputStream(file);
    int n = 0;
    byte[] buffer = new byte[8192];
    while (n != -1) {
        n = fis.read(buffer);
        if (n > 0) {
            digest.update(buffer, 0, n);
        }
    }
    return digest.digest();
}
</code>```

Output:

```<code>Duration: 1531
</code>```

My guess what is causing your slowness is the fact you are inputting it to a list rather the directly using it as a stream.

Title: How does Git compute SHA hashes so quickly?

Body:
Git undoubtedly is faster, but 30 seconds for SHA-1 is not so great.

So I ran a test in java:

public static void main(String[] args) throws Exception{
    long startTime = System.currentTimeMillis();

    byte[] bytes = createSha1(new File("src\\main\\resources\\200mb_file.zip"));
    System.out.println(new String(bytes));

    long endTime = System.currentTimeMillis();
    long duration = (endTime - startTime);
    System.out.format("Duration: %dms\n", duration);
}

private static byte[] createSha1(File file) throws Exception  {
    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    InputStream fis = new FileInputStream(file);
    int n = 0;
    byte[] buffer = new byte[8192];
    while (n != -1) {
        n = fis.read(buffer);
        if (n > 0) {
            digest.update(buffer, 0, n);
        }
    }
    return digest.digest();
}

Output:

Duration: 1531

My guess what is causing your slowness is the fact you are inputting it to a list rather the directly using it as a stream.


问:
Created nuget package's dll can not be accessable from package's loaded project
I want to create a nuget package of my .net core class library.

I copied the nuget.exe file to the root folder of my Solution

Run nuget spec and Solution.nuspec file created. I modified it as below:

```<code><?xml version="1.0"?>
<package >
<metadata>
<id>Solution</id>
<version>1.0.0</version>
<authors>cc Team</authors>
<owners>cc</owners>
<licenseUrl></licenseUrl>
<projectUrl></projectUrl>
<iconUrl></iconUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description></description>
<releaseNotes></releaseNotes>
<copyright>Copyright 2017</copyright>
<tags>c# .net</tags>
<dependencies>
    <dependency id="NETStandard.Library" version="1.6.1" />
</dependencies>
<references>
    <reference file="Solution.dll" />
</references>
</metadata>
<files>
<file src="Solution.dll" target="lib\netstandard1.6\Solution.dll"/>
</code>```

file's node src value outpupath of my solution. (bin\Release\netstandard1.6\Solution.dll)

Run nuget pack Solution.nuspec and  Solution.nupkg file created.

I put it to my package source.

Create a new .net core class library and select my Solution nuget package from local package source. It added to my project. There is no error or warning. But When I try to access a class from my Solution nuget package, it couldn't be found.I dowloaded  'Nuget Package Explorer' and opened my Solution.nupkg. Icould see Solution.dll and Solution.pdb file under lib --> netstandart1.6.

Then I searched about the error and found this :

```<code>"scripts": {
"postcompile": [
  "dotnet pack --no-build --configuration %compile:Configuration%"
]
}
</code>```

After compile my Solution project it creates Solution.1.0.0-0.nupkg file and Solution.1.0.0-0.symbols. I put it to my local package source but these packages are not listed in the 'Nuget Package Manager'.

Do you have any idea?

答: My experience is creating package from solution sometimes crappy. Creating the package from the project file could solve the problem.</p>

Body:
I want to create a nuget package of my .net core class library.

I copied the nuget.exe file to the root folder of my Solution

Run nuget spec and Solution.nuspec file created. I modified it as below:

<?xml version="1.0"?>
<package >
<metadata>
<id>Solution</id>
<version>1.0.0</version>
<authors>cc Team</authors>
<owners>cc</owners>
<licenseUrl></licenseUrl>
<projectUrl></projectUrl>
<iconUrl></iconUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description></description>
<releaseNotes></releaseNotes>
<copyright>Copyright 2017</copyright>
<tags>c# .net</tags>
<dependencies>
    <dependency id="NETStandard.Library" version="1.6.1" />
</dependencies>
<references>
    <reference file="Solution.dll" />
</references>
</metadata>
<files>
<file src="Solution.dll" target="lib\netstandard1.6\Solution.dll"/>

file's node src value outpupath of my solution. (bin\Release\netstandard1.6\Solution.dll)

Run nuget pack Solution.nuspec and  Solution.nupkg file created.

I put it to my package source.

Create a new .net core class library and select my Solution nuget package from local package source. It added to my project. There is no error or warning. But When I try to access a class from my Solution nuget package, it couldn't be found.I dowloaded  'Nuget Package Explorer' and opened my Solution.nupkg. Icould see Solution.dll and Solution.pdb file under lib --> netstandart1.6.

Then I searched about the error and found this :

"scripts": {
"postcompile": [
  "dotnet pack --no-build --configuration %compile:Configuration%"
]
}

After compile my Solution project it creates Solution.1.0.0-0.nupkg file and Solution.1.0.0-0.symbols. I put it to my local package source but these packages are not listed in the 'Nuget Package Manager'.

Do you have any idea?