text:
Q: send respective email of user in ajax i am working on ajax the problem i am facing is i have two functions, first one to get data through ajax for users from server. the data recieved have email along with all other data of each user. the emails for every user is saved in a variable lets suppose we have user A and his email is user@A.com and another user B that have email user@b.com and same for user c and so on if more users. below is the code
$(response).find(".EMP_EMAIL>span").each(function(i, span) {
    employee_email = $(span).text();

remember employee_email is a global variable
now the second function that is for email sending through ajax and the url contain the email as a parameter.the send email function is called through button click and every user record have its own button.  the problem is here if i click the button that is below the user A so the parameter in url should be user@A.com and if button below record of user B is clicked then parameter should be user@B.com and same for c and so on if user exist. below is the code for it.But in my case it only send email to the last email that is saved in employee_email. so i am unable to make logic for it so need you help. if possible please elaborate your answer so that i could understand and could handle such situations by myself in future.
function sendEmail(){

if(flag)
{
    request = $.ajax({
        url: "send_email.php?"+employee_email,
        type: "post",
        success: function(data){
            $("#email_responses").html();
        },
        error:function(){
            alert("failure");
            $("#email_responses").html('error occured');
        }
    });
}
else
    alert('Sending email is unavailable currently. PLease try after some time.');
}

here is the code for button that appears below each user.

<input type="submit" value="Send Email" onClick="sendEmail();">

A: Some advice to help you solve your problem:
1 - Avoid using global variables
In your first code, you iterate over all the span to set the value of your global variable. At the end of your loop, this global variable will only have the last email. That is probably the origin of your problem.
2 - One possible solution
There are different solutions to your problem. Here is one: when the button is clicked, retrieve the selected email with some jquery path from the clicked button. For example, if your html is:

  user@domain.com

     <input type="submit" value="Send Email" />

In your javascript, you could get the selected email with this query:
function sendEmail(event) {
   var target = event.currentTarget;
   var email = $(target).parent().parent().find(".email").text();
   // and so on...
 }

 $('.send_email_notification input').on('click', sendEmail);

Note: you should also avoid the usage of onClick attribute in html elements. A more modern approach is to separate the javascript from the html code: that's why i removed it from my html version of your code.


text:
Q: Disposal of the used acid/hydrogen peroxide etchant? This thread repeated the question how to dispose the used acid/hydgogen peroxide etchant. So how can I dispose acid/hydrogen peroxide etchant?
Perhaps interesting thread to other readers, Disposal of ferric chloride etchant.

A: Disclaimer: This suggestion does not cover all aspects that may be required by your local regulations.
However, with any type of etchant, the most troublesome part is the one about the dissloved copper ions.
As long as you don't pour big amounts of strong basic or acidic solutions down the same drain, no heavy recation will start and cause dangers. Thinning any base or acid by adding large amounts of water will usually make them easy to handle. (Think concentrated acetic acid vs. salad sauce: Same chemistry, just a different concentration!) This applies to pure bases or acids. Your used etchant is more than just a hydrogen donor (acid), it contains copper salts!
Long story short: The pure etchant is usually not a very big deal, the copper ions are very toxic to anything in the nature (including yourself).
Related: Safety of making PCBs

redpajama_set_name: RedPajamaStackExchange


text: Q: Managing (ordering) chrome extensions Is there a way to order chrome extensions other than the limited functionality provided in the UI? The problem is that in the UI you can't order items in the drop down list/overflow area. I've looked at writing an extension but the management.ExtensionInfo object returned through the chrome.management apis doesn't contain the position. Editing ~/.config/google-chrome/Default/Preferences which does have the location doesn't work either.


text:
Q: will I lose data stored in async queue in Node.js project after pm2 reload? Currently, I'm working on a live node.js server that has an async queue running with tons of data.
Will I lose all queued data if I run pm2 reload?
I can't test to see what will happen since it's a live server.
Looking forward to hearing about your experience!

A: answer: I believe you will lose data due to the object storing the data being lost on the process restarting.
From async's queue documentation , a queue is an object that then is pushed onto memory and so if that respective node process is restarted the memory associated with it would be restarted as well.
pm2 reload is essentially a restart, but with gracefulness in keeping at least a process up to prevent zero down time.
From a question on the nuances of pm2 restart vs pm2 reload
SO link,

With reload, pm2 restarts all processes one by one, always keeping at least one process running.


text:
Q: Ionic v3 aplicativo fechando Tenho um aplicativo com uma tela de login e outra home, executo e depuro em um Samsung S6 Android api 23. Criei um novo projeto com api mínima 19 e máxima 28 e quando publiquei alguns aparelhos informaram q o app gerava diversos erros e fechava, baixei para versão do android máxima 27, mesma coisa, agora baixei para a versão máxima 26 e resolveu para alguns aparelhos, mas continua dando o mesmo problema em aparelhos com api 27+.
Em nenhuma das versões em laboratório o app apresenta nenhum tipo de falha, nem quando executa nem quando gero o release para publicação.
Já apaguei a pasta android, node modules e não há nenhuma indicação de erro em nada, posto abaixo minhas configurações, pois estou sem nenhuma idéia do que fazer para resolver o problema:
Ionic:
ionic (Ionic CLI)  : 4.11.0 (C:\Users\user\AppData\Roaming\npm\node_modules\ionic)
   Ionic Framework    : ionic-angular 3.9.3
   @ionic/app-scripts : 3.2.3
Cordova:
cordova (Cordova CLI) : 9.0.0 (cordova-lib@9.0.1)
   Cordova Platforms     : android 7.1.4
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 3.1.2, (and 11 other plugins)
System:
Android SDK Tools : 26.1.1 (G:\android-sdk)
   NodeJS            : v10.15.1 (C:\Program Files\nodejs\node.exe)
   npm               : 6.4.1
   OS                : Windows 10
  "scripts": {
"start": "ionic-app-scripts serve",
"clean": "ionic-app-scripts clean",
"build": "ionic-app-scripts build",
"lint": "ionic-app-scripts lint"
"dependencies": {
"@angular/animations": "5.2.11",
"@angular/common": "5.2.11",
"@angular/compiler": "5.2.11",
"@angular/compiler-cli": "^7.2.13",
"@angular/core": "5.2.11",
"@angular/forms": "5.2.11",
"@angular/http": "5.2.11",
"@angular/platform-browser": "5.2.11",
"@angular/platform-browser-dynamic": "5.2.11",
"@ionic-native/core": "~4.18.0",
"@ionic-native/geolocation": "^4.20.0",
"@ionic-native/http": "^4.20.0",
"@ionic-native/local-notifications": "^4.20.0",
"@ionic-native/native-geocoder": "^4.20.0",
"@ionic-native/network": "^4.20.0",
"@ionic-native/splash-screen": "~4.18.0",
"@ionic-native/status-bar": "~4.18.0",
"@ionic/storage": "2.2.0",
"@types/leaflet": "^1.4.4",
"cordova-android": "7.1.4",
"cordova-plugin-advanced-http": "^2.0.6",
"cordova-plugin-badge": "^0.8.8",
"cordova-plugin-device": "^2.0.2",
"cordova-plugin-file": "^6.0.1",
"cordova-plugin-geolocation": "^4.0.1",
"cordova-plugin-ionic-keyboard": "^2.1.3",
"cordova-plugin-ionic-webview": "^3.1.2",
"cordova-plugin-local-notification": "^0.9.0-beta.2",
"cordova-plugin-nativegeocoder": "^3.2.0",
"cordova-plugin-network-information": "^2.0.1",
"cordova-plugin-splashscreen": "^5.0.2",
"cordova-plugin-statusbar": "^2.4.2",
"cordova-plugin-whitelist": "^1.3.3",
"ionic-angular": "3.9.3",
"ionic-native-http-connection-backend": "^4.0.10",
"ionicons": "3.0.0",
"leaflet": "^1.4.0",
"rxjs": "5.5.11",
"rxjs-compat": "^6.4.0",
"sw-toolbox": "3.6.0",
"zone.js": "0.8.29"
"devDependencies": {
"@ionic/app-scripts": "^3.2.3",
"typescript": "~2.6.2"
"description": "An Ionic project",
"cordova": {
"plugins": {
  "cordova-plugin-whitelist": {},
  "cordova-plugin-statusbar": {},
  "cordova-plugin-device": {},
  "cordova-plugin-splashscreen": {},
  "cordova-plugin-ionic-webview": {
    "ANDROID_SUPPORT_ANNOTATIONS_VERSION": "27.+"
  },
  "cordova-plugin-ionic-keyboard": {},
  "cordova-plugin-geolocation": {},
  "cordova-plugin-nativegeocoder": {},
  "cordova-plugin-network-information": {},
  "cordova-plugin-advanced-http": {},
  "cordova-plugin-local-notification": {}
},
"platforms": [
  "android"
]

O que está me deixando desesperado é que não gera erros, somente quando o cliente baixa o aplicativo via PlayStore e no aparelho dele que é um Samsung S9.
Tenho ideia de que o problema possa estar relacionado a versões ionic/cordova/android mas não sei o que fazer.
Obrigado de antemão a todos q possam me dar uma luz.


text:
Q: Ctrl+Alt+T - shortcut not working I tried the keyboard settings. Currently running on ubuntu 16.04.3 LTS,
recently installed elementary theme in it, later uninstalled. Whenever
I try to use the shortcut there is no response.

A: You Must have disable the combo key somehow.
 I Assume you need the shortcut for opening terminal.
To Re-enable Ctr+Alt+T shortcut follow the following steps:
Step 1:

Goto settings and under Keyboard find the shortcut tab.
Step 2:

Under Launchers sections locate terminal, if not exist goto custom sections.
Click on the + sign a small window will pop up.

Step 3:

Fill in the boxes.
In the name column write terminal or anything that helps you remember.
Under Command column write gnome-terminal
 Next click on Set Shortcut... and press Ctr + Alt + T.
If you click other keys mistakenly press esc to restart the key capturing method.
 That will do it. Now test your settings.


text:
Q: I am a beginner in SharePoint. What is the use of this code?

View All

A: The code that you have mentioned is used to fetch data from a SharePoint list named DPC_Announcements. It fetches the latest 10 items based on their created date and binds it to the content-ltk2 div in HTML using jQuery. It uses the SPServices library to perform the GetListItems operation. It binds the Title and Description field and also gives you a link to the item page "Dispform.aspx" to redirect user to that item's details.


text:
Q: How to detect if Jquery syntax highlighting is applicable to a source file I'm implementing a script to detect if jQuery is being used within a JavaScript source file (for a sublime text plugin).
Right now (aside from the obvious JavaScript extension test) my solution checks if any of the following substrings appears within the file:
jquery_idioms = [
    '$(function',
    '$(document)',
    '$(window)',
    '$(this)'
    '$.fn',
    '$.ajax',
    '$.noConflict',
    'jQuery.noConflict'
]

I don't think that 100% certanity is achievable (because of similar libraries using replicating jQuery's API, etc), but I'm trying to build a good list of substrings that avoids most false positives.
As I am not a huge jQuery expert, the question is:
Am I missing any very often used jQuery idioms?
PS: (I don't think it's possible but) Alternative non substring searching ideas?


text:
Q: Cleanest way to parse some files by hand in SCons I want to pass some custom options to the linker based what is in a header file in my source tree. I'm doing something like this now and it works, but there's got to be a better way:
def getCustomStr():
  for l in open(Dir('#').abspath + "/header.h"):
    if "#define MAGIC_FLAG" in l:
      return munge_flag(l)

env.Append(LINKFLAGS['-Xlinker', getLinkOpt()])

In particular accessing Dir('#') like that gives me the creeps. Any better ideas?

A: If Dir('#') gives you the creeps, try this instead:
for l in open(File('header.h').abspath):


text:
Q: Reset Usage limit per user every month in woocommerce coupon I want to allow customer to use coupon only once every month
I set the Usage limit per user =1, But it only works once. How can programmatically update Usage limit per user every month ??
Eg: if customer used "discount40" coupon will not be able to use it again for a month.
Thanks.


text:
Q: TIBCO Jaspersoft Server empty errorlist We are running a TIBCO Jaspersoft Server where JasperReports is installed.
We have developed some small Reports which are running productive.
But now I wanted to add another email recipient in one report and after clicking on save I get an empty errorlist.enter empty error
Attached a screenshot. Has anyone any idea what I can do now? I can't modifiy anything in the setting for any of our reports.


text:
Q: Typescript and Reducer function with multiple payload options I'm very new to typescript and I'm trying to write a reducer function with three possible payload values : no value, a string, or a number. I'm using discriminated union type and from what I have read I think my code should work, but it is not.
type StateType = {
  isModalOpen: boolean;
  modalContent: string;
  people: {
    id: number;
    name: string;
  }[];
};

type NoPayloadAction = {
  type: string;
};

type NamePayloadAction = {
  type: string;
  payload: {
    name: string;
  };
};

type IdPayloadActionType = {
  type: string;
  payload: {
    id: number;
  };
};

type ActionType = NoPayloadAction | NamePayloadAction | IdPayloadActionType;

const ACTIONS = {
  ADD_ITEM: 'ADD_ITEM',
  NO_ACTION: 'NO_ACTION',
  CLOSE_MODAL: 'CLOSE_MODAL',
  REMOVE_ITEM: 'REMOVE_ITEM',
};

// reducer function
const reducer = (state: StateType, action: ActionType) => {
  switch (action.type) {
    case ACTIONS.ADD_ITEM:
      return {
        people: [
          ...state.people,
          { id: new Date().getTime(), name: action.payload.name },
        ],
        isModalOpen: true,
        modalContent: 'item added',
      };
    case ACTIONS.NO_ACTION:
      return { ...state, isModalOpen: true, modalContent: 'enter a value' };
    case ACTIONS.CLOSE_MODAL:
      return { ...state, isModalOpen: false, modalContent: '' };
    case ACTIONS.REMOVE_ITEM:
      const newPeople = state.people.filter(
        (person) => person.id !== action.payload.id
      );
      return {
        people: [...newPeople],
        isModalOpen: true,
        modalContent: 'item removed',
      };
    default:
      return state;
  }
};

Typescript is throwing two errors:
The lines below throws this error: Property 'payload' does not exist on type 'ActionType'. Property 'payload' does not exist on type 'NoPayloadAction'
{ id: new Date().getTime(), name: action.payload.name },

(person) => person.id !== action.payload.id

The type NoPayloadAction does not have a payload, but the other two do and from what I understand they match their types as one has an id:number field and the other has a name:string field. I'm really puzzled by this.

A: Right now, there is no guarantee that what is being passed in to your action variable is not a NoPayloadAction. If you are sure that your action variable does have a payload you can always use the as keyword tell typescript you know what the variable is. For example:
return { id: new Date().getTime(), name: (action as NamePayloadAction).payload.name },


text:
Q: FlatButton with Text ellipsis overflowed I try to use an ellipsis when the Text of a FlatButton overflows.
It works with a normal FlatButton but not with a FlatButton.icon. I would appreciate an explanation.
void main() => runApp(Test());

class Test extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        // bottomNavigationBar: BottomAppBar(child: widgetOk()),
        bottomNavigationBar: BottomAppBar(child: widgetNotOk()),
      ),
    );
  }
}

Widget widgetOk() {
  return Row(
    children: <Widget>[
      Flexible(
        child: FlatButton(
          child: Text('0123456789' * 10, overflow: TextOverflow.ellipsis),
          onPressed: () {},
        ),
      ),
      Flexible(
        child: FlatButton(
          child: Text('0123456789' * 10, overflow: TextOverflow.ellipsis),
          onPressed: () {},
        ),
      ),
    ],
  );
}

Widget widgetNotOk() {
  return Row(
    children: <Widget>[
      Flexible(
        child: FlatButton.icon(
          icon: Icon(Icons.bug_report),
          label: Text('0123456789' * 10, overflow: TextOverflow.ellipsis),
          onPressed: () {},
        ),
      ),
      Flexible(
        child: FlatButton.icon(
          icon: Icon(Icons.bug_report),
          label: Text('0123456789' * 10, overflow: TextOverflow.ellipsis),
          onPressed: () {},
        ),
      ),
    ],
  );
}

A: You can wrap label with Flexible to see the ellipsis take effect.
Working code below:
Flexible(
        child: FlatButton.icon(
          icon: Icon(Icons.bug_report),
          label: Flexible(
              child: Text('0123456789' * 10, overflow: TextOverflow.ellipsis)),
          onPressed: () {},
        ),
      ),
      Flexible(
        child: FlatButton.icon(
          icon: Icon(Icons.bug_report),
          label: Flexible(
            child: Text('0123456789' * 10, overflow: TextOverflow.ellipsis),
          ),
          onPressed: () {},
        ),
      ),


text:
Q: C++ 11 Best practices for caching in a std::map? (In c++ 11)
I want to store in a map objects (Product) that are somewhat expensive to compute. These objects aren't space cheap so I don't want to create unnecessary copies. The map belongs to a Container class that will give access to the objects. I made an example that represents what I have (the code is also found here: run online):
#include <iostream>
#include <map>
#include <string>
#include <utility>

class Product
{
private:
  std::string m_id, m_name;

public:
  Product () : m_id (), m_name () { std::cout << "\tProduct default constructor.\n"; }

  Product (const std::string & id, const std::string & name) : m_id (id), m_name (name)
  {
    std::cout << "\tProduct parameters constructor <" << m_id << ", " << m_name << ">.\n";
  }

  Product (const Product & copy) : m_id (copy.m_id), m_name (copy.m_name)
  {
    std::cout << "\tProduct copy constructor.\n";
  }
};

class Container
{
private:
  std::map<std::string, Product> m_products_cache;

public:
  Container () : m_products_cache () { }
  Container (const Container & copy) : m_products_cache (copy.m_products_cache) { }

  Container (const std::string & filename) : Container ()
  {
    // Simulate reading file and storing its contents in map with this:
    m_products_cache.insert (std::pair<const std::string, Product> ("A-001", Product ("A-001", "Product 1")));
    m_products_cache.insert (std::pair<const std::string, Product> ("A-002", Product ("A-002", "Product 2")));
  }

  const Product &
  CreateNewProduct (const std::string & id, const std::string & name)
  {
    std::map<std::string, Product>::iterator product_it = m_products_cache.find (id);

    if (product_it != m_products_cache.end ())
      return product_it->second; // Returns a const-reference to the Product

    std::pair<std::map<std::string, Product>::iterator, bool> inserted_it;
    inserted_it = m_products_cache.insert (std::pair<const std::string, Product> (id, Product (id, name)));

    return inserted_it.first->second; // Returns a const-reference to the Product
  }

  // Case (i)  :  Returns a const-reference.
  const Product &
  GetProductById (const std::string & id) const
  {
    std::map<std::string, Product>::const_iterator product_it = m_products_cache.find (id);

    if (product_it == m_products_cache.end ())
      throw std::out_of_range ("Error: Product ID'" + id + "' NOT found.\n");

    return product_it->second;
  }

  // Case (ii)  :  Uses an non-const reference parameter to return the Product, if found.
  bool
  GetProductById (const std::string & id, Product & product) const
  {
    std::map<std::string, Product>::const_iterator product_it = m_products_cache.find (id);

    if (product_it == m_products_cache.end ()) return false;

    product = product_it->second;
    return true;
  }

  // Case (iii)  :  Uses a const Product non-const pointer reference to expose the Product, if found.
  bool
  GetProductById (const std::string & id, const Product *& product) const
  {
    std::map<std::string, Product>::const_iterator product_it = m_products_cache.find (id);

    if (product_it == m_products_cache.end ())
      {
        product = nullptr;
        return false;
      }

    product = &product_it->second;
    return true;
  }
};

int
main (int argc, char **argv)
{
  Container container ("ignored_filename");

  const Product & created_product = container.CreateNewProduct ("B-003", "Product 3");
  std::cout << "\n - Created Product located at " << &created_product << "\n\n";

  std::cout << " - Obtain reference to Product in container:\n\n";

  const Product & product_reference = container.GetProductById ("B-003"); // Gets product at expected address.
  std::cout << "\tCase i  : product located at " << &product_reference
            << (&product_reference == &created_product ? " (Same object)" : " (Different object)") << "\n";

  Product product_param;
  container.GetProductById ("B-003", product_param); // Question 1: Gets a copy, but doesn't call copy constructor, WHY?
  std::cout << "\tCase ii : product located at " << &product_param
            << (&product_param == &created_product ? " (Same object)" : " (Different object)") << "\n";

  const Product *product_pointer_param;
  container.GetProductById ("B-003", product_pointer_param); // Gets product at expected address.
  std::cout << "\tCase iii: product located at " << product_pointer_param
            << (product_pointer_param == &created_product ? " (Same object)" : " (Different object)") << "\n";
}

That produces the following output:
 - Created Product located at 0x6000727b8

 - Obtain reference to Product in container:

    Case i  : product located at 0x6000727b8 (Same object)
    Product default constructor.
    Case ii : product located at 0xffffcb40 (Different object)
    Case iii: product located at 0x6000727b8 (Same object)

I have the following questions:

*

*Question 1: This code doesn't return a reference to 0x6000727b8 and instead creates a copy that is stored at 0xffffcb40, but Product's copy constructor is not called, why?
// Case (ii): Output reference parameter
Product product_param;
container.GetProductById ("B-003", product_param);

*Question 2: I'd like to provide access to the object in the map, to avoid creating copies of the object. I must also indicate, with a boolean or an exception, if the Product was found. I'd prefer something like case (ii): bool GetProductById (const std::string & id, Product & product), but this doesn't enforce constness.
Of the three cases I provided in code, or from another suggestion of yours, which is the best practice to achieve it?

*Question 3: In this case, the Products stored in the map will not change after they are stored. But, if the Products were to be changed after they are stored in the map, do approaches like the ones in question 2 still apply?, is it bad practice to change map value objects directly? (I know keys must be constants).

A: *

*You have 2 objects: product_param and the object stored in the map. When you assign to product_param through the reference product it will use the assignment operator Product::operator=(const Product&) (which is provided for you by the compiler because you didn't tell it not to) to assign the contents. You still have 2 objects and they each have their own id and name.

*case (i) is fine for one that throws an exception. case (iii) is a little awkward but works. Another option is const Product* GetProductById(const std::string& id) const. This can return a pointer to the object if it exists or return nullptr if it doesn't. This unfortunately has the same prototype as case (i) besides the return value, so you'll need to either have a different function name or somehow come up with some other way to distinguish between how to call them.
The way the standard usually does this is use operator[](const Key& key) for the version that doesn't throw and at(const Key& key) for the version that does. It will be slightly awkward for one to return a pointer and the other to return a reference though.

*That's really up to you. There's nothing preventing you from changing the values of a map but if that's not something you want the user to be able to do then you can always return const references or pointers to const back to the user.


text:
Q: tf.scatter_nd_update keeps giving me an AttributeError I'm on TF V1.15.
I followed the doc. This is my code:
# v is a tensor of shape [15360].
num = 15360
sz = 7680
ind = np.random.randint(num, size = sz)
ind = tf.constant(ind)
upd = tf.constant(0., shape=[sz])
v_ = tf.scatter_nd_update(v, ind, upd)

And I keep getting the error:
v_ = tf.scatter_nd_update(v, ind, upd)
File "/root/anaconda/envs/../lib/python2.7/site-packages/tensorflow/python/ops/state_ops.py", line 366, in scatter_nd_update
return ref._lazy_read(gen_state_ops.resource_scatter_nd_update(  # pylint: disable=protected-access
AttributeError: 'Tensor' object has no attribute '_lazy_read'

I tried wrapping upd and ind as tf.Variable looking at this issue but I get the same error.


text:
Q: opening a file from files directory android Hi i have saved a file from a url to my files directory. And set a broadcast recover to detect when the download has completed to then fire an action_view intent to choose which app to open it in. which all works fine but when i choose another application it can't display the file. if i select the file form the notification centre it opens up fine so it definitely gets download loaded into the files directory but no idea why it would load when opened from my application.
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                            request.setTitle(filename);
                            // in order for this if to run, you must use the android 3.2 to compile your app
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                                request.allowScanningByMediaScanner();
                                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                            }

                            ContextWrapper c = new ContextWrapper(getBaseContext());
                            final String filePath = c.getFilesDir().getPath() + "/";
                            Log.v("Search", "filePath = " + filePath);
                            request.setDestinationInExternalFilesDir(getBaseContext(), filePath, filename);

                            // get download service and enqueue file
                            DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                            manager.enqueue(request);
                            Toast.makeText(getBaseContext(), "Downloading...", Toast.LENGTH_LONG).show();

                            BroadcastReceiver onComplete = new BroadcastReceiver() {

                                @Override
                                public void onReceive(Context context, Intent intent) {

                                    String path = getFilesDir().getPath() +"/" + filename;
                                    File f = new File(path);
                                    Log.v("Search", "path = " + path);
                                    String fileExt = Global.getFileExt(filename);
                                    MimeTypeMap myMime = MimeTypeMap.getSingleton();

                                    Intent newIntent = new Intent(Intent.ACTION_VIEW);

                                    String mimeType = myMime.getMimeTypeFromExtension(fileExt);
                                    newIntent.setDataAndType(Uri.fromFile(f), mimeType);
                                    newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    try {
                                        context.startActivity(newIntent);
                                    } catch (android.content.ActivityNotFoundException e) {
                                        Toast.makeText(context, "No handler for this type of file.", 4000).show();
                                    }
                                }

                            };

                            registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

                        }


text:
Q: OS X default listening ports Is there somewhere I can find a default list of open ports on OSX for various versions, or a particular version?
I would like to know what is on by default so I can see if something should be there or not, and so I can disable what I may consider unnecessary.
I cannot find such a list anywhere, which is odd since such lists are available for Windows and Linux distributions.

A: I don't know of any "list" available, since it really depends on what software is installed on your Mac.  To find out though, try Little Snitch.  It's a fantastic firewall program for OSX that lets you see who your Mac is talking to, on what port, and allows you to allow/deny whenever you want.


text:
Q: On weak convergence of probability measure Given probability density function(pdf) $f_n,g:\mathbb{R}\to\mathbb{R}$, if there exists some constanct $c>0$ such that $f_n \to c\cdot g$ pointwise, do we necessarily have $c=1$?
Applying Fatou's lemma immediately gives that $c\leq 1$, but is it possible that $c<1$?

A: Let $f_n(x)={\bf 1}_{[-1/2,0]\cup[n,n+1/2]}(x)$ and $g(x)=2\cdot{\bf 1}_{[-1/2,0]}(x)$, then $c=1/2$.

A: Let $g$ be any pdf, and $f_n= {1\over2}(g+n(n+1) 1_{[{1 \over n+1},{1 \over n}]})$. Then $f_n(x) = {1 \over 2} g(x)$ after a finite number of $n$.


text:
Q: How to pass data between view to another viewmodel? Im using Boilerplatejs and asp.net mvc2 in one of my projects. I have a autocompleting search box in one of the boilerplate views. and i wanted to send the selected "userId"(from the suggestions of the search box) to a viewmodel of another module and give an ajax call to my controller's action method using that "userId" as a parameter and then fetch some specific information to that user and finally display it in that particular module's view.
Here is my autocomplete script
$(document).ready(function () {
    $('#name-list').autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "/Home/Searchuser",
                data: { searchText: request.term, maxResults: 10 },
                dataType: "json",
                success: function (data) {

                    response($.map(data, function (item) {
                        return {
                            value: item.DisplayName,
                            avatar: item.PicLocation,
                            rep: item.Reputation,
                            selectedId: item.UserUniqueid
                        };
                    }))
                }
            })
        },
        select: function (event, ui) {

            return selectedId; // **here im returning the required userId**
        }
    }).data("autocomplete")._renderItem = function (ul, item) {
        var inner_html = '

 Reputation:  ' + item.rep + '

' + item.label + '

';
        return $("

")
                .data("item.autocomplete", item)
                .append(inner_html)
                .appendTo(ul);
    };

});

