问:
Easy admin bundle modal dialog for custom action?
I'm working with Easy Admin Bundle for Symfony2. How can I use my own modal dialog with text input for the custom action in the list?

Let's say custom action is called rename and after hitting button Rename in the list I wanna in modal dialog write a new name of something. Then after hitting button OK I wanna call ranameAction in the controller which will do everything needed, but parameter called name must be sent there.

I have the solution but it is not good, there must be some better way.

I created _simple_form.html.twig:

```<code>{{
    form(rename_form, {
        action: rename_form.vars.action ~ '&referer=' ~ referer,
        method: 'POST',
        attr: { id: 'rename-form', style: 'display: none' }
    })
}}

<div id="modal-rename" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <h4>{{ 'rename_modal.title'|trans(_trans_parameters, 'EasyAdminBundle') }}</h4>
                <p>{{ 'rename_modal.content'|trans(_trans_parameters, 'EasyAdminBundle') }}</p>
                <br />
                <input class="form-control" type="text" />
            </div>
            <div class="modal-footer">
                <button type="button" data-dismiss="modal" class="btn">
                    {{ 'action.cancel'|trans(_trans_parameters, _translation_domain) }}
                </button>

                {% if easyadmin_action_is_enabled(view, 'rename', _entity_config.name) %}
                    {% set _rename_action = easyadmin_get_action(view, 'rename', _entity_config.name) %}
                    <button type="button" data-dismiss="modal" class="btn btn-danger" id="modal-rename-button" formtarget="{{ _rename_action.target }}">
                        {% if _rename_action.icon %}<i class="fa fa-{{ _rename_action.icon }}"></i>{% endif %}
                        {{ 'rename_modal.action'|trans(_trans_parameters, 'EasyAdminBundle') }}
                    </button>
                {% endif %}
            </div>
        </div>
    </div>
</div>
</code>```

In config.yml is a new option:

```<code>list:
                actions:
                    rename:    { name: rename,    type: method, label: 'Rename', css_class: 'btn btn-primary', icon: pencil }
</code>```

In list.html.twig which I'm using:

```<code>{% block main %}

{% block rename_form %}
        {% set referer = paginator.currentPage == paginator.nbPages and 1 != paginator.currentPage and 1 == paginator.currentPageResults.count
            ? path('easyadmin', app.request.query|merge({ page: app.request.query.get('page') - 1 }))
            : app.request.requestUri
        %}

        {{ include('@EasyAdmin/default/includes/_simple_form.html.twig', {
            view: 'list',
            referer: referer|url_encode,
            rename_form: rename_form_template,
            _translation_domain: _entity_config.translation_domain,
            _trans_parameters: _trans_parameters,
            _entity_config: _entity_config,
        }, with_context = false) }}
    {% endblock rename_form %}
{% endblock %}

{% block body_javascript %}
    {{ parent() }}
    <script type="text/javascript">
    $(function() {
        $('#modal-rename-button').on('click', function(e) {
            e.preventDefault();

            var name = $('#name').val();

            var renameForm = $('#rename-form');
                    renameForm.attr('action', renameForm.attr('action').replace('__name__', name));
        });

        $('a.action-rename').on('click', function(e) {
            e.preventDefault();
            var id = $(this).parents('tr').first().data('id');

            $('#modal-rename').modal({ backdrop: true, keyboard: true })
                .off('click', '#modal-rename-button')
                .on('click', '#modal-rename-button', function () {
                    var renameForm = $('#rename-form');
                    renameForm.attr('action', renameForm.attr('action').replace('__id__', id));
                    renameForm.trigger('submit');
                });
        });
    });
</script>
{% endblock %}
</code>```

And finally controller:

```<code>protected function createRenameForm($entityName, $entityId, $name)
    {
        $formBuilder = $this->get('form.factory')->createNamedBuilder('rename_form')
            ->setAction($this->generateUrl('easyadmin', array('action' => 'rename', 'entity' => $entityName, 'id' => $entityId, 'name' => $name)))
            ->setMethod('POST')
        ;

        $formBuilder->add('submit', LegacyFormHelper::getType('submit'), array('label' => 'rename_modal.action', 'translation_domain' => 'EasyAdminBundle'));
        $formBuilder->add('_easyadmin_rename_flag', LegacyFormHelper::getType('hidden'), array('data' => '1'));

        return $formBuilder->getForm();
    }

    public function listAction() {
        $this->dispatch(EasyAdminEvents::PRE_LIST);

        $fields = $this->entity['list']['fields'];
        $paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), $this->config['list']['max_results'], $this->request->query->get('sortField'), $this->request->query->get('sortDirection'), $this->entity['list']['dql_filter']);

        $this->dispatch(EasyAdminEvents::POST_LIST, array('paginator' => $paginator));

        return $this->render($this->entity['templates']['list'], array(
            'title' => 'Branches',
            'entity' => $this->entity['name'],
            'currentBranch' => $this->repo->getCurrentBranchName(),
            'paginator' => $paginator,
            'fields' => $fields,
            'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
            'rename_form_template' => $this->createRenameForm($this->entity['name'], '__id__', '__name__')->createView(),
        ));
    }
</code>```

答:
I had a similar issue because I wanted to show a modal before to perform a custom action. So what I did was modify the button action with jquery

```<code>$(document).ready(function () {
    var $archiveButton = $('a.action-archive');

    $archiveButton.attr('href', '#');
    $archiveButton.attr('data-toggle', 'modal');
    $archiveButton.attr('data-target', '#archive-modal');
    $archiveButton.attr('data-url', '/url/to/load/form/inside/modal/body');
});
</code>```

I don't know if it is the better way, but it helped me to show some info to the user before execute the archiveAction() in the AdminController

EDITED: a way to access POST variables

You can access to POST variables through the Container

```<code>public function renameAction()
    {
        $name = $this->container->get('request')->get('your variable');
        var_dump($name);
        die();
        return $this->redirectToRoute('admin', ['entity' => 'Branch', 'action'     => 'list']);
    }
</code>```

Play a while with the $this->container->get('request') to find what you are looking for

Body:
I'm working with Easy Admin Bundle for Symfony2. How can I use my own modal dialog with text input for the custom action in the list?

Let's say custom action is called rename and after hitting button Rename in the list I wanna in modal dialog write a new name of something. Then after hitting button OK I wanna call ranameAction in the controller which will do everything needed, but parameter called name must be sent there.

I have the solution but it is not good, there must be some better way.

I created _simple_form.html.twig:

{{
    form(rename_form, {
        action: rename_form.vars.action ~ '&referer=' ~ referer,
        method: 'POST',
        attr: { id: 'rename-form', style: 'display: none' }
    })
}}

{{ 'rename_modal.title'|trans(_trans_parameters, 'EasyAdminBundle') }}

{{ 'rename_modal.content'|trans(_trans_parameters, 'EasyAdminBundle') }}

                <input class="form-control" type="text" />

                <button type="button" data-dismiss="modal" class="btn">
                    {{ 'action.cancel'|trans(_trans_parameters, _translation_domain) }}
                </button>

                {% if easyadmin_action_is_enabled(view, 'rename', _entity_config.name) %}
                    {% set _rename_action = easyadmin_get_action(view, 'rename', _entity_config.name) %}
                    <button type="button" data-dismiss="modal" class="btn btn-danger" id="modal-rename-button" formtarget="{{ _rename_action.target }}">
                        {% if _rename_action.icon %}{% endif %}
                        {{ 'rename_modal.action'|trans(_trans_parameters, 'EasyAdminBundle') }}
                    </button>
                {% endif %}

In config.yml is a new option:

list:
                actions:
                    rename:    { name: rename,    type: method, label: 'Rename', css_class: 'btn btn-primary', icon: pencil }

In list.html.twig which I'm using:

{% block main %}

{% block rename_form %}
        {% set referer = paginator.currentPage == paginator.nbPages and 1 != paginator.currentPage and 1 == paginator.currentPageResults.count
            ? path('easyadmin', app.request.query|merge({ page: app.request.query.get('page') - 1 }))
            : app.request.requestUri
        %}

        {{ include('@EasyAdmin/default/includes/_simple_form.html.twig', {
            view: 'list',
            referer: referer|url_encode,
            rename_form: rename_form_template,
            _translation_domain: _entity_config.translation_domain,
            _trans_parameters: _trans_parameters,
            _entity_config: _entity_config,
        }, with_context = false) }}
    {% endblock rename_form %}
{% endblock %}

{% block body_javascript %}
    {{ parent() }}

{% endblock %}

And finally controller:

protected function createRenameForm($entityName, $entityId, $name)
    {
        $formBuilder = $this->get('form.factory')->createNamedBuilder('rename_form')
            ->setAction($this->generateUrl('easyadmin', array('action' => 'rename', 'entity' => $entityName, 'id' => $entityId, 'name' => $name)))
            ->setMethod('POST')
        ;

        $formBuilder->add('submit', LegacyFormHelper::getType('submit'), array('label' => 'rename_modal.action', 'translation_domain' => 'EasyAdminBundle'));
        $formBuilder->add('_easyadmin_rename_flag', LegacyFormHelper::getType('hidden'), array('data' => '1'));

        return $formBuilder->getForm();
    }

    public function listAction() {
        $this->dispatch(EasyAdminEvents::PRE_LIST);

        $fields = $this->entity['list']['fields'];
        $paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), $this->config['list']['max_results'], $this->request->query->get('sortField'), $this->request->query->get('sortDirection'), $this->entity['list']['dql_filter']);

        $this->dispatch(EasyAdminEvents::POST_LIST, array('paginator' => $paginator));

        return $this->render($this->entity['templates']['list'], array(
            'title' => 'Branches',
            'entity' => $this->entity['name'],
            'currentBranch' => $this->repo->getCurrentBranchName(),
            'paginator' => $paginator,
            'fields' => $fields,
            'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
            'rename_form_template' => $this->createRenameForm($this->entity['name'], '__id__', '__name__')->createView(),
        ));
    }

Body:
I had a similar issue because I wanted to show a modal before to perform a custom action. So what I did was modify the button action with jquery

$(document).ready(function () {
    var $archiveButton = $('a.action-archive');

    $archiveButton.attr('href', '#');
    $archiveButton.attr('data-toggle', 'modal');
    $archiveButton.attr('data-target', '#archive-modal');
    $archiveButton.attr('data-url', '/url/to/load/form/inside/modal/body');
});

I don't know if it is the better way, but it helped me to show some info to the user before execute the archiveAction() in the AdminController

EDITED: a way to access POST variables

