How to use decltype in std::future?

Question: In this code, how can I use decltype in std::future to deduce the return type of bar() ? Although directly using std::future<int> works, I would like to know how can decltype be used in such a situation.
#include <iostream>
#include <future>

int bar(int a)
{
    return 50;
}
int main()
{

    std::packaged_task<decltype(bar)> task(bar);

    //std::future<decltype(bar(int))> f = task.get_future(); //doesn't work need to do something like this

    std::future<int> f = task.get_future();   //works

    std::thread t1(std::move(task), 10);
    t1.detach();
    int val = f.get();
    std::cout << val << "\n";
    return 0;
}

Also, is the use of decltype in std::packaged_task correct ?
Comment: I think you mean something like `decltype(bar(0))`?
Comment: Is passing the parameter explicitly the only solution ?
Comment: @bornfree - What's the problem with that? Do you not know the parameter's value or type?
Comment: @bornfree In addition to StoryTeller's comment, in case you can't construct a parameter of the appropriate type, you can use `std::declval()`.
Answer: Note that you can use auto:
auto f = task.get_future();

And everything works as expected.

decltype is used to detect the type of an expression. In this case, bar(int) is not a valid expression. You may use decltype(bar(0)).
Alternatively, you can use the dedicated tools for determining the result of a function invocation. Since you tagged c++11, you can use typename std::result_of<decltype(bar)*(int)>::type (of course, you need to #include <type_traits>).

For the benefit of future readers: I would like to address this question in the perspective of c++17. result_of is expects template argument of the form F(Args...), which suffers since the function type is the return type and is extremely limited. In c++17, invoke_result is introduced, and is way better than result_of: std::invoke_result_t<decltype(bar), int>. Very intuitive.

How to use decltype in std::future?


Simperium duplicates existing records

Question: When my iOS app is started for the first time, it initializes a few entities with default data. The same process is completed for every device of the same user when the app is first installed on the device. This leads to a problem with Simperium, because, even if I have a constraint on one of the entity's attributes, it create duplicates. How can avoid that from happening? Is there a way to make Simperium skip objects locally initialized ? Or to prevent it from inserting duplicates?
Would setting the simperiumKey of the entity to a custom constant value which is the same for all the devices of the user fix the issue? I mean, would that prevent Simperium from importing the very same entity from different devices that would produce duplicates and sync conflicts ?
Because I tried that option and it looks like the buckets on Simperium Server are ok, but when I dispose the view and I open it again the entities are not there anymore. When I restart the app they are back again... it looks like they desappear to reappear after resetting the app.. very strange.
UPDATE
The problem is that I get duplicated entities if I try to insert the same entity from different device. For example. When I setup my app for the first time, I have a function that initializes CURRENCY entities with codes and other things. The same operation would be done from a different device if the user decides to install the app on a new one. In this case, because the new device will initialize again the CURRENCY entities, those info will generate duplicates and conflict errors. I need a way to make Simperium understand that the entities locally inizialized in the devices must not be duplicated. I would remove the inheritance from SPManagedObject in order to stop Simperium from syncing the entities, but in their turn they have relations with other entities and that would definitively create problems with Simperium, because it will try to sync entities which have relations with objects not inheriting from SPManagedObject. Hope you now have a more clear idea.
Comment: Yeah, now I got it. Is it possible to fetch the server entities first. So, as soon as the user launches it will create first. Instead fetch from the server, if nothing found then start inserting.
Comment: Can you please show the code how are you trying to achieve this.
Comment: Which code? Can you please clarify your request? Tx
Comment: What kind of problem are you facing in Simperium in the first place, ideally the first paragraph says there is a problem. You wrote what you tried, but what exactly is the problem.
Comment: I update my question to give you more details. I cannot write too much in a comment
Comment: It looks like inserting a custom simperiumKey when I loccally save the entities would do the trick, but when I signi out I lose part of the data. I mean, data is deleted on exit, it remains on Simperium's server, but it is not replicated back on my device when I log in again. There is something subtle and the documentation should be improved. The solution, at the moment, was to never call signOutAndRemoveLocalData... I don't know if that will cause further problems later on (I mean not calling signOutAndRemoveLocalData on exit)
Comment: You can raise a bug in Simperium. Either they will give the solution or the recommended way to address this.
Answer: After reading various posts on this subject I've understood that not signing out (that means: not calling signOutAndRemoveLocalData) and setting custom simperiumKey-s would prevent data duplication. I tested this solution and it apparently looks good. My app needs Simperium to sync data with other devices of the same user, but it mainly works with the local CoreData database. I hope this solution is good for this scenario.

Simperium duplicates existing records


How to write a series in sigma notation

Question: I'm working through the integration by parts of $(x^k)e^\left( -2x \right)dx$. My teacher wants our final answer in sigma notation.
I'm most of the way there, I have $\sum_{n=0}^{k} -e^\left( -2x \right)e^\left( k-n \right)(?)$
I know my mystery term is going to look like this $\frac{?}{2^\left( n+1\right)}$
And I know my denominator is
$1$ at $n=0$,
$\left( x\right)$ at $n=1$,
$\left( 1\right) \left( x\right) \left( x-1\right) $ at $n=2$,
$\left( 1\right) \left( x\right) \left( x-1\right) \left( x-2\right)$ at $n=3$,
$\left( 1\right) \left( x\right) \left( x-1\right) \left( x-2\right) \left( x-3\right)$ at $n=4$...
So how do I represent this specific sequence with sigma notation?
Answer: This is the falling factorial, which can be represented as $\frac{x!}{(x - n)!}$. However, I don't think your integral is correct. The correct answer should be something of the form
$$
\exp(2x)\sum_{k=0}^n \frac{something}{2^{n+1-k}\cdot(something)}
$$
Check your answer :)

How to write a series in sigma notation


Is it a good idea to have the same feature available from two different menus?

Question: It happens sometimes that one feature seems to belong to more than one place.
Trivial example, let's say I've got the following menus :

File
Pending orders
Accepted orders
Tools
Help

I've got a search feature, and the same search window work for both pending and accepted orders (it's just an 'order status' combo you can change)
Where does this search feature belongs?

The Tools menu seems to be a good choice, but I'm afraid the users may expect the search accepted orders to be in the accepted orders menu, which would make sense
Duplicating the menu entry in both pending and accepted order seems wrong to me.

What would you do? (And let's pretend we cannot merge the two orders menu into one single menu)
Comment: could you make the search visible all the time (e.g. in the right corner) or does it have to be hidden?
Comment: I've already a shortcut button available, but the user can hide it, and it seems a good practice for me that all features available from toolbars should be available from the menus, too
Answer: I think the problem you've run into is that you're thinking like a programmer.  (code duplication bad).  I'm not faulting you for it, I do the same thing.  Multiple paths to the same screen, or multiple ways to handle the same process can actually be extremely beneficial.  I would guess that more than one person is going to use your program and each probably have slightly different job functions.  In essence, they have different needs for the application and will approach using it different ways.   If you stick to the all items have one way of being accessed, some people will find the application beneficial and others won't.  Sure all people can learn to do a task a certain way, but it won't make sense to some users. It's not intuitive (read familiar) to they way they are used to processing information, which means the application will ultimately be less beneficial to them.  When people find a process (program etc.) frustrating, they won't adopt it.  They find reasons why the process will need to be changed or abandoned.
An excellent example of the multiple approaches to a problem is with Adobe Photoshop.  Normally there are at least 2 different ways to access a function.  Most users only know of one, because that's all they are concerned with, but most users are really comfortable with using one, because it makes the most sense to them.  With a little extra work, Adobe scored a huge win, because more people find their product intuitive.
Answer: Having a feature in multiple locations is not a bad thing. Consider the overall workflow for viewing both pending orders and accepted orders, and think of your new feature as a component, rather than a one-off entity.
After you map out exactly what tasks a user completes in the pending and accepted order viewing process, see where having the ability to search would provide value (by shortening the workflow or otherwise). This is where your search component belongs.
Answer: The main thing to remember about UI is that all that really matters in the end is whether your design makes using your application or site a better experience for your users.
In the search example you list above you'll commonly see apps take two approaches:

Put the search feature in a single location and allow the user to filter the search by selecting pending or accepted, or
Put the search feature in both menus, already configured for the type of search to be done based on the menu it was launched from.

If you repeat the above choice for a number of factors you'll see a much more advanced (aka 'complicated') search interface for number one, and a much simpler (aka 'restrictive') search interface for number two.
Which one is best completely depends on your users. This is why many general applications have a simple search by default and a link to a more advanced search for those that want or need the additional capabilities; they're attempting to make everyone happy. There is absolutely nothing wrong with that if you're writing for a wide variety of people with different needs. If you're writing for a set of users with a restricted set of needs however, you can make some better choices.
In my experience your best bet is to work with one or two of your primary users and map out all of the steps they need to take to get each of the tasks the application will be helping them with accomplished. If there aren't a lot of branching points in that sequence of steps there shouldn't be a lot of choices or settings to make in the application; otherwise the users may feel that the app is harder to work with than it needs to be.
For the search example above, if the user has already navigated into the Pending Orders menu, the likelihood that they'll want to launch a search for Accepted Orders is very small and having to make that choice, or go elsewhere to do the search, will be an extra decision or action they'll need to take. Basic principle is if your user has already made a decision, use it; don't make them tell you again.
Use the UI you come up with as a first cut. Let your users, or a subset of them, try it out and make suggestions. If you have the option, watch them use it. You'll learn far more about how to improve the interface  by seeing how they work with it than you will from what they tell you.
Answer: Generally you do not want the same menu item appearing in different menus. It adds complexity and clutter to the menu, and users will wonder if the two menu items are really the same or not. When it appears that a menu item belongs in two places, then you may have a more basic problem with your menu organization.
For instance, your example shows a menu bar that is organized by the class or attribute of the object the commands within act on. In general, the menu bar should be organized by category of action not type of object. For example, you could have a Retrieval menu for commands like Search and other means of displaying orders, and a Modify menu for processing the orders (e.g., updating, accepting, forwarding). Both menus would have menu items that apply to both types of objects, although some commands may apply to only one.
Organizing commands by object type is actually a good idea but it is better accomplished with a context menu (right click) than the menu bar.
Answer: I would try the search in both the Accepted Orders and Pending Orders menus.  However, user testing will show if this is a good idea or not.  But it also depends on your user base.
You are doing user testing right?
Comment: user what? in an ideal world, I would :) I do SO-testing instead !
Answer: ...you may already know this, but this is a good place to use the command\action pattern IMHO.
So to answer your question: IMO, yes, it is ok :) This situation is definitely warranted.
Answer: Just put it under both menus and have it open your search window, pre-configured for the order type who's menu it was launched from. Name them accordingly and voila they're actually two different actions - even though they use the same code/component.
Keep the user-selectable "status combo you can change" in the search window active though so the user still can adjust the settings without relaunching it from the other menu... and then perhaps rethink the structure, see some of the great answers in here for ideas ^^


