text:
Q: Add multiple rows via API to an ExactTarget Data Extension? Using the Fuel PHP SDK I can add rows one at a time to my Data Extension. However, I cannot figure out how to add multiple rows in one call. Is it possible?
As I need to add between 5 and 5000 rows to a Data Extension, the overhead of adding each individually seems crazy, while the number of rows involved don't justify the complexity of a SFTP upload and a triggered import.
I have checked the Java, C#, Ruby & Python SDKs and none have an example of adding multiple rows; however the REST API (and structure of the SOAP payload) make me think this should be possible.

A: To add rows, CreateRequest can be used.
<CreateRequest xmlns="http://exacttarget.com/wsdl/partnerAPI">
                <Objects xsi:type="DataExtensionObject">
                     <CustomerKey>TestDE</CustomerKey>
                     <Properties>
                          <Property>
                               <Name>Nickname</Name>
                               <Value>test1</Value>
                            </Property>
                        <Property>
                              <Name>Amount</Name>
                           <Value>7100</Value>
                        </Property>
                </Properties>
             </Objects>
             <Objects xsi:type="DataExtensionObject">
                     <CustomerKey>TestDE</CustomerKey>
                <Properties>
                          <Property>
                               <Name>Nickname</Name>
                               <Value>test2</Value>
                            </Property>
                        <Property>
                              <Name>Amount</Name>
                           <Value>8100</Value>
                        </Property>
                </Properties>
             </Objects>
    </CreateRequest>

A: I'm not familiar enough with the PHP SDK to tell you the correct syntax. But, I have confirmed you can make a single API call to upsert multiple rows in a data extension. The syntax of the soap envelope looks something like this.
<UpdateRequest xmlns="http://exacttarget.com/wsdl/partnerAPI">
    <Options>
        <SaveOptions>
            <SaveOption>
                <PropertyName>*</PropertyName>
                <SaveAction>UpdateAdd</SaveAction>
            </SaveOption>
        </SaveOptions>
    </Options>
    <Objects xsi:type="DataExtensionObject">
        <PartnerKey xsi:nil="true"/>
        <ObjectID xsi:nil="true"/>
        <CustomerKey>SomeDataExtensionKey</CustomerKey>
        <Properties>
            <Property><Name>keyfield</Name><Value>keyvalue1</Value></Property>
            <Property><Name>field2</Name><Value>data1</Value></Property>
        </Properties>
        <Properties>
            <Property><Name>keyfield</Name><Value>keyvalue2</Value></Property>
            <Property><Name>field2</Name><Value>data2</Value></Property>
        </Properties>
        <Properties>
            <Property><Name>keyfield</Name><Value>keyvalue3</Value></Property>
            <Property><Name>field2</Name><Value>data3</Value></Property>
        </Properties>
    </Objects>
</UpdateRequest>

I hope this helps.

A: The answer is to create multiple "Objects".
SOAP Envelope (within "CreateRequest":
<Objects xsi:type="DataExtensionObject">
    <CustomerKey>MY_DE</CustomerKey>
    <Properties>
       <Property>
          <Name>hey</Name>
          <Value>hi</Value>
       </Property>
    </Properties>
 </Objects>
 <Objects xsi:type="DataExtensionObject">
    <CustomerKey>MY_DE</CustomerKey>
    <Properties>
       <Property>
          <Name>hey</Name>
          <Value>yo</Value>
       </Property>
    </Properties>
 </Objects>

SOAP PHP SDK
// Storing as an array will allow you to insert multiple rows in one call
$cr = new ExactTarget_CreateRequest();
$cr.Objects = array();

A: I highly recommend this resource:
https://sfmcgeeks.com/2020/05/09/create-data-extensions-in-marketing-cloud-via-api/
I leveraged Postman to write this request.
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Header>
      <fueloauth>{{accessToken}}</fueloauth>
   </soapenv:Header>
   <soapenv:Body>
      <CreateRequest xmlns="http://exacttarget.com/wsdl/partnerAPI">
        <Options>
        </Options>
        <Objects xsi:type="DataExtensionObject">
          <PartnerKey xsi:nil="true" />
          <ObjectID xsi:nil="true" />
          <CustomerKey>SampleDataExtension</CustomerKey>
          <Properties>
            <Property>
              <Name>EmailAddress</Name>
              <Value>johndoe@example.com</Value>
            </Property>
            <Property>
              <Name>FirstName</Name>
              <Value>John</Value>
            </Property>
            <Property>
              <Name>LastName</Name>
              <Value>Doe</Value>
            </Property>
            <Property>
              <Name>SubscriberKey</Name>
              <Value>0031234567890</Value>
            </Property>
          </Properties>
        </Objects>
        <Objects xsi:type="DataExtensionObject">
          <PartnerKey xsi:nil="true" />
          <ObjectID xsi:nil="true" />
          <CustomerKey>SampleDataExtension</CustomerKey>
          <Properties>
            <Property>
              <Name>EmailAddress</Name>
              <Value>janedoe@example.com</Value>
            </Property>
            <Property>
              <Name>FirstName</Name>
              <Value>jane</Value>
            </Property>
            <Property>
              <Name>LastName</Name>
              <Value>Doe</Value>
            </Property>
            <Property>
              <Name>SubscriberKey</Name>
              <Value>0030987654321</Value>
            </Property>
          </Properties>
        </Objects>
      </CreateRequest>
   </soapenv:Body>
</soapenv:Envelope>


text:
Q: Compile-Time Lookup-Table with initializer_list Suppose you have some hash values and want to map them to their respective strings at compile time.
Ideally, I'd love to be able to write something along the lines of:
constexpr std::map<int, std::string> map = { {1, "1"}, {2 ,"2"} };

Unfortunately, this is neither possible in C++17 nor C++2a. Nevertheless,
I tried emulating this with std::array, but can't get the size of the initializer list at compile time to actually set the type of the array correctly without explicitly specifying the size.
Here is my mockup:

template<typename T0, typename T1>
struct cxpair
{
    using first_type = T0;
    using second_type = T1;

    // interestingly, we can't just = default for some reason...
    constexpr cxpair()
        : first(), second()
    {  }

    constexpr cxpair(first_type&& first, second_type&& second)
        : first(first), second(second)
    {  }

    // std::pair doesn't have these as constexpr
    constexpr cxpair& operator=(cxpair<T0, T1>&& other)
    { first = other.first; second = other.second; return *this; }

    constexpr cxpair& operator=(const cxpair<T0, T1>& other)
    { first = other.first; second = other.second; return *this; }

    T0 first;
    T1 second;
};

template<typename Key, typename Value, std::size_t Size = 2>
struct map
{
    using key_type = Key;
    using mapped_type = Value;
    using value_type = cxpair<Key, Value>;

    constexpr map(std::initializer_list<value_type> list)
        : map(list.begin(), list.end())
    {  }

    template<typename Itr>
    constexpr map(Itr begin, const Itr &end)
    {
        std::size_t size = 0;
        while (begin != end) {
            if (size >= Size) {
                throw std::range_error("Index past end of internal data size");
            } else {
                auto& v = data[size++];
                v = std::move(*begin);
            }
            ++begin;
        }
    }

    // ... useful utility methods omitted

private:
    std::array<value_type, Size> data;
    // for the utilities, it makes sense to also have a size member, omitted for brevity
};

Now, if you just do it with plain std::array things work out of the box:

constexpr std::array<cxpair<int, std::string_view>, 2> mapp = {{ {1, "1"}, {2, "2"} }};

// even with plain pair
constexpr std::array<std::pair<int, std::string_view>, 2> mapp = {{ {1, "1"}, {2, "2"} }};

Unfortunately, we have to explicitly give the size of the array as second template argument. This is exactly what I want to avoid.
For this, I tried building the map you see up there.
With this buddy we can write stuff such as:
constexpr map<int, std::string_view> mapq = { {1, "1"} };
constexpr map<int, std::string_view> mapq = { {1, "1"}, {2, "2"} };

Unfortunately, as soon as we exceed the magic Size constant in the map, we get an error, so we need to give the size explicitly:
//// I want this to work without additional shenanigans:
//constexpr map<int, std::string_view> mapq = { {1, "1"}, {2, "2"}, {3, "3"} };
constexpr map<int, std::string_view, 3> mapq = { {1, "1"}, {2, "2"}, {3, "3"} };

Sure, as soon as you throw in the constexpr scope, you get a compile error and could just tweak the magic constant explicitly. However, this is an implementation detail I'd like to hide. The user should not need to deal with these low-level details, this is stuff the compiler should infer.
Unfortunately, I don't see a solution with the exact syntax map = { ... }. I don't even see light for things like constexpr auto map = make_map({ ... });. Besides, this is a different API from the runtime-stuff, which I'd like to avoid to increase ease of use.
So, is it somehow possible to infer this size parameter from an initializer list at compile time?

A: std::array has a deduction guide:
template <class T, class... U>
array(T, U...) -> array<T, 1 + sizeof...(U)>;

which lets you write:
// ok, a is array<int, 4>
constexpr std::array a = {1, 2, 3, 4};

We can follow the same principle and add a deduction guide for map like:
template <typename Key, typename Value, std::size_t Size>
struct map {
    constexpr map(std::initializer_list<std::pair<Key const, Value>>) { }
};

template <class T, class... U>
map(T, U...) -> map<typename T::first_type, typename T::second_type, sizeof...(U)+1>;

Which allows:
// ok, m is map<int, int, 3>
constexpr map m = {std::pair{1, 1}, std::pair{1, 2}, std::pair{2, 3}};

Unfortunately, this approach requires naming each type in the initializer list - you can't just write {1, 2} even after you wrote pair{1, 1}.

A different way of doing it is to take an rvalue array as an argument:
template <typename Key, typename Value, std::size_t Size>
struct map {
    constexpr map(std::pair<Key, Value>(&&)[Size]) { }
};

Which avoids having to write a deduction guide and lets you only have to write the type on the first one, at the cost of an extra pair of braces or parens:
// ok, n is map<int, int, 4>
constexpr map n{{std::pair{1, 1}, {1, 2}, {2, 3}, {3, 4}}};

// same
constexpr map n({std::pair{1, 1}, {1, 2}, {2, 3}, {3, 4}});

Note that the array is of pair<Key, Value> and not pair<Key const, Value> - which allows writing just pair{1, 1}. Since you're writing a constexpr map anyway, this distinction probably doesn't matter.

A: @Barry's answer pinpointed me in the right direction. Always explicitly listing pair in the list is undesirable. Moreover, I want to be able to partially specialize the template argument list of map. Consider the following example:
// for the sake of the example, suppose this works
constexpr map n({{1, "1"}, {2, "2"}});
              // -> decltype(n) == map<int, const char*, 2>

// the following won't work
constexpr map<std::size_t, const char*> m({{1, "1"}, {2, "2"}});

However, perhaps the user wants that the map contains std::size_t as key, which does not have a literal. i.e. s/he would have to define a user-defined literal just to do that.
We can resolve this by offloading the work to a make_map function, allowing us to partially specialize the map:
// deduction guide for map's array constructor
template<class Key, class Value, std::size_t Size>
map(cxpair<Key, Value>(&&)[Size]) -> map<Key, Value, Size>;

// make_map builds the map
template<typename Key, typename Value, std::size_t Size>
constexpr auto make_map(cxpair<Key, Value>(&&m)[Size]) -> map<Key, Value, Size>
{ return map<Key, Value, Size>(std::begin(m), std::end(m)); }

// allowing us to do:
constexpr auto mapr = make_map<int, std::string_view>({ {1, "1"},
                                                        {2, "2"},
                                                        {3, "3"} });

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use all array elements as where conditions in LINQ I have a string array
Dim arrtest = New String() {"First", "Second", "Third"}

and a Datatable within a Dataset
_dataset.Table.AsEnumerable()

how is it possible to select all cases that meet the arrtest elements as where conditions?
The full (by feet) solution would look:
dim query = From dt In _dataset.Table.AsEnumerable()
where dt.Field1 = "First" or "Second" or "Third"

I thought of using the stringbuilder to generate a string with all the conditions seperated by "or" but was wondering if any of you Linq experts could help me finding a better solution within Linq?

A: You can use Enumerable.Contains:
dim query = From row In _dataset.Tables(0).AsEnumerable()
            Where arrtest.Contains(row.Field(Of String)("Field1"))


text:
Q: Footer DIV comes up on Container DIV having two children DIVs Container : relative positioned. Have two child div left and right column having 60% and 30% width of container.
Left child : absolute positioned . Top:0; Left:0; width: 60%;
Right child : absolute positioned . Top:0; right:0; width: 30%;
Footer: Relative positioned.
But footer comes up. Code Given below. Visit the following code LIVE here
can anyone tell me whats wrong in the following code, I think technically all correct.

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

A: You will have to mention the height of the #container div. Like this
#container {
  background: none repeat scroll 0 0 #CC6633;
  height: 240px; // mention height
  margin: 0 auto;
  padding: 10px;
  position: relative;
  width: 1000px;
}

