Query to get data from four tables

Question: i have following scheme,
purchase_order
+-------------------+----------------------+
| purchase_order_id | purchase_order       |
+-------------------+----------------------+
|                54 | Purchase Order 12345 |
|                56 | po-laptop-hp-3       |
|                57 | po-laptop-hp-1       |
+-------------------+----------------------+

purchase_order_detail
+--------------------------+-------------------+---------+------------------+
| purchase_order_detail_id | purchase_order_id | item_id | ordered_quantity |
+--------------------------+-------------------+---------+------------------+
|                       61 |                54 |     279 |              500 |
|                       62 |                54 |     286 |              700 |
|                       63 |                56 |     279 |               43 |
|                       64 |                57 |     279 |               43 |
|                       65 |                57 |     286 |               43 |
|                       66 |                57 |     287 |               43 |
+--------------------------+-------------------+---------+------------------+

delivery_order
+-------------------+--------------------------+-------------------+
| delivery_order_id | purchase_order_detail_id | recieved_quantity |
+-------------------+--------------------------+-------------------+
|                62 |                       61 |               250 |
|                63 |                       62 |               300 |
|                64 |                       63 |                34 |
|                65 |                       64 |                34 |
|                66 |                       65 |                34 |
|                67 |                       66 |                34 |
|                68 |                       61 |                34 |
|                69 |                       61 |                34 |
+-------------------+--------------------------+-------------------+

stock
+----------+-------------------+------------+----------+------------------+---------------+
| stock_id | delivery_order_id | project_id | quantity | initial_quantity | stock_type_id |
+----------+-------------------+------------+----------+------------------+---------------+
|       12 |                62 |          1 |       60 |               60 |             1 |
|       13 |                63 |          1 |      120 |              120 |             1 |
|       14 |                63 |          1 |       50 |               50 |             1 |
|       15 |                64 |          1 |       12 |               12 |             1 |
|       16 |                62 |          1 |      120 |              120 |             1 |
|       17 |                62 |          1 |       12 |               12 |             1 |
+----------+-------------------+------------+----------+------------------+---------------+

i have write this query but it returns duplicate results
      SELECT po.created_on
           , po.purchase_order
           , i.item_name
           , u.unit_name
           , pod.ordered_quantity
           , do.recieved_quantity
           , do.recieved_on
           , po.remarks
        FROM purchase_order        po
           , purchase_order_detail pod
           , delivery_order        do
           , stock                 s
           , item                  i
           , unit                  u
       WHERE u.unit_id                    = i.unit_id
         AND i.item_id                    = pod.item_id
         AND po.purchase_order_id         = pod.purchase_order_id
         AND pod.purchase_order_detail_id = do.purchase_order_detail_id
         AND do.delivery_order_id         = s.delivery_order_id
         AND s.project_id                 = 1
    ORDER BY po.purchase_order_id
           , pod.item_id
           ;

The results
+---------------------+----------------------+------------+-----------+------------------+-------------------+---------------------+---------------------------------------+
| created_on          | purchase_order       | item_name  | unit_name | ordered_quantity | recieved_quantity | recieved_on         | remarks                               |
+---------------------+----------------------+------------+-----------+------------------+-------------------+---------------------+---------------------------------------+
| 2015-02-24 22:48:15 | Purchase Order 12345 | HP Laptops | Unit      |              500 |               250 | 2015-02-21 00:00:00 | Adding first Purchase Order as a Test |
| 2015-02-24 22:48:15 | Purchase Order 12345 | HP Laptops | Unit      |              500 |               250 | 2015-02-21 00:00:00 | Adding first Purchase Order as a Test |
| 2015-02-24 22:48:15 | Purchase Order 12345 | Lenovo     | Unit      |              700 |               300 | 2015-02-21 00:00:00 | Adding first Purchase Order as a Test |
| 2015-02-24 22:48:15 | Purchase Order 12345 | Lenovo     | Unit      |              700 |               300 | 2015-02-21 00:00:00 | Adding first Purchase Order as a Test |
| 2015-02-24 22:55:40 | po-laptop-hp-3       | HP Laptops | Unit      |               43 |                34 | 2015-02-21 00:00:00 | dfgsdfgsd                             |
+---------------------+----------------------+------------+-----------+------------------+-------------------+---------------------+---------------------------------------+

relationship is one to many from top to bottom.
What I wanted to get is the each purchase_order , his ordered quantity of each item, and total recieved quantity, and quantity in stock where project_id = 1 from stock.
i am expecting something like this,
+-------------------+---------+------------------+---------------+----------+
| purchase_order_id | item_id | ordered_quantity | totalReceived | quantity |
+-------------------+---------+------------------+---------------+----------+
|                54 |     279 |              500 |           314 |      192 |
|                54 |     286 |              700 |           300 |      170 |
|                56 |     279 |               43 |            34 |       12 |
+-------------------+---------+------------------+---------------+----------+

Comment: What are your expected results form the sample data?
Answer: EDIT
Thank you for clearing up the mistake in my first part. I realize now that we cannot do all calculations in a single query (because we group on different columns in various parts) so I started by writing individual subqueries and joining them together. The steps went something like this:

Get the sum of received total received quantity for each
purchase_order_detail_id from the delivery_order table.
Join that subquery with the delivery_order table itself to get the totalReceived for the various delivery_order_id values.
Join that result set with the purchase_order_detail table to get the purchase_order_id, item_id, and ordered_quantity for each delivery_order_id.

We now have a result set including the delivery_order_id, purchase_order_id, item_id, ordered_quantity, and total received. The last two things are:

Get the SUM() of quantity for each delivery_order_id from the stock table.
Join that with our above result set on the condition that order_id matches (so we will only get one row) and that project_id is 1 (so we only get the necessary delivery_order_id values). I put that condition in the WHERE clause of the sum subquery.

Here is your final query:
SELECT tmp1.purchase_order_id, tmp1.item_id, tmp1.ordered_quantity, tmp1.totalReceived, tmp2.quantity
FROM(
  SELECT tmp.delivery_order_id, pod.purchase_order_id, pod.item_id, pod.ordered_quantity, tmp.totalReceived
  FROM purchase_order_detail pod
  JOIN(
    SELECT do.delivery_order_id, tmp.purchase_order_detail_id, tmp.totalReceived
    FROM delivery_order do
    JOIN(
      SELECT do.purchase_order_detail_id, SUM(do.received_quantity) AS totalReceived
      FROM delivery_order do
      GROUP BY do.purchase_order_detail_id) tmp ON tmp.purchase_order_detail_id = do.purchase_order_detail_id)
    tmp ON tmp.purchase_order_detail_id = pod.purchase_order_detail_id) tmp1
JOIN(
  SELECT s.delivery_order_id, SUM(quantity) AS quantity
  FROM stock s
  WHERE s.project_id = 1
  GROUP BY s.delivery_order_id) tmp2 ON tmp2.delivery_order_id = tmp1.delivery_order_id;

Here is the SQL Fiddle. It shows all of the intermediate steps too, if you'd like to see how the results came together individually.
Comment: you query is quite close but it returns rowing result, running this said that look at the difference of ordered and recievedquantity.
Comment: Hmm, I will try to work it out. Can you edit your question with the correct results I should get?
Comment: the problem with your query is when their is many received_quantity against one ordered_quantity, then it returns incorrect result, else correct. and the same happened with my query.
Comment: @MTaqi I'm sorry for the misunderstanding. I have reworked this out and replaced my answer with a working solution.
Comment: @MTaqi have you had any opportunity to test the edited solution? Any problems?
Comment: Actually, you query is not working giving out errors.
Comment: ERROR 1054 (42S22): Unknown column 'temp1.ordered_quantity' in 'field list'
Comment: @MTaqi simple typo. Should have been tmp1. Without the 'E'
Comment: @Strawberry fiddle seems to be down right now but I believe so. I test every fiddle before I actually add it in my question. I remember correcting the typo in there, simply forgot to edit question.
Comment: I test it on my db also
Answer: Try modifying your query to use DISTINCT and OUTER JOINs instead of cartesian ("comma") joins.
  SELECT DISTINCT po.created_on
       , po.purchase_order
       , i.item_name
       , u.unit_name
       , pod.ordered_quantity
       , do.recieved_quantity
       , do.recieved_on
       , po.remarks
    FROM purchase_order po
    LEFT JOIN purchase_order_detail pod USING (purchase_order_id)
    LEFT JOIN delivery_order do USING (purchase_order_detail_id)
    LEFT JOIN stock s USING (delivery_order_id)
    LEFT JOIN item i USING (item_id)
    LEFT JOIN unit u USING (unit_id)
ORDER BY po.purchase_order_id
       , pod.item_id
       ;

Query to get data from four tables


Is it possible to make 2 or more DataBindingComponent?

Question: I would like to ask is it possible to make 2 or more DataBindingComponent class in android? because i want to escape the static method in binding so i try to use the injection with DataBindingComponent but I got the error of Class 'AppDataBindingComponent' must be either be declared abstract or implement abstract method 'getLoginViewDataBinding' in 'DataBindingComponent' because of this error I can't make the non-static one.
this is the class which i got the problem
public class AppDataBindingComponent implements android.databinding.DataBindingComponent {
    @Override
    public RecyclerViewDataBinding getRecyclerViewDataBinding() {
        return new RecyclerViewDataBinding();
    }
}

First binding class
public class RecyclerViewDataBinding {

    @BindingAdapter({"app:adapter", "app:data"})
    public void bind(RecyclerView recyclerView, DataAdapter adapter, List<DataModel> data) {
        recyclerView.setAdapter(adapter);
        adapter.updateData(data);
    }
}

Second Binding Class
public class LoginViewDataBinding {

    @BindingAdapter({"validation", "errorMsg"})
    public void setErrorEnable(TextInputLayout textInputLayout, StringRule stringRule,
                                      final String errorMsg) {
        Observable<CharSequence> textObservable = RxTextView.textChanges(
                Objects.requireNonNull(textInputLayout.getEditText()));
        compositeDisposable.add(textObservable
                .map(charSequence -> {
                    ......
                })
                .distinctUntilChanged()
                .replay(1).refCount()
                .subscribe());
    }

}

In the Main Class I call the DataBindingComponent
public class MainActivity extends AppCompatActivity {
    private DataViewModel dataViewModel;
    private ActivityMainListMvvmBinding activityBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bind();
    }

    private View bind() {
        activityBinding = DataBindingUtil
                .setContentView(this, R.layout.activity_main_list_mvvm, new AppDataBindingComponent());
        dataViewModel = new DataViewModel();
        activityBinding.setViewModel(dataViewModel);
        return activityBinding.getRoot();
    }

}

The problem is solved if I put getLoginViewDataBinding
public class AppDataBindingComponent implements android.databinding.DataBindingComponent {
    @Override
    public RecyclerViewDataBinding getRecyclerViewDataBinding() {
        return new RecyclerViewDataBinding();
    }

