问:
How to select a color, fill it into the selected image that is uploaded in the canvas using fabric.js?
I have this project, and one of the requirement would be customize and design an uploaded image in a canvas
. So with customizing, I will upload an image, select it, and  I want to change or tint the color with the selected color. But I do not know how.

var canvas = new fabric.Canvas('canvas');
        var clearEl = document.getElementById('clear');
        var reset = document.getElementById('Reset');
        clearEl.onclick = function ()
        {
            canvas.clear()
        };
        reset.onclick = function () {
            window.location.reload();
        };
        document.getElementById('file').addEventListener("change", function (e) {
            var file = e.target.files[0];
            var reader = new FileReader();
            console.log("reader   " + reader);
            reader.onload = function (f) {
                var data = f.target.result;
                fabric.Image.fromURL(data, function (img) {
                    var oImg = img.set({ left: 70, top: 100, width: 250, height: 200, angle: 0 }).scale(0.9);
                    canvas.add(oImg).renderAll();
                    canvas.setActiveObject(oImg);
                });
            };
            reader.readAsDataURL(file);
        });

        $('#fill').change(function () {
            var obj = canvas.getActiveObject();
            if (obj) {
                obj.setFill($(this).val());
            }
            canvas.renderAll();
        });

        $('#font').change(function () {
            var obj = canvas.getActiveObject();
            if (obj) {
                obj.setFontFamily($(this).val());
            }
            canvas.renderAll();
        });

        function addText() {
            var oText = new fabric.IText('Tap and Type', {
                left: 100,
                top: 100,
            });

            canvas.add(oText);
            canvas.setActiveObject(oText);
            $('#fill, #font').trigger('change');
            oText.bringToFront();
        }

        document.querySelector('#txt').onclick = function (e) {
            e.preventDefault();
            canvas.deactivateAll().renderAll();
            document.querySelector('#preview').src = canvas.toDataURL();
        };
$("#saveImg").click(function(){
            $("#canvas").get(0).toBlob(function(blob){
                saveAs(blob, uuidv4());

        });
        });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas{
border:1px solid black;
}</code>```

            <input type="file" id="file">
            <input type="color" value="blue" id="fill" />
            <input type="checkbox" id=tint />
            Tint:
              <input type="color" value="blue" id="fillimage" />
            <select id="font">
                <option>arial</option>
                <option>tahoma</option>
                <option>times new roman</option>
            </select>
            <button onclick="addText(); return false;">Add Custom Text</button>
                 <input type="button" value="Clear Canvas" id="clear" />
              <input type="button" value="Reset" id="Reset" />
             <input type="button" id="saveImg" value="Save Image"/>

            <canvas id="canvas" width="600" height="400"></canvas>

            Preview Image

            ```

答:
The following code provides a basic demo of the functionality that you're trying to implement:

var canvas = new fabric.Canvas('canvas');
var clearEl = document.getElementById('clear');
var reset = document.getElementById('Reset');
clearEl.onclick = function ()
{
    canvas.clear();
};
reset.onclick = function () {
    window.location.reload();
};
document.getElementById('file').addEventListener("change", function (e) {
    var file = e.target.files[0];
    var reader = new FileReader();
    console.log("reader   " + reader);
    reader.onload = function (f) {
        var data = f.target.result;
        fabric.Image.fromURL(data, function (img) {
            var oImg = img.set({ left: 70, top: 100, width: 250, height: 200, angle: 0 }).scale(0.9);
            canvas.add(oImg).renderAll();
            canvas.setActiveObject(oImg);
        });
    };
    reader.readAsDataURL(file);
});

$('#fill').change(function () {
    var obj = canvas.getActiveObject();
    if (obj) {
        obj.setFill($(this).val());
    }
    canvas.renderAll();
});

$('#font').change(function () {
    var obj = canvas.getActiveObject();
    if (obj) {
        obj.setFontFamily($(this).val());
    }
    canvas.renderAll();
});

// Listen for changes in UI
$('#tint').change(function() {
    // Get the selected colour
    var tintHex = $('#fillimage').val();

    if ($(this).is(':checked') === true) {
        applyTint(tintHex);
    } else {
        removeTint();
    }
});

// Apply Tint filter
function applyTint (tintHex) {
    // Get active object
    var object = canvas.getActiveObject();

    if (!object) {
        console.error('No image selected');
        return false;
        // Could prompt the user to select an image, or programmatically do it for them
    }

    // Apply the tint. Based on docs at: http://fabricjs.com/docs/fabric.Image.filters.Tint.html#initialize
    var tintFilter = new fabric.Image.filters.Tint({
        color: tintHex,
        //opacity: 0.5 // Could also pass in an opacity value
    });
    object.filters.push(tintFilter);
    object.applyFilters(canvas.renderAll.bind(canvas));
}

// Remove Tint filter
function removeTint () {
    // Get active object
    var object = canvas.getActiveObject();

    if (!object) {
        console.error('No image selected');
        return false;
        // Could prompt the user to select an image, or programmatically do it for them
    }

    object.filters = []; // Empty filters array
    object.applyFilters(canvas.renderAll.bind(canvas));
}

function addText() {
    var oText = new fabric.IText('Tap and Type', {
        left: 100,
        top: 100,
    });

    canvas.add(oText);
    canvas.setActiveObject(oText);
    $('#fill, #font').trigger('change');
    oText.bringToFront();
}

