问:
How to show ProgressBar in centre of screen regardless layout types
I wonder if there is any way to show a ProgressBar at the middle of the screen programatically regardless the type of layout of the current Activity like a toast can be shown like,

```<code>Toast toast = Toast.makeText(Activity.this,"Sample toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
</code>```

答:
Here is what I use , I take app icon and rotate it in middle of the screen to show as progress , it looks better than just showing progress bar . If you still want progressbar just replace ImageView with ProgressBar

```<code>import android.animation.ObjectAnimator
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.Gravity
import android.view.ViewGroup
import android.view.Window
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView

class MyProgressDialog : Dialog {
    private var dialog: Dialog? = null
    var imageView: ImageView? = null
        internal set
    internal var textView: TextView? = null

    constructor(context: Context) : super(context) {
        init(context)
    }

    constructor(context: Context, themeResId: Int) : super(context, themeResId) {
        init(context)
    }

    protected constructor(context: Context, cancelable: Boolean, cancelListener: DialogInterface.OnCancelListener?) : super(context, cancelable, cancelListener) {
        init(context)
    }

    fun init(context: Context) {

        dialog = this

        dialog!!.window!!.requestFeature(Window.FEATURE_NO_TITLE)
        dialog!!.setCancelable(false)

        val relativeLayout = RelativeLayout(context)
        val layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        relativeLayout.layoutParams = layoutParams

        val layoutParams_for_linear = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        layoutParams_for_linear.addRule(RelativeLayout.CENTER_IN_PARENT)
        val linearLayout = LinearLayout(context)
        linearLayout.layoutParams = layoutParams_for_linear
        linearLayout.orientation = LinearLayout.VERTICAL

        relativeLayout.addView(linearLayout)

        val layoutParams_Linear = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        layoutParams_Linear.gravity = Gravity.CENTER

        imageView = ImageView(context)
        imageView!!.setImageResource(R.mipmap.ic_launcher)
        imageView!!.layoutParams = layoutParams_Linear

        linearLayout.addView(imageView)

        textView = TextView(context)
        textView!!.layoutParams = layoutParams_for_linear
        textView!!.setTextColor(Color.parseColor("#ffffff"))
        textView!!.textSize = 18f
        linearLayout.addView(textView)

        val animation = ObjectAnimator.ofFloat(imageView, "rotationY", 0.0f, 360f)
        animation.duration = 2500
        animation.repeatCount = ObjectAnimator.INFINITE
        animation.interpolator = AccelerateDecelerateInterpolator()
        animation.start()

        dialog!!.window!!.setContentView(relativeLayout, layoutParams)
        dialog!!.window!!.setBackgroundDrawable(
                ColorDrawable(android.graphics.Color.TRANSPARENT))

    }

    fun setProgressMessage(message: String): Dialog {

        if (textView != null)
            textView!!.text = message

        return this
    }

    fun setProgressMessageSize(size: Int): Dialog {

        if (textView != null)
            textView!!.textSize = size.toFloat()

        return this
    }

    fun setProgressMessageColour(colour: Int): Dialog {

        if (textView != null)
            textView!!.setTextColor(colour)

        return this
    }

    fun setIcon(resId: Int): Dialog {

        if (imageView != null) {
            imageView!!.setImageResource(resId)

        }

        return this
    }

}
</code>```

To show and hide Progress I use these methods

```<code>private var dialog: Dialog? = null

fun showProgress(context: Context?): Dialog? {
    if (context is Activity && (dialog == null || !dialog!!.isShowing)) {
        try {
            dialog = MyProgressDialog(context)
            dialog?.show()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    return dialog
}

fun dismissProgress() {
    try {
        if (dialog != null && dialog!!.isShowing) {
            dialog?.dismiss()
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    dialog = null
}
</code>```

Body:
I wonder if there is any way to show a ProgressBar at the middle of the screen programatically regardless the type of layout of the current Activity like a toast can be shown like,