You can access to POST variables through the Container

public function renameAction()
    {
        $name = $this->container->get('request')->get('your variable');
        var_dump($name);
        die();
        return $this->redirectToRoute('admin', ['entity' => 'Branch', 'action'     => 'list']);
    }

Play a while with the $this->container->get('request') to find what you are looking for


来源: stackexchange

问:
Windows XP socket error with recv()
I'm having a strange behaviour with the recv() function.

My C++ (MFC) application with WinSock implements a simple HTTP client (non-blocking socket) for accessing HTML pages on a web server. Some of these pages are taking a few seconds for loading. On Windows 7 this is not a problem, because recv() also returns partial data. But on Windows XP the recv() function always returns SOCKET_ERROR and the error code is WSAEWOULDBLOCK. Only when the connection is finished the data is returned in one access.

Does anyone know this problem? How can I force Windows XP to also receive partial data?

I setted the buffer size (SO_RCVBUF) to 1000 Bytes. On Windows 7 this is also reflected to the TCP Window Size - on XP not.

The real problem which I have with this issue is, that I don't know how to check if the connection is still alive or not. How can I check if a connection is still alive? Or how can I specify a timeout (max time between two received packets from the server)?

答:
By default, a socket operates in blocking mode, so the only way you can get a WSAEWOULDBLOCK error at all is if you explicitly put the socket into non-blocking mode instead.  Doing so, you agree to handle WSAEWOULDBLOCK (otherwise, don't use non-blocking mode).

WSAEWOULDBLOCK is not a real error, it is just an indication that the operation you attempted to perform cannot be completed at that moment because it would block the calling thread.  You need to detect this "error" and simply retry the same operation again at a later time, preferably after a socket state change is detected.

For recv(), WSAEWOULDBLOCK simply means there is no data available on the socket to be read at that moment.  In non-blocking mode, you should be using select() (or WSAEventSelect(), or WSAAsyncSelect(), or Overlapped I/O, or an I/O Completion Port) to detect inbound data before you then read it.

That being said, you are implementing an HTTP client, so you must follow the HTTP protocol properly, regardless of the socket I/O mode you are using, regardless of your socket buffer sizes.  You must follow the pseudo code logic I outlined in this answer on another question:

You must follow the rules outlined in RFC 2616.  Namely:

Read until the "\r\n\r\n" sequence is encountered.  Do not read any more bytes past that yet.

Analyze the received headers, per the rules in RFC 2616 Section 4.4.  They tell you the actual format of the remaining response data.

Read the data per the format discovered in #2.

Check the received headers for the presence of a  Connection: close header if the response is using HTTP 1.1, or the lack of a Connection: keep-alive header if the response is using HTTP 0.9 or 1.0.  If detected, close your end of the socket connection because the server is closing its end.  Otherwise, keep the connection open and re-use it for subsequent requests (unless you are done using the connection, in which case do close it).

Process the received data as needed.

In short, you need to do something more like this instead (pseudo code):

```<code>string headers[];
byte data[];

string statusLine = read a CRLF-delimited line;
int statusCode = extract from status line;
string responseVersion = extract from status line;

do
{
    string header = read a CRLF-delimited line;
    if (header == "") break;
    add header to headers list;
}
while (true);

if ( !((statusCode in [1xx, 204, 304]) || (request was "HEAD")) )
{
    if (headers["Transfer-Encoding"] ends with "chunked")
    {
        do
        {
            string chunk = read a CRLF delimited line;
            int chunkSize = extract from chunk line;
            if (chunkSize == 0) break;

            read exactly chunkSize number of bytes into data storage;

            read and discard until a CRLF has been read;
        }
        while (true);

        do
        {
            string header = read a CRLF-delimited line;
            if (header == "") break;
            add header to headers list;
        }
        while (true);
    }
    else if (headers["Content-Length"] is present)
    {
        read exactly Content-Length number of bytes into data storage;
    }
    else if (headers["Content-Type"] == "multipart/byteranges")
    {
        string boundary = extract from Content-Type header;
        read into data storage until terminating boundary has been read;
    }
    else
    {
        read bytes into data storage until disconnected;
    }
}

if (!disconnected)
{
    if (responseVersion == "HTTP/1.1")
    {
        if (headers["Connection"] == "close")
            close connection;
    }
    else
    {
        if (headers["Connection"] != "keep-alive")
            close connection;
    }
}

check statusCode for errors;
process data contents, per info in headers list;
</code>```

As you can see, HTTP requires reading CRLF-delimited lines of text, or fixed lengths of raw bytes.  To do that, you must call recv() in a loop until you encounter the terminating CRLF, or have received the expected number of bytes, whichever the case may be.  Whether you use a synchronous loop that just ignores WSAEWOULDBLOCK errors while looping, or you use a state machine driven by asynchronous events/callbacks, that is up to you to decide.  That doesn't change how you must process the HTTP protocol.

This applies to all versions of Windows (even all platforms that use BSD-style socket APIs).  What you are encountering is not a Windows bug at all.  It is an underlying flaw in your understanding of how to use socket I/O correctly and effectively.

As for checking if the connection is alive, recv() will return 0 if the server closed the connection gracefully, or will report an error otherwise (usually WSAECONNABORTED or WSAECONNRESET, though there can be others).  But an abnormal disconnect may take a long time to detect, so you should implement timeouts in your code instead.  In synchronous mode, you can use setsockopt(SO_RCVTIMEO). In non-blocking mode, you can use select().  In asynchronous (overlapped) mode, you can use WaitForSingleObject() on whatever event/object you use to drive your state machine.

ContentLicense: CC BY-SA 3.0

Title: Windows XP socket error with recv()

Body:
By default, a socket operates in blocking mode, so the only way you can get a WSAEWOULDBLOCK error at all is if you explicitly put the socket into non-blocking mode instead.  Doing so, you agree to handle WSAEWOULDBLOCK (otherwise, don't use non-blocking mode).

WSAEWOULDBLOCK is not a real error, it is just an indication that the operation you attempted to perform cannot be completed at that moment because it would block the calling thread.  You need to detect this "error" and simply retry the same operation again at a later time, preferably after a socket state change is detected.

For recv(), WSAEWOULDBLOCK simply means there is no data available on the socket to be read at that moment.  In non-blocking mode, you should be using select() (or WSAEventSelect(), or WSAAsyncSelect(), or Overlapped I/O, or an I/O Completion Port) to detect inbound data before you then read it.

That being said, you are implementing an HTTP client, so you must follow the HTTP protocol properly, regardless of the socket I/O mode you are using, regardless of your socket buffer sizes.  You must follow the pseudo code logic I outlined in this answer on another question:

You must follow the rules outlined in RFC 2616.  Namely:

Read until the "\r\n\r\n" sequence is encountered.  Do not read any more bytes past that yet.

Analyze the received headers, per the rules in RFC 2616 Section 4.4.  They tell you the actual format of the remaining response data.

Read the data per the format discovered in #2.

Check the received headers for the presence of a  Connection: close header if the response is using HTTP 1.1, or the lack of a Connection: keep-alive header if the response is using HTTP 0.9 or 1.0.  If detected, close your end of the socket connection because the server is closing its end.  Otherwise, keep the connection open and re-use it for subsequent requests (unless you are done using the connection, in which case do close it).

Process the received data as needed.

In short, you need to do something more like this instead (pseudo code):

string headers[];
byte data[];

string statusLine = read a CRLF-delimited line;
int statusCode = extract from status line;
string responseVersion = extract from status line;

do
{
    string header = read a CRLF-delimited line;
    if (header == "") break;
    add header to headers list;
}
while (true);

if ( !((statusCode in [1xx, 204, 304]) || (request was "HEAD")) )
{
    if (headers["Transfer-Encoding"] ends with "chunked")
    {
        do
        {
            string chunk = read a CRLF delimited line;
            int chunkSize = extract from chunk line;
            if (chunkSize == 0) break;

            read exactly chunkSize number of bytes into data storage;

            read and discard until a CRLF has been read;
        }
        while (true);

        do
        {
            string header = read a CRLF-delimited line;
            if (header == "") break;
            add header to headers list;
        }
        while (true);
    }
    else if (headers["Content-Length"] is present)
    {
        read exactly Content-Length number of bytes into data storage;
    }
    else if (headers["Content-Type"] == "multipart/byteranges")
    {
        string boundary = extract from Content-Type header;
        read into data storage until terminating boundary has been read;
    }
    else
    {
        read bytes into data storage until disconnected;
    }
}

if (!disconnected)
{
    if (responseVersion == "HTTP/1.1")
    {
        if (headers["Connection"] == "close")
            close connection;
    }
    else
    {
        if (headers["Connection"] != "keep-alive")
            close connection;
    }
}

check statusCode for errors;
process data contents, per info in headers list;

As you can see, HTTP requires reading CRLF-delimited lines of text, or fixed lengths of raw bytes.  To do that, you must call recv() in a loop until you encounter the terminating CRLF, or have received the expected number of bytes, whichever the case may be.  Whether you use a synchronous loop that just ignores WSAEWOULDBLOCK errors while looping, or you use a state machine driven by asynchronous events/callbacks, that is up to you to decide.  That doesn't change how you must process the HTTP protocol.

This applies to all versions of Windows (even all platforms that use BSD-style socket APIs).  What you are encountering is not a Windows bug at all.  It is an underlying flaw in your understanding of how to use socket I/O correctly and effectively.

As for checking if the connection is alive, recv() will return 0 if the server closed the connection gracefully, or will report an error otherwise (usually WSAECONNABORTED or WSAECONNRESET, though there can be others).  But an abnormal disconnect may take a long time to detect, so you should implement timeouts in your code instead.  In synchronous mode, you can use setsockopt(SO_RCVTIMEO). In non-blocking mode, you can use select().  In asynchronous (overlapped) mode, you can use WaitForSingleObject() on whatever event/object you use to drive your state machine.


问:
Send mail trough TELNET over OVH with .batch script
I would like to use TELNET to send an email with the content of log.txt using one of my OVH mail accounts (noreply@clement.business hosted on OVH) to a gmail address. Due to my society security politics I am not able to install anything on the servers but the OS itself.

So I tried with both batch and PowerShell but without success, I even tried manually, I can telnet OVH but then don't know how to login.

Here's a few things I tried :

```<code>$subject = $args[0]

# Create from/to addresses
$from = New-Object system.net.mail.MailAddress "noreply@clement.business"
$to = New-Object system.net.mail.MailAddress "random@gmail.com"

# Create Message
$message = new-object system.net.mail.MailMessage $from, $to
$message.Subject = $subject
$message.Body = @"
Am I even suppose to write here
"@

# Set SMTP Server and create SMTP Client
$server = "I have no idea how to OVH here"
$client = new-object system.net.mail.smtpclient $server... Server what, POP3 ?

# Do
"Sending an e-mail message to {0} by using SMTP host {1} port {2}." -f $to.ToString(), $client.Host, $client.Port
try {
$client.Send($message)
}
catch {
"Exception caught in CreateTestMessage: {0}" -f $Error.ToString()
}
</code>```

I cannot figure that out, it is such a struggle to deal with...

PS : I did use the OVH guide about POP3/SMTP setup, but did not work, or I have no idea what I am doing. Useful link here as well.

答:
Just so you know the difference: POP3 is used to receive email, SMTP is used to send email. You can't use them interchangeably.

A quick google for 'ovh smtp server' shows that the ovh help pages list the SMTP servers as:

```Server name: ns0.ovh.net
Port of the outgoing server: 587
Username: identical to the email address
Password: your password for your account, as defined in the creation of the email address```

I can't test these as I don't have an ovh account.

I would use Send-MailMessage to send the email as it's much easier to use than your solution:'

This will send an email with the file log.txt as an attachment:

```<code>$username = "noreply@clement.business"
$password = "passwordforemailaddress" | ConvertTo-SecureString
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password

$parms = @{
    From = "noreply@clement.business"
    To = "email@gmail.com"
    Attachment = "C:\folder\log.txt"
    Subject = "Daily Logs"
    Body = "Your body text here"
    SMTPServer = "ns0.ovh.net"
    SMTPPort = "587"
    Credential = $credentials
}
Send-MailMessage @params
</code>```

And these params this will use log.txt as the email body text:

```<code>$parms = @{
    From = "noreply@clement.business"
    To = "email@gmail.com"
    Body = Get-Content "C:\folder\log.txt"
    Subject = "Daily Logs"
    SMTPServer = "ns0.ovh.net"
    SMTPPort = "587"
    Credential = $credentials
}
</code>```

Body:
I would like to use TELNET to send an email with the content of log.txt using one of my OVH mail accounts (noreply@clement.business hosted on OVH) to a gmail address. Due to my society security politics I am not able to install anything on the servers but the OS itself.

So I tried with both batch and PowerShell but without success, I even tried manually, I can telnet OVH but then don't know how to login.

Here's a few things I tried :

$subject = $args[0]

# Create from/to addresses
$from = New-Object system.net.mail.MailAddress "noreply@clement.business"
$to = New-Object system.net.mail.MailAddress "random@gmail.com"

# Create Message
$message = new-object system.net.mail.MailMessage $from, $to
$message.Subject = $subject
$message.Body = @"
Am I even suppose to write here
"@

# Set SMTP Server and create SMTP Client
$server = "I have no idea how to OVH here"
$client = new-object system.net.mail.smtpclient $server... Server what, POP3 ?

# Do
"Sending an e-mail message to {0} by using SMTP host {1} port {2}." -f $to.ToString(), $client.Host, $client.Port
try {
$client.Send($message)
}
catch {
"Exception caught in CreateTestMessage: {0}" -f $Error.ToString()
}

I cannot figure that out, it is such a struggle to deal with...

PS : I did use the OVH guide about POP3/SMTP setup, but did not work, or I have no idea what I am doing. Useful link here as well.

Body:
Just so you know the difference: POP3 is used to receive email, SMTP is used to send email. You can't use them interchangeably.

A quick google for 'ovh smtp server' shows that the ovh help pages list the SMTP servers as:

Server name: ns0.ovh.net
Port of the outgoing server: 587
Username: identical to the email address
Password: your password for your account, as defined in the creation of the email address

I can't test these as I don't have an ovh account.

I would use Send-MailMessage to send the email as it's much easier to use than your solution:'

This will send an email with the file log.txt as an attachment:

$username = "noreply@clement.business"
$password = "passwordforemailaddress" | ConvertTo-SecureString
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password

$parms = @{
    From = "noreply@clement.business"
    To = "email@gmail.com"
    Attachment = "C:\folder\log.txt"
    Subject = "Daily Logs"
    Body = "Your body text here"
    SMTPServer = "ns0.ovh.net"
    SMTPPort = "587"
    Credential = $credentials
}
Send-MailMessage @params

And these params this will use log.txt as the email body text:

$parms = @{
    From = "noreply@clement.business"
    To = "email@gmail.com"
    Body = Get-Content "C:\folder\log.txt"
    Subject = "Daily Logs"
    SMTPServer = "ns0.ovh.net"
    SMTPPort = "587"
    Credential = $credentials
}


问:
RXJS do operator not getting hit in stream when subscribe is called without a callback parameter
I am experimenting with a Redux-like pattern to maintain state in a service for a particular feature. My intent is that a consumer can subscribe to separate streams of data by calling getItem1() or getItem2(), then call action methods such as initializeItem1() or initializeItem2() on the service as desired to dispatch actions that will change the state of the store. In the service, data may be obtained either from an http call or something else as is simulated in the provided plnkr.

https://plnkr.co/edit/f3HLp5C8ckIpjNsM8dTm?p=preview

Specifically, what I do not understand is why, in my sample code, the observable returned by getItem1() does not emit a value unless I change this.service.initializeItem1().subscribe(); to this.service.initializeItem1().subscribe(() => {});. Can someone please explain if this seems like a bug in rxjs, if there is a good / known explanation as to why this behaves this way, or if I am just missing something? I appreciate any insight the community can provide me with. Thanks.

Component

```<code>//our root app component
import {Component, OnInit} from '@angular/core'
import {Observable} from 'rxjs/Rx'
import {SampleService} from './sample.service'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Item 1 Value</h2>
      <div>{{ item1 }}</div>

      <h2>Item 2 Value</h2>
      <div>{{ item2 }}</div>
    </div>
  `,
})
export class App implements OnInit {
  name:string;
  item1: string;
  item2: string;
  constructor(private service: SampleService) { }