My problem is how to catch this returned userId from the other module's viewmodel? So then i can make an ajax call to the Actionmethod and retrieve necessary information. Can anybody help me?

A: I think you should use URL controller here. Once the user selects a particular userprofile from the search box, you may get the application to navigate to the profile page of the user. Something like:
Boiler.UrlController.goTo("user/"+ user.id);

Now your user profile component should listen to the
controller.addRoutes({
    'user/{id}' : new UserComponent(context),
});

It is always good to be able to address your business objects via URLs. This enhances the ability to bookmark and keep browser history.


text:
Q: Is there a way to build a ushahidi like website using WordPress or Drupal? I would like to know if there is some Drupal module or a WordPress plugin that enables the creation of a ushahidi type website (Ushahidi is a non-profit software company that develops free and open source software for information collection, visualization and interactive mapping.)
I am asking this to know if one can use the feautres that ushahidi is offering, while also leveraging all of the other plugins/modules created in these more mature platforms.
Thanks.

A: The Managing News Drupal distribution might be helpful.


text:
Q: Facing Application crashes (Beginner) I tried my best but unable to resolve this issue, I tried debugging nothing happened, tried making new project same error. Till afternoon project was working perfectly fine but then it is giving an error just tried to update UI of the Android app:
E/StudioProfiler: JVMTI error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE)
    E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.nodemcu.controlnodemcu, PID: 6681
                  java.lang.IllegalStateException: Could not execute method for android:onClick
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)
                      at android.view.View.performClick(View.java:6294)
                      at android.view.View$PerformClick.run(View.java:24770)
                      at android.os.Handler.handleCallback(Handler.java:790)
                      at android.os.Handler.dispatchMessage(Handler.java:99)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6494)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                   Caused by: java.lang.reflect.InvocationTargetException
                      at java.lang.reflect.Method.invoke(Native Method)
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
                      at android.view.View.performClick(View.java:6294)
                      at android.view.View$PerformClick.run(View.java:24770)
                      at android.os.Handler.handleCallback(Handler.java:790)
                      at android.os.Handler.dispatchMessage(Handler.java:99)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6494)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.ref.WeakReference.get()' on a null object reference
                      at com.example.nodemcu.nodemcucontroller.MainActivity$HttpRequestTask.<init>(MainActivity.java:80)
                      at com.example.nodemcu.nodemcucontroller.MainActivity$HttpRequestTask.<init>(MainActivity.java:68)
                      at com.example.nodemcu.nodemcucontroller.MainActivity.buttonClick(MainActivity.java:63)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
                      at android.view.View.performClick(View.java:6294)
                      at android.view.View$PerformClick.run(View.java:24770)
                      at android.os.Handler.handleCallback(Handler.java:790)
                      at android.os.Handler.dispatchMessage(Handler.java:99)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6494)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Application terminated.