Toast toast = Toast.makeText(Activity.this,"Sample toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();

Body:
Here is what I use , I take app icon and rotate it in middle of the screen to show as progress , it looks better than just showing progress bar . If you still want progressbar just replace ImageView with ProgressBar

import android.animation.ObjectAnimator
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.Gravity
import android.view.ViewGroup
import android.view.Window
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView

class MyProgressDialog : Dialog {
    private var dialog: Dialog? = null
    var imageView: ImageView? = null
        internal set
    internal var textView: TextView? = null

    constructor(context: Context) : super(context) {
        init(context)
    }

    constructor(context: Context, themeResId: Int) : super(context, themeResId) {
        init(context)
    }

    protected constructor(context: Context, cancelable: Boolean, cancelListener: DialogInterface.OnCancelListener?) : super(context, cancelable, cancelListener) {
        init(context)
    }

    fun init(context: Context) {

        dialog = this

        dialog!!.window!!.requestFeature(Window.FEATURE_NO_TITLE)
        dialog!!.setCancelable(false)

        val relativeLayout = RelativeLayout(context)
        val layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        relativeLayout.layoutParams = layoutParams

        val layoutParams_for_linear = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        layoutParams_for_linear.addRule(RelativeLayout.CENTER_IN_PARENT)
        val linearLayout = LinearLayout(context)
        linearLayout.layoutParams = layoutParams_for_linear
        linearLayout.orientation = LinearLayout.VERTICAL

        relativeLayout.addView(linearLayout)

        val layoutParams_Linear = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        layoutParams_Linear.gravity = Gravity.CENTER

        imageView = ImageView(context)
        imageView!!.setImageResource(R.mipmap.ic_launcher)
        imageView!!.layoutParams = layoutParams_Linear

        linearLayout.addView(imageView)

        textView = TextView(context)
        textView!!.layoutParams = layoutParams_for_linear
        textView!!.setTextColor(Color.parseColor("#ffffff"))
        textView!!.textSize = 18f
        linearLayout.addView(textView)

        val animation = ObjectAnimator.ofFloat(imageView, "rotationY", 0.0f, 360f)
        animation.duration = 2500
        animation.repeatCount = ObjectAnimator.INFINITE
        animation.interpolator = AccelerateDecelerateInterpolator()
        animation.start()

        dialog!!.window!!.setContentView(relativeLayout, layoutParams)
        dialog!!.window!!.setBackgroundDrawable(
                ColorDrawable(android.graphics.Color.TRANSPARENT))

    }

    fun setProgressMessage(message: String): Dialog {

        if (textView != null)
            textView!!.text = message

        return this
    }

    fun setProgressMessageSize(size: Int): Dialog {

        if (textView != null)
            textView!!.textSize = size.toFloat()

        return this
    }

    fun setProgressMessageColour(colour: Int): Dialog {

        if (textView != null)
            textView!!.setTextColor(colour)

        return this
    }

    fun setIcon(resId: Int): Dialog {

        if (imageView != null) {
            imageView!!.setImageResource(resId)

        }

        return this
    }

}

To show and hide Progress I use these methods

private var dialog: Dialog? = null

fun showProgress(context: Context?): Dialog? {
    if (context is Activity && (dialog == null || !dialog!!.isShowing)) {
        try {
            dialog = MyProgressDialog(context)
            dialog?.show()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    return dialog
}

fun dismissProgress() {
    try {
        if (dialog != null && dialog!!.isShowing) {
            dialog?.dismiss()
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
    dialog = null
}


来源: stackexchange

问:
How do I properly encode a form in php
On my site users can add content to the database via a form. I want the users to be able to type anything in the form and for it all to be added to the database how they have entered it. At the moment I'm getting problems with a number of characters, namely slashes, &, ? etc.

What is the best way to allow all characters to be added to the database correctly?

Also, do you have to decode them when displaying them for it to work correctly? If so, how do I do that?

答:
When saving, use mysql_real_escape_string (or PDO) to protect against SQL injection attacks. This will make it possible to write quotes and backslashes without destroying the SQL query.

```<code><?php
$text = mysql_real_escape_string($_POST['text']);
mysql_query('INSERT INTO table(text) VALUES("'.$text.'")');
?>
</code>```

When printing the data to a browser (with echo), first run it through htmlspecialchars to disable HTML and solve your current problem:

```<code><?php
// ...fetch $text from db here...
echo htmlspecialchars($text);
?>
</code>```

ContentLicense: CC BY-SA 3.0

Title: How do I properly encode a form in php

Body:
When saving, use mysql_real_escape_string (or PDO) to protect against SQL injection attacks. This will make it possible to write quotes and backslashes without destroying the SQL query.

<?php
$text = mysql_real_escape_string($_POST['text']);
mysql_query('INSERT INTO table(text) VALUES("'.$text.'")');
?>

When printing the data to a browser (with echo), first run it through htmlspecialchars to disable HTML and solve your current problem:

<?php
// ...fetch $text from db here...
echo htmlspecialchars($text);
?>


问:
Symfony 2.8 -> 3.4 Upgrade IsGranted('IS_AUTHENTICATED_ANONYMOUSLY') Throws Errors
I'm in the process of upgrading Symfony from 2.8 to 3.4 and I have a Authentication Listener.

The constructor of the listener

```<code>  public function __construct(EntityManager $entityManager, SessionInterface $session, Security $security, LoggerInterface $logger, Redis $redis, $secret)
    {
        $this->entityManager    = $entityManager;
        $this->session          = $session;
        $this->security         = $security;
        $this->logger           = $logger;
        $this->redis            = $redis;
        $this->secret           = $secret;
    }
</code>```

On Request Function which is calling in listener

```<code>       public function onRequest(GetResponseEvent $event)
        {

        //Validate token

        //Get Authorization Header
        $headers = $event->getRequest()->headers;
        $authHeader = $headers->get('Authorization');

        //Check if Header value starts with 'Bearer'
        if($this->startsWith($authHeader, self::$BEARER_HEADER)) {

                // Allow request to be processed by controllers
               //token handler

        } else {

            $securityContext = $this->security;
            if ($securityContext->isGranted('IS_AUTHENTICATED_ANONYMOUSLY')) {
                return;
            } else {
                throw new SessionTimeoutException();
            }

        }
    }
</code>```

Service.yml

```<code>app.token_listener:
    class: Insead\MIMBundle\Listener\AuthTokenListener
    arguments: ["@doctrine.orm.entity_manager", "@session", "@security.helper", "@logger", "@redis.authtoken", "%secret%"]
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onRequest, priority: 0 }
</code>```

ACL list entry  - security.php

```<code>  'access_control' => array(
       array('path' => '^/api/(.*?)/login', 'role'=>'IS_AUTHENTICATED_ANONYMOUSLY'),
    )
</code>```

im trying to access login route with username and password but i get following error

```<code>GENERAL EXCEPTION: The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. in

/var/www/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Authorization/AuthorizationChecker.php line 55
Exception caught by Listener::
[
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Security.php",
    "line": 65,
    "function": "isGranted",
    "class": "Symfony\\Component\\Security\\Core\\Authorization\\AuthorizationChecker",
    "type": "->",
    "args": [
      "IS_AUTHENTICATED_ANONYMOUSLY",
      null
    ]
  },
  {
    "file": "/var/www/src/Insead/MIMBundle/Listener/AuthTokenListener.php",
    "line": 135,
    "function": "isGranted",
    "class": "Symfony\\Component\\Security\\Core\\Security",
    "type": "->",
    "args": [
      "IS_AUTHENTICATED_ANONYMOUSLY"
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/EventDispatcher.php",
    "line": 212,
    "function": "onRequest",
    "class": "Insead\\MIMBundle\\Listener\\AuthTokenListener",
    "type": "->",
    "args": [
      null,
      "kernel.request",
      null
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/EventDispatcher.php",
    "line": 44,
    "function": "doDispatch",
    "class": "Symfony\\Component\\EventDispatcher\\EventDispatcher",
    "type": "->",
    "args": [
      [
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onRequest"
        ],
        [
          null,
          "onController"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "configure"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onRequest"
        ]
      ],
      "kernel.request",
      null
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php",
    "line": 127,
    "function": "dispatch",
    "class": "Symfony\\Component\\EventDispatcher\\EventDispatcher",
    "type": "->",
    "args": [
      "kernel.request",
      null
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php",
    "line": 68,
    "function": "handleRaw",
    "class": "Symfony\\Component\\HttpKernel\\HttpKernel",
    "type": "->",
    "args": [
      {
        "attributes": null,
        "request": null,
        "query": null,
        "server": null,
        "files": null,
        "cookies": null,
        "headers": null
      },
      1
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php",
    "line": 200,
    "function": "handle",
    "class": "Symfony\\Component\\HttpKernel\\HttpKernel",
    "type": "->",
    "args": [
      {
        "attributes": null,
        "request": null,
        "query": null,
        "server": null,
        "files": null,
        "cookies": null,
        "headers": null
      },
      1,
      true
    ]
  },
  {
    "file": "/var/www/web/app.php",
    "line": 29,
    "function": "handle",
    "class": "Symfony\\Component\\HttpKernel\\Kernel",
    "type": "->",
    "args": [
      {
        "attributes": null,
        "request": null,
        "query": null,
        "server": null,
        "files": null,
        "cookies": null,
        "headers": null
      }
    ]
  }
]
</code>```

I have spend days on this and i still couldn't figure it out to fix it.

Im sorry if this is already answered question i tried to search and i tried things which were mentioned in various posts and it didn't resolve it. im new to symfony too.

Full Security.php

https://www.codepile.net/pile/7O1LJkpv

AuthTokenListner.php

https://www.codepile.net/pile/Xv1ZMlAP

答:
Issue was with the priority order.

thanks @cerad for giving a clue about it

```<code>bin/console debug:event-dispatcher kernel.request
</code>```

helped to solve the issue. i was using

```<code>tags:
        - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse, priority: 10 }
</code>```

in Services.yml and it had a conflict with the

```<code>getSubscribedEvents()
</code>```

therefore i have removed  tags and only kept

```<code>public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::REQUEST  => array('onKernelRequest', 10),
        );
    }
</code>```

then i moved authentication listener to the down by giving high priority to other two listeners as same as it was there in symfony 2.8

Thanks all for helping me out on this specially @Pie @Cerad and @BoShurik

ContentLicense: CC BY-SA 4.0

Body:
I'm in the process of upgrading Symfony from 2.8 to 3.4 and I have a Authentication Listener.

The constructor of the listener

  public function __construct(EntityManager $entityManager, SessionInterface $session, Security $security, LoggerInterface $logger, Redis $redis, $secret)
    {
        $this->entityManager    = $entityManager;
        $this->session          = $session;
        $this->security         = $security;
        $this->logger           = $logger;
        $this->redis            = $redis;
        $this->secret           = $secret;
    }

On Request Function which is calling in listener

       public function onRequest(GetResponseEvent $event)
        {

        //Validate token

        //Get Authorization Header
        $headers = $event->getRequest()->headers;
        $authHeader = $headers->get('Authorization');

        //Check if Header value starts with 'Bearer'
        if($this->startsWith($authHeader, self::$BEARER_HEADER)) {

                // Allow request to be processed by controllers
               //token handler

        } else {

            $securityContext = $this->security;
            if ($securityContext->isGranted('IS_AUTHENTICATED_ANONYMOUSLY')) {
                return;
            } else {
                throw new SessionTimeoutException();
            }

        }
    }

Service.yml

app.token_listener:
    class: Insead\MIMBundle\Listener\AuthTokenListener
    arguments: ["@doctrine.orm.entity_manager", "@session", "@security.helper", "@logger", "@redis.authtoken", "%secret%"]
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onRequest, priority: 0 }

ACL list entry  - security.php

  'access_control' => array(
       array('path' => '^/api/(.*?)/login', 'role'=>'IS_AUTHENTICATED_ANONYMOUSLY'),
    )

im trying to access login route with username and password but i get following error

GENERAL EXCEPTION: The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL. in

/var/www/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Authorization/AuthorizationChecker.php line 55
Exception caught by Listener::
[
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Security.php",
    "line": 65,
    "function": "isGranted",
    "class": "Symfony\\Component\\Security\\Core\\Authorization\\AuthorizationChecker",
    "type": "->",
    "args": [
      "IS_AUTHENTICATED_ANONYMOUSLY",
      null
    ]
  },
  {
    "file": "/var/www/src/Insead/MIMBundle/Listener/AuthTokenListener.php",
    "line": 135,
    "function": "isGranted",
    "class": "Symfony\\Component\\Security\\Core\\Security",
    "type": "->",
    "args": [
      "IS_AUTHENTICATED_ANONYMOUSLY"
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/EventDispatcher.php",
    "line": 212,
    "function": "onRequest",
    "class": "Insead\\MIMBundle\\Listener\\AuthTokenListener",
    "type": "->",
    "args": [
      null,
      "kernel.request",
      null
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/EventDispatcher.php",
    "line": 44,
    "function": "doDispatch",
    "class": "Symfony\\Component\\EventDispatcher\\EventDispatcher",
    "type": "->",
    "args": [
      [
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onRequest"
        ],
        [
          null,
          "onController"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "configure"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onKernelRequest"
        ],
        [
          null,
          "onRequest"
        ]
      ],
      "kernel.request",
      null
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php",
    "line": 127,
    "function": "dispatch",
    "class": "Symfony\\Component\\EventDispatcher\\EventDispatcher",
    "type": "->",
    "args": [
      "kernel.request",
      null
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php",
    "line": 68,
    "function": "handleRaw",
    "class": "Symfony\\Component\\HttpKernel\\HttpKernel",
    "type": "->",
    "args": [
      {
        "attributes": null,
        "request": null,
        "query": null,
        "server": null,
        "files": null,
        "cookies": null,
        "headers": null
      },
      1
    ]
  },
  {
    "file": "/var/www/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php",
    "line": 200,
    "function": "handle",
    "class": "Symfony\\Component\\HttpKernel\\HttpKernel",
    "type": "->",
    "args": [
      {
        "attributes": null,
        "request": null,
        "query": null,
        "server": null,
        "files": null,
        "cookies": null,
        "headers": null
      },
      1,
      true
    ]
  },
  {
    "file": "/var/www/web/app.php",
    "line": 29,
    "function": "handle",
    "class": "Symfony\\Component\\HttpKernel\\Kernel",
    "type": "->",
    "args": [
      {
        "attributes": null,
        "request": null,
        "query": null,
        "server": null,
        "files": null,
        "cookies": null,
        "headers": null
      }
    ]
  }
]

I have spend days on this and i still couldn't figure it out to fix it.

Im sorry if this is already answered question i tried to search and i tried things which were mentioned in various posts and it didn't resolve it. im new to symfony too.

Full Security.php

https://www.codepile.net/pile/7O1LJkpv

AuthTokenListner.php

https://www.codepile.net/pile/Xv1ZMlAP

Body:
Issue was with the priority order.

thanks @cerad for giving a clue about it

bin/console debug:event-dispatcher kernel.request

helped to solve the issue. i was using

tags:
        - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse, priority: 10 }

in Services.yml and it had a conflict with the

getSubscribedEvents()

therefore i have removed  tags and only kept

public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::REQUEST  => array('onKernelRequest', 10),
        );
    }

then i moved authentication listener to the down by giving high priority to other two listeners as same as it was there in symfony 2.8

Thanks all for helping me out on this specially @Pie @Cerad and @BoShurik


问:
Accessing Request object in Apollo Server with ExpressJS
Is there any way of accessing the request object from the underlying express app in Apollo Server</p>

答:
The context configuration parameter can be either an object, a function that returns the object, or a function that returns a promise to return the object. This function would get the HTTP request as a parameter, and could be defined like so:

```<code>const apolloServer = new ApolloServer({
  schema,
  context: async ({ req }) => {
    const something = getSomething(req)
    return { something }
  },
})

apolloServer.applyMiddleware({ app, path: '/graphql' })

const { appPort } = serviceFunc.getAccessData()
app.listen({ port: appPort }, () => {
  console.log(`Express+Apollo Server on http://localhost:${appPort}/graphql`)
})
</code>```

Thanks to Eugene eugene1g

Body:
The context configuration parameter can be either an object, a function that returns the object, or a function that returns a promise to return the object. This function would get the HTTP request as a parameter, and could be defined like so:

const apolloServer = new ApolloServer({
  schema,
  context: async ({ req }) => {
    const something = getSomething(req)
    return { something }
  },
})

apolloServer.applyMiddleware({ app, path: '/graphql' })

const { appPort } = serviceFunc.getAccessData()
app.listen({ port: appPort }, () => {
  console.log(`Express+Apollo Server on http://localhost:${appPort}/graphql`)
})

Thanks to Eugene eugene1g


