two way merge sort for 2 file c++

Question: I was asked to apply Two way merge sort on two files(files of records) ,
the algorithm explains the steps as follows :

Sort phase
  1)The records on the file to be sorted are divided into several groups.
  Each group is called a run, and each run  fits into main memory.
  2)An internal sort is applied to each run, 3)and the resulting sorted runs are distributed to two external files.
Merge Sort: 1) One run from each of the external files created in the sort phase merge into a larger runs of sorted records.
  2)The result is stored in a third file.
  3)The data is distributed back into the first two files, and merging continues until all records are in one large run.

I was able to apply Sort Phase only , so the current files is :
(supposed run contains 3 keys only )

file 1:
  50 95 110 | 40 120 153 | 22 80 140
file 2:
  10 36 100 | 60 70 130

here's the steps of merge phase
so if i will solve it theoretically will perform the following :
Merge Phase:
step1 :
file 3 :
 10 36 50 95 100 110 | 40 60 70 120 130 153 | 22 80 140
file 1:
10 36 50 95 100 100 | 22 80 140
file 2 :
40 60 70 120 130 153
step 2 :
file 3 :
10 36 40 50 60 70 95 100 110 120 130 135 | 22 80 140
file 1 :
10 36 40 50 60 70 95 100 110 120 130 135
file 2:
 22 80 140
step 3 :
file 3 :
10 22 36 40 50 60 70 80 95 100 110 120 130 135 140
one run stop sort complete
Now i need to apply merge phase so each key from each file compared to each other and output the smaller to file 3 , and in step 2 redistribute file 3 into two file then merge and sort until have one sort run
How i can apply such algorithm in c++ , i'm little bit confused about how can i determine the size of each run in every step.
Comment: What are you expecing the contents of "file 3" to be?
Comment: i updated the thread with photos check it .
Comment: I think I don't understand the sorting criterion.
Comment: depends on size of block
Comment: Please, edit your question by including both the algorithm and the steps as *text*, not as links to images. This will make your post more clear.
Comment: done check the thread
Comment: The (maximum) size of each run seems to simply double at each step. You can start from one or use a bigger first size and an alternative sort algorithm for the first step.
Comment: If the same process handles the whole thing, it will keep track of how big the runs are. If you want to be able to have all state on disk between steps, you have to invent some way of indicating in the files how long the runs are. I don't know if this is the question you asked.
Answer: As commented by Amdt Jonasson, the program needs to keep track of the run sizes and the end of data for each file. In your example it appears the initial run size is a fixed run size of 3 elements. A merge of two runs of size 3 will result in a single run of size 6 as shown in your steps. In this case, only a single instance of run size and the end of data in each file needs to be tracked.
If the sort is to be a stable sort (the original order preserved on equal keys), and the run size is variable, then an array of run counts for each file will be needed, or some way to denote the end of runs in the file, such as a text file, with a special character sequence used as a end of run indicator.
If the sort is not required to be stable, then an out of order sequence (smaller key value after a larger key value) can be used to indicate the end of a run. The risk here is that two or more runs will appear to be a single run if the runs happen to be in order, which will lose stability and unbalance the run count on the files.
This is a two way merge sort using 3 files. If you use a 4th file, then each merge of runs can alternate between 2 output files, eliminating the need split up the runs after each merge pass.
An alternative for doing a 2 way merge sort with 3 files is a polyphase merge sort, but it's complicated, probably beyond what would be expected for a class assignment, and more of a "legacy" algorithm used back in the days of tape based sorts.

two way merge sort for 2 file c++


Pushing multiple images to docker hub in Jenkins automatically

Question: In the Jenkins file we built multiple docker images. We need to push the images automatically to docker hub without having to write the name of the images every time. Note that the number of images built each time could be different and we have to track what are the new images built and only push those images in Jenkins script.
Answer: AFAIK, there is no readymade tactic for this. You would need to design it.

Findout which new images are built. For this, you may compare the checksum with pushed images.

Push every image in separate thread. Basically use multithreading or background job


JQuery .height(x) is doubled in IE8?

Question: I have a series of Divs in a wrapper, and I need to equalize the height of the two columns. We are using a simple jQuery plugin to do this, which fires the following function:
//find heights of all children, and find the tallest
this.each(function() {
    if ($(this).height() > tallest) {
        tallest = $(this).height();
    }
});
if ((maxHeight) && tallest > maxHeight) tallest = maxHeight;
//assign the tallest height to all child elements
return this.each(function() {
    console.log('tallest: ' + tallest);
    $(this).height(tallest).css("overflow", "visible");
});

console.log is showing a height of 2131px in IE8, however, the target div is being given a height of 4262 px (exactly double?). I stepped through the code, and I see that .height(tallest) is being executed with the proper value, but somehow IE8 and only IE8 is giving it double height.
Edit:
So far I have tried .height(2131) .height('2131px') .css("height","2131px"), and .css('min-height', "2131px"). All with the same effect. Coming up with a use case might be a bit difficult as this is a big, "enterprisey" system, but I'll see if I can replicate it...
Comment: Does this also happen if you only just execute `$(some_element).height(2131)`? Perhaps providing a test case is helpful since I cannot reproduce. http://jsfiddle.net/9C6Qe/
Comment: Try outerHeight(), see if that makes a difference.
Comment: What happens if you take out large parts of or even all of the stylesheets? I've seen IE8 & jQuery behave very strange (up to crashing the JS engine and not showing a page at all) with particularly complex CSS files (i.e. the problem turned out to be the css, not the JS).
Answer: Funny thing is, the .height() jQuery documentation shows a lot of IE8 remarks in the comments, ultimately leading to this other SO question which may help you as well.
Comment: unfortunately I am in IE8 compatability mode, using the html 5 doctype, and confirmed using this script: `javascript:window.alert('You are in ' + (document.compatMode==='CSS1Compat'?'Standards':'Quirks') + ' mode.')`
Comment: Ah shame. In that case I second @pimvdb's comment to your question: a test case would be nice to help out any further.
Answer: It seems as though whoever coded the page before I was responsible for maintaining it had an extra closing  tag, messing the whole thing up. 9_9

JQuery .height(x) is doubled in IE8?


How to configure nullmailer to work with mailchimp?

Question: As my title said i have some problem with configuration of nullmailer.
Basicaly I have been following this website.
I have made an account on Mailchimp - where I have send succesfully the test mail. On my machine i have installed Nullmailer:
Then I have configure the remotes:
smtp.mandrillapp.com smtp --port=587 --starttls --email@example.com --pass=boo

I have set the adminaddr
cat /etc/nullmailer/adminaddr
firstname.lastname@example.com

