问:
Android rx call multiples sentences in sequence
stack overflow community, I am just starting with responsive programming rx, and I have the following code block in which in summary I have an insert with ROOM, with the generated id I save this information through a REST service with retrofit, if the service Answer that it was saved correctly, I update the registry successfully. Until now I have this code but I think it is very ugly in addition to the nests it generates.

Thank you in advance for your support.

Best regards

```<code>        acta.setStatus(0);
        disposable.add( actaDataSource.insert( acta )//Call insert row DAO with ROOM and return Single<Long>
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DisposableSingleObserver<Long>() {
                @Override
                public void onSuccess(Long id) {
                    acta.setId( id );
                    mOcrRepository.putActa( acta )//Call service rest with retrofit for save data in server
                            .subscribeOn( Schedulers.io() )
                            .observeOn( AndroidSchedulers.mainThread() )
                            .subscribeWith( new DisposableSingleObserver<ActaResponse>(){
                                @Override
                                public void onSuccess(ActaResponse actaResponse) {
                                    if( actaResponse.isSuccess() ){
                                        acta.setStatus(1);
                                        actaDataSource.update( acta )//Call update row DAO with ROOM and return Completable
                                                .subscribeOn( Schedulers.io() )
                                                .observeOn( AndroidSchedulers.mainThread() )
                                                .subscribeWith(new CompletableObserver() {
                                                    @Override
                                                    public void onSubscribe(Disposable d) {

                                                    }

                                                    @Override
                                                    public void onComplete() {
                                                        //Return three steps succes complete
                                                    }

                                                    @Override
                                                    public void onError(Throwable e) {
                                                        //Return three steps failed
                                                    }
                                                });
                                    }else{
                                        //Return one step success complete and two step failed

                                    }
                                }

                                @Override
                                public void onError(Throwable e) {
                                    //Return one step success complete and two step failed
                                }
                            });
                }

                @Override
                public void onError(Throwable e) {
                    //Return all  failed
                }
            }));
</code>```

答: Use flatmap operator can help you clean your code and make it look like simple.

Body:
stack overflow community, I am just starting with responsive programming rx, and I have the following code block in which in summary I have an insert with ROOM, with the generated id I save this information through a REST service with retrofit, if the service Answer that it was saved correctly, I update the registry successfully. Until now I have this code but I think it is very ugly in addition to the nests it generates.

Thank you in advance for your support.

Best regards

        acta.setStatus(0);
        disposable.add( actaDataSource.insert( acta )//Call insert row DAO with ROOM and return Single<Long>
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DisposableSingleObserver<Long>() {
                @Override
                public void onSuccess(Long id) {
                    acta.setId( id );
                    mOcrRepository.putActa( acta )//Call service rest with retrofit for save data in server
                            .subscribeOn( Schedulers.io() )
                            .observeOn( AndroidSchedulers.mainThread() )
                            .subscribeWith( new DisposableSingleObserver<ActaResponse>(){
                                @Override
                                public void onSuccess(ActaResponse actaResponse) {
                                    if( actaResponse.isSuccess() ){
                                        acta.setStatus(1);
                                        actaDataSource.update( acta )//Call update row DAO with ROOM and return Completable
                                                .subscribeOn( Schedulers.io() )
                                                .observeOn( AndroidSchedulers.mainThread() )
                                                .subscribeWith(new CompletableObserver() {
                                                    @Override
                                                    public void onSubscribe(Disposable d) {

                                                    }

                                                    @Override
                                                    public void onComplete() {
                                                        //Return three steps succes complete
                                                    }

                                                    @Override
                                                    public void onError(Throwable e) {
                                                        //Return three steps failed
                                                    }
                                                });
                                    }else{
                                        //Return one step success complete and two step failed

                                    }
                                }

                                @Override
                                public void onError(Throwable e) {
                                    //Return one step success complete and two step failed
                                }
                            });
                }

                @Override
                public void onError(Throwable e) {
                    //Return all  failed
                }
            }));


来源: stackexchange

问:
General JNA Questions (Discord Game SDK (C) -> Java)
Goal: Hey guys, I'm trying to use Discord's Game SDK in Java. Just a couple questions, thanks in advance for any help!

Question 1: When creating a JNA Structure, can I leave getters out? Example:

```<code>
import com.sun.jna.Callback;
import com.sun.jna.Structure;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/*
struct IDiscordCore {
    void (*destroy)(struct IDiscordCore* core);
    enum EDiscordResult (*run_callbacks)(struct IDiscordCore* core);
    void (*set_log_hook)(struct IDiscordCore* core, enum EDiscordLogLevel min_level, void* hook_data, void (*hook)(void* hook_data, enum EDiscordLogLevel level, const char* message));
    struct IDiscordApplicationManager* (*get_application_manager)(struct IDiscordCore* core);
    struct IDiscordUserManager* (*get_user_manager)(struct IDiscordCore* core);
    struct IDiscordImageManager* (*get_image_manager)(struct IDiscordCore* core);
    struct IDiscordActivityManager* (*get_activity_manager)(struct IDiscordCore* core);
    struct IDiscordRelationshipManager* (*get_relationship_manager)(struct IDiscordCore* core);
    struct IDiscordLobbyManager* (*get_lobby_manager)(struct IDiscordCore* core);
    struct IDiscordNetworkManager* (*get_network_manager)(struct IDiscordCore* core);
    struct IDiscordOverlayManager* (*get_overlay_manager)(struct IDiscordCore* core);
    struct IDiscordStorageManager* (*get_storage_manager)(struct IDiscordCore* core);
    struct IDiscordStoreManager* (*get_store_manager)(struct IDiscordCore* core);
    struct IDiscordVoiceManager* (*get_voice_manager)(struct IDiscordCore* core);
    struct IDiscordAchievementManager* (*get_achievement_manager)(struct IDiscordCore* core);
};
 */
public class IDiscordCore extends Structure {

    public interface OnDestroy extends Callback {
        void accept(IDiscordCore core);
    }

    public interface OnCallbacks extends Callback {
        EDiscordResult accept(IDiscordCore core);
    }

    private static final List<String> FIELD_ORDER = Collections.unmodifiableList(Arrays.asList(
            "destroy", "run_callbacks", "set_log_hook"
    ));

    public OnDestroy destroy;
    public OnCallbacks run_callbacks;
    public Object set_log_hook;

    @Override
    public boolean equals(Object o) {
        if(this == o)
            return true;
        if(!(o instanceof IDiscordCore))
            return false;
        IDiscordCore that = (IDiscordCore) o;
        return Objects.equals(destroy, that.destroy)
                && Objects.equals(run_callbacks, that.run_callbacks)
                && Objects.equals(set_log_hook, that.set_log_hook) ;
    }

    @Override
    public int hashCode() {
        return Objects.hash(destroy, run_callbacks, set_log_hook);
    }

    @Override
    protected List<String> getFieldOrder() {
        return FIELD_ORDER;
    }

}
</code>```

Question 2: When creating a JNA Structure, can I load fields that I don't intend on using as Java Objects? Example:

```<code>
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/*
//typedef int64_t DiscordClientId;
//typedef void* IDiscordCoreEvents;
struct DiscordCreateParams {
    DiscordClientId client_id;
    uint64_t flags;
    IDiscordCoreEvents* events;
    void* event_data;
    IDiscordApplicationEvents* application_events;
    DiscordVersion application_version;
    struct IDiscordUserEvents* user_events;
    DiscordVersion user_version;
    IDiscordImageEvents* image_events;
    DiscordVersion image_version;
    struct IDiscordActivityEvents* activity_events;
    DiscordVersion activity_version;
    struct IDiscordRelationshipEvents* relationship_events;
    DiscordVersion relationship_version;
    struct IDiscordLobbyEvents* lobby_events;
    DiscordVersion lobby_version;
    struct IDiscordNetworkEvents* network_events;
    DiscordVersion network_version;
    struct IDiscordOverlayEvents* overlay_events;
    DiscordVersion overlay_version;
    IDiscordStorageEvents* storage_events;
    DiscordVersion storage_version;
    struct IDiscordStoreEvents* store_events;
    DiscordVersion store_version;
    struct IDiscordVoiceEvents* voice_events;
    DiscordVersion voice_version;
    struct IDiscordAchievementEvents* achievement_events;
    DiscordVersion achievement_version;
};
 */
public class DiscordCreateParams extends Structure {

    public long client_id;

    public String flags;

    public Object events;

    public Object event_data;

    public Object application_events, application_version, user_events, user_version, image_events, image_version, activity_events, activity_version, relationship_events, relationship_version, lobby_events, lobby_version, network_events, network_version, overlay_events, overlay_version, storage_events, storage_version, store_events, store_version, voice_events, voice_version, achievement_events, achievement_version;

    private static final List<String> FIELD_ORDER = Collections.unmodifiableList(Arrays.asList("client_id", "flags", "events", "event_data", "application_events", "application_version", "user_events", "user_version", "image_events", "image_version", "activity_events", "activity_version", "relationship_events", "relationship_version", "lobby_events", "lobby_version", "network_events", "network_version", "overlay_events", "overlay_version", "storage_events", "storage_version", "store_events", "store_version", "voice_events", "voice_version", "achievement_events", "achievement_version"));

    @Override
    public boolean equals(Object o) {
        if(this == o)
            return true;
        if(!(o instanceof DiscordCreateParams))
            return false;
        DiscordCreateParams that = (DiscordCreateParams) o;
        return Objects.equals(client_id, that.client_id) && Objects.equals(flags, that.flags) && Objects.equals(events, that.events) && Objects.equals(event_data, that.event_data) && Objects.equals(application_events, that.application_events) && Objects.equals(application_version, that.application_version) && Objects.equals(user_events, that.user_events) && Objects.equals(user_version, that.user_version) && Objects.equals(image_events, that.image_events) && Objects.equals(image_version, that.image_version) && Objects.equals(activity_events, that.activity_events) && Objects.equals(activity_version, that.activity_version) && Objects.equals(relationship_events, that.relationship_events) && Objects.equals(relationship_version, that.relationship_version) && Objects.equals(lobby_events, that.lobby_events) && Objects.equals(lobby_version, that.lobby_version) && Objects.equals(network_events, that.network_events) && Objects.equals(network_version, that.network_version) && Objects.equals(overlay_events, that.overlay_events) && Objects.equals(overlay_version, that.overlay_version) && Objects.equals(storage_events, that.storage_events) && Objects.equals(store_version, that.store_version) && Objects.equals(voice_events, that.voice_events) && Objects.equals(voice_version, that.voice_version) && Objects.equals(achievement_events, that.achievement_events) && Objects.equals(achievement_version, that.achievement_version);
    }

    @Override
    public int hashCode() {
        return Objects.hash(client_id, flags, events, event_data, application_events, application_version, user_events, user_version, image_events, image_version, activity_events, activity_version, relationship_events, relationship_version, lobby_events, lobby_version, network_events, network_version, overlay_events, overlay_version, storage_events, storage_version, store_events, store_version, voice_events, voice_version, achievement_events, achievement_version);
    }

    @Override
    protected List<String> getFieldOrder() {
        return FIELD_ORDER;
    }

}
</code>```