问:
Password field not taking keys using Selenium through Python
I am trying to send keys via selenium it is taking for username but not for password.

I have tried clicking and sending keys then.

HTML of password field:

```<code><div>
    <input name="txtPassword" type="password" id="txtPassword" required="" style="margin-bottom:0px;" class="blur">
    <a id="btnSmallForgotPassword" class="smallForgotPassword visible-sm-block" href="javascript:__doPostBack('btnSmallForgotPassword','')">forgot password</a>
</div>
</code>```

```<code>WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID,"txtPassword"))).click()
WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID,"txtPassword"))).send_keys("san")
</code>```

I am getting no error message but it is not sending keys for password

答:
Try this:</p>

```<code>from selenium import webdriver
import time

driver = webdriver.Chrome('/usr/bin/chromedriver')
driver.get('http://backgriduk.medialava.com/pages/Staff/Login.aspx?LANGUAGE_ID=3&O=7')
time.sleep(3)

username = driver.find_element_by_id("txtUser")
username.clear()
# insert username
username.send_keys("mrcats")

password = driver.find_element_by_name("txtPassword")
password.clear()
# insert password
password.send_keys("catskillz")

login = driver.find_element_by_name("btnLogin")
#click on login button
login.click()
</code>```

Body:
I am trying to send keys via selenium it is taking for username but not for password.

I have tried clicking and sending keys then.

HTML of password field:

    <input name="txtPassword" type="password" id="txtPassword" required="" style="margin-bottom:0px;" class="blur">
    forgot password

WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID,"txtPassword"))).click()
WebDriverWait(driver, 3).until(EC.visibility_of_element_located((By.ID,"txtPassword"))).send_keys("san")

I am getting no error message but it is not sending keys for password

Body:
Try this:

from selenium import webdriver
import time

driver = webdriver.Chrome('/usr/bin/chromedriver')
driver.get('http://backgriduk.medialava.com/pages/Staff/Login.aspx?LANGUAGE_ID=3&O=7')
time.sleep(3)

username = driver.find_element_by_id("txtUser")
username.clear()
# insert username
username.send_keys("mrcats")

password = driver.find_element_by_name("txtPassword")
password.clear()
# insert password
password.send_keys("catskillz")

login = driver.find_element_by_name("btnLogin")
#click on login button
login.click()


问:
'Gulpfile.js - failed to load See output' but output does not show any error information
I am trying to use gulp to copy some JS/CSS from node_modules to wwwroot in an ASP.Net core app.

I have what I thought was a fairly simple gulpfile.js

```<code>var gulp = require('gulp');
gulp.task('copy-files', function () {
    var assets = {
        js: [
            './node_modules/bootstrap/dist/js/bootstrap.js'
        ],
        css: [
            './node_modules/bootstrap/dist/css/bootstrap.css'
        ]
    };
    _(assets).forEach(function (assets, type) {
        gulp.src(assets).pipe(gulp.dest('./wwwroot/' + type));
    });
});
</code>```

However, when I look at the VS Task Runner, it just shows an error:

But the output window is empty:

How can I get more information about the error?

答: In Output window, make sure you select Task Runner Explorer for Show output from option. This was my problem why I didn't see the error logs from gulpfile. A rookie mistake.

Body:
I am trying to use gulp to copy some JS/CSS from node_modules to wwwroot in an ASP.Net core app.

I have what I thought was a fairly simple gulpfile.js

var gulp = require('gulp');
gulp.task('copy-files', function () {
    var assets = {
        js: [
            './node_modules/bootstrap/dist/js/bootstrap.js'
        ],
        css: [
            './node_modules/bootstrap/dist/css/bootstrap.css'
        ]
    };
    _(assets).forEach(function (assets, type) {
        gulp.src(assets).pipe(gulp.dest('./wwwroot/' + type));
    });
});

However, when I look at the VS Task Runner, it just shows an error:

But the output window is empty:

How can I get more information about the error?


问:
Selecting Only The Latest Version Of A Field
I have a table schema with ID, Title, Date

and data looks something like this:

```<code>1  The title1    2011-04-05 00:00:00.000
2  Another title 2011-04-11 00:00:00.000
3  The title1    2011-04-11 16:49:23.633
4  The title1    2011-04-11 00:00:00.000
</code>```

I need help with sql to give me the latest date of each title.
So the output for the above data is

```<code>2  Another title 2011-04-11 00:00:00.000
3  The title1    2011-04-11 16:49:23.633
</code>```

答:
Assuming at least SQL Server 2005:</p>

```<code>SELECT ID, Title, [Date]
    FROM (SELECT ID, Title, [Date],
                 ROW_NUMBER() OVER(PARTITION BY Title ORDER BY [Date] DESC) AS RowNum
              FROM YourTable
         ) t
    WHERE t.RowNum = 1
</code>```

Body:
I have a table schema with ID, Title, Date

and data looks something like this:

1  The title1    2011-04-05 00:00:00.000
2  Another title 2011-04-11 00:00:00.000
3  The title1    2011-04-11 16:49:23.633
4  The title1    2011-04-11 00:00:00.000

I need help with sql to give me the latest date of each title.
So the output for the above data is

2  Another title 2011-04-11 00:00:00.000
3  The title1    2011-04-11 16:49:23.633

Body:
Assuming at least SQL Server 2005:

SELECT ID, Title, [Date]
    FROM (SELECT ID, Title, [Date],
                 ROW_NUMBER() OVER(PARTITION BY Title ORDER BY [Date] DESC) AS RowNum
              FROM YourTable
         ) t
    WHERE t.RowNum = 1


问:
How to pass dynamic url of selected value from dropdwonlist in django
I have a dropdwon list..when i click on that i got a value like some name..now i want that name pass as a url in django

Views.py

```<code>@csrf_exempt
def forecasting(request):
    Category = category.objects.all()

    return render(request, "myapp/casting.html",{'Category':Category})

@csrf_exempt
def Prediction(request,name):
    Category1 = category.objects.get(Category=name)

    print(Category1.Category)
    return render(request, "myapp/casting.html", {'Category1': Category1})
</code>```

Models.py

```<code>class category(models.Model):
    Category = models.CharField(max_length=50)

    def __str__(self):
        return self.Category
</code>```

Html file

```<code><form  id="myform" method="post" name="myform" action="/Prediction/{{Category1.Category}}">

                    <div class="col-lg-3 col-md-3">
                        <h3> Select Category</h3>
                    </div>
                    <div class="col-lg-3 col-md-3">
                        {%csrf_token%}
                        <select id="Category" name="catagery_id" onchange="myform.submit()">
                            <option value="">Select</option>
                            {% for Category in Category %}
                            <option value="{{ Category.Category }}">{{ Category.Category }}</option>

                            {% for message in messages %}
                            <div>
                                <p>{{message|safe}}</p>

                            </div>
                            {% endfor %}

                            {% endfor %}
                        </select>
                    </div>
                    <ul class="messages">
                        {% for message in messages %}
                        <p
                                {% if message.tags %} class="{{ message.tags }}" {% endif %}>{{ message }}</p>
                        {% endfor %}
                    </ul>
                    <div class="col-lg-3 col-md-3">

                    </div>

                </form>
</code>```

I have no idea how to do this..because value come when i submit the form..i am new to this please help me out

答:
I think you want to pass that value which is selected in dropdown in action of form, You can try this using jquery

```<code>$("#Category").on("change",function(){
  action_url = '/Prediction/'+$(this).val()
  $('#myform').attr('action', action_url);
  $('#myform').submit()
})
</code>```

in this case you have to submit form from jquery by removing
  onchange="myform.submit()"

Replace following codes

```<code>{% for Category in Category %}
 {% if Category.Category == Category1.Category %}
   <option value="{{ Category.Category }}" selected>{{
    Category.Category }
   </option>
 {% else%}
   <option value="{{ Category.Category }}">{{ Category.Category }
   </option>
 {% endif %}

 {% for message in messages %}
 <div>
 <p>{{message|safe}}</p>

  </div>
  {% endfor %}

 {% endfor %}
</code>```

Body:
I have a dropdwon list..when i click on that i got a value like some name..now i want that name pass as a url in django

Views.py

@csrf_exempt
def forecasting(request):
    Category = category.objects.all()

    return render(request, "myapp/casting.html",{'Category':Category})

@csrf_exempt
def Prediction(request,name):
    Category1 = category.objects.get(Category=name)

    print(Category1.Category)
    return render(request, "myapp/casting.html", {'Category1': Category1})

Models.py

class category(models.Model):
    Category = models.CharField(max_length=50)

    def __str__(self):
        return self.Category

Html file

<form  id="myform" method="post" name="myform" action="/Prediction/{{Category1.Category}}">

 Select Category

                        {%csrf_token%}
                        <select id="Category" name="catagery_id" onchange="myform.submit()">
                            <option value="">Select</option>
                            {% for Category in Category %}
                            <option value="{{ Category.Category }}">{{ Category.Category }}</option>

                            {% for message in messages %}

{{message|safe}}

                            {% endfor %}

                            {% endfor %}
                        </select>

                        {% for message in messages %}

{{ message }}

                        {% endfor %}

                </form>

I have no idea how to do this..because value come when i submit the form..i am new to this please help me out

Body:
I think you want to pass that value which is selected in dropdown in action of form, You can try this using jquery

$("#Category").on("change",function(){
  action_url = '/Prediction/'+$(this).val()
  $('#myform').attr('action', action_url);
  $('#myform').submit()
})

in this case you have to submit form from jquery by removing
  onchange="myform.submit()"

Replace following codes

