Javascript Loop Restrict to only 1

Question: I am using:
$.each(data.mydata, function(index, value){
  output += '
'+value.title+'
';
}

I need to test something and only want the loop to get 1 off the list.
Is there any simple way to do this?
Comment: Is `data.mydata` an object or an array?
Comment: what about `output += ''+data.mydata[0].title+'';`? I don't see the need for a loop if you're only getting one element?
Answer: Break it in the callback by returning false.
$.each(data.mydata, function(index, value){
  output += '
'+value.title+'
';
  return false;
}

Answer: From the documentation:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

So adding return false after your logic would have the desired effect.
Answer: Why not just use a for loop then
for(var i = 0; i < 1; i++) {
  output += '
'+data.mydata[i].title+'
';
}

Or no loop at all really
if(data.mydata.length > 0)
    output += '
'+data.mydata[i].title+'
';

Answer: Why are you looping if you want one?
var myData = data.mydata;
var firstItem = myData[0];
var firstTitle = firstItem.title;

all in one line
var firstTitle = data.mydata[0].title;

Comment: I only wanted 1 to check something out...but would normally loop.

Javascript Loop Restrict to only 1


Updating Image.source from a separate thread in WPF

Question: I am building a WPF program that does some image acquisition, processing and displaying with a Image object. Currently I summon new a thread from c++ to do the acquisition and processing, then update the Image through callbacks.
It seems when I access the Image.source in the callback, it throws a exception of something like "cannot access this object because another thread own it". I tried to construct the Image and access the Image.source both in the STA thread but the same exception occurs. How should I deal with this?
Much appreciated.
Comment: See [this answer](https://stackoverflow.com/a/33917169) in particular, in the marked duplicate
Answer: If you create an ImageSource on a background thread, you can call its Freeze method to make it cross-thread accessible.
You would then set the Source property of an Image control in the UI thread, by calling Dispacher.Invoke:
var bitmap = new BitmapImage();
bitmap.BeginInit();
...
bitmap.EndInit();
bitmap.Freeze();

image.Source.Dispatcher.Invoke(() => image.Source = bitmap);

Answer:  if (InvokeRequired)
 {
    this.Invoke(new Action<source>(ImageObject), new object[] {value});
    return;
 }

OR
Invoke((MethodInvoker)delegate {
MainForm.UpdateImageSource(source);
});

OR
Call Image.source = object
Comment: Sorry, what is "Call"? It does not look like a valid keyword in C#.
Comment: that was the last resort, I am sorry, that is a vb.net keyword, try the options above it
Comment: idk what objects and data youre dealing with as you did not publish any code. so I gave source and image object as ideas, fill in the appropriate data


Probability that $x \equiv 3 \pmod{4}$

Question: I am working on a number theory project and I am interested in the following statement:

What is the probability that an integer $x$ has the property that $|x| \equiv 3 \mod{4}$?

This seems equivalent to me as asking, what is the probability that the Legendre symbol $\left(\frac{-1}{p}\right) = -1$, by Quadratic Reciprocity.
Additionally, since we know from the integers that the probability a number in $\mathbb{Z}$ is divisible by a prime $p$ is $1/p$, can we say that the probability that a Gaussian integer, $a + bi \in \mathbb{Z}[i]$ with $a,b \neq 0$, is divisible by a Gaussian prime is $1/(a^2 + b^2)$? (Notice the theorem regarding Gaussian primes here: Gaussian Primes).
These may seem like disjoint questions, but they are related to the fact that the probability that two gaussian integers are coprime involves the zeta function.
Comment: @Marvis: I suppose my probability measure would be the same as the one presented here: http://planetmath.org/probabilitythattwopositiveintegersarerelativelyprime
Comment: @Marvis That isn't a probability measure, since a probability measure has to be countably additive. That is just a density measure.
Comment: @SamuelReid That example is also not a probability measure, unfortunately. There is no probability measure on a countable set that is uniform. What that theorem reaslly says is that if $N$ is large and we pick two random integers from $1$ to $N$, the probability that the two numbers are relative prime approaches $\frac{6}{\pi^2}$ as $N\to\infty$.
Comment: Also, the Legendre symbol is not defined unless $p$ is prime. It is actually the Jacobian symbol when the "bottom" might be composite.
Comment: @ThomasAndrews Yes. Thanks for pointing it out. Will delete the comment.
Comment: You similarly have to define density (rather than probability) on the Gaussian integer.
Answer: From my comment above, now relocated here:
There are four equivalence classes modulo $4$. Every integer falls into one of those equivalence classes. The equivalence class $[3] = \{n: n = 4k + 3, k\in \mathbb Z\}$. Every fourth integer belongs to $[3]$; that is, consecutive integers map cyclicly into one of four equivalence classes: $$4k \mapsto [0], \;\; 4k+1 \mapsto [1], \;\; 4k + 2 \mapsto [2], \;\; 4k + 3 \mapsto [3],\;\; 4k+ 4 = 4(k+1) \mapsto [0], \cdots$$
Hence the probability that an integer is equivalent to $3 \pmod 4$ is no more than probability of that integer belonging to one of four equivalence classes: probability $\;\large \frac 14$.
I am not at all clear as to how this relates to your second question.
Comment: @SamuelReid That is actually not as trivial to answer - it is a strong version of [Dirichlet's theorem on primes in arithmetic progressions](http://en.wikipedia.org/wiki/Dirichlet's_theorem_on_arithmetic_progressions), a theorem which involves heavy analytic-number-theoretic machinery rather than just observation of translation-invariance of density - though the format of the answer is the same: the probability a prime is congruent to $r$ mod $n$ is $0$ if $r,n$ are not coprime and $1/|({\bf Z}/n{\bf Z})^\times|$ otherwise. Also see http://www.dms.umontreal.ca/~andrew/PDF/PrimeRace.pdf.
Comment: I'll accept your answer if you can answer a follow-up question: What is the probability that a prime number $p$ has $p \equiv 3 \mod{4}$, this would be equivalent to answering my question about the zeta function, I'll make a post about how they are connected as an answer after.
Comment: Thanks, anon! I hope it helps.
Comment: @amWhy: Yes, I learned a lot from both responses, thank you very much!
Answer: The probability that a rational integer (i.e. in $\bf Z$) has residue $r$ modulo $n$ is $1/n$, since the probability attached to each residue is equal and there are $n$ residues. Here we are using an asymptotic notion of "probability distribution" as mentioned in the comments.
Similarly, in any number field $K/{\bf Q}$ with ring of integers ${\cal O}_K$ and ideal ${\frak n}\triangleleft {\cal O}_K$, any intuitively nice asymptotic notion of density would be translation-invariant, so the probability an integer $\in{\cal O}_K$ would be in a fixed residue $r$ mod $\frak n$ (i.e. congruent to $r+{\frak n}$ in the quotient ${\cal O}_K/{\frak n}$) is the same for every choice of $r$, and hence is equal to the reciprocal of the number of equivalence classes, which is the order $|{\cal O}_K/{\frak n}|$ of the quotient, which is (by definition) the norm $N({\frak n})$ of $\frak n$. If ${\frak n}=(n)$ is a principal ideal generated by some integer $n\in{\cal O}_K$, then $N({\frak n})=N_{K/{\bf Q}}(n)$ is the norm of $n$ (this is a fact from algebraic number theory). This is indeed $a^2+b^2$ for $n=a+bi\in$ ${\bf Z}[i]$ $={\cal O}_{{\bf Q}(i)}$.
The same heuristic for deducing that the probability two rational integers are coprime works for computing the probability two integers $\in{\cal O}_K$ of a number field $K$ are coprime (with the caveat that $\cal O$ is a UFD). Originally, we assume that the events "being divisible by the prime $p$" for distinct $p$ are independent, and two numbers are coprime iff for each prime $p$ it is not the case that both are divisible by $p$ (which has probability $1/p^2$), so the probability two rational integers are coprime is given by the Euler product factorization associated with the Riemann zeta function:
$$\prod_p\left(1-\frac{1}{p^2}\right)=\frac{1}{\zeta(2)}=\frac{6}{\pi^2}.$$
Similarly, the probability two integers in ${\cal O}_K$ are coprime is
$$\prod_{\frak p}\left(1-\frac{1}{N({\frak p})^2}\right)=\frac{1}{\zeta_K(2)}.$$
See Dedekind zeta function.
On Mathworld, for Gaussian and Eisenstein integers the probabilities are listed in closed form.
Comment: @SamuelReid Unfortunately, no, I don't have one. I've only seen the claim mentioned in passing by mathematicians, but I follow the heuristic argument easily enough. The formal proof should begin as follows: the probability two integers with norm $\le n$ are coprime, by inclusion-exclusion principle, is $$\sum_{\frak n}(-1)^{\mu({\frak n})} \ell^{-1}\lfloor\ell/N({\frak n})^2\rfloor$$ where $\ell=\#\{x\in{\cal O}:N(x)\le n\}$ and the (finite) sum is taken over ideals of the form $\frak n={\frak p}_1\cdots{\frak p}_{\rm k}$, the ${\frak p}_i$s distinct and $\mu({\frak n}):=k$, with norm $\le n$.
Comment: Do you have a reference for a proof of your last claim regarding the probability two integers in $\mathcal{O}_{K}$ are coprime?

Probability that $x \equiv 3 \pmod{4}$


Jquery / Ajax - Working with a class that is appendet after ajax call

Question: I have 2 ajax calls that takes data from input fields and send those to the server and create a new database record. If the save was successfull, I append a new html table row to my html table.
The seccond ajax call send an ID that belongs to a specific cost point to my server and deletes this record from the database.
Both of the calls works finde. However, if I create a html record and want to delete it again ( without refreshing the page ) it won't work.
Here is my code:
function addNewRow(id, name, cost) {
        $('#costTable tr:last').after('
delete forever	' + name + '	' + cost + '
>');
    }

$(document).on('click', '#saveCost', function () {
            var name = $("input[name='cost-name']").val();
            var cost = $("input[name='cost-price']").val();
            $.ajax({
                type: "post",
                url: "{{ route('saveCost') }}",
                data: {'name': name, 'cost': cost},
                success: function (data) {
                    swal({
                        position: 'top-right',
                        type: 'success',
                        title: 'Kostenpunkt wurde gespeichert',
                        showConfirmButton: false,
                        timer: 1000
                    });
                    $("input[name='cost-name']").val("");
                    $("input[name='cost-price']").val("");
                    addNewRow(data, name, cost);
                },
                error: function (data) {

                }
            }); //end of ajax
        });
        $(document).on('click', '.deleteCost', function () {
            var $this = $(this);
            var costID = $this.closest('tr').data('id');
            $.ajax({
                type: "post",
                url: "{{ route('deleteCost') }}",
                data: {'costID': costID},
                success: function (data) {
                    swal({
                        position: 'top-right',
                        type: 'success',
                        title: 'Kostenpunkt wurde gelöscht',
                        showConfirmButton: false,
                        timer: 1000
                    });
                    $this.closest('tr').remove();
                },
                error: function (data) {

                }
            }); //end of ajax
        });

Thats the table:

              Action
              Kostenpunkt
              Kosten

               @foreach($costs as $cost)

id }}">
                          delete forever
                          {{ $cost->name }}
                          {{ $cost->cost }}

               @endforeach

After I created a new row and want to delete it again ( without refreshing the page ), it won't work. I think it's because I append the data in the "saveCost" ajax Call and the appended data doesn't belong to the actual HTML DOM.
Comment: Do you have pass back Id in first call ? Can you console.log (data) - do you see Id of new record?
Answer: You forgot, in the addNewRow function, to add the class name deleteCost to this element: delete forever. Add this class and delete will work as you expect.
Comment: Oh you're right !! oh man I was so stupid.. haven't seen it :D Thanks for your help! works perfect now. I will mark your answer as correct :)


Swift - passing parameter from non-generic function to a generic one

Question: So here is my playground, i would love to use the openInitial111() function but it just wont compile, the openInitial222() is working perfectly, whats the problem ?
<code>protocol Module : Screen {
   init()
}
extension Module {
   static func entity() -> Self {
      return Self()
   }
}
protocol Screen {

}
class FFF: Module {
   required init() {
   }
}
class ZZZ: NSObject {
    func openInitial111(initialModule: Module.Type) {
        self.openViewController(itemWithScreenStyle: initialModule.entity())  // Error : Cannot invoke openViewController
                                                                          //with an argument list of type '(initWithScreenStyle:Module)
    }

    func openInitial222(initialModule: Module.Type) {
       let f = FFF.self  // FFF.Type
       self.openViewController(itemWithScreenStyle: f.entity())  // works
    }

    func openViewController<T: Screen>(itemWithScreenStyle: T) {
        print("generics")
    }
}
</code>
Comment: [Protocols don't conform to themselves in Swift](http://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself) – therefore you cannot use `Module` as a type that conforms to `Screen`, you need `openViewController`'s `T` to be a concrete type (which is why it works with `FFF`). One possible way to make it work with `Module` would be to build a type erasure, such as shown in Rob's answer to the linked Q&A.
Answer: Indeed as suggested in comments the underlaying issue is that protocol doesn't conform to protocol. The error message is incredibly misleading though.


Evaluating improper integrals with characteristics of both type I and type II

Question: Integrating improper integrals constitute of integrating functions
1) over an infinite integral
2) over an interval where f has a discontinuity.
Namely, integrals type I and type II, respectively. Generally, both types are solved in the same way using limits.
But consider the following integral:
$\int_0^\infty \frac{1}{\sqrt[3]{x}} dx$
In this case, I would proceed to set the integral $\int_0^t \frac{1}{\sqrt[3]{x}} dx$ to $\displaystyle\lim_{t\to \infty}$. However, $\frac{1}{\sqrt[3]{x}}$ is discontinuous at $x=0$.
Why is this disregarded during integration??
Comment: $\int_a^bf(x)dx$ is independent of f(x) for $x\lt a$, so whether or not it is continuous at a doesn't matter.
Comment: You need to set an integral to a limit when the integrand becomes infinite at the end point.
Comment: Your comment about Type II is not correct.  If there is a discontinuity, the integration interval is subdivided at the point of discontinuity.  A discontinuity at an end point is ignored.  I suspect you will have trouble with your example as t becomes infinite - it diverges.
Comment: @herb yes, I know. I just didn't see it necessary to elaborate on type II as the key was the use of the limit :)
Comment: @herb what do you mean "a discontinuity at an end point is ignored"? I've never heard of that and disagree....
Comment: Oh, that makes sense! Thank you :) But now I'm slightly confused as to why we have to set integrals to limits as t approaches b on the interval [a,b) if discontinuity on b doesn't matter? So it's not exactly ignored?
Answer: i think in that case you divide the integral in two because it have two cases of improper integral, so you make
$$\int_{0}^{+\infty}\frac{dx}{\sqrt[3]{x}}=\int_{0}^{1}\frac{dx}{\sqrt[3]{x}}+\int_{1}^{+\infty}\frac{dx}{\sqrt[3]{x}}$$
so you study both part separated and in order to the original integral converge both integrals should converge. so it will be something like
$$\int_{0}^{1}\frac{dx}{\sqrt[3]{x}}=\lim_{t\to0^+}\int_{t}^{1}\frac{dx}{\sqrt[3]{x}}$$
and
$$\int_{1}^{\infty}\frac{dx}{\sqrt[3]{x}}=\lim_{t\to\infty}\int_{1}^{t}\frac{dx}{\sqrt[3]{x}}$$
Comment: In general, subdivide into intervals where each interval has only one of those types at only one endpoint.
Comment: @cand Excellent!! _Infinite_ thanks! ;)


