text:
Q: using terms in elasticsearch js because of the wonderful documentation Elasticsearch has , I cant figure out the proper syntax to search for a term , this is my code:
  let checkuser = await client.search({
        index: "users",
        type: "my_users",
        body: {
          query: {
            term: {
              email: req.body.email
            }
          }
        }
      });

I wish to search for an object that has a key value pair of 'email' with a certain email, but I wish it to be the exact email I wrote, if its a@mail.com ab@mail.com should not match, I know I need to use terms but when i write it like that it doesn't work, whats wrong with my syntax?
PS this is my index mapping:
  "users" : {
    "mappings" : {
      "jobix_users" : {
        "properties" : {
          "confirmed" : {
            "type" : "boolean"
          },
          "email" : {
            "type" : "text",
            "fields" : {
              "keyword" : {
                "type" : "keyword",
                "ignore_above" : 256
              }
            }
          },
          "firstName" : {
            "type" : "text",
            "fields" : {
              "keyword" : {
                "type" : "keyword",
                "ignore_above" : 256
              }
            }
          },
          "jobNotification" : {
            "type" : "boolean"
          },
          "jobTitle" : {
            "type" : "text",
            "fields" : {
              "keyword" : {
                "type" : "keyword",
                "ignore_above" : 256
              }
            }
          },
          "lastName" : {
            "type" : "text",
            "fields" : {
              "keyword" : {
                "type" : "keyword",
                "ignore_above" : 256
              }
            }
          },
          "password" : {
            "type" : "text",
            "fields" : {
              "keyword" : {
                "type" : "keyword",
                "ignore_above" : 256
              }
            }
          },
          "userName" : {
            "type" : "text",
            "fields" : {
              "keyword" : {
                "type" : "keyword",
                "ignore_above" : 256
              }
            }
          }
        }
      }
    }
  }

A: You use default mapping and this means that you use standard tokenizer when you index documents.
How you can see in mapping email field have two interpretations:

*

*text

*keyword
In text standard tokenizer is work and save tokens to your index. This mean you can find for term alex and for term mail.com. If you want to find whole email then your query should look as:
{
    "query": {
        "term": {
            "email.keyword": req.body.email
        }
    }
}

But elasticsearch has special uax_url_email tokenizer for urls and mails. I would like to recommend use this tokenizer for the email field.


text:
Q: Indexed query is still very slow in MongoDB I have a simple query like this:
 ({ public: false, publicate: 1, timeline: 1, timeline_visibility: true }).sort({ date: -1})

I have a specific index for that query and it's being used, but the query is very slow. Here is the output of explain():
"cursor" : "BtreeCursor public_1_publicate_1_timeline_1_timeline_visibility_1_date_-1",
"nscanned" : 141461,
"nscannedObjects" : 141461,
"n" : 141461,
"millis" : 535,
"nYields" : 141,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,

I've tried this with MongoDB 2.0.2, 2.0.9 and 2.4 (all on Linux) – same result. How can I fix it?
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP: $_POST, $_GET and $_REQUEST empty on input form evaluation a question that is being asked many times as far as I can see.
Lots of postings concerning this issue also on this website, for example
here: $_POST empty on form submit
and here:
$_POST, $_GET and $_REQUEST Empty
But none of them cured my problem.
I´ve a simple HTML input form with a submit button.
Its "name" tag is set.
My php.ini settings are:
request_order = "GP"
variables_order = "GPCS"
register_globals = Off

The input data is being processed in the Method "action" in "Util.php".
The code for the input form as well as the Util::action method has been provided by our professor (its an assignment for university), as we developed a similar project during the php seminar.
Unfortunately, the $_REQUEST array stays empty in my project.
here´s the source code of the input form:
<?php
require_once('inc/bootstrap.php');

if (AuthenticationManager::isAuthenticated()) {
    Util::redirect("index.php");
}

$userName = isset($_REQUEST['userName']) ? $_REQUEST['userName'] : null;
?>

<?php
require_once('inc/header.php');
?>

Login

<form method="post" action="<?php echo Util::action('login'); ?>">

            User name:
            <input name="userName"
                value="<?php echo htmlentities($userName); ?>" />

            Password:
            <input type="password" name="password" />

    <input type="submit" value="Login" name='login' />
</form>

<?php
require_once('inc/footer.php');
?>

and here the Util.php:
    <?php

    class Util extends BaseObject {
    // Bereinigen eines Strings für die HTML-Ausgabe
    /**
     * @param string $string
     * @return string
     */
    public static function escape($string) {
        return nl2br(htmlentities($string));

    }

    /**
     * @param string $action
     * @param array $params
     */
    public static function action($action, array $params = null ) {

        //enters ELSE branch as IF branch evaluates to false
        //(because $_REQUEST contains 0 elements
        //(so do $_GET and $_POST)
        $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : $_SERVER['REQUEST_URI'];

        //just an attempt for hardcore debugging...
        $req = array_merge($_GET, $_POST);
        $page = count($req); //evaluates to zero

        $res = '/lib/controller.php?action='.rawurlencode($action).'&page='.rawurlencode($page);
        //result is: localhost/lib/controller.php?action=login&page=0

        if ( is_array($params) ) {
            foreach ( $params as $name => $value ) {
                $res.='&'.rawurlencode($name).'='.rawurlencode($value);
            }
        }

        return $res;
    }

    public static function redirect($page = null) {
        if ( $page == null ) {
            $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : $_SERVER['REQUEST_URI'];
        }

        header('Location: '.$page);
    }

    /**
     * Converts a tinyint (from MySQL DB) to boolean (PHP)
     * @param int $tinyInt
     * @return boolean
     */
    public static function tinyintToBoolean($tinyInt) {
        if ($tinyInt == 1) {
            return true;
        } else {
            return false;
        }
    }
}

?>

bootstrap.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 'On');

/**
 * bootstrap must be included in every callable view
 *
 */
spl_autoload_register(function ($class) {
    include 'lib/' . $class . '.php';

});

// create session
SessionContext::create();

//require_once('lib/data/DataManager_' . $class . '.php');
require_once('lib/DataManager.php');

?>


text:
Q: Regex to match multiple occurances IFF another string occurs I'm really hoping this can be solved in regex, but I fear not....
I'm looking for a regex that will return multiple matches of a term ONLY is another term appears in the same string. This is better explained with an example. Consider:
The numbers are 144, 424, and 345. Not 45.

I'd like to match '144', '424' and '345' only. (Any 3 digit number) - but only if they follow the term 'numbers' somewhere before. So the following aditional example:
The numbers we are looking for: 234 & 992

Should return '234' and '992' only.
The following sentence should not match anything:
Some examples: 234, 244 and 12

I thought I was onto something with the following regex:
(?<=numbers\b)(?:.|\n)*?\b(\d{3})\b

But it only matches the first number. Is what I'm trying to achieve even possible? No manner of lookahead or lookbehind seems to work here. For verious reasons I'm limited to this only being a single regex expression, and I don't have the option to selectivly access individual capturing groups after the fact. So looking for a purely regex method!

A: You may use this regex with \G:
(?:\bnumbers\b|(?!^)\G).*?\b(\d{3})\b

RegEx Demo

*

*\G asserts position at the end of the previous match or the start of the string for the first match.

*(?!^) avoids matching \G at line start


text:
Q: why is there a compiler error in this instanceof test I thought the following code would compile and print "No"
class One{
 public static void main(String[] args) {

   One o = new One();
   if(o instanceof Two) {
     System.out.println("Yes");
   } else {
     System.out.println("No");
   }
 }
}

class Two { }

But it is throwing me a compiler error stating  inconvertible types
shouldn't the instanceof operator check if the object is in the inheritence hierarchy and return true if so, and false if not
Edit:
if it is a case of compiler already knowing that a certain condition can never be true and it throws a compiler error why is this code compiling
if(false) {
  System.out.println("Yes");
}

A: You are getting that message because the compiler is able to tell that o cannot be an instance of Two because classes One and Two have no inheritance relationship.
Maybe you meant to write:
Object o = new One();

In that case your test would make sense.

A: I believe it's because you have declared your "o" variable as being of the "One" type.
Change your code to this, and it should compile
   Object o = new One();
   if(o instanceof Two) {
     System.out.println("Yes");
   } else {
     System.out.println("No");
   }

The instanceof operator is meant to be used when you don't know the type in advance. So when you have an object of something that comes in through a method parameter, or when your variable is declared with the type of a base class and want to have different behavior per subclass type. In the scenario you've provided, the compiler can tell you at compile time that what you wrote will never be true, and does so.
Edit: the if(false) compiles, because a lot of people use a pattern like this:
public class Application{

    private static final boolean DEBUG = true;

    public static void main(String args[]){
        if(DEBUG){
            System.out.println("Debugging information");
        }
    }
}

Now imagine a large application where this sort of pattern is repeated in several places. If the compiler would refuse to compile this, it would be much harder to switch from and to DEBUG mode.
In my earlier explanation, maybe I shouldn't have used the words "the compiler can tell you at compile time that what you wrote will never be true". A better description would be "The compiler can tell that what you're writing does not make sense".

A: instanceof is used to identify objects polymorphically referenced by a reference variable of another class, so if the reference variable o is not able to reference to an object of class Two it won't compile.
So this:
One o = new One();
if(o instanceof Two) {
    System.out.println("ok");
}

as a matter of example would be an error similar to this:
int i = 1;
if (i == "s") {
    System.out.println("ok");
}