document.querySelector('#txt').onclick = function (e) {
    e.preventDefault();
    canvas.deactivateAll().renderAll();
    document.querySelector('#preview').src = canvas.toDataURL();
};
$("#saveImg").click(function(){
    $("#canvas").get(0).toBlob(function(blob){
        saveAs(blob, uuidv4());

});
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas{
  border:1px solid black;
}</code>```

<input type="file" id="file">
<input type="color" value="blue" id="fill" />
<input type="checkbox" id=tint />
Tint:
  <input type="color" value="blue" id="fillimage" />
<select id="font">
    <option>arial</option>
    <option>tahoma</option>
    <option>times new roman</option>
</select>
<button onclick="addText(); return false;">Add Custom Text</button>
     <input type="button" value="Clear Canvas" id="clear" />
  <input type="button" value="Reset" id="Reset" />
 <input type="button" id="saveImg" value="Save Image"/>

<canvas id="canvas" width="600" height="400"></canvas>

Preview Image

```

Key changes:

Using a different CDN for the Fabric JS library. The version of the Fabric JS library that you were linking to was causing an error when attempting to create a Tint filter.

Using jQuery to listen for changes to checkbox state and call the new functions to apply or remove the tint filter

N.B. Be sure to test the example with a semi-transparent PNG image to see the tint in action

Body:
I have this project, and one of the requirement would be customize and design an uploaded image in a canvas
. So with customizing, I will upload an image, select it, and  I want to change or tint the color with the selected color. But I do not know how.

var canvas = new fabric.Canvas('canvas');
        var clearEl = document.getElementById('clear');
        var reset = document.getElementById('Reset');
        clearEl.onclick = function ()
        {
            canvas.clear()
        };
        reset.onclick = function () {
            window.location.reload();
        };
        document.getElementById('file').addEventListener("change", function (e) {
            var file = e.target.files[0];
            var reader = new FileReader();
            console.log("reader   " + reader);
            reader.onload = function (f) {
                var data = f.target.result;
                fabric.Image.fromURL(data, function (img) {
                    var oImg = img.set({ left: 70, top: 100, width: 250, height: 200, angle: 0 }).scale(0.9);
                    canvas.add(oImg).renderAll();
                    canvas.setActiveObject(oImg);
                });
            };
            reader.readAsDataURL(file);
        });

        $('#fill').change(function () {
            var obj = canvas.getActiveObject();
            if (obj) {
                obj.setFill($(this).val());
            }
            canvas.renderAll();
        });

        $('#font').change(function () {
            var obj = canvas.getActiveObject();
            if (obj) {
                obj.setFontFamily($(this).val());
            }
            canvas.renderAll();
        });

        function addText() {
            var oText = new fabric.IText('Tap and Type', {
                left: 100,
                top: 100,
            });

            canvas.add(oText);
            canvas.setActiveObject(oText);
            $('#fill, #font').trigger('change');
            oText.bringToFront();
        }

        document.querySelector('#txt').onclick = function (e) {
            e.preventDefault();
            canvas.deactivateAll().renderAll();
            document.querySelector('#preview').src = canvas.toDataURL();
        };
$("#saveImg").click(function(){
            $("#canvas").get(0).toBlob(function(blob){
                saveAs(blob, uuidv4());

        });
        });

canvas{
border:1px solid black;
}

            <input type="file" id="file">
            <input type="color" value="blue" id="fill" />
            <input type="checkbox" id=tint />
            Tint:
              <input type="color" value="blue" id="fillimage" />
            <select id="font">
                <option>arial</option>
                <option>tahoma</option>
                <option>times new roman</option>
            </select>
            <button onclick="addText(); return false;">Add Custom Text</button>
                 <input type="button" value="Clear Canvas" id="clear" />
              <input type="button" value="Reset" id="Reset" />
             <input type="button" id="saveImg" value="Save Image"/>

            <canvas id="canvas" width="600" height="400"></canvas>

            Preview Image

Body:
The following code provides a basic demo of the functionality that you're trying to implement:

var canvas = new fabric.Canvas('canvas');
var clearEl = document.getElementById('clear');
var reset = document.getElementById('Reset');
clearEl.onclick = function ()
{
    canvas.clear();
};
reset.onclick = function () {
    window.location.reload();
};
document.getElementById('file').addEventListener("change", function (e) {
    var file = e.target.files[0];
    var reader = new FileReader();
    console.log("reader   " + reader);
    reader.onload = function (f) {
        var data = f.target.result;
        fabric.Image.fromURL(data, function (img) {
            var oImg = img.set({ left: 70, top: 100, width: 250, height: 200, angle: 0 }).scale(0.9);
            canvas.add(oImg).renderAll();
            canvas.setActiveObject(oImg);
        });
    };
    reader.readAsDataURL(file);
});

$('#fill').change(function () {
    var obj = canvas.getActiveObject();
    if (obj) {
        obj.setFill($(this).val());
    }
    canvas.renderAll();
});

$('#font').change(function () {
    var obj = canvas.getActiveObject();
    if (obj) {
        obj.setFontFamily($(this).val());
    }
    canvas.renderAll();
});

// Listen for changes in UI
$('#tint').change(function() {
    // Get the selected colour
    var tintHex = $('#fillimage').val();

    if ($(this).is(':checked') === true) {
        applyTint(tintHex);
    } else {
        removeTint();
    }
});

// Apply Tint filter
function applyTint (tintHex) {
    // Get active object
    var object = canvas.getActiveObject();

    if (!object) {
        console.error('No image selected');
        return false;
        // Could prompt the user to select an image, or programmatically do it for them
    }

    // Apply the tint. Based on docs at: http://fabricjs.com/docs/fabric.Image.filters.Tint.html#initialize
    var tintFilter = new fabric.Image.filters.Tint({
        color: tintHex,
        //opacity: 0.5 // Could also pass in an opacity value
    });
    object.filters.push(tintFilter);
    object.applyFilters(canvas.renderAll.bind(canvas));
}

// Remove Tint filter
function removeTint () {
    // Get active object
    var object = canvas.getActiveObject();

    if (!object) {
        console.error('No image selected');
        return false;
        // Could prompt the user to select an image, or programmatically do it for them
    }

    object.filters = []; // Empty filters array
    object.applyFilters(canvas.renderAll.bind(canvas));
}

function addText() {
    var oText = new fabric.IText('Tap and Type', {
        left: 100,
        top: 100,
    });

    canvas.add(oText);
    canvas.setActiveObject(oText);
    $('#fill, #font').trigger('change');
    oText.bringToFront();
}

document.querySelector('#txt').onclick = function (e) {
    e.preventDefault();
    canvas.deactivateAll().renderAll();
    document.querySelector('#preview').src = canvas.toDataURL();
};
$("#saveImg").click(function(){
    $("#canvas").get(0).toBlob(function(blob){
        saveAs(blob, uuidv4());

});
});

canvas{
  border:1px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.4/fabric.min.js"></script>
<input type="file" id="file">
<input type="color" value="blue" id="fill" />
<input type="checkbox" id=tint />
Tint:
  <input type="color" value="blue" id="fillimage" />
<select id="font">
    <option>arial</option>
    <option>tahoma</option>
    <option>times new roman</option>
</select>
<button onclick="addText(); return false;">Add Custom Text</button>
     <input type="button" value="Clear Canvas" id="clear" />
  <input type="button" value="Reset" id="Reset" />
 <input type="button" id="saveImg" value="Save Image"/>
<br />
<canvas id="canvas" width="600" height="400"></canvas>
<br />

<a href='' id='txt' target="_blank">Preview Image</a>
<br />
<img id="preview" />

Key changes:

Using a different CDN for the Fabric JS library. The version of the Fabric JS library that you were linking to was causing an error when attempting to create a Tint filter.

Using jQuery to listen for changes to checkbox state and call the new functions to apply or remove the tint filter

N.B. Be sure to test the example with a semi-transparent PNG image to see the tint in action


来源: stackexchange

问:
Requirements on std::forward_list::remove_if predicates
Consider this code:

```<code>struct T
{
bool status;
UsefulData data;
};

std::forward_list<T> lst;

lst.remove_if([](T &x) -> bool { return x.status= !x.status; });
</code>```

i.e. switching the status and removing inactive elements in one go.

According to cppreference the above code seems to be undefined behavior (emphasis mine):

```<code>template< class UnaryPredicate >
void remove_if( UnaryPredicate p );
</code>```

p - unary predicate which returns true if the element should be removed.
  The signature of the predicate function should be equivalent to the following:

```<code>bool pred(const Type &a);
</code>```

The signature does not need to have const &, but the function must not modify the objects passed to it.
  The type Type must be such that an object of type forward_list<T,Allocator>::const_iterator can be dereferenced and then implicitly converted to Type.

However, the current working draft seems to be less restrictive (N4659 [forwardlist.ops]):

```<code>void remove(const T& value)
template <class Predicate> void remove_if(Predicate pred);
</code>```

Effects:

Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value (for remove()), pred(*i) is true (for remove_if()). Invalidates only the iterators and references to the erased elements.

Throws:

Nothing unless an exception is thrown by the equality comparison or the predicate.

Remarks:

Stable (20.5.5.7).

Complexity:

Exactly distance(begin(), end()) applications of the corresponding predicate.

Are there additional restrictions on predicates in other parts of the Standard?

I have tested the above code on a number of compilers and it compiles and seems to work as intended. Do I really need to transverse the list twice?

答:
In light of the comments under your question, my view is that:

forward_list::remove_if is not an algorithm, and as such does not fall under the rules of [algorithms.requirements].

[forwardlist.ops] places no restriction on what you may do in the predicate.

forward_list::remove_if is required to apply the predicate exactly once per item in the range.

Therefore, it's strictly legal to modify the object in the predicate in this case, if somewhat anti-social.

edit:

In the light of T.C.'s later answer, it won't be legal for long...
https://stackoverflow.com/a/45052149/2015579

ContentLicense: CC BY-SA 3.0

Body:
Consider this code:

struct T
{
bool status;
UsefulData data;
};

std::forward_list<T> lst;

lst.remove_if([](T &x) -> bool { return x.status= !x.status; });

i.e. switching the status and removing inactive elements in one go.

According to cppreference the above code seems to be undefined behavior (emphasis mine):

template< class UnaryPredicate >
void remove_if( UnaryPredicate p );

p - unary predicate which returns true if the element should be removed.
  The signature of the predicate function should be equivalent to the following:

bool pred(const Type &a);

The signature does not need to have const &, but the function must not modify the objects passed to it.
  The type Type must be such that an object of type forward_list<T,Allocator>::const_iterator can be dereferenced and then implicitly converted to Type.

However, the current working draft seems to be less restrictive (N4659 [forwardlist.ops]):

void remove(const T& value)
template <class Predicate> void remove_if(Predicate pred);

Effects:

Erases all the elements in the list referred by a list iterator i for which the following conditions hold: *i == value (for remove()), pred(*i) is true (for remove_if()). Invalidates only the iterators and references to the erased elements.

Throws:

Nothing unless an exception is thrown by the equality comparison or the predicate.

Remarks:

Stable (20.5.5.7).

Complexity:

Exactly distance(begin(), end()) applications of the corresponding predicate.

Are there additional restrictions on predicates in other parts of the Standard?

I have tested the above code on a number of compilers and it compiles and seems to work as intended. Do I really need to transverse the list twice?


问:
using jquery.noConflict()
I have two files. HTML and .js files. in code.js, I have written jquery code and in HTML file, I am including code.js as following:

```<code><script src="jquery-1.4.2.js"></script>
<script src="jquery.interval.js"></script>
<script src="code.js">
jQuery.noConflict();
var $jcode = jQuery;
</script>
</code>```

in code.js, I have written following:

```<code>jcode(document).ready(function() {
     jcode.interval(checkForms, 2000);
});
</code>```

When I run it, it gives me error as can not read property of interval undefined.
I think there is something wrong with my usage of noConflict. Can you please help?

Thanks

答:
You're not defining a jcode variable.  $jcode is entirely different.  Choose one or the other.  Sticking with $jcode:

Also, as noted by cleek, use a separate (earlier) script block for code.js:

```<code><script type="text/javascript">
    $jcode(document).ready(function() {
         $jcode.interval(checkForms, 2000);
    });
</script>
<script src="code.js" type="text/javascript"></script>
</code>```

ContentLicense: CC BY-SA 2.5

Title: using jquery.noConflict()

Body:
I have two files. HTML and .js files. in code.js, I have written jquery code and in HTML file, I am including code.js as following:

in code.js, I have written following:

jcode(document).ready(function() {
     jcode.interval(checkForms, 2000);
});

When I run it, it gives me error as can not read property of interval undefined.
I think there is something wrong with my usage of noConflict. Can you please help?

Thanks

Body:
You're not defining a jcode variable.  $jcode is entirely different.  Choose one or the other.  Sticking with $jcode:

Also, as noted by cleek, use a separate (earlier) script block for code.js:

<script type="text/javascript">
    $jcode(document).ready(function() {
         $jcode.interval(checkForms, 2000);
    });
</script>
<script src="code.js" type="text/javascript"></script>


问:
c# booleans: return true if first boolean is true and the second is false
I'm learning C# and have attempted this question. Please see my two attempts underneath the question below, and can someone point out to me where/how I have gone wrong please? Thanks.

Attempt 1:

        Return true if the first boolean is true and the second is false.

```<code>public static bool ReturnTrueAndFalse(bool boolean1, bool boolean2)
{
    if (boolean1 = true && (boolean2 = false))
    {
        return true;
    }
    return false;
}
</code>```

Attempt 2:

```<code>public static bool ReturnTrueAndFalse(bool boolean1, bool boolean2)
{
    boolean1 = true;
    boolean2 = false;
    return boolean1 && boolean2;
}
</code>```

答:
This is your attempt below. On checking if boolean1 is true, you are saying 'boolean1 set to true' you arent checking if it is true, the same for boolean2.

```<code>public static bool ReturnTrueAndFalse(bool boolean1, bool boolean2)
{
    if (boolean1 = true && (boolean2 = false))
    {
        return true;
    }
    return false;
}
</code>```

I have fixed your code and this will work.

```<code>public static bool ReturnTrueAndFalse(bool boolean1, bool boolean2)
{
    if (boolean1 == true && boolean2 == false)
    {
        return true;
    }
    return false;
}
</code>```

In your if conditions you need to add '==' instead of just '=', to check if it does equal the value you are checking against.

Body:
I'm learning C# and have attempted this question. Please see my two attempts underneath the question below, and can someone point out to me where/how I have gone wrong please? Thanks.

Attempt 1:

        Return true if the first boolean is true and the second is false.

public static bool ReturnTrueAndFalse(bool boolean1, bool boolean2)
{
    if (boolean1 = true && (boolean2 = false))
    {
        return true;
    }
    return false;
}

Attempt 2:

public static bool ReturnTrueAndFalse(bool boolean1, bool boolean2)
{
    boolean1 = true;
    boolean2 = false;
    return boolean1 && boolean2;
}

Body:
This is your attempt below. On checking if boolean1 is true, you are saying 'boolean1 set to true' you arent checking if it is true, the same for boolean2.

public static bool ReturnTrueAndFalse(bool boolean1, bool boolean2)
{
    if (boolean1 = true && (boolean2 = false))
    {
        return true;
    }
    return false;
}

I have fixed your code and this will work.

public static bool ReturnTrueAndFalse(bool boolean1, bool boolean2)
{
    if (boolean1 == true && boolean2 == false)
    {
        return true;
    }
    return false;
}

In your if conditions you need to add '==' instead of just '=', to check if it does equal the value you are checking against.


问:
Convert css position to jquery smooth sliding
I currently have a
 that maintains its position at the top of the left had side of the page, when the page moves up or down. This works fine but isn't very smooth.

I'm looking to re-factor the code below to make this a smooth scroll. Currently when the trigger happens it just sets the CSS top property - which makes it "jittery". I'm a little unsure how to make this a smooth scroll motion opposed to setting the css top value to its exact location

```<code>        //scrolling menu
    if($("#selectedOptions").length > 0){   //if the element exists
        $(window).scroll(function(){
            var div = $("#selectedOptions");        // the div that slides
            if(div) {
                var pos = div.parent().position().top;  //position of the top of the wrapper
                var windowPos = $(window).scrollTop();  //current window postion

                //top of moving div not to go further than
                var bottom = $("#sizeAndQuantHeader").position().top; //where the div shouldn't go past

                //de-bug
                //console.log("pos: " + pos + " - winpos" + windowPos + ", heih: " + divHieght + " doc he: " + $(document).height() + " bott" + bottom);

                //if between the range then display at new postion
                if (windowPos > pos && (windowPos < bottom)) {
                    div.css("top", windowPos-pos);
                    //must be higher than its current position so set to 0
                 } else if (windowPos < pos && windowPos < bottom) {
                     div.css("top", 0);
                }
            }
        });
    }
</code>```

Any help or tips on how to make a
 scroll smoothly down a page would be much appreciated.

**Update

Unfortunately, i have elements that already scroll around different page areas:

```<code>var _scrollTo = function(div){
    $('html,body').animate({
        scrollTop: div.offset().top},
        'slow');
};
</code>```

Now when the function above is called i think it triggers the call:

```<code>  $(window).scroll(function(){animate div...
</code>```

and delays the scrolling of the newly animated div. I cant't use call back either as it's re-used else where. I may be missing something here so i've resorted back to no animation.

答:
add css to div (#selectedOptions)

```<code>transition: all 0.5s ease 0s;
-moz-transition: all 0.5s ease 0s;
-webkit-transition: all 0.5s ease 0s;
-o-transition: all 0.5s ease 0s;
</code>```

It will go smooth automatically.

Body:
I currently have a
 that maintains its position at the top of the left had side of the page, when the page moves up or down. This works fine but isn't very smooth.

I'm looking to re-factor the code below to make this a smooth scroll. Currently when the trigger happens it just sets the CSS top property - which makes it "jittery". I'm a little unsure how to make this a smooth scroll motion opposed to setting the css top value to its exact location

        //scrolling menu
    if($("#selectedOptions").length > 0){   //if the element exists
        $(window).scroll(function(){
            var div = $("#selectedOptions");        // the div that slides
            if(div) {
                var pos = div.parent().position().top;  //position of the top of the wrapper
                var windowPos = $(window).scrollTop();  //current window postion

                //top of moving div not to go further than
                var bottom = $("#sizeAndQuantHeader").position().top; //where the div shouldn't go past

                //de-bug
                //console.log("pos: " + pos + " - winpos" + windowPos + ", heih: " + divHieght + " doc he: " + $(document).height() + " bott" + bottom);

                //if between the range then display at new postion
                if (windowPos > pos && (windowPos < bottom)) {
                    div.css("top", windowPos-pos);
                    //must be higher than its current position so set to 0
                 } else if (windowPos < pos && windowPos < bottom) {
                     div.css("top", 0);
                }
            }
        });
    }

Any help or tips on how to make a
 scroll smoothly down a page would be much appreciated.

**Update

Unfortunately, i have elements that already scroll around different page areas:

var _scrollTo = function(div){
    $('html,body').animate({
        scrollTop: div.offset().top},
        'slow');
};

Now when the function above is called i think it triggers the call:

  $(window).scroll(function(){animate div...

and delays the scrolling of the newly animated div. I cant't use call back either as it's re-used else where. I may be missing something here so i've resorted back to no animation.

Body:
add css to div (#selectedOptions)

transition: all 0.5s ease 0s;
-moz-transition: all 0.5s ease 0s;
-webkit-transition: all 0.5s ease 0s;
-o-transition: all 0.5s ease 0s;

It will go smooth automatically.


问:
ASP.Net website - doesn't load css file correctly
I'm having issues with this website, it seems like the css and image files (all located in the ../Content/ folder. Which is strange because I've never seen this error on other servers I tested the site on.

Problem is I don't have direct access to that problematic server and can only guess from here what might be wrong.

The site is hosted by a local IIS and invoked by http://localhost/application-name/site-name

The css file is referenced in the master file below, and the images are referenced e.g. ~/Content/images/sample.png

Site Master

```<code><html lang="en">
<head runat="server">
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title><%: Page.Title %> - Stackoverfl0w</title>

    <asp:PlaceHolder runat="server">
        <%: Scripts.Render("~/bundles/modernizr") %>
    </asp:PlaceHolder>

    <asp:ContentPlaceHolder ID="Stylesheets" runat="server">
        <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.min.css">
        <link rel="stylesheet" href="/Content/Site.css" type="text/css" />
    </asp:ContentPlaceHolder>

    <webopt:bundlereference runat="server" path="~/Content/css" />

    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />

</head>
</code>```

答:
Use the ~ symbol on file path, so browser can fetch the file from main directory....</p>

```<code><link rel="stylesheet" href="~/Content/Site.css" type="text/css" />
</code>```

Body:
I'm having issues with this website, it seems like the css and image files (all located in the ../Content/ folder. Which is strange because I've never seen this error on other servers I tested the site on.

Problem is I don't have direct access to that problematic server and can only guess from here what might be wrong.

The site is hosted by a local IIS and invoked by http://localhost/application-name/site-name

The css file is referenced in the master file below, and the images are referenced e.g. ~/Content/images/sample.png

Site Master

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title><%: Page.Title %> - Stackoverfl0w</title>

    <asp:PlaceHolder runat="server">
        <%: Scripts.Render("~/bundles/modernizr") %>
    </asp:PlaceHolder>

    <asp:ContentPlaceHolder ID="Stylesheets" runat="server">
        <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.min.css">
        <link rel="stylesheet" href="/Content/Site.css" type="text/css" />
    </asp:ContentPlaceHolder>

    <webopt:bundlereference runat="server" path="~/Content/css" />

    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />

Body:
Use the ~ symbol on file path, so browser can fetch the file from main directory....

<link rel="stylesheet" href="~/Content/Site.css" type="text/css" />


问:
How to generate compile_commands.json for a C++ Bazel project
In a C++ Bazel project, I want to use tools like Clang Tools or RTags, etc.

For that I need to generate a compile_commands.json file.

The solution is trivial for CMake with the CMAKE_EXPORT_COMPILE_COMMANDS.

For simple Makefiles you can still use the Bear tool.

However AFAIK there is no built-in solution for C++ Bazel projects.

答:
Extra information:

Bear is currently not working with Bazel: this issue

a good documentation concerning compile_command.json can be found here.

Suggested solutions:

After Googling about that I found gist:Basics of generating a compile_commands.json file with Bazel.

It works fine and I have written
an automated solution with bash scripts <- my solution

Alternative:

Also on GitHub, you can find:

Kythe: uses Bazel action listeners

github.com/grailbio/bazel-compilation-database: provides a script and a bazel rule.


问:
LINQ and column with Null
I have a DataSet, with a column, lets call it A, of type Int. I want to run a quiote simple LINQ query, using where on column A. The problem is, that column A can contain null values (at least in the T-SQL table from where i get it, I am not sure how these null values are translated in the TableAdapter). This results in an error when I try to run the following query:

```<code>MyTableDataTable dt =
    new MyTableDataTable();

MyTableTableAdapter ta =
     new MyTableTableAdapter();

        ta.Fill(dt);

// This is where the error occurs
var query = from  tbl in dt.AsEnumerable()
            where tbl.A == parentId
            &&    tbl.B == languageId
            select new
            {
                tbl.A,
                tbl.B,
                tbl.C
            };
</code>```

The error message it returns is this:

StrongTypingException was unhandled

An unhandled exception of type
   'System.Data.StrongTypingException' occurred in
  MyProgram.exe

Additional information: The value for column 'A' in
  table 'MyTable' is DBNull.

How should nullvalues be handed in a sceniario like this? I would like to do something like where A is not null, but I can't really find a way to do this...

答:
I found a solution, by accident, when attempting @gencklavyeler's suggestion. While tbl.A != null does not work, there is another way using tbl.IsANull() == false. Like this:

```<code>var query = from  tbl in dt.AsEnumerable()
            where tbl.IsANull() == false
            &&    tbl.A == parentId
            &&    tbl.B == session.LanguageId
            select new
            {
                tbl.A,
                tbl.B,
                tbl.C
            };
</code>```

Title: LINQ and column with Null

Body:
I have a DataSet, with a column, lets call it A, of type Int. I want to run a quiote simple LINQ query, using where on column A. The problem is, that column A can contain null values (at least in the T-SQL table from where i get it, I am not sure how these null values are translated in the TableAdapter). This results in an error when I try to run the following query:

MyTableDataTable dt =
    new MyTableDataTable();

MyTableTableAdapter ta =
     new MyTableTableAdapter();

        ta.Fill(dt);

// This is where the error occurs
var query = from  tbl in dt.AsEnumerable()
            where tbl.A == parentId
            &&    tbl.B == languageId
            select new
            {
                tbl.A,
                tbl.B,
                tbl.C
            };

The error message it returns is this:

StrongTypingException was unhandled

An unhandled exception of type
   'System.Data.StrongTypingException' occurred in
  MyProgram.exe

Additional information: The value for column 'A' in
  table 'MyTable' is DBNull.

How should nullvalues be handed in a sceniario like this? I would like to do something like where A is not null, but I can't really find a way to do this...

Body:
I found a solution, by accident, when attempting @gencklavyeler's suggestion. While tbl.A != null does not work, there is another way using tbl.IsANull() == false. Like this:

var query = from  tbl in dt.AsEnumerable()
            where tbl.IsANull() == false
            &&    tbl.A == parentId
            &&    tbl.B == session.LanguageId
            select new
            {
                tbl.A,
                tbl.B,
                tbl.C
            };


问:
Fetching Data from mca.gov.in using curl and PHP
I am trying to fetch the data from http://mca.gov.in. I am using CURL and PHP for extracting the data.

Here is the form : http://www.mca.gov.in/mcafoportal/viewSignatoryDetails.do

When I do the HTML form submit directly through this HTML form to ( "http://www.mca.gov.in/mcafoportal/viewSignatoryDetails.do"), it works.

I developed my own form and submitted directly to the above link and it works too.

However, when I pass the same parameters to retrieve the data using curl, it is not giving any data.

Here is the code I am using to fetch the data from http://mca.gov.in.

```<code>$data = http_build_query($post_data);

curl_setopt($ch, CURLOPT_URL, "http://www.mca.gov.in/mcafoportal/viewSignatoryDetailsAction.do");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);
echo $result;
</code>```

Any idea, what could be wrong or If I have missed anything ?

答:
Your problem is that the url you are trying to fetch uses a captcha and you cannot bypass this by code.

You need to use a this url "http://www.mca.gov.in/mcafoportal/popupSignatories.do" that does not require a captcha.

So change your code to:

```<code>curl_setopt($ch, CURLOPT_URL, "http://www.mca.gov.in/mcafoportal/popupSignatories.do");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    "companyid" => "AAA-4416"
));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);
echo $result;
</code>```

Additionally if you want the company details, use "http://www.mca.gov.in/mcafoportal/companyMasterDataPopup.do"

```<code>curl_setopt($ch, CURLOPT_URL, "http://www.mca.gov.in/mcafoportal/companyMasterDataPopup.do");
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    "method" => "ajaxGetCompanyMasterData",
    "companyid" => 'AAA-4416'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);

echo $result;
</code>```

Update

There are some new APIs that can be found at company master data API from https://data.gov.in

Body:
I am trying to fetch the data from http://mca.gov.in. I am using CURL and PHP for extracting the data.

Here is the form : http://www.mca.gov.in/mcafoportal/viewSignatoryDetails.do

When I do the HTML form submit directly through this HTML form to ( "http://www.mca.gov.in/mcafoportal/viewSignatoryDetails.do"), it works.

I developed my own form and submitted directly to the above link and it works too.

However, when I pass the same parameters to retrieve the data using curl, it is not giving any data.

Here is the code I am using to fetch the data from http://mca.gov.in.

$data = http_build_query($post_data);

curl_setopt($ch, CURLOPT_URL, "http://www.mca.gov.in/mcafoportal/viewSignatoryDetailsAction.do");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);
echo $result;

Any idea, what could be wrong or If I have missed anything ?

Body:
Your problem is that the url you are trying to fetch uses a captcha and you cannot bypass this by code.

You need to use a this url "http://www.mca.gov.in/mcafoportal/popupSignatories.do" that does not require a captcha.

So change your code to:

curl_setopt($ch, CURLOPT_URL, "http://www.mca.gov.in/mcafoportal/popupSignatories.do");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    "companyid" => "AAA-4416"
));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);
echo $result;

Additionally if you want the company details, use "http://www.mca.gov.in/mcafoportal/companyMasterDataPopup.do"

curl_setopt($ch, CURLOPT_URL, "http://www.mca.gov.in/mcafoportal/companyMasterDataPopup.do");
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    "method" => "ajaxGetCompanyMasterData",
    "companyid" => 'AAA-4416'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);

echo $result;

Update

There are some new APIs that can be found at company master data API from https://data.gov.in

ContentLicense: CC BY-SA 4.0


问:
SQL Server: select rows which has particular id in their json column
I have a table with two columns: [ID] and [Content] (with ISJSON constraint, so every row must have valid JSON in [Content] column).
These JSONs have an array field, which consists of objects with some specific ID (and many more fields) .

```<code>    {
    "departments": [ { "id": 1, "fieldA": "somevalue" },
                     { "id": 2, "fieldA": "somevalue" }]
    }
</code>```

I'd like to perform a select query, which returns all rows with some particular id in the object from departments field.

I managed to create a script that uses a cursor fetching departments field from [Content] column into @content variable and then:

```<code>SELECT * FROM OPENJSON(@content) WITH(id int) WHERE id IN (1, 2, 3, 9)
</code>```

But it returns only departmentid and I need the whole row.
Preferably it should look like that (but code below unfortunately does not work):

```<code>SELECT * FROM ITEM I WHERE EXISTS
(SELECT * FROM OPENJSON(I.CONTENT) WITH(id int) WHERE id IN (1, 2, 3, 9))
</code>```

答:
If I understood you correctly, this could get you what you need:

```<code>declare @someId varchar(10) = '1'
declare @json nvarchar(1000) = N'{ "departments": [ { "id": 1, "fieldA": "somevalue" },  { "id": 1, "fieldA": "test" },  { "id": 2, "fieldA": "somevalue" }] }'

select ids.[key], ids.[value] id_val, depts.value content
from openjson(@json, '$.departments') as depts cross apply OPENJSON(depts.value) as ids
where ids.[key] = 'id' and ids.value = @someId
</code>```

I have added another element to the departments array, with the same Id = 1 just for testing the results.

EDIT:

```<code>select  ids.[key], ids.[value] id_val, depts.value content
from ITEMS i cross apply openjson(i.Content, '$.departments') as depts cross apply OPENJSON(depts.value) as ids
where ids.[key] = 'id' and ids.value = @id
</code>```

Body:
I have a table with two columns: [ID] and [Content] (with ISJSON constraint, so every row must have valid JSON in [Content] column).
These JSONs have an array field, which consists of objects with some specific ID (and many more fields) .

    {
    "departments": [ { "id": 1, "fieldA": "somevalue" },
                     { "id": 2, "fieldA": "somevalue" }]
    }

I'd like to perform a select query, which returns all rows with some particular id in the object from departments field.

I managed to create a script that uses a cursor fetching departments field from [Content] column into @content variable and then:

SELECT * FROM OPENJSON(@content) WITH(id int) WHERE id IN (1, 2, 3, 9)

But it returns only departmentid and I need the whole row.
Preferably it should look like that (but code below unfortunately does not work):

SELECT * FROM ITEM I WHERE EXISTS
(SELECT * FROM OPENJSON(I.CONTENT) WITH(id int) WHERE id IN (1, 2, 3, 9))

Body:
If I understood you correctly, this could get you what you need:

declare @someId varchar(10) = '1'
declare @json nvarchar(1000) = N'{ "departments": [ { "id": 1, "fieldA": "somevalue" },  { "id": 1, "fieldA": "test" },  { "id": 2, "fieldA": "somevalue" }] }'

select ids.[key], ids.[value] id_val, depts.value content
from openjson(@json, '$.departments') as depts cross apply OPENJSON(depts.value) as ids
where ids.[key] = 'id' and ids.value = @someId

I have added another element to the departments array, with the same Id = 1 just for testing the results.

EDIT:

select  ids.[key], ids.[value] id_val, depts.value content
from ITEMS i cross apply openjson(i.Content, '$.departments') as depts cross apply OPENJSON(depts.value) as ids
where ids.[key] = 'id' and ids.value = @id


问:
Using php code in symfony YAML as string value
I want to create some YAML key with value - the code in php. But this code shouldn't be executed - I want to use it as the value itself. How can I do this?

Example:

```<code>somekey: <?php echo 1; ?>
</code>```

This line shouldn't be recognized as somekey: 1 after parsing - I want to receive value for somekey key as <?php echo 1; ?>.

Update:

I want to use this to store some code in database (with fixtures.yml) and then load it and use as php-based template.

答:
I invented my own solution. It looks badly but works:</p>

```<code>somekey: "<?php echo '<?php echo 1; ?>'; ?>"
</code>```

Body:
I want to create some YAML key with value - the code in php. But this code shouldn't be executed - I want to use it as the value itself. How can I do this?

Example:

somekey: <?php echo 1; ?>

This line shouldn't be recognized as somekey: 1 after parsing - I want to receive value for somekey key as <?php echo 1; ?>.

Update:

I want to use this to store some code in database (with fixtures.yml) and then load it and use as php-based template.

Body:
I invented my own solution. It looks badly but works:

somekey: "<?php echo '<?php echo 1; ?>'; ?>"


问:
Event set component using a collada object in A-Frame (webvr)
I am trying to create a rotating animation on a collada object using the event set component plugin for A-frame, I have successfully been able to achieve this using a-box but would like animate the collada object instead. For some reason I cannot see the collada object and I don't know where I'm going wrong. Please see the code below for more info and any help would be highly appreciated , thanks.</p>

```<code><html>
<head>
<title>Model Test</title>
<script src="build.js"></script>
<script src="https://aframe.io/releases/0.5.0/aframe.min.js"></script>
<script src="aframe-animation-component.min.js"></script>
<script src="component/event-proxy.js"></script>
<script src="https://unpkg.com/aframe-event-set-component@3.0.x/dist/aframe-event-set-component.min.js"></script>
<script src="https://unpkg.com/aframe-layout-component@4.1.0/dist/aframe-layout-component.min.js"></script>
</head>
<body>
<a-scene>
  <a-entity id="container" position="0 0 -2">
    <a-collada-model src="iPhone4.dae"
        animation__rotationX="property: rotation; dur: 10000;
                        easing: easeInSine; loop: true; to: 0 360 0;
                        startEvents: rotY; pauseEvents: animationPause;
                        resumeEvents: animationResume; restartEvents: animationRestart"
        animation__rotationY="property: rotation; dur: 10000;
                        easing: easeInSine; loop: true; to: 360 0 0;
                        startEvents: rotX; pauseEvents: animationPause;
                        resumeEvents: animationResume; restartEvents: animationRestart"

      position="0 1 -2">
    </a-collada-model>
    <a-mixin id="option"
             geometry="primitive: sphere; radius: .25;"
             material="color: red"
             event-proxy="listen: click; target: a-collada-model"
             ></a-mixin>
    <a-entity  position="-2.5 0 0">
      <a-entity mixin="option" event-proxy="emit: rotY" text="value: Rotation"></a-entity>
    </a-entity>
    <a-entity  position="2.5 0 0">
      <a-entity mixin="option" event-proxy="emit: rotX" text="value: Rotation"></a-entity>
    </a-entity>

    <a-entity position="0 -1.5 0">
      <a-sphere mixin="option" event-proxy="emit: animationPause" text="value: Pause"></a-entity>
    </a-entity>
  </a-entity>

  <!-- Sky. -->
  <a-sky color="#0fbbff"></a-sky>

  <a-entity position="0 0 3">
    <a-camera><a-cursor color="#FFF"></a-cursor></a-camera>
  </a-entity>
</a-scene>

</body>
</html>
</code>```

答:
First of all, upgrade to 0.6.0. Im not sure how about the event and animation components, but afaik the model handling is better in 0.6.0.

Then try to use the collada loader as a component, instead of a primitive, like in the docs:

```<code><a-entity collada-model="src:iphone4.dae"></a-entity>
</code>```

If You can't make the model to appear, You might want to switch the format to threejs json, or .glTF, by uploading Your iphone to clara.io, or using khronos/kupoman exporters, and then using Don McCurdy's loaders .

Btw You don't seem to have issues with events, but with models, so the topic is kinda off :p

Body:
I am trying to create a rotating animation on a collada object using the event set component plugin for A-frame, I have successfully been able to achieve this using a-box but would like animate the collada object instead. For some reason I cannot see the collada object and I don't know where I'm going wrong. Please see the code below for more info and any help would be highly appreciated , thanks.

<title>Model Test</title>

    <a-collada-model src="iPhone4.dae"
        animation__rotationX="property: rotation; dur: 10000;
                        easing: easeInSine; loop: true; to: 0 360 0;
                        startEvents: rotY; pauseEvents: animationPause;
                        resumeEvents: animationResume; restartEvents: animationRestart"
        animation__rotationY="property: rotation; dur: 10000;
                        easing: easeInSine; loop: true; to: 360 0 0;
                        startEvents: rotX; pauseEvents: animationPause;
                        resumeEvents: animationResume; restartEvents: animationRestart"

      position="0 1 -2">

Body:
First of all, upgrade to 0.6.0. Im not sure how about the event and animation components, but afaik the model handling is better in 0.6.0.

Then try to use the collada loader as a component, instead of a primitive, like in the docs:

<a-entity collada-model="src:iphone4.dae"></a-entity>

If You can't make the model to appear, You might want to switch the format to threejs json, or .glTF, by uploading Your iphone to clara.io, or using khronos/kupoman exporters, and then using Don McCurdy's loaders .

Btw You don't seem to have issues with events, but with models, so the topic is kinda off :p


问:
How to rollback unit test while service layer is @Transactional
I am using Spring Boot 1.5.2.RELEASE and my service classes is annotated with

```<code>@Service
@Transactional(rollbackFor = Exception.class)
</code>```

My unit test class is annotated with:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
</code>```

I wish to roll back changes made in the database by unit test methods after test is finished.

One of the proposed solutions is to add @Transactional annotation over the test class, I tried it but this solution produces some issues, is that sometimes the test transaction is rolled back (even without no exceptions thrown!) before the service transaction is completed.

Is there another good solution to rollback test?

答:
From the docs:

By default, test transactions will be automatically rolled back after
  completion of the test; however, transactional commit and rollback behavior can be configured declaratively via the @Commit and @Rollback annotations.

Your comment:

sometimes the test transaction is rolled back (even without no
  exceptions thrown !) before the service transaction is completed !

doesn't make sense to me. How did you know whether the txn completed or not if it was rolled back? Exceptions don't matter for tests, as I quoted the doc above.

Body:
I am using Spring Boot 1.5.2.RELEASE and my service classes is annotated with

@Service
@Transactional(rollbackFor = Exception.class)

My unit test class is annotated with:

@RunWith(SpringRunner.class)
@SpringBootTest

I wish to roll back changes made in the database by unit test methods after test is finished.

One of the proposed solutions is to add @Transactional annotation over the test class, I tried it but this solution produces some issues, is that sometimes the test transaction is rolled back (even without no exceptions thrown!) before the service transaction is completed.

Is there another good solution to rollback test?


问:
how to filter an object and get the desired output in javascript array?
I have an array of object like this,

```<code>[
  {imgUrl: "A"},
  {imgUrl: "B"},
  {imgUrl: "C", file: {fileName: "D"} }
]
</code>```

Desired output = ["A", "B", "D"];

答:
If I'm understanding correctly, you want the imgUrl of a value array, unless a fileName is present?  If that's the case, there are loads of ways that you can achieve this, but using the reduce functionality, you can do something like this:

```<code>test = [
  {imgUrl: "A"},
  {imgUrl: "B"},
  {imgUrl: "C", file: {fileName: "D"}},
]

output = test.reduce((acc, obj) => {
  return acc.concat([obj.file && obj.file.fileName || obj.imgUrl])
}, [])
</code>```

The || statement here will prioritize the obj.file.fileName iff obj.file exists: if it's a valid value it will just return that value, but if the value is falsy it will instead take the value of obj.imgUrl

Sidenote on "Falsy":
If you do what to consider empty strings or zero values or any value as valid values, you can replace the || statement with a Ternary Statement

i.e.
condition ? if_true_return_value : if_false_return_value

In this case:

(obj.hasOwnProperty("file") && obj.file.fileName) ? obj.file.fileName : obj.imgUrl

Body:
I have an array of object like this,

[
  {imgUrl: "A"},
  {imgUrl: "B"},
  {imgUrl: "C", file: {fileName: "D"} }
]

Desired output = ["A", "B", "D"];

Body:
If I'm understanding correctly, you want the imgUrl of a value array, unless a fileName is present?  If that's the case, there are loads of ways that you can achieve this, but using the reduce functionality, you can do something like this:

test = [
  {imgUrl: "A"},
  {imgUrl: "B"},
  {imgUrl: "C", file: {fileName: "D"}},
]

output = test.reduce((acc, obj) => {
  return acc.concat([obj.file && obj.file.fileName || obj.imgUrl])
}, [])

The || statement here will prioritize the obj.file.fileName iff obj.file exists: if it's a valid value it will just return that value, but if the value is falsy it will instead take the value of obj.imgUrl

Sidenote on "Falsy":
If you do what to consider empty strings or zero values or any value as valid values, you can replace the || statement with a Ternary Statement

i.e.
condition ? if_true_return_value : if_false_return_value

In this case:

(obj.hasOwnProperty("file") && obj.file.fileName) ? obj.file.fileName : obj.imgUrl


问:
IIS Website Application doesnt work anything but port 80
I wrote a WCF service in visual studio 2017. I then added this service to IIS (not the express version but the full fledge IIS). It is added as an application under the default created website. I can access my service end-point without any issues at http://localhost/<websitename>/MyService.svc/test/123. /test/123 is just a simple GET endpoint.

The default website is already configured for port 80.

However, when I changed the port from 80 to say, 1234, it does not work. It merely returns me "Service Unavailable. HTTP Error 503." when I hit the /test/123 endpoint.

I have already executed the console command to add the port to ACL netsh http add urlacl url=http://+:1234/ user=everyone.

Does anyone know how can I get another port (non 80) to work?

Edit:
I am aware that there is an answer How to run WCF service on a specific port which explains how to bind to another port. However, the accepted answer uses the net.tcp protocol. I would like to use the HTTP protocol.

Is there any way to do it with HTTP protocol? If it cannot be done, then I guess ill have to redesign and swap over to net.tcp protocol.

I am extremely new to .NET development and WCF, so hopefully somebody with experience can point me in the right direction.

答:
As it turns out, the problem had nothing to do with the so-called linked answer.

Prior to running my WCF service in IIS, I was trying to deploy it as a WAS and then Console application. In my process of getting those 2 implementations to work, I had to execute the command netsh http add urlacl url=http://+:1234/ user=everyone so that the port could be accessed.

By sheer luck, i stumbled upon this link:
https://serverfault.com/questions/666976/service-unavailable-if-i-try-to-access-iis-website-via-ip-address-works-fine-vi

Although it didnt have an accepted answer, the comments held the answer. My problem was caused exactly because I executed the netsh command. What happens is that the command causes that ip/port to be reserved, and thus, IIS cannot attach to the ip/port and therefore the Service Unavailable error. I assumed that if the WAS and Console version needed that command to be executed, then the IIS version needed it as well.

As for letting an IIS WCF Service be available on any other port, the process is super simple. Within IIS itself (Execute "inetmgr" in Run to launch), in the default or custom website you created, edit the binding and change the HTTP port to whatever port that you want. After that, its done. You should be able to access your application/website from that port via HTTP.
Eg:
http://localhost:<some port>/<websitename>/MyService.svc/test/123

My WCF Service config was a standard config that allowed for HTTP access.

If you would like to access it from another computer or from the internet, then you will need to configure your router to port forward your selected port (if needed) and ensure that your firewall allows data flow for that port.

Many "thanks" to the downvoters who assume this was some duplicate. Your "help" contributed in finding a solution to the problem.


问:
Refactor 2 functions with different arguments but almost same implementation in c
I have 2 functions similar to each other,

```<code>void func1(info1* ari,int l,int r) {
   int size = sizeof_char_array(ari->field_type) ;
   for (int i=0 ; i<size ; i++) {
      if (ari->field_type[i] & MEMORY) {
         mem_info* mi = (mem_info*)ari->field[i] ;
         mi->L = l ;
      }
      else if ...
      else {
         info2* p = (info2*)ri->field[i] ;
         func2(p,l,r);
      }
   }
}
</code>```

Another one is

```<code>void func2(info2* ri,int l,int r) {
   int size = sizeof_char_array(ri->field_type) ;
   for (int i=0 ; i<size ; i++) {
      if (ari->field_type[i] & MEMORY) {
         mem_info* mi = (mem_info*)ri->field[i] ;
         mi->L = l ;
      }
      else if...
      else {
         info2* p = (info2*)ri->field[i] ;
         func2(p,l,r);
      }
   }
}
</code>```

It's easy to find that the only difference between this 2 functions are info1* and info2*. info1 and info2 are structs with similar layouts.

Is there a way to refactor this 2 functions to one elegantly in C?

答:
Unfortunately C doesn't have a mechanism like C++'s templates. You could use a macro to generate the two functions, parametrizing on the type:

```<code>#define DEFINE_FUNC(name, type)                          \
    void name(type* ari, int l, int r)                   \
    {                                                    \
        int size = sizeof_char_array(ari->field_type);   \
        for(int i = 0; i < size; i++)                    \
        {                                                \
            if(ari->field_type[i] & MEMORY)              \
            {                                            \
                mem_info* mi = (mem_info*)ari->field[i]; \
                mi->L = l;                               \
            }                                            \
            else if                                      \
            { /* ... */                                  \
            }                                            \
            else                                         \
            {                                            \
                info2* p = (info2*)ri->field[i];         \
                func2(p, l, r);                          \
            }                                            \
        }                                                \
    }
</code>```

Then you can define your functions and use them as follows:

```<code>DEFINE_FUNC(func1, info1)
DEFINE_FUNC(func2, info2)
#undef DEFINE_FUNC

int main()
{
    func1(some_info1, 0, 5);
    func2(some_info2, 1, 6);
}
</code>```

Body:
I have 2 functions similar to each other,

void func1(info1* ari,int l,int r) {
   int size = sizeof_char_array(ari->field_type) ;
   for (int i=0 ; i<size ; i++) {
      if (ari->field_type[i] & MEMORY) {
         mem_info* mi = (mem_info*)ari->field[i] ;
         mi->L = l ;
      }
      else if ...
      else {
         info2* p = (info2*)ri->field[i] ;
         func2(p,l,r);
      }
   }
}

Another one is

void func2(info2* ri,int l,int r) {
   int size = sizeof_char_array(ri->field_type) ;
   for (int i=0 ; i<size ; i++) {
      if (ari->field_type[i] & MEMORY) {
         mem_info* mi = (mem_info*)ri->field[i] ;
         mi->L = l ;
      }
      else if...
      else {
         info2* p = (info2*)ri->field[i] ;
         func2(p,l,r);
      }
   }
}

It's easy to find that the only difference between this 2 functions are info1* and info2*. info1 and info2 are structs with similar layouts.

Is there a way to refactor this 2 functions to one elegantly in C?

Body:
Unfortunately C doesn't have a mechanism like C++'s templates. You could use a macro to generate the two functions, parametrizing on the type:

#define DEFINE_FUNC(name, type)                          \
    void name(type* ari, int l, int r)                   \
    {                                                    \
        int size = sizeof_char_array(ari->field_type);   \
        for(int i = 0; i < size; i++)                    \
        {                                                \
            if(ari->field_type[i] & MEMORY)              \
            {                                            \
                mem_info* mi = (mem_info*)ari->field[i]; \
                mi->L = l;                               \
            }                                            \
            else if                                      \
            { /* ... */                                  \
            }                                            \
            else                                         \
            {                                            \
                info2* p = (info2*)ri->field[i];         \
                func2(p, l, r);                          \
            }                                            \
        }                                                \
    }

Then you can define your functions and use them as follows:

DEFINE_FUNC(func1, info1)
DEFINE_FUNC(func2, info2)
#undef DEFINE_FUNC

int main()
{
    func1(some_info1, 0, 5);
    func2(some_info2, 1, 6);
}


问:
dynamically open a inputbox in excel with VBA
i have a excel table and a specific area. This area can be
Range("A1:A5") for example and only has to accept 0 and 1. And it has to open a Inputbox automatically when the user enters a 0 (only clicking on a button or something like that). Of course in that moment.

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address.Value = 0 Then 'open InputBox
End If
End Sub

Have this but this does not work.

Thanks all.

答:
```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range
    Dim valueEnter As Long, lastRow As Long
    Set rng = Range("A1:A5") 'specify your range here
    lastRow = Cells(Rows.Count, "B").End(xlUp).Row
    If Intersect(Target, rng) Is Nothing Or Target.Value <> 0 Then Exit Sub
    valueEnter = InputBox("Gebe die ein:", "Eingabe")
    If valueEnter >= 0 Then
        Range("B" & lastRow + 1) = valueEnter
    End If
End Sub
</code>```

EDIT:___________________________________________________________

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
    Dim rng As Range
    Dim valueEnter As Variant, lastRow As Long
    Set rng = Range("A1:A5") 'specify your range here
    lastRow = Cells(Rows.Count, "B").End(xlUp).Row
    If Intersect(Target, rng) Is Nothing Or Target.Value <> 0 Then GoTo Jump
    valueEnter = InputBox("Gebe die ein:", "Eingabe", 1)
    If IsNumeric(valueEnter) Then
        If valueEnter > 0 Then
            Range("B" & lastRow + 1) = CInt(valueEnter)
            Target.Value = ""
        End If
    Else
        Target.Value = ""
    End If
Jump:
    Application.EnableEvents = True
End Sub
</code>```

Body:
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range
    Dim valueEnter As Long, lastRow As Long
    Set rng = Range("A1:A5") 'specify your range here
    lastRow = Cells(Rows.Count, "B").End(xlUp).Row
    If Intersect(Target, rng) Is Nothing Or Target.Value <> 0 Then Exit Sub
    valueEnter = InputBox("Gebe die ein:", "Eingabe")
    If valueEnter >= 0 Then
        Range("B" & lastRow + 1) = valueEnter
    End If
End Sub

EDIT:___________________________________________________________

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = False
    Dim rng As Range
    Dim valueEnter As Variant, lastRow As Long
    Set rng = Range("A1:A5") 'specify your range here
    lastRow = Cells(Rows.Count, "B").End(xlUp).Row
    If Intersect(Target, rng) Is Nothing Or Target.Value <> 0 Then GoTo Jump
    valueEnter = InputBox("Gebe die ein:", "Eingabe", 1)
    If IsNumeric(valueEnter) Then
        If valueEnter > 0 Then
            Range("B" & lastRow + 1) = CInt(valueEnter)
            Target.Value = ""
        End If
    Else
        Target.Value = ""
    End If
Jump:
    Application.EnableEvents = True
End Sub


问:
ERROR:Exception in request: org.apache.http.conn.HttpHostConnectException: Connection to http://********:80 refused
When I use SoapUI for testing SOAP project, I met an error, it pop up ERROR:Exception in request: org.apache.http.conn.HttpHostConnectException: Connection to http://(my website):80 refused. Does anyone know why this happen? I actually post my web app and database to AWS, those are on cloud now. Anyone met similar before? Thanks</p>

答:
Port : 80 is used by default on some programmes. It is probably in use already.
Try changing to a different port. e.g. port:81</p>


问:
Many to one LSTM input shape
My input data has 10 features and it is taken at 25 different timestamps. My output data consists of class labels. So, basically, I am having a many to one classification problem. </p>

<p>I want to implement an LSTM for this problem. Total training data consists of 10000 data points. How should the input and output format (shape) for this LSTM network be? </p>

答:
In the first layer of the model you should define input_shape=(n_timesteps,n_features). So in your case input_shape = (25,10).

Your actual input to the model will have shape (1000,25,10).

You should also use keras.np_utils.to_categorical to convert your labels to one-hot-encoded vectors, so that they will become vectors with length X, where X is your class number. Every element will be equal to zero, except the one corresponding to the corresponding class.

Hope this helps!

Title: Many to one LSTM input shape

Body:
My input data has 10 features and it is taken at 25 different timestamps. My output data consists of class labels. So, basically, I am having a many to one classification problem.

I want to implement an LSTM for this problem. Total training data consists of 10000 data points. How should the input and output format (shape) for this LSTM network be?


问:
using jquery.noConflict()
I have two files. HTML and .js files. in code.js, I have written jquery code and in HTML file, I am including code.js as following:

```<code><script src="jquery-1.4.2.js"></script>
<script src="jquery.interval.js"></script>
<script src="code.js">
jQuery.noConflict();
var $jcode = jQuery;
</script>
</code>```

in code.js, I have written following:

```<code>jcode(document).ready(function() {
     jcode.interval(checkForms, 2000);
});
</code>```

When I run it, it gives me error as can not read property of interval undefined.
I think there is something wrong with my usage of noConflict. Can you please help?

Thanks

答:
You are assigning jQuerys's $ to $jcode.

Therefore you should be using $jcode and not jcode (e.g $jcode(document).ready())

```<code>$jcode(document).ready(function() {
   $jcode.interval(checkForms, 2000);
});
</code>```

This should work.

Title: using jquery.noConflict()

Body:
I have two files. HTML and .js files. in code.js, I have written jquery code and in HTML file, I am including code.js as following:

in code.js, I have written following:

jcode(document).ready(function() {
     jcode.interval(checkForms, 2000);
});

When I run it, it gives me error as can not read property of interval undefined.
I think there is something wrong with my usage of noConflict. Can you please help?

Thanks

Body:
You are assigning jQuerys's $ to $jcode.

Therefore you should be using $jcode and not jcode (e.g $jcode(document).ready())

$jcode(document).ready(function() {
   $jcode.interval(checkForms, 2000);
});

This should work.


问:
Extract details from dir output in Windows XP using for loop (batch script)
I am trying to understand the for loop in batch scripting; in particular with skip and tokens parameters. I have found a great example in this answer followed by this nice read.

I would like to see how I can extract the date and time from a dir in Windows XP which has a slightly different dir output (see below example outputs) compared to Windows 7. In other words, how to extract creation date of a specific folder in Windows XP.

The following modified code from the above mentioned links correctly extracts the date and time of a DIR in Windows 7 but fails (i.e. extracts other characters) in Windows XP:

```<code>SETLOCAL ENABLEDELAYEDEXPANSION
set "path_of_folder=C:\folderA\folderB"

for /f "skip=5 tokens=1,2,4 delims= " %%a in (
 'dir /ad /tc "%path_of_folder%\."') do IF "%%c"=="." (
  set "dt=%%a"
  set dirdate=%%a
  set dirtime=%%b
  echo !dirdate!, !dirtime!
  set dirday=!dirdate:~0,2!
  echo !dirday!
)
</code>```

In Windows 7 the dir command in the command prompt outputs something similar to:

```<code>   Directory of C:\Windows
12/21/2016  12:56    <DIR>          .
12/21/2016  12:56    <DIR>          ..
09/18/2017  07.42            678    config
</code>```

In Windows XP the dir command in the command prompt outputs something similar to:

```<code>   Directory of C:\WINDOWS

12/21/2016  12:56 PM    <DIR>          .
12/21/2016  12:56 PM    <DIR>          ..
09/18/2017  07.42 PM            678    config
</code>```

The only difference (as far as I can notice) is the PM column(?) which does not exist in Windows 7 but does exist in Windows XP.

I know this is probably a trivial question but I am new in batch scripting and seeing a specific example using a complex for loop would help my understanding. Assume use of delayed expansion.

答:
The dir command time format is dependent on the settings in the control panel.
To get the directory creation time independent from the control panel settings you can use dirtimejs.bat:

```<code>@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set "path_of_folder=C:\folderA\folderB"

for /f "tokens=1* delims=:" %%a in ('dirtimejs.bat "%path_of_folder%" ^| find "Created :"') do (
    for /f "tokens=1,2,3,4,5,6 delims=:- " %%A in ("%%b") do (
        echo dir year: %%A
        echo dir month : %%B
        echo dir day :  %%C
    )
)
</code>```

To see what information dirtimejs try with dirtimejs.bat "%path_of_folder%".

Body:
I am trying to understand the for loop in batch scripting; in particular with skip and tokens parameters. I have found a great example in this answer followed by this nice read.

I would like to see how I can extract the date and time from a dir in Windows XP which has a slightly different dir output (see below example outputs) compared to Windows 7. In other words, how to extract creation date of a specific folder in Windows XP.

The following modified code from the above mentioned links correctly extracts the date and time of a DIR in Windows 7 but fails (i.e. extracts other characters) in Windows XP:

SETLOCAL ENABLEDELAYEDEXPANSION
set "path_of_folder=C:\folderA\folderB"

for /f "skip=5 tokens=1,2,4 delims= " %%a in (
 'dir /ad /tc "%path_of_folder%\."') do IF "%%c"=="." (
  set "dt=%%a"
  set dirdate=%%a
  set dirtime=%%b
  echo !dirdate!, !dirtime!
  set dirday=!dirdate:~0,2!
  echo !dirday!
)

In Windows 7 the dir command in the command prompt outputs something similar to:

   Directory of C:\Windows
12/21/2016  12:56    <DIR>          .
12/21/2016  12:56    <DIR>          ..
09/18/2017  07.42            678    config

In Windows XP the dir command in the command prompt outputs something similar to:

   Directory of C:\WINDOWS

12/21/2016  12:56 PM    <DIR>          .
12/21/2016  12:56 PM    <DIR>          ..
09/18/2017  07.42 PM            678    config

The only difference (as far as I can notice) is the PM column(?) which does not exist in Windows 7 but does exist in Windows XP.

I know this is probably a trivial question but I am new in batch scripting and seeing a specific example using a complex for loop would help my understanding. Assume use of delayed expansion.

Body:
The dir command time format is dependent on the settings in the control panel.
To get the directory creation time independent from the control panel settings you can use dirtimejs.bat:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set "path_of_folder=C:\folderA\folderB"

for /f "tokens=1* delims=:" %%a in ('dirtimejs.bat "%path_of_folder%" ^| find "Created :"') do (
    for /f "tokens=1,2,3,4,5,6 delims=:- " %%A in ("%%b") do (
        echo dir year: %%A
        echo dir month : %%B
        echo dir day :  %%C
    )
)

To see what information dirtimejs try with dirtimejs.bat "%path_of_folder%".


问:
Polymer 2 apply mixin
I'm trying to get a better understanding of using mixins in Polymer 2:  Here is my sample:

```<code><dom-module id="x-test">
    <template>

        <custom-style>
            <style is="custom-style">
                html {

                    --center-on-screen: {
                        left: 50%;
                        top: 50%;
                        position: absolute;
                        border: solid 1px red;
                    };

                }
            </style>
        </custom-style>

        <style>

            .signal {
                border-radius: 30px;
                height: 30px;

                width: 30px;
                @apply --center-on-screen;
            }

        </style>

        <div class="signal"></div>

    </template>

    <script>
        'use strict'

        class XTest extends Polymer.Element {

            static get is() {
                return 'x-test';
            }

            static get properties() {
                return {
                }
            }

            static get observers() {
                return [];
            }

            constructor() {
                super();

            }

            ready() {
                super.ready();

            }

            connectedCallback() {
                super.connectedCallback();
            }

            connectedCallback() {
                super.connectedCallback();
            }

        }

        customElements.define(XTest.is, XTest);
    </script>
</dom-module>
</code>```

when the code @apply --center-on-screen; in the class, I would expect the div to have the color red and be centered on the screen.  I have verified it because I had all the code in --center-on-screen in the class .signal.  I moved it into --center-on-screen just for testing purposes.  If anyone can advise me on what i'm doing incorrectly.

**Update **

When I move --center-on-screen into :host then it works.  So it looks like this

```<code>        <style>

             :host {
                --center-on-screen: {
                    left: 50%;
                    top: 50%;
                    position: absolute;
                    border: solid 1px red;
                }
            }

            .signal {
                border-radius: 30px;
                height: 30px;

                width: 30px;
                border: solid 1px red;
                @apply --center-on-screen;
            }

        </style>
</code>```

答:
Thanks for posting this query. I was searching some credible resource on how to use css mixins in polymer 2.0 .

I had this mixin -

```<code>--calendarbox-mixin: {
  display:flex;
  position:relative;
  flex-direction: column;
  border-radius: 5px;
  --webkit-border-radius:5px;
  --moz-border-radius:5px;
  width:11vw;
  margin:10px 5px;
  text-align: center;
  height:18vh;
  justify-content: space-around;
  }
</code>```

I tried adding it just abover another class where I wanted to use the mixin -

```<code>    .dayfare_box {
      @apply(--calendarbox-mixin);
      background: #fbfcfc;
      border:2px solid #e2e2e2;
    }
</code>```

The output came without the mixin applied. Tried adding in :host and it worked!!

Just stumbled upon this link and it confirmed my doubt whether I was doing it right. Thanks for posting :)

Title: Polymer 2 apply mixin

Body:
I'm trying to get a better understanding of using mixins in Polymer 2:  Here is my sample:

<dom-module id="x-test">
    <template>

        <custom-style>

        </custom-style>

    </template>

</dom-module>

when the code @apply --center-on-screen; in the class, I would expect the div to have the color red and be centered on the screen.  I have verified it because I had all the code in --center-on-screen in the class .signal.  I moved it into --center-on-screen just for testing purposes.  If anyone can advise me on what i'm doing incorrectly.

**Update **

When I move --center-on-screen into :host then it works.  So it looks like this

Body:
Thanks for posting this query. I was searching some credible resource on how to use css mixins in polymer 2.0 .

I had this mixin -

--calendarbox-mixin: {
  display:flex;
  position:relative;
  flex-direction: column;
  border-radius: 5px;
  --webkit-border-radius:5px;
  --moz-border-radius:5px;
  width:11vw;
  margin:10px 5px;
  text-align: center;
  height:18vh;
  justify-content: space-around;
  }

I tried adding it just abover another class where I wanted to use the mixin -

    .dayfare_box {
      @apply(--calendarbox-mixin);
      background: #fbfcfc;
      border:2px solid #e2e2e2;
    }

The output came without the mixin applied. Tried adding in :host and it worked!!

Just stumbled upon this link and it confirmed my doubt whether I was doing it right. Thanks for posting :)


