问:
JQuery validate + Gravity form conflict?
As Gravity form doesn't have a client side validatation, I'm using JQuery Validate plugin. But the form is not submitting even if the form is properly filled.

Working :

Filling all the fields before clicking on the submit button THEN click on the submit button -> The form is sending

No Working:

Triggering the client side validation by clicking on the submit button with empty fields -> the validation is triggered -> fill the missing fields THEN click again on the submit button -> Strictly nothing happens.

So what I understand is that when the validation has been triggered once it will prevent the form sending EVEN if the form is properly filled later. Someone says the submitHandler is not needed (Gravity Form is not submitting after client side validations), I've also checked other posts without success.

I have then remove the submitHandler, but the form is still not submitting.

-Code with submitHandler :

```<code>if($(".contact-form").length){

    $(".contact-form").validate({
    rules: {
        input_5: {
            required: true,
        },
        input_2: {
            required: true,
            email: true
        },
        input_3: {
            required: true,
        },
        input_4: {
            required: true,
        },
    },
    messages: {
        input_5: 'Please enter your name',
        input_2: {
            required: 'Please enter your Email address',
            email: 'Please enter a valid Email address'
        },
        input_3: 'Please enter your Telephone Number',
        input_4: 'Please enter your Message',
    },
    submitHandler: function(form) {
        if ($(form).valid())
           {
               form.submit();
           }
        return true;
    },

    });

};
</code>```

-Code without submitHandler :

```<code>if($(".contact-form").length){

    $(".contact-form").validate({
        rules: {
            input_5: {
                required: true,
            },
            input_2: {
                required: true,
                email: true
            },
            input_3: {
                required: true,
            },
            input_4: {
                required: true,
            },
        },
        messages: {
            input_5: 'Please enter your name',
            input_2: {
                required: 'Please enter your Email address',
                email: 'Please enter a valid Email address'
            },
            input_3: 'Please enter your Telephone Number',
            input_4: 'Please enter your Message',
        },

    });

};
</code>```

Both code are preventing the form to be sent.

Thank you.

//// Edit

I have the feeling that it's because all the s*** added to the submit button created by Gravity form :

```<code><input type="submit" id="gform_submit_button_1" class="gform_button button" value="Send" tabindex="5" onclick="if(window["gf_submitting_1"]){return false;}  window["gf_submitting_1"]=true;  " onkeypress="if( event.keyCode == 13 ){ if(window["gf_submitting_1"]){return false;} window["gf_submitting_1"]=true;  jQuery("#gform_1").trigger("submit",[true]); }">
</code>```

Because if I submit the form through the console it's working.

Here is the form generated by Gravity Form :

```<code><div class="gf_browser_chrome gform_wrapper contact-form_wrapper container_wrapper" id="gform_wrapper_1">
    <form method="post" enctype="multipart/form-data" id="gform_1" class="contact-form container" action="/contact/" novalidate="novalidate">
        <div class="gform_heading">
            <h3 class="gform_title">Contact Form</h3>
            <span class="gform_description">Contact Form</span>
        </div>
        <div class="gform_body">
            <ul id="gform_fields_1" class="gform_fields top_label form_sublabel_below description_below">
                <li id="field_1_5" class="gfield form__single-input gfield_contains_required field_sublabel_below field_description_below gfield_visibility_visible">
                    <label class="gfield_label" for="input_1_5">Name<span class="gfield_required">*</span></label>
                    <div class="ginput_container ginput_container_text">
                        <input name="input_5" id="input_1_5" type="text" value="" class="medium" tabindex="1" placeholder="Name*" aria-required="true" aria-invalid="false">
                    </div>
                </li>
                <li id="field_1_2" class="gfield form__single-input gfield_contains_required field_sublabel_below field_description_below gfield_visibility_visible">
                    <label class="gfield_label" for="input_1_2">Email<span class="gfield_required">*</span></label>
                    <div class="ginput_container ginput_container_email">
                        <input name="input_2" id="input_1_2" type="text" value="" class="medium" tabindex="2" placeholder="Email*" aria-required="true" aria-invalid="false">
                    </div>
                </li>
                <li id="field_1_3" class="gfield form__single-input gfield_contains_required field_sublabel_below field_description_below gfield_visibility_visible">
                    <label class="gfield_label" for="input_1_3">Telephone Number<span class="gfield_required">*</span></label>
                    <div class="ginput_container ginput_container_text">
                        <input name="input_3" id="input_1_3" type="text" value="" class="medium" tabindex="3" placeholder="Telephone Number*" aria-required="true" aria-invalid="false">
                    </div>
                </li>
                <li id="field_1_4" class="gfield form__textarea gfield_contains_required field_sublabel_below field_description_below gfield_visibility_visible">
                    <label class="gfield_label" for="input_1_4">Message<span class="gfield_required">*</span></label>
                    <div class="ginput_container ginput_container_textarea"><textarea name="input_4" id="input_1_4" class="textarea medium" tabindex="4" placeholder="Message*" aria-required="true" aria-invalid="false" rows="10" cols="50"></textarea>
                    </div>
                </li>
                <li id="field_1_6" class="gfield gform_validation_container field_sublabel_below field_description_below gfield_visibility_"><label class="gfield_label" for="input_1_6">Phone</label>
                    <div class="ginput_container"><input name="input_6" id="input_1_6" type="text" value=""></div>
                    <div class="gfield_description">This field is for validation purposes and should be left unchanged.</div>
                </li>
            </ul>
        </div>
        <div class='gform_footer top_label'>

            <input type='submit' id='gform_submit_button_1' class='gform_button button' value='Send' tabindex='5' onclick='if(window["gf_submitting_1"]){return false;}  window["gf_submitting_1"]=true;  ' onkeypress='if( event.keyCode == 13 ){ if(window["gf_submitting_1"]){return false;} window["gf_submitting_1"]=true;  jQuery("#gform_1").trigger("submit",[true]); }' />
            <input type='hidden' class='gform_hidden' name='is_submit_1' value='1' />
            <input type='hidden' class='gform_hidden' name='gform_submit' value='1' />

            <input type='hidden' class='gform_hidden' name='gform_unique_id' value='' />
            <input type='hidden' class='gform_hidden' name='state_1' value='WyJbXSIsIjA3ZWZlNTFlNzIwYTFjNDVjNGEzMjExMmZjMTIxMDQ2Il0=' />
            <input type='hidden' class='gform_hidden' name='gform_target_page_number_1' id='gform_target_page_number_1' value='0' />
            <input type='hidden' class='gform_hidden' name='gform_source_page_number_1' id='gform_source_page_number_1' value='1' />
            <input type='hidden' name='gform_field_values' value='' />

        </div>
    </form>
</div>
</code>```

答:
Sparky I'm going to explain you why I shown the 2 codes (with submit handler and without submit handler), but first, please stop to answer questions you haven't read entirely.

To be clear (even if it was already clear before) : The validation is working so copy/pasting the code I gave you in a JSFiddle won't help me (your fiddle doesn't send the form either), obviously it's working, and the validation is also working for me, the problem I have is that the form is not sending after the validation, You have totally removed the "Gravity Form/Wordpress" from the problem, thus your answer is not only incomplete, but you are answering to a question I haven't ask. Unless you install a local version of wordpress, install gravity form, create the same form with gravity, and test it, you won't be able to have the same result as me. NO console error and YES jQuery and jQuery validate plugin are linked.

So now, why I tried with the submit handler? As the implicit "submit" after the validation doesn't work, I was expecting that the explicit way (with the submit handler) would work. Unfortunatly it doesn't, and the reason I shown the 2 versions is to avoid people answering : "try with submit handler".

The first question is : Do someone has the same issue with JQuery validate AND Gravity Form AND Gravity Form AND Gravity form?

By the way I found a workaround, dirty workaround, redundant workaround but it's working in my case :

```<code>var $form = $(".contact-form");

$form.validate({
    rules: {
        input_5: {
            required: true,
        },
        input_2: {
            required: true,
            email: true
        },
        input_3: {
            required: true,
        },
        input_4: {
            required: true,
        },
    },
    messages: {
        input_5: 'Please enter your name',
        input_2: {
            required: 'Please enter your Email address',
            email: 'Please enter a valid Email address'
        },
        input_3: 'Please enter your Telephone Number',
        input_4: 'Please enter your Message',
    },
});

$form.on('click', function(){
    if($form.valid()){
        $form.submit();
    }
});
</code>```

Thank you.

Body:
As Gravity form doesn't have a client side validatation, I'm using JQuery Validate plugin. But the form is not submitting even if the form is properly filled.

Working :

Filling all the fields before clicking on the submit button THEN click on the submit button -> The form is sending

No Working:

Triggering the client side validation by clicking on the submit button with empty fields -> the validation is triggered -> fill the missing fields THEN click again on the submit button -> Strictly nothing happens.

So what I understand is that when the validation has been triggered once it will prevent the form sending EVEN if the form is properly filled later. Someone says the submitHandler is not needed (Gravity Form is not submitting after client side validations), I've also checked other posts without success.

I have then remove the submitHandler, but the form is still not submitting.

-Code with submitHandler :

if($(".contact-form").length){

    $(".contact-form").validate({
    rules: {
        input_5: {
            required: true,
        },
        input_2: {
            required: true,
            email: true
        },
        input_3: {
            required: true,
        },
        input_4: {
            required: true,
        },
    },
    messages: {
        input_5: 'Please enter your name',
        input_2: {
            required: 'Please enter your Email address',
            email: 'Please enter a valid Email address'
        },
        input_3: 'Please enter your Telephone Number',
        input_4: 'Please enter your Message',
    },
    submitHandler: function(form) {
        if ($(form).valid())
           {
               form.submit();
           }
        return true;
    },

    });

};

-Code without submitHandler :

if($(".contact-form").length){

    $(".contact-form").validate({
        rules: {
            input_5: {
                required: true,
            },
            input_2: {
                required: true,
                email: true
            },
            input_3: {
                required: true,
            },
            input_4: {
                required: true,
            },
        },
        messages: {
            input_5: 'Please enter your name',
            input_2: {
                required: 'Please enter your Email address',
                email: 'Please enter a valid Email address'
            },
            input_3: 'Please enter your Telephone Number',
            input_4: 'Please enter your Message',
        },

    });

};

Both code are preventing the form to be sent.

Thank you.

//// Edit

I have the feeling that it's because all the s*** added to the submit button created by Gravity form :

<input type="submit" id="gform_submit_button_1" class="gform_button button" value="Send" tabindex="5" onclick="if(window["gf_submitting_1"]){return false;}  window["gf_submitting_1"]=true;  " onkeypress="if( event.keyCode == 13 ){ if(window["gf_submitting_1"]){return false;} window["gf_submitting_1"]=true;  jQuery("#gform_1").trigger("submit",[true]); }">