It can't compile at all!
EDIT
An example of polymorphism where it would make your code compile (as per other's answers):
Object o = new One();

because o can reference to Two, so instanceof will tell you if it does or not.

A: First of all for above program you will get "Incompatible conditional operand types One and   Two" because One and Two do not have any relationship.
To make above program result as True it should be like,
public class One {
    public static void main(String[] args) {

        One o = new Two();
        if (o instanceof Two) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}

class Two extends One {
}

Here, One is parent and Two is child. Parent referring to child object there fore instance of operator will return true.


text:
Q: Salesforce as an OpenId authentication provider Google Apps offers an OpenID API that allows end users to securely sign in to third party web sites using their Google Apps user account.
I want to offer similar functionality - i.e. I want the users of my web site to be able to authenticate using their Salesforce account using OpenID.
Does Salesforce offer a similar API/functionality? I've checked the documentation and seen mentions of OpenID Connect API, but this seems to be in its early stages of development. I've also checked Salesforce's Identity Provider feature, but this seems more geared towards SSO scenarios (not quite sure though - please correct me if I am wrong).

A: (this is an old answer from before open id connect was supported)
they don't support openid connect yet.  in the meantime, take a look at the "web server" oauth 2.0 flow and use the "id" scope to get the user's id.
http://wiki.developerforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com
at the oauth protocol level, there's no guarantee that this id belongs to the user or that it's unique and non-changing, but people use this kind of id for authentication anyway.  this is basically how openid connect works; openid connect just formalizes it and adds in some extra validation.

A: Yes SalesForce supports OpenIdConnect, here is SalesForce developer guide.
You can find implementations for SalesForce authentication providers here.
Just needs to install AspNet.Security.OAuth.Salesforce nuget package and add this code in Startup.cs
services.AddAuthentication()
    .AddSalesforce(options =>
    {
        options.SignInScheme = "Salesforce";

        options.ClientId = "<insert here>";//client id on salesforce connected app
        options.ClientSecret = "<insert here>";//client secret on salesforce connected app
    });

I have it implemented using IdentityServer4 here


text:
Q: node.js express route.get() error I am using express-generator and installed the dependencies, everything else is as is, except this app.js file I've updated and posted here.
I'm getting the error when running npm start. I've posted the error and app.js file. It's probably something basic, I'm a newb. Thanks so much.
Error message
    ryan@\Ryan:~/Desktop/node/frameworks/expressapi$ npm start

> expressapi@0.0.0 start /home/ryan/Desktop/node/frameworks/expressapi
> node ./bin/www

/home/ryan/Desktop/node/frameworks/expressapi/node_modules/express/lib/router/route.js:196
        throw new Error(msg);
              ^
Error: Route.get() requires callback functions but got a [object Undefined]
    at Route.(anonymous function) [as get] (/home/ryan/Desktop/node/frameworks/expressapi/node_modules/express/lib/router/route.js:196:15)
    at EventEmitter.app.(anonymous function) [as get] (/home/ryan/Desktop/node/frameworks/expressapi/node_modules/express/lib/application.js:481:19)
    at Object.<anonymous> (/home/ryan/Desktop/node/frameworks/expressapi/app.js:45:5)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/ryan/Desktop/node/frameworks/expressapi/bin/www:7:11)
npm ERR! weird error 8
npm WARN This failure might be due to the use of legacy binary "node"
npm WARN For further explanations, please read
/usr/share/doc/nodejs/README.Debian

npm ERR! not ok code 0

Server code
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

var products = [
    {
      id: 0,
      name: 'watch',
      description: 'tell time with this amazing watch',
      price: 30.00
    },
    {
      id: 1,
      name: 'sandals',
      description: 'walk in comfort with these sansdals',
      price: 10.00
    },
    {
      id: 2,
      name: 'watch',
      description: 'protect your eyes!',
      price: 25.00
    }
];

app.get('/', routes.index);

app.get('/products', function(req, res) {
  res.json(products);
});

app.get('/products/:id', function(req, res) {
  if (req.params.id > (products.length - 1) || req.params.id < 0) {
    res.statusCode = 404;
    res.end('NotFound');
  }
  res.json(products[req.params.id]);
});

app.post('/products', function(req, res) {
  if (typeof req.body.name === 'undefined') {
    res.statusCode = 400;
    res.end('a product name is required');
  }
  products.push(req.body);
  res.send(req.body);
});

app.put('/products/:id', function(req, res) {
  if (req.params.id > (products.length - 1) || req.params.id < 0) {
    res.satusCode = 404;
    res.end('not found');
  }
  products[req.params.id] = req.body;
  res.send(req.body);
});

app.delete('/products/:id', function(req, res) {
  if (req.params.id > (products.length - 1) || req.params.id < 0) {
    res.statusCode = 400;
    res.end('not found for that id');
  }
  products.splice(req.params.id, 1);
  res.json(products);
});

if i delete line 45 like some have recommended i get the error
ryan@\Ryan:~/Desktop/node/frameworks/expressapi$ npm start

> expressapi@0.0.0 start /home/ryan/Desktop/node/frameworks/expressapi
> node ./bin/www

/home/ryan/Desktop/node/frameworks/expressapi/bin/www:16
app.set('port', port);
    ^
TypeError: Object #<Object> has no method 'set'
    at Object.<anonymous> (/home/ryan/Desktop/node/frameworks/expressapi/bin/www:16:5)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3
npm ERR! weird error 8
npm WARN This failure might be due to the use of legacy binary "node"
npm WARN For further explanations, please read
/usr/share/doc/nodejs/README.Debian

npm ERR! not ok code 0

A: This error tells me that you're not passing in a proper express middleware function: at Object.<anonymous> (/home/ryan/Desktop/node/frameworks/expressapi/app.js:45:5)
I pasted your code into a text editor and I got this line of code for 45:5:
app.get('/', routes.index);
My guess is that you've deleted the file for routes.index (var routes = require('./routes/index');)
Delete this line of code on 45:5 and see if you succeed/get a different error message.
FYI - You have a lot of spelling mistakes that may lead to issues like line 70: res.satusCode = 404; has statusCode misspelled, but that's not your current issue, I believe.

A: It looks like you're requiring ./routes/index, and then trying to call routes.index in app.get('/').  Try only requiring './routes' initially.


text:
Q: Overloading << operator c++ I am trying to output the values of my linked lists, but I can't seem to get my operator<< to work. When I out << previous->key;   It comes out as -1, which is what the HEAD_OF_LIST is. In the program, I call the function l[2] = LLSortedPosInt(2); which sets list #2 to contain one element which is the integer 2.
This is the Class declaration:
struct  Node;
typedef Node* NodePtr;

// The key value HEAD_OF_LIST is used as a "sentinal" value
const int HEAD_OF_LIST = -1;

class LLSortedPosInt {
  public:
   // constructors
                         LLSortedPosInt();
                         LLSortedPosInt(int  key);
                         LLSortedPosInt(int *keys,  int n);         //int *keys is an array of integers
                         LLSortedPosInt(const LLSortedPosInt &l);

   // destructor
                        ~LLSortedPosInt();

   bool                  containsElement (int key) const;
   bool                  isEmpty         (       ) const;

   LLSortedPosInt&       operator= (const LLSortedPosInt &l);
   bool                  operator==(const LLSortedPosInt &l) const;
   bool                  operator!=(const LLSortedPosInt &l) const;

   friend LLSortedPosInt operator+ (const LLSortedPosInt &l1,
                                      const LLSortedPosInt &l2);
   friend LLSortedPosInt operator- (const LLSortedPosInt &l1,
                                      const LLSortedPosInt &l2);
   friend ostream&       operator<<(ostream &out,
                                      const LLSortedPosInt &l);
  private:
   void                  insert    (int key);
   void                  remove    (int key);

   NodePtr head;
};

This is the createNode function:
static NodePtr createNode(int key, NodePtr p) {
   // allocate a new Node for storing the given key value
   NodePtr n = new Node;

   // store the key value and the next pointer
   n->key  = key;
   n->next = p;

   // return the new Node to the caller
   return n;
}

This is my code for the operator<<
ostream&  operator<<  (ostream &out, const LLSortedPosInt &l) {

// an empty list will be printed as <>
// a singleton list (a list having one key value k) will be
//     printed as <k>
// a list having multiple keys such as 2, 5, 7 will be printed
//     as <2, 5, 7>

// print the left angle bracket
out << "<";

NodePtr previous = l.head;
NodePtr current = l.head->next;

//TEST previous AND current
out << previous->key;
out << current->key << ">" << endl << "<";

// print the values of l
while (current != NULL) {
    if (current->key >= 0) {
        if (current->next == NULL) {
            out << current->key;
            break;
        }
        out << current << ", ";
        previous = current;
        current = current->next;
    }
}

// print the right angle bracket
out << ">";

return out;
}

I also have a function that takes an integer input which is below. I am pretty sure this is written correctly, but I am not sure.
LLSortedPosInt::LLSortedPosInt(int key) {
// create the sentinal Node at the head of the list
head = createNode(HEAD_OF_LIST, nullptr);

// add the single element key, as long as it is positive
if (key > 0) {
    head->next = createNode(key, nullptr);
}
}

A: The definition of operator<< could be:
std::ostream& operator<<(std::ostream& out, const LLSortedPosInt& l) {
    out << "<";
    NodePtr current = l.head;
    // check that it actually points to a Node before accessing any fields
    if(current) {
        out << current->key;
        // loop through the links and stream the keys
        while((current = current->next) != nullptr)
            out << "," << current->key;
    }
    out << ">";
    return out;
}

The constructor LLSortedPosInt(int key) should not create a HEAD_OF_LIST node since it's not used for anything. So you can change that constructor to use the one you already have for a list of keys via delegation. Delegation also makes it easy to add a constructor using an initializer_list:
LLSortedPosInt(const int *keys=nullptr, size_t n=0) :
    head(nullptr)
{
    if(keys && n) {
        while(n--) {
            createNode(*keys);
            ++keys;
        }
    }
}

// single key construction
LLSortedPosInt(int key) :
    LLSortedPosInt(&key, 1) // delegate
{}

// construction using an initializer list
LLSortedPosInt(std::initializer_list<int> il) :
    LLSortedPosInt(il.begin(), il.size()) // delegate
{}

The static createNode interface is a little odd. Users of the function shouldn't need to supply the pointer to the next node. That's what the container class is for. It could be made into a normal member function and create the node in the correct place directly:
NodePtr createNode(int key) {
    NodePtr current = head;
    NodePtr previous = nullptr;

    while(current && (current->key < key)) {
        previous = current;
        current = current->next;
    }

    if(previous) {
        // insert the node between previous and previous->next
        NodePtr rv = new Node(key, previous->next);
        return previous->next = rv;
    } else {
        // insert the node first in the list
        NodePtr rv = new Node(key, head);
        return head = rv;
    }
}

Given that the actual Node looks something like this:
struct Node {
    Node* next;
    int key;
    Node(int k, Node* n) : next(n), key(k) {}
    Node(const Node&) = delete;
    Node(Node&&) = delete;
    Node& operator=(const Node&) = delete;
    Node& operator=(Node&&) = delete;
    ~Node() = default;
};

using NodePtr = Node*;


text:
Q: flask-blueprints - use decorator before function call with separated router and controller files I came accross this syntax:
users.route('/me', methods=["GET"])(get_user)

when instead of the usual definition after the route, I can just specify its name after the route, and define it in another file.
what about decorators? I'm using flask-jwt-extended for auth, can where is the right place to specify the decorator?
previous syntax, before separating the bluepring/routes from controller:
@users.route('/me', methods=["GET"])
@jwt_required()
def get_user():
<function code here>


text:
Q: JQuery not seeing "value" property I have the following function:
$(function () {
    $(".techdropdown").change(function () {
        var recordToUpdate = $(this).attr("id");
        var selectedTech = $(".techdropdown").val();
        window.alert(selectedTech);
        $.post("/CalloutAdmin/UpdateTech?tech=" + selectedTech + "&id=" + recordToUpdate, function () { document.location = "/CalloutAdmin/Index/"; });
    });
});

And a dropdownlist as follows:
@foreach (var item in Model)
                {
    @Html.DropDownList("TechnicianId", null, String.Empty, new { id = item.CalloutId, @class = "techdropdown" })
}

Now what is BIZARRE is the JQuery detects the value property and displays it (selectedTech) with the FIRST dropdown created by the foreach loop, but the other dropdowns straight after seem to send no value property.
I have checked at runtime and the select options most definitely do have the correct value properties, but JQuery just doesn't see them. Any ideas?
UPDATE
Here is my HTML for the table containing my dropdowns:

                        Client Name

                        Technician Name

                        Date/Time Logged

                        Job Status

                        Technician Status

                            Michael Barnett

                            Craig

                            <select class="techdropdown" id="7" name="TechnicianId"><option value="">Choose technician...</option>
<option value="1">Mike</option>
<option value="2">Craig</option>
</select>

                            2013/08/07 01:27:50 AM

                            ASSIGNED

                            Edit |
            Details |
            Delete

                            Michael Barnett

                            <select class="techdropdown" id="8" name="TechnicianId"><option value="">Choose technician...</option>
<option value="1">Mike</option>
<option value="2">Craig</option>
</select>

                            2013/08/07 01:28:19 AM

                            UNASSIGNED

                            Edit |
            Details |
            Delete

A: This is another approach of binding a drop down list. Say you have the following model:
public class TestViewModel
{
    // this will hold the value that we select
    public int SelectedCalloutId { get; set; }

    // these are the actual items
    public IEnumerable<SelectListItem> Technicians { get; set; }

    // add other properties needed for your view
}

Here is sample controller Action:
    public ActionResult Index()
    {
        // or you know fetch them from your data source
        var technicians = new List<Technician>
        {
            new Technician {TechnicianId = "SOME_ID_1", CalloutId = 123},
            new Technician {TechnicianId = "SOME_ID_2", CalloutId = 321},
            new Technician {TechnicianId = "SOME_ID_3", CalloutId = 234}
        };

        IEnumerable<SelectListItem> options = technicians.Select(x => new SelectListItem {Text = x.TechnicianId, Value = x.CalloutId.ToString()});

        return View(new TestViewModel {Technicians = options});
    }

Then finally in your view:
@model YourApp.Models.TestViewModel
@Html.DropDownListFor(x => x.SelectedCalloutId, Model.Technicians, new { @class = "techdropdown"})

This will generate more or less the following html:
<select class="techdropdown" id="SelectedCalloutId" name="SelectedCalloutId">
    <option value="123">SOME_ID_1</option>
    <option value="321">SOME_ID_2</option>
    <option value="234">SOME_ID_3</option>
</select>

Then of course on your client side:
$("#SelectedCalloutId").change(function () {
    // this now has a value
    var selectedId = $(this).val();
});

I hope this helps.
EDIT
Here is a fiddle to demonstrate the last part: http://jsfiddle.net/4K2TD/

A: Try add "option:selected" as follows:
$(function () {
    $(".techdropdown").change(function () {
        var recordToUpdate = $(this).attr("id");
        var selectedTech = $(".techdropdown option:selected").val();
        window.alert(selectedTech);
        $.post("/CalloutAdmin/UpdateTech?tech=" + selectedTech + "&id=" + recordToUpdate, function () { document.location = "/CalloutAdmin/Index/"; });
    });
});

A: looks like your javascript is a bit whacky.
var selectedTech = $(".techdropdown").val();

this will take first element with class "techdropdown" and return its value.
if you want value of the dropdown which triggered the change event then you will need:
var selectedTech = $(this).val();

Hope that helps.

A: Try this:
$(function () {
    $(".techdropdown").change(function () {
        var recordToUpdate = $(this).attr("id");
        var selectedTech = $(".techdropdown").selected.val();
        window.alert(selectedTech);
        $.post("/CalloutAdmin/UpdateTech?tech=" + selectedTech + "&id=" + recordToUpdate, function () { document.location = "/CalloutAdmin/Index/"; });
    });
});


text:
Q: Store and Retrieve JPG in Mysql using PHP I am trying to store jpg images into MySQL database , The insertion works but I am unable to display the results.
here is MySQL table definition:
drop table if exists product_image;
create table product_image(
id_img int not null primary key auto_increment,
name varchar(512),
img LONGBLOB NOT NULL,
id_product int not null
);

PHP script to store User input file:
<!DOCTYPE html>

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="image" >
    <input type="submit" value="Upload" name="submit">
</form>

<?php

$servername = "localhost";
$username   = "root";
$password   = "123456";
$dbname     = "store";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if (isset($_POST['submit'])) {

    $imageName = mysql_real_escape_string($_FILES["image"]["name"]);
    $imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
    $imageType = mysql_real_escape_string($_FILES["image"]["type"]);

    if (substr($imageType, 0, 5) == "image") {

        $sql = "insert into product_image (name,img,id_product) values ('$imageName','$imageData','65') ";

        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "
" . $conn->error;
        }

        echo $imageName, $imageType;
    }

    else {

        echo "select image type:";
    }

}

