text:
Q: Examples of practical usage of Boost::MPL? Can you share any real-world examples of Boost::MPL usage (except lambdas), just to let me better understand its purposes and field of practical usage? The MPL documentation tutorial has a dimensional analysis example, but maybe because it's such an academic example it hasn't given me a feeling of Boost::MPL and when it can be effectively used.

A: I use a more enhanced dimensional analysis library called Boost.Units.
I've developed a compile-time reflection library and then used that library to build a generic class that provides runtime-reflection to any compile-time reflected type passed in.  I've used that support to automatically generate UI components to edit the properties of such reflected types.
It's also paramount to the distribution of events within our application.  For instance, when someone changes the units they wish the system to be in, I don't have to teach that system that new items have been added to given devices because the code uses MPL to analyze those types and just knows that something's been added and changes it.
I've just used metaprogramming techniques to wrap up the Qt signals into something that regains the type safety removed by their system and is able to connect with any functional entity.
But to tell the truth, you've almost certainly used practically applied metaprogramming techniques already when you've used standard algorithms like sort.  A decent implementation of the sort algorithm uses a less evolved form of metaprogramming to analyze the iterators passed in and then uses tag-dispatching to initiate a sort algorithm capable of fully utilizing the features of those iterators.
Quite frankly, if you're not doing metaprogramming then you're not utilizing the power of C++ and you may as well be using something else.

A: When it comes to build matching engine, mostly for Exchange or DarkPool in trading area, we usually need to check if 2 orders could match or not (or we say could cross or not), there could be many aspects to check which we call as Rules, and here are the key requirements in term of organizing these rules:

*

*It should be easy to add a new rule and get applied

*It should be convenient to organize rules into different groups to apply the checks

*Because the rule check are invoked quite frequently - well, of couse, that is the sole job of a matching engine, we want it as optimal as possible

This is a great fit to use boost mpl, which could use compile time sequence boost::mpl::vector  to organize rules, and get them applied with boost::mpl::for_each.
The idea is best illustrated with an example:

*

*It is straightforwrad to add a new rule by simply defining a new Rule class

*It is convenient to group rules using boost::mpl::vector, and use it as a template parameter for canCross check

*Because most of the setting up work are done in compile time, it is fast.

#include <iostream>
#include <vector>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/for_each.hpp>

using namespace std;

struct Order {};

struct Rule1
{
    const char* name() const { return "Rule1"; }
    bool apply(const Order& a, const Order& b) const {  cout << "Checking Rule1..." << endl; return true; }
};

struct Rule2
{
    const char* name() const { return "Rule2"; }
    bool apply(const Order& a, const Order& b) const {  cout << "Checking Rule2..." << endl; return false;}
};

struct Rule3
{
    const char* name() const { return "Rule3"; }
    bool apply(const Order& a, const Order& b) const {  cout << "Checking Rule3..." << endl; return false;}
};

struct Rule4
{
    const char* name() const { return "Rule4"; }
    bool apply(const Order& a, const Order& b) const {  cout << "Checking Rule4..." << endl; return true;}
};

struct RuleApplicator
{
    RuleApplicator(bool& success, std::vector<const char*>& failedRules, const Order& order1, const Order& order2):
        _success(success),
        _failedRules(failedRules),
        _order1(order1),
        _order2(order2)
    {}
    template <typename U> void operator() (U rule)
    {
        if(!rule.apply(_order1, _order2))
        {
            _success = false;
            _failedRules.push_back(rule.name());
        }
    }

private:
    bool& _success;
    std::vector<const char*>& _failedRules;
    const Order& _order1;
    const Order& _order2;
};

template <class Rules>
bool canCross(const Order& a, const Order& b)
{
    bool success = true;
    std::vector<const char*> failedRules;
    RuleApplicator applicator(success, failedRules, a, b);
    boost::mpl::for_each<Rules>(applicator);
    if (!success)
    {
        cout << "Can't cross due to rule check failure:";
        for(const char* ruleName: failedRules)
        {
            cout << ruleName << " ";
        }
        cout << endl;
        return false;
    }
    else
    {
        cout << "Can cross!" << endl;
        return true;
    }
}

int main(int argc, char** argv)
{
    Order a, b;
    canCross<boost::mpl::vector<Rule1, Rule4>>(a, b);
    cout << endl;
    canCross<boost::mpl::vector<Rule1, Rule2, Rule3, Rule4>>(a, b);
}

You will see output as:
Checking Rule1...
Checking Rule4...
Can cross!

Checking Rule1...
Checking Rule2...
Checking Rule3...
Checking Rule4...
Can't cross due to rule check failure:Rule2 Rule3

A: If your application has heavy logic in dealing with key-value pairs, you will need a ultra efficent way to get value from key, typical hashmap works well, but if possible keys are known upfront, optimzation could be done use boost::mpl, with an array, and a method to convert your key to array index at compile time, this is certainly more efficent.
Here is an example on handling fix message, which is a message contains various key-value pairs, it is used heavily in financial trading applications:
#include <iostream>
#include <array>
#include <string>
#include <unordered_set>
#include <boost/mpl/vector_c.hpp>
#include <boost/mpl/find.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/integral_c.hpp>
#include <boost/mpl/size.hpp>

using namespace std;
using namespace boost;

struct TagEntity
{
    bool isValid;
    std::string value;
};

template<class CommonTags>
struct FixMsg
{
    static constexpr uint32_t CommonTagsCount = mpl::size<CommonTags>::type::value;

    template<int Tag>
    constexpr uint32_t index()
    {
        constexpr auto idx = mpl::find<CommonTags, mpl::integral_c<int, Tag>>::type::pos::value;  // this is the key step: convert tag to index in compile time
        static_assert(idx < CommonTagsCount, "tag not found");
        return idx;
    }
    template<int Tag>
    TagEntity& getTagEntity()
    {
        return _commonTags[index<Tag>()];
    }

    std::array<TagEntity, CommonTagsCount> _commonTags; // or else use std::unordered_set, which is not as fast as this approach: absolute O(1) in runtime
};

int main(int argc, char** argv)
{
    using MyCommonTags = mpl::vector_c<int,
          11,
          35,
          10914,
          10916>;

    FixMsg<MyCommonTags> fixMsg;
    auto& tagEntity = fixMsg.getTagEntity<11>();
    tagEntity.isValid = true;
    tagEntity.value = "Get tag entity in O(1)";

    cout << tagEntity.value << endl;

A: I use boost::mpl (and boost::fusion) extensively in my stat_log library.  This library allows the user to specify a hierarchy of statistic and logging tags and their associated behaviors, i.e. per-tag statistic types (histogram, counter, etc).
I rely heavily on metaprogramming to do the right thing with the user does:
stat_log::writeStat<IP_PKTS_RCVD>(450);

For example if the user defines the type trait:
template <>
struct stat_tag_to_type<IP_PKTS_RCVD>
{
   using type = Accumulator<
        stat_log::HistogramCount<
            int,
            1, //start bin
            1500, //stop bin
            10 //num_bits
        >
     >;
};

the "writeStat" call above will proxy (at compile time) to a histogram statistic.  The powerful aspect of this design technique is the "writeStat" call site is not at all coupled with the particular statistic chosen.
I also use a wealth of MPL and boost::fusion to actually view the stats.  Per your question, see the following files for the highest concentration of boost::mpl:
https://github.com/rjmccabe3701/stat_log/blob/master/include/stat_log/util/stat_log_impl.h
https://github.com/rjmccabe3701/stat_log/blob/master/include/stat_log/util/tag_commander.h
https://github.com/rjmccabe3701/stat_log/blob/master/include/stat_log/stat_log.h
especially the nifty template meta "function" in stat_log_impl.h:
//This template is used in conjunction with an MPL algorithm
// with the same semantics as mpl::find_if.
//BoolFunc is the "condition" metafunction.
//StatTagFunc is a metafunction that transforms the given
//   stat_tag into something the algorithm requires.
//   For example the "Identity" metafunction would work here.
//StatTagArgs is extra arguments to the BoolFunc
template <template<typename...> class BoolFunc,
          template<typename...> class StatTagFunc,
          class... StatTagArgs>
struct tag_node_query
{
   template<typename TheTagNode>
   struct apply
   {
      using stat_tag = typename TheTagNode::tag;
      using type = std::integral_constant
         <
            bool,
            BoolFunc<
               typename StatTagFunc<stat_tag>::type,
               StatTagArgs...
            >::value
         >;
   };
};

A: To add to Matthieu's answer, it's also used quite extensively throughout both Boost.Python and Luabind.

A: Something funny I did:
https://github.com/edubois/static-factorial/blob/master/main.cpp
It uses a tiny part of boost::mpl to statically compute the value of factorial<8>()...
This can help to understand the main idea.

A: I've used Boost.Mpl to generate variant-like classes.
For example, given a MPL type list such as this:
typedef boost::mpl::set<Foo, Bar, Baz> type_set;

I then use boost::mpl::fold to build a chain of classes derived from each others which each adds an std::unordered_set of one of the types in the type set. The end result is a class which contains an unordered_set<Foo>, an unordered_set<Bar> and an unordered_set<Baz>.
And because the class is specified in terms of a boost::mpl::set, I can iterate over these types to automatically generate other functions as well, such as an operator== which compares all of the unordered_sets.

A: The fact is, Boost.MPL, like Boost.Preprocessor, are really building blocks.
Most of the times, you probably use it through other libraries, as a number of Boost libraries are built upon those two.
For example:

*

*Boost.Fusion (which crosses the gaps between compile-time and run-time realms)

*Boost.MultiIndex (for an easier interface)

*Boost.Unit (for dimensional analysis)

*Boost.Variant may, I think, also depends on it

You may use it unknowningly already :)


text:
Q: Wordpress Menu dropdown parent item clickable just after opening dropdown I am currently developing a website and I need to make my dropdown menu parent item clickable. I have modified the wp-bootstrap-navwalker.php file to :
        // If item has_children add atts to a.
if ( $args->has_children && $depth === 0 ) {
   $atts['href'] = ! empty( $item->url ) ? $item->url : '';
   //$atts['data-toggle']   = 'dropdown';
   $atts['class']           = 'dropdown-toggle';
} else {
   $atts['href'] = ! empty( $item->url ) ? $item->url : '';
}