Because if I submit the form through the console it's working.

Here is the form generated by Gravity Form :

    <form method="post" enctype="multipart/form-data" id="gform_1" class="contact-form container" action="/contact/" novalidate="novalidate">

Contact Form

            Contact Form

                    Name*

                        <input name="input_5" id="input_1_5" type="text" value="" class="medium" tabindex="1" placeholder="Name*" aria-required="true" aria-invalid="false">

                    Email*

                        <input name="input_2" id="input_1_2" type="text" value="" class="medium" tabindex="2" placeholder="Email*" aria-required="true" aria-invalid="false">

                    Telephone Number*

                        <input name="input_3" id="input_1_3" type="text" value="" class="medium" tabindex="3" placeholder="Telephone Number*" aria-required="true" aria-invalid="false">

                    Message*

<textarea name="input_4" id="input_1_4" class="textarea medium" tabindex="4" placeholder="Message*" aria-required="true" aria-invalid="false" rows="10" cols="50"></textarea>

Phone

<input name="input_6" id="input_1_6" type="text" value="">

This field is for validation purposes and should be left unchanged.

            <input type='submit' id='gform_submit_button_1' class='gform_button button' value='Send' tabindex='5' onclick='if(window["gf_submitting_1"]){return false;}  window["gf_submitting_1"]=true;  ' onkeypress='if( event.keyCode == 13 ){ if(window["gf_submitting_1"]){return false;} window["gf_submitting_1"]=true;  jQuery("#gform_1").trigger("submit",[true]); }' />
            <input type='hidden' class='gform_hidden' name='is_submit_1' value='1' />
            <input type='hidden' class='gform_hidden' name='gform_submit' value='1' />

            <input type='hidden' class='gform_hidden' name='gform_unique_id' value='' />
            <input type='hidden' class='gform_hidden' name='state_1' value='WyJbXSIsIjA3ZWZlNTFlNzIwYTFjNDVjNGEzMjExMmZjMTIxMDQ2Il0=' />
            <input type='hidden' class='gform_hidden' name='gform_target_page_number_1' id='gform_target_page_number_1' value='0' />
            <input type='hidden' class='gform_hidden' name='gform_source_page_number_1' id='gform_source_page_number_1' value='1' />
            <input type='hidden' name='gform_field_values' value='' />

    </form>

Body:
Sparky I'm going to explain you why I shown the 2 codes (with submit handler and without submit handler), but first, please stop to answer questions you haven't read entirely.

To be clear (even if it was already clear before) : The validation is working so copy/pasting the code I gave you in a JSFiddle won't help me (your fiddle doesn't send the form either), obviously it's working, and the validation is also working for me, the problem I have is that the form is not sending after the validation, You have totally removed the "Gravity Form/Wordpress" from the problem, thus your answer is not only incomplete, but you are answering to a question I haven't ask. Unless you install a local version of wordpress, install gravity form, create the same form with gravity, and test it, you won't be able to have the same result as me. NO console error and YES jQuery and jQuery validate plugin are linked.

So now, why I tried with the submit handler? As the implicit "submit" after the validation doesn't work, I was expecting that the explicit way (with the submit handler) would work. Unfortunatly it doesn't, and the reason I shown the 2 versions is to avoid people answering : "try with submit handler".

The first question is : Do someone has the same issue with JQuery validate AND Gravity Form AND Gravity Form AND Gravity form?

By the way I found a workaround, dirty workaround, redundant workaround but it's working in my case :

var $form = $(".contact-form");

$form.validate({
    rules: {
        input_5: {
            required: true,
        },
        input_2: {
            required: true,
            email: true
        },
        input_3: {
            required: true,
        },
        input_4: {
            required: true,
        },
    },
    messages: {
        input_5: 'Please enter your name',
        input_2: {
            required: 'Please enter your Email address',
            email: 'Please enter a valid Email address'
        },
        input_3: 'Please enter your Telephone Number',
        input_4: 'Please enter your Message',
    },
});

$form.on('click', function(){
    if($form.valid()){
        $form.submit();
    }
});

Thank you.


来源: stackexchange

问:
phpmyadmin equivalent for IOS?
Do you know a phpmyadmin equivalent for IOS  (iphone and ipad) ?
I found MySQL Mobile Database Client By Glimpse I/O LLC, but I am not sure if it does the same thing,
or Navicat ?

thank you

答:
Have you tried https://itunes.apple.com/us/app/mysql-querydb-client/id576948046?mt=8 ?

I quote from its description: "The easiest way to view data from your MySQL databases on your iPhone or iPad!"

ContentLicense: CC BY-SA 3.0

Title: phpmyadmin equivalent for IOS?


问:
cocoon in a deeply nested form
I would like to use cocoon with rails 4.0 in a project to implement a deeply nested form. I have a party model, which can be either associated with a person or an organization (not included here for simplicity so party just has its primary key).

Each party should be able to have multiple postal_addresses, telecommunications_numbers and electronic_addresses.

Each of these could be shared between multiple parties

Therefor:

party has many communication_mechanisms :through => party_contact_mechanisms

party_contact_mechanism belongs_to party and belongs_to contact_mechanism

contact_mechanism has_many electronic_addresses, has_many telecommunications_numbers and has_many postal_addresses (only electronic_addresses is included in this example and in the sample aplication.)

(Each instance of contact_mechanism should only have either a single electronic_address, postal_address or telecommunications_number. The has_many relationship was chosen for testing and will be changed later once the nesting works.)

What I want to implement is a nested form, in which I can add multiple contact_mechanisms with as little clicks possible:

So preferably I would have an email link, a postal link and a phone link. So for email I would have a cocoon link to add a dynamic form for electronic_addresses, wrapped inside a form for contact_mechanisms wrapped in a form for party_contact_mechanisms. That way all relations would be setup automatically when submitting the form. When I use that setup (the Email button in parties#new), The following params_hash is submitted, failing to create an electronic_address linked to a contact_mechanims, linked to a party_contact_mechanism. The creation chain breaks at party_contact_mechanims, which get created with a party_id but without a contact_mechanism_id.

```<code>Parameters: {"utf8"=>"✓", "authenticity_token"=>"pyT1zgKlRBJgtBC/LGCNEaOcsPZxlmc5zEO3xd/THlg=", "party"=>{"party_contact_mechanisms_attributes"=>{"1373896051610"=>{"from_date(1i)"=>"2013", "from_date(2i)"=>"7", "from_date(3i)"=>"15", "thru_date(1i)"=>"2013", "thru_date(2i)"=>"7", "thru_date(3i)"=>"15", "contact_mechanisms"=>{"electronic_addresses"=>{"electronic_address_string"=>"juergen.helmers@gmail.com"}}}}}, "commit"=>"Save"}
</code>```

It seems the instances of contact_mechanism and electronic_address do not get build and no values assigned. So I would need a way to insert a form for party_contact_mechanism and instantiate the nested contact_mechanims and electronic_address at the same time.

The second possibility to implement this form is following the cocoon wiki example for belongs_to relations (https://github.com/nathanvda/cocoon/wiki/A-guide-to-doing-nested-model-forms#the-look-up-or-create-belongs_to) and can be tested using the "PCM" button. With this approach one would click first to add a party_contact_mechanism form, then either select an existing contact_mechanism or click again to create a new contact_mechanism.

But the link for adding the nested form for contact_mechanism does not show.

I have a sample application on github for review:

Sample application for this question

Any help on how to best implement this data model is greatly appreciated.

答:
On your link_to_add_association you could use the wrap_object option to build any additional association. If you use fields_for you need a new instance for each of those associations.

For instance, in your case if you want contact_mechanism to appear in the form you must call the helper like this:

```<code># I'm using a helper because code looks messy in the view
def link_to_add_party_contact_mechanism(form)
  wrap_object = proc do |party_contact_mechanism|
    party_contact_mechanism.build_contact_mechanism
    party_contact_mechanism
  end

  link_to_add_association "Add...", form, :party_contact_mechanisms, wrap_object: wrap_object
end
</code>```

Title: cocoon in a deeply nested form

Body:
I would like to use cocoon with rails 4.0 in a project to implement a deeply nested form. I have a party model, which can be either associated with a person or an organization (not included here for simplicity so party just has its primary key).

Each party should be able to have multiple postal_addresses, telecommunications_numbers and electronic_addresses.

Each of these could be shared between multiple parties

Therefor:

party has many communication_mechanisms :through => party_contact_mechanisms

party_contact_mechanism belongs_to party and belongs_to contact_mechanism

contact_mechanism has_many electronic_addresses, has_many telecommunications_numbers and has_many postal_addresses (only electronic_addresses is included in this example and in the sample aplication.)

(Each instance of contact_mechanism should only have either a single electronic_address, postal_address or telecommunications_number. The has_many relationship was chosen for testing and will be changed later once the nesting works.)

What I want to implement is a nested form, in which I can add multiple contact_mechanisms with as little clicks possible:

So preferably I would have an email link, a postal link and a phone link. So for email I would have a cocoon link to add a dynamic form for electronic_addresses, wrapped inside a form for contact_mechanisms wrapped in a form for party_contact_mechanisms. That way all relations would be setup automatically when submitting the form. When I use that setup (the Email button in parties#new), The following params_hash is submitted, failing to create an electronic_address linked to a contact_mechanims, linked to a party_contact_mechanism. The creation chain breaks at party_contact_mechanims, which get created with a party_id but without a contact_mechanism_id.

Parameters: {"utf8"=>"✓", "authenticity_token"=>"pyT1zgKlRBJgtBC/LGCNEaOcsPZxlmc5zEO3xd/THlg=", "party"=>{"party_contact_mechanisms_attributes"=>{"1373896051610"=>{"from_date(1i)"=>"2013", "from_date(2i)"=>"7", "from_date(3i)"=>"15", "thru_date(1i)"=>"2013", "thru_date(2i)"=>"7", "thru_date(3i)"=>"15", "contact_mechanisms"=>{"electronic_addresses"=>{"electronic_address_string"=>"juergen.helmers@gmail.com"}}}}}, "commit"=>"Save"}

It seems the instances of contact_mechanism and electronic_address do not get build and no values assigned. So I would need a way to insert a form for party_contact_mechanism and instantiate the nested contact_mechanims and electronic_address at the same time.

The second possibility to implement this form is following the cocoon wiki example for belongs_to relations (https://github.com/nathanvda/cocoon/wiki/A-guide-to-doing-nested-model-forms#the-look-up-or-create-belongs_to) and can be tested using the "PCM" button. With this approach one would click first to add a party_contact_mechanism form, then either select an existing contact_mechanism or click again to create a new contact_mechanism.

But the link for adding the nested form for contact_mechanism does not show.

I have a sample application on github for review:

Sample application for this question

Any help on how to best implement this data model is greatly appreciated.

Body:
On your link_to_add_association you could use the wrap_object option to build any additional association. If you use fields_for you need a new instance for each of those associations.

For instance, in your case if you want contact_mechanism to appear in the form you must call the helper like this:

# I'm using a helper because code looks messy in the view
def link_to_add_party_contact_mechanism(form)
  wrap_object = proc do |party_contact_mechanism|
    party_contact_mechanism.build_contact_mechanism
    party_contact_mechanism
  end

  link_to_add_association "Add...", form, :party_contact_mechanisms, wrap_object: wrap_object
end


问:
SQL Server: Check Upper Case or Lower Case after certain Character
I have data like 'John is my name; Ram is my name; Adam is my name'.

My rule is such that every first letter that comes after ; should be capital letter.

How do I select all values that satisfy the rule?

答:
Little bit of ugly solution but you can give a try...

```<code>Declare @str nvarchar(max) = 'John is my name; Ram is my name; Adam is my name'

Declare @xml as xml
Set @xml = cast(('<X>'+replace(@str,';' ,'</X><X>')+'</X>') as xml)
Select * from (
    Select RowN = Row_Number() over (order by (SELECT NULL)), LTrim(RTrim(N.value('.', 'nvarchar(MAX)'))) as value FROM @xml.nodes('X') as T(N) -- this is to split if you are using sql server 2016 you can use string_Split
) a
Where unicode(substring(a.[value],1,1)) = unicode(upper(substring(a.[value],1,1)))
</code>```

Idea is to split the string and check with unicode value to see whether it is upper or not

Body:
Little bit of ugly solution but you can give a try...

Declare @str nvarchar(max) = 'John is my name; Ram is my name; Adam is my name'

Declare @xml as xml
Set @xml = cast(('<X>'+replace(@str,';' ,'</X><X>')+'</X>') as xml)
Select * from (
    Select RowN = Row_Number() over (order by (SELECT NULL)), LTrim(RTrim(N.value('.', 'nvarchar(MAX)'))) as value FROM @xml.nodes('X') as T(N) -- this is to split if you are using sql server 2016 you can use string_Split
) a
Where unicode(substring(a.[value],1,1)) = unicode(upper(substring(a.[value],1,1)))

Idea is to split the string and check with unicode value to see whether it is upper or not


问:
how to open a file in javascript with multiple extensions?
I am facing a small issue here...
I want to write a javascript function to open files with different extensions, I have already written a function that can open files but with their extensions hard written in the code, how to make this dynamic? Like Instead of opening "file1.pdf" or "file1.png" I want to store the extension as a variable and open it dynamically.
Here is the code:-

```<code><script>
    function viewCM() {

        var transferID = document.getElementById("theTransferID").value;

        $.get("/Uploads/" + transferID + ".pdf")
            .done(function () {
            // Do something now you know the file exists.
                window.open("/Uploads/" + transferID + ".pdf", '_blank', 'fullscreen=yes');
            }).fail(function () {
            // File doesn't exist - do something else.
                alert("File was not found");
            })

        return true;
    }
</script>
</code>```

The above function works perfectly with any type of extension but I can't manage to know how to make the extension dynamic

Thanks in advance

EDIT: I don't get the file name from the server, The idea is simply that I have an upload button that uploads a file related to a specific "transfer" and I make the name of the uploaded file as transferID.whatever extension then when I want to open the file, I just write the code I posted. so I don't search the server for the file name.

答:
For anyone facing the same issue, I have made a some kind of "naive" workaround to solve this by making multiple JavaScript functions to open various types of files.

It is as simple as : try to read a pdf file, if you can't then call a function that reads a png file etc!!

```<code><script>
    function viewCM() {

        var transferID = document.getElementById("theTransferID").value;

        $.get("/Uploads/" + transferID + ".pdf")
            .done(function () {
            // Do something now you know the file exists.
                window.open("/Uploads/" + transferID + ".pdf", '_blank', 'fullscreen=yes');
            }).fail(function () {
            // File doesn't exist - call the next function.
                viewCMPng();
            })

        return true;
    }

    function viewCMPng() {

        var transferID = document.getElementById("theTransferID").value;

        $.get("/Uploads/" + transferID + ".png")
            .done(function () {
            // Do something now you know the file exists.
                window.open("/Uploads/" + transferID + ".png", '_blank', 'fullscreen=yes');
            }).fail(function () {
            // File doesn't exist - show alert message.
                alert("File was not found");
            })

        return true;
    }

</script>
</code>```

Body:
I am facing a small issue here...
I want to write a javascript function to open files with different extensions, I have already written a function that can open files but with their extensions hard written in the code, how to make this dynamic? Like Instead of opening "file1.pdf" or "file1.png" I want to store the extension as a variable and open it dynamically.
Here is the code:-

The above function works perfectly with any type of extension but I can't manage to know how to make the extension dynamic

Thanks in advance

EDIT: I don't get the file name from the server, The idea is simply that I have an upload button that uploads a file related to a specific "transfer" and I make the name of the uploaded file as transferID.whatever extension then when I want to open the file, I just write the code I posted. so I don't search the server for the file name.

Body:
For anyone facing the same issue, I have made a some kind of "naive" workaround to solve this by making multiple JavaScript functions to open various types of files.

It is as simple as : try to read a pdf file, if you can't then call a function that reads a png file etc!!

<script>
    function viewCM() {

        var transferID = document.getElementById("theTransferID").value;

        $.get("/Uploads/" + transferID + ".pdf")
            .done(function () {
            // Do something now you know the file exists.
                window.open("/Uploads/" + transferID + ".pdf", '_blank', 'fullscreen=yes');
            }).fail(function () {
            // File doesn't exist - call the next function.
                viewCMPng();
            })

        return true;
    }

    function viewCMPng() {

        var transferID = document.getElementById("theTransferID").value;

        $.get("/Uploads/" + transferID + ".png")
            .done(function () {
            // Do something now you know the file exists.
                window.open("/Uploads/" + transferID + ".png", '_blank', 'fullscreen=yes');
            }).fail(function () {
            // File doesn't exist - show alert message.
                alert("File was not found");
            })

        return true;
    }

</script>


问:
( AngularJS + Passport ) User authentication
I am new to Passport and I send email and password as {"email":"gg@gmail.com","password":"xxx"} as request body to the server.On server side,I make use of passportJS as in https://github.com/jaredhanson/passport-local#available-options like,

```<code>   passport.use(new LocalStrategy(
    {usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true
  },
    function(req,username,password,done){
      console.log("am here");
      var x=req.body;
      var email=x.email;
      var password=x.password;
      console.log(x.email);

}
))

app.post('/loginUser',passport.authenticate('local'),function(req,res){
   var x=req.body;
   db.users.findOne({"email":x.email,"password":x.password},function(err,user){
     res.json(user)
   })

 });
</code>```

The Local Strategy isn't getting accessed.The application crashes and I only get TypeError: LocalStrategy requires a verify callback. Please let me know where i went wrong

答:
The LocalStrategy includes optional options where you specify the parameters in the POST body passed to the server (the default parameters looked for are username and password).

Just specify your parameters you're passing in your POST body here, as provided in the documentation: https://github.com/jaredhanson/passport-local#available-options

Body:
I am new to Passport and I send email and password as {"email":"gg@gmail.com","password":"xxx"} as request body to the server.On server side,I make use of passportJS as in https://github.com/jaredhanson/passport-local#available-options like,

   passport.use(new LocalStrategy(
    {usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true
  },
    function(req,username,password,done){
      console.log("am here");
      var x=req.body;
      var email=x.email;
      var password=x.password;
      console.log(x.email);

}
))

app.post('/loginUser',passport.authenticate('local'),function(req,res){
   var x=req.body;
   db.users.findOne({"email":x.email,"password":x.password},function(err,user){
     res.json(user)
   })

 });

The Local Strategy isn't getting accessed.The application crashes and I only get TypeError: LocalStrategy requires a verify callback. Please let me know where i went wrong


问:
Android prevent restoring the activity
I have a viewpager holding many fragments. When the activity is sent to background and when resources are needed, the OS will kill the app or at least some fragments. When I return to the activity it crashes because the activity tries to attach new instances of all fragments it held before the clean-up and now some fields are null. This of course could be fixed by properly implementing state saving and restoring using Bundles, but I don't want to do that.
Instead I want to prevent restoring the fragments. Is there a way to tell the OS that once it has sent the GC in and destroyed fragments, it shouldn't bother recreating them at all? Once the cleaning-up happens, I want the activity to be simply recreated on return, as if a user launched it by taping the icon. Any chance of doing that?

The proposed solution here https://stackoverflow.com/a/15683289/552735 does not work. It causes exceptions
java.lang.IllegalStateException: Fragement no longer exists for key f2: index 3

答:
You can't disable the save/restore instance state actions. In case you don't want to actually implement this logic, you have to reload the form especially if your form heavily loaded with fragments.   </p>

```<code>@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
     startActivity(new Intent(this,YOUR_ACTIVITY.class));
     finish();
}
</code>```

Title: Android prevent restoring the activity

Body:
You can't disable the save/restore instance state actions. In case you don't want to actually implement this logic, you have to reload the form especially if your form heavily loaded with fragments.

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
     startActivity(new Intent(this,YOUR_ACTIVITY.class));
     finish();
}


问:
How to set MongoDB driver on XAMPP
I try to set MongoDB on XAMPP, but don't work :(

I use

Windows 10,

XAMPP v3.2.1

PHP 5.6.8

Which driver I need to download? Thanks to all!! :)

XAMPP INFO: http://oi62.tinypic.com/294qk4k.jpg

答:
I am not sure, if you still need another answer but I guess, I had a similar problem.

I've downloaded the right php_mongodb.dll for my configuration (xampp with PHP 5.6.24, MSVC11, x86 and thread safety enabled) and tried to set up the configuration many times without any changes.

So, I've tried a new php version (xampp with PHP 7.0.18, MSVC14, x86 and thread safety enabled) and I've got all what I've wanted in 5 mins.

Title: How to set MongoDB driver on XAMPP


问:
Why are these templates ambiguous?
The book C++ Templates : The Complete Guide has an example on page 275 that I'm having trouble wrapping my head around.

Quoting excerpts from the book...

```<code>template <typename T>
class Promotion<T,T> {
  public:
    typdef T ResultT;
};

template<typename T1, typename T2>
class Promotion<Array<T1>, Array<T2> > {
  public:
    typedef Array<typename Promotion<T1,T2>::ResultT> ResultT;
};

template<typename T>
class Promotion<Array<T>, Array<T> > {
  public:
    typedef Array<typename Promotion<T,T>::ResultT> ResultT;
};
</code>```

Unfortunately, the partial specialization Promotion<Array<T1>, Array<T2> > is
  neither more nor less specialized than the partial specialization
  Promotion<T,T>. To avoid template selection ambiguity, the last partial
  specialization was added. It is more specialized than either of the previous
  two partial specializations.

Why are the first two templates ambiguous, and why does the last template solve the ambiguity issue? When I try to apply the rules I either can't figure out how it comes up with an ambiguity, or if I think I have a way for it to happen I don't know why the last template solves the problem.

答: Ambiguity is when the same class can be instantiated from different specializations and compiler can't favor one specialization over the other one, because neither is more specialized. Adding a more specialized version makes compiler to choose that version. This resolves ambiguity, because C++ rules dictate that the most specialized template should be chosen over less specialized templates.</p>

ContentLicense: CC BY-SA 2.5

Title: Why are these templates ambiguous?

Body:
The book C++ Templates : The Complete Guide has an example on page 275 that I'm having trouble wrapping my head around.

Quoting excerpts from the book...

template <typename T>
class Promotion<T,T> {
  public:
    typdef T ResultT;
};

template<typename T1, typename T2>
class Promotion<Array<T1>, Array<T2> > {
  public:
    typedef Array<typename Promotion<T1,T2>::ResultT> ResultT;
};

template<typename T>
class Promotion<Array<T>, Array<T> > {
  public:
    typedef Array<typename Promotion<T,T>::ResultT> ResultT;
};

Unfortunately, the partial specialization Promotion<Array<T1>, Array<T2> > is
  neither more nor less specialized than the partial specialization
  Promotion<T,T>. To avoid template selection ambiguity, the last partial
  specialization was added. It is more specialized than either of the previous
  two partial specializations.

Why are the first two templates ambiguous, and why does the last template solve the ambiguity issue? When I try to apply the rules I either can't figure out how it comes up with an ambiguity, or if I think I have a way for it to happen I don't know why the last template solves the problem.


问:
share arraylsit among request in Spring controller
I used the same ArrayList in 2 webservices in spring controller, so I want to get it once from DB using request or session scope I tried to make a bean

```<code>@WebAppConfiguration
public class exampleBean {
List<user> users = new ArrayList<user>();

@Bean
@Scope(value = "request")
public List<user> getuserList(){
    return users ;
}

@Bean
@Scope(value = "request")
public void setAttendessList(List<user>  userList){
    users = userList;
}
</code>```

}

And in Controller

ApplicationContext ctx = new AnnotationConfigApplicationContext(exampleBean .class);
    AttendeesBean attendeeBean = ctx.getBean(exampleBean .class);

and in first service I set the list, but didn't find it in second service.

答:
I just changed @Scope(value ="request") to
@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)