问:
PHP array_search - right way to get values
I have a big CATEGORIES array with structure

```<code>[0] => WP_Term Object ( [term_id] => 1028
[name] => Sale woman
[slug] => sale-woman
[term_group] => 0
[term_taxonomy_id] => 1028)

[1] => WP_Term Object ( [term_id] => 1029
[name] => Sale man
[slug] => sale-man
[term_group] => 0
[term_taxonomy_id] => 1029)...
</code>```

I don't need so many values, i show only part of this array(). So, i create my own array from this array

```<code>$ids = array();
$i = 0;
foreach ( $cats as $key=>$cat ) {

$ids[$i]['id'] = $cat->term_id;
$ids[$i]['catname'] = $cat->name;
$i++;

}
</code>```

It works well and returns me

```<code>Array ( [0] => Array ( [id] => 1028 [catname] => Sale woman )
[1] => Array ( [id] => 1029 [catname] => Sale man ) )...
</code>```

Than i need to find current category in this array and get next and prev ids of categories. I try

```<code>$thisindex = array_search( $this_category_id, $ids['id'] );

$previd = $ids[ $thisindex - 1 ];

$nextid = $ids[ $thisindex + 1 ];
</code>```

But when i try to ECHO $previd or $nextid it returns nothing. $this_category_id works well, i think problem is in array_search( $this_category_id, $ids['id'] );