The defaultdomain remains empty
This is how my mail.log looks like:
EDIT
After adding --insecure flag
Jun 13 17:06:23 tom-VirtualBox postfix/cleanup[5176]: 9A8C31A68: message-id=<email@example.com>
Jun 13 17:06:23 tom-VirtualBox postfix/qmgr[5047]: 9A8C31A68: from=<firstname.lastname@example.com>, size=345, nrcpt=1 (queue active)
Jun 13 17:06:24 tom-VirtualBox postfix/smtp[5178]: connect to gmail-smtp-in.l.google.com[2a00:1450:4010:c03::1b]:25: Network is unreachable
Jun 13 17:06:25 tom-VirtualBox postfix/smtp[5178]: 9A8C31A68: to=<firstname.lastname@example.com>, relay=gmail-smtp-in.l.google.com[126.96.36.199]:25, delay=1.8, delays=0.45/0.09/0.67/0.61, dsn=5.7.1, status=bounced (host gmail-smtp-in.l.google.com[126.96.36.199] said: 550-5.7.1 [184.108.40.206] The IP you're using to send mail is not authorized to 550-5.7.1 send email directly to our servers. Please use the SMTP relay at your 550-5.7.1 service provider instead. Learn more at 550 5.7.1  https://support.google.com/mail/?p=NotAuthorizedError p3si308852ljp.41 - gsmtp (in reply to end of DATA command))
Jun 13 17:06:25 tom-VirtualBox postfix/cleanup[5176]: 8345A1AFF: message-id=<email@example.com>
Jun 13 17:06:25 tom-VirtualBox postfix/qmgr[5047]: 8345A1AFF: from=<>, size=2986, nrcpt=1 (queue active)
Jun 13 17:06:25 tom-VirtualBox postfix/bounce[5179]: 9A8C31A68: sender non-delivery notification: 8345A1AFF
Jun 13 17:06:25 tom-VirtualBox postfix/qmgr[5047]: 9A8C31A68: removed
Jun 13 17:06:25 tom-VirtualBox postfix/local[5180]: 8345A1AFF: to=<email@example.com>, relay=local, delay=0.32, delays=0.08/0.21/0/0.03, dsn=2.0.0, status=sent (delivered to mailbox)
Jun 13 17:06:25 tom-VirtualBox postfix/qmgr[5047]: 8345A1AFF: removed

But I do not really know where to go from this point. Any Ideas?
Thanks.
Comment: Did you try the `--insecure` flag?
Answer: So the fix was in the end quite simple.
I needed to allow less secure application access here. As well as --insecure flag in the remote file was necessary.


Finding $E\left(\frac{X_1 + X_2}{2}\mid X_1+\cdots+X_n=y_1\right)$ where $X_i$'s are i.i.d Binomial$(1,\theta)$

Question: Let $X_1,X_2,\ldots,X_n\,, n > 2$  be a random sample from  the binomial distribution $b(1, \theta)$.
I have shown $$Y_1 = X_1 + X_2 + \cdots + X_n$$ is a complete sufficient statistic for $\theta$ and $$Y_2 = \frac{X_1 + X_2}{2}$$ is unbiased estimator of $\theta$.
The question ask also to find $$E(Y_2\mid Y_1 = y_1)$$
So I am thinking to find the conditional distribution then find the expectation.
\begin{align}
P(Y_2=y_2\mid Y_1=y_1)&=\frac{P(Y_2=y_2,Y_1=y_1)}{P(Y_1=y_1)}
\\\\&=\frac{P(Y_2=y_2)P(Y_1-Y_2=y_1-y_2)}{P(Y_1=y_1)}
\end{align}
But I do not know the distribution of $Y_2 = (X_1 + X_2)/2$.
The question from Introduction to Mathematical Statistics Hogg 7ed page 401 problem 11.
Comment: Please learn some basic MathJax [here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) for typsetting math on this site.
Answer: You do not need the distribution of $Y_2$ to find the conditional expectation.
Since $\sum_{i=1}^n X_i\sim b(n,\theta)$ , and $X_1$ and $\sum_{i=2}^n X_i$ are independently distributed, we directly get
\begin{align}
E(X_1\mid Y_1=y_1)&=P(X_1=1\mid Y_1=y_1)
\\\\&=\frac{P(X_1=1)P\left(\sum_{i=2}^n X_i=y_1-1\right)}{P\left(\sum_{i=1}^n X_i=y_1\right)}
\\\\&=\frac{\theta\binom{n-1}{y_1-1}\theta^{y_1-1}(1-\theta)^{n-y_1}}{\binom{n}{y_1}\theta^{y_1}(1-\theta)^{n-y_1}}
\\\\&=\frac{\binom{n-1}{y_1-1}}{\binom{n}{y_1}}\\\\&=\frac{y_1}{n}=\bar x
\end{align}
So, once again,
\begin{align}
E\left(\frac{X_1+X_2}{2}\mid Y_1=y_1\right)&=\frac{1}{2}\left(E(X_1\mid Y_1=y_1)+E(X_2\mid Y_1=y_1)\right)
\\&=\frac{1}{2}(\bar x+\bar x)=\bar x
\end{align}
Comment: Of course, symmetry arguments (more precisely, *exchangeability*) give instantly the result (as explained several times on the site).
Answer: You do not need the biniomal knowledge.  In general, if the $X_i$ are i.i.d. with any distribution with finite expectation, then clearly $E\left[X_1+\cdots+X_n \mid X_1+\cdots+X_n=y\right] = y$, so by symmetry and exchangeability
$$E\left[X_i \mid X_1+\cdots+X_n=y\right] =  \frac1ny$$
and thus with $n \ge 2$ $$E\left[\tfrac{X_1+X_2}{2} \mid X_1+\cdots+X_n=y\right] =  \frac1ny$$ too
Answer: $P(Y_2 = y_2) = P(X_1 + X_2 = 2 y_2) = \binom{2}{2y_2} \theta^{2 y_2} (1-\theta)^{2 - 2y_2}$ for $y_2 \in \{0, 1/2, 1\}$.


I can't get the Knight's Honor trophy

Question: Knight's Honor trophy will not come up. I've looked all over the net and I have all the weapons. Can someone give me the full list of what they are, please? I need to know if the trophy is glitched or not.  I got a list of all the weapons I need but it still did not come up.  Does anyone know how to resolve this?
Comment: Please stop making low-quality edits to the question. The question is fine as it is.
Comment: Adding help into the title doesn't help your case; the whole *point* of this site is to help.
Comment: are the weapons all on one character?
Comment: yea it all on one
Comment: what about Shields
Comment: yea i have all i think . i need the full list to make sure
Comment: well if you go to the link it will tell you, Ill add it into the answer since you didn't click the link.
Comment: thank u i will see if have them or not i just wrort a it down
Comment: i have them all and the trophie will no pop up HELP
Answer: A quick duckduckgo search provided :Link To Guide With Items
Chaos Blade
Crystal Ring Shield
Darkmoon Bow
Dragonbone Fist
Dragonslayer Spear
Golem Axe
Great lord Greatsword
Greatshield of Artorias
Greatsword of Artorias
(True) Greatsword of Artorias
Lifehunt Scythe
Moonlight Butterfly Horn
Quelaag's Furysword
Smough's Hammer
Tin Darkmoon Catalyst
--Weapons or Shields dropped by enemies--
Black Knight Greataxe
Black knight Greatsword
Black Knight Halberd
Black Knight Shield
Black knight Sword
Channeler's Trident
Crest Shield
Crescent Axe
Demon's Spear
Giant's Halberd
Grant
Sanctus
Silver Knight Shield
Silver Knight Spear
Silver Knight Straight Sword
Stone Greatshield
Stone Greatsword
--Weapons found as treasure--
Astoria's Straight Sword
Blood Shield
Dragon Crest Shield
Dragon Tooth
Dragonslayer Greatbow
Effigy Shield
Havel's Greatshield
Velka's Rapier
--Weapons or Shields acquired from covenants--
Dark Hand
Gravelord Sword
Dragon Greatsword
-- Weapons acquired from cutting off boss tails--
Drake Sword
Dragonking Greataxe
Moonlight Greatsword
Priscilla's Dagger
Answer: There seems to be an issue obtaining this trophy when you've used the Bottomless Box glitch to obtain all of the weapons. Downgrading one of your weapons and re-ascending it may help.
See here for more details: http://forums.demonssouls.info/viewtopic.php?f=76&t=15092

I can't get the Knight's Honor trophy


Which Kubernetes client-go methods are safe for concurrent calls?

Question: The Kubernetes client-go package includes a nice example of creating a single deployment using the client-go api.
I want to create and destroy many kubernetes resources without waiting for each http request to complete.
Is it possible to use the client-go api asynchronously?
Are methods like the ones below safe for concurrent calls from multiple goroutines?
resultPod, err := clientset.CoreV1().Pods("default").Create(desiredPod)

Comment: According to a reputable source in the Kubernetes slack channel: "We use shared clients everywhere in kube itself. They are goroutine safe."
Answer: The k8s client uses http.Client internally which is safe to call concurrently. But it is probably wise to limit the number of concurrent API calls to a reasonable upper limit (I'd start with 4; anything above that is probably not going to improve performance much).


Finding the values of dictionary while looping through a list

Question: I have a list of dictionaries that holds the data of employee and their attendance. I want to find the list of dates(might have 2 of the same date) that the record exists in the list and the dates that it does not exist.
attendance_list = [
{'employee_name': 'Bob', 'attendance_date': '2021-04-01', 'status': 'Present'},
{'employee_name': 'Bob', 'attendance_date': '2021-04-05', 'status': 'Present'},
{'employee_name': 'Bob', 'attendance_date': '2021-04-08', 'status': 'Half Day'},
{'employee_name': 'Bob', 'attendance_date': '2021-04-08', 'status': 'On Leave'},
{'employee_name': 'Bob', 'attendance_date': '2021-04-09', 'status': 'On Leave'}
]

Example: From 2021-04-01 to 2021-04-10
I thought of extracting the list of dates from the list and loop through the dates but how do I find the values of the dictionary inside ?
dates = ['2021-04-01', '2021-04-02', '2021-04-03', '2021-04-04',
'2021-04-05', '2021-04-06', '2021-04-07', '2021-04-08', '2021-04-09',
'2021-04-10']
attended_date = [d['attendance_date'] for d in attendance_list if 'attendance_date' in d]

for d in dates:
  if d not in attended_date:
    print("Not in List")
  else:
    print("In List") #get the values of dict

Comment: try `if d['attendance_date'] not in attended_data:`
Comment: This is not clear at all.  You say that you're trying to get values from a dict, but your code doesn't refer to the dict at all.  Your `attended_date` list is a hand-crafted list of all the dates in the dict, and your loop logic is a questionable version of list intersection.
Comment: Please go through the [intro tour](https://stackoverflow.com/tour) and especially [how to ask a good question](https://stackoverflow.com/help/how-to-ask)  to see how this site works and to help you improve your current and future questions, which can help you get better answers.
Comment: My bad. I edited the `attended_date ` list
Answer: It looks like the list you want is the dicts where the attendance_date is in attended_date. You can do this with list comprehension (docs).
[
    attended_employee for attended_employee in attendance_list
    if attended_employee['attendance_date'] in attended_date
]


Parameterizing labels

Question: Is it possible to add a label to a new node in Neo4j using parameters?
For example:
CREATE (N){nodeLabel}

With parameters:
nodeLabel = "Widget"

I've attempted to do this but have only seen exceptions.
Answer: Currently labels cannot be parameterized. Feel free to file a feature request on https://github.com/neo4j/neo4j/issues/new.
Answer: In short - no. See also this post on Google Groups where I have a poor workaround (for Java/SDN anyway).
Whoo hoo, issue 2000 created to request this feature

Parameterizing labels


Can I move the main electrical panel to the unattached garage?

Question: My main electrical service runs overhead from a pole behind my unattached garage, to the back of the house.  There is also an underground conduit from the house to the garage supplying a sub panel there.  Because I've had tree limbs pull this line down in a storm, and because the overhead wires are in the way of some home improvement projects, I've been considering having the lines buried.  I'm wondering if I have another option.  Can I have things rewired so the garage panel becomes the main panel supplying the panel in the house?  This would allow a very short overhead connection from the pole to the garage.
Thank you for any feedback.
Comment: You'll have to have the meter moved,  put new conductors between the buildings, and possibly make a few other upgrades.  But it's likely possible.
Answer: There's a few ways to do this, though service conductors cannot pass through another building, so all the methods will have to avoid that.
One option would be to install a service disconnect, and then branch from that to the panels.

With this method, you'll handle all the grounding and bonding of the neutral in the disconnect.  So you'll install 4 wire feeders from the disconnect to each panel, and keep the neutral isolated in each panel.
Another option is to use the first panel as the service disconnect, and feed the second panel from the first.

With this method, you'll handle all the grounding and bonding of the neutral in the first panel.  So you'll feed the second panel with a 4 wire feeder, and isolate the neutral in the second panel.
With is approach, the first panel will have to be rated to handle the total current of both panels.
In all cases, you're going to need properly sized feeders, and a grounding electrode system for each building.

The scope of this project is far too vast for a short answer format site, such as this.  I've given a high-level overview of how you might approach the project.  For a more detailed plan, please contact a local licensed Electrician.


How do you make Seahorse (Gnome Keyring) store passwords for ssh keys in?

Question: I'm trying to get Seahorse to remember the password for an existing RSA key I've copied across from another computer.
When I use the key rather than Gnome Keyring prompting me for the password and storing it on the keyring I have to enter the password in terminal and the password isn't remembered?
How do I use Seahorse to save my SSH key password?
Answer: You can also use ssh-add to add the key to the keyring. (This one worked for me whereas the "Configure key..." did not.)
Answer: Problem solved, needed to add the key to be used for each particular machine.
Can do this by going to,
Gnome Keyring -> My Personal Keys -> Right click on key -> Configure key for secure shell
Answer: Use an ssh-agent that remembers your ssh passwords, e.g. https://wiki.gnome.org/Projects/GnomeKeyring/Ssh
Comment: Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


Matlab - Distances of two lines

Question: I have two lines, one straight and one curvy. Both have an arbitrary number of x and y values defining the lines - the number of x and y values are not the same for either line. I am attempting to get separate distances of points between the curved line coordinates and the straight line coordinates. You can think of discrete integration to get a better picture of what I'm talking about, something along the lines of this: http://www.scientific-solutions.ch/tech/origin/products/images/calculus_integral.gif
By adding the different distances, I would get the area. The part on which I am stuck is the actual synchronization of the points. I can simply compare the x and y values of the straight and curve coordinates every ten indices for example because the curved coordinates are time dependent (as in the points do not change at a general rate). I need a way to synchronize the actual coordinates of the two sets of points. I thought about interpolating both sets of points to a specific number of points, but again, the time dependence of the curved set of points makes that solution void.
Could someone please suggest a good way of doing this, outlining the basics? I really appreciate the help.
Code to be tried (pseudo):
xLine = [value1 value2 ...]
yLine = [value1 value2 ...]
xCurve = [value1 value2 ...]
yCurve = [value1 value2 ...]

xLineInterpolate = %interpolate of every 10 points of x until a certain value. same with yLineInterpolate, xCurveInterpolate and yCurveInterpolate.

Then, I could just take the same index from each array and do some algebra to get the distance. My worry is that my line values increase at a constant rate whereas my curve values sometimes do not change (x and y values have different rates of change) and sometimes do. Would such an interpolation method be wrong then?
Comment: Your question seems to be better suited to the [Math StackOverflow site](http://math.stackexchange.com/). But, that aside, if you've done any work towards your problem in Matlab, and are in need to working through it, you could post it here.
Comment: @jrd1 - apologies, didn't realise this "Software that mathematicians use" was in their FAQ. I've pinged the Maths mods to review the question and let me know if ok to migrate.
Comment: intl - please don't cross-post your question, and as jrd1 has rightly pointed out, any work (read code) you've done in Matlab for this question might be  useful supplemental information.
Comment: @intl, we all make honest mistakes. That being said, the reason why I suggested that it be migrated to http://math.stackexchange.com/ is because you were asking how to approach the problem mathematically, which also implied you were attempting / or will attempt to code it after you've figured out how to do it - which is where you are now. That's why. Not because Matlab is the software that Mathematicians use - since its use is not exclusive to Math, it is used in a variety of fields (even Psychology). But, if you have attempted a solution, and need help with it, then here's the right place.
Comment: Would you like this migrated over to the Maths site, or are you happy enough here? One of the Maths mods also suggested reading this: http://mathoverflow.net/questions/40748/intuition-behind-the-notion-of-distance-between-curves/40774#40774 - which is on the the *other* maths website. @ ping me or flag if you'd like this.
Answer: If I understand correctly, you want to know the distance between a straight line and a curve. The easiest way is to perform a coordinate transformation such that the straight line is the new x-axis. In that frame, the y-values of the curved line are the distances you seek.
This coordinate transformation is equal to a rotation and a translation, as in the following:
% estimate coefficients for straight line
sol = [x1 ones(size(x1))] \ y1;
m = sol(1); %# slope
b = sol(2); %# y-offset at x=0

% shift curved line down by b
% (makes the straight line go through the origin)
y2 = y2 - b;

% rotate the curved line by -atan(m)
% (makes the straight line run parallel to the x-axis)
a = -atan(m);
R = [+cos(a) -sin(a)
     +sin(a) +cos(a)];
XY = R*[x2; y2];

% the distances are then the values of y3.
x3 = XY(1,:);
y3 = XY(2,:);

Answer: You need to use interpolation. I don't see how the time-dependence is relevant here - perhaps you are thinking of fitting a straight line to both curves? That's a bad idea.
You can do a simple interpolation for any curve just by assuming that every two adjacent points are connected by a straight line. This can be shown to be a reasonable approximation for the curve.
So, let's say you are looking at (x1,y1) and (x2,y2) which are adjacent to each other and now you choose an x3 that is between x1 and x2 (x1 < x2 < x3), and want to find the y3 value.
A simple way to find y3 is the following:
p=(x3-x1)/(x2-x1)
y3=y1+p*(y2-y1)

The idea is that p shows the relative position between x1 and x2 (0.5 would be the middle, for example), and then you use p as the relative position between y1 and y2.
Comment: I meant time dependence as in some x and y values for the curves change more slowly and some other change more quickly.
Comment: @intl the fact that the values change at different rates shouldn't matter, this is taken into account in the slope.

Matlab - Distances of two lines


Can I update a column I created to show the day of the week from an existing date column in BigQuery?

Question: I created a column called DayofWeek, and I am attempting to update it and insert that day of the week for the date that is in an existing column called ActivityDate.
<code>##Used to create the column
ALTER TABLE `bellabeat-case-study-2-376122.fitbit_data.daily_activity`
ADD COLUMN DayofWeek String;
</code>
<code>##This query brings up the day of the week
SELECT
  FORMAT_DATE('%A', ActivityDate) AS DayofWeek
FROM
  `bellabeat-case-study-2-376122.fitbit_data.daily_activity`
</code>
I attempted to update the DayofWeek column but I couldn't come up with a query that didn't give me any errors.
Answer: This should update aö rows.
The qiestion remains do you need it really. as you could always select it in your query
<code>UPDATE   `bellabeat-case-study-2-376122.fitbit_data.daily_activity`
SET DayofWeek  = FORMAT_DATE('%A', ActivityDate)
</code>


javascript, polymorphic new Myclass()?

Question: I have many classes that has the following form.
static defaultInstance() {

 if (!defaultInstance) {
   defaultInstance = new Child1()
 }
 return defaultInstance
}

Since they have a common base class, I wanted to add the common function to the base class, but don't know how.
(having trouble with new Child1())
Comment: have you tried looking at this answer? http://stackoverflow.com/questions/27642239/what-is-polymorphism-in-javascript
Answer: If Child1 is supposed to refer to the "current" class, i.e. the class that defaultInstance is invoked on, then you can just do
defaultInstance = new this();

This follows the normal JavaScript rules: If you invoke the function with Child1.defaultInstance(), then this refers to Child1.
However, this probably doesn't do what you want. If you define defaultInstance on the base class, then all child classes share the same defaultInstance variable.
If you want to have an instance per class, then each class needs its own defaultInstance method, or you need to use a property instead, e.g.
if (!this.__defaultInstance) {
  this.__defaultInstance = new this();
}

Comment: *"each class has its own __defaultInstance"* Yes. *"I guess map variable could live in someplace where all classes can access/share."* That could just exist in the bas class file.
Comment: Any reason not to use a `Map` instead of `__defaultInstance`? Also that would need to be `this.hasOwnProperty('__defaultInstance')` or the class inheritance could break it.
Comment: You mean a `class name -> instance` map? That would work too. Or maybe a `WeakMap`.
Comment: e.g. `map.set(this, new this());`. Good call that WeakMap probably makes more sense, though unless you're dynamically declaring subclasses, the Map will probably be relatively static.
Comment: Your description of my problem is very correct, I'm a bit lost on the solution part though, `__defaultInstance` is a static member variable and each class has its own __defaultInstance ? I guess `map` variable could live in someplace where all classes can access/share.

javascript, polymorphic new Myclass()?


Save array with multiple columns to csv

Question: If i write like this i get the csv file i want
a = asarray([ [1,2,3], [4,5,6], [7,8,9] ])
savetxt("foo.csv", a, delimiter=",")

but the problem is that for getting the values I have something similar to this:
for j in range(3):
    for i in range(3):
        e = get_val(i)  # so I get 1,2,3; next loop 4,5,6 and third 7,8,9

So I tried to make the array in the format I needed by using append but it
seems I get
a = [1,2,3,4,5,6,7,8,9]

So does anyone know how to have the array in the required format?
Note: the input in the real app I'm working in is the skeleton point in openpose
Comment: If you want help clean up the formaatting.  Show what you need and what you get,
Comment: yes u are right
Answer: I think you need to nest two loops, something like this:
a = []
n = 1
for j in range(1,4):
    b = []
    for i in range(1,4):
        b.append(n)
        n += 1
    a.append(b)
print(a)

You're on the right track, but need to initialize two lists. The inner list, let's call it b, needs to be reinitialized at the beginning of every outer loop, or it will keep growing to 6 and then 9 items long.
Comment: No problem! Would you mind marking it answered, and upvote useful?
Answer: Let's try this backwards. Suppose we have this linear list a, we can make
that into a numpy array as follows. This would allow you to use your function
get_val instead.
import numpy as np

a = [1,2,3,4,5,6,7,8,9]
b = []
for j in range(3):
    b2 = []
    for i in range(3):
        e =  a[3*j+i] # get_val(i)
        b2.append(e)
    b.append(b2)
print(np.asarray(b))
# [[1 2 3]
# [4 5 6]
# [7 8 9]]

Save array with multiple columns to csv


iPhone UIImagePickerController video mode

Question: When using the UIImagePickerController, is there a way to specify the resolution of the captured video, or to restrict the length of the video (based on size).  I would love to be able to have the video capture at a standard lower res mode rather than 720P.
Answer: For iOS 3.1 or later, you can use the videoQuality property of UIImagePickerController. The values are an in the enumeration
UIImagePickerControllerQualityType which defines UIImagePickerControllerQualityType{Low|Medium|High}. The default is UIImagePickerControllerQualityTypeMedium. 4.0 and later have additional resolution options.
As for duration, the property videoMaximumDuration allows you to specify the maximum time in seconds.


editText in android

Question: I am making an application and I have added an EditText in my layout.
What I'm trying to achieve is that when EditText is selected should open a dialog box, with some general text and an OK button. Which method can I use to accomplish this?
Comment: @Reno: You should mention *that* to the user, instead of posting demoralizing comments about his/her grammar. Suggest an edit to the post to fix grammatical and other mistakes. However, you should also consider that the community consensus is that there's nothing wrong with turning to Stack Overflow *before* using Google. If the question is a duplicate, find it and leave a comment. The users with enough rep will vote to close. You can also flag it for moderator attention.
Comment: @Reno Please dont demoralize someone
Comment: Please provide your code. it will help to find out the mistake.
Comment: @Cody Gray just so you know i have done all three, (It was posted as a dupe in the dupe chatroom) I have edited his posts before. Begging for a solution is not the same as grammar mistake. I was not making fun of his grammar. Cut this thread please. I wont be replying here anymore.
Answer: You must try some thing like this
searchtext.setOnKeyListener(new OnKeyListener()
    {
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if (event.getAction() == KeyEvent.ACTION_DOWN)
            {
                     showDialog();
            }
        }
     };

and here goes showDialog() code
private void showDialog()
{
    final AlertDialog.Builder Main_Dialog = new AlertDialog.Builder(this);
    final EditText input = new EditText(this);
    input.setPadding(10, 10, 10, 10);
    input.setText(ipAddress);

    Main_Dialog.setView(input);
    Main_Dialog.setTitle("Enter IP Address:");
    Main_Dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dialog, int whichButton)
        {
                        //Do whatever
        }
    });
    Main_Dialog.show();
}

Answer: If I'm reading your dilemma correctly, you'd set an OnFocusChangeListener for the EditText. Something like the following snip.
    EditText e = new EditText(this);
    e.setOnFocusChangeListener
    (
        new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (v.hasFocus()) {
                    showDialog(COOL_DIALOG);
                }
            }
        }
    );

