问:
Attributed text in swift with line alignment
I have a label that has attributed text. I want to achieve something look like this image.
sample label

Subcategory and price text should be left and right alignment respectively and in a single line. There is some space before Subcategory text.
Please provide any sample code for this kind of attributed text.

答:
```<code>let myLabelWidth = 300
let myLabelHeight = 50

let paragraph = NSMutableParagraphStyle()
paragraph.tabStops = [
    NSTextTab(textAlignment: .right, location: CGFloat(myLabelWidth), options: [:]),
]

let attributed = NSAttributedString(
    string: "Subcategory 1\t$30",
    attributes: [NSAttributedStringKey.paragraphStyle: paragraph]
)

// Change 'x' value to "some" space before the text
let myLabel = UILabel(frame: CGRect(x: 0,
                                    y: 0,
                                    width: myLabelWidth,
                                    height: myLabelHeight))

// Just added to see boundaries of the view that contains the text
myLabel.backgroundColor = UIColor.lightGray
myLabel.attributedText = attributed
</code>```


来源: stackexchange

问:
How does CQRS help reduce lock contention, when receivers still need to update their read store?
One of the reasons i'm looking at CQRS is reduce lock contention on my database, so that the writes simply update the normalized structure, and the reads can lookup the data it needs, free from competing writes.

Assuming the following setup:

Write system writing to it's own normalized DB (WriteDb)

Write system publishing message onto bus to raise event

Read system picking up message, updating it's materialized view (seperate ReadDb)

Read system reading from materialized view (ReadDb)

Won't there still be lock contention during step 3 & 4? The read system still needs to update it's copy of the data, which may happen at the same time as the reads, so i just see this as reducing lock contention, due to narrow/less indexes.. but the danger is still there, albeit to a lesser extent.

What are some strategies to help mitigate this issue? (is this an issue, or am i overthinking it?). Is Event Sourcing the only way?

Note: i'm on .NET / SQL .. so bonus points for any answers specific to that stack :)

Thanks

答:
Won't there still be lock contention during step 3 & 4

A lock is involved, even if only at row/document level, but the idea is that writes are happening a lot less frequent than reads so a lock between Write&Read is (sufficient) rare.

but the danger is still there, albeit to a lesser extent

What danger? If you mean that is affecting reading speed then yes, however it is a lot less painful than a multi-table/multi-join lock.

Using CQRS you can (and should) create read-models (tables if you are using SQL) that are self sufficient for a query, i.e. you won't need any join; in this way the query will be faster and the probability of a locked read will be lower.

Is Event Sourcing the only way?

Event sourcing doesn't need to use transactions so a lock is even smaller (faster) than in plain CQRS - that is the reason why ES is faster on the read side.

One other solution is to use an Event log (not an Event store) that is used only as the source of events for the read-models update. One inconvenient is that this is another moving part of your architecture and it also must be kept in sync with the events from the write-models in an asynchronous way (using a thread or something).

Articles about using an Event log:

Event log vs event streams

Event Sourcing - Projections (go to Rebuilding)

ContentLicense: CC BY-SA 3.0


问:
krpano WebVR plugin enable
I need to implement to existing project WebVR plugin.
I have main krpano.xml file which is pointing to krpano skin file.

I added plugins folder which has webvr.xml and webvr.js files with some other files too.

Inside krpano skin.xml file I added:

```<code><include url="plugins/webvr.xml" devices="html5" />
<plugin name="WebVR" mobilevr_fake_support="true" />
</code>```

And inside navigation layer I added:

```<code><layer name="btn_vr" x="300" url="down.png" crop="0|0|38|38" onclick="enterVR()"/>
</code>```

I'm not getting any plugin errors in my console but clicking on button nothing happens.
I would like to get effect like on this example: https://krpano.com/tours/corfu/
where there is a cardboard icon in navigation and clicking on it vr is opened.

Any idea what I'm doing wrong with this?

答:
This might be because of path related issue.
You can try this:

```<code><include url="%SWFPATH%/plugins/webvr.xml" devices="html5" />
<plugin name="WebVR" mobilevr_fake_support="true" />
</code>```

And inside navigation Layer:

```<code><!-- skin_base - the base skin image -->

<style name="skin_base" url="calc:vtourskinxmlpath.url + skin_settings.design_skin_images" />

    <!-- skin_glow - button glowing (if additional ondown,onup,onout,over events are needed, this style provides ondown2,onup2,onover2,onout2 events) -->
            <style name="skin_glow"
                   ondown="copy(skin_lockglow,name); skin_buttonglow(get(name)); if(ondown2, ondown2() );"
                   onover="if(skin_lockglow === null, copy(skin_lockglow,name); skin_buttonglow(get(name),0.3) ); if(onover2, onover2() );"
                   onout="if(skin_lockglow === name AND !pressed, skin_buttonglow(null);delete(skin_lockglow); ); if(onout2, onout2() );"
                   onup="if(onup2, onup2()); delayedcall(0, if(hovering AND enabled, skin_buttonglow(get(name),0.3); , skin_buttonglow(null);delete(skin_lockglow); ); );"
                   />

    <layer name="skin_btn_vr" style="skin_base|skin_glow" crop="0|0|80|64"    align="center" x="+146" y="0" scale="0.5" onclick="webvr.enterVR();" visible="false" />
</code>```

Title: krpano WebVR plugin enable

Body:
I need to implement to existing project WebVR plugin.
I have main krpano.xml file which is pointing to krpano skin file.

I added plugins folder which has webvr.xml and webvr.js files with some other files too.

Inside krpano skin.xml file I added:

<include url="plugins/webvr.xml" devices="html5" />
<plugin name="WebVR" mobilevr_fake_support="true" />

And inside navigation layer I added:

<layer name="btn_vr" x="300" url="down.png" crop="0|0|38|38" onclick="enterVR()"/>

I'm not getting any plugin errors in my console but clicking on button nothing happens.
I would like to get effect like on this example: https://krpano.com/tours/corfu/
where there is a cardboard icon in navigation and clicking on it vr is opened.

Any idea what I'm doing wrong with this?

Body:
This might be because of path related issue.
You can try this:

<include url="%SWFPATH%/plugins/webvr.xml" devices="html5" />
<plugin name="WebVR" mobilevr_fake_support="true" />

And inside navigation Layer:

<!-- skin_base - the base skin image -->

<style name="skin_base" url="calc:vtourskinxmlpath.url + skin_settings.design_skin_images" />

    <!-- skin_glow - button glowing (if additional ondown,onup,onout,over events are needed, this style provides ondown2,onup2,onover2,onout2 events) -->
            <style name="skin_glow"
                   ondown="copy(skin_lockglow,name); skin_buttonglow(get(name)); if(ondown2, ondown2() );"
                   onover="if(skin_lockglow === null, copy(skin_lockglow,name); skin_buttonglow(get(name),0.3) ); if(onover2, onover2() );"
                   onout="if(skin_lockglow === name AND !pressed, skin_buttonglow(null);delete(skin_lockglow); ); if(onout2, onout2() );"
                   onup="if(onup2, onup2()); delayedcall(0, if(hovering AND enabled, skin_buttonglow(get(name),0.3); , skin_buttonglow(null);delete(skin_lockglow); ); );"
                   />

    <layer name="skin_btn_vr" style="skin_base|skin_glow" crop="0|0|80|64"    align="center" x="+146" y="0" scale="0.5" onclick="webvr.enterVR();" visible="false" />


问:
Why is vector deleting destructor being called as a result of a scalar delete?
I have some code that is crashing in a large system.
However, the code essentially boils down to the following pseudo-code.
I've removed much of the detail, as I have tried to boil this down to the bare bones;
I don't think this misses anything crucial though.

```<code>// in a DLL:

#ifdef _DLL
#define DLLEXP __declspec(dllexport)
#else
#define DLLEXP __declspec(dllimport)
#endif

class DLLEXP MyClass // base class; virtual
{
public:
  MyClass() {};
  virtual ~MyClass() {};

  some_method () = 0; // pure virtual

  // no member data
};

class DLLEXP MyClassImp : public MyClass
{
public:
  MyClassImp( some_parameters )
  {
    // some assignments...
  }

  virtual ~MyClassImp() {};

private:
  // some member data...
};
</code>```

and:

```<code>// in the EXE:

MyClassImp* myObj = new MyClassImp ( some_arguments ); // scalar new
// ... and literally next (as part of my cutting-down)...
delete myObj; // scalar delete
</code>```

Note that matching scalar new and scalar delete are being used.

In a Debug build in Visual Studio (2008 Pro),
in Microsoft's <dbgheap.c>,
the following assertion fails:

```<code>_ASSERTE(_CrtIsValidHeapPointer(pUserData));
</code>```

Near the top of the stack are the following items:

```<code>mydll_d.dll!operator delete()
mydll_d.dll!MyClassImp::`vector deleting destructor'()
</code>```

I think this ought to be

```<code>mydll_d.dll!MyClassImp::`scalar deleting destructor'()
</code>```

That is, the program is behaving as if I'd written

```<code>MyClassImp* myObj = new MyClassImp ( some_arguments );
delete[] newObj; // array delete
</code>```

The address in pUserData is that of myObj itself (as opposed to a member).
The memory around that address looks like this:

```<code>                                ... FD FD FD FD
(address here)
VV VV VV VV MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
FD FD FD FD AB AB AB AB AB AB AB AB EE FE EE FE
...
</code>```