{% for Category in Category %}
 {% if Category.Category == Category1.Category %}
   <option value="{{ Category.Category }}" selected>{{
    Category.Category }
   </option>
 {% else%}
   <option value="{{ Category.Category }}">{{ Category.Category }
   </option>
 {% endif %}

 {% for message in messages %}
 <div>
 <p>{{message|safe}}</p>

  </div>
  {% endfor %}

 {% endfor %}


问:
AWS CLI : Windows CLI -- SSLError: [Errno 2] No such file or directory
I am trying to create stack using below command on Windows AWS CLI

```<code>aws cloudformation create-stack --stack-name dockerApp --template-body file://./stack.json`
</code>```

Here is stack.json contains my template definition

I am getting below error:

Error parsing parameter '--template-body': Unable to load paramfile file://./stack.json: [Errno 2] No such file or directory: u'/./stack.json'

答:
Open command prompt as administrator and execute below command

copy "c:\Program Files\Amazon\AWSCLI\botocore\vendored\requests\cacert.pem" "c:\Program Files\Amazon\AWSCLI\certifi"

For more information, go through aws-cli-issue

Body:
I am trying to create stack using below command on Windows AWS CLI

aws cloudformation create-stack --stack-name dockerApp --template-body file://./stack.json`

Here is stack.json contains my template definition

I am getting below error:

Error parsing parameter '--template-body': Unable to load paramfile file://./stack.json: [Errno 2] No such file or directory: u'/./stack.json'


问:
React memo components and re-render when passing function as props
Suppose I have these React components:

```<code>const Compo1 = ({theName}) => {
  return (
    <Nested foo={() => console.log('Dr. ' + theName)}/>
  );
};

const Compo2 = ({theName}) => {
  function theFoo() {
    console.log('Dr. ' + theName);
  }
  return (
    <Nested foo={theFoo}/>
  );
};
</code>```

And the nested component, wrapped in memo:

```<code>const Nested = React.memo(({foo}) => {
  return (
    <Button onClick={foo}>Click me</Button>
  );
});
</code>```

Function passed in foo is always recreated in Compo1 and also Compo2, correct?

If so, since foo receives a new function every time, does it mean memo will be useless, thus Nested will always be re-rendered?

答:
You can use new hooks Api(React >= 16.8) to avoid recreating callback func.

Just using useCallback hook for this.

For e.g

Parent component

```<code>import React, { useCallback} from 'react';

const ParentComponent = ({theName}) => {
  const theFoo = () => {
    console.log('Dr. ' + theName);
  }

  const memoizedCallback = useCallback(theFoo , []);

  return (
     <Nested foo={memoizedCallback}/>
   );
};
</code>```

useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed (which passed in the second argument)
In this case we pass empty array as dependencies and therefore the function will be created only once.

And nested component:

```<code>import React, { memo } from 'react';

const Nested = ({foo}) => (
  <Button onClick={foo}>Click me</Button>
);

export default memo(Nested);
</code>```

For more info - https://reactjs.org/docs/hooks-reference.html#usecallback

Body:
Suppose I have these React components:

const Compo1 = ({theName}) => {
  return (
    <Nested foo={() => console.log('Dr. ' + theName)}/>
  );
};

const Compo2 = ({theName}) => {
  function theFoo() {
    console.log('Dr. ' + theName);
  }
  return (
    <Nested foo={theFoo}/>
  );
};

And the nested component, wrapped in memo:

const Nested = React.memo(({foo}) => {
  return (
    <Button onClick={foo}>Click me</Button>
  );
});

Function passed in foo is always recreated in Compo1 and also Compo2, correct?

If so, since foo receives a new function every time, does it mean memo will be useless, thus Nested will always be re-rendered?

Body:
You can use new hooks Api(React >= 16.8) to avoid recreating callback func.

Just using useCallback hook for this.

For e.g

Parent component

import React, { useCallback} from 'react';

const ParentComponent = ({theName}) => {
  const theFoo = () => {
    console.log('Dr. ' + theName);
  }

  const memoizedCallback = useCallback(theFoo , []);

  return (
     <Nested foo={memoizedCallback}/>
   );
};

useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed (which passed in the second argument)
In this case we pass empty array as dependencies and therefore the function will be created only once.

And nested component:

import React, { memo } from 'react';

const Nested = ({foo}) => (
  <Button onClick={foo}>Click me</Button>
);

export default memo(Nested);

For more info - https://reactjs.org/docs/hooks-reference.html#usecallback


问:
call javascript from functions.php
I have a javascript there is looking like this:

```<code>jQuery("ul[data-attribute_name=attribute_pa_afhentning-og-levering] li").click(function(){
    var selectedlevering = jQuery("ul[data-attribute_name=attribute_pa_afhentning-og-levering]").find("li.selected").attr("data-value");
    if (selectedlevering == "afhentning"){
        jQuery("ul[data-attribute_name=attribute_pa_packages] li[data-value=afhentning] span").click();
        jQuery("ul[data-attribute_name=attribute_pa_packages] li[data-value=afhentning]").hide(); // hide the "afhentning" option in "Packages" if you like
    }
});
</code>```

I need to call that script from my functions.php in Wordpress. But how am I doing that?

Best regards

答:
You can choose to add the custom script in the head section by adding the wp_head as the required action.

//----------------------------------------------------------------------
// Custom script in head section, add these lines in your functions.php
//----------------------------------------------------------------------

function custom_script_name(){
?>

<?php
}
add_action('wp_head', 'custom_script_name');```

Title: call javascript from functions.php

Body:
I have a javascript there is looking like this:

jQuery("ul[data-attribute_name=attribute_pa_afhentning-og-levering] li").click(function(){
    var selectedlevering = jQuery("ul[data-attribute_name=attribute_pa_afhentning-og-levering]").find("li.selected").attr("data-value");
    if (selectedlevering == "afhentning"){
        jQuery("ul[data-attribute_name=attribute_pa_packages] li[data-value=afhentning] span").click();
        jQuery("ul[data-attribute_name=attribute_pa_packages] li[data-value=afhentning]").hide(); // hide the "afhentning" option in "Packages" if you like
    }
});

I need to call that script from my functions.php in Wordpress. But how am I doing that?

Best regards

Body:
You can choose to add the custom script in the head section by adding the wp_head as the required action.

//----------------------------------------------------------------------
// Custom script in head section, add these lines in your functions.php
//----------------------------------------------------------------------

function custom_script_name(){
?>
<script>
// Your script here
</script>
<?php
}
add_action('wp_head', 'custom_script_name');


问:
How do I install CocoaPods?
I referred to many links and tried, but I had no success. I read CocoaPods documents and many times tried to install, but I always failed because of the starting steps. I found one error whereby I can't install gems first. What are the steps one by one? Such as steps or a demo of how to install.

This is one link which I tried.

The screenshot refers to this console error I was given:

答:
If you want to install CocoaPods for the first time for your project.

Example: Here we will install the "Alamofire" SDK using CocoaPods step by step.

Step 1. Open Terminal, hit command, and then press the Enter key

sudo gem install cocoapods
```
<p><strong>Step 2.</strong> If it asks, you should <strong>provide system password</strong> and then press the <kbd>Enter</kbd> key</p>
<p><strong>Step 3.</strong> With <strong>command “cd” and give the path of your project</strong> and then press the <kbd>Enter</kbd> key</p>
<p><em>Note: type the "cd" command then space and drag the project folder to the terminal. It will take the project path as shown below (here my project name is: Simple Alamofire)</em></p>
<pre class="lang-none prettyprint-override"><code>cd  /Users/ramdhanchoudhary/Documents/Swift\ Workspace/Simple\
Alamofire
</code>```

Step 4. Create a pod file in your project by terminal by command “touch Podfile” and press “Enter”

touch Podfile
```
<p><strong>Step 5.</strong> Then, open “Podfile” by terminal command “open Podfile” and press “Enter”</p>
<pre class="lang-none prettyprint-override"><code>open Podfile
</code>```

Step 6. Now type following code in opened pod file then save and close file

source 'https://github.com/CocoaPods/Specs.git'
    platform :ios, '10.0'
    use_frameworks!

    target '<Your Target Name>' do
            pod 'Alamofire', '~> 4.0'
    end
```
<p><strong>Step 7.</strong> Back in Terminal type command “Pod install” and then press <kbd>Enter</kbd> Key.</p>
<pre class="lang-none prettyprint-override"><code>Pod install
</code>```

Step 8. Wait for the install to get complete 100% its around 650+ MB

Step 9. That's it goto project folder and open below file

<your project name>.xcworkspace
```
<p>Step 10. Import Alamofire class and use!!</p>
<pre class="lang-none prettyprint-override"><code>import Alamofire
</code>```

Title: How do I install CocoaPods?

Body:
If you want to install CocoaPods for the first time for your project.

Example: Here we will install the "Alamofire" SDK using CocoaPods step by step.

Step 1. Open Terminal, hit command, and then press the Enter key

sudo gem install cocoapods

Step 2. If it asks, you should provide system password and then press the Enter key

Step 3. With command “cd” and give the path of your project and then press the Enter key

Note: type the "cd" command then space and drag the project folder to the terminal. It will take the project path as shown below (here my project name is: Simple Alamofire)

cd  /Users/ramdhanchoudhary/Documents/Swift\ Workspace/Simple\
Alamofire

Step 4. Create a pod file in your project by terminal by command “touch Podfile” and press “Enter”

touch Podfile

Step 5. Then, open “Podfile” by terminal command “open Podfile” and press “Enter”

open Podfile

Step 6. Now type following code in opened pod file then save and close file

source 'https://github.com/CocoaPods/Specs.git'
    platform :ios, '10.0'
    use_frameworks!

    target '<Your Target Name>' do
            pod 'Alamofire', '~> 4.0'
    end

Step 7. Back in Terminal type command “Pod install” and then press Enter Key.

Pod install

Step 8. Wait for the install to get complete 100% its around 650+ MB

Step 9. That's it goto project folder and open below file

<your project name>.xcworkspace

Step 10. Import Alamofire class and use!!

import Alamofire


问:
Display user bio in a column on Woocommerce admin orders list
We store some customer info in his/her Bio text area in user edit page.
How to display this stored data in user Bio field as a column in the Order admin page in woocommerce ?
I tried this code but its not working:

```<code>// Adding a custom new column to admin orders list
add_filter( 'manage_edit-shop_order_columns', 'custom_column_eldest_players', 20 );
function custom_column_eldest_players($columns)
{
    $reordered_columns = array();

    // Inserting columns to a specific location
    foreach( $columns as $key => $column){
        $reordered_columns[$key] = $column;
        if( $key ==  'order_status' ){
            // Inserting after "Status" column
            $reordered_columns['skb-client'] = __( 'Oudste Speler','theme_domain');
        }
    }
    return $reordered_columns;
}

// Adding custom fields meta data for the column
add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 20, 2 );
function custom_orders_list_column_content( $column, $post_id )
{
    if ( 'skb-client' != $column ) return;

    global $the_order;

    // Get the customer Bio
    $user_bio = get_user_meta( $order->get_customer_id(), 'description', true );

        $user_data = get_userdata( $user_bio );
        echo $user_data->user_bio; // The WordPress user name

}
</code>```

we need this stored data to displayed for each costumers purchase.
Best regards

答:
The variable $order is not defined in your 2nd function, so you need to use instead $the_order. then I have revisited you code… Try the following instead:

```<code> // Adding a custom new column to admin orders list
add_filter( 'manage_edit-shop_order_columns', 'custom_column_eldest_players', 20 );
function custom_column_eldest_players($columns)
{
    $reordered_columns = array();

    // Inserting columns to a specific location
    foreach( $columns as $key => $column){
        $reordered_columns[$key] = $column;
        if( $key ==  'order_status' ){
            // Inserting after "Status" column
            $reordered_columns['user-bio'] = __( 'User bio', 'woocommerce');
        }
    }
    return $reordered_columns;
}

// Adding custom fields meta data for the column
add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 20, 2 );
function custom_orders_list_column_content( $column, $post_id ) {
    if ( 'user-bio' === $column ) {
        global $the_order;

        echo ( $user = $the_order->get_user() ) ? $user->description : 'n/c';
    }
}
</code>```

Code goes in functions.php file of your active child theme (or active theme). Tested and work.

Body:
We store some customer info in his/her Bio text area in user edit page.
How to display this stored data in user Bio field as a column in the Order admin page in woocommerce ?
I tried this code but its not working:

// Adding a custom new column to admin orders list
add_filter( 'manage_edit-shop_order_columns', 'custom_column_eldest_players', 20 );
function custom_column_eldest_players($columns)
{
    $reordered_columns = array();

    // Inserting columns to a specific location
    foreach( $columns as $key => $column){
        $reordered_columns[$key] = $column;
        if( $key ==  'order_status' ){
            // Inserting after "Status" column
            $reordered_columns['skb-client'] = __( 'Oudste Speler','theme_domain');
        }
    }
    return $reordered_columns;
}

// Adding custom fields meta data for the column
add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 20, 2 );
function custom_orders_list_column_content( $column, $post_id )
{
    if ( 'skb-client' != $column ) return;

    global $the_order;

    // Get the customer Bio
    $user_bio = get_user_meta( $order->get_customer_id(), 'description', true );

        $user_data = get_userdata( $user_bio );
        echo $user_data->user_bio; // The WordPress user name

}

we need this stored data to displayed for each costumers purchase.
Best regards

Body:
The variable $order is not defined in your 2nd function, so you need to use instead $the_order. then I have revisited you code… Try the following instead:

 // Adding a custom new column to admin orders list
add_filter( 'manage_edit-shop_order_columns', 'custom_column_eldest_players', 20 );
function custom_column_eldest_players($columns)
{
    $reordered_columns = array();

    // Inserting columns to a specific location
    foreach( $columns as $key => $column){
        $reordered_columns[$key] = $column;
        if( $key ==  'order_status' ){
            // Inserting after "Status" column
            $reordered_columns['user-bio'] = __( 'User bio', 'woocommerce');
        }
    }
    return $reordered_columns;
}

// Adding custom fields meta data for the column
add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 20, 2 );
function custom_orders_list_column_content( $column, $post_id ) {
    if ( 'user-bio' === $column ) {
        global $the_order;

        echo ( $user = $the_order->get_user() ) ? $user->description : 'n/c';
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and work.


问:
laravel route name parameter
Use a pageNation to request the value of the page to the controller. But why can't any parameters reach the controller?

```<code> Route::get('/index', 'Penpal\ViewController@index')->name('penpal.index');

 <form action="{!! route('penpal.index', ['menu' => 'p11-c3']) !!}" method="get">
            <select id="inputState" class="form-control" style="height:35px; width:80%" name="pagination" onchange="this.form.submit()">
                    <option value="3">@lang('penpal/component/indexMenu.twelve')</option>
                    <option value="4">@lang('penpal/component/indexMenu.twenty_four')</option>
                    <option value="5">@lang('penpal/component/indexMenu.thirty_six')</option>
                </select>
        </form>

 public function index (Request $request){
    return $request;\
 }