    @Override
    public LoginViewDataBinding getLoginViewDataBinding() {
        return null;
    }
}

the answers that I want is somehow like this: (is this possible?)
public class AppDataBindingComponent implements android.databinding.DataBindingComponent {
    @Override
    public RecyclerViewDataBinding getRecyclerViewDataBinding() {
        return new RecyclerViewDataBinding();
    }
}

public class LoginDataBindingComponent implements android.databinding.DataBindingComponent {
    @Override
    public LoginViewDataBinding getLoginViewDataBinding() {
        return null;
    }
}

Comment: nope later, i just used mixed programming between the MVVM methods and some MVC method to do...., cause when i whatever solution visible, there is solution for this kind of answers that I want...
Comment: Did you found any solution for that?
Comment: I have found a solution for that. I will post it soon
Answer: What about this:
public class DataBindingComponent<T> implements android.databinding.DataBindingComponent {
    private T activity;

    public DataBindingComponent(T activity) {
        this.activity = activity;
    }

    public LoginViewDataBinding getLoginViewDataBinding() {
        return (LoginViewDataBinding) activity;
    }

    public RecyclerViewDataBinding getRecyclerViewDataBinding() {
        return (RecyclerViewDataBinding) activity;
    }
}

And than create in both of your class's:
new AppDataBindingComponent(this)


Using loops in Javascript event delegation

Question: I have the following piece of code:
<code>var page = document.getElementById("contentWrapper");
page.addEventListener("click", function (e) {
   var target, clickTarget, propagationFlag;
   target = e.target || e.srcElement;
   while (target !== page) {
      clickTarget = target.getAttribute("data-clickTarget");
      if (clickTarget) {
          clickHandler[clickTarget](e);
          propagationFlag = target.getAttribute("data-propagationFlag");
      }
      if (propagationFlag === "true") {
          break;
      }
      target = target.parentNode;
   }
});
</code>
I'm using a single event handler in my whole project (single page application). Event handlers are identified using attribute "data-clickTarget" and to prevent event propagation "data-propagationFlag" is used.
If the DOM tree is large, should I go with looping approach or conventional event handlers?
Comment: If the dom tree is large, don't weigh it down with jQ.
Comment: @Dude That's a nonsensical statement. And it does not help the OP.
Comment: You are using jQuery then why are you making the coding so complex.  simplify using `this` keyword and `.data()`
Comment: @Tomalak Why? I'm offering advice that can benefit the OP and anybody who sees it, should I stop?
Comment: @Dude I think the statement comes off as overly broad and simplified. I'm missing a bit of substantiation/reflection for that claim.
Comment: @Tomalak I usually don't write 10 page essays concepts that can be explained with a sentence when there is a character limit.
Comment: @Dude Answers were not length-limited, last time I checked. When you can't be bothered to explain a recommendation, don't make it.
Comment: @Tomalak It wasn't an answer.
Comment: @Dude There we go. It wasn't a useful comment, either. Quote *"concepts that can be explained with a sentence"* just that you forgot to actually *explain* anything. EOD.
Comment: @Tomalak Please point me to an authoritative posting that says that comments have to be helpful.
Comment: @Dude I'm pretty sure you want to read your previous comment again and think about it for a bit.
Comment: @Tomalak I've read it. Comments are "a verbal or written remark expressing an opinion or reaction" if the community likes the "expression of opinion or reaction" (for whatever reason: usefulness, humor, etc.), then it should stay. My comment isn't particularly useful, but it is good advice, which the community should like.
Answer: Delegated event handlers can be slow if the document is large and if the selected element is far from the element that triggers the event... from JQuery documentation:

Attaching many delegated event handlers near the top of the document
  tree can degrade performance. Each time the event occurs, jQuery must
  compare all selectors of all attached events of that type to every
  element in the path from the event target up to the top of the
  document. For best performance, attach delegated events at a document
  location as close as possible to the target elements. Avoid excessive
  use of document or document.body for delegated events on large
  documents.

As the documentation says for a "click" event probably this is not going to be a serious issue (because users won't click like crazy on a page) but for events like mouse motion or scroll slow response can become quite annoying.
The specific feature of delegated handlers is that even new elements added later to the DOM will use the handler, but do you really need this? If you are not writing a library but just an application then you control when new elements are added and thus you can factor out the even handler attachment into the element creation (in other words instead of having a function that just creates the new element, make it so that it creates the element and also automatically registers the standard event handler).
Comment: Any other simpler/effective method to implement event delegation?


Only password protect one file in folder with .htaccess

Question: I only want to password protect one file in a folder.  How can I do this with .htaccess?
Answer: Let's say you want to password protect your secret.html file. Just create a .htaccess file in the same folder as the secret file, with the following content (you may need to customize some values according to your config:
<Files secret.html>
AuthName "Login"
AuthType Basic
AuthUserFile /html/username/.htpasswd
require valid-user
</FilesMatch>

You can also use wildcards to filter some file types only. Imagine you want to password protect all zip files:
<FilesMatch "*.zip">
AuthName "Login"
AuthType Basic
AuthUserFile /html/username/.htpasswd
require valid-user
</FilesMatch>

Comment: Do you now how to do the opposite?  That is exclude one or two files from the password protect?
Comment: you need to have some criteria in order to use wildcards. For instance, imagine you want to password protect all .zip files:  every other file will be unlocked.


Add prefix to each word of each line in bash

Question: I have a variable called deps:
deps='word1 word2'

I want to add a prefix to each word of the variable.
I tried with:
echo $deps | while read word do \ echo "prefix-$word" \ done

but i get:

bash: syntax error near unexpected token `done'

any help? thanks
Comment: you need semi colons, not that it will work with them, but it would stop the error.
Comment: `for i in $deps;do echo "prefix-$i";done`
Comment: so you want the output to be `prefix-word1 prefix-word2`, right?
Answer: With sed :
$ deps='word1 word2'
$ echo "$deps" | sed 's/[^ ]* */prefix-&/g'
prefix-word1 prefix-word2

Comment: Perhaps simpler: `echo $deps | sed 's/\` are a GNU syntax, so less portable.
Comment: @techguy2000 Try to add an address(`/^$/!`) to apply the `s` command to non-empty lines only: `echo "$deps" | sed '/^$/!s/[^ ]* */prefix-&/g'`
Comment: when deps is blank, how to avoid the transformation without an if statement?
Answer: For well behaved strings, the best answer is:
printf "prefix-%s\n" $deps

as suggested by 123 in the comments to fedorqui's answer.
Explanation:

Without quoting, bash will split the contents of $deps according to $IFS (which defaults to " \n\t") before calling printf
printf evaluates the pattern for each of the provided arguments and writes the output to stdout.
printf is a shell built-in (at least for bash) and does not fork another process, so this is faster than sed-based solutions.
Answer: In another question I just came across the markers for beginning (\<) and end (\>) of words. With those you can shorten the solution of SLePort above somewhat. The solution also nicely extends to appending a suffix, which I needed in addition to the prefix, but couldn't figure out how to use above solution for it, as the & also includes the possible trailing whitespace after the word.
So my solution is this:
$ deps='word1 word2'

# add prefix:
$ echo "$deps" | sed 's/\</prefix-/g'
prefix-word1 prefix-word2

# add suffix:
$ echo "$deps" | sed 's/\>/-suffix/g'
word1-suffix word2-suffix

Explanation: \< matches the beginning of every word, and \> matches the end of each word. You can simply "replace" these by the prefix/suffix, resulting in them being prepended/appended. There is no need to reference them anymore in the replacement, as these are not "real" characters anyway!
Answer: You can read the string into an array and then prepend the string to every item:
$ IFS=' ' read -r -a myarray <<< "word1 word2"
$ printf "%s\n" "${myarray[@]}"
word1
word2
$ printf "prefix-%s\n" "${myarray[@]}"
prefix-word1
prefix-word2

Comment: You could also use the original string instead of an array `printf "prefix-%s\n" $deps`


How do I get tkinter to work (in vim) and how do I get python-3.x running as my default python for linux?

Question: From my understanding, tkinter comes pre-installed with python.  I can't, for the life of my, understand why every IDE I have tried to run tkinter on isn't recognizing tkinter as a library.
I have tried:
import tkinter as tk
import Tkinter as tk
import * from tkinter
from tkinter import *
import tkinter
import Tkinter
and everything else in between...
The whole snipit I am trying to run:
 import Tkinter
 top = Tkinter.Tk()
 top.mainloop()

Whenever I try to run it in VIM the error message is:
Traceback (most recent call last):
  File "tktest.py", line 1, in <module>
    import Tkinter
  File "usr/lib/python2.7/lib-tk/Tkinter.py", line 42, in <module>
    raise ImportError, str(msg) + ', please install the python-tk package'
ImportError: No module named_tkinter, please install the python-tk package

shell returned 1

Do I need vim to be running python3 in vim (which I thought was default) if so, how do I do that?
I have even tried to install tkinter like it says but I get this large error message:
ken@ken-HP-ENVY-Laptop-13-ah1xxx:~$ pip install Tkinter
Collecting Tkinter
Exception:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 353, in run
    wb.build(autobuilding=True)
  File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 554, in _prepare_file
    require_hashes
  File "/usr/lib/python2.7/dist-packages/pip/req/req_install.py", line 278, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/usr/lib/python2.7/dist-packages/pip/index.py", line 465, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "/usr/lib/python2.7/dist-packages/pip/index.py", line 423, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "/usr/lib/python2.7/dist-packages/pip/index.py", line 568, in _get_pages
    page = self._get_page(location)
  File "/usr/lib/python2.7/dist-packages/pip/index.py", line 683, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "/usr/lib/python2.7/dist-packages/pip/index.py", line 795, in get_page
    resp.raise_for_status()
  File "/usr/share/python-wheels/requests-2.18.4-py2.py3-none-any.whl/requests/models.py", line 935, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
HTTPError: 404 Client Error: Not Found for url: https://pypi.org/simple/tkinter/

It looks like I am running python2.7 on my system by default and I don't know why... how do I get python3.7(or latest version) to be my default for my machine?
For the record, I am using Linux Mint 19.3 Tricia
Comment: it is standard to run Python 2 with command `python` and `python2` and `python2.7`, and Python 3 with `python3`, `python3.7`, `python3.8`, etc. The same with `pip`, `pip2`, `pip3`, `pip3.7`, etc. If you want to run script with some version of Python then you can use `shebang` in first line `#!/usr/bin/env python3` and set it executable `chmod a+x script.py` and then it will run as any program using automatically `python3`
Comment: error shows that your Python2 has no `Tkinter` - you may have to install it with `apt install python-tk`.
Comment: BTW: did you install fresh Mint 19.3 or you updated from older version? I have `Mint 19.3` updated from 19.2, updated from 19.1, updated from 18.0, updated from 17.0 and I have `Tkinter` in `Python 2` at start.
Comment: I will definitely try that! But yes, I installed fresh, not updated. It's strange because a lot of programs dont seem to work for me either like pycharm and intellij-idea. Pycharm worked for like a few minutes (had the same error trying to get tkinter going) and then it did this weird double window thing and wouldn't let me select other files in the sidebar. It only let me edit my code.
Comment: @furas while you are correct about the command names, expect this to change as python2 is deprecated
Comment: @D.BenKnoble I wouldn't change or remove `python2` (even if it is depercated) because system may still use `python2` to run some elements - especailly if I have the same system (with updates) since Mint 17.0 (2014)
Comment: @furas meant to indicate that python may come to mean python3, sorry for not being clear.
Answer: Try running Python 3 in a virtual environment:
Open a terminal, go to your project directory and run
$ python3 -m venv venv
which will create a virtual environment called venv in your project directory.
To activate it, go to your project directory and run $ source venv/bin/activate
Your bash prompt should now read (venv) $ and any work you do will take place inside  a virtual environment.
Once you're done working inside the venv, you want to deactivate it. To deactivate, type $ deactivate
NOW, once your virtual environment is active you have a clean, package-free install of Python 3.x where x is whatever version you have installed and aliased to python3.
From in here, you can upgrade pip: $ pip install -U pip, re-install all the packages you want from a requirements.txt file: $ pip install -r requirements.txt, and install any other single packages you need with pip as usual.
Anything you install in your virtual environment will only scope into your virtual environment, so you can use this as a test bed, and destroy/rebuild as you see fit.  This is advantageous for a lot of reasons.

Once you've done this, try launching vim from inside your virtual environment, then try running your code from inside the virtual environment.  Once inside your venv, the only Python your terminal knows about is the one inside the venv. So it should default to that one.
Comment: Thanks for the info! Unfortunately, after doing these things I am still getting the error message `no module named 'Tkinter'` I tried both caps and non caps... I think it is strange because tkinter should be included with python.


Use swift stepper to multiply my original number not previous number

Question: Here's my code.
My need is if the price label have had number
When pressing add from stepper
I need stepper value to multiply my price number
but I encounter this situation
The price label won't multiply my original number
like if price number originally is 50
I would like to show 50,100,150,200,250
not like this  50 ,100 ,300,400
<code>@IBOutlet weak var stepperValue: UILabel!
@IBOutlet weak var price: UILabel!

@IBAction func stepper(_ sender: UIStepper) {

    let count = Int(sender.value)
    stepperValue.text = String(count)
    let price = Int(price.text!)!
    price.text? = String(price * count)
}
</code>
Is there proper way to solve my logical problem?
Comment: why don't you use "price.text? = String(original price * count)"
Answer: You need to store original value somewhere and use it for incrementation.
E.g.
<code>@IBOutlet weak var stepperValue: UILabel!
@IBOutlet weak var price: UILabel!

private var originalPrice: Int = 50 // or whatever you want

@IBAction func stepper(_ sender: UIStepper) {

    let count = Int(sender.value)
    stepperValue.text = String(count)

    price.text = String(originalPrice * count)
}
</code>


how to use the aggregation of mongodb with meteor

Question: i'm using Meteorjs and mongo
I have a collection structure like this:
{
    "_id" : "LxMaZhRX7ZbAkiFqF",
    "categorie" : "International matches",
    "division" : [
            {
                    "nameDivision" : "div 1",
                    "type" : "Championat"
            },
            {
                    "nameDivision" : "div 2",
                    "type" : "Coupe"
            },
            {
                    "nameDivision" : "div 3",
                    "type" : "Championat"
            },
            {
                    "nameDivision" : "div 4",
                    "type" : "Championat"
            }
    ]
   }

I want to have this result in my subscription:
{
    "_id" : "LxMaZhRX7ZbAkiFqF",
    "categorie" : "International matches",
    "division" : [
            {
                    "type" : "Championat",
                    division:[{
                        "nameDivision" : "div 1",
                        "nameDivision" : "div 3",
                        "nameDivision" : "div 4",
                    }]

            },
            {
                 "type" : "Coupe",
                  "division":[{
                     "nameDivision" : "div 2",
                    }]

            },
            {
    ]
   }

I need your help on how to use the function with mongodb aggegate to group the Elements
thank you
Answer: In Meteor, you can use the meteorhacks:aggregate package to implement the aggregation:
Add to your app with
meteor add meteorhacks:aggregate

Then simply use .aggregate function like below.
var coll = new Mongo.Collection('collectionName');
var pipeline = [
    { "$unwind": "$division" },
    {
        "$group": {
            "_id": "$division.type",
            "id": { "$first": "$_id" },
            "categorie": { "$first": "$categorie" },
            "division": {
                "$push": { "nameDivision": "$division.nameDivision" }
            }
        }
    },
    {
        "$group": {
            "_id": "$id",
            "categorie": { "$first": "$categorie" },
            "division": {
                "$push": {
                    "type": "$_id",
                    "division": "$division"
                }
            }
        }
    }
];
var result = coll.aggregate(pipeline);


Add UITapGestureRecognizer to UIScrollView

Question: UPDATE
I am creating a UIScrollView in my ViewController.  In a Drawing.m class I draw a shape onto the UIScrollView with drawRect.  I want the shape that I am drawing onto the ScrollView to be tappable.  The UITapGestureRecognizer is not working at all, it throws an error every time I tap on the shape (error is: unrecognized selector sent to instance...)
Here is how I am using the UITapGestureRecognizer:
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]
                                         initWithTarget:self.scrollView
                                         action:@selector(singleTapGestureCaptured:)];