A: change margin 0 auto to margin: 0 auto 228px;
Demo: http://jsfiddle.net/KwB5r/
#container {
    position: relative;
    /*margin:0 auto;*/
    margin: 0 auto 228px;
    width: 1000px;
    background: #C63;
    padding: 10px;
    height:auto;
}

or set the heigth of you container to 228px for example

A: You should leave the position: absolute rule from the
 tags that are inside
. And also should add the rule display: inline-block; to the right and left
 tags:

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.


text:
Q: Como puedo llenar varios JTexField con el contenido de un ArrayList? La duda en concreto es que cree JRadioButton de manera dinamica, es decir dependiendo de la cantidad que hay en un ArrayList. De la clase ManejadorArchivo se trae la informacion del usuario y se requiere mostrar en su respectivo JTextField. Este es un segmento de codigo:
    public void crearRadioButton(){
    ManejadorArchivo manejador = ManejadorArchivo.getInstance();
    ArrayList<Usuario> usuarios = manejador.getListaUsuarios();
    JPanel panelUsuarios = new JPanel();
    panelUsuarios.setLayout(new FlowLayout());

    Component botones;

    for(Usuario usr: usuarios){
        botones = panelUsuarios.add(new JRadioButton((usr.toString())));
        grupo.add((AbstractButton) botones);

    }

    panel.add(panelUsuarios, BorderLayout.CENTER);
    panelUsuarios.setBounds(228, 11, 265, 378);

    panel.setVisible(true);
}

Lo que necesito es que a la hora de elegir el nombre de un usuario por medio los JRadioButton me muestre toda la informacion de cierto usuario seleccionado en los JTexfield asignados (Nombre, apellido Materno, Apellido Paterno).

A: Si le agregas un ActionListener a cada JRadioButton al momento de crearlos, luego al codificar el metodo actionPerformed(ActionEvent event), podras invocar el metodo event.getSource() y castear a JRadioButton. Obtenido de esta forma el JRadioButton en cuestion, podras recorrer nuevamente la lista hasta encontrar el usuario cuyo toString() coincida con el nombre del JRadioButton obtenido y una vez obtenido el usuario completar con el los datos en los JTextFields.


text:
Q: Why SHA2 has a 384 bit version? I understand that there is a 256 and 512 versions because they are all powers of 2. But where 384 came from?
I know that binary representation of 384 is 110000000 but I can't understand the logic.
It is not in the middle between 256 and 512. It is not even a logarithmic middle.
Why 384?

A: A quick look on Wikipedia finds this:

SHA-256 and SHA-512 are novel hash functions computed with 32-bit and
  64-bit words, respectively. They use different shift amounts and
  additive constants, but their structures are otherwise virtually
  identical, differing only in the number of rounds. SHA-224 and SHA-384
  are simply truncated versions of the first two, computed with
  different initial values.

Looking at the comparison between all the variants, it seems that SHA-384 is more resistant to length extension attacks than SHA-512 (its longer version).
You can find a more detailed answer on Cryptography Stack Exchange: here.

A: 256 + 128 = 384

It is nothing but addition of two values which are above mentioned powers of 2 !!


text:
Q: Using "SQL Native Client" (ie 2005 driver) with SQL Server 2012? We have an application that has been using the SQL Server 2005 client driver for years to connect to SQL Server 2005, 2008 and 2008 R2.
We now have SQL Server 2012 installed that 'runs fine' using that same driver but I want to ensure that there are no known problems.
I spent an hour looking at MSDN articles but could not find a clear answer on the issue that '2005 driver is supported for 2012 assuming we only want to use server features up to 2005' (as we do for now).
Has anyone else checked this out already?  Can you help point me in the right direction to find a definitive statement?
Thanks in advance, Rob C

A: Under your circumstances it should work fine with the driver you have in place already. However, I would "budget" for updating the driver even if you don't plan on implementing features of newer releases. SQL is good with backwards compatibility and you don't want your application falling too far behind to the point where OS support becomes an issue.
Additionally, check to make sure the compatibility level of the DB you are connecting to is in 90 (SQL 2005) or lower to be on the safe side (it probably already is) as this will ensure any updates to your database do not go beyond the SQL 2005 functionality. You can find this under the database properties in SQL Management Studio.

A: I've just started testing the 2005 client + SQL Server 2014 with ODBC and OLE DB, and haven't found any issues so far. I wouldn't really recommend using compatibility levels unless you actually notice something that it fixes.


text:
Q: meaning of the verb phrase "do anything with someone "
http://www.afb.org/annesullivan/teachingHelen.asp

