问:
XQuery syntax to declare a namespace: [XPST0081] No namespace declared for 'text:p'
What is the syntax to declare a namespace for Libre Office, and what specific namespace needs to be declared?

```<code>thufir@dur:~/fods/flwor$
thufir@dur:~/fods/flwor$ basex text.xq
Stopped at /home/thufir/fods/flwor/text.xq, 3/14:
[XPST0081] No namespace declared for 'text:p'.
thufir@dur:~/fods/flwor$
thufir@dur:~/fods/flwor$ cat text.xq

for $foo  in db:open("foo")
return $foo//text:p

thufir@dur:~/fods/flwor$
</code>```

Of course, returning $foo by itself works fine to return the document in its entirety.

Do I need the namespace stored locally in a file, also?  Or, just add something like:

declare namespace type4="http:///de/tudarmstadt/ukp/dkpro/core/api/segmentation/type.ecore";

答:
Every namespace prefix you use in your query must be declared in the query, too. In your case you can add a line

```<code>declare namespace text="urn:oasis:names:tc:opendocument:xmlns:text:1.0";
</code>```

at the top to fix your query.

Since the namespace prefixes (text in your case) are only a reference to the associated namespace URI, it does not have to match the prefix in the XML document. The following query is 100% equivalent:

```<code>declare namespace whatever="urn:oasis:names:tc:opendocument:xmlns:text:1.0";

for $foo in db:open("foo")
return $foo//whatever:p
</code>```

Body:
What is the syntax to declare a namespace for Libre Office, and what specific namespace needs to be declared?

thufir@dur:~/fods/flwor$
thufir@dur:~/fods/flwor$ basex text.xq
Stopped at /home/thufir/fods/flwor/text.xq, 3/14:
[XPST0081] No namespace declared for 'text:p'.
thufir@dur:~/fods/flwor$
thufir@dur:~/fods/flwor$ cat text.xq

for $foo  in db:open("foo")
return $foo//text:p

thufir@dur:~/fods/flwor$

Of course, returning $foo by itself works fine to return the document in its entirety.

Do I need the namespace stored locally in a file, also?  Or, just add something like:

declare namespace type4="http:///de/tudarmstadt/ukp/dkpro/core/api/segmentation/type.ecore";

Body:
Every namespace prefix you use in your query must be declared in the query, too. In your case you can add a line

declare namespace text="urn:oasis:names:tc:opendocument:xmlns:text:1.0";

at the top to fix your query.

Since the namespace prefixes (text in your case) are only a reference to the associated namespace URI, it does not have to match the prefix in the XML document. The following query is 100% equivalent:

declare namespace whatever="urn:oasis:names:tc:opendocument:xmlns:text:1.0";

for $foo in db:open("foo")
return $foo//whatever:p


来源: stackexchange

问:
Integrated Windows authentication in Microsoft Edge
I am trying to implement Integrated Windows authentication on Edge, but it always prompts me for credentials, whereas Integrated Windows authentication is working for IE, Chrome and Firefox. I have tried adding the site to local intranet sites in security options and enabled automatic login but no luck on edge browser.

Does Edge support Integrated Windows authentication?

I have tried adding the site to local intranet sites in security options and enabled automatic login as well login with current username and password.

答:
Enabling Integrated Windows Authentication

Use the following procedure to enable silent authentication on each computer.

Open the Windows Settings and search Internet Options.

The following window opens.

Click Local intranet > Sites.

Click Advanced.

Enter the tenant specific URL into the Websites text box.

Click Close.

ContentLicense: CC BY-SA 4.0


问:
Dagger injection ViewModel Factory compile time error (dependency cycle in dagger)
I receive following error message from dagger at compile time. It finds a dependency cycle in dagger :

```<code>public abstract interface AppComponent extends dagger.android.AndroidInjector<com.sample.android.storytel.StorytelApplication> {
            ^
  androidx.lifecycle.ViewModelProvider.Factory is injected at
      com.sample.android.storytel.ui.DetailFragment.factory
  com.sample.android.storytel.ui.DetailFragment is injected at
      com.sample.android.storytel.di.DetailModule.providePost$app_debug(fragment)
  com.sample.android.storytel.domain.Post is injected at
      com.sample.android.storytel.viewmodels.DetailViewModel.Factory(…, post)
  com.sample.android.storytel.viewmodels.DetailViewModel.Factory is injected at
      com.sample.android.storytel.di.DetailModule.bindViewModelFactory$app_debug(factory)
  androidx.lifecycle.ViewModelProvider.Factory is injected at
      com.sample.android.storytel.ui.DetailFragment.factory
  com.sample.android.storytel.ui.DetailFragment is injected at
      dagger.android.AndroidInjector.inject(T) [com.sample.android.storytel.di.AppComponent → com.sample.android.storytel.di.ActivityBindingModule_MainActivity$app_debug.MainActivitySubcomponent → com.sample.android.storytel.di.DetailModule_DetailFragment$app_debug.DetailFragmentSubcomponent]
</code>```

Here is my DetailModule :

```<code>@Module
abstract class DetailModule {

    @ContributesAndroidInjector
    internal abstract fun detailFragment(): DetailFragment

    @Binds
    internal abstract fun bindViewModelFactory(factory: DetailViewModel.Factory): ViewModelProvider.Factory

    @Module
    companion object {

        @Provides
        @JvmStatic
        internal fun providePost(fragment: DetailFragment): Post =
            DetailFragmentArgs.fromBundle(fragment.arguments!!).post
    }
}
</code>```

Here is AppComponent :

```<code>@Singleton
@Component(
    modules = [ActivityBindingModule::class,
        AndroidSupportInjectionModule::class,
        Network::class,
        BaseModule::class]
)
interface AppComponent : AndroidInjector<StorytelApplication> {

    @Component.Builder
    interface Builder {

        @BindsInstance
        fun application(application: Application): Builder

        fun build(): AppComponent
    }
}
</code>```

Here is ActivityBindingModule :

```<code>@Module
abstract class ActivityBindingModule {

    @ContributesAndroidInjector(
        modules = [MainModule::class,
            DetailModule::class]
    )
    internal abstract fun mainActivity(): MainActivity
}
</code>```

And this is my DetailViewModel Factory :

```<code>/**
     * Factory for constructing DetailViewModel with parameter
     */
    class Factory @Inject constructor(
        private val useCase: DetailUseCase,
        val post: Post
    ) : ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            if (modelClass.isAssignableFrom(DetailViewModel::class.java)) {
                @Suppress("UNCHECKED_CAST")
                return DetailViewModel(useCase, post) as T
            }
            throw IllegalArgumentException("Unable to construct viewmodel")
        }
    }
</code>```

I have injected factory at my DetailFragment :

```<code>class DetailFragment @Inject
constructor() // Required empty public constructor
    : DaggerFragment() {

    @Inject
    lateinit var factory: DetailViewModel.Factory

    private val viewModel: DetailViewModel by lazy {
        ViewModelProviders.of(this, factory)
            .get(DetailViewModel::class.java)
    }
}
</code>```

答:
I change my providePost method by passing MainActivity as parameter instead of DetailFragment, and problem resolved :

```<code>        @Provides
        @JvmStatic
        internal fun providePost(activity: MainActivity): Post {
            val navHostFragment = activity.supportFragmentManager.findFragmentById(R.id.my_nav_host_fragment)
            val fragment = navHostFragment?.childFragmentManager?.fragments?.get(0);
            return DetailFragmentArgs.fromBundle(fragment?.arguments!!).post
        }
</code>```

Body:
I receive following error message from dagger at compile time. It finds a dependency cycle in dagger :

public abstract interface AppComponent extends dagger.android.AndroidInjector<com.sample.android.storytel.StorytelApplication> {
            ^
  androidx.lifecycle.ViewModelProvider.Factory is injected at
      com.sample.android.storytel.ui.DetailFragment.factory
  com.sample.android.storytel.ui.DetailFragment is injected at
      com.sample.android.storytel.di.DetailModule.providePost$app_debug(fragment)
  com.sample.android.storytel.domain.Post is injected at
      com.sample.android.storytel.viewmodels.DetailViewModel.Factory(…, post)
  com.sample.android.storytel.viewmodels.DetailViewModel.Factory is injected at
      com.sample.android.storytel.di.DetailModule.bindViewModelFactory$app_debug(factory)
  androidx.lifecycle.ViewModelProvider.Factory is injected at
      com.sample.android.storytel.ui.DetailFragment.factory
  com.sample.android.storytel.ui.DetailFragment is injected at
      dagger.android.AndroidInjector.inject(T) [com.sample.android.storytel.di.AppComponent → com.sample.android.storytel.di.ActivityBindingModule_MainActivity$app_debug.MainActivitySubcomponent → com.sample.android.storytel.di.DetailModule_DetailFragment$app_debug.DetailFragmentSubcomponent]

Here is my DetailModule :

@Module
abstract class DetailModule {

    @ContributesAndroidInjector
    internal abstract fun detailFragment(): DetailFragment

    @Binds
    internal abstract fun bindViewModelFactory(factory: DetailViewModel.Factory): ViewModelProvider.Factory

    @Module
    companion object {

        @Provides
        @JvmStatic
        internal fun providePost(fragment: DetailFragment): Post =
            DetailFragmentArgs.fromBundle(fragment.arguments!!).post
    }
}

Here is AppComponent :

@Singleton
@Component(
    modules = [ActivityBindingModule::class,
        AndroidSupportInjectionModule::class,
        Network::class,
        BaseModule::class]
)
interface AppComponent : AndroidInjector<StorytelApplication> {

    @Component.Builder
    interface Builder {

        @BindsInstance
        fun application(application: Application): Builder

        fun build(): AppComponent
    }
}

Here is ActivityBindingModule :

@Module
abstract class ActivityBindingModule {

    @ContributesAndroidInjector(
        modules = [MainModule::class,
            DetailModule::class]
    )
    internal abstract fun mainActivity(): MainActivity
}

And this is my DetailViewModel Factory :

/**
     * Factory for constructing DetailViewModel with parameter
     */
    class Factory @Inject constructor(
        private val useCase: DetailUseCase,
        val post: Post
    ) : ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            if (modelClass.isAssignableFrom(DetailViewModel::class.java)) {
                @Suppress("UNCHECKED_CAST")
                return DetailViewModel(useCase, post) as T
            }
            throw IllegalArgumentException("Unable to construct viewmodel")
        }
    }

I have injected factory at my DetailFragment :

class DetailFragment @Inject
constructor() // Required empty public constructor
    : DaggerFragment() {

    @Inject
    lateinit var factory: DetailViewModel.Factory

    private val viewModel: DetailViewModel by lazy {
        ViewModelProviders.of(this, factory)
            .get(DetailViewModel::class.java)
    }
}

Body:
I change my providePost method by passing MainActivity as parameter instead of DetailFragment, and problem resolved :

        @Provides
        @JvmStatic
        internal fun providePost(activity: MainActivity): Post {
            val navHostFragment = activity.supportFragmentManager.findFragmentById(R.id.my_nav_host_fragment)
            val fragment = navHostFragment?.childFragmentManager?.fragments?.get(0);
            return DetailFragmentArgs.fromBundle(fragment?.arguments!!).post
        }


问:
Web API .NET MVC - Http POST - Fiddler request send string variable
So I'm doing an API where I have to send a huge json file and a name for a variable to the database. Currently am sending and reading the file with my code, and it's working fine.