using @AmtiK advice and with some searching.

And it worked

Body:
I used the same ArrayList in 2 webservices in spring controller, so I want to get it once from DB using request or session scope I tried to make a bean

@WebAppConfiguration
public class exampleBean {
List<user> users = new ArrayList<user>();

@Bean
@Scope(value = "request")
public List<user> getuserList(){
    return users ;
}

@Bean
@Scope(value = "request")
public void setAttendessList(List<user>  userList){
    users = userList;
}

}

And in Controller

ApplicationContext ctx = new AnnotationConfigApplicationContext(exampleBean .class);
    AttendeesBean attendeeBean = ctx.getBean(exampleBean .class);

and in first service I set the list, but didn't find it in second service.


问:
Android Multiline Snackbar
I'm trying to leverage new Snackbar from Android Design Support Library to display multiline snackbar, as shown in http://www.google.com/design/spec/components/snackbars-toasts.html#snackbars-toasts-specs:

```<code>import android.support.design.widget.Snackbar;

final String snack = "First line\nSecond line\nThird line";
Snackbar.make(mView, snack, Snackbar.LENGTH_LONG).show();
</code>```

It displays only First line... on my Nexus 7. How to make it display all lines?

PS: I tried Toast and it displayed all lines.

答:
this works for me</p>

```<code>Snackbar snackbar =  Snackbar.make(mView, "Your text string", Snackbar.LENGTH_INDEFINITE);
((TextView) snackbar.getView().findViewById(android.support.design.R.id.snackbar_text)).setSingleLine(false);
snackbar.show();
</code>```

Title: Android Multiline Snackbar

Body:
I'm trying to leverage new Snackbar from Android Design Support Library to display multiline snackbar, as shown in http://www.google.com/design/spec/components/snackbars-toasts.html#snackbars-toasts-specs:

import android.support.design.widget.Snackbar;

final String snack = "First line\nSecond line\nThird line";
Snackbar.make(mView, snack, Snackbar.LENGTH_LONG).show();

It displays only First line... on my Nexus 7. How to make it display all lines?

PS: I tried Toast and it displayed all lines.

Body:
this works for me

Snackbar snackbar =  Snackbar.make(mView, "Your text string", Snackbar.LENGTH_INDEFINITE);
((TextView) snackbar.getView().findViewById(android.support.design.R.id.snackbar_text)).setSingleLine(false);
snackbar.show();


问:
Node.js: "process run out of memory"
I have the following code which leads to the error: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

It doesn't make any difference whether I set --max_old_space_size=4096 (or bigger numbers) or not. I have 16 GB RAM on my PC.

System: win10/node.js 6.9.2/mongodb 3.4

I have over 16 000 000 messages in the "chatModel". With a smaller amount of messages the code works.

Do you have any suggestions how to solve the problem/optimize the code?

```<code>function sortOutMessages(){

var atSymbol = "@";
var rgx = new RegExp("^\\" +atSymbol);

chatModel.find({messageContent: rgx}, function (err, doc){

    var docs = doc;
    var docsLength = docs.length;

    for (var i =0; i<docsLength;i++) {
        var directedMessagesObj = new directedMessagesModel
        ({
            timeStamp: docs[i].timeStamp,
            channelName: docs[i].channelName,
            userName: docs[i].userName,
            userID: docs[i].userID,
            messageContent: docs[i].messageContent,
            messageLength: docs[i].messageLength,
            subscriber: docs[i].subscriber,
            turbo: docs[i].turbo,
            moderator: docs[i].moderator
        });

        directedMessagesObj.save({upsert:true}, function (err) {
            var fs = require('fs');
            if (err) {
                    fs.appendFile("undefinedLog.txt", "error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n")
                    loggerWinston.warn("error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n");
                    return console.log(err);
            }

        });
    }

});

}
</code>```

答:
Thank you all for your answers! I decided to go a different way and it works for now:</p>

```<code>var cursor = chatModel.find({messageContent: rgx}).cursor();

cursor.on('data',function (doc) {
    var directedMessagesObj = new directedMessagesModel
            ({
                timeStamp: doc.timeStamp,
                channelName: doc.channelName,
                userName: doc.userName,
                userID: doc.userID,
                messageContent: doc.messageContent,
                messageLength: doc.messageLength,
                subscriber: doc.subscriber,
                turbo: doc.turbo,
                moderator: doc.moderator
            });

    directedMessagesObj.save({upsert:true},function (err) {
        var fs = require('fs');
                    if (err) {
                            fs.appendFile("undefinedLog.txt", "error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n");
                            loggerWinston.warn("error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n");
                            return console.log(err);
                    }
    });
});
</code>```

Title: Node.js: "process run out of memory"

Body:
I have the following code which leads to the error: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

It doesn't make any difference whether I set --max_old_space_size=4096 (or bigger numbers) or not. I have 16 GB RAM on my PC.

System: win10/node.js 6.9.2/mongodb 3.4

I have over 16 000 000 messages in the "chatModel". With a smaller amount of messages the code works.

Do you have any suggestions how to solve the problem/optimize the code?

function sortOutMessages(){

var atSymbol = "@";
var rgx = new RegExp("^\\" +atSymbol);

chatModel.find({messageContent: rgx}, function (err, doc){

    var docs = doc;
    var docsLength = docs.length;

    for (var i =0; i<docsLength;i++) {
        var directedMessagesObj = new directedMessagesModel
        ({
            timeStamp: docs[i].timeStamp,
            channelName: docs[i].channelName,
            userName: docs[i].userName,
            userID: docs[i].userID,
            messageContent: docs[i].messageContent,
            messageLength: docs[i].messageLength,
            subscriber: docs[i].subscriber,
            turbo: docs[i].turbo,
            moderator: docs[i].moderator
        });

        directedMessagesObj.save({upsert:true}, function (err) {
            var fs = require('fs');
            if (err) {
                    fs.appendFile("undefinedLog.txt", "error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n")
                    loggerWinston.warn("error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n");
                    return console.log(err);
            }

        });
    }

});

}

Body:
Thank you all for your answers! I decided to go a different way and it works for now:

var cursor = chatModel.find({messageContent: rgx}).cursor();

cursor.on('data',function (doc) {
    var directedMessagesObj = new directedMessagesModel
            ({
                timeStamp: doc.timeStamp,
                channelName: doc.channelName,
                userName: doc.userName,
                userID: doc.userID,
                messageContent: doc.messageContent,
                messageLength: doc.messageLength,
                subscriber: doc.subscriber,
                turbo: doc.turbo,
                moderator: doc.moderator
            });

    directedMessagesObj.save({upsert:true},function (err) {
        var fs = require('fs');
                    if (err) {
                            fs.appendFile("undefinedLog.txt", "error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n");
                            loggerWinston.warn("error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n");
                            return console.log(err);
                    }
    });
});


问:
XSLT element count
I want to count no of elements under a node , In below XML I has 2 report entries , In first entry I has 4 elements and in 2nd entry I has only 3 address is missing.

I want to count the total elements under each report_entry
count is 4 for first report entry and count is 3 for 2nd report entry

Can some body suggest is it possible ? any sample code ?

example xml:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
    <report_data>
     <report_entry>
    <id>12345</id>
    <fname>Venkata</fname>
    <lname>Penumatsa</lname>
    <address>Hyderabad</address>
       </report_entry>
        <report_entry>
    <id>123453</id>
    <fname>stephen</fname>
    <lname>florida</lname>
      </report_entry>
    </report_data>
</code>```

-- Venkata

答:
Use

```<code><xsl:template match="report_entry">
  <xsl:value-of select="count(*)"/>