Proving a limit using the $\epsilon$ - $\delta$ definition of limit.

Question: Given $\lim _{x\to a}\left(f\left(x\right)\right)=\infty$ and $\lim _{x\to a}\left(g\left(x\right)\right)=c$ where $c \in R$, prove $\lim _{x\to a}\left[f\left(x\right)+g\left(x\right)\right]=\infty$.
My attempt:
Let for every $M>0$ exists $\delta_1$ which satisfies $0 < |x-a| < \delta_1 \implies f(x) > M$.
Let for every $\epsilon > 0$ exists $\delta_2$ which satisfies $0 < |x-a| < \delta_2 \implies |g(x) - c| < \epsilon$. Or, I can write it as $0 < |x-a| < \delta_2 \implies c - \epsilon < g(x) < c + \epsilon$.
Let for every $N > 0$ exists $\delta$ which satisfies $0 < |x-a| < \delta \implies f(x) + g(x) > N$.
Using $\delta =$ min{$\delta_1, \delta_2$} so $f(x) > M$ and $g(x) > c - \epsilon$, I get $f(x) + g(x) > M + c - \epsilon$.
And I'm stuck. I've seen a solution somewhere which divides the final equations for $c = 0, c > 0,$ and $c < 0$ but I don't get the idea why do I have to solve it in cases. I don't know how to construct such $\delta$ that satisfies $N$.
I have taken a look at a similar question, proof of limit using epsilon-delta definition, but I'm not quite enlightened with the answer yet.
Answer: We can set $N=M + c - \epsilon$ at any value and since
$$f(x)+g(x)>M + c - \epsilon=N$$
the proof is complete.
Answer: It's useful to start with stating what you want to prove. In this case:
For every $N>0$ there is $\delta>0$ such that
$$ 0<|x-a|<\delta \Rightarrow f(x) + g(x) > N.$$
So, if you choose your $M$ and $\epsilon$ so that $$ M+c-\epsilon \geq N,$$
you are done.
Answer:
Let for every $M>0$ exists $\delta_1$ which satisfies $0 < |x-a| < \delta_1 \implies f(x) > M$.

Good, this is one of the given premises, $\lim_{x\to a}\left(f\left(x\right)\right)=\infty$.

Let for every $\epsilon > 0$ exists $\delta_2$ which satisfies $0 < |x-a| < \delta_2 \implies |g(x) - c| < \epsilon$. Or, I can write it as $0 < |x-a| < \delta_2 \implies c - \epsilon < g(x) < c + \epsilon$.

Good, this is the other given premise, $\lim _{x\to a}\left(g\left(x\right)\right)=c$ where $c \in R$.

Let for every $N > 0$ exists $\delta$ which satisfies $0 < |x-a| < \delta \implies f(x) + g(x) > N$.

Huh? This is what you have to prove. "Let" sounds like you think you can just assume it is true, like the premises.
But it's good to have written this out somewhere so that you know where you have to go.
So the question is, given an arbitrary $N > 0,$ find an $M$ and $\epsilon$
such that $f(x) > M$ and $|g(x) - c| < \epsilon$ together imply $|f(x) + g(x)| > N$.
Although it turns out you can prove $f(x) + g(x) > N$ (as you wrote), which is stronger than the statement with the absolute value.
You have two variables, $M$ and $\epsilon,$ that you can essentially set to whatever you like after you find out what $N$ you have to demonstrate.
This gives you a lot of options. You could, for example, just set $\epsilon = 1$ regardless of $N$, and then increase $M$ far enough to make things work.
Answer: You want to prove that for every $M$, there is a $\delta$ such that $|x-a|<\delta\implies f(x)+g(x)>M$.

Take some $\epsilon$ and some $N$ such that $N+c-\epsilon>M$, and by the given two limits you will find $\delta_f$ and $\delta_g$ such that
$$|x-a|<\delta=\min(\delta_f,\delta_g)
\implies f(x)>N\land g(x)>c-\epsilon
\\\implies f(x)+g(x)>N+c-\epsilon>M.$$
This is because in this neighborhhod of $a$, $f(x)>N$ and $g(x)>c-\epsilon$.


Rails classes reloading in production mode

Question: Is there a way to reload ruby model in runtime?
For example I've a model
<code>class Model
  def self.all_models
    @@all_models ||= Model.all
  end
end
</code>
Records in this model are changed very rarely, but then they do, I don't want to reload whole application, just this one class.
Comment: I've found this http://zilkey.com/2008/7/5/rails-cache-memcached-development-mode-and-offline-cache-invalidation

But it's only for use with Rails.cache, not static variables
Answer: On a Development server, this is not a problem. A production server is a big one.
In reality it's not feasible without restarting the server. The best you could do is add a before filter in ApplicationController to update class variables in each worker thread, but it has to be done on every request. You can't turn this behaviour off and on easily.
If it's an resource intensive operation, you can settle for a less intensive test like a comparing value in a database/last modified time of a file to a constant defined at runtime in an effort to determine if the full reload should occur. But you would still have to do this as part of every request.
However, to the best of my knowledge modifying routes once the server has been loaded is impossible. Modifying other site wide variables may require a little more effort, such as reading from a file/database and updating in a before filter.
There may be another way, but I haven't tried it at all. So there's no guarantee.
If you're using a ruby based server such as mongrel. In theory you could use hijack to update the model/routes/variables in the control thread from which, worker threads are spawned from.


Possible to access Sheet/Report Email Object (Smartsheet)

Question: I think I know the answer to this, and will write an enhancement request if I am correct, but ...
Is it possible to access (either just get it or to update it) the Email Object that is a part of a Sheet or Report?
I am referring to the Email Object that is created when Send As Attachment is setup  with Delivery settings that are recurring.
From my investigation of the Python SDK, I have not seen it.
-Craig
Answer: Nope, I don't believe that's a property that's settable or gettable via the API.
An enhancement request would certainly be the way to go here.
Comment: I thought so and have added an enhancement request.


Comparing in an Array: If two highest value exists, then compare the other value

Question: Suppose I have an array like:
array( [0] => array([item]=>apple [buy]=>50 [sell]=>30)
       [1] => array([item]=>lemon [buy]=>50 [sell]=>60)
       [2] => array([item]=>banana [buy]=>40 [sell]=>20)
       [3] => array([item]=>orange [buy]=>20 [sell]=>30)
     )

Currently I am using this script to check which item has the most buyer
function getMax($array, $val)
{
   $max = 0;
   foreach( $array as $k => $v )
   {
      $max = max( array( $max, $v[$val] ) );
   }
   return $max;
}
$highestBuy = getMax($thisArray, 'buy');

foreach($thisArray as $i=>element){
    if($element['buy'] == $highestBuy){
        $thisArray[$i]['highestBuy'] = 'yes';
    } else {
        $thisArray[$i]['highestBuy'] = 'no';
    }
}

In this case, both apple and lemon will have highestBuy a yes value. But now I want to find out which item is the most popular by checking their sell if there are two or more same value of highestBuy. Which is the most simple or fastest way to make the output like:
array([0] => array([item]=>apple [buy]=>50 [sell]=>30 [mostPopular]=>no)
      [1] => array([item]=>lemon [buy]=>50 [sell]=>60 [mostPopular]=>yes)
      [2] => array([item]=>banana [buy]=>40 [sell]=>20 [mostPopular]=>no)
      [3] => array([item]=>orange [buy]=>20 [sell]=>30 [mostPopular]=>no)
     )

Thanks in advance.
EDIT:
What I want to do is:

find out the highest buy
If this value occur only once(which means there are one highest buy in the array) then push the [mostPouplar]=>yes into the array
If not(there are two or more same highest value), then find out the highest sell.

That's mean if the highest value is unique, it will stop doing further action. If not, it will keep going to find secondary highest value in an array. Is it possible to achieve this?
Answer: Sort array with your rules  and take first element
$array = array( '0' => array('item'=>apple, 'buy'=>50 ,'sell'=>30),
       '1' => array('item'=>lemon, 'buy'=>50, 'sell'=>60),
       '2' => array('item'=>banana, 'buy'=>40, 'sell'=>20),
       '3' => array('item'=>orange, 'buy'=>20 ,'sell'=>30)
     );

usort($array,
    function($a, $b) {
       $res = $b['buy'] - $a['buy'];
       if (!$res) $res = $b['sell'] - $a['sell'];
       return $res; });

result:
Array (
[0] => Array ( [item] => lemon [buy] => 50 [sell] => 60 )
[1] => Array ( [item] => apple [buy] => 50 [sell] => 30 )
[2] => Array ( [item] => banana [buy] => 40 [sell] => 20 )
[3] => Array ( [item] => orange [buy] => 20 [sell] => 30 ) )

Answer: I had changed the getMax() to return the index of the most popular item
function getMax($array, $val, $val2)
{
   $max_item = 0;
   foreach( $array as $k => $v )
   {
      if($array[$max_item][$val] <= $v[$val] && $array[$max_item][$val2] <= $v[$val2])
        $max_item = $k;
   }
   return $max_item;
}

$highestBuy = getMax($thisArray, 'buy', 'sell');

foreach($thisArray as $i => $element){
    $thisArray[$i]['mostPopular'] = ($i == $highestBuy) ? 'yes' : 'no';
}