Libraries imported:
package com.example.nodemcu.nodemcucontroller;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog.Builder;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.URI;
import java.net.URISyntaxException;

Code For MainActivity.java:
public class MainActivity extends AppCompatActivity {

final Context context = this;
private EditText ipAddress;
private Button ledOn, ledOff;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ipAddress = (EditText) findViewById(R.id.edt_ip);
    ledOn = (Button) findViewById(R.id.btn_ledOn);
    ledOff = (Button) findViewById(R.id.btn_ledOff);

}
public void buttonClick(View view) {
    String ledStatus;

    if (ipAddress.getText().toString().equals(""))
        Toast.makeText(MainActivity.this, "Please enter the ip address...", Toast.LENGTH_SHORT).show();

    else {
        if (view == ledOn)
            ledStatus = "1";

        else
            ledStatus = "0";

        String serverAdress = ipAddress.getText().toString() + ":" + "80";
        HttpRequestTask requestTask = new HttpRequestTask(serverAdress);
        requestTask.execute(ledStatus);
    }
}

private static class HttpRequestTask extends AsyncTask<String, Void, String>{

    private String serverAdress;
    private String serverResponse = "";
    AlertDialog dialog;
    private WeakReference<MainActivity> activityReference;
    HttpRequestTask(MainActivity context){
        activityReference = new WeakReference<>(context);
    }
    private HttpRequestTask(String serverAdress) {
        this.serverAdress = serverAdress;

        dialog = new AlertDialog.Builder(activityReference.get())
                .setTitle("HTTP Response from Ip Address:")
                .setCancelable(true)
                .create();
    }