I try also $ids[]['id'] - cause an error

$ids[$i]['id'] - nothing returns

How to find $previd and $nextid? Need help

答:
Try this

```<code> $array = array_column($ids, 'id'); //array of ID
 $thisindex = array_search( $this_category_id, $array );
</code>```

Or build one yourself in the foreach

```<code>$ids = array();
$array = array();
$i = 0;
foreach ( $cats as $key=>$cat ) {

    $ids[$i]['id'] = $cat->term_id;
    $ids[$i]['catname'] = $cat->name;
    $array[$i] = $cat->term_id;
    $i++;

}
</code>```

Or you can write your own search function.

Your array looks like this

```<code> [
    0 => [ 'id' => 1, ..],
    1 => [ 'id' => 2, ..],
 ]
</code>```

But your search is like this

```<code>['id' => [....]]
</code>```

Well except there is no id in the top array, just 0,1 etc.  And even if there was, id is not of the type of array, but instead probably and Int.

UPDATE

To make the array loop, you have to check if you are before the start and after the end like this:

```<code>$previd = $ids[ $thisindex - 1 ];
$nextid = $ids[ $thisindex + 1 ];
$min = 0;
$max = count( $ids ) - 1;

if( $previd < $min ) $previd = $max;
if( $nextid > $max ) $nextid = $min;
</code>```