$conn->close();

?>

PHP script to display image:
<?php
header("content-type:image/jpg");
$servername = "localhost";
$username   = "root";
$password   = "123456";
$dbname     = "store";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$q      = "select * from product_image";
$result = $conn->query($q);

if ($result->num_rows > 0) {
    // output data of each row
    while ($row = $result->fetch_assoc()) {

        $img = $row["img"];
        #echo "id: " . $row["img"]. "
";
        #echo '';
    }
}

else {
    echo "0 results";
}

echo $img;

$conn->close();

?>

I just see small icon when I call the PHP script to view the image. Is there any thing that i am missing.
thanks.

A: use something like this
<img src="data:image/jpeg;base64,<?php echo base64_encode($row['img']); ?>" class="latest_images img-responsive img-thumbnail" alt="Cinque Terre" >


text:
Q: Running docker-compose in another Dockerized Container I'm setting up my development environment and this time around I am using a docker container to run everything... like tmux, vim, etc.
When I run the image that runs my editor I use -v /var/run/docker.sock:/var/run/docker.sock and that way when I use the docker command in the shell of the editor container it links to docker on the host computer and I can run additional docker containers without an issue. This way I can code in my editor container and spin up other containers as dev envs.
However, if I try to run the same Dockerfile from the editor container that worked using docker build and docker run using a docker-compose.yml and docker-compose up I get the following output:
OUTPUT
Recreating frontend_tests_1 ... done
Recreating frontend_web_1   ... done
Attaching to frontend_tests_1, frontend_web_1
tests_1  | npm ERR! path /app/package.json
tests_1  | npm ERR! code ENOENT
tests_1  | npm ERR! errno -2
tests_1  | npm ERR! syscall open
web_1    | npm ERR! path /app/package.json
web_1    | npm ERR! code ENOENT
web_1    | npm ERR! errno -2
web_1    | npm ERR! syscall open
tests_1  | npm ERR! enoent ENOENT: no such file or directory, open '/app/package.json'
tests_1  | npm ERR! enoent This is related to npm not being able to find a file.
tests_1  | npm ERR! enoent
web_1    | npm ERR! enoent ENOENT: no such file or directory, open '/app/package.json'
web_1    | npm ERR! enoent This is related to npm not being able to find a file.
web_1    | npm ERR! enoent
tests_1  |
tests_1  | npm ERR! A complete log of this run can be found in:
tests_1  | npm ERR!     /root/.npm/_logs/2019-03-24T22_08_49_446Z-debug.log
web_1    |
web_1    | npm ERR! A complete log of this run can be found in:
web_1    | npm ERR!     /root/.npm/_logs/2019-03-24T22_08_49_447Z-debug.log
frontend_web_1 exited with code 254
frontend_tests_1 exited with code 254

If I preform the same steps on the host machine using the same directory, I get the following normal output:
EXPECTED
Recreating frontend_web_1   ... done
Recreating frontend_tests_1 ... done
Attaching to frontend_web_1, frontend_tests_1
web_1    |
web_1    | > frontend@0.1.0 start /app
web_1    | > react-scripts start
web_1    |
tests_1  |
tests_1  | > frontend@0.1.0 test /app
tests_1  | > react-scripts test --env=jsdom
tests_1  |
web_1    | Starting the development server...
web_1    |
tests_1  |  PASS  src/App.test.js
tests_1  |   ✓ renders without crashing (22ms)
tests_1  |
tests_1  | Test Suites: 1 passed, 1 total
tests_1  | Tests:       1 passed, 1 total
tests_1  | Snapshots:   0 total
tests_1  | Time:        1.352s
tests_1  | Ran all test suites related to changed files.
tests_1  |
tests_1  | Watch Usage
tests_1  |  › Press p to filter by a filename regex pattern.
tests_1  |  › Press t to filter by a test name regex pattern.
tests_1  |  › Press q to quit watch mode.
tests_1  |  › Press Enter to trigger a test run.
web_1    | Compiled successfully!
web_1    |
web_1    | You can now view frontend in the browser.
web_1    |
web_1    |   Local:            http://localhost:3000/
web_1    |   On Your Network:  http://0.0.0.0:3000/
web_1    |
web_1    | Note that the development build is not optimized.
web_1    | To create a production build, use yarn build.
web_1    |
^CGracefully stopping... (press Ctrl+C again to force)
Stopping frontend_tests_1   ... done
Stopping frontend_web_1     ... done

Dockerfile.dev
FROM node:alpine

WORKDIR '/app'

COPY package.json .

RUN npm install

COPY ./ ./

CMD ["npm", "run", "start"]

docker-compose.yml
version: '3'
services:
  web:
    build:
      context: .
      dockerfile: Dockerfile.dev
    ports:
      - "8080:8080"
    volumes:
      - /app/node_modules
      - .:/app
  tests:
    build:
      context: .
      dockerfile: Dockerfile.dev
    volumes:
      - /app/node_modules
      - .:/app
    command: ["npm", "run", "test"]

A: Docker Compose volumes: directives always reference paths on the host.  (Same for docker run -v.)  If you're launching Docker in some form from a container, there's no way to inject one container's local filesystem into another.
For the application you're describing, I'd suggest two paths:

*