答:
You might like taking a look at the many user mappings submitted to the JNA project, to get a general idea, but the answer to your questions:

You do not need getters. In fact, JNA's Structure class requires that you declare every element as public, so they are unnecessary and redundant.  They are sometimes included as convenience methods for things such as converting character arrays to strings, etc., but usually omitted.

You must include every element, or at least an equivalent byte size, of the native structure you're mapping.  If they are inline structures, you would have to actually use the mappings.  In the example above, they are mostly pointers (struct *) so you can simply put a Pointer object in their place to consume the same amount of memory.

ContentLicense: CC BY-SA 4.0

Body:
Goal: Hey guys, I'm trying to use Discord's Game SDK in Java. Just a couple questions, thanks in advance for any help!

Question 1: When creating a JNA Structure, can I leave getters out? Example:

import com.sun.jna.Callback;
import com.sun.jna.Structure;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/*
struct IDiscordCore {
    void (*destroy)(struct IDiscordCore* core);
    enum EDiscordResult (*run_callbacks)(struct IDiscordCore* core);
    void (*set_log_hook)(struct IDiscordCore* core, enum EDiscordLogLevel min_level, void* hook_data, void (*hook)(void* hook_data, enum EDiscordLogLevel level, const char* message));
    struct IDiscordApplicationManager* (*get_application_manager)(struct IDiscordCore* core);
    struct IDiscordUserManager* (*get_user_manager)(struct IDiscordCore* core);
    struct IDiscordImageManager* (*get_image_manager)(struct IDiscordCore* core);
    struct IDiscordActivityManager* (*get_activity_manager)(struct IDiscordCore* core);
    struct IDiscordRelationshipManager* (*get_relationship_manager)(struct IDiscordCore* core);
    struct IDiscordLobbyManager* (*get_lobby_manager)(struct IDiscordCore* core);
    struct IDiscordNetworkManager* (*get_network_manager)(struct IDiscordCore* core);
    struct IDiscordOverlayManager* (*get_overlay_manager)(struct IDiscordCore* core);
    struct IDiscordStorageManager* (*get_storage_manager)(struct IDiscordCore* core);
    struct IDiscordStoreManager* (*get_store_manager)(struct IDiscordCore* core);
    struct IDiscordVoiceManager* (*get_voice_manager)(struct IDiscordCore* core);
    struct IDiscordAchievementManager* (*get_achievement_manager)(struct IDiscordCore* core);
};
 */
public class IDiscordCore extends Structure {

    public interface OnDestroy extends Callback {
        void accept(IDiscordCore core);
    }

    public interface OnCallbacks extends Callback {
        EDiscordResult accept(IDiscordCore core);
    }

    private static final List<String> FIELD_ORDER = Collections.unmodifiableList(Arrays.asList(
            "destroy", "run_callbacks", "set_log_hook"
    ));

    public OnDestroy destroy;
    public OnCallbacks run_callbacks;
    public Object set_log_hook;

    @Override
    public boolean equals(Object o) {
        if(this == o)
            return true;
        if(!(o instanceof IDiscordCore))
            return false;
        IDiscordCore that = (IDiscordCore) o;
        return Objects.equals(destroy, that.destroy)
                && Objects.equals(run_callbacks, that.run_callbacks)
                && Objects.equals(set_log_hook, that.set_log_hook) ;
    }

    @Override
    public int hashCode() {
        return Objects.hash(destroy, run_callbacks, set_log_hook);
    }

    @Override
    protected List<String> getFieldOrder() {
        return FIELD_ORDER;
    }

}

Question 2: When creating a JNA Structure, can I load fields that I don't intend on using as Java Objects? Example:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/*
//typedef int64_t DiscordClientId;
//typedef void* IDiscordCoreEvents;
struct DiscordCreateParams {
    DiscordClientId client_id;
    uint64_t flags;
    IDiscordCoreEvents* events;
    void* event_data;
    IDiscordApplicationEvents* application_events;
    DiscordVersion application_version;
    struct IDiscordUserEvents* user_events;
    DiscordVersion user_version;
    IDiscordImageEvents* image_events;
    DiscordVersion image_version;
    struct IDiscordActivityEvents* activity_events;
    DiscordVersion activity_version;
    struct IDiscordRelationshipEvents* relationship_events;
    DiscordVersion relationship_version;
    struct IDiscordLobbyEvents* lobby_events;
    DiscordVersion lobby_version;
    struct IDiscordNetworkEvents* network_events;
    DiscordVersion network_version;
    struct IDiscordOverlayEvents* overlay_events;
    DiscordVersion overlay_version;
    IDiscordStorageEvents* storage_events;
    DiscordVersion storage_version;
    struct IDiscordStoreEvents* store_events;
    DiscordVersion store_version;
    struct IDiscordVoiceEvents* voice_events;
    DiscordVersion voice_version;
    struct IDiscordAchievementEvents* achievement_events;
    DiscordVersion achievement_version;
};
 */
public class DiscordCreateParams extends Structure {

    public long client_id;

    public String flags;

    public Object events;

    public Object event_data;

    public Object application_events, application_version, user_events, user_version, image_events, image_version, activity_events, activity_version, relationship_events, relationship_version, lobby_events, lobby_version, network_events, network_version, overlay_events, overlay_version, storage_events, storage_version, store_events, store_version, voice_events, voice_version, achievement_events, achievement_version;

    private static final List<String> FIELD_ORDER = Collections.unmodifiableList(Arrays.asList("client_id", "flags", "events", "event_data", "application_events", "application_version", "user_events", "user_version", "image_events", "image_version", "activity_events", "activity_version", "relationship_events", "relationship_version", "lobby_events", "lobby_version", "network_events", "network_version", "overlay_events", "overlay_version", "storage_events", "storage_version", "store_events", "store_version", "voice_events", "voice_version", "achievement_events", "achievement_version"));

    @Override
    public boolean equals(Object o) {
        if(this == o)
            return true;
        if(!(o instanceof DiscordCreateParams))
            return false;
        DiscordCreateParams that = (DiscordCreateParams) o;
        return Objects.equals(client_id, that.client_id) && Objects.equals(flags, that.flags) && Objects.equals(events, that.events) && Objects.equals(event_data, that.event_data) && Objects.equals(application_events, that.application_events) && Objects.equals(application_version, that.application_version) && Objects.equals(user_events, that.user_events) && Objects.equals(user_version, that.user_version) && Objects.equals(image_events, that.image_events) && Objects.equals(image_version, that.image_version) && Objects.equals(activity_events, that.activity_events) && Objects.equals(activity_version, that.activity_version) && Objects.equals(relationship_events, that.relationship_events) && Objects.equals(relationship_version, that.relationship_version) && Objects.equals(lobby_events, that.lobby_events) && Objects.equals(lobby_version, that.lobby_version) && Objects.equals(network_events, that.network_events) && Objects.equals(network_version, that.network_version) && Objects.equals(overlay_events, that.overlay_events) && Objects.equals(overlay_version, that.overlay_version) && Objects.equals(storage_events, that.storage_events) && Objects.equals(store_version, that.store_version) && Objects.equals(voice_events, that.voice_events) && Objects.equals(voice_version, that.voice_version) && Objects.equals(achievement_events, that.achievement_events) && Objects.equals(achievement_version, that.achievement_version);
    }

    @Override
    public int hashCode() {
        return Objects.hash(client_id, flags, events, event_data, application_events, application_version, user_events, user_version, image_events, image_version, activity_events, activity_version, relationship_events, relationship_version, lobby_events, lobby_version, network_events, network_version, overlay_events, overlay_version, storage_events, storage_version, store_events, store_version, voice_events, voice_version, achievement_events, achievement_version);
    }

    @Override
    protected List<String> getFieldOrder() {
        return FIELD_ORDER;
    }

}


问:
Placing two Firestore.instances inside an initState()
Now this maybe good practice or a complete no no!!

I was trying to resist placing more StreamBuilder(s) under build(BuildContext context) and tried to use initState() instead. I am having trouble due to not using Future/async/await correctly. The String _leaseTenantName (first initState() Firestore.instance) would have correct value but Strings _leaseUnitName & _leaseUnitPropertyUid (second initState() Firestore.instance) usually would return as null. StreamBuilder<PropertyDetails> below build would give the error message 'Invalid document reference. Document references must have an even number of segments, but properties has 1, null)' but kept trying and eventually worked when _leaseUnitPropertyUid finally had a value.

I believe the solution is to somehow wrap the two initState() Firestore.instances in a Future/async/await but could not work out a way to do this. Any ideas?? Or should I just use yet more nested StreamBuilders?

class _LeaseTileState extends State<LeaseTile> {
  String _leaseTenantName = '';
  String _leaseUnitPropertyUid = '';
  String _leaseUnitName = '';
  String _leasePropertyName = '';
  String _leasePropertyUnitName = '';