</xsl:template>
</code>```

if you "want to count the total elements under each report_entry".

Title: XSLT element count

Body:
I want to count no of elements under a node , In below XML I has 2 report entries , In first entry I has 4 elements and in 2nd entry I has only 3 address is missing.

I want to count the total elements under each report_entry
count is 4 for first report entry and count is 3 for 2nd report entry

Can some body suggest is it possible ? any sample code ?

example xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <report_data>
     <report_entry>
    <id>12345</id>
    <fname>Venkata</fname>
    <lname>Penumatsa</lname>
    <address>Hyderabad</address>
       </report_entry>
        <report_entry>
    <id>123453</id>
    <fname>stephen</fname>
    <lname>florida</lname>
      </report_entry>
    </report_data>

-- Venkata

Body:
Use

<xsl:template match="report_entry">
  <xsl:value-of select="count(*)"/>
</xsl:template>

if you "want to count the total elements under each report_entry".


问:
Creating a link button and an image button in ExtJS?
I want to create a link in ExtJS, but one that is made of button, so, that it contains event handlers (and I don't need to add my own event handlers.)

Also, I would like to create a button that does display a big icon with text like:
ICON
TEXT

so that the icon is not positioned on the left side, but on the top (and is larger than the default 16x16).

答: Perhaps this may help: http://www.sencha.com/forum/showthread.php?54602-Link-Button-or-Hyper-link</p>


问:
Deployment files not updating (BitBucket, OneDrive)
I'm developing a bot using the online editor, to add and remove files I was first using the OneDrive continuous integration then tried using BitBucket.

Using OneDrive adding files seemed to work but recently I wanted to also remove some files. I removed them from my local drive, waited for it to sync up to onedrive (I checked and they had gone from the web view) and then did a sync from the bot console.

The new files were created but the files I had deleted are still in the bot and screwing up the compilation.

More recently I have setup a BitBucket account and created everything there, connected it up etc and deployed to the bot account and it also doesn't change any of the code.

答:
Works for me. Maybe the files were in use and could not be deleted? Check /LogFiles/kudu/traces, look for *_POST_deploy*,

e.g. 2017-06-04T11-07-26_08882b_020_Background_POST_deploy_3s.xml

<step title="Applying 2 changes ..." date="2017-06-04T11:07:27.231" >
    <step title="Deleted file D:\home\site\wwwroot\index2.htm"
     date="2017-06-04T11:07:27.263" />
```


问:
VB Macros in two worksheets that compare 4 fields and then paste a value
I am new to VB so any help you can provide would be great.  I have two worksheets.   They have four fields in common between the two sheets.  The rows will have many more fields that will not match.   if the four fields match then I need to paste two fields into the second sheet.

Although this works it is hardcoded and I have to do this for each line.

I would like to create a double loop and allow the four fields on the row to compare to the second sheet to each row to see if there is a match.  if so it will paste the two fields other wise it will go on to the next row in the first sheet and do the process again.

```<code>If [w2.Range.("b2")] = [w1.Range.("g3")] Then
  If [w2.Range.("c2")] = [w1.Range.("b3")] Then
   If [w2.Range.("d2")] = [w1.Range.("c3")] Then
     w1.Select
     Range("N3:O3").Select
     Selection.Copy
     w2.Select
     Range("G2:H2").Select
     ActiveSheet.Paste
 End If
 End If
 End If
</code>```

Any help would be great.

I got the two sheets worked and basically the comparison.   the only issue I have now is how the loops and incrementing  and not going down to the next row.

```<code>Sub Macro1()
'
' Macro1 Macro
'
Set w1 = Worksheets("DDR_Mar'17")
Set w2 = Worksheets("Release DrillDown")
Dim drea As String
Dim seva As String

SelRow = Selection.Row

'category ITSR on "DDR_Mar'17" sheet
   itsra = w1.Cells(SelRow, 7)
'category Application on "DDR Mar'17" sheet
   appa = w1.Cells(SelRow, 2)
'category SubCategory on "DDR Mar'17" sheet
   scata = w1.Cells(SelRow, 3)
'category DRE on "DDR Mar'17" sheet
   drea = w1.Cells(SelRow, 14)
'category SEV on "DDR Mar'17" sheet
   seva = w1.Cells(SelRow, 15)

lr = w1.Cells(Rows.Count, 1).End(xlUp).Row

SelRow = Selection.Row
'category ITSR on "Release Drilldown" sheet
   itsrb = w2.Cells(SelRow, 2)
'category Application on "Release Drilldown" sheet
   appb = w2.Cells(SelRow, 3)
'category SubCategory on "Release Drilldown" sheet
   scatb = w2.Cells(SelRow, 4)
'category DRE on "Release Drilldown" sheet
   dreb = w2.Cells(SelRow, 7)
'category SEV on "Release Drilldown" sheet
 '  sevb = w2.Cells(SelRow, 8)

lr2 = w2.Cells(Rows.Count, 1).End(xlUp).Row

For x = 1 To lr2
   w2.Cells(x, 1) = x
 For y = 1 To lr
   w1.Cells(y, 1) = y

  If itsra = itsrb Then
    If appa = appb Then
     If scata = scatb Then
          w = w + 1
  End If
  End If
  End If

Next y
Next x

End Sub
</code>```

答:
You can loop through each row testing the values with a for loop

```<code>Dim trange As Range
Set trange = w2.Range("B2:D4") 'Range you're testing
For Each trow In trange.Rows
    If trow.Columns(1) = w1.Range("G3") _
    And trow.Columns(2) = w1.Range("B3") _
    And trow.Columns(3) = w1.Range("C3") Then
        w1.Range("N3:O3").Copy Destination:=trow.Offset(0, 5)
        Exit For
    End If
Next
</code>```

If you're looking to loop through w1 as well, you can set up a second range and nest the for eaches

```<code>For each trow In trange.rows
     For each rrow in rrange.rows
         if trow.column(1) = rrow.column(1) And ect....
</code>```

Body:
I am new to VB so any help you can provide would be great.  I have two worksheets.   They have four fields in common between the two sheets.  The rows will have many more fields that will not match.   if the four fields match then I need to paste two fields into the second sheet.

Although this works it is hardcoded and I have to do this for each line.

I would like to create a double loop and allow the four fields on the row to compare to the second sheet to each row to see if there is a match.  if so it will paste the two fields other wise it will go on to the next row in the first sheet and do the process again.

If [w2.Range.("b2")] = [w1.Range.("g3")] Then
  If [w2.Range.("c2")] = [w1.Range.("b3")] Then
   If [w2.Range.("d2")] = [w1.Range.("c3")] Then
     w1.Select
     Range("N3:O3").Select
     Selection.Copy
     w2.Select
     Range("G2:H2").Select
     ActiveSheet.Paste
 End If
 End If
 End If

Any help would be great.

I got the two sheets worked and basically the comparison.   the only issue I have now is how the loops and incrementing  and not going down to the next row.

Sub Macro1()
'
' Macro1 Macro
'
Set w1 = Worksheets("DDR_Mar'17")
Set w2 = Worksheets("Release DrillDown")
Dim drea As String
Dim seva As String

SelRow = Selection.Row

'category ITSR on "DDR_Mar'17" sheet
   itsra = w1.Cells(SelRow, 7)
'category Application on "DDR Mar'17" sheet
   appa = w1.Cells(SelRow, 2)
'category SubCategory on "DDR Mar'17" sheet
   scata = w1.Cells(SelRow, 3)
'category DRE on "DDR Mar'17" sheet
   drea = w1.Cells(SelRow, 14)
'category SEV on "DDR Mar'17" sheet
   seva = w1.Cells(SelRow, 15)

lr = w1.Cells(Rows.Count, 1).End(xlUp).Row

SelRow = Selection.Row
'category ITSR on "Release Drilldown" sheet
   itsrb = w2.Cells(SelRow, 2)
'category Application on "Release Drilldown" sheet
   appb = w2.Cells(SelRow, 3)
'category SubCategory on "Release Drilldown" sheet
   scatb = w2.Cells(SelRow, 4)
'category DRE on "Release Drilldown" sheet
   dreb = w2.Cells(SelRow, 7)
'category SEV on "Release Drilldown" sheet
 '  sevb = w2.Cells(SelRow, 8)

lr2 = w2.Cells(Rows.Count, 1).End(xlUp).Row

For x = 1 To lr2
   w2.Cells(x, 1) = x
 For y = 1 To lr
   w1.Cells(y, 1) = y

  If itsra = itsrb Then
    If appa = appb Then
     If scata = scatb Then
          w = w + 1
  End If
  End If
  End If

Next y
Next x

End Sub

Body:
You can loop through each row testing the values with a for loop

Dim trange As Range
Set trange = w2.Range("B2:D4") 'Range you're testing
For Each trow In trange.Rows
    If trow.Columns(1) = w1.Range("G3") _
    And trow.Columns(2) = w1.Range("B3") _
    And trow.Columns(3) = w1.Range("C3") Then
        w1.Range("N3:O3").Copy Destination:=trow.Offset(0, 5)
        Exit For
    End If
Next

If you're looking to loop through w1 as well, you can set up a second range and nest the for eaches

For each trow In trange.rows
     For each rrow in rrange.rows
         if trow.column(1) = rrow.column(1) And ect....


答:
I think Select method is not gooo.</p>

```<code>If [w2.Range.("b2")] = [w1.Range.("g3")] Then
  If [w2.Range.("c2")] = [w1.Range.("b3")] Then
        If [w2.Range.("d2")] = [w1.Range.("c3")] Then
            w2.Range("G2:H2").Value = w1.Range("N3:O3").Value
        End If
    End If
 End If
</code>```

Title: VB Macros in two worksheets that compare 4 fields and then paste a value

Body:
I think Select method is not gooo.

If [w2.Range.("b2")] = [w1.Range.("g3")] Then
  If [w2.Range.("c2")] = [w1.Range.("b3")] Then
        If [w2.Range.("d2")] = [w1.Range.("c3")] Then
            w2.Range("G2:H2").Value = w1.Range("N3:O3").Value
        End If
    End If
 End If