  ngOnInit() {
    this.item1 = this.service.getItem1().subscribe(item1 => this.item1 = item1);
    this.item2 = this.service.getItem2().subscribe(item2 => this.item2 = item2);

    /* broken */
    //Item 1 does not display
    //Item 2 displays as expected
    this.scenario1();

    /* works */
    //Item 1 displays as expected
    //Item 2 displays as expected
    // this.scenario2();
  }

  private scenario1() {
    this.service.initializeItem1().subscribe();
    this.service.initializeItem2().subscribe();
  }

  private scenario2() {
    this.service.initializeItem1().subscribe(() => {});
    this.service.initializeItem2().subscribe();
  }
}
</code>```

Service

```<code>import {Injectable} from '@angular/core'
import {Observable, Subject} from 'rxjs/Rx'
import { Http, Headers } from '@angular/http';

@Injectable()
export class SampleService {
  constructor(private http: Http) { }
  private headers: Headers = new Headers({ 'Content-Type': 'application/json' });
  private _store: Subject<any> = new Subject<any>();
  private store = this._store.asObservable()
      .startWith({})
      .scan(reducer);

  public initializeItem1(): Observable<string> {
    return this.http.get('api/foobar')
      .map(response => response.json().item).do(data => {
        console.log('not hit in scenario 1, but hit in scenario 2:', data);

        this._store.next({
          type: 'INITIALIZE_1',
          payload: data
        });
      });
  }

  public initializeItem2(): Observable<string> {
    return Observable.of('foobar-2').do(data => {
      console.log('hit in scenario 1 and scenario 2:', data);

      this._store.next({
        type: 'INITIALIZE_2',
        payload: data
      });
    });
  }

  getItem1(): Observable<string> {
        return this.store.map(store => store.settings1);
    }

  getItem2(): Observable<string> {
      return this.store.map(store => store.settings2);
  }
}

function reducer(store, action) {
    switch(action.type) {
        case 'INITIALIZE_1':
            return Object.assign({ }, store, {
                initialSettings: action.payload,
                settings1: action.payload
            });
        case 'INITIALIZE_2':
            return Object.assign({ }, store, { settings2:action.payload });
        default:
            return store;
    }
}
</code>```

答:
This is a bug in RxJS 5 up to the RxJS 5.2.0 version. It's fixed already but it hasn't been released yet.

The only workaround is to use any subscriber for example () => {} (I think using just {} should work as well).

Merged PR on RxJS GitHub fixing this issue:

https://github.com/ReactiveX/rxjs/pull/2238

Related Issues:

https://github.com/ReactiveX/rxjs/issues/2283

https://github.com/ReactiveX/rxjs/issues/2237

Body:
I am experimenting with a Redux-like pattern to maintain state in a service for a particular feature. My intent is that a consumer can subscribe to separate streams of data by calling getItem1() or getItem2(), then call action methods such as initializeItem1() or initializeItem2() on the service as desired to dispatch actions that will change the state of the store. In the service, data may be obtained either from an http call or something else as is simulated in the provided plnkr.

https://plnkr.co/edit/f3HLp5C8ckIpjNsM8dTm?p=preview

Specifically, what I do not understand is why, in my sample code, the observable returned by getItem1() does not emit a value unless I change this.service.initializeItem1().subscribe(); to this.service.initializeItem1().subscribe(() => {});. Can someone please explain if this seems like a bug in rxjs, if there is a good / known explanation as to why this behaves this way, or if I am just missing something? I appreciate any insight the community can provide me with. Thanks.

Component

//our root app component
import {Component, OnInit} from '@angular/core'
import {Observable} from 'rxjs/Rx'
import {SampleService} from './sample.service'

@Component({
  selector: 'my-app',
  template: `

Item 1 Value

{{ item1 }}

Item 2 Value

