问:
Is there a better way to accomplish this loop?
I'm pretty new with VBA, but I've been muddling through to make a program for my team.
This piece of code works most of the time, but tends to hang on occasion. I can't figure out why it would hang sometimes, and work perfectly most of the time, so I'm now trying to figure out a better way to accomplish this loop. I know that this method of looping isn't the best way to do things, but not sure how to accomplish the task.

My webpage operates in a PEGA Web application, and the native IE ready state indicators are always 'ready' so I have to use the web application's ready state markers.

Can anyone help me out?

```<code>Public Sub WaitingForRS()
' FIND THE C360 WINDOW
        Marker = 0
        Set objShell = CreateObject("Shell.Application")
        IE_count = objShell.Windows.Count
        For x = 0 To (IE_count - 1)
            On Error Resume Next
            my_url = objShell.Windows(x).Document.Location
            my_title = objShell.Windows(x).Document.title

            If my_title Like "Coverage User" & "*" Then
                Set C360Window = objShell.Windows(x)
                Marker = 1
                Exit For
            Else
            End If
        Next

        If Marker = 0 Then
            MsgBox ("C360 window is not found. Please ensure C360 is open in Internet Explorer and try again")
        Else
        End If

'FIND THE READY STATE INDICATOR
    RSIndicatorDocMarker = 0
    RSIndicatorDataMarker = 0
    Set RSIndicatorPage = C360Window.Document
    Set RSIndicatorClass = RSIndicatorPage.getelementsbyclassname("document-statetracker")(0)

RSIndicatorCheck:
'CHECK THE READY STATE DOC STATUS
    If RSIndicatorClass.getattribute("data-state-doc-status") = "ready" Then
        RSIndicatorDocMarker = 1
        Else: RSIndicatorDocMarker = 0
    End If

'CHECK THE READY STATE
    If RSIndicatorClass.getattribute("data-state-busy-status") = "none" Then
        RSIndicatorDataMarker = 1
        Else: RSIndicatorDataMarker = 0
    End If

'Compare the RSIndicators
    If RSIndicatorDataMarker = 1 And RSIndicatorDocMarker = 1 Then

    Else: GoTo RSIndicatorCheck
    End If
End Sub
</code>```

答:
Check out my answer on this post Excel VBA Submitting data via IE on an online MS Forms not working

@ Idea 5 subheading. The WaitForLoadSETx() function has a manual time over-ride and double loop to help catch the state.

This was the best I could do in VBA with IE object. Ideally you want to learn Selenium, PhantomJS, or Puppeteer for actual browser manipulation. There are of course cool apps, folks have built on top of these libraries to help (puppeteer recorder chrome add in)

Or to keep things in Excel, use a simple XMLHTTPRequest object to cut the browser out of the equation, and deal solely with the request / response from the web page. This is a good alternative because it lets you focus on scraping the html content, in text form without the Javascript or waiting for page to load.

Body:
I'm pretty new with VBA, but I've been muddling through to make a program for my team.
This piece of code works most of the time, but tends to hang on occasion. I can't figure out why it would hang sometimes, and work perfectly most of the time, so I'm now trying to figure out a better way to accomplish this loop. I know that this method of looping isn't the best way to do things, but not sure how to accomplish the task.

My webpage operates in a PEGA Web application, and the native IE ready state indicators are always 'ready' so I have to use the web application's ready state markers.

Can anyone help me out?

Public Sub WaitingForRS()
' FIND THE C360 WINDOW
        Marker = 0
        Set objShell = CreateObject("Shell.Application")
        IE_count = objShell.Windows.Count
        For x = 0 To (IE_count - 1)
            On Error Resume Next
            my_url = objShell.Windows(x).Document.Location
            my_title = objShell.Windows(x).Document.title

            If my_title Like "Coverage User" & "*" Then
                Set C360Window = objShell.Windows(x)
                Marker = 1
                Exit For
            Else
            End If
        Next

        If Marker = 0 Then
            MsgBox ("C360 window is not found. Please ensure C360 is open in Internet Explorer and try again")
        Else
        End If

'FIND THE READY STATE INDICATOR
    RSIndicatorDocMarker = 0
    RSIndicatorDataMarker = 0
    Set RSIndicatorPage = C360Window.Document
    Set RSIndicatorClass = RSIndicatorPage.getelementsbyclassname("document-statetracker")(0)

RSIndicatorCheck:
'CHECK THE READY STATE DOC STATUS
    If RSIndicatorClass.getattribute("data-state-doc-status") = "ready" Then
        RSIndicatorDocMarker = 1
        Else: RSIndicatorDocMarker = 0
    End If

'CHECK THE READY STATE
    If RSIndicatorClass.getattribute("data-state-busy-status") = "none" Then
        RSIndicatorDataMarker = 1
        Else: RSIndicatorDataMarker = 0
    End If

'Compare the RSIndicators
    If RSIndicatorDataMarker = 1 And RSIndicatorDocMarker = 1 Then

    Else: GoTo RSIndicatorCheck
    End If
End Sub


来源: stackexchange

问:
How do I change the name of an existing project in Visual Studio 2008?
How to change the name of a project in VS 2008 to something else? I have already created a project and now I want to change its name.</p>

答:
To rename your project:

Right-click on the project in the Solution Explorer.

Click "Rename".

Type in your new name, and then press Enter.

To rename the assembly it generates:

Double-click on the "Properties" node for your project in the Solution Explorer.

Change the text in the "Assembly name" textbox.

ContentLicense: CC BY-SA 3.0


问:
Strange beaver when use order_by with conditions Cannot resolve keyword '-pub_date into field
This code work fine, except it's not the result that i want.  For each Case it's order goes by to old one to new one

```<code>def get_queryset(self, *args, **kwargs):
        return super(PublishedManager, self).get_queryset().filter(
            pub_date__lte=timezone.now(), status="published").order_by(
                Case(When(status_ranking='1', then='pub_date')).asc(),
                Case(When(status_ranking='2', then='pub_date')).asc(),
                Case(When(status_ranking='3', then='pub_date')).asc(),
                Case(When(status_ranking='4', then='pub_date')).asc()
                )
</code>```

Whenever i use this method, i got the error; Cannot resolve keyword '-pub_date into field

```<code>def get_queryset(self, *args, **kwargs):
        return super(PublishedManager, self).get_queryset().filter(
            pub_date__lte=timezone.now(), status="published").order_by(
                Case(When(status_ranking='1', then='-pub_date')).asc(),
                Case(When(status_ranking='2', then='-pub_date')).asc(),
                Case(When(status_ranking='3', then='-pub_date')).asc(),
                Case(When(status_ranking='4', then='-pub_date')).asc()
                )
</code>```

答:
You can make use of .desc() [Django-doc] instead of .asc() [Django-doc] to order in descending order.

That being said, it is quite unreadable what you aim to do. If you first want to sort on the status_ranking (in ascending order), and then on pub_date (in descending order), you can use:

```<code>return super(PublishedManager, self).get_queryset().filter(
    pub_date__lte=timezone.now(), status='published'
).order_by(<b>'status_ranking', '-pub_date'</b>)</code>```

or if you only want to order in the status rankings for one to four:

```<code>return super(PublishedManager, self).get_queryset().filter(
    pub_date__lte=timezone.now(), status='published'
).order_by('status_ranking', <b>Case(When(<b>status_ranking__in=[1,2,3,4]</b>, then='pub_date')).desc()</b>)</code>```

ContentLicense: CC BY-SA 4.0

Body:
This code work fine, except it's not the result that i want.  For each Case it's order goes by to old one to new one

def get_queryset(self, *args, **kwargs):
        return super(PublishedManager, self).get_queryset().filter(
            pub_date__lte=timezone.now(), status="published").order_by(
                Case(When(status_ranking='1', then='pub_date')).asc(),
                Case(When(status_ranking='2', then='pub_date')).asc(),
                Case(When(status_ranking='3', then='pub_date')).asc(),
                Case(When(status_ranking='4', then='pub_date')).asc()
                )

Whenever i use this method, i got the error; Cannot resolve keyword '-pub_date into field

def get_queryset(self, *args, **kwargs):
        return super(PublishedManager, self).get_queryset().filter(
            pub_date__lte=timezone.now(), status="published").order_by(
                Case(When(status_ranking='1', then='-pub_date')).asc(),
                Case(When(status_ranking='2', then='-pub_date')).asc(),
                Case(When(status_ranking='3', then='-pub_date')).asc(),
                Case(When(status_ranking='4', then='-pub_date')).asc()
                )

Body:
You can make use of .desc() [Django-doc] instead of .asc() [Django-doc] to order in descending order.

That being said, it is quite unreadable what you aim to do. If you first want to sort on the status_ranking (in ascending order), and then on pub_date (in descending order), you can use:

return super(PublishedManager, self).get_queryset().filter(
    pub_date__lte=timezone.now(), status='published'
).order_by('status_ranking', '-pub_date')

or if you only want to order in the status rankings for one to four:

return super(PublishedManager, self).get_queryset().filter(
    pub_date__lte=timezone.now(), status='published'
).order_by('status_ranking', Case(When(status_ranking__in=[1,2,3,4], then='pub_date')).desc())


问:
How does [Authorize] attribute know if a user has a role?
Lets say I have a working implementation of authentication and authorization in an ASP.NET Core MVC app, and on an action I have [Authorize(Roles = "Admin")] attribute. I have just logged in and I'm about to call that action.

When that action is called, where does the [Authorize(Roles = "Admin")] attribute look to see if the user has the role of "Admin"? Where is "Admin" stored?

答:
It could depend on what kind of authentication you are using. I've only been using the JwtBearer authentication scheme.

At that case these informations are usually encoded into the access token (by either your application, or some other identity provider) and your client sends that with your request along with other personal data in the token.


问:
Gensim's Doc2Vec - How to use pre-trained word2vec (word similarities)
I don't have large corpus of data to train word similarities e.g. 'hot' is more similar to 'warm' than to 'cold'. However, I like to train doc2vec on a relatively small corpus ~100 docs so that it can classify my domain specific documents.

To elaborate let me use this toy example. Assume I've only 4 training docs given  by 4 sentences - "I love hot chocolate.", "I hate hot chocolate.", "I love hot tea.", and "I love hot cake.".
Given a test document "I adore hot chocolate", I would expect, doc2vec will invariably return "I love hot chocolate." as the closest document. This expectation will be true if word2vec already supplies the knowledge that "adore" is very similar to "love". However, I'm getting most similar document as "I hate hot chocolate" -- which is a bizarre!!

Any suggestion on how to circumvent this, i.e. be able to use pre-trained word embeddings so that I don't need to venture into training "adore" is close to "love", "hate" is close to "detest", and so on.