问:
C OVERFLOW! number gets negative
i'm trying to multiply 2 integers and I always get a negative number, can somebody help me?
(with this function, i'm trying to make from this string "3924456639" a integer)

here is my code:

```<code>long temp = 0;

fgets(buf, sizeof buf, stdin);

for(int i = 0; i < sizeof buf ;i++){
  if(buf[i] != ' ' && buf[i] != '\n'){
    temp *=  10;// <- gets negative
    temp = temp +  buf[i] - '0';

  }}
</code>```

答:
You need to check what is sizeof(long) on your system, its probably 4.

32 bit long variable will hold max value of 2147483647, if you store bigger value in it it will go in negative range, so you need to declare temp unsigned long

Title: C OVERFLOW! number gets negative

Body:
i'm trying to multiply 2 integers and I always get a negative number, can somebody help me?
(with this function, i'm trying to make from this string "3924456639" a integer)

here is my code:

long temp = 0;

fgets(buf, sizeof buf, stdin);

for(int i = 0; i < sizeof buf ;i++){
  if(buf[i] != ' ' && buf[i] != '\n'){
    temp *=  10;// <- gets negative
    temp = temp +  buf[i] - '0';

  }}


问:
How to determine corner/vertex cells in an arbitrary shape composed of grid cells
I am dealing with polygons composed of square tiles on a 2D grid. A polygon is simply stored as a list of tuples, with each tuple representing the coordinates of a tile. The polygons are always contiguous and have no holes.

What I want to be able to do is determine which of the tiles represent vertices along the border of the polygon, such that later I could trace between each one to produce the polygon's border, or determine the distance between two consecutive vertices to find the length of a side, etc.

Here is an example of a polygon (a 5x4 rectangle with a 3x2 rectangle subtracted from the top left, producing a backward 'L'):

```<code>polygon_tiles = [(3, 0), (4, 0), (3, 1), (4, 1), (0, 2), (1, 2), (2, 2), (3, 2),
    (4, 2), (0, 3), (1, 3), (2, 3), (3, 3), (4, 3)]
</code>```

Ideally the algorithm I am seeking would produce a result that looked like this:

```<code>polygon_verts = [(3, 0), (4, 0), (4, 3), (0, 3), (0, 2), (3, 2)]
</code>```

with the vertices listed in order tracing around the border clockwise.

Just fiddling around with some test cases, this problem seems to be much more complicated than I would have thought, especially in weird circumstances like when a polygon has a 1-tile-wide extrusion (in this case one of the tiles might have to be stored as a vertex twice??).

I'm working in Python, but any insight is appreciated, even if it's in pseudocode.

答:
This problem is a convex hull variation, for which e.g. the gift wrapping algorithm could be applied. The constraints of discrete coordinates and line directions lead to simplifications. Here is some python code that gives the desired answer (Patashu's answer is in the same spirit):</p>

```<code>#!/usr/bin/python

import math

def neighbors(coord):
    for dir in (1,0):
        for delta in (-1,1):
            yield (coord[0]+dir*delta, coord[1]+(1-dir)*delta)

def get_angle(dir1, dir2):
    angle = math.acos(dir1[0] * dir2[0] + dir1[1] * dir2[1])
    cross = dir1[1] * dir2[0] - dir1[0] * dir2[1]
    if cross > 0:
        angle = -angle
    return angle

def trace(p):
    if len(p) <= 1:
        return p

    # start at top left-most point
    pt0 = min(p, key = lambda t: (t[1],t[0]))
    dir = (0,-1)
    pt = pt0
    outline = [pt0]
    while True:
        pt_next = None
        angle_next = 10 # dummy value to be replaced
        dir_next = None

        # find leftmost neighbor
        for n in neighbors(pt):
            if n in p:
                dir2 = (n[0]-pt[0], n[1]-pt[1])
                angle = get_angle(dir, dir2)
                if angle < angle_next:
                    pt_next = n
                    angle_next = angle
                    dir_next = dir2
        if angle_next != 0:
           outline.append(pt_next)
        else:
            # previous point was unnecessary
            outline[-1]=pt_next
        if pt_next == pt0:
            return outline[:-1]
        pt = pt_next
        dir = dir_next

polygon_tiles = [(3, 0), (4, 0), (3, 1), (4, 1), (0, 2), (1, 2), (2, 2), (3, 2),
                 (4, 2), (0, 3), (1, 3), (2, 3), (3, 3), (4, 3)]
outline = trace(polygon_tiles)
print(outline)
</code>```

Body:
I am dealing with polygons composed of square tiles on a 2D grid. A polygon is simply stored as a list of tuples, with each tuple representing the coordinates of a tile. The polygons are always contiguous and have no holes.

What I want to be able to do is determine which of the tiles represent vertices along the border of the polygon, such that later I could trace between each one to produce the polygon's border, or determine the distance between two consecutive vertices to find the length of a side, etc.

Here is an example of a polygon (a 5x4 rectangle with a 3x2 rectangle subtracted from the top left, producing a backward 'L'):

polygon_tiles = [(3, 0), (4, 0), (3, 1), (4, 1), (0, 2), (1, 2), (2, 2), (3, 2),
    (4, 2), (0, 3), (1, 3), (2, 3), (3, 3), (4, 3)]

Ideally the algorithm I am seeking would produce a result that looked like this:

polygon_verts = [(3, 0), (4, 0), (4, 3), (0, 3), (0, 2), (3, 2)]

with the vertices listed in order tracing around the border clockwise.

Just fiddling around with some test cases, this problem seems to be much more complicated than I would have thought, especially in weird circumstances like when a polygon has a 1-tile-wide extrusion (in this case one of the tiles might have to be stored as a vertex twice??).

I'm working in Python, but any insight is appreciated, even if it's in pseudocode.

Body:
This problem is a convex hull variation, for which e.g. the gift wrapping algorithm could be applied. The constraints of discrete coordinates and line directions lead to simplifications. Here is some python code that gives the desired answer (Patashu's answer is in the same spirit):

#!/usr/bin/python

import math

def neighbors(coord):
    for dir in (1,0):
        for delta in (-1,1):
            yield (coord[0]+dir*delta, coord[1]+(1-dir)*delta)

def get_angle(dir1, dir2):
    angle = math.acos(dir1[0] * dir2[0] + dir1[1] * dir2[1])
    cross = dir1[1] * dir2[0] - dir1[0] * dir2[1]
    if cross > 0:
        angle = -angle
    return angle

def trace(p):
    if len(p) <= 1:
        return p

    # start at top left-most point
    pt0 = min(p, key = lambda t: (t[1],t[0]))
    dir = (0,-1)
    pt = pt0
    outline = [pt0]
    while True:
        pt_next = None
        angle_next = 10 # dummy value to be replaced
        dir_next = None

        # find leftmost neighbor
        for n in neighbors(pt):
            if n in p:
                dir2 = (n[0]-pt[0], n[1]-pt[1])
                angle = get_angle(dir, dir2)
                if angle < angle_next:
                    pt_next = n
                    angle_next = angle
                    dir_next = dir2
        if angle_next != 0:
           outline.append(pt_next)
        else:
            # previous point was unnecessary
            outline[-1]=pt_next
        if pt_next == pt0:
            return outline[:-1]
        pt = pt_next
        dir = dir_next

polygon_tiles = [(3, 0), (4, 0), (3, 1), (4, 1), (0, 2), (1, 2), (2, 2), (3, 2),
                 (4, 2), (0, 3), (1, 3), (2, 3), (3, 3), (4, 3)]
outline = trace(polygon_tiles)
print(outline)


问:
Tracing execution with annotations
Is there a way I can tell Java to trace certain functions by marking them with an annotation?  I want to be able to do this:

```<code>class Foo {

    @trace
    int foo(int bar) {
        return bar + 5;
    }
}
</code>```

Then, if tracing is enabled, I get:

** Entering foo(5)

** foo returning: 10

答:
you can do this using spring aop, with @Around annotations

How to implement AOP logging:

add this to applicationContext.xml

```<code> <aop:aspectj-autoproxy/>
  <context:annotation-config/>
  <context:component-scan base-package="com.company.*"/>
</code>```

create the following class in com.company.* package:

```<code>package com.company.*;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Component
@Aspect
public class AOPMethodLogger {

    @Around("bean(*Service)")
    public Object timeMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object retVal = joinPoint.proceed();
        stopWatch.stop();
        if(stopWatch.getTotalTimeMillis() > 35){
            StringBuffer logMessageStringBuffer = new StringBuffer();
            logMessageStringBuffer.append(joinPoint.getTarget().getClass().getName());
            logMessageStringBuffer.append(".");
            logMessageStringBuffer.append(joinPoint.getSignature().getName());
            logMessageStringBuffer.append("(");
            logMessageStringBuffer.append(joinPoint.getArgs());
            logMessageStringBuffer.append(")");
            logMessageStringBuffer.append(" execution time: ");
            logMessageStringBuffer.append(stopWatch.getTotalTimeMillis());
            logMessageStringBuffer.append(" ms");
            System.out.println(logMessageStringBuffer.toString());
        }
        return retVal;
    }

}
</code>```

Title: Tracing execution with annotations

Body:
Is there a way I can tell Java to trace certain functions by marking them with an annotation?  I want to be able to do this:

class Foo {

    @trace
    int foo(int bar) {
        return bar + 5;
    }
}

Then, if tracing is enabled, I get:

** Entering foo(5)

** foo returning: 10

Body:
you can do this using spring aop, with @Around annotations

How to implement AOP logging:

add this to applicationContext.xml

 <aop:aspectj-autoproxy/>
  <context:annotation-config/>
  <context:component-scan base-package="com.company.*"/>

create the following class in com.company.* package:

package com.company.*;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Component
@Aspect
public class AOPMethodLogger {

    @Around("bean(*Service)")
    public Object timeMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object retVal = joinPoint.proceed();
        stopWatch.stop();
        if(stopWatch.getTotalTimeMillis() > 35){
            StringBuffer logMessageStringBuffer = new StringBuffer();
            logMessageStringBuffer.append(joinPoint.getTarget().getClass().getName());
            logMessageStringBuffer.append(".");
            logMessageStringBuffer.append(joinPoint.getSignature().getName());
            logMessageStringBuffer.append("(");
            logMessageStringBuffer.append(joinPoint.getArgs());
            logMessageStringBuffer.append(")");
            logMessageStringBuffer.append(" execution time: ");
            logMessageStringBuffer.append(stopWatch.getTotalTimeMillis());
            logMessageStringBuffer.append(" ms");
            System.out.println(logMessageStringBuffer.toString());
        }
        return retVal;
    }

}


问:
How to share user generated content to Facebook?
Usually I use Firebase Dynamic link to let user share content from my app via SMS or Email.So I generate a link like below for them to do that.

https://appcode.app.goo.gl/?link=http://www.example.com/?post_id=112&apn=com.example.com

Usually after user clicked this link will lead to my app's SinglePostActivity.java and show Post with Id=112.My Content have text,image as well.

But when I integrate Facebook share button with the same link,it not redirect to my apps as usual,but it just a broken link,and Facebook also blocked the link.

Here is how I integrate with Facebook share

```<code>facebookShare = (Button)findViewById(R.id.facebookShare);

facebookShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ShareDialog.canShow(ShareLinkContent.class)) {
                    ShareLinkContent content = new ShareLinkContent.Builder()
                            .setContentUrl(Uri.parse(generateDeepLink(postId)))//this will generate the link above
                            .build();

                    shareDialog.show(content);
                }
            }
        });
</code>```

So my question is,how to let user share the content,and lead user to to my SinglePostActivity.java when they click the link?And I don't have website version for my app currently.

答:
Yes, mine is android only too.  You're basically just adding a custom (protocol) scheme to your manifest that handles when the link of that webpage gets clicked.  Something like, myapp://app.mycompany.com/123.  Facebook native app will then forward to your app I believe.

Here's more info about app links

The issue I have with this is that the data cannot (easily) be dynamic.  It has to exist beforehand - or - you have to dynamically build the head tag that points to the data?  I'm not sure if the head tag can be dynamic....  That's what I'm struggling with at the moment.

Body:
Usually I use Firebase Dynamic link to let user share content from my app via SMS or Email.So I generate a link like below for them to do that.

https://appcode.app.goo.gl/?link=http://www.example.com/?post_id=112&apn=com.example.com

Usually after user clicked this link will lead to my app's SinglePostActivity.java and show Post with Id=112.My Content have text,image as well.

But when I integrate Facebook share button with the same link,it not redirect to my apps as usual,but it just a broken link,and Facebook also blocked the link.

Here is how I integrate with Facebook share

facebookShare = (Button)findViewById(R.id.facebookShare);

facebookShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ShareDialog.canShow(ShareLinkContent.class)) {
                    ShareLinkContent content = new ShareLinkContent.Builder()
                            .setContentUrl(Uri.parse(generateDeepLink(postId)))//this will generate the link above
                            .build();

                    shareDialog.show(content);
                }
            }
        });