[self.scrollView addGestureRecognizer:singleTap];

and the method it should be going to:
- (void)singleTapGestureCaptured:(UIGestureRecognizer *)gesture
{
   NSLog(@"I was tapped");
}

How do I setup a UITapGestureRecognizer for a shape drawn on to a UIScrollView?
Comment: why not get the parent view controller (from your view's super view) and then call "`presentViewController`" or "`performSegue`" from the view controller that hosts your UIView as a subview?
Comment: Are you referring to using self.super or self.superview?  Neither of those will allow me to access anything from the superview.
Comment: The code that recognizes the tap should be in the view controller not the view, then you wouldn't have this problem. It's not the view's job to be presenting view controllers.
Comment: @rdelmar I will take that into consideration.  I tried that and ran into issues registering the UIView with a tap gesture recognizer.  Still working on it though. Thanks
Answer: The target should be self not self.scrollView unless the target selector is in a subclass of UIScrollView. It's crashing because on tap it's attempting to call a your -singleTapGestureCaptured: method on UIScrollView, instead of on your UIViewController subclass.


.NET generic class instance - passing a variable data type

Question: As the title suggests, I'm tyring to pass a variable data type to a template class. Something like this:
frmExample = New LookupForm(Of Models.MyClass) 'Works fine

Dim SelectedType As Type = InstanceOfMyClass.GetType() 'Works fine
frmExample = New LookupForm(Of SelectedType) 'Ba-bow!
frmExample = New LookupForm(Of InstanceOfMyClass.GetType()) 'Ba-bow!

LookupForm<Models.MyClass> frmExample;
Type SelectedType = InstanceOfMyClass.GetType();
frmExample = new LookupForm<SelectedType.GetType()>(); //Ba-bow
frmExample = new LookupForm<(Type)SelectedType>(); //Ba-bow

I'm assuming it's something to do with the template being processed at compile time but even if I'm off the mark there, it wouldn't solve my problem anyway. I can't find any relevant information on using Reflection to instance template classes either.
(How) can I create an instance of a dynamically typed repository at runtime?
Comment: You're not going to find any information at all on creating a dynamic template in VB.NET or C#, since neither language supports templates. They both support generics, which are substantially different.
Comment: possible duplicate of [Pass An Instantiated System.Type as a Type Parameter for a Generic Class](http://stackoverflow.com/questions/266115/pass-an-instantiated-system-type-as-a-type-parameter-for-a-generic-class)
Answer: A C# example of something pretty close is located here on a question I had:
typeof(MyClass).GetMethod("Foo").MakeGenericMethod(new[] { param.GetType() }).Invoke(null, new[] { param });

Converting to VB.NET, changing it to type creation not method invocation and using your example names for you:
Dim frmExample as LookupForm<Models.MyClass>;
Dim SelectedType as Type = InstanceOfMyClass.GetType();
Dim GenericLookupType as Type = GetType(LookupForm(Of)).MakeGenericType(SelectedType)
frmExample = Activator.CreateInstance(GenericLookupType, new object(){})

(Ah for some reason I thought you wanted it in VB.NET but here is a C# example)
LookupForm<Models.MyClass> frmExample;
Type SelectedType = InstanceOfMyClass.GetType();
Type GenericLookupType = typeof(LookupForm<>).MakeGenericType(SelectedType);
frmExample = Activator.CreateInstance(GenericLookupType, new object[]{});

Comment: Possibly because the original title had VB.NET at the start and the question only had a VB.NET example :) I removed the title reference and added a C# hoping to tap a larger mindset.
Comment: Thanks for the accept. You'll find out about lots of little rabbit holes with most of the applications of this kind of stuff, but it's a good way to find boundary cases of a language.
Answer: Use Type.MakeGenericType.
Type modelType = typeof(Models.MyClass);
var repoType = typeof(LookupForm<>).MakeGenericType(new [] {modelType} );
//at this point repoType == typeof(LookupForm<Models.MyClass>);
var repo = Activator.CreateInstance(repoType );
//Ta-dah!!!

And VB.NET version :)
    Dim modelType As Type = GetType(Models.MyClass)
    Dim repoType As Type = GetType(LookupForm(Of )).MakeGenericType(New Type() {modelType})
    'at this point repoType = GetType(LookupForm(of Models.MyClass))'
    Dim repo = Activator.CreateInstance(repoType)
    'Ta-dah!!!'

Answer: This sounds like a candidate for the Dynamic Language Runtime, 'Dynamic' type in C#, but that would require you to use .NET 4.0
Comment: I think you'd still have to use Activator.CreateInstance but you could deal with that better at compile time {i.e. LookupForm a = (LookupForm)Activator.CreateInstance(etc.); } and ensure that SomeInstanceType matched other dynamically generated types. Kind of hard to explain right now but you no doubt know what I mean.
Answer: Unfortunately you can't do this without reflection and even then its not very friendly. The reflection code will looks something like this:
Type baseType = typeof(LookupForm<>);
Type selectedType = InstanceOfMyClass.GetType(); //or however else you want to get hold of it
Type genericType = baseType.MakeGenericType(new Type[] { selectedType });
object o = Activator.CreateInstance(genericType);

Of course now you don't know what to cast your object to (assuming selectedType was dynamically set), but you can still call the methods on it via reflection, or you could create a non-generic interface to cast it to & call the methods on that.
Comment: It doesn't have to be friendly in implementation as long as the interface plays nice :)


Counting problem: digit sequences with restricted digits and fixed digit sum

Question: How many different six digit positive integers are there (duplicates allowed), where each digit is between 0 and 7 (inclusive), and the sum equals 20?
I know that there are 229,376 total possible 6 digit numbers which do not have an 8 or a 9. But what process do I use to eliminate those numbers whose digital sums do not equal 20?
Answer: The answer is the coefficient of $x^{20}$ in $$(x+x^2+\cdots+x^7)(1+x+\cdots+x^7)^5$$ Do you see why? Then the first bracket is $x(1-x^7)/(1-x)$, and then second is the 5th power of $(1-x^8)/(1-x)$. OK? So now you need to be able to expand $x(1-x^7)(1-x^8)^5(1-x)^{-6}$, and pick out the coefficient of $x^{20}$. Can you use the Binomial Theorem to do that?
Comment: Still seems like a lot to do by hand.
$(1-x^8)^5 = 1 - 5 x^8 + 10 x^{16} + $ (higher powers than $x^{20}$).  Multiplying by $x - x^8$ is no problem.  But then
divide by $1-x$ six times, or multiply by $(1-x)^{-6} = 1 + 6 x + \ldots + 53130 x^{20} + \ldots$?
Comment: @Robert, $(1-x)^{-6}=\sum{n+5\choose5}x^n$, so you'll wind up with a sum of 5 terms, each a small multiple of a binomial coefficient. If you want a number, you have to compute those binomials, but on homework many are happy with things like $14\choose5$ left unevaluated.
Answer: You could use dynamical programming.  Let $a(m,n)$ be the number of $m$-digit nonnegative integers with each digit 0 to 7 and the sum of digits is $n$.  Then $a(1,n) = 1$ for $0 \le n \le 7$, $0$ otherwise, and
$$a(m+1,n) = \sum_{d=0}^{\min(n,7)} a(m,n-d)$$
EDIT: That solution allows leading zeros.  If leading zeros are not allowed, take $a(1,0) = 0$ as well.
EDIT: Let $a(m,n)$ be as above in the version with leading zeros not allowed, and $b(m,n)$ the version with leading zeros allowed.  Then $a(6,20) = \sum_{k=0}^{20} a(3,k) b(3,20-k)$.
For $m = 1,2,3$ we make the following tables:
<code> n   a(m,n)              b(m,n)
       m=1     2     3     1     2    3
  0      0     0     0     1     1     1
  1      1     1     1     1     2     3
  2      1     2     3     1     3     6
  3      1     3     6     1     4    10
  4      1     4    10     1     5    15
  5      1     5    15     1     6    21
  6      1     6    21     1     7    28
  7      1     7    28     1     8    36
  8      0     7    35     0     7    42
  9      0     6    40     0     6    46
 10      0     5    43     0     5    48
 11      0     4    44     0     4    48
 12      0     3    43     0     3    46
 13      0     2    40     0     2    42
 14      0     1    35     0     1    36
 15      0     0    28     0     0    28
 16      0     0    21     0     0    21
 17      0     0    15     0     0    15
 18      0     0    10     0     0    10
 19      0     0     6     0     0     6
 20      0     0     3     0     0     3
</code>
Then (going down the $a(3,n)$ column and up the $b(3,n)$ column) your answer is
$$\eqalign{&0 \times 3 + 1 \times 6 + 3 \times 10 + 6 \times 15 + 10 \times 21 + 15 \times 28 + 21 \times 36 + \cr &28 \times 42 + 35 \times 46 + 40 \times 48 + 43 \times 48 + 44 \times 46 + 43 \times 42 + 40 \times 36 + \cr &35 \times 28 + 28 \times 21 + 21 \times 15 + 15 \times 10 + 10 \times 6 + 6 \times 3 + 3 \times 1 \cr}$$
Comment: I have no idea how you would solve that.
Comment: Probably not by hand, but easy in any computer language or spreadsheet.
Comment: This is a homework problem I must solve by hand.
Comment: Leading zeros are not allowed. 000001 is not a 6 digit number. It is the number 1.


What could be in the stud in my wall?

Question: I am trying to mount a floating shelf. I have located two studs, 16in apart. Drilled one hole just fine, and the wall plug fit perfectly.
When I drilled the other hole, my drill bit won't go more than ~0.5in.
I looked in the hole with a flashlight and it looks like metal inside? It almost looks like a metal hole. What could this be?

I need to drill about 1inch for the wall plug to fit. If the wall plug doesn't go all the way in, would it be alright to have it half inside the wall and half protruding? Is there a way I can secure the anchor regardless?
I'm not crazy about having to remove the first successful plug and fill in the hole and start again.
Comment: DO NOT PUT PLUGS INTO STUDS! Wall plugs, mollys, rawl plugs, whatever are made for mounting into _drywall_ when you _cannot_ find a stud in the proper location. If you have located studs and you can put screws into them, DO NOT USE ANY SORT OF PLUG, just use the screw!
Comment: If a wire or pipe runs through a stud, there is actually supposed to be a metal plate to prevent accidentally drilling into the stud. That matches the general nature of the problem, but I'm not sure how you would end up with a "metal hole", unless you managed to drill through it.
Comment: @Ruskes Would only work if it's *ferrous* metal, like steel.  If it were, say, aluminum, copper, etc., a magnet won't work.
Comment: What kind of wall are we talking about? Brick, cinderblock, poured concrete (with rebar) etc?
Comment: Also not sure what "plug" you are referring to. Normally you would use some sort of expanding anchor if you are *not* going into a stud, but if you are mounting directly on a stud then you use a screw through a mounting bracket into the stud.
Comment: The floating shelf came with expanding anchors (which is what I referred to as wall plugs). And I'm not entirely sure it's a metal hole, it just seems to be what that looks like from what I can see in the hole. :(
Comment: use magnet to find out if it is metal
Comment: @jess can you move the shelf over one stud spacing?  You'd have to fill this hole, but can continue using the first hole.
Answer: If you are going into studs, you do not want to use those expanding anchors. You just use regular wood screws. The anchors are only needed if you aren't using studs and putting it into just drywall. Studs are a lot stronger than drywall, so if you can use studs that's the better way to mount it.
It's hard to tell from the photo exactly what you hit. It could be a drywall screw with its head broken off. Or it could be part of a metal plate that is often installed in front of wires and pipes so you don't accidentally drill into them - though I doubt you would have easily drilled a hole into that without noticing it.
Comment: Thank you for your answer!! That helps ease my mind a little, and I will make sure not to use the expanding anchors in anything aside from drywall.
Answer: You probably hit a stud guard. They are designed to protect wires and pipes that are embedded in the stud. Depending on the length of the guard, you can move up or down to avoid it.
https://www.lowes.com/pd/AMERICAN-VALVE-3-in-x-1-1-2-in-Stud-Guard/1244107
Comment: 'No longer sold at Lowes' - never seen them in UK. Seem like a good idea, though.
Answer: When drilling into walls, of any sort, a 'stud finder' is an absolute necessity. You could be drilling through all sorts that you don't know about - as here.
A good stud finder will differentiate between metal, wood and crucially, live wires (or water pipes). Drilling through live wires isn't only dangerous, it's a real big job to repair them. As is water pipes. Messy, too!
Firstly, you don't use the expanding anchors to fix into studs. Studs are either wood or metal, both of which will happily take screws that fix through the plasterboard, into them.
It seems you've hit an unidentified item in the wall. If possible, unless you use a proper stud finder, drill a couple of smaller (much smaller) holes, left or right, near to where you could put an anchor. If that goes well, open up, and away you go. It could be a protective sheath over water or electricity - as Grant says, or the head of a nail/screw holding the stud to something. Either way, avoid like the plague. But whatever, find somewhere else a couple of inches away, and leave that area alone. And get a good stud finder!
Comment: If it is something nasty to drill into that is in the stud, usually better to move up or down to miss it, instead of right or left.
Comment: The vertical nasties are more on the side of a stud, than though a stud.  Change stud to wall then you would be right.  OP stated they trying to drill into a stud.
Comment: @crip659 - I've found that 'something nasty' could go vertically or horizontally, 60:40 or so. In UK live wires far more often go vertically. But once again, lack of location leaves things vague.
Comment: Thank you both!! I think I will try just a bit lower and if it happens again I'll consider it a metal plate and leave it alone/find somewhere else entirely.
Comment: @crip659 Nasties that penetrate a stud will go in the opposite direction of the stud.  Nasties that don't penetrate the stud will go in the same direction--but if you aim correctly you shouldn't be touching them in the first place.  Thus the only real concern is nasties in the cross direction.  I have never encountered a situation where there was a horizontal piece of wood I wanted to anchor to but it's not inherently impossible.

What could be in the stud in my wall?


How to set different width for different form in mat-horizontal-stepper

Question: I want to set different width for different form in mat-step.The content in first form to be as width of 400px and the second form content to be as width of 700px.
<mat-horizontal-stepper labelPosition="bottom" #stepper>
  <mat-step [stepControl]="firstFormGroup">
    <form [formGroup]="firstFormGroup">
      <ng-template matStepLabel>Fill out your name</ng-template>

 <mat-form-field>
        <input matInput placeholder="Last name, First name" formControlName="firstCtrl" required>
      </mat-form-field>

        <button mat-button matStepperNext>Next</button>

    </form>
  </mat-step>
  <mat-step [stepControl]="secondFormGroup">
    <form [formGroup]="secondFormGroup">
      <ng-template matStepLabel>Fill out your address</ng-template>

         <mat-form-field>
        <input matInput placeholder="Address" formControlName="secondCtrl" required>
      </mat-form-field>

        <button mat-button matStepperPrevious>Back</button>
        <button mat-button matStepperNext>Next</button>

    </form>
  </mat-step>
  <mat-step>
    <ng-template matStepLabel>Done</ng-template>
    You are now done.

      <button mat-button matStepperPrevious>Back</button>
      <button mat-button (click)="stepper.reset()">Reset</button>

  </mat-step>
</mat-horizontal-stepper>

But it is not working , Can anyone please help me how to achieve this.
Comment: I am not sure. It should take the specified width. If you're talking about the form-field not taking the entire width, then you need to add `.mat-form-field { width: 100% }` to your css.
Answer: Since only the visibility of the mat-step components are changing you should overwrite the width of the invisible ones.
Use the following code in the CSS file:
::ng-deep .mat-horizontal-stepper-content[aria-expanded="false"] {
  width: 0px !important;
}

After using this you can use different width sizes for every step.
Comment: Elegant solution to a most annoying problem. Thank you.


Moving bigquery data to Redshift

Question: I'm in need to move my bigquery table to redshift.
Currently I have a python job that is fetching data from redshift, and it is incremental loading my data on the redshift.
This python job is reading bigquery data, creating a csv file in the server, drops the same on s3 and the readshift table reads the data from the file on s3. But now the time size would be very big so the server won't be able to handle it.
Do you guys happen to know anything better than this ?
The new 7 tables on bigquery I would need to move, is around 1 TB each, with repeated column set. (I am doing an unnest join to flattening it)
Comment: Extra context: https://www.reddit.com/r/bigquery/comments/cbkkrc/moving_bigquery_data_to_redshift/
Comment: If your CSV is too big or is slowing down the process... can you subdivide or query your BQ source tables into smaller files or incremental files?
Answer: You could actually move the data from Big Query to a Cloud Storage Bucket by following the instructions here. After that, you can easily move the data from the Cloud Storage bucket to the Amazon s3 bucket by running:
<code>gsutil rsync -d -r gs://your-gs-bucket s3://your-s3-bucket
</code>
The documentation for this can be found here

Moving bigquery data to Redshift


Are all odd numbers coprime to powers of two?

Question: I need to pick a number $n$ which is co-prime to a number which is a power of two $m = 2^b$. It seems true to me that all odd numbers between 1 and $m$ will  be coprime to $m$, but I can't find a specific proof of this anywhere.
I have tested this with code up to a 32 bit power of two $1 < b < 32$, but that doesn't prove it's always true...
Comment: You cannot find a $2$ in the unique decomposition of any odd number by Fundamental Theorem of Arithmetic
Comment: Yes, that makes sense - I also needed to realise that powers of two would *only* have two as a prime factor.
Answer: Not just up to $m$.  All odd numbers will be coprime.
An odd number will not have $2$ as a prime factor.  A number $m = 2^b$ will only have $2$ as a prime factor.  So any odd number and any $m = 2^b$ will have no prime factors in common.  So they will be coprime.  QED.
Comment: Thanks, that makes sense.  I could see that odd numbers wouldn't have 2 as a prime factor, but I didn't go on to see that powers of two would *only* have two as a factor.
Answer: Think about it this way: in your typical computer, in an integer data type (signed or unsigned, regardless of word length), the least significant bit of an odd number is 1. Which means that if you divide an odd number by 2, you're going to need a real data type rather than an integer data type.
For example, 101 in binary (5 in decimal) divided by 10 (2) is 10.1 (2.5 in decimal). 101 divided by 100 (4) is 1.01, 101 divided by 1000 (8) is 0.101... you get the idea.
I don't know much about how computers represent non-integral numbers, but the point here is that if you divide an odd number number by a power of 2 (with a positive integer exponent), the result of that operation can't be held in an integer data type.

EDIT: For some strange reason I mistakenly thought the commenter was someone other than the asker, so I felt no urgency to respond. I only aimed to provide a different angle to look at this from, not give a rigorous proof.
But that's still easily done while looking at the bits of an integer data type. If $n$ is an odd number greater than 1, and $m$ and $\alpha$ are both positive integers, which may be even or odd, we seek to find $mn = 2^\alpha$. Let's say $n = 2k + 1$, where $k$ is a positive integer.
If $m$ is also odd, let's express it as $2j + 1$, with $j$ is also a positive integer. Then $mn = 4kj + 2k + 2j + 1$, an odd number. So $m$ must be even after all, so $m = 2j$. Then $mn = 4kj + 2j$, an even number, which is what we want. But $mn$ has at least two on bits, since $4 > 2$ and $kj > j$, but $2^\alpha$ has only one on bit, followed by $\alpha$ off bits.
Comment: That's a cool way of looking at it.  I find the prime factors explanation easier to understand, but algebra + binary does the job too!
Comment: It's certainly true that a binary representation makes oddness very obvious - the lsb is always one.  However, doesn't answer the question of whether odd numbers are coprime to powers of two!
Comment: I've edited, hopefully that's a bit clearer, pun intended.
Answer: Yes, that is correct, since the only prime factor(s) of any number $m = 2^b$ is $2$, while any odd number $n$ does not have $2$ as a prime factor. Hence, such $m$ and $n$ share no prime factors, and are therefore co-prime.
Comment: Also thanks for an equally good explanation as fleabloods.
Comment: And two minutes before mine....
Comment: Well, you were both impressively fast!  I thought I might get something back in a day or two!
Comment: @MattPalmer Typically, you'll get a response within the hour, and indeed sometimes in just minutes ... But if you haven't gotten anything in a day, chances are you might not get anything at all.


Phpunit - mocking SoapFault->getMessage()

Question: I'm connecting to a third party service using SOAP. This service will return SoapFaults some times. Because this is expected, I want to test this, by mocking the SoapFaults. There are five standard SoapFaults it will return.
Here is the start of a real SoapFault:
object(SoapFault)#7 (11) {
  ["message":protected]=>
  string(19) "{ 'INVALID_INPUT' }"

I am interested in this message. In my code I use $e->getMessage().
catch (SoapFault $e)
{
    // Catch any Soap faults and convert to an error message
    switch ($e->getMessage())
    {
        case "{ 'INVALID_INPUT' }":
            $this->addError(self::INVALID_INPUT);
            return FALSE;

but I cannot figure out how to mock the SoapClient response. The SoapClient object doesn't appear to take in any input to set the message, and the method getMessage() is final, so I can't mock it.
Any ideas would be appreciated. Thanks.
Comment: In case it's helpful: `new SoapFault(0, 'put your message here');` will set the `getMessage();` return value.
Answer: There should be no need to mock SoapFault. You can just use the real exception (usually exceptions are not mocked for testing as they are Value objects) and mock the SoapClient to throw your prepared exception.
By doing so you get around not being able to mock getMessage because you build the SoapFault in your test case like shown below.
As I've had troube figuring out what exactly your problem was i build a little test case to make sure it works out. As it was there already i guess the code explains it better than i could.
Test example:
<?php

class SoapFaultTest extends PHPUnit_Framework_TestCase {

    public function testSoapFault() {
        $soapFault = new SoapFault("test", "myMessage");
        $soapClient = $this->getMockBuilder('SoapClient')
            ->setMethods(array('methodOnService'))
            ->disableOriginalConstructor()
            ->getMock();

        $soapClient->expects($this->once())
            ->method('methodOnService')
            ->will($this->throwException($soapFault));

        $x = new Consumer();
        $this->assertSame(
            "InvalidInput",
            $x->doSoapStuff($soapClient)
        );
    }

}

class Consumer {

    public function doSoapStuff(SoapClient $soapClient) {
        try {
            $soapClient->methodOnService();
        } catch(Exception $e) {
            if($e->getMessage() == "myMessage") {
                return "InvalidInput";
            }
        }
    }
}

Outputs:
 phpunit SoapFaultTest.php
PHPUnit 3.6.3 by Sebastian Bergmann.

.

Time: 0 seconds, Memory: 3.75Mb

OK (1 test, 2 assertions)

The assertion is kept simple but you should be easily able to adapt this for your way of handling errors
Answer: Next to what edorian answered, there should be no need to test that a third-party component works as announced. Don't write tests for components you don't have written the code (or for which you can not write code, if they are broken, they're broken and you're lost).
Just test that your code works as expected. You should be able to mock your own code.
Example: Your code will always break if code or data of it is missing, e.g. files of your application get partially deleted under circumstances. Do you write tests for such scenarios? Naturally not.
You can however write yourself an integration suite that automatically tests if certain remote dependencies provide the expected interface and responses. But I would put that suite apart from your testsuites that cover your own code-base.
Additionally you can create your own assertion functions that can be used in each testcase, for example one for SoapClient Exception Message.
Comment: I was just expecting him to mock out the SoapClient call anyways (as testing again the remote service and then mocking a fault would be strange to me) but you are about the decoupling needed. I was just assuming that all he was testing for is that his code handles faults on the other side right and needs help producing those for testing :)
Comment: @edorian: You're right, reading your answer does actually suggest to not test the remote component but only test how the own code reacts to possible input values from the remote access layer.
Answer: I want to thank hakre for his comment. This is exactly what I wanted.
The SoapFault extends Exception, which expects an input of ($message, $code, $previous).
But the SoapFault expects ($faultcode, $faultstring, $faultactor, $detail, $faultname, $headerfault).
This is what threw me.
The $faultstring maps to the exception message.
So to mock it, I did:
$mock_soap->expects($this->once())
                         ->method('checkVat')
                         ->will($this->throwException(new SoapFault('a', "Error Message")));

And in my real code
$e->getMessage() now returns 'Error Message'


How to make SVG the same size as its internal  element?

Question: I have an svg of an eye, and am using it as an icon.
This svg has a <switch> element inside that contains all the path drawing stuff. When you inspect this <switch> element in the javascript console it shows its dimensions as 700px X 500px. The SVG containing it, however is 707px X 707px.
I.e. The SVG has a load of blank space at the top.
I would like to know how to make the SVG the same size as the element contained in it. I need to do this because I want to add a bootstrap tooltip to the image, but the tooltip gets placed much too high above the image because it is padded with all this white space!
I'm new to this SVG stuff - I tried changing the size of the viewport on the SVG, but that just cut the bottom off the image, and left the blank space at the top.
Here is the code for the SVG image:
<svg xmlns:x="http://ns.adobe.com/Extensibility/1.0/" xmlns:i="http://ns.adobe.com/AdobeIllustrator/10.0/" xmlns:graph="http://ns.adobe.com/Graphs/1.0/" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve">
  <switch>
    <foreignobject requiredExtensions="http://ns.adobe.com/AdobeIllustrator/10.0/" x="0" y="0" width="1" height="1"></foreignobject>
    <g i:extraneous="self">
      <g>
        <path d="M98.066,57.193c-0.177-0.209-3.629-4.26-9.421-9.081l9.468-11.834l-4.226-3.381l-9.502,11.878     c-0.088-0.065-0.172-0.13-0.261-0.195c-4.013-2.935-8.08-5.37-12.147-7.306l7.502-15.005l-4.841-2.42L66.99,35.146     c-3.896-1.456-7.768-2.423-11.569-2.904l-4.959-17.064l-5.196,1.51l4.418,15.202c-5.41,0.042-11.018,1.142-16.674,3.256     l-7.648-15.297l-4.841,2.42l7.502,15.005c-4.067,1.936-8.134,4.371-12.147,7.306c-0.089,0.065-0.172,0.13-0.261,0.195     L6.113,32.897l-4.226,3.381l9.468,11.834c-5.792,4.82-9.244,8.872-9.421,9.081L0.456,58.94l1.478,1.747     c0.219,0.259,5.455,6.406,13.942,12.613C27.234,81.608,39.034,86,50,86s22.766-4.392,34.124-12.699     c8.487-6.207,13.723-12.354,13.942-12.613l1.478-1.747L98.066,57.193z M71.647,58.94c0,11.514-9.036,20.954-20.388,21.608     c-0.419,0.014-0.837,0.039-1.259,0.039s-0.84-0.025-1.259-0.039C37.389,79.894,28.353,70.454,28.353,58.94     c0-11.936,9.711-21.646,21.647-21.646c0.422,0,0.84,0.025,1.259,0.04C62.611,37.988,71.647,47.427,71.647,58.94z M7.666,58.941     c3.102-3.247,10.491-10.35,20.2-15.537c-3.098,4.401-4.925,9.757-4.925,15.536c0,5.773,1.823,11.126,4.916,15.524     c-3.277-1.745-6.214-3.656-8.681-5.455C13.808,65.097,9.762,61.139,7.666,58.941z M80.824,69.01     c-2.467,1.798-5.404,3.71-8.681,5.455c3.093-4.398,4.916-9.751,4.916-15.524c0-5.773-1.823-11.125-4.916-15.523     c3.277,1.745,6.214,3.656,8.681,5.454c5.37,3.914,9.415,7.872,11.511,10.069C90.24,61.138,86.193,65.096,80.824,69.01z"></path>
        <path d="M39.179,58.94c0,5.98,4.845,10.825,10.818,10.825c5.98,0,10.825-4.845,10.825-10.825c0-5.98-4.845-10.825-10.825-10.825     C44.024,48.114,39.179,52.96,39.179,58.94z M45.941,61.646c-2.239,0-4.056-1.817-4.056-4.055c0-2.246,1.817-4.063,4.056-4.063     c2.239,0,4.056,1.817,4.056,4.063C49.997,59.829,48.18,61.646,45.941,61.646z"></path>
      </g>
    </g>
  </switch>
</svg>

I've included it here in a PLNKR so you can see what is happening:
http://plnkr.co/edit/gw1k0vQGon3dxUOVvuDB
Here is the current look of the picture, with new colours for clarity:

Here is how I would like the image to look (again - ignore the poxy colours...):

I want to strip all the blank space from the top and the bottom.
Any ideas?
Comment: switch elements always autosize to their contents. BTW SVG is case sensitive so it's foreignObject an not foreignobject.
Comment: dont know how that got changed to a small 'O'.... plnkr updated
Comment: so how do i change the size of the SVG to match the  element?
Comment: Measure it using getBBox and then set the size from that.
Comment: I'm pretty unlearned about svgs.... Is there a way i do it in the  tag without having to do it programaticaly?
Comment: Sure, edit the file and make the width and height whatever you want.
Comment: I put the width and height in the  tag, but when I do that, it proportionally shrinks the  element, which is not what i need.....
Comment: Also decrease the viewBox values (or remove it entirely).
Comment: That doesn't work either - it still just cuts the bottom of the eye and leaves the top blank.... you can see the results in the update plnkr: http://plnkr.co/edit/gw1k0vQGon3dxUOVvuDB
Comment: Hi Robert, I've update the question to include the pictures showing the problem and the desired outcome.... hope this help clarify things...
Answer: Like so? I've added a rect background so it's easy to see the extent of the SVG. All I've done is modify the viewBox so that values match the shape extents.

      <svg viewBox="0 14 100 73" width="100" height="71" xmlns:x="http://ns.adobe.com/Extensibility/1.0/" xmlns:i="http://ns.adobe.com/AdobeIllustrator/10.0/" xmlns:graph="http://ns.adobe.com/Graphs/1.0/" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" enable-background="new 0 0 100 100" xml:space="preserve" overflow="hidden">
        <rect width="100" height="100" fill="lightblue"/>
        <switch>
          <foreignObject requiredExtensions="http://ns.adobe.com/AdobeIllustrator/10.0/" x="0" y="0" width="1" height="1"></foreignobject>
          <g i:extraneous="self">
            <g>
              <path d="M98.066,57.193c-0.177-0.209-3.629-4.26-9.421-9.081l9.468-11.834l-4.226-3.381l-9.502,11.878     c-0.088-0.065-0.172-0.13-0.261-0.195c-4.013-2.935-8.08-5.37-12.147-7.306l7.502-15.005l-4.841-2.42L66.99,35.146     c-3.896-1.456-7.768-2.423-11.569-2.904l-4.959-17.064l-5.196,1.51l4.418,15.202c-5.41,0.042-11.018,1.142-16.674,3.256     l-7.648-15.297l-4.841,2.42l7.502,15.005c-4.067,1.936-8.134,4.371-12.147,7.306c-0.089,0.065-0.172,0.13-0.261,0.195     L6.113,32.897l-4.226,3.381l9.468,11.834c-5.792,4.82-9.244,8.872-9.421,9.081L0.456,58.94l1.478,1.747     c0.219,0.259,5.455,6.406,13.942,12.613C27.234,81.608,39.034,86,50,86s22.766-4.392,34.124-12.699     c8.487-6.207,13.723-12.354,13.942-12.613l1.478-1.747L98.066,57.193z M71.647,58.94c0,11.514-9.036,20.954-20.388,21.608     c-0.419,0.014-0.837,0.039-1.259,0.039s-0.84-0.025-1.259-0.039C37.389,79.894,28.353,70.454,28.353,58.94     c0-11.936,9.711-21.646,21.647-21.646c0.422,0,0.84,0.025,1.259,0.04C62.611,37.988,71.647,47.427,71.647,58.94z M7.666,58.941     c3.102-3.247,10.491-10.35,20.2-15.537c-3.098,4.401-4.925,9.757-4.925,15.536c0,5.773,1.823,11.126,4.916,15.524     c-3.277-1.745-6.214-3.656-8.681-5.455C13.808,65.097,9.762,61.139,7.666,58.941z M80.824,69.01     c-2.467,1.798-5.404,3.71-8.681,5.455c3.093-4.398,4.916-9.751,4.916-15.524c0-5.773-1.823-11.125-4.916-15.523     c3.277,1.745,6.214,3.656,8.681,5.454c5.37,3.914,9.415,7.872,11.511,10.069C90.24,61.138,86.193,65.096,80.824,69.01z"></path>
              <path d="M39.179,58.94c0,5.98,4.845,10.825,10.818,10.825c5.98,0,10.825-4.845,10.825-10.825c0-5.98-4.845-10.825-10.825-10.825     C44.024,48.114,39.179,52.96,39.179,58.94z M45.941,61.646c-2.239,0-4.056-1.817-4.056-4.055c0-2.246,1.817-4.063,4.056-4.063     c2.239,0,4.056,1.817,4.056,4.063C49.997,59.829,48.18,61.646,45.941,61.646z"></path>
            </g>
          </g>
        </switch>
      </svg>
Comment: Thats perfect Rob! Looks like I was missing the '14' element of the viewbox... Muchas Gracias...


Using Same Stored Procedure for Inserting List of Values and Query Results

Question: I have a stored procedure to insert a row, with a list of values which came as input parameters, into a table (tmp).
This table mirrors another table (data), and I'm looking for a way to use the same SP to insert a row from data into tmp.
I've seen Pass result of a query into stored procedure, but I can't put INSERT in a UDF.
Is there an easy way, not requiring

a query which puts all the values into variables and sends the variables?
a table-typing or other additions to our already-too-full database

Edit The desired result would be a way to write something like
EXEC sp_insert (SELECT c1,c2,c3 FROM data)

Comment: I guess I don't understand the question, it sounds like you just need to do an INSERT..SELECT from data to tmp.
Comment: Can you please be a little more explicit / clearer with exactly what you are trying to do? What is stopping you from inserting into `tmp` directly from an select from `data`?
Comment: A trick we used to do a few jobs ago was to have the stored procedure insert from a temp table, so instead of passing in parameters you have it check if the temp table exist and if it does insert what is in it. This way you can choose either the data table as source or some other  source
Comment: So you have an SP that accepts a bunch of parameters and inserts them into table `tmp`.  And you want this same SP to insert a row into `tmp` that is selected from `data` instead of inserting the passed-in parameters?  1) is that correct?  2) how will the SP know whether it should insert the passed-in parameters or insert a row that is selected from `data`?
Comment: @DeadZone, 1. correct, 2. that's the question, or, if I can pass it in a way that he'll think it's parameters
Comment: Let me elaborate on question #2... Is the SP supposed to determine (use some intelligence and decide) what to do, or is the caller supposed to tell (dictate to the SP) the SP what to do?  If the latter, simply add a `bit` parameter to your SP to toggle between inserting parameter values and inserting selected rows.  If the former, then wrap your SP in a big IF statement... If X then Insert parameters ELSE Insert from `data`.  (If there's something we're all missing, please elaborate on where the hang-up lies.)
Comment: @deadzone, neither. I've actually been hoping the SP could be oblivious to the whole thing
Comment: I think you're going to need to edit your question to be more explicit about the exact nature of the problem.  I don't think it's clear what you're looking for.
Comment: I've added to the question. It's similar to what appears in the linked question
Comment: `EXEC sp_insert (SELECT c1,c2,c3 FROM data)` you can't get this because `EXEC` allows only `value/@variable/DEFAULT`. Without using variable to store temporary result it is not possible to use syntax like that.
Answer: Maybe you can use variable table as the parameter for the SP (search for this)
It needs to define user defined table type , but I'm using this method.
Table used as a parameter can get values from inserting or selecting from other table.
alter procedure sp_insert
@table your_table_type readonly
AS
BEGIN
--here you take a row (maybe the only one) from @table and insert it to TMP
END

Comment: Welcome to SO! Thanks for your answer, it's written well, but I specified I was looking for an answer not using this option. Keep up the good work.


Is using a strong named assembly for Plug In secure?

Question: I was searching on way to prevent an unknown party from attaching their own Plug In containing malicious code into my application. And I ran across this post
.NET Assembly Plugin Security
It suggests to Strong Name the assembly and check it is strong named with the expected key on load.
However, when I look at the MSDN documentation regarding Strong Named Assemblies at this site
Strong-Named Assemblies
There is a Caution that says
Do not rely on strong names for security. They provide a unique identity only.
What does this mean? What security are they referring to, and is this relevant to the answer in the above stack overflow link I provided?
Answer: It's an interesting comment.
From what I understand a signed assembly indicates
1) it has been signed with a certain key and
2) is could not have been modified after signing
On point 1, the security of the key is important as anyone with the key could modify and re-sign the assembly.
On point 2, I have seem an example online of a successful modification of an assembly while still passing the strong name verification. It was not trivial.
So technically correct, you can use this to verify identity but not necessarily security - or rather the difference between Authentication (the plugin was signed and not tampered with) versus Authorization (the code itself is authorized to do a certain action).
Authentication versus Authorization