{{ item2 }}

  `,
})
export class App implements OnInit {
  name:string;
  item1: string;
  item2: string;
  constructor(private service: SampleService) { }

  ngOnInit() {
    this.item1 = this.service.getItem1().subscribe(item1 => this.item1 = item1);
    this.item2 = this.service.getItem2().subscribe(item2 => this.item2 = item2);

    /* broken */
    //Item 1 does not display
    //Item 2 displays as expected
    this.scenario1();

    /* works */
    //Item 1 displays as expected
    //Item 2 displays as expected
    // this.scenario2();
  }

  private scenario1() {
    this.service.initializeItem1().subscribe();
    this.service.initializeItem2().subscribe();
  }

  private scenario2() {
    this.service.initializeItem1().subscribe(() => {});
    this.service.initializeItem2().subscribe();
  }
}

Service

import {Injectable} from '@angular/core'
import {Observable, Subject} from 'rxjs/Rx'
import { Http, Headers } from '@angular/http';

@Injectable()
export class SampleService {
  constructor(private http: Http) { }
  private headers: Headers = new Headers({ 'Content-Type': 'application/json' });
  private _store: Subject<any> = new Subject<any>();
  private store = this._store.asObservable()
      .startWith({})
      .scan(reducer);

  public initializeItem1(): Observable<string> {
    return this.http.get('api/foobar')
      .map(response => response.json().item).do(data => {
        console.log('not hit in scenario 1, but hit in scenario 2:', data);

        this._store.next({
          type: 'INITIALIZE_1',
          payload: data
        });
      });
  }

  public initializeItem2(): Observable<string> {
    return Observable.of('foobar-2').do(data => {
      console.log('hit in scenario 1 and scenario 2:', data);

      this._store.next({
        type: 'INITIALIZE_2',
        payload: data
      });
    });
  }

  getItem1(): Observable<string> {
        return this.store.map(store => store.settings1);
    }

  getItem2(): Observable<string> {
      return this.store.map(store => store.settings2);
  }
}

function reducer(store, action) {
    switch(action.type) {
        case 'INITIALIZE_1':
            return Object.assign({ }, store, {
                initialSettings: action.payload,
                settings1: action.payload
            });
        case 'INITIALIZE_2':
            return Object.assign({ }, store, { settings2:action.payload });
        default:
            return store;
    }
}


问:
"Lock" character selection in python regular expressions
How would you create a pattern that would be able to take any character, but any subsequent characters should be the same as the first? For example, ax + bx + x, where a, b, and x can be any character, but the 'x' character must stay the same.
I am trying to create a pattern to recognize quadratics(ax^2+bx+c), but I realized that with my pattern,  using 2 different letters would match the pattern.
The pattern:</p>

```<code> r"([\d+]*)([\D])\^2\+?\-?([\d+]*)([^\+\-\d])\+?\-?([\d+])+$"
</code>```

答:
This might be a better job for a parser. Even if it's just for matching. However if you insist on using regex, then it can be done by doing:

```<code>^(?:\d+|\D)(\D)(?:[+\-*\/^](?:\d+\1?|\D\1?))+$
</code>```

Which will match input like:

```<code>ax
ax+bx+x
ay+ay+y
ax^2+bx+c
</code>```

It works by matching \D then capturing the subsequent \D. Then every time it finds 2 characters, the second character must be that previously matched character (\D\1?).

Live preview

If you want to be able to have stuff like 2+ beforehand. Then it gets a bit more tricky:

```<code>^(?:\d+[+\-*\/^](?:\d+[+\-*\/^])*)?\D(\D)(?:[+\-*\/^](?:\d+\1?|\D\1?))*$
</code>```

Which will match input like:

```<code>ax
ax+bx+x
ay+ay+y
ax^2+bx+c
2+ax
2+ax+bx
2-1+ax+bx
</code>```

Live preview

If you need to match decimals and not just integers, then change those \d+ into \d+(?:\.\d+)?.

```<code>^(?:\d+(?:\.\d+)?[+\-*\/^](?:\d+(?:\.\d+)?[+\-*\/^])*)?\D(\D)(?:[+\-*\/^](?:\d+(?:\.\d+)?\1?|\D\1?))*$
</code>```

Note that this doesn't take whitespaces into account, so you'd have to sprinkle a few \s* around if that is needed.

Body:
How would you create a pattern that would be able to take any character, but any subsequent characters should be the same as the first? For example, ax + bx + x, where a, b, and x can be any character, but the 'x' character must stay the same.
I am trying to create a pattern to recognize quadratics(ax^2+bx+c), but I realized that with my pattern,  using 2 different letters would match the pattern.
The pattern:

 r"([\d+]*)([\D])\^2\+?\-?([\d+]*)([^\+\-\d])\+?\-?([\d+])+$"

Body:
This might be a better job for a parser. Even if it's just for matching. However if you insist on using regex, then it can be done by doing:

^(?:\d+|\D)(\D)(?:[+\-*\/^](?:\d+\1?|\D\1?))+$

Which will match input like:

ax
ax+bx+x
ay+ay+y
ax^2+bx+c

It works by matching \D then capturing the subsequent \D. Then every time it finds 2 characters, the second character must be that previously matched character (\D\1?).

Live preview

If you want to be able to have stuff like 2+ beforehand. Then it gets a bit more tricky:

^(?:\d+[+\-*\/^](?:\d+[+\-*\/^])*)?\D(\D)(?:[+\-*\/^](?:\d+\1?|\D\1?))*$

Which will match input like:

ax
ax+bx+x
ay+ay+y
ax^2+bx+c
2+ax
2+ax+bx
2-1+ax+bx

Live preview

If you need to match decimals and not just integers, then change those \d+ into \d+(?:\.\d+)?.

^(?:\d+(?:\.\d+)?[+\-*\/^](?:\d+(?:\.\d+)?[+\-*\/^])*)?\D(\D)(?:[+\-*\/^](?:\d+(?:\.\d+)?\1?|\D\1?))*$

Note that this doesn't take whitespaces into account, so you'd have to sprinkle a few \s* around if that is needed.


问:
Jaxb generated xml - problem with root element prefix
I am trying to generate xml using jaxb. I created xsd and generated java classes.
But when I generate xml, I am geeting prefix ns2 to the root tag, which I don't want.

ex: I want root tag to be

```<code> <report>
   <id>rep 1</id>
</report>
</code>```

, But getting as

```<code><ns2:report>
....
</ns2:report>
</code>```

In the generated java class, I gave annotation as @XmlRootElement(name="report",namespace="urn:report")

Can some one pls help

答: Take a look at this answer. It describes how to use a SAX Filter to remove any namespace.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am trying to generate xml using jaxb. I created xsd and generated java classes.
But when I generate xml, I am geeting prefix ns2 to the root tag, which I don't want.

ex: I want root tag to be

 <report>
   <id>rep 1</id>
</report>

, But getting as

<ns2:report>
....
</ns2:report>

In the generated java class, I gave annotation as @XmlRootElement(name="report",namespace="urn:report")

Can some one pls help


问:
Remove standard SAS libraries from GUI
I'd like to remove/delete/unassign the standard SAS libraries from my SAS 9.3 GUI.

I've tried two solutions to remove a library which haven't worked:

%sysfunc(libname(maps)) results in:

ERROR 180-322: Statement is not valid or it is used out of proper order.

Comment out the offending start up code in the file sasv9.cfg

I don't have permission to modify (C:\Program Files...) files in that directory

Thanks!

The libraries are:
 - Maps

Mapsgfk

Mapssas

Sashelp

Sasuser

答:
You got the 180-322 because the libname function returns a value and you call it in open code and the code it generated is not valid.

```<code>29         %put NOTE: %sysfunc(libname(maps));
NOTE: -630193
</code>```

Do as above an you will see the value.  However it looks like you cannot clear LIBREF MAPS.

Title: Remove standard SAS libraries from GUI

Body:
You got the 180-322 because the libname function returns a value and you call it in open code and the code it generated is not valid.

29         %put NOTE: %sysfunc(libname(maps));
NOTE: -630193

Do as above an you will see the value.  However it looks like you cannot clear LIBREF MAPS.


问:
Creating a non-tracking in-app web browser
I am trying to create a webview (as an exercise) that does not track or store any browsing history locally.

I have made it so that when the webview is closed, it calls the following

```<code>[[NSURLSession sharedSession]resetWithCompletionHandler:^{}];
</code>```

but I am finding that things like google search history persists some how between sessions. I have also tried clearing cookies separately through

```<code>NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [storage cookies]) {
       [storage deleteCookie:cookie];
    }
[[NSUserDefaults standardUserDefaults] synchronize];
</code>```

still to no avail. Google searches still show when a new web view is created.

Is anyone aware of a way to remove the identifier that google is using to match that search history back to me? I'm concerned it's something like the bundle identifier, which is probably a bit trickier to prevent being read.

Any ideas are appreciated.

Regards,

Luke

答:
To compliment Durai Amuthan.H's answer, here is the answer for us plebs who still like to use Obj-C  </p>

```<code>WKWebViewConfiguration * config = [WKWebViewConfiguration new];
config.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
webView = [[WKWebView alloc]initWithFrame:viewFrame configuration:config];
</code>```

Body:
I am trying to create a webview (as an exercise) that does not track or store any browsing history locally.

I have made it so that when the webview is closed, it calls the following

[[NSURLSession sharedSession]resetWithCompletionHandler:^{}];

but I am finding that things like google search history persists some how between sessions. I have also tried clearing cookies separately through

NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [storage cookies]) {
       [storage deleteCookie:cookie];
    }
[[NSUserDefaults standardUserDefaults] synchronize];

still to no avail. Google searches still show when a new web view is created.

Is anyone aware of a way to remove the identifier that google is using to match that search history back to me? I'm concerned it's something like the bundle identifier, which is probably a bit trickier to prevent being read.

Any ideas are appreciated.

Regards,

Luke

Body:
To compliment Durai Amuthan.H's answer, here is the answer for us plebs who still like to use Obj-C

WKWebViewConfiguration * config = [WKWebViewConfiguration new];
config.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
webView = [[WKWebView alloc]initWithFrame:viewFrame configuration:config];


问:
AccessDenied for ListObjects for S3 bucket when permissions are s3:*
I am getting:

An error occurred (AccessDenied) when calling the ListObjects operation: Access Denied

When I try to get folder from my S3 bucket.

Using this command:

```<code>aws s3 cp s3://bucket-name/data/all-data/ . --recursive
</code>```

The IAM permissions for the bucket look like this:

```<code>{
"Version": "version_id",
"Statement": [
    {
        "Sid": "some_id",
        "Effect": "Allow",
        "Action": [
            "s3:*"
        ],
        "Resource": [
            "arn:aws:s3:::bucketname/*"
        ]
    }
] }
</code>```

What do I need to change to be able to copy and ls successfully?

答:
I was unable to access to S3 because

first I configured key access on the instance (it was impossible to attach role after the launch then)

forgot about it for a few months

attached role to instance

tried to access.
The configured key had higher priority than role, and access was denied because the user wasn't granted with necessary S3 permissions.

Solution: rm -rf .aws/credentials, then aws uses role.

ContentLicense: CC BY-SA 4.0

Body:
I am getting:

An error occurred (AccessDenied) when calling the ListObjects operation: Access Denied

When I try to get folder from my S3 bucket.

Using this command:

aws s3 cp s3://bucket-name/data/all-data/ . --recursive

The IAM permissions for the bucket look like this:

{
"Version": "version_id",
"Statement": [
    {
        "Sid": "some_id",
        "Effect": "Allow",
        "Action": [
            "s3:*"
        ],
        "Resource": [
            "arn:aws:s3:::bucketname/*"
        ]
    }
] }

What do I need to change to be able to copy and ls successfully?


问:
lines in a file with comma
I would like to know how to create a sub file with a number of commas, for example.

123,abc,qwe,ert

123,456,abc,qwe,fgh

I want to create a file .txt with the line that has 4 commas. (123,456,abc,qwe,fgh).

I tried with this.

awk -F\, '{print NF-1}'

But only gives me the number of commas that each line has.

答:
I want to create a file .txt with the line that has 4 commas.

Alternative sed approach:

```<code>cat testfile | sed -En 's/^([^,]+,){4}[^,]*$/&/p' > file.txt
</code>```

Title: lines in a file with comma

Body:
I want to create a file .txt with the line that has 4 commas.

Alternative sed approach:

cat testfile | sed -En 's/^([^,]+,){4}[^,]*$/&/p' > file.txt


问:
PHP - Add form element before submit - Buy Button
I need to dynamically add form elements to an HTML form as soon as the Submit button is clicked but before the POST data is sent to a server. The new elements must be "read" from a PHP file on my server.

HISTORY:
Currently my HTML form has "hidden" fields that are submitted to another server for processing. I have no control over the other server. My problem is that anyone can edit these hidden fields.

How can I dynamically add form elements to the POST data as soon as the form is submitted?

答:
If you need any control over what is submitted to the other server, you have to do that yourself. Make the form submit to your own server, then validate it, add your data and re-submit it to the other server.

You can use the CURL extension in PHP to post data from your server.


问:
How to run a command in child process in grunt tasks?
I want to write a grunt task, which will start a server, and run some tests based on that server:

```<code>grunt.initConfig({
    shell: {
      sbtRun: {
        options: {
          stdout: true
        },
        command: './sbt run'
      }
   }
});