*If your goal is to run the application in development mode, with debuggers and live reloading, put away Docker entirely and just use npm/yarn locally.  (I bet you have vim and tmux installed on your host anyways for basic administration of that's the tooling you use, and installing Node is strictly easier than installing Docker.)

*If your goal is to run the application in Docker for production or pre-production testing, remove the volumes: directives from the Dockerfile.  After having built and tested your application from step 1, docker build an image and run the image itself, without attempting to replace its code.
Also remember that anyone or anything that can run Docker commands has unrestricted root access over the host.  I don't see an obvious benefit to running Docker Compose in a container the way you're describing.

A: I figured out what was up. When I start up the editor container, I mount a volume where all my projects are stored (i.e -v path/to/host/projects:/path/to/container/projects).
When docker-compose complies the .yml file (specifically when it turns abbreviated paths like . into full paths) it does so on the editor container but then when it sends the commands to docker, it is sending it to docker on the host due to -v /var/run/docker.sock:/var/run/docker.sock. So docker tries to mount the volume using the container's working path on the host, which docker obviously can not find. My current (crappy) work around is to mount the volume to the same path name (i.e. -v /path/to/projects:/path/to/projects). It is not clean but it works :)
Open to any ideas for a better solution!

A: I was getting this when using docker-compose as well. I solved it by changing .:/app to .:/src/app under volumes inside docker-compose.yml


text:
Q: Apache Camel Thread JDBC I have a query JDBC that has 168570, I use a split with multithreading, when I launch the app I have a different number result, anyone can tell me where I am wrong?
<from uri="start" />
<to uri="jdbc:dsDB" />
<split>
<simple>$body</simple>
<to uri="bean:testProcessor" />
</split>

I tried to split parallelProcessing="true" and instantiate a threadPool:
<threadPoolProfile id="outTestThreadPoolProfile" defaultProfile="true"
    poolSize="1500"
    maxPoolSize="1500"
    maxQueueSize="1500"
    rejectedPolicy="CallerRuns"/>

is how a thread finish the job before the split is complete


text:
Q: Javascript to PHP else if ": ?" operator conversion I have never encountered this in javascript thus far although I am aware : ? means else if. I am having trouble figuring out how to lay it out in PHP. Here is what I did - where am I going wrong if it is wrong?
JSCRIPT
var midparams = dparams2.isramped() ? dparams2 : DailyParams.avg(dparams1, dparams2);

PHP
$midparams = $dparams2->isramped() if $dparams2 = $midparams else $DailyParams->avg($dparams1, $dparams2);

A: You can do this:
$midparams = $dparams2->isramped() ? $dparams2 : $DailyParams->avg($dparams1, $dparams2);

Or this:
if($dparams2->isramped()) {
  $midparams = $dparams2;
} else {
  $midparams = $DailyParams->avg($dparams1, $dparams2);
}

You can read more about the ternary operator in:

PHP Manual

A: You've got 2 options. 1st one is almost the same as JavaScript
$midparams = ($dparams2 -> isramped()) ? $dparams2 : $DailyParams->avg($dparams1, $dparams2);

The second one is more trivial:
if ($dparams2 -> isramped()) {
    $midparams = $dparams2;
} else {
    $midparams = $DailyParams->avg($dparams1, $dparams2);
}

First one says: midparams will be dparams if statement before is true, or $DailyParams->avg($dparams1, $dparams2) if it is not. Second is the same thing but in a more straight forward fashion.

A: This is called the ternary operator. It sets a variable based on a condition. In PHP, what it's saying (in pseudocode here) is:
setSomeVariable = (test condition) ? value if true : value if false;

So, if for example, you wanted to set the value of $a to 10 if the $score is greater than 100, or set $a to 0 if $score is less than or equal to 100, the code would look like this:
$a = ($score > 100) ? 10 : 0;

See the documentation here: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary

A: It's called a ternary operator; it's used the same way in PHP as it is in JavaScript -
/* most basic usage */
$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true

Straight from David Walsh's blog - http://davidwalsh.name/php-shorthand-if-else-ternary-operators
Also note: I think you're thinking about it a bit backwards -
It is not (repeat, not) used like this:
$var = (assign this value) ? (if this is true) : (otherwise, assign this value)
It is used like this:
$var = (is this true) ? (then assign this value) : (otherwise, assign this value)

EDIT Per @Pointy pointy-ing this out, there is a slight difference between how the statements are evaluated in JavaScript in PHP - See example #4 in the documentation. Although only a crazy person would write a long-winded unparenthesized ternary expression. http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary


text:
Q: How can I keep the new files and delete the files older than 7200 seconds only? How can I keep the new files (Less than 7200 seconds) and delete the older files only?
My php code:
<?php
date_default_timezone_set("Europe/Amsterdam"); // bepaal de tijd zone!
// Bepaal het root path
$site_root_path = $_SERVER['DOCUMENT_ROOT'] . '/';

// Leegt de cache map en verwijderd de bestanden op basis van de leeftijd
function verwijder_cache(){
    global $site_root_path;
    $site_cache = ($site_root_path . 'cache');

    // tijd in seconden dat de bestanden toegestaan zijn in de cache directory te verblijven
    $seconds_oud = 7200; // 604800 is 7 dagen, 7200 is 2 uur!

    // directory check-in first
    if (is_dir($site_cache)){
        $verwerk = opendir($site_cache);
        while (false !== ($tmp_site_cache_files = readdir($verwerk))){
            // We gaan nu alles verwijderen behalve index.php, .htaccess en alle sub mappen in de cache directory
            if ($tmp_site_cache_files != "." && $tmp_site_cache_files != ".." && $tmp_site_cache_files != "index.php" && $tmp_site_cache_files != ".htaccess"){
                $verschil = (time() - filectime($site_cache / $tmp_site_cache_files));
                if ($verschil >= $seconds_oud){ // Testje...
                    unlink($site_cache. '/' . $tmp_site_cache_files);
                    }
                    }
                    }
                    closedir($verwerk);
                    echo 'Alle bestanden, ouder dan ' . $seconds_oud . ' seconden zijn verwijderd van de server website cache!' . "\r\n";
                    }
                    // Dit zou nooit mogen gebeuren...
                    else
                        {
                        trigger_error('CACHE DIRECTORY ERROR');
                        }
                        }
                        verwijder_cache();
                        ?>

I'd like to delete files from a folder with php7.
I use the code displayed above and I'd like to keep files younger than 7200 seconds only, files over 7200 seconds should be deleted from the folder.
I also want to keep index.php, .htaccess and all directories/folders in the cache folder
The code does delete the files corectly and doesn't delete the files I'd like to keep but it does delete the files less than 7200 seconds as well.
How can I keep the new files (Less than 7200 seconds) and delete the older files only?


text:
Q: What are the naming conventions that you use while coding? What are the naming conventions that you use while coding?

A: I hope we will not discuss prefixes for field names and brace styles here :)
Here is my bible for .NET:

Also MSDN gives solid guidelines.
Another useful source is MS Internal Coding Guidelines

A: Here's a list of general naming conventions from MSDN.
I tend to just go-with-the-flow, however.  Whatever standards are currently in place, it's usually easiest to just go with them and maybe slowly shift it over time. It's not really practical to just come into a project with your own idea of "standards" and try to implement them.
It doesn't REALLY matter what standards are used, imo -- just that there are some and people know what they are.

A: I use a combination of Hungarian, camel case, and other rules I come up with in the beginning of a project. Like right now:

*

*Methods are upper case (DoThis)

*variables are camel case (thisThing)

*page level variables are prefaced with _ (_thisWorksEverywhere)

*regions are all lower case (#region foreign properties)

*Properties and Objects are uppercase (Object.Property)

*Foreign properties are prefaced by _ (Object._ForeignGroups)

*Controls are Hungarian to an extent, like (txtTextBox) and (rptRepeater). I'm not too strict as to what's customary because "Watermark" can be wm or wk or whatever, as long as they all match each other accross my application.

...etc. Some things are standard, others are up to interpretation, but the most important thing is consistency across your application.

A: Hungarian notation can be used. I don't bother myself, but I give various things (variables, controls, etc.) sensible names.
For example, I use a Hungarian-style prefix for control names such as txt for TextBoxes, btn for Buttons, pic for PictureBoxes, lbl for Labels, etc. That helps to easily identify what a control is.
For function names I try and use sensible explanatory names, but nothing with any particular rules. For variable names again I just use explanatory names but nothing special.

A: To add on to the answer from @Aku authors of the Framework Design Guidelines have published on online digest version of their guidelines, with an emphasis on naming convetions.
Framework Design Guidelines Digest v2
Download here
Consistency is key.  Depending on the size of your development team, using a consistent and documented convetion will make it easier to pick up someone elses code and for others to pick up your own code.

A: Folks, please don't post answers like "I like __field" or "I like m__field". It's a very personal and subjective question without a single answers.
If you have any guidlines it's already a big win. Worse thing in dev team is a lack of common conventions.
It would be nice if would try to describe some benefits of given guideline.
For example:

prefixing fields with underscore can
  improve auto-completion with
  intellisense

A: Pick one at be consistent. Changing name styles leads to confusion.


text:
Q: Modify the "lastlog" part in the modern motd After the small scripts on /etc/update-motd.d/ are run and, before login runs my shell (if I understood the docs properly) lastlog is somehow run and shown like this:
Last login: Wed Oct 18 12:08:39 2017 from xx.xx.xx.xx

I'd like to intercept that output to improve it. I was thinking storing the last three IP's to successfully log in or something and make a quick check to see if there's something new I should know.
I'd also like to throw in the number of failed/success accesses, for the same purpose.
It occurs to me I could code it and put it like a 98-ssh-seccheck thing, but that lastlog line would still show up, pointlessly.
TL;DR: How is that lastlog inserted and how can I intercept/modify it?


text:
Q: Display html element with if statement I have a cart shopping in the form of a table containing a number of products.
Based on the Id of the product, I want to display a link or an other.
I worked with thymeleaf, and it was like this

How can I use an if without thymeleaf, only with css?


text:
Q: Exclude Specific Categories? the code I'm currently using to display categories is <?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' ';}?>
I would like to exclude a category called "home-featured" or the category with ID "65" how would I add this to the code above?

A: You could do it like this:
<?php
$exclude = array( 'home-featured' );
foreach( get_the_category() as $category ) {
    if ( ! in_array( $category->cat_name, $exclude )
        echo $category->cat_name . ' ';
}
?>


text:
Q: How does the isAbsolute method run[Java]? The isAbsolute method does not have a body in the path interface, but I can run it in the following code. How is this possible?
Path path= Paths.get("D:\\Example\\1.txt");
    System.out.println(path.isAbsolute());//prints true

A: Imagine following code:
public interface Foo {
  public boolean bar();
}

public class Fooz implements Foo {
  @Override
  public boolean bar() {
    return false;
  }
}

And:
public Foo getFoo() {
  return new Fooz();
}

public static void main(String[] args) {
  Foo myFoo = getFoo();
  System.out.println(myFoo.bar()) //false
}

If you are looking for actual implementation of this function, I advise looking thru the source code of JVM of your choosing. Example of one such implementation can be found in UnixPath.java on OpenJDK github repo.


text:
Q: Buttons work, ImageButtons do NOT I have searched for a lot of references on ImageButton for Android. And did exactly the same, but it did not seem to work. The strange part, it worked when I used 'Button' only.
Have I missed out some important part?
Can anyone help me with my problem please?
I have listed down my code below.
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Button connectBtn = (Button)this.findViewById(R.id.connectBtn); //<<<=== THIS WORKS
    ImageButton connectBtn = (ImageButton) this.findViewById(R.id.connectBtn); // <<<=== THIS NOT
    ImageButton getPy = (ImageButton) findViewById(R.id.getFilePy); // <<<=== THIS NOT
    ImageButton runPy = (ImageButton) findViewById(R.id.runPy); // <<<=== THIS NOT

    connectBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mySetConfig();
        }
    });

    getPy.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showFileChooser();
        }
    });
    runPy.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pythonButton();
        }
    });
}

XML:

<ImageButton
    android:id="@+id/connectBtn"
    android:layout_width="match_parent"
    android:layout_height="90dp"
    android:background="@drawable/button_1" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="5dp" />

<ImageButton
    android:id="@+id/getPy"
    android:layout_width="match_parent"
    android:layout_height="90dp"
    android:background="@drawable/button_2" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<ImageButton
    android:id="@+id/runPy"
    android:layout_width="match_parent"
    android:layout_height="90dp"
    android:background="@drawable/button_3" />

 <FrameLayout
    android:id="@+id/FrameLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