Compilation failed in require - BEGIN failed

Question: I started using Padre and while working on a particular program which works just fine when run from the command line, Padre shows a Compilation failed in require error message suggesting that there is a problem in BEGIN and I do not have a BEGIN block in my module.
So if someone could shed some light on what are the possible scenarios that this could happen. The module that is causing the error is over 500 lines of code, so don't think it is wise to paste all that.
Sometimes I wonder why I chose an IDE to cause me more (perhaps unnecessary) grief :-)
Thanks a lot.
Answer:  use Foo;

is short for
BEGIN {
   require Foo;
   import Foo;
}

Anyway that error message isn't noteworthy. It means that "I usually try to find all there errors, but I can't this time. Fix the earlier errors first." So what error did you actually get?
Comment: Well, the problem is that when I open the Module in Padre, there is only two `uninitialized value` warnings and there is no other error in the main script either. Thanks Anyway. I suppose the debugger is getting confused because the actual script is supposed to run on a Solaris box and I am trying to emulate the environment in my windows PC just for the sake of running Padre and I am missing a module somewhere... Better be content to Vim over Putty.
Comment: The message you gave will never ever happen without another fatal error message, no matter which OS you use. Now, it could be that's a bug in Padre that's hiding it...
Comment: Found the problem. One of the used modules in my module calls getpwuid which is not available on windows, of course. The weird part was that it wasn't reporting it until I exlicitly put the `use TheModule` inside a BEGIN block. I suppose your clarification helped in a way. Thanks
Comment: huh? How odd because `use TheModule;` is the same as `BEGIN { require TheModule; import TheModule; }`. It actually does create a BEGIN block internally!
Comment: That's why I didn't figure it out in the first place. The actual error was in TheModule.pm and the IDE was not reporting it, but the same IDE was reporting it when it was used in another script. I checked it over and over again. Here: http://imageshack.us/photo/my-images/607/scr1h.png/ and http://imageshack.us/photo/my-images/3/scr2vq.png/. Check the Syntax Check window in both screenshots.
Comment: I see you got the actual error message when you got the BEGIN failed message, like I said you should have gotten. Now, it would be nice if it showed an error on the `use` line (like EPIC, the Perl plugin for Eclipse does), but that's the first time this has come up in this conversation.
Comment: I have used EPIC. I found PADRE to be faster. Anyways, I am not even sure if it is a Padre thing or my error somewhere. Thanks for all your help.