Note, this seems like a somewhat odd user interaction. Why not just have them use the EditText for what it was made for? If you really want to do this, I'd suggest using a regular TextView or Button and use a click handler to pop the dialog. This would create a more "expected" interaction for the user.
Answer: You mean you want to display the dialog when your EditView gets focus? I think overriding View.onFocusChanged() would be the way to go. If you want to track the detailed input into EditText, implement TextWatcher and use TextView.addTextChangedListener() to add it to the EditText instance.

editText in android


DIY fiber optic network connection: 600ft through forest

Question: What equipment, tools and supplies do I need, in order to build and maintain a single fiber optic network connection between two buildings that are about 600 ft apart, separated by forest?
The way I am thinking about this problem is, instead of connecting an ethernet cable between two ethernet switches, I need to make a similar connection with a fiber optic cable. I'd like for it to be reliable for years. But I really don't know how to do it at all.
EDIT/UPDATE: thanks very much for all of the excellent replies. In just one day there's a huge wealth of information I was unable to find previously. I have incorporated some edits to clarify things that were unclear.
EDIT/UPDATE 2: In the interest of focus, I moved my question to the top. There are several clarifying questions below, which are not required to answer the main question, but give insight into my process so far and may be helpful components of the overall answer.
Note, I'm also considering alternate solutions -- see the below section on alternate solutions. I'm asking about fiber and other possibilities, so I can gather sufficient information to compare them to the other options-- including the pair of Ubiquiti Nanobeam 2.4G dishes that I'm running right now.
Some optional clarifying questions that have come up in my mind:

Do I need a media converter on each side, or is there another option for connecting the cable on each side?
Does it make sense to get a fiber optic cable of the correct length with connectors pre-installed?
Alternately, could I buy cable and the tools and connectors, and install the connectors myself? If so, what tools and supplies would I need to do this?
My initial research pointed me towards OM3, is this a good choice for my scenario? (more details below)
I'm considering either getting some armored cable and running it across the forest floor, or getting some conduit, perhaps metal conduit or liquidtite, and then I probably don't need armored cable. Any recommendations on this topic? (more details below)
It would be great to be able to patch a section of damaged cable if needed. Is this a practical thing to learn to do? What tools would I need? Is single-mode cable easier to patch?
Where can I purchase the different tools, cable, connectors, media converters, etc.?

A few more details about my specific project:
This is for residential use, including working from home. The two buildings are actually a well pump house and my main house. The ISP service comes into the pump house - this is a small rural ISP - and I need to bring the service to my residence, which is a long way from the road and utility pole. The ISP charges $12.50/foot for trenching and fiber installation past 100 feet, so they installed their ONT just inside the property and I'm taking care of the remaining distance. I'm outside Seattle, so we don't get a lot of intense heat, but there's a lot of moisture for much of the year.
My ISP offers Gigabit speeds so it would be nice to install something faster than that, 10GB seems like a good way to be future proof. Although there are valid arguments against this so-called future proofing since 1GB is already way more than needed for almost anyone.
In the short-term, I'll be laying this down on the forest floor. Thus, it won't be a straight run, I'll need to go around trees and bushes, and sometimes pass it through thick brush.
(Several people have advised that laying cable down on the forest floor is a terrible idea, so I am reconsidering this. Although it is notable that a CAT6 cable has been laying on the forest floor here connecting a different building, and it still works after about 2 years; it appeared undamaged when I rerouted it a few months ago.)
Maybe in a year or two I'll be able to dig a shallow trench and bury conduit, but that's a much bigger project, and I need an easier short-term solution for now. I'll probably be using a flexible conduit to protect it -- recommendations welcome. Or maybe direct burial cable will be sufficiently strong and easier than dealing with conduit. Deer could step on it, but there isn't anything bigger than that around here. I'll probably route 2 cables on different paths so I have a backup / redundancy.
On another post I saw a recommendation for some single mode cable with steel wire protecting it, but it seemed that it didn't really bend in all 4 directions very well, which would be troublesome.
Someone suggested routing in existing conduit. The well pump has its own separate electrical service. For the home, the power company has an underground conduit that goes directly from the utility pole along the 700 foot driveway, not directly to the house but first to a utility owned box that remedies the voltage drop (at least I assume that's what it does.) I would not consider attempting to route anything in this existing conduit. There is also an old DSL line, a 3/8" cable in a 1/2" thin metal conduit. Maybe it's 7/16" cable, it's really tight in there. I am certain it would be impractical to attempt anything with this. There are no other conduits, unless you count the water line.
If I do bury conduit, on the one hand it might be easier to just go along the gravel driveway. However the driveway is narrow enough that we wouldn't be able to drive on it while the trenching is underway, which could be a considerable inconvenience. There just aren't easy answers here.
Alternate solutions:

I have a wifi bridge working now -- that is, a pair of Ubiquiti 2.4G Nanobeam dishes. There is a risk of trees blocking the signal intermittently, especially in bad weather. I'm also unsure how it will perform in a rainstorm or the rare snowstorm. I will keep it as a backup. Cutting trees is not an option. No trees will be cut to create a better line of sight for wireless.
Cat6a cable signal degrades after 300 feet or so. I have tested it at 500ft in a nearby location: it works sometimes, but is comparatively slow (60Mbps) and some networking hardware refuses to connect with it at all. (Google Nest router in particular would not make any connection.)
Two or more Cat6a cables with PoE extender(s) in the middle would also be an option, and it's probably what I'll do if I can't figure out the fiber option. But the need for moisture protection makes this option tricky to execute. I'd like to be able to compare this option vs fiber, so that's why I'm asking about how the fiber option could be done.

Notable recommendations from answers:

Someone recommended getting a switch with an SFP interface, rather than buying media converters.
Someone asserted that the info about OM3 being cheaper or better is out of date, and that single mode is the way to go now.
Someone suggested hanging the cable from trees in an aerial way, will consider!
Someone suggested coax rather than fiber, so I'm adding to the list of possibilities that I need to research more.

Thanks for advice!
Comment: You will not want to try to splice or terminate a single-mode fiber in the field, by hand, without prior training. I'm not sure if it's feasible at all, but it's definitely not easy.
Comment: How are power and water connected between the pump and main  house?  Explore that, and perhaps running a new conduit alongside those pipes will be easiest, IE rather than forge your own path beneath the forest floor, just follow the one already in use with a new conduit.
Comment: Install conduit with lead lines, and always use your last lead line to pull at least two more leadlines.
Comment: @DKNguyen "pull cords" and "draw wires" are other names for leadlines.  (Adding for completeness)
Comment: Any cable laid bare on the ground has a short lifetime.  At least with electric cable you can have a fried dinner.  Does the house and well house share the same power line?
Comment: Trenching may be less work than you are expecting if you rent a slit trencher.
Comment: If your small rural ISP is anything like mine, we are laughing at everybody struck with the big ones.
Comment: Why not use non-metallic liquidtite conduit to protect the fiber? It's cheap enough and strong enough and flexible enough to run on the forest floor, and can later be fully or partially trenched. If certain sections need more protection, you can use the plastic-jacketed metal liquidtite for those.
Comment: 2.4 nanobeams were *nice for their time*, but a pair of 5AC litebeams would be a giant upgrade for little money.
Comment: Please do NOT edit responses into your question - it makes it _very_ confusing for people who are late to the party. If you need to address a suggestion made in an answer, do so in the comments to that answer. If someone comments asking for clarification on a point, edit _that_ into your question. Otherwise, you're just confusing people.
Comment: Do you *really* need that much speed? I'd be tempted to just build a pair of directional "cantennas" and do a more focused wifi link. (I've had reasonable success with the coffee-can side-fired design, which is much easier to build than the original potato-chip-tube design. Assuming you can still find coffee cans.)
Comment: If you don't mind taking a risk with aliexpress gear, there's under 100 USD ethernet switches with 1- 2 SFP+ sockets  and some 2.5 gig ports. Also for an idea of costs https://sschueller.github.io/posts/wiring-a-home-with-fiber/ is a home network but its the same tools. That said, I recall there's armoured fibre optic cable for outdoor use, but I can't remember where I saw it
Comment: You don't actually need fibre - consider looking at 10Gbit switches and cat-7 cable; there are reinforced cables made for outdoor use.
Comment: Do you need or want high speed?   https://www.etherwan.com/products/ed3541-series is rated at 100 Mbit over 200 metres over cat6 UTP, which should be adequate for most things.   Not sure about latency but its still ethernet.
Comment: This is still 7 questions in one. #2 & #4 are opinion based and #7 is a shopping question so those are all off-topic in and of themselves.
Comment: _PLEASE_ take the [tour]. Nobody has any problems finding any of the 7 questions you've asked. The problem is that you've asked _SEVEN_ questions in one! That's just not how this site works.
Comment: @FreeMan I don't think I can satisfy you so I will stop trying. If there is a way to iterate and reach consensus _before_ submitting an edit, I'd be willing, but I don't know how to open a private dialog. I already received the guidance I need to proceed with my project, so I'm finished with this question, and I'm grateful for this community. Several people gave great answers, providing a lot of useful information that is hard to find.
Answer: Your research is polluted by misinformation that's been circulating since the days when it wasn't misinformation. Single mode fiber is what you want - it actually costs less than OM3 or OM4 multimode, and the electronics to connect to it have come way down in price from when the trope you've been fed was true. More than 10 years ago it was already not true. So much so that the cheaper fiber more than offsets the slight premium for the interface electronics. And it can go as fast as the electronics allow, even with electronics that haven't been invented yet, unlike multimode.
Don't buy media converters - you'll pay too much. A small switch (or one as big as you need for your other devices) with a fiber interface port is almost always cheaper than a two-port switch, one of which is a fiber interface port, sold as a "media converter."
If you buy fiberglass reinforced drop cable it MIGHT make it a while before being broken by animals, trees or people if run along the ground, but I really can't recommend doing that. Use a chainsaw on the trees and make a reliable path for wireless point-to-point radios as suggested here: https://diy.stackexchange.com/a/134077/18078, until you can bury fiber. A note: Serious wireless point-to-point radios exist. You should use a pair. With an appropriate clear path you can do more than a gigabit over such a link, (but not 10 Gig at present.) Faster does cost more money than "pretty fast, pretty cheap" versions which are currently 300-600 Megabits.
Or, hang fiber from trees or actual poles, using drop fiber. See here: https://diy.stackexchange.com/a/117312/18078 for info on drop fiber. That will get it above most animal damage, and if you cast a suspicious glance around for trees likely to fall on it and remove them, can last for years. Burial is more damage resistant, though.
Comment: It is common for fiber installers to have a trencher that direct-buries a filled conduit. I don't know what your forest looks like but I work for a company that does this on a daily basis; we would be able to do this for you (for cost+labor, which is minimal). Your ISP _may_ do the same and save you the trouble. We also use fiber that you can literally drive a truck over, although we still pull it across poles. In all other aspects, this is your answer.
Comment: Thanks a lot for all of these suggestions, these are great! I edited the original question to incorporate several of these, and am seriously considering several of these as viable solutions.
Answer: Fiber - or anything other than some pretty good conduit - e.g., PVC Schedule 80 or rigid metal conduit - is not likely to last long with all the critters around. So that means one of:

Good conduit on the ground - not ideal but should work.
Good conduit a little below the ground (6" rigid metal, 18"  PVC)
Direct burial cable 24" below the ground - I really don't like  this option here