Comment: your code seems get something wrong. It returned `banana` as most popular. Or did I missed something? [Example Here](http://codepad.viper-7.com/AxJuos).


How to correct Apache2 Ubuntu Default page showing in place of Gitlab

Question: I'm trying to get Gitlab running on my Ubuntu server which already has Apache2 running.
I first installed it per https://about.gitlab.com/installation/#ubuntu?version=ce, then I followed these directions https://ryansechrest.com/2015/08/use-apache-instead-of-built-in-nginx-in-gitlab-ce/ but instead of getting the Gitlab setup page, I'm getting Apache2 default page.
The URL looks to be properly redirected. However, when I look into the DocumentRoot directory /opt/gitlab/embedded/service/gitlab-rails/public I don't see an index page. I can access the deploy.html page from the URL. My guess it's not fully installed. But I'm not sure.
Any suggestion?
Answer: Make sure you don't have Apache or Nginx installed on your host when you install Gitlab.
To find out if a package is installed:
dpkg -l | grep -e apache -e nginx
If this is not the reason, can you show the content of your /etc/gitlab/gitlab.rb file?
Can you also check that everything is running with this command:
gitlab-ctl status
If not can you check your gitlab log files for errors in /var/log/gitlab/


Growth Rate Problem?

Question: If I want a number x to grow to the number y over z periods, how do I compute my growth rate per period? So assume x = 10, and y = 80 and z = 3, then I would have a growth rate of 100% every period:

10
20 (1st period)
40 (2nd period)
80 (3rd period)

How to compute that growth rate?
Comment: That's really 3 periods, not 4. Classic [fence post error](http://en.wikipedia.org/wiki/Fence_post_error).
Comment: Ah, you are right.
Answer: It's easier to think of growth factor at first: So your number is multiplied by $g$ at each step. After $z$ steps, it is multiplied by $g^z$, so you end up with an equation $$g^zx=y$$ to be solved for $g$. To do that, take logarithms and end up with a linear equation for $\log g$.
Afterwards, you convert your $g$ to a growth rate $g-1$. Multiply by 100 if you want it as a percentage.
In your example, the equation is $$g^3\cdot10=80,$$ i.e., $g^3=8$. You hardly need logs to do that one, but if you do, logarithms with base 2 can't be beat: $3\log_2 g=\log_28=3$, so $\log_2g=1$, and $g=2^1=2$.
Comment: can you rewrite the formula with `g` on the left side and `x`, `y`, and `z` on the right side? I'm trying to put this formula in GDocs Spreadsheet and need something simple.
Comment: $g=(\frac{y}{x})^{\frac{1}{z}}$
Comment: @Avatar: Indeed. I was just typing it up myself, but you beat me to it by a few seconds. I could well have done the whole thing without the logs, but I was in a hurry when typing my answer and the obvious solution didn't occur to me (duh).
Comment: @HaraldHanche-Olsen: I wrote the formula correct, but the approach to solve is exactly you gave in your answer. Here, taking $z^{th}$ root was simple, but in general first you have to first compute $\log g$ using $\log$ tables and then compute $anti-log$ of $\log g$ to get $g$

Growth Rate Problem?


Name of variable passed as argument

Question: I want to do something along the lines of
<code>static PyObject* printArgs(PyObject* self, PyObject* args) {
    PyObject * oarg1 = NULL;
    PyArg_ParseTuple(args,"O",&oarg1);
    return -- magic --
}
</code>
Such that calling modulename.printArgs(a) returns 'a'.
Is this possible? The best I could think of is looking through locals() for a variable that points to whatever I got in args, but if there's more than one name for the value I could get the wrong name.
Answer: Not really possible. In no way is it guaranteed that the parameter even has a name, it could be an anonymous expression. As such, this is not a limitation of the API, it is a fundamental issue with what you are trying to achieve. Can you give some motivation for the printArgs function?
Comment: I don't mind getting a null pointer if it's anonymous.

I'm adding an interpreter to a c++ application and I want to identify objects by their names in the python interpreter.
Comment: Then you can just assume that every parameter is anonymous (because in a way, it is) and just return a null pointer right away. :-)
Comment: Depending on what objects you want to identify, making them register themselves (through constructors, eg.) sounds like a much better plan.

Name of variable passed as argument


Well-definedness of induced representation

Question: I am sorry if this is too silly but I can't, for the life of me, understand how this works.
This is the definition I am working with.

Definition. Let $G$ be an arbitrary group and $H$ be a subgroup with a representation $V$. Then the induced representation from $H$ to $G$ is the vector space
$$Ind_H^G=\{f:G\rightarrow V∣f(gh^{-1})=hf(g) \;\;\forall g\in G, h\in H\}$$
with action defined by $$gf(x)=f(g^{-1}x).$$

Why should this be a well-defined action? Wouldn't this require
$$f(abx)=(b^{-1}a^{1}f)(x)=f(bax)?$$
Edit: This was a stupid question, I was doing $$f(abx)=(ab)^{-1}f(x)=b^{-1}a^{-1}f(x)=b^{-1}f(ax)=f(bax)$$ and now I realize I was just applying it in the wrong order. Sorry for wasting your time.
Comment: $f(h)$ for $h\in H$ is the given representation?
Comment: $(a(bf))(x) = (bf)(a^{-1}x) = f(b^{-1}a^{-1}x) = f((ab)^{-1}(x) = ((ab)f)(x)$ so $a(bf) = (ab)f$ as required.
Answer: Where did you get $f(abx)=(abf)(x)$ from? That's not how the action is defined. In fact $(abf)(x)=f((ab)^{-1}x)=f(b^{-1}a^{-1}x)$. And that's the reason why you have $g^{-1}$ inside: precisely for associativity to work.
In order to check correctness we need the following two things:

The operator is well defined, meaning it maps $Ind_H^G$ to itself, i.e. $gf\in Ind_H^G$ for $g\in G$ in $f\in Ind_H^G$. This holds, because for any $x\in G$ and $h\in H$ we have
$$(gf)(xh^{-1})=f(g^{-1}xh^{-1})=hf(g^{-1}x)=h\big((gf)(x)\big)$$
Note the subtleties here: $gf$ is the action of $g$ on $f$ (the last one defined). Inside $f$ we have group mutliplication, while $hf(x)$ is actually the action of $h$ (as an element of $H$) on $f(x)$ (as an element of $V$). In particular $hf(x)$ is not the same as $(hf)(x)$.
The operator is a group action. It is trivial that for the neutral element $e\in G$ we have $ef=f$. While the associativity goes as follows:
$$(abf)(x)=f\big((ab)^{-1}x\big)=f(b^{-1}a^{-1}x)=(bf)(a^{-1}x)=\big(a(bf)\big)(x)$$


Oracle SQL - string not equal to

Question: I have a trigger in Oracle SQL.
CREATE OR REPLACE TRIGGER test
BEFORE INSERT ON SomeTable
FOR EACH ROW
    DECLARE str1 VARCHAR(30);
            str2 VARCHAR(30);
    BEGIN
        -- some code
        IF ( str1 <> str 2 ) THEN
            DBMS_OUTPUT.PUT_LINE( ' if ' );
        ELSE
            DBMS_OUTPUT.PUT_LINE( ' else ' );
        END IF;
    END;

Now, this always goes to the else statement, even when the strings are definitely not equal. I tried to use != instead of <> with the same result. However, it works, in reverse, if I just use
IF ( str1 = str2 ) THEN ... ELSE ... END If;

So what is the right way to test for two strings not being equal to each other (in Oracle)?
Comment: Is the space in `str 2` just a typo?
Comment: Is it possible that one of the "str" values is NULL at the time of comparison?
Answer: Can you show us the actual values being used?
It is possible that the reason for the above behavior is becuase one of the values is null?
If it is possible for str1 and str2 to have null values, your if's should be like..
IF (str1 is null and str2 is null) then
   <statments depending on whether you want to treat nulls as equal>
else if (
   (str1 is null and str2 is not null) or
   (str2 is null and str1 is not null) or
   (str1 <> str2)) then
  <statements when str1 and str2 are not equal>
else
  <statements when str1 and str2 are equal?
end if;

Comment: Yes, I had thought setting the string to '' (empty string) would get rid of the null, but apparently '' is the same as null. Thanks.
Comment: (1) You have imbalanced parentheses in your *else if* branch; (2) you duplicate a `str1`/`str2` criterion in the same.
Comment: @pilcrow: I'm pretty sure both of those were just typos so I fixed them. Good call pointing them out though.
Comment: FWIW, this construct might be more concisely rendered as checking for nullity, then equality, else inequality:  `IF (s1 IS NULL AND s2 IS NULL) THEN ... ELSE IF (s1 = s2) THEN ... ELSE ... END IF`  Fewer conditionals to typo. :)
Comment: @RajeshChamarthi Sorry to nitpick, but for those Googling this and finding it, I think ``, though all that would just get replaced by the OP's logic, anyway :)
Answer: This should determine if one character string exists inside another character string:
IF instr(str1,str2)<>0 THEN

Answer: Sometimes it is easier to negate the equality condition. E.g. if not equal(val1, val2);
function equals(
  val1 varchar2,
  val2 varchar2
) return boolean is
begin
  if val1 is null then
    return val2 is null;
  elsif val2 is null then
    return false;
  end if;

  return val1 = val2;
end;

And the in your code you would have:
BEGIN
    -- some code
    IF NOT equals(str1, str2) THEN
        DBMS_OUTPUT.PUT_LINE( ' if ' );
    ELSE
        DBMS_OUTPUT.PUT_LINE( ' else ' );
    END IF;
END;

Oracle SQL - string not equal to


What's the best gem/plugin to develop a Facebook Canvas/iFrame App (Rails 2.3.8, Ruby 1.8.7)?

Question: we're developing a Facebook Canvas App in Rails 2.3.8, we tried a couple of gems out there and for now we're using mini_fb but it's not really well documented and we're having some issue with the authentication/authorization process, and more importantly we couldn't find a tutorial on how integrate cucumber.
I know there're plenty of options out there: facebooker (too old?), oauth2 gem, omniauth, mogli and so on.
What we ideally need is:

Support for Canvas/iFrame app (not just Facebook connect)
Support for the new OAuth 2.0 for Canvas (beta) facebook docs & for the old REST API as well
Documentation (very hard to find, also cause Facebook API are in first place not so extensively documentend, especially for Ruby)
Support/Documentation/Tutorials for Cucumber integration
Cover basic API features like Wall posting, Friends handling ...

What's the best option in your opinion/past experience?
Thank you guys,
Leo
Answer: Take a look at Koala...
https://github.com/arsduo/koala/
Very well documented and maintained.
Works with Ruby 1.8/1.9 & Rails 2/3


Will supported 2x8s or unsupported 2x12s added to existing joists result in higher rigidity?