grunt.loadNpmTasks('grunt-shell');

grunt.registerTask('run-test-only', ...);

grunt.registerTask('start-server-and-test', ['shell:sbtRun', 'run-test-only']);
</code>```

But the problem is, the task ./sbt run is not running in daemon. When I run:

```<code>grunt start-server-and-test
</code>```

It will blocking in the shell:sbtRun task forever.

Is there any way to start it in a child process? So the second task run-test-only will be called, and the server will be destroyed automatically after testing?

答:
I was facing a similar issue. I wanted to connect to a database and store the result of a query in a .csv. I created a separate file to do all that work and I was successful in running that file through the command line using:

```<code>node filename.js
</code>```

I used grunt-shell and grunt-exec to run this command but everytime I saw the same error:

```<code>const child = require('child_process').exec;
</code>```

Then, I found another grunt plugin i.e grunt-execute which was able to create a child process and the task was completed successfully. You could find more about grunt-execute here, https://www.npmjs.com/package/grunt-execute.

Hope this helps.

Body:
I want to write a grunt task, which will start a server, and run some tests based on that server:

grunt.initConfig({
    shell: {
      sbtRun: {
        options: {
          stdout: true
        },
        command: './sbt run'
      }
   }
});

grunt.loadNpmTasks('grunt-shell');

grunt.registerTask('run-test-only', ...);

grunt.registerTask('start-server-and-test', ['shell:sbtRun', 'run-test-only']);

But the problem is, the task ./sbt run is not running in daemon. When I run:

grunt start-server-and-test

It will blocking in the shell:sbtRun task forever.

Is there any way to start it in a child process? So the second task run-test-only will be called, and the server will be destroyed automatically after testing?

Body:
I was facing a similar issue. I wanted to connect to a database and store the result of a query in a .csv. I created a separate file to do all that work and I was successful in running that file through the command line using:

node filename.js

I used grunt-shell and grunt-exec to run this command but everytime I saw the same error:

const child = require('child_process').exec;

Then, I found another grunt plugin i.e grunt-execute which was able to create a child process and the task was completed successfully. You could find more about grunt-execute here, https://www.npmjs.com/package/grunt-execute.

Hope this helps.


问:
Remove leading or trailing spaces in an entire column of data
How do I remove leading or trailing spaces of all cells in an entire column?

The worksheet's conventional Find and Replace (aka Ctrl+H) dialog is not solving the problem.

答:
I was able to use Find & Replace with the "Find what:" input field set to:

" * "

(space asterisk space with no double-quotes)

and "Replace with:" set to:

""

(nothing)


问:
What does TestFlight do to my iOS executable?
I hash my iOS executable at launch to verify its integrity, and have had no problems doing so until TestFlight -- which appears to modify the executable as well as install it in some funky (undocumented?) way.

Even more concerning is I get multiple hash values, which appear to vary by device or iOS version or carrier or something.  I don't own enough devices to be certain.  But none of the hashes match the one I compute prior to uploading to TestFlight.

So I have two questions: (1) What is TestFlight doing to my executable, and is the process documented somewhere?  And (2) Does the final app store release pull the same shennanigan, or something similar, or does it leave my executable unmodified from when I uploaded it?

答:
That's what code signing is for.

Code signing your app assures users that it is from a known source and
  the app hasn’t been modified since it was last signed.

Source: https://developer.apple.com/support/code-signing/

It seems like Apple encrypts your app. While this post is about App Store submission, could be the same for Test Flight (not sure about this).

See: https://stackoverflow.com/a/5784332/2019384

Also it's not recommended to verify your apps integrity by yourself, as you'll run in such issues. Besides iOS already does this for you:

Apple does not provide any supported way for you to check your app’s
  integrity.  iOS already does that by default.

Source: https://forums.developer.apple.com/thread/52801


问:
What is the difference in the following vector creations?
```<code>vector<int>myvec;
</code>```

and

```<code>vector<int>myvec[20];
</code>```

When i tried to do a standard push_back operation in second case(myvec.push_back(41))i got a compile error.
I think i need to mention the position where 41 needs to be inserted i this case.Am I right?

答: The second declaration does not create a single vector, it creates an array of 20 vectors.  You would have to do myvec[0].push_back(...) instead, to add an element to the first vector in the array.

Body:
vector<int>myvec;

and

vector<int>myvec[20];

When i tried to do a standard push_back operation in second case(myvec.push_back(41))i got a compile error.
I think i need to mention the position where 41 needs to be inserted i this case.Am I right?


问:
When is a factory appropriate?
Taken from wikipedia:

In object-oriented computer
  programming, a factory is an object
  for creating other objects. It is an
  abstraction of a constructor, and can
  be used to implement various
  allocation schemes.

Could anyone please explain when a factory class is required or beneficial?

I am currently working on a project where I have a class and use the constructor to initialize an object (duh!) but it can fail and not initialize at all. I have a Success property to check if it was created properly. Is this a good example for when a factory class should be implemented? This way the Create() method can return null and I can get rid of the Success property. Do I have the right idea?

答:
A factory's purpose is to determine, at run-time and hence potentially and often with data unavailable when the program was compiled, which of many classes, all derived from a specific class with virtual methods, should capture that data for your program.

The point is that polymorphic language features allow you to work with different types of data (sharing a common base class), invoking the type-appropriate behaviours.  To benefit from this, you need to have objects of different derived types.  When learning about this in a Comp Sci course, you probably hard-code creation of a few of each of the Derived types and play with them through pointers to the base class.  In complex real-world problems, rather than hard-coding creation it is often driven off data arriving from the programs input, such as database tables, files, and sockets.  Depending on what exactly you see at each point, you want to create an appropriately-typed object to represent it, but you'll probably need to keep a record of it using a compile-time known type: the pointer to base class.  Then, not only can you preform the operations that the base class promises - some of which may involve dynamic dispatch to the derived class's implementation, but you can also - if necessary - determine exactly what the real type of the data is and invoke actions accordingly.

For example, say you read the following file, which shows how you've collected different types of data for each:

```<code>elephant name Tip-Toes partner Mega
mule name Dare-You mane_length 132
</code>```

You have the following class heirarchy to represent these:

```<code>struct Animal
{
    Animal(const std::string& name) : name_(name) { }

    virtual void eat_from(Supplies&) = 0; // animals must do in their own way...
    virtual bool can_jump() { return false; } // some animals might, assume not...

    std::string name_;
};

struct Elephant : Animal
{
    Elephant(const std::string& name, const std::string& partner)
      : Animal(name), partner_(partner)
    { }

    std::string partner_;

    virtual void eat_from(Supplies&) { supplies.consume(Tofu, 10 * kg); }
    void swing_trunk(); // something specific to elephants
};

struct Mule : Animal
{
    Mule(const std::string& name, double kgs) : Animal(name), kilograms_(kgs) { }
    double kilograms_;

    virtual void eat_from(Supplies&) { supplies.consume(Grass, 2 * kg); }
    virtual bool can_jump() { return true; }
};
</code>```

The factory method's job is to distinguish elephant from mule and return a new object of the appropriate type (derived from - but not simply - Animal):

```<code>Animal* factory(std::istringstream& input)
{
    std::string what, name;
    if (input >> what && input >> name)
    {
        if (what == "elephant")
        {
            std::string partner;
            if (input >> partner)
                return new Elephant(name, partner);
        }
        else if (what == "mule")
        {
            double mane_length;
            if (input >> mane_length)
                return new Mule(name, mane_length);
        }
    }
    // can only reach here on unparsable input...
    throw runtime_error("can't parse input");
}
</code>```

You can then store Animal*s and perform operations on them:

```<code>std::vector<Animal*> animals;
// we expect 30 animals...
for (int i = 0; i < 30; ++i) animals.push_back(factory(std::cin));