    @Override
    protected String doInBackground(String... params) {
        dialog.setMessage("Data sent , waiting response from server...");

        if (!dialog.isShowing())
            dialog.show();

        String val = params[0];
        final String url = "http://" + serverAdress + "/led/" + val;

        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet getRequest = new HttpGet();
            getRequest.setURI(new URI(url));
            HttpResponse response = client.execute(getRequest);

            InputStream inputStream = null;
            inputStream = response.getEntity().getContent();
            BufferedReader bufferedReader =
                    new BufferedReader(new InputStreamReader(inputStream));

            serverResponse = bufferedReader.readLine();
            inputStream.close();

        } catch (URISyntaxException e) {
            e.printStackTrace();
            serverResponse = e.getMessage();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            serverResponse = e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            serverResponse = e.getMessage();
        }
        return serverResponse;
    }

    @Override
    protected void onPostExecute(String s) {
        dialog.setMessage(serverResponse);

        if (!dialog.isShowing())
            dialog.show();
    }

    @Override
    protected void onPreExecute() {
        dialog.setMessage("Sending data to server, please wait...");

        if (!dialog.isShowing())
            dialog.show();
       }
   }
}

Activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<EditText
    android:id="@+id/edt_ip"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="@string/ip_address"
    android:inputType="text"/>

<Button
    android:id="@+id/btn_ledOff"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="buttonClick"
    android:text="@string/led_off" />

<Button
    android:id="@+id/btn_ledOn"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="buttonClick"
    android:text="@string/led_on" />

</LinearLayout>

A: Complete Edit
As per this line in your crash logs
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.ref.WeakReference.get()' on a null object reference at com.example.nodemcu.nodemcucontroller.MainActivity$HttpRequestTask.

Problem is your activityReference is null while creating alert dialog.
You have two constructors inside your HttpRequestTask.
EDIT
Change your HttpRequestTask constructor like this:
 private WeakReference<MainActivity> activityReference;

    private HttpRequestTask(String serverAdress, MainActivity context) {
        this.serverAdress = serverAdress;
        this.activityReference = new WeakReference<>(context);

        dialog = new AlertDialog.Builder(activityReference.get())
                .setTitle("HTTP Response from Ip Address:")
                .setCancelable(true)
                .create();
    }

A: Try this code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{

private Context context = this;
private EditText ipAddress;
private Button ledOn, ledOff;
private String ledStatus;

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);

   ipAddress = (EditText) findViewById(R.id.edt_ip);
   ledOn = (Button) findViewById(R.id.btn_ledOn);
   ledOff = (Button) findViewById(R.id.btn_ledOff);

   if (ipAddress.getText().toString().equals("")) {
            Toast.makeText(MainActivity.this, "Please enter the ip address...", Toast.LENGTH_SHORT).show();
       } else {
         ledOn.setOnclicklistener(this);
         ledOff.setOnclicklistener(this);
    }

}

@Override
public void onClick(View view) {

    switch(view.getId()){
       case R.id.ledOn:
         ledStatus = "1";
       break;
       case R.id.ledOff:
         if (ledStatus == "1") { ledStatus = "0"; }
       break;
    }
   // do your async task here
}
}

The buttons should work now without errors. DOn't know about your async task but that should work too depending on if it's receiving input from ledOn or ledOff buttons, then you can put the code there, otherwise, it's fine. Try this way.


text:
Q: Cloudfoundry command line tool doesn't push all files I'm trying to push a simple application to IBMBluemix (Cloudfoundry) but some files are not picket up.
I have a folder containing some files (index.php, test.html, ...). All these are pushed, but my css folder for example is not.
In the root folder containing these files and folders I type:
cf push -m 128M -b https://github.com/dmikusa-pivotal/cf-php-build-pack.git testname

So after this
testname.mybluemix.net/index.php

is accessible, but
testname.mybluemix.net/css/reveal.min.cs

is not.
Any ideas?
Best Regards
Romeo

A: When you push your app make sure you are in the root directory of your app. (ex. /Users/jsmith/dev/myapp.  Make sure you are in the folder that has your index.php file.  Also check to make sure there isn't a .cfignore file as well.

A: Have you tried using the -p parameter to let the cli know where your application is living?
for example if my app is located on my Desktop I would cd to my desktop and do something like this
cf push testname1 -m 128m -b https://github.com/dmikusa-pivotal/cf-php-build-pack.git -p myApp

A: Thanks a lot! The problem was not files not being pushed. The buildpack I specified just ignored them. Changing the buildpack solved the issue. But I've learned about .cfignore and the -p parameter so the discussion was worth it.


text:
Q: What is segmentation fault in Objective-C? I have written a small Objective-C program to archive an object. The object is an NSDictionary. There was no problem during compiling. But when it was called it displayed a message "Segmentation fault" in the terminal, and no archive XML file was created. The problem was caused by the writeToFile method, as after I had commented it out there was no error (of course no archiving either). What does this error message mean? And how to fix it?
I just found out the reason of the problem. My program is based on the example in a book and there is a misprint so the dictionary object has never actually initialized. Sorry I did not check this problem throughly before asking.

A: A segmentation fault is caused by an attempt to dereference bad pointer. It's possible the file instance you're passing to writeToFile: is nil.  You need to check your return codes for success, and check your pointers are all valid.
Given it does not crash when you comment out that line, you just need to ensure all the parameters to that call are valid and you will find your bug.
Some more reading:

*

*What is a segmentation fault?

A: Segmentation fault usually means that your program is accessing memory it shouldn't. Run your program in a debugger, and it should show you where the error happen.

A: It's hard to pinpoint the exact problem without any sample code, but a segmentation fault occurs when the CPU is trying to access memory that it does not own. This generally means that you have a pointer that is not initialized, or doesn't point to the right place, and then you're attempting to de-reference it which causes the crash. I suggest combing over your code and make sure all your pointers are doing what you expect them to do.


text:
Q: TypeError: undefined is not an object (evaluating 'Object.keys(routeConfigs)') React native Project app So i'm currently developing a react native application, but i'm getting this error. I think it may have to do with the version of some libraries that i'm using but i'm not sure.
This is my app.js file
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Provider } from 'react-redux';
import HomeScreen from './screens/HomeScreen';
import MapScreen from './screens/MapScreen';
import { store } from './store';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import 'react-native-gesture-handler';
import {NavigationContainer} from '@react-navigation/native';
import { createStackNavigator } from "react-navigation-stack";

export default function App() {
  const Stack = createStackNavigator();

  return (
    <Provider store={store}>
      <NavigationContainer>
        <SafeAreaProvider>
          <Stack.Navigator>
            <Stack.Screen
            name='HomeScreen'
            component={HomeScreen}
            options={{
              headerShown: false,
            }}
            />
            <Stack.Screen
            name='MapScreen'
            component={MapScreen}
            options={{
              headerShown: false,
            }}
            />
          </Stack.Navigator>
        </SafeAreaProvider>
      </NavigationContainer>
    </Provider>
  );
}

My HomeScreen.js file, which is rendered when the app starts.
import React from 'react'
import { StyleSheet, Text, View, SafeAreaView, Image } from 'react-native'
import tw from 'tailwind-react-native-classnames';
import NavOptions from '../components/NavOptions';

const HomeScreen = () => {
    return (
        <SafeAreaView style = {tw`bg-white h-full`}>
            <View style = {tw`p-5`}>
                <Image
                style = {{
                    width: 100,
                    height: 100,
                    resizeMode: "contain",
                }}
                source={{
                    uri: "https://links.papareact.com/gzs"
                }}
                />
                <NavOptions/>
            </View>
        </SafeAreaView>
    )
}

export default HomeScreen

My MapScreen.js file, the other screen I have.
import React from 'react'
import { StyleSheet, Text, View } from 'react-native'

const MapScreen = () => {
    return (
        <View>
            <Text>Here is the map stuff...</Text>
        </View>
    )
}

export default MapScreen

The NavOptions.js file, which renders two buttons on the screen to select one.
import { useNavigation } from '@react-navigation/native';
import React from 'react'
import { FlatList, Text, Touchable, TouchableOpacity, View, Image } from 'react-native'
import { Icon } from 'react-native-elements/dist/icons/Icon';
import tw from 'tailwind-react-native-classnames';

const data = [
    {
        id: "123",
        title: "Get a ride",
        image: "https://links.papareact.com/3pn",
        screen: "MapScreen",
    },
    {
        id:"456",
        title:"Order food",
        image: "https://links.papareact.com/28w",
        screen: "EatsScreen", // Change in future....
    }
]