  @override
  void initState() {
    super.initState();
    Firestore.instance
        .collection("companies")
        .document(widget.leaseDetails.tenantUid)
        .snapshots()
        .listen((snapshot) {
      _leaseTenantName = snapshot.data['companyName'];
    });

    Firestore.instance
        .collection("units")
        .document(widget.leaseDetails.unitUid)
        .snapshots()
        .listen((snapshot) {
      _leaseUnitName = snapshot.data['unitName'];
      _leaseUnitPropertyUid = snapshot.data['propertyUid'];
    });
  }

  @override
  Widget build(BuildContext context) {
    final user = Provider.of<User>(context);
    return StreamBuilder<PropertyDetails>(
        stream: DatabaseServices(propertyUid: _leaseUnitPropertyUid)
            .propertyByDocumentID,
        builder: (context, userCompany) {
          if (!userCompany.hasData) return Loading();
          _leasePropertyName = userCompany.data.propertyName;
          _leasePropertyUnitName = '$_leasePropertyName - $_leaseUnitName';
          return Card(
```

答:
That's a big no no.

Firstly, there's nothing wrong in using multiple StreamBuilder, StreamBuilder help you simplify the usage of Streams so you don't end up messing things up with their subscriptions... like you did in initState().

When you call listen() on snapshots() as you did on initState(), you created a subscription, that subscription should be canceled on dispose(), but you don't cancel it, so you are leaking memory right there, a StreamBuilder would saved you here as it manages this for you.

Another thing to keep in mind is that you are using _leaseUnitPropertyUid on build(), but you don't check if _leaseUnitPropertyUid is valid. _leaseUnitPropertyUid is only going to be set after the Firebase snapshot() Stream emits one value and build() could be called before that. Again, StreamBuilder would have saved you here as well as you could check if it has emitted a value or not.

Also you are hardcoding the Firebase.instance on your code, which makes it very hard to test. Take a look on Dependency Injection and try to inject the Firebase.instance onto your class, like a Repository pattern or something similar, so you can swap the Firebase.instace for a testing Mock and make your code more testable.


问:
Cannot Understand The Exception
This is the code :

```<code>import java.awt.*;
import javax.swing.*;

class tester {
JFrame fr;
JPanel p;
Graphics g;

tester() {
 buildGUI();
}

public void buildGUI() {
 fr=new JFrame();
 p=new JPanel();
 p.setBackground(Color.red);
 g.setColor(Color.black);
 g.drawOval(18,45,78,39);
 g.fillOval(18,45,78,39);
 fr.add(p);
 fr.setVisible(true);
 fr.setSize(500,500);
}

 public static void main(String args[]) {
  new tester();
 }
}
</code>```

These are the exceptions produced when i try to run the code :

Exception in thread "main" java.lang.NullPointerException
        at tester.buildGUI(tester.java:17)
        at tester.<init>(tester.java:10)
        at tester.main(tester.java:26)

Why do i get these exceptions?
How can i solve it.

答: Always go to the line where the NullpointerException occured and see which objects are used on that line. In this case it was only the Graphic object "g" that was in use. Then try to figure out why "g" has a null reference. As you can see "g" was never instantiated, it was only declared. You have to new it up.</p>

ContentLicense: CC BY-SA 3.0

Title: Cannot Understand The Exception

Body:
This is the code :

import java.awt.*;
import javax.swing.*;

class tester {
JFrame fr;
JPanel p;
Graphics g;

tester() {
 buildGUI();
}

public void buildGUI() {
 fr=new JFrame();
 p=new JPanel();
 p.setBackground(Color.red);
 g.setColor(Color.black);
 g.drawOval(18,45,78,39);
 g.fillOval(18,45,78,39);
 fr.add(p);
 fr.setVisible(true);
 fr.setSize(500,500);
}

 public static void main(String args[]) {
  new tester();
 }
}

These are the exceptions produced when i try to run the code :

Exception in thread "main" java.lang.NullPointerException
        at tester.buildGUI(tester.java:17)
        at tester.<init>(tester.java:10)
        at tester.main(tester.java:26)

Why do i get these exceptions?
How can i solve it.


问:
redirect to specific div when img click
im trying to redirect to a specific location from the page when i click an image with link, the image has a link redirection.

sample img1 link www.test.com/#contactUs

```<code><div id="home">
</div>

<div id="aboutUs">
</div>

<div id="contactUs">
</div>
</code>```

what i wanted to do is when i click the img it will redirect to the contactUs div but the problem is when i tried to access access the page and clicks the link it redirects exactly to the contactUs tab but when i tried to use other device i encountered the img link redirects at the middle of aboutUs tab and constactUs tab or above contactUs div it doesn't redirects to the contactUs tab exactly

答:
Try doing the following code on onclick of image:

elmnt = document.getElementById("contactUs");
 elmnt.scrollTop = 0

Hope, this will help you.

Title: redirect to specific div when img click

Body:
im trying to redirect to a specific location from the page when i click an image with link, the image has a link redirection.

sample img1 link www.test.com/#contactUs

what i wanted to do is when i click the img it will redirect to the contactUs div but the problem is when i tried to access access the page and clicks the link it redirects exactly to the contactUs tab but when i tried to use other device i encountered the img link redirects at the middle of aboutUs tab and constactUs tab or above contactUs div it doesn't redirects to the contactUs tab exactly


问:
in Vue single-page app, how to prevent 404s on refresh
My single-page Vue app is running at my_domain.com/my_app/, but when I refresh anywhere, I get a 404/not found (not in my local dev environment). I have set an .htaccess file according to the docs and my router & vue.config.js file are configured according to my understanding as to how to prevent this but still I'm getting the 404s. Can someone please shed some light on this? (This is all according to Deploying vue js app and getting 404 error in routes & the Vue.js docs)

my vue.config.js (pertinent excerpt):

module.exports = {
    publicPath: process.env.NODE_ENV === 'production' ? '/my_app/' : '/',
    // [ etc. ]
```

<p>routes.js (pertinent excerpt):</p>

<pre class="lang-js prettyprint-override"><code>export default new Router({
    mode: "history",
    base: process.env.BASE_URL, // base: '/my_app/', also NG
    routes: [
        {
            path: '*',
            redirect: '/index.html'
        },
        {
            path: '/',
            redirect: '/index.html'
        },
        // [ SNIP ... my named routes here ]
        // and I also tried moving ...
        {
            path: '*',
            redirect: '/index.html'
        },
        // ... to the end of my routes
]
</code>```

.htaccess:

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /my_app/
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>
</code>```

Many thanks in advance,

Whiskey T.

答:
You need to use a path relative to the RewriteBase in the final RewriteRule, ie

```<code>RewriteRule . index.html [L]
</code>```

https://htaccess.madewithlove.be?share=b74bdbac-b8d3-5ee7-a586-2083808e0740

A much better option these days is to use the FallbackResource Directive. All you need is

```<code>FallbackResource /my_app/index.html
</code>```

and the appropriate Indexes override which you probably have already.

Body:
My single-page Vue app is running at my_domain.com/my_app/, but when I refresh anywhere, I get a 404/not found (not in my local dev environment). I have set an .htaccess file according to the docs and my router & vue.config.js file are configured according to my understanding as to how to prevent this but still I'm getting the 404s. Can someone please shed some light on this? (This is all according to Deploying vue js app and getting 404 error in routes & the Vue.js docs)

my vue.config.js (pertinent excerpt):

module.exports = {
    publicPath: process.env.NODE_ENV === 'production' ? '/my_app/' : '/',
    // [ etc. ]

routes.js (pertinent excerpt):

export default new Router({
    mode: "history",
    base: process.env.BASE_URL, // base: '/my_app/', also NG
    routes: [
        {
            path: '*',
            redirect: '/index.html'
        },
        {
            path: '/',
            redirect: '/index.html'
        },
        // [ SNIP ... my named routes here ]
        // and I also tried moving ...
        {
            path: '*',
            redirect: '/index.html'
        },
        // ... to the end of my routes
]

.htaccess:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /my_app/
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>

Many thanks in advance,

Whiskey T.

Body:
You need to use a path relative to the RewriteBase in the final RewriteRule, ie

RewriteRule . index.html [L]

https://htaccess.madewithlove.be?share=b74bdbac-b8d3-5ee7-a586-2083808e0740

A much better option these days is to use the FallbackResource Directive. All you need is

FallbackResource /my_app/index.html

and the appropriate Indexes override which you probably have already.


问:
MSAL Consent Problem in a multi tier app registration (Angular + .NetCore WebApi)
I'm Building an Angular 9 + Asp.Net Core WebApi App using Azure active directory for the authentication in a multitenant context. The WebApi Component have to call some MS Graph Api.
So following the documentation, I created two apps on the portal (one for each component). In the web Api app i did the following operation:

added the authorizazion needed for the graph calls

added the ID of the client app in the knownClientApplications section of the manifest

Defined a scope in the "expose Api" Section

On the client app I added the scope definided at point three below.

On the Angular App I configured as follow the MSal library:

```<code>   MsalModule.forRoot({
        auth: {
          clientId: 'CLIENT APP ID', // This is your client ID
          authority: 'https://login.microsoftonline.com/common', // This is your tenant info
          redirectUri: 'http://localhost:4200' // This is your redirect URI
        },
        cache: {
          cacheLocation: 'localStorage',
          storeAuthStateInCookie: true, // Set to true for Internet Explorer 11
        },
      },
      {
        popUp: true,
        consentScopes: [
          'user.read',
          'openid',
          'profile',
          'api://xxxxxxxxxxxxxxxxxx/.default'
        ],
        unprotectedResources: ['http://localhost:4200'],
        protectedResourceMap: [
          ['https://localhost:44351', ['api://xxxxxxxxxxxxxxx/api_usage']]
        ],
        extraQueryParameters: {}
      })
</code>```

The problem is : When i login, the only consent prompted are like "user read information" and "user save information". The consent for the the web api are not reported, so the web api service principal in the customer tenant for web api is not created, lately the following calls from web api to graph fails for
absence of permits.

For testing purpouse i tried to put other scopes (like calendar.read or place.read in the consentScopes of Msal configuration but the result is the same: the only consent requested is the two above.

Anyone can help me?

答:
The code uses the Implicit grant flow, you could not specify the Microsoft Graph permissions together with your own web api permission in the consentScopes, you could just specify the consentScopes with the permissions of one API.

In your case, it should be like below:

```<code> consentScopes: [
          'api://xxxxxxxxxxxxxxxxxx/.default'
        ]
</code>```

Body:
I'm Building an Angular 9 + Asp.Net Core WebApi App using Azure active directory for the authentication in a multitenant context. The WebApi Component have to call some MS Graph Api.
So following the documentation, I created two apps on the portal (one for each component). In the web Api app i did the following operation:

added the authorizazion needed for the graph calls

added the ID of the client app in the knownClientApplications section of the manifest

Defined a scope in the "expose Api" Section

On the client app I added the scope definided at point three below.

On the Angular App I configured as follow the MSal library:

   MsalModule.forRoot({
        auth: {
          clientId: 'CLIENT APP ID', // This is your client ID
          authority: 'https://login.microsoftonline.com/common', // This is your tenant info
          redirectUri: 'http://localhost:4200' // This is your redirect URI
        },
        cache: {
          cacheLocation: 'localStorage',
          storeAuthStateInCookie: true, // Set to true for Internet Explorer 11
        },
      },
      {
        popUp: true,
        consentScopes: [
          'user.read',
          'openid',
          'profile',
          'api://xxxxxxxxxxxxxxxxxx/.default'
        ],
        unprotectedResources: ['http://localhost:4200'],
        protectedResourceMap: [
          ['https://localhost:44351', ['api://xxxxxxxxxxxxxxx/api_usage']]
        ],
        extraQueryParameters: {}
      })

The problem is : When i login, the only consent prompted are like "user read information" and "user save information". The consent for the the web api are not reported, so the web api service principal in the customer tenant for web api is not created, lately the following calls from web api to graph fails for
absence of permits.

For testing purpouse i tried to put other scopes (like calendar.read or place.read in the consentScopes of Msal configuration but the result is the same: the only consent requested is the two above.

Anyone can help me?

Body:
The code uses the Implicit grant flow, you could not specify the Microsoft Graph permissions together with your own web api permission in the consentScopes, you could just specify the consentScopes with the permissions of one API.

In your case, it should be like below:

 consentScopes: [
          'api://xxxxxxxxxxxxxxxxxx/.default'
        ]


问:
Integrate "Nova Filemanager" with "Nova TinyMCE text editor with images" Package
Is there a way to integrate Nova Filemanager with "Nova TinyMCE text editor with images" package? I have tried to search for a solution for this, but couldn't find any.

In NovaTinyMCE.php config file it uses 'use_lfm' to call UniSharp Laravel Filemanager to upload images. but my setup uses Nova Filemanager to upload images. So the question is is it possible to call nova filemanager instead of laravel filemanager?

Settings in NovaTinyMCE.php:

```<code>$this->withMeta([
            'options' => [
                'content_css' => '/vendor/tinymce/skins/ui/oxide/content.min.css',
                'skin_url' => '/vendor/tinymce/skins/ui/oxide',
                'path_absolute' => '/',
                'plugins' => [
                    'lists preview hr anchor pagebreak image wordcount fullscreen directionality paste textpattern'
                ],
                'toolbar' => 'undo redo | styleselect | bold italic forecolor backcolor | alignleft aligncenter alignright alignjustify | image | bullist numlist outdent indent | link',
                'relative_urls' => false,
                'use_lfm' => true,
                'lfm_url' => 'nova-filemanager'
            ]
        ]);
</code>```

Packages Used:
Tiny MCE: https://novapackages.com/packages/emilianotisato/nova-tinymce

Nova Filemanager: https://novapackages.com/packages/infinety-es/nova-filemanager

答:
I added the following URL into the lfm_url value and set use_lfm to true:

```<code>NovaTinyMCE::make('body')->options([
            'use_lfm' => true,
            'lfm_url' => 'nova/nova-filemanager'
        ]),
</code>```

This does work and pops up with the full admin interface where you can select the URL for the image to insert into the inoutbox, it's not ideal but it works.

For more information, read https://novapackages.com/packages/emilianotisato/nova-tinymce

Body:
Is there a way to integrate Nova Filemanager with "Nova TinyMCE text editor with images" package? I have tried to search for a solution for this, but couldn't find any.

In NovaTinyMCE.php config file it uses 'use_lfm' to call UniSharp Laravel Filemanager to upload images. but my setup uses Nova Filemanager to upload images. So the question is is it possible to call nova filemanager instead of laravel filemanager?

Settings in NovaTinyMCE.php:

$this->withMeta([
            'options' => [
                'content_css' => '/vendor/tinymce/skins/ui/oxide/content.min.css',
                'skin_url' => '/vendor/tinymce/skins/ui/oxide',
                'path_absolute' => '/',
                'plugins' => [
                    'lists preview hr anchor pagebreak image wordcount fullscreen directionality paste textpattern'
                ],
                'toolbar' => 'undo redo | styleselect | bold italic forecolor backcolor | alignleft aligncenter alignright alignjustify | image | bullist numlist outdent indent | link',
                'relative_urls' => false,
                'use_lfm' => true,
                'lfm_url' => 'nova-filemanager'
            ]
        ]);

Packages Used:
Tiny MCE: https://novapackages.com/packages/emilianotisato/nova-tinymce

Nova Filemanager: https://novapackages.com/packages/infinety-es/nova-filemanager

Body:
I added the following URL into the lfm_url value and set use_lfm to true:

NovaTinyMCE::make('body')->options([
            'use_lfm' => true,
            'lfm_url' => 'nova/nova-filemanager'
        ]),

This does work and pops up with the full admin interface where you can select the URL for the image to insert into the inoutbox, it's not ideal but it works.

For more information, read https://novapackages.com/packages/emilianotisato/nova-tinymce


问:
python3 sockets never stops trying to read data
i'm using a tcp socket to read data from a website, HTTP requests to be exact. I want to use sockets and not requests or pycurl so please do not suggest me any higher level library.

```<code>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = wrap_socket(s)
response_bytes = b""
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
s.connect((website))
s.send(all of this works good)
#this is where my problems occur
while True:
    response_bytes+=s.recv(4096)
    if not response_bytes: break

</code>```

this solution should work perfectly according to multiple stack posts. I want to use the most efficient way without a timeout. If i use try/except and set a socket timeout it works fine but thats  not very good imo. This seems to make the code hang forever and make it try to read infinitely. Is there any reason it is doing this?

答:
this solution should work perfectly according to multiple stack posts

No, you missed an important detail.

while True:
    response_bytes+=s.recv(4096)
    if not response_bytes: break
```

<p>If <code>response_bytes</code> is ever non-empty then it stays non-empty, and this becomes an infinite loop. Instead, do something like</p>

<pre class="lang-py prettyprint-override"><code>while True:
    buf = s.recv(2048)
    if not buf:
        break
    response_bytes+=buf
</code>```

Body:
i'm using a tcp socket to read data from a website, HTTP requests to be exact. I want to use sockets and not requests or pycurl so please do not suggest me any higher level library.

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = wrap_socket(s)
response_bytes = b""
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
s.connect((website))
s.send(all of this works good)
#this is where my problems occur
while True:
    response_bytes+=s.recv(4096)
    if not response_bytes: break

this solution should work perfectly according to multiple stack posts. I want to use the most efficient way without a timeout. If i use try/except and set a socket timeout it works fine but thats  not very good imo. This seems to make the code hang forever and make it try to read infinitely. Is there any reason it is doing this?

Body:
this solution should work perfectly according to multiple stack posts

No, you missed an important detail.

while True:
    response_bytes+=s.recv(4096)
    if not response_bytes: break

If response_bytes is ever non-empty then it stays non-empty, and this becomes an infinite loop. Instead, do something like

while True:
    buf = s.recv(2048)
    if not buf:
        break
    response_bytes+=buf


问:
Haskell: why is usleep + threaded compile option more precise than threadDelay?
I wrote a test program in Haskell on the Raspberry Pi that plays a delightful tune
on a buzzer connected to a GPIO pin.

Here are the imports I used:

```<code>import qualified Control.Concurrent as C
import qualified Control.Monad as M
import System.IO
import qualified System.Posix.Unistd as P
</code>```

Here are the functions that toggle the pin by writing to
the  /sys/class/gpio/gpio16/value  file:

```<code>changePin2 :: Handle -> String -> Int -> IO ()
changePin2 handle onOff delay = do
  pos <- hGetPosn handle
  hPutStr handle (onOff ++ "\n")
  hFlush handle
  hSetPosn pos
  P.usleep delay
  --C.threadDelay delay

blinkOn2 :: Handle -> Int -> IO ()
blinkOn2 handle delay = do
  changePin2 handle "1" delay
  changePin2 handle "0" delay
</code>```

finally, here is an example of playing one note with a pause before the next one:

```<code>  mapM_ (blinkOn2 h) (replicate 26 1908)
  P.usleep 50000
  -- C.threadDelay 50000
</code>```

When I first tried it, I used threadDelay and it sounded terrible. It was low pitched,
suggesting the delay was longer than expected and all notes sounded more or less the same.
Using the usleep function improved things considerably.
Finally, adding the -threaded option when compiling with ghc made the sound even cleaner.

```<code>ghc -threaded buzzer1t.hs
</code>```

I do not understand why either of these improved it and if anyone knows it would help greatly.

googling seems to reveal that usleep and friends are delays at the OS level whereas threadDelay
only pertains to the thread in the Haskell program itself. threadDelay also seems like the
more recommended one and considered better practice even though in this case usleep is clearly
superior.

答:
I think the documentation is a good start here:

GHC Note: threadDelay is a better choice. Without the -threaded option, usleep will block all other user threads. Even with the -threaded option, usleep requires a full OS thread to itself. threadDelay has neither of these shortcomings.

To expand a bit further:  The GHC runtime multiplexes user threads over system threads.  The default runtime uses only a single OS thread, regardless of how many user threads there are.  Most blocking calls to external code are written such that they deschedule the current Haskell user thread while they're in external code, which is allowed to execute concurrently with Haskell code.  This means that even the default runtime with a single OS thread can handle multiple user threads doing IO simultaneously, for instance.

In this world, actually blocking the OS thread is considered a somewhat hostile activity.  threadDelay just marks the current thread as not runnable until the specified amount of time has expired.  This is much friendlier with the runtime system, as it releases the underlying OS thread.

When you use the threaded runtime, you get multiple OS threads to execute user threads, but it's still somewhat hostile to grab one and not release it.  Among other things, it prevents the garbage collector from running (it waits until it can pause all user threads at known safe points, so it doesn't corrupt memory in use concurrently), and OS threads are significantly more memory-heavy than user threads if you add extras to make up for lost concurrency.

So for most software, threadDelay is a much better citizen.  But it has downsides.  The thread doesn't necessarily resume immediately.  It becomes available to be scheduled at the given time, but that doesn't mean it actually runs.  That still depends on other threads yielding. That's almost certainly the cause of the trouble you were having - the additional delay waiting to go from runnable to actually running.  usleep is around specifically for the cases when that gets in the way.  Seems like a fine reason to use it when needed.

Body:
I wrote a test program in Haskell on the Raspberry Pi that plays a delightful tune
on a buzzer connected to a GPIO pin.

Here are the imports I used:

import qualified Control.Concurrent as C
import qualified Control.Monad as M
import System.IO
import qualified System.Posix.Unistd as P

Here are the functions that toggle the pin by writing to
the  /sys/class/gpio/gpio16/value  file:

changePin2 :: Handle -> String -> Int -> IO ()
changePin2 handle onOff delay = do
  pos <- hGetPosn handle
  hPutStr handle (onOff ++ "\n")
  hFlush handle
  hSetPosn pos
  P.usleep delay
  --C.threadDelay delay

blinkOn2 :: Handle -> Int -> IO ()
blinkOn2 handle delay = do
  changePin2 handle "1" delay
  changePin2 handle "0" delay

finally, here is an example of playing one note with a pause before the next one:

  mapM_ (blinkOn2 h) (replicate 26 1908)
  P.usleep 50000
  -- C.threadDelay 50000

When I first tried it, I used threadDelay and it sounded terrible. It was low pitched,
suggesting the delay was longer than expected and all notes sounded more or less the same.
Using the usleep function improved things considerably.
Finally, adding the -threaded option when compiling with ghc made the sound even cleaner.

ghc -threaded buzzer1t.hs

I do not understand why either of these improved it and if anyone knows it would help greatly.

googling seems to reveal that usleep and friends are delays at the OS level whereas threadDelay
only pertains to the thread in the Haskell program itself. threadDelay also seems like the
more recommended one and considered better practice even though in this case usleep is clearly
superior.


问:
Processing - Is there a way to check where a mouse is being clicked on a generated sphere?
in the development program "Processing" -- Is there a way to check where a mouse is being clicked on a generated sphere?

I've got a map of Earth on a sphere and I want to know where a user clicks on the sphere so I can map it to a city.

Let me know if more information is needed.

答:
You can use dist(), which calculates the distance between 2 2-d positions.

This code should do the trick:

```<code>void setup(){
    size(500, 500);
}

int x = 250;
int y = 250;
int diameter = 100;

void draw(){
    background(200);
    if(dist(mouseX, mouseY, x, y) < diameter / 2) fill(250);
    else fill(0);

    ellipse(x, y, diameter, diameter);
}
</code>```

Body:
You can use dist(), which calculates the distance between 2 2-d positions.

This code should do the trick:

void setup(){
    size(500, 500);
}

int x = 250;
int y = 250;
int diameter = 100;

void draw(){
    background(200);
    if(dist(mouseX, mouseY, x, y) < diameter / 2) fill(250);
    else fill(0);

    ellipse(x, y, diameter, diameter);
}


问:
Linker error encountered upon attempting to use RtlInitUnicodeString()
The function RtlInitUnicodeString() used to initialize the UNICODE_STRING structure cannot be used as a linker error stating that an unresolved external symbol RtlInitUnicodeString referenced in function ***func_name*** (LNK2019) is thrown during compilation.

I tried using the statement #pragma comment(lib, "NtosKrnl.lib") to solve the issue at hand (as I assumed that linking the library mentioned here would resolve it) but a linker error stating the message cannot open file 'ntoskrnl.lib' (LNK1104) is thrown.

Thanks in advance.

答: The function cannot be called directly as they belong to the internal API and their mere prototype header is exposed via the winternl.h header file (at least in this case). In order to use the functions that are part of the internal API, one can either use run-time dynamic linking to link the Ntdll.dll library as stated here or link the library file ntdll.lib, which is a provided as a part of the WDK.


问:
How to create two consecutive Group By in SQL
I have this kind of code

```<code>SELECT MONTH(date_entered) AS Month,sex, COUNT(*) AS Customer
  FROM customer
GROUP BY month
ORDER BY Month
</code>```

I want to split sex (M and F) for each month. But the result that I get combine both sex

答:
You need to include sex in group by as well

```<code>SELECT
    MONTH(date_entered) AS Month,
    sex,
    COUNT(*) AS Customer
FROM customer
GROUP BY
    MONTH(date_entered),
    sex
ORDER BY
    Month
</code>```

Body:
I have this kind of code

SELECT MONTH(date_entered) AS Month,sex, COUNT(*) AS Customer
  FROM customer
GROUP BY month
ORDER BY Month

I want to split sex (M and F) for each month. But the result that I get combine both sex

Body:
You need to include sex in group by as well

SELECT
    MONTH(date_entered) AS Month,
    sex,
    COUNT(*) AS Customer
FROM customer
GROUP BY
    MONTH(date_entered),
    sex
ORDER BY
    Month


问:
Error 400 Bad request when getting Open Weather API (geolocation)
I want to get the weather API to display the current location but it gives back an 400 error. I don't know how to fix it.
(I open my api on browser and its works fine. But when I put it in the code bellow, it's gave error)</p>

```<code>state: {
        weather:{},
        api_key: 'c9f562aaffcdefaf40f2ed808d202c9b',
        url_base: 'https://api.openweathermap.org/data/2.5/',
        query: '',
        icons: {
            'Rain': require('../assets/regnerisch.png'),
            'Clear': require('../assets/sonne.png'),
            'Clouds': require('../assets/wolkig.png'),
            'Snow': require('../assets/schnee.png'),
            'Drizzle':require('../assets/regnerisch.png'),
            'Thunderstorm':require('../assets/regnerisch.png')
        },
    },

 actions:{
         currentCity({commit}) {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(position => {
                axios
                .get(`${this.url_base}weather?&lat=${position.coords.latitude}&lon=${position.coords.longitude}&units=metric&APPID=${this.api_key}`)
                .then(res=>res.data)
                .then(weather=>{
                    commit('currentCity',weather)
                })
            })
        }
    }
},
     mutations:{
         currentCity (state, weather){
             state.weather = weather
         }
     }
</code>```

答:
400 error means your request was malformed. Since all of your payload data is storedas a query string I assume your url is wrong, Is this part below meant to be backticked?
${this.url_base}weather?&lat=${position.coords.latitude}&lon=${position.coords.longitude}&units=metric&APPID=${this.api_key}? Is yes then consider logging the variables to make sure you're getting valid input to the query string

Body:
I want to get the weather API to display the current location but it gives back an 400 error. I don't know how to fix it.
(I open my api on browser and its works fine. But when I put it in the code bellow, it's gave error)

state: {
        weather:{},
        api_key: 'c9f562aaffcdefaf40f2ed808d202c9b',
        url_base: 'https://api.openweathermap.org/data/2.5/',
        query: '',
        icons: {
            'Rain': require('../assets/regnerisch.png'),
            'Clear': require('../assets/sonne.png'),
            'Clouds': require('../assets/wolkig.png'),
            'Snow': require('../assets/schnee.png'),
            'Drizzle':require('../assets/regnerisch.png'),
            'Thunderstorm':require('../assets/regnerisch.png')
        },
    },

 actions:{
         currentCity({commit}) {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(position => {
                axios
                .get(`${this.url_base}weather?&lat=${position.coords.latitude}&lon=${position.coords.longitude}&units=metric&APPID=${this.api_key}`)
                .then(res=>res.data)
                .then(weather=>{
                    commit('currentCity',weather)
                })
            })
        }
    }
},
     mutations:{
         currentCity (state, weather){
             state.weather = weather
         }
     }


问:
Skip_elements() function using enumerate() function
Try out the enumerate function for yourself in this quick exercise. Complete the skip_elements function to return every other element from the list, this time using the enumerate function to check if an element is on an even position or an odd position.

```<code>def skip_elements(elements):
# code goes here

return ___

print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
</code>```

I have no idea how to use enumerate for this. Please help.

答:
```<code>def skip_elements(elements):
    elements = [v for i, v in enumerate(elements) if i % 2 == 0]

    return elements
</code>```

Body:
Try out the enumerate function for yourself in this quick exercise. Complete the skip_elements function to return every other element from the list, this time using the enumerate function to check if an element is on an even position or an odd position.

def skip_elements(elements):
# code goes here

return ___

print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']

I have no idea how to use enumerate for this. Please help.


问:
Hashing Plaid Request Body Webhook
I am trying to verify a webhook sent from Plaid's API. Every webhook request is sent with a 'plaid-verification' header which is a JSON Web Token.

The steps required to validate are:

Extract JWT from request header

signed_jwt = eyJhbGciOiJFUzI1NiIsImtpZCI6IjZjNTUxNmUxLTkyZGMtNDc5ZS1hOGZmLTVhNTE5OTJlMDAwMSIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1OTA4ODcwMDEsInJlcXVlc3RfYm9keV9zaGEyNTYiOiJiNjNhMDdiNTQ3YjAwZjk5MjU0N2Y2YmJjOGQ5YWNjNjFhOGNjZWUxMzhiYzgyZjQ0YTZiYWEwOTY4M2E1ZDBmIn0.OOKvIihgqCj7Qrb2bmz7T3t7uK-0JyjiEqL2s1kWeJBM4MMmjaHKK8GmU_z91QolBWMzvPgs718EElY-rE3cwQ

Extract JWT header value without validating the signature, which looks like this:

```<code>    {
      "alg": "ES256",
      "kid": "6c5516e1-92dc-479e-a8ff-5a51992e0001",
      "typ": "JWT"
    }
</code>```

Extract the kid and POST to /webhook_verification_key/get

```<code>    POST /webhook_verification_key/get
    {
        "client_id": "MY_CLIENT_ID"
        "secret": "MY_SECRET_ID"
        "key_id": "6c5516e1-92dc-479e-a8ff-5a51992e0001"
    }
</code>```

The response is:

```<code>{
  "key": {
    "alg": "ES256",
    "created_at": 1560466143,
    "crv": "P-256",
    "expired_at": null,
    "kid": "6c5516e1-92dc-479e-a8ff-5a51992e0001",
    "kty": "EC",
    "use": "sig",
    "x": "35lvC8uz2QrWpQJ3TUH8t9o9DURMp7ydU518RKDl20k",
    "y": "I8BuXB2bvxelzJAd7OKhd-ZwjCst05Fx47Mb_0ugros"
  },
  "request_id": "HvfCtrDLG1ihcp7"
}
</code>```

Interpret key as a JSON Web Key, validate that the signature of the JSON Web Key is valid, and extract the payload (using jose python library)

```<code>claims = jwt.decode(signed_jwt, key, algorithms=['ES256'])

claims = {
             "iat": 1590887001,
             "request_body_sha256": "b63a07b547b00f992547f6bbc8d9acc61a8ccee138bc82f44a6baa09683a5d0f"
         }
</code>```

Compute the SHA-256 of the request body and ensure that it matches claims['request_body_sha256']:

Body is in a file body.json

```<code>{
    "error": null,
    "item_id": "yxQbxDjnD8hr69pKbQpbcKeVn3GL9QuyA7NV3",
    "new_transactions": 390,
    "webhook_code": "HISTORICAL_UPDATE",
    "webhook_type": "TRANSACTIONS"
}
</code>```

Compute SHA-256 of body.json

```<code>f = open('body.json')
body = json.load(f)
f.close()

m = hashlib.sha256()
m.update(json.dumps(body).encode())
body_hash = m.hexdigest()
print(body_hash)

body_hash = 'efbb5274864518f7eb3834125d9bcdb95fb03066d3d1bed3ebcc6163d8dc3579'
</code>```

The body hash in the example above does not equal the body hash received from Plaid. There's 2 possible problems here:

Plaid isn't sending the correct body hash (unlikely)

The hash method I'm using to hash the body is not the same as Plaid's method

Is there something I'm missing here? Perhaps the request body is encoded differently on my end? I'm using Node.js and Express in production but I made a Python script to follow the method Plaid outlined here, but I'm still not getting the correct hash. I'm honestly out of ideas.

答: It seems to be a problem with whitespace.  If you modify body.json to have 2 spaces per ‘tab’ on each new line, it will generate the right hash.</p>

Title: Hashing Plaid Request Body Webhook

Body:
I am trying to verify a webhook sent from Plaid's API. Every webhook request is sent with a 'plaid-verification' header which is a JSON Web Token.

The steps required to validate are:

Extract JWT from request header

signed_jwt = eyJhbGciOiJFUzI1NiIsImtpZCI6IjZjNTUxNmUxLTkyZGMtNDc5ZS1hOGZmLTVhNTE5OTJlMDAwMSIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1OTA4ODcwMDEsInJlcXVlc3RfYm9keV9zaGEyNTYiOiJiNjNhMDdiNTQ3YjAwZjk5MjU0N2Y2YmJjOGQ5YWNjNjFhOGNjZWUxMzhiYzgyZjQ0YTZiYWEwOTY4M2E1ZDBmIn0.OOKvIihgqCj7Qrb2bmz7T3t7uK-0JyjiEqL2s1kWeJBM4MMmjaHKK8GmU_z91QolBWMzvPgs718EElY-rE3cwQ

Extract JWT header value without validating the signature, which looks like this:

    {
      "alg": "ES256",
      "kid": "6c5516e1-92dc-479e-a8ff-5a51992e0001",
      "typ": "JWT"
    }

Extract the kid and POST to /webhook_verification_key/get

    POST /webhook_verification_key/get
    {
        "client_id": "MY_CLIENT_ID"
        "secret": "MY_SECRET_ID"
        "key_id": "6c5516e1-92dc-479e-a8ff-5a51992e0001"
    }

The response is:

{
  "key": {
    "alg": "ES256",
    "created_at": 1560466143,
    "crv": "P-256",
    "expired_at": null,
    "kid": "6c5516e1-92dc-479e-a8ff-5a51992e0001",
    "kty": "EC",
    "use": "sig",
    "x": "35lvC8uz2QrWpQJ3TUH8t9o9DURMp7ydU518RKDl20k",
    "y": "I8BuXB2bvxelzJAd7OKhd-ZwjCst05Fx47Mb_0ugros"
  },
  "request_id": "HvfCtrDLG1ihcp7"
}

Interpret key as a JSON Web Key, validate that the signature of the JSON Web Key is valid, and extract the payload (using jose python library)

claims = jwt.decode(signed_jwt, key, algorithms=['ES256'])

claims = {
             "iat": 1590887001,
             "request_body_sha256": "b63a07b547b00f992547f6bbc8d9acc61a8ccee138bc82f44a6baa09683a5d0f"
         }

Compute the SHA-256 of the request body and ensure that it matches claims['request_body_sha256']:

Body is in a file body.json

{
    "error": null,
    "item_id": "yxQbxDjnD8hr69pKbQpbcKeVn3GL9QuyA7NV3",
    "new_transactions": 390,
    "webhook_code": "HISTORICAL_UPDATE",
    "webhook_type": "TRANSACTIONS"
}

Compute SHA-256 of body.json

f = open('body.json')
body = json.load(f)
f.close()

m = hashlib.sha256()
m.update(json.dumps(body).encode())
body_hash = m.hexdigest()
print(body_hash)

body_hash = 'efbb5274864518f7eb3834125d9bcdb95fb03066d3d1bed3ebcc6163d8dc3579'

The body hash in the example above does not equal the body hash received from Plaid. There's 2 possible problems here:

Plaid isn't sending the correct body hash (unlikely)

The hash method I'm using to hash the body is not the same as Plaid's method

Is there something I'm missing here? Perhaps the request body is encoded differently on my end? I'm using Node.js and Express in production but I made a Python script to follow the method Plaid outlined here, but I'm still not getting the correct hash. I'm honestly out of ideas.


问:
Given using C++ or C, how could I measure how long it takes to do a thread switch under linux?Is it possible?
Given using C++ or C, how could I measure how long it takes to do a thread switch under linux?Is it possible? At most platform, how long does it takes?Could anybody give me some typical value?

I don't wanna to measure thread quantum indeed. I hope to find a practical method to measure the duration of swithing a thread to another(not how long a thread could run).

I would appreciate that if you could provide the code.

I would be grateful for any hint on this question.

答:
See you again :)

It is possible, but you need to do a little change about kernel code. So openwrt or something else may be good for you.

You can see my blog and the source code to solve the problem. The preemption schedule will do the time check, and it is like below

```<code>/*
 * Preempt the current task with a newly woken task if needed:
 */
static void
check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
{
    unsigned long ideal_runtime, delta_exec;
    struct sched_entity *se;
    s64 delta;
    ideal_runtime = sched_slice(cfs_rq, curr);
    delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
    if (delta_exec > ideal_runtime) {
        resched_curr(rq_of(cfs_rq));
        /*
         * The current task ran long enough, ensure it doesn't get
         * re-elected due to buddy favours.
         */
        clear_buddies(cfs_rq, curr);
        return;
    }
    /*
     * Ensure that a task that missed wakeup preemption by a
     * narrow margin doesn't have to wait for a full slice.
     * This also mitigates buddy induced latencies under load.
     */
    if (delta_exec < sysctl_sched_min_granularity)
        return;
    se = __pick_first_entity(cfs_rq);
    delta = curr->vruntime - se->vruntime;
    if (delta < 0)
        return;
    if (delta > ideal_runtime)
        resched_curr(rq_of(cfs_rq));
}
</code>```

Here we have several time helpful for you

ideal_runtime : the time this task run in this schedule period

sum_exec_runtime : total time the task run

prev_sum_exec_runtime : history total time

Body:
See you again :)

It is possible, but you need to do a little change about kernel code. So openwrt or something else may be good for you.

You can see my blog and the source code to solve the problem. The preemption schedule will do the time check, and it is like below

/*
 * Preempt the current task with a newly woken task if needed:
 */
static void
check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
{
    unsigned long ideal_runtime, delta_exec;
    struct sched_entity *se;
    s64 delta;
    ideal_runtime = sched_slice(cfs_rq, curr);
    delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
    if (delta_exec > ideal_runtime) {
        resched_curr(rq_of(cfs_rq));
        /*
         * The current task ran long enough, ensure it doesn't get
         * re-elected due to buddy favours.
         */
        clear_buddies(cfs_rq, curr);
        return;
    }
    /*
     * Ensure that a task that missed wakeup preemption by a
     * narrow margin doesn't have to wait for a full slice.
     * This also mitigates buddy induced latencies under load.
     */
    if (delta_exec < sysctl_sched_min_granularity)
        return;
    se = __pick_first_entity(cfs_rq);
    delta = curr->vruntime - se->vruntime;
    if (delta < 0)
        return;
    if (delta > ideal_runtime)
        resched_curr(rq_of(cfs_rq));
}

Here we have several time helpful for you

ideal_runtime : the time this task run in this schedule period

sum_exec_runtime : total time the task run

prev_sum_exec_runtime : history total time


问:
Fast tcp server availability check
I want to make an Unity3D app that has a tcp/ip client. It should check regularly if there is an available server, and if there is one, tries to connect to it. I tried this as following

```<code>            _client = new TcpClient(_tcpAddress, _tcpPort);
            if (!_client.Connected)
            {
                return false;
            }
</code>```

But every time it calls the constructor, it lags badly. Is there any faster method that checks if there is a server at the specified port?

答:
Looking at the specific constructor you're using it states (emphasis mine):

This constructor creates a new TcpClient and makes a synchronous connection attempt to the provided host name and port number. The underlying service provider will assign the most appropriate local IP address and port number. TcpClient will block until it either connects or fails. This constructor allows you to initialize, resolve the DNS host name, and connect in one convenient step.

Your code isn't "lagging", it's actively waiting for the connection to succeed or fail.

I would suggest instead using the default constructor and either call the BeginConnect and corresponding EndConnect methods, or if you can use the async/await pattern in Unity, perhaps try using ConnectAsync.

Although in Unity, I think a simpler method might be to just use a coroutine (I'm not a Unity programmer so this might not be 100% right):

```<code>StartCoroutine(TestConnectionMethod());

private IEnumerator TestConnectionMethod()
{
     _client = new TcpClient(_tcpAddress, _tcpPort);
     yield return _client.Connected;
}
</code>```

Title: Fast tcp server availability check

Body:
I want to make an Unity3D app that has a tcp/ip client. It should check regularly if there is an available server, and if there is one, tries to connect to it. I tried this as following

            _client = new TcpClient(_tcpAddress, _tcpPort);
            if (!_client.Connected)
            {
                return false;
            }

But every time it calls the constructor, it lags badly. Is there any faster method that checks if there is a server at the specified port?

Body:
Looking at the specific constructor you're using it states (emphasis mine):

This constructor creates a new TcpClient and makes a synchronous connection attempt to the provided host name and port number. The underlying service provider will assign the most appropriate local IP address and port number. TcpClient will block until it either connects or fails. This constructor allows you to initialize, resolve the DNS host name, and connect in one convenient step.

Your code isn't "lagging", it's actively waiting for the connection to succeed or fail.

I would suggest instead using the default constructor and either call the BeginConnect and corresponding EndConnect methods, or if you can use the async/await pattern in Unity, perhaps try using ConnectAsync.

Although in Unity, I think a simpler method might be to just use a coroutine (I'm not a Unity programmer so this might not be 100% right):

StartCoroutine(TestConnectionMethod());

private IEnumerator TestConnectionMethod()
{
     _client = new TcpClient(_tcpAddress, _tcpPort);
     yield return _client.Connected;
}


问:
How to make a dot product in a vector of matrices in numpy?
I have

```<code>a = np.ones((10, 4, 3))
b = np.ones((10, 3, 5))
</code>```

and I want

```<code>c = np.dot(a, b, axis=0)
assert c.shape == (10, 4, 5)
</code>```

How do I do this?

答:
As I understand it, there are 10 matrices in a of shape 4 x 3 and 10 in b of shape 3 x 5, and you wish to (matrix-)multiply corresponding matrices in the two sets.

As already mentioned, np.matmul(a, b) or a @ b achieves this purpose. If the operation is unclear, however, it is interesting to look at an explicit way of achieving what you want using np.einsum, which explicitly specifies indices as in mathematics:

```<code>np.einsum('ijl,ilk->ijk', a, b)
</code>```

In the string in the first argument, left-hand side specifies the indices of the input matrices and the right-hand side the output indices. Read the docs to understand it better.

Just to check that the results are the same:

```<code>>>> np.allclose(np.einsum('ijl,ilk->ijk', a, b), a @ b)

True
</code>```

But einsum takes some more time, so for such simple usages, it's wise to resort to @:

```<code>>>> %timeit np.einsum('ijl,ilk->ijk', a, b)
    %timeit a @ b

14.2 µs ± 176 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
2.73 µs ± 22.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

Hope this helps!

Body:
I have

a = np.ones((10, 4, 3))
b = np.ones((10, 3, 5))

and I want

c = np.dot(a, b, axis=0)
assert c.shape == (10, 4, 5)

How do I do this?

Body:
As I understand it, there are 10 matrices in a of shape 4 x 3 and 10 in b of shape 3 x 5, and you wish to (matrix-)multiply corresponding matrices in the two sets.

As already mentioned, np.matmul(a, b) or a @ b achieves this purpose. If the operation is unclear, however, it is interesting to look at an explicit way of achieving what you want using np.einsum, which explicitly specifies indices as in mathematics:

np.einsum('ijl,ilk->ijk', a, b)

In the string in the first argument, left-hand side specifies the indices of the input matrices and the right-hand side the output indices. Read the docs to understand it better.

Just to check that the results are the same:

>>> np.allclose(np.einsum('ijl,ilk->ijk', a, b), a @ b)

True

But einsum takes some more time, so for such simple usages, it's wise to resort to @:

>>> %timeit np.einsum('ijl,ilk->ijk', a, b)
    %timeit a @ b

14.2 µs ± 176 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
2.73 µs ± 22.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Hope this helps!


问:
My transparency for my button isn't working. I am also trying to add a border
button_border.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke android:width="3dp"
        android:color="@color/white" />
    <corners android:radius="3dp" />
    <stroke android:width="5px" android:color="#00000000" />
</shape>
</code>```

My button

```<code><Button
    android:id="@+id/button_one"
    android:layout_width="356dp"
    android:layout_height="251dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="96dp"
    android:background="@drawable/button_border"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</code>```

答:
Add android:alpha="0.50" in your  layout xml and try it out.
or
also try it out : android:background="@android:color/transparent"

See this link for better understanding: http://developer.android.com/guide/topics/resources/drawable-resource.html for border related issues.

Body:
button_border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke android:width="3dp"
        android:color="@color/white" />
    <corners android:radius="3dp" />
    <stroke android:width="5px" android:color="#00000000" />
</shape>

My button

<Button
    android:id="@+id/button_one"
    android:layout_width="356dp"
    android:layout_height="251dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="96dp"
    android:background="@drawable/button_border"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />


问:
How can I find the current DNS server?
I'm using Delphi and need to get the current Windows DNS server IP address so I can do a lookup. What function should I call to find it? The only solution I have right now does an ipconfig/all to get it, which is horrible.</p>

答:
Do you really need to know what is DNS server to do a lookup? </p>

<p>Here is a solution how to get a IP address using 2 functions: GetHostName and GetHostByName. I assume the GetHostByName function does the lookup you need for you, or am I wrong? </p>

ContentLicense: CC BY-SA 2.5

Title: How can I find the current DNS server?

LastEditorDisplayName: Nick Berardi

Body:
Do you really need to know what is DNS server to do a lookup?

Here is a solution how to get a IP address using 2 functions: GetHostName and GetHostByName. I assume the GetHostByName function does the lookup you need for you, or am I wrong?

OwnerDisplayName: Pawel


问:
Using jQuery UI to style a div
I have the jQuery UI "smoothness" theme and I would like to use the "look" to style divs on my page.  E.g. apply the gray, shaded, rounded-corner effect to a regular div that ISN'T an accordion, button, etc.

I thought it would be easy! Perhaps it is?!

Thanks!

答:
Have a look at jQuery UI themeroller. You can select an existing theme or customize one, then using Chrome or Firefox/Firebug, for example, Right-click → Inspect element and copy the class names.

ui-widget, ui-widget-content and ui-corner-all are the most likely class names you will be looking for.

Title: Using jQuery UI to style a div


问:
Node.js express: trying to get text from HTML form, req.body empty
I'm trying to build a basic text to speech form, but I cannot grab the text from the form.
I'm trying to get text from an HTML form using an express server and req.body turns up empty every time. I've tried using body-parser and changing the enctype on the form, nothing seems to work.

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>index.html</title>
  </head>
  <body>

    <h1>Speech!!</h1>
    <main>
        <form action="/speak" method="POST" id="speak-form" enctype="multipart/form-data">
            <div id="text-container">
                <label for="text-box">Text to Speech!</label>
                <input type="text" id="text-box" title="text" placeholder="Type what you want to say here!"/>
            </div>
            <div class="button-container">
                <button type="submit" id="submit-button">Speak!</button>
            </div>
            <div class="button-container">
                <button type="reset" id="clear-form">Clear Text</button>
            </div>
        </form>
    </main>
  </body>
</html>
</code>```

app.js

```<code>    const express = require("express");
    const bodyParser = require('body-parser');
    const app = express();
    const configRoutes = require("./routes");

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

    configRoutes(app);

    app.listen(3000, () => {
      console.log("Speech Server");
    });
</code>```

index.js

```<code>const express = require("express");
const speakRoutes = require("./speak");

const constructorMethod = (app) => {
    app.use("/speak",speakRoutes);

    app.use("*", (req,res) => {
        res.sendFile("index.html", { root: "./public" });
    });
};

module.exports = constructorMethod;
</code>```

speak.js

```<code>const express = require("express");
const router = express.Router();

router.post("/", async (req,res) => {
    console.log("POST");
    console.log(req.body);
    res.sendFile("index.html", { root: "./public" });
});

module.exports = router;
</code>```

I would greatly appreciate some help! Thank you!

答:
Your input has no name, give your input a name so you know what property to look for in the form:

```<code><input type="text" id="text-box" name="whatever" ... />
</code>```

EDIT: A client-only example. One field has a name.

$('form').on('submit', function(e) {
  e.preventDefault();
  console.log($(e.currentTarget).serialize());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <h1>Speech!!</h1>
    <main>
        <form action="/speak" method="POST" id="speak-form" enctype="multipart/form-data">
            <div id="text-container">
                <label for="text-box">Text to Speech!</label>
                <input type="text" id="text-box" title="text" placeholder="Type what you want to say here!" name="whatever" />
                <input type="text" id="text-box" title="text" placeholder="I have no name so I won't be sent!" />
            </div>
            <div class="button-container">
                <button type="submit" id="submit-button">Speak!</button>
            </div>
            <div class="button-container">
                <button type="reset" id="clear-form">Clear Text</button>
            </div>
        </form>
    </main></code>```

Body:
I'm trying to build a basic text to speech form, but I cannot grab the text from the form.
I'm trying to get text from an HTML form using an express server and req.body turns up empty every time. I've tried using body-parser and changing the enctype on the form, nothing seems to work.

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>index.html</title>

Speech!!

        <form action="/speak" method="POST" id="speak-form" enctype="multipart/form-data">

                Text to Speech!
                <input type="text" id="text-box" title="text" placeholder="Type what you want to say here!"/>

                <button type="submit" id="submit-button">Speak!</button>

                <button type="reset" id="clear-form">Clear Text</button>

        </form>

app.js

    const express = require("express");
    const bodyParser = require('body-parser');
    const app = express();
    const configRoutes = require("./routes");

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

    configRoutes(app);

    app.listen(3000, () => {
      console.log("Speech Server");
    });

index.js

const express = require("express");
const speakRoutes = require("./speak");

const constructorMethod = (app) => {
    app.use("/speak",speakRoutes);

    app.use("*", (req,res) => {
        res.sendFile("index.html", { root: "./public" });
    });
};

module.exports = constructorMethod;

speak.js

const express = require("express");
const router = express.Router();

router.post("/", async (req,res) => {
    console.log("POST");
    console.log(req.body);
    res.sendFile("index.html", { root: "./public" });
});

module.exports = router;

I would greatly appreciate some help! Thank you!

Body:
Your input has no name, give your input a name so you know what property to look for in the form:

<input type="text" id="text-box" name="whatever" ... />

EDIT: A client-only example. One field has a name.

$('form').on('submit', function(e) {
  e.preventDefault();
  console.log($(e.currentTarget).serialize());
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <h1>Speech!!</h1>
    <main>
        <form action="/speak" method="POST" id="speak-form" enctype="multipart/form-data">
            <div id="text-container">
                <label for="text-box">Text to Speech!</label>
                <input type="text" id="text-box" title="text" placeholder="Type what you want to say here!" name="whatever" />
                <input type="text" id="text-box" title="text" placeholder="I have no name so I won't be sent!" />
            </div>
            <div class="button-container">
                <button type="submit" id="submit-button">Speak!</button>
            </div>
            <div class="button-container">
                <button type="reset" id="clear-form">Clear Text</button>
            </div>
        </form>
    </main>


问:
problems Setting a interval or timeout on my function
I have a system that checks a database to see if their UserToken is in the database, If it's not it will stop the bot and display an error message, I'm trying to make the bot repeat the same function every minute to see if my database has been updated. Here is the code I'm using:

setInterval(() => {
  const getToken = dtoken => new Promise((resolve, reject) => {
    MongoClient.connect(url, {
      useUnifiedTopology: true,
    }, function(err, db) {
      if (err) {
        reject(err);
      } else {
        let dbo = db.db("heroku_fkcv4mqk");
        let query = {
          dtoken: dtoken
        };
        dbo.collection("tokens").find(query).toArray(function(err, result) {
          resolve(result);
        });
      }
    })
  })

  bot.on("ready", async message => {

    const result = await getToken(dtoken)
    if (result.length == 1) {
      return
    } else {
      console.error('Error:', 'Your token has been revoked.')
      bot.destroy()
    }
  })

}, 5000);
```

<p>But it doesn't work and I keep getting this error message:</p>

<pre class="lang-none prettyprint-override"><code>(node:9808) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 ready listeners added to [Client]. Use emitter.setMaxListeners() to increase limit
</code>```

if I could get some help with the timeout that would be amazing.

答:
Bot object listens to the event ready on each execution in setInterval(). So after every 5 seconds, a new listener is being added on bot object which you have never removed. That's why it is throwing an error that the maximum limit has been reached.

I think you can take the listener out of the setInterval. It will work.

Updated Code:::

```<code>let isReady = false;
bot.on("ready", () => {
  isReady = true;
});

const getToken = dtoken => new Promise((resolve, reject) => {
  MongoClient.connect(url, {
    useUnifiedTopology: true,
  }, function(err, db) {
    if (err) {
      reject(err);
    } else {
      let dbo = db.db("heroku_fkcv4mqk");
      let query = {
        dtoken: dtoken
      };
      dbo.collection("tokens").find(query).toArray(function(err, result) {
        resolve(result);
      });
    }
  })
})

setInterval(() => {
  if (isReady) {
    const result = await getToken(dtoken)
    if (result.length == 1) {
      return
    } else {
      console.error('Error:', 'Your token has been revoked.')
      isReady = false
      bot.destroy()
    }
  }
}, 5000);
</code>```

Body:
I have a system that checks a database to see if their UserToken is in the database, If it's not it will stop the bot and display an error message, I'm trying to make the bot repeat the same function every minute to see if my database has been updated. Here is the code I'm using:

setInterval(() => {
  const getToken = dtoken => new Promise((resolve, reject) => {
    MongoClient.connect(url, {
      useUnifiedTopology: true,
    }, function(err, db) {
      if (err) {
        reject(err);
      } else {
        let dbo = db.db("heroku_fkcv4mqk");
        let query = {
          dtoken: dtoken
        };
        dbo.collection("tokens").find(query).toArray(function(err, result) {
          resolve(result);
        });
      }
    })
  })

  bot.on("ready", async message => {

    const result = await getToken(dtoken)
    if (result.length == 1) {
      return
    } else {
      console.error('Error:', 'Your token has been revoked.')
      bot.destroy()
    }
  })

}, 5000);

But it doesn't work and I keep getting this error message:

(node:9808) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 ready listeners added to [Client]. Use emitter.setMaxListeners() to increase limit

if I could get some help with the timeout that would be amazing.

Body:
Bot object listens to the event ready on each execution in setInterval(). So after every 5 seconds, a new listener is being added on bot object which you have never removed. That's why it is throwing an error that the maximum limit has been reached.

I think you can take the listener out of the setInterval. It will work.

Updated Code:::

let isReady = false;
bot.on("ready", () => {
  isReady = true;
});

const getToken = dtoken => new Promise((resolve, reject) => {
  MongoClient.connect(url, {
    useUnifiedTopology: true,
  }, function(err, db) {
    if (err) {
      reject(err);
    } else {
      let dbo = db.db("heroku_fkcv4mqk");
      let query = {
        dtoken: dtoken
      };
      dbo.collection("tokens").find(query).toArray(function(err, result) {
        resolve(result);
      });
    }
  })
})

setInterval(() => {
  if (isReady) {
    const result = await getToken(dtoken)
    if (result.length == 1) {
      return
    } else {
      console.error('Error:', 'Your token has been revoked.')
      isReady = false
      bot.destroy()
    }
  }
}, 5000);


问:
No Web data in the table `events_intraday_YYYYMMDD` in BigQuery
After I have integrated the Google Analytics with the BigQuery in Firebase console, only the analytics data from IOS and ANDROID platform are found in the table events_intraday_YYYYMMDD. The WEB data is missing in this table.

However, the WEB data can be found in the tables events_YYYYMMDD.

May I know how to make the WEB data appear in the table events_intraday_YYYYMMDD?

答:
I got the reply from Firebase Support team. Here is the message:

Currently, web streams are not eligible for intraday tables in BigQuery export, and only have daily tables. Only mobile app (Android/iOS) streams will get both intraday and daily BigQuery export. We already have a request to consider adding this feature in the future. As of now, we are yet to find out any details or timelines on when (or if) this will be implemented. You can check our release notes from time to time for any updates on this.

Thanks a lot to the team for answering my question.


问:
Creating a Windows XP Junction
I need to create a Junction point (directory symbolic link) from C:\x to C:\xxx\yyy\zzz\aaa\bbb since I am running up against the Windows XP maximum file path length when adding files to this directory and I have no control over the directory structure.

I was reading that creating Junction points is not built-in to Windows so I will need a tool or software library to do it. How can I create a Junction point in code? I was looking at using Junction, but legal is telling me that I cannot distribute it.

My codebase is primarily in Java. I would prefer to not introduce C/C++ to do this.

答:
Marc B had the right idea but did not post an answer so I will post this one.
This Windows article details the linkd utility: http://support.microsoft.com/kb/205524/en-us

Linkd.exe

Grafts any target folder onto a Windows 2000 version of NTFS folder

This EXE can be download via Windows Server 2003 Resource Kit Tools: http://www.microsoft.com/downloads/en/details.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd

Although it is for Windows 2003, it will install with no problems on Windows XP. Note that this kit is not compatible with Vista and Vista already has a built-in utility (mklink) for creating Junction points.

One installed, a Junction can can be created:

```<code>linkd C:\x C:\xxx\yyy\zzz\aaa\bbb
</code>```

Title: Creating a Windows XP Junction

Body:
Marc B had the right idea but did not post an answer so I will post this one.
This Windows article details the linkd utility: http://support.microsoft.com/kb/205524/en-us

Linkd.exe

Grafts any target folder onto a Windows 2000 version of NTFS folder

This EXE can be download via Windows Server 2003 Resource Kit Tools: http://www.microsoft.com/downloads/en/details.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd

Although it is for Windows 2003, it will install with no problems on Windows XP. Note that this kit is not compatible with Vista and Vista already has a built-in utility (mklink) for creating Junction points.

One installed, a Junction can can be created:

linkd C:\x C:\xxx\yyy\zzz\aaa\bbb