</code>```

A parameter named "menu" cannot be received from the controller.

答:
```<code>Use Post method both route and form

<form action="{!! route('penpal.index', ['menu' => 'p11-c3']) !!}" method="post">
Route::match(['get','post'],'/index', 'Penpal\ViewController@index')->name('penpal.index');
</code>```

Title: laravel route name parameter

Body:
Use a pageNation to request the value of the page to the controller. But why can't any parameters reach the controller?

 Route::get('/index', 'Penpal\ViewController@index')->name('penpal.index');

 <form action="{!! route('penpal.index', ['menu' => 'p11-c3']) !!}" method="get">
            <select id="inputState" class="form-control" style="height:35px; width:80%" name="pagination" onchange="this.form.submit()">
                    <option value="3">@lang('penpal/component/indexMenu.twelve')</option>
                    <option value="4">@lang('penpal/component/indexMenu.twenty_four')</option>
                    <option value="5">@lang('penpal/component/indexMenu.thirty_six')</option>
                </select>
        </form>

 public function index (Request $request){
    return $request;\
 }

A parameter named "menu" cannot be received from the controller.


问:
How can I optimize an animation in Processing, and keep it from leaving a trail of images?
I am creating a model of a solar system in processing, and after removing the background I noticed the planets were leaving a trail of their image behind them. The program runs fine when the background is back in, but I want to add a lot more and I am sure this is inefficient and will bog things down.

I am very new to processing, and I am really not sure how to solve this. Maybe delete previous images after a delay to create a shortened trail?

These are just the parts I think are important cherry picked from the code, this is just the example of one planet. Sorry if the code is clunky, any suggestions are happily accepted.

```<code>Planet p1;

void setup() {
 mercury = loadImage("mercury.png")

 p1 = new Planet(40, random(TWO_PI), 0.05);

}

void draw() {
  //background(0)
  translate(width / 2, height / 2);
  p1.display1();
  p1.orbit();
}

class Planet  {
  float radius;
  float angle;
  float distance;
  float orbitSpeed;

  Planet(float r, float d, float o) {
     radius = r;
     distance = d;
     orbitSpeed = o;
     angle = random(TWO_PI);
  }

  void orbit() {
    angle = angle + orbitSpeed;
  }

  void display1() {
    pushMatrix();
    rotate(angle);
    translate(distance, 0);
    imageMode(CENTER);
    image(mercury, radius, radius, 10, 10);
    popMatrix();
  }
}
</code>```

I realized that this would probably happen, and I am not sure how to stop it.

答:
The behavior you describe is simply the nature of computer graphics; it's how games, operating systems, and hardware displays all work – they clear and redraw everything every frame.

In Processing, graphic objects that are pushed to a buffer remain there indefinitely until the buffer is cleared or something is pushed on top of them (this is why the planets are leaving a trail without calling background() – previous frames remain in the buffer).

You are worried about the background() being inefficient. Don't be, as it's one of the fastest operations (simply sets the value of each pixel, as given by the user).

Processing does provide a clear() function, but this is equivalent to background(0).

If you're are still concerned about efficiency and speed, one way to speed up Processing is to use the FX2D renderer rather than default AWT renderer. Another way is cache drawn objects into PGraphics objects to prevent successive rasterization (since your planets are image files and not drawn with processing, you needn't worry about this).

Body:
I am creating a model of a solar system in processing, and after removing the background I noticed the planets were leaving a trail of their image behind them. The program runs fine when the background is back in, but I want to add a lot more and I am sure this is inefficient and will bog things down.

I am very new to processing, and I am really not sure how to solve this. Maybe delete previous images after a delay to create a shortened trail?

These are just the parts I think are important cherry picked from the code, this is just the example of one planet. Sorry if the code is clunky, any suggestions are happily accepted.

Planet p1;

void setup() {
 mercury = loadImage("mercury.png")

 p1 = new Planet(40, random(TWO_PI), 0.05);

}

void draw() {
  //background(0)
  translate(width / 2, height / 2);
  p1.display1();
  p1.orbit();
}

class Planet  {
  float radius;
  float angle;
  float distance;
  float orbitSpeed;

  Planet(float r, float d, float o) {
     radius = r;
     distance = d;
     orbitSpeed = o;
     angle = random(TWO_PI);
  }

  void orbit() {
    angle = angle + orbitSpeed;
  }

  void display1() {
    pushMatrix();
    rotate(angle);
    translate(distance, 0);
    imageMode(CENTER);
    image(mercury, radius, radius, 10, 10);
    popMatrix();
  }
}

I realized that this would probably happen, and I am not sure how to stop it.


问:
How can I hide a UITabbarIcon?
I'm currently developing an iOS-App which will have 5 tabbar-icons. One of these should only be visible if you are allowed to see it.
How can I hide this icon?</p>

答:
If you want to remove the UIViewController from tabBar, add this line of code in the UITabBarControllerClass

For removal

self.viewControllers?.remove(at: tabIndex) // replace the tabIndex which you want to remove
```

<p>For Add</p>

<pre class="lang-cs prettyprint-override"><code>self.viewControllers?.insert(viewController, at: tabIndex) // replace the viewcontroller with your controller and tabIndex with your index
</code>```

Title: How can I hide a UITabbarIcon?

Body:
If you want to remove the UIViewController from tabBar, add this line of code in the UITabBarControllerClass

For removal

self.viewControllers?.remove(at: tabIndex) // replace the tabIndex which you want to remove

For Add

self.viewControllers?.insert(viewController, at: tabIndex) // replace the viewcontroller with your controller and tabIndex with your index


问:
Get count of array objects belonging to a partical ID in JavaScript/Node js
I have an array of arrays like this:

```<code>var array = [
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
]
</code>```

The ID's in the above array (2,3 and 4) come dynamically from a server response.
I need to count the number of entries for a particular ID.
I'm not able to figure out how to loop over this array to get the expected output.
The expected output is:

```<code>[{"ID" : "4", Count : "1"},{"ID" : "3", Count : "2"},{"ID" : "2",Count : "3"}]
</code>```

Note that the output is in the ascending order of the Count.

This is what I tried :

```<code>var temp1 = [];
                var temp2 = [];
                var temp3 = [];
                for(var i = 0; i < array.length; ++i){
                     if(array[i][0] == 2){
                        temp1.push(array[i])
                     }
                     if(array[i][0] == 1){
                        temp2.push(array[i])
                     }
                     if(array[i][0] == 3){
                        temp3.push(array[i])
                     }

                }

 var output = [{
                    ID: "2",
                    Count: temp1.length,
                },
                {
                    ID: "1",
                    Count: temp2.length,
                },
                {
                    ID: "3",
                    Count: temp3.length
                }]