How can I convert a single Object of objects, into an array of objects?

Question: I am retrieving an list of books from my Firebase database, where each "book" is an object.
The payload of books, is one monolithic object of objects as such:
{
      key1: {
       "title": "A Good Book"
       "author": "A Person"
      },
      key2: {
       "title": "Another Good Book"
       "author": "Another person"
      }
     ...and so on
    }

I need to change that monolithic object into an array of objects, so that I can map through each and extract the values I want.
The expected array that I need:
    [
       {
         "title": "A Good Book"
         "author": "A Person"
       },
       {
         "title": "Another Good Book"
         "author": "Another person"
       }
    ]

I've tried using Object.entries(myObject) and Object.values(myObject) but this just returns garbled metadata about the object.
I've tried other answers from stack overflow such as this:
    var array = Object.entries(data).map(([phrase, date]) => ({phrase,date}));

But this doesn't work.
I initially thought this should be straightforward and common issue, but after combing through stack overflow and google for a few days, I have not encountered a similar problem & solution.
Comment: Your first snippet does not contain valid object literal syntax. How does your object really look? An object without keys isn't really an object.
Comment: @jmedran The snapshot paylod is everything but a plain data object, it's a `Snapshot` instance! "*You can retrieve the data in the snapshot with the `.val()` method.*".
Comment: If your data is a JSON Object, then use jacksons Object mapper. https://www.baeldung.com/jackson-object-mapper-tutorial
Comment: @Bergi is correct, you can't create an object without a key, In your case, It might like this `{ '0': {}, '1': {} }`
Comment: All - I've updated the object syntax to more closely reflect what my object(s) look like. The "key" in this instance is in fact the title of the book. @Bergi
Comment: @jmedran For that object, `Object.values` should work fine. What "*garbled metadata about the object*" do you see?
Comment: @Dasarathan This is javascript, not java.
Comment: @Bergi `console.log(Object.values(myObject))` returns a gigantic nested object with stuff such as "LazyHash", "priorityNode", "indexMap" etc. Not sure what all of that is.
Comment: @jmedran What does `console.log(myObject)` log? Is it plain data, is it an instance of some class? Notice that `Object.values` should never return a gigantic object, but always an array.
Comment: @Bergi `console.log(myObject)` returns plain data (JSON). The payload is a _"static snapshot"_ of the path I am referencing to my Firebase Database. See this link for Google's simple explanation: [Reading From Firebase DB](https://firebase.google.com/docs/database/web/read-and-write#reading_and_writing_data). So `myObject` is actually the `snapshot` value you see in the docs.
Comment: @Bergi You are correct! Frankly, this was the root of all my issues, by not having the`snapshot.val()` method. Quite embarrassing I missed that in the docs. Thank you helping me through this issue!
Answer: There must be some keys in any object like this(i edited them):
    let data = {
       {
      "Harry Potter": {
          "BookInfo": {
               "Pages": 500,
               "Author": "JK Rowling"
           },
          "SaleInfo": "For Sale"
      },
     "A Clockwork Orange": {
           "BookInfo": {
               "Pages": 200,
               "Author": "Anthony Burgess"
           },
          "SaleInfo": "For Sale"
      }
    }
     ...and so on
    }

if so then you can use Object.valus() as:
const books =  {
      "Harry Potter": {
          "BookInfo": {
               "Pages": 500,
               "Author": "JK Rowling"
           },
          "SaleInfo": "For Sale"
      },
     "A Clockwork Orange": {
           "BookInfo": {
               "Pages": 200,
               "Author": "Anthony Burgess"
           },
          "SaleInfo": "For Sale"
      }
     ...
    }
const booksMapped = Object.keys(books).map(bookName => {
  return {
    bookName,
    ...books[bookName]
  }
})

console.log(booksMapped)
/*
[
  {
    "bookName": "Harry Potter",
    "BookInfo": {
      "Pages": 500,
      "Author": "JK Rowling"
    },
    "SaleInfo": "For Sale"
  },
  {
    "bookName": "A Clockwork Orange",
    "BookInfo": {
      "Pages": 200,
      "Author": "Anthony Burgess"
    },
    "SaleInfo": "For Sale"
  }
]
*/

basically Object.keys() will give you an array with every keys given object and then you can chain any array method on it
eg:
map
reduce
forEach
filter
find
etc
let person {
  name: "John Doe",
  age: 18
}

Object.keys(person) // => ["name", "age"]
Object.values(person) // => ["John Doe", 18]

Answer: You could map the entries of the object to get an array of objects:

const input = {
  "Harry Potter": {
    BookInfo: { Pages: 500, Author: "JK Rowling" },
    SaleInfo: "For Sale",
  },
  "A Clockwork Orange": {
    BookInfo: { Pages: 200, Author: "Anthony Burgess" },
    SaleInfo: "For Sale",
  }
};

const output = Object.entries(input).map(([title, value ]) => ({
  title,
  author: value.BookInfo.Author
}))

console.log(output)
Answer: The most elegant solution is to use flatMap():
const sorce = {
      key1: {
       "title": "A Good Book",
       "author": "A Person"
      },
      key2: {
       "title": "Another Good Book",
       "author": "Another person"
      }
    };

const result = Object.keys(sorce).flatMap(key => sorce[key]);
console.log(result);

Result:
  [
  { title: 'A Good Book', author: 'A Person' },
  { title:'Another Good Book', author: 'Another person' }
  ]

P.S. We can use map at this case with the same result:
const result = Object.keys(sorce).map(key => sorce[key]);


How do I generate DOM elements in AngularJS?

Question: I have a controller with some data with are actions and variable numbers of parameters:
$scope.actions = [
 {name : 'rotate', r : '30'},
 {name : 'translate', x : '10', y : '10'},
 {name : 'scale', x : '10', 'y' : 10},
]

So rotate has one parameter, translate and scale have two. I would like to show a select for each name in actions and then when one is selected show a input type='text' for each parameter that that action has. What is the easiest way to do this in Angular?
Answer: The easiest way that i can think of is to use templates with ng-include
Create 3 templates one for each dropdown value, such as

The template name should match the selected element name
Define a ng-include like
<ng-include src ="selectedAction.name"></ng-include>

