text:
Q: Can I use Exchange Web Services to get active directory listing? I am a developer on a system that connects to external customer mail servers using EWS.  This is the only direct connection we have with them.
They also occasionally send us a CSV dump of their active directory users so we can upload it into our system.
I'd like to improve this process.
If I log on to the OWA portal using the EWS credentials I can see all their corporate users under Contacts, so the information is there and accessible in some form.
Is there a way I can pull that data myself through the EWS connection (eg as an LDAP query)? and process their user records from our side?

A: It really depends on the version of Exchange the customer is running and the size of the Address book. On Exchange 2010 EWS is limited in what it can do on the Address side you have ResolveName https://msdn.microsoft.com/en-us/library/office/aa563518(v=exchg.150).aspx where you can get a maximum of 100 entries returned at a time so if you do a resolve on "SMTP:" that will return the first 100 entries in the GAL (so if its less than 100 it will work fine) if its greater than 100 than its doesn't work that well. One workaround is putting all the entries in a Group and then using Expand Group to get all the Email Address then use multiple ResolveNames to get the contact details.
On 2013 there is the FindPeople operation https://msdn.microsoft.com/en-us/library/office/jj191039%28v=exchg.150%29.aspx which if you have the Address book Guid you can return all the entries in the GAL (Find People support paging when using the eg)
FindPeopleType fpType = new FindPeopleType();
IndexedPageViewType indexPageView = new IndexedPageViewType();
indexPageView.BasePoint = IndexBasePointType.Beginning;
indexPageView.Offset = 0;
indexPageView.MaxEntriesReturned = 100;
indexPageView.MaxEntriesReturnedSpecified = true;
fpType.IndexedPageItemView = indexPageView;

fpType.ParentFolderId = new TargetFolderIdType();
DistinguishedFolderIdType contactsFolder = new DistinguishedFolderIdType();
AddressListIdType adList = new AddressListIdType();
adList.Id = "2117949e-abe8-4915-91eb-6b9f867fd8de";

fpType.ParentFolderId.Item = adList;
FindPeopleResponseMessageType fpm = null;
do
{
    fpm = esb.FindPeople(fpType);
    if (fpm.ResponseClass == ResponseClassType.Success)
    {
        foreach (PersonaType PsCnt in fpm.People) {
            Console.WriteLine(PsCnt.EmailAddress.EmailAddress);
        }
        indexPageView.Offset += fpm.People.Length;
    }
    else {
        throw new Exception("Error");
    }
} while (fpm.TotalNumberOfPeopleInView > indexPageView.Offset);

If they are using Office365 then the Graph API a better option.
Cheers
Glen


text:
Q: Не подключается SVG спрайт Пробую подключить SVG спрайт с помощью object, но он не подгружает svg файл и use не срабатывают. Я уже совсем отчаялся. Возможно кто-то сталкивался с таким или просто ткнет меня носом, где я косяк допустил.
<object type="image/svg+xml" data="/images/sprite.svg">
</object>

подключаю в body.
<svg>
     <use xlink:href="images/sprite.svg#cloth"/></use>
</svg>

такая конструкция не срабатывает
А может что-то в самом спрайте не так сделал. Если что - вот ссыль http://dropmefiles.com/0q1J8

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I get the treasure in the Lava Pools section of Ignan Ruins(2-3)? As the last remaining secret treasure I haven't discovered in the Ignan Ruins, I am very eager to find riches in the Lava Pools. However, I'm struggling quite a bit, and I don't want to waste my precious health purchasing a hint.
Currently I have tried:

*

*Luring all of the bombs together(like a bomb party, or a bomb family reunion). This failed because the bombs hit an invisible wall when they venture too far from their spawn points.

*Hitting all the rocks

*Hitting all the rocks as many times as the fire pillars near them shoot up

*Jumping into the fire pillars that shoot out from the lava

*Jumping into all the lava I can find while craning my neck in a vain attempt to look for sekret passages

*Luring the bomb at the top-most platform into the bridge gap to kill it

*Running around in circles

I have NOT tried:

*

*Killing only bombs/fire slimes/bees/mushrooms since the jumping enemies are very suicidal and I'm too young to die from a frustration-induced stroke

*Killing all the jumping enemies by making them jump into the lava because this isn't Waiting For Godot

*Rubbing my belly and patting my head while singing because I'd feel silly

What do I do?!

A: The solution to this is to only break the barrels after you have cleared all of the enemies.
Naturally, the barrels are in your way at the start, and you can't exactly jump over them. Which means we need to take a shortcut.
First, clear out all of the enemies on your starting side of the barrels. So, all of those purple Mushrooms, a handful of Bees, and that one Bomb in the middle. Once you've got none left (Red slimes don't count), you need to move onto the central platform. Head straight east and jump to land roughly in the middle of a circle of Mushrooms. Now you're past the barrels!
You'll need to double back towards the barrels to catch a couple Bees and Mushrooms. Make sure not to break the barrels yet. As well, you should hopefully harvest enough magical gems from enemies to take out the Bombs safely. Once you clear the last enemy (it'd dispel the barrier, if this is your first time or a time trial), then double back and break the barrels. You'll spawn the chest near the entrance of the room.
Your prize is as follows.

 Ferromin! That's... it. +10 Max HP, though, so use it to buy more hints!


text:
Q: Is deleting every index individually the only way? I am trying to make an array of pointers of a class data type Pool but deleting it as if it were an array does not work.
This is the code:
struct Pool {
    /* in reality, complicated stuff here */
    int size;
};

Pool* createLargePool() { return new Pool{100}; }
Pool* createMediumPool() { return new Pool{20}; }
Pool* createSmallPool() { return new Pool{5}; }

int main() {
    using namespace std;

    enum ePool{
        small,
        medium,
        large,
        last
    };

    Pool *pools[ePool::last] = {
        createLargePool()
        , createMediumPool()
        , createSmallPool()
    };

    //Individually works.
    delete pools[0];
    delete pools[1];
    delete pools[2];
    //delete[] pools;// error. (assertion error?)
    system("pause");
    return 0;
}

To my understanding, my line Pool *pools[] is creating an array of Pool pointers. And that is exactly what my IDE is saying I'm doing. I'm running the code without problems until I reach the delete statement.
for some reason delete[] causing me problems, but deleting each one individually does not:
What's going on and how can I get delete[] to work?

A: The only way to delete each element with a single command is to make it a std::vector<std::unique_ptr<Pool>> and call pools.clear().
All other solutions require you to loop over the elements and delete them individually.

Moreover, your create*Pool() functions should not return raw pointers. They should return smart pointers, for two reasons:

*