Then thing is that I have to send a string for a service name (may have "/" characters, that's why I didn't put it as the file name, or query string.

I tried sending this request (HTTP POST) :

```<code>---------------------------32r23rfewfwfaedef
Content-Disposition: form-data; name="fieldNameHere"; filename="XXXXXX.json"
Content-Type: application/json

{"name":"test"}

<@INCLUDE *C:\....\XXXXXX.json*@>
---------------------------32r23rfewfwfaedef--
</code>```

The thing is that I can't find that variable anywhere in my controller... My code is like this:

```<code>public HttpResponseMessage Post()
        {
            if (HttpContext.Current.Request.Files.Count != 1)
                throw new HttpResponseException(new HttpResponseMessage()
                {
                    ReasonPhrase = "One file is required, a json in order to create the Swagger.",
                    StatusCode = HttpStatusCode.BadRequest
                });

            SwaggerSaveModel model = new SwaggerSaveModel();

            HttpPostedFile postedFile = HttpContext.Current.Request.Files[0];

            using (System.IO.StreamReader myFile = new System.IO.StreamReader(postedFile.InputStream))
            {
                var XmlObj = new StreamReader(postedFile.InputStream).ReadToEnd();
                model.SwaggerJson = XmlObj.ToString();
            }

            return Request.CreateResponse(HttpStatusCode.Created, "blabla");

        }
</code>```

The file reading is fine, but I can't find the "name" variable... I also can´t change that json file, because it's a swagger and it has to be used exactly as it is being sent.

Please help..

答:
For future doubts like mine, I figured out how to do this. I'm sending my request like this:

```<code>parameter: FileName
</code>```

And accessing on my controller like this:

```<code>HttpContext.Current.Request.Params["HTTP_PARAMETER"]
</code>```

Then it returns "FileName"

Body:
So I'm doing an API where I have to send a huge json file and a name for a variable to the database. Currently am sending and reading the file with my code, and it's working fine.

Then thing is that I have to send a string for a service name (may have "/" characters, that's why I didn't put it as the file name, or query string.

I tried sending this request (HTTP POST) :

---------------------------32r23rfewfwfaedef
Content-Disposition: form-data; name="fieldNameHere"; filename="XXXXXX.json"
Content-Type: application/json

{"name":"test"}

<@INCLUDE *C:\....\XXXXXX.json*@>
---------------------------32r23rfewfwfaedef--

The thing is that I can't find that variable anywhere in my controller... My code is like this:

public HttpResponseMessage Post()
        {
            if (HttpContext.Current.Request.Files.Count != 1)
                throw new HttpResponseException(new HttpResponseMessage()
                {
                    ReasonPhrase = "One file is required, a json in order to create the Swagger.",
                    StatusCode = HttpStatusCode.BadRequest
                });

            SwaggerSaveModel model = new SwaggerSaveModel();

            HttpPostedFile postedFile = HttpContext.Current.Request.Files[0];

            using (System.IO.StreamReader myFile = new System.IO.StreamReader(postedFile.InputStream))
            {
                var XmlObj = new StreamReader(postedFile.InputStream).ReadToEnd();
                model.SwaggerJson = XmlObj.ToString();
            }

            return Request.CreateResponse(HttpStatusCode.Created, "blabla");

        }

The file reading is fine, but I can't find the "name" variable... I also can´t change that json file, because it's a swagger and it has to be used exactly as it is being sent.

Please help..

Body:
For future doubts like mine, I figured out how to do this. I'm sending my request like this:

parameter: FileName

And accessing on my controller like this:

HttpContext.Current.Request.Params["HTTP_PARAMETER"]

Then it returns "FileName"


问:
Axios Delete req.body not received in the backend
This is my axios Delete request:

adminActions.js

```<code>export const deleteAdmin = (email) => dispatch => {
  console.log('receivedEmail in deleteAdmin action is: ', email)
  // Logs this:  received email inside delete Admin action is:  {email: "testDeleteButton@gmail.com"}
  return  axios
     .delete("http://localhost:3083/api/admin/deleteAdminAccountByEmail", {email: email})
     .then(res => {
       console.log("inside POST http://localhost:3083/api/admin/deleteAdminAccountByEmail");
       console.log("res.data.admin", res);
       if (res.data.success) {
       console.log('ADMIN HAS BEEN SUCCESSFULLY DELETED')
       }
       return (true)
     })
     .catch(err => {
       console.log("Admin Deletion has failed. ERROR: ");
       console.log(err);
       return(false)
     });
 };
</code>```

I am calling that function here:

User.js

```<code>  deleteAdmin() {
    const user = this.state.usersInformation.find(
      user => user.id.toString() === this.props.match.params.id
    );
    this.props.deleteAdmin(user.email);
  }
</code>```

In the backend, I am receiving the request here:

admin_routes.js

```<code>// @route  DELETE api/admin/deleteAdminAccountByEmail
// @desc   deleteAdminAccount By email
// @access Private

    router.delete("/deleteAdminAccountByEmail", isLoggedIn, function(req, res) {
      logger.notice("INSIDE ROUTE: deleteAdminAccountByEmail");
      console.log('Received email inside deleteAdminAccountByEmail route: ')
      console.log(req.body)
      // Logs this :Received email inside deleteAdminAccountByEmail route:  {}
      let loggedInAdmin = {
        token: req.user.token,
        id: req.user.id,
        email: req.user.email,
        name: req.user.name,
        role: req.user.role
      };

      if (loggedInAdmin.role === "super_user") {
        logger.notice("The logged-in admin's role is super_user.");
        // Can delete admin account 'administrateur','operateur_sav','agent_support_tel','agent_magasin'
        adminService.deleteAdminByEmail(req.body.email, req, res);
      } else if (loggedInAdmin.role === "administrateur") {
        logger.notice("The logged-in admin's role is administrateur.");

        adminService.isSuper_UserByEmail(req.body.email).then(isSuper_User => {
          logger.info(
            "req.params.email: INSIDE RETURNE PROMISE ",
            req.params.email
          );
          if (isSuper_User) {
            logger.debug(
              "adminService.isSuper_User(req.params.email): ",
              isSuper_User
            );
            res.status(200).json({
              unauthorized: "The operation is unauthorized"
            });
          } else {
            //UserToBeDeleted is not Super_User. Check if it is administrateur.
            adminService
              .isAdministrateurByEmail(req.body.email)
              .then(isAdministrateur => {
                logger.info(
                  "req.params.email: INSIDE RETURNE PROMISE ",
                  req.params.email
                );
                if (isAdministrateur) {
                  logger.debug(
                    "adminService.isAdministrateur(req.params.email): ",
                    isAdministrateur
                  );
                  res.status(200).json({
                    unauthorized: "The operation is unauthorized"
                  });
                } else {
                  //UserToBeDeleted is neither Admin nor Super_User. So the administrateur can delete it.
                  adminService.deleteAdminByEmail(req.body.email, req, res);
                }
              });
          }
        });
      } else {
        // The logged-in admin's role is neither super_user nor administrateur. Deletion of admin accounts is forbidden.
        logger.notice(
          "The logged-in admin's role is neither super_user nor administrateur. Deletion of admin accounts is forbidden."
        );
        res
          .status(401)
          .send({ success: false, tag: "Unauthorized to delete admin accounts" });
      }
    });
</code>```

Notice in the action, I have this in the log:

// Logs this:  received email inside delete Admin action is:
  {email: "testDeleteButton@gmail.com"}

Notice in the backend, I have this in the log:

Received email inside deleteAdminAccountByEmail route: {}

So the req.body is not received in the backend.

PS: I have followed the instructions in various stackoverflow questions including this one by modifying the axios request like this:

```<code> axios
 .delete("http://localhost:3083/api/admin/deleteAdminAccountByEmail", { data:{email: email}})
</code>```

Notice, I added the data key. But I still get the same result.

答:
Try accessing it via:</p>

```<code>req.params.email
</code>```

Body:
This is my axios Delete request:

adminActions.js

export const deleteAdmin = (email) => dispatch => {
  console.log('receivedEmail in deleteAdmin action is: ', email)
  // Logs this:  received email inside delete Admin action is:  {email: "testDeleteButton@gmail.com"}
  return  axios
     .delete("http://localhost:3083/api/admin/deleteAdminAccountByEmail", {email: email})
     .then(res => {
       console.log("inside POST http://localhost:3083/api/admin/deleteAdminAccountByEmail");
       console.log("res.data.admin", res);
       if (res.data.success) {
       console.log('ADMIN HAS BEEN SUCCESSFULLY DELETED')
       }
       return (true)
     })
     .catch(err => {
       console.log("Admin Deletion has failed. ERROR: ");
       console.log(err);
       return(false)
     });
 };

I am calling that function here:

User.js

  deleteAdmin() {
    const user = this.state.usersInformation.find(
      user => user.id.toString() === this.props.match.params.id
    );
    this.props.deleteAdmin(user.email);
  }

In the backend, I am receiving the request here:

admin_routes.js

// @route  DELETE api/admin/deleteAdminAccountByEmail
// @desc   deleteAdminAccount By email
// @access Private

    router.delete("/deleteAdminAccountByEmail", isLoggedIn, function(req, res) {
      logger.notice("INSIDE ROUTE: deleteAdminAccountByEmail");
      console.log('Received email inside deleteAdminAccountByEmail route: ')
      console.log(req.body)
      // Logs this :Received email inside deleteAdminAccountByEmail route:  {}
      let loggedInAdmin = {
        token: req.user.token,
        id: req.user.id,
        email: req.user.email,
        name: req.user.name,
        role: req.user.role
      };

      if (loggedInAdmin.role === "super_user") {
        logger.notice("The logged-in admin's role is super_user.");
        // Can delete admin account 'administrateur','operateur_sav','agent_support_tel','agent_magasin'
        adminService.deleteAdminByEmail(req.body.email, req, res);
      } else if (loggedInAdmin.role === "administrateur") {
        logger.notice("The logged-in admin's role is administrateur.");

        adminService.isSuper_UserByEmail(req.body.email).then(isSuper_User => {
          logger.info(
            "req.params.email: INSIDE RETURNE PROMISE ",
            req.params.email
          );
          if (isSuper_User) {
            logger.debug(
              "adminService.isSuper_User(req.params.email): ",
              isSuper_User
            );
            res.status(200).json({
              unauthorized: "The operation is unauthorized"
            });
          } else {
            //UserToBeDeleted is not Super_User. Check if it is administrateur.
            adminService
              .isAdministrateurByEmail(req.body.email)
              .then(isAdministrateur => {
                logger.info(
                  "req.params.email: INSIDE RETURNE PROMISE ",
                  req.params.email
                );
                if (isAdministrateur) {
                  logger.debug(
                    "adminService.isAdministrateur(req.params.email): ",
                    isAdministrateur
                  );
                  res.status(200).json({
                    unauthorized: "The operation is unauthorized"
                  });
                } else {
                  //UserToBeDeleted is neither Admin nor Super_User. So the administrateur can delete it.
                  adminService.deleteAdminByEmail(req.body.email, req, res);
                }
              });
          }
        });
      } else {
        // The logged-in admin's role is neither super_user nor administrateur. Deletion of admin accounts is forbidden.
        logger.notice(
          "The logged-in admin's role is neither super_user nor administrateur. Deletion of admin accounts is forbidden."
        );
        res
          .status(401)
          .send({ success: false, tag: "Unauthorized to delete admin accounts" });
      }
    });

Notice in the action, I have this in the log:

// Logs this:  received email inside delete Admin action is:
  {email: "testDeleteButton@gmail.com"}

Notice in the backend, I have this in the log:

Received email inside deleteAdminAccountByEmail route: {}

So the req.body is not received in the backend.

PS: I have followed the instructions in various stackoverflow questions including this one by modifying the axios request like this:

 axios
 .delete("http://localhost:3083/api/admin/deleteAdminAccountByEmail", { data:{email: email}})

Notice, I added the data key. But I still get the same result.

Body:
Try accessing it via:

req.params.email


问:
Live streaming: node-media-server + Dash.js configured for real-time low latency
We're working on an app that enables live monitoring of your back yard.
Each client has a camera connected to the internet, streaming to our public node.js server.

I'm trying to use node-media-server to publish an MPEG-DASH (or HLS) stream to be available for our app clients, on different networks, bandwidths and resolutions around the world.

Our goal is to get as close as possible to live "real-time" so you can monitor what happens in your backyard instantly.

The technical flow already accomplished is:

ffmpeg process on our server processes the incoming camera stream (separate child process for each camera) and publishes the stream via RTSP on the local machine for node-media-server to use as an 'input' (we are also saving segmented files, generating thumbnails, etc.). the ffmpeg command responsible for that is:

-c:v libx264 -preset ultrafast -tune zerolatency -b:v 900k -f flv rtmp://127.0.0.1:1935/live/office

node-media-server is running with what I found as the default configuration for 'live-streaming'

```<code>private NMS_CONFIG = {
server: {
  secret: 'thisisnotmyrealsecret',
},
rtmp_server: {
  rtmp: {
    port: 1935,
    chunk_size: 60000,
    gop_cache: false,
    ping: 60,
    ping_timeout: 30,
  },
  http: {
    port: 8888,
    mediaroot: './server/media',
    allow_origin: '*',
  },
  trans: {
    ffmpeg: '/usr/bin/ffmpeg',
    tasks: [
      {
        app: 'live',
        hls: true,
        hlsFlags: '[hls_time=2:hls_list_size=3:hls_flags=delete_segments]',
        dash: true,
        dashFlags: '[f=dash:window_size=3:extra_window_size=5]',
      },
    ],
  },
},
</code>```

};

As I understand it, out of the box NMS (node-media-server) publishes the input stream it gets in multiple output formats: flv, mpeg-dash, hls.
with all sorts of online players for these formats I'm able to access and the stream using the url on localhost. with mpeg-dash and hls I'm getting anything between 10-15 seconds of delay, and more.

My goal now is to implement a local client-side mpeg-dash player, using dash.js and configure it to be as close as possible to live.

my code for that is:

<!doctype html>

        <title>Dash.js Rocks</title>

            <video autoplay="" id="videoPlayer" controls=""></video>

```

with the online test video (https://dash.akamaized.net/envivio/EnvivioDash3/manifest.mpd) I see that the live latency value is close to 2 secs (but I have no way to actually confirm it. it's a video file streamed. in my office I have a camera so I can actually compare latency between real-life and the stream I get).
however when working locally with my NMS, it seems this value does not want to go below 20-25 seconds.

Am I doing something wrong? any configuration on the player (client-side html) I'm forgetting?
or is there a missing configuration I should add on the server side (NMS) ?

答:
HLS and MPEG DASH are not particularly low latency as standard and the figures you are getting are not unusual.

Some examples from a publicly available DASH forum document (linked below) include:

Given the resources of some of these organisations, the results you have achieved are not bad!

There is quite a focus in the streaming industry at this time on enabling lower latency, the target being to come as close as possible to traditional broadcast latency.

One key component of the latency in chunked Adaptive Bit Rate (ABR, see this answer for more info: https://stackoverflow.com/a/42365034/334402 ) is the need for the player to receive and decode one or more segments of the video before it can display it. Traditionally the player had to receive the entire segment before it could start to decode and display it. The diagram from the first linked open source reference below illustrates this:

Low latency DASH and HLS leverage CMAF, 'Common Media Application Format' which breaks the segments, which might be 6 seconds long for example, into smaller 'chunks' within each segment. These chunks are designed to allow the player to decode and start playing them before it has received the full segment.

Other sources of latency in a typical live stream will be any transcoding from one format to another and any delay in a streaming server receiving the feed, from the webcam in your case, and encoding and packaging it for streaming.

There is quite a lot of good information available on low latency streaming at this time both from standards bodies and open source discussions which I think will really help you appreciate the issues (all links current at time of writing). From open source and standards discussions:

https://dashif.org/docs/Report%20on%20Low%20Latency%20DASH.pdf (DASH focus)

https://github.com/video-dev/hlsjs-rfcs/pull/1. (HLS focus)

and from vendors:

https://bitmovin.com/cmaf-low-latency-streaming/

https://websites.fraunhofer.de/video-dev/dash-js-low-latency-streaming-with-cmaf/

https://aws.amazon.com/blogs/media/alhls-apple-low-latency-http-live-streaming-explained/

Note - a common use case often quoted in the broadcast world is the case where someone watching a live event like a game may hear their neighbours celebrating a goal or touchdown before they see it themselves, because their feed has higher latency than their neighbours. While this is a driver for low latency, this is really a synchronisation issue which would require other solutions if a 'perfectly' synchronised solution was the goal.

As you can see low latency streaming is not a simple challenge and it may be that you want to consider other approaches depending on the details of your use case, including how many subscribers you have, whether some loss of quality if a fair trade off for lower latency etc. As mentioned by @user1390208 in the comments, a more real time focused video communication technology like WebRTC may be a better match for the solution you are targeting.

If you want to provide a service that provides life streaming and also a recording, you may want to consider using a real time protocol for the live streaming view and HLS/DASH streaming for anyone looking back through recordings where latency may not be important but quality may be more key.

Body:
We're working on an app that enables live monitoring of your back yard.
Each client has a camera connected to the internet, streaming to our public node.js server.

I'm trying to use node-media-server to publish an MPEG-DASH (or HLS) stream to be available for our app clients, on different networks, bandwidths and resolutions around the world.

Our goal is to get as close as possible to live "real-time" so you can monitor what happens in your backyard instantly.

The technical flow already accomplished is:

ffmpeg process on our server processes the incoming camera stream (separate child process for each camera) and publishes the stream via RTSP on the local machine for node-media-server to use as an 'input' (we are also saving segmented files, generating thumbnails, etc.). the ffmpeg command responsible for that is:

-c:v libx264 -preset ultrafast -tune zerolatency -b:v 900k -f flv rtmp://127.0.0.1:1935/live/office

node-media-server is running with what I found as the default configuration for 'live-streaming'

private NMS_CONFIG = {
server: {
  secret: 'thisisnotmyrealsecret',
},
rtmp_server: {
  rtmp: {
    port: 1935,
    chunk_size: 60000,
    gop_cache: false,
    ping: 60,
    ping_timeout: 30,
  },
  http: {
    port: 8888,
    mediaroot: './server/media',
    allow_origin: '*',
  },
  trans: {
    ffmpeg: '/usr/bin/ffmpeg',
    tasks: [
      {
        app: 'live',
        hls: true,
        hlsFlags: '[hls_time=2:hls_list_size=3:hls_flags=delete_segments]',
        dash: true,
        dashFlags: '[f=dash:window_size=3:extra_window_size=5]',
      },
    ],
  },
},

};

As I understand it, out of the box NMS (node-media-server) publishes the input stream it gets in multiple output formats: flv, mpeg-dash, hls.
with all sorts of online players for these formats I'm able to access and the stream using the url on localhost. with mpeg-dash and hls I'm getting anything between 10-15 seconds of delay, and more.

My goal now is to implement a local client-side mpeg-dash player, using dash.js and configure it to be as close as possible to live.

my code for that is:

<!doctype html>

        <title>Dash.js Rocks</title>

            <video autoplay="" id="videoPlayer" controls=""></video>

with the online test video (https://dash.akamaized.net/envivio/EnvivioDash3/manifest.mpd) I see that the live latency value is close to 2 secs (but I have no way to actually confirm it. it's a video file streamed. in my office I have a camera so I can actually compare latency between real-life and the stream I get).
however when working locally with my NMS, it seems this value does not want to go below 20-25 seconds.

Am I doing something wrong? any configuration on the player (client-side html) I'm forgetting?
or is there a missing configuration I should add on the server side (NMS) ?


问:
How to split and sum comma separated multiple line values in php
I have one issue. How can i split and sum up multiple comma separated line values in php. Following my mysql table screenshot

here my date wise miles filter page

I want to output miles colums like following when users enter from and to date.

```<code>IA      59.62
MD       7.88
IL     359.22

Total Miles : 426.72

How can i achieve this in php? Please help me.

</code>```

my php code:

```<code><?php
// Range.php
if(isset($_POST["From"], $_POST["to"]))
{
    $conn = mysqli_connect("localhost", "root", "", "truckinvo");

    $result = '';
    $query = "SELECT * FROM tble_states_miles WHERE order_date BETWEEN '".$_POST["From"]."' AND '".$_POST["to"]."'";
    $sql = mysqli_query($conn, $query);
    ?>
    <table class="table table-bordered">
    <tr>
Total Miles from the date between <?php echo $_POST["From"]; ?> to <?php echo $_POST["to"]; ?>
<th width="40%">Miles</th>
    </tr>
    <?php
    if(mysqli_num_rows($sql) > 0)
    {
        while($row = mysqli_fetch_array($sql))
        {
            ?>
            <tr>

            <td>
            <?php

            echo nl2br($row["miles"]); ?></td>
            </tr>
            <?php
        }
    }
    else
    {
    ?>

        <tr>
        <td colspan="5">No Data Found</td>
        </tr>
        <?php
    }
    ?>
    </table>
    <?php   echo $result; }
?>
</code>```

I tried to use following code to split

```<code><?php
    $f1 = preg_replace('/,\\s*/', "', '", $row["miles"]);
$f2 = preg_replace('/\\n/', "'), \n('", $f1);
?>
    <?php echo $f2;  ?>
</code>```

答:
Break per line, break each row to parts, display the name and sum up the values. Try:

Before the loop:

```<code><?php $totalMiles = 0 ?>
</code>```

Instead of:

```<code><td>
<?php
  echo nl2br($row["miles"]); ?>
</td>
</code>```

In the loop:

```<code><td>
<?php
    // iterate per state
    foreach (explode("\n", $row['miles']) as $stateRow) {
        // prepare the parts, we don't want any whitespace
        $stateParts = array_filter(array_map('trim', explode(',', $stateRow)));

        // the state's name (the first part)
        $stateName = $stateParts[0];

        // sum everything in the array
        // this works, because the name will get cast to "0"
        // try it: echo (int) 'IL';
        $stateMiles = array_sum($stateParts);

        // total mileage sum
        $totalMiles += $stateMiles;

        // display the result, any way you want
        printf('%s miles %.2f', $stateName, $stateMiles);
    }
?>
</td>
</code>```

After the loop:

```<code>Total miles <?= $totalMiles ?>
</code>```

And please, use prepared statements, your application is unsecure.

Body:
I have one issue. How can i split and sum up multiple comma separated line values in php. Following my mysql table screenshot

here my date wise miles filter page

I want to output miles colums like following when users enter from and to date.

IA      59.62
MD       7.88
IL     359.22

Total Miles : 426.72

How can i achieve this in php? Please help me.

my php code:

<?php
// Range.php
if(isset($_POST["From"], $_POST["to"]))
{
    $conn = mysqli_connect("localhost", "root", "", "truckinvo");

    $result = '';
    $query = "SELECT * FROM tble_states_miles WHERE order_date BETWEEN '".$_POST["From"]."' AND '".$_POST["to"]."'";
    $sql = mysqli_query($conn, $query);
    ?>

Total Miles from the date between <?php echo $_POST["From"]; ?> to <?php echo $_POST["to"]; ?>
Miles

    <?php
    if(mysqli_num_rows($sql) > 0)
    {
        while($row = mysqli_fetch_array($sql))
        {
            ?>

            <?php

            echo nl2br($row["miles"]); ?>

            <?php
        }
    }
    else
    {
    ?>

        No Data Found

        <?php
    }
    ?>

    <?php   echo $result; }
?>

I tried to use following code to split

<?php
    $f1 = preg_replace('/,\\s*/', "', '", $row["miles"]);
$f2 = preg_replace('/\\n/', "'), \n('", $f1);
?>
    <?php echo $f2;  ?>

Body:
Break per line, break each row to parts, display the name and sum up the values. Try:

Before the loop:

<?php $totalMiles = 0 ?>

Instead of:

<td>
<?php
  echo nl2br($row["miles"]); ?>
</td>

In the loop:

<td>
<?php
    // iterate per state
    foreach (explode("\n", $row['miles']) as $stateRow) {
        // prepare the parts, we don't want any whitespace
        $stateParts = array_filter(array_map('trim', explode(',', $stateRow)));

        // the state's name (the first part)
        $stateName = $stateParts[0];

        // sum everything in the array
        // this works, because the name will get cast to "0"
        // try it: echo (int) 'IL';
        $stateMiles = array_sum($stateParts);

        // total mileage sum
        $totalMiles += $stateMiles;

        // display the result, any way you want
        printf('%s miles %.2f', $stateName, $stateMiles);
    }
?>
</td>

After the loop:

Total miles <?= $totalMiles ?>

And please, use prepared statements, your application is unsecure.


问:
Sequelize query call procedure firing twice
Calling procedure in Sequelize query resulting two times.

```<code>return await sequelize.query('CALL get_products();', { type: sequelize.QueryTypes.SELECT});
</code>```

// In route

```<code>module.exports = (app) => {
  let router = require('express').Router();

  const verifyToken       = require('../../middlewares/verifyToken');
  const productController = require('../../controllers/api/productController');

  router.get('/products', verifyToken, productController.getProducts);
  router.get('/products/:productId', verifyToken, productController.getProduct);

  app.use('/api', router);
};
</code>```

// productController.js

```<code>const db        = require('../../models');
const Product   = db.products;
const sequelize = db.sequelize;

 exports.getProducts = async (request, response) => {
  let responseData = {};
  let products     = [];

  // Get products
  products = await sequelize.query('CALL get_products();')
  .then(data => {
    return data;
  })
  .catch(error => {
    //
  });
  //-------------

 // Set response data
 if (products) {
  responseData = {
    status: true,
    message: 'Products found.',
    data: {
      products: products
    }
  };
} else {
  responseData = {
    status: false,
    message: 'Products not found.',
    data: null
  };
}
//------------------

return response.status(200).json(responseData);
</code>```

console.log firing twice in the function even if the query code removed. looks like this is a code error of mine.

答:
The error is in having both await and .then(...).catch(...).

You should use just one of these two constructs, depending on your preference.

Here with .then().catch()

```<code>const db        = require('../../models');
const Product   = db.products;
const sequelize = db.sequelize;

exports.getProducts = (request, response) => {
  let responseData = {};
  let products     = [];

  // Get products
  products = await sequelize.query('CALL get_products();').then(data => {
    // Set response data
    if (products) {
      responseData = {
        status: true,
        message: 'Products found.',
        data: {
          products: products
        }
      };
    } else {
      responseData = {
        status: false,
        message: 'Products not found.',
        data: null
      };
    }
  }).catch(error => {
    // handle any error
  });
}
</code>```

Here with await

```<code>const db        = require('../../models');
const Product   = db.products;
const sequelize = db.sequelize;

exports.getProducts = async (request, response) => {
  let responseData = {};
  let products     = [];

  // Get products
  products = await sequelize.query('CALL get_products();');

  // Set response data
  if (products) {
    responseData = {
      status: true,
      message: 'Products found.',
      data: {
        products: products
      }
    };
  } else {
    responseData = {
      status: false,
      message: 'Products not found.',
      data: null
    };
  }
}
</code>```

I always prefer using .then().catch() syntax so I don't really know how to handle any error with the await pattern. Maybe a try-catch could do. I hope this helps.

Body:
Calling procedure in Sequelize query resulting two times.

return await sequelize.query('CALL get_products();', { type: sequelize.QueryTypes.SELECT});

// In route

module.exports = (app) => {
  let router = require('express').Router();

  const verifyToken       = require('../../middlewares/verifyToken');
  const productController = require('../../controllers/api/productController');

  router.get('/products', verifyToken, productController.getProducts);
  router.get('/products/:productId', verifyToken, productController.getProduct);

  app.use('/api', router);
};

// productController.js

const db        = require('../../models');
const Product   = db.products;
const sequelize = db.sequelize;

 exports.getProducts = async (request, response) => {
  let responseData = {};
  let products     = [];

  // Get products
  products = await sequelize.query('CALL get_products();')
  .then(data => {
    return data;
  })
  .catch(error => {
    //
  });
  //-------------

 // Set response data
 if (products) {
  responseData = {
    status: true,
    message: 'Products found.',
    data: {
      products: products
    }
  };
} else {
  responseData = {
    status: false,
    message: 'Products not found.',
    data: null
  };
}
//------------------

return response.status(200).json(responseData);

console.log firing twice in the function even if the query code removed. looks like this is a code error of mine.

Body:
The error is in having both await and .then(...).catch(...).

You should use just one of these two constructs, depending on your preference.

Here with .then().catch()

const db        = require('../../models');
const Product   = db.products;
const sequelize = db.sequelize;

exports.getProducts = (request, response) => {
  let responseData = {};
  let products     = [];

  // Get products
  products = await sequelize.query('CALL get_products();').then(data => {
    // Set response data
    if (products) {
      responseData = {
        status: true,
        message: 'Products found.',
        data: {
          products: products
        }
      };
    } else {
      responseData = {
        status: false,
        message: 'Products not found.',
        data: null
      };
    }
  }).catch(error => {
    // handle any error
  });
}

Here with await

const db        = require('../../models');
const Product   = db.products;
const sequelize = db.sequelize;

exports.getProducts = async (request, response) => {
  let responseData = {};
  let products     = [];

  // Get products
  products = await sequelize.query('CALL get_products();');

  // Set response data
  if (products) {
    responseData = {
      status: true,
      message: 'Products found.',
      data: {
        products: products
      }
    };
  } else {
    responseData = {
      status: false,
      message: 'Products not found.',
      data: null
    };
  }
}

I always prefer using .then().catch() syntax so I don't really know how to handle any error with the await pattern. Maybe a try-catch could do. I hope this helps.


问:
Useful data structure for the following case
Which can be the beste data structures for the following case.

1.Should have operations like search, insert and delete. Mostly searching activities will be there.Around 90% of the operations will be search and rest are delete and insert.

2 Insertion,deletion and searching will  be based on the  key of the objects. Each key will point to a object. The keys will be sorted.

Any suggestion for optimal data structure will be highly appreciated.

答: Self-balancing tree of sorts (AVL, RB), or a hash table.</p>

ContentLicense: CC BY-SA 3.0


问:
Can not pass Data To ContainerView
I have tried 2 methods to pass the data from ViewController to ContainerView, with and without segue
Here is without segue method

ViewController

```<code> class DetailPostBookReviewVC: UIViewController {

        var postid: String!

        @IBAction func Menubutton(_ sender: Any) {

        print(postid!)

        let storyboard = UIStoryboard(name: "Main", bundle: nil)

        let vc = storyboard.instantiateViewController(withIdentifier: "MenuBookReviewVC") as! MenuBookReviewVC

        vc.favpostid = postid
 }
</code>```

ContainerView

```<code>class MenuBookReviewVC: UIViewController {

    var favpostid = String()
     @IBAction func Deletepost(_ sender: Any) {
        print(favpostid)
    }
}
</code>```

result: favposid has Nill Value

UPDATE this is with segue method

```<code>class DetailPostBookReviewVC: UIViewController {

     var postid: String!

     @IBAction func Menubutton(_ sender: Any) {
        print(postid!)

     func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){

    if (segue.identifier == "toMenuBookReviewVC") { //"toMenuBookReviewVC" is identifier

       let vc = segue.destination as! MenuBookReviewVC
        vc.favpostid = postid!
    }
}
</code>```

答:
For Passing Data To Container View you can use this

UserDefaults.standard.set(value, forKey: "SomeKey")

after your data is used you can clear that default value.

UserDefaults.standard.set("", forKey: "SomeKey")

Title: Can not pass Data To ContainerView

Body:
I have tried 2 methods to pass the data from ViewController to ContainerView, with and without segue
Here is without segue method

ViewController

 class DetailPostBookReviewVC: UIViewController {

        var postid: String!

        @IBAction func Menubutton(_ sender: Any) {

        print(postid!)

        let storyboard = UIStoryboard(name: "Main", bundle: nil)

        let vc = storyboard.instantiateViewController(withIdentifier: "MenuBookReviewVC") as! MenuBookReviewVC

        vc.favpostid = postid
 }

ContainerView

class MenuBookReviewVC: UIViewController {

    var favpostid = String()
     @IBAction func Deletepost(_ sender: Any) {
        print(favpostid)
    }
}

result: favposid has Nill Value

UPDATE this is with segue method

class DetailPostBookReviewVC: UIViewController {

     var postid: String!

     @IBAction func Menubutton(_ sender: Any) {
        print(postid!)

     func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){

    if (segue.identifier == "toMenuBookReviewVC") { //"toMenuBookReviewVC" is identifier

       let vc = segue.destination as! MenuBookReviewVC
        vc.favpostid = postid!
    }
}


问:
Using dictionary key as the _id when using pymongo
I have a dictionary like so:

a_dictionary = {
                'UniqueNumber': 1,
                'YearResults' : [],
               }
```

<p>When I use:</p>

<pre class="lang-py prettyprint-override"><code>MyCollection.replace_one(
        {'UniqueNumber': a_dictionary['UniqueNumber']}, a_dictionary, upsert=True)
</code>```

Mongodb is creating an _id field: _id: 5e467caa3cec0556ddcb3a41.

I don't want this, I want to use my UniqueNumber and have no _id field.

答:
As per the documentation: Insert document

When a document is inserted a special key, "_id", is automatically added if the document doesn’t already contain an "_id" key. The value of "_id" must be unique across the collection

So in order to have your custom identifier you can add _id to the record you are inserting. Please note The value of "_id" must be unique across the collection

Hope it helps.

Body:
I have a dictionary like so:

a_dictionary = {
                'UniqueNumber': 1,
                'YearResults' : [],
               }

When I use:

MyCollection.replace_one(
        {'UniqueNumber': a_dictionary['UniqueNumber']}, a_dictionary, upsert=True)

Mongodb is creating an _id field: _id: 5e467caa3cec0556ddcb3a41.

I don't want this, I want to use my UniqueNumber and have no _id field.


问:
Checkboxes in powershell GUI not working as supposed to
I have a GUI created in powershell, which contains some checkboxes. Later in the script I use the values from the checkboxes to set parameters of a user account, but it seems the script doesn't take the values as intended. I mean, sometimes the account is created with correct values, sometimes not. I wasn't able to discover any pattern when it works and when not.

```<code>$Orig_exec_policy = Get-ExecutionPolicy
Set-ExecutionPolicy Bypass -Force
<# This form was created using POSHGUI.com  a free online gui designer for PowerShell
.NAME
    Untitled
#>

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

#region Window properties
$AD_user_creation                = New-Object system.Windows.Forms.Form
$AD_user_creation.ClientSize     = '480,740'
$AD_user_creation.text           = "AD user creation - WG Mustang"
$AD_user_creation.TopMost        = $false
#endregion

[void]$AD_user_creation.SuspendLayout()

#region Real name of the user
$Display_name_lbl                = New-Object system.Windows.Forms.Label
$Display_name_lbl.text           = "User`'s real name"
$Display_name_lbl.AutoSize       = $true
$Display_name_lbl.width          = 25
$Display_name_lbl.height         = 10
$Display_name_lbl.location       = New-Object System.Drawing.Point(10,10)

$First_name_val                  = New-Object system.Windows.Forms.TextBox
$First_name_val.multiline        = $false
$First_name_val.width            = 120
$First_name_val.height           = 20
$First_name_val.location         = New-Object System.Drawing.Point(200,10)

$Second_name_val                 = New-Object system.Windows.Forms.TextBox
$Second_name_val.multiline       = $false
$Second_name_val.width           = 120
$Second_name_val.height          = 20
$Second_name_val.location        = New-Object System.Drawing.Point(330,10)

$Display_name_val                = New-Object system.Windows.Forms.Label
$Display_name_val.Text           = ""
$Display_name_val.width          = 250
$Display_name_val.height         = 20
$Display_name_val.location       = New-Object System.Drawing.Point(200,40)
#endregion

#region User name of the user
$User_name_lbl                   = New-Object system.Windows.Forms.Label
$User_name_lbl.text              = "User logon name"
$User_name_lbl.AutoSize          = $true
$User_name_lbl.width             = 25
$User_name_lbl.height            = 10
$User_name_lbl.location          = New-Object System.Drawing.Point(10,70)

$User_name_val                   = New-Object system.Windows.Forms.TextBox
$User_name_val.multiline         = $false
$User_name_val.width             = 250
$User_name_val.height            = 20
$User_name_val.location          = New-Object System.Drawing.Point(200,70)
#endregion

#region Account password
$Password_lbl                    = New-Object system.Windows.Forms.Label
$Password_lbl.text               = "Password"
$Password_lbl.AutoSize           = $true
$Password_lbl.width              = 25
$Password_lbl.height             = 10
$Password_lbl.location           = New-Object System.Drawing.Point(10,100)

$Password_ini_val                = New-Object system.Windows.Forms.MaskedTextBox
$Password_ini_val.multiline      = $false
$Password_ini_val.width          = 250
$Password_ini_val.height         = 20
$Password_ini_val.UseSystemPasswordChar = $true
$Password_ini_val.location       = New-Object System.Drawing.Point(200,100)

$Password_conf_val               = New-Object system.Windows.Forms.MaskedTextBox
$Password_conf_val.multiline     = $false
$Password_conf_val.width         = 250
$Password_conf_val.height        = 20
$Password_conf_val.UseSystemPasswordChar = $true
$Password_conf_val.location      = New-Object System.Drawing.Point(200,130)
#endregion

#region Location of the user
$Location_lbl                    = New-Object system.Windows.Forms.Label
$Location_lbl.text               = "Location"
$Location_lbl.AutoSize           = $true
$Location_lbl.width              = 25
$Location_lbl.height             = 10
$Location_lbl.location           = New-Object System.Drawing.Point(10,160)

$Location_val                    = New-Object system.Windows.Forms.TextBox
$Location_val.multiline          = $false
$Location_val.text               = "OU=Users,OU=ADM,DC=Mustangeng,DC=com"
$Location_val.width              = 250
$Location_val.height             = 20
$Location_val.location           = New-Object System.Drawing.Point(200,160)
#endregion

#region Checkboxes
$Must_chg_pass                   = New-Object system.Windows.Forms.CheckBox
$Must_chg_pass.text              = "User must change password at next logon"
$Must_chg_pass.AutoSize          = $false
$Must_chg_pass.width             = 290
$Must_chg_pass.height            = 20
$Must_chg_pass.location          = New-Object System.Drawing.Point(200,190)

$Cannot_chg_pass                 = New-Object system.Windows.Forms.CheckBox
$Cannot_chg_pass.text            = "User cannot change password"
$Cannot_chg_pass.AutoSize        = $false
$Cannot_chg_pass.width           = 250
$Cannot_chg_pass.height          = 20
$Cannot_chg_pass.location        = New-Object System.Drawing.Point(200,220)
$Cannot_chg_pass.Checked         = $true

$Pass_not_expires                = New-Object system.Windows.Forms.CheckBox
$Pass_not_expires.text           = "Password never expires"
$Pass_not_expires.AutoSize       = $false
$Pass_not_expires.width          = 250
$Pass_not_expires.height         = 20
$Pass_not_expires.location       = New-Object System.Drawing.Point(200,250)
$Pass_not_expires.Checked        = $true

$Account_disabled_val            = New-Object system.Windows.Forms.CheckBox
$Account_disabled_val.text       = "Account is active"
$Account_disabled_val.AutoSize   = $false
$Account_disabled_val.width      = 250
$Account_disabled_val.height     = 20
$Account_disabled_val.location   = New-Object System.Drawing.Point(200,280)
$Account_disabled_val.Checked    = $false
#endregion

#region Description
$GECOS_lbl                       = New-Object system.Windows.Forms.Label
$GECOS_lbl.text                  = "Description"
$GECOS_lbl.AutoSize              = $true
$GECOS_lbl.width                 = 25
$GECOS_lbl.height                = 10
$GECOS_lbl.location              = New-Object System.Drawing.Point(10,310)

$GECOS_val                       = New-Object system.Windows.Forms.TextBox
$GECOS_val.multiline             = $false
$GECOS_val.width                 = 250
$GECOS_val.height                = 20
$GECOS_val.location              = New-Object System.Drawing.Point(200,310)
#endregion

#region Group membership
$ADGroups_lbl                    = New-Object system.Windows.Forms.Label
$ADGroups_lbl.text               = "AD Groups"
$ADGroups_lbl.AutoSize           = $true
$ADGroups_lbl.width              = 25
$ADGroups_lbl.height             = 10
$ADGroups_lbl.location           = New-Object System.Drawing.Point(10,340)

$ADGroups_val                    = New-Object system.Windows.Forms.TextBox
$ADGroups_val.multiline          = $true
$ADGroups_val.width              = 250
$ADGroups_val.height             = 160
$ADGroups_val.location           = New-Object System.Drawing.Point(200,340)
#endregion

#region Additional attributes
$Ext_Attribute5_lbl              = New-Object System.Windows.Forms.Label
$Ext_Attribute5_lbl.Text         = "Extension Attribute5"
$Ext_Attribute5_lbl.AutoSize     = $true
$Ext_Attribute5_lbl.Width        = 25
$Ext_Attribute5_lbl.Height       = 10
$Ext_Attribute5_lbl.Location     = New-Object System.Drawing.Point(10,510)

$Ext_Attribute5_val              = New-Object System.Windows.Forms.TextBox
$Ext_Attribute5_val.Text         = "Company name"
$Ext_Attribute5_val.Multiline    = $false
$Ext_Attribute5_val.Width        = 250
$Ext_Attribute5_val.Height       = 20
$Ext_Attribute5_val.Location     = New-Object System.Drawing.Point(200,510)

$Ext_Attribute10_lbl             = New-Object System.Windows.Forms.Label
$Ext_Attribute10_lbl.Text        = "Extension Attribute10"
$Ext_Attribute10_lbl.AutoSize    = $true
$Ext_Attribute10_lbl.Width       = 25
$Ext_Attribute10_lbl.Height      = 10
$Ext_Attribute10_lbl.Location    = New-Object System.Drawing.Point(10,540)

$Ext_Attribute10_val             = New-Object System.Windows.Forms.TextBox
$Ext_Attribute10_val.Text        = "Region"
$Ext_Attribute10_val.Multiline   = $false
$Ext_Attribute10_val.Width       = 250
$Ext_Attribute10_val.Height      = 20
$Ext_Attribute10_val.Location    = New-Object System.Drawing.Point(200,540)

$Ext_Attribute15_lbl             = New-Object System.Windows.Forms.Label
$Ext_Attribute15_lbl.Text        = "Extension Attribute15"
$Ext_Attribute15_lbl.AutoSize    = $true
$Ext_Attribute15_lbl.Width       = 25
$Ext_Attribute15_lbl.Height      = 10
$Ext_Attribute15_lbl.Location    = New-Object System.Drawing.Point(10,570)

$Ext_Attribute15_val             = New-Object System.Windows.Forms.TextBox
$Ext_Attribute15_val.Text        = "EH/WH"
$Ext_Attribute15_val.Multiline   = $false
$Ext_Attribute15_val.Width       = 250
$Ext_Attribute15_val.Height      = 20
$Ext_Attribute15_val.Location    = New-Object System.Drawing.Point(200,570)

$Job_Title_lbl                   = New-Object System.Windows.Forms.Label
$Job_Title_lbl.Text              = "Job title"
$Job_Title_lbl.AutoSize          = $true
$Job_Title_lbl.Width             = 25
$Job_Title_lbl.Height            = 10
$Job_Title_lbl.Location          = New-Object System.Drawing.Point(10,600)

$Job_Title_val                   = New-Object System.Windows.Forms.TextBox
$Job_Title_val.Text              = "NA"
$Job_Title_val.Multiline         = $false
$Job_Title_val.Width             = 250
$Job_Title_val.Height            = 20
$Job_Title_val.Location          = New-Object System.Drawing.Point(200,600)

$Department_lbl                  = New-Object System.Windows.Forms.Label
$Department_lbl.Text             = "Department"
$Department_lbl.AutoSize         = $true
$Department_lbl.Width            = 25
$Department_lbl.Height           = 10
$Department_lbl.Location         = New-Object System.Drawing.Point(10,630)

$Department_val                  = New-Object System.Windows.Forms.TextBox
$Department_val.Text             = "NA"
$Department_val.Multiline        = $false
$Department_val.Width            = 250
$Department_val.Height           = 20
$Department_val.Location         = New-Object System.Drawing.Point(200,630)

$Company_lbl                     = New-Object System.Windows.Forms.Label
$Company_lbl.Text                = "Company"
$Company_lbl.AutoSize            = $true
$Company_lbl.Width               = 25
$Company_lbl.Height              = 10
$Company_lbl.Location            = New-Object System.Drawing.Point(10,660)

$Company_val                     = New-Object System.Windows.Forms.TextBox
$Company_val.Text                = "IBM"
$Company_val.Multiline           = $false
$Company_val.Width               = 250
$Company_val.Height              = 20
$Company_val.Location            = New-Object System.Drawing.Point(200,660)
#endregion

#region Buttons
$Confirm_Button                  = New-Object system.Windows.Forms.Button
$Confirm_Button.BackColor        = "#00ff00"
$Confirm_Button.text             = "OK"
$Confirm_Button.width            = 100
$Confirm_Button.height           = 30
$Confirm_Button.location         = New-Object System.Drawing.Point(200,690)
$Confirm_Button.Font             = 'Microsoft Sans Serif,10,style=Bold'
$Create_ADuser = {
  if ($Password_ini_val.Text -cne $Password_conf_val.Text)
  {
    [System.Windows.MessageBox]::Show("Passwords don't match")
  } elseif ($Password_ini_val.Text.Length -lt 8)
  {
    [System.Windows.MessageBox]::Show("Password is too short")
  } else {
    $password = $Password_ini_val.Text | ConvertTo-SecureString -AsPlainText -Force
    $Display_name = $Display_name_val.Text + " [ADM]"
    New-ADUser -GivenName $First_name_val.Text -Surname $Second_name_val.Text -DisplayName $Display_name -AccountPassword $password -Path $Location_val.Text -Name $User_name_val.Text`
     -CannotChangePassword $Cannot_chg_pass.Checked -PasswordNeverExpires $Pass_not_expires.Checked -ChangePasswordAtLogon $Must_chg_pass.Checked -Enabled $Account_disabled_val.Checked`
     -Description $GECOS_val.Text -OtherAttributes @{'ExtensionAttribute5' = $Ext_Attribute5_val.Text;'ExtensionAttribute9' = "People";'ExtensionAttribute10' = $Ext_Attribute10_val.Text;`
     'ExtensionAttribute11' = "Other";'ExtensionAttribute12' = "No";'ExtensionAttribute14' = "NA";'ExtensionAttribute15' = $Ext_Attribute15_val.Text;'Division' = "WG Mustang"}`
     -Office "NA" -OfficePhone "NA" -Title $Job_Title_val.Text -Department $Department_val.Text -Company $Company_val.Text -SamAccountName $User_name_val.Text -PassThru | `
     Add-ADPrincipalGroupMembership -MemberOf $ADGroups_val.Text
    $AD_user_creation.Close()
  }
}
$Confirm_Button.add_Click($Create_ADuser)

$Cancel_button                   = New-Object system.Windows.Forms.Button
$Cancel_button.BackColor         = "#ff0000"
$Cancel_button.text              = "Cancel"
$Cancel_button.width             = 100
$Cancel_button.height            = 30
$Cancel_button.location          = New-Object System.Drawing.Point(350,690)
$Cancel_button.Font              = 'Microsoft Sans Serif,10,style=Bold'
<#$Cancel = {
    $AD_user_creation.Close()
    exit
}#>
$Cancel_button.add_Click({
    $AD_user_creation.Close()
    exit
})

$AD_user_creation.AcceptButton   = $Confirm_Button
$AD_user_creation.CancelButton   = $Cancel_button
#endregion

$AD_user_creation.controls.AddRange(@($Display_name_lbl,$First_name_val,$Second_name_val,$User_name_lbl,$Display_name_val,$User_name_val,$Password_lbl,$Password_ini_val,$Password_conf_val,$Location_lbl,`
$Location_val,$Must_chg_pass,$Cannot_chg_pass,$Pass_not_expires,$Account_disabled_val,$GECOS_lbl,$GECOS_val,$ADGroups_lbl,$ADGroups_val,$Ext_Attribute5_lbl,$Ext_Attribute5_val,$Ext_Attribute10_lbl,`
$Ext_Attribute10_val,$Ext_Attribute15_lbl,$Ext_Attribute15_val,$Job_Title_lbl,$Job_Title_val,$Department_lbl,$Department_val,$Company_lbl,$Company_val,$Confirm_Button,$Cancel_button))

$showFullName = { $Display_name_val.Text = ($First_name_val.Text + " " + $Second_name_val.Text) }

[void]$Second_name_val.Add_Leave( { & $showFullName } )
[void]$First_name_val.Add_Leave(  { & $showFullName } )

[void]$AD_user_creation.ResumeLayout()

$result = $AD_user_creation.ShowDialog()
[void]$AD_user_creation.Dispose()

Set-ExecutionPolicy $Orig_exec_policy -Force
</code>```

Definitions of checkboxes start at the row 101 and user gets created at the rows 268-272.
The user sometimes gets created as active, sometimes as disabled. And once I notice that even the "user cannot change password" doesn't get checked in the account, even though the value in the form is set to True. I didn't notice any problems with the other checkboxes. Any idea what's happening?

答:
I believe the error stems from the way you use the New-User cmdlet. That piece of code looks complicated enough to not see that there is at least one backtick in the wrong place.

Better use Splatting for this:

```<code>$params = @{
    'GivenName'             = $First_name_val.Text
    'Surname'               = $Second_name_val.Text
    'DisplayName'           = $Display_name
    'AccountPassword'       = $password
    'Path'                  = $Location_val.Text
    'Name'                  = $User_name_val.Text
    'CannotChangePassword'  = $Cannot_chg_pass.Checked
    'PasswordNeverExpires'  = $Pass_not_expires.Checked
    'ChangePasswordAtLogon' = $Must_chg_pass.Checked
    'Enabled'               = $Account_disabled_val.Checked
    'Description'           = $GECOS_val.Text
    'Office'                = "NA"
    'OfficePhone'           = "NA"
    'Title'                 = $Job_Title_val.Text
    'Department'            = $Department_val.Text
    'Company'               = $Company_val.Text
    'SamAccountName'        = $User_name_val.Text
    'OtherAttributes'       = @{'ExtensionAttribute5'  = $Ext_Attribute5_val.Text
                                'ExtensionAttribute9'  = "People"
                                'ExtensionAttribute10' = $Ext_Attribute10_val.Text
                                'ExtensionAttribute11' = "Other"
                                'ExtensionAttribute12' = "No"
                                'ExtensionAttribute14' = "NA"
                                'ExtensionAttribute15' = $Ext_Attribute15_val.Text
                                'Division'             = "WG Mustang"}
    'PassThru'              = $true
}
$newUser = New-ADUser @params
if ($newUser) {
    $newUser | Add-ADPrincipalGroupMembership -MemberOf $ADGroups_val.Text
}
else {
    [System.Windows.MessageBox]::Show("Error creating new user")
}
</code>```

Body:
I have a GUI created in powershell, which contains some checkboxes. Later in the script I use the values from the checkboxes to set parameters of a user account, but it seems the script doesn't take the values as intended. I mean, sometimes the account is created with correct values, sometimes not. I wasn't able to discover any pattern when it works and when not.

$Orig_exec_policy = Get-ExecutionPolicy
Set-ExecutionPolicy Bypass -Force
<# This form was created using POSHGUI.com  a free online gui designer for PowerShell
.NAME
    Untitled
#>

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

#region Window properties
$AD_user_creation                = New-Object system.Windows.Forms.Form
$AD_user_creation.ClientSize     = '480,740'
$AD_user_creation.text           = "AD user creation - WG Mustang"
$AD_user_creation.TopMost        = $false
#endregion

[void]$AD_user_creation.SuspendLayout()

#region Real name of the user
$Display_name_lbl                = New-Object system.Windows.Forms.Label
$Display_name_lbl.text           = "User`'s real name"
$Display_name_lbl.AutoSize       = $true
$Display_name_lbl.width          = 25
$Display_name_lbl.height         = 10
$Display_name_lbl.location       = New-Object System.Drawing.Point(10,10)

$First_name_val                  = New-Object system.Windows.Forms.TextBox
$First_name_val.multiline        = $false
$First_name_val.width            = 120
$First_name_val.height           = 20
$First_name_val.location         = New-Object System.Drawing.Point(200,10)

$Second_name_val                 = New-Object system.Windows.Forms.TextBox
$Second_name_val.multiline       = $false
$Second_name_val.width           = 120
$Second_name_val.height          = 20
$Second_name_val.location        = New-Object System.Drawing.Point(330,10)

$Display_name_val                = New-Object system.Windows.Forms.Label
$Display_name_val.Text           = ""
$Display_name_val.width          = 250
$Display_name_val.height         = 20
$Display_name_val.location       = New-Object System.Drawing.Point(200,40)
#endregion

#region User name of the user
$User_name_lbl                   = New-Object system.Windows.Forms.Label
$User_name_lbl.text              = "User logon name"
$User_name_lbl.AutoSize          = $true
$User_name_lbl.width             = 25
$User_name_lbl.height            = 10
$User_name_lbl.location          = New-Object System.Drawing.Point(10,70)

$User_name_val                   = New-Object system.Windows.Forms.TextBox
$User_name_val.multiline         = $false
$User_name_val.width             = 250
$User_name_val.height            = 20
$User_name_val.location          = New-Object System.Drawing.Point(200,70)
#endregion

#region Account password
$Password_lbl                    = New-Object system.Windows.Forms.Label
$Password_lbl.text               = "Password"
$Password_lbl.AutoSize           = $true
$Password_lbl.width              = 25
$Password_lbl.height             = 10
$Password_lbl.location           = New-Object System.Drawing.Point(10,100)

$Password_ini_val                = New-Object system.Windows.Forms.MaskedTextBox
$Password_ini_val.multiline      = $false
$Password_ini_val.width          = 250
$Password_ini_val.height         = 20
$Password_ini_val.UseSystemPasswordChar = $true
$Password_ini_val.location       = New-Object System.Drawing.Point(200,100)

$Password_conf_val               = New-Object system.Windows.Forms.MaskedTextBox
$Password_conf_val.multiline     = $false
$Password_conf_val.width         = 250
$Password_conf_val.height        = 20
$Password_conf_val.UseSystemPasswordChar = $true
$Password_conf_val.location      = New-Object System.Drawing.Point(200,130)
#endregion

#region Location of the user
$Location_lbl                    = New-Object system.Windows.Forms.Label
$Location_lbl.text               = "Location"
$Location_lbl.AutoSize           = $true
$Location_lbl.width              = 25
$Location_lbl.height             = 10
$Location_lbl.location           = New-Object System.Drawing.Point(10,160)

$Location_val                    = New-Object system.Windows.Forms.TextBox
$Location_val.multiline          = $false
$Location_val.text               = "OU=Users,OU=ADM,DC=Mustangeng,DC=com"
$Location_val.width              = 250
$Location_val.height             = 20
$Location_val.location           = New-Object System.Drawing.Point(200,160)
#endregion

#region Checkboxes
$Must_chg_pass                   = New-Object system.Windows.Forms.CheckBox
$Must_chg_pass.text              = "User must change password at next logon"
$Must_chg_pass.AutoSize          = $false
$Must_chg_pass.width             = 290
$Must_chg_pass.height            = 20
$Must_chg_pass.location          = New-Object System.Drawing.Point(200,190)

$Cannot_chg_pass                 = New-Object system.Windows.Forms.CheckBox
$Cannot_chg_pass.text            = "User cannot change password"
$Cannot_chg_pass.AutoSize        = $false
$Cannot_chg_pass.width           = 250
$Cannot_chg_pass.height          = 20
$Cannot_chg_pass.location        = New-Object System.Drawing.Point(200,220)
$Cannot_chg_pass.Checked         = $true

$Pass_not_expires                = New-Object system.Windows.Forms.CheckBox
$Pass_not_expires.text           = "Password never expires"
$Pass_not_expires.AutoSize       = $false
$Pass_not_expires.width          = 250
$Pass_not_expires.height         = 20
$Pass_not_expires.location       = New-Object System.Drawing.Point(200,250)
$Pass_not_expires.Checked        = $true

$Account_disabled_val            = New-Object system.Windows.Forms.CheckBox
$Account_disabled_val.text       = "Account is active"
$Account_disabled_val.AutoSize   = $false
$Account_disabled_val.width      = 250
$Account_disabled_val.height     = 20
$Account_disabled_val.location   = New-Object System.Drawing.Point(200,280)
$Account_disabled_val.Checked    = $false
#endregion

#region Description
$GECOS_lbl                       = New-Object system.Windows.Forms.Label
$GECOS_lbl.text                  = "Description"
$GECOS_lbl.AutoSize              = $true
$GECOS_lbl.width                 = 25
$GECOS_lbl.height                = 10
$GECOS_lbl.location              = New-Object System.Drawing.Point(10,310)

$GECOS_val                       = New-Object system.Windows.Forms.TextBox
$GECOS_val.multiline             = $false
$GECOS_val.width                 = 250
$GECOS_val.height                = 20
$GECOS_val.location              = New-Object System.Drawing.Point(200,310)
#endregion

#region Group membership
$ADGroups_lbl                    = New-Object system.Windows.Forms.Label
$ADGroups_lbl.text               = "AD Groups"
$ADGroups_lbl.AutoSize           = $true
$ADGroups_lbl.width              = 25
$ADGroups_lbl.height             = 10
$ADGroups_lbl.location           = New-Object System.Drawing.Point(10,340)

$ADGroups_val                    = New-Object system.Windows.Forms.TextBox
$ADGroups_val.multiline          = $true
$ADGroups_val.width              = 250
$ADGroups_val.height             = 160
$ADGroups_val.location           = New-Object System.Drawing.Point(200,340)
#endregion

#region Additional attributes
$Ext_Attribute5_lbl              = New-Object System.Windows.Forms.Label
$Ext_Attribute5_lbl.Text         = "Extension Attribute5"
$Ext_Attribute5_lbl.AutoSize     = $true
$Ext_Attribute5_lbl.Width        = 25
$Ext_Attribute5_lbl.Height       = 10
$Ext_Attribute5_lbl.Location     = New-Object System.Drawing.Point(10,510)

$Ext_Attribute5_val              = New-Object System.Windows.Forms.TextBox
$Ext_Attribute5_val.Text         = "Company name"
$Ext_Attribute5_val.Multiline    = $false
$Ext_Attribute5_val.Width        = 250
$Ext_Attribute5_val.Height       = 20
$Ext_Attribute5_val.Location     = New-Object System.Drawing.Point(200,510)

$Ext_Attribute10_lbl             = New-Object System.Windows.Forms.Label
$Ext_Attribute10_lbl.Text        = "Extension Attribute10"
$Ext_Attribute10_lbl.AutoSize    = $true
$Ext_Attribute10_lbl.Width       = 25
$Ext_Attribute10_lbl.Height      = 10
$Ext_Attribute10_lbl.Location    = New-Object System.Drawing.Point(10,540)

$Ext_Attribute10_val             = New-Object System.Windows.Forms.TextBox
$Ext_Attribute10_val.Text        = "Region"
$Ext_Attribute10_val.Multiline   = $false
$Ext_Attribute10_val.Width       = 250
$Ext_Attribute10_val.Height      = 20
$Ext_Attribute10_val.Location    = New-Object System.Drawing.Point(200,540)

$Ext_Attribute15_lbl             = New-Object System.Windows.Forms.Label
$Ext_Attribute15_lbl.Text        = "Extension Attribute15"
$Ext_Attribute15_lbl.AutoSize    = $true
$Ext_Attribute15_lbl.Width       = 25
$Ext_Attribute15_lbl.Height      = 10
$Ext_Attribute15_lbl.Location    = New-Object System.Drawing.Point(10,570)

$Ext_Attribute15_val             = New-Object System.Windows.Forms.TextBox
$Ext_Attribute15_val.Text        = "EH/WH"
$Ext_Attribute15_val.Multiline   = $false
$Ext_Attribute15_val.Width       = 250
$Ext_Attribute15_val.Height      = 20
$Ext_Attribute15_val.Location    = New-Object System.Drawing.Point(200,570)

$Job_Title_lbl                   = New-Object System.Windows.Forms.Label
$Job_Title_lbl.Text              = "Job title"
$Job_Title_lbl.AutoSize          = $true
$Job_Title_lbl.Width             = 25
$Job_Title_lbl.Height            = 10
$Job_Title_lbl.Location          = New-Object System.Drawing.Point(10,600)

$Job_Title_val                   = New-Object System.Windows.Forms.TextBox
$Job_Title_val.Text              = "NA"
$Job_Title_val.Multiline         = $false
$Job_Title_val.Width             = 250
$Job_Title_val.Height            = 20
$Job_Title_val.Location          = New-Object System.Drawing.Point(200,600)

$Department_lbl                  = New-Object System.Windows.Forms.Label
$Department_lbl.Text             = "Department"
$Department_lbl.AutoSize         = $true
$Department_lbl.Width            = 25
$Department_lbl.Height           = 10
$Department_lbl.Location         = New-Object System.Drawing.Point(10,630)

$Department_val                  = New-Object System.Windows.Forms.TextBox
$Department_val.Text             = "NA"
$Department_val.Multiline        = $false
$Department_val.Width            = 250
$Department_val.Height           = 20
$Department_val.Location         = New-Object System.Drawing.Point(200,630)

$Company_lbl                     = New-Object System.Windows.Forms.Label
$Company_lbl.Text                = "Company"
$Company_lbl.AutoSize            = $true
$Company_lbl.Width               = 25
$Company_lbl.Height              = 10
$Company_lbl.Location            = New-Object System.Drawing.Point(10,660)

$Company_val                     = New-Object System.Windows.Forms.TextBox
$Company_val.Text                = "IBM"
$Company_val.Multiline           = $false
$Company_val.Width               = 250
$Company_val.Height              = 20
$Company_val.Location            = New-Object System.Drawing.Point(200,660)
#endregion

#region Buttons
$Confirm_Button                  = New-Object system.Windows.Forms.Button
$Confirm_Button.BackColor        = "#00ff00"
$Confirm_Button.text             = "OK"
$Confirm_Button.width            = 100
$Confirm_Button.height           = 30
$Confirm_Button.location         = New-Object System.Drawing.Point(200,690)
$Confirm_Button.Font             = 'Microsoft Sans Serif,10,style=Bold'
$Create_ADuser = {
  if ($Password_ini_val.Text -cne $Password_conf_val.Text)
  {
    [System.Windows.MessageBox]::Show("Passwords don't match")
  } elseif ($Password_ini_val.Text.Length -lt 8)
  {
    [System.Windows.MessageBox]::Show("Password is too short")
  } else {
    $password = $Password_ini_val.Text | ConvertTo-SecureString -AsPlainText -Force
    $Display_name = $Display_name_val.Text + " [ADM]"
    New-ADUser -GivenName $First_name_val.Text -Surname $Second_name_val.Text -DisplayName $Display_name -AccountPassword $password -Path $Location_val.Text -Name $User_name_val.Text`
     -CannotChangePassword $Cannot_chg_pass.Checked -PasswordNeverExpires $Pass_not_expires.Checked -ChangePasswordAtLogon $Must_chg_pass.Checked -Enabled $Account_disabled_val.Checked`
     -Description $GECOS_val.Text -OtherAttributes @{'ExtensionAttribute5' = $Ext_Attribute5_val.Text;'ExtensionAttribute9' = "People";'ExtensionAttribute10' = $Ext_Attribute10_val.Text;`
     'ExtensionAttribute11' = "Other";'ExtensionAttribute12' = "No";'ExtensionAttribute14' = "NA";'ExtensionAttribute15' = $Ext_Attribute15_val.Text;'Division' = "WG Mustang"}`
     -Office "NA" -OfficePhone "NA" -Title $Job_Title_val.Text -Department $Department_val.Text -Company $Company_val.Text -SamAccountName $User_name_val.Text -PassThru | `
     Add-ADPrincipalGroupMembership -MemberOf $ADGroups_val.Text
    $AD_user_creation.Close()
  }
}
$Confirm_Button.add_Click($Create_ADuser)

$Cancel_button                   = New-Object system.Windows.Forms.Button
$Cancel_button.BackColor         = "#ff0000"
$Cancel_button.text              = "Cancel"
$Cancel_button.width             = 100
$Cancel_button.height            = 30
$Cancel_button.location          = New-Object System.Drawing.Point(350,690)
$Cancel_button.Font              = 'Microsoft Sans Serif,10,style=Bold'
<#$Cancel = {
    $AD_user_creation.Close()
    exit
}#>
$Cancel_button.add_Click({
    $AD_user_creation.Close()
    exit
})

$AD_user_creation.AcceptButton   = $Confirm_Button
$AD_user_creation.CancelButton   = $Cancel_button
#endregion

$AD_user_creation.controls.AddRange(@($Display_name_lbl,$First_name_val,$Second_name_val,$User_name_lbl,$Display_name_val,$User_name_val,$Password_lbl,$Password_ini_val,$Password_conf_val,$Location_lbl,`
$Location_val,$Must_chg_pass,$Cannot_chg_pass,$Pass_not_expires,$Account_disabled_val,$GECOS_lbl,$GECOS_val,$ADGroups_lbl,$ADGroups_val,$Ext_Attribute5_lbl,$Ext_Attribute5_val,$Ext_Attribute10_lbl,`
$Ext_Attribute10_val,$Ext_Attribute15_lbl,$Ext_Attribute15_val,$Job_Title_lbl,$Job_Title_val,$Department_lbl,$Department_val,$Company_lbl,$Company_val,$Confirm_Button,$Cancel_button))

$showFullName = { $Display_name_val.Text = ($First_name_val.Text + " " + $Second_name_val.Text) }

[void]$Second_name_val.Add_Leave( { & $showFullName } )
[void]$First_name_val.Add_Leave(  { & $showFullName } )

[void]$AD_user_creation.ResumeLayout()

$result = $AD_user_creation.ShowDialog()
[void]$AD_user_creation.Dispose()

Set-ExecutionPolicy $Orig_exec_policy -Force

Definitions of checkboxes start at the row 101 and user gets created at the rows 268-272.
The user sometimes gets created as active, sometimes as disabled. And once I notice that even the "user cannot change password" doesn't get checked in the account, even though the value in the form is set to True. I didn't notice any problems with the other checkboxes. Any idea what's happening?

Body:
I believe the error stems from the way you use the New-User cmdlet. That piece of code looks complicated enough to not see that there is at least one backtick in the wrong place.

Better use Splatting for this:

$params = @{
    'GivenName'             = $First_name_val.Text
    'Surname'               = $Second_name_val.Text
    'DisplayName'           = $Display_name
    'AccountPassword'       = $password
    'Path'                  = $Location_val.Text
    'Name'                  = $User_name_val.Text
    'CannotChangePassword'  = $Cannot_chg_pass.Checked
    'PasswordNeverExpires'  = $Pass_not_expires.Checked
    'ChangePasswordAtLogon' = $Must_chg_pass.Checked
    'Enabled'               = $Account_disabled_val.Checked
    'Description'           = $GECOS_val.Text
    'Office'                = "NA"
    'OfficePhone'           = "NA"
    'Title'                 = $Job_Title_val.Text
    'Department'            = $Department_val.Text
    'Company'               = $Company_val.Text
    'SamAccountName'        = $User_name_val.Text
    'OtherAttributes'       = @{'ExtensionAttribute5'  = $Ext_Attribute5_val.Text
                                'ExtensionAttribute9'  = "People"
                                'ExtensionAttribute10' = $Ext_Attribute10_val.Text
                                'ExtensionAttribute11' = "Other"
                                'ExtensionAttribute12' = "No"
                                'ExtensionAttribute14' = "NA"
                                'ExtensionAttribute15' = $Ext_Attribute15_val.Text
                                'Division'             = "WG Mustang"}
    'PassThru'              = $true
}
$newUser = New-ADUser @params
if ($newUser) {
    $newUser | Add-ADPrincipalGroupMembership -MemberOf $ADGroups_val.Text
}
else {
    [System.Windows.MessageBox]::Show("Error creating new user")
}


问:
How do I render the values returned from a computed property in Ember.js?
I have the following code in the template of my component:

```<code>      <th scope="row">{{@order.id}}</th>
      <td>Name: {{@order.customer_name}}
      </td>
      <td>Delivery address: {{@order.address}}
          Products in order: {{@order.products}}
          Items: {{items}}
      <td>{{@order.total_price}}$</td>
</tr>
</code>```

And I have my computed property which should return and render each product name in the array of objects returned from the database:

```<code>items: computed('order.products', function() {
        let products = this.get('order.products');
        products.forEach(product => {
            for(let i=0; i<products.length; i++){
                return console.log(products[i].name);
            }
        });
    }),
</code>```

And when I run the following everything works okay and the names are displayed in the console like this:

```<code>Cheese on toast
3 Pizza
2 Macaroons bowl
</code>```

But when I try to remove console.log and just return products[i].name, nothing seems to be returned. Am I missing something or trying to render it on my page incorrectly?

答:
From the snippet, I'm presuming you want to return only the name of the products from the items computed property. If so, then there is some issue here is with the handling of loops and not with the actual computed property.

So in your case, you can use map to filter out only the name of the product from the products array.

items: computed('order.products', function() {
  let products = this.get('order.products');
  let productNames = products.map((product) => {
    return product.name;
  });
  return productNames;
})
```

Also, the computed property only retain the value that was returned from the definition. Thus you need to return the value explicitly as shown in the above snippet (return productNames).

Body:
I have the following code in the template of my component:

      {{@order.id}}
      Name: {{@order.customer_name}}

      Delivery address: {{@order.address}}
          Products in order: {{@order.products}}
          Items: {{items}}
      {{@order.total_price}}$

And I have my computed property which should return and render each product name in the array of objects returned from the database:

items: computed('order.products', function() {
        let products = this.get('order.products');
        products.forEach(product => {
            for(let i=0; i<products.length; i++){
                return console.log(products[i].name);
            }
        });
    }),

And when I run the following everything works okay and the names are displayed in the console like this:

Cheese on toast
3 Pizza
2 Macaroons bowl

But when I try to remove console.log and just return products[i].name, nothing seems to be returned. Am I missing something or trying to render it on my page incorrectly?

Body:
From the snippet, I'm presuming you want to return only the name of the products from the items computed property. If so, then there is some issue here is with the handling of loops and not with the actual computed property.

So in your case, you can use map to filter out only the name of the product from the products array.

items: computed('order.products', function() {
  let products = this.get('order.products');
  let productNames = products.map((product) => {
    return product.name;
  });
  return productNames;
})

Also, the computed property only retain the value that was returned from the definition. Thus you need to return the value explicitly as shown in the above snippet (return productNames).


问:
Upload photo graphql by Flutter
I use https://pub.dev/packages/graphql_flutter package to upload Photos. It worked well but after the upgrade of packages, it crushed. The error

```<code>I/flutter (12390): GraphQL Errors:
I/flutter (12390): Variable "$uploadPhoto" got invalid value {};
Expected type Upload. Upload value invalid.: Undefined location
</code>```

Also, maybe the problem on backEnd side
Node js code

or maybe problem on Flutter side
Flutter code
I use https://pub.dev/packages/multi_image_picker

Mutation

```<code> mutation (
       $uploadPhoto:Upload
       $childServiceIds: [String!]
       $executors: [String!]
       $institutionId: String!
       $description:String!
       $price: Float!
       $name:String!
      ){
      createService(
        institutionId: $institutionId
        description: $description
        iconImage: $uploadPhoto
        name: $name
        price: $price
        token:""
        childServiceIds: $childServiceIds
        executors: $executors
      ){
        services{
          _id
                    name
            price
            description
            childServiceIds
            iconLogoUrl
        }
    }
      }
</code>```

答:
You have no null check.

Possibly uploadPhoto is null and your end up in type mismatch.

PS share method dart code in text not in picture.

Title: Upload photo graphql by Flutter

Body:
I use https://pub.dev/packages/graphql_flutter package to upload Photos. It worked well but after the upgrade of packages, it crushed. The error

I/flutter (12390): GraphQL Errors:
I/flutter (12390): Variable "$uploadPhoto" got invalid value {};
Expected type Upload. Upload value invalid.: Undefined location

Also, maybe the problem on backEnd side
Node js code

or maybe problem on Flutter side
Flutter code
I use https://pub.dev/packages/multi_image_picker

Mutation

 mutation (
       $uploadPhoto:Upload
       $childServiceIds: [String!]
       $executors: [String!]
       $institutionId: String!
       $description:String!
       $price: Float!
       $name:String!
      ){
      createService(
        institutionId: $institutionId
        description: $description
        iconImage: $uploadPhoto
        name: $name
        price: $price
        token:""
        childServiceIds: $childServiceIds
        executors: $executors
      ){
        services{
          _id
                    name
            price
            description
            childServiceIds
            iconLogoUrl
        }
    }
      }


问:
how to close a bootstrap modal with the browser back button instead of going back a page?`
I have found this an issue with smartphones and it can relate to desktops. We have 'modded' our bootstrap modal to be responsive, however when displayed on a smartphone it is in full screen, the user assumes the modal is a page and clicks back to 'close' it. We have included the in the top right X but would also like the back button to close the modal. Anyone have any ideas?

Thanks

答:
You can do that by writing a few lines of code however you'll need a better method in order to achieve a consistent result in which pressing the browser/mobile back button AND hiding modal using [x] button or clicking outside the modal work identical.

I consider the following method a better solution in that sense. it works on modern browsers (HTML5 Javascript ES6) with Bootstrap 4.0 or higher but you'd be able to adapt it for older browser support.

1- Assign a data-hash="#some-hash" attribute to all of the modals that you want to close via browser back button.

2- the block responsible for appending hash to the url

```<code>// Add hash to the URL on open modal event
$('.modal').on('shown.bs.modal', function() {
    if (typeof(this.dataset.hash) !== 'undefined') {
        history.pushState(null, null, this.dataset.hash)
    }
})
</code>```

3- listen to hide.bs.modal event and determine if the back button is pressed or not

```<code>// trigger browser back button when the modal is dismissed (using x button etc...)
$('.modal').on('hide.bs.modal', function(event) {
    if (this.dataset.pushback !== 'true') {
        event.preventDefault()
        history.back()
    }
    this.dataset.pushback = ''
})
</code>```

4- the block responsible to handle browser back button. we add the pushback attribute as a flag to indicate back button press event.

```<code>// Close current open modal (if any) on browser back event
window.onpopstate = function() {
    let open_modal = document.querySelector('.modal.show')
    if (open_modal) {
        open_modal.dataset.pushback = 'true';
        $(open_modal).modal('hide')
    }
}
</code>```

Body:
You can do that by writing a few lines of code however you'll need a better method in order to achieve a consistent result in which pressing the browser/mobile back button AND hiding modal using [x] button or clicking outside the modal work identical.

I consider the following method a better solution in that sense. it works on modern browsers (HTML5 Javascript ES6) with Bootstrap 4.0 or higher but you'd be able to adapt it for older browser support.

1- Assign a data-hash="#some-hash" attribute to all of the modals that you want to close via browser back button.

2- the block responsible for appending hash to the url

// Add hash to the URL on open modal event
$('.modal').on('shown.bs.modal', function() {
    if (typeof(this.dataset.hash) !== 'undefined') {
        history.pushState(null, null, this.dataset.hash)
    }
})

3- listen to hide.bs.modal event and determine if the back button is pressed or not

// trigger browser back button when the modal is dismissed (using x button etc...)
$('.modal').on('hide.bs.modal', function(event) {
    if (this.dataset.pushback !== 'true') {
        event.preventDefault()
        history.back()
    }
    this.dataset.pushback = ''
})

4- the block responsible to handle browser back button. we add the pushback attribute as a flag to indicate back button press event.

// Close current open modal (if any) on browser back event
window.onpopstate = function() {
    let open_modal = document.querySelector('.modal.show')
    if (open_modal) {
        open_modal.dataset.pushback = 'true';
        $(open_modal).modal('hide')
    }
}


问:
didReceiveRemoteNotification Not Working when clicked on notification (background) but when working when app is Foreground
Need some solutions regarding the PUSH Notifications . I tried different solutions from the stack but couldn't worked for me !

My issue is that when I triggered the notfication from my PHP script the notification itself get triggerred . The thingon clicking the notification i want  to navigate to a New View from my app .

When the app is in the Background mode and clicking on notification does nothing with a completion handler warning , but when the app is in the active state and triggering notification does the work and it navigates to the other view
Please revert for this Issue i have attached the code below.

ERROR when notifications are clicked on background mode
 Warning: UNUserNotificationCenter delegate received call to -userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: but the completion handler was never called.

Any help is Appreciated

```<code>func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],

                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // If you are receiving a notification message while your app is in the background,

        let application = UIApplication.shared
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "LaunchScreenViewController")
        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()

        if let messageID = userInfo[gcmMessageIDKey] {

            print("Message ID: \(messageID)")

        }

        // Print full message.

        print(userInfo)

        print("Hello u have entered through Push  notification ")

        completionHandler(UIBackgroundFetchResult.newData)
    }
</code>```

答:
Hello I just got solution for my answer !!
I tried navigation to the other view in the usernotificationcenter extension method And it worked .

```<code>extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("Entry through the Notification")

        let application = UIApplication.shared
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "stationListVC")
        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()

        if response.actionIdentifier == "remindLater" {
            let newDate = Date(timeInterval: 900, since: Date())
            scheduleNotification(at: newDate)
        }
    }
}
</code>```

Thanks all for the HELP ;)

Body:
Need some solutions regarding the PUSH Notifications . I tried different solutions from the stack but couldn't worked for me !

My issue is that when I triggered the notfication from my PHP script the notification itself get triggerred . The thingon clicking the notification i want  to navigate to a New View from my app .

When the app is in the Background mode and clicking on notification does nothing with a completion handler warning , but when the app is in the active state and triggering notification does the work and it navigates to the other view
Please revert for this Issue i have attached the code below.

ERROR when notifications are clicked on background mode
 Warning: UNUserNotificationCenter delegate received call to -userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: but the completion handler was never called.

Any help is Appreciated

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],

                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // If you are receiving a notification message while your app is in the background,

        let application = UIApplication.shared
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "LaunchScreenViewController")
        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()

        if let messageID = userInfo[gcmMessageIDKey] {

            print("Message ID: \(messageID)")

        }

        // Print full message.

        print(userInfo)

        print("Hello u have entered through Push  notification ")

        completionHandler(UIBackgroundFetchResult.newData)
    }

Body:
Hello I just got solution for my answer !!
I tried navigation to the other view in the usernotificationcenter extension method And it worked .

extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("Entry through the Notification")

        let application = UIApplication.shared
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController = storyboard.instantiateViewController(withIdentifier: "stationListVC")
        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()

        if response.actionIdentifier == "remindLater" {
            let newDate = Date(timeInterval: 900, since: Date())
            scheduleNotification(at: newDate)
        }
    }
}

Thanks all for the HELP ;)