where the four VVs are presumably the address of the virtual function table,
the MM...MM is recognisable member data,
and the other bytes are various special markers put in place by the debugger
(e.g. the FD FDs are 'guard bytes' around the object's storage).

Shortly before the assertion failure I do see the VVs change,
and wonder if that is due to a switch to the base class's virtual function table.

I'm aware of the problem of the wrong level in the class hierarchy undergoing destruction.
That's not the problem here; my destructors are all virtual.

I note Microsoft's page
"BUG: Wrong Operator Delete Called for Exported Class"
http://support.microsoft.com/kb/122675
but that seems to be regarding the wrong executable (with the wrong heap) attempting to take responsibility for destruction of the data.

In my case, it's that the wrong 'flavour' of deleting destructor appears to be being applied:
i.e. vector rather than scalar.

I am in the process of trying to produce minimal cut-down code that still exhibits the problem.

However, any hints or tips to help with how to investigate this problem further would be much appreciated.

Perhaps the biggest clue here is the mydll_d.dll!operator delete() on the stack.
Should I expect this to be myexe_d.exe!operator delete(),
indicating that the DLLEXPs have been 'lost'?

I suppose this could be an instance of a double-delete (but I don't think so).

Is there a good reference I can read regarding what _CrtIsValidHeapPointer checks for?

答:
This behavior is special to MSVC 9, where the delete operator for a exported class, that has a virtual destructor is implicitly generated and mangled to vector dtor with an associated flag, where 1 means (scalar) and 3 means (vector).

The true problem with this thing is, that it breaks the canonical form of new/delete, where the client coder is not able to disable the vector delete operator in its code, if he thinks, that it is a bad idea to use it.

Moreover the vector dtor, also seems to be executed wrong, if the new is allocated in another module than the module the implementation resides in and is then hold in a static variable via a reference count, which executes a delete this (here the vector dtor comes into play) on process shutdown.

This matches to the heap problem 'bshields' already mentioned before, the dtor is executed on the wrong heap and the code crahses either with 'cannot read that memory location' or 'access violation' on shutdown - such problems seem to be very common.

The only way around this bug, is to forbid the usage of a virtual destructor and execute it your own, by enforcing the usage of a delete_this function from the base class - stupid as it is you imitate the stuff the virtual dtor should do for you. Then also the scalar dtor is executed and on shutdown any ref counted objects shared between modules, can be instantiated in a safe way, because heap is always addressed correctly to the origin module.

To check, if you have such problems, simply forbid the usage of the vector delete operator.

ContentLicense: CC BY-SA 2.5

Body:
I have some code that is crashing in a large system.
However, the code essentially boils down to the following pseudo-code.
I've removed much of the detail, as I have tried to boil this down to the bare bones;
I don't think this misses anything crucial though.

// in a DLL:

#ifdef _DLL
#define DLLEXP __declspec(dllexport)
#else
#define DLLEXP __declspec(dllimport)
#endif

class DLLEXP MyClass // base class; virtual
{
public:
  MyClass() {};
  virtual ~MyClass() {};

  some_method () = 0; // pure virtual

  // no member data
};

class DLLEXP MyClassImp : public MyClass
{
public:
  MyClassImp( some_parameters )
  {
    // some assignments...
  }

  virtual ~MyClassImp() {};

private:
  // some member data...
};

and:

// in the EXE:

MyClassImp* myObj = new MyClassImp ( some_arguments ); // scalar new
// ... and literally next (as part of my cutting-down)...
delete myObj; // scalar delete

Note that matching scalar new and scalar delete are being used.

In a Debug build in Visual Studio (2008 Pro),
in Microsoft's <dbgheap.c>,
the following assertion fails:

_ASSERTE(_CrtIsValidHeapPointer(pUserData));

Near the top of the stack are the following items:

mydll_d.dll!operator delete()
mydll_d.dll!MyClassImp::`vector deleting destructor'()

I think this ought to be

mydll_d.dll!MyClassImp::`scalar deleting destructor'()

That is, the program is behaving as if I'd written

MyClassImp* myObj = new MyClassImp ( some_arguments );
delete[] newObj; // array delete

The address in pUserData is that of myObj itself (as opposed to a member).
The memory around that address looks like this:

                                ... FD FD FD FD
(address here)
VV VV VV VV MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
FD FD FD FD AB AB AB AB AB AB AB AB EE FE EE FE
...

where the four VVs are presumably the address of the virtual function table,
the MM...MM is recognisable member data,
and the other bytes are various special markers put in place by the debugger
(e.g. the FD FDs are 'guard bytes' around the object's storage).

Shortly before the assertion failure I do see the VVs change,
and wonder if that is due to a switch to the base class's virtual function table.

I'm aware of the problem of the wrong level in the class hierarchy undergoing destruction.
That's not the problem here; my destructors are all virtual.

I note Microsoft's page
"BUG: Wrong Operator Delete Called for Exported Class"
http://support.microsoft.com/kb/122675
but that seems to be regarding the wrong executable (with the wrong heap) attempting to take responsibility for destruction of the data.

In my case, it's that the wrong 'flavour' of deleting destructor appears to be being applied:
i.e. vector rather than scalar.

I am in the process of trying to produce minimal cut-down code that still exhibits the problem.

However, any hints or tips to help with how to investigate this problem further would be much appreciated.

Perhaps the biggest clue here is the mydll_d.dll!operator delete() on the stack.
Should I expect this to be myexe_d.exe!operator delete(),
indicating that the DLLEXPs have been 'lost'?

I suppose this could be an instance of a double-delete (but I don't think so).

Is there a good reference I can read regarding what _CrtIsValidHeapPointer checks for?


问:
Transfer the Pop-up message to the specific location
Can Anyone solve this problem?pop-up message

I have this code below

```<code><body>
     <div class="contact-form-wrap responsive">

          <!--- pop-up message start --->
                <div class="status alert alert-success contact-status"></div>
          <!--- pop-up message end --->

                    <form id="main-contact-form4" class="contact-form" name="contact-form" method="post" action="app.php" role="form">

                    <legend style="padding-bottom: 20px; color: #708090;">Please provide us your information.</legend>

                            <!-- Name Filed Starts -->
                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <div class="input-group">
                                             <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                                                <input type="text" class="form-control" name="name" id="name" required="required" placeholder="Full Name">
                                        </div>
                                    </div>
                                </div>
                            <!-- Name Filed Ends -->

            <!---------------- Pop-up Message here ---------------->

                            <!-- Button starts -->
                                <div class="col-sm-12">
                                    <div class="form-group">
                                        <button type="submit" class="btn btn-primary btn-block">Submit</button>
                                    </div>
                                </div>
                            <!-- Button Ends -->
                   </form>
                </div>
             </div>
          </body>
</code>```

I like to move my pop-up message on the top of the button. so every time the button will press the pop-up message will notice immediately.

here is my js

```<code> $(".contact-form").submit(function() {
    var rd = this;
    var url = "app.php";
    $.ajax({
        type: "POST",
        url: url,
        data: $(".contact-form").serialize(),
        success: function(data) {
            $(rd).prev().text(data.message).fadeIn();
        }
    });
    return false;
});
</code>```

答:
The problem with your code is that you're selecting the popup message based on it's location in the DOM. You need to select it on a proper selector instead. Since it has a class called contact-status, let's use that.

Change:

```<code>$(rd).prev().text(data.message).fadeIn();
</code>```

to

```<code>$('.contact-status').text(data.message).fadeIn();
</code>```

It's a bad idea to select elements from their location in the DOM since you sometimes (like now) want to move them. Using proper selectors (like id's or classes) will keep your code working regardless where in the DOM the element is.

Body:
Can Anyone solve this problem?pop-up message

I have this code below

                    <form id="main-contact-form4" class="contact-form" name="contact-form" method="post" action="app.php" role="form">

                    <legend style="padding-bottom: 20px; color: #708090;">Please provide us your information.</legend>

                                                <input type="text" class="form-control" name="name" id="name" required="required" placeholder="Full Name">

                                        <button type="submit" class="btn btn-primary btn-block">Submit</button>

                   </form>

I like to move my pop-up message on the top of the button. so every time the button will press the pop-up message will notice immediately.

here is my js

 $(".contact-form").submit(function() {
    var rd = this;
    var url = "app.php";
    $.ajax({
        type: "POST",
        url: url,
        data: $(".contact-form").serialize(),
        success: function(data) {
            $(rd).prev().text(data.message).fadeIn();
        }
    });
    return false;
});

Body:
The problem with your code is that you're selecting the popup message based on it's location in the DOM. You need to select it on a proper selector instead. Since it has a class called contact-status, let's use that.

Change:

$(rd).prev().text(data.message).fadeIn();

to

$('.contact-status').text(data.message).fadeIn();

It's a bad idea to select elements from their location in the DOM since you sometimes (like now) want to move them. Using proper selectors (like id's or classes) will keep your code working regardless where in the DOM the element is.


问:
Direction arrow does not show, but polyline is showing in google map
I am trying to draw the direction arrows for my poly line.
My code does not show arrows but plots every markers with info windows and the poly line using my data set.
I want to add arrows like this.
http://jsfiddle.net/nX8U8/2/
Here is my code with .done function of ajax callback.

Can someone explain me what was the wrong I done.

var path1 = [];
    var poliLine;

```<code>function getData(){

    $.ajax({
        url: '/filter',
        dataType:'json',
        type: 'POST',
        data: {'mmsi':$('input[name=mmsi]').val(),'from': $("input[name='from']").val(), 'to': $("input[name='to']").val()}

    }).done(function(data) {
        initMap();
        console.log(data.length);
        console.log(data);
        $.each(data, function(index, obj){
            console.log( obj.latitude +  " - " +obj.longitude   );
            //console.log("helloooo");
            var pos = {lat: obj.latitude, lng: obj.longitude};
            path1.push({lat: parseFloat(obj.latitude), lng: parseFloat(obj.longitude)});

            contentString = "<p>" +obj.last_received_date+ "<br>"+obj.last_received_time+"</p>";
            var infowindow = new google.maps.InfoWindow({
                content: contentString
            });
            var circleIcon = {
                path: google.maps.SymbolPath.CIRCLE,
                fillColor: '#600d48',
                fillOpacity: 0.8,
                scale: 2,
                strokeColor: '#600d48'
            };
            var pathMarker = new google.maps.Marker({
                position: pos,
                icon: circleIcon,
                map: map
            });
            pathMarker.addListener('mouseover', function() {
                infowindow.open(map, pathMarker);
            });
            // assuming you also want to hide the infowindow when user mouses-out
            pathMarker.addListener('mouseout', function() {
                infowindow.close();
            });

        });
        var lineSymbol = {
            path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
        };

        var polylineoptns = {
            strokeOpacity: 0.8,
            strokeWeight: 3,
            path: path1,
            strokeColor: '#FF0000',
            strokeOpacity: 1.0,
            map: map,
            icons: [{
                icon: lineSymbol,
                repeat: '70px',
                offset: '100%'
            }],
        };
        polyline = new google.maps.Polyline(polylineoptns);

        path1 = [];

    }).always(function() {

    }).fail(function(jqXHR, textStatus, errorThrown) {
        alert('Error: ' + errorThrown);
    })

}
</code>```

答: I could do it by plotting the arrow icon as a marker with the rotation of bearing which is the attribute of the location updates by Google.</p>

Body:
I am trying to draw the direction arrows for my poly line.
My code does not show arrows but plots every markers with info windows and the poly line using my data set.
I want to add arrows like this.
http://jsfiddle.net/nX8U8/2/
Here is my code with .done function of ajax callback.

Can someone explain me what was the wrong I done.

var path1 = [];
    var poliLine;

function getData(){

    $.ajax({
        url: '/filter',
        dataType:'json',
        type: 'POST',
        data: {'mmsi':$('input[name=mmsi]').val(),'from': $("input[name='from']").val(), 'to': $("input[name='to']").val()}

    }).done(function(data) {
        initMap();
        console.log(data.length);
        console.log(data);
        $.each(data, function(index, obj){
            console.log( obj.latitude +  " - " +obj.longitude   );
            //console.log("helloooo");
            var pos = {lat: obj.latitude, lng: obj.longitude};
            path1.push({lat: parseFloat(obj.latitude), lng: parseFloat(obj.longitude)});

            contentString = "
" +obj.last_received_date+ "
"+obj.last_received_time+"
";
            var infowindow = new google.maps.InfoWindow({
                content: contentString
            });
            var circleIcon = {
                path: google.maps.SymbolPath.CIRCLE,
                fillColor: '#600d48',
                fillOpacity: 0.8,
                scale: 2,
                strokeColor: '#600d48'
            };
            var pathMarker = new google.maps.Marker({
                position: pos,
                icon: circleIcon,
                map: map
            });
            pathMarker.addListener('mouseover', function() {
                infowindow.open(map, pathMarker);
            });
            // assuming you also want to hide the infowindow when user mouses-out
            pathMarker.addListener('mouseout', function() {
                infowindow.close();
            });

        });
        var lineSymbol = {
            path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
        };

        var polylineoptns = {
            strokeOpacity: 0.8,
            strokeWeight: 3,
            path: path1,
            strokeColor: '#FF0000',
            strokeOpacity: 1.0,
            map: map,
            icons: [{
                icon: lineSymbol,
                repeat: '70px',
                offset: '100%'
            }],
        };
        polyline = new google.maps.Polyline(polylineoptns);

        path1 = [];

    }).always(function() {

    }).fail(function(jqXHR, textStatus, errorThrown) {
        alert('Error: ' + errorThrown);
    })

}


问:
systemctl daemon reload without ssh to the node
I am working on s3 storage and kubernetes technologies and I have a scenario where we need to do a systemctl dameon-reload after  the driver binary is copied. How can this be done from a privileged pod without doing ssh to the worker node.

答:
I don't have the code in front of me, but I had great success using CoreOS/go-systemd and volume mounting /var/lib/dbus (IIRC) into a privileged container (as you already mentioned)

My use case was to do this in a DaemonSet, so every Node did it, but if you wish to target just one node, then spec: nodeName: of the PodSpec would enable you to schedule on that one specific Node

I will try to remember to update this with a gist containing the tl;dr of the go binary


问:
test-path not working when in a scheduled task
I have a script to return the list of database backup files on a number of remote database servers.

I use Test-Path to check if the UNC path exists, if it exists it returns the list of files using Get-ChildItem.

When I test this script the Test-Path works at a command prompt but when I run the script in a Scheduled Task it always returns FALSE.

I have tried a number of different ways to use Test-Path but none of them work.
The script runs under the same account at the command prompt and for the Schedule task.

The schedule task runs with highest privileges and whether the user is logged on or not.

The script is located on a script server and is called via UNC, it was tested this way at the command prompt and in the scheduled task on a MSSQL Database Server.

```<code>if(test-path -path "filesystem::$TargetUNCFolder") {
    ... Do Something
}
</code>```

and

```<code>$LocalUNCFolderExists = test-path -path $TargetUNCFolder
if($LocalUNCFolderExists -eq $true) {
    ... Do Something
}
</code>```

and

```<code>if($(try {test-path -path $TargetUNCFolder} catch {$false})) {
    ... Do Something
}
</code>```

If I bypass the Test-Path and allow it to drop to the Get-childItem, it returns the number of items correctly but the Foreach does not iterate through the list returned from  Get-ChildItem, this again is only if it is ran in a Scheduled task

```<code># Add an underscore to the current database name
$DatabaseName = "$DbName" + "_"

# Get all files with the <Database name> followed by an underscore
$LocalFiles = gci $TargetUNCFolder -Include $DatabaseName* -Recurse -File | Sort CreationTime -Descending  | Select fullname, name, Directory, Extension, Length, LastWriteTime

# Get the number of files
$FilesOnLocalServer = @($LocalFiles).count;

# Log the number of files, using the custom log function
Log-Output($LogFile) ("Number of files on server: $FilesOnLocalServer");

# Loop through the files
foreach($Backupfile in $LocalFiles) {
    ... Do Something
}
</code>```

Nothing else in the script fails when called from the scheduled task, just anything to do with reading files from the file-system.

Edit Question:
The code with just the relevant parts

```<code>  #For each server instance in the list, check and gather Server, Instancce and Database data
    foreach ($Row in $DataSetServerList.Tables[0].Rows) {
         # ...
        $ServerName = $($Row[1]).Trim()    # The current server's name
        ...
        $InstanceName = $($Row[3]).Trim()  # The current instances's name

    # ... Scan server

    $TargetUNCFolder = "\\$ServerName\BackupsFull$\$InstanceName\"
    for ($i=0;$i -lt $DataSetServerDatabases.tables.count;$i++){
        foreach($Database in $DataSetServerDatabases.Tables[$i].rows) {
            #...
            $DbName  = $($Database[0])
            # ...

            # Check the the UNC path exists
            # *** Always returns false when ran in a scheduled task
            if(test-path -path "filesystem::$TargetUNCFolder") {

                # Add an underscore to the current database name
                $DatabaseName = "$DbName" + "_"

                # Get all files with the <Database name> followed by an underscore
                # *** Doesn't return a List of files when ran in a scheduled task
                $LocalFiles = gci $TargetUNCFolder -Include $DatabaseName* -Recurse -File | Sort CreationTime -Descending  | Select fullname, name, Directory, Extension, Length, LastWriteTime

                # Get the number of files
                $FilesOnLocalServer = @($LocalFiles).count;

                # Log the number of files, using the custom log function
                Log-Output($LogFile) ("Number of files on server: $FilesOnLocalServer");

                # Loop through the files
                foreach($Backupfile in $LocalFiles) {
                    # ... Do Something

                }
            }
        }
    }
}
</code>```

答:
Just bumped into this. Instead of Test-Path I used

[System.IO.File]::Exists('\\srv\c$\target_file')

Body:
I have a script to return the list of database backup files on a number of remote database servers.

I use Test-Path to check if the UNC path exists, if it exists it returns the list of files using Get-ChildItem.

When I test this script the Test-Path works at a command prompt but when I run the script in a Scheduled Task it always returns FALSE.

I have tried a number of different ways to use Test-Path but none of them work.
The script runs under the same account at the command prompt and for the Schedule task.

The schedule task runs with highest privileges and whether the user is logged on or not.

The script is located on a script server and is called via UNC, it was tested this way at the command prompt and in the scheduled task on a MSSQL Database Server.

if(test-path -path "filesystem::$TargetUNCFolder") {
    ... Do Something
}

and

$LocalUNCFolderExists = test-path -path $TargetUNCFolder
if($LocalUNCFolderExists -eq $true) {
    ... Do Something
}

and

if($(try {test-path -path $TargetUNCFolder} catch {$false})) {
    ... Do Something
}

If I bypass the Test-Path and allow it to drop to the Get-childItem, it returns the number of items correctly but the Foreach does not iterate through the list returned from  Get-ChildItem, this again is only if it is ran in a Scheduled task

# Add an underscore to the current database name
$DatabaseName = "$DbName" + "_"

# Get all files with the <Database name> followed by an underscore
$LocalFiles = gci $TargetUNCFolder -Include $DatabaseName* -Recurse -File | Sort CreationTime -Descending  | Select fullname, name, Directory, Extension, Length, LastWriteTime

# Get the number of files
$FilesOnLocalServer = @($LocalFiles).count;

# Log the number of files, using the custom log function
Log-Output($LogFile) ("Number of files on server: $FilesOnLocalServer");

# Loop through the files
foreach($Backupfile in $LocalFiles) {
    ... Do Something
}

Nothing else in the script fails when called from the scheduled task, just anything to do with reading files from the file-system.

Edit Question:
The code with just the relevant parts

  #For each server instance in the list, check and gather Server, Instancce and Database data
    foreach ($Row in $DataSetServerList.Tables[0].Rows) {
         # ...
        $ServerName = $($Row[1]).Trim()    # The current server's name
        ...
        $InstanceName = $($Row[3]).Trim()  # The current instances's name

    # ... Scan server

    $TargetUNCFolder = "\\$ServerName\BackupsFull$\$InstanceName\"
    for ($i=0;$i -lt $DataSetServerDatabases.tables.count;$i++){
        foreach($Database in $DataSetServerDatabases.Tables[$i].rows) {
            #...
            $DbName  = $($Database[0])
            # ...

            # Check the the UNC path exists
            # *** Always returns false when ran in a scheduled task
            if(test-path -path "filesystem::$TargetUNCFolder") {

                # Add an underscore to the current database name
                $DatabaseName = "$DbName" + "_"

                # Get all files with the <Database name> followed by an underscore
                # *** Doesn't return a List of files when ran in a scheduled task
                $LocalFiles = gci $TargetUNCFolder -Include $DatabaseName* -Recurse -File | Sort CreationTime -Descending  | Select fullname, name, Directory, Extension, Length, LastWriteTime

                # Get the number of files
                $FilesOnLocalServer = @($LocalFiles).count;

                # Log the number of files, using the custom log function
                Log-Output($LogFile) ("Number of files on server: $FilesOnLocalServer");

                # Loop through the files
                foreach($Backupfile in $LocalFiles) {
                    # ... Do Something

                }
            }
        }
    }
}


问:
How to get index and the range of a div element from a group of divs using jQuery
If I have a group of tokenized divs like the following.

```<code><script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<div> Barrack </div>
<div> Obama </div>
<div> was </div>
<div> the </div>
<div> president </div>
<div> of </div>
<div> the </div>
<div> United </div>
<div> States </div>
<div> from </div>
<div> the </div>
<div> year </div>
<div> 2012 </div>
<div> to </div>
<div> 2016 </div>
<div> . </div>

<button id="btnClick"> Click me </button>

<script>
$(function(){

$('#btnClick').click(function(){
var selection = window.getSelection();
alert(selection);
});

});
</script>
</code>```

I have tried the above

1) I want to get the index of divs when I click on multiple divs on mouse click event.
Example is if I click on div which contains Barrack and 2012, I am not able to get the selected div's index.

2) If I select the div which contains both Barrack and Obama
I want the range of the div, something like:
startIndex -> 0 and length -> 2.
Where startIndex = "Barrack" is the 0th div and it ranges 2 divs Barrack and Obama.

