Keyboard input in Amazon.com main search field

Steps to reproduce:

  1. On a device with a keyboard, go to amazon.com.
  2. Type several words in the main search field; it turns into a drop-down suggestion list.
  3. Try editing your entry using your keyboard’s left and right arrow keys to move around in it.

You can’t.
(Furthermore, in my machine, if I use the mouse to place the cursor anywhere in the text field, either arrow key skips the cursor to the end of the input text.)

Expected behavior:

It’s a text input field. We should be able to use the left/right arrow keys (and their alt/Ctrl/shift modifiers depending on your OS) to move about the field.

Notes:

Tested in Chrome, Chrome Incognito, and Safari (MacOS) – on 2 different machines. Same behavior. I checked that afaik no plugins/extensions are affecting this behavior.

Why I posted this:

  1. Please test to see if you reproduce the same behavior.
  2. If you happen to be a web wiz, diagnose what’s happening. I venture Amazon forces the browser’s focus wrongly somehow – the dropdown element steals all keyboard input instead of only up+down, so the browser doesn’t “realize” you’re trying to control the text field.
  3. Are there user-side ways to mitigate or workaround this? For now best I found was “Escape” to dismiss the drop-down suggestions..

unity – Strategy for temporarily blocking user input

As DMGregory noted, a Canvas Group is an easy way to control interactivity for a group of UI controls. Just assign the Canvas Group to the parent containing your UI controls, and update the interactable property:

canvasGroup.interactable = false;

As for user interaction with non-UI GameObjects, there are several approaches depending on how you process input:

  • Update() does not run if the MonoBehaviour is disabled. For example:
public class ClickableGameObject : MonoBehaviour {
    void Update() {
        if (Input.GetMouseButtonDown(0)) {
            //handle click here
        }
    }
}

clickableGO.enabled = false; //disables the Update() function
  • For other functions like OnMouseDown() or OnPointerClick(), you’ll need a flag you can check to see if the input should be disabled. There are several ways to do this. Here are a few examples:
//This solution is clean but may require you to call `Interactable = true;` or `Interactable = false;` 
//on many objects depending on your game structure.
public class ClickableGameObject : MonoBehaviour {
    (SerializeField) private bool interactable = true;
    public bool Interactable { get => interactable; set => interactable = value; }

    void OnMouseDown() {
        if (!interactable) return;
        //handle click here
    }
}
//this solution uses a global static variable, which is generally bad practice,
//but can save a lot of effort in this case:
public static class UserInput {
    public static bool InputEnabled {get; set;} = true;
}

public class ClickableGameObject : MonoBehaviour {
    void OnMouseDown() {
        if (!UserInput.InputEnabled) return;
        //handle click here
    }
}
//this solution is a compromise between the above two solutions
public class UserInputSettings {
    public bool InputEnabled {get; set;} = true;
}

public class ClickableGameObject : MonoBehaviour {
    public UserInputSettings InputSettings { get; set; }
    
    void OnMouseDown() {
        if (!InputSettings.InputEnabled) return;
        //handle click here
    }
}

//create the settings instance before instantiating your GameObjects
UserInputSettings settings = new UserInputSettings();

//assign the settings to your GameObjects immediately after instantiating them
ClickableGameObject clickableGO1 = Instantiate(clickableGOPrefab);
clickableGO1.InputSettings = settings;
ClickableGameObject clickableGO2 = Instantiate(clickableGOPrefab);
clickableGO2.InputSettings = settings;

//affects all GameObjects we've assigned the settings to
settings.InputEnabled = false;

php – INSERTAR INPUT FILE EN MYSQL

Buenas tardes estoy realizando un formulario que con java agregue o elimine dos input file, el problema es que cuando quiero que estos se envien y la ruta se inserte en una tabla de mysql, no me toma el valor del segundo input, solo el primero.

este es el fragmento del html para el envio de los archivos

<div class="card shadow mb-4">
<div class="card-header py-3 card" style="background-color: #17325c;">
<h6 class="m-0 font-weight-bold text-white"> <i class="fas fa-file"></i> Enviar Tarea</h6>
</div>
<div class="card-body">
       <table class="table table-bordered" id="dynamic_field">
       <tr>
  <div class="input-group mb-3">
  <div class="input-group-prepend">
  <td><input type="file" name="file" class="form-control" /></td>
     
  </div>
  <div class="input-group-append">

  <td style="width:15px;"><button name="add" id="add" class="btn text-white" style="background-color: #17325c;" type="button">+</button></td>
  
  </div>
 </div></tr>
 </table>  
 
    <div align="right">
            
    <input type="submit" name="submit" value="Enviar" class="btn text-white"style="background-color: #17325c;"></div>