// do things to each animal...
for (int i = 0; i < 30; ++i)
{
    Animal* p_unknown = animals[i];

    std::cout << p_unknown->name() << '\n';

    if (Elephant* p = dynamic_cast<Elephant*>(p_unknown))
        p->swing_trunk();
}
</code>```

Returning to your question:

I am currently working on a project where I have a class and use the constructor to initialize an object (duh!) but it can fail and not initialize at all. I have a Success property to check if it was created properly. Is this a good example for when a factory class should be implemented? This way the Create() method can return null and I can get rid of the Success property. Do I have the right idea?

No, not a situation where a factory is useful, as there's still only one type involved.  Just stick with what you've got (in an OO sense), but you could choose to throw an exception, abort the program etc. rather than set a flag that the called may or may not bother to check.

Title: When is a factory appropriate?

Body:
A factory's purpose is to determine, at run-time and hence potentially and often with data unavailable when the program was compiled, which of many classes, all derived from a specific class with virtual methods, should capture that data for your program.

The point is that polymorphic language features allow you to work with different types of data (sharing a common base class), invoking the type-appropriate behaviours.  To benefit from this, you need to have objects of different derived types.  When learning about this in a Comp Sci course, you probably hard-code creation of a few of each of the Derived types and play with them through pointers to the base class.  In complex real-world problems, rather than hard-coding creation it is often driven off data arriving from the programs input, such as database tables, files, and sockets.  Depending on what exactly you see at each point, you want to create an appropriately-typed object to represent it, but you'll probably need to keep a record of it using a compile-time known type: the pointer to base class.  Then, not only can you preform the operations that the base class promises - some of which may involve dynamic dispatch to the derived class's implementation, but you can also - if necessary - determine exactly what the real type of the data is and invoke actions accordingly.

For example, say you read the following file, which shows how you've collected different types of data for each:

elephant name Tip-Toes partner Mega
mule name Dare-You mane_length 132

You have the following class heirarchy to represent these:

struct Animal
{
    Animal(const std::string& name) : name_(name) { }

    virtual void eat_from(Supplies&) = 0; // animals must do in their own way...
    virtual bool can_jump() { return false; } // some animals might, assume not...

    std::string name_;
};

struct Elephant : Animal
{
    Elephant(const std::string& name, const std::string& partner)
      : Animal(name), partner_(partner)
    { }

    std::string partner_;

    virtual void eat_from(Supplies&) { supplies.consume(Tofu, 10 * kg); }
    void swing_trunk(); // something specific to elephants
};

struct Mule : Animal
{
    Mule(const std::string& name, double kgs) : Animal(name), kilograms_(kgs) { }
    double kilograms_;

    virtual void eat_from(Supplies&) { supplies.consume(Grass, 2 * kg); }
    virtual bool can_jump() { return true; }
};

The factory method's job is to distinguish elephant from mule and return a new object of the appropriate type (derived from - but not simply - Animal):

Animal* factory(std::istringstream& input)
{
    std::string what, name;
    if (input >> what && input >> name)
    {
        if (what == "elephant")
        {
            std::string partner;
            if (input >> partner)
                return new Elephant(name, partner);
        }
        else if (what == "mule")
        {
            double mane_length;
            if (input >> mane_length)
                return new Mule(name, mane_length);
        }
    }
    // can only reach here on unparsable input...
    throw runtime_error("can't parse input");
}

You can then store Animal*s and perform operations on them:

std::vector<Animal*> animals;
// we expect 30 animals...
for (int i = 0; i < 30; ++i) animals.push_back(factory(std::cin));

// do things to each animal...
for (int i = 0; i < 30; ++i)
{
    Animal* p_unknown = animals[i];

    std::cout << p_unknown->name() << '\n';

    if (Elephant* p = dynamic_cast<Elephant*>(p_unknown))
        p->swing_trunk();
}

Returning to your question:

I am currently working on a project where I have a class and use the constructor to initialize an object (duh!) but it can fail and not initialize at all. I have a Success property to check if it was created properly. Is this a good example for when a factory class should be implemented? This way the Create() method can return null and I can get rid of the Success property. Do I have the right idea?

No, not a situation where a factory is useful, as there's still only one type involved.  Just stick with what you've got (in an OO sense), but you could choose to throw an exception, abort the program etc. rather than set a flag that the called may or may not bother to check.


问:
Querying in Cassandra, retrieving from a SET of UDT
City Information as a UDT. city code will be 'work' or 'home' or 'templocation'.

```<code>CREATE TYPE facetmanager_ps1.city (
    id int,
    citycode text,
    cityname text
);
</code>```

A UDT which holds the list of part_time_employees; it has a set of city UDT

```<code>CREATE TYPE facetmanager_ps1.part_time_employees (
    firstname text,
    lastname text,
    address_set frozen<set<frozen<city>>>
);
</code>```

A table which hold the employee information.It has a set of part_time_employee_set.

```<code>CREATE TABLE facetmanager_ps1.employee (
    id int PRIMARY KEY,
    name text,
    part_time_employee_set set<frozen<part_time_employees>>,
    PRIMARY KEY (id)
)

insert into employee (id,name,part_time_employee_set)
values
( 1, 'raghu',
    {
        {
            firstname: 'r1',
            lastname:'r2',
            address_set : {
                {
                    id: 600000,
                    citycode: 'work',
                    cityname: 'chennai'
                },
                {
                    id:600020,
                    citycode: 'home',
                    cityname: 'kanchipuram'
                }
            }
        }
    }
);

update employee set part_time_employee_set
= part_time_employee_set +
{ { firstname: 'arun', lastname : 'kannan', address_set :
    {
        {
            id: 600000,
            citycode:'work',
            cityname: 'chennai'
        },
        {
            id: 600000,
            citycode:'home',
            cityname: 'chennai'
        }
    }
}} where id=1;
</code>```

select * from employee where id=1;
it gives all the part_time_employee information

My Main Issue:

Now i want only employee information of the part_time_employee r1. i want his work location and home location i.e.) i want the complete address_set
how to get that?

```<code>select * from employee where id=1 and part_time_employee_set = { { firstname: 'r1' }};
InvalidRequest: Error from server: code=2200 [Invalid query] message="Collection column 'part_time_employee_set' (set<frozen<part_time_employees>>) cannot be restricted by a '=' relation"

select * from employee where id=1 and part_time_employee_set in { { firstname: 'r1' }};
SyntaxException: line 1:64 no viable alternative at input '{' (...employee where id=1 and [part_time_employee_set] in...)
</code>```

Issue 2:(minor issue)

```<code>select * from employee;

<<set(2)>>
</code>```

how to display the expanded result in devcenter?. "Expand ON" command is not working as a command in dev center
however if i copy the values are copied, into a textedit or other editor. this is not a major concern for me at this point.

答:
You can't query with non-primary key, unless you create index.

Even if you create index on part_time_employee_set collection you can't query with a piece of a frozen field (firstname). Frozen fields means to be a compact.
And another thing you can't select a partial item in a collection. you need to select the entire collection.

If you want to query with firstname you have to change your data model.

```<code>CREATE TABLE employee (
    id int,
    firstname text,
    lastname text,
    address_set set<frozen<city>>,
    name text static,
    PRIMARY KEY (id, firstname, lastname)
);
</code>```

Now you can select address_set of part time employee who have first name 'r1'

```<code>SELECT * FROM employee_test WHERE id = 1 AND firstname = 'r1';
</code>```

Output :

```<code> id          | 1
 firstname   | r1
 lastname    | r2
 name        | raghu
 address_set | {{id: 600000, citycode: 'work', cityname: 'chennai'}, {id: 600020, citycode: 'home', cityname: 'kanchipuram'}}
</code>```

Body:
City Information as a UDT. city code will be 'work' or 'home' or 'templocation'.

CREATE TYPE facetmanager_ps1.city (
    id int,
    citycode text,
    cityname text
);

A UDT which holds the list of part_time_employees; it has a set of city UDT

CREATE TYPE facetmanager_ps1.part_time_employees (
    firstname text,
    lastname text,
    address_set frozen<set<frozen<city>>>
);

A table which hold the employee information.It has a set of part_time_employee_set.

CREATE TABLE facetmanager_ps1.employee (
    id int PRIMARY KEY,
    name text,
    part_time_employee_set set<frozen<part_time_employees>>,
    PRIMARY KEY (id)
)

insert into employee (id,name,part_time_employee_set)
values
( 1, 'raghu',
    {
        {
            firstname: 'r1',
            lastname:'r2',
            address_set : {
                {
                    id: 600000,
                    citycode: 'work',
                    cityname: 'chennai'
                },
                {
                    id:600020,
                    citycode: 'home',
                    cityname: 'kanchipuram'
                }
            }
        }
    }
);

update employee set part_time_employee_set
= part_time_employee_set +
{ { firstname: 'arun', lastname : 'kannan', address_set :
    {
        {
            id: 600000,
            citycode:'work',
            cityname: 'chennai'
        },
        {
            id: 600000,
            citycode:'home',
            cityname: 'chennai'
        }
    }
}} where id=1;

select * from employee where id=1;
it gives all the part_time_employee information

My Main Issue:

Now i want only employee information of the part_time_employee r1. i want his work location and home location i.e.) i want the complete address_set
how to get that?

select * from employee where id=1 and part_time_employee_set = { { firstname: 'r1' }};
InvalidRequest: Error from server: code=2200 [Invalid query] message="Collection column 'part_time_employee_set' (set<frozen<part_time_employees>>) cannot be restricted by a '=' relation"

select * from employee where id=1 and part_time_employee_set in { { firstname: 'r1' }};
SyntaxException: line 1:64 no viable alternative at input '{' (...employee where id=1 and [part_time_employee_set] in...)

Issue 2:(minor issue)

select * from employee;

<<set(2)>>

how to display the expanded result in devcenter?. "Expand ON" command is not working as a command in dev center
however if i copy the values are copied, into a textedit or other editor. this is not a major concern for me at this point.

Body:
You can't query with non-primary key, unless you create index.

Even if you create index on part_time_employee_set collection you can't query with a piece of a frozen field (firstname). Frozen fields means to be a compact.
And another thing you can't select a partial item in a collection. you need to select the entire collection.

If you want to query with firstname you have to change your data model.

CREATE TABLE employee (
    id int,
    firstname text,
    lastname text,
    address_set set<frozen<city>>,
    name text static,
    PRIMARY KEY (id, firstname, lastname)
);

Now you can select address_set of part time employee who have first name 'r1'

SELECT * FROM employee_test WHERE id = 1 AND firstname = 'r1';

Output :

 id          | 1
 firstname   | r1
 lastname    | r2
 name        | raghu
 address_set | {{id: 600000, citycode: 'work', cityname: 'chennai'}, {id: 600020, citycode: 'home', cityname: 'kanchipuram'}}


问:
Eclipse Helios manage Weblogic 9.2
I have installed Eclipse Helios on my linux workstation and would like to manage a Weblogic 9.2 application server install.  I search the server runtime enviroments and there is no option for Weblogic only Oracle.  Is there a way to do this?

Thanks,
Tom

答:
Update site for Oracle Enterprise Pack for Eclipse:

http://download.oracle.com/otn_software/oepe/helios

Title: Eclipse Helios manage Weblogic 9.2


问:
Run macro on newly created .xlsx file from another workbook
I am opening and converting a .csv to an .xlsx file on a shared drive location.  Once the .xlsx is created it remains open.  The macros to do this are in a master Workbook located on the shared drive as well. Right now I have it set for a user to open the workbook and select a command button that opens and converts the file.

The user the selects the template needed from a list box and clicks a second command button which runs the following macro that calls a specific macro which converts the .xlsx just created to the correct format.

All my macros work except the macro below.  It stops at the first Workbooks..  Right now the newly created .xlsx is the only .xlsx in its folder but eventually there may be multiple .xlsx files created from multiple .csv files.

```<code>  Sub Run_Macros()

    'IF USER SELECTED FXX_Rejects
    If Range("A8").Value = Range("A2").Value Then
    'ACTIVATE OTHER WORKBOOK
    Workbooks("*.xlsx").Activate
    Workbooks("*.xlsx").Sheets("Sheet1").Select
    'AND THEN RUN APPROPRIATE MACRO
     Call aaLayout

    'IF USER SELECTED LXX_Rejects
    ElseIf Range("A8").Value = Range("A3").Value Then
    'ACTIVATE OTHER WORKBOOK
    Workbooks("*.xlsx").Activate
    Workbooks("*.xlsx").Sheets("Sheet1").Activate
    'AND THEN RUN APPROPRIATE MACRO
    Call abLayout

    'IF USER SELECTED HXXXX_Rejects
    ElseIf Range("A8").Value = Range("A4").Value Then
    'ACTIVATE OTHER WORKBOOK
    Workbooks("*.xlsx").Activate
    Workbooks("*.xlsx").Sheets("Sheet1").Activate
    'AND THEN RUN APPROPRIATE MACRO
    Call acLayout

    'IF USER SELECTED SXXX_Rejects
    ElseIf Range("A8").Value = Range("A5").Value Then
    'ACTIVATE OTHER WORKBOOK
    Workbooks("*.xlsx").Activate
    Workbooks("*.xlsx").Sheets("Sheet1").Activate
    'AND THEN RUN APPROPRIATE MACRO
    Call adLayout

    End If

    End Sub