Efficiently accessing 2 array of structs in a loop

Question: I have following 2 array of structs, and a container class:
[Serializable]
public struct Pointer {

    public byte State;

}

[Serializable]
public struct Data {

    public uint Hash;
    public byte SomeIndex;
    public byte SomeMoreIndex;
    public byte SomeFurtherIndex;

}

[Serializable]
public class Grid {

    public Pointer[] Cells;
    public Data[] CellData;

}

And I intend to loop them over as following:
int index = 0;
for (var i = 0; i < Cells.Length; i++) {
    if (Cells[i] != 0) {
        // access CellData[index], and do more work
        index++;
    }
}

I know how CPU cache miss affects performance on a basic level, so I try to access these 2 arrays in order. But my questions are:

Since we are accessing 2 arrays interleavingly: Does it nullify the performance benefit of sequential memory access?
If not, how does CPU cache work with these sort of cases?
What if inside the loop, after reading CellData[index], I use its Hash to access a Dictionary<Hash, ItemClass>, does it further complicate performance of the loop itself?
I choose to split 1 struct into 2 to save some memory (and I could have used byte[] instead of Pointer[]), as the grid can be quite big and potentially sparse, is it a fair trade-off?
Comment: This sounds more like a question for https://codereview.stackexchange.com
Comment: Could you explain how you're saving memory by splitting structs? Otherwise it's a complicated matter but no, using two arrays doesn't nullify it. It may not be as effective (*may*) but there's still cache around. But it all depends on what else is being done in the core/group of cores etc etc etc.
Comment: @SamiKuhmonen `Pointer[]` is a representation of cells on grid, and cells can be empty (= 0), which means I don't need to read `Data[]`, if I put Data in the same struct as Pointer, then they are just stored as default value. Note that `Pointer[]` and `Data[]` don't have the same Length.
Comment: I think it's not hard to compare the performace between interleavingly and orderly accessing, Have you do it?
Answer: Elements within the same 64B line will still have the caching benefits if the recurrence is fast enough (i.e. "more work" does not thrash the cache).
Elements across lines should still enjoy the benefit of HW prefetching if the arrays are on distinct pages.
Using the Hash field will create data dependency and incur a penalty of course. This is a common A[B[i]] problem and there are some academic prefetchers addressing it (e.g., IMP), but nothing in commercial CPUs to the best of my knowledge. Existing "sequential" HW prefetching should mitigate most of it if it runs far enough ahead to prefetch the Hash data enough iterations before it's actually used, in which case the penalty will be reduced into two back-to-back L1 accesses (or whichever cache level implements that prefetcher - usually the L1 should have one).
Note that the effect on performance is not direct, since different iterations are independent, but memory latency will translate into memory BW limitation once you saturate your miss-handling buffers.