</form>

el script para agregar y eliminar el input, no permite agregar mas de 2

<script>
$(document).ready(function() {

$("#fuSubirExcel").on('change', function() {
    var fileName = $(this).val().split("\").pop();
    $(this).siblings(".custom-file-label").addClass("selected").html(fileName);        
})

});

$(document).ready(function(){
    var i=1;
    $('#add').click(function(){
        i++;
    if (i>=3){

alert("NO PUEDES AGREGAR MAS"); }
  
 if (i==2){
        $('#dynamic_field').append('<tr id="row'+i+'"><td><input type="file" name="jon" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
    }
  });
$(document).on('click', '.btn_remove', function(){
        var button_id = $(this).attr("id"); 
        $('#row'+button_id+'').remove();
    });
});
</script>

el php con el que se cargan los archivos y donde no me lee el segundo input, me lo marca como desconocido

<?php
$archivo=$ncuenta.basename($_FILES('file')('name'));
$archivo1=$ncuenta.basename($_FILES('jon')('name'));
$directorio = 'NUEVO/';
$subir_archivo = $directorio.$ncuenta.basename($_FILES('file')('name'));
$subir_archivo1 = $directorio.$ncuenta.basename($_FILES('file2')('name'));
if (move_uploaded_file($_FILES('file')('tmp_name'), $subir_archivo) || (move_uploaded_file($_FILES('file2')('tmp_name'), $subir_archivo1))) {
  
$sql="INSERT INTO tareasenviadas (ncuenta,nombre,fecha,grupo,profesor,titulo,materia,comentarios,archivo,archivo1) VALUES ('$ncuenta','$nombre','$fecha','$grupo','$profesor','$titulo','$materia','$reporte','$archivo','$archivo1')";
   
$db = obtenerConexion();
$rs=ejecutarQuery($db, $sql);
?>

espero me puedan ayudar, ya que he intentado concatenar el name del segundo input pero ni asi me lo detecta.

Best practice for comma separated input size for the search field

So to reiterate:

  • Users have .csvs or other files where large numbers of IMEis are listed
  • They need to be able to search for these IMEIs in your system

Ideally you’d have access to analytics or user interviews that could help you define the upper limit users search. It sounds like you don’t have access to either, so in the meantime we can make a few assumptions.

As you said, it seems the most likely scenario is that they’ll be copying and pasting these numbers, as they are difficult to correctly input due to their length. They likely won’t be checking their work, again due to length, so displaying the pasted content is mostly irrelevant – you can display “1234567890abcde, 1234567890abcde, and 498 more“, which should give them enough information about their search to complete their task.

The main bottleneck will likely be your backend system, not the UI. If you paste 500 IMEIs, how fast does the system respond? If it slows at any point and effects the UX, you’ve found your limit. If it responds adequately for 10,000 IMEIs, there’s little reason to limit it at all.

c++ – Unit Test template function with terminal input

I wrote some template function, which helps me with reading input from terminal, doing error handling, validating input.

The full code with template specialisation for strings looks like this:

template <typename T>
T getInput(const std::string& prompt, std::istream& istream, std::ostream& ostream,
           std::function<bool(T)> isValid = nullptr) {
    T input;

    while(true) {
        ostream << prompt << "n>> ";

        if((istream >> input) && (!isValid || isValid(input)))
            break;

        if(istream)
            continue;

        istream.clear();
        istream.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
        ostream << "Reading input failed, please try again!n";
    }
    istream.ignore(std::numeric_limits<std::streamsize>::max(), 'n');

    return input;
}

template <>
inline std::string getInput<std::string>(const std::string& prompt, std::istream& istream, std::ostream& ostream,
                                         std::function<bool(std::string)> isValid) {
    std::string textInput;

    while(true) {
        ostream << prompt << "n>> ";

        if(std::getline(istream, textInput) && (!isValid || isValid(textInput)))
            break;

        if(istream)
            continue;

        ostream << "You probably entered EOF or exceeded the maximum text input size, please try again!n";
        istream.clear();
    }

    return textInput;
}

Some usage might look like this:

getInput<double>("Enter positve number?", istream, ostream, ()(const double input) {
        bool correctInput = (input >= 0);
        if(!correctInput)
            ostream << "Number can only be greater than 0.n";
        return correctInput;
});

So the function works like this in a nutshell:

  • Print Question
  • Read Input from command line
  • If not sucessfull (cin fails), print some generic error message and repeat
  • If sucessfull, call lambda validation function (if existent)
  • If input is valid return it, otherwise the lambda will print some specific error message and repeat

So what I thought I need to test:

  • Reading numbers without lambda function works and fails when expected (cin fails or not)
  • Reading numbers with lambda function works and fails when exspected (input valid or not)
  • The same just with strings (specialisation)

So in sum 8 TestCases which I structured into two Scenarios: Read numeric input, read non-numeric input.

The whole Code looks like this (uses Catch2 as Unit Test Framework):

using Catch::Matchers::Contains;
using Catch::Matchers::Matches;

SCENARIO("Read numeric input from command line") {
    GIVEN("Some input and output stream") {
        std::istringstream iss {};
        std::ostringstream oss {};

        WHEN("calling getInput<int> without valid function entering some non-numeric value") {
            iss.str("42");

            int input = getInput<int>("Some Question", iss, oss);

            THEN("message is printed once and input returned") {
                REQUIRE_THAT(oss.str(), Contains("Some Question"));
                REQUIRE(input == 42);
            }
        }

        WHEN("calling getInput<int> without valid function entering some non-numeric value") {
            iss.str("Stringn42");

            int input = getInput<int>("Some Question", iss, oss);

            THEN("error message is printed and question is repeated") {
                REQUIRE_THAT(
                    oss.str(),
                    Matches("(\s\S)*Some Question(\s\S)*please try again(\s\S)*Some Question(\s\S)*"));
            }
        }

        WHEN("calling getInput<int> with valid function entering some valid numeric input") {
            iss.str("42");

            int input = getInput<int>("Some Question", iss, oss, ()(int value) { return value > 0; });

            THEN("message is printed once and input returned") {
                REQUIRE_THAT(oss.str(), Contains("Some Question"));
                REQUIRE(input == 42);
            }
        }

        WHEN("calling getInput<int> with valid function entering some invalid numeric input") {
            iss.str("-20n20");

            int input = getInput<int>("Some Question", iss, oss, ()(int value) { return value > 0; });

            THEN("the question is repeated") {
                REQUIRE_THAT(oss.str(), Matches("(\s\S)*Some Question(\s\S)*Some Question(\s\S)*"));
            }
        }
    }
}

SCENARIO("Read text input from command line") {
    GIVEN("Some input and output stream") {
        std::istringstream iss {};
        std::ostringstream oss {};

        WHEN("calling getInput<std::string> without valid function entering some text") {
            iss.str("Some input");

            std::string input = getInput<std::string>("Some Question", iss, oss);

            THEN("message is printed once and input returned") {
                REQUIRE_THAT(oss.str(), Contains("Some Question"));
                REQUIRE(input == "Some input");
            }
        }

        WHEN("calling getInput<int> without valid function entering some non-numeric value") {
            iss.str("StringnString");
            iss.setstate(std::ios::failbit);

            std::string input = getInput<std::string>("Some Question", iss, oss);

            THEN("error message is printed and question is repeated") {
                REQUIRE_THAT(
                    oss.str(),
                    Matches("(\s\S)*Some Question(\s\S)*please try again(\s\S)*Some Question(\s\S)*"));
            }
        }

        WHEN("calling getInput<int> with valid function entering some valid text input") {
            iss.str("Some input");

            std::string input = getInput<std::string>("Some Question", iss, oss,
                                                      ()(std::string value) { return value.length() >= 3; });

            THEN("message is printed once and input returned") {
                REQUIRE_THAT(oss.str(), Contains("Some Question"));
                REQUIRE(input == "Some input");
            }
        }

        WHEN("calling getInput<int> with valid function entering some invalid text input") {
            iss.str("anabc");

            std::string input = getInput<std::string>("Some Question", iss, oss,
                                                      ()(std::string value) { return value.length() >= 3; });

            THEN("the question is repeated") {
                REQUIRE_THAT(oss.str(), Matches("(\s\S)*Some Question(\s\S)*Some Question(\s\S)*"));
            }
        }
    }
}

My ideas how to test it:

  • Mock input and output by using stringstreams
  • In success cases check that input is correctly (obviously) and that question was in fact asked (Not to sure if one would do that … but I thought this is something I expect from the method, so why not test it)
  • In failure cases, check if question was asked twice (to test whether the user is asked again for input) and possibly check if some error message is printed if it’s expected (-> cin fails)

In general I’m happy for any suggestion. But just to list some things / questions in particular, where I would love to get feedback:

  • Are my Scenarios / test cases good chosen, i.e. is the structure good
  • Can my wording be improved. I don’t mean specific language errors here, but rather if the content is good. So for example that I need fake streams here doesn’t seems so relevant. Mainly because I just need them to make the function testable. Without tests, I wouldn’t need them. But in this case, there would be nothing else that I need in the given part (usually for classes you would need at least the object with some properties set)
  • Is the code in the right place, for example I wondered whether the iss.str() part shouldn’t be in the “GIVEN” rather as I usually configure mocks there. But the concrete values for mocks depend here on my THEN, which makes it clearer to me to put them inside the THEN.
  • Are my Asserts any good? I had particular problems to test my failure cases as in these case, the function enters the while loop. So I always had to mock the stream, so it would fail first and then pass, which seemed a little bit weird to me. Furthermore it wasn’t to easy to assert that behaviour then.

As said, if you see other improvements please show me them as well 🙂

Thanks for your valuable feedback!

Search field comma separated input size best practice

In case working with large number of entries in web UI such as IoT device list with IMEI. And in case there is a need to make quick multiple selection by IMEI.
Would it be good practice to provide search field with possibility to enter comma separated IMEIs?
In most cases those IMEIs will be pasted into search field.

What would be sane maximum limit for such input?
50 IMEIs (850 symbols), 100 IMEIs (1700 symbols), even more?
What is main bottle neck for such solution?

I understand CSV file import could be used, but we want quicker solution.

woocommerce offtopic – No access to the created input

I added an extra field to the cart.php using Snippet plugin.

function action_woocommerce_cart_coupon() { 
    echo '<input type="text" name="card" class="input-text" id="card" value="" placeholder="Card" />';
}; 
         
add_action( 'woocommerce_cart_coupon', 'action_woocommerce_cart_coupon'); 

And I would my own validation when the Apply coupon button is clicked. Unfortunately, There is no way I can get value of this new field.

I downloaded the post in several places but I don’t have access to this field.

if ( ! empty( $_POST('card') ) ) {
    echo '<script>console.log("' . $_POST('card') . '")</script>';
} else {
    echo '<script>console.log("PHP error")</script>';
}
function action_woocommerce_applied_coupon( $coupon_code ) { 
        foreach ($_POST as $key => $value) {
            echo '<script>console.log("' . $key . " " . $value . '")</script>';
        }
}; 
         
add_action( 'woocommerce_applied_coupon', 'action_woocommerce_applied_coupon'); 

Output:

security ac228a43c2
coupon_code 1

I understand this is called in class-wc-cart.php but I can’t understand how I could pass this field to this method. Is anyone able to tell me something about this?

I will also appreciate any other ideas to solve this problem.

magento2 – How can i add a custom input filed (not attribute) using phtml in product edit page in magneto 2.4

I want to add a custom checkbox list filed (not attribute)in product edit page. Therefore I call a phtml file in product admin and set checkbox input filed (which is dynamic).But when i am using observer “controller_action_catalog_product_save_entity_after” and print $_POST value my custom filed is not showing or coming.

i am shsreing the code

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="add_product_label_ids">
       <argument name="data" xsi:type="array">
           <item name="config" xsi:type="array">
               <item name="label" xsi:type="string" translate="true">Product Label</item>
               <item name="collapsible" xsi:type="boolean">true</item>
               <item name="sortOrder" xsi:type="number">9999</item>
           </item>
       </argument>
       <container name="add_product_label_ids" >
           <argument name="data" xsi:type="array">
               <item name="config" xsi:type="array">
                   <item name="sortOrder" xsi:type="number">1</item>
               </item>
           </argument>
           <htmlContent name="html_content_demo">
               <argument name="block" xsi:type="object">CustommizationProductlabelcustomizationBlockAdminhtmlCatalogProductEditTabProductlabel</argument>
           </htmlContent>
       </container>
   </fieldset>
</form>

then in CustommizationProductlabelcustomizationBlockAdminhtmlCatalogProductEditTabProductlabel

<?php
namespace CustommizationProductlabelcustomizationBlockAdminhtmlCatalogProductEditTab;

use MagentoBackendBlockWidgetFormGeneric;
use MagentoBackendBlockWidgetTabTabInterface;
use MagentoFrameworkObjectManagerInterface;
class Productlabel extends Generic implements TabInterface
{
    protected $_template = 'Productlabel.phtml';

    protected $_systemStore;

    protected $_scopeConfig;
    
    protected $_labellistFactory;
    
    protected $objectManager;
    
    protected $_registry;

    public function __construct(
        MagentoBackendBlockTemplateContext $context,
        MagentoFrameworkDataFormFactory $formFactory,
        MagentoStoreModelSystemStore $systemStore,
        MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig,
        CustommizationProductlabelcustomizationModelLabellistFactory $labellistFactory,
        MagentoFrameworkRegistry $registry,
        ObjectManagerInterface $objectManager,
        array $data = ()
    ) {
        $this->_systemStore = $systemStore;
        $this->_scopeConfig = $scopeConfig;
        $this->_labellistFactory = $labellistFactory;
        $this->objectManager = $objectManager;
        $this->_registry = $registry;
        parent::__construct($context, $registry, $formFactory, $data);
    }

    public function getTabLabel()
    {
        return __('Actions');
    }

    public function getTabTitle()
    {
        return __('Actions');
    }

    public function canShowTab()
    {
        return true;
    }

    public function isHidden()
    {
        return false;
    }

    public function getReqest()
    {
        return $this->getRequest()->getParams();
    }
    
    public function getProductlabels()
    {
        $labelmodel = $this->_labellistFactory->create();
        return $labelmodel->getCollection();
    }
    public function getMediaUrl(){

        $media_dir = $this->objectManager->get('MagentoStoreModelStoreManagerInterface')
            ->getStore()
            ->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);

        return $media_dir;
    }
    public function getCurrentProductsku()
    {        
        $productdata = $this->_registry->registry('current_product');
        return $productdata->getSku();
    }  
    public function getcheckval($labelid,$skuval){
        $serval = array();
        $flag = 0;
        $labelmodel = $this->_labellistFactory->create()->load($labelid);
        $labelarray = $labelmodel->getData();
        if (array_key_exists("cond_serialize",$labelarray)){
            $serval = json_decode($labelarray('cond_serialize'), true);
            if($serval != NULL){
                foreach($serval as $key=>$val){
                    if($key == 'conditions'){
                        //$data() = $val; 
                        foreach($val as $nest){
                            if($nest('attribute') == 'sku'){
                                if($nest('value') == $skuval)
                                return $flag = 1;
                            }
                        }
                    }
                }
            }       
        }
        return $flag;
    }
    
}

Next in Productlabel.phtml

<div class="fieldset-wrapper-amasty-product-label" id="add-products-to-amasty-product-label">
    <fieldset class="fieldset-amasty-product-label" id="grop_fields-amasty-product-label">
        <legend class="legend-amasty-product-label">
            <span><?= $block->escapeHtml(__('Product Label')) ?></span>
        </legend>
        <br>
        <div class="store-scope-amasty-product-label">
            <div class="store-tree-amasty-product-label" id="add-products-to-amasty-product-label-content">
                <?php 
                    $skuval = $block->getCurrentProductsku();
                ?>
                
                 <?php foreach ($block->getProductlabels() as $_label):?>
                    <div class="label-name-amasty-product-label">
                        <?php
                                $checkcheked = $block->getcheckval($_label->getLabelId(),$skuval);                               
                               ?>
                        <input name="product(add_product_label_ids)()"
                               value="<?= $block->escapeHtmlAttr($_label->getLabelId()) ?>"
                               class="checkbox label-checkbox"
                               id="add_product_label_<?= $block->escapeHtmlAttr($_label->getLabelId()) ?>"
                               type="checkbox" 
                               <?php if ($checkcheked == 1):?>
                                    checked
                                <?php endif;?>
                               />
                        <img src="<?= $block->getMediaUrl().'amasty/amlabel/'.$_label->getProdImg() ?>" alt="<?= $_label->getName() ?>" >
                        <!--<label for="add_product_label_<?= $block->escapeHtmlAttr($_label->getLabelId()) ?>">
                            <?= $block->escapeHtml($_label->getName()) ?>
                        </label>-->
                        
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </fieldset>
</div>

using i get checkbox list in product edit page but when click on save
under this observer “controller_action_catalog_product_save_entity_after” i am tring get print_r($POST)
all post are showing expect my custom filed.
can anyone help me out.

linux – Using command Output (with spaces) as other command Input (BASH)

Any one know why this works?

cat `echo "FilenameWithoutSpaces.txt"` # shows file content

FILE CONTENT

And this not?

cat `echo "Filename With Spaces.txt"` # trying to show "Filename With Spaces.txt" content

cat: ‘Filename’: No such file or directory

cat: ‘With’: No such file or directory

cat: Spaces.txt: No such file or director

What would be the correct way to pass an output (with spaces) as a input of another command?

The example above is a simplified case of what i need. What I have to to is:

To use list of files (that may contain spaces) returned by a command as argument for another command.