In your controller code create a selectedAction variable on the scope, and change it whenever the selection changes.
Whenever selectedAction property changes, this would cause a appropriate template to get loaded based on the action selected.
Answer: If the unique set of name values is relatively small, you might be able to get away with using ng-switch:
<select ng-model="selectedAction" ng-options="action.name for action in actions">
  <option value="">Select an Action</option>
</select>

r: <input ng-model="selectedAction.r">

x: <input ng-model="selectedAction.x">

y: <input ng-model="selectedAction.y">

x: <input ng-model="selectedAction.x">

y: <input ng-model="selectedAction.y">

JSFiddle example


Adding Undersized Fuse to Doorbell Circuit?

Question: So recently my doorbell button got stuck and it burnt out both the electromagnetic coil in the chime and the transformer. As I'm replacing everything I was thinking that I could add fuse to prevent a rogue button from causing so much damage again.
The transformer is 16VAC 10W and I measured the voltage as just over 20VAC. The chime consists of an electromagnetic coil that drives a pin hitting a chime (separate coils for the front and back buttons). It claims it's suitable for a 16VAC 10W or 16VAC 15W transformer.

Let's say that x amps run through the circuit when the button is depressed. Normally the button is depressed for very short periods of time (let's say <10 seconds for an enthusiastic doorbell ringer). I've read that a fuse can withstand more than its rated current for a period of time depending of how high the current is over the rated current... can I undersize a fuse such that the blow time for an x amp load would be 10–15 seconds? Would sizing the fuse be so finicky as to be not worth it?
Comment: Instead of a fuse, I wonder whether a suitable PTC thermistor could be found that would have an appropriate thermal time constant.
Comment: @user43744  This is a nicely written question.  However, it deals with house wiring, and as such, it's off-topic on EE.SE .  There is a stack dedicated to home improvement, which is where I'm migrating this question.
Comment: Are you sure you're fixing a problem that actually exists? If you mind the switch (maybe check it once a year?) and replace it if it shows the least bit of wear you shouldn't have this problem again. Also how old was the old switch and chime and transformers?
Comment: Also does your new chime continue to ring or does it get stuck on and buzz if your switch gets stuck on? In other words will it fail or just keep ringing if the switch sticks?
Comment: @Freiheit it gets stuck on with the solenoid holding the pin against the chime and buzzes. Eventually this causes the solenoid to overheat. The chime and transformer were many years old but in good condition. The button had been recently replaced and was only a couple months old (I guess it was defective).
Answer: Wouldn't a slow-blow fuse work? I don't think you'd want to under size it. Just understand what voltage/current ratings you need and find a slow-blow fuse that can handle 10-15 seconds of that.
Something like this. Just figure out where you need to be on the Average Time Current Curves.
Comment: 10W at 16–20V would put me at 0.5–0.625A... I think the 0315 from the [396 series](http://www.littelfuse.com/~/media/electronics/datasheets/fuses/littelfuse_fuse_396_datasheet.pdf.pdf) would work. I don't have a multimeter that can measure >0.2A but I'm assuming that if the electromagnetic coil is energized holding the pin against the chime the resistance would be very low.
Comment: Can't you find the coil resistance by removing the chime from the circuit and using your multimeter? That will give you the minimum resistance (maximum power) that your chime will use.
Comment: 7.5 Ohms, so 2.6A? It's been a while since I've done this. That's quite a bit higher than I expected.
Comment: That's what ohms law would state. If you're driving it from a transformer though, it probably drops to around (or slightly below) 16 volts under load. That would make it around 2.13 Amps. It's not terribly surprising that the designers under-spec'd the transformer and coil as they never expected it to be held down for long periods of time. You could try out one of the fuses shown in the link and see how long it would take for the fuse to blow.
Answer: A good old bimetallic strip positioned close to the bell can open the circuit to prevent excessive over-heating.

As the bell solenoid gets a little warm, the bimetal elements warp mechanically and open circuit the bell current. After it has cooled down a bit the contacts close: -
Comment: Self-resetting thermal breaker is another name for these, commonly used in automotive circuits where you have similar problems, something sticks, but it's the prolonged current, not overcurrent that is the issue. The intermittent circuit operation is the failure indicator, a constantly ringing doorbell would alert you that the button was stuck.
Comment: @FiascoLabs Actually older vehicles used something like this to control their turn signals.
Comment: Yep, Thermal Resetting Breakers and Bimetalic Turn/Emergency Signal Flashers. One neat thing was you could tell by the frequency of the flash if all bulbs were lit (burned filament slow or no flash). Adding a trailer made them work like they had heart arrhythmia.
Comment: But I'd probably have to build it from scratch, right?
Comment: Try ebay http://www.ebay.co.uk/sch/sis.html?_nkw=KSD9700%20110C%20N%20C%20Bimetal%20Temperature%20Control%20Switch%20Thermo%20Protector&_itemId=400409939881 BUT read the spec to make sure it is suitable and is normally closed at low temperatures and opens at the correct temperature.
Comment: That's great! Thanks! The lowest I can find is 40C... that should be good, I think.
Comment: @FiascoLabs: If the amount of current involved would be appropriate for such devices, an old-fashioned automotive blinker might be perfect.
Answer: Having had doorbell problems myself, I feel your pain.
I would recommend against this kind of hack. Consider what would happen if an overly enthusiastic Girl Guide decided to hold down your doorbell button.
From my personal experience, I found no problems holding down the doorbell continuously. This leads me to suspect that one of your components failed in some other way that violated the part's ratings. Perhaps some coils short circuited. Hopefully new parts rated to the power you specified will last longer.
Edit: As a tip, taping down your doorbell while inside testing connections is particularly helpful.
Comment: Perhaps my answer wasn't clear. My belief is that under normal operation (which includes holding the button), the components should be able to withstand the continuous current. Otherwise it seems unfathomable to me that houses around the world are operating a system that can be so easily destroyed.

You have two possible failure modes.
1. Doorbell systems can't withstand long term current.
2. You were subject to bad luck/age and your components just randomly failed creating condition 1.

I find #2 easier to believe.
Comment: I think that in the case of a door chime that operates with a solenoid pushing a pin mechanically against a chime this is something they are subject to. Take any solenoid and fix the load and run current through it for a prolonged period of time and it will overheat. Any electric fan is vulnerable to this failure mode as well.
Comment: As the button was stuck and I didn't catch it I think it was held open continuously (possibly a couple days). :( If it was held continuously wouldn't the fuse just blow? I'd rather replace a fuse than the chime and transformer next time.


Having a different design and interactions between mobile and tablet devices can have a big impact from overall UX?

Question: I have 2 design approach for a specific module 1 is for mobile and 1 is for tablet. The goal of this is for analyzation of the historical dates of the financial data.
A. Mobile phone design - Straight forward horizontal bar chart to differentiate each data from the previous periods.

B. Tablet Design - This is to increase users interactions by providing more relevant information for analysis to filter the data and period based on their preferences.
Does it make sense from the users perspective do have different designs from the different screen? Does it not affect the learnability and familiarity on the app?
Thank you
Comment: Do you have any info on what proportion of users will be switching between the two? If _most_ users use _either_ a tablet (or perhaps desktop), _or_ a mobile, and only a few will switch between the two, it may be less important that they look different.
Comment: "Does it make sense from the users perspective do have different designs from the different screen? " Yes.  Try not to make the differences too different however.
Comment: Just to note, the charts aren't just about design and look. Different chart types have different purposes... so I say go with the same chart for every device but allow some tweaking. For example, let the user scroll, resize or zoom the chart. Another option is limiting data: Show all 10 columns in larger screen, but show only 5 in smaller screens and let the user navigate (eg, see next 5 columns)
Answer: When it comes to consistency and knowledge of application design, it is necessary to maintain the same system design (Typography, colors, spaces etc.)
The issue of functionality is also important - because once the logic is written - it can easily be adapted to all types of devices.
I would recommend using a similar approach on any resolution

maintaining consistent clean code
no sense of surprise / confusion by the user
don't have to remember about different places in the application (in case of changes, you have to enter them 2x)

Currently, phones have great resolution, so designing a large number of functions should not be a problem

Credit for Iwona Sikora
Comment: Thanks for sharing your thought! I agree that consistency should be applied, but one thing in my mind is considering the other relevant information or actions that can be adopted on the larger screens. So that I'm torn between the consistency for the other screens.
Comment: Yes of course, If is need to be more functionalities/actions on larger screen it's should be apply and hide in smaller.

Everything depends on the context, I recommend that You consult programmers and another designer on this issue :)
Answer: With the understanding of two device screens holding same requirement - design components will differ to an extent due to real estate space. The differences lay within the design paradigm would make it familiar to the user. For example sort, filter can vary by interactive technique. But the larger sense of first-hand information should remain or depict in similar lines. This is how familiarity of both screens are addressed.
Familiarity - Through which the unified sense of experience is felt while moving between the devices. It means adding extra details on tablet (viz. content or text) against mobile device is not a bad ploy (As long as the design language is intact)
Learnability - Once user is under control (not alarmingly frustrated or questions the user interpretation or mental model) by means of familiarity the learnability will kick-in and user will evaluate if minor interaction (micro-interactions) would need to be learnt.
In summary, keep holistic sense of the app/screen in similar direction factoring for the miniscule interactions whether it would be tablet (landscape or portrait) vs. mobile (landscape or portrait).


After 16.10 upgrade, ethernet is not working

Question: Ok. I really need help. I messed up Ubuntu 16.04 LTS so I decided that upgrading to 16.10 will fix the broken packages. It did, but now I can't use the internet. At all. I have a Lenovo Ideapad with Realtek ethernet adapter. It says that the ethernet is "not managed". I tried modifying the managed=false to managed=true in /etc/NetworkManager/NetworkManager.conf but that didn't work. Can anybody help me?
Answer: For me the following commands solved the issue and LAN connection was immediately detected.
sudo touch /etc/NetworkManager/conf.d/10-globally-managed-devices.conf
sudo service network-manager restart

if the above doesn't work try the following
sudo sh -c "echo 'net.ipv6.conf.all.disable_ipv6 = 1' >> /etc/sysctl.conf"
sudo sh -c "echo 'net.ipv6.conf.default.disable_ipv6 = 1' >> /etc/sysctl.conf"
sudo sh -c "echo 'net.ipv6.conf.lo.disable_ipv6 = 1' >> /etc/sysctl.conf"
sudo sysctl -p
sudo sed -i 's/false/true/g' /etc/NetworkManager/NetworkManager.conf
sudo reboot -i NOW

Good luck!
Comment: excellent! the "touch" command plus reboot did the trick for me...
Answer: I solved the problem. Unfortunately, I needed to reinstall Ubuntu 16.10. And now I need to reinstall all the programs. Because Ubuntu live-USB doesn't have "Repair Current Install", which I consider a shame, since may other distros have that.


Multi subnet in ubuntu with dnsmasq