Code (Jupyter Nodebook. Python 3.7. Jensim 3.8.1)

```<code>from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from nltk.tokenize import word_tokenize
data = ["I love hot chocolate.",
        "I hate hot chocolate",
       "I love hot tea.",
       "I love hot cake."]

tagged_data = [TaggedDocument(words=word_tokenize(_d.lower()), tags=[str(i)]) for i, _d in enumerate(data)]
print(tagged_data)
#Train and save
max_epochs = 10
vec_size = 5
alpha = 0.025

model = Doc2Vec(vector_size=vec_size, #it was size earlier
                alpha=alpha,
                min_alpha=0.00025,
                min_count=1,
                dm =1)

model.build_vocab(tagged_data)

for epoch in range(max_epochs):
    if epoch % 10 == 0:
        print('iteration {0}'.format(epoch))
    model.train(tagged_data,
                total_examples=model.corpus_count,
                epochs=model.epochs) #It was model.iter earlier
    # decrease the learning rate
    model.alpha -= 0.0002
    # fix the learning rate, no decay
    model.min_alpha = model.alpha

print("Model Ready")

test_sentence="I adore hot chocolate"
test_data = word_tokenize(test_sentence.lower())
v1 = model.infer_vector(test_data)
#print("V1_infer", v1)

# to find most similar doc using tags
sims = model.docvecs.most_similar([v1])
print("\nTest: %s\n" %(test_sentence))
for indx, score in sims:
    print("\t(score: %.4f) %s" %(score, data[int(indx)]))
</code>```

答:
Just ~100 documents is way too small to meaningfully train a Doc2Vec (or Word2Vec) model. Published Doc2Vec work tends to use tens-of-thousands to millions of documents.

To the extent you may be able to get slightly meaningful results from smaller datasets, you'll usually need to reduce the vector-sizes a lot – to far smaller than the number of words/examples – and increase the training epochs. (Your toy data has 4 texts & 6 unique words. Even to get 5-dimensional vectors, you probably want something like 5^2 constrasting documents.)