So my question is,how to let user share the content,and lead user to to my SinglePostActivity.java when they click the link?And I don't have website version for my app currently.


问:
Inputs on left depends on div
I have two inputs in div

Here is code

                <form>
                  <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                  <input class="form-control" type="text" id="lname" name="lname" placeholder="From" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                </form>

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

<p>But they floating to left because of div</p>

<p>I need them to be like this</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-html lang-html prettyprint-override"><code><div style="width:100%;height:500px;border-style:solid;border-color:#1d69b4;margin-top:25px;">

        <div style="width:100%;height:30%;">
                <form>
                  <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                  <input class="form-control" type="text" id="lname" name="lname" placeholder="From" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                </form>
        </div>
    </div></code>```

But div need to be floating to left, how I can do this?

答:
1)You say container must be 70%,so,Can use Media Queries and change width's Text Box.

2)You use same name ID for Different two Element,this is Wrong.ID Name must be Unique, I change lname to Class name.

.wrapper {
 width:100%;
 height:500px;
 border-style:solid;
 border-color:#1d69b4;
 margin-top:25px;
}

.container {
 float:left;
 width:70%;
 height:100%;
}

.frm {
 width:100%;
 height:30%
}

.lname {
 padding: 12px 20px;
 margin: 8px 0;
 box-sizing: border-box;
        border-radius:50px;
}

@media screen and (max-width: 653px) {
 .lname {
  width: 150px;
 }
}

@media screen and (max-width: 477px) {
 .lname {
  width: 50px;
 }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
    <div class="container">
        <div class="frm">
                <form>
                  <input type="text" class="form-control lname" name="lname" placeholder="Last Name">
                  <input type="text" class="form-control lname" name="lname" placeholder="From">
                </form>
        </div>
    </div>
</div></code>```

Title: Inputs on left depends on div

Body:
I have two inputs in div

Here is code

                <form>
                  <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                  <input class="form-control" type="text" id="lname" name="lname" placeholder="From" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                </form>

But they floating to left because of div

I need them to be like this

                <form>
                  <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                  <input class="form-control" type="text" id="lname" name="lname" placeholder="From" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;"/>
                </form>

But div need to be floating to left, how I can do this?

Body:
1)You say container must be 70%,so,Can use Media Queries and change width's Text Box.

2)You use same name ID for Different two Element,this is Wrong.ID Name must be Unique, I change lname to Class name.

.wrapper {
 width:100%;
 height:500px;
 border-style:solid;
 border-color:#1d69b4;
 margin-top:25px;
}

.container {
 float:left;
 width:70%;
 height:100%;
}

.frm {
 width:100%;
 height:30%
}

.lname {
 padding: 12px 20px;
 margin: 8px 0;
 box-sizing: border-box;
        border-radius:50px;
}

@media screen and (max-width: 653px) {
 .lname {
  width: 150px;
 }
}

@media screen and (max-width: 477px) {
 .lname {
  width: 50px;
 }
}

<div class="wrapper">
    <div class="container">
        <div class="frm">
                <form>
                  <input type="text" class="form-control lname" name="lname" placeholder="Last Name">
                  <input type="text" class="form-control lname" name="lname" placeholder="From">
                </form>
        </div>
    </div>
</div>


问:
„no such module“ error for custom framework
The goal:

I want to use a custom framework in order to make certain methods and properties only accessible within the framework, and not by other classes of the app.

What I did:

I followed this tutorial: For testing purposes, I setup a new framework project, copied 1 class from the original project to this new project, and made the initialisers and some other functions public. This framework project builds without errors.

I then removed the copied class from the original project. As expected, it does no longer build and shows „undeclared type“ errors for the removed class.

To add the framework project as a subproject to the original project, I added the framework project’s xcodeproj file, and added the frameworks framework file as an embedded binary to my original project target, which adds it automatically to „Linked Frameworks and Binaries“. Eventually, I the added import MyFramework statements to the relevant 2 files that use the class that was moved to the framework.

The problem:

When I build, the „undeclared type“ errors are now completely gone, but I get „no such module“ errors at the import statements.

This means that the public class and its public functions of the framework are visible to the original project.

But why do I anyway get „no such module“ errors? And what should I do to fix my problem?

PS:

I have read the „no such module“ posts on SO, but none of them seems to address my problem.

EDIT

A friend of mine pointed out that there is a big difference between the cited tutorial app and mine. Sorry that I did not mention this. I was not aware of its relevance:

The tutorial app has a single target, iOS, whereas my app has 2 targets, iOS and watchOS. The class that I moved to my framework is used by both targets.

Since the class that I moved to my framework is used by both targets, the framework needs also the same targets and a build produces two products, one framework for iOS and one framework for watchOS, see my answer below.

答:
If the app uses two targets, say iOS and watchOS, and the framework classes are used by both targets, the framework must also have these two targets, say MyFrameworkIOS and MyFrameworkwatchOS.

If the project is built, the code shared by both targets has now to import the framework that belongs to the compiled target. This can be done by conditionally importing the frameworks like:

```<code>#if os(iOS)
    import MyFrameworkIOS
#else
    import MyFrameworkwatchOS
#endif
</code>```

Body:
If the app uses two targets, say iOS and watchOS, and the framework classes are used by both targets, the framework must also have these two targets, say MyFrameworkIOS and MyFrameworkwatchOS.

If the project is built, the code shared by both targets has now to import the framework that belongs to the compiled target. This can be done by conditionally importing the frameworks like:

#if os(iOS)
    import MyFrameworkIOS
#else
    import MyFrameworkwatchOS
#endif


问:
The trait bound `&str: From<MyType>` is not satisfied even though I implemented `From<&str> for MyType`
I tried to implement run length encoding with the help of From and Into. The idea is I am going to implement only from and get into implementation for free.

```<code>extern crate regex;

use regex::Regex;

struct RLE(pub String);

impl<'a> From<&'a str> for RLE {
    fn from(s: &str) -> Self {
        let reg = Regex::new(r"(\d*)([\w\s])").unwrap();
        let mut accum = String::new();
        for c in reg.captures_iter(s) {
            let n = c.get(1).unwrap().as_str().parse::<usize>().unwrap_or(1);
            let c = c.get(2).unwrap().as_str();
            accum.push_str(&c.repeat(n));
        }
        RLE(accum)
    }
}
</code>```

decode("2ab3c") => "aabccc"

```<code>pub fn decode(s: &str) -> String {
    let RLE(string) = RLE::from(s);
    string
}
</code>```

encode("aabccc") => "2ab3c"

```<code>pub fn encode(s: &str) -> String {
    let string: &'static str = RLE(s.to_string()).into();
    string.to_string()
}
</code>```

But I get the following error:

error[E0277]: the trait bound `&str: std::convert::From<RLE>` is not satisfied
  --> src/main.rs:26:51
   |
26 |     let string: &'static str = RLE(s.to_string()).into();
   |                                                   ^^^^ the trait `std::convert::From<RLE>` is not implemented for `&str`
   |
   = note: required because of the requirements on the impl of `std::convert::Into<&str>` for `RLE`