</code>```

I have edited my question post and added the macro below that locates and converts the .CSV files preparing them for templating.  Maybe this can assist answering my original question.

```<code>    Sub CSVFiles()
        Dim MyFiles As String, ThisMonth As String
        Dim startPath As String
        Dim wb As Workbook
        ThisMonth = Format(Date, "mmmm")
        startPath = "\\XXX\2017\" & ThisMonth & "\"
        MyFiles = Dir(startPath & "*.csv")
        Do While MyFiles <> ""

        Set wb = Workbooks.Open(startPath & MyFiles)

        Call XLSXConvert
        'Converts all csv files, saves and closes files.  Prepares files for full template creation.
        wb.SaveAs fileName:=startPath & Replace  (MyFiles, ".csv", ".xlsx"),FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
        wb.Close
        MyFiles = Dir
        Loop
    End Sub
</code>```

答:
Your problem is with "*.xlsx".  Operating system commands accept the * as a wildcard but you're not calling an operating system command.  You are calling a VBA method on the Workbooks collection of objects that uses a number, usually the order in which the files were opened, as its identifier. Workbooks().Activate does not go out to the folder and look at all the available files and pick one that matches. Workbooks.Open() would do that but it still doesn't accept wildcards, and you said the workbook you want is already open.

Workbooks().Activate looks through the list of open workbooks for an identifier. The object you're trying to Activate was created in the code that ran before you get to this point, that we can't see from your posting.  Somewhere in that code, you could assign that object to a variable and then you could create an argument in this code so you could pass in that variable.

What you could also do, IF you know that the only .xlsx file you have open is the one you want, is loop through all the open files and check the name to see if it ends in .xlsx and if it does assign that to a variable.  Illustrated below:

```<code>  Sub Run_Macros()

    Dim wb As Workbook
    Dim target As Workbook
    Dim wbs As Workbooks

    Set wbs = Workbooks
    For Each wb In wbs
        If LCase(Right(wb.FullName, 5)) = ".xlsx" Then
            Set target = wb
        End If
    Next wb

    'IF USER SELECTED FXX_Rejects
    If Range("A8").Value = Range("A2").Value Then
    'ACTIVATE OTHER WORKBOOK
    target.Activate
    target.Sheets("Sheet1").Select
    'AND THEN RUN APPROPRIATE MACRO
    Call aaLayout

    'IF USER SELECTED LXX_Rejects
    ElseIf Range("A8").Value = Range("A3").Value Then
    'ACTIVATE OTHER WORKBOOK
    target.Activate
    target.Sheets("Sheet1").Activate
    'AND THEN RUN APPROPRIATE MACRO
    Call abLayout

    'IF USER SELECTED HXXXX_Rejects
    ElseIf Range("A8").Value = Range("A4").Value Then
    'ACTIVATE OTHER WORKBOOK
    target.Activate
    target.Sheets("Sheet1").Activate
    'AND THEN RUN APPROPRIATE MACRO
    Call acLayout

    'IF USER SELECTED SXXX_Rejects
    ElseIf Range("A8").Value = Range("A5").Value Then
    'ACTIVATE OTHER WORKBOOK
    target.Activate
    target.Sheets("Sheet1").Activate
    'AND THEN RUN APPROPRIATE MACRO
    Call adLayout

    End If

    End Sub
</code>```

Body:
I am opening and converting a .csv to an .xlsx file on a shared drive location.  Once the .xlsx is created it remains open.  The macros to do this are in a master Workbook located on the shared drive as well. Right now I have it set for a user to open the workbook and select a command button that opens and converts the file.

The user the selects the template needed from a list box and clicks a second command button which runs the following macro that calls a specific macro which converts the .xlsx just created to the correct format.

All my macros work except the macro below.  It stops at the first Workbooks..  Right now the newly created .xlsx is the only .xlsx in its folder but eventually there may be multiple .xlsx files created from multiple .csv files.

  Sub Run_Macros()

    'IF USER SELECTED FXX_Rejects
    If Range("A8").Value = Range("A2").Value Then
    'ACTIVATE OTHER WORKBOOK
    Workbooks("*.xlsx").Activate
    Workbooks("*.xlsx").Sheets("Sheet1").Select
    'AND THEN RUN APPROPRIATE MACRO
     Call aaLayout

    'IF USER SELECTED LXX_Rejects
    ElseIf Range("A8").Value = Range("A3").Value Then
    'ACTIVATE OTHER WORKBOOK
    Workbooks("*.xlsx").Activate
    Workbooks("*.xlsx").Sheets("Sheet1").Activate
    'AND THEN RUN APPROPRIATE MACRO
    Call abLayout

    'IF USER SELECTED HXXXX_Rejects
    ElseIf Range("A8").Value = Range("A4").Value Then
    'ACTIVATE OTHER WORKBOOK
    Workbooks("*.xlsx").Activate
    Workbooks("*.xlsx").Sheets("Sheet1").Activate
    'AND THEN RUN APPROPRIATE MACRO
    Call acLayout

    'IF USER SELECTED SXXX_Rejects
    ElseIf Range("A8").Value = Range("A5").Value Then
    'ACTIVATE OTHER WORKBOOK
    Workbooks("*.xlsx").Activate
    Workbooks("*.xlsx").Sheets("Sheet1").Activate
    'AND THEN RUN APPROPRIATE MACRO
    Call adLayout

    End If

    End Sub

I have edited my question post and added the macro below that locates and converts the .CSV files preparing them for templating.  Maybe this can assist answering my original question.

    Sub CSVFiles()
        Dim MyFiles As String, ThisMonth As String
        Dim startPath As String
        Dim wb As Workbook
        ThisMonth = Format(Date, "mmmm")
        startPath = "\\XXX\2017\" & ThisMonth & "\"
        MyFiles = Dir(startPath & "*.csv")
        Do While MyFiles <> ""

        Set wb = Workbooks.Open(startPath & MyFiles)

        Call XLSXConvert
        'Converts all csv files, saves and closes files.  Prepares files for full template creation.
        wb.SaveAs fileName:=startPath & Replace  (MyFiles, ".csv", ".xlsx"),FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
        wb.Close
        MyFiles = Dir
        Loop
    End Sub

Body:
Your problem is with "*.xlsx".  Operating system commands accept the * as a wildcard but you're not calling an operating system command.  You are calling a VBA method on the Workbooks collection of objects that uses a number, usually the order in which the files were opened, as its identifier. Workbooks().Activate does not go out to the folder and look at all the available files and pick one that matches. Workbooks.Open() would do that but it still doesn't accept wildcards, and you said the workbook you want is already open.

Workbooks().Activate looks through the list of open workbooks for an identifier. The object you're trying to Activate was created in the code that ran before you get to this point, that we can't see from your posting.  Somewhere in that code, you could assign that object to a variable and then you could create an argument in this code so you could pass in that variable.

What you could also do, IF you know that the only .xlsx file you have open is the one you want, is loop through all the open files and check the name to see if it ends in .xlsx and if it does assign that to a variable.  Illustrated below:

  Sub Run_Macros()

    Dim wb As Workbook
    Dim target As Workbook
    Dim wbs As Workbooks

    Set wbs = Workbooks
    For Each wb In wbs
        If LCase(Right(wb.FullName, 5)) = ".xlsx" Then
            Set target = wb
        End If
    Next wb

    'IF USER SELECTED FXX_Rejects
    If Range("A8").Value = Range("A2").Value Then
    'ACTIVATE OTHER WORKBOOK
    target.Activate
    target.Sheets("Sheet1").Select
    'AND THEN RUN APPROPRIATE MACRO
    Call aaLayout

    'IF USER SELECTED LXX_Rejects
    ElseIf Range("A8").Value = Range("A3").Value Then
    'ACTIVATE OTHER WORKBOOK
    target.Activate
    target.Sheets("Sheet1").Activate
    'AND THEN RUN APPROPRIATE MACRO
    Call abLayout

    'IF USER SELECTED HXXXX_Rejects
    ElseIf Range("A8").Value = Range("A4").Value Then
    'ACTIVATE OTHER WORKBOOK
    target.Activate
    target.Sheets("Sheet1").Activate
    'AND THEN RUN APPROPRIATE MACRO
    Call acLayout

    'IF USER SELECTED SXXX_Rejects
    ElseIf Range("A8").Value = Range("A5").Value Then
    'ACTIVATE OTHER WORKBOOK
    target.Activate
    target.Sheets("Sheet1").Activate
    'AND THEN RUN APPROPRIATE MACRO
    Call adLayout

    End If

    End Sub


问:
expose a field in wpf user control for external use
I am very new to wpf and I would like to create a simple user control that consists of a textblock and a textbox so that I can reuse it. However, I do not really know how to bind the content of the textblock so that it can be set from outside and expose the textbox so that it could be bound to other field from the outside calling xaml.

The following is the code for my user control

```<code><UserControl x:Class="WPFLib.UserControlLibs.TextBoxUsrCtrl"
                         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                         xmlns:local="clr-namespace:WPFLib.UserControlLibs"
                         mc:Ignorable="d"
                         d:DesignHeight="20"
                         d:DesignWidth="300">
    <StackPanel Orientation='Horizontal'
                            Width='{Binding ActualWidth, ElementName=parentElementName}'
                            Height='{Binding ActualWidth, ElementName=parentElementName}'>
        <Grid HorizontalAlignment='Stretch'>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width='1*' />
                <ColumnDefinition Width='1*' />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            <TextBlock Text='{Binding Text, ElementName=parentElementName}'
                                 Background='Aqua'
                                 Grid.Column='0'
                                 Grid.Row='0' />
            <TextBox x:Name='UserTxBox'
                             Grid.Column='1'
                             Grid.Row='0'
                             Background='Red'
                             HorizontalAlignment='Stretch'
                             Text='this is a test to see how it works' />
        </Grid>
    </StackPanel>