Also, gensim's Doc2Vec doesn't offer any official option to import word-vectors from elsewhere. The internal Doc2Vec training is not a process where word-vectors are trained 1st, then doc-vectors calculated. Rather, doc-vectors & word-vectors are trained in a simultaneous process, gradually improving together. (Some modes, like the fast & often highly effective DBOW that can be enabled with dm=0, don't create or use word-vectors at all.)

There's not really anything bizarre about your 4-sentence results, when looking at the data as if we were the Doc2Vec or Word2Vec algorithms, which have no prior knowledge about words, only what's in the training data. In your training data, the token 'love' and the token 'hate' are used in nearly exactly the same way, with the same surrounding words. Only by seeing many subtly varied alternative uses of words, alongside many contrasting surrounding words, can these "dense embedding" models move the word-vectors to useful relative positions, where they are closer to related words & farther from other words. (And, since you've provided no training data with the token 'adore', the model knows nothing about that word – and if it's provided inside a test document, as if to the model's infer_vector() method, it will be ignored. So the test document it 'sees' is only the known words ['i', 'hot', 'chocolate'].)

But also, even if you did manage to train on a larger dataset, or somehow inject the knowledge from other word-vectors that 'love' and 'adore' are somewhat similar,  it's important to note that antonyms are typically quite similar in sets of word-vectors, too – as they are used in the same contexts, and often syntactically interchangeable, and of the same general category. These models often aren't very good at detecting the flip-in-human-perceived meaning from the swapping of a word for its antonym (or insertion of a single 'not' or other reversing-intent words).

Ultimately if you want to use gensim's Doc2Vec, you should train it with far more data. (If you were willing to grab some other pre-trainined word-vectors, why not grab some other source of somewhat-similar bulk sentences? The effect of using data that isn't exactly like your actual problem will be similar whether you leverage that outside data via bulk text or a pre-trained model.)

Finally: it's a bad, error-prone pattern to be calling train() more than once in your own loop, with your own alpha adjustments. You can just call it once, with the right number of epochs, and the model will perform the multiple training passes & manage the internal alpha smoothly over the right number of epochs.

Body:
I don't have large corpus of data to train word similarities e.g. 'hot' is more similar to 'warm' than to 'cold'. However, I like to train doc2vec on a relatively small corpus ~100 docs so that it can classify my domain specific documents.

To elaborate let me use this toy example. Assume I've only 4 training docs given  by 4 sentences - "I love hot chocolate.", "I hate hot chocolate.", "I love hot tea.", and "I love hot cake.".
Given a test document "I adore hot chocolate", I would expect, doc2vec will invariably return "I love hot chocolate." as the closest document. This expectation will be true if word2vec already supplies the knowledge that "adore" is very similar to "love". However, I'm getting most similar document as "I hate hot chocolate" -- which is a bizarre!!

Any suggestion on how to circumvent this, i.e. be able to use pre-trained word embeddings so that I don't need to venture into training "adore" is close to "love", "hate" is close to "detest", and so on.

Code (Jupyter Nodebook. Python 3.7. Jensim 3.8.1)

from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from nltk.tokenize import word_tokenize
data = ["I love hot chocolate.",
        "I hate hot chocolate",
       "I love hot tea.",
       "I love hot cake."]

tagged_data = [TaggedDocument(words=word_tokenize(_d.lower()), tags=[str(i)]) for i, _d in enumerate(data)]
print(tagged_data)
#Train and save
max_epochs = 10
vec_size = 5
alpha = 0.025

model = Doc2Vec(vector_size=vec_size, #it was size earlier
                alpha=alpha,
                min_alpha=0.00025,
                min_count=1,
                dm =1)

model.build_vocab(tagged_data)

for epoch in range(max_epochs):
    if epoch % 10 == 0:
        print('iteration {0}'.format(epoch))
    model.train(tagged_data,
                total_examples=model.corpus_count,
                epochs=model.epochs) #It was model.iter earlier
    # decrease the learning rate
    model.alpha -= 0.0002
    # fix the learning rate, no decay
    model.min_alpha = model.alpha

print("Model Ready")

test_sentence="I adore hot chocolate"
test_data = word_tokenize(test_sentence.lower())
v1 = model.infer_vector(test_data)
#print("V1_infer", v1)

# to find most similar doc using tags
sims = model.docvecs.most_similar([v1])
print("\nTest: %s\n" %(test_sentence))
for indx, score in sims:
    print("\t(score: %.4f) %s" %(score, data[int(indx)]))


问:
How to update my working Git branch from another branch (develop)?
I made a new branch called feature1 from the main develop branch a month ago.

```<code>⇒  git branch
  develop
* feature1
</code>```

I've been working on feature1 for a month now and a lot of changes have been pushed to develop.

How can I update my current branch feature1 with the latest commits from develop?

I DO NOT want to checkout master and merge my feature1 branch into it. Neither do I want to use git cherry-pick to manually move commits from develop to feature1.

How would I go about doing this?

答:
```<code>$ git checkout <another-branch> <path-to-file> [<one-more-file> ...]
$ git status
$ git commit -m "Merged file from another branch"
</code>```

Body:
I made a new branch called feature1 from the main develop branch a month ago.

⇒  git branch
  develop
* feature1

I've been working on feature1 for a month now and a lot of changes have been pushed to develop.

How can I update my current branch feature1 with the latest commits from develop?

I DO NOT want to checkout master and merge my feature1 branch into it. Neither do I want to use git cherry-pick to manually move commits from develop to feature1.

How would I go about doing this?


问:
How to merge 2 pdf vector image assets in Swift
I have two vector images. I want to merge them so the dots appear on top of the first image.
The solutions for regular png assets don't work, as they use the actual size of the image, and the combined image comes out very blurry.

One solution that I found was placing a second UIImageView (same size, centred) on top of the first one, but it seems really dumb.

I need to make this inside the app because I also want to have the squared coloured differently (change the tint of the vector), and then merged with the black border image. So I can have 3 assets in my project (square, border and dots).

答:
I suggest using sublayers:

```<code>["firstOne", "secondOne"].forEach {
let myLayer = CALayer()
let myImage = UIImage(named: $0)?.cgImage
myLayer.frame = myView.bounds
myLayer.contents = myImage
myView.layer.addSublayer(myLayer)
}
</code>```

Or create a custom layer class

Body:
I suggest using sublayers:

["firstOne", "secondOne"].forEach {
let myLayer = CALayer()
let myImage = UIImage(named: $0)?.cgImage
myLayer.frame = myView.bounds
myLayer.contents = myImage
myView.layer.addSublayer(myLayer)
}

Or create a custom layer class


问:
This app is not authorized to use Firebase Authentication.Please verify that the correct package name and SHA-1 are configured in the Firebase Console
Firebase auth was working fine, the debug build suddenly started failing without any change of code, logging the folloing message

D/PhoneAuthActivity( 7392): signInWithCredential:failure:com.google.firebase.auth.FirebaseAuthException: This app is not authorized to use Firebase Authentication. Please verifythat the correct package name and SHA-1 are configured in the Firebase Console. [ App validation failed ].

The only notable action inbetween a successful login and failure is android studio upgrade.

答: If you are using a Emulator for phone OTP verification it won't work since it does not have a sim. So try installing it to your mobile(with sim) and check if the error persists.


问:
Advice needed: Project Structure for Namespaced App Laravel
I am developing an app that has two name spaced differentiated folders.

Lets say

App/Http/Users/ and
App/Http/Drivers/

I have two api routes setup api.php and dapi.php.
The routes are also prefixed by localhost/api/foo and localhost/dapi/bar respectively.

Everything works ok but the issue is that there are some methods that I need to call for both. Such as save address info or call. Right now I have to make same controllers for both and duplicate a lot of code. What would be the best approach for this kind of project?

答:
you should use traits

Traits are a mechanism for code reuse in single inheritance languages
  such as PHP. A Trait is intended to reduce some limitations of single
  inheritance by enabling a developer to reuse sets of methods freely in
  several independent classes living in different class hierarchies. The
  semantics of the combination of Traits and classes is defined in a way
  which reduces complexity, and avoids the typical problems associated
  with multiple inheritance and Mixins.

for example:

in your traite:

```<code>    trait SameMethods {
        function call() { /*1*/ }
        function saveAddress() { /*2*/ }
    }
</code>```

.

```<code>namespace App\Http\Drivers;

        class Foo extends Controller{
            use SameMethods ;
            /* ... */
        }
</code>```

.

```<code>namespace App\Http\Users;

        class Bar extends Controller{
            use SameMethods ;
            /* ... */
        }
</code>```

Now you have these methods on your controllers.

another way is you have an another class for example ParentController extended from Controller that it contains same methods and foo and bar extends from this class

```<code>ParentController extends Controller {
    function call() { /*1*/ }
    function saveAddress() { /*2*/ }
}
</code>```

.

```<code>namespace App\Http\Drivers;

        class Foo extends ParentController {

            /* ... */
        }
</code>```

.

```<code>namespace App\Http\Users;

        class Bar extends ParentController {

            /* ... */
        }
</code>```

Body:
you should use traits

Traits are a mechanism for code reuse in single inheritance languages
  such as PHP. A Trait is intended to reduce some limitations of single
  inheritance by enabling a developer to reuse sets of methods freely in
  several independent classes living in different class hierarchies. The
  semantics of the combination of Traits and classes is defined in a way
  which reduces complexity, and avoids the typical problems associated
  with multiple inheritance and Mixins.

for example:

in your traite:

    trait SameMethods {
        function call() { /*1*/ }
        function saveAddress() { /*2*/ }
    }

.

namespace App\Http\Drivers;

        class Foo extends Controller{
            use SameMethods ;
            /* ... */
        }

.

namespace App\Http\Users;

        class Bar extends Controller{
            use SameMethods ;
            /* ... */
        }

Now you have these methods on your controllers.

another way is you have an another class for example ParentController extended from Controller that it contains same methods and foo and bar extends from this class

ParentController extends Controller {
    function call() { /*1*/ }
    function saveAddress() { /*2*/ }
}

.

namespace App\Http\Drivers;

        class Foo extends ParentController {

            /* ... */
        }

.

namespace App\Http\Users;

        class Bar extends ParentController {

            /* ... */
        }


问:
Template function calling
```<code>#include <iostream>
#include <memory>
#include <initializer_list>
#include <cassert>
template <typename T>
class Vector
{
    // Your implementation of the Vector class starts here

    private:
//attributes
    int length;
    T* data;

    public:
//constructors
    Vector()
    :length(0),
    data(nullptr)
    {
        std::cout<<"New empty object created"<<std::endl;
    }

    Vector(int length)
    :length(length),
    data(new T[length])
    {
        std::cout<< "Length of object is = " <<length <<std::endl;
    }

    //use a copy of another Vector
    Vector(const Vector& other)
    : Vector(other.length)
    {
        for(int i=0;i<length;i++)
            data[i]=other.data[i];

    }

    // using initializer list
    Vector(std::initializer_list<T> list)
    : Vector((int)list.size())
    {
        std::uninitialized_copy(list.begin(), list.end(), data);
        std::cout<< "The elements in the object are: ";
        for (auto it = std::begin(list); it!=std::end(list); ++it)
        std::cout << ' ' << *it;
        std::cout<<std::endl;
    }

//operators

    //copy
    Vector<T>& operator=(const Vector<T>& other)
    {
        if(this!= &other)
        {
            std::cout<<"Copied constructor"<<std::endl;
            delete[] data;
            length = other.length;
            std::cout<<"New length ="<<length<<std::endl;
            data = new T[length];
            std::cout<<"The elements in the object are: ";
            for(int i=0;i<length;i++)
            {
                data[i]=other.data[i];
                std::cout<<data[i]<<" ";
            }
        }
        std::cout<<std::endl;
        //std::cout << "copy operator" << std::endl;
        return *this;
    }
    //move
    Vector<T>& operator=(Vector<T>&& other)
    {
        if(this!= &other)
        {
            delete[] data;
            length = other.length;
            data = new T[length];
            for(int i=0;i<length;i++){
                data[i]=other.data[i];}
            other.length = 0;
            delete[] other.data;
            other.data = nullptr;
        }
        //std::cout << "Move operator" << std::endl;
        return *this;
    }
    ///////////////////////////////////////////////
    //add
    Vector<T> operator+(const Vector<T>& other) const
    {
        assert(length == other.length);
        Vector<T> newer(length);
        std::cout<<"The addition gives: ";
        for(auto i=0;i<length;i++)
        {
            newer.data[i] = data[i]+other.data[i];
            std::cout<<newer.data[i]<<" ";
        }
        std::cout<<std::endl;
        return newer;
    }
    //minus
    Vector<T> operator-(const Vector<T>& other) const
    {
        assert(length == other.length);
        Vector<T> newer(length);
        for(auto i=0;i<length;i++)
            newer.data[i] = data[i]-other.data[i];
        return newer;
    }
    // Multiply by a scalar
    Vector<T> operator*(T scalar)
    {
        Vector<T> newer(length);
        std::cout<<"Multiplication of a new vector by scalar provides: ";
        for (auto i=0; i<length; i++)
        {
            newer.data[i] = data[i] * scalar;
            std::cout<<newer.data[i]<<" ";
        }
        std::cout<<std::endl;
        return newer;
    }
    //////////////////////////////////////////
    // Add to existing Vector
    Vector<T>& operator+=(const Vector<T>& other)
    {
        for (auto i=0; i<length; i++)
            data[i] += other.data[i];
        return *this;
    }
    // Multiply existing Vector by a scalar
    Vector<T>& operator*=(T scalar)
    {
        std::cout<<"Multiplication of an existing vector by scalar provides: ";
        for (auto i=0; i<length; i++)
        {
            data[i] *= scalar;
            std::cout<<data[i]<<" ";
        }
        std::cout<<std::endl;
        return *this;
    }
    double Valueform(int i)
    {
        return data[i];
    }
    int Lengthfinder()
    {
        return length;
    }
    ///////////////////////////////////////////
//destructor
    ~Vector()
    {
        delete[] data;
        data = nullptr;
        length = 0;
    }
};

template<typename T>
T dot(const Vector<T>& lhs, const Vector<T>& rhs)
{
    // Your implementation of the dot function starts here
    T result = 0;
    for (auto i=0; i<lhs.Lengthfinder(); i++)
    {
        result = lhs.Valueform(i)*rhs.Valueform(i);
        //result + = multiply(lhs.data[i],rhs.data[i]);
       // result += lhs.data[i]*rhs.data[i];
    }
    return result;
}
//failsafe for value multiplied by a vector
template <typename T, typename I>
Vector<T> operator*(I i,Vector<T> other)
{
    std::cout<<"Multiplication was done by a vector and failsafe activated"<<std::endl;
    return(other* T(i)) ;
}

int main()
{
    Vector<double> a(5);
    Vector<double> b({ 1 , 2 , 3 , 4 });
    Vector<double> c({ 2 , 3 , 4 });
    Vector<double> d({ 5 , 2 , 1 });

   // std::cout<< "a=c" <<std::endl;
    a = c;
  //  std::cout<< "e = c+d" <<std::endl;
    Vector<double> e;
    e = c+d;
  //  std::cout<< "f = c*5" <<std::endl;
    Vector<double> f;
    f = c*5;
 //   std::cout<< "g = 5*d" <<std::endl;
    Vector<double> g;
    g = 5*d;
    Vector<double> Dott;
    Dott = dot(c,d);
    return 0;
}
</code>```

The code does not allow me to call for the functions Valueform and Lengthfinder, anyone has a possible work around where I can get specific data values and length since the class variables are private? The functions are mostly worked around the template but I would like to just call 2 functions to get certain attributes and they are giving me errors that shouldn't exist, althought I'm not sure why exactly.

答:
Your dot function is taking constant vectors:

```<code>template<typename T>
T dot(const Vector<T>& lhs, const Vector<T>& rhs)
{ //  ^^^^^-----------------^^^^^----- these are const
    // Your implementation of the dot function starts here
}
</code>```

But, your member functions are not marked as const. You should declare them const to make these functions available:

```<code>double Valueform(int i) const
{
    return data[i];
}
int Lengthfinder() const
{
    return length;
}
</code>```

Title: Template function calling

Body:
#include <iostream>
#include <memory>
#include <initializer_list>
#include <cassert>
template <typename T>
class Vector
{
    // Your implementation of the Vector class starts here

    private:
//attributes
    int length;
    T* data;

    public:
//constructors
    Vector()
    :length(0),
    data(nullptr)
    {
        std::cout<<"New empty object created"<<std::endl;
    }

    Vector(int length)
    :length(length),
    data(new T[length])
    {
        std::cout<< "Length of object is = " <<length <<std::endl;
    }

    //use a copy of another Vector
    Vector(const Vector& other)
    : Vector(other.length)
    {
        for(int i=0;i<length;i++)
            data[i]=other.data[i];

    }

    // using initializer list
    Vector(std::initializer_list<T> list)
    : Vector((int)list.size())
    {
        std::uninitialized_copy(list.begin(), list.end(), data);
        std::cout<< "The elements in the object are: ";
        for (auto it = std::begin(list); it!=std::end(list); ++it)
        std::cout << ' ' << *it;
        std::cout<<std::endl;
    }

//operators

    //copy
    Vector<T>& operator=(const Vector<T>& other)
    {
        if(this!= &other)
        {
            std::cout<<"Copied constructor"<<std::endl;
            delete[] data;
            length = other.length;
            std::cout<<"New length ="<<length<<std::endl;
            data = new T[length];
            std::cout<<"The elements in the object are: ";
            for(int i=0;i<length;i++)
            {
                data[i]=other.data[i];
                std::cout<<data[i]<<" ";
            }
        }
        std::cout<<std::endl;
        //std::cout << "copy operator" << std::endl;
        return *this;
    }
    //move
    Vector<T>& operator=(Vector<T>&& other)
    {
        if(this!= &other)
        {
            delete[] data;
            length = other.length;
            data = new T[length];
            for(int i=0;i<length;i++){
                data[i]=other.data[i];}
            other.length = 0;
            delete[] other.data;
            other.data = nullptr;
        }
        //std::cout << "Move operator" << std::endl;
        return *this;
    }
    ///////////////////////////////////////////////
    //add
    Vector<T> operator+(const Vector<T>& other) const
    {
        assert(length == other.length);
        Vector<T> newer(length);
        std::cout<<"The addition gives: ";
        for(auto i=0;i<length;i++)
        {
            newer.data[i] = data[i]+other.data[i];
            std::cout<<newer.data[i]<<" ";
        }
        std::cout<<std::endl;
        return newer;
    }
    //minus
    Vector<T> operator-(const Vector<T>& other) const
    {
        assert(length == other.length);
        Vector<T> newer(length);
        for(auto i=0;i<length;i++)
            newer.data[i] = data[i]-other.data[i];
        return newer;
    }
    // Multiply by a scalar
    Vector<T> operator*(T scalar)
    {
        Vector<T> newer(length);
        std::cout<<"Multiplication of a new vector by scalar provides: ";
        for (auto i=0; i<length; i++)
        {
            newer.data[i] = data[i] * scalar;
            std::cout<<newer.data[i]<<" ";
        }
        std::cout<<std::endl;
        return newer;
    }
    //////////////////////////////////////////
    // Add to existing Vector
    Vector<T>& operator+=(const Vector<T>& other)
    {
        for (auto i=0; i<length; i++)
            data[i] += other.data[i];
        return *this;
    }
    // Multiply existing Vector by a scalar
    Vector<T>& operator*=(T scalar)
    {
        std::cout<<"Multiplication of an existing vector by scalar provides: ";
        for (auto i=0; i<length; i++)
        {
            data[i] *= scalar;
            std::cout<<data[i]<<" ";
        }
        std::cout<<std::endl;
        return *this;
    }
    double Valueform(int i)
    {
        return data[i];
    }
    int Lengthfinder()
    {
        return length;
    }
    ///////////////////////////////////////////
//destructor
    ~Vector()
    {
        delete[] data;
        data = nullptr;
        length = 0;
    }
};

template<typename T>
T dot(const Vector<T>& lhs, const Vector<T>& rhs)
{
    // Your implementation of the dot function starts here
    T result = 0;
    for (auto i=0; i<lhs.Lengthfinder(); i++)
    {
        result = lhs.Valueform(i)*rhs.Valueform(i);
        //result + = multiply(lhs.data[i],rhs.data[i]);
       // result += lhs.data[i]*rhs.data[i];
    }
    return result;
}
//failsafe for value multiplied by a vector
template <typename T, typename I>
Vector<T> operator*(I i,Vector<T> other)
{
    std::cout<<"Multiplication was done by a vector and failsafe activated"<<std::endl;
    return(other* T(i)) ;
}

int main()
{
    Vector<double> a(5);
    Vector<double> b({ 1 , 2 , 3 , 4 });
    Vector<double> c({ 2 , 3 , 4 });
    Vector<double> d({ 5 , 2 , 1 });

   // std::cout<< "a=c" <<std::endl;
    a = c;
  //  std::cout<< "e = c+d" <<std::endl;
    Vector<double> e;
    e = c+d;
  //  std::cout<< "f = c*5" <<std::endl;
    Vector<double> f;
    f = c*5;
 //   std::cout<< "g = 5*d" <<std::endl;
    Vector<double> g;
    g = 5*d;
    Vector<double> Dott;
    Dott = dot(c,d);
    return 0;
}

The code does not allow me to call for the functions Valueform and Lengthfinder, anyone has a possible work around where I can get specific data values and length since the class variables are private? The functions are mostly worked around the template but I would like to just call 2 functions to get certain attributes and they are giving me errors that shouldn't exist, althought I'm not sure why exactly.

Body:
Your dot function is taking constant vectors:

template<typename T>
T dot(const Vector<T>& lhs, const Vector<T>& rhs)
{ //  ^^^^^-----------------^^^^^----- these are const
    // Your implementation of the dot function starts here
}

But, your member functions are not marked as const. You should declare them const to make these functions available:

double Valueform(int i) const
{
    return data[i];
}
int Lengthfinder() const
{
    return length;
}


问:
PostgreSQL union two tables and join with a third table
I want to union to tables and join them with a third metadata table and I would like to know which approach is the best/fastest?

The database is a PostgreSQL.

Below is my two suggestions, but other approaches are welcome.

To do the join before the union on both tables:

```<code>SELECT a.id, a.feature_type, b.datetime, b.file_path
FROM table1 a, metadata b WHERE a.metadata_id = b.id
UNION ALL
SELECT a.id, a.feature_type, b.datetime, b.file_path
FROM table2 a, metadata b WHERE a.metadata_id = b.id
</code>```

Or to do the union first and then do the join:

```<code>SELECT a.id, a.feature_type, b.datetime, b.file_path
FROM
(
    SELECT id, feature_type, metadata_id FROM table1
    UNION ALL
    SELECT id, feature_type, metadata_id FROM table2
)a, metadata b
WHERE a.metadata_id = b.id
</code>```

答: it can be unpredictable due to sql-engine optimizator. it's better to look at the execution plan. finally both approaches can be represented in the same way</p>

Body:
I want to union to tables and join them with a third metadata table and I would like to know which approach is the best/fastest?

The database is a PostgreSQL.

Below is my two suggestions, but other approaches are welcome.

To do the join before the union on both tables:

SELECT a.id, a.feature_type, b.datetime, b.file_path
FROM table1 a, metadata b WHERE a.metadata_id = b.id
UNION ALL
SELECT a.id, a.feature_type, b.datetime, b.file_path
FROM table2 a, metadata b WHERE a.metadata_id = b.id

Or to do the union first and then do the join:

SELECT a.id, a.feature_type, b.datetime, b.file_path
FROM
(
    SELECT id, feature_type, metadata_id FROM table1
    UNION ALL
    SELECT id, feature_type, metadata_id FROM table2
)a, metadata b
WHERE a.metadata_id = b.id


问:
The maximum number of users who have logged in to the Oracle Database
Is there any variable or view in the Oracle Database 12 that stores the maximum number of users who have logged in at the same time (for example since the last restart)?</p>

答:
You can check system view V$RESOURCE_LIMIT for the MAX_UTILIZATION of resource called SESSIONS:

```<code>SELECT MAX_UTILIZATION FROM V$RESOURCE_LIMIT WHERE RESOURCE_NAME = 'SESSIONS'
</code>```

From the documentation:

SESSIONS specifies the maximum number of sessions that can be created in the system. Because every login requires a session, this parameter effectively determines the maximum number of concurrent users in the system.

MAX_UTILIZATION is like a high-water mark that shows the maximum value that the parameter reached. It is reset everytime the instance restarts.

Body:
You can check system view V$RESOURCE_LIMIT for the MAX_UTILIZATION of resource called SESSIONS:

SELECT MAX_UTILIZATION FROM V$RESOURCE_LIMIT WHERE RESOURCE_NAME = 'SESSIONS'

From the documentation:

SESSIONS specifies the maximum number of sessions that can be created in the system. Because every login requires a session, this parameter effectively determines the maximum number of concurrent users in the system.

MAX_UTILIZATION is like a high-water mark that shows the maximum value that the parameter reached. It is reset everytime the instance restarts.


问:
Sign in card prompt only one time after that their no more prompt of sign in card on any input from user to bot
I hava bot made using framework v4 using c#. It has been authenticated using azure ad. The first time i send user a message it prompt me with sign in prompt, but if i didn't sign in and the next time i send message to bot it doesnot prompt me sign in card again.I want that even if user doesnot sign in , the next time when user send a input to bot, the sign card should prompt again
The image in emulator

**The code used for ad authentication*

```<code>public class MainDialog : ComponentDialog
{
    private readonly IBotServices _botServices;
    protected readonly ILogger _logger;
    private readonly UserState _userState;

    private readonly string _connectionName;

    private readonly IConfiguration _configuration;
    public MainDialog(IConfiguration configuration,ILogger<MainDialog> logger, IBotServices botServices)
        : base(nameof(MainDialog))
    {
        _configuration = configuration;
        _logger = logger;
        _botServices = botServices ?? throw new System.ArgumentNullException(nameof(botServices));
        _connectionName = configuration["ConnectionName"];

        AddDialog(new OAuthPrompt(
          nameof(OAuthPrompt),
          new OAuthPromptSettings
          {
              ConnectionName = configuration["ConnectionName"],
              Text = "Please Sign In",
              Title = "Sign In",
              Timeout = 300000, // User has 5 minutes to login (1000 * 60 * 5)
          }));

        AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));

        AddDialog(new ChoicePrompt(nameof(ChoicePrompt)));
        AddDialog(new luisandqnamakerDialog(_botServices,_configuration,_logger));
        AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
        {
            PromptStepAsync,
            LoginStepAsync
        }));

        // The initial child Dialog to run.
        InitialDialogId = nameof(WaterfallDialog);
    }

    private async Task<DialogTurnResult> PromptStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        return await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);
    }

    private async Task<DialogTurnResult> LoginStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {

        // Get the token from the previous step. Note that we could also have gotten the
        // token directly from the prompt itself. There is an example of this in the next method.
        var tokenResponse = (TokenResponse)stepContext.Result;
        if (tokenResponse != null)
        {
            if (IsAuthCodeStep(stepContext.Context.Activity.Text))
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text("You are now logged in."), cancellationToken);
                return await stepContext.NextAsync();
            }
            else
            {
                 await stepContext.PromptAsync(nameof(luisandqnamakerDialog), new PromptOptions { Prompt = MessageFactory.Text("Would you like to ask your question?") }, cancellationToken);
                return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
            }
        }

        await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);

        return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
    }

    private bool IsAuthCodeStep(string code)
    {
        if (string.IsNullOrEmpty(code) || !code.Length.Equals(6)) return false;
        if (!int.TryParse(code, out int result)) return false;
        if (result > 1) return true;
        return false;
    }

    protected override async Task<DialogTurnResult> OnBeginDialogAsync(DialogContext innerDc, object options, CancellationToken cancellationToken = default(CancellationToken))
    {
        var result = await InterruptAsync(innerDc, cancellationToken);
        if (result != null)
        {
            return result;
        }

        return await base.OnBeginDialogAsync(innerDc, options, cancellationToken);
    }

    protected override async Task<DialogTurnResult> OnContinueDialogAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
    {
        var result = await InterruptAsync(innerDc, cancellationToken);
        if (result != null)
        {
            return result;
        }

        return await base.OnContinueDialogAsync(innerDc, cancellationToken);
    }

    private async Task<DialogTurnResult> InterruptAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
    {
        if (innerDc.Context.Activity.Type == ActivityTypes.Message)
        {
            var text = innerDc.Context.Activity.Text.ToLowerInvariant();

            if (text == "logout")
            {
                // The bot adapter encapsulates the authentication processes.
                var botAdapter = (BotFrameworkAdapter)innerDc.Context.Adapter;
                await botAdapter.SignOutUserAsync(innerDc.Context, _connectionName, null, cancellationToken);
                await innerDc.Context.SendActivityAsync(MessageFactory.Text("You have been signed out."), cancellationToken);
                return await innerDc.CancelAllDialogsAsync(cancellationToken);
            }
        }

        return null;
    }
}
</code>```

答:
The easy way to handle this is to just reprompt with text that tells the user to click the button that has already been sent. You can do this with the RetryPrompt property of PromptOptions. (Note that this will not work if the bot sends a typing activity.)

```<code>return await stepContext.BeginDialogAsync(
    nameof(OAuthPrompt),
    new PromptOptions
    {
        RetryPrompt = MessageFactory.Text("Please click the sign-in button.")
    }, cancellationToken);
</code>```

If you really want to reprompt with the whole card again then you have two options and they're both sort of complicated.

Option 1: Create the card yourself

The actual card that the OAuth prompt uses is generated in a private method, so there's no way for you to call that code. You'll have to have a look at the source code and copy it for your own use:

```<code>// Ensure prompt initialized
if (prompt == null)
{
    prompt = Activity.CreateMessageActivity();
}

if (prompt.Attachments == null)
{
    prompt.Attachments = new List<Attachment>();
}

// Append appropriate card if missing
if (!ChannelSupportsOAuthCard(turnContext.Activity.ChannelId))
{
    if (!prompt.Attachments.Any(a => a.Content is SigninCard))
    {
        var link = await adapter.GetOauthSignInLinkAsync(turnContext, _settings.OAuthAppCredentials, _settings.ConnectionName, cancellationToken).ConfigureAwait(false);
        prompt.Attachments.Add(new Attachment
        {
            ContentType = SigninCard.ContentType,
            Content = new SigninCard
            {
                Text = _settings.Text,
                Buttons = new[]
                {
                    new CardAction
                    {
                        Title = _settings.Title,
                        Value = link,
                        Type = ActionTypes.Signin,
                    },
                },
            },
        });
    }
}
else if (!prompt.Attachments.Any(a => a.Content is OAuthCard))
{
    var cardActionType = ActionTypes.Signin;
    string signInLink = null;

    if (turnContext.Activity.IsFromStreamingConnection())
    {
        signInLink = await adapter.GetOauthSignInLinkAsync(turnContext, _settings.OAuthAppCredentials, _settings.ConnectionName, cancellationToken).ConfigureAwait(false);
    }
    else if (turnContext.TurnState.Get<ClaimsIdentity>("BotIdentity") is ClaimsIdentity botIdentity && SkillValidation.IsSkillClaim(botIdentity.Claims))
    {
        // Force magic code for Skills (to be addressed in R8)
        signInLink = await adapter.GetOauthSignInLinkAsync(turnContext, _settings.ConnectionName, cancellationToken).ConfigureAwait(false);
        cardActionType = ActionTypes.OpenUrl;
    }

    prompt.Attachments.Add(new Attachment
    {
        ContentType = OAuthCard.ContentType,
        Content = new OAuthCard
        {
            Text = _settings.Text,
            ConnectionName = _settings.ConnectionName,
            Buttons = new[]
            {
                new CardAction
                {
                    Title = _settings.Title,
                    Text = _settings.Text,
                    Type = cardActionType,
                    Value = signInLink
                }
            }
        }
    });
}
</code>```

You'll notice that this code uses another private method called ChannelSupportsOAuthCard, and if the channel doesn't support OAuth cards then it uses a signin card instead. You haven't mentioned what channel you're using so I've included both cases here, but if you know that all the channels you're using do support OAuth cards then you can just use the OAuth card code. Alternatively, if you don't want any of your channels to use OAuth cards then you can just use the signin card code. Once you've created the activity with the card in it, you can use it for both the Prompt and the RetryPrompt properties of your prompt options:

```<code>return await stepContext.BeginDialogAsync(
    nameof(OAuthPrompt),
    new PromptOptions
    {
        Prompt = prompt,
        RetryPrompt = prompt
    }, cancellationToken);
</code>```

Option 2: Restart the dialog

If you really don't want to worry about creating the card yourself, the only way to use the builtin code for this purpose is to call BeginDialogAsync again. There are several ways to approach this but I'll try to go with the simplest route.

It looks like you already have some "try again" functionality in LoginStepAsync where you end the dialog and I presume whatever code you have calling the MainDialog will begin it again automatically on the next turn. If you don't want to wait for the next turn then you can use a little trick where you replace a dialog with itself:

```<code>await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);

return await stepContext.ReplaceDialogAsync(nameof(WaterfallDialog), cancellationToken: cancellationToken);
</code>```

Of course, to get to the LoginStepAsync step you'll need a way to end the OAuth prompt when the user types something. You can do this by returning true from the prompt's validator:

```<code>AddDialog(new OAuthPrompt(
  nameof(OAuthPrompt),
  new OAuthPromptSettings
  {
      ConnectionName = configuration["ConnectionName"],
      Text = "Please Sign In",
      Title = "Sign In",
      Timeout = 300000, // User has 5 minutes to login (1000 * 60 * 5)
  }, (_, _) => Task.FromResult(true)));
</code>```

This example will make the prompt's validator always return true and so it will end the prompt on the next turn no matter what. If you want, you could put your own logic in the validator so that it checks the activity and the recognizer result and decides based on that. But once the prompt ends and the waterfall proceeds to the next step, LoginStepAsync will see a null token response and so it will know that it needs to restart the dialog.

Body:
I hava bot made using framework v4 using c#. It has been authenticated using azure ad. The first time i send user a message it prompt me with sign in prompt, but if i didn't sign in and the next time i send message to bot it doesnot prompt me sign in card again.I want that even if user doesnot sign in , the next time when user send a input to bot, the sign card should prompt again
The image in emulator

**The code used for ad authentication*

public class MainDialog : ComponentDialog
{
    private readonly IBotServices _botServices;
    protected readonly ILogger _logger;
    private readonly UserState _userState;

    private readonly string _connectionName;

    private readonly IConfiguration _configuration;
    public MainDialog(IConfiguration configuration,ILogger<MainDialog> logger, IBotServices botServices)
        : base(nameof(MainDialog))
    {
        _configuration = configuration;
        _logger = logger;
        _botServices = botServices ?? throw new System.ArgumentNullException(nameof(botServices));
        _connectionName = configuration["ConnectionName"];

        AddDialog(new OAuthPrompt(
          nameof(OAuthPrompt),
          new OAuthPromptSettings
          {
              ConnectionName = configuration["ConnectionName"],
              Text = "Please Sign In",
              Title = "Sign In",
              Timeout = 300000, // User has 5 minutes to login (1000 * 60 * 5)
          }));

        AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));

        AddDialog(new ChoicePrompt(nameof(ChoicePrompt)));
        AddDialog(new luisandqnamakerDialog(_botServices,_configuration,_logger));
        AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
        {
            PromptStepAsync,
            LoginStepAsync
        }));

        // The initial child Dialog to run.
        InitialDialogId = nameof(WaterfallDialog);
    }

    private async Task<DialogTurnResult> PromptStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        return await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);
    }

    private async Task<DialogTurnResult> LoginStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {

        // Get the token from the previous step. Note that we could also have gotten the
        // token directly from the prompt itself. There is an example of this in the next method.
        var tokenResponse = (TokenResponse)stepContext.Result;
        if (tokenResponse != null)
        {
            if (IsAuthCodeStep(stepContext.Context.Activity.Text))
            {
                await stepContext.Context.SendActivityAsync(MessageFactory.Text("You are now logged in."), cancellationToken);
                return await stepContext.NextAsync();
            }
            else
            {
                 await stepContext.PromptAsync(nameof(luisandqnamakerDialog), new PromptOptions { Prompt = MessageFactory.Text("Would you like to ask your question?") }, cancellationToken);
                return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
            }
        }

        await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);

        return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
    }

    private bool IsAuthCodeStep(string code)
    {
        if (string.IsNullOrEmpty(code) || !code.Length.Equals(6)) return false;
        if (!int.TryParse(code, out int result)) return false;
        if (result > 1) return true;
        return false;
    }

    protected override async Task<DialogTurnResult> OnBeginDialogAsync(DialogContext innerDc, object options, CancellationToken cancellationToken = default(CancellationToken))
    {
        var result = await InterruptAsync(innerDc, cancellationToken);
        if (result != null)
        {
            return result;
        }

        return await base.OnBeginDialogAsync(innerDc, options, cancellationToken);
    }

    protected override async Task<DialogTurnResult> OnContinueDialogAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
    {
        var result = await InterruptAsync(innerDc, cancellationToken);
        if (result != null)
        {
            return result;
        }

        return await base.OnContinueDialogAsync(innerDc, cancellationToken);
    }

    private async Task<DialogTurnResult> InterruptAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
    {
        if (innerDc.Context.Activity.Type == ActivityTypes.Message)
        {
            var text = innerDc.Context.Activity.Text.ToLowerInvariant();

            if (text == "logout")
            {
                // The bot adapter encapsulates the authentication processes.
                var botAdapter = (BotFrameworkAdapter)innerDc.Context.Adapter;
                await botAdapter.SignOutUserAsync(innerDc.Context, _connectionName, null, cancellationToken);
                await innerDc.Context.SendActivityAsync(MessageFactory.Text("You have been signed out."), cancellationToken);
                return await innerDc.CancelAllDialogsAsync(cancellationToken);
            }
        }

        return null;
    }
}