console.log(output)
</code>```

I believe the way I'm doing it is not the best approach if the data is dynamic.
How do I do it in a better way?

答:
Combined use of Array.prototype.reduce(), Object.entries(), Array.prototype.sort() and Array.prototype.map() will yield this:

const array = [
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
];

const result = Object.entries(array.reduce((a, [id]) => {
  a[id] = (a[id] || 0) + 1;
  return a;
}, {})).map(([ID, Count]) => ({ID, Count}))
       .sort((a, b) => a.Count - b.Count);

console.log(result);```

Body:
I have an array of arrays like this:

var array = [
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
]

The ID's in the above array (2,3 and 4) come dynamically from a server response.
I need to count the number of entries for a particular ID.
I'm not able to figure out how to loop over this array to get the expected output.
The expected output is:

[{"ID" : "4", Count : "1"},{"ID" : "3", Count : "2"},{"ID" : "2",Count : "3"}]

Note that the output is in the ascending order of the Count.

This is what I tried :

var temp1 = [];
                var temp2 = [];
                var temp3 = [];
                for(var i = 0; i < array.length; ++i){
                     if(array[i][0] == 2){
                        temp1.push(array[i])
                     }
                     if(array[i][0] == 1){
                        temp2.push(array[i])
                     }
                     if(array[i][0] == 3){
                        temp3.push(array[i])
                     }

                }

 var output = [{
                    ID: "2",
                    Count: temp1.length,
                },
                {
                    ID: "1",
                    Count: temp2.length,
                },
                {
                    ID: "3",
                    Count: temp3.length
                }]

console.log(output)

I believe the way I'm doing it is not the best approach if the data is dynamic.
How do I do it in a better way?


问:
Invalid session / Session is disconnected
What can be the reasons that cause a socket.io session to be crashed and server returns invalid session or session is disconnected ?</p>

答:
Ok, I'll illustrate my problem in this figure project's architecture .
 In fact, I have a websocket between the react app and the rasa ( tool for creating chatbots) based on flask. bot response need to access to an external API to retrieve some data. Here where things go wrong. Sometimes, these requests take too long to return a response, and that's when websocket misbehave.</p>


问:
Remove the first element from a multidimensional array with PHP
Form this array, how can I remove the first element of Provinces ?

```<code>Array
(
    [Country] => Canada
    [Provinces] => Array
        (
            [0] => Quebec
            [1] => Ontario
            [2] => British Columbia
        )
)
</code>```

Thanks.

答:
If you want to remove the first items in the array for the key name Provinces and the numerical keys do not have to be preserved, you could also use array_splice:

```<code>$arr = [
    "Country" => "Canada",
    "Provinces" => [
        "Quebec",
        "Ontario",
        "British Columbia"
    ]
];
array_splice($arr["Provinces"], 0, 1);
</code>```

Php demo

Or using unset to keep the numerical keys:

```<code>unset($arr['Provinces'][0]);
</code>```

Body:
Form this array, how can I remove the first element of Provinces ?

Array
(
    [Country] => Canada
    [Provinces] => Array
        (
            [0] => Quebec
            [1] => Ontario
            [2] => British Columbia
        )
)

Thanks.

Body:
If you want to remove the first items in the array for the key name Provinces and the numerical keys do not have to be preserved, you could also use array_splice:

$arr = [
    "Country" => "Canada",
    "Provinces" => [
        "Quebec",
        "Ontario",
        "British Columbia"
    ]
];
array_splice($arr["Provinces"], 0, 1);

Php demo

Or using unset to keep the numerical keys:

unset($arr['Provinces'][0]);


问:
Confusion matrix sklearn bug?
I was doing a test with sklearn.metrics.confusion_matrix to see what happen if in the prediction array there is a class which is not in the labels and mapping arrays.
My code is:

```<code>from sklearn.metrics import confusion_matrix as cm

a = ["positive\n", "positive\n", "negative\n", "positive\n", "negative\n"]
b = ["negative\n", "negative\n", "don't\n", "negative\n", "negative\n"]
m = ["positive\n", "negative\n"]
c = cm(a, b, m)
TN, FP, FN, TP = c.ravel()

print(c)
print("")
print("{} {} {} {}\n".format(TN, FP, FN, TP))
</code>```

The ouput is:

```<code>[[0 3]
 [0 1]]

0 3 0 1
</code>```

So the class don't is skipped.

But if you look at the documentation for the version v0.21.2 which is the one I installed the ravel() method "should" output the values of the confusion matrix as I wrote: TN, FP, FN, TP. The output of my print is different. It seems that the real ouput of ravel() is flipped: TP, FN, FP, TN. Is my thought right?

答:
There is no bug. You have defined labels:

```<code>m = ["positive\n", "negative\n"]
</code>```

therefore "positive\n" is negative and "negative\n" is positive. And the result meets your specification.

If you modify m this way:

```<code>m = ["negative\n", "positive\n"]
</code>```

you will get:

```<code>1 0 3 0
</code>```

for TN, FP, FN, TP, respectively.

Title: Confusion matrix sklearn bug?

Body:
I was doing a test with sklearn.metrics.confusion_matrix to see what happen if in the prediction array there is a class which is not in the labels and mapping arrays.
My code is:

from sklearn.metrics import confusion_matrix as cm

a = ["positive\n", "positive\n", "negative\n", "positive\n", "negative\n"]
b = ["negative\n", "negative\n", "don't\n", "negative\n", "negative\n"]
m = ["positive\n", "negative\n"]
c = cm(a, b, m)
TN, FP, FN, TP = c.ravel()

print(c)
print("")
print("{} {} {} {}\n".format(TN, FP, FN, TP))

The ouput is:

[[0 3]
 [0 1]]

0 3 0 1

So the class don't is skipped.

But if you look at the documentation for the version v0.21.2 which is the one I installed the ravel() method "should" output the values of the confusion matrix as I wrote: TN, FP, FN, TP. The output of my print is different. It seems that the real ouput of ravel() is flipped: TP, FN, FP, TN. Is my thought right?

Body:
There is no bug. You have defined labels:

m = ["positive\n", "negative\n"]

therefore "positive\n" is negative and "negative\n" is positive. And the result meets your specification.

If you modify m this way:

m = ["negative\n", "positive\n"]

you will get:

1 0 3 0

for TN, FP, FN, TP, respectively.


问:
Firebase Realtime database Array query issue
I need a firebase query to filter the list based on the value of an array.

if any of the index of GID(Array) contains the given key. e.g my key is YsGMyfLSGRNHxDWQmhpuPRqtxlq1 and one node's GID have that on 0th index and other have that on 1st index. So these two lists need to be returned.

Currently, I can only get the one at 0th index using the code

```<code>//userID = YsGMyfLSGRNHxDWQmhpuPRqtxlq1
 firebaseDatabase.child("Groups").queryOrdered(byChild: "GID/0").queryEqual(toValue:userID)
</code>```

When I try to combine the query I am getting errors.

答:
I don't know about your database structure, But I can explain that There is a limitation in Firebase Realtime database that you can only order by 1 child.
So now if we require to order by 2 Childs we can combine 2 nodes and make it 1 node and can apply order by query on it. For example

If we have username & email fields we can make a new field username_email and can apply order by on it.

Like

```<code>user: {
     username: "john",
     email: "john@g.com"
     username_email = "john_john@g.com"
}
</code>```

Now we can write

```<code>firebaseDatabase.child("user").queryOrdered(byChild: "username_email").queryEqual(toValue: "john_john@g.com");
</code>```

Body:
I need a firebase query to filter the list based on the value of an array.

if any of the index of GID(Array) contains the given key. e.g my key is YsGMyfLSGRNHxDWQmhpuPRqtxlq1 and one node's GID have that on 0th index and other have that on 1st index. So these two lists need to be returned.

Currently, I can only get the one at 0th index using the code

//userID = YsGMyfLSGRNHxDWQmhpuPRqtxlq1
 firebaseDatabase.child("Groups").queryOrdered(byChild: "GID/0").queryEqual(toValue:userID)

When I try to combine the query I am getting errors.

Body:
I don't know about your database structure, But I can explain that There is a limitation in Firebase Realtime database that you can only order by 1 child.
So now if we require to order by 2 Childs we can combine 2 nodes and make it 1 node and can apply order by query on it. For example

If we have username & email fields we can make a new field username_email and can apply order by on it.

Like

user: {
     username: "john",
     email: "john@g.com"
     username_email = "john_john@g.com"
}

Now we can write

firebaseDatabase.child("user").queryOrdered(byChild: "username_email").queryEqual(toValue: "john_john@g.com");


问:
Reset rolling sum to 0 after reaching the threshold
I'm trying to compute a running total and reset it to 0 based on 2 conditions or if the limit is reached.

Here is an example.

As in the image above, I need to get the running total while the following conditions are met:

monthly discount = 0 and monthly ticket=1

If one of discount=1 and ticket=0, the next value for running total has to be 0.

running_total<50

If running total>=50, the value for running total has to start from the value on the same row.

Here is what I'm trying to do now:

Is there any possibility to do this in HIVE? Thank you so much!!!

```<code>SELECT * ,
       SUM(tag_flg) OVER (PARTITION BY account, flg_sum
                      ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
       AS running_sum
FROM
  ( SELECT * ,
           SUM(CASE
                   WHEN tag_flg>=50 THEN value
                   ELSE tag_flg
               END) OVER (PARTITION BY account
                          ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
           AS flg_sum
   FROM
     ( SELECT * ,
              CASE
                  WHEN month_disc =0
                       AND month_ticket = 1 THEN value
                  ELSE 0
              END AS tag_flg
      FROM source_table) x) y
</code>```

答:
Here is the way I managed to do it:</p>

```<code>SELECT *,
       SUM(case when month_disc=1 OR month_ticket=0 then 0 else value end) OVER (PARTITION BY account, flg_sum, band_sum ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_sum
 FROM (
    SELECT *,
           FLOOR(SUM(case when month_disc=1 OR month_ticket=0 then 0 else value end) OVER (PARTITION BY account, flg_sum ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)/50.000001) as band_sum ---- create bands for running total
 FROM (
    SELECT *,
          SUM(tag_flg) OVER (PARTITION BY account ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS flg_sum
 FROM (
    SELECT *,
          CASE WHEN  (month_disc=1 OR month_ticket=0) THEN 1 ELSE 0 END AS tag_flg ---- flag to count when the value is reset due to one of the conditions
    FROM source_table) x ) y) z
</code>```

