C++ function accepting any callable of a given templated signature

Question: If I understand it correctly, the standard way to write a function that accepts any callable as a parameter is:
template<typename Fn> void myFunction(Fn&& f) { ... }

I would like to do something similar, except I want to be able make Fn conform to a certain signature and I need to know the type of its parameter. For instance, something like:
template<typename T> void myFunction(std::function<void (T)>&& f) { ... }

The problem is this can't accept packaged_task or lambdas that capture move-only types like std::promise.

Update: Added an sample use case
Consider a simplified network request function:
template<typename T> void get(const Url& url,
                              const UrlQuery& params,
                              std::function<void (T)>&& callback) {
    auto response = doGet(url, query);
    callback(fromJson<T>(response));
}

This works reasonably well most of the time, but when I try to pass it a lambda that captures a std::promise it fails. I could use some workarounds to make that work, but I'm wondering if there is a more elegant way. Something closer to this pseudo code:
template<typename Fn<T>>
void get(const Url& url,
         const UrlQuery& params,
         Fn<T>&& callback) {
    auto response = doGet(url, query);
    callback(fromJson<T>(response));
}

Obviously that doesn't compile, but it sort of shows what I'd like.
To se the T parameter in the body of get while also keeping the Fn&& style parameter (eg. not specifying std::function or std::packaged_task as the type for callback) and also not needing to jump through any hoops when calling get.
Comment: Use `enable_if`?
Comment: Whats the signature you want?
Comment: The signature I want is like the second example: `void (T)` where T is a template parameter.
Comment: You want to deduce the `T` or you want to deduce the function type and require a given `T`? The former isn't generally possible - what would you want `myFunction([](auto ){})` to do?
Comment: Providing `T` would be fine.
Answer: The following, addressing the non-copyable-lambda part, works with MinGW g++ 7.2 and Visual C++ 2017:
#include <functional>       // std::function
#include <memory>           // std::shared_ptr
#include <utility>          // std::move

template< class Type >
void foo( std::function<void (Type)>&& f )
{
    f( 42 );
}

struct No_copy
{
    No_copy( No_copy const& ) = delete;
    auto operator=( No_copy const& ) -> No_copy& = delete;

    No_copy() {}
    No_copy( No_copy&& ) {}
    auto operator=( No_copy&& ) -> No_copy& { return *this; }
};

template< class Type >
class Copyable
{
    std::shared_ptr<Type> pf_;

public:
    template< class... Args >
    auto operator()( Args&&... args )
    { return (*pf_)( std::forward<Args>( args )... ); }

    Copyable( Type&& o )
        : pf_{ std::make_shared<Type>( std::move( o ) ) }
    {}
};

// Necessary for Visual C++ 2017:
template< class Type >
auto copyable( Type&& o ) { return Copyable<Type>{ std::move( o ) }; }

#include <iostream>
using namespace std;
auto main()
    -> int
{
No_copy o;
#ifdef DETAILED
    auto lambda = [oh{move(o)}]( int x ){ cout << x << " " << &oh << endl; };
    auto const c = copyable( move( lambda ) );
    foo<int>( c );
#else
    foo<int>( copyable( [oh{move(o)}]( int x ){ cout << x << " " << &oh << endl; } ) );
#endif
}

I haven't tried the particular types you mention, though.
Also, this code does not address the issue of deducing the argument type, if you want that (you'll have to add such deduction, if desired).
And, uhm, there's the issue of possible reference return type, not addressed here either.
:)


System.UnauthorizedAccessException: Access to the path denied

Question: I am trying to launch automatically my application when I turn on the computer. I've wrote this program into my code :
<code>if (Convert.ToInt32(_param.AUTOMATIC_LAUNCH) == 1)
{
    registryKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true);
    registryKey.SetValue("XXX", Process.GetCurrentProcess().MainModule.FileName.ToString());
}
if (Convert.ToInt32(_param.AUTOMATIC_LAUNCH) == 0 && registryKey != null)
{
    registryKey.DeleteValue("XXX", true);
}
</code>
The key is indeed in the folder :  "Software\Microsoft\Windows\CurrentVersion\Run".
But I have a this message which appears in my log :

System.UnauthorizedAccessException: access to the path 'C:\WINDOWS\System32\XXXXXX.ini' denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
(....)

I've tried to grant autorization to the user in the folder of my application but it doesn't work. In addition, the "config-borne.ini" is a file which doesn't exist.
Comment: Do you run your application as administrator?
Comment: Hello, yes I run it as administrator
Comment: @harili, based on my test, I can set the value successfully. Then, where do you see the error, do you throw a exception or other else?  I suggest that you can put your app in D disk to have a try.
Comment: @JackJJun-MSFT Hello, I can also set the key successfully. When I turn on the computer (to test if the app is going to launch itself alone), the exception abore appears. Yes I throw an exception and I've try to ad a pop-up which suggests you to run the app with administrator access, but no success. Then I am going to try to put it into my D:.
Comment: I believe this is a problem with a temporary environment variable not being set and something defaulting to c:\windows which your program doesn't have access to. I have the same problem but I can't figure out which environment variable it's using.
Comment: a ha. one of these... TMP TEMP USERPROFILE ... https://github.com/dotnet/runtime/issues/10779#issuecomment-408306217
Answer: Finnaly I got a solution but it's a little different. I didn't create a key in the registry due to the lack of autorization. To overcome this problem, I choose to create a shortcut directly in the startup folder (CTRL+R and shell:startup if you want to see it).


Setup DNS server for local network (with DHCP) for use with apache

Question: I've set up an ubuntu-server to host a website. But at first i want to configure it to work in my local network.
Actually it serves as DHCP server for the whole network with static ip 192.168.170.250 (and configured, but not accessable hostname "ubuntu-server") and now i want to access this server (and all the apache virtual-hosts) via hostnames.
I already tried to install and configure a DNS server on this machine but without success... (Those tutorials didn't work for me: Tutorial 1 and Tutorial 2)
Also read other questions like this and that but the first one is a complete different question and the other is confusing me because i don't understand the impact of the differences to the first mentioned tutorials... (And I would really prefer to understand what i'm doing and configurating...)
I just want to write something like "ubuntu-server.home.lan" on any PC in my network to access my ubuntu-server, or "website1.home.lan" to access a virtual host of apache running on my ubuntu-server.
And maybe later register this server to an official domain to make it accessible from web...
I would be glad for every hint!
Answer: I don't know where the difference is between the first tutorials and the one i tried now but now it works.
This tutorial did help me:
Worked
Comment: Please add the answer that has been given in the link that you provided, to your answer rather than just posting the link itself.


Python : Fibonacci sequence using range(x,y,n)

Question: I was interested in finding a way to make a variable that gets a value and store it in another variable then getting a new value.
A close practical example is the Fibonacci sequence.
I reasonably searched hard through available python code for this sequence.
There were tons, most often too cryptic for my basic grasp.
I came up with this one. Simple and should do the job :
a = 1
b = 0
print (b)
print(a)
for i in range(0,100):
 c = b
 b = a
 a = c + b
 print(a)

In the end, the loop should print the values passing through the variable a, as in :
0,1,1,2,3,5,8,13,21,34,55,89
But that freakin i keeps going all the way to 100^10.
As in the final output for that code is :
0,1,2,3,5,8,13,21,34,55,89,144,233,377, ..., 573147844013817084101
Would someone explain what is happening ?
Comment: It's because the loop is doing exactly what you told it to do: print the first _i_ Fibonnaci numbers, with _i_ at most 100. For the record, the 100th Fibonnaci is 354224848179261915075.
Comment: Ok. I set the increment to 10, and that divided the number of values. But I, now, have more questions than before.
Comment: You are getting 100 values, the `for` you have will make the calculations 100 times
Comment: @Ashkat I get that the range is between 0 calculations and n number of calculations. I know now that I don't understand this function. Thanks guys
Answer: You are running through the lines
 c = b
 b = a
 a = c + b
 print(a)

100 times. So you get the first 100 fibonacci numbers.
If you want to print fibonacci numbers up to 100, change the for loop to a while loop as such
while (a < 100):
     c = b
     b = a
     a = c + b
     print(a)

Comment: Thank you. I should have used this iteration. The fist comments pointed me to adding an increment as :  in for i in range(0,100,10)
Answer: You might prefer this kind of output as a list instead of printing everything in the loop. Here are the Fibonacci numbers less than 1000:
fib = [1,1]
i = 0
while i < 1000:
    fib.append(fib[-1]+fib[-2])
    i = fib[-1]
#we need to remove the last entry because the loop doesn't stop until the output exceeds 1000.
fib.remove(fib[-1])
print(fib)

It is more interesting to get the Fibonacci numbers up until a certain condition is met instead of an arbitrary numerical cutoff. For instance, the code below detects the first Fibonacci number after 1 that is a square using a while loop over list comprehensions:
#find the lowest square above 1 in the fibonacci sequence
squares_in_fib = []
squares = []
fib = [1,1]
i=0

while squares_in_fib == []:
    i = i+1
    squares = [x**2 for x in range(1,i)]
    fib.append(fib[-1]+fib[-2])
    squares_in_fib = [x for x in squares if x in fib and x > 1]
print(squares_in_fib)

As an aside, I think 144 is the only one!


Getting result from mult in mips