Finding the region bounded by a circle and rosetta leaf

Question: I want to find the following region:
$R$ is the region bounded by the circle of radius $a$ and and the center at the origin and the rosetta leaf $r=2a\cos(\theta)$ with $x \ge 0$ and $r \ge a$.
So, I draw the region. There are two parts,  one is above and the other one is below the $x-$axis. I try to write one integral and then multiply it by $2$ to find solution.
Here is what I wrote:
$\displaystyle 2\int_{0}^{\frac{arc\cos(1/2)}{2}} \int_a^{2a\cos(2\theta)}rdrd\theta$
Is it correct, any hints would be helpful. Thank you.
Comment: In you question you ask about $r = 2a\cos\theta$, but in your integral you use the expression $2a\cos(2\theta)$. Is one of these a typo?
Comment: Where have you seen this strange name "Rosetta leaf" ?
Answer: If the second curve has equation $r=2a\cos\theta$, it's a circle.

The two circles intersect when
$$
    2a \cos\theta = a \implies \cos\theta = \frac{1}{2} \implies \theta = \pm\frac{\pi}{3}
$$
Therefore the area of the region is
\begin{align*}
    \int_{-\pi/3}^{\pi/3} \int_a^{2 a\cos\theta} r\,dr\,d\theta
    &= 2 \int_{0}^{\pi/3} \int_a^{2 a\cos\theta} r\,dr\,d\theta \\
    &= \int_{0}^{\pi/3}\left. r^2 \right|_a^{2 a\cos\theta} \,d\theta \\
    &= \int_{0}^{\pi/3}\left(4a^2\cos^2\theta - a^2\right)\,d\theta \\
    &= a^2 \int_{0}^{\pi/3}\left(2(1+\cos2\theta) - 1\right)\,d\theta \\
    &= a^2 \int_{0}^{\pi/3}\left(1+2\cos2\theta\right)\,d\theta \\
    &= a^2 \left[\theta+\sin 2\theta\right]_{0}^{\pi/3}\\
    &= a^2 \left(\frac{\pi}{3} + \frac{\sqrt{3}}{2}\right)