*Users will then know that they are responsible for deleting the pointer.
(With raw pointers they'd have to look at the internal implementations and/or documentation to know that.)

*This makes memory leaks virtually impossible, because the user now doesn't have to remember to call delete somewhere, which can be very difficult to get right in a complex project.
So I'd recommend returning a std::unique_ptr:
std::unique_ptr<Pool> createLargePool() { return std::unique_ptr<Pool>(new Pool{100}); }

or better yet (in C++14):
std::unique_ptr<Pool> createLargePool() { return std::make_unique<Pool>(100); }

Now, even if you store the smart pointers in a raw static array:
std::unique_ptr<Pool> pools[ePool::last] = {
    createLargePool()
    , createMediumPool()
    , createSmallPool()
};

they will delete their managed pointer when the array goes out of scope.

A:
"What's going on and how can I get delete[] to work?"

Of course delete[] or delete without a prior new[] or new statement doesn't work.
Calling either form of delete in case the memory wasn't allocated dynamically, raises undefined behaviour.

A: You would use delete[] if you were creating a dynamic array of Pools. But what (it looks to me like) you're doing here is creating a static array of pointers to dynamic Pools. So, rather than delete[]ing the whole thing as though it were a dynamic array, which it isn't, what you need to do instead is delete each individual pointer in the array, as you inadvertently discovered.
Note, however, that deleting each element explicitly is verbose and fragile; better to loop through them like this:
for (int i = 0; i < ePool::last; ++i)
    delete pools[i];

or, even better, like this:
for (Pool *p: pools)
    delete p;

A:
To my understanding, my line Pool *pools[] is creating an array of Pool pointers.

Correct.  Specifically, a local static array of 3 Pool* pointers.

for some reason delete[] causing me problems, but deleting each one individually does not

You are not allocating the array with new[], so you cannot free it with delete[].  It lives on the stack, not on the heap, and thus will be reclaimed when the array goes out of scope.
However, your array elements are pointers to dynamically allocated Pool objects, and those need to be freed with delete regardless of how the array is allocated.  Even if the array were allocated dynamically with new[], you would still need to delete the individual Pool objects before freeing the array with delete[].

What's going on and how can I get delete[] to work?

If you really want to use delete[], you have to use new[]:
Pool** pools = new Pool*[ePool::last];
pools[0] = createLargePool(Vector3i(12, 45));
pools[1] = createMediumPool(Vector3i(12, 45));
pools[2] = createSmallPool(Vector3i(12, 45));

...

delete pools[0];
delete pools[1];
delete pools[2];
delete[] pools;

Otherwise, you should use a std::vector instead of new[]:
std::vector<Pool*> pools(ePool::last);
pools[0] = createLargePool(Vector3i(12, 45));
pools[1] = createMediumPool(Vector3i(12, 45));
pools[2] = createSmallPool(Vector3i(12, 45));

Or:
std::vector<Pool*> pools;
pools.reserve(ePool::last);
pools.push_back(createLargePool(Vector3i(12, 45)));
pools.push_back(createMediumPool(Vector3i(12, 45)));
pools.push_back(createSmallPool(Vector3i(12, 45)));

To free the pools, you can use a loop:
// C++11 and later only...
for (Pool* pool : pools)
    delete pool;

Or:
for (int i = ePool::small; i < ePool::last; ++i)
    delete pools[i];

Or:
for (std::vector<Pool*>::iterator iter = pools.begin(); iter != pools.end(); ++iter)
    delete *iter;

Or:
void freePool(Pool *pool)
{
    delete pool;
}

std::for_each(pools.begin(), pools.end(), freePool);

If you are using C++11, you can use std::unique_ptr<Pool> instead of Pool* as the std::vector elements and eliminate calling delete manually (std::auto_ptr is not safe to use in STL containers, so don't try it):
std::vector<std::unique_ptr<Pool>> pools;
...

However, since you have a small fixed number of pools, an array of std::unique_ptr<Pool> (C++11 and later) or std::auto_ptr<Pool> elements would be less overhead than a std::vector:
#include <memory>

int main()
{
    std::unique_ptr<Pool> pools[ePool::last];
    pools[ePool::small] = createSmallPool();
    pools[ePool::medium] = createMediumPool();
    pools[ePool::large] = createLargePool();
    /*
    std::auto_ptr<Pool> pools[ePool::last];
    pools[ePool::small].reset(createSmallPool());
    pools[ePool::medium].reset(createMediumPool());
    pools[ePool::large].reset(createLargePool());
    */

    ...

    system("pause");
    return 0;
}

BTW on a side note, you are creating your pools in backward order.  Your enum is ordered as small/medium/large, but your array is ordered as large/medium/small instead.  You need to swap createLargePool() and createSmallPool() around, as shown above.

A: As mentioned in the comments you can't call delete[] on an array that wasn't allocated on the free-store with new[]. However, to answer the other aspect of your question that is posed, there is a better way to de-allocate everything automatically. Instead of an array, use a std::vector<Pool> pools and for each pool just do pools.push_back( createMediumPool(Vector3i(12, 45)) ) etc...
Then, when pools goes out of scope, it automatically will call the destructor of every pool it contains, and all of the deallocations will happen automatically. As an added bonus, if you throw an error and take the "unhappy path" of your code at some point, it will still deallocate all of the resources automatically. This is the Resource Allocation Is Initialization (RAII) principle.

A: Your array is allocated on the stack and does not need to be deleted. Stack based variables don't have to be, and in fact, should not be deleted. You only use delete to clean up heap based objects. Take this example (assume that you have a typical 32 bit system and that sizeof(int) == 4 bytes)
void foo() {
    int x    = 10;             // x on stack. consumes 4 bytes
    int y[3] = { 29, 42, 17};  // y on stack. consumes 12 bytes
    int z    = 11;             // z on stack. another 4 bytes

    cout << "Address of x    = " << &x    << endl;
    cout << "Address of y[0] = " << &y[0] << endl;
    cout << "Address of y[1] = " << &y[1] << endl;
    cout << "Address of y[2] = " << &y[2] << endl;
    cout << "Address of z    = " << &z    << endl;

    delete x; // NO! Don't delete a stack based variable
    delete y; // NO! Don't delete him either
    delete z; // NO! What's wrong with you.
}

The compiler generates code to manage stack based variables. Spaced is allocated on the stack at the start of the function, and is reclaimed when the function returns.
Objects on the heap follow different lifecycle rules. It is up to you to to delete them when you are done with them.
void foo() {
    int *x   = new int;      // x points to a 4 byte memory block on the heap
    int *y   = new int[3];   // y points to a 12 byte memory block on the heap

    delete x;   // Yes. Thank you.
    delete []y; // Correct.
}

Your code example gets a little complicated because you have a stack based array that holds heap based objects. You need to delete the individual heap based objects in the array, but not the array itself.
Here is an example that shows the various flavors
struct Pool {
   int x;
};

int main() {
    Pool p1[2] = {1,2} ; // array of objects. Everything lives on the stack.
    Pool* p2[2] = {new Pool, new Pool} ; // array of pointers. Array on stack. Pools in it live on the heap
    Pool *p3 = new Pool[2]; // heap based array of objects.
    p3[0].x=1;
    p3[1].x=7;
    Pool **p4 = new Pool*[2]; // heap based array of pointers to objects.
    p4[0] = new Pool;
    p4[1] = new Pool;

    // cleanup
    // none for p1
    delete p2[0];  // delete the heap based objects inside p2
    delete p2[1];

    delete [] p3;  // delete the heap of objects

    delete p4[0]; // delete pointers inside p4
    delete p4[1];
    delete []p4;  // plus the heap based array;
    return 0;
}


text:
Q: Getting unique elements and intersection of two (or x) lists efficiently If I have two (or more) lists, I would like to get all parts of the "venn diagram" made by those lists: i.e. elements unique to A, elements unique to B, and the intersection of A and B.
The "standard", but also naive, way of getting such a result would be using two loops, by going through all of A and checking if the elements are in B or not, thus getting the results of A_unique and intersection. By then looping through B and checking if the elements are in A, we would get B_unique.
Most languages have some kind of intersect or difference function implemented in their standard libraries, but they usually work that way anyway.
However, this seems extremely inefficient. Is there a better way / algorithm of getting those three parts, without having to loop twice (and perhaps even without using standard "contains" calls on the other list, which usually loops through that list as well, thus making each loop O(n^2)...)?
Would it perhaps already be an improvement to make both lists be queues, and pop the first item on each loop, thus reducing the amount of subsequent checks?

A: You can do this with a single loop in (at least) two ways, with a preprocessing step. The following algorithms assume that neither list has duplicate elements; modifying it to handle duplicate elements is simpler with the second algorithm but can be done with the first one as well.
With a hash set.

*

*Create a hash table from list A. (Perhaps better, from the smaller of the lists, but I'm going to write this as if it's list A.)

*Create empty lists Only B and In Both

*For each element in B:

*

*If it's not in the hash table, put in in Only B.

*If it's in the hash table, remove it and put in In Both.

*When you're done with the loop, whatever is left in the hash table is Only A.
Using heaps / priority queues

*

*Use makeheap to turn both lists into min heaps

*While both heaps have elements:

*

*If the smallest element in A is (strictly) less than the smallest element in B, remove it and put it in Only A.

*Otherwise, if the smallest element in B is (strictly) less than the smallest element in A, remove it and put it into Only B

*Otherwise, the smallest element of both heaps are equal. Remove both of them and put one in In Both.

*When one heap is empty, put all the elements of the other heap into Only A or Only B, depending on which heap still has elements left. If you want the new sets to be sorted, use the heap's remove-min method; if you don't care, you can save a few cycles by just copying from the underlying array.

You can run this algorithm in-place to avoid memory allocations, as long as you don't care about the order of the resulting lists, by keeping In Both at the end of one (or both) of the originals, maintaining a partition point, which is initially at the very end (indicating that the In Both list is empty). Instead of putting an element present in both lists into a separate data structure, you remove it as usual from its heap, which moves it to the beginning of the free space, then swap it with the element just before the partition point, and finally move the partition back one element.


text:
Q: Laravel 4 - Model not being saved Having this code:
class SearchIndex extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'searchindex';

    //no timestamps
    public $timestamps = false;

    //mass-assignment
    public $fillable = array('url', 'content', 'version', 'digest');
    public $guarded = array();

    public static function updateIndex($url, $version, $content)
    {
        self::retrieveSearchEntry($url, $version)->updateContent($content)->save();
    }

    public static function retrieveSearchEntry($url, $version)
    {
        try
        {
            return self::withoutContent()->where('url', $url)->where('version', $version)->firstOrFail(array('url', 'version', 'digest'));
        }
        catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e)
        {
            return new SearchIndex(array('url' => $url, 'version' => $version));
        }
    }

    public function updateContent($content)
    {
        $hash = md5($content);
        if (!isset($this->digest) || ($this->digest != $hash))
        {
            $this->content = $content;
            $this->digest = $hash;
        }
        return $this;
    }

    public static function search($content)
    {

    }
}

If I call updateIndex providing a new combination of url+version, an entry is created.
If I call updateIndex providing an existing pair of url+version, the entry is not updated with the new content. I'm seeing it has something to do with the fact that I'm omitting the 'content' field (reason: is huge, and I want to set it, not get it, in that function).
question: How can I not-get the content field, but be able to set it when saving?

A: Solved. Reason: I was not selecting the "id" field when doing the custom selection in firstOrFail(). In that way, id was null and the generated SQL tried to update (since it was an existent object) "where id is NULL", which would affect 0 rows.


text:
Q: If light has energy, does it have mass? Light has energy, so does that mean it has mass due to what $E=mc^2$ tells us? And if light does have mass, then how does it still travel at the speed of causality? I feel like I'm getting confused between relativistic mass and rest mass or I'm misinterpreting $E=mc^2$.