</FrameLayout>

<EditText
    android:id="@+id/app_status"
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:ems="10"
    android:singleLine="false" >

    <requestFocus />
</EditText>

</LinearLayout>

Thank you in advance for your kind heart.

A: The correct way to put the click Listener to an ImageButton:
    ImageButton connectBtn = (ImageButton) findViewById(R.id.connectBtn);

    connectBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
                      mySetConfig();

        }

    });

Here's a nice tut for you.
And please remove the "this" word from herE:
ImageButton connectBtn = (ImageButton)this.findViewById(R.id.connectBtn);  <<<=== THIS NOT


text:
Q: Python file read line startswith to endswith and move to list i have file like below:
=======
line1 contents
line2 contents
line3 contents
=======
=======
line4 contents
line5 contents
=======
=======
line6 contents
line7 contents
=======

Read file contents that startswith ======= to endswith =======. Send output to list.
Below is expected output for list of list
 [["line1 contents", "line2 contents", "line3 contents"],
  ["line4 contents", "line5 contents"],
  ["line6 contents", "line7 contents"]]

A: Assuming your input text is stored in variable s, you can use the following list comprehension:
[l.splitlines() for l in s.split('=======\n')[1::2]]

With your sample input, this returns:
[['line1 contents', 'line2 contents', 'line3 contents'], ['line4 contents', 'line5 contents'], ['line6 contents', 'line7 contents']]