const NavOptions = () => {
    const navigation = useNavigation();

    return (
        <FlatList
        data = {data}
        horizontal
        keyExtractor = {(item) => item.id}
        renderItem={({item}) => (
            <TouchableOpacity
                onPress={() => navigation.navigate(item.screen)}
                style = {tw`p-2 pl-6 pb-8 pt-4 bg-gray-200 m-2 w-40`}
            >
                <View>
                    <Image
                    style = {{
                        width: 120,
                        height: 120,
                        resizeMode: "contain",
                    }}
                    source={{
                        uri: item.image
                    }}
                    />
                    <Text style={tw`mt-2 text-lg font-semibold`}>{item.title}</Text>
                    <Icon
                    style = {tw`p-2 bg-black rounded-full w-10 mt-4`}
                    name="arrowright" color="white" type="antdesign"/>
                </View>
            </TouchableOpacity>
        )}
        />
    )
}

export default NavOptions

A: normally undefined is not a object occurs when you are asking for parameter value from parameter that does not exist.
for example:
let data = [
             {
             arr:[{name:"aaa"},{name:"bbb"}],
             b:'outside1'
             },
             {
             arr:[{name:"ccc"},{name:"ddd"}],
             b:'outside2'
             },
           ]

in here if you right data[0].b then it will return outside1
but data[0].b.c will be undefine and data[0].b.c.d will give error undefined is not a object.
in your code I am not seeing any this kind of pattern so please check your code if this is happening anywhere .

A: For others with the same error but in different context:
I had this issue when I imported modules from 'aws-amplify-react-native', but 'aws-amplfify-react-native' wasn't installed and so it was "undefined"


text:
Q: Python Pivot Table conditional count I am trying to generate a pivot table with following result
wondering how i calculate the # of win, lost, and draw....
essentially, I want to say count only if Result == 'Win'
I didn't want to use Result as a column because I don't want to have Speed breakdown by Win/Lost/Draw...is there a way to just count # of
Name    Result     Win   Loss   Draw   Speed
James    6         2      2      2       50
Bob      9         7      2      0       48
Mary     10        5      3      2       70

This is the code
report = pd.pivot_table(df,index=["Name"], values=["Result", "Speed"],  aggfunc= {"Result": len, "Speed": np.mean}, fill_value=0)

Thank you in advance

A: Assuming your data looks something like this:
# sample data
df = pd.DataFrame({
    'Name' : ['James']*6 +\
             ['Bob']*9 +\
             ['Mary']*10,
    'Result' : ['Win']*2 + ['Loss']*2 + ['Draw']*2 +\
               ['Win']*7 + ['Loss']*2 +\
               ['Win']*5 + ['Loss']*3 + ['Draw']*2,
    'Speed' : [50]*6 +\
              [48]*9 +\
              [70]*10
})

Then just filter on 'Win' and pivot:
# Filter on 'Win'; make pivot table
df[df.Result == 'Win'].pivot_table(index = 'Name',
                                   values = ['Result', 'Speed'],
                                   aggfunc = {'Result' : 'count',
                                              'Speed' : 'mean'},
                                   fill_value = 0).rename(columns = {'Result' : 'Win'})

Or groupby and aggregate:
# groupby.agg()
df[df.Result == 'Win'].groupby('Name').agg({'Result' : 'count',
                                            'Speed' : 'mean'}).rename({'Result' : 'Win'})

Same results:


text:
Q: PostConfirmationTrigger for federated sign-in in AWS Cognito I am using AWS Cognito for auth. I am using AWS Amplify framework.
Currently I have email-password signup option. On Cognito PostConfirmationTrigger I add user to User DynamoDB table.
I want to add google signup option as well.
In federated sign-in (signup time), this trigger is not triggered so I am unable to add user to User DynamoDB table.
Any hints how can I invoke that trigger lambda only for first time federated sign-in (signup)?

A: The post confirmation trigger is worth avoiding as it also doesn't trigger for admin confirmations. Reimplement it as a post-authentication or pre-token-generation trigger and, if need be, add a condition expression to your put item request to avoid overwriting existing user items.
Cognito is a bit borked when it comes to federated sign-on and triggers. Triggers only seem to be called the first time a user logs in.


text:
Q: Evitar do cálculo ficar negativo Colegas,
Como eu faria para que o cálculo do carrinho não ficasse negativo. Veja abaixo:
Quando clico no botão -  a quantidade permanece em 1, mas o cálculo continua para o negativo:

O Código que estou usando é:
 // subtrair quantidade
$('.value-minus').on('click', function(){
 var divUpd = $(this).parent().find('.value'), newVal = parseInt(divUpd.text(), 10)-1;
 if(newVal>=1) divUpd.text(newVal);
 var valorProduto = $(this).closest('tr').find('td[data-nome]').data('nome'); // Funcional
 trocar = valorProduto.replace(",",".");
 valorTTotal =  document.getElementById("total").innerHTML;
 trocarSTotal = valorTTotal.replace(",",".");
 valorTotal = trocarSTotal - trocar;

if(result == '0.00'){ resultado = result; }else{ resultado = ''; }
 document.getElementById("total").innerHTML = valorTotal.toFixed(2) + resultado;
 document.getElementById("subtotal").innerHTML = valorTotal.toFixed(2);
 $.ajax({
     type: "GET",
     dataType: 'json',
      data:{ valor: valorTotal.toFixed(2) },
     url: "atualizar-carrinho.php",
     success: function(resposta){
     }
  });
});

HTML

1

A: Consegui resolver. Criei uma condicional ficando dessa forma:
if(newVal >= 1){
     valorTotal = trocarSTotal - trocar;
}

newVal é a quantidade.


text:
Q: Mongo array limit I'm trying to insert an object in Mongo using the native node library. I have an object that has an array property that has 1620 objects. In the documentation it says mongo has support for nesting up to 100 levels which I'm not running into. The objects in the array are just objects, they don't have any arrays. The size of the total document with all the items is only 456Kb. If I limit the array to 788 objects they do get saved in the database but it crashses the app. Am I running into a problem with the native mongo library for node? Missing a setting for database?
var droplist = convertOptionList(data);

MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
  if(err) {console.log('error'); throw err;}

  var collection = db.collection('droplist');

  collection.insert(droplist, function(err, objects) {
    if(err) {
      console.log('error');
      throw err;
    }
    //never see this message. app crashes but with fewer items the query passes
    console.log("A-Ok");
  });
  db.close();
});

Update
Working version of the code. Slight change to move the db.close() inside of the callback for insert and preventing the db.close to be called before the objects have all been inserted.
var droplist = convertOptionList(data);

MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
  if(err) {console.log('error'); throw err;}

  var collection = db.collection('droplist');

  collection.insert(droplist, function(err, objects) {
    if(err) {
      console.log('error');
      throw err;
    }
    db.close();
  });
});

A: Rookie mistake. I put my db.close() outside of my callback so the connection was closing before the query could run/finish.  Moved my db.close() into the callback and everything works now.