Body:
The easy way to handle this is to just reprompt with text that tells the user to click the button that has already been sent. You can do this with the RetryPrompt property of PromptOptions. (Note that this will not work if the bot sends a typing activity.)

return await stepContext.BeginDialogAsync(
    nameof(OAuthPrompt),
    new PromptOptions
    {
        RetryPrompt = MessageFactory.Text("Please click the sign-in button.")
    }, cancellationToken);

If you really want to reprompt with the whole card again then you have two options and they're both sort of complicated.

Option 1: Create the card yourself

The actual card that the OAuth prompt uses is generated in a private method, so there's no way for you to call that code. You'll have to have a look at the source code and copy it for your own use:

// Ensure prompt initialized
if (prompt == null)
{
    prompt = Activity.CreateMessageActivity();
}

if (prompt.Attachments == null)
{
    prompt.Attachments = new List<Attachment>();
}

// Append appropriate card if missing
if (!ChannelSupportsOAuthCard(turnContext.Activity.ChannelId))
{
    if (!prompt.Attachments.Any(a => a.Content is SigninCard))
    {
        var link = await adapter.GetOauthSignInLinkAsync(turnContext, _settings.OAuthAppCredentials, _settings.ConnectionName, cancellationToken).ConfigureAwait(false);
        prompt.Attachments.Add(new Attachment
        {
            ContentType = SigninCard.ContentType,
            Content = new SigninCard
            {
                Text = _settings.Text,
                Buttons = new[]
                {
                    new CardAction
                    {
                        Title = _settings.Title,
                        Value = link,
                        Type = ActionTypes.Signin,
                    },
                },
            },
        });
    }
}
else if (!prompt.Attachments.Any(a => a.Content is OAuthCard))
{
    var cardActionType = ActionTypes.Signin;
    string signInLink = null;

    if (turnContext.Activity.IsFromStreamingConnection())
    {
        signInLink = await adapter.GetOauthSignInLinkAsync(turnContext, _settings.OAuthAppCredentials, _settings.ConnectionName, cancellationToken).ConfigureAwait(false);
    }
    else if (turnContext.TurnState.Get<ClaimsIdentity>("BotIdentity") is ClaimsIdentity botIdentity && SkillValidation.IsSkillClaim(botIdentity.Claims))
    {
        // Force magic code for Skills (to be addressed in R8)
        signInLink = await adapter.GetOauthSignInLinkAsync(turnContext, _settings.ConnectionName, cancellationToken).ConfigureAwait(false);
        cardActionType = ActionTypes.OpenUrl;
    }

    prompt.Attachments.Add(new Attachment
    {
        ContentType = OAuthCard.ContentType,
        Content = new OAuthCard
        {
            Text = _settings.Text,
            ConnectionName = _settings.ConnectionName,
            Buttons = new[]
            {
                new CardAction
                {
                    Title = _settings.Title,
                    Text = _settings.Text,
                    Type = cardActionType,
                    Value = signInLink
                }
            }
        }
    });
}