\end{align*}
If the second curve has equation $r=2a\cos2\theta$, it's a rose of four leaves.
 The curves intersect when
$$
    a = 2a \cos2 \theta \implies \cos2 \theta = \frac{1}{2}
$$
The portion in the right half-plane has three components.  Let's find the area of the largest component.  That is the portion with $-\frac{\pi}{6} \leq \theta \leq \frac{\pi}{6}$.  Its area is
$$
    A = 2 \int_0^{\pi/6}\int_0^{2a\cos2 \theta} r\,dr\,d\theta
$$
Substituting $\phi = 2\theta$ and $d\phi = 2d\theta$ transforms this integral into the previous one.  So
$$
    A = \frac{1}{2}\cdot a^2 \left(\frac{\pi}{3} + \frac{\sqrt{3}}{2}\right)
      = a^2 \left(\frac{\pi}{6} + \frac{\sqrt{3}}{4}\right)
$$
Comment: In the first case diameter is $2a$, not $3a$
Comment: In the first case of two intersecting circles I don't think the answer is right. I can't work out where you went wrong but https://math.stackexchange.com/a/402891/5011 shows the answer I get by a geometric approach (rather than using integrals).
Comment: @Narasimham: If you are talking about the graph then a = 1.5 in those graphs (I don't know why but it is).
Comment: Both circles need to be scaled down
Comment: @Chris Are we talking about the same region?  The linked question seems to ask about the region which is inside both circles.  As I read the OP's question it seems to ask about the region outside the center (blue) circle but inside the green circle.
Comment: @Narasimham: I used a Desmos applet with a parameter $a$.  For purposes of the diagram I set $a$ to be 1.5.  If I get a chance I'll redo it, display the parameter, and provide a link.
Comment: @MatthewLeingang: Ah yes, you may be right. My bad! I think I saw two intersecting circles and just assumed. :)
Answer: Apologies for the poor quality sketch. For a simple geometrical situation direct computation may be ok.
The "rosetta" or 2 leaved rose of two circles  passes through origin with center on x-axis. Due to equality of side and circle radius we have a regular hexagon.

The pointed areas between regular hexagon and circle have area
$$ A_{needle}=(\pi a^2- \frac{\sqrt3}{4} a^2 \cdot 6) \cdot \frac{1}{6}$$
Area above x-axis has areas as a semi-circle radius $a$ - sector area radius $a$ /6 - needle area
$$ A = 2 (\pi a^2/2 - \frac16 \cdot \pi a^2 - [\frac{\pi a^2}{6} -\frac{\sqrt3}{4} a^2])= \frac{\pi a^2}{3} + \frac{\sqrt3}{2} a^2 $$
after doubling it for required area.


Method signature clashes when class and its parameters extends from the same trait

Question: Apologies for the slightly vague title, it was difficult to try to summarize my problem into a single-liner. Hoping that the following snippets of codes explains better my intentions.
Let's start by introducing a trait for all things that are Reduceable:
trait Reduceable[A] {
  def reduceWith(other: A): A
}

Examples of such Reduceable things can be counters as such:
case class GenderCounter(male: Int, female: Int)
    extends Reduceable[GenderCounter] {
  override def reduceWith(other: GenderCounter): GenderCounter =
    GenderCounter(male + other.male, female + other.female)
}

case class FruitCounter(apples: Int, oranges: Int)
    extends Reduceable[FruitCounter] {
  override def reduceWith(other: FruitCounter): FruitCounter =
    FruitCounter(apples + other.apples, oranges + other.oranges)
}

GenderCounter(5, 10) reduceWith GenderCounter(4, 11)
// res: GenderCounter = GenderCounter(9,21)

A class with the above counters as parameters can also be itself a Reduceable
case class CompoundCounter(c1: GenderCounter, c2: FruitCounter)
    extends Reduceable[CompoundCounter] {
  override def reduceWith(
    other: CompoundCounter)
    : CompoundCounter = CompoundCounter(
    c1 reduceWith other.c1,
    c2 reduceWith other.c2
  )
}

CompoundCounter(GenderCounter(5, 10), FruitCounter(11, 2)) reduceWith CompoundCounter(GenderCounter(5, 10), FruitCounter(11, 2))
// res: CompoundCounter = CompoundCounter(GenderCounter(10,20),FruitCounter(22,4))

However, a problem arises when I try to introduce a generic Reduceable class where its parameters are also generic Reduceables
case class CollectionReduceable[A, B](r1: Reduceable[A], r2: Reduceable[B])
    extends Reduceable[CollectionReduceable[A, B]] {
  override def reduceWith(
    other: CollectionReduceable[A, B])
    : CollectionReduceable[A, B] = CollectionReduceable(
    r1 reduceWith other.r1,
    r2 reduceWith other.r2
  )
}

// error: type mismatch
// found   : other.r1.type (with underlying type Reduceable[A])
// required: A
//           r1 reduceWith other.r1,