text:
Q: Reading barcode from an external reader device in browser I would to receive barcode string events in the browser  when a barcode reader device is connected to the computer. I have got no idea about how this is possible. But im expecting an implementation like:
window.addEventListener('scanner', function(readerEvent){
  console.log(readerEvent
})

A: A lot of barcode reader devices operate as a "keyboard wedge" - that is, when reading a barcode, they act as if someone was typing the equivalent text using a keyboard. Your program just uses the normal I/O operations used for obtaining input typed on a keyboard.
In the case of USB connected barcode readers, I imagine they comply with the USB HID profile.


text:
Q: I'm trying to make expanding cards using Vue, the problem is that when expanding a card, the cards on the right create an empty space I'm trying to make expanding cards using Vue, the problem is that when expanding a card, the cards on the right create an empty space,the entire bottom row goes down, and I just wanted the card directly below it to go down, not all.
This is the way it is currently:

This is the way I want to:

Here is the part of the code that I believe controls this, or would it be in the expansion part?
<v-container class="pt-0 mt-0">
  <v-layout row wrap>
    <v-flex
      xs12
      md6
      lg3
      v-for="stateCard in filteredSearch"
      :key="stateCard.name"
    >
      <MakeTheCard :item="infoCard" />

    </v-flex>
  </v-layout>
</v-container>

A: I think that you have a CSS problem rather than Vue.
One approach is to make a flex container with columns, each containing X amount of elements.
like so:

      <Card v-for="card in 2" :key="card" />

      <Card v-for="card in 2" :key="card" />

      <Card v-for="card in 1" :key="card" />

Just made a demo for you: https://codesandbox.io/s/withered-leaf-mv8lp


text:
Q: Use structured array to name axis in numpy array I must be making some sort of really trivial mistake, but I'm trying to create a structured array with names for a single axis, e.g., I have an array data with shape (2, 3, 4), and I want to name the first axis such that I can access data['a'] and data['b'] in an both cases get (3, 4) shaped slices.  I tried:
shape = (2, 3, 4)
data = np.arange(np.product(shape)).reshape(shape)

dtype = [(nn, float) for nn in ['a', 'b']]
data = np.array(data, dtype=dtype)

But this seems to duplicates all of the data into both 'a' and 'b', e.g.
print(data.shape)
print(data['a'].shape)
> (2, 3, 4)
> (2, 3, 4)

I tried specifying that the shape (in the dtype specification) should be (3, 4) but that duplicated the data 12 more times... and I tried changing the axes order to (3, 4, 2), but that doesn't do anything.  Any help appreciated!

A: In [263]: shape = (2, 3, 4)
     ...: data = np.arange(np.product(shape)).reshape(shape)
     ...:
     ...: dtype = [(nn, float) for nn in ['a', 'b']]

While it may be possible to transform data, the surer approach is to make the desired target array, and copy values to it:
In [264]: res = np.zeros(shape[1:], dtype)
In [265]: res['a'] = data[0]
In [266]: res['b'] = data[1]
In [267]: res
Out[267]:
array([[( 0., 12.), ( 1., 13.), ( 2., 14.), ( 3., 15.)],
       [( 4., 16.), ( 5., 17.), ( 6., 18.), ( 7., 19.)],
       [( 8., 20.), ( 9., 21.), (10., 22.), (11., 23.)]],
      dtype=[('a', '<f8'), ('b', '<f8')])
In [268]: res['a'].shape
Out[268]: (3, 4)

In this structured array a record consists of 2 floats, and databuffer, contains:
In [272]: res.view(float).ravel()
Out[272]:
array([ 0., 12.,  1., 13.,  2., 14.,  3., 15.,  4., 16.,  5., 17.,  6.,
       18.,  7., 19.,  8., 20.,  9., 21., 10., 22., 11., 23.])

This is different from the data, [0,1,2,3,...].  So there isn't any sort of reshape or view or astype that will convert one to the other.
So there is a simple mapping from the structured array to a (3,4,2) array, but not your source.
In [273]: res.view(float).reshape(3,4,2)
Out[273]:
array([[[ 0., 12.],
        [ 1., 13.],
        [ 2., 14.],
        [ 3., 15.]],

       [[ 4., 16.],
        [ 5., 17.],
        [ 6., 18.],
        [ 7., 19.]],

       [[ 8., 20.],
        [ 9., 21.],
        [10., 22.],
        [11., 23.]]])


text:
Q: Reactor on-demand flux or a sink Consider a HTTP controller endpoint that accepts requests, validates and then returns ack, but in a meantime in a background does some "heavy work".
There are 2 approaches with Reactor (that I'm interested in) that you can achieve this:
First approach
@PostMapping(..)
fun acceptRequest(request: Request): Response {
  if(isValid(request)) {
    Mono.just(request)
      .flatMap(service::doHeavyWork)
      .subscribe(...)
    return Response(202)
  } else {
    return Response(400)
  }
}

Second approach
class Controller {
  private val service = ...
  private val sink = Sinks.many().unicast().onBackpressureBuffer<Request>()
  private val stream = sink.asFlux().flatMap(service::doHeavyWork).subscribe(..)

  fun acceptRequest(request: Request): Response {
    if(isValid(request)) {
      sink.tryEmitNext(request) // for simplicity not handling errors
      return Response(202)
    } else {
      return Response(400)
    }
  }
}

Which approach is better/worse and why?
The reason I'm asking is, that in Akka, building streams on demand was not really effective, since the  stream needed to materialize every time, so it was better to have the "sink approach". I'm wondering if this might be a case for reactor as well or maybe there are other advantages / disadvantages of using those approaches.

A: I'm not too familiar with Akka, but building a reactive chain definitely doesn't attract a huge overhead with Reactor - that's the "normal" way of handling a request. So I don't see the need to use a separate sink like in your second approach - that just seems to be adding complexity for little gain. I'd therefore say the first approach is better.
That being said, generally, subscribing yourself as you do in both examples isn't recommended - but this kind of "fire and forget" work is one of the few cases it might make sense. There's just a couple of other potential caveats I'd raise here that may be worth considering:

*

*You call the work "heavy", and I'm not sure if that means it's CPU heavy, or just IO heavy or takes a long time. If it just takes a long time due to firing off a bunch of requests, then that's no big deal. If it's CPU heavy however, then that could cause an issue if you're not careful - you probably don't want to execute CPU heavy tasks on your event loop threads. In this case, I'd probably create a separate scheduler backed by your own executor service, and then use subscribeOn() to offload those CPU heavy tasks.

*Remember the "fire and forget" pattern in this case really is "forget" - you have absolutely no way of knowing if the heavy task you've offloaded has worked or not, since you've essentially thrown that information away by self-subscribing. Depending on your use-case that might be fine, but if the task is critical or you need some kind of feedback if it fails, then it's worth considering that may not be the best approach.


text:
Q: does not match format '%Y-%m-%d %H:%M:%S Can't see the issue with not matching the format.
chDate = []
for value in sheet.iter_cols(min_row=2,min_col=6,max_col=6, values_only=True):
    chDate.append(str(value))

chDate = [datetime.strptime(d, "%Y-%m-%d %H:%M:%S") for d in chDate]

error output


text:
Q: Dockerized Hyperledger Caliper Exited with code 0 I'm using Hyperledger Caliper 0.4.2 to benchmark a Hyperldger Fabric 2.1.0 network deployed on a Docker Swarm Cluster. The Fabric network is up and running and all the Chaincodes are installed and initiated properly. The Caliper benchmark is dockerized and I'm running this on the same Docker network. However, when I start the container it hangs up after enrolling all the clients as shown in the log below.
    caliper_2.2    | 2021.04.17-14:45:21.445 info  [caliper] [cli-launch-manager]   Binding specification is present, performing binding for "fabric:2.1.0"
caliper_2.2    | 2021.04.17-14:45:21.448 warn  [caliper] [bind]         Working directory not specified. Using "/hyperledger/caliper/workspace"
caliper_2.2    | 2021.04.17-14:45:21.448 info  [caliper] [bind]         User-provided arguments for npm: "-g"
caliper_2.2    | 2021.04.17-14:45:21.448 info  [caliper] [bind]         Binding for fabric@2.1.0. This might take some time...
caliper_2.2    | 2021.04.17-14:45:21.448 info  [caliper] [bind]         Using working directory: /hyperledger/caliper/workspace
caliper_2.2    | 2021.04.17-14:45:21.449 info  [caliper] [bind]         Calling npm with: install -g fabric-common@2.1.0 fabric-protos@2.1.0 fabric-network@2.1.0 fabric-ca-client@2.1.0
caliper_2.2    | npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
caliper_2.2    | npm WARN deprecated har-validator@5.1.5: this library is no longer supported
caliper_2.2    | + fabric-protos@2.1.0
caliper_2.2    | + fabric-network@2.1.0
caliper_2.2    | + fabric-common@2.1.0
caliper_2.2    | + fabric-ca-client@2.1.0
caliper_2.2    | updated 4 packages in 5.591s
caliper_2.2    | 2021.04.17-14:45:27.588 info  [caliper] [cli-launch-manager]   Set workspace path: /hyperledger/caliper/workspace
caliper_2.2    | 2021.04.17-14:45:27.589 info  [caliper] [cli-launch-manager]   Set benchmark configuration path: /hyperledger/caliper/workspace/scenarios/config.yaml
caliper_2.2    | 2021.04.17-14:45:27.589 info  [caliper] [cli-launch-manager]   Set network configuration path: /hyperledger/caliper/workspace/networks/fabric/network-config3.yaml
caliper_2.2    | 2021.04.17-14:45:27.589 info  [caliper] [cli-launch-manager]   Set SUT type: fabric
caliper_2.2    | 2021.04.17-14:45:27.631 info  [caliper] [benchmark-validator]  No observer specified, will default to `none`
caliper_2.2    | 2021.04.17-14:45:27.631 info  [caliper] [caliper-engine]       Starting benchmark flow
caliper_2.2    | 2021.04.17-14:45:28.154 info  [caliper] [fabric-connector]     Initializing gateway connector compatible with installed SDK: 2.1.0
caliper_2.2    | 2021.04.17-14:45:28.586 info  [caliper] [caliper-engine]       Network configuration attribute "caliper.command.start" is not present, skipping start command
caliper_2.2    | 2021.04.17-14:45:28.586 info  [caliper] [connectors/v2/fabric-gateway]         Fabric SDK version: 2.1.0; TLS: server
caliper_2.2    | 2021.04.17-14:45:28.587 warn  [caliper] [connectors/v2/fabric-gateway]         Administrative actions are not possible with Fabric SDK version: 2.1.0
caliper_2.2    | 2021.04.17-14:45:28.587 info  [caliper] [connectors/v2/fabric-gateway]         Fabric SDK version: 2.1.0; TLS: server
caliper_2.2    | 2021.04.17-14:45:28.587 info  [caliper] [connectors/v2/fabric-gateway]         Creating new InMemoryWallets for organizations
caliper_2.2    | 2021.04.17-14:45:28.588 info  [caliper] [connectors/v2/fabric-gateway]         Initializing administrators
caliper_2.2    | 2021.04.17-14:45:28.588 info  [caliper] [connectors/v2/fabric-gateway]         No admin.Org1 found in caliper configuration file - unable to perform admin options
caliper_2.2    | 2021.04.17-14:45:28.588 info  [caliper] [connectors/v2/fabric-gateway]         No admin.Org2 found in caliper configuration file - unable to perform admin options
caliper_2.2    | 2021.04.17-14:45:28.588 info  [caliper] [connectors/v2/fabric-gateway]         No admin.Org3 found in caliper configuration file - unable to perform admin options
caliper_2.2    | 2021.04.17-14:45:28.589 info  [caliper] [connectors/v2/fabric-gateway]         No admin.Org4 found in caliper configuration file - unable to perform admin options
caliper_2.2    | 2021.04.17-14:45:28.589 info  [caliper] [connectors/v2/fabric-gateway]         No admin.Org5 found in caliper configuration file - unable to perform admin options
caliper_2.2    | 2021.04.17-14:45:28.589 info  [caliper] [connectors/v2/fabric-gateway]         Completed initializing administrators
caliper_2.2    | 2021.04.17-14:45:29.946 info  [caliper] [connectors/v2/fabric-gateway]         Initializing users
caliper_2.2    | 2021.04.17-14:45:29.947 info  [caliper] [connectors/v2/fabric-gateway]         Client client0.org1.digiblocks.com being initialized using provided crypto content
caliper_2.2    | 2021.04.17-14:45:29.947 info  [caliper] [connectors/v2/fabric-gateway]         Adding identity for name client0.org1.digiblocks.com to wallet for organization Org1
caliper_2.2    | 2021.04.17-14:45:29.947 info  [caliper] [connectors/v2/fabric-gateway]         Identity client0.org1.digiblocks.com created and imported to wallet
caliper_2.2    | 2021.04.17-14:45:29.947 info  [caliper] [connectors/v2/fabric-gateway]         Client client0.org2.digiblocks.com being initialized using provided crypto content
caliper_2.2    | 2021.04.17-14:45:29.948 info  [caliper] [connectors/v2/fabric-gateway]         Adding identity for name client0.org2.digiblocks.com to wallet for organization Org2
caliper_2.2    | 2021.04.17-14:45:29.948 info  [caliper] [connectors/v2/fabric-gateway]         Identity client0.org2.digiblocks.com created and imported to wallet
caliper_2.2    | 2021.04.17-14:45:29.948 info  [caliper] [connectors/v2/fabric-gateway]         Client client0.org3.digiblocks.com being initialized using provided crypto content
caliper_2.2    | 2021.04.17-14:45:29.948 info  [caliper] [connectors/v2/fabric-gateway]         Adding identity for name client0.org3.digiblocks.com to wallet for organization Org3
caliper_2.2    | 2021.04.17-14:45:29.948 info  [caliper] [connectors/v2/fabric-gateway]         Identity client0.org3.digiblocks.com created and imported to wallet
caliper_2.2    | 2021.04.17-14:45:29.948 info  [caliper] [connectors/v2/fabric-gateway]         Client client0.org4.digiblocks.com being initialized using provided crypto content
caliper_2.2    | 2021.04.17-14:45:29.949 info  [caliper] [connectors/v2/fabric-gateway]         Adding identity for name client0.org4.digiblocks.com to wallet for organization Org4
caliper_2.2    | 2021.04.17-14:45:29.949 info  [caliper] [connectors/v2/fabric-gateway]         Identity client0.org4.digiblocks.com created and imported to wallet
caliper_2.2    | 2021.04.17-14:45:29.949 info  [caliper] [connectors/v2/fabric-gateway]         Client client0.org5.digiblocks.com being initialized using provided crypto content
caliper_2.2    | 2021.04.17-14:45:29.949 info  [caliper] [connectors/v2/fabric-gateway]         Adding identity for name client0.org5.digiblocks.com to wallet for organization Org5
caliper_2.2    | 2021.04.17-14:45:29.949 info  [caliper] [connectors/v2/fabric-gateway]         Identity client0.org5.digiblocks.com created and imported to wallet
caliper_2.2    | 2021.04.17-14:45:29.949 info  [caliper] [connectors/v2/fabric-gateway]         Completed initializing users
caliper_2.2    | 2021.04.17-14:45:29.949 info  [caliper] [caliper-engine]       Executed "init" step in 1.363 seconds
caliper_2.2    | 2021.04.17-14:45:29.950 warn  [caliper] [connectors/v2/fabric-gateway]         Install smart contract not available with Fabric SDK version: 2.1.0
caliper_2.2    | 2021.04.17-14:45:29.950 info  [caliper] [caliper-engine]       Executed "install" step in 0 seconds
caliper_2.2    | 2021.04.17-14:45:29.952 info  [caliper] [monitor.js]   Attempting to create resource monitor of type docker
caliper_2.2    | 2021.04.17-14:45:29.954 info  [caliper] [default-observer]     Observer interval set to 5000 seconds
caliper_2.2    | 2021.04.17-14:45:29.955 info  [caliper] [round-orchestrator]   Preparing worker connections
caliper_2.2    | 2021.04.17-14:45:29.956 info  [caliper] [worker-orchestrator]  Launching worker 1 of 1
caliper_2.2    | 2021.04.17-14:45:29.962 info  [caliper] [worker-orchestrator]  Messenger not configured, entering configure phase...
caliper_2.2    | 2021.04.17-14:45:29.962 info  [caliper] [worker-orchestrator]  No existing workers detected, entering worker launch phase...
caliper_2.2    | 2021.04.17-14:45:29.963 info  [caliper] [worker-orchestrator]  Waiting for 1 workers to be connected...
caliper_2.2    | 2021.04.17-14:45:30.387 info  [caliper] [cli-launch-worker]    Worker is a locally forked process, skipping binding step already performed by the manager process
caliper_2.2    | 2021.04.17-14:45:30.389 info  [caliper] [cli-launch-worker]    Set workspace path: /hyperledger/caliper/workspace
caliper_2.2    | 2021.04.17-14:45:30.389 info  [caliper] [cli-launch-worker]    Set benchmark configuration path: /hyperledger/caliper/workspace/scenarios/config.yaml
caliper_2.2    | 2021.04.17-14:45:30.389 info  [caliper] [cli-launch-worker]    Set network configuration path: /hyperledger/caliper/workspace/networks/fabric/network-config3.yaml
caliper_2.2    | 2021.04.17-14:45:30.389 info  [caliper] [cli-launch-worker]    Set SUT type: fabric
caliper_2.2 exited with code 0

The strange this is it does not output any errors. Following is the Docker-Compose file of the Caliper
version: "3"
networks:
  caliper-overlay:
    external:
      name: caliper-overlay

services:
  caliper_2_2:
    container_name: caliper_2.2
    image: hyperledger/caliper:0.4.2
    command: launch manager --caliper-fabric-gateway-enabled --caliper-fabric-gateway-localhost=false
    environment:
      - CALIPER_BIND_SUT=fabric:2.1.0
      - CALIPER_BENCHCONFIG=scenarios/config.yaml
      - CALIPER_NETWORKCONFIG=networks/fabric/network-config3.yaml
    volumes:
      - ./:/hyperledger/caliper/workspace
    networks:
      caliper-overlay:
        aliases:
          - caliper.digiblocks.com

Any insights to debug this issue will be appreciated.


text:
Q: clearing the cache from jQuery's data-dom-cache with button click I have a search page which has data-dom-cache in the page. So if the user happens to go back to the search page, his/her results are saved. However, after the user goes through the whole process, he/she can choose to press the button "Search Again" to start over again. This time the page needs to  reset to the default stage and not have the saved results.
Is there any way I can do this in jQuery? I'm also using MVC 4 RC, so if theres any way to fix that in the controller, I'd be happy to hear it. I tried using
HttpResponse.RemoveOutputCacheItem("/Views/Booking/Index.cshtml");

but I wasn't able to get it to work. Thanks for your help.


text:
Q: HTML5  element on Android According to:
http://developer.android.com/sdk/android-2.0-highlights.html
Android 2.0 should support the HTML5 video element. I haven't been able to get this to work using a Motorola Droid, and haven't been able to successfully view a video on any of the HTML5 video example pages out there. Since there currently isn't support for QuickTime or Flash, this is the only other thing I can think of for embedding mp4 video in a web page. Has anyone had any luck with this?

A: Roman's answer worked fine for me - or at least, it gave me what I was expecting. Opening the video in the phone's native application is exactly the same as what the iPhone does.
It's probably worth adjusting your viewpoint and expect video to be played fullscreen in its own application, and coding for that. It's frustrating that clicking the video isn't sufficient to get it playing in the same way as the iPhone does, but seeing as it only takes an onclick attribute to launch it, it's not the end of the world.
My advice, FWIW, is to use a poster image, and make it obvious that it will play the video. I'm working on a project at the moment that does precisely that, and the clients are happy with it - and also that they're getting the Android version of a web app for free, of course, because the contract was only for an iPhone web app.
Just for illustration, a working Android video tag is below. Nice and simple.
<video src="video/placeholder.m4v" poster="video/placeholder.jpg" onclick="this.play();"/>

A: Here I include how a friend of mine solved the problem of displaying videos in HTML in Nexus One:
I never was able to make the video play inline. Actually many people on the internet mention explicitly that inline video play in HTML is supported since Honeycomb, and we were fighting with Froyo and Gingerbread... Also for smaller phones I think that playing full screen is very natural - otherwise not so much is visible. So the goal was to make the video open in full screen. However, the proposed solutions in this thread did not work for us - clicking on the element triggered nothing. Furthermore the video controls were shown, but no poster was displayed so the user experience was even weirder. So what he did was the following:
Expose native code to the HTML to be callable via javascript:
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(jsInterface, "JSInterface");

The code itself, had a function that called native activity to play the video:
public class JavaScriptInterface {
    private Activity activity;

    public JavaScriptInterface(Activity activiy) {
        this.activity = activiy;
    }

    public void startVideo(String videoAddress){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse(videoAddress), "video/3gpp"); // The Mime type can actually be determined from the file
        activity.startActivity(intent);
    }
}

Then in the HTML itself he kept on failing make the video tag work playing the video. Thus, finally he decided to overwrite the onclick event of the video, making it do the actual play. This almost worked for him - except for no poster was displayed. Here comes the most weird part - he kept on receiving ERROR/AndroidRuntime(7391): java.lang.RuntimeException: Null or empty value for header "Host" every time he set the poster attribute of the tag. Finally he found the issue, which was very weird - it turned out that he had kept the source subtag in the video tag, but never used it. And weird enough exactly this was causing the problem. Now see his definition of the video section:
<video width="320" height="240" controls="controls" poster='poster.gif'  onclick="playVideo('file:///sdcard/test.3gp');" >
   Your browser does not support the video tag.
</video>

Of course you need to also add the definition of the javascript function in the head of the page:
<script>
  function playVideo(video){
    window.JSInterface.startVideo(video);
  }
</script>

I realize this is not purely HTML solution, but is the best we were able to do for Nexus One type of phone.
All credits for this solution go to Dimitar Zlatkov Dimitrov.

A: I've just done some experimentation with this, and from what I can tell you need three things:

*

*You must not use the type attribute when calling the video.

*You must manually call video.play()

*The video must be encoded to some quite strict parameters; using the iPhone setting on Handbrake with the 'Web Optimized' button checked usually does the trick.

Have a look at the demo on this page: http://broken-links.com/tests/video/
This works, AFAIK, in all video-enabled desktop browsers, iPhone and Android.
Here's the markup:
<video id="video" autobuffer height="240" width="360">
<source src="BigBuck.m4v">
<source src="BigBuck.webm" type="video/webm">
<source src="BigBuck.theora.ogv" type="video/ogg">
</video>

And I have this in the JS:
var video = document.getElementById('video');
video.addEventListener('click',function(){
  video.play();
},false);

I tested this on a Samsung Galaxy S and it works fine.

A: If you manually call video.play() it should work:
<!DOCTYPE html>
<html>
<head>
  <script>
    function init() {
      enableVideoClicks();
    }

    function enableVideoClicks() {
      var videos = document.getElementsByTagName('video') || [];
      for (var i = 0; i < videos.length; i++) {
        // TODO: use attachEvent in IE
        videos[i].addEventListener('click', function(videoNode) {
          return function() {
            videoNode.play();
          };
        }(videos[i]));
      }
    }
  </script>
</head>
<body onload="init()">

  <video src="sample.mp4" width="400" height="300" controls></video>

  ...

</body>
</html>

A: pointing my android 2.2 browser to html5test.com, tells me that the video element is supported, but none of the listed video codecs... seems a little pointless to support the video element but no codecs??? unless there is something wrong with that test page.
however, i did find the same kind of situation with the audio element: the element is supported, but no audio formats. see here:
http://textopiablog.wordpress.com/2010/06/25/browser-support-for-html5-audio/

A: Nothing worked for me until I encoded the video properly.  Try this guide for the correct handbrake settings:
http://forum.handbrake.fr/viewtopic.php?f=7&t=9694

A: Maybe you have to encode the video specifically for the device eg:
<video id="movie" width="320" height="240" autobuffer controls>
  <source src="pr6.ogv" type='video/ogg; codecs="theora, vorbis"'>
  <source src="pr6.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
<source src="pr6.mp4" type='video/mp4; codecs="some droid video codec, some droid audio codec"'>
</video>

There are some examples of encoding configurations that worked on here:
https://supportforums.motorola.com

A: Try h.264 in an mp4 container. I've had much success with it on my Droid X. I've been using zencoder.com for format conversions.

A: This works for me:
<video id="video-example" width="256" height="177" poster="image.jpg">
<source src="video/video.mp4" type="video/mp4"></source>
<source src="video/video.ogg" type="video/ogg"></source>
This browser does not support HTML5
</video>

Only when the .mp4 is on top and the videofile is not to big.

A: It's supposed to work, but watch the resolution:
Android 2.0 and webkit

Canvas works right out of the box,
  while Geolocation seems to not work at
  all in the Emulator. Of course, I have
  to send it mock locations to get it to
  work, so I have no idea what this
  would be like on an actual phone. I
  can say the same thing with the video
  tag. There are issues with it not
  actually playing the video, BUT I
  think it's the fact that the video is
  a higher resolution than what the
  Emulator can handle. We'll know more
  once someone tries this on a Motorola
  Droid or other next-gen Android device

A: This might not exactly answer your question, but we're using the 3GP or 3GP2 file format. Better even to use the rtsp protocol, but the Android browser will also recognize the 3GP file format.
You can use something like
self.location = URL_OF_YOUR_3GP_FILE

to trigger the video player. The file will be streamed and after playback ends, handling is returned to the browser.
For me this solves a lot of problems with current video tag implementation on android devices.

A: According to : https://stackoverflow.com/a/24403519/365229

This should work, with plain Javascript:
var myVideo = document.getElementById('myVideoTag');

myVideo.play();
if (typeof(myVideo.webkitEnterFullscreen) != "undefined") {
    // This is for Android Stock.
    myVideo.webkitEnterFullscreen();
} else if (typeof(myVideo.webkitRequestFullscreen)  != "undefined") {
    // This is for Chrome.
    myVideo.webkitRequestFullscreen();
} else if (typeof(myVideo.mozRequestFullScreen)  != "undefined") {
    myVideo.mozRequestFullScreen();
}

You have to trigger play() before the fullscreen instruction,
  otherwise in Android Browser it will just go fullscreen but it will
  not start playing. Tested with the latest version of Android Browser,
  Chrome, Safari.

I've tested  it on Android 2.3.3 & 4.4 browser.

A: After much research, in many different devices, up to now, I've reached the simple conclusion that MP4 is much less supported than MOV format.
So, I'm using MOV format, which is supported by all Android and Apple devices, on all browsers.
I've detected weather the device is a mobile device or a desktop browser, and set the SRC accordingly:
if (IsMobile()) {
    $('#vid').attr('src', '/uploads/' + name + '.mov');
}
else {
    $('#vid').attr('src', '/uploads/' + name + '.webm');
}

function IsMobile() {
    var isMobile = false; //initiate as false

    if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
                || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4))) isMobile = true;
    return isMobile;
}