Question: I have a multi lan port box that install ubuntu server 11.10.
I am setup network in /etc/network/interfaces file as follow:
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
       address 192.168.128.254
       netmask 255.255.255.0
       network 192.168.128.0
       broadcast 192.168.128.255
       gateway 192.168.128.1
       dns-nameservers xxxxxx

auto eth1
iface eth1 inet static
       address 192.168.11.1
       netmask 255.255.255.0
       network 192.168.11.0
       broadcast 192.168.11.255

auto eth2
iface eth2 inet static
       address 192.168.21.1
       netmask 255.255.255.0
       network 192.168.21.0
       broadcast 192.168.21.255

auto eth3
iface eth3 inet static
       address 192.168.31.1
       netmask 255.255.255.0
       network 192.168.31.0
       broadcast 192.168.31.255

I am also enable the ip forward by echo 1 > /proc/sys/net/ipv4/if_forward in rc.local.
my dnsmasq config as follow
except-interface=eth0
dhcp-range=interface:eth1,set:wifi,192.168.11.101,192.168.11.200,255.255.255.0
dhcp-range=interface:eth2,set:kids,192.168.21.101,192.168.21.200,255.255.255.0
dhcp-range=interface:eth3,set:game,192.168.31.101,192.168.31.200,255.255.255.0

the dhcp was working fine in eth1,eth2,eth3, any machine plug in the subnet can get correct subnet's ip.
My problem was, each subnet machine can't ping each other. for example.
192.168.11.101 can't ping 192.168.21.101 but can ping 192.168.128.1
192.168.31.101 can't ping 192.168.21.101 but can ping 192.168.128.1
I am also trying with following command:
route add -net 192.168.11.0 netmask 255.255.255.0 gw 192.168.11.1
(and also 192.168.21.0/192.168.31.0) at this multi-lan-port machine.
But still won't work.
Does anyone can help ? Thanks.
Answer: -----------Next answer------------
It's also possible that you've configured the gateway incorrectly for each interface. Please configure the interfaces as follows:
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
 address 192.168.128.254
 netmask 255.255.0.0
 gateway 192.168.1.1
 network 192.168.128.0
 broadcast 192.168.128.255
 dns-nameservers xxxxxx

auto eth1
iface eth1 inet static
 address 192.168.11.1
 netmask 255.255.0.0
 network 192.168.11.0
 broadcast 192.168.11.255

auto eth2
iface eth2 inet static
 address 192.168.21.1
 netmask 255.255.0.0
 network 192.168.21.0
 broadcast 192.168.21.255

auto eth3
iface eth3 inet static
 address 192.168.31.1
 netmask 255.255.0.0
 network 192.168.31.0
 broadcast 192.168.31.255

With these changes, all of the interfaces should look to the same gateway and communicate properly. You may need to remove some of the routing that you did.
Comment: It's won't work, now, the subnet machine can't ping the interface now. for example, clinet 192.168.21.x can't ping 192.168.21.1
Answer: What you're attempting to do is called "Multihoming" with multiple links and multiple address spaces. The problem you're facing is that there is no routing/networking configured and enabled between the different interfaces.
For traffic to pass back and forth between the interfaces, they'll need to be connected through an internal interface. Then you can NAT the external addresses if I'm correct. However, I think what you're trying to do is either going to require virtualization of another interface to associate the internal addresses with.
Essentially, you may be asking too much of the equipment you're describing.
What I would do in this case is configure an internal network that eth1, eth2, eth3 exist on to pass traffic to the NAT'd eth0.
Actually, after writing this response I've got another answer I'm about to respond with for organization's sake.
Comment: thanks your reply.

what i trying to do was to split around 120 pcs from single class c, into 4 class c subnet. one class c (192.168.1.0) was connect to an ip-share machine that connecet to Internet.
Comment: You're going to need some kind of load balancing/firewall in place in order to correctly NAT the route the traffic.
Comment: I have an 4wans ports load balancing/firewall in 192.168.1.1 and the 192.168.1.0/24 class c net are working fine. Now I try to install this 4 ports linux box to split about 120 pcs into 4subnets. 30s for 192.168.1.0/24, 30s for 192.168.11.0/24, 30s for 192.168.21.0/24, 30s for 192.168.31.0/24 ....
Answer: Hi  I ham having a senario where I am using 3 lancards and they are able to ping I will just put up how i have configure u see if thats works for u or not as i think u need to enable packet forwarding /etc/sysctl.conf & may be u will also need to use iptables to route packets.Also disable firewall if it is enable to check.
I know u have have configure in a almost similar way still can give a try as i am able to ping using the below configuration
/etc/network/interfaces:
-- The loopback network interface
auto lo
iface lo inet loopback
-- The primary network interface
auto eth0
iface eth0 inet static
 address 192.168.1.15
 netmask 255.255.255.0
 gateway 192.168.1.1
--The secondary network interfaces
auto eth1
iface eth1 inet static
 address 10.0.0.15
 netmask 255.0.0.0
auto wlan0
iface wlan0 inet static
 address 10.0.1.15
 netmask 255.255.255.0
Give static ip but just mention correct gateway for the corresponding
pc-1
ip address - 10.0.0.21
subnet mask - 255.0.0.0
gateway - 10.0.0.15
dns - 10.0.0.15
dns - 192.168.1.15

pc-2
ip address - 10.0.1.21
subnet mask - 255.255.255.0
gateway - 10.0.1.15
dns - 10.0.1.15
dns - 192.168.1.15

I have enable packet forwarding for IPv4 and IPv6 (/etc/sysctl.conf)
Net.ipv4.ip_forward = 1
Net.ipv6.conf.all.forwarding = 1

This should work else you have to also use iptables and mention route for each interface
u need
Hope this works
I am not good with iptables i have found this on net and mentioning below the same
In case if u need to use iptable try below change the interface as u need to write the lines for all the interfaces as below is the example for 1 interfaces only as only 1 interface. I n this case I think eth0 will able to ping to eth1 for vice versa u need to mention same line for eth1 also
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
sudo iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT

Multi subnet in ubuntu with dnsmasq


Counting substring of a string

Question: public class Test {
    public static void main(String[] args) {
        System.out.println(countHi("xhixhxihihhhi"));
    }
    public static int countHi(String str) {
        if( str.length() < 2 ) return 0;
        if ( str.indexOf("hi") == -1 ) {
            return 0;
        }
        if ( str.length() == 2 ) {
            if ( str.indexOf("hi") == 0 ) return 1;
            return 0;
        }
        int i = str.indexOf("hi");
        return 1 + countHi( str.substring(0,i) + str.substring(i+1, str.length()));
    }

}