if its less then 0 then it equals the count of the array - 1 ( the end ), if it's past the end then it equals the start or ( 0 ) in this case.

Body:
I have a big CATEGORIES array with structure

[0] => WP_Term Object ( [term_id] => 1028
[name] => Sale woman
[slug] => sale-woman
[term_group] => 0
[term_taxonomy_id] => 1028)

[1] => WP_Term Object ( [term_id] => 1029
[name] => Sale man
[slug] => sale-man
[term_group] => 0
[term_taxonomy_id] => 1029)...

I don't need so many values, i show only part of this array(). So, i create my own array from this array

$ids = array();
$i = 0;
foreach ( $cats as $key=>$cat ) {

$ids[$i]['id'] = $cat->term_id;
$ids[$i]['catname'] = $cat->name;
$i++;

}

It works well and returns me

Array ( [0] => Array ( [id] => 1028 [catname] => Sale woman )
[1] => Array ( [id] => 1029 [catname] => Sale man ) )...

Than i need to find current category in this array and get next and prev ids of categories. I try

$thisindex = array_search( $this_category_id, $ids['id'] );

$previd = $ids[ $thisindex - 1 ];

$nextid = $ids[ $thisindex + 1 ];

But when i try to ECHO $previd or $nextid it returns nothing. $this_category_id works well, i think problem is in array_search( $this_category_id, $ids['id'] );