This link is the letter of Annie Sullivan [Helen's teacher].

In this letter, Annie explained to Mrs. Keller how difficult it was going to be to do anything with Helen.

I am so confused with the usage of "do anything with Helen". I consider Annie intend to teach good manners to  Helen.
Please read and explain it to me.Thanks in advance.

A: There's nothing complicated to the phrase "to do anything with".  It means what it says. You could substitute "accomplish" or "achieve" for "do".
In the example you give, Annie Sullivan is saying that teaching Helen Keller is going to be very difficult.  Your idea about manners could be inferred from the rest of the letter, but has nothing to do with the sentence you quoted.
Examples:
My car is badly wrecked.  I have it towed to a repair shop.  The mechanic says, "I don't think we'll be able to do anything with it."
I'm unsatisfied with my haircut.  So I go to a different barber and say "Can you do anything with my hair?"
I'm interviewing a chef, and ask "Can you do anything with chicken that's different and exciting?"


text:
Q: Ruby Strings - Checking against a set of strings to match I am trying to check an array of strings for containing one or more matching strings.
Currently I am doing this by using if statements - not nice, but it works - However now I am looking for a more Ruby-like way to do this.
row[:datapoints].each do |data|
    if data[:direction].include? "Beusselstr"
        data[:image] = "category-1"
    end
    if data[:direction].include? "Ostkreuz"
        data[:image] = "category-1"
    end
    if data[:direction].include? "Westend"
        data[:image] = "category-2"
    end
    if data[:direction].include? "1)S Gr"
        data[:image] = "category-3"
    end
end

Instead of this I'd like to store the matching strings in an array. To make it a bit more complicated I actually have different categories of matching terms with their own result actions (see category specific assignment of the data[:image] value).
category_1_keywords = ["Beusselstr","Ostkreuz"]
category_2_keywords = ["nefeld Bhf","Greifswalder","Westend"]
category_3_keywords = ["1)S Gr"]

imagecategories = {:category_1 => category_1_keywords,:category_2 => category_2_keywords,:category_3 => category_3_keywords}

How would filtering the array (row[:datapoints]) using such a matching array (imagecategories) look like?

A: You would probably want to use the array intersection operator & and check if it's empty.
if (data[:direction] & category_1_keywords).any?
  data[:image] = "category-1"
end

4 if's in a row though start looking like time for an iterator:
keywords = {
'category_1' => ["Beusselstr","Ostkreuz"],
'category_2' => ["nefeld Bhf","Greifswalder","Westend"],
'category_3' => ["1)S Gr"]
}

data[:image] = keywords.find{|k,v| (data[:direction] & v).any?}[0]

A: Assuming that data[:direction] is a string, you can find the category with:
data[:image], _ = imagecategories.find { |category, keywords|
  keywords.any? { |keyword|
    data[:direction].include?(keyword)
  }
}

In plain text: find the first category-keywords pair (imagecategories.find) having any keyword (keywords.any?) that the data[:direction] string contains.


text:
Q: Slim rowspan aggregation with Rails data I'm using Rails with Slim.
I have this view with data (I hope that's ok to be filled with Russian):

So first column is filling with data I want to aggregate on. I want to see something like this:

But I really cannot figure out how can I do this.
Here is my Slim code:
  tbody
- @managers.each do |m|
  tr
    td= m.region
    td= m.name
    ...

And I've got hash with aggregated data like this:
{ region1: [row1, row2...],
  region2: [row3, row4...]}

But it's true problem to apply rowspan to first td only, and skip it for all other rows but first.
Please help.

A: You can achieve it like this
tbody
- @managers.each do |region, data|
  - data.each_with_index do |m, index|
    tr
      - if index.zero?
        td{rowspan: data.count}= m.region
      td= m.name
      ...


text:
Q: Why can't compilers expand arguments of a variadic template via comma operator? I know that we can't use variadic expansions as if it is a chain of comma operators. In that question the sample is like this:
template<typename... Args>
inline void increment_all(Args&... args)
{
    ++args...;
}

It might be ambiguous either to increment or expand first so parentheses won't hurt:
template<typename... Args>
inline void increment_all(Args&... args)
{
    (++args)...;
}

or something like this:
template<typename... Args>
void cout_all(Args&&... args)
{
    (std::cout << std::forward<Args>(args))...;
}

I know that we can use some recursion tricks to get what we want, like this. What I don't know is why does not the standard describe such behavior? I mean, what is the reason behind it?

A: The other contexts where a pack expansion is allowed are lists where a comma is a separator between list elements, not an operator.
For example, f(args...) expands to a function argument list, tuple<Args...> expands to a template argument list.
In your examples the pack expansion forms a statement, and commas between sub-expressions of a statement are the comma operator, which could be overloaded, leading to arbitrarily complicated code, and unlike the builtin comma operator, not forcing left-to-right evaluation.  You'd be surprised if your (std::cout << std::forward<Args>(args))...;  example wrote out the args in unspecified order because one of the types in the parameter pack overloaded operator<< and operator, and broke the order of evaluation.
Doing this would not be a simple extension to the current rules, it would be a completely different context with very different effects.

It might be ambiguous either to increment or expand first so parentheses won't hurt:

No, it wouldn't be ambiguous. It's OK to use f(++args...) and it's clear and unambiguous. The difficulty with your suggestion is not how to parse ++args... it's what happens after you expand it to a statement containing comma operators.


text:
Q: TS2531 with useRef I'm getting an issue TSLink throwing TS2531 (Object is possibly 'null'.) in a code on my project to the point I'm doing the most simple test to isolate the issue.
The point is that I testing the exact same code in a React + TS sandbox on codesandbox and it's working fine. Here is the code:
import React from "react";

export const SimpleComp = () => {
    const refName = React.useRef(null);

    const getValue = (): void => {
        if (refName.current !== null) {
            console.log(refName.current.value);
        }
    };

    return (
        <>
            <input type="text" ref={refName} />
            <button onClick={() => getValue()}>Get Value</button>
        </>
    );
};

My guess it that I can fix it on tsconfig.json, but I'm not sure of how, since I copied the same tsconfig.json from the codesandbox and I'm still having the same issue. BTW, I'm using webstorm.
Any idea of how to fix it?
PS: here is the link for my the codesandbox: https://codesandbox.io/s/competent-franklin-ww4xk

A: TypeScript can not infer what the reference will be for. You can pass in the HTMLInputElement for the useRef<T> generic function.
Change:
const refName = React.useRef(null);

To:
const refName = React.useRef<HTMLInputElement>(null);


text:
Q: FaceBook logging out when getting error on a request So I am using the Facebook iOS SDK and I get this very annoying thing where I am getting logged out when a request to the open graph fails. How do I prevent this from happening? Here's how I am posting it:
 [_facebook requestWithGraphPath:graphPath
                              andParams:params
                          andHttpMethod:@"POST"
                            andDelegate:nil];

A: Fb SDK is a complete mess, but what you could do:

*

*set your object to be a delegate

*implement protocol methods that catches error

*

*in that methods check if you're still logged in

*if not - login, or do whatever you want (present error alert/start another request/etc)


text:
Q: Small and Cap case in js I have a basic typing tutor built in javascript. It has two portions:
The first portion contains the text/lesson to type and the second portion has keyboard with keys.
I code like this:
$(document).on('keyup', function(e){
    if( String.fromCharCode(e.keyCode) == TextCharacter )
        // Character was typed correctly
});

The problem is that it works for small case letters. If the lesson contains any character in capital case, it does not work since the user has to type "shift + character".
Is there any way to check if character key is pressed while holding the shift key?
Thanks

A: event (e) has two properties to check if shift/ ctrl are pressed. event.shiftKey and event.ctrlKey properties  are set to true if respective key is pressed.

A: for Shift key, you can use shiftKey:

//like
e.shiftKey

A: A quick search for "Javascript keycodes" came up with this: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
So I guess you'll just detect when shift (keycode 16) and the character is pressed.


text:
Q: What's wrong with my vdims in my HoloViews Python code? display(df_top5_frac.head())

The code below produces an error.
%opts Overlay [width=800 height=600 legend_position='top_right'] Curve

hv.Curve((df_top5_frac['Blocked Driveway'])      , kdims = ['Hour'], vdims = ['Fraction'], label = 'Blocked Driveway') *\
hv.Curve((df_top5_frac['HEAT/HOT WATER'])        , kdims = ['Hour'], vdims = ['Fraction'], label = 'HEAT/HOT WATER') *\
hv.Curve((df_top5_frac['Illegal Parking'])       , kdims = ['Hour'], vdims = ['Fraction'], label = 'Illegal Parking') *\
hv.Curve((df_top5_frac['Street Condition'])      , kdims = ['Hour'], vdims = ['Fraction'], label = 'Street Condition') *\
hv.Curve((df_top5_frac['Street Light Condition']), kdims = ['Hour'], vdims = ['Fraction'], label = 'Street Light Condition')

Here is the error:

A: Cause of your error:
The vdim should be the name of the column you want to have on the y-axis, but the column name 'Fraction' doesn't exist, so you get the error.

Here's a possible solution:
When you set hour as the index, you could specify: kdim='hour' and vdim='blocked_driveway', but in this case you don't really need them and can leave them out:
# import libraries
import numpy as np
import pandas as pd
import holoviews as hv
hv.extension('bokeh')

# create sample data
data = {'hour': ['00', '01', '02'],
        'blocked_driveway': np.random.uniform(size=3),
        'illegal_parking': np.random.uniform(size=3),
        'street_condition': np.random.uniform(size=3),}

# create dataframe and set hour as index
df = pd.DataFrame(data).set_index('hour')

# create curves:
# in this case the index is automatically taken as kdim
# and the series variable, e.g. blocked_driveway is taken as vdim
plot1 = hv.Curve(df['blocked_driveway'], label='blocked_driveway')
plot2 = hv.Curve(df['illegal_parking'], label='illegal_parking')
plot3 = hv.Curve(df['street_condition'], label='street_condition')

# put plots together
(plot1 * plot2 * plot3).opts(legend_position='top', width=600, height=400)

Alternative and shorter solution:
In this case however I would use library hvplot which is built on top of holoviews.
It has even easier syntax and you need a lot less code to get the plot you want:
import hvplot.pandas

# you don't have to set hour as index this time, but you could if you'd want to.
df.hvplot.line(
    x='hour',
    y=['blocked_driveway',
       'illegal_parking',
       'street_condition'],
)

Resulting plot:


text:
Q: Runtime Exception java.lang.NoSuchMethodError: com.google.common.base.Optional.toJavaUtil()L with Spark-BigQuery connector Currently I'm trying to connect to BigQuery from Spark. I'm have built fat jar file using sbt assembly plugin and trying to launch the job in local mode using spark-submit. I'm observing java.lang.NoSuchMethodError: com.google.common.base.Optional.toJavaUtil()Ljava/util/Optional; exception as soon as Spark job is launched.
Below is the Exception Trace,
Exception in thread "main" java.lang.NoSuchMethodError: com.google.common.base.Optional.toJavaUtil()Ljava/util/Optional;
    at com.google.cloud.spark.bigquery.SparkBigQueryConfig.getOption(SparkBigQueryConfig.java:265)
    at com.google.cloud.spark.bigquery.SparkBigQueryConfig.getOption(SparkBigQueryConfig.java:256)
    at com.google.cloud.spark.bigquery.SparkBigQueryConfig.lambda$getOptionFromMultipleParams$7(SparkBigQueryConfig.java:273)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.Spliterators$IteratorSpliterator.tryAdvance(Spliterators.java:1812)
    at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
    at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:499)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:486)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
    at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:464)
    at com.google.cloud.spark.bigquery.SparkBigQueryConfig.getOptionFromMultipleParams(SparkBigQueryConfig.java:275)
    at com.google.cloud.spark.bigquery.SparkBigQueryConfig.from(SparkBigQueryConfig.java:119)
    at com.google.cloud.spark.bigquery.BigQueryRelationProvider.createSparkBigQueryConfig(BigQueryRelationProvider.scala:133)
    at com.google.cloud.spark.bigquery.BigQueryRelationProvider.createRelationInternal(BigQueryRelationProvider.scala:71)
    at com.google.cloud.spark.bigquery.BigQueryRelationProvider.createRelation(BigQueryRelationProvider.scala:45)
    at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:340)
    at org.apache.spark.sql.DataFrameReader.loadV1Source(DataFrameReader.scala:239)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:227)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:174)
    at com.bigquery.OwnDataSetReader$.delayedEndpoint$com$$bigquery$OwnDataSetReader$1(OwnDataSetReader.scala:18)
    at com.bigquery.OwnDataSetReader$delayedInit$body.apply(OwnDataSetReader.scala:6)
    at scala.Function0$class.apply$mcV$sp(Function0.scala:34)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
    at scala.App$$anonfun$main$1.apply(App.scala:76)
    at scala.App$$anonfun$main$1.apply(App.scala:76)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:35)
    at scala.App$class.main(App.scala:76)
    at com..bigquery.OwnDataSetReader$.main(OwnDataSetReader.scala:6)
    at com..bigquery.OwnDataSetReader.main(OwnDataSetReader.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.spark.deploy.JavaMainApplication.start(SparkApplication.scala:52)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:894)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:198)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:228)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:137)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