Question: Background: I have a kitchen supported with 2x8s 16" o/c over a 13' 3" span. I want to install a 12x24 tile floor, so that much deflection is just not going to work.
Question: I have 2 options I am considering. The first is to sister the 2x8s with another 2x8 so that both would be supported at both ends. The second is to sister the 2x8s with 2x12s but the 2x12 would not be supported on either end as they can't fit between the beam and the floor.
Which one will add more rigidity to the floor?
Side question: Which is more rigid one 2x12 or two 2x8s sistered?
Comment: Is there a full basement under this kitchen? What about an engineered beam perpendicular at mid span? Maybe several 2 x 12s made into a beam. How much intrusion into the space below is acceptable?
Comment: I have a 13'3 x 40' room under that side of the house. it would lol rather weird and ugly to put a beam and a column right there is the middle of the room.
Comment: Does the room under the kitchen have a finished ceiling that you are going to take down for access to sister in the extra 2 x joists? What is the height of this room? What is the current flooring in the kitchen?
Answer: Side answer - beam stiffness goes as depth cubed, width directly.
12 cubed is 1726, 8 cubed is 512
So 2x12 is 1726 .vs. 2x(512) for 2 2x8. roughly 1.7 times stiffer, that is.
You can "haunch" the ends of the 2x12 to 8 inches - it should be done as a taper, not as a notch - 45 degrees, not 90 degrees - it's actually stronger that way, which is a bit counter-intuitive).
Joist hangers may offer other options to retain full depth to the ends.
Comment: All possibilities, but all more complicated than the original plan.
Comment: Could an additional 3.5" be added to the bottoms of the 2 x 8 joists? Perhaps  2 x 4s with slow setting adhesive braced in the center or in 2 or 3 places then screwed at 6" intervals to the existing 2 x 8 joists. Another way to supply extra tension on the bottom, could a steel strap be nailed or screwed to the bottoms of the 2 x 8 joists which would be temporarily braced while the strap is nailed at 8" intervals. (This is how the wooden treads of ladders used to be braced from below with metal tension rods.)
Comment: How is the steel strapping more complicated than sistering on more joists? You may know that this would not work, but, if it would, it seems it would be simpler. Do the original joists have any plumbing or wiring in them? What about bolting angle or square cross section steel on one or both sides of the bottom edges of the original joists. The original joists could be temporarily braced from below at mid-span all the way across while the steel was screwed in or bolted through. This would have the advantage of not changing the ceiling height in the room under the kitchen.
Comment: Strapping will not work without vertical tensioners of some sort below the center of each joist, creating a sort of truss. This makes it complicated and time-consuming.
Comment: Ecnerwal: So would this be appropriate? (I modeled it in SolidWorks) a full 45 instead of a notch or should I use a notch and try my best to beat the rest of the 2x12 in between the 2x8 plate and the floor upstairs?
https://ibb.co/gH4BOv
Answer: Your second option would result in a stiffer floor. It's not necessary that the ends of the sistered lumber rest on the foundation. The movement that you feel is the result of deflection (bending, and not compression of the joist at the supported ends), as you've correctly described.
The critical concern is that you have solid connections between the old and new lumber. Three 16d nails or 2-1/2" construction screws every 16" and distributed vertically should do.
Comment: Construction adhesive is helpful as well.
Comment: Glue, then screw before it dries, using screws with 1-1/2" of non-thread, that way all the screw is in the other piece and it clamps them together instead of holding them at gap.   Glue is worthless if a gap remains.  And epoxy (eg West System with adhesive filler) is the best.
Comment: I considered recommending construction adhesive, but it doesn't seem necessary here. The fastener pattern I suggested will lock things down solid, and noise is unlikely. Couldn't hurt, I suppose.


Custom Minecraft 1.8 spawners

Question: I am working on a minecraft 1.8 server and am trying to make a mob spawner that spawns items.  This example:How can I make a spawner that summons Items? works on new versions of minecraft but not on 1.8.  It seems that any mob spawners placed down by command blocks don't work.  The following command:
/setblock ~ ~1 ~ mob_spawner 0 replace {SpawnData:{id:zombie},Delay:299}

Creates an empty mob spawner that does not spawn anything.  I am using minecraft forge with worldedit but no other mods.  How can I fix this?
Comment: 1.8 was years ago.
Comment: But it does seem like you put effort into this so I upvoted it :)
Comment: @BronsonHunter lots of people still use 1.8, its probably the second most used version.
Answer: The below code is generated from mcstacker 1.8, 1.9, and 1.10 version.  The following code should place a zombie spawner.
/setblock ~ ~1 ~ minecraft:mob_spawner 0 replace {EntityId:Zombie,Delay:299}

The next command should place a spawner that spawns diamonds.
/setblock ~ ~1 ~ minecraft:mob_spawner 0 replace {EntityId:Item,SpawnData:{Item:{id:diamond,Count:1}},Delay:299}

Try that.  The command isn't tested, but mcstacker usually works for me.  It may not for you because you are on a server.  You can change it with mcstacker.  I hope this helps.
Answer: I don't believe that you can get custom mob spawners in Java Edition and that the only spawners you can get are Pig Spawners. They way you can obtain pig spawners is using the /give command. Example: /give @p 52 1
Comment: I don't think that is true since I have seen a video where there is a spawner spawning fireworks and other things.  But it seems like I might have to use skript.
Comment: If your trying to get custom spawners on Vanilla Minecraft, that is not possible. I believe that you would have to use plugins/mods. Do you know if in the video that they used commands?
Comment: @darthvader1925 it is possible.  I only know how to do it in 1.13 and up.  Maybe be the same process.

Custom Minecraft 1.8 spawners


Expose private internal class size

Question: I need to expose a compile time constant with the size of internal class. To do so I tried next code:
#include <cassert>

struct A
{
    //consider Private class as private for this example, just to be able to put the assert like this in main
    class Private{};
    enum { PrivateSize = sizeof(Private) };
};

int main()
{
    //here I have warning on some compilers, signed/unsigned comparison
    assert(A::PrivateSize == sizeof(A::Private));
}

My problem is that PrivateSize is signed on some compiler and unsigned on others and I get warnings about this when comparing it with signed types. As far as I know enum's underlying type is implementation defined and can't be forced to be signed or unsigned.
Do you know a way to expose sizeof(A::Private) outside A as compile time constant, but keeping Private class... private? Please note I can't use constexpr as the code will be used on some old compilers.
Comment: I assume you can not change A
Comment: @DieterLücking I can change A, but I have to keep internal class private
Comment: You may use `static const unsigned PrivateSize` instead of enum to avoid warning.
Comment: A friend function holding the assert will do it
Answer: Following works:
struct A
{
    friend int main(int argc, char *argv[]); // For test purpose
private:
    class Private{};
public:
    static const unsigned int PrivateSize = sizeof (Private);
};

int main(int argc, char *argv[])
{
    assert(A::PrivateSize == sizeof(A::Private));
    return 0;
}

Expose private internal class size


DualBoot with two disks on BIOS level

Question: I have two disks. W10 is installed on one disk. I want to install Ubuntu on the other disk. I hate fiddling around with MBR and fixing Grub when anything goes wrong. Therefore, I thought it would be a good idea to install Ubuntu on the other disk. And do the boot decision on bios-level. Is this possible and maybe even preferred?
Answer: It is very possible, and a very good idea, because if anything goes very wrong, you can reinstall it easily. The fact that each OS has its own HDD is good, too, since it gives you more control over each of them.

DualBoot with two disks on BIOS level


Will ARC tell me when I must use __block?

Question: AFAIK, __block is used when you're changing, inside the block, the address that a variable (declared outside the block) points to.
But, what if I'm changing the value that the variable points to but the pointer stays the same? E.g., what if I have NSMutableArray *array and am just doing [array addObject:object] inside the block? In this case, I'm not changing the pointer array, but I'm changing the value it points to. So, must I still use __block in declaring NSMutableArray *array?
Answer: You only need __block if you are changing the value of the variable.
I.e. if you have:
NSArray* foo;

You only need __block if you change the value of foo.  Now, keep in mind that foo is nothing more than "a pointer to a thing that is typed NSArray".   I.e.  foo is effectively a 64 bit or 32 bit integer, depending on platform.  If you change that integer, you need __block.  If you don't, you don't need __block.
So, no, you don't need __block to call addObject: on the array since you aren't actually changing the value of foo.
If you were to do something like foo = (expression);, then you'd need __block.
(note that this is one of the reasons why concurrent programming under OO is so damned hard... it is exceptionally hard to define the "domain of variance" for any given execution path)
Comment: `__block` indicates that the variable can change.  Whether or not the variable is `__block` or a const-copy (as is the default), calling a method on the object will not be impacted.
Comment: If you are using `self.foo = ...;` then, no, no `__block` is needed because that is a method call.  Nor would it be needed to modify the instance variable directly (since the reference to the ivar is through self).
Comment: What about compiler optimization? `__block` might hint it that an object never changes, and if `NSArray` was inlined, subsequent calls to capacity might have been wrong.
Comment: But what happens if the variable (NSArray *) is a self property ? Does the __block need to be added ?


Row data for specific column headers based on row ID

Question: I have a worksheet with a few hundred rows of employee data.  At its most basic level it lists EmployeeID's, Name and lists the skills that they have.
What I have done is on another worksheet (in my Employee Lookup workbook) I have used a combination of the index and match functions to look up an EmployeeID that I enter and return the skill level from the employee skills data sheet.
What I want to do is try to simplify how the data is obtained (I have limited vba knowledge but some excel formula knowledge, hence nesting index match). The Employee Skills sheet has Column A with EmployeeIDs and Row A with skill names (and prior headers).
I can set up the Index/Match for each row but then I need the column numbers for each skill and look up that EmployeeID and return the skills (even if they are blank).
I wouldn't really bother with trying to figure out how to begin to code this but I would think there would be an easier way to do this than making an Index/Match formula for each referenced skill (with there being anywhere from ~15-50 skills per department when I assist with 4 departments).
The Index/Match functions would take a lot of time and already has for one group. I don't think what I am wanting can be done in Excel but unfortunately that is the data resource I am left with.
Example of spreadsheet layout:
Comment: Welcome to Stack Overflow!  I'm having bit of trouble following your explanation.   The top of that image is what you have, and the bottom is what you want?
Comment: ...if so, you shouldn't need need VBA.  I believe *one* formula will do the trick; the key is to using the "correct mix" of dynamic & absolute references.  In fact, if I understand what you're trying to do, VBA would overcomplicate.
Comment: @ashleedawg what you are stating is correct, The top is the data sheet and the bottom is my lookup sheet (in another workbook).