// Desired outcome: same as CompoundCounter

I get the origin of the error message - its because the reduceWith signature of the trait calls for other: A, but if I change it then GenderCounter and FruitCounter will break. What can change I to achieve my intended outcome? Thanks!!
Comment: Is it possible to phrase the question and title better for it to be more easily found by future user?
Answer: Try
case class CollectionReduceable[A <: Reduceable[A], B <: Reduceable[B]](r1: A, r2: B) extends Reduceable[CollectionReduceable[A, B]] {
  override def reduceWith(other: CollectionReduceable[A, B]): CollectionReduceable[A, B] =
    CollectionReduceable(
      r1.reduceWith(other.r1),
      r2.reduceWith(other.r2)
    )
  }

CollectionReduceable(GenderCounter(5, 10), FruitCounter(11, 2)) reduceWith CollectionReduceable(GenderCounter(5, 10), FruitCounter(11, 2))
// CollectionReduceable(GenderCounter(10,20),FruitCounter(22,4))

Comment: can you please add some explanation to your answer ? What was the problem and how your answer solve this?


c# RDLC new Columns in ASPNET Forms page are empty

Question: I have a ASPNET Forms page that render a .rdlc report.
My intention is to add 2 new columns in the SQL procedure used from report to show in page.
So, I update the procedure adding the new columns with success.

I chance the existing .xsd adding the 2 new columns with teh same name as the procedure SQL result.

So, I went to my .rdlc and I recriate my DataSet in Report Data

In my .rdlc[Design] I add the 2 new Columns without problem.

When I run my website and render the .rdlc the page All columns are displayed with values except the new 2 columns.

My aspx and my aspx.cs don't suffer modifications because I didnt change everything like ReportPath, rsweb:ReportViewer ,  DataSourceId="ObjectDataSource1" .
I didn't understand why the new columns are empty and the others are returning data.
Some more information:
The aspx report bind data is devirated from the code above:
    <asp:Panel...>
                    <rsweb:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Verdana" Font-Size="8pt" HyperlinkTarget="_blank"
                        Width="816px" ShowCredentialPrompts="False" ShowDocumentMapButton="False" ShowParameterPrompts="False" InteractiveDeviceInfos="(Collection)">
                        <LocalReport ReportPath="The path of my .rdlc file" EnableExternalImages="True" EnableHyperlinks="True">
                            <DataSources>
                                <rsweb:ReportDataSource DataSourceId="ObjectDataSource1" Name="My DataSet name in Report Data" />
                            </DataSources>
                        </LocalReport>
                    </rsweb:ReportViewer>
                </asp:Panel>

 <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" OldValuesParameterFormatString="original_{0}"
                    SelectMethod="[My DAO Method]" TypeName="[My DAO Class]">
                    <SelectParameters>

The [My DAO Method]" and "[My DAO Class] are working on page and returnig a list of My target Object
IList<TheObjectTarget>

I get in the Sql Profiller the Procedure that executes in [My DAO Method] with success in get the new columns.
The execution of the Report happening inside click event when I set the parameters, turns it visible, made a LocalReport.Refresh and enable Panel:
 ReportViewer1.LocalReport.SetParameters(param);
                ReportViewer1.Visible = true;
                ReportViewer1.LocalReport.Refresh();
                MyPanel.Visible = true;

Does anyone know?
Comment: At your C# code behind, how are you querying the database?
Comment: Trejo, I add new section called "Some more informations" explaining the .aspx and aspx.cs behavior.
Answer: I had the same issue but I was using LINQtoSQL classes (dbml) and I had to refresh the reference to my stored procedure (deleted it and added it again from the dbml class). Maybe you'll have to do the same with your DataSource.


How can I fix "NT_STATUS_LOGON_FAILURE" error when mounting using cifs?

Question: I've recently upgraded my station to 13.04 and all mounts I had on /etc/fstab stopped working. I can't even mount them at terminal (using mount -t cifs) through smbclient or nautilus. I always get NT_STATUS_LOGON_FAILURE.
Provided nothing has changed at the server, I assume some configuration has changed in the packages of 13.04. Maybe password encryption, maybe port? I have just spent 10 hours looking for a solution and, since I have a serious time retrain, I am considering rolling back to 12.10. Could someone give a clue where to find it?
Thanks all.
Comment: I found the answer in another topic [[link here](http://askubuntu.com/questions/285874/how-can-i-mount-cifs-shares-in-kubuntu-13-04)], using the sec=ntlm option for cifs.mount
Answer: Had a similar problem. I found that adding nounix as an option in the fstab file allow for the network shares to be accessed.
Comment: Welcome to Ask Ubuntu! The "My problem now is..." part is a new question. Please use the "Your Answer" section only for actual answers. If you have another question, please ask it by clicking the [Ask Question](http://askubuntu.com/questions/ask) button. I have removed the question now.


Scriptable 2D platformer

Question: Does anyone know a highly scriptable 2D platformer? one that allows creation of entirely new characters, modification of the behavior of the already existing characters, etc. It doesn't really matter if it free or not or if it is or isn't indie.
Comment: This question is considered game-recommendation, and due to it's subjective nature it is considered off-topic on our site as stated in our [FAQ](http://gaming.stackexchange.com/faq). You are welcome to ask in our [chat](http://chat.stackexchange.com/rooms/35/the-bridge) though, where you may find users able to help you.
Answer: I played Cortex Command a couple of hours and figured out that there is a lot you can customize/create in the included editors maybe do some research on that? Though I must say it isn't the simplest game to play.

Scriptable 2D platformer


Images (smilies) in a TextView in a ListView

Question: So I've been searching a long time for this, trying out a lot of stuff, but it doesn't seem to work... I've recently started programming for Android, and I'm making a chat-application for a website.
Now I've come to a point where I want to add smileys/emoticons to the application, and by searching I found these websites:
http://blog.stylingandroid.com/archives/177
http://www.coderanch.com/t/488673/Android/Mobile/styling-items-ListView
My code:
private void updateList()
{
    ListView list = this.getListView();

    if(!parsedData.isEmpty())
    {
        ArrayAdapter<String> adapter = new MyAdapter(this, R.layout.list_item, parsedData);

    list.setAdapter(adapter);
    list.setTextFilterEnabled(true);
    }
}

class MyAdapter extends ArrayAdapter<String>
{
    ArrayList<String> mStrings;
    LayoutInflater mInflater;

    public MyAdapter(Context context, int textViewResourceId, ArrayList<String> parsedData)
    {
        super(context, textViewResourceId, parsedData);
        mStrings = parsedData;
        mInflater = (LayoutInflater) HopeloosChatActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        if (convertView == null)
        {
            convertView = mInflater.inflate(R.layout.main, null, false);
        }

        TextView text = (TextView)convertView.findViewById(R.id.TextView);
        SpannableStringBuilder ssb = new SpannableStringBuilder("Test  ");
        Bitmap emoticon = BitmapFactory.decodeResource( getResources(), R.drawable.icon);
        ssb.setSpan(new ImageSpan(emoticon), 5, 6, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        text.setText(ssb, BufferType.SPANNABLE);

        return convertView;
    }
}

I do use setContentView(R.layout.main); in the OnCreate()-method
My main.xml contains the ListView part:
<ListView android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_weight="1" />
And list_item.xml contains the TextView:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/TextView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp"
android:autoLink="web"
android:linksClickable="true" >
</Textview>

When I run my code, I get a Nullpointer because text is null, and I'm kinda stuck. Could anyone point me in the right direction or help me a bit?
Thanks in advance!
Comment: I am doing something similar HERE!!! http://stackoverflow.com/questions/16768930/implementations-of-emoji-emoticon-view-keyboard-layouts
Answer: First take one hash map like below:
private static final HashMap<String, Integer> emoticons = new HashMap<String, Integer>();
static {
  emoticons.put(":)", R.drawable.smilie1);}

secondly, write function to convert smiley text to image
// Get image for each text smiles
public static Spannable getSmiledText(Context context, String text) {
      SpannableStringBuilder builder = new SpannableStringBuilder(text);
      int index;
      for (index = 0; index < builder.length(); index++) {
        for (Entry<String, Integer> entry : emoticons.entrySet()) {
          int length = entry.getKey().length();
          if (index + length > builder.length())
            continue;
          if (builder.subSequence(index, index + length).toString().equals(entry.getKey())) {
            builder.setSpan(new ImageSpan(context, entry.getValue()), index, index + length,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            index += length - 1;
            break;
          }
        }
      }
      return builder;
    }

Thirdly, when you send text,red all text and if it contains ":)" then call function like below
chattext.(getSmiledText(getApplicationContext(),":)"));

Hope it helps! Let me know if you have any doubts.
Comment: Thanks for your answer, but it worked immediatly when I just changed the view part. I'm still going to use this tho! Also I'm implementing Emoji's, so I'd have to put like 800+ smileys in the hashmap :P
Answer: You are inflating convertView using R.layout.main:
convertView = mInflater.inflate(R.layout.main, null, false);

This isn't right; you're inflating your ListView's layout each time. Use this instead:
convertView = mInflater.inflate(R.layout.list_item, null, false);

Additionally, your TextView should be wrapped in a layout, or convertView may be the TextView itself, and findViewById(...) won't work on it. Actually, thanks to @Jens, this crossed-out text doesn't apply; using findViewById on the same object you're looking for will still work.
Comment: Yeah, he already checks `if (convertView == null)` before creating a new one.
Comment: The only thing Eric is wrong about is the `findViewById(..)` bit - it works just fine if invoked on a `View` that has the requested id - it will just return **itself**.
Comment: @Jens Ah, good to know. I wasn't sure of that (I always wrap in layouts) so I just wanted to make sure the OP didn't make that mistake. I'll correct my post.
Comment: You should always avoid adding pointless layouts (i.e. ViewGroup:s) if you can - hell, in most cases your "main" layout can be a big old `` - unless you are messing with size of the layout (i.e. not `match_parent` or a specific background).
Comment: Thanks a lot Eric, how could I have missed that haha :P


Remove PreferredFocusedView tvOS

Question: I have a code in Objective C which I have used a PreferredFocusedView Constraints then I wonder how can I remove this later without changing the view,

when I say I wanna remove it means I wanna remove this virtual places (in green and blue ) totally and not only remove the FocusGuid layout from the view
I already managed to remove the FocusGuide by using
MyfocusGuide.preferredFocusedView = [self preferredFocusedView];

But still, those goats buttons (green and blue) exist and in action every time I move to their location.
Answer: The solution I have found is to use the new array UIFocuseEnvironment with tvOS 10.0 that make it easy for me
- (NSArray<id<UIFocusEnvironment>> *)preferredFocusEnvironments  //Called By [self setNeedsFocusUpdate]
{
    if (CONDITION)
    {
        return @[BUTTON1, BUTTON2];
    }
    else
    {
        return nil;
    }
}

Remove PreferredFocusedView tvOS