A: In special relativity mass can be interpreted as the energy of a system in the (inertial) frame that minimizes the energy (the "rest frame") or equivalently as the absolute value of the square root of the norm of the total energy-momentum four vector of the system.
For a single photon/beam of light, there is no minimum energy frame, but the greatest lower bound of the energy is zero, so a photon/beam of light has zero mass.
However in a system of, for example, two photons taking antiparallel paths there is a frame that minimizes the energy of the system and that minimum energy is non-zero and so the system is not massless. This means that a system consisting entirely of photons can have a non-zero mass, even though individual photons are necessarily massless.

A: $E = mc^2 = \gamma m_0 c^2$, where $m_0$ is the rest mass and $m = \gamma m_0$ is the 'relativistic mass' (Note that this is not a 'real' mass - it's a mathematical trick to make the relativistic momentum formula look the same as it does in classical mechanics - $p = mv$ is still true in special rel if m is relativistic mass). The term is misleading, however, because $KE \neq mv^2$, $KE = (1-\gamma)m_0c^2$.
Let's look in detail at what happens to $E = \gamma m_0c^2$ as $v \rightarrow c$ and $m_0 \rightarrow 0$.
$E = \frac{m_0}{\sqrt{1-v^2/c^2}}c^2 \rightarrow \frac{0}{0}c^2$
Now that 0/0 term is nasty - the mathematicians call it 'indeterminate form' because it doesn't actually have any meaning. In other words, the mathematics says "I have no heckin' idea what the energy is," we need to use something else to figure it out.
This mathematics is also a strong motivation that any particle traveling at c must have zero mass - if the numerator were anything other than zero, $m_0/0$ would cease to be indeterminate and become undefined - indeterminate means that the equation is unhelpful, but undefined means that the equation is violated. Hence any luminal particle must have zero rest mass.
Light has no rest mass, but it is possible to think of it as having a 'relativistic mass' by applying $m = E/c^2$ with no regard to the gamma factor. However, this does not mean that light has mass in any meaningful way - it is simply a measure of how much mass a stationary particle would give up to be entirely converted into the light.
TL;DR: Light has no rest mass, but we can assign it a 'mass' based on $E=mc^2$. However, it is not 'real mass' in the sense that it cannot be used to accurately calculate the mechanical properties of photons in the way you'd expect.
Side note: Most physicists prefer the more complete formula $E^2 = p^2c^2 + m_0^2c^4$, where $E$ is the particle's energy, $p$ is the particle's momentum, and $m_0$ is the particle's rest mass. For a stationary, massive particle, $p=0 \Rightarrow E^2 = m_0^2c^4 \Rightarrow E = m_0c^2$, and for a massless particle, $E^2 = p^2c^2 \Rightarrow E = pc$, which is the fundamental relationship for light.


text:
Q: Can only counterexamples disprove conditional statements Consider the statement "If $\sum x_n$ converges conditionally and every $x_n$ contains no digit 2 in its decimal expansion then $\sum x_n$ converges absolutely". It is almost certainly false, containing a digit 2 is irrelevant from converging absolutely. Yet it seems quite difficult/awkward to come up with a counter example. Please don't give one, its besides the point of this question. Is there any logical argument that disproves a conditional statement like this without having to provide an example?
Something to the effect of  "Property $X$ is irrelevant to Property $Y$ thus $X \nRightarrow Y $". Traditionally we're taught that this line of reasoning is cardinal sin so I am anticipating a fat "NO".

A: The point is: If the claim is false and a counter example exists, then there are often many counter examples or even infinitely many (which applies IMO to your example).
This means that any generic proof will be a superset of (infinitely) many explicit counter examples.  And such "generic" counter examples are usually harder to find than a specific one; that's the reason why you'll typically see specific counterexamples.  The smaller the set is that the generic proof encompasses, the harder it is usually to write and to understand.  Yet trying some generic proof can lead you to (more) specific counter examples, or to more refined versions of the proposition.
Moreover, "conditional convergence" is a rather technical term from inifnite series, which means that re-ordering the sequence under consideration might change its convergence behavior or value.  So I am not shure if you confused "conditional statement" with "conditional convergence"?  "Conditional convergence" basically means "convergent but not absolutely convergent".


text:
Q: Cmake: link openscenegraph to my shared library I'm new in using CMake, and I need to link openscenegraph library to my shared library.
Part of code responsible for it looks like this:
add_library (MyLib SHARED ${${PROJECT_NAME}_sources})
target_link_libraries(MyLib ${OPENSCENEGRAPH_LIBRARIES})

Im finding osg like this:
find_package(OpenSceneGraph REQUIRED osgDB osgUtil osg osgViewer osgGA osgShadow)
include_directories(${OPENSCENEGRAPH_INCLUDE_DIRS})
add_definitions(${OPENSCENEGRAPH_DEFINITIONS})

And everything looks like it is linking, CMake isn't giving me any errors, but during building with Visual Studio 2010 I got errors like:
fatal error C1083: Cannot open include file: 'osg/Node': No such file or directory

Usually I was finding answers to all my questions without asking them (this is my first question here).
This may be trivial, but can someone tell me what am I doing wrong, and how can I make it work?

A: This doesn't seems related to linking, but to compile. The error says that MSVC doesn't find the file 'osg/Node' in the list of included directories.
Somewhere in your source code, you probably have an include like
#include "osg/Node"

so compiler will search for a file called 'Node' in the directory called 'osg' in one of the 'include directories'.
In CMake, print the list of include dirs for OpenSceneGraph (after find_package(OpenSceneGraph ...)
message(STATUS "OSG Incl dirs: ${OPENSCENEGRAPH_INCLUDE_DIRS}")

then check this list. If it contains something like C:/path/to/openscenegraph/include then you should import Node using
#include "osg/Node"

If instead you have a folder for each module (ex: C:/path/to/openscenegraph/include/osg) so you must use
#include "Node"

If you don't want to modify includes in your code, then you have to add C:/path/to/openscenegraph/include in your include directories (from CMake script)
include_directories(C:/path/to/openscenegraph/include)


text:
Q:  How do I load multiple textures from the same file? How do I load multiple textures from the same file?
I'm learning LibGDX and I don't know how this process is named.
I have a file that contains all the textures I need. Is it possible to load textures by selecting regions on the same file?

A: look this ->
https://github.com/libgdx/libgdx/wiki/Texture-packer
I think what you are looking for is the textureAtlas the link also talks about that and can look elsewhere.
I do not use gui for texturePacket, but maybe this this is to your liking
http://www.aurelienribon.com/blog/category/desktop-applications/libgdx-texturepacker-gui/
Also, on the other hand:
How to use/setup TexturePacker2 libgdx
I hope help
perhaps also want to look at this ->
https://github.com/libgdx/libgdx/wiki/Managing-your-


text:
Q: Using Switch and Try Statement to Validate user Input I've been working on this for a little while and it won't compile. It gives me an error saying

variable choice might not have been
  initialized
                switch(choice)
                       ^

but I have that variable set in the program. So I don't know what the problem is? Is it really something else that's keeping this from compiling?
 import java.io.*;
    import javax.swing.JOptionPane;

    public class MyType
    {
        public static void main(String[] args)
        {
            String strChoice = "", strTryString, strTryInt, strTryDouble;
            Integer choice, tryInt;
            double tryDouble;
            boolean done = false;

            while(!done)
        {
                try
                {
                    String answer = JOptionPane.showInputDialog(null, "What's my type\n\n\n1) String\n2) integer\n3) double\n4) Quit the program");
                    choice = Integer.parseInt(strChoice);

                    //test for valid codes 1, 2, 3, or 4
                    if (choice<1 || choice>4) throw new NumberFormatException();
                    else done = true;
                }
                    catch(NumberFormatException e)
                {
                    JOptionPane.showInputDialog(null, "Please enter a 1, 2, 3, or 4", "Error", JOptionPane.INFORMATION_MESSAGE);
                    switch(choice)
                {
                        case 1:
                            JOptionPane.showMessageDialog(null, "Correct, any input can be saved as a String");
                            break;

                        case 2:
                            JOptionPane.showMessageDialog(null, "Correct!");
                            tryInt = Integer.parseInt(strChoice);
                            break;

                        case 3:
                            JOptionPane.showMessageDialog(null, "Correct!");
                            tryDouble = Integer.parseInt(strChoice);
                            break;

                        case 4:
                            done = true;
                            JOptionPane.showMessageDialog(null, "Exit.");
                            System.exit(0);
                            break;
                        default:  throw new NumberFormatException();
            }
            }

            }
        }
    }

A: If the showInputDialog throws, then 'choice' is not set.
try
            {
                String answer = JOptionPane.showInputDialog(null, "What's my type\n\n\n1) String\n2) integer\n3) double\n4) Quit the program");
                choice = Integer.parseInt(strChoice);

                //test for valid codes 1, 2, 3, or 4
                if (choice<1 || choice>4) throw new NumberFormatException();
                else done = true;
            }
                catch(NumberFormatException e)
            {

A: you should iniatialize the choice variable before try block, as you are referencing it in catch which in some case if the exception is thrown before initialization of choice happining then the varaible choice will be uninitialized.


text:
Q: @RequestScoped + new thread We use javaEE RequestScoped with OpenLiberty and new threads via EJB @Asynchronous. I am just curious what the actual value comes from when we inject RequestScoped bean inside a new thread? Will the RequestScoped bean be freshly initialized? Or will it be pulled from the latest request?

A: In OpenLiberty, you'll get a new request scope every time you make an EJB @Asynchronous call, meaning that you'll get a new freshly initialized instance of any injected RequestScoped beans while you're within that method call.


text:
Q: iPhone / iPod Touch mailto link destroys javascript timers In mobile safari on iPhone or iPod Touch if a user clicks on a mailto link and then returns to the page (either send or cancel), timers no longer function inside of javascript.  I've posted a bug to apple, and on openradar.
However, I was wondering if anyone out there has come across this before and come up with some sort of workaround.
update:  Here is some sample code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <title>Testing</title>

Normal: 0

Timed: 0

Interval: 0

        Click Me

        Mail To

To clear up some apparent confusion about what I'm saying is a bug, its not that when you leave the page and return any timers that had been running have stopped, this is to be expected.  The problem is that once a user returns to the page if you start new timers, they will never fire.

A: That' not a bug because the browser windows is actually closed when the Mail application launches. When the user returns, it's restored but any scripts that were running will have halted.
Though this is not very nice, it's expected.


text:
Q: How to provide data to users in a way similar to Mathematica's curated data How can one go about implementing a custom data backend usable by Mathematica? For example something like CountryData or FinancialData?
I would like to expose our data backend as a service with similar access logic used in the above mentioned data libraries.

A: More of a long comment...
You can easily write a function that will enable your end users to Import data from your custom backend.
customData[param1_]:= Import[...]
customData[param1_, param2_]:= Import[...]
customData[param1_, param2_, param3_]:= Import[...]

Using different parameter sets in your function definition can give you all the kinds of flexibility you see in CountryData or FinancialData.
Placing you functions in an automatically loaded package would make the user experience even better.
I/we would really need some better idea of what you have tried to provide a more complete and useful answer.


text:
Q: Is it possible to change the edges for some tree level using forest package? Is it possible to change this MWE which is using forest package to produce a tree, similar to that produced by the next MWE that is not using forest? The very last level of child nodes would have to be stacked on top of each other with edge drawn from the south of the parent to the west of the child.
After reading the Forest manual, I got an impression that the key where n children=0 should be able to help, and added the line with the comment, but no matter what grow parameter I supplied, such as north/south, or 0-45-90-120 etc, the direction of growth did not change.
The solution probably lies in the pp. 10-12 of the Forest manual, but it is evading me :(
\documentclass{article}
\usepackage{forest}

\begin{document}

\begin{forest}
for tree={
  where n children=0{draw=red,grow=120}{}, %<============
  edge path={
    \noexpand\path[\forestoption{edge}]
      (!u.parent anchor) -- +(0,-15pt) -|
      (.child anchor)\forestoption{edge label};
  },
  l sep=10pt,
}
[P
  [N1
    [N1C1]
    [N1C2]
  ]
  [N2
    [N2C1]
    [N2C2]
  ]
]
\end{forest}
\end{document}

Without forest (the lowest level edge is different and the nodes are stacked):
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{trees}

\begin{document}

\begin{tikzpicture}[
    children/.style={grow=down,xshift=-0.2cm,
        edge from parent path={(\tikzparentnode.201) |- (\tikzchildnode.west)}
    },
    level1/.style ={level distance=4em,anchor=west},
    level2/.style ={level distance=8em,anchor=west},
    level 1/.style={edge from parent fork down,sibling distance=5em,level distance=4em
    }
]
    \node[anchor=south](super){P}[]
    child{node {N1}
        child[children,level1] {node {N1C1}}
        child[children,level2] {node {N1C2}}
    }
    child{node {N2}
        child[children,level1] {node {N2C1}}
        child[children,level2] {node {N2C2}}};
\end{tikzpicture}
\end{document}

A: Option where n children is the correct choice. However, setting grow changes the growth direction of child nodes, not the node itself. Thus:
where n children=0{draw=red,for parent={grow'=120}}{},

(grow' reverses the order of children.)
It goes without saying that further customisation will be needed to achieve the result shown in the non-forest example below. As it is, the child nodes of N1 and N2 are grown in the desired direction, but placed to the right of the nodes, not below them ...


text:
Q: Create chunks from file in JavaScript Im trying to create chunks from a file using the function .slice() :
  public sliceFile(file, startPointer, endPointer): Blob {
    return file.slice(startPointer, endPointer, file.type);
  }

  public preview(event): void {
    let file = event[0];
    let reader = new FileReader();

    let chunkSize = 10;
    let startPointer = 0;
    let endPointer = chunkSize;

    reader.readAsDataURL(this.sliceFile(file, startPointer, endPointer));

    reader.onloadend = (event) => {
      console.log(reader.result);
    };
  }

But when im doing it, after the slice, I have a corrupted file data.
// Using file.slice() :
data:text/plain;base64,eW95b3k=

// Without using file.slice() :
data:text/plain;base64,eW95b3lveW8=

You can see when im using the same file, the function slice is adding some letter at the end (k=) and the number of letter he add is always random.


text:
Q: $k-$ degree polynomial regression $\phi: \mathbb{R}^d \to \mathbb{R}^m $ is the feature mapping for performing $k-$ degree polynomial regression on a $d-$ dimensional input. for example when $k=3$ and $d=2$ then,
$$ \phi([x_1, x_2 ]) = [1, x_1, x_2, x_1^2, x_2^2, x_1^3, x_2^3, x_1x_2, x_1^2x_2, x_1x_2^2]$$
For any arbitrary $d$ and $k$, how to write $m$ as a function of $d$ and $k$?

A: You ask for the number of distinct monomials in $d$ variables $x_1,x_2,\ldots,x_d$ of total degree less than or equal to $k.$  These are the monomials of the form
$$x_1^{e_1}\,x_2^{e_2}\,\cdots x_d^{e_d}$$
where the $e_1$ are non-negative integers whose sum (the total degree) does not exceed $k.$
One simple way to count them is to consider the sequence of natural numbers
$$\left(f_0, f_1, \ldots, f_d\right) = \left(k-e_1-\cdots-e_d+1, e_1+1, e_2+1, \ldots, e_d+1\right)$$
These sum to $k+d+1.$  For $i=1,\ldots, d,$ their partial sums
$$s_i = f_0 + f_1 + \cdots + f_{i-1}$$
form a sequence of $d$ distinct, increasing integers in the range $\{1,2,\ldots, k+d\}$ (with $s_{d+1}=k+d+1$ always) and thereby correspond to a subset of those integers of size $d.$  Conversely, any such subset when ordered gives a sequence of such $s_i$ from which the powers $e_i$ can be recovered from the successive differences
$$s_i - s_{i-1} - 1 = e_i,\ i=1,2,\ldots, d.$$
Consequently the number of such monomials is the same as the number of such subsets, given by
$$\binom{k+d}{d} = \frac{(k+d)!}{k!\,d!}.$$
For instance, with $k=3$ and $d=2$ the value is $(3+2)!/(3!\,2!) = 10.$
It may be instructive to examine the correspondence explicitly in a small example like this.  Here is a table of the monomials and the corresponding sequences.
$$\begin{array}{lcr}
\text{Monomial} & \text{Sequence} & \text{Subset} \\
\hline
1 & (4,1,1) & \{4,5\}\\
x_1 & (3,2,1) & \{3,5\}\\
x_2 & (3,1,2) & \{3,4\}\\
x_1^2 & (2,3,1) & \{2,5\}\\
x_1x_2 & (2,2,2) & \{2,4\}\\
x_2^2 & (2,1,3) & \{2,3\}\\
x_1^3 & (1,4,1) & \{1,5\}\\
x_1^2x_2 & (1,3,2) & \{1,4\}\\
x_1x_2^2 & (1,2,3) & \{1,3\}\\
x_2^3 & (1,1,4) & \{1,2\}
\end{array}$$
Finally -- again as an illustration -- the following R code uses combn to produce an array of subsets and converts that into a representation of the monomials.  Here is the output for $k=d=3;$ that is, a list of the monomials in three variables up to degree $3:$

monomials <- function(k, d, varname="x") {
  vars <- paste0(varname, "[", 1:d, "]")
  s <- function(e) ifelse(e > 1, paste0(vars, "^", e, sep=""), ifelse(e==1, vars, ""))
  mult <- function(a) paste(a[a > ""], collapse="*")
  a <- apply(apply(apply(rbind(combn(k+d, d), k+d+1), 2, diff) - 1, 2, s), 2, mult)
  a[a==""] <- "1"
  rev(a)
}

mai <- par("mai")
par(mai=rep(0,4))
a <- monomials(3,3)
plot(c(1, length(a)), 0:1, type="n", xaxt="n", yaxt="n", xlab="", ylab="", bty="n")
invisible(sapply(seq_along(a), function(i) text(i, 1/2, parse(text=a[i]))))
par(mai=mai)


text:
Q: How to run Ubuntu desktop on QEMU? I've installed Ubuntu 16.04 Desktop on QEMU, but now when I start it with:
qemu-system-i386 -m 1024M -enable-kvm -drive file=./ubuntu-desktop.img,index=0,media=disk,format=raw

I see this picture:

Whats going on? How can I fix this?

A: Working Ubuntu 18.04 setup
Tested in an Ubuntu 18.10 host.

ubuntu-18.04.1-desktop-amd64.sh
#!/usr/bin/env bash

set -eux

# Parameters.
id=ubuntu-18.04.1-desktop-amd64
disk_img="${id}.img.qcow2"
disk_img_snapshot="${id}.snapshot.qcow2"
iso="${id}.iso"

# Get image.
if [ ! -f "$iso" ]; then
  wget "http://releases.ubuntu.com/18.04/${iso}"
fi

# Go through installer manually.
if [ ! -f "$disk_img" ]; then
  qemu-img create -f qcow2 "$disk_img" 1T
  qemu-system-x86_64 \
    -cdrom "$iso" \
    -drive "file=${disk_img},format=qcow2" \
    -enable-kvm \
    -m 2G \
    -smp 2 \
  ;
fi

# Create an image based on the original post-installation image
# so as to keep a pristine post-install image.
if [ ! -f "$disk_img_snapshot" ]; then
  qemu-img \
    create \
    -b "$disk_img" \
    -f qcow2 \
    "$disk_img_snapshot" \
  ;
fi

# Run the copy of the installed image.
qemu-system-x86_64 \
  -drive "file=${disk_img_snapshot},format=qcow2" \
  -enable-kvm \
  -m 2G \
  -smp 2 \
  -soundhw hda \
  -vga virtio \
  "$@" \
;

GitHub upstream.
This script will do two QEMU runs:

*

*first an installation run, skips this if already done.

*then a regular boot

The first time QEMU comes up:

*

*Install Ubuntu

*continue, continue, continue...

*wait a few minutes

*at the end "Restart now"

*now you can close the QEMU window

The installer looks like this:

After the install is complete, the script automatically takes a post-install disk snapshot to ubuntu-18.04-desktop-amd64.img.qcow2, and creates a diffed copy to ubuntu-18.04-desktop-amd64.snapshot.qcow2.
It then runs with ubuntu-18.04-desktop-amd64.snapshot.qcow2, and saves any post-regular-boot changes there.
So next time you re-run ./ubuntu-18.04.1-desktop-amd64.sh just starts back from where you last left off.
And if you want to start from the pristine post-manual installation stage to test stuff in a clean environment, you can just:
rm ubuntu-18.04-desktop-amd64.snapshot.qcow2
./ubuntu-18.04.1-desktop-amd64.sh

The snapshot will be re-generated starting from the clean install.
The snapshot only stores the diffs between the original image, and so it does not take a lot of disk space.
This setup has, by default, a funky system that automatically resizes the guest resolution to best fit the QEMU window size, you can see this if you do one of:

*

*drag the window with the mouse

*toggle fullscreen with Ctrl + Alt + F or or start QEMU with -full-screen
Notes:

*

*-vga virtio option is to be able to get higher resolutions: https://superuser.com/questions/132322/how-to-increase-the-visualized-screen-resolution-on-qemu-kvm/1331924#1331924

*-soundhw hda enables sound. Why QEMU does not enable it by default beats me.

*Once inside the VM, reduce the GRUB menu wait time and show some boot messages for next boot with:
printf 'GRUB_TIMEOUT=1\nGRUB_CMDLINE_LINUX_DEFAULT=""\n' | sudo tee -a /etc/default/grub
sudo update-grub

TODO clipboard sharing

*

*How can I copy&paste from the host to a KVM guest?

*https://unix.stackexchange.com/questions/109117/virt-manager-copy-paste-functionality-to-the-vm

*https://unix.stackexchange.com/questions/59079/clipboard-doesnt-work-in-kvm

*https://wiki.archlinux.org/index.php/QEMU#SPICE

*https://www.linux-kvm.org/page/SPICE
Tried -spice port=5930,disable-ticketing + remote-viewer spice://127.0.0.1:5930, and spice-vdagent is pre-installed on guest, but no success.
The root cause of the mess is that QEMU devs seem more focused on non-interactive usage, rather than implementing things like this reliably and therefore killing VirtualBox once and for all: https://bugs.launchpad.net/qemu/+bug/614958
TODO: host 3D acceleration
Still with SPICE and QXL, glxgears gives 1k FPS, and the exact same with regular SDL. But on host __GL_SYNC_TO_VBLANK=0 vblank_mode=0 glxgears gives 20k FPS, so I'm guessing graphics were not accelerated?
Related:

*

*Ubuntu 22.04 GPU passthrough (QEMU)

*https://unix.stackexchange.com/questions/108122/installing-ubuntu-13-0-desktop-in-qemu
Disable networking (e.g. for malware analysis)
Pass: -nic none on the CLI.
Mentioned at: https://wiki.qemu.org/Documentation/Networking#How_to_disable_network_completely
Share a host directory with the guest
Add to QEMU CLI:
-virtfs local,path=/path/to/share,mount_tag=host0,security_model=mapped,id=host0

and mount on guest with:
sudo mkdir /mnt/9p
mount -t 9p -o trans=virtio,version=9p2000.L host0 /mnt/9p

More details at: https://superuser.com/questions/628169/how-to-share-a-directory-with-the-host-without-networking-in-qemu/1301973#1301973 That also shows the corresponding fstab entry.
https://serverfault.com/questions/516097/how-to-efficiently-share-hosts-folder-with-kvm-guests claims is is not ultra fast though.
More dedicated question: How to share a folder between KVM host and guest using virt-manager?
This section was tested on Ubuntu 20.04 host.
Prebuilt bootable images
If you want an image that boots without the need for any interaction on the installer, see: Is there any prebuilt QEMU Ubuntu image(32bit) online?
Server
The exact same procedure as mentioned for desktop also worked for the server image.
I just wasn't able to do the initial install with -nogrphic to get rid of the GUI entirely: How to boot and install the Ubuntu server image on QEMU -nographic without the GUI?
But after the initial boot, after editing GRUB configs I achieve that: How to get to the GRUB menu at boot-time using serial console?
However, for the most part, you will likely just want to use the cloud image instead of the server image with emulation, as it does not have the interactive installer, and is usable from the CLI by default.
Tested on an Ubuntu 18.04 host, QEMU 1:2.11+dfsg-1ubuntu7.3, nvidia-384 version 390.48-0ubuntu3, Lenovo ThinkPad P51, NVIDIA Corporation GM107GLM [Quadro M1200 Mobile] GPU.

A: Installation steps described (by Ciro )worked for me.  The cmd line used in script worked fine, But I had to use other options which were causing boot issues after that (booting stops showing storage blocks info)
-vga cirrus helped finally (max 1280 x 1024 resolution). I have nvidia GPU on host with dual monitor setup. Not sure what was causing issue. Also -vga std and -vga virtio didn't work.
Host OS = 16.4 LTS & Guest OS = 18.4.2 LTS
sudo ./x86_64-softmmu/qemu-system-x86_64 -m 8196 -M q35,accel=kvm,kernel-irqchip=split -cpu host -smp 8 -drive file=~/qemu/ubuntu-18.04.2-desktop-amd64.img.qcow2,format=qcow2 -vnc :5 -net nic -net user,hostfwd=tcp::2222-:22 -device intel-iommu,intremap=on  **-vga cirrus**


text:
Q: Cypress intercept not honoring actual pathname/query I've had this a few times now, 100+ routes in this cypress application however sometimes they work, sometimes they don't, the issue is that even though i've setup my routes correctly they're showing up as an asterix in the route section (see screenshots), after the /campaign route you can see a bunch of asterix, which are all the interceptions using pathname and query.
Why are these showing up as a wild matching route?
I've tried regular expression matches, pathname & query, default method & url:
cy.intercept('GET', new RegExp(`\/placement\?where\={"campaign"\:"${campaign.id}"}$`), {
    body: placements
});
cy.intercept('GET', `/placement?where={"campaign":"${campaign.id}"}`, {
    body: placements
});
cy.intercept({
    method: 'GET',
    pathname: `/placement`
    query: {
        where: `{"campaign":"${campaign.id}"}`
    }
}, {
    body: placements
});

As per their documentation, i don't see why ANY of the above 3 examples shouldn't work, they all match the same thing?


text:
Q: how do i configure two forest with one exchange server I work for financial company; we have 9 branches, and each has its own AD forest.  I would like to install exchange server 2010 (in one domain), and use this installation of exchange to service email for all the users in all the branches.  Is this possible, and how can I make it happen?

A: This would be helpful to review:
http://technet.microsoft.com/en-us/library/aa998031(v=exchg.141).aspx


text:
Q: Searching a certain module for comparing arrays Is there a module which can do this more nicely (not only replacing the smart-matching part)?
#!/usr/bin/env perl
use warnings;
use 5.014;

my @array_all = ( qw( one two three four ) );
my @array_part = ( qw( two four six ) );

my @temp;
for my $i ( @array_part ) {
    push @temp, $i if not $i ~~ @array_all;
}

# if ( @temp ) { do something );

A: You are looking for the set difference or perhaps the relative complement, the example is ambiguous. Any of the numerous set modules will suffice.
use Set::Object qw();
Set::Object
    ->new(qw(two four six))
    ->difference(Set::Object->new(qw(one two three four)))
    ->members;    # ('six')

A: You could use List::Compare
#!/usr/bin/env perl
use strict;
use warnings;
use List::Compare;
my @array_all  = ( qw( one two three four ) );
my @array_part = ( qw( two four six ) );
my @temp;
my $lc = List::Compare->new('--unsorted',\@array_all,\@array_part);
@temp  = $lc->get_complement;
print "@temp\n";


text:
Q: remove unused classes with proguard for Android History/Context
I have a project[1] where size really matters - recently I moved stuff to a shared lib[2] and thought proguard will take care and remove the unused classes because I had a config that was drastically reducing the size but by using the lib i came over the magic 100kb mark so I investigated: classes which I do not use for sure are in the resulting dex file - and even with full name ( not shortened to single-char ) - e.g. I see the SquareView in the dex which I in no way use in the App.
Question
Surprisingly I found in the proguard documentation the following:
The library jars themselves always remain unchanged.

Can I somehow tell/trick proguard (in)to process them? I find this really strange especially because I expect more stuff to be removeable in the lib than in the App itself..
[1] https://github.com/ligi/FAST
[2] https://github.com/ligi/AndroidHelper

A: The Eclipse/Ant/Gradle build processes in the Android SDK automatically specify your code (from bin/classes) and its libraries (from libs) with the option -injars. This means that the complete application is compacted, optimized, and obfuscated (in release builds, assuming ProGuard is enabled).
The build processes only specify the Android runtime android.jar with the option -libraryjars. It is necessary to process the code, but it should not end up in the processed apk, since it is already present on the device.
So it should all work out automatically. You may still see entire libraries with their original names in processed apks, if your configuration proguard-project.txt contains lines like -keep class org.mylibrary.** { *; }. Such configuration is typically a conservative solution to account for reflection. With some research and experimentation, you can often refine the configuration and get better results. You can figure out why classes are being kept with the option -whyareyoukeeping.

A: I believe you have to use -injars:

-injars class_path
      Specifies the input jars (or wars, ears, zips, or directories) of the application to be processed. The class files in these jars will be
  processed and written to the output jars. By default, any non-class
  files will be copied without changes. Please be aware of any temporary
  files (e.g. created by IDEs), especially if you are reading your input
  files straight from directories. The entries in the class path can be
  filtered, as explained in the filters section. For better readability,
  class path entries can be specified using multiple -injars options.

Source: http://proguard.sourceforge.net/index.html#manual/usage.html


text:
Q: How to change version code after AGP 7.0.0-alpha15 Before AGP 7.0.0-alpha15 I could change version code of an app for example like that
android {
  defaultConfig {
    applicationVariants.all {
      if (buildType.name == "debug") {
        outputs.forEach { output ->
          (output as? com.android.build.gradle.internal.api.ApkVariantOutputImpl)?.versionCodeOverride = 1
        }
      }
    }
  }
}

applicationVariants seems missing after AGP 7.0.0-alpha15, how to change it?
PS: It seems ok in plain gradle, above is Kotlin
Edit
With answer from below I was able to override version code in build:
android {
  androidComponents.onVariants { appVariant ->
    if (appVariant.buildType == "release") {
      appVariant.outputs.forEach {
        it.versionCode.set(1)
      }
    }
  }
}

A: The Variant API is going to change to a lazily-evaluated model in AGP 7.0.0, and it seems like Alpha 15 has removed the old APIs for this now. Going forward, you will need to use the androidComponents DSL, which gives access to variants. I am not sure if you'll be able to rewrite the version code like this, however. Check out beforeVariants and onVariants for more info:
android {
  androidComponents.beforeVariants { variantBuilder ->
    // Callback before variants are built. Can be modified, but doesn't allow access to outputs
  }
  androidComponents.onVariants { variant ->
    // Callback after variants are built. Apparently it's read-only access at this point, but outputs are available here
    println(variant.outputs)
  }
}

A: In Java plugin code, one can set the version code & name alike this:
class SomePlugin implements Plugin<Project> {

    @Override
    @SuppressWarnings("UnstableApiUsage")
    public void apply(@NotNull Project project) {

        ApplicationAndroidComponentsExtension androidComponents = project.getExtensions()
                .getByType(ApplicationAndroidComponentsExtension.class);

        androidComponents.finalizeDsl(extension -> {
            for (AndroidSourceSet sourceSet : extension.getSourceSets()) {
                System.out.println(sourceSet.getName());
            }
        });

        int versionCode = 1;
        String versionName = "1.0.0";

        VariantSelector selector = androidComponents.selector().all();
        androidComponents.onVariants(selector, variant -> {
            for (VariantOutput variantOutput : variant.getOutputs()) {
                variantOutput.getVersionName().set( versionName );
                variantOutput.getVersionCode().set( versionCode );
                System.out.println(">>>> " +
                        variant.getName() + " " +
                        variantOutput.getVersionCode().get() + " / " +
                        variantOutput.getVersionName().get());

            }
        });
    }
}

finalizeDsl happens before onVariants.

A: android {
    // ..
    splits {
        abi {
            enable true
            reset()
            include 'x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'arm64-v8a'
        }
    }
    // ..
}

androidComponents {
    onVariants(selector().all()) { appVariant ->
        for (VariantOutput variantOutput : appVariant.getOutputs()) {
            def versionCodes = ['[armeabi]'       : 100000,
                                '[armeabi-v7a]'   : 200000,
                                '[x86]'           : 300000,
                                '[arm64-v8a]'     : 400000,
                                '[x86_64]'        : 500000]
            String abi = variantOutput.getFilters().identifier;
            Integer version = versionCodes.get(abi) + versionCode
            if (appVariant.getName().contains("Debug")) {
                version += 10000
            }
            variantOutput.getVersionCode().set(version);
        }
    }
}

dependencies {
    // ...
}


text:
Q: Why does my program look for Commons.dll instead of Commons.lib? In the project properties -> Linker -> Input -> Additional Dependencies I guided the compiler to look for Commons.lib.
Moreover,
at VC++ directories -> Library Directories I added $(SolutionDir)\Debug, where Commons.lib is to be found.
Yet, for some reason when running the project it's trying to look for Commons.dll and failing.
Why?
Here's the message:

The program can't start because Commons.dll is missing from your
  computer. Try reinstalling the program to fix this problem.

A: Some libraries are so-called export libraries, which only contains stubs for the function in a DLL. To be able to use the library the DLL must be loaded.
The library is used by the linker as part of the build-process, and the DLL is loaded by Windows (or equivalent) when your program is loaded to be executed.


text:
Q: More recursive method to print Pascal's triangle I'll try to use a recursive method to print pascals triangle to the standard output. I started by making an iterative method to get an idea of how I wanted the method to work. See the code below.
/**
 * Print Pascal's triangle with PrintOut.
 *
 * @param n The amount of rows in total
 */
public static void printPascal(int n) {
    for (int i = 0; i < n; i++) {
        System.out.format("%" + (n - i) * 3 + "s", "");
        for (int j = 0; j <= i; j++) {
            System.out.format("% 6d", binom(i, j));
        }
        System.out.println();
    }
}

Javadoc and the signature of binom
/**
 * Method which calculates the values in Pascal's triangle.
 *
 * @param n The row of "the place"
 * @param k The column of "the place"
 * @return A value on "the place" from the triangle
 */
public static int binom(int n, int k)

Then i began to work on the recursive method. I can not use any class variable for printing - so I can not use a vector. I can not have any object, the class the methods are in, the two methods and main are the only methods I can implement.
The biggest problem is that I can not save the variables that binom should use because they reset after each iteration.
Now I have this code for printPascal:
if (n < 0) {
    return;
}
printPascal(n - 1);
for (int k = 0; k <= n; k++) {
    System.out.format("%6d", binom(n, k));
}
System.out.println();

Is there a way to make the method above more recursive - is there a way to take away the for-loop?

A: I hope this helps?
public class PascalTriangle {
    public static void main(String[] args) {
        printPascal(5);
    }

    private static void printPascal(int i) {
        auxPrintPascal(0, i);
    }

    private static void auxPrintPascal(int row, int numOfRows) {
        if (row > numOfRows) {
            return;
        }
        printPascalTriangleRow(row, 0);
        System.out.println();
        auxPrintPascal(row + 1, numOfRows);
    }

    private static void printPascalTriangleRow(int row, int col) {
        if (col > row) {
            return;
        }
        System.out.print(binomial(row, col) + " ");
        printPascalTriangleRow(row, col + 1);
    }

    private static long binomial(int n, int k) {
        if (k > n - k)
            k = n - k;

        long b = 1;
        for (int i = 1, m = n; i <= k; i++, m--)
            b = b * m / i;
        return b;
    }
}

If you insist, this should work?
private static void sillyPrintPascal(int row, int col, int numOFRows) {
    if (row > numOFRows) {
        return;
    }
    if (col > row) {
        return;
    }
    System.out.print(binomial(row, col) + " ");
    if (col == row) {
        System.out.println();
        sillyPrintPascal(row + 1, 0, numOFRows);
    } else {
        sillyPrintPascal(row, col + 1, numOFRows);
    }
}


text:
Q: A custom TypeConverter for generates AddRange() in WinForms designer not working From question: Get designer to generate AddRange for simple List property of UserControl
Following TypeConverter doesn't generate AddRange(). While I see Some Controls generate it with same code manner.
Form1.designer.cs
        // userControl11
        //
        this.userControl11.BackColor = System.Drawing.Color.Red;
        this.userControl11.Fruits.Add(new WindowsFormsApp2.Fruit(false, null));
        this.userControl11.Fruits.Add(new WindowsFormsApp2.Fruit(false, null));
        this.userControl11.Fruits.Add(new WindowsFormsApp2.Fruit(false, null));
        this.userControl11.Fruits.Add(new WindowsFormsApp2.Fruit(false, null));
        this.userControl11.Fruits.Add(new WindowsFormsApp2.Fruit(false, null));
        this.userControl11.Fruits.Add(new WindowsFormsApp2.Fruit(false, null));
        this.userControl11.Fruits.Add(new WindowsFormsApp2.Fruit(false, null));
        this.userControl11.Location = new System.Drawing.Point(278, 224);
        this.userControl11.Name = "userControl11";

It should be
this.userControl1.Fruits.AddRange(new Fruite[]{new Fruit(X, Y), new Fruit(X, Y), etc})
While I see standard controls do same but it generates well:
    // listBox1
    //
    this.listBox1.FormattingEnabled = true;
    this.listBox1.Items.AddRange(new object[] {   // WORKS in standard controls...
    "123",
    "123",
    "123"});

My code:
 [TypeConverter(typeof(FruitConverter))]
    public class Fruit
    {
        public Fruit() { }
        public Fruit(bool edible, string name) : this()
        {
            Edible = edible;
            Name = name;
        }
        public bool Edible { get; set; }
        public string Name { get; set; }
    }

    public class FruitConverter : ExpandableObjectConverter
    {
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(InstanceDescriptor)) return true;
            return base.CanConvertTo(context, destinationType);
        }
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(InstanceDescriptor) && (value is Fruit pi))
            {
                ConstructorInfo ctor = typeof(Fruit).GetConstructor(new Type[] { typeof(bool), typeof(string) });
                object[] pars = new object[] { pi.Edible, pi.Name };
                return new InstanceDescriptor(ctor, pars);
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }

Test in UserControl
public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    private Collection<Fruit> fruits = new Collection<Fruit>();
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public Collection<Fruit> Fruits => fruits;

}

What should I do now?

A: Its really too hard. But here's article explain some:
https://www.codeproject.com/Articles/5372/How-to-Edit-and-Persist-Collections-with-Collectio

Third, the collection class must implement one or both of the
following methods: Add and AddRange. Although IList interface has an
Add member and CollectionBase implements IList, you still have to
implement an Add method for your collection, given that CollectionBase
declares an explicit member implementation of the IList's Add member.
The designer serializes the collection according to what method you
have implemented. If you have implemented both, the AddRange is
preferred.

When serializing with the Add method, for every item it uses a new line.
this.tc.SimpleItems.Add(new Test.Items.SimpleItem_FullTc(-1, "Item1"));
this.tc.SimpleItems.Add(new Test.Items.SimpleItem_FullTc(-1, "Item2"));`

When the designer uses the AddRange method, all the items are added on a single line.
this.tc.SimpleItems.AddRange
  (new Test.Items.SimpleItem[]{new Test.Items.SimpleItem_FullTc(-1, "Item1"),
new Test.Items.SimpleItem_FullTc(-1, "Item2")});

So you must implement a class inherits from Collection<T> or CollectionBase then add AddRange() Method.


text:
Q: How to make label increase in increments as user adds Calories in my App I have a food diary in my app and i'm wondering how I can write the logic so my label can update to the accumulation of calories the user has eaten for the day. I'm thinking maybe I can save the state of the cals as an integer of other variable... but other than that i'm pretty stuck. Heres a pic of the app:

This is all I have so far in my function... I'm thinking of adding a class level variable such as
var appJustLoaded = true
to save the state of the app, then switching it off once the user inputs a food. Any suggestions? I basically want my calories label to update as the user inputs more food with calories. I know its quite simple but im stuck haha
 func didAddRow(name: String, calories: String, section: Int) {

    var newCals = Int(calories)

    calsforToday.text = calories

A: You can have a variable called totalCalories and in your didAddRow function you can add the calories to the total. Then since this is simply and integer you can save it using UserDefaults. Check this out for an example of how to use UserDefaults to store data.
https://www.hackingwithswift.com/read/12/2/reading-and-writing-basics-userdefaults

A: You could append the new calories to an array and then you can total them.
var caloriesArray = [1,2,3,4,5,6,7,8,9,10]
func didAddRow(name: String, calories: String, section: Int) {

    var newCals = Int(calories)

    caloriesArray.append(newCals!)

    calsforToday.text = caloriesArray.reduce(0, +)

}

If you are storing the data in CoreData the you would use something like this when you are fetching the data to get your total.
let result = try! context.fetch(request) as! [NSManagedObject];
let sum = result.reduce(0) { $0 + ($1.value(forKey: "Value") as? Int16 ?? 0) }


text:
Q: How to fix mongos post request from postman I am new ,i am having problem posting some data on mongodb model(users) from postmanenter image description here
Expecting a successful post request

A: For the latest version of Express which is (Express v4.16.0 and higher) Use this in your server.js file: ----->
const express = require('express');

app.use(express.json());
app.use(express.urlencoded({
  extended: true
}));
// For Express version less than 4.16.0 // ------------------------------------

const bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));


text:
Q: UITextView and the Mysterious Missing Space I have an app with a handful of UITextViews of various sizes.  It appears that if a UITextView small enough has a font.pointSize high enough, there's no way to add a space after the text is big enough to fill the text view.
For example:
I'm trying to figure out what was going on here, I starting typing my usual debug string, I typed "What" hit the space key and no space appeared (but this is usual).  I typed "the" and the looked like it was tacked right onto the end of the previous word.  Sure enough, there was no space.  I could go back and add the space just fine and once I do add the space, I can add other spaces as word wrapping then becomes effective.
Another mysterious behavior is that when you double tap space, it doesn't add a period to the end.  It replaces the last character with a period.  So, "What" + space + space becomes "Wha."
Now, I'm doing some interesting things with the font size like I'm automatically resizing the font so that the text fills the space provided within reasonable bounds, but when I disable that, I can still reproduce the behavior.  The only difference then is that instead of fitting on one line, the word wraps to the next line.
For example, if I type "What" + space + "the" it comes out "Whatthe" with "What" on the first line and "the" on the second (though I can only see the tops of the "the."  Further, here's some log information from the textViewDidChange:.
Character    textView.text.length
---------    --------------------
W            1
h            2
a            3
t            4
<space>      4
t            5
h            6
<space>      7    <----  Here's a wierd one . . . now spaces all
?            8           work fine unless it's resizing

A:
Another mysterious behavior is that when you double tap space, it
  doesn't add a period to the end. It replaces the last character with a
  period. So, "What" + space + space becomes "Wha."

That is not mysterious. That means that your UITextView uses autocorrection.
Fix:
UITextView *txtView; // your UITextView
[txtView setAutocorrectionType:UITextAutocorrectionTypeNo];

About spaces... as space is not a drawable symbol, your UITextView can't measure is size (width differs with different alignment), so your UITextView's contentSize property won't be changed and behaves mysteriously. You should set contentSize manually (you can easily calculate size of your NSString with sizeWithFont: method).


text:
Q: Creating virtual layers using the processing toolbox A few days ago Cy T posted an interesting question about creating virtual layers using the Python console:
Creating new Virtual Layer programmatically in QGIS?
Is it also possible to create virtual layers through the processing toolbox?
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# ----- define interface -----
##Virtual Layers=group
##Point on surface (ST_PointOnSurface)=name
##Input_polygons=vector

from qgis.core import QgsVectorLayer, QgsMapLayerRegistry

inptlyr = processing.getObject(Input_polygons)

vlayer = QgsVectorLayer( "?query=SELECT rowid AS gid,ST_PointOnSurface(geometry)AS geom FROM inptlyr.name()", "vlayer", "virtual" )
QgsMapLayerRegistry.instance().addMapLayer(vlayer)

The log says Algorithm Point on surface (ST_PointOnSurface) finished, but nothing happens.
Edit: ?query= added

A: I think the issue lies with inptlyr.name(). Since you inserted it into the string, this is exactly how it will be read (and I doubt you have a layer called "inptlyr.name()").
Personally, I find it easier to separate queries/formulae as it makes it easier to find mistakes. So the following example works for me:
##Virtual Layers=group
##Point on surface (ST_PointOnSurface)=name
##Input_polygons=vector

from qgis.core import QgsVectorLayer, QgsMapLayerRegistry

inptlyr = processing.getObject(Input_polygons)
query = """ SELECT * FROM '""" + inptlyr.name() + """' """

vlayer = QgsVectorLayer( "?query={}".format(query), "vlayer", "virtual" )
QgsMapLayerRegistry.instance().addMapLayer(vlayer)

Two things to notice:

*

*Single quotes are used for layer names (particularly useful when layer names contain spaces).

*inptlyr.name() is outside the string so that the name can be extracted correctly.
So when the above query is read by the script, it will look like:
SELECT * FROM 'polygon example'

This should be enough to create and load your virtual layer. You can test it by using your query.

EDIT:
Your code could look like the following:
##Virtual Layers=group
##Point on surface (ST_PointOnSurface)=name
##Input_polygons=vector

from qgis.core import QgsVectorLayer, QgsMapLayerRegistry

inptlyr = processing.getObject(Input_polygons)
query = """ SELECT rowid AS gid,ST_PointOnSurface(geometry)AS geom FROM '""" + inptlyr.name() + """' """

vlayer = QgsVectorLayer( "?query={}".format(query), "vlayer", "virtual" )
QgsMapLayerRegistry.instance().addMapLayer(vlayer)


text:
Q: How do I extend WCF WebHttp (REST) to support ETags and Conditional Gets? I have a read-only WCF REST service (all GET's baby!) I'd like to add ETag/Conditional get support to every single operation in my service.
Basically I'm interested in extending the technique in this article:
http://blogs.msdn.com/b/endpoint/archive/2010/02/25/conditional-get-and-etag-support-in-wcf-webhttp-services.aspx
My site is backed by a couple of XML files, and my app knows (and raises an event) when any of them change. I don't understand where the extension points are though. How do I hook into the pipeline to add these headers for every call instead of one-at-a-time?

A: This turned out not to be so bad. I used an IDispatchMessageInspector which I hooked into a ServiceBehavior that's applied to all my services.  I'm a little uncomfortable with how the request gets routed but it seems to work.
public class ConditionalGetMessageInspector : IDispatchMessageInspector
{
    private enum GetState { Modified, Unmodified }

    private string ETag {
        get { return XmlDataLoader.LastUpdatedTicks.ToString(); }
    }
    private DateTime LastModified {
        get { return new DateTime(XmlDataLoader.LastUpdatedTicks);}
    }

    public object AfterReceiveRequest(ref Message request,
        IClientChannel channel, InstanceContext instanceContext)
    {
        try
        {
            WebOperationContext.Current.IncomingRequest
                .CheckConditionalRetrieve(ETag);
        }
        catch (WebFaultException)
        {
            instanceContext.Abort();
            return GetState.Unmodified;
        }
        // No-op
        return GetState.Modified;
    }

    public void BeforeSendReply(ref Message reply, object correlationState)
    {
        if ((GetState)correlationState == GetState.Unmodified)
        {
            WebOperationContext.Current.OutgoingResponse.StatusCode =
                HttpStatusCode.NotModified;
            WebOperationContext.Current.OutgoingResponse.SuppressEntityBody =
                true;
        }
        else
        {
            WebOperationContext.Current.OutgoingResponse.SetETag(ETag);
            WebOperationContext.Current.OutgoingResponse.LastModified =
                LastModified;
        }
    }
}

A: That's what a HttpOperationHandler is for in the new WCF Web API http://wcf.codeplex.com
I don't know if there is any easy way to do it with WebHttpBinding.


text:
Q: getting runtime error in terminal whereas it's okay in xcode the below one is my code in a competition, i just started to do these things. so when i compiled this in xcode it is fine but when i compiled it in terminal it is giving as error. can some one spot the error please.
#include<stdio.h>
int main()
{
    int n, i,count=0,ans,prev=0;
    scanf("%d",&n);
    int a[n];
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    for(i=0;i<n;i++)
    {
        if(a[i]==0)
            ans++;
        else if(a[i]==3)
        {
            if(i>=1)
            {if(a[i-1]==1||a[i-1]==2)
                prev=a[i-1];
            }
            count++;
        }
        else if(a[i]==2||a[i]==1)
        {if(i!=0){
            if(a[i]!=prev&&((count-1)%2)==0)
                ans++;
            if(a[i]==prev&&(count%2)==0)
                ans++;
            prev=a[i];
            count=0;}
        }
    }
    printf("%d",ans);
}

A: Looking at the code I can see some errors

*

*Check the return values of your scanf calls as they should return the number of values parsed

*ans is not guaranteed to be initialized to 0 it could be any value left there ( I would guess hat running it in Xcode or a debugger would have initialized it )

*Put curly braces around your conditional statement, you are a beginner and putting curly braces would help you read your own code.


text:
Q: Gray Triangle in Top Right Corner of Excel Cell I'm getting this gray triangle in the top left corner of a cell in an excel document and cannot for the life of me find the cause of it - I'm using Excel 2016 on a Windows 10 Machine.

A: I had the same issue and I just found out what caused it in my case.
I got these by copying and pasting from an old website into excel, probably the HTML code contained "something" which then got transferred into excel when Control+V.


text:
Q: Advanced HTACCESS Subdomain Redirection (foo.dom2.com to foo.dom1.com) I have domain1.tld and domain2.tld. Domain1.tld is the primary domain name and domain2.tld is merely an alias. I have domain2.tld successfully redirected to domain1.tld, via HTACCESS, but I want all subdomains on domain2.tld to likewise redirect to their parallel subdomain on domain1.tld, dynamically.
For example: bla.domain2.tld should redirect to bla.domain1.tld, and foo.domain2.tld should redirect to foo.domain1.tld.
This solution needs to be dynamic, not hard-coded to specific subdomains.
Haha, I guess what I'm writing is a catch-all, one-to-one, subdomain-inclusive, alias domain redirection script in HTACCESS.
Information:

*

*I am on Bluehost, without access to VHOSTS, HTTPD.CONF, etc.

*I have a Wordpress subdomain network (multisite). This means my domain1.tld subdomains are virtual. Wordpress handles this, so as long I can get foo.domain2.tld fully redirected to foo.domain1.tld, Wordpress should be none-the-wiser and work properly. Right?

*Wordpress has the "Professional Domain Mapping" plugin. This allows the sites on my network to have their own domain names. But the issue at hand only concerns sites on my network that don't have their own domain names, and thus utilize subdomains on my primary domain (domain1.tld).

*Thus, I have a wildcard subdomain set up for domain1.tld.

*But I also have a wildcard subdomain set for domain2.tld, just to make sure that all subdomains on domain2.tld are going to the same IP address as domain1.tld: my thinking being that then these subdomains should be readable by the HTACCESS in my root folder.
This is the rule in my HTACCESS that I'm expecting to do this:
RewriteCond %{HTTP_HOST} ^(www\.)?([a-z0-9-]+\.)?domain2\.com$ [NC]
RewriteRule ^(www\.)?([a-z0-9-]+\.)?(.*) http\:\/\/%2domain1\.com\/ [L]

But this isn't working. What am I missing?
I have also tried using an environmental variable, like this:
RewriteCond %{HTTP_HOST} ^(www\.)?[E=subdm:([a-z0-9-]+\.)]?domain2\.com [NC]
RewriteRule ^(.*) http\:\/\/%{ENV:subdm}domain1\.com\/ [L]

...but this just plains breaks both domains. :D
I'm relatively proficient with regular expressions, hence how comfortable I am working with HTACCESS, but I'm actually quite new to the world HTACCESS. I need another pair of eyes!
↓ UPDATE (2011-11-08 9:33am EST) ↓
I tried the first solution Jon Lin suggested, and had to edit it slightly. Originally, it wouldn't handle domain2.com without a subdomain until I put the period inside the second match parenthesis pair and followed the pair with a question mark.
As you can see below, I have gone ahead and provided the entire contents of my HTACCESS, in case you can tell that something is conflicting.
Currently redirecting properly with the suggested RewriteRule: www.domain2.com, domain2.com, and domain2.com/foo
Currently NOT redirecting with the suggested RewriteRule: foo.domain2.com
# Use PHP5 Single php.ini as default
AddHandler application/x-httpd-php5s .php

Options +SymLinksIfOwnerMatch
RewriteEngine on

RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+\.)?domain2\.com$ [NC]
RewriteRule ^(.*)$ http\:\/\/%2domain1\.com\/$1 [L,R]

# BEGIN WordPress
RewriteBase /
RewriteRule ^index\.php$ - [L]

# uploaded files
RewriteRule ^files/(.+) wp-includes/ms-files.php?file=$1 [L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule . index.php [L]
# END WordPress

A: You're on the right track with %{HTTP_HOST} but you need to use backreferences (%1, %2, etc) to access the match against it. You want to do something like this:
RewriteCond %{HTTP_HOST} ^(www\.)?([^\.]+)\.domain2\.com$ [NC]
RewriteRule ^(.*)$ http://%2.domain1.com/$1  [L,R]

Note that if you try to access: http://www.sub.domain2.com/foo it will redirect you to http://sub.domain1.com/foo, The "www." of the original request is gone. If you want the www, change the rule to:
RewriteRule ^(.*)$ http://%1%2.domain1.com/$1  [L,R]


text:
Q: How to find possible closed-form-formula for a given decimal expansion online? What mathematical program or library can guess formula for decimal fraction? For example, for number 2.414213562373095 right guess is 1 + $\sqrt 2$. Are there such tools online? I cannot find one.

A: Using keywords from Peter's comment ("closed form by decimal expansion") I found Inverse Symbolic Calculator
Also see Sympy number identification


text:
Q: Styling the admin bar in SharePoint 2010 I know most of you would not style the admin bar, but I am going for a consistent look and feel and the issue is, I cannot find the classes responsible for creating:

The green tabbed section. I want the border and the green gone, hell I would love to edit this html piece but I can do what I need with HTML. I have tried inspecting it but cannot find the appropriate classes or Id's responsible for creating it.
help?

A:
I inspected the green box with the F12 developer tools and found it:

The outer box has id="Ribbon.Calendar". You can search for that in the markup to further inspect the inner elements.
Edit
Why can't you target them? I just did.
I tested with: #Ribbon\.Calendar { font-size:12px; }
Is it because you aren't escaping the .?
Special characters in CSS selectors