You'll notice that this code uses another private method called ChannelSupportsOAuthCard, and if the channel doesn't support OAuth cards then it uses a signin card instead. You haven't mentioned what channel you're using so I've included both cases here, but if you know that all the channels you're using do support OAuth cards then you can just use the OAuth card code. Alternatively, if you don't want any of your channels to use OAuth cards then you can just use the signin card code. Once you've created the activity with the card in it, you can use it for both the Prompt and the RetryPrompt properties of your prompt options:

return await stepContext.BeginDialogAsync(
    nameof(OAuthPrompt),
    new PromptOptions
    {
        Prompt = prompt,
        RetryPrompt = prompt
    }, cancellationToken);

Option 2: Restart the dialog

If you really don't want to worry about creating the card yourself, the only way to use the builtin code for this purpose is to call BeginDialogAsync again. There are several ways to approach this but I'll try to go with the simplest route.

It looks like you already have some "try again" functionality in LoginStepAsync where you end the dialog and I presume whatever code you have calling the MainDialog will begin it again automatically on the next turn. If you don't want to wait for the next turn then you can use a little trick where you replace a dialog with itself:

await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful please try again."), cancellationToken);

return await stepContext.ReplaceDialogAsync(nameof(WaterfallDialog), cancellationToken: cancellationToken);