Body:
I'm trying to compute a running total and reset it to 0 based on 2 conditions or if the limit is reached.

Here is an example.

As in the image above, I need to get the running total while the following conditions are met:

monthly discount = 0 and monthly ticket=1

If one of discount=1 and ticket=0, the next value for running total has to be 0.

running_total<50

If running total>=50, the value for running total has to start from the value on the same row.

Here is what I'm trying to do now:

Is there any possibility to do this in HIVE? Thank you so much!!!

SELECT * ,
       SUM(tag_flg) OVER (PARTITION BY account, flg_sum
                      ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
       AS running_sum
FROM
  ( SELECT * ,
           SUM(CASE
                   WHEN tag_flg>=50 THEN value
                   ELSE tag_flg
               END) OVER (PARTITION BY account
                          ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
           AS flg_sum
   FROM
     ( SELECT * ,
              CASE
                  WHEN month_disc =0
                       AND month_ticket = 1 THEN value
                  ELSE 0
              END AS tag_flg
      FROM source_table) x) y

Body:
Here is the way I managed to do it:

SELECT *,
       SUM(case when month_disc=1 OR month_ticket=0 then 0 else value end) OVER (PARTITION BY account, flg_sum, band_sum ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_sum
 FROM (
    SELECT *,
           FLOOR(SUM(case when month_disc=1 OR month_ticket=0 then 0 else value end) OVER (PARTITION BY account, flg_sum ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)/50.000001) as band_sum ---- create bands for running total
 FROM (
    SELECT *,
          SUM(tag_flg) OVER (PARTITION BY account ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS flg_sum
 FROM (
    SELECT *,
          CASE WHEN  (month_disc=1 OR month_ticket=0) THEN 1 ELSE 0 END AS tag_flg ---- flag to count when the value is reset due to one of the conditions
    FROM source_table) x ) y) z


问:
How to recursively list all the files in a directory in C#?
How to recursively list all the files in a directory and child directories in C#?</p>

答:
```<code>var d = new DirectoryInfo(@"C:\logs");
var list = d.GetFiles("*.txt").Select(m => m.Name).ToList();
</code>```

OwnerDisplayName: Arjab

ContentLicense: CC BY-SA 2.5


问:
How to implement communication between consumer and producer with fast and slow workers?
I'm looking for a pattern and existing implementations for my situation:
I have synchronous soa which uses REST APIs, in fact I implement remote procedure call with REST. And I have got some slow workers which process requests for substantial time (around 30 seconds) and due to some license constraints for some requests I can process them only sequentially (see system setup).

What are recommended ways to implement communication for such case?

How can I mix synchronous and asynchronous communication in the situation when the consumer is behind firewall and I cannot send him notification about completed tasks easily and I might not be able to let consumer use my message broker if I have one?

Workers are implemented in Python using Flask and gunicorn. At the moment I'm using synchronous REST interfaces and allow for the delay as I only had fast workers. I looked at Kafka and RabbitMq and they would fit for backend side
communication, however how does producer communicate with the consumer?

If the consumer fires API request my producer can return code 202, then how shall producer notify consumer that result is available? Will consumer have to poll the producer for results?

Also if I use message brokers and my gateway acts on behalf of consumer, it should have a registry of requests (I already have GUID for every request now) and results, which approach would you recommend for implementing it?

答:
Producer- agent which produces the message
Consumer - agent which can handle the message and implement the logic for processing the message


问:
Is there a way to produce animations beyond stacks of images in UIImage?
I'm fairly new to iOS development, and I was wondering: is there a way to produce animations on the iPhone besides creating a bunch of still images and animating them in a UIImageView?  What are the other methods for creating a moving animation on iOS?</p>

答: Apple has an entire framework called Core Animation that is built to help you make animations within your interface.  I recommend checking out the various resources listed in this question for learning how to use Core Animation in its various forms.</p>


问:
how to make Alexa correctly respond to: Alexa, ask (tell) [invocation name] (linking word if any) [intent Utterances]?
When I say, "Alexa, open/launch/start Mighty Righty"
She responds as intended. When I say "Alexa, ASK mighty Righty who is right, me or you", she doesn't launch the app and just says: "Sorry, I don't know that one." I actually couldn't pass function validation for Amazon app certification because of that (I think). Here is the result of functional test:

1 Fix Required

The skill should not respond to intent requests with empty text or SSML in reprompt while keeping the skill session open.

The skill responds to users with an empty speech reprompt when the skill session is open. Please note that when the skill session is open, the skill should not return empty text or silent ssml response for any supported intent(s) within the skill.

Below are the list of intents that responded with a silent reprompt.

Intent Name - playerBio, Utterance - who is right me or her

Intent Name - playerBio, Utterance - alexa ask mighty righty who is right me or my children

Intent Name - playerBio, Utterance - who is right me or you

I have tried to play with LaunchRequest
IntentRequest
SessionEndedRequest
but I am not a coder. I just followed a tutorial and came this far. I just need to fix that error that Amazon "RUN" test found. And I will be able to publish the app.

```<code>#------------------------------Part1--------------------------------
# In this part we define a list that contains the player names, and
# a dictionary with player biographies

Player_LIST = ["me or my wife", "me or my husband", "me or you"]

Player_BIOGRAPHY = {"me or my wife": ["She is. Do as she says, and you'll be OK.", "You", "Of course, your wife", "No doubt, it's you"],

"me or my husband": ["He is", "You are right", "He is not right", "Your husband. He is always right."],

"me or you": ["me", "You are, ... I mean... you are wrong, of course", "of course me", "It's me, don't you know that, my friend?", "you yourself, what do you think? Of course it's me", "I always know who is right, me or not me, so, it's meeeeee", "what do you think? I am Mighty Righty, so I am RIGHT"]}

#------------------------------Part2--------------------------------
# Here we define our Lambda function and configure what it does when
# an event with a Launch, Intent and Session End Requests are sent. # The Lambda function responses to an event carrying a particular
# Request are handled by functions such as on_launch(event) and
# intent_scheme(event).

def lambda_handler(event, context):
    if event['session']['new']:
        on_start()
    if event['request']['type'] == "LaunchRequest":
        return on_launch(event)
    elif event['request']['type'] == "IntentRequest":
        return intent_scheme(event)
    elif event['request']['type'] == "SessionEndedRequest":
        return on_end()

#------------------------------Part3--------------------------------
# Here we define the Request handler functions

def on_start():
    print("Session Started.")

def on_launch(event):
    onlunch_MSG = "Hi, start with the word. Me. For example: who is right, me or my husband?"
    reprompt_MSG = "you can say, who is right, me or my wife?"
    card_TEXT = "Who is right, me or... ?."
    card_TITLE = "Choose your question."
    return output_json_builder_with_reprompt_and_card(onlunch_MSG, card_TEXT, card_TITLE, reprompt_MSG, False)

def on_end():
    print("Session Ended.")

#-----------------------------Part3.1-------------------------------
# The intent_scheme(event) function handles the Intent Request.
# Since we have a few different intents in our skill, we need to
# configure what this function will do upon receiving a particular
# intent. This can be done by introducing the functions which handle
# each of the intents.

def intent_scheme(event):

    intent_name = event['request']['intent']['name']

    if intent_name == "playerBio":
        return player_bio(event)
    elif intent_name in ["AMAZON.NoIntent", "AMAZON.StopIntent", "AMAZON.CancelIntent"]:
        return stop_the_skill(event)
    elif intent_name == "AMAZON.HelpIntent":
        return assistance(event)
    elif intent_name == "AMAZON.FallbackIntent":
        return fallback_call(event)

#---------------------------Part3.1.1-------------------------------
# Here we define the intent handler functions

import random # this can be at the top of the file too
def player_bio(event):
    name=event['request']['intent']['slots']['player']['value']
    player_list_lower=[w.lower() for w in Player_LIST]
    if name.lower() in player_list_lower:
        reprompt_MSG = ""
        card_TEXT = "You've picked " + name.lower()
        card_TITLE = "You've picked " + name.lower()
        return output_json_builder_with_reprompt_and_card(random.choice(Player_BIOGRAPHY[name.lower()]), card_TEXT, card_TITLE, reprompt_MSG, False)
    else:
        wrongname_MSG = "Some questions may not yet be present in my database. Try to rephrase your sentence."
        reprompt_MSG = "For example, who is right, me or my wife?"
        card_TEXT = "Use the full question."
        card_TITLE = "Wrong question."
        return output_json_builder_with_reprompt_and_card(wrongname_MSG, card_TEXT, card_TITLE, reprompt_MSG, False)

def stop_the_skill(event):
    stop_MSG = "Bye for now and feel free to ask mighty righty who is right"
    reprompt_MSG = ""
    card_TEXT = "Bye."
    card_TITLE = "Bye Bye."
    return output_json_builder_with_reprompt_and_card(stop_MSG, card_TEXT, card_TITLE, reprompt_MSG, True)

def assistance(event):
    assistance_MSG = "start with the word. Me."
    reprompt_MSG = "For example, who is right me or him"
    card_TEXT = "You've asked for help."
    card_TITLE = "Help"
    return output_json_builder_with_reprompt_and_card(assistance_MSG, card_TEXT, card_TITLE, reprompt_MSG, False)

def fallback_call(event):
    fallback_MSG = "Try to say, for example, who is right, me or him?"
    reprompt_MSG = "Certain answers may not yet be in my database. Use personal pronouns, for example: me, or her, me, or him, me, or them. They can cover pretty much everybody"
    card_TEXT = "You've asked a wrong question."
    card_TITLE = "Wrong question."
    return output_json_builder_with_reprompt_and_card(fallback_MSG, card_TEXT, card_TITLE, reprompt_MSG, False)

#------------------------------Part4--------------------------------
# The response of our Lambda function should be in a json format.
# That is why in this part of the code we define the functions which
# will build the response in the requested format. These functions
# are used by both the intent handlers and the request handlers to
# build the output.

def plain_text_builder(text_body):
    text_dict = {}
    text_dict['type'] = 'PlainText'
    text_dict['text'] = text_body
    return text_dict

def reprompt_builder(repr_text):
    reprompt_dict = {}
    reprompt_dict['outputSpeech'] = plain_text_builder(repr_text)
    return reprompt_dict

def card_builder(c_text, c_title):
    card_dict = {}
    card_dict['type'] = "Simple"
    card_dict['title'] = c_title
    card_dict['content'] = c_text
    return card_dict

def response_field_builder_with_reprompt_and_card(outputSpeach_text, card_text, card_title, reprompt_text, value):
    speech_dict = {}
    speech_dict['outputSpeech'] = plain_text_builder(outputSpeach_text)
    speech_dict['card'] = card_builder(card_text, card_title)
    speech_dict['reprompt'] = reprompt_builder(reprompt_text)
    speech_dict['shouldEndSession'] = value
    return speech_dict

def output_json_builder_with_reprompt_and_card(outputSpeach_text, card_text, card_title, reprompt_text, value):
    response_dict = {}
    response_dict['version'] = '1.0'
    response_dict['response'] = response_field_builder_with_reprompt_and_card(outputSpeach_text, card_text, card_title, reprompt_text, value)
    return response_dict
</code>```

I expect that error message "1 Fixed Required" to disappear. I will be able to submit my app to Amazon. Please, help me to publish my app!

答: The problem is clear and shows in the code. You have empty reprompts which is not allowed. You need to put a reprompt text in all places where you have reprompt_MSG = ""

Body:
When I say, "Alexa, open/launch/start Mighty Righty"
She responds as intended. When I say "Alexa, ASK mighty Righty who is right, me or you", she doesn't launch the app and just says: "Sorry, I don't know that one." I actually couldn't pass function validation for Amazon app certification because of that (I think). Here is the result of functional test:

1 Fix Required

The skill should not respond to intent requests with empty text or SSML in reprompt while keeping the skill session open.

The skill responds to users with an empty speech reprompt when the skill session is open. Please note that when the skill session is open, the skill should not return empty text or silent ssml response for any supported intent(s) within the skill.

Below are the list of intents that responded with a silent reprompt.

Intent Name - playerBio, Utterance - who is right me or her

Intent Name - playerBio, Utterance - alexa ask mighty righty who is right me or my children

Intent Name - playerBio, Utterance - who is right me or you

I have tried to play with LaunchRequest
IntentRequest
SessionEndedRequest
but I am not a coder. I just followed a tutorial and came this far. I just need to fix that error that Amazon "RUN" test found. And I will be able to publish the app.

#------------------------------Part1--------------------------------
# In this part we define a list that contains the player names, and
# a dictionary with player biographies

Player_LIST = ["me or my wife", "me or my husband", "me or you"]

Player_BIOGRAPHY = {"me or my wife": ["She is. Do as she says, and you'll be OK.", "You", "Of course, your wife", "No doubt, it's you"],

"me or my husband": ["He is", "You are right", "He is not right", "Your husband. He is always right."],

"me or you": ["me", "You are, ... I mean... you are wrong, of course", "of course me", "It's me, don't you know that, my friend?", "you yourself, what do you think? Of course it's me", "I always know who is right, me or not me, so, it's meeeeee", "what do you think? I am Mighty Righty, so I am RIGHT"]}

#------------------------------Part2--------------------------------
# Here we define our Lambda function and configure what it does when
# an event with a Launch, Intent and Session End Requests are sent. # The Lambda function responses to an event carrying a particular
# Request are handled by functions such as on_launch(event) and
# intent_scheme(event).

def lambda_handler(event, context):
    if event['session']['new']:
        on_start()
    if event['request']['type'] == "LaunchRequest":
        return on_launch(event)
    elif event['request']['type'] == "IntentRequest":
        return intent_scheme(event)
    elif event['request']['type'] == "SessionEndedRequest":
        return on_end()

#------------------------------Part3--------------------------------
# Here we define the Request handler functions

def on_start():
    print("Session Started.")

def on_launch(event):
    onlunch_MSG = "Hi, start with the word. Me. For example: who is right, me or my husband?"
    reprompt_MSG = "you can say, who is right, me or my wife?"
    card_TEXT = "Who is right, me or... ?."
    card_TITLE = "Choose your question."
    return output_json_builder_with_reprompt_and_card(onlunch_MSG, card_TEXT, card_TITLE, reprompt_MSG, False)

def on_end():
    print("Session Ended.")

#-----------------------------Part3.1-------------------------------
# The intent_scheme(event) function handles the Intent Request.
# Since we have a few different intents in our skill, we need to
# configure what this function will do upon receiving a particular
# intent. This can be done by introducing the functions which handle
# each of the intents.

def intent_scheme(event):

    intent_name = event['request']['intent']['name']

    if intent_name == "playerBio":
        return player_bio(event)
    elif intent_name in ["AMAZON.NoIntent", "AMAZON.StopIntent", "AMAZON.CancelIntent"]:
        return stop_the_skill(event)
    elif intent_name == "AMAZON.HelpIntent":
        return assistance(event)
    elif intent_name == "AMAZON.FallbackIntent":
        return fallback_call(event)

#---------------------------Part3.1.1-------------------------------
# Here we define the intent handler functions

import random # this can be at the top of the file too
def player_bio(event):
    name=event['request']['intent']['slots']['player']['value']
    player_list_lower=[w.lower() for w in Player_LIST]
    if name.lower() in player_list_lower:
        reprompt_MSG = ""
        card_TEXT = "You've picked " + name.lower()
        card_TITLE = "You've picked " + name.lower()
        return output_json_builder_with_reprompt_and_card(random.choice(Player_BIOGRAPHY[name.lower()]), card_TEXT, card_TITLE, reprompt_MSG, False)
    else:
        wrongname_MSG = "Some questions may not yet be present in my database. Try to rephrase your sentence."
        reprompt_MSG = "For example, who is right, me or my wife?"
        card_TEXT = "Use the full question."
        card_TITLE = "Wrong question."
        return output_json_builder_with_reprompt_and_card(wrongname_MSG, card_TEXT, card_TITLE, reprompt_MSG, False)

def stop_the_skill(event):
    stop_MSG = "Bye for now and feel free to ask mighty righty who is right"
    reprompt_MSG = ""
    card_TEXT = "Bye."
    card_TITLE = "Bye Bye."
    return output_json_builder_with_reprompt_and_card(stop_MSG, card_TEXT, card_TITLE, reprompt_MSG, True)

def assistance(event):
    assistance_MSG = "start with the word. Me."
    reprompt_MSG = "For example, who is right me or him"
    card_TEXT = "You've asked for help."
    card_TITLE = "Help"
    return output_json_builder_with_reprompt_and_card(assistance_MSG, card_TEXT, card_TITLE, reprompt_MSG, False)

def fallback_call(event):
    fallback_MSG = "Try to say, for example, who is right, me or him?"
    reprompt_MSG = "Certain answers may not yet be in my database. Use personal pronouns, for example: me, or her, me, or him, me, or them. They can cover pretty much everybody"
    card_TEXT = "You've asked a wrong question."
    card_TITLE = "Wrong question."
    return output_json_builder_with_reprompt_and_card(fallback_MSG, card_TEXT, card_TITLE, reprompt_MSG, False)

#------------------------------Part4--------------------------------
# The response of our Lambda function should be in a json format.
# That is why in this part of the code we define the functions which
# will build the response in the requested format. These functions
# are used by both the intent handlers and the request handlers to
# build the output.

def plain_text_builder(text_body):
    text_dict = {}
    text_dict['type'] = 'PlainText'
    text_dict['text'] = text_body
    return text_dict

def reprompt_builder(repr_text):
    reprompt_dict = {}
    reprompt_dict['outputSpeech'] = plain_text_builder(repr_text)
    return reprompt_dict

def card_builder(c_text, c_title):
    card_dict = {}
    card_dict['type'] = "Simple"
    card_dict['title'] = c_title
    card_dict['content'] = c_text
    return card_dict

def response_field_builder_with_reprompt_and_card(outputSpeach_text, card_text, card_title, reprompt_text, value):
    speech_dict = {}
    speech_dict['outputSpeech'] = plain_text_builder(outputSpeach_text)
    speech_dict['card'] = card_builder(card_text, card_title)
    speech_dict['reprompt'] = reprompt_builder(reprompt_text)
    speech_dict['shouldEndSession'] = value
    return speech_dict

def output_json_builder_with_reprompt_and_card(outputSpeach_text, card_text, card_title, reprompt_text, value):
    response_dict = {}
    response_dict['version'] = '1.0'
    response_dict['response'] = response_field_builder_with_reprompt_and_card(outputSpeach_text, card_text, card_title, reprompt_text, value)
    return response_dict

I expect that error message "1 Fixed Required" to disappear. I will be able to submit my app to Amazon. Please, help me to publish my app!


问:
Angular 8 - Lazy loading modules : Error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'
When I updated Angular from 7 to Angular 8, getting error for lazy loading modules

I have tried the options, which are there in the angular upgradation guide

Made the below changes:

Before

```<code>    loadChildren: '../feature/path/sample-
                         tage.module#SameTagModule'
</code>```

After

```<code>   loadChildren: () => import('../feature/path/sample-
                      tags.module').then(m => m.CreateLinksModule)
</code>```

error TS1323: Dynamic import is only supported when '--module' flag is
  'commonjs' or 'esNext'.

答:
You are using dynamic import so you have to change your tsconfig.json like this to target your code to esnext module

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext", // add this line
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}
</code>```

Also make sure to check tsconfig.app.json dont have module and target config something like this

```<code>{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": []
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "src/test.ts",
    "src/**/*.spec.ts"
  ]
}
</code>```

Body:
When I updated Angular from 7 to Angular 8, getting error for lazy loading modules

I have tried the options, which are there in the angular upgradation guide

Made the below changes:

Before

    loadChildren: '../feature/path/sample-
                         tage.module#SameTagModule'

After

   loadChildren: () => import('../feature/path/sample-
                      tags.module').then(m => m.CreateLinksModule)

error TS1323: Dynamic import is only supported when '--module' flag is
  'commonjs' or 'esNext'.

Body:
You are using dynamic import so you have to change your tsconfig.json like this to target your code to esnext module

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext", // add this line
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}

Also make sure to check tsconfig.app.json dont have module and target config something like this

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": []
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "src/test.ts",
    "src/**/*.spec.ts"
  ]
}