Code which adds indeed a link to my parent item, but that is only happening after I open the dropdown - So if I want tot open the link to the whole category(Parent Item) i have to click twice, once for opening dropdown and the second time for actually going to the link.
I think it may be a theme problem that is having some loading order code but I do not actually know where, the theme I am using is Uncode.
After using that code, on Inspect element i do not see the data-toggle information, so it worked, but not quite.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to grep for quotation symbol (") I have this code:
> head(row.names(django_c1))
[1] "10" "16" "25" "26" "28" "48"
> row.names(django_c1) <- gsub("\"", "", row.names(django_c1))
> head(row.names(django_c1))
[1] "10" "16" "25" "26" "28" "48"

What I am trying to do is to delete all the quotation marks ("), however, it doesn't seem to work.
I have also tried:
row.names(django_c1) <- as.numeric(row.names(django_c1))

and:
row.names(django_c1) <- gsub(""", "", row.names(django_c1))

But none of these seem to work either. How can I delete the quotation marks?

A: You have this display because the result of rownames is a vector of character strings typeof()=="character", so R displays " around it to show that fact.
If you do head(django_c1) you won't see them.
Row and colum names are always character strings, if you want to access by arbitrary index, either use a list (but you will probably create issues since list[[2]]=0 automatically creates list[[1]]=NA) or use django_c1[str(custom_index),].
Precision : gsub('"', '', string) will perfectly remove " from your string if they are really part of your string, which means 'hey"' (displayed "hey\"") becomes 'hey' (displayed "hey"). The distinction must be clear between the content of the string and the way it is displayed.


text:
Q: PHP RSS feed help gettiong XML tags to apprear I'm using the following code to generate an RSS feed for my site. When I run the code, I get an error: Error on line 1 at column 14: XML declaration allowed only at the start of the document. If I take out the header(), the page runs, but the data is not formatted correctly, including the whole data array. When I ask for an RSS feed from my Word-Press site, I get the properly formatted XML response. Any ideas on what I'm missing?
Thanks,
Darrell
Code:

if($result){
       //header( "Content-type: text/xml");
        echo "<?xml version='1.0' encoding='UTF-8'?>
        <rss version='2.0'>
       <channel>
       <title>Mom Minder | RSS</title>
       <link>www.darrellh89.com</link>
       <description>Mom Minder Notes</description>
       <language>en-us</language>";

    while($row = mysqli_fetch_array($result)){
        //print_r($row);
        $rssTitle=$row["Title"];
        $rssNote=$row["Note"];
        $rssDate=$row["postDate"];
        $rssTime=$row["postTime"];

       echo "<item>
        <title>$rssTitle</title>
        <note>$rssNote</note>
       <postdate>$rssDate</postdate>
       <posttime>$rssTime</posttime>
       </item>";
   }
   echo "</channel></rss>";

    }

Bad Response: The source code looks correct with ...
www.darrellh89.com Mom Minder Notes en-us Did you brush your teeth? 2020-12-21 08:30:00 What restaurant do you want to eat at? 2020-12-21 04:56:05 I'll pick you up at 5 2020-12-21 04:56:05 I'll pick you up at 4PM on Wednesday for the foot doctor 2020-12-22 04:56:05 Did you eat all your eggs? 2021-01-03 12:06:00
What I want

<channel>
    <title>Adventure Scuba</title>
    <atom:link href="https://ohioadventurescuba.com/feed/" rel="self" type="application/rss+xml" />
    <link>https://ohioadventurescuba.com</link>
    <description>Individual Instruction on Your Schedule</description>
    <lastBuildDate>Sun, 20 Dec 2020 15:37:02 +0000</lastBuildDate>


text:
Q: How to automatically add a dot after the nth character automatically in textarea? I have to write a textarea in which the user should enter the given latitude in decimal degrees.
For example: 60.45678 or 05.1
What should I do to make a dot appear in the textarea automatically after the second character?
I already have a function to check if the characters are numbers:
<script language=Javascript>
        function isNumberKey(evt) {
            var charCode = (evt.which) ? evt.which : event.keyCode
            if (charCode > 31 && (charCode < 48 || charCode > 57))
                return false;

            return true;
        } </script>

Maybe it can be somehow modified so that it would add a dot and check if the first two numbers are smaller than 90?
<textarea name="LongitudeEW" placeholder="Longitude East/West." onkeypress="return isNumberKey(event)"></textarea>

Thanks for the help :)

A: Try this
var DECIMAL_REGEXP = /(?<=^.{2}$)/g;

function handleKeyUp(e) {
  var target = e.target;
  var charCode = e.which || e.keyCode;

  if(charCode > 31 && (charCode < 48 || charCode > 57)){
    return false;
  }

  target.value = target.value.replace(DECIMAL_REGEXP, '.');

  return true;
}

var DECIMAL_REGEXP = /(?<=^.{2}$)/g;

function handleKeyUp(e) {
  var target = e.target;
  var charCode = e.which || e.keyCode;

  if(charCode > 31 && (charCode < 48 || charCode > 57)){
    return false;
  }

  target.value = target.value.replace(DECIMAL_REGEXP, '.');

  return true;
}
<textarea name="LongitudeEW" placeholder="Longitude East/West." onkeypress="return handleKeyUp(event)"></textarea>

In case you want to bind to the elements keypress event vs inlining:

// cache the regexp
var DECIMAL_REGEXP = /(?<=^.{2}$)/g;

// ref the textarea
var textrea = document.getElementById('LongitudeEW');

// bind to the keypress event
textrea.addEventListener('keypress', function(e){
  var target = e.target,
      charCode = e.which || e.keyCode;

  if(charCode > 31 && (charCode < 48 || charCode > 57)){
    e.preventDefault();
  }

  target.value = target.value.replace(DECIMAL_REGEXP, '.');
});
<textarea id="LongitudeEW" name="LongitudeEW" placeholder="Longitude East/West."></textarea>

A: You can try using this library: https://nosir.github.io/cleave.js/
For example as your requirement. Hope to help, my friend :))
<script src="cleave.js"></script>

<input class="input-element" type="textarea" >

<script>
    $(function(){

        var cleave = new Cleave('.input-element', {
            delimiter: '.',
            blocks: [2, 100],
            numericOnly: true
        });
    });
</script>


text:
Q: Unknown CMake command "cotire". This is my dockerfile:
from ubuntu:16.04
maintainer Nico Cesar <nico@nicocesar.com>

# Set the env variable DEBIAN_FRONTEND to noninteractive
ENV DEBIAN_FRONTEND noninteractive

RUN apt-get update &&  apt-get install -y git cmake python-virtualenv python-pip

RUN git clone https://github.com/lyft/envoy.git
RUN cd envoy && make
RUN cd envoy && mkdir -p build && cd build && cmake ..

And I get this error
CMake Error at source/common/CMakeLists.txt:141 (cotire):
   Unknown CMake command "cotire".

How do I add a command to CMake? this is taken from the envoy github.
They claim that ubuntu14 will work, but g++ is too old, and ubuntu16 has this missing cotire that I'm unfamiliar with, any idea how to add it?

A: cotire is a cmake module on github that automates the process of creating precompiled headers for your implementation files in a cross-platform way. The github project has a bunch of fluff files, but the only file you really need is located at CMake/cotire.cmake. If this file is present in CMake's module search path, your build should continue as normal.


text:
Q: I got a error while sending mail using vb.net the error is The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. t77sm26908892pfg.102 - gsmtp
          Dim SmtpServer As New SmtpClient()
            Dim mail As New MailMessage()
            SmtpServer.Port = 587
            SmtpServer.Host = "smtp.gmail.com"
            SmtpServer.Credentials = New  _
        Net.NetworkCredential("user@gmail.com", "user1")
            mail = New MailMessage()
            mail.From = New MailAddress("user@gmail.com")

            mail.To.Add("user2@gmail.com")
            mail.Subject = "Test Mail"
            mail.Body = "This is for testing SMTP mail from GMAIL"
            SmtpServer.Send(mail)
            MsgBox("mail send")

A: As Codexer said in his comment, you are not enabling SSL by setting SmtpServer.EnableSsl = True
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
SmtpServer.Port = 587
SmtpServer.EnableSsl = True ' <---- this
SmtpServer.Host = "smtp.gmail.com"
SmtpServer.Credentials = New  _
Net.NetworkCredential("user@gmail.com", "user1")
mail = New MailMessage()
mail.From = New MailAddress("user@gmail.com")
mail.To.Add("user2@gmail.com")
mail.Subject = "Test Mail"
mail.Body = "This is for testing SMTP mail from GMAIL"
SmtpServer.Send(mail)
MsgBox("mail send")

It always a good idea to not send your credentials as plain text over the internet...


text:
Q: How To Abstract NHibernate To Avoid Tight Dependency and Facilitate Testing Is it possible to adopt the use of an O/RM like NHibernate or Entity Framework, and abstract it in such a way that it could be replaced if a situation is encountered that  the O/RM cannot handle.
It seems tempting to create a service with chunky service methods inside of which, a session is created, the session is used to get / upsert entities and is then used to save all dirty objects.
I would have considered the repository pattern so that the service operation asks the repository for entities, and the O/RM session is embedded in the repository. But what do you do about saving related entities, and does an Update(T entity) method flush changes imediately. It seems to simple and generally unsatisfactory.
What I am leaning toward now is a single O/RM wrapper class that exposes an interface with generic methods like "StartSession", "EndSession", "AbandonSession", "GetById(object id)" etc.
At least this would allow the OR/M to be faked in testing which is another big concern of mine.
I guess I'm saying that I don't want to closely intertwine business logic, and O/RM data access code, because switching to another O/RM could cause most of that code to be replaced.
What do people do in the real world?

A: My strong opinion would be to do some tests on smaller projects and choose a toolset to use up front rather then put off the decision until later by building an abstract wrapper that you'll be able to change "someday". In my experience that someday never comes and the complexity you introduce is not worth it.
I have attempted to build a generic wrapper for nHibernate in the past and essentially met with nothing but pain because of it. ORM Tools are really a wrapper and toolset themselves. When you try to create a wrapper of a wrapper, you end up needing to develop (and subsequently maintain) relatively complex tools and mechanisms to accomplish what the thing you are wrapping does natively.
And, in my own experience, the wrapper I spent a LARGE amount of time building ended up only exposing a fraction of the abilities of the underlying ORM tools. And then I NEVER ended up using the wrapper with anything but nHibernate... so I could have saved myself massive amounts of time and effort by just using vanilla nHibernate itself.
I would recommend looking closely at what your requirements are and instead of spending the time abstracting out a swiss army knife solution, do the research, pick a toolset first and run with it. Yes your code will be tightly coupled to a third party tool, but the code will be simpler, you will get there faster and, likely, the results will be better.
Hope that helps,
Max Schilling

A: I handle C/U/D transactions to the database with the unit of work pattern. I don't go much further than that in abstracting, because I don't want to abstract the abstraction of the abstraction. Linq is a good abstraction for the querying part, a generic repository is a good abstract for the querying part. These are the abstractions I use in almost any project with a relational database:
interface IRepository<T> : IQueryable<T>
{
   void Add(T entity);
   void Remove(T entity);
   T Get(Guid id);
}

interface IUnitOfWork : IDisposable
{
   void RollBack();
   void Commit();
}

// I don't do this every time, the generic repository is enough for almost everything.
[Example]
interface IOrderRepository : IRepository<Order>
{
   IList<Order> GetOrdersForUser(User user);
}

// This interface is only used in the repository implementation
interface INHiberanteUnitOfWork : IUnitOfWork
{
  ISession Session { get; }
}

Sometimes, I use the generic repository, sometimes I use a more specific generic repository with specification pattern support, and sometimes I create a separate repository for a specific entity type.
You can search stack overflow on NHibernate + Unit of work to find more information about implementing these patterns.
I don't abstract the mapping, because every orm has it's own features in mapping, and I think the mapping is already an abstraction. I use fluentnhibernate for mapping.

A: One option is to define your domain model as POCOs, and then use BoostMap to proxy between your custom types and the underlying OR/M.  This lets you swap out the underlying OR/M if needed, and also mock up an iQueryable source for unit testing that doesn't rely on the database :-)


text:
Q: understanding casting of argv in c++ I recently started learning C++. I come from a background of python and web development so bear that in mind.
I wanted to write a program which takes a second argument which is an integer and does stuff. But then it started acting crazy and I realized this was a problem with casting. So I wrote this:
int main(int argc, char** argv) {
    int iMynum = int(argv[1]);
    cout << argv[1] << endl;
    cout << iMynum << endl;
    return 0;
};

running myprogram 100 results in:
100
3429646

I don't understand this. I found similar questions on SO but the answers were complicated and confused me even more. I tried doing this instead:
int iMynum = (int) *argv[1];

Which resulted in:
100
49

What is going on here?
update
Obviously, I'm an idiot - int(argv[1]) is python. So the answers really helped me understand what I was doing, but suggested code solution did not work (except for atoi which I take is not recommended). I kept looking and tried this:
into mynum = const_cast<int>(argv[1][0])

And got an error saying const_cast cannot convert 'char' to 'int'. So what should I use instead?

A: You seem to be trying to obtain an int from a string like "123" by simply casting a char-pointer — which contains only a memory address! — into an integer.
That's not how it works. Casts are tools of the static type system, not magical runtime data transformers. You have to parse the string.
There are plenty of questions on Stack Overflow about parsing strings (even C-strings like yours) into integers. For example, you can use a std::stringstream, boost::lexical_cast, std::strtol or (in C++11) std::stoi.
I leave it up to you to go and research this topic, now that you know what mistake you made and what to look for next.

Here's what I'd do:
#include <iostream>
#include <cassert>
#include <boost/lexical_cast.hpp>

int main(int argc, char** argv)
{
    assert(argc >= 2);
    const int iMynum = boost::lexical_cast<int>(argv[1]);

    std::cout << argv[1] << '\n';
    std::cout << iMynum << '\n';
};

A: arg[1] is char* type and the string will be output.
(int)arg[1] only return the address of the parameter, so you will get the address.

A: The input parameter is a string array which was stored in char*, when you get arg[1], it just return the string array (char*), if you output it, the whole string will be output.
But if you convert it ot string, it just convert the memory address of the parameter to int, so you will just see the address result.

A: To parse an int from the argument list, you want to use atoi() which is defined in stdlib.h
int iMynum = atoi(argv[1]);
You should also check that argv is at least length 2 before hand.


text:
Q: Array values as assoc array keys i wanted to fill an assoc array from variables from another array.
I have an array like this
$keys = array("key1", "key2", "key3");

and now i want to fill an array with these keys like this
$someArray["key1"]["key2"]["key3"] = "some value";

and of course it would work like this as well
$someArray[$keys[0]][$keys[1]][$keys[2]] = "some value";

But the number of keys may vary and they are different for each loop.
I want to translate some data in a hierarchy structure.
So I would love to do this dynamically from the $keys array.
For now I create a Json String, push the decoded Json to $someArray and use array_merge on it - but i thought there should be a more elegant way.
Thank you guys

A: Use a loop with a reference variable:
$someArray = array();
$where =& $someArray;
foreach (array_slice($keys, 0, -1) AS $key) {
    $where[$key] = array();
    $where =& $where[$key];
}
$where[$keys[count($keys)-1]] = "some value";


text:
Q: Sharepoint: document remains check out after it is uploaded I am uploading document using Copy Services into document library, after that setting libraries required fields too but document still remains checked out for that user. I have also checked version settings for that library. Did not help anything.! Is there anything that i am missing?

A: Even though i was filling all the required fields, document remained checked out. So simply changing all required fields to optional fixed the problem.


text:
Q: get-childitem variable return empty value I'm trying to figure out why, my Get-ChilddItem variable is returning an empty $null value while running the below scriptblock, whereas from ISE, if i enter variables values manually, i'm able to get an output of the .sql files I've selected before the Get-ChildItem command. Below is a beginning of the function i'm writing:
Function test{
[CmdletBinding()]
Param (
   [Parameter(Mandatory=$True]
   [string]$client
   )
# Define variables
$Master = 'master'
$Slave = 'slave'
$SourcePath = "C:\somefolder\folder"
$Masterfolder = "C:\somemasterfolder"
$Slavefolder = "C:\someslavefolder"

# Create folders
    $clientdir2 = New-Item -Path $Slavefolder -name "$client" -ItemType    Directory

# Create folder on secondary server
    $clientdir = New-Item -Path "Microsoft.PowerShell.Core\FileSystem::\\$master\somemasterfolder" -name "$client" -ItemType Directory

# Getting all sql files and copy them to the destination folder
    $gflz = Get-ChildItem $SourcePath\* -Include __07*, __08*, __10*
# Copy
    Copy-Item $gflz $clientdir2

# Replace values in each sql files
    $cpz = @(Get-ChildItem $clientdir2\* -Include *.sql)
if ($cpz -ne $null) {
    Foreach ($flz in $cpz) {
        (Get-Content $flz.FullName) | ForEach-Object { $_ -replace'clientID', "$client" -replace 'C:\LSpath', `
        "$Masterfolder" -replace'C:\LSPath2', "$Slavefolder" } | Set-Content $flz.FullName}}

Thus, the replace operation cannot take place, as it loops on nothing.
Am I writing this the wrong way for the intended purpose?
Would you point me out to the right direction?
Thanks!

A: Figured out my problem from this Stackoverflow post PowerShell Script to Find and Replace for all Files with a Specific Extension.
I was pretty sure that the files property in the Get-Content command included Fullname or Name as member. Turns out that when I checked for the members i could not get any properties match FullName or Name:
Get-Content $sqlfiles | gm -MemberType Properties

     TypeName: System.String

Name         MemberType   Definition
----         ----------   ----------
PSChildName  NoteProperty System.String
PSChildName=Mysqlfiles.sql
PSDrive      NoteProperty System.Management.Automation.PSDriveInfo PSDrive=C
PSParentPath NoteProperty System.String
PSParentPath=C:\parentpath
PSPath       NoteProperty System.String
PSPath=mysqlfilefullpathname.sql
PSProvider   NoteProperty System.Management.Automation.ProviderInfo
PSProvider=Microsoft.PowerShell.Core\FileSystem
ReadCount    NoteProperty System.Int64 ReadCount=1
Length       Property     int Length {get;}

So the only properties that relates to FullName property was PSPath as suggested in the post that i quoted above.
Defining the right properties turns out to help replace the string inside each files as i was expecting to do.
Credits to Daniel Liuzzi and Robben_Ford_Fan_boy for the hints.


text:
Q: Inserting a string method into an string array I am trying to make a selection for a set of values, each of the methods return a string array which I am trying to put into a string array in the main. Here is the code:
string[] array = { MethodA1(), MethodA2(), MethodA3() };

I am trying to make the string[] array, just one item. This works: (but it only allows the user to show/select one value)
string[] array = MethodA1();

Can anyone think of a way to allow multiple method returns into an array?

A: Something like this?
string[] array = MethodA1().Concat(MethodA2()).Concat(MethodA3()).ToArray();

Edit:  It sounds from your comments that you are actually trying to achieve something entirely different: to select the results of one of these methods based on a parameter.  Do you mean something like this?
private string[] SelectFiles(object userInput)
{
    string[] array;

    if (userInput == 1)
    {
        array = MethodA1();
    }
    else if (userInput == 2)
    {
        array = MethodA2();
    }
    else
    {
        array = MethodA3();
    }

    return array;
}

A: You could use SelectMany to flatten everything to a single string[]:
string[] array = (new[] { MethodA1(), MethodA2(), MethodA3() })
    .SelectMany(a => a)
    .ToArray();

A: Maybe you should consider
List<string>

You could simply use
myList.AddRange(stringArrayMethod());


text:
Q: Gaussian integers and ideals a). In the ring of Gaussian integers $\Bbb Z[i] = \{a + bi \mid a, b ∈ Z\}$, describe the ideal $\langle i\rangle$.
b). In the ring of Gaussian integers $\Bbb Z[i]$, show that $2 \in J$ where $J$ is the ideal $\langle i+ 1\rangle$.
I'm having trouble doing this one. So far I know that the ideal $\langle i\rangle=\{(a+bi)i \mid (a+bi)\in \Bbb Z[i] \}$ based on the definition. For b),
$$
\langle i+ 1\rangle=\{(a+bi)(i+1) \mid (a+bi)\in \Bbb Z[i] \} = \{(a + b)i + (a-b) \mid (a+bi)\in \Bbb Z[i] \}.
$$
I'm very confused on where to go from with this. Any help would be appreciated.

A: Note that $2=(1-i)(1+i)$, which is enough to have $2\in J$.
For the part a) you can see that $(a+bi)i=-b+ai$ which can be seen a anti-clock 90º rotation of the Gaussian grid.


text:
Q: Error: No puede cargar el archivo o ensamblado netstandard me acaban de pasar un proyecto en xamarin forms, lo descargué de su repositorio, y cuando restauré los paquetes nugets, me salen con un icono de admiración, entonces lo que hice fue desinstalarlos y volverlos a instalar manualmente, pero aun así siguen saliendo los iconos de admiración, y me salen tres errores peculiares, que no encuentro solución en google, espero alguien me pueda ayudar a solucionarlo:
Ésta es la imagen del error

A: Limpia todo el proyecto y vuelvelo a compilar.

Compilar -> Compilación por lotes -> Seleccionar Todo -> Limpiar.

A veces también debes de cerrar el proyecto y volverlo a cargar.


text:
Q: rename the 10 most-recently modified files on AIX I have some .xls files in a defined directory (say in /A/B). I want to rename top 10 latest files and append "-bkp" in their names.
I tried, not working
ls -lt *.xls | head -1 | awk '{print "mv " $9 " "$9-bkp}' | sh

I tried find and -exec but how do we get top l0 latest modified files

A: You should use -10 and not -1 as argument to head, and you also need quotes around -bkp, so
 ls -lt *.xls | head -10 | awk '{print "mv " $9 " "$9"-bkp"}' | sh

should work. And you would probably have realised if you had tried removing | sh, so the command just ends with awk printing the commands.

A: If you don't want to make any assumption on what character filenames may contain, you could do:
ls -dt ./*.xls | awk -v q="'" -v n=10 '
  function process() {
    if (NR > 1) {
      gsub(q, q "\\" q q, file)
      print "mv " q file q, q file "-bkp" q
      if (!--n) exit
    }
  }
  /\// {
    process()
    file = $0
    next
  }
  {file = file "\n" $0}
  END  {process()}' | sh -x

Or if you have zsh:
for f (*.xls(om[1,10])) cp -- $f $f-bkp

Or
autoload zmv
zmv -C '*.xls(#qom[1,10])' '$f-bkp'

A: If you have ksh93 (for the arrays) and perl (for the timestamp/stat), then this will work:
files=(*.xls)
# exit early if there are no matching files
[ "$files" = "*.xls" ] && exit 0

for index in ${!files[@]}
do
  t[$index]=$(perl -e '$x=(stat(shift))[9]; print "$x"' "${files[index]}")
done

for i in ${!t[@]}
do
  printf "%d %d\n" ${t[i]} $i
done | sort -rn  | head -10 | while read t i
do
  mv "${files[i]}" "${files[i]}-bkp"
done

It works by gathering the list of *.xls files, then loops over those files, calling the perl one-liner to print the last-modified timestamp of each file, saving the result into a parallel array t.
It then loops over t, printing the timestamp and the array index, pipes that to sort to get the most-recently modified files to the beginning, pipes that to head to get the top 10, then loops back over that output to call the mv command on the corresponding files.

A: ls has a "sort"-parameter that can take a value of "time".
#!/bin/bash
IFS=$'\n'
for file in $(ls *.xls --sort=time|head -n 10);
do
    mv $file $file-bkp
done
unset IFS

The IFS-shenanigans are because the for-loop becomes ill-mannered if you have spaces in your filenames. I believe there are more orthodox solutions to that issue, but my solution works. You can remove the lines containing IFS if you know for a fact that your filenames contain no spaces.


text:
Q: Show that $(1-i)^{7}=8(1+i)$ Homework Problem: Show that $(1-i)^{7}=8(1+i)$ by converting to polar form, taking the seventh power, and then converting back to standard form. Here is what I have:
$r=\sqrt{2}$ and $\theta=\arctan{(-1)}=-\frac{\pi}{4}$, then $(\sqrt{2})^{7}e^{-i7\pi/4}= 8\sqrt{2}e^{i3\pi/4}=8\sqrt{2}(\cos{(\frac{3\pi}{4})}+i\sin{(\frac{3\pi}{4})}=8\sqrt{2}(-\frac{\sqrt{2}}{2}+i\frac{\sqrt{2}}{2})=8\sqrt{2}(-\frac{1}{\sqrt{2}}+i\frac{1}{\sqrt{2}})=8(i-1)$.
I cannot figure out what I am doing wrong. My assumption is that I am not handling the argument correctly. Any help would be much appreciated.

A: $e^{-i7\pi/4}$ is $e^{i\pi/4}$.


text:
Q: Update hierarchical / tree structure in Clojure I have an Atom, like x:
(def x (atom {:name "A"
              :id 1
              :children [{:name "B"
                          :id 2
                          :children []}
                         {:name "C"
                          :id 3
                          :children [{:name "D" :id 4 :children []}]}]}))

and need to update a submap like for example:
if :id is 2 , change :name to "Z"

resulting in an updated Atom:
{:name "A"
 :id 1
 :children [{:name "Z"
             :id 2
             :children []}
            {:name "C"
             :id 3
             :children [{:name "D" :id 4 :children []}]}]}

how can this be done?

A: You could do it with postwalk or prewalk from the clojure.walk namespace.
(def x (atom {:name "A"
              :id 1
              :children [{:name "B"
                          :id 2
                          :children []}
                         {:name "C"
                          :id 3
                          :children [{:name "D" :id 4 :children []}]}]}))
(defn update-name [x]
  (if (and (map? x) (= (:id x) 2))
    (assoc x :name "Z")
    x))

(swap! x (partial clojure.walk/postwalk update-name))

A: You could also use Zippers from the clojure.zip namespace
Find a working example here: https://gist.github.com/renegr/9493967


text:
Q: java.sql.SQLException: Invalid column index - shown in output, but test passes and returns right result faced this issue.
I'm using spring with dbunit, jdbctemplate and c3p0. I'm trying to create some tests for my dao layer.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-test-config.xml"})
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
                     TransactionalTestExecutionListener.class,
                     DbUnitTestExecutionListener.class})
@DatabaseSetup(value = "classpath:dbunit-testdata.xml", type = DatabaseOperation.CLEAN_INSERT)
public class NotesJdbcTemplateDaoTest {

private static Logger LOG = LoggerFactory.getLogger(NotesJdbcTemplateDaoTest.class);

@Autowired
private NotesDao notesJdbcTemplateDao;

@Test
public void testReceive() throws Exception {

    Note note = notesJdbcTemplateDao.receive(2);

    Assert.assertNotNull(note);
    LOG.debug(note.toString());
}

This test passes well: in DB table is generated from dbunit dataset. I can get my test data from this table and print to log, but I also got exception message in logs.
2016-02-19 08:16:02 DEBUG SqlUtils:85 - Attempted to convert SQLException to SQLException. Leaving it alone. [SQLState: 99999; errorCode: 17003]
java.sql.SQLException: Invalid column index
    at oracle.jdbc.driver.OracleResultSetImpl.getString(OracleResultSetImpl.java:1263)
    at com.mchange.v2.c3p0.impl.NewProxyResultSet.getString(NewProxyResultSet.java:3316)
    at org.dbunit.util.SQLHelper.createColumn(SQLHelper.java:404)
    at org.dbunit.database.DatabaseTableMetaData.getColumns(DatabaseTableMetaData.java:333)
    at org.dbunit.dataset.AbstractTableMetaData.getColumnIndex(AbstractTableMetaData.java:106)
    at org.dbunit.operation.AbstractOperation.getOperationMetaData(AbstractOperation.java:89)
    at org.dbunit.operation.AbstractBatchOperation.execute(AbstractBatchOperation.java:143)
    at org.dbunit.operation.CompositeOperation.execute(CompositeOperation.java:79)
    at com.github.springtestdbunit.DbUnitRunner.setupOrTeardown(DbUnitRunner.java:194)
    at com.github.springtestdbunit.DbUnitRunner.beforeTestMethod(DbUnitRunner.java:66)
    at com.github.springtestdbunit.DbUnitTestExecutionListener.beforeTestMethod(DbUnitTestExecutionListener.java:186)
    ......

What can be the matter of it??
Also adding spring config and dataset
<context:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="${jdbc.driverClassName}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"/>
        <property name="minPoolSize" value="${jdbc.minPoolSize}"/>
        <property name="maxStatements" value="${jdbc.maxStatements}"/>
        <property name="testConnectionOnCheckout" value="${jdbc.testConnection}"/>
    </bean>

    <bean id="notesJdbcTemplateDao" class="com.sgleb.springrest.dao.impl.NotesJdbcTemplateDao"/>

<?xml version='1.0' encoding='UTF-8'?>
<dataset>

    <NOTES NOTE_ID="1" TOPIC="TOPIC 1" FULL_TEXT="Full text 1"/>
    <NOTES NOTE_ID="2" TOPIC="Topic two" FULL_TEXT="Fulltext 2"/>
    <NOTES NOTE_ID="3" TOPIC="topic 3three" FULL_TEXT="fulltext 3"/>
    <NOTES NOTE_ID="4" TOPIC="aaaaaaaaaaaa" FULL_TEXT="bcdefg12345"/>
    <NOTES NOTE_ID="5" TOPIC="note five" FULL_TEXT="note 5 full text"/>

</dataset>

and also piece of dao
@Repository("notesJdbcTemplateDao")
public class NotesJdbcTemplateDao implements NotesDao {

    private final String SQL_RECEIVE_BY_ID = "SELECT * FROM NOTES WHERE NOTE_ID = ?";

    @Autowired
    private DataSource dataSource;

    private JdbcTemplate jdbcTemplate;

    @Override
    public Note receive(long id) {

        jdbcTemplate = new JdbcTemplate(dataSource);
        List<Note> result = jdbcTemplate.query(SQL_RECEIVE_BY_ID, new Object[]{id}, new NotesRowMapper());

        if (result.size() != 0)
            return result.get(0);
        else
            return null;
    }

Note 1: if I'm trying to receive data from real DB, it works perfect (without dbunit)
Note 2: If I clean all lines inside receive test method - i.e. left it empty, exeption still occures in debug. So it seems that it's a problem with DbUnit


text:
Q: Can an OpenGLES 2.0 framebuffer be bound to a texture and a renderbuffer at the same time? Brad Larson provides some great code here and here for 'rendering your scene into a texture-backed framebuffer', but it's not clear whether this is the same framebuffer that I use for the rest of the drawing.
If you attach a renderbuffer to a framebuffer, can the framebuffer also render into a texture with the same call?

A: Sounds like you might be a bit confused with FBO usage. If you need it, this should get you started: Apple Developer - Drawing offscreen. This could help too.
Renderbuffer is something you can bind to an FBO (framebuffer object). FBO is something you create when you don't want your rendering to be displayed immediately, but want to read the rendering result back or perform additional rendering to it. The way FBOs work in OpenGL ES 2.0, you have only one color attachment point available (GL_COLOR_ATTACHMENT0 - your fragment shader output variable gl_FragColor is connected to this attachment point), and it can only have one texture or renderbuffer attached to it. So to answer that last question, you cannot have an FBO that would simultaneously write color to a renderbuffer and a texture.
As for the first part of your question, it depends whether you are already using an FBO or the default framebuffer. Chances are the behavior you're looking for is something like this:

*

*bind an FBO

*render something to a texture attached to the FBO

*bind the default framebuffer

*use the texture from step 2 to affect rendering in your second renderpass.

Hope this answers your question even a little bit.


text:
Q: INSERT Statement in PL/SQL fails in Oracle database When executing an SQL statement in PLSQL with
DBMS_SQL.EXECUTE('insert into tablename VALUES(aNumber)');

It gives an ASCII character error.
And when inserting it directly it succeeds and inserts it.

A: In PL/SQL you could write the INSERT statement directly.
DECLARE
  tablevalue      varchar2(200);
BEGIN
  tablevalue := 'Hello World!';

  INSERT   INTO tablename
         VALUES (tablevalue);
END;

Your statement fails because that is not the way DBMS_SQL.EXECUTE works. Check out the documentation and the example: http://docs.oracle.com/cd/B28359_01/appdev.111/b28419/d_sql.htm#BABBFFFJ
According to the example given in the reference documentation you should do it like this (first you prepare the statement, then bind the variable and then run it).
CREATE OR REPLACE PROCEDURE demo(tablevalue IN varchar2) AS
    cursor_name INTEGER;
    rows_processed INTEGER;
BEGIN
    cursor_name := dbms_sql.open_cursor;
    DBMS_SQL.PARSE(cursor_name, 'INSERT INTO tablename VALUES(:x)',
                   DBMS_SQL.NATIVE);
    DBMS_SQL.BIND_VARIABLE(cursor_name, ':x', tablevalue);
    rows_processed := DBMS_SQL.EXECUTE(cursor_name);
    DBMS_SQL.CLOSE_CURSOR(cursor_name);
EXCEPTION
WHEN OTHERS THEN
    DBMS_SQL.CLOSE_CURSOR(cursor_name);
    raise;
END;

You use it then like this
 exec demo('something');

Hope it helps


text:
Q: error when I use ArrayList in fxml   <children>
   <fx:define>
       <ArrayList fx:id="buttons">
       <Button fx:id="btn1" layoutX="93.0" layoutY="31.0" mnemonicParsing="false" text="Button" />
       <Button fx:id="btn2" layoutX="187.0" layoutY="31.0" mnemonicParsing="false" text="Button" />
       <Button fx:id="btn3" layoutX="255.0" layoutY="31.0" mnemonicParsing="false" text="Button" />
       <Button fx:id="btn6" layoutX="505.0" layoutY="31.0" mnemonicParsing="false" text="Button" />
       <Button fx:id="btn4" layoutX="351.0" layoutY="31.0" mnemonicParsing="false" text="Button" />
       <Button fx:id="btn5" layoutX="436.0" layoutY="31.0" mnemonicParsing="false" text="Button" />
       </ArrayList>
   </fx:define>

I get error in each button and I even can't open fxml in sceneBuilder. What is wrong with thisenter image description here
Full code of fxml below
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>

<?import java.util.ArrayList?>
<AnchorPane fx:controller="sample.Controller" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">

   <children>
       <fx:define>
           <ArrayList fx:id="buttons">
           <Button fx:id="btn1" layoutX="93.0" layoutY="31.0" mnemonicParsing="false" text="Button" />
           <Button fx:id="btn2" layoutX="187.0" layoutY="31.0" mnemonicParsing="false" text="Button" />
           <Button fx:id="btn3" layoutX="255.0" layoutY="31.0" mnemonicParsing="false" text="Button" />
           <Button fx:id="btn6" layoutX="505.0" layoutY="31.0" mnemonicParsing="false" text="Button" />
           <Button fx:id="btn4" layoutX="351.0" layoutY="31.0" mnemonicParsing="false" text="Button" />
           <Button fx:id="btn5" layoutX="436.0" layoutY="31.0" mnemonicParsing="false" text="Button" />
           </ArrayList>
       </fx:define>
   </children>

</AnchorPane>

I want to store all buttons in one array in controller

A: I don't think it's possible to add children in a List, especially standard ArrayList. FX components use ObservableList to store children components.
I suggest you add your buttons to a group, like this:
    <AnchorPane>
        <Group fx:id="group">
            <Button fx:id="btn1" layoutX="93.0" layoutY="31.0" mnemonicParsing="false" text="Button"/>
            <Button fx:id="btn2" layoutX="187.0" layoutY="31.0" mnemonicParsing="false" text="Button"/>
            <Button fx:id="btn3" layoutX="255.0" layoutY="31.0" mnemonicParsing="false" text="Button"/>
            <Button fx:id="btn6" layoutX="505.0" layoutY="31.0" mnemonicParsing="false" text="Button"/>
            <Button fx:id="btn4" layoutX="351.0" layoutY="31.0" mnemonicParsing="false" text="Button"/>
            <Button fx:id="btn5" layoutX="436.0" layoutY="31.0" mnemonicParsing="false" text="Button"/>
        </Group>
    </AnchorPane>

Your buttons will be visible in your app and you can do operations on group children almost like it was a standard list.


text:
Q: How to transfer data from a waterfalldialog to another? I am working on a bot framework project (C# - Bot Framework v4) which contains at least 2 dialogs. I want to transfer informations that I've created (not from the user) from a first dialog to another one. How can I do it ?
I tried to set the second parameter of the BeginDialogAsync function but it was empty on the arrival.
EDIT :
I have a first dialog (SignInDialog) which is used to connect the user with OAuthPrompt. When the user is connected, in the same class, I will then handle his intent with the Dispatcher (Microsoft) and LuisRecognizer, to tell if I have to use QnA or LUIS.
What I am trying to do is to call a specific dialog located in another Dialog class (PersonalInfoDialog), according to the user's intent. But whenever I pass some arguments to the BeginDialogAsync method, I don't find a way to get it from the destination dialog.
SignInDialog class
        private async Task<DialogTurnResult> PromptStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            return await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);
        }

        private async Task<DialogTurnResult> DispatchStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {

            var tokenResponse = (TokenResponse)stepContext.Result;
            if (tokenResponse != null)
            {

                var recognizerResult = await BotServices.Dispatch.RecognizeAsync(stepContext.Context, cancellationToken);

                var topIntent = recognizerResult.GetTopScoringIntent();

                var intent = topIntent.intent;

                switch (intent)
                {

                    case "CASE_1":
                        return await stepContext.BeginDialogAsync(nameof(PersonalInfoDialog), recognizerResult, cancellationToken);

                    case "CASE_2":
                        ...
                    default:
                        Logger.LogInformation($"Dispatch unrecognized intent: {intent}.");
                        break;
                }

            }

            return await stepContext.EndDialogAsync(null, cancellationToken);
        }

PersonalInfoDialog class
Here, in debug mode, test is null.
    private async Task<DialogTurnResult> PromptStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
    {
        var test = stepContext.Options as LuisResult;
        return await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);
    }

Thanks for the help.

A: If I understood you correctly and you really have no other options to transfer the data in one Waterfall-Dialog:
You could use state property accessors to store/ load the data.
In the Docs you find a example. Have a look at the UserProfile: https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-howto-v4-state?view=azure-bot-service-4.0&tabs=csharp
And for more information I recommend the Doc article about states: https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-concept-state?view=azure-bot-service-4.0


text:
Q: Axios.post request successfull, but callback in .then(res => ... doesn't execute I am developing a full stack application with a NodeJS backend and a ReactJS frontend. I am using PassportJS to do authentication with login and password.
Here is my post request in the back end when a user logs in:
    let username;
    let uid;

    app.post('/login', (req, res, next) => {
      passport.authenticate('local',
      (err, user, info) => {
        if (err) {
          console.log(err);
        }

        if (!user) {
          return res.send({"message": "Password or username is incorrect"});
        }

        req.logIn(user, function(err) {
          if (err) {
            return next(err);
          }
          username = user.username;
          uid = user._id;

          return res.send({"message": "User Authenticated"});

        });

      })(req, res, next);
    });

Here is my front end ReactJS code:
function LoginPage(props) {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const SERVER_URL = process.env.REACT_APP_SERVER_URL;
    const navigate = useNavigate();

    const handleLogin = async() => {
      // props.onChange();
        axios.post(SERVER_URL + "/login", {"username": username, "password": password})
        .then(res => {
          console.log(res.data);
          console.log("login successful");
        })
        .catch(err => console.log(err.data))
      }
    return (

      Login

        <form onSubmit={handleLogin}>
          Username:
            <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} />

          Password:
            <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />

          <input type="submit" value="Login" />
          </form>

    );
  }

  export default LoginPage;

The post request works in that once it is logged in, passportJS middleware creates req.user object. I have another request in the backend that fetches this data. However, it is only triggered when I manually refresh the page, triggering the render of the user's profile page instead of login (I use a boolean isAuthenticated to do this)
Even though the post is successful, once I click the submit button, none of the "res.send" functions send anything to the client side. i.e. "login successful" nor "res.data" show up. I tried using useNavigate() to redirect but it wasn't executing either. The function in .then() does not execute. none of the "res.send" functions do anything. How can I fix this?


text:
Q: Only black screen in my UIWebView I have two View Controllers. In the first one i have a button and when you click it you need to display a Web Page in a second View Controller. When I click the button, I see only a black screen.
Here is TabulkaViewController.m code:
#import "TabulkaViewController.h"
#import "WebViewController.h"

@interface TabulkaViewController ()

@end

@implementation TabulkaViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    _hbutton.layer.borderWidth = 1;
    _hbutton.layer.borderColor = [[UIColor grayColor] CGColor];
}
- (IBAction)hbutton:(id)sender

{
   NSURL *url = [NSURL URLWithString:@"http://apple.com"];
   WebViewController *webViewController = [[WebViewController alloc] initWithURL:url andTitle:@"Apple"];
    [self presentViewController:webViewController animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

Here is code of WebViewController.h:
    #import <UIKit/UIKit.h>

    @interface WebViewController : UIViewController <UIWebViewDelegate>
    {
        NSURL *theURL;
        NSString *theTitle;
        IBOutlet UIWebView *webView;
        IBOutlet UINavigationItem *webTitle;

    }

    - (id)initWithURL:(NSURL *)url;
    - (id)initWithURL:(NSURL *)url andTitle:(NSString *)string;
    - (IBAction) done:(id)sender;

    @end

And here is code of WebViewController.m:
#import "WebViewController.h"

@interface WebViewController ()

@end

@implementation WebViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    webTitle.title = theTitle;
    NSURLRequest *requestObject = [NSURLRequest requestWithURL:theURL];
    [webView loadRequest:requestObject];}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (id)initWithURL:(NSURL *)url andTitle:(NSString *)string {
    if( self = [super init] ) {
        theURL = url;
        theTitle = string;
    }
    return self;
}

-(id)initWithURL:(NSURL *)url {
    return [self initWithURL:url andTitle:nil];
}

- (IBAction) done:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    webView.delegate = nil;
    [webView stopLoading];
}
-(void)webViewDidStartLoad:(UIWebView *)webView
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

A: You need to instantiate the webView at some point. I suggest you change your viewDidLoad to this:
- (void)viewDidLoad
{
    [super viewDidLoad];
    webView = [[UIWebView alloc] init];
    webTitle.title = theTitle;
    NSURLRequest *requestObject = [NSURLRequest requestWithURL:theURL];
    [webView loadRequest:requestObject];
}

Since your webView is nullat the start of the method, it needs to be created before you can load any Requests. Just declaring it in the header file is not enough, thats why you need webView = [[UIWebView alloc] init];.
EDIT:
Of course, you could also put that line into your ìnitWithURL:andTitle: method, where the other instantiations take place.


text:
Q: JavaFX treeview state incorrect I have a situation where the state of the JavaFX TreeView is not correct when the items are added to the root one by one which can be recreated with the code below.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class App extends Application {

    @Override
    public void start(Stage stage) {

        TreeView<String> treeView = new TreeView<>();
        TreeItem<String> root = new TreeItem<>("Root");
        treeView.setRoot(root);
        treeView.setShowRoot(false);

        root.getChildren().add(new TreeItem<>("Foo"));
        root.getChildren().add(new TreeItem<>("Bar"));
        root.getChildren().add(new TreeItem<>("Baz"));

        var scene = new Scene(new StackPane(treeView), 640, 480);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

As you can see the second item has a blue rectangle around it (I think this means the item is focused). Using treeView.refresh() or treeView.getFocusModel() does not seem to clear this up however as soon as I interact with the TreeView using the keyboard and mouse everything is corrected.
If I change the code above to replace the three calls to add with addAll then nothing is selected or focused when the window opens.
I have noticed that if the root node is added to the TreeView after all the items have been added to it then the state of the tree view is consistent when using add or addAll; In these cases the first item in the TreeView is surrounded by a blue rectangle.
Can anyone explain the difference in behaviour? Is this a bug?
This was tested using version 15.0.1 of the JDK and JavaFX.


text:
Q: I want to print a formatted array in java I haven't been able to find any questions similar to my situation so I hope I'm not missing something.
I have an array of strings. I want to print every 3 strings on their own line with commas and spacing.
Here is my method:
public static void Modify(String stringSearch)
{
    ArrayList<String> records = new ArrayList<String>();
    try {
        File file = new File("Temp.txt");
        input = new Scanner(file);
    }
    catch (IOException ioe) {
        ioe.printStackTrace();
    }

    if (input.hasNext()) {
        while (input.hasNext())
        {
            String firstName = input.next();
            String lastName = input.next();
            String phoneNumber = input.next();

            if ((Objects.equals(firstName, stringSearch)) || (Objects.equals(lastName, stringSearch)) || (Objects.equals(phoneNumber, stringSearch))) {

                records.add(firstName);
                records.add(lastName);
                records.add(phoneNumber);
            }
        } // end while
    }
    int size;
    size = (records.size()) / 3;
    System.out.printf("Found %d records:%n", size);

    String[] Array = records.toArray(new String[0]);

    for (int s = 0; s < Array.length; s++) {
        System.out.printf("%s", Array[s]);
    }
}

I am converting an arrayList to a string array in order to try and format it. I'm very new to java and am working on a project in a time crunch.
I need it to print exactly like this:
Found 2 records:
1) Garcia,     John      505-338-2567
2) John,       Joseph    212-780-3342

It is printing like this:
Found 2 records:
GarciaJohn505-338-2567JohnJoseph212-780-3342

A: Java is an Object-Oriented language, and you should use it.
Create a class representing your Person, with firstName, lastName, and phoneNumber as fields.
Then you create a List<Person> with 2 objects in it, and write a method for printing that list. The System.out.printf() you're already using can help output values in columns like you want.

A: You probably need to create you own data-structure, with a toString() method that suits your needs.
Something like:
public class PersonalCustomerData {
    private String firstName;
    private String lastName;
    private String phoneNumber;

...

    @Override
    public String toString() {
        return lastName + "," + " " + firstName + " " + phoneNumber;
    }
}

And, as @Andreas mentioned in his answer, you also need a Collection<PersonalCustomerData>, that when you iterate over it, you print your fully formatted output:
private Collection<PersonalCustomerData> col;

// init the collection + do stuff...

public void printCustomerData() {
    int lineNumber = 0;

    for(PersonalCustomerData pcd : col) {
        lineNumber++;

        System.out.println(lineNumber + ")" + " " + pcd);
    }
}

A: If you don't want to use object to contain your values and stick with your plan of doing. you can use this code to print it with format.
Replace this:
     String[] Array = records.toArray(new String[0]);
     for (int s = 0; s < Array.length; s++) {
         System.out.printf("%s", Array[s]);
     }

to this:
    int numberOfLine = 1; // Counter of words per line
    String[] Array = records.toArray(new String[0]);
    for(String str : Array) {
        String strSperator = "";
        switch (numberOfLine) {
        case 1:
            strSperator = ",    ";
            numberOfLine++;
            break;
        case 2:
            strSperator = "     ";
            numberOfLine++;
            break;
        case 3:
            strSperator = "\n";
            numberOfLine = 1;
            break;
        }
        System.out.printf("%s%s",str,strSperator);
    }

A: replace this line
    for (int s = 0; s < Array.length; s++) {
    System.out.printf("%s", Array[s]);`

to something like this. I didn't test out the code so there might be small typos or what not. I think this will do what you want.
As Andreas said, it would be better if you make a person class. It will look more organized and probably easier to understand.
int counter = 1;
System.out.print(records.get(0) + ",\t")
while (counter !=records.size())
{
if(counter %3 ==0)
System.out.println(records.get(counter));
else if(counter% 3== 1)
System.out.print(records.get(counter) + ",\t");
else
System.out.print(records.get(counter)+ "\t");
counter ++;
}

Since your first element will always be first name , 2nd element will be last name and 3rd element is the phone number, I print the first one initially then the modding and the while loop should handle everything I believe.


text:
Q: What does "fidelity" mean? In particular I am interested in whether it is more closely related to "precision" or "accuracy". So a somewhat mathematical description might be appropriate.
For example the word "fidelity" occurs at 23:54 in the BICEP2 press release video, where it is emphasised as being different to sensitivity.

A: Warning - a certain amount of personal interpretation here.
When I asked Google, the definition included both "accuracy" and "precision":

I would say that it has to first be accuracy and next precision. Here is my reasoning:
You can have a very precise measurement (when you repeat it 100 times, you get the same answer within 0.1%) that has a large systematic error (bias) - for example, measuring a length with a ruler that has a worn end. Such a measurement is not faithful to the thing being measured - it's "low fidelity".
If you have a measurement that is accurate but has low precision, you can repeat it 100 times and you will slowly converge on the correct answer (since accuracy implies low bias).
This makes accuracy more important - and means that "fidelity" in a measurement, while really requiring a fair amount of both, should primarily be equated with accuracy.

A: I've used the term most often to describe the quality of a mathematical model relative to how well it can predict a real physical process. One speaks of a high fidelity model as one that can faithfully predict outcomes from measurements.

A: It would be in reference to precision. This may sound pendantic, but every measurement in science has some degree of error no matter how small. These small errors are important, because if they repeat in subsequent experiments, then a pattern is realized. The reproducability of errors that make patterns reveal degrees of precision, (among other things). This is a critical distinction from the notion of accuracy, which assumes a thing is perfectly known. I would expect the use of the term 'fidelity' is in reference to precision, as accuracy is a unicorn in science.


text:
Q: How do you build algorithms to optimize high scores on games My favorite app I have ever played is drop7, a puzzle game. I have linked the wikipedia page if you're not familiar with it
https://en.m.wikipedia.org/wiki/Drop7
Since I've started playing this game Ive just been trying to get high scores in their blitz round because it's a quick game. I want to write a script, preferably in Python, where I can simulate this game. I then want to find Out some strategies that help you get higher scores or if I can learn about optimizing a game like drop 7.
I'm not sure where to start and I would like your help. I know how to code in Python, but not terribly well, classes confuse me a bit so I stick to just functions.
Thank you for your insight


text:
Q: split library jar into impl jar and api jar? Imagine we have a Lib .jar and two executable jars - App1 and App2 which both depend on the Lib .jar at compile time. Our current situation is that whenever we change the Lib's implementation (while keeping the signatures intact), we also need to change App1 and App2: while the source code in the executables themselves does not change at all, we are still required to update the Lib's version number within each executable's pom file, increase each executable version number, and redeploy them - hefty.
I imagine a better situation in which after changing Lib's implementation, the Lib's jar gets deployed and the executables only need to be restarted on the production environment to pick up those changes - no need to modify each executable's pom; no need to create new executable jars; no need to deploy new executable jars to the prod environment.
How can that better situation be orchestrated? We use Maven as our build system.
Notice that we would prefer an approach in which the lib is loaded in the same JVM as each of the executables - we don't want to have a web service architecture with the Lib's implementation running on another VM.
In addition, consider that we also maintain the executables and we develop them on our desktops i.e within an IDE, run maven commands on the command line, etc and we would like to preserve that ability.
Thanks.

A: Here is an attempt to split the lib into two jars - an api jar and an impl jar - and an app that at compile time only depends on the lib api hence it does not need to change when the lib impl changes - see ma?!:

*

*the app is made to depend at compile time on the lib api (1)

*the app's dependency on the lib impl is only stated on the app's pom for development purposes (2) and kept as a runtime dependency to avoid introducing undesired compile time dependencies (3)

*at compile time the app only depends on the lib api and thus it does not know how to construct the implementation objects whose construction then becomes something else's responsibility e.g. Spring (4)

*the api is based on interfaces (5). This helps with the definition of the signatures in a single place as well as avoiding Java's single inheritance limitation on the implementation classes.

*to orchestrate the loading of the impl jar at runtime, I rely on a convention to include a sentinel class on the impl jar that is loaded initially as the app comes up (6) to force the loading of the entire impl jar into the app's JVM

*what's left to do (not shown below) is to reference the impl jar at runtime on the prod environment via the classpath command line option

lib-api
public interface Foo { // 5
    void bar();
}

lib-impl
pom.xml
<dependencies>
    <dependency>
        <groupId>splitlib</groupId>
        <artifactId>lib-api</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId> <!-- 4 -->
    </dependency>
</dependencies>

ImplFoo.java
import org.springframework.stereotype.Component;

@Component
final class ImplFoo implements Foo {
    @Override
    public void bar() {
        System.out.println("hello world");
    }
}

Sentinel.java
public final class Sentinel {
    private Sentinel() {}
}

app
pom.xml
<profiles>
    <profile>
        <id>development</id> <!-- 2 -->
        <activation>
            <os><family>mac</family></os>

            <!-- or whatever -->

        </activation>
        <dependencies>
            <dependency>
                <groupId>splitlib</groupId>
                <artifactId>lib-impl</artifactId> <!-- 2 -->
                <scope>runtime</scope> <!-- 3 -->
            </dependency>
        </dependencies>
    </profile>
</profiles>

<dependencies>
    <dependency>
        <groupId>splitlib</groupId>
        <artifactId>lib-api</artifactId>    <!-- 1 -->
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId> <!-- 4 -->
    </dependency>
</dependencies>

Main.java
final class Main {
    static {
        try {
            // 6
            Class.forName(format("%s.Sentinel",  Foo.class.getPackage().getName()));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        // 4
        new AnnotationConfigApplicationContext(Foo.class.getPackage().getName())
                .getBean(Foo.class)
                .bar();
    }
}


text:
Q: Рабочее пространство в кастомном файле Задача:
Необходимо в Activity сделать рабочее пространство. Имеется ввиду прямоугольное поле в которое можно вставлять изображения, текст, аудио и т.п. Все эти компоненты можно масштабировать и размещать в любом месте рабочей области. Саму же область можно масштабировать и сохранять в файл. Аналог Adobe Illustrator
Как это можно реализовать?


text:
Q: Upload large video to server swift using Alamofire I have created an application for recording video and upload it to the server, but I meet problem related with huge file size, after some time I get error:

Task <>.<6> finished with error [-1001] Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={_kCFStreamErrorCodeKey=-2102, NSUnderlyingError=0x280562c70 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <>.<6>, _NSURLErrorRelatedURLSessionTaskErrorKey=("LocalDataTask <6C0A7FA8-C553-4D15-9A2F-8D68E028CE51>.<6>">

How can i upload Data(video-data) using Alamofire "multipart form-data"?
AF.upload(
        multipartFormData: { multipartFormData in
            multipartFormData.append(fileUrl.url, withName: "file", fileName: "testVideo.mp4", mimeType: "video/mp4")
        },
        to: URLs.COMMENT_URL,
        method: .post,
        headers: headers
        ).responseData { response in
           print(response.response?.description)
        }
}

A: One of the solution is to increase the default session timeout by -
// Alamofire Session Object
// Expected in Seconds
session.configuration.timeoutIntervalForRequest = 5*60


text:
Q: How To pass a variable from aspx.cs page to a separate JS file in the same project Ok so   i am fetching data from sql database and i have converted it to json format and stored it in a variabl. And this variable is in the adminBookInventory.aspx.cs .....Now i want to pass this varaible to a separate JS file Named allArtsAndDesignBooks.js ..... anyone here who have any idea about this or have done this before ? i am waiting for your assistance ....
The following code is one of my functions in  adminBookInventory.aspx.cs ...
public void getArtsAndDesignBooks() {

            SqlConnection conn = new SqlConnection(connstring);

            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand(" SELECT * FROM allArtAndDesignBooks", conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            var JSONString = new StringBuilder();
            if (dt.Rows.Count >= 1) {
                JSONString.Append("[");
                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    JSONString.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j < dt.Columns.Count - 1)
                        {
                            JSONString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JSONString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
                        }
                    }
                    if (i == dt.Rows.Count - 1)
                    {
                        JSONString.Append("}");
                    }
                    else
                    {
                        JSONString.Append("},");
                    }
                }
                JSONString.Append("]");
            }
            var allArtsAndDesignBooks= JSONString.ToString();
        }


text:
Q: Define a DerivedClass::BaseClass obj; does not work I am a beginner of c++. I am learning a text on lookup names(or parsing).
I define a instance by "Derived::Base obj" in code below. But the obj does not have a void print() function of Base class. It is strange for me. Or I misunderstand the meaning of "Derived::Base obj".
If someone can tell me what happens in the code. Please tell me it.
class Base {
public:
    void print(void) {
        std::cout << "Base::print()." << std::endl;
    }
};

class Derived : public Base {
};

Derived::Base obj;
obj.print();  // Error!! Compiler gives me an error message "error: 'obj' does not name a type"

A: You can not do this:
 Derived::Base obj;

to create object of derived class, just use:
 Derived d;
 d.print();

(from the comments): the reason compiler didnt gave you any error while:
 Derived::Base obj;

because, it created Base object, instead of derived object.
you can test that, by making similar function in derived class:
void print(void) {
    std::cout << "Derived::print()." << std::endl;
}

and:
Derived d;
d.print();

Derived::Base obj;

obj.print();


text:
Q: Google Wallet API miss in google-play-services I try use Google Wallet API in my own app. I update my Eclipse and SDK to latest version. I try start example from google https://developers.google.com/commerce/wallet/instant-buy/android/resources/instant-buy-android-sample.zip with last google-play-services.jar (file size 632030).
But I get error:

The import com.google.android.gms.wallet cannot be resolved

because in jar-file miss wallet folder.
Where I can get last google-play-services.jar with wallet?

A: The library is not the one which can be downloaded from android sdk
you have to submit request by filling a form for now.
In wallet tutorial they have mentioned it

Important: To run Instant Buy for Android API samples, you'll need to
  download Google Play Services second-party libraries and include them
  in your development project. If you don't already have a Google
  contact to provide access for you, submit the Instant buy interest
  form. Google will respond to qualified merchants with instructions on
  how to get the required libraries and credentials.

link is here


text:
Q: Automatic shutdown after 2 hours on every boot I am using both Ubuntu and Lubuntu 16.04 and this question is regarding both of them.
I want my computer to always shut down 2 hours after it was turned on, i tried to use these instructions that I found to run a timed shutdown on startup but it does not work.
How can I do that?

A: 1.Edit sudoers (you must be root):
gedit /etc/sudoers

At the end add following:
yourusername ALL=(ALL) NOPASSWD: /sbin/shutdown

and save.
2.Crete .sh script:
gedit myscript.sh

add following there:
#!/bin/sh
sudo shutdown -P +120 # shut down after 120 minutes

3.run "startup applications" tool you just need write it in search box. And press Add button:

Write there your .sh script name and path to it. Press add there too.


text:
Q: Error in SQL case statement when trying to create binary flag? Here's my query where I'm testing my case structure:
SELECT TOP 1 CASE 130
WHEN '000000000000000' THEN '0'
WHEN '' THEN '0'
WHEN 'XXX' THEN '0'
WHEN 'RETIRED' THEN '0'
WHEN 'STUDENT' THEN '0'
ELSE '1'
END AS employed_flag
INTO #employedbeta
FROM CreditBureau.Experian

I'm just trying to make a new temporary table, but I'd like my case to work first. I keep getting the error:
Conversion failed when converting the varchar value 'XXX' to data type int.
In the database, the column 130 is a char, and I don't know why it thinks I want to make it a number. SQL server management studio, if it matters.
The column name is 130, I left the '1' off because I rewrote it here but I get the error regardless in my actual query.

A: 130 is an integer literal. If that's really the column name, you'll have to escape it using double quotes. As a side note, you should probably return the same type (char) in the else branch too:
CASE "130"
WHEN '000000000000000' THEN '0'
WHEN '' THEN '0'
WHEN 'XXX' THEN '0'
WHEN 'RETIRED' THEN '0'
WHEN 'STUDENT' THEN '0'
ELSE '1'
END AS employed_flag

A: 130 is a really bad column name.  But, I would simplify the logic to:
SELECT TOP 1 (CASE WHEN [130] IN ('000000000000000', '', 'XXX', 'RETIRED', 'STUDENT')
                   THEN 0 ELSE 1
              END) AS employed_flag
INTO #employedbeta
FROM CreditBureau.Experian;

Note that I also changed the employed_flag to a numeric value rather than a string.  That makes more sense to me.


text:
Q: Deriving the distribution of poisson random variables. Let $X_1, \dots, X_n$ be independent and identically distributed Poisson(µ) random variables.
Derive the distribution of $W= \sum X_i$.
I'm not sure how to answer this, should I use the moment generating function?

A: Yes, we can use the moment generating functions to prove this. We have that
$$
M_W(t)=M_{X_1}(t)M_{X_2}(t)\ldots M_{X_n}(t)=[\exp(\mu(e^t-1))]^n=\exp(n\mu(e^t-1))
$$
using the independence and identical distributions. This means that the sum is a Poisson random variable with the parameter equal to $n\mu$.


text:
Q: Not Executing Function at The Right Time, But Executed After Completion Block Need help in figuring out why my function is not executing when I thought it should but it executed after the completion block in the code. I am fairly new to Xcode so please excuse me if things sound confusing here. Below is my code.
class ImageDownloader{
typealias completionHandler = (Result<Set<ARReferenceImage>, Error>) -> ()
typealias ImageData = (image: UIImage, orientation: CGImagePropertyOrientation, physicalWidth: CGFloat, name: String)

static let URLDic = [ReferenceImagePayload]()

class func getDocumentData(completion:@escaping ([ReferenceImagePayload]) -> ()) {
    var documentCollection: [ReferenceImagePayload] = []
    db.collection("Users").getDocuments {(snapshot, error) in
        if error == nil && snapshot != nil {
            var index = 0
            for document in snapshot!.documents {
                let loadData = document.data()
                index += 1
                if loadData["Target URL"] != nil {
                    let url = loadData["Target URL"]
                    let urlString = URL(string: "\(String(describing: url ?? ""))")
                    let urlName = loadData["Target Image"]
                    documentCollection.append(ReferenceImagePayload(name: urlName as! String, url: urlString!))
                    if snapshot!.documents.count == index {
                        // After finished, send back the loaded data
                        completion(documentCollection)
                    }
                }
            }
          }
    }
}

static var receivedImageData = [ImageData]()

class func downloadImagesFromPaths(_ completion: @escaping completionHandler) {

// THE LINE BELOW WHERE I CALL THE FUNCTION IS NOT EXECUTED WHEN THIS CLASS IS INITIALLY CALLED. BUT AS THE CODE RUNS, THIS LINE BELOW IS EXECUTED AFTER THE COMPLETIONOPERATION = BLOCKOPERATION IS COMPLETED.
    let loadedDataDic: () = getDocumentData { (URLDic) in
        print(URLDic.self, "Got it")
    }

    let operationQueue = OperationQueue()

    operationQueue.maxConcurrentOperationCount = 6

    let completionOperation = BlockOperation {
        OperationQueue.main.addOperation({
        completion(.success(referenceImageFrom(receivedImageData)))

// LINE "let loadedDataDic: () = getDocumentData" ONLY GOT EXECUTED AT THIS POINT
        })
    }

    URLDic.forEach { (loadData) in

            let urlstring = loadData.url

            let operation = BlockOperation(block: {

                do{
                    let imageData = try Data(contentsOf: loadData.url)
                    print(imageData, "Image Data")

                    if let image = UIImage(data: imageData){

                        receivedImageData.append(ImageData(image, .up, 0.1, loadData.name))

                    }
                    }catch{

                        completion(.failure(error))
                    }
                })

                completionOperation.addDependency(operation)
            }

    operationQueue.addOperations(completionOperation.dependencies, waitUntilFinished: false)
    operationQueue.addOperation(completionOperation)

}

}


text:
Q: pthread_join not waiting on threads to finish I am using pthreads.h on Windows, for a simple raytracer. It seems like the main function is not waiting for the threads to finish. When I just run the program like this(I now simplified it, to just test the threads, but it still gives the error):
typedef struct {
    unsigned int id;
} Thread_Data;

void* render_band(void* arg) {
    Thread_Data* data = (Thread_Data*)arg;
    printf("This is thread number %d", data->id);
    pthread_exit(0);
}

int main() {
    pthread_t threads[NUM_THREADS];
    Thread_Data data[NUM_THREADS];
    for (int i = 0; i < NUM_THREADS; i++) {
        data[i].id = id;

        int rc = pthread_create(&threads[i], NULL, render_band, &data[i]);
        if (rc) {
            printf("[ERROR] From pthread_create: %d\n", rc);
        }
    }

    for (int i = 0; i < NUM_THREADS; i++) {
        int rc = pthread_join(threads[i], NULL);
        if (rc) {
            printf("[ERROR] From pthread_join: %d\n", rc);
        }
    }
}

The image won't be completed and only renders a couple of pixels.
When I add a sleep however, the image does finish. Leading me to believe that pthread_join doesn't wait, even though the documentation says so. What am I missing here?
Edit: Added error checking, it returns error code 3 for the pthread_join.

A: I am sorry for wasting everbody's time. The issue ended up being the library itself. When I was looking for pthreads.h on Windows, I found some library on sourceforge. But apparently MinGW already had pthread support, and it messed everything up. So for people with the same issue, just use the one that comes with MinGW.


text:
Q: Deselect Stages By Default In Azure Devops multistage YAML pipeline we got multiple environments.
In stages to run normally we do a build and deploy only in QA, so we need to deselect each stage manually. By default all stages are selected is it possible to have exact opposite, where all stages are deselected by default???

trigger: none
pr: none
stages:
- stage: 'Build'
  jobs:
  - deployment: 'Build'
    pool:
      name: Default
# testing
    environment: INT
    strategy:
      runOnce:
        deploy:
          steps:
          - checkout: none
          - powershell: |
              echo "Hello Testing"
              Start-Sleep -Seconds 10
- stage: 'Sandbox'
  jobs:
  - job: 'Sandbox'
    pool:
      name: Default
    steps:
    - checkout: none
# testing
    - powershell: |
        echo "Hello Testing"
- stage: 'Test'
  jobs:
  - job: 'DEV'
    pool:
      name: Default
    steps:
    - checkout: none
    - powershell: |
        echo "Hello Testing"
- stage: 'QA'
  dependsOn: ['Test','Test1','Test2']
  jobs:
  - job: 'QA'
    pool:
      name: Default
    steps:
    - checkout: none
      # Testing
    - powershell: |
        echo "Hello Testing"

A: I am afraid that there is no UI (like stage to run) method that can meet your needs.
You could try to add parameters to your Yaml Sample.
Here is an example:
trigger: none
pr: none

parameters:
- name: stageTest
  displayName: Run Stage test
  type: boolean
  default: false
- name: stageBuild
  displayName: Run Stage build
  type: boolean
  default: false

stages:
- ${{ if eq(parameters.stageBuild, true) }}:
  - stage: 'Build'
    jobs:
    - deployment: 'Build'
      pool:
        name: Default
      environment: INT
      strategy:
        runOnce:
          deploy:
            steps:
            - checkout: none
            - powershell: |
                echo "Hello Testing"
                Start-Sleep -Seconds 10

- ${{ if eq(parameters.stageTest, true) }}:
  - stage: Test
    dependsOn: []
    jobs:
    - job: B1
      steps:
      - script: echo "B1"

The parameters are used to  determine whether to run these stages. You could add expressions before the stage to check if the parameter value could meet expression.
The default value is false. This means that the stage will not run by default.
Here is the result:

You can select the stage you need to run by clicking the selection box.
Update
Workaround has some limitations. When the select stage has depenencies, you need to select all dependent stages to run.
For example:
  - stage: 'QA'
    dependsOn: ['Test','Test1','Test2']

On the other hand, I have created a suggestion ticket to report this feature request. Here is the suggestion ticket link: Pipeline Deselect Stages By Default You could vote and add comment in it .

A: I've used this solution to build a nuget-package, and:

*

*always push packages from master

*conditionally push packages from other branches

Using GitVersion ensures that the packages from other branches get prerelease version numbers, e.g. 2.2.12-my-branch-name.3 or 2.2.12-PullRequest7803.4. The main branch simply gets 2.2.12, so the master branch is recognized as a "regular" version.
The reason I'm repeating the answer above, is that I chose to make the stage conditional instead of using an if:
trigger:
  - master

parameters:
- name: pushPackage
  displayName: Push the NuGet package
  type: boolean
  default: false

stages:
  - stage: Build
    jobs:
    - job: DoBuild
      steps:
      - script: echo "I'm building a NuGet package (versioned with GitVersion)"

  - stage: Push
    condition: and(succeeded('build'), or(eq('${{ parameters.pushPackage }}', true), eq(variables['build.sourceBranch'], 'refs/heads/master')))
    jobs:
    - job: DoPush
      steps:
      - script: echo "I'm pushing the NuGet package"

Like the other answer, this results in a dialog:

But what's different from the (equally valid) solution with '${{ if }}', is that the stage is always shown (even if it's skipped):


text:
Q: How to set content-type in node-fetch this is my code:
return fetch("https://www.motiondevelopment.top/api/v1.2/bots/" + botid + "/stats", {
        method: "post",
        headers: {
            "Content-Type": "application/json",
            "key": apikey,
        },
        body: { "guilds": serverNumber }
    }).then((response) => {
        return response.json().then((data) => {
            return data;
        }).catch((err) => {
            console.log("[MotionBotList]: " + err);
        })
    });

At the moment it will not use the content-type application/json and I don't know why. Could someone help please?

A: I think you need to stringify body object.
here is the updated code:
fetch("https://www.motiondevelopment.top/api/v1.2/bots/" + botid + "/stats", {
  method: "post",
  headers: {
    "Content-Type": "application/json",
    "key": apikey,
  },
  body: JSON.stringify({ "guilds": serverNumber })
})
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.log(err))

you can read details about feach api here


text:
Q: How to start using Ribbons in WPF I tried referencing the System.Windows.Controls.Ribbon, the toolbox tab does not show up. If I right-click a tab and click show all, the tab is there, but controls aren't light up. I can add a tab and controls related manually, but after adding the ribbon, things like quickaccesstoolbar and menuitem does not work properly - they are being treated as tabs for some reason. Control groups don't work as well. Simply nothing works as it's supposed to.
I have tried editing XAML directly. It fails in the same manner as using the designer.
The tutorials online are either outdated, for a paid control suite, or simply don't work.
I don't want to use mark-up solutions like http://www.codeproject.com/Articles/364272/Easily-Add-a-Ribbon-into-a-WinForms-Application-Cs , I want something that works in a designer -- Is that too much to ask? If so I'll gladly go back to winforms.
If you work with ribbons, how did you do it? This question seems simple, but after digging for hours I still don't have an answer.
I'm an individual developer, making an open source, free software. As a student I really can't afford 1000$ control suites. I use VS2013 community, I tried using 2015 instead, but all the problems above are the same.

A: Please take a look at the following. You should be able to have a very basic idea about Ribbon.
http://blogs.msdn.com/b/wpf/archive/2010/08/03/introducing-microsoft-ribbon-for-wpf.aspx
Sample project download
If you want to run the project, you need to change the project's .NET Framework version to 4.0 or above.
Add System.Window.Controls.Ribbon reference to the project
Remove reference like System.Window.Shell and RibbonControlLibrary
The sample should be able to run after you fixed all the namespaces in xmal and the codebehind .cs
http://blogs.msdn.com/b/wpf/archive/2010/08/03/building-a-simple-ribbon-application-in-wpf.aspx
Microsoft Ribbon for WPF (Get the one with Sample for more comprehensive sample)
http://www.microsoft.com/en-us/download/details.aspx?id=11877

A: Add this reference:

and this namespace in the XAML file:

and try working with this code example:
 <DockPanel>
    <Ribbon DockPanel.Dock="Top" Margin="0,-22,0,0">
        <Ribbon.ApplicationMenu>
            <RibbonApplicationMenu SmallImageSource="Images/list.png">
                <RibbonApplicationMenu.AuxiliaryPaneContent>
                    <RibbonGallery ScrollViewer.VerticalScrollBarVisibility="Auto">
                        <RibbonGalleryCategory MaxColumnCount="1">
                            <RibbonGalleryItem
                            x:Name="GalleryItem1" Content="Application menu content"
                            MouseOverBackground="Transparent"
                            MouseOverBorderBrush="Transparent"
                            CheckedBackground="Transparent"
                            CheckedBorderBrush="Transparent"
                            />
                            <RibbonGalleryItem>
                                <Hyperlink x:Name="hl1" Click="hl1_Click">
                                    <Run Text="http://www.bing.com"/>
                                </Hyperlink>
                            </RibbonGalleryItem>
                        </RibbonGalleryCategory>
                    </RibbonGallery>
                </RibbonApplicationMenu.AuxiliaryPaneContent>
                <RibbonApplicationMenuItem x:Name="menuItem1" Header="Add"
                    ImageSource="Images/add.png"/>
                <RibbonApplicationMenuItem x:Name="menuItem2" Header="Settings"
                    ImageSource="Images/system_preferences.png"/>
            <RibbonApplicationMenu>
        </Ribbon.ApplicationMenu>
        <RibbonTab x:Name="rbnTab1" Header="Tab1">
            <RibbonGroup x:Name="rbnGr1" Header="General">
                <RibbonButton x:Name="btnRibbon1" Label="Save"
                    LargeImageSource="Images/filesave.png"/>
                <RibbonButton x:Name="btnRibbon2" Label="Open"
                    LargeImageSource="Images/load.png"/>
            </RibbonGroup>
            <RibbonGroup x:Name="rbnGr2" Header="New group">
                <RibbonButton x:Name="btnRibbon3" Label="Font"
                    LargeImageSource="Images/fonts.png"/>
                <RibbonButton x:Name="btnRibbon4" Label="Delete"
                    LargeImageSource="Images/recycle_bin.png"/>
            </RibbonGroup>
        </RibbonTab>
        <RibbonTab x:Name="rbnTab2" Header="Tab2">
            <RibbonGroup x:Name="rbnGr3" Header="Other Group">
                <RibbonButton x:Name="btnRibbon5" Label="Play"
                    LargeImageSource="Images/play.png"/>
                <RibbonButton x:Name="btnRibbon6" Label="List"
                    LargeImageSource="Images/kmenuedit.png"/>
            </RibbonGroup>
            <RibbonGroup x:Name="rbnGr4" Header="What a group">
                <RibbonButton x:Name="btnRibbon7" Label="Sleep"
                    LargeImageSource="Images/icon_sleep.png"/>
                <RibbonButton x:Name="btnRibbon8" Label="Add"
                    LargeImageSource="Images/add.png"/>
            </RibbonGroup>
        </RibbonTab>
    </Ribbon>

    <Grid>
        <!-- add your content here-->

    </Grid>
</DockPanel>

You can remove the <Ribbon.ApplicationMenu> if you don't like it by addin this property Visibility="Collapsed"
<Ribbon.ApplicationMenu>
    <RibbonApplicationMenu Visibility="Collapsed">
    </RibbonApplicationMenu>
</Ribbon.ApplicationMenu>