Of course, to get to the LoginStepAsync step you'll need a way to end the OAuth prompt when the user types something. You can do this by returning true from the prompt's validator:

AddDialog(new OAuthPrompt(
  nameof(OAuthPrompt),
  new OAuthPromptSettings
  {
      ConnectionName = configuration["ConnectionName"],
      Text = "Please Sign In",
      Title = "Sign In",
      Timeout = 300000, // User has 5 minutes to login (1000 * 60 * 5)
  }, (_, _) => Task.FromResult(true)));

This example will make the prompt's validator always return true and so it will end the prompt on the next turn no matter what. If you want, you could put your own logic in the validator so that it checks the activity and the recognizer result and decides based on that. But once the prompt ends and the waterfall proceeds to the next step, LoginStepAsync will see a null token response and so it will know that it needs to restart the dialog.


问:
Input control in Angular: invalid input not detected
I'm using Angular 8 for my client application.
I want an error message to be displayed under the input box for the user when she inserts a wrong input. I'm using this inside my HTML:

```<code>  <!-- Score input -->
  <div class="form-group">
    <label for="score">Score</label>
    <input type="number" class="form-control"
           placeholder="0.0 ÷ 10.0"
           min="0.0" max="10.0" step="0.1" name="score"
           id="score"
           [(ngModel)]="model.score"
           #score="ngModel">
    <div [hidden]="score.valid" class="alert alert-danger">
      Insert a value between 0.0 and 10.0
    </div>
  </div>
</code>```

I would expect it to be displayed if the user was to input "asdf" for example instead of a number like "6.7". But it never appears. I tried removing [hidden]="score.valid" and it gets correctly displayed. Why is Angular considering "asdf" a valid input even if I set all those attributes: type="number" min="0.0" max="10.0" step="0.1" ?

答:
For better validation, you have to use FormControl in .ts file, also you could take a look at official doc https://angular.io/guide/form-validation.

FormControl more flexible than ngModel - worth trying:)

```<code>scoreControl = new FormControl('',
 Validators.compose([
   Validators.required,
   Validators.pattern('^[0-9]*$'),
   Validators.max(10)
 ])
);
</code>```

and modify your template with it:

```<code>  <div class="form-group">
    <label for="score">Score</label>
    <input type="number" class="form-control"
           placeholder="0.0 ÷ 10.0"
           min="0.0" max="10.0" step="0.1" name="score"
           id="score"
           [formControl]="scoreControl">

    <div *ngIf="score.invalid" class="alert alert-danger">
      Insert a value between 0.0 and 10.0
    </div>

   </div>
</code>```

Regarding only numbers input you could check here:
https://stackoverflow.com/a/41479077/9178709

The best approach is using directive

Body:
I'm using Angular 8 for my client application.
I want an error message to be displayed under the input box for the user when she inserts a wrong input. I'm using this inside my HTML:

    Score
    <input type="number" class="form-control"
           placeholder="0.0 ÷ 10.0"
           min="0.0" max="10.0" step="0.1" name="score"
           id="score"
           [(ngModel)]="model.score"
           #score="ngModel">

      Insert a value between 0.0 and 10.0

I would expect it to be displayed if the user was to input "asdf" for example instead of a number like "6.7". But it never appears. I tried removing [hidden]="score.valid" and it gets correctly displayed. Why is Angular considering "asdf" a valid input even if I set all those attributes: type="number" min="0.0" max="10.0" step="0.1" ?

Body:
For better validation, you have to use FormControl in .ts file, also you could take a look at official doc https://angular.io/guide/form-validation.

FormControl more flexible than ngModel - worth trying:)

scoreControl = new FormControl('',
 Validators.compose([
   Validators.required,
   Validators.pattern('^[0-9]*$'),
   Validators.max(10)
 ])
);

and modify your template with it:

  <div class="form-group">
    <label for="score">Score</label>
    <input type="number" class="form-control"
           placeholder="0.0 ÷ 10.0"
           min="0.0" max="10.0" step="0.1" name="score"
           id="score"
           [formControl]="scoreControl">

    <div *ngIf="score.invalid" class="alert alert-danger">
      Insert a value between 0.0 and 10.0
    </div>

   </div>

Regarding only numbers input you could check here:
https://stackoverflow.com/a/41479077/9178709

The best approach is using directive


问:
Magento and Wordpress not sharing session data (like number of items in cart)
Using the code below in the index.php file of a WP template:

```<code>require_once '/Users/xxx/Documents/Projects/honora/trunk/app/Mage.php';
umask(0);
Mage::app('default');
Mage::getSingleton('core/session', array('name' => 'frontend'));
Mage::log(Mage::helper('checkout/cart')->getCart()->getItemsCount());
</code>```

should in theory give me the number of items in my cart in a Wordpress blog in the Mage log.  After adding an item to my cart in one version of Magento I have, the log of when I arrive at my blog shows that I correctly have 1 item.  However, in a completely different version of Magento, this isn't the case, and instead logs 0.

Now I know that this is a pretty vague question, but can anyone throw out some possible solutions or ways to check into what's going on?  I don't believe it's necessarily an issue with WP, instead believing it's something that's happening between Mage::app() and the call to the session model.

Any help would be appreciated.

答: I realise this is an old question, but our new Wordgento plugin should help people solve this issue in future.</p>

ContentLicense: CC BY-SA 2.5

Body:
Using the code below in the index.php file of a WP template:

require_once '/Users/xxx/Documents/Projects/honora/trunk/app/Mage.php';
umask(0);
Mage::app('default');
Mage::getSingleton('core/session', array('name' => 'frontend'));
Mage::log(Mage::helper('checkout/cart')->getCart()->getItemsCount());

should in theory give me the number of items in my cart in a Wordpress blog in the Mage log.  After adding an item to my cart in one version of Magento I have, the log of when I arrive at my blog shows that I correctly have 1 item.  However, in a completely different version of Magento, this isn't the case, and instead logs 0.

Now I know that this is a pretty vague question, but can anyone throw out some possible solutions or ways to check into what's going on?  I don't believe it's necessarily an issue with WP, instead believing it's something that's happening between Mage::app() and the call to the session model.

Any help would be appreciated.


问:
Swift 3 OutputStream hanging?
I wrote a simple Swift program to write to a server; I want to send data back to back or in a loop to a server; I tried doing something simple where I can simply send a message back to back (two pieces of data) but there is a hang; that is, the server only receives the first message but not the second message; why is this?

I am using StreamDelegate in Swift 3 and I am using OutputStream write method

```<code>print("Hello, World!")

import Foundation

class Connection: NSObject, StreamDelegate {

    private var inputStream: InputStream!
    private var outputStream: OutputStream!

    private var my_address: CFString
    private var my_port: UInt32

    init (address: CFString, port:UInt32) {
        self.my_address = address
        self.my_port = port
        super.init()
    }

    func connect() {
        print("connecting...")

        var readStream:  Unmanaged<CFReadStream>?
        var writeStream: Unmanaged<CFWriteStream>?

        CFStreamCreatePairWithSocketToHost(nil, self.my_address, self.my_port, &readStream, &writeStream)

        // Documentation suggests readStream and writeStream can be assumed to
        // be non-nil. It might be wise to test if either is nil
        // and implement error-handling as needed.

//        self.inputStream = readStream!.takeRetainedValue()
        self.outputStream = writeStream!.takeRetainedValue()

//        self.inputStream.delegate = self
        self.outputStream.delegate = self

//        self.inputStream.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
//        self.outputStream.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)

//        self.inputStream.open()
        self.outputStream.open()
    }

    func disconnect() {
        self.inputStream.close()
        self.outputStream.close()
    }

    func stream(aStream: Stream, handleEvent eventCode: Stream.Event) {
        switch (eventCode){
        case Stream.Event.errorOccurred:
            NSLog("ErrorOccurred")
        case Stream.Event.endEncountered:
            NSLog("EndEncountered")
        case Stream.Event.hasBytesAvailable:
            NSLog("HasBytesAvaible")
            var buffer = [UInt8](repeating: 0, count: 4096)
            while (inputStream.hasBytesAvailable){
                var len = inputStream.read(&buffer, maxLength: buffer.count)
                if(len > 0){
                    var output = NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue)
                    if (output != ""){
                        NSLog("server said: %@", output!)
                    }
                } else {
                    print("empty string from stream")
                }
            }
        case Stream.Event.openCompleted:
            NSLog("OpenCompleted")
        case Stream.Event.hasSpaceAvailable:
            NSLog("HasSpaceAvailable")
        default: print("default reached. unknown stream event")
        }
    }

    func sendMessage(message: String) {
        let buff = [UInt8](message.utf8)
        self.outputStream.write(buff, maxLength: buff.count)
    }

    func getOutputStream() -> OutputStream {
        return self.outputStream
    }

}

var socket = Connection(address: "000.000.0.000" as CFString, port: 0000)

socket.connect()

socket.sendMessage(message: "Hey you! 1")
socket.sendMessage(message: "Hey you! 2")
</code>```