```

What am I doing wrong?

答:
You've got it backwards.  From<&str> for RLE cannot possibly be used to do an RLE → &str conversion.  That's like using a recipie to bake a cake to deconstruct it back into its constituent ingredients.

From<&str> for RLE implies the existence of Into<RLE> for &str.  It means you can do a_str.into() rather than RLE::from(a_str).  You can work this out by looking at the documentation for Into, which lists the following implementation:

```<code>impl<T, U> Into<U> for T where U: From<T>
</code>```

If you substitute the types for your From implementation (with U = RLE and T = &str), you get:

```<code>impl Into<RLE> for &str where RLE: From<&str>
</code>```

What you're trying to do with REL(s.to_string()).into() would require impl Into<&str> for RLE.

Body:
I tried to implement run length encoding with the help of From and Into. The idea is I am going to implement only from and get into implementation for free.

extern crate regex;

use regex::Regex;

struct RLE(pub String);

impl<'a> From<&'a str> for RLE {
    fn from(s: &str) -> Self {
        let reg = Regex::new(r"(\d*)([\w\s])").unwrap();
        let mut accum = String::new();
        for c in reg.captures_iter(s) {
            let n = c.get(1).unwrap().as_str().parse::<usize>().unwrap_or(1);
            let c = c.get(2).unwrap().as_str();
            accum.push_str(&c.repeat(n));
        }
        RLE(accum)
    }
}

decode("2ab3c") => "aabccc"

pub fn decode(s: &str) -> String {
    let RLE(string) = RLE::from(s);
    string
}

encode("aabccc") => "2ab3c"

pub fn encode(s: &str) -> String {
    let string: &'static str = RLE(s.to_string()).into();
    string.to_string()
}

But I get the following error:

error[E0277]: the trait bound `&str: std::convert::From<RLE>` is not satisfied
  --> src/main.rs:26:51
   |
26 |     let string: &'static str = RLE(s.to_string()).into();
   |                                                   ^^^^ the trait `std::convert::From<RLE>` is not implemented for `&str`
   |
   = note: required because of the requirements on the impl of `std::convert::Into<&str>` for `RLE`

What am I doing wrong?

Body:
You've got it backwards.  From<&str> for RLE cannot possibly be used to do an RLE → &str conversion.  That's like using a recipie to bake a cake to deconstruct it back into its constituent ingredients.

From<&str> for RLE implies the existence of Into<RLE> for &str.  It means you can do a_str.into() rather than RLE::from(a_str).  You can work this out by looking at the documentation for Into, which lists the following implementation:

impl<T, U> Into<U> for T where U: From<T>

If you substitute the types for your From implementation (with U = RLE and T = &str), you get:

impl Into<RLE> for &str where RLE: From<&str>

What you're trying to do with REL(s.to_string()).into() would require impl Into<&str> for RLE.


问:
CreateFile fails with error ERROR_SHARING_VIOLATION
Im using the CreateFile api and some times it randomly fails with the error: ERROR_SHARING_VIOLATION.

I have googled and there is almost nothing about this error. The strange thing is next time it is quite happy to open the same file.

Here is my code:

```<code>void FileHandle::open(const char* fileName, FILE_MODE mode)
{
    if (m_bIsOpen)
        close();

    HANDLE fh = NULL;

    DWORD dwDesiredAccess  = GENERIC_READ;
    DWORD dwShareMode = FILE_SHARE_READ;
    DWORD dwCreationDisposition = OPEN_EXISTING;

    switch (mode)
    {
    case FILE_READ:
        break;

    case FILE_WRITE:
        dwDesiredAccess  = GENERIC_WRITE;
        dwShareMode = 0;
        dwCreationDisposition = CREATE_ALWAYS;
        break;

    case FILE_APPEND:
        dwDesiredAccess  = GENERIC_WRITE;
        dwShareMode = 0;
        dwCreationDisposition = OPEN_ALWAYS;
        break;

    default:
        throw gcException(ERR_INVALID, "The mode was invalid");
        break;
    }

    fh = CreateFile(fileName, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, 0, NULL);

    if (!fh || fh == INVALID_HANDLE_VALUE)
        throw gcException(ERR_INVALIDFILE, GetLastError(), gcString("Failed to open the file {0}", fileName));

    m_hFileHandle = fh;
    m_bIsOpen = true;

    if (mode == FILE_APPEND)
    {
        DWORD high = 0;
        DWORD low = GetFileSize(fh, &high);

        uint64 pos = (((uint64)high)<<32) + (uint64)low;
        seek(pos);
    }
}
</code>```

Am i doing something wrong or is there an issue with the api?

Edit:
Im using the full file name (i.e. C:\somefile.txt) and mode=FILE_WRITE

答:
There is nothing wrong with CreateFile - a sharing violation means that something else has the same file open.  Which could be your own program, if you have the file open with a share mode of 0, you won't be able to open it again.

When you get the error you can use Process Explorer to determine what processes have the file open.

Body:
Im using the CreateFile api and some times it randomly fails with the error: ERROR_SHARING_VIOLATION.

I have googled and there is almost nothing about this error. The strange thing is next time it is quite happy to open the same file.

Here is my code:

void FileHandle::open(const char* fileName, FILE_MODE mode)
{
    if (m_bIsOpen)
        close();

    HANDLE fh = NULL;

    DWORD dwDesiredAccess  = GENERIC_READ;
    DWORD dwShareMode = FILE_SHARE_READ;
    DWORD dwCreationDisposition = OPEN_EXISTING;

    switch (mode)
    {
    case FILE_READ:
        break;

    case FILE_WRITE:
        dwDesiredAccess  = GENERIC_WRITE;
        dwShareMode = 0;
        dwCreationDisposition = CREATE_ALWAYS;
        break;

    case FILE_APPEND:
        dwDesiredAccess  = GENERIC_WRITE;
        dwShareMode = 0;
        dwCreationDisposition = OPEN_ALWAYS;
        break;

    default:
        throw gcException(ERR_INVALID, "The mode was invalid");
        break;
    }

    fh = CreateFile(fileName, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, 0, NULL);

    if (!fh || fh == INVALID_HANDLE_VALUE)
        throw gcException(ERR_INVALIDFILE, GetLastError(), gcString("Failed to open the file {0}", fileName));

    m_hFileHandle = fh;
    m_bIsOpen = true;

    if (mode == FILE_APPEND)
    {
        DWORD high = 0;
        DWORD low = GetFileSize(fh, &high);

        uint64 pos = (((uint64)high)<<32) + (uint64)low;
        seek(pos);
    }
}

Am i doing something wrong or is there an issue with the api?

Edit:
Im using the full file name (i.e. C:\somefile.txt) and mode=FILE_WRITE


问:
SMTP server response: 530 5.7.0 Must issue a STARTTLS command first
SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

I get this error message when i use mail() function in php script file...

I m using gmail SMTP server and gmail using STARTTLS which is secure SSL
and i already use these commands in my contact.php file

```<code>ini_set("SMTP","smtp.gmail.com");
ini_set("sendmail_from","<email-address>@gmail.com>");
</code>```

so what command i can use to enable STARTTLS or configure in php,ini file??

答:
I am going to share my way and it worked for me after implementing following:

Open Php.ini file and fill the all the values in the respective fields by taking ref from Gmail SMTP Settings

Remove comments from the [mail function] Statements which are instructions to the smtp Server and Match their values.

Also the sendmail SMTP server is a Fake server. Its nothing beside a text terminal (Try writing anything on it. :P).
It will use gmail s,tp to send Mails.
So configure it correctly by matching Gmail SMTP settings:

```<code>smtp.gmail.com
Port: 587
</code>```

ContentLicense: CC BY-SA 4.0

Body:
SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

I get this error message when i use mail() function in php script file...

I m using gmail SMTP server and gmail using STARTTLS which is secure SSL
and i already use these commands in my contact.php file

ini_set("SMTP","smtp.gmail.com");
ini_set("sendmail_from","<email-address>@gmail.com>");

so what command i can use to enable STARTTLS or configure in php,ini file??

Body:
I am going to share my way and it worked for me after implementing following:

Open Php.ini file and fill the all the values in the respective fields by taking ref from Gmail SMTP Settings

Remove comments from the [mail function] Statements which are instructions to the smtp Server and Match their values.

Also the sendmail SMTP server is a Fake server. Its nothing beside a text terminal (Try writing anything on it. :P).
It will use gmail s,tp to send Mails.
So configure it correctly by matching Gmail SMTP settings:

smtp.gmail.com
Port: 587


问:
SVG - animate/move dots along path
I'm looking for a way to move dots along existing path in order to get animation that looks like this:

I was thinking about working with dasharray but wasn't able to get this exact behavior.

Here is an example of something I tried, but as you can see it doesn't really work:

path.link {
  stroke-width: 3px;
  stroke-dasharray: 5 5;
  stroke: black;
}
path.link-anim {
  stroke-width: 3px;
  animation: link-anim 5s linear infinite;
}
path.red {
  stroke: red;
}
path.blue {
  stroke: blue;
}
path.green {
  stroke: green;
}
path.pink {
  stroke: pink;
}
@keyframes link-anim {
    0% {
        stroke-dashoffset: 0;
        stroke-dasharray: 5 5 100%;
    }
    100% {
        stroke-dashoffset: 100%;
        stroke-dasharray: 100% 5 5;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg width="450" height="450">
  <g>
    <path class="link" d="M10,10L100,10"></path>
    <path class="link-anim red" d="M10,10L100,10"></path>
  </g>
  <g>
    <path class="link" d="M50,50L200,50"></path>
    <path class="link-anim blue" d="M50,50L200,50"></path>
  </g>
  <g>
    <path class="link" d="M75,75L75,200"></path>
    <path class="link-anim green" d="M75,75L75,200"></path>
  </g>
  <g>
    <path class="link" d="M85,85L450,450"></path>
    <path class="link-anim pink" d="M85,85L450,450"></path>
  </g>
</svg></code>```

Note - the angle of the line is not something I care about. I should have written this from the start. What I need is the 3 dots to move forward (and only those 3 dots).

答:
What you need to do is add a rotate in your path. I also changed some of your settings so you can see the line work:

https://jsfiddle.net/yex8n8nj/

```<code><div>
<svg>
  <g>
    <path class="link" d="M120,0L0,-120" transform='rotate(45)'></path>
    <path class="link-anim blue" d="M120,0L0,-120" transform='rotate(45)' >
 </path>
  </g>
</svg>
</div>

path.link {
  stroke-width: 3px;
  stroke-dasharray: 5 5;
  stroke: black;
}
path.link-anim {
  stroke-width: 3px;
  animation: link-anim 5s linear infinite;
}
path.red {
  stroke: red;
}
path.blue {
  stroke: blue;
}
@keyframes link-anim {
    0% {
        stroke-dashoffset: 0;
        stroke-dasharray: 5 5 100%;
    }
    100% {
        stroke-dashoffset: 100%;
        stroke-dasharray: 100% 5 5;
    }
}
div {
  margin-left: 50px;
  width: 100%;
  text-align: center;
  float: right;
}
</code>```

Title: SVG - animate/move dots along path

Body:
I'm looking for a way to move dots along existing path in order to get animation that looks like this:

I was thinking about working with dasharray but wasn't able to get this exact behavior.

Here is an example of something I tried, but as you can see it doesn't really work:

path.link {
  stroke-width: 3px;
  stroke-dasharray: 5 5;
  stroke: black;
}
path.link-anim {
  stroke-width: 3px;
  animation: link-anim 5s linear infinite;
}
path.red {
  stroke: red;
}
path.blue {
  stroke: blue;
}
path.green {
  stroke: green;
}
path.pink {
  stroke: pink;
}
@keyframes link-anim {
    0% {
        stroke-dashoffset: 0;
        stroke-dasharray: 5 5 100%;
    }
    100% {
        stroke-dashoffset: 100%;
        stroke-dasharray: 100% 5 5;
    }
}

<svg width="450" height="450">
  <g>
    <path class="link" d="M10,10L100,10"></path>
    <path class="link-anim red" d="M10,10L100,10"></path>
  </g>
  <g>
    <path class="link" d="M50,50L200,50"></path>
    <path class="link-anim blue" d="M50,50L200,50"></path>
  </g>
  <g>
    <path class="link" d="M75,75L75,200"></path>
    <path class="link-anim green" d="M75,75L75,200"></path>
  </g>
  <g>
    <path class="link" d="M85,85L450,450"></path>
    <path class="link-anim pink" d="M85,85L450,450"></path>
  </g>
</svg>

Note - the angle of the line is not something I care about. I should have written this from the start. What I need is the 3 dots to move forward (and only those 3 dots).

Body:
What you need to do is add a rotate in your path. I also changed some of your settings so you can see the line work:

https://jsfiddle.net/yex8n8nj/

<div>
<svg>
  <g>
    <path class="link" d="M120,0L0,-120" transform='rotate(45)'></path>
    <path class="link-anim blue" d="M120,0L0,-120" transform='rotate(45)' >
 </path>
  </g>
</svg>
</div>

path.link {
  stroke-width: 3px;
  stroke-dasharray: 5 5;
  stroke: black;
}
path.link-anim {
  stroke-width: 3px;
  animation: link-anim 5s linear infinite;
}
path.red {
  stroke: red;
}
path.blue {
  stroke: blue;
}
@keyframes link-anim {
    0% {
        stroke-dashoffset: 0;
        stroke-dasharray: 5 5 100%;
    }
    100% {
        stroke-dashoffset: 100%;
        stroke-dasharray: 100% 5 5;
    }
}
div {
  margin-left: 50px;
  width: 100%;
  text-align: center;
  float: right;
}