I would want the skills of Bob (listed top to bottom, as on the look up sheet) if I enter his employee ID in the lookup cell.
Comment: I have the index and nested match functions with appropriate references but maybe I am doing the dynamic and absolute bit wrong as I have to edit the references manually myself :( quite tedious honestly.
Comment: ...so for example, you would enter an employee number in `B9`, and you would want `B12 to B15` to auto-populate?  Or would the list of skills `A12 to A15` also need to change depending on the employee?
Comment: ...so for example, you would enter an employee number in `B9`, and you would want `B12 to B15` to auto-populate?  Or would the list of skills `A12 to A15` also need to change depending on the employee??  Also, with correctly written formulas (or VBA), you should only ever have to type something once. :-)
Comment: @ashleedawg the skills for the department are all the same so they could remain listed in the column even if that employee doesn't have the skill.
Comment: I'll put together an example in a couple mins...
Comment: @ashleedawg I had the formulas once and the references got deleted and the columns for the skills were referenced and I had to look up each individual lot so it was tedious and I wanted to see how to simplify it. That's what led me here :)
Comment: *individual skill
Comment: VBA definitely has many powerful applications (and you *should* learn it!) but in this case would be more tedious, especially if you're new to VBA.  Gimme a couple mins...
Comment: I appreciate the help a lot, I figured the absolute references would be the way to go but I was unsure how that would affect the columns (but I guess it doesn't) because it's just referencing the cells in the header row.
Comment: np, gets easier with practice
Answer: Short Answer:
(A detailed & color-coded screenshot breaking down the formula is further down, or full-screen .PNG here.)
Here's a solution using sample data similar to yours:

The "short version" of the formula in D16 is:
=INDEX($C$4:$I$8,MATCH($D$11,$A$4:$A$8,0),MATCH(C16,$C$3:$I$3,0))

The actual formula I used looks scarier but it's just the above formula twice (copy/pasted) along with an IF so that it will bring over a blank cell if the "source cell" is blank (like Jane's Partying score)...
=IF(INDEX($C$4:$I$8,MATCH($D$11,$A$4:$A$8,0),MATCH(C16,$C$3:$I$3,0))=0,"",INDEX($C$4:$I$8,MATCH($D$11,$A$4:$A$8,0),MATCH(C16,$C$3:$I$3,0)))

Once that formula is in D16, I just "filled down" (or copy/paste) to the other skills.

Note that all cell references in the above formula are "Absolute" except for C16.

We want all cell ranges to stay the same even if we copy/paste (or fill) the cell to another cell... except for C16: that's what our lookups are based on so that once does need to change when we copy the cell elsewhere.

"Two-dimensional Index/Match" Example:

Download .xslx sample file:
To get a better idea of how it works, you can download the Excel file from my screenshot here to experiment, modify, and adapt as desired.
It's a direct-download link to a Macro-free .XSLX, hosted by Jumpshare, which allows you to view online but it doesn't like complex formulae, and the columnar formatting is messed up on some browsers (however you can also download from the online viewer with the DOWNLOAD button at the ↗top-right↗ of the viewer.

INDEX & MATCH Function Documentation & More Examples:

Microsoft (Office.com): MATCH and INDEX functions (with videos)
Microsoft: Switch between relative, absolute, and mixed references
ExcelJet: Two-way lookup with INDEX and MATCH
MSDN: Performing Two-Dimensional Lookups
mbaExcel: Tutorial: How to Decide Which Excel Lookup Formula to Use
Stack Overflow: Index/Match with VBA
ExcelTip: How To Use Index/Match for 2 Criteria with VBA

A Crash-Course on Absolute vs. Relative Cell References
Cell Reference — A cell reference refers to a cell or a range of cells on a worksheet and can be used in a formula so that Microsoft Office Excel can find the values or data that you want that formula to calculate.  (Source)

By default, a cell reference is relative. For example, when you refer to cell A2 from cell C2, you are actually referring to a cell that is two columns to the left (C minus A), and in the same row (2). A formula that contains a relative cell reference changes as you copy it from one cell to another.
As an example, if you copy the formula =A2+B2 from cell C2 to D2, the formula in D2 adjusts to the right by one column and becomes =B2+C2. If you want to maintain the original cell reference in this example when you copy it, you make the cell reference absolute by preceding the columns (A and B) and row (2) with a dollar sign ($). Then, when you copy the formula =$A$2+$B$2 from C2 to D2, the formula stays exactly the same.
In less frequent cases, you may want to make a cell reference "mixed" by preceding either the column or the row value with a dollar sign to "lock" either the column or the row (for example, $A2 or B$3).

(Source)

>

"Regional Afterthought":
While answering a question about Excel's regional differences, I wondered if $ is the international symbol for Absolute References, or whether the symbol varied "across the pond".

("Will Brexit change "U.K. Absolutes" from =€A€1 to =£A£1?!")

A quick search revealed that the $ is indeed the "worldwide" symbol used for Excel Absolutes — however some users (having never typed a $ before) had trouble locating it.  Here's a link describing How to type the $ Dollar Sign on Non-American Keyboards...

Good luck with your project! Let me know if you have any questions...
Comment: @ashleedawg I think part of this is with index match I've only used index to reference one column, where you have $C$4:$I$4 I only had $C:$C (I believe, the remaining formula are on my work computer). So I'll have to dissect that more tomorrow so I know why that array is a better option.
Comment: @jnjustice — Download the `.XLSX` example (direct link **[here](https://storage.jumpshare.com/download/FKdEI1MHFFMcOmklF1ZICsHOZNjatt-lUCuq2WvF1gve3hucf5aC-Ez7HS_xUOtUFsh649UsyeAU1tdvgLCAqg)**) and play with the formulas, and they should make more sense.  (You were halfway there on your own!) ...Take note of which sections of each `Index`/`Match` formula are *relative* and which are ***$absolute$***  Let me know if you have any questions.
Comment: @ashleedawg so I updated the excel sheet with the formula and I get an **#N/A** error.

The formula as the data is updated is:

`=IF(INDEX($S$2:$BH$1000,MATCH($A$7,$A$2:$A$1000,0),MATCH(A16,$S$1:$BH$1,0))=0,"",INDEX($S$2:$BH$1000,MATCH($A$7,$A$2:$A$1000,0),MATCH(A16,$S$1:$BH$1,0)))`

I have updated your numbers from the formula:

`Before:

$C$4:$I$8
$D$11
$A$4:$A$8
C16
$C$3:$I$3

After:
$S$2:$BH$1000
$A$7
$A$2:$A$1000
A16
$S$1:$BH$1`
Comment: When troubleshooting a formula, break it down into smaller formulas to see what result you get from each part. Your formula is `=MATCH($A$7,$A$2:$A$1000,0)` (looking in `A2:A1000` to find an exact match for the value in `A7`) **and** `=MATCH(A16,$S$1:$BH$1,0)` (looking in `S1:BH1` to find an exact maych for the value in `A16`.)  Is that what you intended?  What do you get when you enter one of those two formulas into a cell by itself?  (**Notice** that I left off the `IF` formula for now, for troubleshooting.)
Comment: ...and then if you still can't find the mistake, tell me what value is in cells 'A7` and `A16`, and which "position" in each range you find those values.
Comment: @jnjustice — Did you get it figured out?
Comment: I did not see your reply until today and I will check again at work tomorrow when have access to the data. @ashleedawg
Comment: @ashleedawg there was no error with the formula, I had the wrong reference conlumn for the employee ID to look up. The formula itself will say me a lot of time because I was not looking things up based on the skill name in the look up sheet but now if I update those it will save a lot of time (where as before if the columns changed I would have to adjust manually)


How to consume Active Directory data from Power BI?

Question: I am using the Active Directory connector:
I am consuming 2 columns:

But after hours it keeps loading and never finishes:

Any ideas on how to consume the data properly?
Answer: you can try query maybe something like...
First thing we'll do is create our linked server, Active Directory Service Interface also known as ASDI, to Active Directory using the code below:
Make sure you change the @rmtuser and @rmtpassword variables to a login and password that has access to your Active Directory.
USE [master]
GO
EXEC master.dbo.sp_addlinkedserver @server = N'ADSI', @srvproduct=N'Active Directory Service Interfaces', @provider=N'ADSDSOObject', @datasrc=N'adsdatasource'
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'ADSI',@useself=N'False',@locallogin=NULL,@rmtuser=N'DOMAIN\USER',@rmtpassword='*********'
GO
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'collation compatible',  @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'data access', @optvalue=N'true'
GO
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'dist', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'pub', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'rpc', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'rpc out', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'sub', @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'connect timeout', @optvalue=N'0'
GO
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'collation name', @optvalue=null
GO
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'lazy schema validation',  @optvalue=N'false'
GO
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'query timeout', @optvalue=N'0'
GO
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'use remote collation',  @optvalue=N'true'
GO
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'remote proc transaction promotion', @optvalue=N'true'
GO

Once the linked server is created we can now setup our query to return the information we need.
SELECT * FROM OpenQuery
  (
  ADSI,
  'SELECT streetaddress, pager, company, title, displayName, telephoneNumber, sAMAccountName,
  mail, mobile, facsimileTelephoneNumber, department, physicalDeliveryOfficeName, givenname
  FROM  ''LDAP://DOMAIN.com/OU=Players,DC=DOMAIN,DC=com''
  WHERE objectClass =  ''User''
  ') AS tblADSI
ORDER BY displayname

Comment: Thanks. I am a bit lost.  Which connector in Power BI can I use to use this code?
Comment: @Chicago1988 [check this](https://learn.microsoft.com/en-us/sql/t-sql/functions/openquery-transact-sql?redirectedfrom=MSDN&view=sql-server-ver16) also you can find more info in the internet...
Comment: I dont see how this answer helps. I have tried it from SSMS (not power bi) and I have no linked server named 'ADSI'
Comment: @Chicago1988 revised...
Comment: [Querying Active Directory Data from SQL Server](https://www.mssqltips.com/sqlservertip/2580/querying-active-directory-data-from-sql-server/)


Workstation sink

Question: Most of the new workstation sinks don't have a knockout for air gap and don't accommodate a disposal… what's the best solution for dishwasher venting?
Comment: I believe this question could be improved with evidence that "most" new workstation sinks are not disposal/air-gap compatible, or information that makes available disposal/air-gap compatible workstation sinks not suitable for your situation.
Answer: Some "workstation sinks" on sale now do have disposal-compatible sink holes and an extra top hole for an air gap. I did a web-search on "workstation sink" and found plenty of kitchen sinks at Home Depot. One is this (no endorsement implied, only to show they exist on sale now):
https://www.homedepot.com/p/Glacier-Bay-AIO-33-in-Drop-in-Undermount-Single-Bowl-18-Gauge-Stainless-Steel-Workstation-Kitchen-Sink-with-Faucet-Cutting-Board-4332F/318258381#overlay

This is from the above sink's instruction manual showing the typical 4" to ~2" drain adapter that can be taken out and replaced with the disposal adapter:
Answer: a knockout for air gap
Many dishwashers can use a high hose loop instead of a traditional air gap. That is easier to install and avoids the ugly air gap cover. However, if local code does not allow for a high hose loop then you can drill a hole to install the air gap.
In the opposite scenario, if you have an air gap for a dishwasher and get a new dishwasher that can use a high hose loop instead, you can install a soap dispenser using the old air gap hole.

Workstation sink


Sending data to service array brute force

Question: I can't find an answer to my question, can you help me friends
what kind of requests, I get: facebook, linkedin, reddit
I don't want to write a lot of code, so I want to ask you how I can make
How do I create a check loop, and send the data (the data is the same for all services)
to go through and find the right service. send the right service and data. Again, the data for all services is the same
as you can see, I write a lot of conditional statements, and I don't like it, I want to put
I use ejs, express
I just want to get rid of a lot of code..
everything into one loop and work
    var servies = ["facebook", "linkedin", "reddit"]

    servies.forEach(service => {
        console.log(service);
    });

    if (service == "linkedin") {
        res.render('linkedin', {
            id: xssFilters(id),
            name: xssFilters(name),
            image: xssFilters(photo),
            firstName: xssFilters(firstName),
        })
    }
    if (service == "reddit") {
        res.render('reddit', {
            id: xssFilters(id),
            name: xssFilters(name),
            image: xssFilters(photo),
            firstName: xssFilters(firstName),
        })
    }

    if (service == "facebook") {
        res.render('facebook', {
            id: xssFilters(id),
            name: xssFilters(name),
            image: xssFilters(photo),
            firstName: xssFilters(firstName),
        })
    }

Answer: You can try
 var servies = ["facebook", "linkedin", "reddit"]

    servies.forEach(service => {
        console.log(service);

        res.render(service, {
            id: xssFilters(id),
            name: xssFilters(name),
            image: xssFilters(photo),
            firstName: xssFilters(firstName),
        })

    });

since in your example code, you don't do anything different between the different services, but only replace the string name of the service, and you already have a loop for that.
Comment: Yes, but it doesn't work.
Comment: can you elaborate? does the `res.render` not get called, is the behavior wrong, or is the data sent wrong?
Comment: ahahaha, I'm working)) I posted a ready answer to my own question, Sorry.Thanks XDD


Accessing the Properties of a class dynamically

Question: Hi I have to different classes with Same properties and I want to access the peoperties of my classes Dynamically.
public Class1
{
public const prop1="Some";
}
public Class2
{
 public const prop1="Some";
}

And in my code I am getting my class name like this
string classname="Session["myclass"].ToString();";//Say I have Class1 now.

And I want to get the prop1 value .
Something like
 string mypropvalue=classname+".prop1";//my expected result is Some

///
     Type typ=Type.GetType(classname);
Please help me in getting this
Comment: you can use reflection to dynamically get property values from class name.
Comment: I am trying for the same but unable to get it right.
Comment: show code how you use reflection.
Comment: @slavoo actually my class is a static class...and I want to retrieve its property value dynamically
Answer: Reflection
var nameOfProperty = "prop1";
var propertyInfo = Class1Object.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(myObject, null);

for static:
var nameOfProperty = "prop1";
var propertyInfo = typeof(Class1).GetProperty("prop1", BindingFlags.Static);
var value = propertyInfo.GetValue(myObject, null);

Class reference from string
EDIT (I made example):
class Program
    {
        static void Main(string[] args)
        {

            var list = Assembly.Load("ConsoleApplication4").GetTypes().ToList();
            Type ty = Type.GetType(list.FirstOrDefault(t => t.Name == "Foo").ToString());
            //This works too: Type ty = Type.GetType("ConsoleApplication4.Foo");
            var prop1
                 = ty.GetProperty("Temp", BindingFlags.Static | BindingFlags.Public);

            Console.WriteLine(prop1.GetValue(ty.Name, null));
            Console.ReadLine();
        }

    }

    public static class Foo
    {
        private static string a = "hello world";
        public static string Temp
        {
            get
            {
                return a;
            }
        }
    }

Msdn
Comment: To access field "a" use: `var prop1 = ty.GetField("a", BindingFlags.Static | BindingFlags.Public);
Console.WriteLine(prop1.GetValue(ty.Name));` but need set field "a" as public
Comment: My classname is retrieved from session .
Comment: Thnks .It Worked For me..And Cant we access the "a" directly?
Answer: you can use following function to get a property value fron an object dynamically:
just pass object to scan & property name
public static object GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}

Comment: How to get the value of a static class Property
Comment: refer http://stackoverflow.com/questions/1487867/c-sharp-get-values-of-static-properties-from-static-class


How to find in a collection?

Question: i have the following variable and collection
def currentProduct = "ITEM1"
def currentPresentation = "Crema"
def curentMeasure = "1ml"

def items = [[product:"ITEM1", presentation:"Crema", measure:"1ml", quantity:5, total:77.50], [product:"ITEM1", presentation:"Spray", measure:"Habracadabra", quantity:9, total:158.40]]

I need to get the quantity value in a map that its product, its presentation and its measure are equal to variable values, hopefully you can help me
Thanks for your time
Comment: Did you try anything yet?
Comment: i tried this
list.each { item ->
    if (item.product == "ITEM1" && item.presentation == "Crema" && item.measure == "1ml") {
        println item.quantity
    }
}
and i get the value but i want to find the recomended way to handle this scenarios
Answer: Here You go:
items.find { it.product == currentProduct && it.presentation == currentPresentation && it.measure == curentMeasure}?.quantity

Answer: Another simpler approach will be as below:
def currentProductDetails = [
    product:"ITEM1", presentation:"Crema", measure:"1ml"
]

items.find { !( currentProductDetails - it ) }?.quantity

// in case of multiple products
items.findAll { !( currentProductDetails - it ) }*.quantity

You can tailor currentProductDetails with whichever key value pair you have in hand for the current product instead of maintaining each variable separately.
Above logic is inspired from this question which is explained in details in this blog.
Comment: Seems complicated at first touch. But nice ;]
Comment: @Opal Yes it looks like, but as it is mentioned in the blog it was very entertaining to drill down to least amount of code which was the objective and the power of higher order functions in Groovy. :)
Comment: Yeah. Definitely yes :)
Answer: Use grep :
items.grep{it.product==currentProduct && it.presentation==currentPresentation && it.measure==curentMeasure}.collect{it.quantity}

FIDDLE
Answer: Dispite good @Opal's answer i will list here some additional possibilities:

Passing partial item map
If your item is [product:"ITEM1", presentation:"Crema", measure:"1ml", quantity:5, total:77.50]
and you want to search by some specified values of item, you can just pass submap of the item.
e.g.
def item = [product:currentProduct, presentation:currentPresentation, measure:curentMeasure]
def firstQuantity = items.find {it.subMap(item.keySet())==item}.quantity

That way allows you to be independent of item's keys.
Searching all quantities and suming them
Maybe in some cases you would like to have some of found quantities. You need then to use findAll() method.
def all = items.findAll { it.product == currentProduct && it.presentation == currentPresentation && it.measure == curentMeasure}.quantity.sum()

Comment: nice solution subMap in new to me

How to find in a collection?


"In file included from error" with vector

Question: I am trying to make an aggregate class, Pile, that takes a vector of Cards as its data.
I have been trying to figure out what the deal is with this error for the past 3 hours and am stumped. Here is the error:
In file included from /usr/include/c++/5/vector:62:0,
                 from Pile.h:16,
                 from Pile.cpp:15:
/usr/include/c++/5/bits/stl_construct.h: In instantiation of 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = Card; _Args = {}]':
/usr/include/c++/5/bits/stl_uninitialized.h:519:18:   required from 'static _ForwardIterator std::__uninitialized_default_n_1<_TrivialValueType>::__uninit_default_n(_ForwardIterator, _Size) [with _ForwardIterator = Card*; _Size = long unsigned int; bool _TrivialValueType = false]'
/usr/include/c++/5/bits/stl_uninitialized.h:575:20:   required from '_ForwardIterator std::__uninitialized_default_n(_ForwardIterator, _Size) [with _ForwardIterator = Card*; _Size = long unsigned int]'
/usr/include/c++/5/bits/stl_uninitialized.h:637:44:   required from '_ForwardIterator std::__uninitialized_default_n_a(_ForwardIterator, _Size, std::allocator<_Tp>&) [with _ForwardIterator = Card*; _Size = long unsigned int; _Tp = Card]'
/usr/include/c++/5/bits/stl_vector.h:1311:36:   required from 'void std::vector<_Tp, _Alloc>::_M_default_initialize(std::vector<_Tp, _Alloc>::size_type) [with _Tp = Card; _Alloc = std::allocator<Card>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]'
/usr/include/c++/5/bits/stl_vector.h:279:30:   required from 'std::vector<_Tp, _Alloc>::vector(std::vector<_Tp, _Alloc>::size_type, const allocator_type&) [with _Tp = Card; _Alloc = std::allocator<Card>; std::vector<_Tp, _Alloc>::size_type = long unsigned int; std::vector<_Tp, _Alloc>::allocator_type = std::allocator<Card>]'
Pile.cpp:27:23:   required from here
/usr/include/c++/5/bits/stl_construct.h:75:7: error: no matching function for call to 'Card::Card()'
     { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
       ^
In file included from Pile.h:17:0,
                 from Pile.cpp:15:
card.h:30:5: note: candidate: Card::Card(const Card&)
     Card(const Card& old);     //copy constructor
     ^
card.h:30:5: note:   candidate expects 1 argument, 0 provided
card.h:29:5: note: candidate: Card::Card(int, char)
     Card(int r, char s); //parameterized constructor
     ^
card.h:29:5: note:   candidate expects 2 arguments, 0 provided

Call Stack
#   Function    File:Line
Local Variables
Variable    Value
Display Expressions
Expression  Value
Breakpoints and Watchpoints
    #   Description

I feel like I am so close I had a bunch of other errors I was able to solve but I can't get passed this "In file included from" error as I can't make out what it even means. I have tested my card class alone and it is functioning as intended.
Here is my Pile.h code:
#ifndef PILE_H
#define PILE_H
#include <vector>
#include "card.h"

using namespace std;

class Pile
{
protected:
    vector<Card> p;

public:

    Pile();
    Pile(vector<Card> p);

    Card dealCard();
    int getCount();
    void shuffle();
    void clear();
    Pile operator + (const Card& c) const;
    Pile operator + (Pile& b);
    friend ostream& operator << (ostream& out, const Pile& p);

};

and here is my Pile.cpp code:
#include "Pile.h"
#include <iomanip>
#include <algorithm>  //shuffle
#include <time.h>
#include <sstream>
#include <stdexcept>
#include <cstdlib>

using namespace std;

Pile::Pile()
{
    p = vector<Card>(0);
}

Pile::Pile(vector<Card> p)
{
    this->p = p;
}

//draws card from the top of the pile and removes it from the vector
Card Pile:: dealCard()
{
    if(p.size() > 0)
    {
        Card tempCard = p.front();
        p.erase(p.begin());

        return tempCard;
    }
    else
        throw std::length_error("Pile is empty");

}

int Pile:: getCount()
{
    return p.size();
}

void Pile:: shuffle()
{
    srand(unsigned(time(NULL)));
    random_shuffle(p.begin(), p.end());
}

void Pile:: clear()
{
    p.clear();
}

Pile Pile:: operator + (const Card& c) const
{
    Pile tempPile(p);       //make a copy of the pile to be returned
    tempPile.p.push_back(c);  //push the new card onto the end of the pile
    return tempPile;        //return the new pile
}

Pile Pile:: operator + (Pile& b)
{
    Pile tempPile(p);

    while(b.p.size() > 0)
    {
        tempPile.p.push_back(b.p.front());
        b.p.erase(b.p.begin());
    }
    return tempPile;
}

ostream& operator << (ostream& out, const Pile& p)
{
    int count = 0;
    int index = 0;

    while(p.p.size() > 0)
    {
        out << p.p[index] << setw(2);
        count++;
        index++;

        if(count == 10)
        {
            out << endl;
            count = 0;
        }
    }
}

My best guess is that maybe I am missing a #include somewhere. I tried googling the issue for the past couple hours and the only thing I can come up with is to move "using namespace std" but I have tried that and I am still getting the error.
Edit:
Here is my Card.cpp
#include <cstdlib>
#include "card.h"
#include <sstream>
#include <stdexcept>
using namespace std;

Card::Card(int r, char s)
{
    if(r <= 13 && r > 0)
        this->r = r;
    else
        throw std::invalid_argument("Rank must be valid (1-13)");

    if(s == 'd' || s == 'D')        //diamonds
        this->s = 'D';
    else if(s == 'h' || s == 'H')   //hearts
        this->s = 'H';
    else if(s == 's' || s == 'S')   //spades
        this->s = 'S';
    else if(s == 'c' || s == 'C')   //clubs
        this->s == 'C';
    else
        throw std::invalid_argument("Suit must be valid (H, S, C, D");
}

Card::Card(const Card& old)
{
    r = old.r;
    s = old.s;
}

void Card::setCard(int r, char s)
{
    if(r <= 13 && r > 0)
        this->r = r;
    else
        throw std::invalid_argument("Rank must be valid (1-13)");

    if(s == 'd' || s == 'D')        //diamonds
        this->s = 'D';
    else if(s == 'h' || s == 'H')   //hearts
        this->s = 'H';
    else if(s == 's' || s == 'S')   //spades
        this->s = 'S';
    else if(s == 'c' || s == 'C')   //clubs
        this->s == 'C';
    else
        throw std::invalid_argument("Suit must be valid (H, S, C, D");
}

int Card::getRank()
{
    return r;
}

 bool Card:: operator == (const Card c) const
 {
     if(r == c.r)
         return true;
     else
         return false;
 }

 bool Card:: operator >(const Card c) const
 {
     if(r > c.r)
         return true;
     else
         return false;
 }

 ostream& operator << (ostream& out, const Card c)
 {
     if(c.r == 1)
         out << "A" << c.s;
     else if(c.r > 1 && c.r <= 10)
         out << c.r << c.s;
     else if(c.r == 11)
         out << "J" << c.s;
     else if(c.r == 12)
         out << "Q" << c.s;
     else      //must be king
         out << "K" << c.s;
 }

and card.h:
#ifndef CARD_H
#define CARD_H

#include <string>
#include <iostream>
using namespace std;

class Card
{
private:
    int r;
    char s;

public:

    Card(int r, char s); //parameterized constructor
    Card(const Card& old);     //copy constructor

    void setCard(int r, char s);
    int getRank();
    bool operator ==(const Card c) const;
    bool operator >(const Card c) const;
    friend ostream& operator << (ostream& out, const Card c);

};

Comment: There is no need for `Card` to have a user-defined copy constructor or assignment operator.  Also, you may not be needing the default constructor, but what if `vector` needs it?  Aha.
Comment: The real error message starts `error: no matching function for call to 'Card::Card()'`  , the stuff before it is explaining where we were at in the compliation process before this problem occurred
Comment: *no matching function for call to 'Card::Card()'* Looks like Card needs a default constructor.
Comment: [Get rid of the `using namespace std;` in the header file](https://stackoverflow.com/questions/4872373/why-is-including-using-namespace-into-a-header-file-a-bad-idea-in-c).  Post the `Card` class.
Comment: `srand` should usually only be called once per program ad this looks to fall into usually. Remove it from `Pile:: shuffle()` and put it somewhere near the top of the `main` function.
Comment: @PaulMcKenzie I removed using namespace std; and posted the card class.
Comment: @user4581301 Thank you I removed it from the class file and added to main. I added a default constructor and it worked. Do you need a default constructor no matter what? I'm not using default constructor for anything so why does it need it?
Answer: The issue is this line:
p = vector<Card>(0);

Initializing vectors this way requires a default constructor.  Please see std::vector constructor (3).  You can simply remove that line, since it really isn't necessary.  A std::vector starts out as empty anyway, so there is no need to do redundant work.
You will see that if you remove that line, you will note that your code will compile without need of a default constructor.  However if you add more code, you need to be careful you're not using std::vector in a way where the default constructor is needed.  Thus it may not hurt just to provide a default constructor.

Having said that, your code produced a few warnings that you need to address.  For example, in your overloaded << operators, you failed to return a value.  Returning nothing from a function that is supposed to return a value leads to undefined behavior.
The other issue is that there is no need for you to write a user-defined copy constructor for either Pile or Card, since both classes have all their members containing correct copy semantics (int, char, for the Card class, and std::vector<Card> for the Pile class).  There is no need to introduce code that the compiler provides to you for free, without bugs, and is efficient.
Answer: Default constructor for Card class is missing. C++ does not generate default constructor when user defined constructor (with parameters or without parameters) is present in the class.
In your code default constructor is need in Pile.cpp:27.


Explain what TraitCollectionDidChange/UITraitCollection is in simple terms?

Question: I have the following code:
public override void TraitCollectionDidChange(previousTraitCollection: UITraitCollection)
{
    base.TraitCollectionDidChange(previousTraitCollection)
    ...
}

What does base.TraitCollectionDidChange() do?
Comment: https://developer.apple.com/documentation/uikit/uitraitenvironment/1623516-traitcollectiondidchange
Answer: This methods will be called when your size class change. So you can adapt your layout :)
Have you heard about size class ?
Size class are an apple abstraction to define a size device.
For example to Iphone X have, that values :
For Portrait :
 - Compact width, regular height
For Landscape :
 - Compact width, compact height
With TraitCollection you can identify when this classes changes, for example from Portrait to Landscape, with this information you can update your layout.
Here an tutorial:
https://www.hackingwithswift.com/example-code/uikit/how-to-detect-when-your-size-class-changes
Here an tutorial about size class:
https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/adaptivity-and-layout/


Reactive @Input is not getting data properly in angular

Question: I have one parent component ( container.component) and one child component ( plotting.component).
From the container, the user can upload a file. one submit button will send this data into the plotting component. Unfortunately, I can send data from containers to plotting just once. If I try to upload multiple data back and forth, its not working. plotting component is not update with the proper data.
Here is my container.component.html:

        <input type="file" class="custom-file-input inputFile" id="inputFile" (change)="upload($event.target)" />
         {{fileName}}

    <button class="btn btn-primary mt-2" (click)="passDAta()"> submit </button>

    <plotting [data]="data"></plotting>

container.ts file:
data = new BehaviorSubject<any[]> ([]);
  scanData: any = [];

upload(input: HTMLInputElement) {
    const files = input.files;
    const fileToRead = files[0];

    if (fileToRead.type === "text/csv") {
      this.fileName = fileToRead.name;

      const fileReader = new FileReader();

      fileReader.onload = event => {
        const result = fileReader.result;
        if (typeof result !== "string") {
          throw new Error("Unexpected result from FileReader");
        }
        result.split("\n").map(data => {
          let [a, b] = data.split(",");
          this.scanData.push(this.p2c(parseFloat(b), parseFloat(a)));
        });
      };

      fileReader.readAsText(fileToRead, "UTF-8");
    } else {
      this.fileName = " unknow file type. csv only"
    }
  }

  passDAta() {
    this.data.next(this.scanData);
    console.log("parent: ", this.scanData)

  }

My plotting component.ts is :
private _data: any;

@Input()
  set data(data: Observable<any>) {
    data.subscribe(data => {
      this._data = data;
    });
  }
  get data () {
    return this._data;
  }

I have tried with ngOnchanges as well. But cant detects the change. I have also created a stackbliz. you can download the csv1 and csv2. if you upload the file back and forth you will see, data is not passing into plotting from the container. How can I solve this issue?
Here is the stackblitz
Answer: Using a BehaviorSubject in this case isn't elegant and might lead to too many subscriptions. You could just pass the data to setter and not worry about the change detection. Try the following
container component
data = [];

passDAta() {
  this.data = this.scanData;
  console.log("parent: ", this.scanData)
}

plotting component
private _data: any;

@Input()
set data(data: any) {
  this._data = data;
}

get data () {
  return this._data;
}

Update
Old data from the variable scanData isn't removed before new data is pushed to it. So @Input() is working as expected, except the new data is getting appended to the end of the old data. You could just remove the old data using this.scanData = []; at the beginning of the upload() function. Try the following
upload(input: HTMLInputElement) {
  this.scanData = [];
  .
  .
}

I've modified your Stackblitz.
I've removed the CSV file check in the upload() function in the Stackblitz to get it working. If not, it kept throwing me the ''unknown file type. csv only' error. I've also assigned the type Array<{'x': number, 'y': number}> to the _data member variable in plotting component.
Comment: I downloaded your sample CSV files and tried to upload them and got 'unknown file type. csv only' error. I am uploading CSV files.
Comment: I've updated the code. Please see if it works for you.
Comment: i did.. but same problem. just works for the very first time. If you upload different file, plotting is not getting any. please check the stackbliz. @michael-d
Comment: i have upload the csv again. @michael-d
However, still I don't know, why my code with BehaviorSubject
Comment: I was having a nightmare. this silly mistake destroys my whole day. you just saved me. thanks a lot. answer accepted and upvoted. @michael-d


Retrieving pointer data from Parse.com in Android

Question: I'm trying to retrieve the data from a pointer in my parse.com database from the class User which field is "companyId" Pointer Company (It gets the company objectId from the class Company) to add that data in another table called Note into a field called companyId when creating an object.
This is my parse.com database:
Class Name: User
objectId String|companyId Pointer Company|username String |password String
Class Name: Note
objectId String| companyId String |text String
I've look for solutions and I don't find anyone as I don't know how to retrieve the companyId value as it is a Pointer.
Thanks in advance for any repply.
EDIT: Problem solved, below there is how it worked for me and other way of solving it by "bigdee94".
Thanks!
Answer: Carlos, you can try this : -

According to the docs, in order to call relational data from pointer columns you can use the include() method.For example:-

ParseQuery<ParseObject> userQuery = ParseUser.getQuery();
userQuery.include("companyId");
userQuery.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objects, ParseException e) {
   if (e == null) {
      // userObjects retrieved successfully
      ParseObject companyIdObject = (ParseObject) objects.get("companyObjectIdColumn");
   } else {
      Log.d("objects", "Error: " + e.getMessage());
   }
});

Where companyObjectIdColumn is the objectId column in you Company table(class) andobjects is the queried list of objects
P.S: you can make ParseObject companyIdObject a global variable so that you can access it from any where.
Comment: No @CarlosRomero, You just have to call the objectId column into another ParseObject like so, `ParseObject companyIdObject = (ParseObject) objects.get("companyObjectIdColumn");`. I haven't tried it though but I believe it's logically correct. I'm glad you found a simpler solution
Comment: bigdee94, Thanks for replying but I founded an easier solution as I described below. I believe it works but if I'm not wrong with your answer I would have to make another ParseQuery to get the objectId from the table Company. Even though it might help if anyone wants to do it like that.
Comment: There's no need to cast the parse object, you can just use `objects.getParseObject("")` opposed to what you have there
Answer: One mate helped me and here is how we solved it:
Note n = new Note();
ParseUser user = ParseUser.getCurrentUser();
ParseObject userObj= user.getParseObject("companyId");
note.put("companyId", userObj.getObjectId().toString());

I founded kinda tricky as if you do try as:
Note n = new Note();
ParseUser user = ParseUser.getCurrentUser();
user.getParseUser("companyId");

It won't give the data in the field, I believe you get the memory access where the data is.
Thanks for your time, hope this helps more people!
Answer: I have created pointer object and i retrieved from that easily ..Below code
 final ProgressDialog progress = new ProgressDialog(this);
    progress.setMessage("Loading ...");
    progress.setCancelable(false);
    progress.show();
    ParseGeoPoint point = new ParseGeoPoint(l1, l2);
    ParseUser user = ParseUser.getCurrentUser();
    ParseObject shop = new ParseObject("ShopLocations");
    shop.put("locationName", locname.getText().toString());
    shop.put("pin", Integer.parseInt(setpin.getText().toString()) );
    shop.put("location", point);
    shop.put("menu", ParseUser.getCurrentUser()); // this is poniter object creation in User table
    shop.put("business", ParseUser.getCurrentUser()); // this is another pointer
    shop.put("userobjectId", user.getObjectId());
    shop.saveInBackground();
    shop.saveInBackground(new SaveCallback() {

        @Override
        public void done(ParseException e) {
            // TODO Auto-generated method stub
            progress.dismiss();
            if (e == null) {
                Toast.makeText(Createloctaion.this, "success", Toast.LENGTH_SHORT).show();
                // success
            } else {
                customToast(e.getMessage());
            }
        }
    });

Below code for retrieving pointer object :
 if(ParseUser.getCurrentUser()!=null) {
        ParseQuery<ParseObject> query = ParseQuery.getQuery("ShopLocations");
        query.whereEqualTo("menu", ParseUser.getCurrentUser());
        query.whereEqualTo("business",ParseUser.getCurrentUser());
        query.whereEqualTo("userobjectId",ParseUser.getCurrentUser().getObjectId());
        query.findInBackground(new FindCallback<ParseObject>() {
            public void done(List<ParseObject> object, ParseException e) {
                if (e == null) {

                    if (object.size() > 0) {
                    for (ParseObject user : object) {

                        String chkbank = user.getString("locationName");
                        Toast.makeText(Dashboard.this, ""+chkbank, Toast.LENGTH_SHORT).show();
                    }
                    } else {
                    // Handle the exception
                    }
                } else {
                    Toast.makeText(Dashboard.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();

                }
            }
        });

    }


How can I determine which MERV filters would be best for my air handler?

Question: I have a Carrier 3.5 ton, 1/2HP air handler (Model Number:fc4bnf042).  I have been using MERV 13 a/c filters for a few years now because my son has allergies.  I recently discovered that the higher MERV filters can cause resistance that can strain the blower.  Does anyone know if there is a simple way of determining whether I am OK with the MERV 13?
Answer: One website I found is selling filters in the same range as yours for that model.
Outside of checking with Carrier, though, I can't think of an absolute answer.


Can a MWBC ever be on 2 breakers?

Question: Has it ever been acceptable for a multi wire branch circuit to be on 2 separate breakers? My house, which was built in the mid 90s, has the dishwasher and the disposal on the same 12/3 cable, but not on a common trip breaker.
I'm going to replace the breaker, but I'm just curious if this was ever allowed.
Comment: If I understand correctly, a MWBC is _always_ on 2 separate breakers. There's a requirement that they be handle-tied, and they can be one single "double" breaker, but each circuit is on its own breaker. This may just be a minor matter of semantics, though.
Answer: Yes, it was allowed to have MWBC on separate breakers. My house was built in 1981 and I had my refrig and two outlets on one MWBC and my dishwasher and disposal on another. They were not handle tied and not even next to each other in the panel but they were on different phases so the neutral wouldn't be overloaded. The whole subdivision was built like that and many panels that I've been in have had them wired the same way.
Answer: I suspect the handle-tie requirement came along either in the late 90s or the 00s.  Back in 1994 they were still allowing 3-prong range and dryer connections to be built (though, not with NM nor UF cable).
Answer: Yes it is allowed, up through the 2020 NEC section 240.15(B)(1) single pole 120/240v breakers with handle ties are still allowed when the MWBC only feeds line to neutral loads.
I don't have my old books, but it wasn't until the 2000's that the common trip requirements entered the code, but even then your local authority may have not have immediately adopted the code or that section immediately upon publication. For instance 3 states are still using the 2008, four cycles behind.
Free access to the NEC at https://www.nfpa.org/codes-and-standards/all-codes-and-standards/list-of-codes-and-standards/detail?code=70

Can a MWBC ever be on 2 breakers?


Driveway Gutter / Rain Guide?

Question: Our house was built a little over 20 years ago.  The person who paved the asphalt driveway didn't grade it right, so in addition to the slight downward slope towards the road, it has alternating slopes between the left and right sides.  The driveway immediately abuts grass at the same level -- no curbs.  When it rains hard, water sheets across the driveway, then courses along one side, killing the grass and creating lots of mud and soggy ground.  It then crosses over to the other side of the driveway and does the same thing further down, before it ends up at an extremely soggy patch at the end of the driveway.
We'd love to add curbs or something to the driveway, but we don't want to have to build the grass up on the sides.  We were wondering if there would be some way to create gutters for the driveway -- perhaps poured concrete or clay channels that would sit below driveway level on either side and carry the water down to the end of the driveway.  Is there a common way to do this?  Are there pre-made channels that we could put in?  I'd appreciate any input here.
We live in New England, so whatever is put in has to be able to deal with freezing and thawing, as well as moderate amounts of snow, ice, rain, and baking sunshine at different parts of the year.  Plowing isn't an issue as we always shovel/snowblow the driveway.
Comment: What is the slope of the driveway along its length?
Answer: I'll let others chime in with gutter ideas.  Just keep in mind that you'll need to make sure they can handle the expansion from ice without cracking.  But I did want to mention a few alternative solutions you may want to consider.
If you want to keep the lawn, you may consider at a french drain, possibly with some ground level openings to handle severe weather (install these in a way that you can close them in the winter).
If you want to change the look, consider some raised beds on either side of the driveway (which has an added benefit of keeping cars off of the lawn).
Comment: The french drain is exactly what I'd do with this problem.  Putting some nice looking gravel in a layer on top will help the appearance and give you a buffer between the driveway and your lawn.
Answer: This site should give you an informed view and information on how to go about what you need to do. More specific information is contained in links at the base of the page.
Bookmark the site, it's a keeper!

Driveway Gutter / Rain Guide?


Is it smart to use asp.net Application[] for caching website contents?

Question: i am trying to do a project with asp.net and i want to know is it true too use Application for caching the contents of website?
for example I used a method with 100 line code and the method connected to database and did a lot of things... and finally it returns a string which length of it is 10000 chars.. is it true to save this string in asp.net application and use this application till the program is working instead of do the method every time? or i have to do this method every time when users check my website?
Answer:
You should probably use the word 'smart' instead of 'true'.
You can do what you write. You can also simply use static classes to store your "cache". In my opinion it is the easiest way to do that.
Comment: Hah, replacing smart with true and the question almost makes sense. Incredible. :D
Comment: thx for your answer :X i decide to use static classes for cache
Comment: +1 for true to smart conversion