\

```<code>import Darwin
import Foundation
import UIKit
import Dispatch

class ViewController: UIViewController {

    @IBOutlet private weak var joystickMove: Joystick!
    @IBOutlet private weak var joystickRotate: Joystick!

    private var joystick = Joystick()
    private var contour = Contours()
    private var contour_index: Int = 0

    private var socket = Connection(address: "000.000.0.000" as CFString, port: 0000)

    override func viewDidLoad() {
        super.viewDidLoad()
        createJoystick()
        createContours()
        createButton()
    }

    private func createJoystick() {

        let n: CGFloat = 100.0
        let x: CGFloat = (UIScreen.main.bounds.width/2) - (n/2.0)
        let y: CGFloat = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/4.0)

        self.joystick.frame = CGRect(x: x, y: y, width: n, height: n)
        self.joystick.backgroundColor =  UIColor.clear

        self.joystick.substrateColor = UIColor.lightGray
        self.joystick.substrateBorderColor = UIColor.gray
        self.joystick.substrateBorderWidth = 1.0
        self.joystick.stickSize = CGSize(width: 50.0, height: 50.0)
        self.joystick.stickColor = UIColor.darkGray
        self.joystick.stickBorderColor = UIColor.black
        self.joystick.stickBorderWidth = 2.0
        self.joystick.fade = 0.5

        var packet = ""

        DispatchQueue.global(qos: .userInitiated).async { // do some task

            self.joystick.trackingHandler = { (data) -> () in

                let power = sqrt(pow(Double(data.velocity.x), 2.0) + pow(Double(data.velocity.y), 2.0))
                let theta = atan2(Double(-data.velocity.y), Double(data.velocity.x))
                let degrees = theta * (180.0 / M_PI)

                if degrees >= 55 && degrees <= 125 { // move forward
                    packet = "\(1) \(1) \(power) \(power)"
                } else if degrees >= -125 && degrees <= -55 { // move backwards
                    packet = "\(-1) \(-1) \(power) \(power)"
                } else if degrees >= -55 && degrees <= 55 { // turn right
                    packet = "\(1) \(-1) \(power) \(power)"
                } else if (degrees >= 125 && degrees <= 180) && (degrees >= -180 && degrees <= -125) { // turn left
                    packet = "\(-1) \(1) \(power) \(power)"
                }

                self.socket.connect()

                let sent = self.socket.sendMessage(message: packet)

                if sent {
                    print("packet sent!\n \(packet)")
                }

                self.socket.stream(aStream: self.socket.inputStream, handleEvent: Stream.Event.hasBytesAvailable)

//                self.socket.changeWhenHasBytesAvailable = { str in
//                    print("my-str: \(str.characters)")
//                }

                self.socket.disconnect()
            }

        }

        view.addSubview(joystick)
    }

    private func createContours() {
        let n: CGFloat = 350.0
        let x: CGFloat = (UIScreen.main.bounds.width/2.0) - (n/2.0)
        let y: CGFloat = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/4.0) - n - 100.0
        self.contour.frame = CGRect(x: x, y: y, width: n, height: n)
        self.contour.backgroundColor = UIColor.clear
        view.addSubview(self.contour)
    }

    private func createButton() {
        let width: CGFloat = 150.0
        let height: CGFloat = 75.0
        let x: CGFloat = (UIScreen.main.bounds.width/2.0) - (width/2.0)
        let y: CGFloat = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/4.0) - width

        let button: UIButton = UIButton(frame: CGRect(x: x, y: y, width: width, height: height))
        button.backgroundColor = UIColor.blue
        button.setTitle("Contour Views", for: .normal)
        button.addTarget(self, action: #selector(self.buttonAction), for: .touchUpInside)
        button.tag = 1
        view.addSubview(button)
    }

    @objc private func buttonAction(sender: UIButton!) {
        var btnsendtag: UIButton = sender
        if btnsendtag.tag == 1 {
            self.contour_index = (self.contour_index + 1) % 2
            switch self.contour_index {
            case 0:
                for index in 0...356 {
                    if self.contour.distx[index] != -1 && self.contour.disty[index] != -1 {
                        self.contour.circles[index].alpha = 0
                    }
                }
            case 1:
                for index in 0...356 {
                    if self.contour.distx[index] != -1 && self.contour.disty[index] != -1 {
                        self.contour.circles[index].alpha = 1
                    }
                }
            default:
                for index in 0...356 {
                    if self.contour.distx[index] != -1 && self.contour.disty[index] != -1 {
                        self.contour.circles[index].alpha = 1
                        UIColor.cyan.setFill()
                        self.contour.lines[index].fill()
                        self.contour.lines[index].stroke()
                    }
                }
            }

        }
    }

    override func viewDidAppear(_ animated: Bool) {
        DispatchQueue.global(qos: .background).async { // do some task
            //            self.socket.connect()
            //            var packet = "1 1 0 0"
            //            let sent = self.socket.sendMessage(message: packet)
            //            if sent {
            //                print("packet sent!\n \(packet)")
            //            }
            //            self.socket.disconnect()
        }
    }

    public func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
        DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
            completion()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillDisappear(_ animated: Bool) {
        //        self.socket.disconnect()
    }
}
</code>```

\

```<code>import Foundation

class Connection: NSObject, StreamDelegate {

    public var inputStream: InputStream!
    private var outputStream: OutputStream!

    private var my_address: CFString
    private var my_port: UInt32

    public var changeWhenHasBytesAvailable: ((String)->())?

    init (address: CFString, port:UInt32) {
        self.my_address = address
        self.my_port = port
        super.init()
    }

    public func connect() {

        var readStream:  Unmanaged<CFReadStream>?
        var writeStream: Unmanaged<CFWriteStream>?

        CFStreamCreatePairWithSocketToHost(nil, self.my_address, self.my_port, &readStream, &writeStream)

        self.inputStream = readStream!.takeRetainedValue()
        self.outputStream = writeStream!.takeRetainedValue()

        self.inputStream.delegate = self
        self.outputStream.delegate = self

        self.inputStream.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
        self.outputStream.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)

        self.inputStream.open()
        self.outputStream.open()

    }

    public func stream(aStream: Stream, handleEvent eventCode: Stream.Event) {

        //        DispatchQueue.global(qos: .userInitiated).async { // do some task

        print("stream")

        if aStream === self.inputStream {
            switch eventCode {

            case Stream.Event.openCompleted:
                print("open")
                break

            case Stream.Event.errorOccurred:
                print("error")
                break

            case Stream.Event.hasBytesAvailable:
                print("available!")

                //                    var inputBuffer = Array<UInt8>(repeating: 0, count:2048)
                //                    self.inputStream?.read(&inputBuffer, maxLength: 2048)
                //                    self.changeWhenHasBytesAvailable?(String(bytes: inputBuffer, encoding: String.Encoding.utf8)!)

                var buffer = [UInt8](repeating: 0, count: 512)
                while (self.inputStream.hasBytesAvailable){
                    print("before read")
                    var len = self.inputStream.read(&buffer, maxLength: buffer.count)
                    print("after read")
                    if(len > 0){
                        //                            var output = NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue)
                        var output = NSString(bytes: &buffer, length: len, encoding: String.Encoding.utf8.rawValue)
                        if (output != ""){
                            print("output: \(output!)")

                        }
                    } else {
                        print("empty string from stream")
                    }
                    print("while")
                }

                break
            default:
                print("default")
                break
            }
        }
        //        }
    }

    public func sendMessage(message: String) -> Bool {
        var sent: Bool = false
        let buff = [UInt8](message.utf8)
        let result = self.outputStream.write(buff, maxLength: buff.count)

        if result != -1 {
            sent = true
        }
        return sent
    }

    public func disconnect() {
        self.inputStream.close()
        self.outputStream.close()

        //        self.inputStream.remove(from: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
        //        self.outputStream.remove(from: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
    }

}
</code>```

update; send works! but not receiving data?

答:
Don't use a while inside the StreamDelegate when you are reading:

```<code>while (inputStream.hasBytesAvailable){
   var len = inputStream.read(&buffer, maxLength: buffer.count)
   ...
}
</code>```

Just call read. If there are more bytes, your delegate will be called again.

Title: Swift 3 OutputStream hanging?

Body:
I wrote a simple Swift program to write to a server; I want to send data back to back or in a loop to a server; I tried doing something simple where I can simply send a message back to back (two pieces of data) but there is a hang; that is, the server only receives the first message but not the second message; why is this?

I am using StreamDelegate in Swift 3 and I am using OutputStream write method

print("Hello, World!")

import Foundation

class Connection: NSObject, StreamDelegate {

    private var inputStream: InputStream!
    private var outputStream: OutputStream!

    private var my_address: CFString
    private var my_port: UInt32

    init (address: CFString, port:UInt32) {
        self.my_address = address
        self.my_port = port
        super.init()
    }

    func connect() {
        print("connecting...")

        var readStream:  Unmanaged<CFReadStream>?
        var writeStream: Unmanaged<CFWriteStream>?

        CFStreamCreatePairWithSocketToHost(nil, self.my_address, self.my_port, &readStream, &writeStream)

        // Documentation suggests readStream and writeStream can be assumed to
        // be non-nil. It might be wise to test if either is nil
        // and implement error-handling as needed.

//        self.inputStream = readStream!.takeRetainedValue()
        self.outputStream = writeStream!.takeRetainedValue()

//        self.inputStream.delegate = self
        self.outputStream.delegate = self

//        self.inputStream.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
//        self.outputStream.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)

//        self.inputStream.open()
        self.outputStream.open()
    }

    func disconnect() {
        self.inputStream.close()
        self.outputStream.close()
    }