A: I tried using the .mp4 format to play a video on Android devices but that did not go well. So after some trial and error, I converted the video into the .webm format and following code with no extra javascript or JQuery:
<video id="video" class="video" muted loop autoplay>
    <source src="../media/some_video.webm" type="video/webm">
    Sorry, your browser doesn't support embedded videos.
</video>

It worked on an older Android device (at least a few years old as of 2020).

A: HTML5 is supported on both Google (android) phones such as Galaxy S, and iPhone. iPhone however doesn't support Flash, which Google phones do support.


text:
Q: How to avoid duplicated objects being inserted in NSArray? Well, I am having problems with an nsarray that it is adding duplicate objects from an nsdictionary.
The situation is this: I have a plist file with an array of dictionaries. Each dictionary have the key being 'codigo' and 'var'.
What I did is I am checking each 'var' value if it is < 0 and if it is 'codigo' and 'var' will get a color using NSAttributedStrings.
The problem comes when I iterate through the array and add the evaluated 'var' into the new array. I am getting duplicated objects in the final array.
EDIT: Solution derived from xlc0212's answer and help through chat:
_timer = [NSTimer scheduledTimerWithTimeInterval:0.020 target:self
                                        selector:@selector(time:) userInfo:nil repeats:YES];

NSDictionary *redAttrs    = @{NSForegroundColorAttributeName:[UIColor redColor]};
NSDictionary *greenAttrs  = @{NSForegroundColorAttributeName:[UIColor colorWithRed:0.118 green:0.506 blue:0.000 alpha:1.000]};
NSDictionary *orangeAttrs = @{NSForegroundColorAttributeName:[UIColor orangeColor]};