Because this is low voltage cable (or technically no voltage at all for fiber) and not  120V/above, you don't have to follow the usual rules. But while the rules aren't so relevant in terms  of protecting people from wires, they are still relevant in terms of protecting wires from critters.
The WiFi alternative may be a worthwhile long-term choice here. Depending on where the trees are, you might even be able to rig up a solar/battery repeater in the middle.
I wouldn't worry about going faster than 1 Gig. If you had two houses and wanted to share huge files between them, maybe. But this connection here is just to provide internet access. 1 Gig. is huge overkill for most people - kind of like putting in 60A to charge a commuter EV. Unless you're throwing a party for 50 people and each of those people is  staring at their own device instead of enjoying the party, you just don't need that much bandwidth. With WiFi you won't get anywhere near 1 Gig. over that distance, but you should  be able to get a usable connection. Once you put in conduit, you can always upgrade the connection later if your ISP ever offers more than 1 Gig.
Comment: I'd agree with the not going faster than one Gig, but when OP buries this, it should be somewhat future proofed. But I'd future proof with conduit and a pull string, rather than by gambling that whatever giant bundle of fibre I put in the ground will be sufficient.
Comment: Future proofing is worthwhile investing in, even if you can't see it ever being the case. With current internet speeds I could have sent the entire contents of my first hard drive several times over in the time its taken for me to write this comment - back then I never would have predicted things would get this data heavy.
Comment: Over a distance of 600 feet the question which mechanical protection offers best value for the money becomes interesting. I mean, even buying 600 ft of simple PVC sewage pipes appears to cost hundreds of dollars, similar for steel pipes.
Comment: I'd argue that's changing - most modern systems are doing multigig, and 10 gig internet is coming onstream, and if you're not picky prices are dropping. The network I'm building/acquiring parts for will be 10 gig capable - even if I'm doubtful I can use all of it on a single client, simply cause availability of 10 gig parts was easier at the time.
Answer: It is amazing how similar your situation is to one I just encountered earlier this year, except my property is in the south-east, I had internet to a barn rather than the pump house and it was a 630ft run if I went directly through the forest.
After spending entirely too much time researching products and estimating costs, I found my local ISP was willing and able to run a fiber from my barn to the house along the driveway for ~1.10 per foot. This included the direct burial rated fiber, the terminations and burying the fiber ~14 inches. I supplied my own media converters. They used a machine that was able to bury the cable without trenching so it only took about two hours and my driveway was never blocked. While this was much cheaper than anything I was looking at doing myself, I was also able to get a $300 credit in exchange for signing a 3 year agreement.
Many ISPs contract out the actual install work. If your local ISP isn't as willing to work with you, perhaps they would be willing to let you know which contractors they use so you might get a quote from them directly.
Comment: That's a great suggestion! My particular local ISP charges $12.50 a foot though :-/ at least that's their price to bring a fiber cable from the utility pole all the way to the house, so I can't expect that the price would be very different for burying my own fiber cable. That's awesome that your ISP has such a great affordable service.
Answer: Have you considered running coax instead?
I have a similar setup here in Montana — the internet is several hundred feet away up the side of a mountain. The vegetation is too dense for a good wireless connection (and it's hard to make a good wireless connection anyway) but the run is much too far for Cat6e.
Instead I ran direct burial RG11 coax https://www.amazon.com/gp/product/B01LWJXQII/ and used Ethernet over Coax adapters https://www.amazon.com/Nexuslink-Performance-Streaming-Locations-GCA-2000-KIT/dp/B09SKSKQR3
The cable is pretty tough, we have the full range of critters from Grizzly on down and nothing has bothered it to date, though I hope to bury it someday. It is also easy to cut to length, attach your own terminators, etc. And the system requires very little power and can operate directly from 12v DC which is handy as we only have solar power available.
Comment: What kind of speeds do you get over your coax connection?
Comment: I've always thought this stuff was more for when you already have some coax cable installed and want to reuse it.  The cost of running new coax would be similar to running any other cable, no?
Comment: Really appreciate this real-world-experience recommendation! I had not considered coax but I will look into it now.
Comment: Why on earth would you suggest this? Coax provides lower bandwidth, the cable is more expensive, the electronics is more expensive, and has exactly zero benefit.
Answer: if you have power cables buried in conduit then fibre in the same conduit. If you have them on poles the fibre on the same poles.
If you can get unobstructed line of sight then wireless, you might need to build towers both ends.
Buy fiber cables pre-made.  Buy the fiber network equipment from an expert unless you are one.
Answer: If the pump house is powered from the residence you are trying to connect internet to (or vice versa) then you might be able to use powerline ethernet which uses the existing power line and puts an additional signal on it to carry data.
A quick search gives me a few products that claim 600ft range and gigabit speeds.
Comment: @MikeB, bald assertions like that aren't useful, here or anywhere. Without some reasoning or evidence it's just noise.
Comment: Powerline is NEVER the answer.
Comment: @MikeB this is the kind of statement that is ALWAYS false. One single case where this is the answer and you are wrong. The setup at my neighbor's for instance.
Comment: @MikeB powerline falls into the "last resort" category.  It can be slow, unreliable, intermittent, and might never connect (so make sure its returnable!)  and sometimes it just works, and there's no good way to predict how good or bad it will be.
Comment: @MikeB: I use power line adapters to bring network out to my garage for my birdhouse cameras, it works just fine.
Comment: @Criggie  It is always possible to predict the massive radio interference that it causes, which most people aren't aware of.
Comment: The pump house has totally separate electrical service so this isn't an option. I edited the original question to make this clear. Thanks for the suggestion all the same!
Answer: Fiber cable
As @Ecnerwall already said: Use singlemode cable.
I personally prefer LC connectors. Fibre cable itself is quite cheap, and in case of single mode, good for up to 10KM. So get some reserve length.
Getting the fiber: The keyword you need is "200m single mode patch cable LC". Certain shops make custom cables. At 200m that should be viable.
Install
Tools: You won't need any tools on an pre-made fiber patch cable.
I don't understand the part of four directions bending: The fiber cables I used are flexible and resistant. They are extremely resistant to tearing, but are quite vulnerable to sharp bends. One kink and the cable is gone. I recommend an trench and conduit, should you absolutely don't want that now, at least get armored cable. An friend of mine lost an awful amount of installs to rodents chewing on his fibre cables. Non metallic fiber should be ok in an conduit together with power.
Modules
You can also save some budget if you use 1.25GB SFP modules now. At the time of writing they cost ~20€/module at my location. An 10GB SFP+ module costs about 150€. So get two SFP+ modules when you upgrade, not now. But use an SFP+ switch or router. SFP modules aren't always compatible with every switch or router. From personal experience: Mikrotik switches and Unifi SFP modules are compatible.
Comment: Posting this as acomment: FS.com (no affilation) makes an custom 600ft simplex patch cable for about $34. Armored cable is at $225 now
Comment: A single strand is **always** a bad idea.  When it fails, you're just down.  What costs is digging the hole, not what you put in it, and single-mode glass is cheap.  Today price for  **Corning** 12F is ~50c/foot.
Comment: Thanks so much for this really useful advice and information!
Answer: Building a fiber network, especially a single segment, is not the mysterious and complex art that we all thought it to be.
Electronics
SFP modules are a great way to convert between the optical and electrical domains. There are many wavelengths offered -- it really doesn't matter which wavelength you pick; just choose the same for both ends. Bi-directional ("bi-di") modules use two wavelengths at the same time; the advantage is they use a single strand but you have to match them correctly (eg TX/RX 1490/1310 on one end; TX/RX 1310/1490 on the other end). Others use a single wavelength transmitting on one strand and receiving on a separate strand (eg 1310 nm TX on one strand and 1310 nm RX on another). Of course you have to arrange it so that TX at one end connects to the opposite end's RX.
Conduit
Vibratory plowing is an amazing way of dropping conduit into the ground on the cheap. Check with your ISP to see whether they, or a contractor they know, can help you with this. Somebody who has a plow may also have spools of HDPE conduit, either microduct (12.7 mm, 18 mm, or other outside diameter) or traditional (3/4", 1.25", etc). These come in spools of 5000-8000 feet. I've plowed up to 200 feet continuous in good soil, but in rocky soil results are often not so good.
Pre-terminated
Others have mentioned the fact that custom and off-the-shelf pre-terminated cable assemblies are available. FS.com is one source; discount-low-voltage.com is another. Ubiquiti has a few entries here as well (FC-SM-100, FC-SM-200, etc). You can even buy couplers to plug multiple segments of cable together. (Perhaps it would make sense to buy multiple short cables rather than one full-length so that if/when a section is damaged by wildlife it can be replaced without replacing the entire length.)
DIY splicing
Fusion splicing single-mode 250 um fiber has really become quite easy, and basic splicing machines are not impossibly expensive as they once were.
If you want to build your own cable and be equipped for independently making repairs, shop eBay or elsewhere for a splicer. I've used both the Fitel Ninja and the Inno M7. I own one of the latter and prefer it over the Ninja, primarily because it came with "universal" fiber holders that allow me to work with both 250 um and 900 um fiber. Splicers in this class can be had used for under US$1500. Choose one that includes a cleaver and the only other tool you'll really need is a stripper, though a ringer and slitter are really handy for opening the cable jacket and the loose tube containing the fiber without damaging the fibers. (They're not as fragile as you'd expect, by the way.) You'll also need some splice sleeves, which are just inexpensive heat shrink tube with a piece of stainless steel wire inside.
It's possible your small rural ISP is already equipped for splicing fiber or desires to become so -- have you asked whether they would help you terminate cable for a fee?
Raw cable and other bits and pieces can also be had from the vendors who sell to small ISPs, like Baltic Networks, ISP Supplies, and others (they're also a great place to get Ubiquiti and Mikrotik parts).
The simplest way to terminate bulk cable is to use pigtails, either sold as such with a connector on one end and bare fiber on the other, or buy a patch cord and cut it in half. I've done both. It's cleanest with 900 um pigtails; the 2 mm and 3 mm patch cords have 900 um fiber inside wrapped in aramid or other yarn for strength. The yarn gets in the way, though it can be cut back.
If your splices will be exclusively indoors then simple splice trays from FS.com work great. For outdoors a small splice case like the PLP Coyote DTC4 or DTC6, or the Commscope OFDC-A4, are nice units that you should be able to find around US$60-80. (I have both in my little network.)
There's a dizzying spectrum of fiber types available even within the category of single mode. Bend insensitive is nice for a novice but not essential, and just about all the other possibilities won't make a difference for a distance as short as yours so don't sweat them. Armored gives a measure of protection against gnawing and stomping wildlife, but if you'll string it aerially or put it in conduit, even above ground, then armor is probably just extra hassle.
Answer: If you want a cheap solution that's better than just laying it on the floor, you might consider a shallow trench with HDPE / poly water pipe as conduit.
Even the thin wall 1/2 inch drip irrigation tubing would be better than nothing, and it comes in continuous long lengths.
Conduit is far better future proofing than any choice of fiber etc would be.
Also worth looking at other Ubiquti point-to-point. The lower frequency you can use, the better it will penetrate trees etc.
Answer: Depending on budget, outdoor-rated armored fiber could be a good option: https://falcontech.com/collections/os2-pre-terminated-fiber-optic-cable/jacket_armored
Pre-terminated fiber like that is more expensive, but for only a couple of fiber runs, it's probably not worth buying the tools for DIY termination.
Another option if you can find a route with few roots would be to use a spade like this to put non-armored fiber just below the dirt: https://www.wiltonthinlinetrenchingspades.com/store/product/2
I don't have experience with either of these products, but I have worked with fiber some before. We've always run it in conduit but have discussed options like this for future projects.


How do I fix the "reencode mismatch" error when using the Gibbed Save Editor?

Question: I'm getting a "reencode mismatch" error with the Gibbed Save Editor for Borderlands 2. How do I fix it?
Answer: That error message means you are using a version of Gibbed Save Editor that is not compatible with the version of Borderlands 2 you have. If you haven't already, update Borderlands 2 and get the latest version of Gibbed Save Editor here.


Exception is not thrown in coressponding try block

Question: I am trying execute below code. But I am getting compile time errors. I have written below code to display the contents of the file "myfile.txt".
But Actually there is no file "myfile.txt". Then an exception "FileNotFound" should be thrown at run time. But the below programme is not compiled.
Why am i getting compile time errors?
code:
import java.io.*;
class rethrow {
    public static void main(String args[]) {
        rethrow rt = new rethrow();
        try {
            rt.m1();
        } catch (FileNotFoundException FNFE) {
            FNFE.printStackTrace();
        }
    }

    void m1() {
        try {
            FileInputStream fin = new FileInputStream("myfile.txt");
            System.out.println("file contents");
            int ch;
            while ((ch = fin.read()) != -1)
                System.out.println((char) ch);
            fin.close();
        } catch (FileNotFoundException FNFE) {
            FNFE.printStackTrace();
            throw FNFE;
        } catch (IOException IOE) {
            IOE.printStackTrace();
        }
    }
}

---------------------------`---------------------------
OUT PUT:
rethrow.java:11: exception java.io.FileNotFoundException is never thrown in bod
y of corresponding try statement
catch(FileNotFoundException FNFE)
^

rethrow.java:30: unreported exception java.io.FileNotFoundException; must be ca
ught or declared to be thrown
throw FNFE;
^
2 errors

Comment: your method m1 should look like that `void m1() throws FileNotFoundException`. But rethrowing it at `throw FNFE` is quite unneccessary.
Answer: you have to add the throws clause in method m1:
  void m1() throws FileNotFoundException {

otherwise you have a Unreachable catch block for FileNotFoundException in your main method and Unhandled exception type FileNotFoundException in your method m1.
catching the exception in m1 is not necessary with that change.
Comment: Thanks . I have understood.
Answer: Declare your method as following
void m1() throws FileNotFoundException
{
 try
 {
  FileInputStream fin=new FileInputStream("myfile.txt");
  System.out.println("file contents");
  int ch;
  while((ch=fin.read())!= -1)
  {
   System.out.println((char)ch);

  }
  fin.close();
 }
 catch(FileNotFoundException FNFE)
 {
   FNFE.printStackTrace();
   throw FNFE;
 }
 catch(IOException IOE)
 {
  IOE.printStackTrace();
 }
}

You should declare what type of exceptions your method throws to the calling method.


Find all strings that have more than 255 characters that are not whitespace in PHP

Question: The following command will find me those strings which have more than 255 characters that are not white space.
egrep -norq '[^ ]{255,}'

If I have a string in $content, how would I find (in PHP) all the occurrences of strings that are longer than 255 characters, and save those occurrences so that later I can echo them?
Comment: Someone already answered your question, but one small thing I noticed is how you said "more than 255", but you used the quantifier `{255,}`, which would grab strings 255 characters long or more (i.e. it includes 255 itself, instead of being more than 255, which would be `{256,}`)
Answer: In PHP you use preg_match for matching:
// assuming $content is your input
if ( preg_match_all('/\S{255,}/', $content , $m ) ) {
    // save $content
}

\S => matches any non space character
{255,} => makes sure there are at least 255 characters in input
Comment: Awesome. And if it finds more than one occurrence it will be in $m? as m[0], m[1]..?
Comment: actually to need more than we need `preg_match_all` and all those matches will be in `$m[0]`


Can a convection oven be used without exterior venting?

Question: My home is 20 years old. I have a free standing stove/oven and a microwave above installed when home was new. Neither is vented and the roof is tile and exterior is stucco so I won't be able to vent.
I purchased an LG studio microwave/convection oven and a stove oven/convection. Will I be able to use the convection feature if not vented to the exterior?
Comment: What is stopping you making a hole in the wall for a vent? Been done before...
Comment: I wasn't aware that a convection oven had any air exchange with the exterior!  Are you **absolutely sure** yours does ?  That would be an incredibly energy-inefficient design.   See mfarver's answer.
Comment: convection ovens do not use a vent ... they have a blower that circulates hot air inside the oven ... that is so that the oven does not have any hot spots
Comment: 20 years old is faily new, It would seem strange to me, that a microwave vent unit would be installed by the builder without a vent above the oven location.
Comment: Electric, or gas?
Answer: Convection baking uses a fan to circulate air inside of the oven.  It does not require a vent to the outside.  You may want a vented range hood to collect smoke and odors from the cooktop, but you do not need one for the oven.
Answer: Yes - You can use the Convection feature without a vent.
The Microwave is a vent for the oven. Why are you not installing a vent through the wall?
Install a vent like this:

My apology,  This new model allows the vent to be recirculating by changing the vent motor orientation.  While not as effective as external venting, it appears to be an acceptable venting solution.  Probably would be acceptable or not acceptable depending on local code.
Comment: Thank You for all the feedback about venting my new appliances...as for not wanting to vent it's about 5 ft.to exterior wall and the cupboards are there , thanks for pictures we may consider side vent
Comment: The vent would be run in the ceilin; in between the ceiling joists to the exterior wall. the cupboards would not interfer.  The problem may be the joists do not run in the direction you want to go.


Accessing Liftmaster controlled garage door from afar

Question: Is there an iPhone App that will allow me to access my HomeLink controlled Lift Master garage door opener when I am away from home?
Answer: Newer Liftmaster has "MyQ" technology built in.  MyQ is the technology that allows internet control. Chamberlain is a related brand and also uses MyQ technology.
If your liftmaster has a MyQ logo on the housing (myQ is made to be obvious and easy to spot), then buy Liftmasters internet gateway (Amazon has it) and download the app from your app store.  (iOS or Google-Play)
Most older Liftmasters can be upgraded to MyQ by replacing the wired in-garage wall controller (and purchasing the internet gateway), however I'd call Liftwaster customer service/support and give them your door operators model number and ask which in-garage MyQ controller works with your door operator. (This one works with most models since 1998, and there are options for older door operators too, even a generic interface that works with any brand can be added.)
(Liftmaster Support is amazing... I wish every company supported product the way they do. They will walk you through any code changes or limit programming over the phone for Any liftmaster opener no matter how old.)
By the way, "HomeLink" car support is something different and has nothing to do with MyQ and internet control. As such, I edited that word out of your questions title.
Screenshot from my phone:


How do you get minecart hoppers to put items in chests?

Question: In Minecraft, I have tried to make minecart hoppers to put items in chests but it doesn't work. I haven't figured out a way to do this.
Answer: You can't directly place a rail on a chest but you can place a rail on a hopper. Just make sure the hopper is not powered or it will not work.
Below I've included an Image on how to set it up

By the way, the rails don't have to be powered, but you can risk de-activating it using an activator rail.


Replacing cabinet hinges but plates don't have matching screws

Question: I'd like to replace my cabinet hinges with soft-close hinges. I've read about overlay measurements, cup-depth, etc. I purchased a couple hinges to test and discovered that the new hinges have much smaller holes for the screws which attach the hinges to the inside of the cabinet.

The two holes at the top are the cabinet-side holes. The screw goes with the original hinge on the left - the soft-close hinges have much smaller diameter holes and the original screws won't fit.

This is a problem because the holes that are already in the cabinets from the original screws are larger than the screws that came with the new, soft-close hinges. So I can't use the new screws, they're too small and won't secure the door. The holes align perfectly so I can't screw in the hinge somewhere else or the door won't line up. I've searched for a long time looking for other soft-close hinges with larger holes but, for some reason, they all have the same narrow ovals or smaller screws.
I'm at a loss trying to think of a solution besides using a drill bit to open up the hole on the new hinges, but I know there might be a better solution than that. Thanks for your help!
Answer: Well, I have used two solutions in this situation:

open up the holes in the metal hinge as you suggest - quick and easy,

I have, with time available and planning, filled the larger holes in the wood with pegs or matchsticks that are glued in. Once dry re-drill the pilot holes and works well.
Comment: @MaraJade A piece of hard wood dowel (purchased at your local home improvement center for a couple of bucks), glued into the existing screw holes (in the, most likely, particle board doors) with standard yellow carpenter's glue will hold your hinge screws far better than any screw threaded into the particle board could ever hope to. It's probably safer and easier than trying to hold the small hinge while trying to drill out the screw holes (drill bit grabs the edges of the hole, rips the hinge out of your hand, cutting your hand in the process).
Comment: Hmm okay I'll research more about filling the holes while doing a test with the hinges to see if they hold securely after the holes are drilled out. I just wasn't sure if my idea was too "DI-Why?" when something simpler may have existed. Thanks!
Answer: The problem is that the screws you want to use are meant for press board cabinet case (as seen by the course thread size). These screws are hard to substitute because they require a larger pilot hole (1/4 inch or there about).
The only solution since you are limited in using the new screws, is to fill in the existing holes in the cabinet. This requires finding an appropriate sized wooden dowel and gluing it in the original screw holes.
They don't have to be a flush fit and when the glue dries can be trimmed flush with the cabinet walls with a utility knife and/or sandpaper.
Next drill an a pilot hole for the new screws.


Solving $\int dx/(x^{2}+1)$ with polynomial interpolation on the complex plane and with trigonometric substitution

Question: Using the Lagrange interpolation theory for $x_{0}=-i$ and $x_{1}=i$ we have
$\displaystyle
\int \frac{dx}{(x^{2}+1)}= \frac{-1}{2i}\int \frac{dx}{x+i} + \frac{1}{2i}\int\frac{dx}{x-i}=\frac{1}{2i}(\ln|x-i|+\ln|x+i|)+ C$
So I was wondering in how to prove the equivalence with the trigonometric solution given when we do $x=tg(  \theta)$ that we obtain
$arc tg(x)+ C_{1}$
Comment: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Logarithmic_forms
Answer: Actually the sign is minus between the two $\ln$'s.
Hence you can arrange them as:$$\ln \frac{x+i}{x-i}$$
Now these are complex conjugates, hence when going
over to polar coordinates, $r$ is cancelled and
there remains: $$\ln (\exp 2it) = 2it$$
Recall that $t$ is $\arctan x$, and you are done.
Comment: Please use [MathJax](https://math.meta.stackexchange.com/q/5020/399334) to properly format answers.
Answer: You can do this algebraically.  Set
$$y=\arctan x$$
$$\tan y =x$$
$$\frac{e^{iy} - e^{-iy}}{i(e^{iy} + e^{-iy})} = x$$
$$e^{iy} - e^{-iy} = i(e^{iy}x + e^{-iy}x)$$
$$e^{2iy}-1=e^{2iy}ix+ix$$
$$e^{2iy}(1-ix) = 1+ix$$
$$e^{2iy} = \frac{1+ix}{1-ix}$$
$$2iy = \ln\left(\frac{i(-i+x)}{i(-1-x)}\right)$$
$$y = \frac{1}{2i}\ln\left(-\frac{x-i}{x+i}\right)$$
$$y =\frac{1}{2i}\left( \ln(x-i) -\ln(x+i) +\ln(-1)\right)$$
Answer: Caution, in the complex,
$$\int\frac{dx}{x+i}=\log(x+i),$$ and not $$\log|x+i|.$$
More precisely, there comes an imaginary part,
$$\log(x+i)=\log|x+i|+i\left(\arctan\frac1x+2k\pi\right).$$
This is how the arc tangent term appears. Also notice that
$$\log|x+i|-\log|x-i|=0$$ so that the integral remains real.


Where am I going wrong when removing brackets from (s+1)(s+5)(s-3)

Question: One of my text book exercises is to remove the brackets from this expression:
$ (s+1)(s+5)(s-3) $
The I've tried a number of times and the result I keep getting is:
$ s^3 -3s^2 -13s -15 $
However, my textbook says the answer is:
$ s^2 -3s^2 -13s -15 $
I keep getting the same answer, but I'm reluctant to think the text book is wrong.
Here's how I come to that result:
$ (s+1)(s+5)(s-3)$
$ = s((s+1)(s+5)) - 3((s+1)(s+5))$
$ = s(s(s+1) + 5(s+1)) - 3(s(s+1) + 5(s+1))$
$ = s(s^2 + s + 5s + 5) - 3(s^2 + s + 5s + 5)$
$ = s^3 + s^2 + 5s^2 + 5s - 3s^2 -3s -15s -15$
Then re-arrange that to:
$ = s^3 +6s^2 - 3s^2  + 5s - 3s -15s -15$
And my final answer (Updated to reflect jorikis answer below):
$ s^3 +3s^2 -13s -15 $
Any advice greatly appreciated.
Comment: thank you! that's good to hear, think I'm starting to get a grasp on this daunting subject!
Comment: (Just a small comment on language - you remove *parentheses* from an *expression* (it is a thing) and *not a statement* (which is a *verb*). :)
Answer: Neither of these results is correct; the correct result is $s^3+3s^2-13s-15$. The error in your calculation is where you replace $6s^2-3s^2$ by $-3s^2$.
Comment: Isn't that the result I have? sorry I see now
Comment: @mal Almost, as joriki say - you have $1\cdot s^2 + s\cdot 5\cdot s +  s^2\cdot(-3)= 3s^2$...
Comment: @mal: Perhaps there's a delay in displaying your edits? In the version of the page that I'm being shown, you have $-3s^2$ instead of $+3s^2$.
Answer: The error is, in fact, in your textbook: The product $(s+1)(s+5)(s-3)$ will, after expansion, have a term $s^3$ in it (as in your result). Since it is missing in the textbook, the answer given there is wrong.
On the other hand, your derivation looks fine to me, so I would say that you are right and the textbook has a typo in it.
Edit: In fact, there is an error in your calculation; see the other answer. Still, the textbook answer is wrong.
Answer: $1$.  The textbook answer obviously has a typo. It is highly implausible that anyone would intend $ s^2 -3s^2 -13s -15 $ as a final answer.
$2.$  While you were doing the calculation, you had the intermediate expression
$ s(s^2 + s + 5s + 5) - 3(s^2 + s + 5s + 5)$, and then multiplied without changing the $s^2+s+5s+5$ automatically to $s^2+6s+5$. The more terms you have, the more work you need to do. Each step up in complexity introduces new opportunities for error.
$3.$  I would have as a matter of strategy preferred to find $(s+5)(s-3)$ first, since multiplying by $s+1$ is more pleasant than multiplying by $s-3$.
$4.$  Any calculation involves the possibility of computational error, or error in writing down the result of the computation. It is not a bad idea to make a final plausibility scan, like evaluating the original expression and the expanded one at some nice number, such as $x=1$.
$5.$ You have undoubtedly acquired visual shortcuts for expanding things like $(x+a)(x+b)$, and even $(px+a)(qx+b)$.  Note that $(x+a)(x+b)(x+c)=x^3+(a+b+c)x^2+(ab+bc+ca)x+abc$.


How to make CSS float left not bend around when browser width is shrunk

Question: I have 2 div boxes. It's all working fine but when the browser is shrunk to less than 800 pixels or so, the second div moves underneath the first div. How can I force it to always stay to the right of it?
#testbox1 {
background-color: #0000ff;
min-width: 300px;
width: 30%;
height: 200px;
position: relative;
float: left;
}

#testbox2 {
background-color: #00ffff;
width: 500px;
height: 200px;
position: relative;
float: left;
}

Comment: `position: relative` does nothing in the above. `position: relative` changes the behaviour of `position: absolute` descendant elements. On a side note, this is trivial with a table.
Answer: Give the parent element a min-width: 800px;.


Conditions under which $a+b+c$ divides $1-abc$

Question: What are the conditions such that $a+b+c$ divides $1-abc$, where $(a, b, c)$ are nonzero integers ?
Comment: something to start with $a+b$ and $c$ must be relatively prime. Indeed if $d$ was a factor of both $a+b$ and $c$ then it is a factor of $a+b+c$ and of $abc$ but not of $1-abc$.
Answer: The triples $(a,b,c)$ with the property that $a+b+c$ divides $1-abc$ can be characterized as triples $(a,b,d-a-b)$, where $d$ is a divisor of $1+ab(a+b)$.  This is because $a+b+c=d$ for such triples, while
$$1-abc=1-ab(d-a-b)=1+ab(a+b)-abd$$
For example, if $a=b=4$, we have $1+ab(a+b)=129$, which has $8$ divisors:  $d=\pm1,\pm3,\pm43$ and $\pm129$, giving triples
$$\begin{align}
&(4,4,-7)\\
&(4,4,-9)\\
&(4,4,-5)\\
&(4,4,-11)\\
&(4,4,35)\\
&(4,4,-51)\\
&(4,4,121)\\
&(4,4,-137)
\end{align}$$


Crashing when calling indexPathForCell

Question: I have a UITableView with custom cells. Within each UITableViewCell, there is a UIButton. I'm attempting to find out which cell the button is located in when it  is tapped. To do this I've done this:
- (IBAction)likeTap:(id)sender {

UIButton *senderButton = (UIButton *)sender;
UITableViewCell *buttonCell = (UITableViewCell *)[senderButton superview];
UITableView* table = (UITableView *)[buttonCell superview];
NSIndexPath *pathOfTheCell = [table indexPathForCell:buttonCell];
NSInteger rowOfTheCell = [pathOfTheCell row];
NSLog(@"rowofthecell %d", rowOfTheCell);

I thought this would work fine, but when indexPathForCell is called, an exception is thrown.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITableViewCell indexPathForCell:]: unrecognized selector sent to instance 0x756d650'

Any ideas about what I've done wrong?
Thanks!
Answer: This is your problem:
(UITableViewCell *)[senderButton superview]

It should be:
(UITableViewCell *)[[senderButton superview] superview]

Because the superview of the button is not the cell, is the contentView which subview of the cell.
Comment: note: this will work on iOS7 but not in iOS6 !
Answer: Why you dont set tag for each button in your cellForRowAtIndexPAth method:
button.tag = indexPath.row;

and then in your method you have:
- (IBAction)likeTap:(id)sender {
    NSLog(@"rowofthecell %d", button.tag);
}

Answer: I use custom UITableViewCell and i have a crash too on ios7
On ios 6, it's work like a charm
UITableViewCell *cell=(UITableViewCell*)[[sender superview] superview];
UITableView *table=(UITableView*)[cell superview];
NSIndexPath *path=[[sender superview] indexPathForCell:cell];

on ios7, this code above crash,
This code works on ios7 but i don't understand why...
UITableViewCell *cell = (UITableViewCell*)[[sender superview] superview];
UITableView *table = [[(UITableView*)[cell superview] superview] superview];
NSIndexPath *path=[[sender superview] indexPathForCell:cell];

So i use edzio27 answer. I set a tag on my button.
Comment: Here is the the solution to work both on iOS6 & iOS7 http://stackoverflow.com/a/19651825/1294448
Answer: Either you can set tag for each button as suggested by edzio27 or you can try using introspection as shown below :
- (IBAction)likeTap:(UIButton *)sender {

    UIButton *senderButton = (UIButton *)sender;

    if ([senderButton.superView isKindOfClass:[UITableViewCell class]]) {
        UITableViewCell *buttonCell = (UITableViewCell *)[senderButton superview];

        if ([buttonCell.superView isKindOfClass:[UITablewView class]]) {
            UITableView* table = (UITableView *)[buttonCell superview];

            NSIndexPath *pathOfTheCell = [table indexPathForCell:buttonCell];
            NSInteger rowOfTheCell = [pathOfTheCell row];
            NSLog(@"rowofthecell %d", rowOfTheCell);
        }
    }
}

Crashing when calling indexPathForCell


Can anyone identify this old wiring in my walls?

Question: In several of the rooms of the house I moved into last year (built 1973, USA), there are blank wall plates. I've removed a few to investigate and found somehting similar to the below pictures each time: a loop of what appears to be thick brown electrical cable, accompanied by a foot or so of thin 2-conductor black cable that is either insulated with rubber or a very flexible plastic, and covered in orange muck.
I've given the large loop a god tug and it doesn't appear to be an off-cut tucked back up into the wall. If it is, it's jammed in there pretty good.
Neither appears to carry any voltage according to a NCV tester, and it doesn't resemble the mains wiring in any of the live outlets or switches (which is all white plastic NMC and generally a bit thinner than the thick brown wire here).
I'm not intending to do anything with it at this point, just curious as to what it is/was.
Comment: Looks like lamp cord. Not appropriate for boxes carrying line voltage, but it may have been intended for speaker wiring. Also, if the other cable is line voltage, you are not supposed to house it in the same undivided box as low voltage wiring. However, the other cable might also be some type of media carrier.
Comment: The fact it seems to have been housed with very different (possibly high voltage) wiring was what made it so confusing to me too. I routinely install Cat6 as part of my job so I know about not mixing low voltage with line voltage. As I said, neither appears to be carrying any voltage at present in any of the locations I've opened up, so I'm confident that whatever it _was_, it's not a hazard now. Speaker wiring is a possibility.
Comment: The smaller cord looks like speaker wiring. Perhaps you should take off all the blank covers and see if there is one where there are multiple cords. That would suggest that was the one the stereo receiver could connect to and the others are for speakers.
Answer: Partial answer: the larger cable is Belden 8290 shielded twin lead TV antenna cable, which was introduced the 1960s and so is probably original to the house.
It's been literally years since I posted this question so in all likelihood nobody will happen upon this, but while working in my attic today I uncovered an old UHF/VHF antenna that was laying on the rafters and buried by the blown cellulose insulation. After digging it out a bit I immediately recognized the wire it was connected to as my mystery large wire and could finally get a good look at it.
There was no sign of the smaller wire in the attic so what that was used for remains anybody's guess.
Comment: Thanks for coming back; if this is the best answer, feel free to accept it.
Comment: Since the new answer bumps the question to the top of the pile, it most certainly will be found! (As you may have noticed.) Thank you, indeed, for coming back to answer your own question, and please do click the check-mark next to it so others know it's been answered.
Answer: Given that the large loop (that will be a multi-conductor cable - if you could see more of the writing on the jacket you could tell exactly what sort of multiconductor cable without cutting it open - It's Belden, based on "BELD" visible) is uncut, I'd guess whatever this was planned for was never actually installed. The "Zip-cord-like wire" also resembles certain types of telephone two-wire service cord and in any case was probably intended for something low-voltage or it would not have passed inspection even in 1970.
But the fact that the large cable loop is uncut leads me to think that this was planned for, and then never completed.
You could look around in the basement or where the telephone service comes into the building for wire ends that look like these.
Comment: I would agree on high end spec homes we used to pre wire both phone and intercom circuits in most rooms but usually only terminated 1 phone location unless the home was purchased prior to finishing. The zip or 2 wire could have been for a audio feed,  if a intercom most of the intercoms back then had 1 wire for  each location with a common on the nicer units so you could call a specific location (if there were 6 locations a total of 7 wires went to each so only that only 2 zones could be active or all of trying to find someone) back then there was a listed 14 fine strand speaker wire.
Answer: I believe you are showing regular zip cord.
What is zip cord? (Wikipedia)
Excerpt:

Zip-cord is a type of electrical cable with two or more conductors
  held together by an insulating jacket that can be easily separated
  simply by pulling apart.
Typical uses include lamp cord and speaker wire.
Conductors may be identified by a color tracer on the insulation, or
  by a ridge molded into the insulation of one wire, or by a colored
  tracer thread inside the insulation.
Zip cords are intended for use on portable equipment, and the US and Canadian electrical codes do not permit their use for permanently installed wiring of line-voltage circuits.

Certainly no licensed electrician would have installed such wiring.
One of the biggest concerns is that if it is pulled it might chafe off some of the insulation (perhaps at bends in a conduit), and then you could end up with a hot conduit.  Either that or a breaker that appears to blow for no apparent reason.
In any case, this is not a good thing to find in your wall.
Comment: Right now I'm viewing it as a mystery rather than a concern. If either set of wiring was energized the NCV would have picked that up, so I'm pretty sure this wiring is no longer live. I won't be pulling on it any more though, just in case - at least until I can figure out where it goes. The attic immediately above the room where this photo was taken is accessible but is filled with blown cellulose insulation, which doesn't make it easy to locate wiring.
Answer: Likely an old intercom system.  These used to be quite popular in the 60s and 70s, but are often removed or inactivated, leaving behind mystery wires in the walls.

The smaller wires are speaker/signal wires for the units and the larger wires to power the systems.  The signal wires wouldn't carry any voltage without units installed and the power wires were likely disconnected at the breaker when the units were removed, hence no voltage on any of the wires now.


Compiler error "use of undeclared identifier" when I remove my @synthesize statements

Question: With the latest LLVM build, the requirement for synthesizing properties has been removed.
Therefore I was able to remove all my @synthesize statements except for the ones for NSFetchedResultsController.  Does anyone know why the compiler is warning me when I remove the @synthesize fetchedResultsController; line?
Error:

Use of undeclared identifier "fetchedResultsController", did you mean _fetchedResultsController?

This is my code:
@property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController;

@synthesize fetchedResultsController;

- (NSFetchedResultsController *)fetchedResultsController {
    if (fetchedResultsController) {
        return fetchedResultsController;
    }

    if (!self.managedObjectContext) {
        self.managedObjectContext = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    }

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Session" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    [fetchRequest setPredicate: self.predicate];

    [fetchRequest setFetchBatchSize:20];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];

    fetchedResultsController= [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
    fetchedResultsController.delegate = self;

    NSError *error = nil;
    if (![fetchedResultsController performFetch:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return fetchedResultsController;
}

Comment: might help if you shared the exact warning.
Comment: Thanks. By the way, that is not a warning - that is an error.
Answer: When you don't put an @synthesize in your code, the instance variable created to back the property is named _propertyName. You are referring to the instance variable fetchedResultsController which no longer exists after you remove the @synthesize. Instead, change all references to fetchedResultsController to _fetchedResultsController.
Answer: Because the default synthesized variable is _fetchedResultsController not fetchedResultsController
Answer: The property fetchedResultsController is automatically synthesized to _fetchedResultsController, and this happens for every synthesized variable.
You should synthesize it explicitly to change its name.


Why is $ A_1 x + ... + A_n x^n $ a solution of $ \sum_0^{n} (-1)^n \frac{x^n}{n!} \frac{d^n y}{d x^n} = 0 $?

Question: I was playing(/fiddling) around with some maths and I saw this pattern(
where $ A_n $ is a constant.):
$ A_1 x $ is a soultion of:
$$ \frac{y}{x} - \frac{dy}{dx} = 0 $$
$ A_1 x + A_2 x^2 $ is a solution of:
$$ \frac{y}{x} - \frac{dy}{dx} + \frac{x}{2!} \frac{d^2y}{dx^2} =0 $$
$ A_1 x + A_2 x^2 + A_3 x^3 $ is a solution of:
$$ \frac{y}{x} - \frac{dy}{dx} + \frac{x}{2!} \frac{d^2y}{dx^2} - \frac{x^2}{3!} \frac{d^3y}{dx^3} =0 $$
It continues so on. Can someone prove the solution of
$ A_1 x + A_2 x^2 + A_3 x^3 + ... + A_n x^n $ is:
$$ \sum_{k=0}^{n} (-1)^k \frac{x^{k-1}}{k!} \frac{d^k y}{d x^k} = 0 $$
Comment: do you mean summing like this $\sum_{1}^{\infty}$
Comment: Your differential equation should read as follows: $$\sum_{k=0}^n(-1)^k\frac{x^{k-1}}{k!}\frac{d^ky}{dx^k}=0.$$ Notice that the power on $x$ is $k-1$, not $k$.
Answer: For any polynomial $P(x)$ of degree at most $n$, we have $\frac{d^k}{dx^k}P(x) = 0$ for any $k > n$. As a result, for any constant $y$, we have
$$\sum_{k=0}^{n} \frac{(y-x)^k}{k!} \frac{d^k}{d x^k}P(x)
= \sum_{k=0}^{\infty} \frac{(y-x)^k}{k!} \frac{d^k}{d x^k}P(x) = P(y)$$
The last equality is true because the expression in the middle is nothing but
the Taylor expansion of $P(y)$ with respect to the point $x$.
Substitute $y = 0$, we find any polynomial $P(x)$ with $P(0) = 0$ satisfy the ODE
$$\sum_{k=0}^n \frac{(-x)^k}{k!} \frac{d^k}{dx^k} P(x) = P(0) = 0$$
Answer: Use induction. Suppose the property holds for
$$ A_1 x + A_2 x^2 + A_3 x^3 + ... + A_n x^n $$
Prove that it works for $ n+1$ terms by writing the expression, use the fact that $\dfrac{\mathrm d^{n+1}y}{\mathrm dx^{n+1}}f = \dfrac{\mathrm d^{n}y}{\mathrm dx^{n}}\left(\dfrac{\mathrm dy}{\mathrm dx}f\right)$ and then show that your new equation is equivalent to one with $n$ terms.
Comment: What's  $ f $ ? I can't seem to understand your identity ...
Comment: What is $f$ supposed to be in the "fact" you state, as certainly it's not a general rule for functions $y$ and $f$ (unless you're simply applying the differential operator to $f$, in which case there shouldn't be any $y$'s involved).
Comment: @Anant $f$ is just a function. The identity holds in general.
Answer: To briefly outline one way of solving this (by induction), assume that $y = x^i$ are solutions for $i=1,...,n$ (where $n$ is the order of the particular ODE), and then note that in the $(n+1)$th case the above solutions are already covered as the $y^{(n+1)}$ terms disappear, and $y=x^{n+1}$ is a solution as after substituting this in, you're left with what ends up being the binomial expansion of $(1-1)^{n+1}$.
You could also try using the sub $z = \log(x)$, but this gets a lot nastier.
Answer: Let $z=\frac yx$.  Then we have
$$\dfrac{d^nz}{dx^n}=\dfrac{d^n(yx^{-1})}{dx^n}=\sum_{k=0}^n\binom nk\dfrac{d^ky}{dx^k}\dfrac{d^{n-k}(x^{-1})}{dx^{n-k}}=$$
$$\sum_{k=0}^n\binom nk\dfrac{d^ky}{dx^k}(-1)^{n-k}(n-k)!x^{-1-n+k}=$$
$$\sum_{k=0}^n(-1)^{n-k}\dfrac{n!}{k!}x^{-1-n+k}\dfrac{d^ky}{dx^k}$$
So we have
$$(\pm1)n!x^{n+1}\dfrac{d^nz}{dx^n}=\sum_{k=0}^n(-1)^k\dfrac{x^k}{k!}\dfrac{d^ky}{dx^k}$$
Setting this to $0$, since $x=0$ won't work, we have $\dfrac{d^nz}{dx^n}=0$.  Integrate $n$ times, then $y=zx$.
Answer: First, note that $$\displaystyle \sum_{k=0}^n \frac{(-x)^k}{k!} \dfrac{d^k y}{dx^k}=0$$ is a linear ODE,  i.e. if $y_1,y_2$ are solutions then so is any linear combination of them. (This is the same ODE as above except for an overall factor of $x$.) Hence it suffices to show that $x^m$ is a solution for any positiveinteger $m\leq n$. But
\begin{align}
\sum_{k=0}^n \frac{(-x)^k}{k!}\dfrac{d^k}{dx^k}(x^m)
&=\sum_{k=0}^n \frac{(-x)^k}{k!}\cdot\dfrac{m!}{(m-k)!}x^{m-k}\\
&=\left[\sum_{k=0}^n (-1)^k\binom mk\right]x^m\\
\end{align}
(The first equality is valid for $m\geq 1$.) So all we need to show is that this sum vanishes. But $\binom{m}{k}=0$ if $k\geq m$, and since $m\leq n$ by assumption the sum is
$\displaystyle \sum_{k=0}^m (-1)^k\binom mk=(1+(-1))^k=0$ by the binomial theorem. Thus we conclude that $\{x^m\}_{1\leq m \leq n}$ is indeed a set of solutions, and by linearity of the ODE it follows that so is $\displaystyle \sum_{k=1}^n A_k x^k$ for arbitrary $\{A_k\}$.


Implicit conversion in glsl shaders

Question: When specifying member values for a structure consisting of float values like vec3 or mat3, is it guaranteed that if an integer value is passed it's going to be promoted to a float? For example if I write
vec3 var = vec3(1, 0, 0)

Same when assigning an integer value to a float variable:
float var = 1

Is the implicit conversion guaranteed here?
Answer: Yes, it is guaranteed by the GLSL language specifications (click me). Section "4.1.10. Implicit Conversions" says

In some situations, an expression and its type will be implicitly converted to a different type.

The spec shows all possible implicit conversions inside a table, also int -> float. It further says:

When an implicit conversion is done, it is the same conversion that would be done under explicit
  conversion, using a constructor.

e.g.
float a = 1;

is equivalent to writing
float a = float(1);

There is one sentence at the end of the section, that you should keep in mind:

The conversions in the table above are done only as indicated by other sections of this specification.

If read it correctly, it says that you can not rely on implicit conversions in any kind of instruction you might come up with. However, regarding vec3 var = vec3(1, 0, 0) section "5.4.2. Vector and Matrix Constructors" says:

If the basic type (bool, int, float, or double) of a parameter to a constructor does not match the
  basic type of the object being constructed, the scalar construction rules (above) are used to convert
  the parameters

So it calls the constructor float(int) before consuming each value.
Even though both cases are explicitly backed by the language specifications, my personal advice is to never rely on implicit conversions. They can lead to subtle, hard to track bugs. Not sure how it is in GLSL, since I didn't test it, but in C++ this one:
float a = 1 / 2; # <--- this evaluates to 0.f!

, deeply hidden somewhere in larger calculations, has cost me several hours of debugging more than once. It gets worse if one or both values of the fraction are taken from a variable. However, in C++ I can step through the code with a nice debugger, something that is not so easily done in GLSL. So if the only reason for using implicit conversions is laziness or some sort of taste-related decision, force yourself to be explicit. It will safe you a lot of pain.

Implicit conversion in glsl shaders