    func stream(aStream: Stream, handleEvent eventCode: Stream.Event) {
        switch (eventCode){
        case Stream.Event.errorOccurred:
            NSLog("ErrorOccurred")
        case Stream.Event.endEncountered:
            NSLog("EndEncountered")
        case Stream.Event.hasBytesAvailable:
            NSLog("HasBytesAvaible")
            var buffer = [UInt8](repeating: 0, count: 4096)
            while (inputStream.hasBytesAvailable){
                var len = inputStream.read(&buffer, maxLength: buffer.count)
                if(len > 0){
                    var output = NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue)
                    if (output != ""){
                        NSLog("server said: %@", output!)
                    }
                } else {
                    print("empty string from stream")
                }
            }
        case Stream.Event.openCompleted:
            NSLog("OpenCompleted")
        case Stream.Event.hasSpaceAvailable:
            NSLog("HasSpaceAvailable")
        default: print("default reached. unknown stream event")
        }
    }

    func sendMessage(message: String) {
        let buff = [UInt8](message.utf8)
        self.outputStream.write(buff, maxLength: buff.count)
    }

    func getOutputStream() -> OutputStream {
        return self.outputStream
    }

}

var socket = Connection(address: "000.000.0.000" as CFString, port: 0000)

socket.connect()

socket.sendMessage(message: "Hey you! 1")
socket.sendMessage(message: "Hey you! 2")

\

import Darwin
import Foundation
import UIKit
import Dispatch

class ViewController: UIViewController {

    @IBOutlet private weak var joystickMove: Joystick!
    @IBOutlet private weak var joystickRotate: Joystick!

    private var joystick = Joystick()
    private var contour = Contours()
    private var contour_index: Int = 0

    private var socket = Connection(address: "000.000.0.000" as CFString, port: 0000)

    override func viewDidLoad() {
        super.viewDidLoad()
        createJoystick()
        createContours()
        createButton()
    }

    private func createJoystick() {

        let n: CGFloat = 100.0
        let x: CGFloat = (UIScreen.main.bounds.width/2) - (n/2.0)
        let y: CGFloat = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/4.0)

        self.joystick.frame = CGRect(x: x, y: y, width: n, height: n)
        self.joystick.backgroundColor =  UIColor.clear

        self.joystick.substrateColor = UIColor.lightGray
        self.joystick.substrateBorderColor = UIColor.gray
        self.joystick.substrateBorderWidth = 1.0
        self.joystick.stickSize = CGSize(width: 50.0, height: 50.0)
        self.joystick.stickColor = UIColor.darkGray
        self.joystick.stickBorderColor = UIColor.black
        self.joystick.stickBorderWidth = 2.0
        self.joystick.fade = 0.5

        var packet = ""

        DispatchQueue.global(qos: .userInitiated).async { // do some task

            self.joystick.trackingHandler = { (data) -> () in

                let power = sqrt(pow(Double(data.velocity.x), 2.0) + pow(Double(data.velocity.y), 2.0))
                let theta = atan2(Double(-data.velocity.y), Double(data.velocity.x))
                let degrees = theta * (180.0 / M_PI)

                if degrees >= 55 && degrees <= 125 { // move forward
                    packet = "\(1) \(1) \(power) \(power)"
                } else if degrees >= -125 && degrees <= -55 { // move backwards
                    packet = "\(-1) \(-1) \(power) \(power)"
                } else if degrees >= -55 && degrees <= 55 { // turn right
                    packet = "\(1) \(-1) \(power) \(power)"
                } else if (degrees >= 125 && degrees <= 180) && (degrees >= -180 && degrees <= -125) { // turn left
                    packet = "\(-1) \(1) \(power) \(power)"
                }

                self.socket.connect()

                let sent = self.socket.sendMessage(message: packet)

                if sent {
                    print("packet sent!\n \(packet)")
                }

                self.socket.stream(aStream: self.socket.inputStream, handleEvent: Stream.Event.hasBytesAvailable)

//                self.socket.changeWhenHasBytesAvailable = { str in
//                    print("my-str: \(str.characters)")
//                }

                self.socket.disconnect()
            }

        }

        view.addSubview(joystick)
    }

    private func createContours() {
        let n: CGFloat = 350.0
        let x: CGFloat = (UIScreen.main.bounds.width/2.0) - (n/2.0)
        let y: CGFloat = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/4.0) - n - 100.0
        self.contour.frame = CGRect(x: x, y: y, width: n, height: n)
        self.contour.backgroundColor = UIColor.clear
        view.addSubview(self.contour)
    }

    private func createButton() {
        let width: CGFloat = 150.0
        let height: CGFloat = 75.0
        let x: CGFloat = (UIScreen.main.bounds.width/2.0) - (width/2.0)
        let y: CGFloat = UIScreen.main.bounds.height - (UIScreen.main.bounds.height/4.0) - width

        let button: UIButton = UIButton(frame: CGRect(x: x, y: y, width: width, height: height))
        button.backgroundColor = UIColor.blue
        button.setTitle("Contour Views", for: .normal)
        button.addTarget(self, action: #selector(self.buttonAction), for: .touchUpInside)
        button.tag = 1
        view.addSubview(button)
    }

    @objc private func buttonAction(sender: UIButton!) {
        var btnsendtag: UIButton = sender
        if btnsendtag.tag == 1 {
            self.contour_index = (self.contour_index + 1) % 2
            switch self.contour_index {
            case 0:
                for index in 0...356 {
                    if self.contour.distx[index] != -1 && self.contour.disty[index] != -1 {
                        self.contour.circles[index].alpha = 0
                    }
                }
            case 1:
                for index in 0...356 {
                    if self.contour.distx[index] != -1 && self.contour.disty[index] != -1 {
                        self.contour.circles[index].alpha = 1
                    }
                }
            default:
                for index in 0...356 {
                    if self.contour.distx[index] != -1 && self.contour.disty[index] != -1 {
                        self.contour.circles[index].alpha = 1
                        UIColor.cyan.setFill()
                        self.contour.lines[index].fill()
                        self.contour.lines[index].stroke()
                    }
                }
            }

        }
    }

    override func viewDidAppear(_ animated: Bool) {
        DispatchQueue.global(qos: .background).async { // do some task
            //            self.socket.connect()
            //            var packet = "1 1 0 0"
            //            let sent = self.socket.sendMessage(message: packet)
            //            if sent {
            //                print("packet sent!\n \(packet)")
            //            }
            //            self.socket.disconnect()
        }
    }

    public func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
        DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
            completion()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillDisappear(_ animated: Bool) {
        //        self.socket.disconnect()
    }
}

\

import Foundation

class Connection: NSObject, StreamDelegate {

    public var inputStream: InputStream!
    private var outputStream: OutputStream!

    private var my_address: CFString
    private var my_port: UInt32

    public var changeWhenHasBytesAvailable: ((String)->())?

    init (address: CFString, port:UInt32) {
        self.my_address = address
        self.my_port = port
        super.init()
    }

    public func connect() {

        var readStream:  Unmanaged<CFReadStream>?
        var writeStream: Unmanaged<CFWriteStream>?

        CFStreamCreatePairWithSocketToHost(nil, self.my_address, self.my_port, &readStream, &writeStream)

        self.inputStream = readStream!.takeRetainedValue()
        self.outputStream = writeStream!.takeRetainedValue()

        self.inputStream.delegate = self
        self.outputStream.delegate = self

        self.inputStream.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
        self.outputStream.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)

        self.inputStream.open()
        self.outputStream.open()

    }

    public func stream(aStream: Stream, handleEvent eventCode: Stream.Event) {

        //        DispatchQueue.global(qos: .userInitiated).async { // do some task

        print("stream")

        if aStream === self.inputStream {
            switch eventCode {

            case Stream.Event.openCompleted:
                print("open")
                break

            case Stream.Event.errorOccurred:
                print("error")
                break

            case Stream.Event.hasBytesAvailable:
                print("available!")

                //                    var inputBuffer = Array<UInt8>(repeating: 0, count:2048)
                //                    self.inputStream?.read(&inputBuffer, maxLength: 2048)
                //                    self.changeWhenHasBytesAvailable?(String(bytes: inputBuffer, encoding: String.Encoding.utf8)!)

                var buffer = [UInt8](repeating: 0, count: 512)
                while (self.inputStream.hasBytesAvailable){
                    print("before read")
                    var len = self.inputStream.read(&buffer, maxLength: buffer.count)
                    print("after read")
                    if(len > 0){
                        //                            var output = NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue)
                        var output = NSString(bytes: &buffer, length: len, encoding: String.Encoding.utf8.rawValue)
                        if (output != ""){
                            print("output: \(output!)")

                        }
                    } else {
                        print("empty string from stream")
                    }
                    print("while")
                }

                break
            default:
                print("default")
                break
            }
        }
        //        }
    }

    public func sendMessage(message: String) -> Bool {
        var sent: Bool = false
        let buff = [UInt8](message.utf8)
        let result = self.outputStream.write(buff, maxLength: buff.count)

        if result != -1 {
            sent = true
        }
        return sent
    }

    public func disconnect() {
        self.inputStream.close()
        self.outputStream.close()

        //        self.inputStream.remove(from: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
        //        self.outputStream.remove(from: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
    }

}

update; send works! but not receiving data?

Body:
Don't use a while inside the StreamDelegate when you are reading:

while (inputStream.hasBytesAvailable){
   var len = inputStream.read(&buffer, maxLength: buffer.count)
   ...
}

Just call read. If there are more bytes, your delegate will be called again.


问:
How to display a div/element on mouse hover using external JavaScript?
My divs are nested so i understand i cant display an element if its already hidden. I want the information(p1 inside my html code)to display once the mouse hovers over another element(h1 in my html. I have already made my paragraph 1 style to none in JavaScript, now i need it to re-appear, i have tried the following code to attempt to make it re-appear document.getElementById("1").onmouseover.style.display = "block"; but with no success.

This is My HTML code, ignore the order im new to web dev lol

This is the code i have tried but it doesnt seem to work

This is the end result i want, the circled text on hover display the paragraph

答:
So a few things. For starters, put actual code into your questions instead of screen shots. If we can't reproduce your issue it's difficult to troubleshoot usually from just pictures.

Next, you might familiarize yourself with syntax a bit more since p1 isn't a valid HTML element.

Then, try not to rely on javascript too much and keep presentation stuff on the compositor thread. Here's an example accomplishing your goal with no javascript. Hope it helps, cheers!

p {
  display: none;
}

h1:hover + p {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Hover me</h1>

<p>PEEK A BOO!</p></code>```

Body:
So a few things. For starters, put actual code into your questions instead of screen shots. If we can't reproduce your issue it's difficult to troubleshoot usually from just pictures.

Next, you might familiarize yourself with syntax a bit more since p1 isn't a valid HTML element.

Then, try not to rely on javascript too much and keep presentation stuff on the compositor thread. Here's an example accomplishing your goal with no javascript. Hope it helps, cheers!

p {
  display: none;
}

h1:hover + p {
  display: block;
}

<h1>Hover me</h1>

<p>PEEK A BOO!</p>