After doing some research on the exception, I found that this exception can happen due to multiple version of guava library. I made sure that there are no such conflicts in the final build jar, I also verified it by decompiling my jar file. No conflicts were observed, but issue still persists :(. Below is the build.sbt snippet,
name := "bigquer-connector"

version := "0.1"

scalaVersion := "2.11.8"
test in assembly := {}

assemblyJarName in assembly := "BigQueryConnector.jar"

assemblyMergeStrategy in assembly := {
  case x if x.startsWith("META-INF") => MergeStrategy.discard
  case x =>
    val oldStrategy = (assemblyMergeStrategy in assembly).value
    oldStrategy(x)

}

libraryDependencies += ("com.google.cloud.spark" %% "spark-bigquery" % "0.18.0")
  .exclude("com.google.guava", "guava")
  .exclude("org.glassfish.jersey.bundles.repackaged", "jersey-guava")

libraryDependencies += "com.google.guava" % "guava" % "30.0-jre"

libraryDependencies += ("org.apache.spark" % "spark-core_2.11" % "2.3.1")
  .exclude("com.google.guava", "guava")
  .exclude("org.glassfish.jersey.bundles.repackaged", "jersey-guava")

libraryDependencies += ("org.apache.spark" % "spark-sql_2.11" % "2.3.1")
  .exclude("com.google.guava", "guava")
  .exclude("org.glassfish.jersey.bundles.repackaged", "jersey-guava")

Below is the Main class,
object OwnDataSetReader extends App {

  val session = SparkSession.builder()
    .appName("big-query-connector")
    .config(getConf)
    .getOrCreate()

  session.read
    .format("com.google.cloud.spark.bigquery")
    .option("viewsEnabled", true)
    .option("parentProject", "my_gcp_project")
    .option("credentialsFile", "<path to private json file>")
    .load("my_gcp_data_set.my_gcp_view")
    .show(2)

  private def getConf : SparkConf = {
    val sparkConf = new SparkConf
    sparkConf.setAppName("biq-query-connector")
    sparkConf.setMaster("local[*]")

    sparkConf
  }
}

Command used for launching the Spark in my local terminal : spark-submit --deploy-mode client --class com.bigquery.OwnDataSetReader BigQueryConnector.jar. I'm using spark version 2.3.x on my local machine

A: I was able to fix the issue. It was with merge strategy in my build.sbt file.
assemblyMergeStrategy in assembly := {
  case x if x.startsWith("META-INF") => MergeStrategy.discard
  case x =>
    val oldStrategy = (assemblyMergeStrategy in assembly).value
    oldStrategy(x)

}

I was discarding the files in META-INF folder. The config files inside META-INF folder of spark-bigquery connector are used during library bootstrap. So, instead of discarding, changing the strategy like below worked for me.
case PathList("META-INF", xs @ _*) =>
    (xs map {_.toLowerCase}) match {
      case ("manifest.mf" :: Nil) | ("index.list" :: Nil) | ("dependencies" :: Nil) | ("license" :: Nil) | ("licence.txt" :: Nil) | ("notice.txt" :: Nil) | ("notice" :: Nil)=>
        MergeStrategy.discard
      case ps @ (x :: xs) if ps.last.endsWith(".sf") || ps.last.endsWith(".dsa") || ps.contains("license") || ps.contains("notice") =>
        MergeStrategy.discard
      case "plexus" :: xs =>
        MergeStrategy.discard
      case "services" :: xs =>
        MergeStrategy.filterDistinctLines
      case _ => MergeStrategy.last
    }

A: Probably it is because of version mismatch among dependent libraries of com.google.cloud.spark:spark-bigquery_2.11:0.18.1. It was resolved for me using com.google.cloud.spark:spark-bigquery-with-dependencies_2.11:0.18.1 which brings in all the dependent libs.


text:
Q: IBM Cloud cannot create account at the moment I already have an IBMid and wanted to sign up for the IBM cloud, but once I clicked "Create account", it gave me an error message saying that it can't create the account at the moment. I've already tried signing up in a different browser, but it didn't work there either. My error code is: 6af6b529-81e2-4105-ac52-48b25fa0cb0b I'd really appreciate your help. Thanks in advance!
Edit:
What worked for me was to use my Gmail email address. It seems like IBM just doesn't like some email providers. So, if you have any such problems, just use another email address.

A: Often, account creation issues on IBM Cloud can be traced back to anti-fraud measures that the IBM Cloud registration team takes in order to prevent abuse.
While it's not clear exactly what these measures are, the most common workaround is to use another email address to create your account. IBM Cloud tends to favor corporate email addresses and is more likely to flag public email providers, especially outlook.com.
Good luck!

A: I had same issue while i give my outlook email id. I solved it by changing it to my gmail id.

A: Changing email didn't work for me. What worked was turning off my VPN.

A: Despite often, account creation issues on IBM Cloud can be traced back to anti-fraud measures as he has said, you have to avoid use specially outlook.com because is practically impossible to open an account on IBM Cloud with that provider, anyway, if you still having a problem with other providers, IBM is recommending to try the following,

*

*Clear your browser's cache, and then restart it.

*Use the private browsing mode of your browser, for example, a private or incognito window.

*Use a different browser. For more information about browsers that are supported by IBM Cloud, see IBM Cloud prerequisites.

*Try another computer or network-connect device, such as a phone or tablet.

*Try a different domain email ID to create the account.

A: For me all I had to do was go incognito mode, worked first time after that!

A: I had the same issue. AOL e-mail didn't work, but yahoo e-mail (+ USA as country) worked


text:
Q: Why isn't the Skype Chrome extension showing up on my home PC? I have Chrome installed at both home and work and I'm syncing:

*

*Bookmarks

*Extensions

*Preferences

between the two.
Changes I make to bookmarks and preferences on one are showing up (as expected) on the other.
However, the Skype extension is not installed on my home PC while it is on my work PC. I have Skype installed on both machines too. And when Skype updated to the latest version it installed the Firefox extension and the IE toolbar.
What do I have to do to get the extension on my home PC?
Oops - forgot to add - Home PC is Windows XP, work PC is Windows 7 (not that it should really make a difference).

A: You can try installing it manually from here http://www.skype.com/intl/en-us/get-skype/on-your-computer/clickandcall/.

A: If the extension is not available on the Chrome Web store, then it will not be synced. I've seen this happen to several extensions which are in private beta (Xobni), or are not available in Chrome Webstore ( eg: user scripts) or those installed from respective websites ( an extension that I created, LastPass).
The only solution is as Peter Maxwell mentioned, to install them manually.


text:
Q: How can I use my PC to make phone calls from my mobile phone? Is there a possibility to use my PC headset on Windows 10 to make phone calls from my Android phone connected via Bluetooth?
Microsoft's Phone Link should be capable to do that, but I don't want to use that due to privacy concerns (why do they require a Microsoft account for that?).
There was a solution for Windows 7 but this seems to not work in Windows 10 anymore.
Any suggestions for applications would be greatly appreciated (preferably open-source)!


text:
Q: Javascript: How to prevent the next line executed until SetInterval loop has been clearinterval? Recently I'm working on a project which uses SetInterval and SetTimeout
Here's the simple code:
(Note:functionB,functionC are related to jquery ajax requests)
    function functionB() {
      jQuery.ajax({
        type: 'POST',
        url: 'https://MYHOSTNAME',
        headers: {
          'Content-Type': 'XXX',
          'Accept': 'XXX'
        },
        data: MYDATA,
        dataType: 'html',
        success: function (data, status, xhr) {
          var RESPONSEDATA = data;
          //true if match my special string
          var Compare = RESPONSEDATA.indexOf(MYSTRING) > -1;
          if (Compare === true){
              //stop the loop
              clearInterval(loop1);
          }
        }
      });
    }

    function Main(){

      functionA();//can be anything

      var loop1 = setInterval(function () {
         setTimeout(functionB, 1000);
         setTimeout(functionC, 1000);
      }, 3000);

      functionD();//can be anything

      setTimeout(Main, 16000);
    }
   main();

I'm trying to make sure functionD will only be executed once loop1 has been ended with clearInterval, it can not be executed when functionB and functionC is still in loop, and only when functionD is executed, the function Main will wait 16000ms and restart again.
I tried a lot of ways with setInterval and setTimeout but no luck.
Any javascript expert knows how to do this?

A: When you want this:

*

*running functionA()

*running functionB() and functionC() parallel every 4 seconds

*when stopped running functionB() and functionC() then run functionD once

*when functionD is finished run Main() with a delay of 16 seconds

Add a alive check for the loop
var loop1;

function functionB() {
  jQuery.ajax({
    type: 'POST',
    url: 'https://MYHOSTNAME',
    headers: {
      'Content-Type': 'XXX',
      'Accept': 'XXX'
    },
    data: MYDATA,
    dataType: 'html',
    success: function (data, status, xhr) {
      var RESPONSEDATA = data;
      //true if match my special string
      var Compare = RESPONSEDATA.indexOf(MYSTRING) > -1;
      if (Compare === true){
          //stop the loop
          clearInterval(loop1);
          loop1 = false;
      }
    }
  });
}

function aliveCheckOfLoop(){
  if(loop1){
    addTimeout(aliveCheckOfLoop, 500);
  }else{
    functionD();//can be anything
    setTimeout(Main, 16000);
  }
}

function Main(){

  functionA();//can be anything

  loop1 = setInterval(function () {
     setTimeout(functionB, 1000);
     setTimeout(functionC, 1000);
  }, 3000);

  aliveCheckOfLoop();
}

main();

A: A other approach would be to split your main function into parts and call the second part after clearing the loop.
var loop1;

function functionB() {
  jQuery.ajax({
    type: 'POST',
    url: 'https://MYHOSTNAME',
    headers: {
      'Content-Type': 'XXX',
      'Accept': 'XXX'
    },
    data: MYDATA,
    dataType: 'html',
    success: function (data, status, xhr) {
      var RESPONSEDATA = data;
      //true if match my special string
      var Compare = RESPONSEDATA.indexOf(MYSTRING) > -1;
      if (Compare === true){
          //stop the loop
          clearInterval(loop1);
          goOn();
      }
    }
  });
}

function goOn(){
  functionD();//can be anything
  setTimeout(Main, 16000);
}

function Main(){
  functionA();//can be anything

  loop1 = setInterval(function () {
     setTimeout(functionB, 1000);
     setTimeout(functionC, 1000);
  }, 3000);
}
main();


text:
Q: Проблема с vk_api, python Бот не реагирует на сообщения в чате, в чём может быть проблема?
    from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
import vk_api
import time
import random

vk = vk_api.VkApi(token='мой токен')
vk._auth_token()
vk.get_api()
longpoll = VkBotLongPoll(vk, 'айди группы')
while True:
    try:
        for event in longpoll.listen():
            if event.type == VkBotEventType.MESSAGE_NEW:
                if event.object.text.lower() == 'привет':
                    vk.method('messages.send', {'chat_id': event.chat_id, 'message': 'Привет!', 'random_id': 0})
                elif event.object.text.lower() == 'бот лох':
                    vk.method('messages.send', {'chat_id': event.chat_id, 'message': 'Пошёл ты!', 'random_id': 0})
                else:
                    vk.method('messages.send', {'chat_id': event.chat_id, 'message': 'Не понятно', 'random_id': 0})

    except Exception as e:
        print(e)
        time.sleep(1)

A: Бот работает, проверьте данные в виде: токен, ID группы.
Также не забудьте настроить LongPoll в настройках группы и выдать боту в беседе права администратора.


text:
Q: Customized ListView with scolling background EDIT: Solved this by from Java-code adding headers and footers with transparent background to the ListView.
Hi, I'm trying to make a ListView that has a gradient as a background and the content inside a frame. I have some screenshots of what I'm trying to acheive.
The first screenshots shows how I want it too look from start. The list is shown in a box with rounded corners and a green background. This is acheived by adding padding to the LinearLayout surronding the ListView. However, when I add padding on top, the scrolling looks like in the third picture, which is not what I want. The first field with name and phonenumber is a header for the listview.
Any suggestions on how to make the listview behave like this?

A: You should use Relative layout for solving this problem.


text:
Q: Sprint Rest AuthenticationPrincipal returns customUser with only null values I am trying to get the currently logged in user (basic auth) in a spring boot REST backend:
@RequestMapping(value = "/someURL", method = RequestMethod.GET)
public @ResponseBody Map someMethod(
  Authentication auth,   //  <==== works
  @AuthenticationPrincipal(expression = "liquidoUserModel") UserModel liquidoUserModel
)
{
  log.debug(auth.getPrincipal())  // <==== THIS WORKS
  log.debug(liquidoUserModel)  // <==== returns an intance with empty fields
}

Here is my custom UserModel
@Data  // Lombok magic for all the getters and setters
@Entity
@RequiredArgsConstructor
@Table(name = "users")
public class UserModel {
   @Id
   Long id;

   @NonNull
   @Column(unique = true)
   public String email;

   [...]
}

And this is my UserDetailsService
public class LiquidoUserDetailsService implements UserDetailsService {
  @Autowired
  UserRepo userRepo;

  @Override
  public LiquidoAuthUser loadUserByUsername(String email) throws UsernameNotFoundException {
    UserModel userModel = userRepo.findByEmail(email);
    return new LiquidoAuthUser(userModel.getEmail(), userModel.getPasswordHash(), getGrantedAuthorities(userModel), userModel);
  }
}

And finally the LiquidoAuthUser
public class LiquidoAuthUser extends User {
  private UserModel liquidoUserModel;

  public LiquidoAuthUser(String username, String password, Collection<? extends GrantedAuthority> authorities, UserModel liquidoUserModel) {
    super(username, password, authorities);
    this.liquidoUserModel = liquidoUserModel;
  }

  public UserModel getLiquidoUserModel() {
    return liquidoUserModel;
  }

  public void setLiquidoUserModel(UserModel userModel) {
    this.liquidoUserModel = userModel;
  }
}

And of course I have the @EnableWebMvc annotation on my main SpringApplication class.
My problem: How can I get the currently authenticated custom UserModel in the REST handler?
The strange thing: I actually can get my custom user from the Authentication auth object. Why does the @AuthenticationPrincipal not work?
I am using spring-security-4.1.3-RELEASE
Full code is open source at https://github.com/Doogiemuc/liquido-backend-spring

A: I tried and debug your code but not able to find issue of
@AuthenticationPrincipal. Typically this annotation is resolved by AuthenticationPrincipalArgumentResolver class of spring security web annotation. By using @EnableWebSecurity you will automatically have this added to your Spring MVC configuration. Need to be debug more on AuthenticationPrincipalArgumentResolver that for time being I will suggest go with Authentication class and get your object.


text:
Q: iis 7 response slow even on localhost with a text file My server (windows 2008 r2) began serving files really really slowly in IIS 7 after I rebooted the machine.
To test what was causing this I created a file "test.txt" on the site directory and accessed it via
"http://127.0.0.1/test.txt"

and it took at least 5 minutes to load, the file has the contents
"This is a test file".

I am assuming it is an IIS configuration setting, but I cannot find anything that would make it run this slow.
I also tested this in chrome dev tools, the network tab says the entire delay is "waiting (TTFB)"
Is there some configuration that affects file serving time?
I cannot find anything else that would make it run slow, cpu is less than 5% during request.

A: To answer the comments on the original question, storage was fine and everything else normal.
I even started a temporary node js server to test network speed and it was blazing fast.
No updates were installed prior to the reboot (there were 2 months earlier).
The answer ended up being to restart the machine a second time. It just "fixed itself".
Always try the dumb stuff first.. Thanks for the ideas


text:
Q: 5 blocks of volume 1 cc ,1 cc ,1 cc ,1 cc , and 4 cc are placed one above another ..... I came across this sum in an examination...
5 blocks of volume 1 cc
,1 cc
,1 cc
,1 cc
, and 4 cc are placed one above another to form a structure like this

Suppose the sum of surface areas of upper face of each block is $48 cm^2
$
.
Determine
the minimum possible height of the whole structure.

A: It is "obvious" that all the $1$ cc blocks should be the same height, though you should justify this by showing that if two differ you can reduce the height by making them the same.  Let the $1$ cc blocks have height of $h$ and the $4$ cc block have height $k$.  The overall height is $4h+k$.  The total area is $48=\frac 4h +\frac 4k$.  Solve this for one variable, plug it into the total height of $4h+k$ getting an expression in one variable, differentiate, set to zero, solve.

A: For each such block $B_k$ we have $h_k={V_k\over A_k}$, where $A_k$ denotes the area of the top surface of $B_k$. Let $B_0$ be the large block. Then
$$H:=\sum_{k=0}^4 h_k=\sum_{k=0}^4{V_k\over A_k}=4\left({1\over A_0}+{1\over4}\sum_{k=1}^4{1\over A_k}\right)\ .$$
Since the function $x\mapsto{1\over x}$ $(x>0)$ is convex we obtain
$$H\geq4\left({1\over A_0}+{1\over{1\over4}\sum_{k=1}^4 A_k}\right)=4\left({1\over A_0}+{4\over 48-A_0}\right)\ ,\tag{1}$$
with equality iff all $A_k$ $(1\leq k\leq 4)$ are equal. The RHS goes to $\infty$ when $A_0\to0+$ or $A_0\to48-$, and takes its minimum at $A_0=16$. In this case $A_k=8$ $(1\leq k\leq 4)$, and $(1)$ gives $H={3\over4}$.


text:
Q: How to avoid wobble in beamer overlay inside tcolorbox? (inside tabular) I have a table with several values witch I need to highlight during a presentation. I used tcolorbox to distinguish these data from the rest and colorbox to the highlight.
The problem is the text keeps wobbling around. As the first text gets highlighted it moves right and the second line moves down. Also there's an extra line in the tcolorbox environment which only disappears at the end.
MWE
\documentclass{beamer}
\mode<presentation>
\usepackage{fixltx2e}
\usepackage{soul}               % to striketrhourhg text
\usepackage{tcolorbox}          % fancy colored boxes

\begin{document}
\begin{frame}[c,fragile]

    \begin{tcolorbox}[colback=lightgray,
        colframe=white,
        rounded corners=all]
        \begin{tabular}{ l l }
            \only<1>{\(a=7\)  & \(cI=8\) \\}
            \only<2->{\(a=7\) & \colorbox{yellow}{\(cI=8\)} \\}

            \only<-3>{\(b=2\) & \(dS=3\)\\}
            \only<4>{\(b=2\) & \colorbox{yellow}{\(dS=3\)} \\}
            \only<5->{\colorbox{yellow}{\(b=2\)} & \(dS=3\) \\}
        \end{tabular}
    \end{tcolorbox}

\end{frame}
\end{document}

A: First of all, let's say your are asking a question about

*

*how to make \alert works like \colorbox instead of \textcolor; and

*how to stabilize these \colorboxes?

The first question is simple since Beamer provide \newcommand<>.
Now you can define a \boxalert<2,4>{} working just like \alert<2,4>{}.
\newcommand<>\boxalert[1]{
    \alt#2{\colorbox{yellow}{$#1$}}{$#1$}

For the second, make sure your contents are put inside a \colorbox all  the time:
\newcommand<>\boxalert[1]{
    \alt#2{\colorbox{yellow}{$#1$}}{\colorbox{lightgray}{$#1$}}

and the following code gives stable result:

\begin{frame}[fragile]
    \begin{tcolorbox}[colback=lightgray,colframe=white,rounded corners=all]
        \begin{tabular}{ll}
            \boxalert<2,4,6,8>{a=7} & \boxalert<3,4,7,8>{cI=8} \\
            \boxalert<5,6,7,8>{b=2} & \boxalert<      0>{dS=3} \\
        \end{tabular}
    \end{tcolorbox}
\end{frame}

If pseudo-transparent background is not desired, tcolorbox, which seems to be used by you already, gives a way to define a real transparent background:
\renewcommand<>\boxalert[1]{
    \alt#2{\tcbox[colback=yellow,frame empty]{$#1$}}{\tcbox[colback=red,opacityback=0,frame empty]{$#1$}}
}

Note that the spacing is inconsistent. I guess that is inevitable while having colorbox, beamercolorbox, and tcolorbox in the same document.


text:
Q: SQL - sort alphabetically for strings within a column I am working with postgresql and I have a table like this:
Group | Name
======================================
1     | Mary
2     | Barry,Ann,Peter
3     | Max,Chris
4     | Richard,Mary,Peter,Oliver

The table is an example, you can consider there will be more than 10,000 different names, the max number of names in one group is 4.
I want to sort the name within each group alphabetically so the result would be like this:
Group | Name
======================================
1     | Mary
2     | Ann,Barry,Peter
3     | Chris,Max
4     | Mary,Peter,Oliver,Richard

Thanks

A: SELECT t.Group, string_agg(n.names, ',' ORDER BY n.names) AS Name
FROM my_table t,
     regexp_split_to_table(t.Name, ',', 'g') n(names)
GROUP BY 1
ORDER BY 1;


text:
Q: SQL Server: How to get rows where the date is older than X years? Question
I would like to pull all assets from a database which is a certain amount of years old, in this case years. Is this statement correct?
Background
The database is called AssetRegister
The table is called dbo.Assets
the column is called AcquiredDate
Statement so far
SELECT * FROM dbo.Assets WHERE AcquiredDate < '2008-01-01'

A: SELECT * FROM dbo.Assets
WHERE DATEDIFF(YEAR, AcquiredDate, GetDate()) >= 8

For an performance optimized query look at @Horaciuxs answer.

A: SELECT * FROM dbo.Assets WHERE AcquiredDate >= '2006-01-01'

or
SELECT * FROM dbo.Assets WHERE AcquiredDate >= (year(getdate()) - 8)

A: The answer by @Juergen bring the right results:
SELECT * FROM dbo.Assets
WHERE DATEDIFF(YEAR, AcquiredDate, GetDate()) >= 8

But, the SQL optimizer can't use an index on AcquiredDate, even if one exists. It will literally have to evaluate this function for every row of the table.
For big tables is recommended to use:
DECLARE @limitDate Date
SELECT @limitDate=DATEADD(year,-8,GETDATE()) --Calculate limit date 8 year before now.

SELECT * FROM dbo.Assets
WHERE AcquiredDate <= @limitDate

Or simply:
SELECT * FROM dbo.Assets
    WHERE AcquiredDate <= DATEADD(year,-8,GETDATE())

A: CAREFUL - DATEDIFF only looks at year. Consider this query:
SELECT DATEDIFF(year,'2012-10-01','2022-06-01')

clearly the date is 9 years 8 months old but the query returns 10. So if you are deleting records >= 10 years old based on this kind of query you're in a fix....

Better to use something like this as highlighted by @Horaciux
WHERE dt > DATEADD(YEAR,-10,'20220501')

A: SELECT * FROM dbo.Assets
 WHERE YEAR(AcquiredDate) < 2008

The solution posted by juergen d and Ankit are better, but if you want to compare the Year, you can use the YEAR function.


text:
Q: configure entitydatasource with entity set that includes multiple tables I have an entity data model with two entities.  One entity called Posts contains blog posts and another entity called Comment contains comments.  I set up the association as a one to many relationship and the primary keys are both postid in both Posts and Comment.
However, when I try to bind this to an entitydatasource control it only lets me select either the Posts or the Comment entity set not both.  What I want to do is to be able to bind the post with its comments to the data source, but I can't seem to figure out a way to do this.
Any help would be appreciated!


text:
Q: Is this hashing function overkill I recently began work on a project and it contains the following function to hash passwords :
function hash_password($password) {
    $account_id = $this->account_id;

    /*
     * Cook up some randomness
     */
    $password = str_rot13($password);

    $random_chars = "1%#)(d%6^".md5($password)."&H1%#)(d%6^&HB(D{}*&$#@$@FEFWB".md5($password)."``~~+_+_O(Ed##fvdfgRG:B>";

    $salt = $account_id;
    $salt = ((int)$salt * 123456789) * 1000;

    $salt_len     = strlen($salt);

    for($i=0; $i <= $salt_len; $i++) {
        $salt .= $random_chars[$i];
    }

    $salt = str_repeat($salt, 3);

    return hash('sha256', base64_encode($password.$salt.$password), false);
}

*$account_id is unique to each user account.
My question is : Is this function any more secure than doing something as simple as :
$salt = sha1($account_id);
$hash = hash('sha256', base64_encode($password.$salt), false);

Cheers!

A: Using the account ID as a salt is probably not a good idea - if someone can steal your hashed passwords, then they can probably get the account ID's too.  Having a more convoluted hash in code in this instance is therefore probably more secure, provided that the code is also well protected.  Using a known random string as the salt in the code means that someone would have to hack both your data and your code in order to attack passwords - that has to be better than just having to attack the database alone.


text:
Q: URLEncoder: encoding string in android I am constructing String in my android app and then pass it to URLEncoder.
String searchStr;
// then I get some searchStr from shared preferences
// i check it is correct
searchStr = searchStr + "/page/"+pageNumber+"";

Then I pass that searchStr to URL encoder:
try {
  String url_params = URLEncoder.encode(params[0]);
  String result = downloadURL("some url/" + url_params);
  Log.d("key", url_params); // -> php/page/10
}catch (IOException){
  Log.d("key", e.getMessage() );
}

So here i get IOException which shows me this message:
http://some url/php%2Fpage%2F10

If I copy paste it to browser it shows me Not found error with this message:
The requested url  someurl/php/page/10 was not found on this server

Also if I change those strange sign %2F into / in browser I am able to get the page. So how can I construct proper string with / instead of %2F sign?

A: You don't encode the entire URL, only parts of it that come from "unreliable sources".
String query = URLEncoder.encode("apples oranges", "utf-8");
String url = "http://stackoverflow.com/search?q=" + query;


text:
Q: Pairwise combinations of entries in a javascript array I'm given an array of entries in javascript, such as :
var entries = ["cat", "dog", "chicken", "pig"];

I'd now like to iterate over all unique pairwise combinations of them.  In this example, I'd like to see:
("cat", "dog"),
("cat", "chicken"),
...

In other languages, like scala, this is super easy.  You just do
entries.combinations(2)

is there a similar method or function in a library for javascript?  Or do I just have to write it myself the ugly way with nested loops?

A: var arr = ["cat","dog","chicken","pig"].map(function(item,i,arr) {
    return arr.map(function(_item) { if( item != _item) return [item, _item];});
});

This will return the expected results. There are caveats, it does not work in older browsers without shims.
Also the duplicate value is 'undefined' instead of there being 4 arrays of 3. I'm sure there is a more graceful way to handle this.
Array.prototype.map() - MDN
edit
this will give you the proper pairwise combinations.
var arr = ["cat","dog","chicken","pig"].map(function(item,i,arr) {
    var tmp = arr.map(function(_item) { if( item != _item) return [item, _item];});
    return tmp.splice(tmp.indexOf(undefined),1), tmp;
});

Array splice method - MDN
and here is a more readable version of the same code.
var myArray = ["cat", "dog", "chicken", "pig"];
var pairwise = myArray.map(function(item, index, originalArray) {
    var tmp = originalArray.map(function(_item) {
        if (item != _item) {
            return [item, _item];
        }
    });
    tmp.splice(tmp.indexOf(undefined), 1); // because there is now one undefined index we must remove it.
    return tmp;
});

A: Not as far as I know. I think you have to stick to nested loops.
A similar question has been asked here: Output each combination of an array of numbers with javascript maybe you can find an answer there.

A: With ES6 syntax, one can use a shorter version of @rlemon's answer:
["cat","dog","chicken","pig"].sort().reduce(
  (acc, item, i, arr) => acc.concat(
    arr.slice(i + 1).map(_item => [item, _item])
  ),
[])

This takes care of undefineds, and also outputs only unique combinations, as per OP's question.

A: After reviewing the question, this answer doesn't correctly solve the question. The question asks for all combinations, but the function below combines all adjacent even and odd indexes of the array.
Here is a pairwise implementation I did using reduce
function pairwise(arr) {
    return arr.reduce(function(acc, current, index) {
        var isFirstPair = (index % 2) === 0;

        if (isFirstPair) {
            acc.push([current]);
        } else {
            lastElement = acc[acc.length - 1];
            lastElement.push(current);
        }

        return acc;
    }, []);
};

var nums = [1,2,3,4,5,6];

var res = pairwise(nums);

res.forEach(function(elem) {
   console.log(elem);
});

Returns:
[
  [1, 2]
  [3, 4]
  [5, 6]
]

A: Here's a generic TypeScript implementation (you can get the pure JS by removing the types):
// Returns an array of size
const sizedArray = (n: number): null[] => Array(n).fill(null);

// calls the callback n times
const times = (n: number, cb: () => void): void => {
  while (0 < n--) {
    cb();
  }
};

// Fills up the array with the return values of subsequent calls of cb
const fillWithCb = <T>(n: number, cb: () => T): T[] => sizedArray(n).map(cb);

// Generic to produce pairwise, 3 element wise etc..
const nWise = (n: number): (<T>(array: T[]) => T[][]) => <T>(
  array: T[]
): T[][] => {
  const iterators = fillWithCb(n, () => array[Symbol.iterator]());
  iterators.forEach((it, index) => times(index, () => it.next()));
  return fillWithCb(array.length - n + 1, () =>
    iterators.map(it => it.next().value)
  );
};

// curried nWise with 2 -> pairWise
export const pairWise = nWise(2);

A: The most effective and simple solution can be reduced and slice. However, if you just want to get values. You can use a generator.
// Util class
function pairWise(arr) {
     return {
         [Symbol.iterator]: function *() {
             for(let i =0; i< arr.length; i= i+2)
             yield arr.slice(i, i+2)
         }
     }
    }
 // How to use it
for(ent of pairWise([1,2,3,4,5,6, 7])){
    console.log(ent)
}
// Output
/*
[ 1, 2 ]
[ 3, 4 ]
[ 5, 6 ]
[ 7 ]
*/


text:
Q: How can I make an SBT build for multi-projects and multi-platforms? I'm starting on a medium project with many independent components that can run either on Android or the JVM and I'm wondering how to break it into SBT projects so that the dependencies behave nicely.  Here's what I've got so far:
core/ for platform agnostic core code, must not break on either platform, this includes interfaces for component launchers
android-core/ for implementations of the core interfaces that depend on android libraries  (note, this project depends on sbt-android)
jvm-core/ for implementations of the core interfaces that depend on libraries that don't play well with or depend on android
So far so good, but now it's time to consume the core projects in the individual components.  My requirements are:

*

*Each component should compile to a separate Android app (perhaps sharing an aar library?), and the apps can be individually installed (still via sbt, a la the android:install task)

*There is a wrapper build so that all project builds can be done from the same place.

*It is so easily extensible that fresh grad students can correctly add components (bonus points if adding a component needs no change whatsoever to the build).

*If a component depends on a platform specific library it does not prevent other components from being compiled agnostically.

Some of the questions I have are:

*

*Should each component have an sbt project?  (I'm inclined to think so so that students could add dependencies on libraries that don't run on both platforms, but I'm open to being wrong)

*If so, will each component's project require an sbt build?

*If so, how can I bootstrap the component builds to require minimum skill from the component author?

*Later I'm going to be adding code generation to generate message classes from descriptions (think protobuf/thrift), that will want to run as a first pass before the components get compiled, I'm assuming this can be done, but do you have a link that explains how?

*If two components each compile against the messages of each other will that create impossible circular dependencies?

Basically I'm looking for wisdom and experience, the nitty gritty code I'm sure I can hack my way through once I know what terms to search the docs to understand and roughly how the whole thing wants to hang together.  Thanks for your help!


text:
Q: Find a number $a$ such that $f(x)=\sin(x+\pi/4)$ with $a\leq x\leq a+\pi,$ has an inverse Sorry, this question looks trivial but it's actually from someone close by.

Find a number $a$ such that the function $f(x)=\sin(x+\pi/4)$ with domain $a\leq x\leq a+\pi$ has an inverse

My trial
Let $y=f(x)$, then \begin{align}y=\sin(x+\pi/4)&\iff x+\pi/4=\arcsin y\iff x=\arcsin y-\pi/4\\&\quad f^{-1}y=\arcsin y-\pi/4.\end{align}
However, how do I deal with the interval $a\leq x\leq a+\pi$, to get the requested value of $a?$

A: The function $\sin:[-\pi/2,\pi/2]$ is injective, so you need that
$$-\frac\pi2=a+\frac\pi4$$
Of course you can start with any interval where $\sin$ is injective, like $[\pi/2,3\pi/2]$, etc.


text:
Q: Regular expression including special characters I'm trying to create an array of elements drawn from a regular expression that include punctuation symbols, but I get only get a single value.
Thi is the String Example
'00000002 BLABLA'<MADRID CENTRO>,'00000006 FAFAFAFA'<BARCELONA ORIENTE>,'00000919 HUAWEI'<LA CANDELA>,

I want an array like those values, including separators:
'00000002 BLABLA'<MADRID CENTRO>,

My wrong regular expression:
 regex = /^'[0-9]{8}\s[a-zA-Z\'{1}]*[\<{1}a-zA-Z\>{1}]*/;

A: How about
var re = /'\d{8} [a-z]+'<[^>]+>,/ig

str.match(re);
/*  [
       "'00000002 BLABLA'<MADRID CENTRO>,",
       "'00000006 FAFAFAFA'<BARCELONA ORIENTE>,",
       "'00000919 HUAWEI'<LA CANDELA>,"
    ] */

A: because you are using ^
use this :
''[0-9]{8}\s[a-zA-Z\'{1}]*[\<{1}a-zA-Z\>{1}][^,]+,/g

demo here :  http://regex101.com/r/nZ7nZ9
check this out :
var str = "'00000002 BLABLA'<MADRID CENTRO>,'00000006 FAFAFAFA'<BARCELONA ORIENTE>,'00000919 HUAWEI'<LA CANDELA>,";
var res = str.match(/('[0-9]{8}\s[a-zA-Z\'{1}]*[\<{1}a-zA-Z\>{1}][^,]+,)/g);
console.log(res);

o/p:
["'00000002 BLABLA'<MADRID CENTRO>,", "'00000006 FAFAFAFA'<BARCELONA ORIENTE>,", "'00000919 HUAWEI'<LA CANDELA>,"]

A: This regex works for me:
'[0-9]{8}\s[a-zA-Z\'{1}]*[\<{1}a-zA-Z\s\>,{1}]*

You should use this tool to test regex : http://www.gethifi.com/tools/regex
EDIT: like @aelor said, you're using ^ which will only match with a start of line. I also add \s to catch whitespaces in the last part of your expression (like

A: Your errors:

*

*You've used the start-of-line anchor (^). Of course you only ever get one match: the one at the start of the line.

*You seem to think that character classes ([]) are some form of grouping. They are not.

*Angle brackets have no meaning in JS regular exressions, you don't have to escape them.

*You say you want to match the separators but you did not include them in your expression

*You did not use the global modifier (g)

*You could use the case-insensitive modifier (i)

Better
var regex = /'[0-9]{8}\s[a-z]*'<[a-z ]*>,/ig;

In any case: It could be that you're over-specific. What about:
var regex = /'[^']*'<[^>]*>,/g;

Overly specific regular expressions are hard to debug and maintain while providing no real benefit. (Careful with not-specific-enough expressions, though. Find the right balance.)


text:
Q: Using asset pipeline to include a javascript file in rails 4 project I added a simple Javascript file to my rails project beer_background.js and put the file in app/assets/javascripts  I want to load the beer_background.js when the application.html.erb is rendered, so I put the following line in the application.html.erb
<%= javascript_include_tag('beer_background.js') %>
However this is causing the rails app to produce error that looks like the following.

Update
application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require turbolinks
//= require_tree .
//= require d3

A: You shouldn't have to use javascript_include_tag. Having the files in the location you do and //= require_tree . in your application.js should be enough.
http://guides.rubyonrails.org/asset_pipeline.html#manifest-files-and-directives

The require_tree directive tells Sprockets to recursively include all JavaScript files in the specified directory into the output. These paths must be specified relative to the manifest file. You can also use the require_directory directive which includes all JavaScript files only in the directory specified, without recursion.

A: You should include your javascript file from within the application.js file:
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require turbolinks
//= require d3
//= require beer_background

or use //= require_tree . which will include all assets under the current directory


text:
Q: required field error not appearing When using this code to try an show an error, the page redirects to myaccount, but should only redirect there if the required field has been completed, for example;
error message appears if birth_country is not chosen
if(empty($birth_country))
    {
        $err[] = "ERROR - Enter Birth Country";
           header("Location: personal.php?msg=$err[0]");
    }

but if it is chosen, should redirect to...
header("location: myaccount.php?id=" . $_SESSION['user_id']. "");
exit();

However it always goes to myaccount no matter what
Thanks

A: After your first header put exit as well. Your code just continues on and it likely emits the second location header as well, negating the first.

A: Like Frits says, you will have to print out the error to the screen if you want it to be seen; however, you can not print out any HTML before a header or the header won't work.  If you want to print the error on the redirecting page then I would suggest putting the error message in a $_SESSION cookie, then call and echo that cookie/variable on the redirecting page.  But by doing this, you will need to use php session_start() at the top of the question page and the top of your redirect page in order to use the $_SESSION variables
Also, your second header
header("location: myaccount.php?id=" . $_SESSION['user_id']. "");
exit();

Should look like this:
header("Location: myaccount.php?id=$_SESSION['user_id']")

By using the double quotes, you don't need to add the $_SESSION[] tag, then add blank "" at the end.


text:
Q: Facebook graph check if a photo post has a single or multiple photos I'm trying to parse the posts of a facebook page using graph API and here's the sample json output:
{
    "posts": {
        "data": [
            {
                "message": "post1",
                "object_id": "786625684729323",
                "type": "photo",
                "updated_time": "2014-10-19T16:59:07+0000",
                "id": "381290831929479_786636778061547",
                "created_time": "2014-10-19T16:59:07+0000"
            },
            {
                "message": "post2",
                "object_id": "778854645506427",
                "type": "photo",
                "updated_time": "2014-10-19T16:09:04+0000",
                "id": "381290831929479_786616228063602",
                "created_time": "2014-10-19T16:09:04+0000"
            }
        ]
    }
}

Multi-photo upload is when you upload more than one picture and it will appear on the news feed that you've added X photos in an album.
The first post is a multi-photo upload but if I will get the picture using the object_id, it will only return the first picture uploaded. The second post is a single photo upload which works fine. How do you determine if a photo post contains more than one picture? and if it is a multi-photo post, how do you get the object_id of the other pictures?

A: Recently I came across this situation in my app and this is how I handle. You get only first picture URL in your feed in picture or full_picture parameter in your feed section.
If you add photo in your post, you will get an object_id value for that, so don't confuse with that.
Add link parameter in your feed section, which gives you the number of photos that the user has uploaded in their post using the count. Refer below link.
https://www.facebook.com/photo.php?fbid=806635336044169&set=pcb.806635264577497&type=1&relevant_count=2
Now you got the number of photos you have posted in that particular post. Also get the created_time API as of now. Like this,
me?fields=id,name,feed{created_time,link}
Save the created_time parameter value and now go to photos section in albums. And pass the parameters as,
me?fields=id,name,albums{photos,created_time}
Match the created_time value in the photos section and get the photo's related to that post. As of now, am working on this way and its working fine. Sometimes I get one minute delay in post photos created_time. You also need to handle this. Hope it helps you as of now and I get you once I get proper parameter to handle this situation.


text:
Q: IOS Swift IBAction behaviour when combining actions I have a custom keyboard extension which works as expected but I am coming across some odd behaviour which I can't explain. It is designed primarily for data input into Excel spreadsheets, so the fewer the keystrokes the better.
I have 2 IBActions.
Keypressed takes the value of the keypresses and inserts it into the current cell.
Returnpressed emulates the enter key which moves the cursor onto the next cell.
These work as described above, which is all good, but I am now trying to combine the actions, so that the user only has to press the first key and it inserts the text and then moves onto the next cell.
So when I simply extend the code in the Keypressed IBAction to include the code in the Returnpressed action, it simply inserts a carriage return into the text and stays in the same cell.
What am I missing please?
Here is a code snippet:
extension UIKeyInput{
    func `return`() -> Void{
        insertText("\n")
    }

}

class KeyboardViewController: UIInputViewController, AVAudioPlayerDelegate {

@IBAction func KeyPressed(_ sender: Any) {

    let string =  (sender as AnyObject).titleLabel??.text

    (textDocumentProxy as UIKeyInput).insertText("\(string!)")

    **//THIS IS THE LINE THAT FIXED THIS FOR ME
    textDocumentProxy.adjustTextPosition(byCharacterOffset: -1)**

    self.EnterPressed(nil)

}

@IBAction func EnterPressed(_ sender: Any?) {

    //default action for a return key press
    textDocumentProxy.return()

}

A: I think you need to override the UITextInputDelegate textDidChange method (UIInputViewController implements UITextInputDelegate).It turns out that textDidChange is called when the text changes. And make the first responder to the next text field of your cell.

A: I managed to fudge this by determining what action s caused textDidChange to fire. It turns out that by simply adjusting the cursor portion, between inserting the text and firing the Return action works.
Not really sure how, but achieves what I want without the the user knowing it is a kludge and no overhead. I have changed the original code snippet to show the fix.


text:
Q: What's Xiaomi Mi Store app's page intent? I'm developer of an Android library for rating apps, which asks user if he likes an app, and if he wants to rate the app redirects it to the app store.
Does someone know, what's Xiaomi Mi Store's launch intent for redirecting user right to the given app?
For example, for Google Play it's:
val intent = Intent(Intent.ACTION_VIEW).apply {
    data = Uri.parse(
            "https://play.google.com/store/apps/details?id=com.example.android")
    setPackage("com.android.vending")
}

A: Well, finally I've got an answer from the Xiaomi Developer support:

The link below could be used to open GetApps and take to the app page,on condition that the user has already installed GetApps.
Link:  mimarket://details?id=packagename&back=true|false&ref=refstr&startDownload=true
Note: you could replace the package name with yours

So I guess we have to use this code:
val intent = Intent(Intent.ACTION_VIEW)
   .apply {
      data = Uri.parse("mimarket://details?id=com.example.android&back=true|false&ref=refstr&startDownload=true")
}


text:
Q: Invalid Cast Exception, json, windows phone Hi Why am i getting an inalid cast exception?
    public class RootContainer2
    {
            [DataMember]
            public string StopName { get; set; }

            [DataMember]
            public string StopId { get; set; }

            [DataMember]
            public string Stop { get; set; }

            [DataMember]
            public ObservableCollection<Stops> Stops { get; set; }
    }

        private void ContentPanel_Loaded(object sender, RoutedEventArgs e)
        {
            textRouteId.Text = this.NavigationContext.QueryString["name"];

            string myvar = textRouteId.Text;

            try
            {
                WebClient webClient = new WebClient();
                Uri uri = new Uri("websiteurl");
                webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
                webClient.OpenReadAsync(uri);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            DataContractJsonSerializer ser = null;

            try
            {
                ser = new DataContractJsonSerializer(typeof(RootContainer2));
                RootContainer2 rootContainer = ser.ReadObject(e.Result) as RootContainer2;
                foreach (Stops em in rootContainer.Stops)
                {

                    string df = em.StopName;
                    string dt = em.StopId;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

Here is the json output which I am trying to read but I get an invalid cast exception.
{"RouteId": "1231", "RouteName":"1 Whitehawk - Mile Oak", "Stops": [ { "StopId":"6882", "StopName":"Swanborough Drive", "OperatorsCode4":"bridmpj", "Lat":"50.8326729229821", "Lng":"-0.103217996656901" } , { "StopId":"6883", "StopName":"Haybourne Road", "OperatorsCode4":"brimapm", "Lat":"50.8317788816436", "Lng":"-0.10486427645364671" } , { "StopId":"6884", "StopName":"Coolham Drive", "OperatorsCode4":"brijtwm", "Lat":"50.829695439856089", "Lng":"-0.10512229365031489" } , { "StopId":"6885", "StopName":"St Cuthmans Church", "OperatorsCode4":"briapdg", "Lat":"50.8283233642578", "Lng":"-0.104808002710342" } ,

Plus the class in stops.cs :
public class Stops
{
    public string StopId { get; set; }
    public string StopName { get; set; }
}

EDIT:
So after creating my own url and then testing the data, it's something to do with the URL that I was given I think. Just doing further testing.
Edit 2
If i put the data into a text file and debug the data, it works if i do the following.
the end of the feed is like this:
"Lng":"-0.277833998203278", "" } ] }
If  i remove the , and "" then it works. but how do i stop it getting there in the first place?

A: ReadObject() takes a Stream (or some XML-related types) but e.Result is of type object.
Try:
RootContainer2 rootContainer = ser.ReadObject((Stream)e.Result) as RootContainer2;

Edit:  On second thoughts, that would probably throw an Invalid Parameter exception rather than an Invalid Cast.
Looks like the object being returned by ReadObject() is not castable to type RootContainer2.

A: The exception could be caused by missing [DataContract] and [DataMember] attributes, in particular on the Stops class. With the exception of Silverlight 5, DataContract is an opt-in model where all classes and properties that should be serialized have to carry a explicit attribute.
Update:
After your comment, I've looked in more detail into the JSON data you receive. You provide two pieces of JSON. If combined, they look like this:
{
    "RouteId": "1231",
    "RouteName": "1 Whitehawk - Mile Oak",
    "Stops": [
        {
            "StopId": "6882",
            "StopName": "Swanborough Drive",
            "OperatorsCode4": "bridmpj",
            "Lat": "50.8326729229821",
            "Lng": "-0.103217996656901"
        },
        {
            "StopId": "6883",
            "StopName": "Haybourne Road",
            "OperatorsCode4": "brimapm",
            "Lat": "50.8317788816436",
            "Lng": "-0.10486427645364671"
        },
        {
            "StopId": "6884",
            "StopName": "Coolham Drive",
            "OperatorsCode4": "brijtwm",
            "Lat": "50.829695439856089",
            "Lng": "-0.10512229365031489"
        },
        {
            "StopId": "6885",
            "StopName": "St Cuthmans Church",
            "OperatorsCode4": "briapdg",
            "Lat": "50.8283233642578",
            "Lng": "-0.277833998203278",
            ""
        }
    ]
}

I'm afraid this is simply invalid for JSON. As you found out yourself there is an extra comma and an extra emtpy pair of quotes close to the end. They make the difference between correct and invalid JSON. You can check it with an onlne JSON validator like JSONLint.
The best solution would be if you could fix it on the server side. Otherwise it's probably best to try to fix the data before you passed it into the serializer.


text:
Q: Is there a simpler way to get three numbers from the user and print them in ascending order? I'm working through the exercises in Bjarne Stroustrup's book "Principles and Practice Using C++" (chapter 3 exercise 6). You're asked to make a program that takes user input (3 integer values) and prints the 3 values in order from smallest to largest. Here's my solution,
#include <iostream>
#include <string>
using namespace std;

int main()
{
    cout << "Please enter 3 integers: ";
    int num1, num2, num3;
    while (cin >> num1 >> num2 >> num3) {

    if (num1 < num2 && num2 < num3)
        cout << num1 << ", " << num2 << ", " << num3 << endl;

    if (num2 < num1 && num1 < num3)
        cout << num2 << ", " << num1 << ", " << num3 << endl;

    if (num3 < num1 && num1 < num2)
        cout << num3 << ", " << num1 << ", " << num2 << endl;

    if (num1 > num2 && num1 > num3 && num2 < num3)
        cout << num2 << ", " << num3 << ", " << num1 << endl;

    if (num1 > num2 && num1 > num3 && num2 > num3)
        cout << num3 << ", " << num2 << ", " << num1 << endl;

    if (num1 < num2 && num1 < num3 && num2 > num3)
        cout << num1 << ", " << num3 << ", " << num2 << endl;

    if (num1 == num2 && num1 < num3)
        cout << num1 << ", " << num2 << ", " << num3 << endl;

    if (num1 == num3 && num3 < num2)
        cout << num1 << ", " << num3 << ", " << num2 << endl;

    if (num1 == num2 && num1 > num3)
        cout << num3 << ", " << num2 << ", " << num1 << endl;

    if (num1 == num3 && num2 < num3)
        cout << num2 << ", " << num3 << ", " << num1 << endl;

    if (num3 == num2 && num1 < num3)
        cout << num1 << ", " << num2 << ", " << num3 << endl;

    if (num3 == num2 && num1 > num3)
        cout << num3 << ", " << num2 << ", " << num1 << endl;
   }
}

Although this worked for me, it just looks like a lot of code and I would really appreciate a more "simple" take on the problem.

A: You can add the values to a vector, then sort it, and output the values in order.
#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    std::cout << "Please enter 3 values" << '\n';
    std::vector<int> values;
    for (int i = 0; i < 3; ++i)
    {
        int value;
        std::cin >> value;
        values.push_back(value);
    }
    std::sort(values.begin(), values.end());
    std::cout << values[0] << ", " << values[1] << ", " << values[2] << '\n';

    return 0;
}

A: If you were to store the numbers in a sequential data structure (array, lits, deque) instead of separate variables then a simpler algorithm is possible:

*

*Sort the sequence.

*Print the sequence in order.

C++ standard library has an algorithm for sorting: std::sort.

A: Functions can help reduce redundancy. You can create a function to take three numbers and print them out in order.
void PrintNumbers(int a, int b, int c) {
    cout << a << ", " << b << ", " << c << endl;
}

Then all you would have to do is call the method and pass the numbers in a different order instead of rewritting your print logic every time. Exmaple
PrintNumbers(num1, num2, num3);
PrintNumbers(num2, num3, num1);
PrintNumbers(num3, num2, num1);

Also, if you look into using arrays, you can create a sort method that takes an array and returns a sorted array. Alternatively, if you look into passing variables by reference (instead of by value). Then you can write a method that will make it so num1 is always the smallest, num2 is always the middle, and num3 is always the largest. This would allow you to basically
Having these two methods (One to sort, and one to print) would turn  this part of your main function into basically two lines of code.
SortNumbers(num1, num2, num3);
PrintNumbers(num1, num2, num3);

Or if you use arrays (and if you can, I recommend that you do)
int[] sortedNumbers = SortNumbers(myNumbers);
PrintNumbers(sortedNumbers);

A: You can do something like this:
int main()
{
    std::vector<int> values;

    for (int i = 0; i < 3; ++i)
    {
        int value;
        std::cin >> value;
        values.push_back(value);
    }
    std::cout << std::fminf(std::fminf(values[0], values[1]), values[2]);
    std::cout << std::fmaxf(std::fminf(values[0], values[1]), std::fminf(values[1], values[2]));
    std::cout << std::fmaxf(std::fmaxf(values[0], values[1]), values[2]);

}

A: Some rules.
If you have a bunch of data you want to treat uniformly, except possibly order-wise, you want to use an array.
If you want to place things in a particular order, you sort them.
If you don't need them unsorted afterwards, you sort them in place.
And don't using namespace std; it is a really bad habit.
std::cout << "Please enter 3 integers: ";
int num[3]; // an array of 3 integers
while (std::cin >> num[0] >> num[1] >> num[2] {
  std::sort( std::begin(num), std::end(num) );
  std::cout << num[0] << ", " << num[1] << ", " << num[2] << "\n";
}

std::endl both inserts a newline and flushes the io buffer.  Only do it when you really, really want to flush the buffer.
We can improve the above further:
enum {count = 3};
int num[count]; // an array of 3 integers
std::cout << "Please enter " << count << " integers: ";
while ( [&]{
  for (int& n:num)
    if (!std::cin >> n) return false;
  return true;
}()) {
  std::sort( std::begin(num), std::end(num) );
  for (int& n:num) {
    if (&n != num) std::cout << ", ";
    std::cout << n;
  }
  std::cout << "\n";
}

and now I can change how many integers I'm working with by changing count at one spot.  There are 4 numbers in computer science: 0, 1, 2 and infinity.
Now, here we hard-code how many integers at compile time.  This is sometimes a good idea, sometimes not.
std::size_t count;
std::cout << "How many integers at a time?";
if (!std::cin >> count) return -1;
std::vector<int> num(count); // an array of count integers
std::cout << "Please enter " << count << " integers: ";
while ( [&]{
  for (int& n:num)
    if (!std::cin >> n) return false;
  return true;
}()) {
  std::sort( std::begin(num), std::end(num) );
  for (int& n:num) {
    if (&n != num.data()) std::cout << ", ";
    std::cout << n;
  }
  std::cout << "\n";
}

This now asks the user how many integers per clump.

A: My solution without using the array:
void order_integer() {
    int a, b, c;
cout << "Enter 3 integers: \n";
cin >> a >> b >> c;
if (a <= b && a <= c) {
    if (b <= c) cout << a << ' ' << b << ' ' << c << endl;
    if (c <= b) cout << a << ' ' << c << ' ' << b << endl;
}

else if (b <= a && b <= c) {
    if (a <= c) cout << b << ' ' << a << ' ' << c << endl;
    if (c <= a) cout << b << ' ' << c << ' ' << a << endl;
}

else if (c <= a && c <= b) {
    if (a <= b) cout << c << ' ' << a << ' ' << b << endl;
    if (b <= a) cout << c << ' ' << b << ' ' << a << endl;
}

}


text:
Q: Puppet notify, before, require not working as intended I'm trying to create a relationship between a service resource and two exec resources. The service should trigger the Exec['before'] when something changes and start the Exec['after'] when the service has been modified.
class foobar (
$debug = true
) {

    service { "sshd":
        ensure => 'stopped',
        notify => Exec['before']
    }

    exec { "before":
        command => "/bin/echo before",
        refreshonly => true,
    }

    exec { "after":
        refreshonly => true,
        command => "/bin/echo after",
    }

}

I've tried literally everything but the Exec['before'] keeps getting triggered after the service:
Notice: Compiled catalog for puppet.puppettest.local in environment production in 0.55 seconds
Notice: /Stage[main]/Foobar/Service[sshd]/ensure: ensure changed 'running' to 'stopped'
Notice: /Stage[main]/Foobar/Exec[before]: Triggered 'refresh' from 1 events
Notice: Applied catalog in 0.04 seconds

How can I make sure that the Exec['before'] runs before the service but only if there have been changes to the service and not with every run?
kr

A: Your metaparameters are not correct. By setting ThingA to notify ThingB you are telling Puppet that ThingA must run before ThingB. Things which are refresh_only => true are going to be tricky to have execute before anything else, because they need something to have run first, in order to refresh them.
If you want your order to be Exec['before'] -> Service['sshd'] -> Exec['after'] you'll need to do something like this.
class foobar (
    $debug = true
) {

    service { "sshd":
        ensure  => 'stopped',
        notify  => Exec['after'],
        require => Exec['before'],
    }

    exec { "before":
        command => "/bin/echo before",
        onlyif  => "some command that helps determine if this should run",
    }

    exec { "after":
        command     => "/bin/echo after",
        refreshonly => true,
    }

}


text:
Q: Does the number of proucts in magento affect the performance of website? If a website is having thousands of products.
Will it be affecting performance of website or page load time?

A: No..It doesn't .. If you try to load all the products(1000), then it will be slow or cannot be load due to the memory limit. But we always load less no of products in front end at a time.

A: I have to ay it does it, Recently my store slows down, and i got a call with magento support team, and they said me the problem was that i had more than 150K products.
So, yes, it is affect the store performance.
Greetings.

A: I think this link may help you in your answer and what you can do to help prevent your site slowing down
https://magento.stackexchange.com/questions/3652/is-magento-the-right-platform-for-1m-products