I try also $ids[]['id'] - cause an error

$ids[$i]['id'] - nothing returns

How to find $previd and $nextid? Need help

Body:
Try this

 $array = array_column($ids, 'id'); //array of ID
 $thisindex = array_search( $this_category_id, $array );

Or build one yourself in the foreach

$ids = array();
$array = array();
$i = 0;
foreach ( $cats as $key=>$cat ) {

    $ids[$i]['id'] = $cat->term_id;
    $ids[$i]['catname'] = $cat->name;
    $array[$i] = $cat->term_id;
    $i++;

}

Or you can write your own search function.

Your array looks like this

 [
    0 => [ 'id' => 1, ..],
    1 => [ 'id' => 2, ..],
 ]

But your search is like this

['id' => [....]]

Well except there is no id in the top array, just 0,1 etc.  And even if there was, id is not of the type of array, but instead probably and Int.

UPDATE

To make the array loop, you have to check if you are before the start and after the end like this:

$previd = $ids[ $thisindex - 1 ];
$nextid = $ids[ $thisindex + 1 ];
$min = 0;
$max = count( $ids ) - 1;

if( $previd < $min ) $previd = $max;
if( $nextid > $max ) $nextid = $min;

if its less then 0 then it equals the count of the array - 1 ( the end ), if it's past the end then it equals the start or ( 0 ) in this case.