Question: I am new to assembly language, and I am really confused over multiplying.
I was reading the quick tutorial here (dead link, web archive here)
It says after I use mult $t0, $t1 the results are stored in Hi and Lo, I understand these are special registers for mult and div, but how do I access them?
Lets say I do mult $t0, $t1 where $t0 and $t1 are both 2. How do I get the result? (4)
Comment: Use `mfhi $t0` to move HI to t0, and `mflo $t1` to move LO to t1.  Note, you can move HI and LO to any of the GPRS with these instructions.  You can also move values into HI and LO with `mthi` and `mtlo`.  Check your MIPS instruction reference manual for details.
Comment: There are special instructions for accessing these registers. See [here](http://stackoverflow.com/questions/2320196/in-mips-what-is-hi-and-lo)
Comment: I read that thread, still a little confused, I tried to find an example of multiplication but couldnt, could you tell me how can I access the result of the question above?
Answer: You have to use MFHI and MFLO to move data from HI and LO to general purposes register.
Reference
Answer: for E.g:
      .globl main
       main:
            li $t0,3
            li $t1,2
            mult $t0,$t1

The mult condition multiplies 2 signed 32 bits and form 64 bit result. To access that first store the values in registers using commands. This stores HI, LO values to general purpose registers.
             mfhi $t2
             mflo $t3

and then print these values using printing statement:
             move $a0,$t2
             li $v0,1
             syscall

             move $a0,$t3
             li $v0,1
             syscall

to get the output on console.
To get the result of multiplication you can use another command i.e.
            mul $t2,$t0,$t1

where you store the product of values in Register 1 and Register 0 in Register 2.This however corrupts HI and LO.
Answer: MULT $t1, $t2 #multiplies 2 registers
MFLO $t3 #stores the product in this register
MFHI $t4 #stores the remainder

Because there is no modulus command, you can do the multiplication and take whatever result is in MFHI to be the result. For division, it also uses MFLO and MFHI for the result of the operation.

Getting result from mult in mips


Adaptive payments and preapproved/recurring payments

Question: I am in the process of implementing a solution where the user would buy a product using one of two options, either using Credit card or using PayPal. Now basically I would want that the if the user does not have any credits left in his account I charge their PayPal account with a certain amount of money. I am going to use Adaptive Payments for this and I will be using .NET.
Now I have some questions. Does anyone know whether this can be done?
And something else. If I am going to use Adaptive payments.. are adaptive payments more expensive from PayPal side?
Thanks
Answer: So just to make sure I follow, their account will have 'credits' to purchase things. They will select items, and check out paying with credits. If the item costs 10 credits and they only have 8, you will charge them the appropriate amount for 2 credits?
This doesnt need to be adaptive payments. All you need to do is edit your checkout flow to account for multiple payment methods (credits and cc or credits and paypal).
So the flow would be like:
Cust adds item to cart -> Cust checks out -> Cart determines if any money is due -> Cart presents new adjusted total (minus credits) to the merchant -> Cust selects payment method and pays.


Does react-native-touch-id support android?

Question: I cant find anything saying one way or the other. Looking through everything, theres no reason that it shouldnt, however I am new to developing on either android or ios, so Im not entirely sure of the different methods available and how they link with react-native and react-native-touch-id
The only thing I can find online is something from two years ago that states react-native-touch-id does not support android "yet". And I found another node package called react-native-touch-id-android which I am having trouble building
Answer: I've been able to use React Native Touch ID for both iOS and Android on the latest version of RN. Someone forked this repo to also allow the device passcode as a fallback.
https://github.com/tradle/react-native-local-auth


What are the exact buffs that baron gives?

Question:
Possible Duplicate:
What effect do neutral buffs have in League of Legends?

I just saw baron getting taken by jpak and freinds in the ggClassic semifinals, so I was just curious what baron gives as a buff, experience, gold, etc.
Comment: Duplicate of http://gaming.stackexchange.com/questions/33968/what-effect-do-neutral-buffs-have-in-league-of-legends
Answer: There seem to be a few statistic/number questions here so I'll go ahead and link the LoL wiki.  This site is updated almost immediately after changes occur in patches/hotfixes and is generally very reliable.
http://leagueoflegends.wikia.com/wiki/Baron_Nashor

(Passive): On death, Baron Nashor awards the team who slew him 300
  gold and 900 experience per head, and empowers them with a buff for 4
  minutes. The buff grants the wearer 40 attack damage, 40 ability
  power, 3% of their maximum health as hp/5 and 1% of their maximum mana
  as mp/5. The enemy who scored the last hit is awarded a bonus 25 gold.
Comment: please quote the information from the site you link to in case it goes down so the information is persisted on this site
Comment: Sorry about that.  Forgot there was a quote function as well :P


creating linked List in c++

Question: I'm trying to create a linked list in c++ that inserts elements from the end. I have the following code
<code>#include<iostream>

using namespace std;

//Define a structure
    struct Node{
        int info;
        Node* next;
    } *start, *newptr, *current, *ptr;

Node* createNewNode(int);
void insertEnd(Node*);
void display(Node*);

int main(){
    char ch='y';
    while(ch=='y')
    {
        int inf;
        //Initialize the start pointer to NULL
        start = NULL;

        //Prompt the user for information
        cout<<"Enter the information -> ";
        cin>>inf;

        //Call the function to create a new node
        newptr = createNewNode(inf);
        cout<<"New node created successfully \n";

        //Insert the node in the beginning
        insertEnd(newptr);

        //Traversal
        display(start);

        //Asks the user for input
        cout<<"Want to enter more -> ";
        cin>>ch;
    }

    return 0;

}

Node* createNewNode(int a)
{
    ptr = new Node;
    ptr->info = a;
    ptr->next = NULL;
    return ptr;
}

void insertEnd(Node* p)
{
    if(start == NULL){
        start = p;
        current = p;
    }else {
        current->next = p;
        current = p;
    }
}

void display(Node* p)
{
    while(p!=NULL){
        cout<<p->info<<"->";
        p=p->next;
    }
}
</code>
When I compile the program runs fine but it does not display the complete list. It only displays the number recently inserted in the list by the user. What's wrong with this code?
Comment: You have the list backwards...
Comment: have you tried debugging?
Comment: why the global variables. remove them.
Answer: Your start of the list is reset in every iteration.
<code>int main(){
    char ch='y';
    while(ch=='y')
    {
        int inf;
        //Initialize the start pointer to NULL
        start = NULL; // remove this line and do it before the while loop
</code>
Comment: Thanks, mate! I would like to ask one more thing. When I run the program the cmd prompt window is triggered instantly but the program initializes after few seconds say, 10-15 sec. I have tried compiling with CodeBlocks, DevC++ and MSVC++.

creating linked List in c++


Prove or disprove: a continuous function R → R is open if and only if it is strictly monotone.

Question: Prove or disprove: a continuous function $\Bbb R \to \Bbb R$ is open if and only if it is strictly monotone.
Does $f(x)=x^2$ disprove it? it sounds a bit to easy for me
Comment: Your $f(x)$ is not open, since it maps the open set $(-1,1)$ to the not-open set $[0,1)$.
Comment: Hint: If a map is not strictly monotone it will have a local minimum/maximum somewhere. Use that to show it can't be an open map for a similar reason as to why $x^2$ fails to be open.
Answer: $f(x)=x^2$ is not open and it is not strictly monotone on $\mathbb{R}$. So your example does not disprove the assertion
Comment: Adding an example as to why it isn't open (which the OP may have believed was true) may be helpful, though. (for instance, $f((-\infty, 1)) = [0,\infty)$).
Comment: You're right, did you find any counter example then? or maybe its true? I did manage to prove the other direction (if f is open and continuous its strictly monotone)
Answer: If $f:\mathbb{R}\to\mathbb{R}$ is continuous and strictly monotone, then for every $(a,b)\subseteq \mathbb{R}$ we have that $f(a,b)=\{f(x):a<x<b\}=\{f(x):f(a)<f(x)<f(b)\}=(f(a),f(b))$, so $f$ will be open. (because it sends open sets to open sets).
On the other hand, if $f$ is continuous but not strictly monotone, there are points $a<b$ such that $f(a)=f(b)$. Then, since $f$ achieves a minimum and a maximum value in the interval $[a,b]$, $f((a,b))=[\min f([a,b]),\max f([a,b])]$ and we would conclude that $f$ is not open.
I guess then that, under the assumption that $f:\mathbb{R}\to\mathbb{R}$ is continuous, $f$ is open if and only if $f$ is strictly monotone.
Comment: I forgot to say: your example $f(x)=x^2$ is neither an open function nor strictly monotone, so does not work as a counterexample.
Comment: concise and clear. definitely a good answer +1


Is there a way to implement Google Sign-in with a custom login prompt?

Question: I'm following the Google tutorial on how to implement Google Sign-in: aside RADIUS and Active Directory, I want to offer a Google-based login to my site.
For testing purpose I have two machines (host1 and host2): host2 has a SimpleHTTPServer Python module loaded with a web page where only the Sign-in button is showed, host1 connects to host2 and click to the button in order to be redirected to home page.
My usual login prompt is made of two empty rectangles where users enter their username and password (RADIUS and AD login), while with Google Sign-in they will not type in the rectangles but click Sign-in button and enter credentials in the new window that will open.
I'd like to separate the credentials insertion from their sending to Google servers: I'd like the users to be able to enter their Google username and password in the same login prompt I offer for RADIUS and AD login; then, I'add another login button next to the usual one, maybe with "Login with Google" written inside.
Comment: The whole point of OAuth is for users not to provide the 3rd party developer with their permanent credentials. What you are trying to accomplish is a very bad security practice and should be highly discouraged. Firebase Auth will not allow you to do so either. You are basically building a phishing site.
Comment: That's the idea, yes.  The users name/pass should never be available to any code you might write - including a UI.
Comment: I doubt it.  If you could, you would be able to make a sign-in form that looks like Googles and capture the user/pass.
Comment: You mean that, with Google Sign-in button, there's no way I could see user/pass?
Comment: I'll try with Firebase `signInWithRedirect()` method, and let you know
Answer: No, you cannot and should not be allowed to do this.
If you were able to, that would mean you could capture someone's Google credentials and successfully log them in so it appears to them they logged in with Google, when actually you stole their credentials. This is a massive security risk, so even if you found a way to make this work, Google will actively close your loopholes to increase their security.
Any third party authorization service needs to own the authentication process from beginning to end. If they allow people like you to inject themselves as a middleman passing credentials from the user to them, that totally defeats all their security measures.
You also shouldn't attempt to do this for the users' ease of use. If a user clicks 'Sign in with Google', one of two things happen; 1. They enter their Google credentials into Google's form, or 2. They are already logged into Google and they just give permission for your site to access whatever identity information your site needs. Now on subsequent logins, If I'm already logged in with Google (like I checked my Gmail or something), when I click 'Sign in with Google', I automatically sign in, no additional entry of user/password required! But if you inject your custom login form in the mix, now I'm required to enter my exact same credentials a second time to authorize myself with something I'm already authorized to. This is incredibly annoying and a user hostile design.
So basically, No and Don't.
Comment: As an aside it sounds like you're playing with microservices/multiple apps, where you would like to have only one of the apps handle authentication? You can't check someone's credentials, but what the auth service can do is handle the _tokens_ that Google auth returns. Then you just need to ask your auth handler, if this token the user possesses belongs to x user. The auth service then confirms with the token from Google according to the protocol. If they match, then they are who they say they are.
Comment: Very clear and understandable answer. What if I wish to offer an authentication service, but instead of using RADIUS _et similia_ (where custom credentials may be stored) I use Google credentials?
As you wrote, the login process must be entirely owned by Google so this means I can't see nor store credentials: is there no way to tell at least if Google username and password exist? Some way to tell "Your Google credentials exist, you may go on"?
Comment: How would you propose checking Google credentials without collecting them? I can't think of a way. And if you collect them then you see them/could store them...


can 'who liked you' data be achieved in Facebook API?

Question: I see a path to get what appears to be like counts ->  https://developers.facebook.com/docs/graph-api/reference/v2.2/user/likes but this is no good.
I would like to know 'who liked me' or even better yet who 'liked' my POSTing (the ideal solution), and possibly a link to their profile.
FB has a public feed api which possibly will do this in the future, but it is closed as of now.
Is there any workaround for finding 'who liked my post' data in the Facebook api?
Answer: you can get the likes on a particular facebook post by issuing a request to the given end point when using graph api.
https://graph.facebook.com/'.$post_id.'/likes?limit=0 // for likes

or fQL
SELECT user_id FROM like WHERE object_id={object id} LIMIT 1000

you will receive the ids of users by which you can generate links to their profile.
getting the likes might depend on the user privacy settings.


java program to download artifacts and compare

Question: I want to download the builds artifacts from Jfrogartifactory and compare the two builds artifacts. looking for any API or java program to download artifacts and compare, Anyone please share any resource to refer.
Comment: What would you like to find out in the comparison?
Comment: the build will have the jar files and war files i want to get the difference in contents of those files and get the output in a pdf file.
Answer: There is currently no 'easy' way to download the build dependencies using Java.
However with JFrog CLI you can download the build dependencies easily:
<code>jfrog rt dl '*' --build=BUILD_NAME/BUILD_NUMBER
</code>
If you still want to download build dependencies you can use the Build Info Extractor. Use ArtifactoryBuildInfoClient to download build info and ArtifactoryDependenciesClient to download the build artifacts.


Eloquent get only one column as an array

Question: How to get only one column as one dimentional array in laravel 5.2 using eloquent?
I have tried:
$array = Word_relation::select('word_two')->where('word_one', $word_id)->get()->toArray();

but this one gives it as 2 dimentional array like:
array(2) {
      [0]=>
      array(1) {
        ["word_one"]=>
        int(2)
      }
      [1]=>
      array(1) {
        ["word_one"]=>
        int(3)
      }
    }

but I want to get it as:
array(2) {
    [0]=>2
    [1]=>3
}

Answer: You can use the pluck method:
Word_relation::where('word_one', $word_id)->pluck('word_two')->toArray();

For more info on what methods are available for using with collection, you can you can check out the Laravel Documentation.
Comment: While a `Collection` also has a `pluck()` method - What you are using is a method of [`QueryBuilder`](https://laravel.com/docs/5.4/queries#retrieving-results).
Comment: Thanks, that was the function I saw somewhere but didn't find it anymore, also for the record, for the answer to be presice, then maybe add ->toArray() since it returns colletion at the moment and select can be left out from the query for laravel 5.2 at least.
Comment: True about the `select` being redundant, but I don't see a problem with having a collection as a result, because a collection is just a _fancy_ array that can be iterated over the same as an array. I rarely use arrays instead of collections since the memory footprint is generally not a problem, and collections can be easily cast to arrays where needed because they implement the [`toArray`](https://github.com/laravel/framework/blob/5.2/src/Illuminate/Support/Collection.php#L961-L967) method. However, for consistency with your question, I  modified the answer to do convert the result.
Comment: At the moment I am quite new to laravel and eloquent, so I needed these as array of numbers to later merge the array with similar one and use it in another query
Comment: why toArray()? only pluck is good enough i think. Oh!! got your point. sorry for pointing this.
Answer: That can be done in short as:
Model::pluck('column')

where model is the Model such as User model & column as column name like id
if you do
User::pluck('id') // [1,2,3, ...]

& of course you can have any other clauses like where clause before pluck
Answer: If you receive multiple entries the correct method is called lists.
    Word_relation::select('word_two')->where('word_one', $word_id)->lists('word_one')->toArray();

Comment: `lists()` is deprecated in Laravel Ver.5.2 and later, where `pluck()` as in the tagged answer is the way.
Comment: Awesome! The `lists()` works fine by it self. Thank you.
Comment: Boom! This works perfectly. But don't need to use toArray() function because lists() returns an array.
Answer: I came across this question and thought I would clarify that the lists() method of a eloquent builder object was depreciated in Laravel 5.2 and replaced with pluck().
// <= Laravel 5.1
Word_relation::where('word_one', $word_id)->lists('word_one')->toArray();
// >= Laravel 5.2
Word_relation::where('word_one', $word_id)->pluck('word_one')->toArray();

These methods can also be called on a Collection for example
// <= Laravel 5.1
  $collection = Word_relation::where('word_one', $word_id)->get();
  $array = $collection->lists('word_one');

// >= Laravel 5.2
  $collection = Word_relation::where('word_one', $word_id)->get();
  $array = $collection->pluck('word_one');

Answer: In Laravel 5.2, you can retrieve a single column as a one-dimensional array from a database using Eloquent by using the pluck method. The pluck method retrieves a collection of a single column's values. Here's an example of how you can use it:
1- Basic Usage of pluck Method:
$columnValues = YourModel::pluck('columnName')->all();

In this example, replace YourModel with the name of your Eloquent model and columnName with the name of the column you want to retrieve. The all() method is used to convert the collection into a plain PHP array.
2- Applying Conditions:
You can also apply conditions before plucking the values. For instance, if you want to get values of a column where another column meets a certain condition, you can do:
$columnValues = YourModel::where('anotherColumnName', 'value')->pluck('columnName')->all();

This will first filter the rows where anotherColumnName equals value and then pluck the values of columnName.
Comment: As far as I am aware doing `Model::get(['ColumnName'])->toArray();` is equivalent of doing `Model::select('ColumnName')->get()->toArray()` which results in a multi dimensional array.
Comment: Can you please explain that.


Force all options of a select list to appear as expanded on click

Question: I would like to create the following functionality:
A user clicks on a button (any button will do), and a select list will appear with all the options expanded inside a slide down window below the button.
I know how to make the slide window and all that, but I haven't found any info on how to make a select list appear as expanded given a click event.
The tricky part is, I'm working within a CMS context where I cannot change the html, so I have to implement a solution with only jQuery.
Here is the code for the form.

Example Button (Could be any element outside the form)

<form accept-charset="UTF-8" action="/accreditations" class="lang_dropdown_form language" id="lang_dropdown_form_language" method="post" name="lang_dropdown_form_language">

                <select class="lang-dropdown-select-element form-select" id="lang-dropdown-select-language" name="lang_dropdown_select" style="width:165px">
                    <option selected="selected" value="en">
                        English
                    </option>

                    <option value="de">
                        Deutsch
                    </option>

                    <option value="pt-br">
                        Português
                    </option>

                    <option value="es">
                        Espa├▒ol
                    </option>
                </select>

        <input name="en" type="hidden" value="/accreditations">
        <input name="de" type="hidden" value="/de/accreditations">
        <input name="pt-br" type="hidden" value="/pt-br/accreditations">
        <input name="es" type="hidden" value="/es/accreditations">
        <div> <input type="submit" id="edit-submit" name="op" value="Go" class="form-submit" /> </div>

        <input name="form_build_id" type="hidden" value="form-IpZgiF0U6WXF2LbQDnlwtEw2rz1lh2s6DMwGFTeumzE">
        <input name="form_id" type="hidden" value="lang_dropdown_form">

</form>
Answer: This would work, but only with Chrome.
jsFiddle
window.expand = function () {
    var dropdown = document.getElementById('lang-dropdown-select-language');
    var event;
    event = document.createEvent('MouseEvents');
    event.initMouseEvent('mousedown', true, true, window);
    dropdown.dispatchEvent(event);
};

Answer: Here's a thought - Give your lang-dropdown-select-language SELECT a low z-index and an absolute position in CSS.  In your javascript set the size of it to 1 if its not already set that way:
($('#lang-dropdown-select-language').attr('size', value)

Then in your javascript create a new select with a higher z-index, display: none; and set the size to the number of options in your first select. Set the left and top to be the same as your first select. Attach an onchange event to the 2nd one.  That function should set the selectedIndex of the 1st select to that of the 2nd, and then switch display:none on 2nd select.
Then in your onClick for your button make the 2nd one appear by setting display: block; in code.
Does this concept sound plausible?


How do you expose methods from NativeScript custom components?

Question: I want to expose a method from a custom component in a NativeScript project. Here is the conceptual setup:
MyComponent.xml

<StackLayout loaded="loaded"> ...UI markup... </StackLayout>

MyComponent.ts

export function loaded(args) { //do stuff };
export function myCustomMethod() { //do more stuff };

MyPage.xml

<Page xmlns:widget="..." loaded="loaded">
   <widget:MyComponent id="myComponent" />
</Page>

MyPage.ts

export function loaded(args) {
   let page = <Page>args.object;
   let widget = page.getViewById("myComponent");
   widget.myCustomMethod(); //<--THIS DOES NOT WORK
}

Question: How do I properly expose the myCustomMethod on the custom component so that the hosting page can access and call it via JavaScript?
By default, when trying to get a reference to the custom component on the page, a reference to the custom component's layout container is returned (in this example, a StackLayout).
So, as a workaround, I am doing this:
MyComponent.ts

export function loaded(args) {
   let stackLayout = <StackLayout>args.object; //Layout container
   stackLayout.myCustomMethod = myCustomMethod; //Attach custom method to StackLayout
}

It's a bit of a hack, but it's working. Is there any better way to expose custom component methods short of creating a super class for the layout container?
UPDATE
To be more accurate, the custom component has instance properties, so the eventual solution would need to support a scenario like...
MyComponent.ts

let isStarted = false;
export function loaded(args){ // do stuff };
export function myCustomMethod() { isStarted = true; };

Comment: Even I'm interested in this
Comment: Todd any solution nowaday?
Comment: Switching to TypeScript made this quite a bit more natural/easier to solve. If I have a "visual" custom component today, I usually extend a StackLayout and then add my new public methods/properties. So my primary recommendation is to start using TypeScript with NativeScript (if you're not already).
Answer: As the method you want to reuse is not coupled to your customCompoenent, you can create a common file and require it where needed and reuse the exposed methods accordingly. Or you can directly import your MyComponent.ts and reuse its exported methods (not so good idea as you will probably have access to all exposed methods of your MyCompoennt.ts like onLoaded, onNavigationgTo, etc.)
For example:
in your navigator.ts (or if you prefer to your MyComponent.ts)
import frame = require("ui/frame");
export function navigateBack() {
    frame.goBack();
}

and then reuse it where needed like this:
MyPage.ts
import navigatorModule = require("navigator");

export function goBack(args: observable.EventData) {
    navigatorModule.goBack(); // we are reusing goBack() from navigator.ts
}

Another applicable option is to use MVVM pattern and expose your methods via the binding context.
Comment: I will experiment with this. Ultimately, in my case, there is "instance" state for the custom component. Not sure if this approach would work...but I will investigate and report back. Thanks!


How to find the generator of a $\Sigma$ Algebra

Question: Can you help me with the following?

For $A \subset \mathbb{R}^d$ and $\mathbb{a}> 0$, let $\mathbb{a}A:=\{\mathbb{a}x\mid x\in A\}$. If $A$ is a Borel set in $\mathbb{R}^d$, then $\mathbb{a}A$ is also a Borel set.

I thought about using the good set principle and I already showed that $aA$ is a $\sigma$-Algebra. The only thing missing, is to show that $aA$ contains the generator of the Borel-Algebra.
But we've never learned how to find it and I don't have an idea how to do that.
Thanks for your help.
Comment: How did you show $aA$ is a $\sigma$-algebra? It is definitely not since, say, $\emptyset$ isn't an element. $aA$ is like a scaled version of your original set $A$. I think your whole approach is a bit off here. You want to show that $aA$ is a Borel set.
Comment: Well if you showed $aA$ is Borel, then aren't you done?
Comment: Sorry, I meant I did show that $aA$ is a $\sigma$-Algebra. Just edited it.
Comment: I changed $\mathbb{a}A$:={$\mathbb{a}x$|$x\in A$} to $\mathbb{a}A:=\{\mathbb{a}x \mid x\in A\}.$ One shouldn't alternate in and out of MathJax like that. Just keep all the math notation inside the MathJax tags. That way you don't get font mismatches and lack of proper spacing and incorrect alignment.
Comment: There are several generators for the Borel $\sigma$-algebra - I find it odd that you have not seen examples of some of them in lectures or your book,
Comment: Actually we have seen some, but I don't see how to determine the generator of an unkown Borel set.
Comment: Also, I think you might be a bit confused about generating $\sigma$-algebras. You seem to want to find a generator of a Borel set, but that doesn't make sense. Given a collection of sets, you can consider the smallest $\sigma$-algebra containing those sets. We say that such a $\sigma$-algebra is generated by those sets. For instance, the Borel $\sigma$-algebra on a topological space is defined as the $\sigma$-algebra generated by the open sets of $X$. That is, it is the smallest $\sigma$-algebra containing all the open sets. There are many generating sets for it though.
Answer: As mentioned above you should recap expressions like "Borel set", "$\sigma$-Algebra" and "generator".
If you did consider the function $f(x) = \frac{1}{\mathbb{a}}x$ which is continuous hence measurable and it holds $$\mathbb{a}A = f^{-1}(A)$$ and so $\mathbb{a}A$ is a Borel set because $A$ is.


How can I read the projects list from a GitLab group with GitPython?

Question: I am trying to find a way to clone all the git repositories from a remote GitLab group with Python (gitPython for example).
Can you help me, please?
Comment: A simple web search can give you same options: https://lmgtfy.app/?q=git+clone+all+repositories
I don't think there's a single command to that, you'd probably need to list all the repos from the group, parse the response and then clone the repos. Something like: https://gist.github.com/milanboers/f34cdfc3e1ad9ba02ee8e44dae8e093f
Comment: without gitPython , you can use the api  https://docs.gitlab.com/ee/api/groups.html#list-a-groups-projects  to list all the repos from a group
Answer: You should install python-gitlab (to iterate over the GitLab project structures) and GitPython (to clone the Git repos) packages first.
If you have a self-hosted GitLab instance, then you also need to get a personal token. Go to https://gitlab.your-company.com/-/profile/personal_access_tokens to access the token interface, like on the screenshot:

Save the obtained token (step 1).
You also need a deploy token for each repository that you are going to clone. To do so, go to https://gitlab.your-company.com/your_group/your_project/-/settings/repository -> "Deploy tokens", like on the screenshot below:

You'll get a token username (like gitlab+deploy-token-1488) and the token itself. Save this username/token pair (step 2) and repeat this step for each repo.
As the last step, you should get the ID of the group which contains your repos. It should be displayed on the web interface of your group at https://gitlab.your-company.com/your_group like on the screenshot:

Save this ID too (step 3).
Now you are all set to run this code snippet:
import git
import os
import gitlab

local_cloned_repos_dir = 'local_cloned_repos_dir'

gl = gitlab.Gitlab('https://gitlab.your-company.com', private_token='insert_token_from_step_1')

deploy_token_map = {
    'your_project_name': 'gitlab+deploy-token-1488:insert_token_from_step_2'
}

for project in gl.groups.get('insert_id_from_step_3').projects.list():
    local_cloned_project_dir = os.path.join(local_cloned_repos_dir, project.name)
    os.makedirs(local_cloned_project_dir, exist_ok=True)
    git.Repo.clone_from('https://{}@gitlab.your-company.com/{}'.format(deploy_token_map[project.name], project.path_with_namespace), local_cloned_project_dir)

Note that I've created a map to match the name of the project with the corresponding token username / deploy token pair, but you don't have to handle it exactly this way.
Hope it helps!


Azure Databricks save file in a mount point

Question: guys.
I'm using a personal compute cluster on Azure Databricks and proceeding with a mount point creation on as follows:
configs = {"fs.azure.account.auth.type": "OAuth",
          "fs.azure.account.oauth.provider.type": "org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider",
          "fs.azure.account.oauth2.client.id": "xxxxxx",
          "fs.azure.account.oauth2.client.secret": "xxxxx",
          "fs.azure.account.oauth2.client.endpoint": "https://login.microsoftonline.com/xxxxxx/oauth2/token"}

dbutils.fs.mount(
  source = "abfss://firstname.lastname@example.com/xxx/yyy",
  mount_point = "/mnt/MyMount/",
  extra_configs = configs)

When I try to access the mount using dbutils.fs.ls("/mnt/MyMount/") it's accessible. But when I start to read with code as follows:
from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("MyApp").getOrCreate()
views = ['view_1', 'view_2', 'view_3', 'view_4', 'view_5']
logs = ['Log_views']

for view in views:
    print(f'Start save view {view}.')
    spark.read.format("delta").load(f"/mnt/source/{view}").toPandas().to_csv(f"/mnt/MyMount/{view}.csv", index=False)
    print(f'View {view} save sucessfuly.')

for log in logs:
    spark.read.format("parquet").load(f"/mnt/source/{log}").toPandas().to_csv(f"/mnt/MyMount/{log}.csv", index=False)
    print(f'Logs {log} save successfully.')

I got an error:
OSError: Cannot save file into a non-existent directory: '/mnt/MyMount'

I tried to remove and recreate the mount point and confirmed all access is working fine.
Answer: You need to include /dbfs/ in path.
Because the path outside spark context need to be given from root filesystem and your mount will be under dbfs folder.
Below is the data:

Code
spark.read.format("parquet").load(f"/mnt/source/{log}").toPandas().to_csv(f"/dbfs/mnt/MyMount/{log}.csv", index=False)

And output:

For more information on working with files in databricks
refer this


Setting a button

Question: I have 2 buttons. One is "add". The other is "cancel". In the cancel button action, I want to write that until the add method is not called, this button do nothing. How can I do that?
Answer: Disable the cancel button initially. Then, in the add action listener, enable the cancel button.
JButton add = new JButton("Add");
JButton cancel = new JButton("Cancel");

cancel.setEnabled(false);

// Then something along these lines...
add.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
        cancel.setEnabled(true);
    }
});

NOTE: I haven't used Swing in a while, so my syntax could be off...
Answer: When you initialize your app, you could call setEnabled(false) on your cancel JButton. Then in your handler for your add JButton, you could call setEnabled(true) on the cancel JButton. Here is a demo from Sun's Swing Tutorial for disabling/enabling JButtons (source code available at link).

Setting a button


NullPointerException for my for loop? java

Question:  public static double[] returnArray()
 {
   for (int a=0; a<31; a++) {
     double i = Double.valueOf(days[a]);
      dataArray[a]=i;
   }
   return(dataArray);
 }

days[] is a array of string and static double[] dataArray is declared
and it says i got NullPointerException at double i = Double.valueOf(days[a]);?
please help,
Comment: where do you initialize your days and dataArray ?
Comment: Can you please show your code to initialize days[] ?
Comment: Are you sure you have access to the days var inside this method?
Comment: Most likely your `days` array has not been fully populated.  Though it's certainly possible that you never even created the array for `days`.  You did not provide nearly enough info to be any more specific than that.
Comment: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html - specifically, the part about creating/initializing.
Answer: Check there are values in days[a] before you do
double i = Double.valueOf(days[a]);

My suspicion is that days like days[30] might have no value inside sometimes.
Comment: `days[31]` should never be accessed =)
Answer: double i = Double.valueOf(days[a] != null ? days[a] : "0");

Answer: On which iteration does it give a NullPointer Exception?  If it's on the first iteration (a=0) then you probably don't have access to the arrays in that method.  If it's not until (a=30) then maybe it's because you're working with the month of February (28-29 days) so a[29] and a[30] are both null.
Answer: Make sure days[] has been initialized. This would cause your problem:
private String[] days;

or
days = null;


why java has no StringBufferOutputStream

Question: So if there is a java.io.StringBufferInputStream, you would think that there would be a StringBufferOutputStream.
Any ideas as to why there isn't??
Likewise,there is also a SequenceInputStream but no SequenceOutputStream.
Answer: My guess is that someone never got around to making a StringBufferOutputStream in Java 1.0 since the product was somewhat "rushed to market."  By the time Java 1.1 rolled around and people actually understood that readers and writers were for characters, and inputstreams and outputstreams were for bytes, the whole concept of using streams for strings was realized to be wrong, so the StringBufferInputStream was rightly deprecated, with no chance ever of a partner coming along.
A SequenceInputStream is a nice way to read from a bunch of streams all concatenated together, but it doesn't make much sense to write a single stream to multiple streams.  Well, I suppose you could make sense of this if you wanted to write a large stream into multiple partitions (reminds me of Hadoop here).  It's just not common enough to be in a standard library.  A complication here would be that you would need to specify the size of each output partition and would really only make sense for files (which can have names with increasing suffixes, perhaps), and so would not generalize into arbitrary output streams in a nice manner.
Answer: StringBufferInputStream is deprecated, because bytes and characters are not the same thing.  The correct classes to use for this are StringReader and StringWriter.
If you think about it, there is no way to make a SequenceOutputStream work.  SequenceInputStream reads from the first stream until it is exhausted, then reads from the next stream.  Since an OutputStream is never exhausted (unless, say, it happens to be connected to a socket whose peer closes the connection), how would a SequenceOutputStream class know when to move on to the next stream?
Answer: StringBufferInputStream has long been depreciated.
Use StringReader and StringWriter.


LDAP Query to check if user exists in a group or subgroup

Question: I'm authenticating users against an LDAP server and I need to see if the user belongs to a particular group. All users belonging to a subgroup under this group should also be allowed to login. Here's the code I'm currently using:
<code>    private String[] returnedAtts = { "sn", "givenName", "mail", "objectSid", "memberOf" };
    SearchControls searchCtls = new SearchControls();
    searchCtls.setReturningAttributes(returnedAtts);
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    LdapContext ldatCtxt = null;
    try{
        ldatCtxt= getInitialContext(userName, password);
    }
    catch(AuthenticationException e){
        throw new AppException(AppMessageHandler.getClientString("invalidCredentials"));
    }
    String searchFilter = userSearchQuery.replace("$USERID$", userName);

    NamingEnumeration<?> answer = ldatCtxt.search(searchBase, searchFilter,searchCtls);
    String userGroup=null;
    if(answer==null || !answer.hasMoreElements()){
        throw new AppLoginException(AppMessageHandler.getClientString("invalidCredentials"));
    }
    SearchResult searchresult = (SearchResult) answer.next();
    Attribute memberOf = (Attribute) searchresult.getAttributes().get("memberOf");
    if(memberOf==null){
        throw new AppLoginException(AppMessageHandler.getClientString("userNotInADGroup"));
    }
    userGroup = (String) memberOf.get();
    String[] groups=userGroup.split(",");
    boolean isMemberOfGroup = false;
    for(String groupName:groups)
    {
        if(groupName.equals("CN="+appUserGrp))
            isMemberOfGroup = true;
    }
    if(!isMemberOfGroup){
            throw new AppLoginException(AppMessageHandler.getClientString("userNotInADGroup"));
        }
</code>
This works fine when I'm checking for a specific group, but doesn't work when a user from a subgroup(which is a member of the parent group - appUserGrp. Is there a way to check if a user belongs to a specific group or any subgroup that is a member of that group?
Here's a sample of the group structure that I have:
Group1

User1
User2
SubGroup1
-User3
-User4
SubGroup2
-User5

Group2

User6
User7

User1-5 should be able to login, but user6 and user7 should not be able to login.
Comment: What is the LDAP server software you're using? Some implementations offer operational attributes to check membership in nested group structures.
Comment: I'm using Microsoft Active Directory.
Answer: I am assuming as you show searching for "ObjectSid", you are using Microsoft Active Directory.
If so, You can to use the extensible matching filter using LDAP_MATCHING_RULE_IN_CHAIN. Query the group with the scope=BASE and Something like:
<code>(member:1.2.840.1135126.96.36.1991:=CN=John Smith,DC=MyDomain,DC=NET)
</code>
Should work.
More examples are available.
Comment: Thanks! Let me try this out!
Comment: The example link does not work.
Comment: Try:
https://ldapwiki.com/wiki/Active%20Directory%20User%20Related%20Searches#section-Active+Directory+User+Related+Searches-AllGroupsAUserIsAMemberOfIncludingNestedGroups


DI with Unity when multiple instances of the same type is needed

Question: I need help with this. I'm using Unity as my container and I want to inject two different instances of the same type into my constructor.
class Example
{
   Example(IQueue receiveQueue, IQueue sendQueue) {}
}

....and IQueue is implemented in my MessageQueue class....
class MessageQueue : IQueue
{
    MessageQueue(string path) {}
}

How can I inject two different instances of MessageQueue into my Example class? Each of the MessageQueue instances to be created with different path.
Answer: There are many ways to achieve the results you want (as evidenced by the multiple answers).  Here is another way using named registrations (without attributes):
IUnityContainer container = new UnityContainer();

container.RegisterType<IQueue, MessageQueue>("ReceiveQueue",
    new InjectionConstructor("receivePath"));

container.RegisterType<IQueue, MessageQueue>("SendQueue",
    new InjectionConstructor("sendPath"));

container.RegisterType<Example>(
    new InjectionConstructor(
        new ResolvedParameter<IQueue>("ReceiveQueue"),
        new ResolvedParameter<IQueue>("SendQueue")));

Example example = container.Resolve<Example>();

The downside of this approach is that if the Example constructor is changed then the registration code must also be modified to match.  Also, the error would be a runtime error and not a more preferable compile time error.
You could combine the above with an InjectionFactory to invoke the constructor manually to give compile time checking:
IUnityContainer container = new UnityContainer();

container.RegisterType<IQueue, MessageQueue>("ReceiveQueue",
    new InjectionConstructor("receivePath"));

container.RegisterType<IQueue, MessageQueue>("SendQueue",
    new InjectionConstructor("sendPath"));

container.RegisterType<Example>(new InjectionFactory(c =>
    new Example(c.Resolve<IQueue>("ReceiveQueue"),
                c.Resolve<IQueue>("SendQueue"))));

Example example = container.Resolve<Example>();

If you are using a composition root then the use of the magic strings ("ReceiveQueue" and "SendQueue") would be limited to the one registration location.
Answer: Not everything has to be automatically wired by the container. You can register the Example class like this:
container.Register<Example>(new InjectionFactory(c =>
{
    var receive = new MessageQueue("receivePath");
    var send = new MessageQueue("sendPath");
    return new Example(receive, send);
});

Comment: The OP has a single class `MessageQueue` -- no separate `ReceiveQueue` and `SendQueue` classes.
Comment: @ErenErsönmez: Thanks for bringing this to my attention; I missed this point. This makes my answer much shorter. I updated my answer.
Comment: @Steven: Your original answer was really interesting. If creating new classes and interfaces is an option I think that solution looks good.
Comment: @ErikZ: It's important to try remove ambiguity from the design, but after rereading your question more thoroughly (thanks to Eren) I noticed that adding interfaces might not be the right solution in your case. However, it's always good to keep this in mind.
Answer: You could register the two instances with names:
myContainer.RegisterInstance<IQueue>("ReceiveQueue", myReceiveMessageQueue);
myContainer.RegisterInstance<IQueue>("SendQueue", mySendMessageQueue);

and then you should be able to resolve by name, but it requires using the Dependency attribute:
class Example
{
    Example([Dependency("ReceiveQueue")] IQueue receiveQueue,
            [Dependency("SendQueue")] IQueue sendQueue) {
   }
}

or inject the unity container and then resolve the instances within the constructor:
class Example
{
    Example(IUnityContainter container)
    {
        _receiveQueue = container.Resolve<IQueue>("ReceiveQueue");
        _sendQueue = container.Resolve<IQueue>("SendQueue");
    }
}

Comment: Although this answers the question, it's not a very good solution, because this clutters the application with attributes and couples the application to the Unity container. I would rather use an `InjectionFactory` instead.
Comment: I'm sorry, but your second (updated) example is a bad idea, that's why you get my downvote. You should not promote injecting the container into classes, that is [bad practice](http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/).
Comment: @Steven you're right, I take back that edit. the linked article has some very valid points.
Answer: Well, don't
You should use the factory pattern in this case.
class Example
{
   Example(IQueueFactory factory)
   {
       _sendQueue = factory.Create("MySend");
       _receiveQueue = factory.Create("MyReceive");
   }
}

It makes the intention a lot more clear and you can internally in the Example class handle if the queues are not found or incorrectly configured.
Comment: Thank you! That was my first thought, but how do I avoid newing up the MessageQueue classes in the factory. Should I inject the container into the factory and use the ParameterOverrides proposed in another answer?
Comment: A factory is especially useful for delaying the creation of instances, but in your example you're still creating those queues during object graph construction. We could even argue that you complicated the design of `Example`, since it now depend on an extra abstraction. I would remove the `IQueueFactory` dependency from `Example` and if the use of the factory is needed, register it using an `InjectionFactory` as follows: `container.Register(new InjectionFactory(c => new Example(c.Resolve().Create("Receive"), c.Resolve<IQueueFactory().Create("Send"))));`.
Comment: @ErikZ: Ok. so you are sharing the queues between different classes?
Comment: @jgauffin: No, the queues is only used inside the Example class.
Comment: The the queues will get the same lifetime as your Example class if you use a factory. I therefore think that it's the most straightforward solution as the actual creation only becomes an implementation detail.
Comment: @jgauffin: That makes sense, but should I inject the container into the factory?
Comment: @Steven: It's only a matter of where the factory is used. The question is what makes the code easiest to read.
Answer: 5 years later, but I was looking for this answer too.
I worked through it with my own code and then decided to create working code using (slightly altered) classes the OP provided.
This is an entire working example that you can copy into LINQPad (programmer's playground) and run.
Using Statement / Unity Libary
You'll need to add a reference to Microsoft.Practices.Unity.dll
You'll also need to add a using statement of :
Microsoft.Practices.Unity

In LinqPad you press F4 to add the reference and the using statement (namespace import).
void Main()
{
    // Create your unity container (one-time creation)
    UnityContainer uc = new UnityContainer();

    // Create simple list to hold your target objects
    // (makes the sample easy to follow)
    List<MessageQueue> allMQs = new List<MessageQueue>();

    // I'm adding TransientLifetimeManager() in order to
    // explicitly ask for new object creation each time
    // uc.Resolve<MessageQueue>() is called
    uc.RegisterType<IQueue, MessageQueue>(new TransientLifetimeManager());
// ### override the parameters by matching the parameter name (inPath)
    var item = uc.Resolve<MessageQueue>(new ParameterOverride("inPath", "extra.txt").OnType<MessageQueue>());
    allMQs.Add(item);
    item = uc.Resolve<MessageQueue>(new ParameterOverride("inPath", "super.txt").OnType<MessageQueue>());
    allMQs.Add(item);

    foreach (MessageQueue mq in allMQs){
        Console.WriteLine($"mq.Path : {mq.Path}");
    }

    Console.WriteLine("######################\n");

    uc.RegisterType<Example>(new InjectionConstructor((allMQs[0] as IQueue),(allMQs[1] as IQueue)));

    // #### Create a new Example from the UnityContainer
    var example1 = uc.Resolve<Example>();
    // ##### Notice that the Example object uses the default values of super.txt & extra.txt

    Console.WriteLine("#### example1 obj. uses default values ###########");
    Console.WriteLine($"example1.receiver.Path : {example1.receiver.Path}");
    Console.WriteLine($"example1.sender.Path : {example1.sender.Path}");

    // ##################################################
    // Override the parameters that he Example class uses.
 // ### override the parameters by matching the parameter
 // names (receiveQueue, sendQueue) found in the target
// class constructor (Example class)
    var example2 = uc.Resolve<Example>(
        new ParameterOverrides {
             {"receiveQueue", new MessageQueue("newReceiveFile")},
             { "sendQueue", new MessageQueue("newSendFile")}
        }.OnType<Example>());

    Console.WriteLine("######################\n");

    Console.WriteLine("#### example1 obj. uses ParameterOverride values ###########");
    Console.WriteLine($"example2.sender.Path : {example2.sender.Path}");
    Console.WriteLine($"example2.receiver.Path : {example2.receiver.Path}");
}

class Example
{
   public MessageQueue receiver {get;set;}
   public MessageQueue sender {get;set;}

   public Example(IQueue receiveQueue, IQueue sendQueue) {
    this.receiver = receiveQueue as MessageQueue;
    this.sender = sendQueue as MessageQueue;

   }
}

public class MessageQueue : IQueue
{
    public string Path {get;set;}
    public MessageQueue(string inPath) {
        Path = inPath;}
}

interface IQueue{

}

Output For Examination
If you run the script above you'll see sample output which will look like the following:
mq.Path : extra.txt
mq.Path : super.txt
######################

#### example1 obj. uses default values ###########
example1.receiver.Path : extra.txt
example1.sender.Path : super.txt
######################

#### example1 obj. uses ParameterOverride values ###########
example2.sender.Path : newSendFile
example2.receiver.Path : newReceiveFile

Answer: I think this has been asked before on Stackoverflow.
You need to use ParameterOverride:
ParameterOverride enables you to pass in values for constructor parameters to override a parameter passed to a given named constructor. Only the parameter value is overridden, not the constructor.
Link to MSDN Article
Link to Stackoverflow Article
var exampleInstance = new Example();

var queue1 = unityContainer.Resolve<IQueue>(new ParameterOverrides<MessageQueue> { { "path", "yourPath" }});

var queue2 = unityContainer.Resolve<IQueue>(new ParameterOverrides<MessageQueue> { { "path", "yourPath2Queue2" }});

exampleInstance.Example(queue1,queue2);

Comment: Thank you! But I want to resolve Example like this, container.Resolve(). How do I specify the two different MessageQueue instances?


Hahn Banach theorem and sublinear functionals

Question: I find it strange that it is such a useful property for a linear functional to be bounded by a sublinear functional. What information does it really give?
Let $X$ be a Banach space and $p,f:X\to\mathbb{R}$. Well I realize that if $p$ is a sublinear functional and $f$ is a linear one, the condition $|f(x)|\le p(x)$ is weaker than the condition $||f||<\infty$. But what does it really imply? I mean ok, if $p$ is bounded then $f$ is bounded, but what is $p$ is not bounded?
For example, if $f$ is defined on $V$ a subspace of $X$ and we take $\lim_{\,n\to\infty}f(x_n)$, with $x_n\to x\in\overline{V}\backslash V$ can we deduct that the limit exists (with the possibility of being infinity) or it may not even exist at all? Do we get any information on the spectrum of $f$?
Answer: I think that the main point of the condition is that Hahn Banach applies in more generality than normed spaces.
For example one can prove that any two convex sets in a topological vector space (not even locally convex), with one of them open, can be separated by a continuous functional (i.e "geometric Hahn-Banach theorem"). The proof uses Hahn Banach where $p$ is the Minkowski functional of a well-chosen neighbourhood of zero.


Trouble adding event listeners via JavaScript

Question: Currently I have a function which loops to create multiple HTML objects. Each time an object is created, I want to add an onClick function listener to that object so that I can trigger a function when each one is clicked.
What's the best way to do this?
Here's the code which creates my objects:
    RenderMultipleChoice:function()
{
    this.c = paper.rect(this.x, this.y, this.shapeWidth, this.shapeHeight);
}

Answer: You might consider to use event delegation instead of adding a click listener to each created element. Then you only have one event listener on a parent, and see what element the event bubbled from. It will also magically work for elements created in the future.
jQuery has two methods to handle this for you:

.live() - bind event listener to the body element (has disadvantages)
.delegate() - bind event listener to the (parent)elements you specify (better performance)

Example:
$("#parent").delegate(".child", "click", RenderMultipleChoice);

live is an awesome function, but you should be aware of it's disadvantages:
Performance difference between jQuery's .live('click', fn) and .click(fn)
http://paulirish.com/2010/on-jquery-live/
Comment: I was unaware of event delegation until now, thanks very much for suggesting this. Looks like the way to go for what I'm doing.
Answer: You can use addEventListener or attachEvent.  Assuming paper.rect returns a DOM element:
if(this.c.addEventListener)
{
  this.c.addEventListener("click", listenerFunction, false);
}
else
{
  this.c.attachEvent("onclick", listenerFunction);
}

There are libraries to abstract this away.
Comment: actually you need to use both if you are going to have some sort of cross browser compatibility.


ReportViewer reporting from a DataTable

Question: I was wondering if there was a way to design a report for ReportViewer from a SQL query. So from the SQL query I'd get all the data I need to make a report and then design the report in the designer?
I am very new to ReportViewer and I am quite confused. Right now I can see I can populate the DataSet from a wizard, however as far as I can see there is no way to throw a SQL query in there and then design from that.
Is what I want even possible or will I have to use a DataGridView? I really want to use the reportviewer because of the printing/exporting support. Is there any literature available on the subject?
Answer: If you are using the LocalReport Class (reportViewer.LocalReport) and not the SSRS (everything is clickable there), a sample is in the link.
ReportDataSource Class has constructor that accepts a DataTable object.
You only need to design the report and add datasets to the RDL file.
Edit: Insert datasets as xml like this:
<DataSources>
    <DataSource Name="MyDataSource">
      <ConnectionProperties>
        <ConnectString />
        <DataProvider>SQL</DataProvider>
      </ConnectionProperties>
    </DataSource>
    ...
</DataSources>

<DataSets>
    <DataSet Name="MyDataSet">
      <Query>
        <CommandText>MyDataSet</CommandText>
        <DataSourceName>MyDataSource</DataSourceName>
      </Query>
      <Fields>
        <Field Name="Id">
          <DataField>ID</DataField>
        </Field>
        <Field Name="SomeOtherField">
          <DataField>SOME_OTHER_FIELD</DataField>
        </Field>
      </Fields>
   </DataSet>
</DataSets>

Answer: Firstly, it depends on whether you're using a local report or a server report (SQL Server Reporting Services). Both can be displayed within the ReportViewer control.
For a server report, things are simple. The report contains data sources and you can either choose to use an SQL statement or an existing stored procedure.
For a local report, things are a bit more difficult. You'd have to design a typed data set that contains your data. This can be filled from anything as usual (SQL command, stored procedure, etc.). You'd then assign the instance of this data set to the report's data source.
Please note that while the server reports allow you to filter the data, you'd have to write some filtering feature yourself when using local reports.

ReportViewer reporting from a DataTable


Cannot implicitly convert type `System.Collections.Generic.List` to `Leap.Hand`

Question: I've got this error
Cannot implicitly convert type System.Collections.Generic.List<Leap.Hand> to Leap.Hand
Here's my code:
using UnityEngine;
using System.Collections;
using Leap;
using Leap.Unity;

public class Swimming : MonoBehaviour {

    Controller controller;

    void Start(){
        controller = new Controller ();
    }

    void Update(){

        Frame frame =  controller.Frame (); // controller is a Controller object
        Hand hand = frame.Hands;

        for (int i = 0; i < frame.Hands.Count; i++) {
            if (frame.Hands [i].IsLeft) {
                Debug.Log ("Left Hand Detected");
          }
        }
    }
}

I've searched a lot but i couldn't find something. Can anyone help me please
Comment: `frame.Hands` is a collection of `Hand` instances. It is not a single `Hand`. It is a thing which contains many `Hand`s. That is a different thing. A box containing kittens is not a kitten. You cannot feed the box. If you want one kitten, you must reach in and take one kitten out. That is the kitten. The box is not the kitten.
Answer: Your problem is here:
Hand hand = frame.Hands;

frame.Hands is a collection of Hand, but you're trying to assign this value to a single instance of Hand. So, instead, you should be doing this:
List<Hand> hands = frame.Hands;

Comment: Thank you so much sir . So does my code can detect if the hand is right / is left?
Comment: Well actually, your code looks fine even without this collection of hands. Not sure why you're assigning this variable at all, really.
Comment: base on what i understand the for loop is for the finger count. so if the hand is left it'll debug.log(Left hand detected);


Class template function signature syntax

Question: I have a class defined like this:
template< class TBoundingBox >
class BoundingBoxPlaneCalculator
{
  typedef PlaneSpatialObject< TBoundingBox::PointDimension > PlaneSpatialObjectType;
  typedef typename PlaneSpatialObjectType::Pointer      PlaneSpatialObjectPointer;
  std::vector<PlaneSpatialObjectPointer> GetPlanes() const{}
}

If I call the function like:
std::vector<PlaneCalculatorType::PlaneSpatialObjectPointer> planes = planeCalculator->GetPlanes();

It works fine. However, if I change the delcaration to simply
  std::vector<PlaneSpatialObjectPointer> GetPlanes() const;

and then try to define the function outside of the header:
template< class TBoundingBox >
std::vector<BoundingBoxPlaneCalculator< TBoundingBox >::PlaneSpatialObjectPointer>
BoundingBoxPlaneCalculator< TBoundingBox >::GetPlanes() const
{

}

I get
itkBoundingBoxPlaneCalculator.txx:61:82: error: type/value mismatch at argument 1 in template parameter list for 'template<class _Tp, class _Alloc> class std::vector'
itkBoundingBoxPlaneCalculator.txx:61:82: error:   expected a type, got 'itk::BoundingBoxPlaneCalculator<TBoundingBox>::PlaneSpatialObjectPointer'

I also tried adding typename, but nothing changed:
template< class TBoundingBox >
std::vector<typename BoundingBoxPlaneCalculator< TBoundingBox >::PlaneSpatialObjectPointer>
BoundingBoxPlaneCalculator< TBoundingBox >::GetPlanes() const

Can anyone see what is wrong with this syntax?
Thanks,
David
Comment: It's a good idea when posting here to reduce the issue to the minimum - particularly don't use very long names, good though they may be in your actual application code.
Comment: What is `TBoundingBox::PointDimension` ? A type? An integer? If it's a type, I keep wondering why you don't need a `typename` before that... And what compiler are you using?
Answer: I pretty much copy-pasted your code but used int to replace a type you didn't define, and this works fine for me (using g++ 4.4):
#include <vector>

template<class TBoundingBox>
class BoundingBoxPlaneCalculator
{
public:
    typedef int* PlaneSpatialObjectPointer;
    std::vector<PlaneSpatialObjectPointer> GetPlanes() const;
};

template<class TBoundingBox>
std::vector<typename BoundingBoxPlaneCalculator<TBoundingBox>::PlaneSpatialObjectPointer>
    BoundingBoxPlaneCalculator<TBoundingBox>::GetPlanes() const {}

int main()
{
    BoundingBoxPlaneCalculator<int> planeCalculator;
    planeCalculator.GetPlanes();
}

The thing is, this doesn't look really different from what you posted, except for the fact that PlaneSpatialObjectPointer wasn't declared in your code.  So either there's a typo or missing piece somewhere in your real code, or something else is afoot.
Comment: I'm using gcc 4.6. I'm trying to reduce the issue to a standalone, compilable example.
Comment: I wonder if throwing a `typename` in front of that might help then?  I don't know, I'm not super-familiar with MSVC and particularly not with this purported bug (got a link?).
Comment: Forget my comment, OP isn't using MSVC and even MSVC (2010 atleast) chokes when `PointDimension` is a type.
Comment: I tried to simplify the problem so it would stand alone. I don't know if I got it exactly right, but the new errors are: template argument 1 is invalid on the std::vector<> line in main()
Comment: Whose main(), yours or mine?  Does my code work for you or not?  If not, please paste the complete compiler error.
Answer: It looks like I just had to add typename in the calling function:
std::vector<typename PlaneCalculatorType::PlaneSpatialObjectPointer> planes = planeCalculator->GetPlanes();

I'm confused why it worked without it when the function was defined inside the class??


finding the surface where curve is given as geodesics

Question: the parametric equation of the following curves can be given by
(1) Astroid :-$(a \cos^3 t , a \sin^3 t)$
(2) Cardioid:- $(a(2\cos t-\cos 2t), a(2\sin t-\sin 2t))$
(3) Deltoid :- $(2a\cos t+a\cos 2t , 2a\sin t-a\sin 2t)$
Can someone tell are there any surfaces in which they becomes geodesics of the surfaces. thanks for your precious time.
Comment: Before that shall I add to your list a simple (0) Circle:- $( a \cos t , a \sin t )?$
Comment: To me the question appears vague without a unique answer. If a surface is given we can find a geodesic. But if a geodesic is given then it can form a part of many sets of surfaces.
Comment: E.g., given is a straight line segment in 3d. Now rotate it around any axis. You get a hyperboloid of 1-sheet, Give it a uniform or non-uniform twist/torsion around an arbitrary line forming helical surface sets... such as a Moebius strip etc.
Answer: HINT:
a) All cylindrical  surfaces "vertically extruded" by parameter $u$ are  (trivial) examples .
(1) Astroid cylinder :-$(a \cos^3 t , a \sin^3 t, b u ) = ( X(t),Y(t), b u ) $
(2) Cardioid cylinder :- $(a(2\cos t-\cos 2t), a(2\sin t-\sin 2t, b u ))$
(3) Deltoid cylinder :- $(2a\cos t+a\cos 2t , 2a\sin t-a \sin 2t, b u)$
b) All surfaces of revolution obtained by rotating through angle $u$ on one of above axes $X(t),Y(t)$  which make up the meridians.
$$ (X(t) \cos u, X(t) \sin u, Y(t) ) $$
and to it we may also add helices
$$ (X(t) \cos u, X(t) \sin u, b u  ) $$
HINT2:
For a particular metric (  E, F are functions of u, v only ) example that is not a surface of revolution,
$$ ds^2=(1+u^2)~ du^2 + 2 uv~ du ~dv + (1+v^2) ~dv^2 $$
we can work out from canonical geodesic equations  where c is a constant,
$$u+v=c$$
A simple $ (u,v)$ relation on arc s
$$ u= \frac{s}{\sqrt{2+c^2}},~ v= c-\frac{s}{\sqrt{2+c^2}}$$
Hope you take it further with simple parametrization in 3-space
Comment: yes, thats true. But did there any other except the surface of revolution


Highcharts Angular with API data

Question: I'm using the official Highcharts angular wrapper from https://github.com/highcharts/highcharts-angular and have got a test chart working in my Angular 6 project.
The problem I'm having is trying to get the chart to only show once I have retrieved my data from an api.
This is my html:

        <highcharts-chart
        [Highcharts]="Highcharts"
        [options]="chartOptions"
        style="width: 100%; height: 400px; display: block;"
    ></highcharts-chart>

and this is my component
loading = true;
Highcharts: any;
chartOptions: any;

public constructor(
    private dashboardService: DashboardService) {
}

ngOnInit() {
    this.dashboardService.getClaimProviderCountsByMonth()
        .pipe(first())
        .subscribe(
            data => {
                // this.chartOptions.series = [{
                //     data: data
                // }];
                this.Highcharts = Highcharts;
                this.chartOptions = {
                    chart: {
                        type: 'column'
                    },
                    title: {
                        text: 'Stacked column chart'
                    },
                    xAxis: {
                        categories: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
                    },
                    series: data.data
                };
                this.loading = false;
            },
            () => { });

}

However I get the error "ERROR TypeError: Cannot read property 'chart' of undefined"
My API data is formatted properly, and if I hard code it in it works ok, but I'm obviously running into async issues.
Comment: This should be ``
Answer: Since you are loading the Chart data from API asynchronously, you need to either use *ngIf or safe navigation operator to check the chartOptions as follows,

Highcharts Angular with API data


PHP Calculating with time with a negative start value

Question: I'm trying to convert a certain excel sheet to a php app.
Within the excel sheet you could do time calculations as eg:

A starting time A1 (could be negative), and for every day you add or substract a certain amount of hours and minutes.
<code> - A1= -10:59
 - A2= -7:36
 - A3= -18:35 (A1 + A2)

 - B2= 4:24
 - B3= -14:11 (A3 + B2)
</code>
And so on ...

Here is some code i've tested with without succes ofcourse...
<code>    $startTime = new \DateTime('00:00:00');
    $startVal = new \DateInterval('PT10H59M');
    $startTime->sub($startVal); // -10:59:00

    $timeSpan = new \DateInterval('PT7H36M'); // 7:36:00
    $addTime = $startTime->add($timeSpan);
</code>
What is the best way to solve this in PHP? I've been testing around with DateTime but this won't allow me te start with a negative time value.
Hope someone can give me a hand.
Kind regards,
Jochem
Comment: I would convert time to seconds, sum them (depends the sign + or -) and after that convert to minutes
Answer: I have written a simple class to handle this. It works for your given example but I was unable to test further as I cannot get negative times in my version of Excel. Let me know if it fails at some point.
<code>class MyTime
{
  private $positive = true;
  private $hour=0;
  private $minute=0;

  /**
   * MyTime constructor.
   * Split the given time string into hours and minutes and whether it is positive or negative
   *
   * @param string $timeString In the format '-10:59', '4:35', or optionally just minutes '24'
   */
  public function __construct($timeString)
  {
    if(!empty($timeString))
    {
      if(strpos($timeString,'-')===0)
      {
        $this->positive = false;
        $timeString = substr($timeString,1);
      }

      $timeParts = explode(':',$timeString);
      if(!empty($timeParts))
      {
        if(count($timeParts) == 1)
        {
          $this->hour = 0;
          $this->minute = intval($timeParts[0]);
        }
        else
        {
          $this->hour = intval($timeParts[0]);
          $this->minute = intval($timeParts[1]);
        }
      }
    }
  }

  public function getHour()
  {
    return $this->hour;
  }

  public function getMinute()
  {
    return $this->minute;
  }

  /**
   * Convert into minutes either negative or positive
   * @return int
   */
  public function inMinutes()
  {
    $minutes = ($this->hour*60)+$this->minute;
    if(!$this->positive)
    {
      $minutes *= -1;
    }
    return $minutes;
  }

  /**
   * Convert back to a string for output
   * @return string
   */
  public function __toString()
  {
    return ($this->positive?'':'-').$this->getHour().':'.str_pad($this->getMinute(),2,'0',STR_PAD_LEFT);
  }

  /**
   * Add on the given time which could be negative
   * @param MyTime $time
   *
   * @return $this
   */
  public function add(MyTime $time)
  {
    $newMinutes = $this->inMinutes() + $time->inMinutes();
    if($newMinutes<0)
    {
      $this->hour = (int) ceil($newMinutes/60);
    }
    else
    {
      $this->hour = (int) floor($newMinutes/60);
    }
    $this->minute = abs($newMinutes-($this->hour*60));

    if($newMinutes<0)
    {
      $this->positive = false;
      $this->hour *= -1;
    }
    else
    {
      $this->positive = true;
    }
    return $this;
  }
}

$time = new MyTime('-10:59');
echo $time."\n";
echo $time->add(new MyTime('-7:36'))."\n";
echo $time->add(new MyTime('4:24'))."\n";
echo $time->add(new MyTime('18:32'))."\n";

$time = new MyTime('10:59');
echo $time."\n";
echo $time->add(new MyTime('-59'))."\n";
</code>
Comment: Hey Mark!

I'm realy thankfull for what you created! Much thanks!
However i stumbled up on a litle bug i guess. eg:

`$time = new MyTime('-24:59');
echo $time."\n";
echo $time->add(new MyTime('+12:00'))."\n";
echo $time->add(new MyTime('+12:00'))."\n";
echo $time."\n";`

This gives "0:59" but it should be "-0:59".

Any idea why this is ?
Comment: I have corrected the code. The problem was in the add function. After setting the new hour and minute I was checking if `$this->getHour()<0` and in your example it was exactly zero so the function made it positive even though there were some minutes to consider. I should have been checking the original `$newMinutes` result to see if it was less than zero. Let me know if you spot any other mistakes :)
Comment: Mark, i had found one more bug but did a small fix for it:
When the minutes where eg '08* minutes a decimal number would only set '8' as minutes:
i've added this bit of code to fix it, probable not the cleanest but it works.

In the Add function

        `$minutes = abs($newMinutes - ($this->hour*60));
        $this->minute = strlen($minutes) == 1 ?  0 . $minutes : $minutes;`
Comment: If you've got it working that's fine but hours and minutes were supposed to remain as integer types until the class is converted to a string with __toString then it prepends the leading zero. This is because of all the calculations on them. I am not sure I understand the bug you mention nor what your fix is supposed to be doing. If you are converting $this->minutes into a string PHP will have to convert it back to an integer every time it needs it for a calculation.
Comment: Hi Mark, sorry for the bad explination, let me give you an example

        `$time = new MyTime('-6:32');
        echo $time."\n";
        echo $time->add(new MyTime('-7:36'))."\n";
        echo $time."\n";`

This time returns '-14:80' however it should be '-14:08'. Hope this clears out abit of the confusion
Comment: Thanks for the clarification, I have fixed the code. The correct place to fix that was in the `__toString()` function and not the `add()` function. As I say, `$this->minute` should remain as an integer. I simply added `STR_PAD_LEFT` in the `__toString()` function. Sorry for the mistake as it was quite obvious once you pointed it out :)
Comment: Hey Mark, you don't have to apologize! I'm realy thankfull for what you build here and everything seems to be working on point now !
Best regards, Jochem


How can I make this generic and pass any enum to it?

Question: Okay, it's time I learned arguments, parameters, generics... Oh yay me!! I see how to use explicit typing but have no clue as to making this method generic and pass in the enum of choice. Any advice/"tutor code" would be great.
using System;

public class Program

{
    enum FarmAnimals { Cow = 1, Chicken, Goat, Horse }

    enum ForrestAnimals { Lion = 1, Tiger, Elephant, Panther, Monkey }

    enum SeaAnimals{ Whale = 1, Shark, Eel, Tuna, Swordfish, Dolphin, Sealion }

    public static void Main()

    {
        Test();
    }

    static void Test()
    {
        bool whatever = true;
        bool ok;
        int pick = 0;

        foreach (FarmAnimals animals in Enum.GetValues(typeof(FarmAnimals)))
        {
            int id = Convert.ToInt32(animals);
            String name = Enum.GetName(typeof(FarmAnimals), animals);
            Console.WriteLine("{0} - {1}", id, name);
        }

        while (whatever == true)
        {
            Console.Write("Pick a number ");
            String line = Console.ReadLine();
            ok = int.TryParse(line, out pick);

            if (ok)
            {
                int counter = Enum.GetValues(typeof(FarmAnimals)).Length;
                if (pick < 1 || pick > counter)
                {
                    Console.WriteLine("You have an invalid number! You used {0}.", pick);
                }
                else
                {
                    FarmAnimals animals = (FarmAnimals)pick;
                    Console.WriteLine("Great! You picked: {0}", animals);

                }
            }
            else
            {
                Console.WriteLine("Please pick a number.");
            }
        }

    }
}

Comment: Make _what_ method generic?
Answer: Your code have endless loop. There must be an exit condition.
Bellow code remove endless loop and use generic method, You can pass any enum to it
public static void Test<T>() where T : Enum
{
    Type enumType = typeof(T);

    foreach (T enumValue in Enum.GetValues(enumType))
        Console.WriteLine("{0} - {1}", Convert.ToInt32(enumValue), Enum.GetName(enumType, enumValue));

    while (true)
    {
        Console.Write("Pick a number ");
        string line = Console.ReadLine();
        int pick;

        bool ok = int.TryParse(line, out pick);

        if (ok)
        {
            if (pick < 1 || pick > Enum.GetValues(enumType).Length)
                Console.WriteLine("You have an invalid number! You used {0}.", pick);
            else
                Console.WriteLine("Great! You picked: {0}", Enum.GetName(enumType, pick));

            break;
        }

        Console.WriteLine("Please pick a number.");
    }
}

And then, you can use it like this
Test<SeaAnimals>();
Test<ForrestAnimals>();

Comment: Thank you. I wasn't expecting an outright answer. I was hoping for tutor code (where you add comments throughout the code) or something. I'll dissect it and study it that way. Thank you so much.


Grouping php array items based on user and created time

Question: This is an array of objects showing a user uploading photos:
Array
(
    [12] => stdClass Object
        (
            [type] => photo
            [created] => 2010-05-14 23:36:41
            [user] => stdClass Object
                (
                    [id] => 760
                    [username] => mrsmith
                )

            [photo] => stdClass Object
                (
                    [id] => 4181
                )

        )

    [44] => stdClass Object
        (
            [type] => photo
            [created] => 2010-05-14 23:37:15
            [user] => stdClass Object
                (
                    [id] => 760
                    [username] => mrsmith
                )

            [photo] => stdClass Object
                (
                    [id] => 4180
                )

        )
)

However instead of showing:

mr smith uploaded one photo
mr smith uploaded one photo

I'd like to display:

mr smith uploaded two photos

by grouping similar items, grouping by user ID and them having added them within, let's say 15 minutes of each other. So I'd like to get the array in this sort of shape:
Array
(
    [12] => stdClass Object
        (
            [type] => photo
            [created] => 2010-05-14 23:36:41
            [user] => stdClass Object
                (
                    [id] => 760
                    [username] => mrsmith
                )

            [photos] => Array
                (
                    [0] => stdClass Object
                          (
                           [id] => 4181
                          )

                     [1] => stdClass Object
                          (
                           [id] => 4180
                          )
                )

        )
)

preserving the first item of the group and it's created time, and supplementing it with any other groupable photos and then unsetting any items that were grouped (so the final array doesn't have key 44 anymore as it was grouped in with 12).
The array contains other actions than just photos, hence the original keys of 12 and 44. I just can't figure out a way to do this efficiently. I used to use MySQL and PHP to do this but am trying to just use pure PHP for caching reasons.
Can anyone shed any insights? I thought about going through each item and seeing if I can group it with the previous one in the array but the previous one might not necessarily be relevant or even a photo. I've got total brain freeze :(
Comment: Is this data you're getting from a database?  If so, it is very inefficient to load entire tables into an array.  Perhaps you could clarify the application further?
Comment: I agree with Jonah.  Have you considered simply caching the result of the MySQL query?  Two birds, one stone and all that.
Comment: It's a users activity stream, akin to facebook stream. It used to grab activity from separate tables and combine into one unified array of objects. Of course this was quite inefficient and I couldn't use LIMIT.

So I was going to move everything to an activity table, where I can query activity very quickly and in one single query. The problem with that is, I can't then use MySQL to group photos together anymore as I'd done before. Like this:

 id user_id object_id type created

 1 2 48592  photo 18:18:50
 2 2 48593  photo 18:18:51
 3 2 548592  comment 18:18:55
 4 2 48594  photo 18:18:59
Comment: This is just my opinion, but I *think* you're causing a lot of extra work for yourself as well as setting yourself up for scalability problems down the road.  If it were me, again, my opinion, I'd stick with MySQL and the normalized tables, get your app up and running, and begin to focus on performance improvements, query tuning, etc, *after* figuring out where bottlenecks might be with something like xdebug. YMMV.
Comment: Thanks Jeremy, that's why I'm faced with this problem though, I'd started off with the normalised tables and with the app getting more attention it was causing frequent downtime with the server. The problem were these queries and the memory usage all on one page hit, and with users and search engines the server was struggling.

Running some benchmarks with the de-normalized "activity" table, an idea I'd got from questions here, while it does create more headaches, indicated it was much much faster and less memory intensive.
Comment: @Jim - Ah, well then, you're way ahead of me. That's what I get for making assumptions ;)  Wish I could actually help.  Good luck!
Comment: Thanks! I'll give the answer a go but I think my brain has given up for the day
Answer: If the entries are ordered by date you can do the following:

Keep an array (let's call it $foo) with all the photos in a 15 minute window. Use the array as a FIFO list (use array_shift to remove items and $foo[] = ... to add).
Iterate over the original array

Check the date of the current item and remove from the beginning of $foo all the entries whose date is more than 15 minutes less than the current item. Once you find an item that for something that happened less than 15 minutes ago, you can stop (it's a one line for loop).
Iterate over the the entries in $foo
If a photo by the same person is found, then

Alter the reference stored in $foo so that the new data is added
Remove the current item from the original array
break from inner loop

If not

Add a reference to the current item to the end $foo with $foo = &$var.

You may then reindex the original array with array_values to fill the gaps.


Test Hangs at "Instantiating tests..." for 20 seconds using Gradle

Question: I am running a test using Gradle and it says "Instantiating tests..." for about 20 seconds before actually running the test. How can I avoid this?

I am using Quarkus 2.2.3.Final, and gradle-7.2.
My test class:
class OrganizationServiceImplTest {
    @Test
    void getAllOrganizations() {
        assertTrue(true);
    }
}

The Run Configuration shows the following run command:
:test --tests "com.doortodoor.services.impl.OrganizationServiceImplTest.getAllOrganizations"

Idea Log File shows as follows:
2022-11-09 21:56:29,387 [117677008]   INFO - s.plugins.gradle.GradleManager - Instructing gradle to use java from C:\Program Files\OpenJDK\jdk-17.0.2
2022-11-09 21:56:29,387 [117677008]   INFO - s.plugins.gradle.GradleManager - Instructing gradle to use java from C:\Program Files\OpenJDK\jdk-17.0.2
2022-11-09 21:56:29,466 [117677087]   INFO - xecution.GradleExecutionHelper - Passing command-line args to Gradle Tooling API: --init-script C:\Users\242924\AppData\Local\Temp\1\ijmapper.gradle --tests com.doortodoor.services.impl.OrganizationServiceImplTest.getAllOrganizations --init-script C:\Users\242924\AppData\Local\Temp\1\ijresolvers.gradle
2022-11-09 21:56:30,284 [117677905]   INFO - rationStore.ComponentStoreImpl - Saving appDaemonCodeAnalyzerSettings took 64 ms
2022-11-09 21:56:30,381 [117678002]   INFO - rationStore.ComponentStoreImpl - Saving Project(name=quarkus-quickstart-security, containerState=COMPONENT_CREATED, componentStore=C:\source\quarkus-quickstart-security)Encoding took 11 ms, RunManager took 36 ms

Solutions I have tried that didn't work include:
Solution 1: Use Eclipse Compiler
Why does IntelliJ take 20+ seconds to launch a unit test?
Compiler -> Java Compiler

Use compiler: Eclipse
Generate no warnings

Problem: It didn't improve the time.
Solution 2: Use shared Spring Context
Gradle is executing tests terribly slow because it is adding to much tests to the suite
Problem: I'm not annotating my tests with @SpringBootTest (or using Spring for that matter).
Solution 3: Enable Eclipse features such as incremental compilation
Intellij idea tests compilation takes too long (compared with Eclipse)
Comment: Could it be related to our Dev Services feature and that Quarkus is actually starting a Docker container for a database or any other service?
Answer: For anybody wondering, I was able to resolve the long hanging time by changing the test runner to IntelliJ Idea in File | Settings | Build, Execution, Deployment | Build Tools | Gradle.
Comment: Thank you!! That made a huge difference. Don't forget to *delete* your previous run configuration (which is still using Gradle) so that IntelliJ creates a new one using IntelliJ.


mod operation proof

Question: Prove:
$  ab\,\bmod\,d = ((a\,\bmod\,d)\,(b\,\bmod\,d))\,\bmod\,d $ where $a$, $b$ and $d$ are non-negative integers.
Reference : http://en.wikipedia.org/wiki/Modulo_operation#Equivalencies
Context :
I was solving the problem 'C. DNA Alignment' in Codeforces Round #195(div.2).
To solve the problem, I had to calc (a^b)%n in Big-O(N) without overflow.
This could be done simply if above equation is always true.
I assumed this equality is always true and solve the problem.
But I couldn't prove my solution because of this equation, so I searched it but faild.
So I decided to ask the proof of this problem.
Problem Source : http://codeforces.com/contest/520/problem/C
Comment: Done, now what?
Comment: I wanted to prove "ab mod d = ((a mod d) * b) mod d" not "ab mod d=((a mod d)(b mod d))mod d" even they are mathematically same.
Answer: Let $a=\alpha d+j, b=\beta d+k$. $a\mod d =j$, so the right hand side is:
$$jb\mod d=(j\beta d+jk) \mod d=jk \mod d$$.
Looking at the left hand side:
$$ab \mod d=(\alpha d+j)(\beta d+k)=\alpha\beta d^2 + \alpha dk + \beta dj + jk=jk \mod d$$
and these are equal.

mod operation proof


How to merge two dataframes based on header and columns values?

Question: I have two dataframes. The first one contains the data of different cities.
dfTmp:
    City        2005    2007
0   London       3       7
1   Paris        2       0

then an empty dataframe that I want to populate
dfData:
    City        Year
0   London      2005
1   London      2007
2   Paris       2005
3   Paris       2007

I want to merge the two datasets. Then dfData should become as the following
dfData:
    City        Year    Value
0   London      2005     3
1   London      2007     7
2   Paris       2005     2
3   Paris       2007     0

Answer: You don't need the second dataframe, dfData.  All the data you need is in the dfTmp.  You just need to reshape dfTmp using the following:
Option 1
using set_index and stack
dfData = dftmp.rename_axis('Year', 1).set_index('City').stack().reset_index(name='Value')

print(dfData)

Output:
     City  Year  Value
0  London  2005      3
1  London  2007      7
2   Paris  2005      2
3   Paris  2007      0

Option 2
using melt:
dfData = dftmp.melt(id_vars='City', var_name='Year', value_name='Value')

print(dfData)

Output:
     City  Year  Value
0  London  2005      3
1   Paris  2005      2
2  London  2007      7
3   Paris  2007      0

Answer: The solution given above, - avoiding merge using only dfTmp -, seems optimal.
In case you insist to use Merge, the following could be done:
First take care that the Pandas package is imported:
import pandas as pd

We have the following data:
Tmp = {'City': ['London', 'Paris'],
    '2005': [3,2],
   '2007': [7,0]}
dfTmp = pd.DataFrame(data, columns = ['City', '2005', '2007'])

And:
data = {'City': ['London', 'London', 'Paris', 'Paris'],
    'Year': [2005,2007, 2005, 2007]}
dfData = pd.DataFrame(data, columns = ['City', 'Year'])

Then use Merge in Pandas:
dfNew = pd.merge(dfData, dfTmp)
dfNew.iloc[0:4,0:3]