can someone explain to me why the result of the appearence of "hi" is 5 and not 3?
Comment: Possible duplicate of [How to find the count of substring in java](https://stackoverflow.com/questions/45888605/how-to-find-the-count-of-substring-in-java)
Comment: May you explain the problem a little more?
Comment: Use a debugger to step through your code. Pay close attention to the `String str`.
Comment: Why do you include `str.substring(0,i)` in the recursive call if `hi` did not appear there?
Answer: Because for the recursion you pass
str.substring(0,i) + str.substring(i+1, str.length())

instead of just
str.substring(i+1, str.length())

and since the initial string contains multiple hs, you create new his that weren't there at the start.
Change to this:
public static int countHi(String str) {
    String s = "hi";
    if( str.length() < s.length() ) return 0;
    if (!str.contains(s)) return 0;
    if (str.length() == s.length()) return 1;
    int i = str.indexOf(s);
    return 1 + countHi(str.substring(i + 1));
}

Answer: A easier way to solve your problem with apache commons lang. Try this.
public class Test {
    public static void main(String[] args) {
        System.out.println(countHi("xhixhxihihhhi"));
    }
    public static int countHi(String str) {
        return StringUtils.countMatches(str, "hi");
    }
}

If you use Spring then..
public class Test {
    public static void main(String[] args) {
        System.out.println(countHi("xhixhxihihhhi"));
    }
    public static int countHi(String str) {
        return StringUtils.countOccurrencesOf(str, "hi");
    }
}

Counting substring of a string


Why can't I use cars in solo mode that I've unlocked in Career mode?

Question: I unlocked cars in Career mode in the game for PS3 Blur, but I do not find them. They are not available in the solo race.
Is it because they are a higher level? or is it simply that it might be usable in multiplayer and I do not see them.
Answer: Continuing the career mode slightly, I found the cars I unlocked earlier. It functions by category. The cars I had won are Class C, and I was at the race level D. When unlocking, the category is indicated.


What is the lava bucket used for?

Question: Once you beat the Nether you receive a Lava Bucket. It has no use apparently. It is used lately? Can I get more beating the Nether again? Can I try to mix it to make potions?
Answer: In a updated version you use the lava bucket to fix a machine past the cookie clicker in the hole you dug that turns gold bars into iron bars.
Comment: You can get multiple lava buckets from the nether while that machine uses 1.  Is there a place for the additional ones you can get?

What is the lava bucket used for?


Do weapon specific perks work while dual striking in Skyrim?

Question: In Skyrim, if you do a dual strike, where you hit both attack buttons to hit with both weapons simultaneously, do the weapon-specific perks (sword crit, mace ignore armor, axe... something) apply?
There are several combinations of this question I'm wondering about, but I'm guessing they all have the same answer.  For example, does Fighting Stance work when you are dual wielding?  And do Savage Strike and Dual Savagery stack?
Answer: Yes, based on several types of evidence.

I dual-wield exclusively and I know that Fighting Stance, Savage Strike, Dual Savagery etc. stack.
The dagger specific perks from the Sneak perk tree stack with the perks from the One-Handed perk tree.
The UESP One-Handed Page has a section on dual-wielding which says:

Allows the use of two perk proficiencies at once, such as Hack and Slash, Bladesman, or Bone Breaker, by mixing weapon types.

and

Dual Savagery and Dual Fury can make for almost scary damage output.


Solving second order PDE

Question: I have the PDE $x^2U_{xx}-2xyU_{xy}+y^2U_{yy}+xU_x + yU_y = 0.$
I thought this could be handled by a change of variables $X = ln|x|$ , $Y=ln|y|$ , but this approach gets me stuck pretty fast.
How can I solve it?
Comment: Some. I've done separation of variables, method of characteristics, and change of variables, but I haven't done any fourier/laplace transformations  for PDEs yet.
Comment: Have you studied techniques for solving pde's ?
Comment: Related question by OP: http://math.stackexchange.com/q/1659989/11127
Answer: The change of variables  $\begin{cases}
X=\ln|x|\\
Y=\ln|y|
\end{cases}$
transforms the PDE into :
$$U_{XX}-2U_{XY}+U_{YY}=0$$
A second change of variables :
$\begin{cases}
s=X+Y\\
t=X-Y
\end{cases}$ reduces the PDE to :
$$U_{tt}=0$$
The double integration of this very simple differential equation gives :
$$U(s,t)=f(s)t+g(s)$$
where $f$ and $g$ are any derivable functions.
Then, coming back to the preceeding variables :
$$U(X,Y)=(X-Y)f(X+Y)+g(X+Y)$$
$$U(x,y)=\ln|\frac{x}{y}| f(\ln|xy|)+g(\ln|xy|)$$
Or, on an equivalent form with any derivable functions $F$ and $G$ :
$$U(x,y)=\ln\left|\frac{x}{y}\right|\: F(xy)+G(xy)$$

Solving second order PDE


Why isn't my Java LinkedHashSet removing an object it contains?

Question: I have an object in a LinkedHashSet that implements equals, hashCode and compareTo (in a superclass) but when I try to remove that exact object from the set set.remove(obj) the remove method returns false and the object remains in the set. Is the implementation of LinkedHashSet supposed to call the equals() method of its objects? Because it doesn't.  Could this be a java bug?  I'm running 1.6.0_25.
Comment: [First rule of programming: It's always your fault](http://www.codinghorror.com/blog/2008/03/the-first-rule-of-programming-its-always-your-fault.html) Without seeing your code, we can't tell you what you're doing wrong.
Comment: Please hold a mirror up in front of your webcam so I can see your code. Oh, and reverse all the windows so I don't have to read it backwards. At this point I'm... skeptical it's a Java bug.
Comment: Post here the code of `equals()` and `hashCode()`
Comment: Test `equals` on the object you are passing to remove and the object you think should be removed first.
Comment: A `HashSet` removes an element if they are `equal()`. http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html#remove(java.lang.Object)
Answer: My guess would be that your object's hashCode() implementation is returning a different value than when you added the object to the set.
Comment: Which is why we're asking to see the code--not really an answer yet ;)
Comment: That 'caveat' is mentioned in the javadoc of hashCode() on Object: "[..] invoked on the same object more than once [..], the hashCode method must consistently return the same integer, [..]"
Comment: @Dave well my reasoning is that mekazu says equals() isn't being called, which it wouldn't be if the object wasn't found by its hash due to the hash changing.
Comment: Not saying you're wrong, saying it's premature :) Could just be the object's state is changing, too--who knows.
Comment: @mekazu in Oracle's 1.6.0_25 LinkedHashSet, both contains() and remove() end up mapping the hashCode() of the supplied object to an index in an array. The hash is compared to the hash of the entries found there, since multiple hashes can map to the same index, and if the hash is the same, then the equals method is called. If your objects are equal, they should return the same hashcode, as per the javadocs on hashCode()
Comment: Correct! The object key was added to the object after it was inserted into the Set. Thus hashCode returned a different value to when it was first added. It's strange that the [javadoc](http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html#remove(java.lang.Object)) doesn't make mention of this caveat.
Answer: LinkedHashSet works fine for me:
import java.util.*;

public class Test {
    public static void main( String[] args ) {
        LinkedHashSet<String> lhs = new LinkedHashSet<String>();
        String s = "hi";
        lhs.add( s );
        System.out.println( lhs );
        lhs.remove( s );
        System.out.println( lhs );
    }
}

Perhaps you're passing in a reference to a different object to the remove method? Are you sure you didn't change the reference in any way?
Also make sure that hashCode() returns the same value when you insert it as when you are trying to remove it.
Comment: More likely it's an issue with OP's equals/hash/compare code.
Comment: He says he calls remove on "that exact object". So I assume he meant that exact reference (or lack thereof).
Answer: The chances of this being a bug in LinkedHashSet are infinitessimnally small.  You should dismiss this as a plausible explanation of your problem.
Assuming that this is a bug in your code, then it could be due to a number of things.  For instance:

Your equals and hashCode methods are returning contradictory answers for the object.
Your equals or hashCode methods depend on mutable fields and those fields are being changed while the object is in the set.  (For instance, if the hashcode value changes, the object is likely to be on the wrong hash chain, causing the remove method to not find it.)
You have declared the equals method as an overload, not an override of equals(Object).  (That could explain why your equals is not being called ... assuming that your assertion is factually correct.)
The object you are trying to remove is (in reality) not the one you inserted.
Something else has already removed the object.
You are running a different version of some class that does not match the source code you have been examining.

Now, I know that you have dismissed some of these explanations.  But that may have been premature.  Review the evidence that you based that dismissal on.
Another approach you could use is to use a Java debugger to forensically examine the data structures (e.g. the innards of the LinkedHashSet) and single-step the code where the deletion is supposed to be happening.


Is point exist in circle?

Question: Let us consider x and y is a point and then make a radius of some value r.If suppose i had a point a and b, I need to check whether the point a and b is in the radius r from x and y or not. Can give me the formula to this solution,So that i can implement in c programming.
Comment: Distance formula $\sqrt{(x-a)^2+(y-b)^2}\le r$?
Answer: The point $(a,b)$ is inside the circle of radius $r$ around $(x,y)$ iff $(a-x)^2+(b-y)^2<r^2$.
Answer: You can easily get rid of the square root as well.
Here is the distance formula:$$
d = \sqrt{(x - a)^2 + (y - b)^2}
$$
The point is in the circle, if $$d \leq r$$
So your formula is $$
\sqrt{(x - a)^2 + (y - b)^2} \leq r
$$
Just square it and you get $$
(x - a)^2 + (y - b)^2 \leq r^2$$
Since you can' t have a negative radius.
This is useful when you have lots of points, because you can get rid all of the square roots in trade of a single calculation of $r^2$. This is of course good only when you iterate over the circles, and check each point for each circle. Pseudocode:
for x, y, radius in circles:
    rs = radius * radius
    for a, b in points:
        if (x - a)^2 + (y - b)^2 <= rs:
            // The point is in the circle

If you have only a single point, the simple distance formula should be perfect too.
If you don't consider points on the radius of the circle to be in the circle, your formula is $d < r$. (By the way $d = r$ is the formula for point is exactly on the radius)
Comment: Though `d==r` may not work due to floating point precision.
Comment: @peterwhy yes! But floating point numbers are not necessary here or am I missing something? If all coordinates and radiuses are integers, no floating point operation is required. (Unless the numbers are too big)
Comment: Yea, so just a side note here. Your answer is perfectly fine.

Is point exist in circle?


Using different wallpapers on multiple monitors (Gnome 2 + Compiz)

Question: This seems like a simple question, yet I could not find any satisfying answer using Google or Ask Ubuntu.
So I have a triple-monitor setup. Basically what I want is simply to have a different background on each of the three monitors. Now I am not speaking about different virtual desktops (aka workspaces) here. Most of the solutions I googled were about different backgrounds on different workspaces. I have only the one workspace, but three monitors, like so:

Monitor 1 (on top) is my big TV that's attached to the wall above my two normal monitors.
I am using Gnome 2 with Compiz (aka gnome-session-fallback aka Gnome Classic (with effects) in the login manager dropdown list) on Ubuntu 13.04.
I tried the following methods trying to set a different background for each monitor:

ccsm (compiz-config-settings-manager), that is, setting a background via the window manager (Compiz). More precisely, I used the Wallpaper plugin of Compiz.
gnome-control-center, that is, setting a background via the Gnome System Settings. More precisely, I used the Background panel in the Gnome System Settings.
XDG_CURRENT_DESKTOP=Unity gnome-control-center, that is, settting a background via the Gnome System Settings, but mimicking Unity behavior. More precisely, I used the Appearance panel in the Gnome System Settings.

However, none of these methods seem to enable me to select a different background for each monitor. In each case, I can only set a single background (or possibly several that can then be cycled periodically, or used for different workspaces) for all three monitors. Then, I typically have options like center, tile, crop or scale that control how this single background is rendered across the three monitors.
The workaround I have gone with so far is to use Gimp to create one "big" background that encompasses the entire virtual resolution of all three monitors together. Basically, I create one big background image of size 3840x2160, in which I paste three backgrounds at the right places. Then I set this big background as the single background for the three monitors using possibility (1) or (3) above, and use the span option to span this big background across all three monitors. This results in three different backgrounds on the three monitors, provided the three smaller backgrounds were placed correctly on the big background image (Note: possibility (2) does not offer a span option).
However, this seems like an awful hack to achieve such a simple thing as setting a different background for each of my monitors. It also has several disadvantages:

When I want to change the arrangement of the monitors (the big TV on top can be slided some way to the left or to the right, and I like to adjust the monitor positions accordingly using xrandr or an associated GUI such as the Displays panel in the Gnome System Settings, so as to keep mouse movement intuitive), clearly the upper background does not slide along with the monitor it's supposed to be displayed on, which means I only see part of the upper background.
The big background has some gray areas (dead space) in the upper corners that are uselessly loaded at login time by Compiz or Gnome when the big background is loaded.
Worst of all, when I want to change a single one of the three backgrounds, then I have to gimp-edit the whole big background. This is too much work considering I simply want to change a single background (yep, I know about Gimp layers, but still) - this ought to be possible with a few clicks and without a heavy-weight image manipulation program.

The first point means this workaround is not robust. The second means it is not efficient. And the third means it's a pain in the butt :)
So my question is this:
Is there some way - using either Gnome 2 or Compiz - to simply tell the system that I want a different background for each monitor? This would be the logical approach to me, as it would actually tell the system what my intention is. It would also be more efficient.
Really, it feels like this cannot be such an uncommon scenario. I would think many people have multiple monitors; and at least some of those must prefer to have different backgrounds on these monitors. So can it be true that there is no straightforward solution, and users are expected to come up with awful hacks such as creating their own custom backgrounds with heavy-weight programs in order to get this to work?
Comment: Braiam, this doesn't make a lot of sense to me. If the question "How do I set a desktop background / wallpaper?" doesn't deserve the tags "background" or "wallpaper", then which question does? Also the tags seemed to be fine for similar questions such as http://askubuntu.com/questions/26529/how-do-i-set-different-wallpapers-for-different-virtual-desktops?rq=1 or http://askubuntu.com/questions/365913/how-to-use-custom-background-picture-in-ubuntu-13-10. But then, you seem to spend a lot of your free time on askubuntu, so if it makes you happy... it's fine ;)
Comment: Is this good enough? If not PM me.
Comment: Wallpaper and background meanings change wildly from question to question. I'm leaving the more relevant ones which are gnome and compiz. If I change gnome to kde the kind of answers will change totally.
Comment: Funny how XFCE default behavior is actually what the OP needs, and I'm in the reverse case: I'd like to get with XFCE what the OP gets with gnome. At least there's an easy workaround in most cases: manually set background on all monitors to refer to the same picture.
Comment: I came here for kubuntu (KDE) and realized that per monitor bg setup comes out of the box in it. Right click and configure
Answer: Edit (2019): Nitrogen is no longer maintained. Nitrogen doesn't fully work on newer Ubuntu distros.
You can use nitrogen
To install it, run the following command in terminal:
sudo apt-get install nitrogen

Because nitrogen doesn't have a desktop file by default when is installed, you need to run the following command from terminal to start it:
nitrogen

How to use it?

In it's Preferences, add your wallpaper folder, then at the bottom [...] select Screen 1, 2, etc., to set a different wallpaper for each monitor:

To be able to set a different wallpaper for each monitor, you must
  disable the file manager from handling the desktop. This means you'll
  no longer have folders on the desktop.
In GNOME / Unity, install GNOME Tweak Tool:
sudo apt-get install gnome-tweak-tool

Then open GNOME Tweak Tool and on the Desktop section, set Icons on Desktop (previously Have file manager handle the desktop) to OFF.
And finally, to have the wallpapers restored each time you log in, add the following command:
nitrogen --restore

to your Startup Applications.

Source: UBUNTU MULTI-MONITOR TWEAKS (FULL SCREEN FLASH FIXES, SPAN WALLPAPER ACROSS MONITORS, MORE)
Comment: It should be noted that this option is now known as "Icons on Desktop" instead of "Have file manager handle the desktop"
Comment: Also see https://wiki.archlinux.org/index.php/nitrogen.
Comment: @MalteSkoruppa You don't need to create an executable script that runs `nitrogen --restore` at login. Just open [**Startup Applications**](http://askubuntu.com/q/48321/147044) and add this command (`nitrogen --restore`). For **Name** and **Comment** write whatever you want.
Comment: I tested this method with 2 monitors in Ubuntu 13.10 using Unity and it works great!
Comment: Guys, two things: First, I noted that backgrounds set in nitrogen do not get restored automatically when you log in. To achieve that, we have to run `nitrogen --restore`. So in order to make the changes permanent we have to create an executable script that runs this command at login, using Autostart. Please update your answers with instructions on how to do that.
Comment: Hey Radu, thanks and you're right, an executable script would be overkill. I personally know how to do it and already did it; I would just like those instructions added to your and/or Rinzwind's answers for other, less experienced users, who are trying to achieve different wallpapers on different monitors, and of course want them to persist across a reboot :) This is simply to improve the quality of the answer.
Comment: @MalteSkoruppa I hope that I made it clear now. If you consider to add more, you can edit yourself the answer; **Ask Ubuntu** [it's built and run *by you*](http://askubuntu.com/tour) :).
Comment: "Icons on Desktop" is no longer available, the option to choose monitor on nitrogen is no longer available too. This answer is no longer relevant.
Comment: I haven't found the multiple monitors option in `nitrogen` for Ubuntu 18.04. I've followed [these instructions](https://itsfoss.com/wallpaper-multi-monitor/) instead
Answer: From webupd8.org it seems there are 2 options. (copy from the website plus some extra things added by me):
The default Ubuntu Appearance settings doesn't let you span a single large wallpaper across both monitors or use a different wallpaper for each monitor, but there are two applications that you can use to do this.

The first one is SyncWall. Install it in Ubuntu using the following commands:
sudo add-apt-repository ppa:nilarimogard/webupd8
sudo apt-get update
sudo apt-get install syncwall

Here's how my desktops looks like after using SyncWall:

Current Features

Scheduling : you can change wallpaper at start-up, by interval or at fixed time
Ability to use/define system hot-keys to change wallpaper manually.
Basic multi-monitor support in order to share the wallpaper across screens
Ability to add some special effects (emboss, edge, blur, ...) to the displayed wallpaper.
Ability to rate images in order to display them more often (if random order is selected)
Several resizing methods and background filling
Network synchronization of wallpaper change by defining a server and clients. Display parameters are shared across the network (same resizing type on all the desktops)
Supported files :SyncWall uses Qt plugins to load image, so by default it can read basic formats as BMP, PNG, JPG. You can add more formats if needed by using bridge plugins to the FreeImage or the Devil libraries.
For linux platform, the common windows managers are supported (Gnome, Gnome3, KDE3, KDE4, XFCE, ...).

Another such tool is nitrogen , which besides being able to set the same wallpaper to extend across displays, it can also be used to set a different wallpaper to each monitor.
Nitrogen is available in the official Ubuntu repositories so to install it, search for it in Ubuntu Software Center or use the following command:
 sudo apt-get install nitrogen

Nitrogen doesn't have a desktop file, so run it from the command line:
nitrogen

To be able to set a different wallpaper for each monitor, you must disable the file manager from handling the desktop. This means you'll no longer have folders on the desktop.
In GNOME / Unity, install GNOME Tweak Tool:
 sudo apt-get install gnome-tweak-tool

Then open GNOME Tweak Tool and on the "Desktop" section, set "Have file manager handle the desktop" to OFF.
And finally, to have the wallpapers restored each time you log in, add "nitrogen --restore" to your startup applications.
Here's how my desktop looks like with different wallpapers for each monitor:

Features :

Multihead and Xinerama support.
Recall mode to restore wallpapers via startup script.
Uses freedesktop.org standard for thumbnails.
Can set GNOME background.
Command line set modes for script usage.
Inotify monitoring of browsed directories.
Lazy loading of thumbnails - conserves memory (new in 1.3).
"Automatic" set mode - determines best mode to set an image based on its size. (new in 1.4).
Display preview images in a tiled icon layout (new in 1.5).

Nitrogen seems to be the best option. Syncwall seems to be using the hack you described (large image to split across several monitors.
Comment: Do you really have multiple monitors there? It looks like. Workspaces...
Comment: I just installed `syncwall`; it doesn't have any option to set a different wallpaper for each monitor...
Comment: @Rinzwind One thing I don't understand: if *syncwall seems to use the hack described in the question*, what is the reason to add it as an answer? The question is clear: different wallpapers on multiple monitors. And another thing: if you would tested nitrogen on two monitors, you wouldn't say that the last image is photoshoped; try it yourself, make a desktop print screen when you use two monitors and you will understand what I mean.
Comment: The nitrogen solution, also described by Radu, works great! You would both deserve the bounty :) To decide which answer is better I am trying to assess the usability of the Syncwall solution. However I have been unable to get it to work. In *Preferences -> Display Parameters*, I see the option "Extend image then crop (one file per monitor)", however I can't figure how to actually add several files. Even with this option set, Syncwall uses only one file. It behaves the same as with "Extend image then crop (one file for all monitors)". Could you elaborate on how to add several files in Syncwall?
Comment: Syncwall seems to work but not to replicate the screen layout from the original question.. it doesn't let me stack screens on top of anotner but just left and right :/
Answer: the XFCE Desktop Manager Plugin (that comes in the xubuntu-desktop package) allows you to edit each display individually while still retaining the folders on your desktops.
A screenshot of my 2 desktops with the manager open :
in the yellow box it says "Move this dialog to the display you want to edit the settings for."
I'm sorry i cant be more help as to giving instruction on to how to install it, nor what the actual plug in is called ( I tried to find it but decided to re-install the whole package instead ) - But hopefully this leads you or somebody on the right track, and this answer can be improved through edits.
Answer: HydraPaper is the best option since 2020.
Answer: I was glad to see there actual was a Gnome/Unity answer.
That said, I still feel switching to KDE might offer a more consistent experence.
KDE's native settings manager not only allows for multiple wallpapers across multiple monitors, it allows them to be set differently for each virtual desktop AND Activity. (Activity's a like virtual desktops that contain virtual desktops and can be configured to have different settings, such as a screen-saver after 5 minutes of stillness in one activity, but no timeout when switched to another, say for presentations or movies.)
Moreover, it handles the addition and subtraction of monitors on the fly (via plugging and unplugging HDMI) without issue!!
Answer: sudo apt-get install feh

feh --bg-center <path_to_big_image> --no-xinerama

No need to hide your icons from desktop
Comment: Welcome to Ask Ubuntu! I recommend to [edit] this answer to expand it with specific details about what this command does. A plain command or command sequence is rarely considered an answer. (See also [How do I write a good answer?](/help/how-to-answer) for general advice about what sorts of answers are considered most valuable on Ask Ubuntu.)
Answer: I'm looking for a command line method of doing this. Hyrdapaper's OK but I don't want to have to start a GUI to pick my images. I have a script that already handles all of that, setting images are predetermined intervals. I just need to know how to set each monitor separately and/or span an image. feh looked like it might be a solution however it doesn't actually set the wallpaper. Or rather it says it but doesn't show it until the terminal I'm typing the command in loses focus (I have pointer focus on). Then the background changes for a second then goes back to my current background.
Note I'm using Mate with Compiz if that matters.


Output from maven dependency:tree, which version will override

Question: Here is an output from mvn dependency:tree
Check the dependencies for kafka.
I see it coming at two places and want to know which dependency will come into play when the application is run.
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ suite ---
[INFO] com.company.foo.qe:suite:jar:2.8.0-SNAPSHOT
[INFO] +- org.apache.kafka:kafka_2.11:jar:0.8.2-V3-PATCH:compile
[INFO] |  +- org.scala-lang.modules:scala-xml_2.11:jar:1.0.2:compile
[INFO] |  +- com.yammer.metrics:metrics-core:jar:2.2.0:compile
[INFO] |  +- net.sf.jopt-simple:jopt-simple:jar:3.2:compile
[INFO] |  +- org.scala-lang.modules:scala-parser-combinators_2.11:jar:1.0.2:compile
[INFO] |  +- org.scala-lang:scala-library:jar:2.11.2:compile
[INFO] |  +- org.apache.kafka:kafka-clients:jar:0.8.2-V3-PATCH:compile
[INFO] |  |  \- net.jpountz.lz4:lz4:jar:1.2.0:compile
[INFO] +- com.company.foo:ec:jar:2.8.0-SNAPSHOT:compile
[INFO] |  +- com.company.foo:solr:jar:2.8.0-SNAPSHOT:compile
[INFO] |  +- org.apache.kafka:kafka_2.10:jar:0.8.1.1:compile

Answer: From the documentation: "By Default Maven will solve conflicts with a nearest-win approach" [Resolving Conflicts]. This  translates to picking org.apache.kafka:kafka_2.11:jar:0.8.2-V3-PATCH:compile in your example. Also see  Transitive Dependencies
The nearest-win approach just picks  the version of the dependency closest to the left in the Maven dependency tree output. This approach chooses a dependency based on how close they are to your pom.xml dependency declaration. If you declare  dependency conflicting-2.0 explicitly in your pom that dependency will be the one picked by Maven. If you declare dependency B which in turn depends on conflicting-1.0, then  conflicting-1.0 would be considered  to be further away that of conflicting-2.0 in your dependencies.
To exemplify :
  [INFO] +- conflicting-2.0    (dependency declared in your pom, level 0)
  [INFO] +- B                  (dependency declared in your pom, level 0)
  [INFO] |  \- conflicting-1.0 (dependency declared in B,        level 1)

In this case Maven would pick conflicting-2.0 as the right version for the dependency since it is declared explicitly in the project pom.
To be sure, you can invoke the dependency tree with the -Dverbose flag (mvn dependency:tree -Dverbose) and maven will tell you which jar is not picked:
 \- (org.apache.kafka:kafka_2.10:jar:0.8.1.1:compile - omitted for conflict with 2.11)

Comment: Thank you and double thank you for the -Dverbose tip!
Comment: One question though, I dont see how the version picked up is the nearest win. What is it nearest to?


Joining multiple dataframes and duplicate columns

Question: I'm sure i'm doing something wrong but it's not obvious to me.
I have many dataframes which i want to join. I'm joining using pd.merge left joins i do this as
Database=pd.merge(df1, df2, left_on='key', Right_on='key',how='left')

Database=pd.merge(df3, df4, left_on='key', Right_on='key',how='left')

Repeating but always writing back to the database dataframe, all works fine but at the end i have multiple duplicates, ie df1_code has been repeated as df1_code_x, df1_code_x_x which is making the resultant df very large. I attempted;
Database.T.drop_duplicates().T

but this caused a cms memory error, how can i stop the columns duplicating to start with.
Comment: Can you provide a reproducible example?
Answer: I don't think you can avoid having the duplicates, at least not by means of using pd.merge with any arguments.
pd.DataFrame.drop_duplicates() seem to be working in dropping duplicate rows. That explains why you are transposing and the trying drop_duplicates. Might be an idea to use it after each merge rather than once at the end?
Also, according to your sample calls, you don't really need to define both right_on and left_on arguments. Both seem to be the same so you can save yourself the typing and tun this to:
Database = df1.merge(df2, how='left', on='key')
Database = df3.merge(df4, how='left', on='key')
...

I hope that helps


How could I do this kind of scheduled task in AppEngine Python?

Question: I have a form with a text field for entering a number without decimal
places representing an amount of minutes that will have to be added to the current time
and will be inserted into a table named Alarm.
When the resulting time comes, my web app must make an insert operation over another table.
For example, if the user enters 20 minutes, and the current time is 22:10, the result time
will have to be 22:30 and will be inserted into Alarm table. So, when the 22:30 arrives, a new insert will have to be made over the another table.
How can I do this on AppEngine using Python?
Comment: I have read this article http://code.google.com/intl/en/appengine/docs/python/config/cron.html but I don't know how to apply it to this problem.
Answer: Depending on your requirements, you may also want to consider using Tasks with an eta or countdown.
If you plan to allow users to cancel the action, you'd need to use some type of no-op marker the task checks for before adding to the "other" table.  Or, make the task check the Alarm table before performing the add.
Also, note that the countdown / eta are not precise, they are more like polite requests.  So if your queues are backing up with tasks, your adds will happen after they are supposed to.  (though cron, particularly 1 minute jobs, also periodically suffer timing issues).
The advantage of this method is that you don't have to figure out how to avoid missing work.  Each task represents one add (or a related set of adds).  Also, if a write fails the task will retry, which is nice.
Cron may be a better solution for your particular problem though.
Comment: many thanks Robert. I think the solution given by Daniel Roseman is working properly, so I'll implement
his suggestion but I'll consider your second opinion in case something start going wrong =)
Answer: You've said that you're storing the target time in the Alarm table. So, your cron just has to run every minute (or every 5 or 10, depending on the resolution of your alarms) and check if there's an alarm matching the current time, and if so then do the action.
Comment: Thanks Daniel, please correct me if I'm wrong: you suggest I must invoke from my cron to the url with the method handler that
performs a select over "Alarm" and in that method I check the current time and in case it matches the time stored on "Alarm" table I must do the action, right?


Would a projector lamp explode

Question: I have a projector lamp that has been used over its life hours. Its still working though, no colour distortion, etc. But if I keep on using it, will it just won't light up when it finally stopped working or will it explode and destroy the projector?
Answer: There is nothing explosive inside a projector bulb, so "explosion" is the wrong word here.  The glass envelope, however, can burst and that can shower glass fragments around inside the enclosure.  I've seen this happen but I have never seen a projector destroyed by it.
An older bulb can be more likely to burst due to the extreme thermal cycling they go through so you should be looking at getting a replacement soon since this on has reached the end of its useful life.
The more clear danger with such a bulb is that the filament is close to breaking and that will leave you without your projector usually when you need it the most.
Comment: The lamp compartment should keep all the glass inside itself.
Comment: "bursting and showering glass fragments everywhere" sounds like an explosion to me. Explosions don't have to be caused by explosive chemicals.
Comment: OK, would the burst strong enough to launch the glass fragments flying and hurt nearby people? Or it simply just shatter?
Answer: If used in a projector, any breakage would normally be contained by the projector housing.
Having the envelope (glass/quartz containment of the filament and halogen) burst is more common from poor handling practices (getting fingerprints on the envelope when installing the bulb) than from end of life.
Normally end of life is a boring filament break and nothing bursts.
"Life hour rating" is partly about trying to make sure that the projector does not go out in the middle of use in a professional setting (where you might be wasting hundreds of peoples time) and partly about driving profits (the company that cares about wasting hundreds of peoples time may have a different view of a bulb costing half what the projector does than a home user, but you can bet the profit on the bulb assembly is large in either case.)
Edit to add: LED "bulb" life hour rating is about maintaining rated brightness (and that is also a factor in halogen bulb life hours.)

Would a projector lamp explode


Some questions on Proof of Structure Theorem

Question: I understand the general idea of the proof of Structure Theorem for finitely generated modules over a principal ideal domain but I found it quite difficult to follow some lines of reasoning in the proof. I have spent hours tried to think about it and look for other sources but still unable to fully convince myself. Any detailed helps are truly appreciated.
The Theorem is stated as follows:

Let $M$ be a finitely generated module over a principal ideal domain $R$. Then there exist elements $d_1, d_2, ..., d_k \in R$ satisfying $d_1\mid d_2\mid\cdots\mid d_k$ such that $$M\cong R/(d_1)\oplus R/(d_2)\oplus \cdots\oplus R/(d_k).$$

Proof:
Since $M$ is finitely generated (by $k$ elements say), then $M\cong R^k/N$. But $N\le R^k\Rightarrow N\cong R^s$ for some $s\le k$. Let $\zeta:R^s\to N$ be an isomorphism. This gives a homomorphism $\varphi:R^s\to R^k$ with $\operatorname{im}(\varphi)= N, \ker(\varphi)=\{0\}$. Let $A\in M_{k\times s}(R)$ be the matrix of $\varphi$ with respect to the standard bases for $R^s$ and $R^k$. Then A is equivalent to a matrix
$$D=\begin{bmatrix}d_1 & 0 & ... & & 0\\0 & d_2 & 0 & ... & 0\\ & &.& & \\ & &:& & \\0 & 0 & 0 & ... & d_s\\0 & 0 & 0 & ... \\0 & 0 & 0 & ... \end{bmatrix},$$ where $D = XAY$, for $X\in M_{k\times k}(R)$ invertible and $Y\in M_{s\times s}(R)$ invertible. So $D=[\varphi]_{C,B}$ for some bases $B$ for $R^s$, $C$ for $R^k$. Let $C=\{f_1,f_2,...,f_k\}$ be a basis for $R^k$, then $\varphi(B)=\{d_1f_1,d_2f_2,...,d_kf_k\}$ is a basis for $N\subseteq R^k$.
So we have
$$R^k=\langle f_1 \rangle \oplus \langle f_2 \rangle \oplus \cdots \oplus \langle f_k \rangle,$$
$$N=\langle d_1f_1 \rangle \oplus \langle d_2f_2 \rangle \oplus \cdots \oplus \langle d_sf_s \rangle \oplus \langle 0f_{s+1} \rangle \oplus \cdots \oplus \langle0f_k \rangle$$
where $d_i:=0$ for $s<i\le k$. So,
$$R^k/N \cong \frac{\langle f_1 \rangle}{\langle d_1f_1 \rangle} \oplus \frac{\langle f_2 \rangle}{\langle d_2f_2 \rangle} \oplus \cdots \oplus \frac{\langle f_k \rangle}{\langle d_kf_k \rangle}.$$
But for any $v\in R^k\setminus \{0\}$, by the First Isomorphism Theorem, $\langle v \rangle/\langle dv \rangle \cong R/(d)$. Then I get:
$$R^k/N\cong R/(d_1)\oplus R/(d_2)\oplus \cdots \oplus R/(d_k),$$
$$d_1 \mid d_2 \mid \cdots \mid d_{s} \mid d_{s+1}=0 \mid \cdots$$
Exactly as I wished. $\blacksquare$
My questions are:

Why is $\ker(\varphi)=\{0\}$? I could not find any convincing explanation.
I have been told that $C$ is given by columns of $Y$ and $B$ is given by columns of $X^{-1}$. I have some understanding of change of bases but how can we show it in a more rigorous way?
The part that I struggle the most are $R^k=\langle f_1 \rangle \oplus \langle f_2 \rangle \oplus \cdots \oplus \langle f_k \rangle$ and $N=\langle d_1f_1 \rangle \oplus \langle d_2f_2 \rangle \oplus \cdots \oplus \langle d_sf_s \rangle \oplus \langle 0f_{s+1} \rangle \oplus \cdots \oplus \langle 0f_k \rangle$, what does $\langle \cdot \rangle$ represent, why are we taking their direct sum and how do we derive them?
Lastly, why can we just divide $R^k/N\cong\frac{\langle f_1 \rangle}{\langle d_1f_1 \rangle }\oplus\frac{\langle f_2 \rangle}{\langle d_2f_2 \rangle} \oplus \cdots \oplus \frac{\langle f_k \rangle}{\langle d_kf_k \rangle}$ on both sides, how can I explain/convince myself rigorously.
I have consulted other sources, in the final step, it is given that the map $\psi:R^k\to R/(d_1)\oplus R/(d_2)\oplus ...\oplus R/(d_k)$ given by $\psi(\sum_{i=1}^{k}r_if_i)=(r_1+(d_1),...,r_k+(d_k))$ is a homomorphism of $R$-modules. The result follows from FIT since $\psi$ is surjective and $\ker(\psi)=N$. How can we show $\psi$ is surjective and $\ker(\psi)=N$?
Why if $d_i=0$, then $d_i=0$ for all $j\ge i$? And why if $d_i$ is a unit, then $d_j$ is a unit for all $j\le i$?

Many thanks in advance!
Comment: Some important LaTeX tips: Please use `\cdots` or `\ldots` instead of `...`, use `\langle` and `\rangle` instead of `<` and `>`, use `\ker` and `\operatorname{im}` instead of `ker` and `im`, and write quotient structures as `A/B` instead of `\frac{A}{B}`.
Comment: I think this is a too long, complex question. Perhaps you should "chop it" down in several parts, focusing in what you've done and where you're stuck.
Comment: Thanks @DonAntonio. The proof is quite long, I wrote the complete proof for reference only. My questions are just those six. What I have done is that I am able to understand and reconstruct the proof except at those places where I got stuck. Each question is already asked specifically. Hopefully they are clear enough.
Comment: Or if necessary I can separate each question into several posts.
Answer: Some ideas:
The homomorphism $\,\phi\,$ described there could be thought of as an embedding one: note that $\,N\cong R^s\le R^k\,$ , so one can embed the former in the latter.
Of course, this embedding is usually far from being unique. From here  $\,\ker\phi=0\,$ is immediate.
The notation $\,\langle x\rangle\,$ usually denotes the cyclic (module, group, etc. ) generated by $\,x\,$ . In this case for example, $\,\langle f_i\rangle\,$ denotes the cyclic $\;R$-module  generated by $\,f_i\,$ in $\,R^k\,$ , i.e.:
$$\langle f_i\rangle:=\{rf_i\;;\;r\in R\}$$
Observe that any finitely generated $\,R$-module $\;M\;$ is the set of all the $\,R$-linear combinations of a finite number of elements of $\,M\,$ , and from here the term "basis" .
The dividing thing is just taking the quotient module...Apparently you already proved before this that the quotient takes that form (this is (5) in your questions):
$$\bigoplus_{i=1}^k\langle f_i\rangle/\bigoplus_{i=1}^k\langle d_if_i\rangle \cong\bigoplus_{i=1}^k \langle f_i\rangle/\langle d_if_i\rangle$$
Your questions about $\,\psi\,$ could probably be partially answered if you read carefully about the CRT = Chinese Remainder Theorem , which has a very similar homomorphism there, yet directly: clearly $\,\psi\,$ is surjective since any element in the direct sum of quotient modules on the right is precisely of the form $\;r_j+(d_j)\;$ , for some $\,r_j\in R\,$ , and you can take an element in $\,R^k\,$ with these $\,r_j$-s as corresponding coefficients of the basis $\,\{f_1,...f_k\}\,$ . That $\,N=\ker\psi\,$ is even more trivial (Sorry, I'm not teasing you, honest) if one understand what's the role of each thing (and this is why I thought subdividing the question in several, focused parts could help...)
Comment: DonAntonio, thanks for the answer. It was really helpful, from there I could understand my remaining questions quite easily. And thank you for the honest feedback. Yes, I will try to cut down the question to smaller chunks next time.


USB internet not accessible

Question: I'm brand new to ubuntu and linux. We access internet from a usb stick issued by a local telephone company. When I plug the stick into the computer, I see the device listed under internet connections as a mobile broadband device but it is grayed out and inaccessible.
I tried to create a new mobile broadband connection but my country (Gabon) is not listed and we have no payment plans per se (we pay from a pre-paid card system)..
Any clues as to how I can get the system to recognize the internet connection?
Thanks for any help...
Answer: you have a option here . If your country not listed then you have option for that also . I mean look this

The only thing here matters is APN of your Network , no matter how you pay .
Hope that helps .
Comment: From what the user said the option is grayed out and inaccessible. So he may not be able to do that
Comment: If there is no connection created then it will grayed out .
Comment: I also have an USB internet stick and that's not what happens. The option is not grayed out or inaccessible.

USB internet not accessible


Dynamically adding a textbox to a panel on button click

Question: I just don't understand how this is done. I've gone through several questions here and from a few other websites.
Basically, a company will be adding process steps, and I want there to be a textbox with a button next to it that reads "Add another step." Once clicked, a new textbox will appear beneath the current one, and the button will be moved next to the new text box. What do I need to do?
Comment: Creating the controls manually seems like a very cumbersome method. Would a grid with an add new row at the bottom not be enough?
Comment: Maybe, I'd just like to learn this way since it does seem like it could be useful.
Answer: Well things will get a little more complex once you ask how to maintain ViewState.  However, since you didn't ask that (yet), the simple answer is just that on button click event you should instantiate a new TextBox and Insert it into the Controls before the Button.
Comment: I've done that, but it only adds one more, then it doesn't do anything but refresh the page it seems
Answer: Okay, finally found an answer I can understand. Using listviews seems to be a good way to go. I found this website
Link
And I got the results I wanted.


Why items such as leather strips keep disappearing from my chests?

Question: In The Elder Scrolls V: Skyrim, with the Hearthfire DLC, my items, such as leather strips, keep disappearing from chests in my Falkreath home. This is very annoying.
My wife Ysolda lives in this house. She keeps selling me my own stuff for 100+ gold each. I can't kill her.
Why are my items disappearing?
Comment: Where are these chests? In your marital house? Which house is that?
Comment: Yes they are in my house on the property in falkreath
Comment: Who is your spouse? After a little research (http://gaming.stackexchange.com/questions/37587/how-is-the-inventory-of-a-spouses-shop-determined, https://steamcommunity.com/app/72850/discussions/0/483368526573218533/, http://www.uesp.net/wiki/Skyrim_talk:Marriage/Archive_4#Spouses_Taking_Stored_Items) it sounds like whether the spouse was a trader or not before may affect how they acquire their items.
Comment: Ysolda from whiterun.
Comment: I all noticed you play fallout 4 so I had a question
Comment: If you have a question about Fallout 4, post it as a question. I'll certainly look at it, and so will other users.
Answer: I've found references to others having this same issue: (1, 2). It doesn't match the designed behavior reported by most of the people that play the game, and therefore appears to be a bug. It seems to only affect Xbox players.
There's no known solution or cause. It seems that you simply need to store your items somewhere else so that your greedy wife can't get to them.
Set up a man-cave.
You need to put your stuff in safe locations or containers. These are places that don't respawn, meaning that your stuff will still be there when you get back.
This includes houses you've bought such as your marital home, obviously, but also quite a few other places. I put the list in another answer, and there's also a whole question devoted to the subject.
Comment: OK thank you a lot I invested in the 10 safes in the celler of my house and everything's safe
Comment: @EverettMatthews No problem. Sorry I couldn't provide a real solution. If you find an answer useful, don't forget to upvote.


Binary Injection into ELF File

Question: I have an ELF file generated through the SDCC compiler using the —out-fmt-elf and —debug options. I need to inject data into the actual binary (this will be loaded to an STM8 microcontroller). Doing this with a hex file is easy, as I can just directly specify the memory address I want the bytes in. However, since SDCC appears to have hacked in DWARF debug support, it is impossible as far as I can tell to split the ELF file into a Hex and Debug file, then rejoin them. Theoretically I could do this with SDCDB, but that doesn't work with my project infrastructure. It is looking for a main.c, main.asm, project.hex, and project.cdb. When I point it to these files it breaks and I am assuming it is because of how the directories are structured. I would also overall prefer to be able to use GDB.
Is there a way I can inject ~250 bytes at a specific memory address into an ELF file?
Thanks!
Answer:
Is there a way I can inject ~250 bytes at a specific memory address into an ELF file?

Sure: declare the data so it exists in appropriate section and with desired size, e.g.
__attribute__((section, ...))
char my_data[256];

Build/link your binary with a linker script to locate my_data at desired target address.
After the link, find the offset of the data in the file and write desired (new) bytes at that offset.

Binary Injection into ELF File


Pest-proof and air-seal electrical wire penetrations in stud walls

Question: I'm replacing all the wiring in my house, and I've decided that I would like to make it as difficult as possible for any bugs or rodents to travel inside my wall cavities through the holes that electrical wiring and pipes run through.  Is there a "best" way to seal up the holes that the NM cable runs through?
I considered the 3M red foam, but I'm not sure if that's effective against bugs and rodents.  Should I pack the holes with rockwool, then cover that with fire block caulk?
Answer: Plug the holes with fire caulk (IMHO rockwool serves no useful purpose in your proposed scheme.)
If you really want to do a better job, particularly with respect to rodents, ditch the NM and use MC or AC cable instead, or run EMT conduit. But for sealing the penetrations, that's what fire caulk is made to do.
Comment: Thanks.  I just mentioned the rockwool as packing if the hole size was too large for the fire caulk.  I wasn't sure what size gap I could fill with that.  I haven't even ripped down the drywall, so I don't know what I'm going to find in there when I do.  The house was built in 1978, so...


Proving that $R$ is an equivalence relation.

Question: Let $A$ be the set of all statement forms in three variables $p$, $q$, and $r$.  Let $R$ be the relation defined on $A$ as follows: For all $P$ and $Q$ in $A$,
$$P\; R\; Q \longleftrightarrow P\; \mbox{and}\; Q\; \mbox{have the same truth table.}$$
Prove that $R$ is an equivalence relation.
Comment: @JohnMaddux we don't edit out the details of the question once it has been answered. On the other hand, I'm not sure how to do the Rollback thing, so I'll just edit the question back in
Comment: ive been looking at it for a couple hours and i dont even know where to begin
Answer: equivalence relations have three properties, check them one by one for your 'same truth table' relation
Comment: yes, reflexive, symmetric, transitive. how would i find these properties from a truth table?
Comment: you don't even need to know what a truth table is. you need to check (1) '$P$ has the same truth table as $P$', (2) 'if $P$ has the same truth table as $Q$ then $Q$ has the same truth table as $P$' and (3) 'if $P$ has the same truth table as $Q$ and $Q$ has the same truth table as $S$ then $p$ has the same truth table as $S$'
Comment: maybe i misread the question. my understanding was that pRq <--> p has the same truth table as q.  does this mean that pRq has the same truth table as p?
Comment: no, $R$ is shorthand for 'has the same truth table as'
Comment: i did not know that! thanks! this makes the problem very simple!


Log4net External Configuration (C#)

Question: I don't know if it is possible to do the following using log4net.
I have a service which reads all its configuration at startup from a database. Within the configuration there is log configuration like "log level" and "logfile location".
The requirement is to write all the log, including the log from service startup to the log file location read from the database (this is of course if there was any problem connecting to the database).
A coworker wrote a very simple log class to fulfill this requirement, but I would really like to use log4net in order to use several features that log4net already provides.
Do you have any idea in how to make this?
Answer: The easiest hack is to read the existing configuration from database at startup, and then generate an external config file which matches log4net's format.
Then you can ask log4net to read this file directly, following "Reading Files Directly" section in this article,
http://logging.apache.org/log4net/release/manual/configuration.html
Comment: That solve half of the problem, although the real "problem" is that the log from service startup will not be written to the logpath that is configured in the database. PS. I do not read configuration directly from database, the service is integrated to a framework that connects through an API that internally makes a TCP connection to a configuration server in order to get the service configuration. I'm interested in log this connection among other things to the configured logpath
Comment: Is it OK that you provide a set of default log4net settings at startup, so that before loading the new settings all log entries go to a default log file? That's a workaround which gives you enough information if you want to troubleshoot the connection. Alternatively, if you really want to write all log entries to "logpath", then you will have to cache log entries before loading new settings. I never did that, and I am not sure whether log4net already has some support for caching.
Comment: Exactly that support for caching is what I'm looking for. I don't know, maybe using a custom appender or modifying some property in log4net. I proposed the same workaround you suggested but apparently it is not acceptable, that's why we are using a very simple logger implementation a coworker did.

Log4net External Configuration (C#)