答:
Something like this should do the trick. Is this what you want?

```<code>  var selectedDiv = [];

  $("div").click(function() {
    selectedDiv.push($(this).text());
  });
</code>```

EDIT

Get the index of div

```<code> var indexNo = $("div").index($(this));
</code>```

$(function() {
  var selectedDiv = [];

  $("div").click(function() {
    $(this).addClass("selected");
    var indexNo = $("div").index($(this));
    selectedDiv.push(indexNo);
    // selectedDiv.push($(this).text());
  });

  $('#btnClick').click(function() {
    // var selection = window.getSelection();
    alert(selectedDiv);
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  width: 100px;
  background: #00f;
  color: #fff;
  margin: 3px;
  cursor: pointer;
}
div.selected {
  background: #f0f;
}</code>```

 Barrack

 Obama

 was

 the

 president

 of

 the

 United

 States

 from

 the

 year

 2012

 to

 2016

 .

<button id="btnClick"> Click me </button>```

Body:
If I have a group of tokenized divs like the following.

 Barrack

 Obama

 was

 the

 president

 of

 the

 United

 States

 from

 the

 year

 2012

 to

 2016

 .

<button id="btnClick"> Click me </button>

I have tried the above

1) I want to get the index of divs when I click on multiple divs on mouse click event.
Example is if I click on div which contains Barrack and 2012, I am not able to get the selected div's index.

2) If I select the div which contains both Barrack and Obama
I want the range of the div, something like:
startIndex -> 0 and length -> 2.
Where startIndex = "Barrack" is the 0th div and it ranges 2 divs Barrack and Obama.

Body:
Something like this should do the trick. Is this what you want?

  var selectedDiv = [];

  $("div").click(function() {
    selectedDiv.push($(this).text());
  });

EDIT

Get the index of div

 var indexNo = $("div").index($(this));

$(function() {
  var selectedDiv = [];

  $("div").click(function() {
    $(this).addClass("selected");
    var indexNo = $("div").index($(this));
    selectedDiv.push(indexNo);
    // selectedDiv.push($(this).text());
  });

  $('#btnClick').click(function() {
    // var selection = window.getSelection();
    alert(selectedDiv);
  });

});

div {
  width: 100px;
  background: #00f;
  color: #fff;
  margin: 3px;
  cursor: pointer;
}
div.selected {
  background: #f0f;
}

<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<div> Barrack </div>
<div> Obama </div>
<div> was </div>
<div> the </div>
<div> president </div>
<div> of </div>
<div> the </div>
<div> United </div>
<div> States </div>
<div> from </div>
<div> the </div>
<div> year </div>
<div> 2012 </div>
<div> to </div>
<div> 2016 </div>
<div> . </div>

<button id="btnClick"> Click me </button>


问:
How to feed array of user_ids to flickr.people.getInfo()?
I have been working on extracting the flickr users location (not lat. and long. but person's country) by using their user_ids. I have made a dataframe (Here's the dataframe) consisted with photo id, owner  and few other columns. My attempt was to feed each of the owner to flickr.people.getInfo() query by iterating owner column in dataframe. Here is my attempt

```<code>for index, row in df.iterrows():
     A=np.array(df["owner"])
for i in range(len(A)):
    B=flickr.people.getInfo(user_id=A[i])
</code>```

unfortunately, it results only 1 result. After careful examination I've found that it belongs to the last user in the dataframe. My dataframe has 250 observations. I don't know how could I extract others.
Any help is appreciated.

答:
It seems like you forgot to store the results while iterating over the dataframe. I haven't use the API but I think that this snippet should do it.

result_dict = {}
for idx, owner in df['owner'].iteritems():
    result_dict[owner] = flickr.people.getInfo(user_id=owner)
```

<p>The results are stored in a dictonary where the user id is the key.</p>

<p>EDIT:</p>

<p>Since it is a JSON you can use the read_json function to parse the result.
Example:  </p>

<pre class="lang-py prettyprint-override"><code>result_list = []
for idx, owner in df['owner'].iteritems():
    result_list.appen(pd.read_json(json.dumps(flickr.people.getInfo(user_id=owner)),orient=list))
    # you may have to set the orient parameter.
    # Option are: 'split','records','index', Default is 'index'
</code>```

Note: I switched the dictonary to a list, since it is more convenient

Afterwards you can concatenate the resulting pandas serieses together like this:

df = pd.concat(result_list, axis=1).transpose()
```

I added the transpose() since you probably want the ID as the index.
Afterwards you should be able to sort by the column 'location'.
Hope that helps.

Body:
I have been working on extracting the flickr users location (not lat. and long. but person's country) by using their user_ids. I have made a dataframe (Here's the dataframe) consisted with photo id, owner  and few other columns. My attempt was to feed each of the owner to flickr.people.getInfo() query by iterating owner column in dataframe. Here is my attempt

for index, row in df.iterrows():
     A=np.array(df["owner"])
for i in range(len(A)):
    B=flickr.people.getInfo(user_id=A[i])

unfortunately, it results only 1 result. After careful examination I've found that it belongs to the last user in the dataframe. My dataframe has 250 observations. I don't know how could I extract others.
Any help is appreciated.

Body:
It seems like you forgot to store the results while iterating over the dataframe. I haven't use the API but I think that this snippet should do it.

result_dict = {}
for idx, owner in df['owner'].iteritems():
    result_dict[owner] = flickr.people.getInfo(user_id=owner)

The results are stored in a dictonary where the user id is the key.

EDIT:

Since it is a JSON you can use the read_json function to parse the result.
Example:

result_list = []
for idx, owner in df['owner'].iteritems():
    result_list.appen(pd.read_json(json.dumps(flickr.people.getInfo(user_id=owner)),orient=list))
    # you may have to set the orient parameter.
    # Option are: 'split','records','index', Default is 'index'

Note: I switched the dictonary to a list, since it is more convenient

Afterwards you can concatenate the resulting pandas serieses together like this:

df = pd.concat(result_list, axis=1).transpose()

I added the transpose() since you probably want the ID as the index.
Afterwards you should be able to sort by the column 'location'.
Hope that helps.


问:
accurately timing an execution of a system call using perl
Is there a better way programmatically using perl to track the timing of a unix process (start time, end time)??

For example, I have a perl script that launches a unix command using system(). I print the timestamp before the system() and after.

My log of the start time and end time are the same. I know for sure that when the process completes its a matter of minutes, so its not accurate.

Here's my code thus far:

```<code>my $dt  = strftime('%Y%m%d', localtime(time));
my $dt2 = strftime('%Y%m%d-%H:%M:%S', localtime(time));
my @tbls = qx(mysql -u foo -pmypw --database $dbsrc -h $node -ss -e "show tables");

open (CRLOG, ">dump-$dt.log") || die "cannot append";
foreach my $tbls (@tbls)
{
   chomp $tbls;
   print CRLOG "TIME START => $dt2\n";
   my $crfile = qq{mysql -u foo -pmypw --database $dbsrc -h $node.test.com -ss -e "SELECT 'a','b','c' UNION SELECT 1,2,3 FROM $tbls"| tr "\t" ",">$node-$tbls.$dt.csv};   system($crfile);
   print CRLOG "COMMAND => $crfile\n";
   print CRLOG "TIME END => $dt2\n";
};
close (CRLOG);
</code>```

答:
Have you tried using the "time" command to time the command execution?

http://www.computerhope.com/unix/utime.htm

So in your perl script it would be something like this to capture the output:

```<code>$time_me = `/usr/bin/time $my_command`;
</code>```

Then parse the $time_me variable to get the values.

Body:
Is there a better way programmatically using perl to track the timing of a unix process (start time, end time)??

For example, I have a perl script that launches a unix command using system(). I print the timestamp before the system() and after.

My log of the start time and end time are the same. I know for sure that when the process completes its a matter of minutes, so its not accurate.

Here's my code thus far:

my $dt  = strftime('%Y%m%d', localtime(time));
my $dt2 = strftime('%Y%m%d-%H:%M:%S', localtime(time));
my @tbls = qx(mysql -u foo -pmypw --database $dbsrc -h $node -ss -e "show tables");

open (CRLOG, ">dump-$dt.log") || die "cannot append";
foreach my $tbls (@tbls)
{
   chomp $tbls;
   print CRLOG "TIME START => $dt2\n";
   my $crfile = qq{mysql -u foo -pmypw --database $dbsrc -h $node.test.com -ss -e "SELECT 'a','b','c' UNION SELECT 1,2,3 FROM $tbls"| tr "\t" ",">$node-$tbls.$dt.csv};   system($crfile);
   print CRLOG "COMMAND => $crfile\n";
   print CRLOG "TIME END => $dt2\n";
};
close (CRLOG);

Body:
Have you tried using the "time" command to time the command execution?

http://www.computerhope.com/unix/utime.htm

So in your perl script it would be something like this to capture the output:

$time_me = `/usr/bin/time $my_command`;

Then parse the $time_me variable to get the values.


问:
Drools Decision Tables
I have created a Decision Table, but I keep on getting this error.

Data cell C11 has an empty column header

My xls DT.

Any advice?

Thanks

答:
Read Section 6.5.4, Spreadsheet Syntax, of the Drools Manual very carefully. Below RuleTable you need four (4) rows: one row with headers like CONDITION; below that one cell with a pattern; below that one cell for the constraint expression and then one row for a comment cell.

You have five rows.

To combine two or more patterns, use two or more columns. See the examples in that section.

Edit Code to compile a spreadsheet and display the generated DRL:

```<code>private void testSpreadsheet( String dtPath ){
  File dtf = new File( dtPath );
  InputStream is;
  try {
    is = new FileInputStream( dtf );
    SpreadsheetCompiler ssComp = new SpreadsheetCompiler();
    String s = ssComp.compile( is, InputType.XLS );
    System.out.println( "=== Begin generated DRL ===" );
    System.out.println( s );
    System.out.println( "=== End generated DRL ===" );
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
}
</code>```

Title: Drools Decision Tables

Body:
Read Section 6.5.4, Spreadsheet Syntax, of the Drools Manual very carefully. Below RuleTable you need four (4) rows: one row with headers like CONDITION; below that one cell with a pattern; below that one cell for the constraint expression and then one row for a comment cell.

You have five rows.

To combine two or more patterns, use two or more columns. See the examples in that section.

Edit Code to compile a spreadsheet and display the generated DRL:

private void testSpreadsheet( String dtPath ){
  File dtf = new File( dtPath );
  InputStream is;
  try {
    is = new FileInputStream( dtf );
    SpreadsheetCompiler ssComp = new SpreadsheetCompiler();
    String s = ssComp.compile( is, InputType.XLS );
    System.out.println( "=== Begin generated DRL ===" );
    System.out.println( s );
    System.out.println( "=== End generated DRL ===" );
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
}


问:
usage of attr_accessor in a rails model class
Excuse me for the noob question.I am a newbie to ruby and rails and Needed some help in Understanding the attr_accessor which I have come across in the code

```<code>  create_table "pets", force: :cascade do |t|
            t.string   "name"
            t.string   "colour"
            t.string   "owner_name"
            t.text     "identifying_characteristics"
            t.text     "special_instructions"
            t.datetime "created_at"
            t.datetime "updated_at"
            t.string   "email"
            t.string   "password"
          end
</code>```

model

```<code> class Pet < ActiveRecord::Base
  has_many :pet_photos
  cattr_accessor :form_steps do
    %w(identity characteristics instructions)
  end

  attr_accessor :form_step
  validates :email, presence: true
  validates :name, :owner_name, presence: true, if: -> { required_for_step?(:identity) }
  validates :identifying_characteristics, :colour, presence: true, if: -> { required_for_step?(:characteristics) }
  validates :special_instructions, presence: true, if: -> { required_for_step?(:instructions) }

  def required_for_step?(step)
    return true if form_step.nil?
    return true if self.form_steps.index(step.to_s) <= self.form_steps.index(form_step)
  end

end
</code>```

and

```<code>      class Pet::StepsController < ApplicationController
        include Wicked::Wizard
        steps *Pet.form_steps

        def show
          @pet = Pet.find(params[:pet_id])
          render_wizard
        end

        def update
          @pet = Pet.find(params[:pet_id])
          @pet.update(pet_params(step))

            if params[:images]

                params[:images].each do |image|
                @pet.pet_photos.create(image: image)
              end
            end

          render_wizard @pet
        end

        private

        def pet_params(step)
          permitted_attributes = case step
                                 when "identity"
                                   [:name, :owner_name]
                                 when "characteristics"
                                   [:colour, :identifying_characteristics]
                                 when "instructions"
                                   [:special_instructions]
                                 end

          params.require(:pet).permit(permitted_attributes).merge(form_step: step)
        end

      end
</code>```

routes

```<code>  PetThing::Application.routes.draw do
          resources :pets, only: [:new, :create, :index, :destroy] do
            resources :steps, only: [:show, :update], controller: 'pet/steps'
          end

          root to: 'pets#index'
</code>```

1) what  I all only know about  attr_accessor  is, it nothing more than a getter/setter for an object.I do not have a form_step as an attribute of my Pet Model(pets table).But in the model, there is attr_accessor :form_step.How is getter/setter generated to :form_step ?

2) Is :form_step an object of Pet class?

I am not totally understanding the usage of attr_accessor method in Rails model class.

3) Kindly explain me a scenario where I must generate getter/setter for Model attributes (pets table attributes or fields)

eg: attr_accessor :name
      attr_accessor :colour ..etc

when do we use attr_accessor for model attributes or fields?

答:
Part of the Rails' magic is that when you have a class Pet and a table pets, you get the accessors for all the columns in the table for free. It's as if you've declared attr-accessor for all of them, only you don't need to.

In your example, #form_step is not created in the table. But it is declared using attr_accessor. It works just like plain old ruby. This gives you a getter/setter (answer to your Q1).

It's an instance method of Pet class. You call it on a Pet object, like Pet.new.form_step = 5(answer to Q2).

But you can't persist whatever value you assign to #form_step to db. So the answer to Q3 is that you usually do this when you need to pass some messages (i.e. call methods) between your objects, but you don't need to persist them to db.

Body:
Excuse me for the noob question.I am a newbie to ruby and rails and Needed some help in Understanding the attr_accessor which I have come across in the code

  create_table "pets", force: :cascade do |t|
            t.string   "name"
            t.string   "colour"
            t.string   "owner_name"
            t.text     "identifying_characteristics"
            t.text     "special_instructions"
            t.datetime "created_at"
            t.datetime "updated_at"
            t.string   "email"
            t.string   "password"
          end

model

 class Pet < ActiveRecord::Base
  has_many :pet_photos
  cattr_accessor :form_steps do
    %w(identity characteristics instructions)
  end

  attr_accessor :form_step
  validates :email, presence: true
  validates :name, :owner_name, presence: true, if: -> { required_for_step?(:identity) }
  validates :identifying_characteristics, :colour, presence: true, if: -> { required_for_step?(:characteristics) }
  validates :special_instructions, presence: true, if: -> { required_for_step?(:instructions) }

  def required_for_step?(step)
    return true if form_step.nil?
    return true if self.form_steps.index(step.to_s) <= self.form_steps.index(form_step)
  end

end

and

      class Pet::StepsController < ApplicationController
        include Wicked::Wizard
        steps *Pet.form_steps

        def show
          @pet = Pet.find(params[:pet_id])
          render_wizard
        end

        def update
          @pet = Pet.find(params[:pet_id])
          @pet.update(pet_params(step))

            if params[:images]

                params[:images].each do |image|
                @pet.pet_photos.create(image: image)
              end
            end

          render_wizard @pet
        end

        private

        def pet_params(step)
          permitted_attributes = case step
                                 when "identity"
                                   [:name, :owner_name]
                                 when "characteristics"
                                   [:colour, :identifying_characteristics]
                                 when "instructions"
                                   [:special_instructions]
                                 end

          params.require(:pet).permit(permitted_attributes).merge(form_step: step)
        end

      end

routes

  PetThing::Application.routes.draw do
          resources :pets, only: [:new, :create, :index, :destroy] do
            resources :steps, only: [:show, :update], controller: 'pet/steps'
          end

          root to: 'pets#index'

1) what  I all only know about  attr_accessor  is, it nothing more than a getter/setter for an object.I do not have a form_step as an attribute of my Pet Model(pets table).But in the model, there is attr_accessor :form_step.How is getter/setter generated to :form_step ?

2) Is :form_step an object of Pet class?

I am not totally understanding the usage of attr_accessor method in Rails model class.

3) Kindly explain me a scenario where I must generate getter/setter for Model attributes (pets table attributes or fields)

eg: attr_accessor :name
      attr_accessor :colour ..etc

when do we use attr_accessor for model attributes or fields?


问:
Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"
I'm looking for more information on the message below. Xcode 9 seems to be hanging for a couple minutes already...

How can I tell Xcode 9 to quickly recognize my previously used device updated to iOS 11?

.Alex’s iPhone is busy: Preparing debugger support for .Alex’s iPhone

Xcode will continue when .Alex’s iPhone is finished.

答:
I have been using my iPhone X to debug via Network and suddenly had this problem.

Disable "Connect via network" and try again with USB.
This trick worked for me.

ContentLicense: CC BY-SA 4.0


问:
Why socket.io is messing up my ajax headers?
I am using custom headers in ajax requests:

```<code>$.ajaxSetup({
                beforeSend: function (xhr)
                {
                    xhr.setRequestHeader("Authorization",  'Bearer ' + token);
                    xhr.setRequestHeader("Accept",  'application/json');
                }
            });
</code>```

It was working great until I added socket.io chat to my app. When I include socket.io.js file served by my socket.io server my headers are gone :(

Sure I can put my headers in every ajax request but it's not convenient. My original approach is cleaner.

Anyone can help me with this? Why my headers are gone? Is there a way to make them work again while using socket.io?

UPDATE

When I get rid of socket.io.js script include:

```<code><script src="http://localhost:6001/socket.io/socket.io.js"></script>
</code>```

It's all working fine. And no, there are no errors because I do it this way:

```<code>if(typeof io !== 'undefined') {
    self.echo = window.Echo = new Echo({
        broadcaster: 'socket.io',
        host: CONFIG.socket_url + ":" + CONFIG.socket_port,
        auth: {
               headers: {
                        Authorization: 'Bearer ' + auth.getToken(),
                        Accept:  'application/json'
               },
        },
     });
 }
</code>```

UPDATE2

Well the problem might be not the socket.io, but laravel-echo (which uses socket.io for broadcasting).

答:
What if you comment out that Echo code?

Look, all I can do is comment on code I can see. I stand by my assertion that there's nothing in socket.io that messes with jQuery Ajax calls.

So, the problem is probably caused by code you are running when socket.io is active, not by socket.io itself.

Body:
I am using custom headers in ajax requests:

$.ajaxSetup({
                beforeSend: function (xhr)
                {
                    xhr.setRequestHeader("Authorization",  'Bearer ' + token);
                    xhr.setRequestHeader("Accept",  'application/json');
                }
            });

It was working great until I added socket.io chat to my app. When I include socket.io.js file served by my socket.io server my headers are gone :(

Sure I can put my headers in every ajax request but it's not convenient. My original approach is cleaner.

Anyone can help me with this? Why my headers are gone? Is there a way to make them work again while using socket.io?

UPDATE

When I get rid of socket.io.js script include:

It's all working fine. And no, there are no errors because I do it this way:

if(typeof io !== 'undefined') {
    self.echo = window.Echo = new Echo({
        broadcaster: 'socket.io',
        host: CONFIG.socket_url + ":" + CONFIG.socket_port,
        auth: {
               headers: {
                        Authorization: 'Bearer ' + auth.getToken(),
                        Accept:  'application/json'
               },
        },
     });
 }

UPDATE2

Well the problem might be not the socket.io, but laravel-echo (which uses socket.io for broadcasting).


问:
Remove object from array1 where object.prop is in array2
E.g:

```<code>const array1 = [
  {id: 1, name: 'Bob', age: 29},
  {id: 2, name: 'Anne', age: 18},
  {id: 3, name: 'Dave', age: 29},
  {id: 4, name: 'Barry', age: 50},
  {id: 5, name: 'Jill', age: 35},
];

const array2 = [29, 50];
</code>```

I want to go through array1 and remove all objects where object.age is in array2. I have lodash at my disposable but their documentation confuses me...

答:
If you are ok with mutating the array (modify in place)

```<code>_.pullAllBy(array1, [{ age: 29 }, { age: 50 }], 'age');
</code>```

If you want a new array:

```<code>const newArray = _.differenceBy(array1, [{ age: 29 }, { age: 50 }], 'age');
</code>```

Body:
E.g:

const array1 = [
  {id: 1, name: 'Bob', age: 29},
  {id: 2, name: 'Anne', age: 18},
  {id: 3, name: 'Dave', age: 29},
  {id: 4, name: 'Barry', age: 50},
  {id: 5, name: 'Jill', age: 35},
];

const array2 = [29, 50];

I want to go through array1 and remove all objects where object.age is in array2. I have lodash at my disposable but their documentation confuses me...

Body:
If you are ok with mutating the array (modify in place)

_.pullAllBy(array1, [{ age: 29 }, { age: 50 }], 'age');

If you want a new array:

const newArray = _.differenceBy(array1, [{ age: 29 }, { age: 50 }], 'age');


答:
The canonical way to achieve that is to use an apply. It will be much more efficient.

```<code>import pandas as pd
import numpy as np

np.random.seed(0)

# A function to simulate the call to the API
def get_user_info(id):
    return np.random.randint(id, id + 10)

# Some test data
df = pd.DataFrame({'id': [0,1,2], 'name': ['Pierre', 'Paul', 'Jacques']})

# Here the call is made for each ID
df['info'] = df['id'].apply(get_user_info)

#    id     name  info
# 0   0   Pierre     5
# 1   1     Paul     1
# 2   2  Jacques     5
</code>```

Note, another way to write the same thing is

```<code>df['info'] = df['id'].map(lambda x: get_user_info(x))
</code>```

Title: How to feed array of user_ids to flickr.people.getInfo()?

Body:
The canonical way to achieve that is to use an apply. It will be much more efficient.

import pandas as pd
import numpy as np

np.random.seed(0)

# A function to simulate the call to the API
def get_user_info(id):
    return np.random.randint(id, id + 10)

# Some test data
df = pd.DataFrame({'id': [0,1,2], 'name': ['Pierre', 'Paul', 'Jacques']})

# Here the call is made for each ID
df['info'] = df['id'].apply(get_user_info)

#    id     name  info
# 0   0   Pierre     5
# 1   1     Paul     1
# 2   2  Jacques     5

Note, another way to write the same thing is

df['info'] = df['id'].map(lambda x: get_user_info(x))


问:
Is it possible to customise column width of bar chart created using AmChart
I am having issue with the AmChart column width that column names is overlapping to each other. See below image.

Please advise if possible to change column width or to bring extra content in next line

答: By simply adding \n (New Line operator) now extra content is coming to next line</p>


问:
Multiple main C++ files in a single project in Code::Blocks?
I do not regularly write code. There are times I write code daily for 6 months, and then do not code for up to 2 years. This approach has forced me to keep a bunch or reference code that I (and other much, much better programmers) have written. I refer to this "library" when writing code after a long period; I read it, I execute it, and that is a massive help in refreshing myself. This system has served me very well with Eclipse & Java over the past 5 years.

I am now learning C++ and am using Code::Blocks. I would like to somehow stuff a bunch of C++ files that have main methods into a single Code::Blocks project. I am willing to rewrite the code to achieve this task (if it's reasonable...)

I am not the first to look for a meaningful answer for this issue: https://stackoverflow.com/questions/35917504/how-can-i-make-multiple-programs-in-a-single-project-in-codeblocks and https://www.reddit.com/r/learnprogramming/comments/3opp5r/how_to_run_multiple_cpp_files_separately_in_same/

I do not want to change the IDE or compare it to other IDEs. What I am looking for, is the ability to execute one of hundreds of tiny programs that are in a well organized in an expandable file tree in C::B quickly and easily. If I put each C++ file with a main in it's own project I will have so many C::B projects that it will be unreasonable.

I do understand that C::B is not Eclipse and C++ is not Java, and that C::B is intended to have a single c++ file with a main function per project.

Any answers, and even very creative answers would be very appreciated! Scripts, settings, how to rewrite my code, whatever - if you have a suggestion I would love to hear it so I may consider it.

In the interest of full disclosure, currently I am keeping all my tiny programs in directories and use the O/S to drill through the directories and simply double click on the .cpp file which C::B opens. I am willing to dramatically modify my code to be able to achieve the objective.

Thanks for your time.

答:
To compile and run a single main() file in a Code::Blocks project with multiple main() files:

In the "Projects" tab on the left, right-click on a file that you do not want to compile.

In the menu that appears, point to Options, and uncheck both Compile file and Link file.

This has to be done for all the files that you do not want to compile.

Now, when the project is built and run with F9, only the desired file will be compiled; the others will be ignored.

Note: It is not necessary to create a project in Code::Blocks to compile and run single file. To compile and run single files (without creating projects)

Just click on File -> Empty -> New file.

Save the file with .cpp extension anywhere (not in a project).

To compile and run the file, just press F9 or Build -> Build and run

However, such files (without projects) cannot be debugged. The most appropriate thing would be to just have a project with multiple main() files, as explained in the early part of this answer.


问:
Tar archive: How reliable is append?
I noticed that the -a option in TAR allows appending files to an existing archive. How reliable is this for creating incremented backups of a set folder?
Is there anyone here who can share their experiences?

From the TAR manual:

```<code> -A, --catenate, --concatenate
       append tar files to an archive
</code>```

答: Very reliable. tar doesn't store any information about the entries within the archive in the file header, so appending works fine. Just remember that append really does mean append, so any new entries with the same name as older ones will not remove the older entries from the archive.

Title: Tar archive: How reliable is append?

Body:
I noticed that the -a option in TAR allows appending files to an existing archive. How reliable is this for creating incremented backups of a set folder?
Is there anyone here who can share their experiences?

From the TAR manual:

 -A, --catenate, --concatenate
       append tar files to an archive


问:
Splitting strings into characters using DTL in Sesam
I wish to split a string into individual characters, but struggle to get the DTL correct.

I have:

```<code>"foo":"bar"
</code>```

I wish to get

```<code>"foo":["b","a","r"]
</code>```

答:
You can solve this using "range" and "substring". Performance might not be great.

```<code>{
  "_id": "split-word",
  "type": "pipe",
  "source": {
    "type": "embedded",
    "entities": [{
      "_id": "baz",
      "foo": "bar"
    }]
  },
  "transform": {
    "type": "dtl",
    "rules": {
      "default": [
        ["add", "foo",
          ["map",
            ["substring",
              "_.", ["plus", "_.", 1], "_S.foo"],
            ["range", 0,
              ["length", "_S.foo"]
            ]
          ]
        ]
      ]
    }
  }
}
</code>```

Gives the following result:

```<code>[
  {
    "_id": "baz",
    "foo": [
      "b",
      "a",
      "r"
    ]
  }
]
</code>```

Body:
I wish to split a string into individual characters, but struggle to get the DTL correct.

I have:

"foo":"bar"

I wish to get

"foo":["b","a","r"]

Body:
You can solve this using "range" and "substring". Performance might not be great.

{
  "_id": "split-word",
  "type": "pipe",
  "source": {
    "type": "embedded",
    "entities": [{
      "_id": "baz",
      "foo": "bar"
    }]
  },
  "transform": {
    "type": "dtl",
    "rules": {
      "default": [
        ["add", "foo",
          ["map",
            ["substring",
              "_.", ["plus", "_.", 1], "_S.foo"],
            ["range", 0,
              ["length", "_S.foo"]
            ]
          ]
        ]
      ]
    }
  }
}

Gives the following result:

[
  {
    "_id": "baz",
    "foo": [
      "b",
      "a",
      "r"
    ]
  }
]


问:
Combine multiple text rows with identical column
I need to combine rows with 1 column being the same and the rest is of type nvarchar.

TempTable

```<code>Id | Key          | Description1 | Description2
 1 | 60287F58-4631| Lorem Ipsum  | dolor sit amet
 2 | 60287F58-4631| consectetur  | adipiscing elit
 3 | 74553234-7543| Test test    | test test
</code>```

I need to get this result:

```<code>Key          | DescriptionCombined
60287F58-4631| Lorem Ipsum, dolor sit amet, consectetur, adipiscing elit
74553234-7543| Test test, test test
</code>```

I know that group by will not work because Description1 and Description2 are different between common rows. I started experimenting with for xml path(''), but this combines every row. I guess I need to first extract groups with the same key and then apply for xml path(''), but I cannot get this to work.

```<code>select ',' + t1.Description1, t1.Description2 from TempTable t1
for xml path('')
</code>```

答:
YOU Can Achive This Using STUFF Function In CTE </p>

```<code>CREATE TABLE #TEMP (ID INT,[KEY] NVARCHAR(50),Description1 NVARCHAR(50),Description2 NVARCHAR(50))

INSERT INTO #TEMP
SELECT  1,'60287F58-4631','Lorem Ipsum','dolor sit amet'   UNION ALL
SELECT  2,'60287F58-4631','consectetur','adipiscing elit'  UNION ALL
SELECT 3,'74553234-7543','Test test','test test'

;WITH CTE
AS
    (   SELECT       [Key],
                    STUFF(
                        (
                            SELECT ', '+Description1+', '+Description2
                            FROM #TEMP a
                            WHERE a.[Key]=b.[Key]
                            ORDER BY a.Id
                            FOR XML PATH('')
                        ),1,2,'') DescriptionCombined
FROM (SELECT DISTINCT [Key] FROM #TEMP) b
)
SELECT * FROM CTE
</code>```

Body:
I need to combine rows with 1 column being the same and the rest is of type nvarchar.

TempTable

Id | Key          | Description1 | Description2
 1 | 60287F58-4631| Lorem Ipsum  | dolor sit amet
 2 | 60287F58-4631| consectetur  | adipiscing elit
 3 | 74553234-7543| Test test    | test test

I need to get this result:

Key          | DescriptionCombined
60287F58-4631| Lorem Ipsum, dolor sit amet, consectetur, adipiscing elit
74553234-7543| Test test, test test

I know that group by will not work because Description1 and Description2 are different between common rows. I started experimenting with for xml path(''), but this combines every row. I guess I need to first extract groups with the same key and then apply for xml path(''), but I cannot get this to work.

select ',' + t1.Description1, t1.Description2 from TempTable t1
for xml path('')

Body:
YOU Can Achive This Using STUFF Function In CTE

CREATE TABLE #TEMP (ID INT,[KEY] NVARCHAR(50),Description1 NVARCHAR(50),Description2 NVARCHAR(50))

INSERT INTO #TEMP
SELECT  1,'60287F58-4631','Lorem Ipsum','dolor sit amet'   UNION ALL
SELECT  2,'60287F58-4631','consectetur','adipiscing elit'  UNION ALL
SELECT 3,'74553234-7543','Test test','test test'

;WITH CTE
AS
    (   SELECT       [Key],
                    STUFF(
                        (
                            SELECT ', '+Description1+', '+Description2
                            FROM #TEMP a
                            WHERE a.[Key]=b.[Key]
                            ORDER BY a.Id
                            FOR XML PATH('')
                        ),1,2,'') DescriptionCombined
FROM (SELECT DISTINCT [Key] FROM #TEMP) b
)
SELECT * FROM CTE


问:
Blend alpha color using bitwise operations
I have code below to blend alpha color in ARGB format:

a, b, o are integers, but should always fall in [0x00ffffff,0xffffffff]

o = ( ( ( a >> 24 ) * ( b >> 24 ) ) >> 8 ) << 24;

Is there anyway to optimize it?

Thanks!

答:
```<code>unsigned int blend(unsigned int a, unsigned int b)
{
  return (((a >> 24) * (b >> 24)) << 16) & 0xFF000000;
}
</code>```

Is this what you are trying to do? I don't think this is any faster though, but more accuracte according to what you stated.

If you don't need to use bitwise operators you can use pointers too, as shown by other solutions.

Body:
unsigned int blend(unsigned int a, unsigned int b)
{
  return (((a >> 24) * (b >> 24)) << 16) & 0xFF000000;
}

Is this what you are trying to do? I don't think this is any faster though, but more accuracte according to what you stated.

If you don't need to use bitwise operators you can use pointers too, as shown by other solutions.


问:
Method alias with TypeScript
I assume this is the easiest way to implement a method alias with TS:

```<code>export class Foo {

 bar(){

 }

 aliasOfBar(){
   return this.bar.apply(this, arguments);
 }

}
</code>```

but I am simply wondering if there is another way we can define an alias with TS (or JS). Perhaps ideally without an extra function call.

If I do this, for example:

```<code>let mySharedFn = function () {

};

export class Foo {
  public bar = mySharedFn
  public aliasBar = mySharedFn
}
</code>```

it transpiles to this:

```<code>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var mySharedFn = function () {
};
var Foo = (function () {
    function Foo() {
        this.bar = mySharedFn;
        this.aliasBar = mySharedFn;
    }
    return Foo;
}());
exports.Foo = Foo;
</code>```

I'd like to avoid those extra calls that come with using the constructor to create the methods, etc.

答:
You can add the alias method to the class using an interface and the prototype, like this:

class Person {
    constructor(public name: string) {}
    greet(greeting: string): string { return `${greeting}, ${this.name}`; }
}

interface Person {
    hi: typeof Person.prototype.greet;
}
Person.prototype.hi = Person.prototype.greet;

const p = new Person("Alice");
console.log(p.greet("Hey"));
console.log(p.hi("Hi"));
```

Title: Method alias with TypeScript

Body:
I assume this is the easiest way to implement a method alias with TS:

export class Foo {

 bar(){

 }

 aliasOfBar(){
   return this.bar.apply(this, arguments);
 }

}

but I am simply wondering if there is another way we can define an alias with TS (or JS). Perhaps ideally without an extra function call.

If I do this, for example:

let mySharedFn = function () {

};

export class Foo {
  public bar = mySharedFn
  public aliasBar = mySharedFn
}

it transpiles to this:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var mySharedFn = function () {
};
var Foo = (function () {
    function Foo() {
        this.bar = mySharedFn;
        this.aliasBar = mySharedFn;
    }
    return Foo;
}());
exports.Foo = Foo;

I'd like to avoid those extra calls that come with using the constructor to create the methods, etc.


问:
Do you know how to apply color to individual keywords in textarea?
Do you know how to apply color to individual keywords in textarea?

I want to place an underline instead of an alert in the textarea area for the banning

答:
Sorry, but you really can't.

As <input> are self closing, they cannot accommodate any tags like  to add individual properties to.

You can however use some hacks.

Some Hacks

Body:
Sorry, but you really can't.

As <input> are self closing, they cannot accommodate any tags like <span> to add individual properties to.

You can however use some hacks.

Some Hacks


问:
Opencart v 2.3 create module from another module
on opencart v2.3 I did create a module from manufacturer

I created a table on mysql similar to manufacturer table and I duplicated this files

admin/controller/catalog/manufacturer.php

admin/language/en-gb/catalog/manufacturer.php

admin/model/catalog/manufacturer.php

admin/view/template/catalog/manufacturer_form.tpl

admin/view/template/catalog/manufacturer_list.tpl

and changed manufacturer to enchere and also inside the files i changed manufacturer to enchere and the class names too

admin/controller/catalog/enchere.php

admin/language/en-gb/catalog/enchere.php

admin/model/catalog/enchere.php

admin/view/template/catalog/enchere_form.tpl

admin/view/template/catalog/enchere_list.tpl

but when i uploaded the files to my opencart in the same folders where manufacturer are I didn't see no where enchere

can someone help me plz

答: You have to go to System>Users>User Groups>Edit to your group then give access to the new module, you can do a small search to be sure search for catalog/enchere you will find it unselected, once you select it it will appear.</p>


问:
Browser adds zeroes when posting in NopCommerce
When updating prices in NopCommerce Product edit, the zeroes behind the dot is added to the number.

e.g. 440.0000 becomes 4400000

The prices is stored in a decimal type. The language used on the client machine is Danish, which normally uses ',' as decimal separator. In the Edit webpage dot '.' is used as decimal separator and it will not accept ','. By googling around I have seen that other Danes has had the same problem.

This question and answer could identify the problem and a maybe offer a solution. Can anyone tell me how to implement it in NopCommerce?

It is not an option to make any change in the NopCommerce source code, despite it's "open source", because I am trying to fix a legacy system.

The problem occurs in both Chrome and Firefox.

答:
Depending on the version of nopCommerce you use have a look at

Global.asax.cs - SetWorkingCulture()

```<code>if (webHelper.GetThisPageUrl(false).StartsWith(string.Format("{0}admin", webHelper.GetStoreLocation()),
    StringComparison.InvariantCultureIgnoreCase))
{
    //admin area

    //always set culture to 'en-US'
    //we set culture of admin area to 'en-US' because current implementation of Telerik grid
    //doesn't work well in other cultures
    //e.g., editing decimal value in russian culture
    CommonHelper.SetTelerikCulture();
}
</code>```

ComonHelper.cs - SetTelerikCulture()

```<code>public static void SetTelerikCulture()
{
    //little hack here
    //always set culture to 'en-US' (Kendo UI has a bug related to editing decimal values in other cultures). Like currently it's done for admin area in Global.asax.cs

    var culture = new CultureInfo("en-US");
    Thread.CurrentThread.CurrentCulture = culture;
    Thread.CurrentThread.CurrentUICulture = culture;
}
</code>```

The above code blocks represent nopCommerce 3.90.

It is not an option to make any change in the NopCommerce source code, despite it's "open source", because I am trying to fix a legacy system.

Since you do not want to change the nopCommerce source code, you have no choice but to use nop Admin using en-US culture.

Edit

One thing you could try is adding one of the culture scripts provided by telerik. See ~/Scripts/kendo/2014.1.318/cultures/...

Although this requires a minor change on a view (source code)

Body:
Depending on the version of nopCommerce you use have a look at

Global.asax.cs - SetWorkingCulture()

if (webHelper.GetThisPageUrl(false).StartsWith(string.Format("{0}admin", webHelper.GetStoreLocation()),
    StringComparison.InvariantCultureIgnoreCase))
{
    //admin area

    //always set culture to 'en-US'
    //we set culture of admin area to 'en-US' because current implementation of Telerik grid
    //doesn't work well in other cultures
    //e.g., editing decimal value in russian culture
    CommonHelper.SetTelerikCulture();
}

ComonHelper.cs - SetTelerikCulture()

public static void SetTelerikCulture()
{
    //little hack here
    //always set culture to 'en-US' (Kendo UI has a bug related to editing decimal values in other cultures). Like currently it's done for admin area in Global.asax.cs

    var culture = new CultureInfo("en-US");
    Thread.CurrentThread.CurrentCulture = culture;
    Thread.CurrentThread.CurrentUICulture = culture;
}

The above code blocks represent nopCommerce 3.90.

It is not an option to make any change in the NopCommerce source code, despite it's "open source", because I am trying to fix a legacy system.

Since you do not want to change the nopCommerce source code, you have no choice but to use nop Admin using en-US culture.

Edit

One thing you could try is adding one of the culture scripts provided by telerik. See ~/Scripts/kendo/2014.1.318/cultures/...

Although this requires a minor change on a view (source code)


问:
In reality, are server controls rarely added programmatically to aspx pages?
I mean, it's easy to add a Button programmactically to an aspx page, but a server control's event handler probably has to be set early in the page life cycle (maybe before Control.Load event). As a result in reality, are dynamic controls rarely added to apsx pages?

I wish there is a way to call postback at the server, so that a event is never too late.

答: If you add the controls in the PreInit or Init events, there are no problems.  I dynamically add controls to my webforms pages all the time.</p>


问:
How can I have carousel of basic cards in google actions app
I want to show a carousel with a list of  of basic cards (https://developers.google.com/actions/assistant/responses#basic_card) in google actions conversation response. I looked at the rich response(https://developers.google.com/actions/assistant/responses#rich-responses) and it allows only one basic card in it.

The reason I want to use basic card instead of carousel of option is simple. When I click on the carousel option it proceeds to next conversation, but with basic card I will be redirected to the external link, which is what I needed.

I'm using the code below to display a list of items(options) in carousel for a chat response currently. Any suggestions and help appreciated

```<code>        let carousel = app.buildCarousel()
        // carousel.addSimpleResponse();
        products_raw.forEach(function(item){
            console.log(item);
            carousel.addItems(
              app.buildOptionItem(item.title,)
              .setTitle(item.title)
              .setDescription(`Price: ${item.price}`)
              // .addButton('know more', item.url)
              .setImage(item.image, item.title)
              // .setImageDisplay('CROPPED')
            )
        });
        app.askWithCarousel(answerData.message_text, carousel)
</code>```

答: You can make a carrousel or list selector with multiple sites that you want to be able to choose from. Then when a user selects an item, build a basic card with the site you passed from the selector.</p>

Body:
I want to show a carousel with a list of  of basic cards (https://developers.google.com/actions/assistant/responses#basic_card) in google actions conversation response. I looked at the rich response(https://developers.google.com/actions/assistant/responses#rich-responses) and it allows only one basic card in it.

The reason I want to use basic card instead of carousel of option is simple. When I click on the carousel option it proceeds to next conversation, but with basic card I will be redirected to the external link, which is what I needed.

I'm using the code below to display a list of items(options) in carousel for a chat response currently. Any suggestions and help appreciated

        let carousel = app.buildCarousel()
        // carousel.addSimpleResponse();
        products_raw.forEach(function(item){
            console.log(item);
            carousel.addItems(
              app.buildOptionItem(item.title,)
              .setTitle(item.title)
              .setDescription(`Price: ${item.price}`)
              // .addButton('know more', item.url)
              .setImage(item.image, item.title)
              // .setImageDisplay('CROPPED')
            )
        });
        app.askWithCarousel(answerData.message_text, carousel)


问:
Client-side validation does not work when inherting from RequiredAttribute in ASP.NET MVC 3?
I created an inherited attribute like this in ASP.NET MVC3:

```<code>public sealed class RequiredFromResourceAttribute : RequiredAttribute
{
    public RequiredFromResourceAttribute(string errorResourceName, string errorResourceTypeName)
    {
        this.ErrorMessageResourceName = errorResourceName;
        this.ErrorMessageResourceType = Type.GetType(errorResourceTypeName);
    }
}
</code>```

And use it like this:

```<code>[RequiredFromResource("Title", "Resources.Resource, MyProject.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")]
public string Title { get; set; }
</code>```

It didn't work and the MVC ignored it. Then I create a simpler class which just inherited from RequiredAttribute like this:

```<code>public class MyRequiredAttribute : RequiredAttribute
{
}
</code>```

I use it like that I said. But it didn't work again.

Although, all these ways work on "DisplayNameAtrribute" perfectly.

What is the problem?

答:
It's only client-side validation that does not work with inherited attributes. The reason for that is that MVC uses strict type equality when mapping server-side attributes to client validation behaviors.

To work around this you will need your custom attribute to implement IClientValidatable:

```<code>public class MyRequiredAttribute : IClientValidatable {
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
         yield return new ModelClientValidationRequiredRule();
    }
}
</code>```

Body:
I created an inherited attribute like this in ASP.NET MVC3:

public sealed class RequiredFromResourceAttribute : RequiredAttribute
{
    public RequiredFromResourceAttribute(string errorResourceName, string errorResourceTypeName)
    {
        this.ErrorMessageResourceName = errorResourceName;
        this.ErrorMessageResourceType = Type.GetType(errorResourceTypeName);
    }
}

And use it like this:

[RequiredFromResource("Title", "Resources.Resource, MyProject.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")]
public string Title { get; set; }

It didn't work and the MVC ignored it. Then I create a simpler class which just inherited from RequiredAttribute like this:

public class MyRequiredAttribute : RequiredAttribute
{
}

I use it like that I said. But it didn't work again.

Although, all these ways work on "DisplayNameAtrribute" perfectly.

What is the problem?

Body:
It's only client-side validation that does not work with inherited attributes. The reason for that is that MVC uses strict type equality when mapping server-side attributes to client validation behaviors.

To work around this you will need your custom attribute to implement IClientValidatable:

public class MyRequiredAttribute : IClientValidatable {
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
         yield return new ModelClientValidationRequiredRule();
    }
}


问:
How does UISlider call setValue() method before self becomes available?
I'm subclassing UIControl to make a custom slider as an exercise in learning UIKit. The setValue(value:) method takes a float/double argument and animates the slider to that value. However, if the slider is not instantiated with an explicit frame, but instead sized using constraints, the setValue() method cannot be called without crashing as it requires the intrinsic width of the slider to determine where to animate the slider's thumb.

What would the proper strategy be to make sure an optional property (in this case, the width of self) becomes available before a method that has already been called is fully executed?

```<code>func addSlider() {

    slider.minimumValue = 0
    slider.maximumValue = 42
    slider.setValue(39)
    slider.addTarget(self, action: #selector(sliderAction(_:)), for: .valueChanged)
    slider.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(slider)
    slider.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    slider.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    slider.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -64).isActive = true

}
</code>```

The problem is that slider.setValue(39) requires the slider's width to make the calculation.

```<code>override func draw(_ rect: CGRect) {

    superWidth = rect.width
    drawTrack()
    drawThumb()

}

...

func setValue(_ value: Float) {

    let thumbX = CGFloat(value / maximumValue!) * (superWidth - thumbDimension)

    UIView.animate(withDuration: 1, animations: { [weak self] in
        self?.thumbLayer.frame.origin.x = thumbX
    })

}
</code>```

答:
So what I did was create a conditional statement that stores value (the argument) in an instance property if the intrinsic width is not available:

```<code>@objc func setValue(_ value: Float) {

    if superWidth != nil {

        let thumbX = CGFloat(value / maximumValue!) * (superWidth - thumbDimension)

        UIView.animate(withDuration: 1, animations: { [weak self] in
            self?.thumbLayer.frame.origin.x = thumbX
        })

    } else {

        valueToBeSet = value

    }

}
</code>```

And then re-called the method once the width was set:

```<code>var superWidth: CGFloat! {
    didSet {
        if valueToBeSet != nil {
            setValue(valueToBeSet!)
            valueToBeSet = nil
        }
    }
}
</code>```

It works, but is this an acceptable practice?

Body:
I'm subclassing UIControl to make a custom slider as an exercise in learning UIKit. The setValue(value:) method takes a float/double argument and animates the slider to that value. However, if the slider is not instantiated with an explicit frame, but instead sized using constraints, the setValue() method cannot be called without crashing as it requires the intrinsic width of the slider to determine where to animate the slider's thumb.

What would the proper strategy be to make sure an optional property (in this case, the width of self) becomes available before a method that has already been called is fully executed?

func addSlider() {

    slider.minimumValue = 0
    slider.maximumValue = 42
    slider.setValue(39)
    slider.addTarget(self, action: #selector(sliderAction(_:)), for: .valueChanged)
    slider.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(slider)
    slider.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    slider.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    slider.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -64).isActive = true

}

The problem is that slider.setValue(39) requires the slider's width to make the calculation.

override func draw(_ rect: CGRect) {

    superWidth = rect.width
    drawTrack()
    drawThumb()

}

...

func setValue(_ value: Float) {

    let thumbX = CGFloat(value / maximumValue!) * (superWidth - thumbDimension)

    UIView.animate(withDuration: 1, animations: { [weak self] in
        self?.thumbLayer.frame.origin.x = thumbX
    })

}

Body:
So what I did was create a conditional statement that stores value (the argument) in an instance property if the intrinsic width is not available:

@objc func setValue(_ value: Float) {

    if superWidth != nil {

        let thumbX = CGFloat(value / maximumValue!) * (superWidth - thumbDimension)

        UIView.animate(withDuration: 1, animations: { [weak self] in
            self?.thumbLayer.frame.origin.x = thumbX
        })

    } else {

        valueToBeSet = value

    }

}

And then re-called the method once the width was set:

var superWidth: CGFloat! {
    didSet {
        if valueToBeSet != nil {
            setValue(valueToBeSet!)
            valueToBeSet = nil
        }
    }
}

It works, but is this an acceptable practice?


问:
How to find object value from property path in Javascript object
I explain the problem with sample.

For example i have javascript object. It looks like:

```<code>var trial= { points:[{x:1,y:2},{x:5,y:2},{x:3,y:4}] , obj:{id:5,name:"MyName"} }
</code>```

I use deep diff module to find difference between two json array. Then it find the differences and find difference path. If value of x is changed, then it finds.

For example

```<code>path = ["points",0,"x"]
or
path= ["obj","name"]
</code>```

So my question is that how to generate json object from these path.

For example i have to generate that

```<code>trial.points[0].x        or    trial.obj.name
</code>```

How to do that ?  thank you for your answer.

答:
You can use the following logic:</p>

```<code>for(var i = 0, result = trial; i < path.length; i++) {
    result = result[path[i]];
}
</code>```

Body:
I explain the problem with sample.

For example i have javascript object. It looks like:

var trial= { points:[{x:1,y:2},{x:5,y:2},{x:3,y:4}] , obj:{id:5,name:"MyName"} }

I use deep diff module to find difference between two json array. Then it find the differences and find difference path. If value of x is changed, then it finds.

For example

path = ["points",0,"x"]
or
path= ["obj","name"]

So my question is that how to generate json object from these path.

For example i have to generate that

trial.points[0].x        or    trial.obj.name

How to do that ?  thank you for your answer.

Body:
You can use the following logic:

for(var i = 0, result = trial; i < path.length; i++) {
    result = result[path[i]];
}


问:
expect script not working with ssh taking input from a file
I have an expect script like below.

```<code>/usr/bin/expect << EOD
    spawn ssh root@192.168.83.100 -o StrictHostKeyChecking=no -p 830 -s netconf < $FILE1
    expect "Password:"
    send "$PASSWD\n"
EOD
</code>```

The ssh command does not work. It is not taking input from $FILE1.

What is the syntax?

UPDATE:

I have an expect script like below.

```<code>#!/bin/bash

FILE=/home/eorstae/mtasCDivBlackList_temp.xml
FILE1=/home/eorstae/mtasCDivBlackList.xml
PASSWD=rootroot

COUNT=0
while [ $COUNT -lt 2048 ]
do
  sed  -e "s/VARA/${COUNT}/g" $FILE > $FILE1
  COUNT=`expr $COUNT + 1`
  /usr/bin/expect <<EOD
    spawn bash -c "ssh root@192.168.83.100 -o StrictHostKeyChecking=no -p 830 -s netconf <  $FILE1"
    expect "Password: "
    send "$PASSWD\r"
EOD

  sleep 5
done
</code>```

Output when running the script:

```<code>[/home/eorstae] ->./myTest.sh

spawn bash -c ssh root@192.168.83.100 -o StrictHostKeyChecking=no -p 830 -s netconf <  /home/eorstae/mtasCDivBlackList.xml

Password: spawn bash -c ssh root@192.168.83.100 -o StrictHostKeyChecking=no -p 830 -s netconf <  /home/eorstae/mtasCDivBlackList.xml

Password: spawn bash -c ssh root@192.168.83.100 -o StrictHostKeyChecking=no -p 830 -s netconf <  /home/eorstae/mtasCDivBlackList.xml
</code>```

The netconf snippet is not executed on the remote node.
Something wrong with the script.

答:
You can use bash -c:

```<code>spawn bash -c "ssh root@192.168.1.1 -o StrictHostKeyChecking=no -p 830 -s netconf < $FILE1"
</code>```

Body:
I have an expect script like below.

/usr/bin/expect << EOD
    spawn ssh root@192.168.83.100 -o StrictHostKeyChecking=no -p 830 -s netconf < $FILE1
    expect "Password:"
    send "$PASSWD\n"
EOD

The ssh command does not work. It is not taking input from $FILE1.

What is the syntax?

UPDATE:

I have an expect script like below.

#!/bin/bash

FILE=/home/eorstae/mtasCDivBlackList_temp.xml
FILE1=/home/eorstae/mtasCDivBlackList.xml
PASSWD=rootroot

COUNT=0
while [ $COUNT -lt 2048 ]
do
  sed  -e "s/VARA/${COUNT}/g" $FILE > $FILE1
  COUNT=`expr $COUNT + 1`
  /usr/bin/expect <<EOD
    spawn bash -c "ssh root@192.168.83.100 -o StrictHostKeyChecking=no -p 830 -s netconf <  $FILE1"
    expect "Password: "
    send "$PASSWD\r"
EOD

  sleep 5
done

Output when running the script:

[/home/eorstae] ->./myTest.sh

spawn bash -c ssh root@192.168.83.100 -o StrictHostKeyChecking=no -p 830 -s netconf <  /home/eorstae/mtasCDivBlackList.xml

Password: spawn bash -c ssh root@192.168.83.100 -o StrictHostKeyChecking=no -p 830 -s netconf <  /home/eorstae/mtasCDivBlackList.xml

Password: spawn bash -c ssh root@192.168.83.100 -o StrictHostKeyChecking=no -p 830 -s netconf <  /home/eorstae/mtasCDivBlackList.xml

The netconf snippet is not executed on the remote node.
Something wrong with the script.

Body:
You can use bash -c:

spawn bash -c "ssh root@192.168.1.1 -o StrictHostKeyChecking=no -p 830 -s netconf < $FILE1"


答:
As reliable as your hardware.
Which is not.

Also, I am not sure it will replace.

Title: Tar archive: How reliable is append?

Body:
I noticed that the -a option in TAR allows appending files to an existing archive. How reliable is this for creating incremented backups of a set folder?
Is there anyone here who can share their experiences?

From the TAR manual:

 -A, --catenate, --concatenate
       append tar files to an archive


问:
Make Gradle use Maven local repository for downloading artifacts
I know I can configure Gradle to use local Maven repository

```<code>repositories {
    mavenLocal()
    mavenCentral()
}
</code>```

Can I configure Gradle to download into Local (maven) repository? (So that Maven would also be able to use those jars)

ref Gradle configuration to use maven local repository

答:
A solution was given in the gradle forums:
https://discuss.gradle.org/t/need-a-gradle-task-to-copy-all-dependencies-to-a-local-maven-repo/13397/2

using this gradle plugin: https://github.com/ysb33r/ivypot-gradle-plugin
you can call a new tasg

```<code>gradle syncRemoteRepositories
</code>```

which will download all dependencies to a local Ivy repository (which is the same library Maven uses). The folder you point to with

```<code>syncRemoteRepositories {
   repoRoot '/path/to/repo'
}
</code>```

will contain the dependencies. I would suggest first trying out with a different local path than your M2_HOME, because I saw some warning about the Ivy repository structure having changed between Maven versions.

Body:
I know I can configure Gradle to use local Maven repository

repositories {
    mavenLocal()
    mavenCentral()
}

Can I configure Gradle to download into Local (maven) repository? (So that Maven would also be able to use those jars)

ref Gradle configuration to use maven local repository

Body:
A solution was given in the gradle forums:
https://discuss.gradle.org/t/need-a-gradle-task-to-copy-all-dependencies-to-a-local-maven-repo/13397/2

using this gradle plugin: https://github.com/ysb33r/ivypot-gradle-plugin
you can call a new tasg

gradle syncRemoteRepositories

which will download all dependencies to a local Ivy repository (which is the same library Maven uses). The folder you point to with

syncRemoteRepositories {
   repoRoot '/path/to/repo'
}

will contain the dependencies. I would suggest first trying out with a different local path than your M2_HOME, because I saw some warning about the Ivy repository structure having changed between Maven versions.