</UserControl>
</code>```

How do I expose the Text from the TextBlock and TextBox so that it could be set and retrieved from the calling xaml?

For example

```<code>        <Window x:Class="TestWPF.MainWindow"
                        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                        xmlns:local="clr-namespace:TestWPF"
                          xmlns:controls='clr-namespace:WPFLib.UserControlLibs'
    `                   mc:Ignorable="d"
                        Title="MainWindow"
                        Height="350"
                        Width="525"
                        WindowState='Maximized'
                        FontSize='18'>
            <StackPanel>
<controls:TextBoxUsrCtrl Width='500' HorizontalAlignment='Left' **Text='NEED TO SET THE TEXT BLOCK HERE'**/>
            </StackPanel>
        </Window>
</code>```

答:
You should give it two dependency properties, one for each of the two text properties you want to expose (this is a horrible amount of boilerplate; I use Visual Studio's snippet feature to generate it all). Then in the UserControl XAML, you bind control properties to those.

```<code>public partial class TextBoxUsrCtrl : UserControl
{
    public TextBoxUsrCtrl()
    {
        InitializeComponent();
    }

    #region Text Property
    public String Text
    {
        get { return (String)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register(nameof(Text), typeof(String), typeof(TextBoxUsrCtrl),
            new FrameworkPropertyMetadata(null) {
                //  It's read-write, so make it bind both ways by default
                BindsTwoWayByDefault = true
            });
    #endregion Text Property

    #region DisplayText Property
    public String DisplayText
    {
        get { return (String)GetValue(DisplayTextProperty); }
        set { SetValue(DisplayTextProperty, value); }
    }

    public static readonly DependencyProperty DisplayTextProperty =
        DependencyProperty.Register(nameof(DisplayText), typeof(String), typeof(TextBoxUsrCtrl),
            new PropertyMetadata(null));
    #endregion DisplayText Property
}
</code>```

XAML. I simplified this so the layout works as I think you intended.

Note how the bindings use RelativeSource={RelativeSource AncestorType=UserControl} to bind to the dependency properties we defined above on the UserControl. By default, Binding will bind to properties of UserControl.DataContext, but we're not using that. The reason is that if we set UserControl.DataContext here, that will break the viewmodel property bindings in the final XAML fragment at the end of this answer. Those bindings will look for those properties on our control. There are workarounds but it gets ugly. The way I've done it here is best because it never breaks anybody's assumptions about DataContext inheritance.

```<code><UserControl
    x:Class="WPFLib.UserControlLibs.TextBoxUsrCtrl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:WPFLib.UserControlLibs"
    mc:Ignorable="d"
    d:DesignHeight="20"
    d:DesignWidth="300"
    >
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width='*' />
            <ColumnDefinition Width='*' />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <TextBlock
            Text='{Binding DisplayText, RelativeSource={RelativeSource AncestorType=UserControl}}'
            Background='Aqua'
            Grid.Column='0'
            Grid.Row='0'
            />
        <TextBox
            x:Name='UserTxBox'
            Grid.Column='1'
            Grid.Row='0'
            Background='Red'
            HorizontalAlignment='Stretch'
            Text='{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}}'
            />
    </Grid>
</UserControl>
</code>```

Usage in window, bound to viewmodel properties:

```<code>    <local:TextBoxUsrCtrl
        Text="{Binding TestText}"
        DisplayText="{Binding ShowThisText}"
        />
</code>```

Lastly, I'm not sure what you were getting at with ElementName=parentElementName. If that's meant to be a reference to a parent control, you can't do that, and it wouldn't be a good idea if you could. You wouldn't want a UserControl constrained by a requirement that a parent control must have a particular name. The answer to that requirement is simply that controls in XAML are only responsible for sizing themselves if they have a fixed size. If they should size to the parent, the parent is always the one responsible for that. So if you want to size two instances of TextBoxUsrCtrl to two different parents, that's fine. Each parent sizes its own children as it pleases.

Body:
I am very new to wpf and I would like to create a simple user control that consists of a textblock and a textbox so that I can reuse it. However, I do not really know how to bind the content of the textblock so that it can be set from outside and expose the textbox so that it could be bound to other field from the outside calling xaml.

The following is the code for my user control

<UserControl x:Class="WPFLib.UserControlLibs.TextBoxUsrCtrl"
                         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                         xmlns:local="clr-namespace:WPFLib.UserControlLibs"
                         mc:Ignorable="d"
                         d:DesignHeight="20"
                         d:DesignWidth="300">
    <StackPanel Orientation='Horizontal'
                            Width='{Binding ActualWidth, ElementName=parentElementName}'
                            Height='{Binding ActualWidth, ElementName=parentElementName}'>
        <Grid HorizontalAlignment='Stretch'>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width='1*' />
                <ColumnDefinition Width='1*' />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
            <TextBlock Text='{Binding Text, ElementName=parentElementName}'
                                 Background='Aqua'
                                 Grid.Column='0'
                                 Grid.Row='0' />
            <TextBox x:Name='UserTxBox'
                             Grid.Column='1'
                             Grid.Row='0'
                             Background='Red'
                             HorizontalAlignment='Stretch'
                             Text='this is a test to see how it works' />
        </Grid>
    </StackPanel>
</UserControl>

How do I expose the Text from the TextBlock and TextBox so that it could be set and retrieved from the calling xaml?

For example

        <Window x:Class="TestWPF.MainWindow"
                        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                        xmlns:local="clr-namespace:TestWPF"
                          xmlns:controls='clr-namespace:WPFLib.UserControlLibs'
    `                   mc:Ignorable="d"
                        Title="MainWindow"
                        Height="350"
                        Width="525"
                        WindowState='Maximized'
                        FontSize='18'>
            <StackPanel>
<controls:TextBoxUsrCtrl Width='500' HorizontalAlignment='Left' **Text='NEED TO SET THE TEXT BLOCK HERE'**/>
            </StackPanel>
        </Window>

Body:
You should give it two dependency properties, one for each of the two text properties you want to expose (this is a horrible amount of boilerplate; I use Visual Studio's snippet feature to generate it all). Then in the UserControl XAML, you bind control properties to those.

public partial class TextBoxUsrCtrl : UserControl
{
    public TextBoxUsrCtrl()
    {
        InitializeComponent();
    }

    #region Text Property
    public String Text
    {
        get { return (String)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register(nameof(Text), typeof(String), typeof(TextBoxUsrCtrl),
            new FrameworkPropertyMetadata(null) {
                //  It's read-write, so make it bind both ways by default
                BindsTwoWayByDefault = true
            });
    #endregion Text Property

    #region DisplayText Property
    public String DisplayText
    {
        get { return (String)GetValue(DisplayTextProperty); }
        set { SetValue(DisplayTextProperty, value); }
    }

    public static readonly DependencyProperty DisplayTextProperty =
        DependencyProperty.Register(nameof(DisplayText), typeof(String), typeof(TextBoxUsrCtrl),
            new PropertyMetadata(null));
    #endregion DisplayText Property
}

XAML. I simplified this so the layout works as I think you intended.

Note how the bindings use RelativeSource={RelativeSource AncestorType=UserControl} to bind to the dependency properties we defined above on the UserControl. By default, Binding will bind to properties of UserControl.DataContext, but we're not using that. The reason is that if we set UserControl.DataContext here, that will break the viewmodel property bindings in the final XAML fragment at the end of this answer. Those bindings will look for those properties on our control. There are workarounds but it gets ugly. The way I've done it here is best because it never breaks anybody's assumptions about DataContext inheritance.

<UserControl
    x:Class="WPFLib.UserControlLibs.TextBoxUsrCtrl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:WPFLib.UserControlLibs"
    mc:Ignorable="d"
    d:DesignHeight="20"
    d:DesignWidth="300"
    >
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width='*' />
            <ColumnDefinition Width='*' />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <TextBlock
            Text='{Binding DisplayText, RelativeSource={RelativeSource AncestorType=UserControl}}'
            Background='Aqua'
            Grid.Column='0'
            Grid.Row='0'
            />
        <TextBox
            x:Name='UserTxBox'
            Grid.Column='1'
            Grid.Row='0'
            Background='Red'
            HorizontalAlignment='Stretch'
            Text='{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}}'
            />
    </Grid>
</UserControl>

Usage in window, bound to viewmodel properties:

    <local:TextBoxUsrCtrl
        Text="{Binding TestText}"
        DisplayText="{Binding ShowThisText}"
        />

Lastly, I'm not sure what you were getting at with ElementName=parentElementName. If that's meant to be a reference to a parent control, you can't do that, and it wouldn't be a good idea if you could. You wouldn't want a UserControl constrained by a requirement that a parent control must have a particular name. The answer to that requirement is simply that controls in XAML are only responsible for sizing themselves if they have a fixed size. If they should size to the parent, the parent is always the one responsible for that. So if you want to size two instances of TextBoxUsrCtrl to two different parents, that's fine. Each parent sizes its own children as it pleases.