text:
Q: Querying the cost of launching a instance from the AWS Pricing API I am using the AWS Pricing API:
http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/price-changes.html
The issue is that it has data like
"KV46EU5KJGKB53ZX" : {
  "sku" : "KV46EU5KJGKB53ZX",
  "productFamily" : "Compute Instance",
  "attributes" : {
    "servicecode" : "AmazonEC2",
    "location" : "US East (N. Virginia)",
    "locationType" : "AWS Region",

I don't know how to correlate locationType and location with the data I use to launch EC2 instances (e.g. in us-east-1).
Is there a way to know the cost of launching an EC2 instance?

A: I recommend jq to work with large json documents. For OnDemand pricing of sku KV46EU5KJGKB53ZX for example:
curl -s https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/index.json \
 | jq .terms.OnDemand.KV46EU5KJGKB53ZX

gives
{
  "KV46EU5KJGKB53ZX.JRTCKXETXF": {
    "offerTermCode": "JRTCKXETXF",
    "sku": "KV46EU5KJGKB53ZX",
    "effectiveDate": "2016-12-01T00:00:00Z",
    "priceDimensions": {
      "KV46EU5KJGKB53ZX.JRTCKXETXF.6YS6EN2CT7": {
        "rateCode": "KV46EU5KJGKB53ZX.JRTCKXETXF.6YS6EN2CT7",
        "description": "$0.156 per Dedicated RHEL m1.medium Instance Hour",
        "beginRange": "0",
        "endRange": "Inf",
        "unit": "Hrs",
        "pricePerUnit": {
          "USD": "0.1560000000"
        },
        "appliesTo": []
      }
    },
    "termAttributes": {}
  }
}

A: I am not aware of the presence of this cross-reference/mapping data within the structures provided by the price list API, and it is unfortunately not provided by DescribeRegions in the EC2 API, either.
It is, however, readily available on the Regions and Endpoints page under general documentation.  From that info, you can build a simple dictionary or lookup table.

A: Just built it myself. I know it will not be updated but...
NB: China is missing from this list I extracted from AWS pricing user interface
{
    "AWS GovCloud (US-East)": "us-gov-east-1",
    "AWS GovCloud (US-West)": "us-gov-west-1",
    "Africa (Cape Town)": "af-south-1",
    "Asia Pacific (Hong Kong)": "ap-east-1",
    "Asia Pacific (Mumbai)": "ap-south-1",
    "Asia Pacific (Osaka-Local)": "ap-northeast-3",
    "Asia Pacific (Seoul)": "ap-northeast-2",
    "Asia Pacific (Singapore)": "ap-southeast-1",
    "Asia Pacific (Sydney)": "ap-southeast-2",
    "Asia Pacific (Tokyo)": "ap-northeast-1",
    "Canada (Central)": "ca-central-1",
    "EU (Frankfurt)": "eu-central-1",
    "EU (Ireland)": "eu-west-1",
    "EU (London)": "eu-west-2",
    "EU (Milan)": "eu-south-1",
    "EU (Paris)": "eu-west-3",
    "EU (Stockholm)": "eu-north-1",
    "Middle East (Bahrain)": "me-south-1",
    "South America (Sao Paulo)": "sa-east-1",
    "US East (Boston)": "us-east-1-bos-1",
    "US East (Houston)": "us-east-1-iah-1",
    "US East (Miami)": "us-east-1-mia-1",
    "US East (N. Virginia)": "us-east-1",
    "US East (Ohio)": "us-east-2",
    "US East (Verizon) - Atlanta": "us-east-1-wl1-atl1",
    "US East (Verizon) - Boston": "us-east-1-wl1",
    "US East (Verizon) - Dallas": "us-east-1-wl1-dfw1",
    "US East (Verizon) - Miami": "us-east-1-wl1-mia1",
    "US East (Verizon) - New York": "us-east-1-wl1-nyc1",
    "US East (Verizon) - Washington DC": "us-east-1-wl1-was1",
    "US West (Los Angeles)": "us-west-2-lax-1",
    "US West (N. California)": "us-west-1",
    "US West (Oregon)": "us-west-2",
    "US West (Verizon) - Las Vegas": "us-west-2-wl1-las1",
    "US West (Verizon) - San Francisco Bay Area": "us-west-2-wl1",
}


text:
Q: var replacement = $("
*").text($(this).text()).get(0); Means? This is a jQuery example. But i didn't get the part below:
var replacement = $("
").text($(this).text()).get(0);

The original code:
var mappedItems = $("li").map(function (index) {
  var replacement = $("
").text($(this).text()).get(0);
  if (index == 0) {
    // make the first item all caps
    $(replacement).text($(replacement).text().toUpperCase());
  } else if (index == 1 || index == 3) {
    // delete the second and fourth items
    replacement = null;
  } else if (index == 2) {
    // make two of the third item and add some text
    replacement = [replacement,$("
").get(0)];
    $(replacement[0]).append(" - A");
    $(replacement[1]).append("Extra  - B");
  }
  // replacement will be an dom element, null,
  // or an array of dom elements
  return replacement;
});
$("#results").append(mappedItems);

Any comments?

A: The jQuery methods usually return the jQuery object, so that they can be chained. So, the expression does the same as:
var x = $("
");
x.text($(this).text());
var replacement = x.get(0);

It creates a new li element that is wrapped in a jQuery object, sets the text of the element, and then gets the element itself from the jQuery object.

A: Also worth to mention, .get() returns a DOM element. Since jQuery objects are stored in arrays ("array like objects"), you could also access the underlying DOM element by calling
var replacement = $('
')[0];


text:
Q: Re-ordering a Silverlight Listbox - MVVM-stylee I am using RIA services to serve entities to a MVVM-Light enabled Silverlight application.
I have a ViewModel which present a CollectionViewSource of entities to a listbox on the View.  The reason I use a CollectionViewSource is so I can control the selected item in the ViewModel; when a new item is created I can create it and then select it for further editing (selecting an item in the listbox enables the editing of that item in a data form).
I need to enable dragdropping for the listbox to allow reordering of the items.  I have looked at using the Silverlight Toolkit's ListBoxDragDropTarget to enable this functionality but it doesn't work - I assume this is because I need to set the listbox ItemsSource to an ObservableCollection.
If I change the CollectionViewSource in the ViewModel to an ObservableCollection how can I programmatically change the Selected Item of the listbox from the ViewModel?
Any ideas?

A: You can have a separate property in your ViewModel namely SelectedThing and bind ListBox.SelectedItem to it
<ListBox ItemsSource="{Binding TheCollection}" SelectedItem="{Binding SelectedThing}" />

A: You can wrap your ObservableCollection<T> within the CollectionViewSource...as seen here...so that it is the backing collection of data used by the CollectionViewSource gaining the INotifyCollectionChanged behavior without losing the benefits from the CollectionViewSource; which you need for selecting an item.
    <UserControl.Resources>
       <local:DataSource x:Key="dataSource" />
          <CollectionViewSource x:Name="cvs"
                    Source="{Binding Names, Source={StaticResource dataSource}}">
          </CollectionViewSource>
    </UserControl.Resources>

    ...

    <ListBox ItemsSource="{Binding Source={StaticResource cvs}}"
               Margin="5,5,5,1" Grid.ColumnSpan="4" />

An end to end example from Tim Heuer can be found here which should also help you out in achieving the complete solution.


text:
Q: Find the value of $MF^2$ with the given information Acute triangle $ABC$ has orthocenter H. The foot of the altitude from $C$ to $AB$ is point $F$ and the foot of the altitude from $A$ to $BC$ is $D$. Let $M$ be the midpoint of $AC$ and let $N$ be that midpoint of $HC$. If $AH=10$ , $HD=6$, and $CN= \sqrt{58}$, compute $MF^2$.
So I know I can pythag to find $AC=\sqrt{452}$ and $HC=\sqrt{232}$.
I find that $FM$ is the perpendicular bisector of $AD$.
Now, I don't know how to continue.

A: $MF$ is the median of right triangle $CFA$ and is thus half the hypotenuse $AC$.


text:
Q: Find the Wronskian? Let $W$ be the Wronskian of the two linearly independent solution of the ODE
$$2y''+y'+t^2y=0; ~ t\in \mathbb{R}$$
Then, for all $t$, there exists a constant $C\in \mathbb{R}$ such that $W(t)$ is

*

*$Ce^{-t}$

*$Ce^{-t/2}$

*$Ce^{2t}$

*$Ce^{-2t}$

What I have done is try to solve the problem by using auxiliary equation and the find the solution. But I stuck in solving due to the presence of $t$, means the value of the auxiliary equation doesn't look good. Which option is correct? Help me out.

A: Hint:
$$W'=(u'v-uv')'=u''v-uv''=\frac{-u'-t^2u}2v-u\frac{-v'-t^2v}2$$


text:
Q: LaTeX @ (at) symbol
Possible Duplicate:
Why do LaTeX internal commands have an @ in them?

What does the @ symbol mean in LaTeX? I'm looking at the source of apa.cls, and there's a declaration:
\newsavebox\gr@box

and later on
\sbox\gr@box{\includegraphics[width=\linewidth]{#2}}.

It seems like @ isn't acting as a normal character, but I can't figure out exactly what it's doing, and couldn't find anything after bit of googling (how I would love a Google regex feature!) Thanks.
EDIT: Thanks for the help; of the links I looked through I found http://www.tug.org/pipermail/tugindia/2002-January/000178.html to be very helpful and concise. To summarize, the @ character is not normally allowed in the names of macros, so as a hack for scoping, LaTeX packages declare it internally to be a valid name character and use it for their macros. You can use \makeatletter in a document to access these macros, but you obviously must be very careful since you have can now overwrite essential LaTeX kernel macros; use \makeatother to revert.

A: Answered here.
The LaTeX commands are built using commands with the @ sign. In order to prevent these commands from being modified, @ is usually redefined to be a special symbol. Occasionally, if you know what you're doing, you can "make at letter" (\makeatletter) to do some fine tuning, and then you would "make at other" (\makeatother) again when you're finished.

A: Every char has the category code from 0 up to 15.

*

*0 - Escape character; this signals the start of a control sequence. backslash \ (Unicode code point U+005C) is a default escape character.

*1 - Beginning of group; such a character causes TeX to enter a new level of grouping. The open brace { is a beginning-of-group character.

*2 - End of group; TeX closes the current level of grouping. TeX has the closing
brace } as end-of-group character.

*3 - Math shift; TeX uses the dollar sign $ for this.

*4 - Alignment tab; TeX uses the ampersand &.

*5 - End of line; a character that TeX considers to signal the end of an input line.

*6 - Parameter character; this indicates parameters for macros. In TeX this is the hash sign #.

*7 - Superscript; default superscript is the circumflex ^.

*8 - Subscript; default superscript is underscore _.

*9 - Ignored; characters of this category are removed from the input.

*10 - Space; space characters receive special treatment. TeX assigns this category to the space (Unicode code point U+0020) and tab characters (U+0009).

*11 - Letter; in TeX only the characters a..z, A..Z are in this category. Often, macro
packages make some 'secret' character (for instance @) into a letter, see below.

*12 - Other; TeX puts everything that is not in the other categories into this category.
It includes, for instance, digits, punctuation and @.

*13 - Active; active characters function as a TeX command, without being preceded by
an escape character. The tie character ~ has such category.

*14 - Comment character; the default comment character is %.

*15 - Invalid character; this category is for characters that should not appear in the input. TeX causes an error in the case of such chars.

A macro name consists only of letters (code 11). The @ symbol has category code 12 and can therefore not be included in the macro name. However, you can change the category of any symbol
\catcode`\@ = 11 % Macro \makeatletter does the same

Now you can use @ as letter in your macro names. All LaTeX packages change catcode of the @ to 11 and return it to 12 at the end.
\catcode`\@ = 12 % Macro \makeatother does the same

Note you can change catcode any character, not only @. For example, if you want to use [, ] as open and close group symbols write
\catcode`\[ = 1
\catcode`\] = 2

A: @ character in a macro name simply marks the macro as internal to the package, see
https://texfaq.org/FAQ-atsigns


text:
Q: download dynamic file through javascript from web api 2 Angularjs Thanks for taking your time to read this question.
What do I need:
We have a SOAP web service hosted somewhere that will take a couple of parameters and generate reports by using SQL Server Reporting Services. The format of the report file could be a couple including excel and pdf. We don't own that service and we cannot change it.
We need a web app that calls the SOAP web service I mentioned above, generate a report, and stream the file back to the browser.
It has to be a web api 2/ angularjs app.
What do I have:
So far I got client calling web api no problem, and i can see the result all the way back from the SOAP web service, but I cannot download the file, or even I got the file downloaded, it's either saying the file is corrupted or the file is blank.
My Code:
-server side:
        var reportResponse = new RequestResponse();
            try
            {
                reportResponse = client.RenderReport(reportHeader);

                if (!reportResponse.Successful)
                {
                    return new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        Content = new StringContent(reportResponse.ErrorMessage)
                    };
                }

                var stream = new MemoryStream(reportResponse.Result);
                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StreamContent(stream);
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = outputName + fileExtension;
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

                return response;

            }
            catch (Exception exception)
            {
                return new HttpResponseMessage(HttpStatusCode.BadRequest)
                    {
                        Content = new StringContent(exception.Message)
                    };
            }

-client side:
function getReport(request) {
        return $http.get('/api/reports/', {
            params: request
        }, { responseType: 'arraybuffer' })
            .then(
                function (result) {
                    var octetStreamMime = 'application/octet-stream';

                var success = false;

                // Get the headers
                var headers = result.headers;

                // Get the filename from the x-filename header or default to "download.bin"
                var filename = headers['x-filename'] || 'download.bin';

                // Determine the content type from the header or default to "application/octet-stream"
                var contentType = headers['content-type'] || octetStreamMime;

                try {
                    // Try using msSaveBlob if supported
                    console.log("Trying saveBlob method ...");
                    var blob = new Blob([result.data], { type: contentType });
                    if (navigator.msSaveBlob)
                        navigator.msSaveBlob(blob, filename);
                    else {
                        // Try using other saveBlob implementations, if available
                        var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
                        if (saveBlob === undefined) throw "Not supported";
                        saveBlob(blob, filename);
                    }
                    console.log("saveBlob succeeded");
                    success = true;
                } catch (ex) {
                    console.log("saveBlob method failed with the following exception:");
                    console.log(ex);
                }

                if (!success) {
                    // Get the blob url creator
                    var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
                    if (urlCreator) {
                        // Try to use a download link
                        var link = document.createElement('a');
                        if ('download' in link) {
                            // Try to simulate a click
                            try {
                                // Prepare a blob URL
                                console.log("Trying download link method with simulated click ...");
                                var blob = new Blob([result.data], { type: contentType });
                                var url = urlCreator.createObjectURL(blob);
                                link.setAttribute('href', url);

                                // Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
                                link.setAttribute("download", filename);

                                // Simulate clicking the download link
                                var event = document.createEvent('MouseEvents');
                                event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                                link.dispatchEvent(event);
                                console.log("Download link method with simulated click succeeded");
                                success = true;

                            } catch (ex) {
                                console.log("Download link method with simulated click failed with the following exception:");
                                console.log(ex);
                            }
                        }

                        if (!success) {
                            // Fallback to window.location method
                            try {
                                // Prepare a blob URL
                                // Use application/octet-stream when using window.location to force download
                                console.log("Trying download link method with window.location ...");
                                var blob = new Blob([result.data], { type: octetStreamMime });
                                var url = urlCreator.createObjectURL(blob);
                                window.location = url;
                                console.log("Download link method with window.location succeeded");
                                success = true;
                            } catch (ex) {
                                console.log("Download link method with window.location failed with the following exception:");
                                console.log(ex);
                            }
                        }

                    }
                }

                if (!success) {
                    // Fallback to window.open method
                    console.log("No methods worked for saving the arraybuffer, using last resort window.open");
                    window.open(httpPath, '_blank', '');
                }
                },
                function (error) {
                    logger.error('Error getting report', error);
                })
            .catch(function (error) {
                logger.error('Error getting report', error);
            });
    }

For the client side code, I referenced this post. I tried to get a report in pdf, and I did get the file saved on the client side named download.bin. I can take a look at the header and figure it out, but I don't think that's the problem. In this case, download.bin can be opened with Adobe Reader, and it even knows it's a two page pdf file, but it shows blank.
I tried to save the file from my api controller, it has no problem at all, which means the web service I called has no problem.
I use chrome to check the get response, in my result.data, it is something like this(I delete some of the chars between "stream" and "endstream"):
    [/PDF /Text /ImageB /ImageC /ImageI]
endobj
6 0 obj
<< /Length 3655 /Filter /FlateDecode >> stream
xË·÷ô
D;iÞ/ÚÙpdØâdg1I$=9ÐÛ§Èî.Vߦx`ñÿë;d7Éfw|òÇ`¼CBÛ48+ágJ
·§áÃÛHuèoRÁ%'btVQxí  .þúfª¦Zv¬eæZEà«ÃOÌ äðâ×AÿuZO¥HJ^jÒÃWç?\}xsz{7ützyºþóôjøúêîôÙðâ?ÿ{ñàë·³®ªõy7Æ
wàýË77ïI
endstream
endobj
8 0 obj
<< /Type /Page /Parent 7 0 R /MediaBox [0 0 612.0 792.0] /Contents 9 0 R /Resources << /ProcSet 1 0 R /XObject << /Im5 5 0 R >> /Font << /F3 3 0 R /F4 4 0 R >> >> >>
endobj
3 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>
endobj
4 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>
endobj
7 0 obj
<< /Type /Pages /Kids [ 2 0 R 8 0 R ] /Count 2 >>
endobj
10 0 obj
<< /Type /Catalog /Pages 7 0 R >>
endobj
11 0 obj
<< /Title <feff004700520050005f00410053004f005000610079006d0065006e0074>
/Author <>
/Subject <>
/Creator (Microsoft Reporting Services 10.0.0.0)
/Producer (Microsoft Reporting Services PDF Rendering Extension 10.0.0.0)
/CreationDate (D:20150922094257-04'00')
>>
endobj
xref
0 12
0000000000 65535 f
0000000010 00000 n
0000003799 00000 n
0000079131 00000 n
0000079236 00000 n
0000003983 00000 n
0000000065 00000 n
0000079336 00000 n
0000078947 00000 n
0000077371 00000 n
0000079404 00000 n
0000079457 00000 n
trailer << /Size 12 /Root 10 0 R /Info 11 0 R >>
startxref
79744
%%EOF

If I understand this correctly, it could very well be an encoding problem. I tried to use Uint8Array() for creating the blob, it did not work.
I also tried to use FileSaver.js, and got the same thing.
Could someone point me to the right direction? Thanks so much.


text:
Q: How to make a command with default if missing I want to make a command that has as inputs $X,t$ and outputs
E[X_t] if t is given and outputs
E[X]
if t is missing.

So far
If I don't have the condition on t then
\newcommand{\e}[1]{E[#1]}

works, but otherwise... I'm stumpted.

A: To allow that syntax you can use \@ifnextchar to check if there is a comma after the first argument. This is, however, a dubious syntax, and can cause unpredictable behavior. Either way you shouldn't use one-letter command names:
\documentclass{article}

% Option 1:
\makeatletter
\newcommand{\CmdE}[1]{%
  E[#1%
  \@ifnextchar,{\grab@sub}]}
\def\grab@sub,#1{%
  _{#1}]}
\makeatother

\begin{document}
\pagenumbering{gobble}

\begin{tabular}{ll}
\(\CmdE X\)      & \(\CmdE {XX}\)      \\
\(\CmdE X,t\)    & \(\CmdE {XX},t\)    \\
\(\CmdE X,{tt}\) & \(\CmdE {XX},{tt}\) \\
\end{tabular}

\end{document}

produces:

I propose a clearer (and more robust) syntax, using xparse:
\documentclass{article}

% Option 2:
\usepackage{xparse}
\NewDocumentCommand\CmdE{mo}
  {%
    E[#1\IfValueT{#2}{_{#2}}]%
  }

\begin{document}

\begin{tabular}{ll}
\(\CmdE {X}\)     & \(\CmdE {XX}\)     \\
\(\CmdE {X}[t]\)  & \(\CmdE {XX}[t]\)  \\
\(\CmdE {X}[tt]\) & \(\CmdE {XX}[tt]\) \\
\end{tabular}

\end{document}

the result is the same for both approaches.
Ooh, yes, there's plain LaTeX syntax too:
\documentclass{article}

% Option 3:
\newcommand{\CmdE}[2][]
  {%
    E[#2%
    \if\relax\detokenize{#1}\relax
    \else
      _{#1}%
    \fi]%
  }

\begin{document}

\begin{tabular}{ll}
\(\CmdE {X}\)     & \(\CmdE {XX}\)     \\
\(\CmdE [t]{X}\)  & \(\CmdE [t]{XX}\)  \\
\(\CmdE [tt]{X}\) & \(\CmdE [tt]{XX}\) \\
\end{tabular}

\end{document}

A: With the example below, \CmdE takes an undelimited argument and checks whether one of the tokens of that argument is a comma.
Use \CmdE only in mathmode as it does nothing about space tokens surrounding the comma and the other components of its argument.
\documentclass{article}

\makeatletter
\newcommand\CheckWhetherArgBlank[1]{%
  \if\relax\detokenize\expandafter{\@firstoftwo#1{}.}\relax
  \expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi
}%
\newcommand\gobbletocomma{}\long\def\gobbletocomma#1,{}%
\newcommand\removecomma{}\long\def\removecomma#1,{#1}%
\newcommand\gobbledot{}\def\gobbledot.{}%
\newcommand\firsttoSelDoM{}\long\def\firsttoSelDoM#1,#2\SelDoM{{#1},}%
\newcommand\keeptillcomma[1]{%
   \expandafter\CheckWhetherArgBlank\expandafter{\gobbletocomma#1}{%
     \expandafter\gobbledot\removecomma#1%
   }{%
    \expandafter\keeptillcomma\expandafter{\firsttoSelDoM#1}%
   }%
}%
\newcommand\CmdE[1]{%
  \expandafter\CheckWhetherArgBlank\expandafter{\gobbletocomma#1,}%
  {E[#1]}% no comma
  {\expandafter\CheckWhetherArgBlank\expandafter{\gobbletocomma#1}%
    {\removecomma E[#1]}% comma but only blankness behind it.
    {E[{\keeptillcomma{.#1\SelDoM}}_{\gobbletocomma#1}]}% comma and something other than blankness behind it
  }%
}%
% Blankness = Either only explicit space tokens or no tokens at all.
\makeatother

\begin{document}

\begin{verbatim}
\begin{tabular}{ll}
\(\CmdE{X}\)          & \(\CmdE{{XX}}\)          \\
\(\CmdE{X,t}\)        & \(\CmdE{{XX},t}\)        \\
\(\CmdE{X, t}\)       & \(\CmdE{{XX}, t}\)       \\
\(\CmdE{X,{tt}}\)     & \(\CmdE{{XX},{tt}}\)     \\
\(\CmdE{X, tt}\)      & \(\CmdE{XX, tt}\)        \\
\(\CmdE{[XX], [tt]}\) & \(\CmdE{[XX], [tt],u}\)  \\
\(\CmdE{X,}\)         & \(\CmdE{{[XX], [tt]},u}\)\\
\end{tabular}
\end{verbatim}

\begin{tabular}{ll}
\(\CmdE{X}\)          & \(\CmdE{{XX}}\)          \\
\(\CmdE{X,t}\)        & \(\CmdE{{XX},t}\)        \\
\(\CmdE{X, t}\)       & \(\CmdE{{XX}, t}\)       \\
\(\CmdE{X,{tt}}\)     & \(\CmdE{{XX},{tt}}\)     \\
\(\CmdE{X, tt}\)      & \(\CmdE{XX, tt}\)        \\
\(\CmdE{[XX], [tt]}\) & \(\CmdE{[XX], [tt],u}\)  \\
\(\CmdE{X,}\)         & \(\CmdE{{[XX], [tt]},u}\)\\
\end{tabular}

\end{document}

A: A different expl3 implementation:
\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\E}{m}
 {
  \clist_set:Nn \l_aimblb_e_clist { #1 }
  \clist_pop:NN \l_aimblb_e_clist \l_aimblb_e_main_tl
  E[ \l_aimblb_e_main_tl % print the main
     \clist_if_empty:NF \l_aimblb_e_clist
      {
       \sb{ \clist_use:Nn \l_aimblb_e_clist { , } }
      }
  ]
 }
\clist_new:N \l_aimblb_e_clist
\tl_new:N \l_aimblb_e_main_tl
\ExplSyntaxOff

\begin{document}

Simple: $\E{X}$

With subscript: $\E{X,t}$

More subscripts: $\E{X,t,u}$

\end{document}

This supports more subscripts; since it is for free, I added them. You may have different usages for them.

A classical implementation:
\documentclass{article}

\makeatletter
\newcommand{\E}[1]{\aimblb@E#1,,\@nil}
\def\aimblb@E#1,#2,#3\@nil{%
  E[#1\if\relax\detokenize{#2}\relax\else_{#2}\fi]
}

\begin{document}

$\E{X}$

$\E{X,t}$

$\E{X,abcdef}$

Comparing with Ulrich's:

\begin{verbatim}
\begin{tabular}{ll}
\(\E{X}\)          & \(\E{{XX}}\)          \\
\(\E{X,t}\)        & \(\E{{XX},t}\)        \\
\(\E{X, t}\)       & \(\E{{XX}, t}\)       \\
\(\E{X,{tt}}\)     & \(\E{{XX},{tt}}\)     \\
\(\E{X, tt}\)      & \(\E{XX, tt}\)        \\
\(\E{[XX], [tt]}\) & \(\E{[XX], [tt],u}\)  \\
\(\E{X,}\)         & \(\E{{[XX], [tt]},u}\)\\
\end{tabular}
\end{verbatim}

\begin{tabular}{ll}
\(\E{X}\)          & \(\E{{XX}}\)          \\
\(\E{X,t}\)        & \(\E{{XX},t}\)        \\
\(\E{X, t}\)       & \(\E{{XX}, t}\)       \\
\(\E{X,{tt}}\)     & \(\E{{XX},{tt}}\)     \\
\(\E{X, tt}\)      & \(\E{XX, tt}\)        \\
\(\E{[XX], [tt]}\) & \(\E{[XX], [tt],u}\)  \\
\(\E{X,}\)         & \(\E{{[XX], [tt]},u}\)\\
\end{tabular}

\end{document}


text:
Q: Add messages from server in apollo response (Nodejs) When u api restful i will send response like :
{
data,
code: 1,
msg: 'This is the messages'
}

With response like that i can show a success message if code = 1, or error messages if code = 2,many thing.
But when i try use graphql (apollo response)...i dont know how to do that...response from apollo response just only have data i defined in Schema like this...i cant add anything else
{
  "data": {
    "getBanners": [
      {
        "link": "example.com",
        "avatar": null
      },
      {
        "link": "example.com",
        "avatar": "example.com/0_banner_1597917871_3211.jpg"
      },
      {
        "link": "example.com/16709365405930105",
        "avatar": "example.com/0_banner_1597917938_5116.jpg"
      }
    ]
  }
}

I want response like when i use restful. How to do that. Please help me

A: You could define a return type in your GraphQL schema:
type GetBannersResponse {
  data: [Banners]
  code: Int!
  msg: String
}

And then define this as the result when executing the query:
type Query{
  getBanners: GetBannersResponse
}

Now you should be able to request all objects you want and in the resolver of the query you can create an object containing your data.


text:
Q: how to detect invalid route and show 404 error in hapi js? I want to show a 404 view page when user is trying to access the invalid route which is not defined. for example if i am trying to access /myData then it should redirect to /404.
server.js
server.route(routes);

routes.js
 module.exports =[
{
  path:'/',
  method:'GET',
  handler:function(request, reply) {
    reply.view('index').unstate('token');
  }
},
{
  path:'/login',
  method:'GET',
  handler:function(request, reply) {
    reply.view('login');
  }
},
{
  path:'/login',
  method:'POST',
  handler:handlers.loginHandler,
  config: {
      state: {
          parse: true, // parse and store in request.state
          failAction: 'error' // may also be 'ignore' or 'log'
      }
  }
},
{
  path:'/register',
  method:'GET',
  handler:function(request, reply) {
    reply.view('register');
  }
}];

A: You can decide based on the response of the server like this
server.ext({
    type: 'onPreResponse',
    method(request, reply) {
      if (request.response.output.statusCode == 404) {
        //serve your page here
      }
      reply.continue();
    },
 });


text:
Q: C : enQueue : How does create a new pointer to the tail? Alright, So I have a queue.h that says:
typedef struct {
    int key;
    int value;
} data_t;

typedef struct queueNode {
    struct queueNode *next, *prev;
    data_t *data;
} QueueNode;
h
typedef struct queueType {
    QueueNode *head;
    QueueNode *tail;
} Queue;

And my goal now is to figure out how to iterate over the queue to find a specific Node, and later a specific Value, within said queue.
The issue I see is that I don't have a way to say Queue{?} to take me to a specific queueNode, and I don't know of a way to say:
for queueNode in queue{scan return `queueNode` if valid}.

I've recently crossed the threshold of figuring out how to use a global variable size to know exactly how many queueNodes there are, but that still leaves me with the same issues.

A: With structures like this, a usual way to iterate over the list would be:
Using next
QueueNode *queue_find_forward(Queue *queue, int key)
{
    if(queue == NULL)
        return NULL;

    QueueNode *current = queue->head;

    while(current)
    {
        if(current->data->key == key)
            return current;

        current = current->next;
    }

    // no node has the requested key
    return NULL;
}

Using prev
QueueNode *queue_find_backwards(Queue *queue, int key)
{
    if(queue == NULL)
        return NULL;

    QueueNode *current = queue->tail;

    while(current)
    {
        if(current->data->key == key)
            return current;

        current = current->prev;
    }

    // no node has the requested key
    return NULL;
}

But be aware that the queue has to be properly initialized, the nodes have be to
properly initialized, the next pointer of the last element must point to
NULL, and the prev pointer of the first element must point to NULL as
well.
Both function do a check in the while loop:
        if(current->data->key == key)

I decided to use key for determining which element to look for. Of course you can
change that, you could check for the value or another property, or a
combination of both. This is up to you (or most likely the assignment you are
working on). The important thing is that you leave the loop once you've
found your element.
In struct queueNode, I'd change data_t *data; to data_t data;. I don't see
the benefit of having a pointer to data_t, you would need to allocate memory
for it, and would have to free it as well. It would increase the amount of code
you need to write for this. A pointer would only be useful if you are intending to have an array of
data_t objects per node, but otherwise not having it as pointer will make life
easier for you in the end.


text:
Q: PHP Datetime query how? Sorry my English a little,
My date column is 1375801584 valuable epoch format.
I wanna only select now and next time records, i want hide history times record.
eg: 19:45 and later.
<?php
$sql = mysql_query("select tarih from table where tarih < '$date' order by tarih ASC");
while($r = mysql_fetch_assoc($sql)){
?>

<?php echo date("Y-m-d", $r['tarih']); ?>
    <?php echo date("H:i", $r['tarih']); ?>

<?php
}
?>

A: You close. Your current query is selecting older records (<). Try using >=:
$sql = mysql_query("select date from table where date >= '$date;' order by date ASC");


text:
Q: Android: Display ImageView on the Activity after touching the Activity Is it possible to display ImageView, on the Activity after I touch the Activity Screen.
I am able to get the x, y coordinate after I touch the screen. But unable to display the ImageView at the said location. Because there is no method to show the ImageView like we display the Popup Window using method, showAtLocation().
How it could be possible? Please share your thoughts.

A: Just set the imageView margins to x,y from tap:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(x, y, 0, 0);
imageView.setLayoutParams(lp);

You can replace LinearLayout.LayoutParams with any MarginLayoutParams subclass

A: Set the margins of the ImageView to correspond to the x, y of the touch.


text:
Q: How to send a List> list to another activity I was trying to send  List> list to another activity. I tried many ways but couldn't. Please help!

A: You could use Intent
hashMap.put("key", "value");
Intent intent = new Intent(this, otherActivity.class);
intent.putExtra("mapkey", hashMap);
startActivity(intent);

EDIT:
For fatching the value in otherActivity
    Intent intent = getIntent();
    HashMap<String, String> hashMap = (HashMap<String, String>) intent.getSerializableExtra("mapkey");
    intent.getSerializableExtra("mapkey");

EDIT (Convert it back to List) try sth like:
HashMap<String, String> map = new HashMap<String, String>();
List<String> hashMap = new ArrayList<String>(map.values());

Happy coding!


text:
Q: How to overload clear Overloading clear() with a function is easy. But how to access the workspace of the upstream function (from which clear was called) to clear the workspace? builtin('clear') will only clear the workspace of the overloaded function.
function ret = someFun(a,b)
    ret = a + b;
    clear
    ret = 1;
end

function clear()
    persistent boring
    if isempty(boring), boring = 0; end
    boring = boring + 1;
    builtin('clear')
end

Screenshot: workspace of the upstream function after calling the overloaded clear function

A: Use evalin with the 'caller' option. That is, replace your line

builtin('clear')

by
evalin('caller', 'builtin(''clear'')')

This will clear all variables from the workspace of the caller function.
Should you want want to clear all variables from the Matlab base workspace, use the 'base' option:
evalin('base', 'builtin(''clear'')')


text:
Q: Trying to add a click event to individual elements but want them to execute one at a time I have three div elements on a page and when each one is clicked they are supposed to disappear one at a time. Right now when I click one div element, they all disappear as a group. How do I make them disappear one at a time?
HTML

  ×
  Error!

    ×
    Success!

   ×
    Warning!

JAVASCRIPT
document.addEventListener("click", function(){

    document.getElementById('alert').style.display = 'none';
    document.getElementById('alert2').style.display = 'none';
    document.getElementById('alert3').style.display = 'none';

});

A: First create an Array and then add an event listener to every element in the array using Array.forEach method of ES6.
The Code:

window.onload = function() {
  var divs = Array.from(document.querySelectorAll('.alerts'));
  divs.forEach(div => div.addEventListener('click', function() {
    div.style.display = 'none';
  }));
}

    ×
    Error!

    ×
    Success!

    ×
    Warning!

A: You can try using timeout like this

document.addEventListener("click", function() {
  document.getElementById('alert').style.display = 'none';
  setTimeout(() => {
    document.getElementById('alert2').style.display = 'none';
    setTimeout(() => {
      document.getElementById('alert3').style.display = 'none';
    }, 500);
  }, 500);
});

    ×
    Error!

    ×
    Success!

    ×
    Warning!


text:
Q: creating my own Word wrapper for string How do I make my own word wrap function for strings?  I want each line to be no longer than 50 characters and respect existing CRLFs.

A: Something like this, it will get you started (just a quick samle i mashed together):
Private Sub Doit()
    Dim Source As String = ""
    Source &= "How to make my own word wrap function for string, I want each line to be no longer than 50chars and take respect existing CRLFs" & vbCrLf & vbCrLf
    Source &= "So this will be a new row."
    Dim wrappedtext As String = wrap(Source, 20, vbNewLine)
    MsgBox(wrappedtext)
End Sub

Function wrap(ByVal text As String, ByVal maxlength As Integer, ByVal newline As String) As String

    Dim tmp() As String = Split(text.Replace(vbCrLf, " | "), " ")
    Dim ret As String = ""
    Dim wrk As String = ""
    For Each word As String In tmp
        If word = "|" Then
            ret &= newline
            wrk = ""
        ElseIf word = "" Then

        Else

            If Len(wrk & word) <= maxlength Then
                wrk &= " " & word
            Else
                ret &= wrk & newline
                wrk = word & " "
            End If

        End If
    Next
    If wrk <> "" Then ret &= wrk
    Return ret
End Function

A: From which point of view? SW architecture?
Take a look at the decorator pattern. If you like to work with streams, in the book "Heads First: Design Patterns" a string modifier is proposed. It's in Java, but the general programming concept is described in a good way. Some pages are missing but you can find many infos here.
The algorithm itself is trivial, isn't it?


text:
Q: How to search if every word in string starts with any of the word in list using python I am trying to filter sentences from my pandas data-frame having 50 million records using keyword search. If any words in sentence starts with any of these keywords.
WordsToCheck=['hi','she', 'can']
text_string1="my name is handhit and  cannary"
text_string2="she can play!"

If I do something like this:
if any(key in text_string1 for key in WordsToCheck):
    print(text_string1)

I get False positive as handhit as hit in the last part of word.
How can I smartly avoid all such False positives from my result set?
Secondly, is there any faster way to do it in python? I am using apply function currently.
I am following this link so that my question is not a duplicate: How to check if a string contains an element from a list in Python

A: If the case is important you can do something like this:
def any_word_starts_with_one_of(sentence, keywords):
  for kw in keywords:
    match_words = [word for word in sentence.split(" ") if word.startswith(kw)]
    if match_words:
      return kw
  return None

keywords = ["hi", "she", "can"]
sentences = ["Hi, this is the first sentence", "This is the second"]
for sentence in sentences:
   if any_word_starts_with_one_of(sentence, keywords):
     print(sentence)

If case is not important replace line 3 with something like this:
match_words = [word for word in sentence.split(" ") if word.lower().startswith(kw.lower())]


text:
Q: Nearest Neighbor distance frequency distribution I have a dataset of 6455 points. Is there a way to produce the frequency distribution of nearest neighbour distances in the data set in ArcGIS 10.3?
The Average Nearest Neighbor tool only produces the mean distance, not the whole distribution.

A: You can use Generate Near Table to obtain the nearest neighbour distances and then use a pivot table in excel to create the frequecy distribution. That should work.


text:
Q: How to convert a sparse histogram into dense histogram in CUDA? I am implementing an algorithm using raw CUDA kernels, in which every threadblock needs the dense histogram of available data to that threadblock, now the question is that do I have to calculate the dense histogram from the scratch? (is it worth calculating the dense histogram at all, provided that i already have the sparse histogram which is implemented using shared memory)
I have come up with this idea of converting, I will try to elaborate my idea with example (temp and hist both are in shared memory)
   0,1,2,3,4,5,6... //array indexes
   4,3,0,2,1,0,5... //contents of hist[]
   0,0,2,0,0,5,0... //contents of temp[] if(hist[x]>0)temp[x]=x;
   for_every_element     //this is sequential part :(
       if(temp[x]>0)
         shift elements from index x to 256
   4,3,2,1,0,5... //pass 1 of the for loop
   4,3,2,1,5...   //pass 2 of the for loop
                  //this goes on until all the 0s are compacted

Now I know above is sequential in nature, but the shifting can be done with constant time (and in parallel) because threads_per_block is already set to 256, so shifting is not the main issue, the main issue is how to improve this (or any other suggestion is welcomed).
Edit: i am thinking of another idea, that is as follows
Assuming threads_per_block=256 if i can count which of histogram bins are non-zeros (this operation is parallel because each thread is assigned to each bin, i can atomicadd the values generated by each thread) let's say that i can then start a new shared index variable sindex=0 and each time a thread wants to store the value into d_hist[] it can take the latest value from sindex and store it's values to d_hist[sindex]=hist[treadIdx.x] after that i can atomicAdd the sindex
Now there is only one problem, there is going to be a race condition to getting the value of sindex, so i may have to setup a flag which can be locked or unlocked when a thread is adding any value to d_hist (but i think there can be a deadlock situation here)
Will this technique work? and is there any other technique better than that?

A: Converting a sparse histogram to a dense histogram is a scatter operation.  If the sparse histogram is composed of s_index[S_N] and s_hist[S_N], then first we create a dense histogram d_hist[N] composed of all zeroes (you can do this from host code, perhaps).  Then we populate the dense histogram with d_hist[s_index[i]] = s_hist[i];  This can be done in parallel and uses as many threads as there are valid indices in your sparse histogram (i < S_N).  Assuming your histogram is sorted, you'll get whatever coalescing benefit may be possible based on the distribution of your sparse histogram indices.
It may not make sense for your case where each threadblock is doing a separate histogram, but you may also be interested in thrust scatter.

A: Well I guess the simplest method is to find out which bins>0 and after that, and exclusive scan can be done (in order to calculate the target indexes let's say sum_array[]) after that for allbins>0 move to d_hist[sum_array[threadIdx.x]-1]=s_hist[threadIdx.x]
 0,1,2,3,4,5,6... //s_indexes[]

 4,3,0,2,1,0,5... //contents of s_hist[]
 1,1,0,1,1,0,1... //all bins which are > 0 = sum_array[]

 1,2,2,3,4,4,5... //inclusive_scan of summ_array[]

 //after the moving part
 0,1,3,4,6... //s_indexes[]
 4,3,2,1,5... //d_hist[]
 0,1,2,3,4... //d_indexes[]

The reason why I am inclined to use this pattern is because it takes log_base_2(256) time in order to calculate the sum_array plus, other than that, moving and checking parts are just constant time operations, if anyone have different idea than this, please share.


text:
Q: Can you refer to yourself with "yourself" instead of "myself"? Is this interchangeable? For example:

*

*"Yes, I like to read news from other part of the world because it's a good way to keep yourself up to date with the rest of the world."

using yourself to refer to reading news as "a good way to keep up with the rest of the world" while still referring to myself as the subject
instead of going with "Yes, I like to read news from other part of the world because it's a convenient way for me to keep myself up to date with the rest of the world."

A: I'm sure there's a lot of useful grammar information that could be extracted from those two grammatically correct sentences, but I wouldn't interchange them that way. It depends a lot on the context.
The first one, "Yes, I like to read news from other parts of the world because it's a good way to keep yourself up to date." suggests generality, matter-of-fact, or even didactic undertones, in a lot of cases.
For example, when a father says that to a kid.
The second one, "Yes, I like to read news from other parts of the world because it's a good way for me to keep myself up to date." suggests an opinion, a piece of conversation, specific to that person, that might not hold for another, in a lot of cases.
For example, when a friend who gets news through the radio, asks another out of curiosity if and why they read a lot of newspapers.
It depends on the context. There are examples where the first one is not didactic at all and where the second one is.