NSString *stringUm = @"";
NSString *stringDois = @"";
NSString *stringTres = @"";

arrayAtivos = [[NSMutableOrderedSet alloc] init];
NSDictionary *item = [[NSDictionary alloc]init];

for (item in array){

    NSString *alfa = [item objectForKey:@"var"];

    float fltNumber = [alfa floatValue];

    if (fltNumber < 0) {
        stringUm = [NSString stringWithFormat:@"%@ %.2f  ",[item objectForKey:@"codigo"], fltNumber];
        int strLength = [stringUm length];
        attStr = [[NSMutableAttributedString alloc] initWithString:stringUm];
        [attStr setAttributes:redAttrs range:NSMakeRange(0,strLength)];

    } else if (fltNumber > 0 ) {
        stringDois = [NSString stringWithFormat:@"%@ %.2f  ",[item objectForKey:@"codigo"], fltNumber];
        int strLength = [stringDois length];
        attStr = [[NSMutableAttributedString alloc] initWithString:stringDois];
        [attStr setAttributes:greenAttrs range:NSMakeRange(0,strLength)];

    } else if (fltNumber == 0) {
        stringTres = [NSString stringWithFormat:@"%@ %.2f  ",[item objectForKey:@"codigo"], fltNumber];
        int strLength = [stringTres length];
        attStr = [[NSMutableAttributedString alloc] initWithString:stringTres];
        [attStr setAttributes:orangeAttrs range:NSMakeRange(0,strLength)];
    }

    [arrayAtivos addObject:attStr];

}

A: NSMutableOrderedSet is what you want. Just replace NSMutableArray with NSMutableOrderedSet and done.
If you want to filter the array, use this
NSArray *array = // your array
NSMutableArray *filteredArray = [[[NSOrderedSet alloc] initWithArray: array] mutableCopy];

Replace
arrayAtivos = [NSMutableArray new];

with this
arrayAtivos = [[NSMutableOrderedSet alloc] init];

and change the type of arrayAtivos to NSMutableOrderedSet

A: If I understand this correctly you could just do a simple check before adding the objects into the array:
if (![arrayAtivos containsObject:attStr]) {
     [arrayAtivos addObject:attStr];
}

A: You could just add them all to an NSSet, which doesn't allow duplicates.
You can get an array from that, although you'll be responsible for sorting them if that is important.


text:
Q: How can I make spring MVC PathVariable more robust? In PathVariable example below:
@GetMapping("/{id}")
SomeReturn get(@PathVariable Long id)
{
      ....
}

If I call this API like /api/100abc, will get a number format exception.
Is there any way to make id more robust, for example:

*

*/api/100

*/api/100abc
In both of them, I'd like to call /api/100.
I know I can change the API parameter type of path variable from Long to String, and do some logic to make things done.
Is there any other way like AOP or Filter to do so?

A: Based on https://www.baeldung.com/spring-mvc-custom-data-binder
You can try :
public class RobustId {
    private Long id;

    public RobustId(Long id) {
        this.id = id;
    }

    // getters and setters below...
}

public class RobustIdConverter implements Converter<String, RobustId> {

    @Override
    public RobustId convert(String from) {
        Long id = null;

        for (int i=0; i<from.length(); i++) {
            char c = from.charAt(i);
            if ( !Character.isDigit(c) ) {
                id = Long.parseLong(from.substring(0, i));
                break;
            }
        }
        return new RobustId(id);
    }
}

@GetMapping("/{id}")
SomeReturn get(@PathVariable RobustId id) {
      ....
}

A: Yes, you can (make path variable "more robust")! ... by implementing custom "binding" and/or "formatting".

Some annotated controller method arguments that represent String-based request input (such as @RequestParam, @RequestHeader, @PathVariable, @MatrixVariable, and @CookieValue) can require type conversion if the argument is declared as something other than String.
For such cases, type conversion is automatically applied based on the configured converters. By default, simple types (int, long, Date, and others) are supported. You can customize type conversion through a WebDataBinder (see DataBinder) or by registering Formatters with the FormattingConversionService. See Spring Field Formatting.
...

Source: MVC|WebFlux


text:
Q: what is the meaning of "flux"? In the present case, we knew that collaboration would be a key theme, so we entered into the construction of this volume with the
meta-issues not only in mind, but also in flux.

A: It's just the ordinary meaning of flux. I'd attribute the odd turn of phrase to zeugma.

flux noun
  3 (mass noun) Continuous change.
  'since the fall of the wall Berlin has been a city in flux'
  'the whole political system is in a state of flux'
  - ODO

The quote says that because they knew the topic of collaboration was important, they started with the meta-issues in mind ... and because collaboration was important, they started with the assumption that the meta-issues weren't fixed. Presumably, the meta-issues would need to be sorted out via collaboration.


text:
Q: @PostMapping doesn't work: Neither BindingResult nor plain target object for bean name 'XXX' available as request attribute I am new to thymeleaf and Spring-Boot, I followed this tutorial to create a submit form I made exactly the same thing,  but I am getting the following exception:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'conjugation' available as request attribute

Can someone tell me what's wrong in my code, knowing that this is my Conjugation class
public class Conjugation {
    private String v;

    public String getV() {
        return this.v;
    }

    public void setV(String v) {
        this.verb = v;
    }

}

This is what I used in my controller
//The Controller
@GetMapping("/conjugate")
  public String vForm(Model model) {
    model.addAttribute("conjugate", new Conjugation());
    return "conjugate";
  }

@PostMapping("/conjugate")
  public String vbSubmit(@ModelAttribute Conjugation conjugate) {
    System.out.println("-->"+conjugate.getV());
    return "index";
  }

And this my index.html file:
<form action="#" th:action="@{/conjugate}" th:object="${conjugation}" method="post">

        V

        <input class="cell" type="text"  th:field="*{v}" />

        <input type="submit" value="Submit" />

A: You add the attribute named as conjugate:
model.addAttribute("conjugate", new Conjugation());

but in your html file you say conjugation
th:object="${conjugation}"

This will work if you replace your current model.addAttribute, with:
model.addAttribute("conjugation", new Conjugation());