remote consumer running slow for kafka

Question: Background :
We were trying to run mirrormaker to try and replicate some data from one of our datacenters to aws. When trying to do this we ran into an issue where we seemed to be bottlenecking in terms of throughput per partitions. We were encountering an issue in some of our topics which have large message sizes and decent throughput .  We were running mirrormaker on aws side along with our back up kafka cluster there [ on different machines] .
How did we conclude we were bottlenecking in throughput per partition ?
When we increased the number of partitions in the topic the throughput increased. Also when producing to a single partition in a topic with a bunch of partitions the throughput was low.
To further debug we tried using consumer-perf-test on the aws side to try and figure out if consumer might be the bottleneck [ considering it should ideally be either the consumer or producer there ] .
We saw a drastic decrease in the throughput of our consumer on aws as compared to bringing it up on our datacenter. Also, another observation tweaking a bunch of properties does not seem to impact the batch size of the consumer at all on aws side .
Properties we tried out for reference -
fetch.min.bytes=4000000
max.partition.fetch.bytes=33554432
max.poll.records=20000
So just wondering if there is some configuration that I might be  missing here that can lead to this drop ?
Edit 1 :
Ok, so tuning the socket buffer on the broker does positively impact the consumer perf test script quite a bit. But it seems like the mirrormaker is still bottlenecking somewhere . One peculiar thing I noticed is -
consumer-fetch-manager-metrics:fetch-latency-avg:{client-id=consumer-perf-consumer-4331-1}                                                   : 145.250
This metric is around 145 ms in the performance test script. But when checking the same via jmx stats for mirromaker , for the same topic this stat is around 1300 ms which is very weird considering they should be somewhat similar for both.
Edit 2:
So I saw something very wierd. It seems like mirrormaker is not picking my overrided config for the consumers mirrormaker creates to replicate data.
<code>org.apache.kafka.common.config.AbstractConfig [2022-03-19 00:06:34,709] INFO ConsumerConfig values:
    allow.auto.create.topics = true
    auto.commit.interval.ms = 5000
    auto.offset.reset = earliest
    bootstrap.servers = [hidden.ip:9092]
    check.crcs = true
    client.dns.lookup = use_all_dns_ips
    client.id = consumer-null-6
    client.rack =
    connections.max.idle.ms = 540000
    default.api.timeout.ms = 60000
    enable.auto.commit = false
    exclude.internal.topics = true
    fetch.max.bytes = 52428800
    fetch.max.wait.ms = 500
    fetch.min.bytes = 1
    group.id = null
    group.instance.id = null
    heartbeat.interval.ms = 3000
    interceptor.classes = []
    internal.leave.group.on.close = true
    internal.throw.on.fetch.stable.offset.unsupported = false
    isolation.level = read_uncommitted
    key.deserializer = class org.apache.kafka.common.serialization.ByteArrayDeserializer
    max.partition.fetch.bytes = 1048576
    max.poll.interval.ms = 300000
    max.poll.records = 500
    metadata.max.age.ms = 300000
    metric.reporters = []
    metrics.num.samples = 2
    metrics.recording.level = INFO
    metrics.sample.window.ms = 30000
    partition.assignment.strategy = [class org.apache.kafka.clients.consumer.RangeAssignor]
    **receive.buffer.bytes = 65536**
    reconnect.backoff.max.ms = 1000
    reconnect.backoff.ms = 50
    request.timeout.ms = 30000
    retry.backoff.ms = 100
    sasl.client.callback.handler.class = null
    sasl.jaas.config = null
    sasl.kerberos.kinit.cmd = /usr/bin/kinit
    sasl.kerberos.min.time.before.relogin = 60000
    sasl.kerberos.service.name = null
    sasl.kerberos.ticket.renew.jitter = 0.05
    sasl.kerberos.ticket.renew.window.factor = 0.8
    sasl.login.callback.handler.class = null
    sasl.login.class = null
    sasl.login.refresh.buffer.seconds = 300
    sasl.login.refresh.min.period.seconds = 60
    sasl.login.refresh.window.factor = 0.8
    sasl.login.refresh.window.jitter = 0.05
    sasl.mechanism = GSSAPI
</code>
From jmx stats under the consumer section what I understand is that this should be the named client id which is actually doing the heavy lifting and porting the data. -

I have set the properties as mentioned on the kip of mirrormaker at https://cwiki.apache.org/confluence/display/KAFKA/KIP-382%3A+MirrorMaker+2.0 . According to logs these are reflecting for the producer side of things but not for my consumers at all it seems.. I am using mirrormaker 2 from the 2.7.1 distribution.
Comment: Are you using MirrorMaker2?
Comment: Yes, using mirror maker 2. Yesterday night  I think i found it though ! On the brokers tuning the property send.buffer.bytes to be 1 mbish does seem to increase the throughput by 4-6x when testing out with consumer-perf-test script of Kafka and trying to.consume in our datacenter from aws. Will try out once with mirrormaker next week. But still the perf test seems to record the average batch size still at 15 , was wondering if I can still make it better.
Comment: Average batch size is 15 for messages size around 66 kb for reference!
Comment: I've not used the perf scripts for actual performance testing, but yes, increasing buffer sizes or increasing poll frequency should increase throughput
Answer: Ok, so I got it. In the kafka 2.7. distribution, it seems like there is a bug where in the consumer properties are not getting picked for the core consumer which actually polls the data for the source cluster. They are picked for the produce side weirdly.
I upgraded to 3.1 and sharing improvements for reference -
data being replicated -  a single partition topic that has average message size ~100kb
when replicating from a cluster which has the default send buffer bytes, throughput increased by 3x of original [ used the recommended higher settings for buffers, poll records and so on ]
On a cluster with tuned send.buffer.bytes [ 1 mb instead of 100kb default] my throughput increased 30x.
The latency between data centers was ~70ms for reference.

remote consumer running slow for kafka


Error: failed to get the task for process

Question: I have the same Question like this Xcode: failed to get the task for process. Every time I want to test my app on my iPhone I get the error "failed to get the task for process". The solution of this thread was to change the settings to the developer certificate as far I understand this. Unfortunately this is not the solution for my. Is there an other way to solve the problem?
Edit: I have checked that "Code Signing Identity" is set to iOS Developer (in project) and "Code Signing Style" is set to Automatic (in target) -> in manual my build will crash. I tried to restart Xcode and my iPhones. I tried to install the app while the iPhone is locked and unlocked it later. Nothing worked :(.
Comment: Please explain in more detail what you tried; there are a number of possible solutions listed in the answers you linked.
Comment: ok thank you, I updated the question.
Answer: I was having the same issue, the error was:
<code>failed to get the task for process 325
</code>
In my case, I was trying to run the application by selecting the Ad-Hoc signing certificate in the provisioning profile. As soon as I switched it to a Development signing certificate in the provisioning profile, the application started running into my iPhone.
There are many solutions to this. And the above one worked for me.


jQuery Filtering

Question: Is there a way to filter a multi-line select box using jQuery?
I'm a new to jQuery and can't seem to figure out the best way to do this.
For example if I have:
<select size="10">
   <option>abc</option>
   <option>acb</option>
   <option>a</option>
   <option>bca</option>
   <option>bac</option>
   <option>cab</option>
   <option>cba</option>
   ...
</select>

I want to filter this list based on a selection drop down with:
<select>
   <option value="a">Filter by a</option>
   <option value="b">Filter by b</option>
   <option value="c">Filter by c</option>
</select>

Answer: Something like this might do the trick (assuming you give your 'Filter by...' select an id of filter and the filtered / other select an id of otherOptions):
$(document).ready(function() {
    $('#filter').change(function() {
        var selectedFilter = $(this).val();
        $('#otherOptions option').show().each(function(i) {
            var $currentOption = $(this);
            if ($currentOption.val().indexOf(selectedFilter) !== 0) {
                $currentOption.hide();
            }
        });
    });
});

UPDATE: As @Brian Liang pointed out in the comments, you might have problems setting the <option> tags to display:none. Therefore the following should give you a better cross-browser solution:
$(document).ready(function() {
    var allOptions = {};

    $('#otherOptions option').each(function(i) {
        var $currentOption = $(this);
        allOptions[$currentOption.val()] = $currentOption.text();
    });

    $('#filter').change(function() {
        // Reset the filtered select before applying the filter again
        setOptions('#otherOptions', allOptions);
        var selectedFilter = $(this).val();
        var filteredOptions = {};

        $('#otherOptions option').each(function(i) {
            var $currentOption = $(this);

            if ($currentOption.val().indexOf(selectedFilter) === 0) {
                filteredOptions[$currentOption.val()] = $currentOption.text();
            }
        });

        setOptions('#otherOptions', filteredOptions);
    });

    function setOptions(selectId, filteredOptions) {
        var $select = $(selectId);
        $select.html('');

        var options = new Array();
        for (var i in filteredOptions) {
            options.push('<option value="');
            options.push(i);
            options.push('">');
            options.push(filteredOptions[i]);
            options.push('</option>');
        }

        $select.html(options.join(''));
    }

});

Comment: @Brian Liang I did do a quick test in Firefox before I posted and it worked. However I have just checked in Opera, Safari, Chrome and IE 8 and you're right: it does not work in those browsers.
Comment: I don't think this works since you cannot hide that option element.
Comment: Tim, I tried it in Chrome/IE and it works like a charm. Great work Ian!

jQuery Filtering


How to write a report script in Oracle

Question: My knowledge on SQL and Oracle does not go beyond querying I'm afraid, but what I'm looking to do is run some kind of script which will produce multiple reports from one execution. I have a whole bunch of code and at the moment I'm rerunning it about 30 times, each time replacing the following in the WHERE clause with a different "SUBJECT_ID":
SELECT ...
FROM ...
WHERE ...
AND (v.SUBJECT_ID LIKE 'B%')
...

I'm thinking I should be able to run some kind of loop script and output all the 30 reports in one go...? I am hoping to get some kind of training on this quite soon, but any help would be greatly appreciated!
Answer: Assuming by

each time replacing the following in the WHERE clause with a different "SUBJECT_ID"

you mean v.subject_id like '<some value>', where  is different for each loop round the code, I would do the following if I were you:
replace the v.subject_id like '<some value>' with v.subject_id like '&&subj_id.' (the . is necessary to say that's the end of the parameter name) and create that as it's own script, eg. report.sql.
Then I'd create a new script and do:
define subj_id set <some value>;

@@report.sql

define subj_id set <some other value>;

@@report.sql

...

Comment: Thanks for this - any step-by-step guides on how to create scripts...? Ideally I'm looking to run each query (x30) and save a .xlsx export to a local directory.
Comment: I've not come across any step-by-step guides; basically a script is just a collection of sql and pl/sql statements, along with any sqlplus commands to affect the output (eg. spool to a file, switch off headers, etc). Writing the guts of them isn't too difficult; getting the exact output you need can be slightly more tricky!
Comment: I'd suggest you give it a go, and if you get stuck, ask a new question with details of what you've done, what issues you've had, etc. Table scripts and sample data would help too. [This](http://www.orafaq.com/wiki/SQL*Plus_FAQ) and [this](https://docs.oracle.com/cd/E11882_01/server.112/e16604/ch_twelve001.htm) should help you with the sqlplus commands you can use.

How to write a report script in Oracle


Copy & Paste between terminal(s) and application windows in i3

Question: I have recently installed the i3 tiling window manager [1] on my Ubuntu system and I'm trying to figure out how to copy & paste between various terminal and application windows.
How can this be done?
[1] http://i3wm.org
Answer: Some terminals use CTRL+SHIFT+C and CTRL+SHIFT+V to copy and paste, while others use CTRL+ALT+C and CTRL+ALT+V, like urxvt (See https://wiki.archlinux.org/index.php/Rxvt-unicode#Cut_and_paste ).
For i3wm, try using a clipboard manager, like clipit.
sudo apt-get update
sudo apt-get install clipit

Add exec --no-startup-id clipit to ~/.i3/config to start it automatically.
Comment: Note, `clipit` is not longer maintained. `diodon` is a common replacement
Answer: I have just had success using the middle mouse button with xterm in i3 to copy from a remote terminal to firefox. Use the middle mouse button to copy and paste.
Comment: Yeah - it's working - select text from terminal and middle click to paste to browser
Answer: You have had good answers above, I will just add a detail. As a default, the clipboard of each container is emptied when the container is closed. So if you copy some text from a terminal, close the terminal, and paste the text in another terminal - it will not work, because the clipboard will have been emptied in the meanwhile.
Comment: This should be the answer
Answer: I installed xfce4-terminal which pretty much does exactly what I need.
sudo apt-get install xfce4-terminal

Answer: I don't use that myself, but your copy buffer might be accessible through ctrl +shift+c to copy and v to paste. These is also programs like xclipboard for capturing output of terminal commands into a clipboard. Try it out, report back!
Comment: Hi. I tried the `ctrl+shift+c` and `ctrl+shift+v` but it definitely doesn't work. Not sure about the `xclipboard` thing, sounds a bit complicated.
Comment: yah, it's more to pipe the output of a command into to get it into your clipboard
Comment: Have you tried terminator ? It's another tiling terminal which `ctrl+shift+c` works in
Comment: Terminator is kinda defying the point of i3. I tried `gnome-terminal` but it does something weird like not everything is displayed correctly.
Answer: I just got mine done by holding down Ctrl+mouse wheel. Then selecting from the popup that comes the option: Select to clipboard by moving the mouse to that option and releasing the mouse wheel. Then I went ahead and selected the text I wanted to copy in the terminal and it worked.
This was done in i3 wm


Why below private method return 0 instead 15 in java?

Question: public class Sacrifice {
    private int variableA = showOutput();
    private int variableB = 15;

    private int showOutput() {
        return variableB;
    }

    public static void main(String s[]) {
        System.out.println( (new Sacrifice()).variableA);
    }
}

Comment: Put a breakpoint in showOutput and run your program in the debugger
Answer: Fields of a class are initialized in textual order.
That means that the initial value of variableA is computed before variableB has been initialized.   Therefore the showOUtput() method is seeing ... and returning ... the default initial value for variableB.   The default initial value for an int variable is 0.
(This is all specified in the Java Language Specification, but I doubt that JLS references would be helpful for you ... at this stage.)
Comment: Yes ... it is a lot more complicated than that simple sentence.  There are also `static` variables, blank initializations, initializer blocks and constructors to consider.   But if you just have simple instance fields with (non-blank) initializers as per the example, then "in textual order" covers it.


print web report in C#.Net

Question: I need to create a clients details report for a web based application in c#.Net. There will be multiple client details one by one.
When take print of this web page, the first page will be the cover page and the remaining pages contains clients details. The pages except the cover page should be numbered "page x of y" in the centre of the footer. The top of each page should display the client name that is the subject of the sub-report. If part of a sub-report section spans onto a new page, the whole section should be moved to the new page. Any solution for implementing this?
Answer: I would  create a template of my report with the ReportViewer control. Then I would push data into it from code behind or link it to my DB to generate report automatically. You can find a Getting start with report viewer there.

print web report in C#.Net


How to display debug error in xamarin vscode?

Question: When attempting to redirect to another page on my xamarin app, if there is a runtime error in the xaml page that I am redirecting to or the constructor for the view model, the page doesn't redirect but it also does not display any error and sits on the same page. Is there a way to debug this in vscode like I would with the chrome debugger console?
A stack trace or something along these lines to find out what the problem is would make life a lot easier.
Comment: Can you show the code causes the error?
Answer: Just wrap the InitializeComponent(); of this page in the try-catch block and process the error.
Comment: This doesn't work. The Initialize component isn't throwing an error. I know exactly which line of code is preventing the redirect and it seems to be a service I'm injecting into the constructor of the view model. When I remove it the page redirects. I'm just not sure why the service is failing.
Comment: Create the viewmodel manually before InitilizeComponent inside the wrapper?..
Comment: Turns out I wasn't injecting the service but this answer effectively answers my original question of how to debug a xaml page. Accepted answer. Thanks Nick.


Can Plasma's networkmanager store passwords somewhere other than KWallet?

Question: I'm running Ubuntu 20.04 with Plasma desktop.  When I boot up and login to the computer, I get a "KDE Wallet Service" modal with the message

The application 'kded5' has requested to open the wallet 'kdewallet'. Please enter the password for this wallet below.

I want this not to appear.  In trying to gather the information needed to fulfil this desire, I found this AskUbuntu question which seems to describe the same problem.
One of the answers on that post has this tidbit of information:

On login, networkmanager tries to connect to the wifi and therefore needs access to kwallet. org.kde.plasmanetworkmanagement is a kded module so the request comes from the kded5 process.

Because my modal occurs when the machine attempts to connect to WiFi, and because it will not connect to WiFi until after I enter my sudo password, I'm certain this is my issue: Plasma's networkmanager is trying to get my WiFi password stored in KWallet's default wallet kdewallet, so I have to open the wallet each time.
I never asked to use KWallet, and in fact I never knew exactly what it was until today.  On my Ubuntu systems that use the Gnome or Cinnamon desktops, I've never had to worry about wallets or built-in password managers.  Instead, I type in my WiFi password once, and it's remembered forever without me having to deal with it ever again.  This experience with other DEs demonstrates that it is within the realm of Turing completeness for my computer to store my WiFi password without me having to administer a specific password manager for it or to open a password wallet every time I want to use it.
Given that this experience is known to be possible, can it be implemented in Plasma?  Specifically, is it possible to make the Plasma networkmanager store my WiFi password somewhere other than KWallet, but instead somewhere analogous to where Gnome and Cinnamon store it, such that I don't have to administer a password manager and open its database manually every time I want to use WiFi?
Answer: If you don't want to have to enter a password for the KDE password manager KWallet, you will need to remove the password by changing the password and entering nothing.  Be aware that this will reduce the security of passwords stored in the password manager.
Comment: It's not that I don't want to have to enter a password for KWallet, it's that I don't want to use KWallet at all.  I'd rather have my WiFi password stored wherever Gnome and Cinnamon store it, which I assume is not KWallet.  Is that possible?
Comment: Idk about Cinnamon but GNOME has its own password manager that works the same way. But you don't have GNOME, you have KDE.


How can I tell if a breaker uses both phases/legs

Question: Good day.
I hooked up Sense monitor by adding a 240v breaker to my panel (bottom 2 slots on one leg). Problem is Sense has detected that my breaker is sitting on two slots that occupy the same phase/leg of the panel.
How can I tell of there is 2 slots in the electrical panel that will occupy both phase/legs so that Sense will work properly? From reading I suspect Sense monitor power needs to be connected to both phases/legs.
Panel:

Stab-lok CAT NO. BE 116-32
MAINS 125 AMP.MAX.
120/240 VOLTS A.C.
1 Phase 3 Wire
Y24-863A
Comment: If it is a 240v (two pole) breaker that is designed for that panel, it _should_ hit both legs.  If you test the voltage between the two lugs on the breaker is it 240v?
Comment: This is a straight up guess, but it looks like all of your other 240v breakers straddle one of those thick lines on the breaker numbering label.  So the order of the slots could be AA|BB|AA|BB.
Comment: Added some images to original post.
Comment: Sense Response: we noticed that your Sense power wires are drawing from the same phase, or leg. of your electrical panel. It's possible that the power wires were either installed on a tandem breaker or, if you installed on a 240V breaker, Sense is sitting on two slots that occupy the same phase/leg of the panel.
While the 240V breaker does ensure that it draws power from two different slots on the panel, depending on where it is placed, those two slots can be drawing from the same phase. To put it into perspective, this is what the phase pattern of the left side of your panel could look like:
Comment: phase A
phase B
phase A
phase B
phase B
phase B

If your double breaker is attached on a spot where the phase repeats (consecutive phase A), such as towards the bottom, you may run into the issue I've described. I cannot say for sure what your panel phase map is, but you should refer to what is printed on the panel, or reach out to your electrician.
Comment: I don't know this stuff and this was the first time I have ever connected anything to an electrical panel. I have done wiring before like adding outlets, lights, switches, but have never connected anything to the electrical panel before. I understand what their support is telling me (sort of) but no idea how to tell if there somewhere in this panel that I can connect the breaker and have it do what it's supposed to.
Comment: **STOP** Tell us when you have read up on the FPE/Stab-Lok problem. If you determine that your breaker panel (the entire thing, not just the one breaker you are working with right now) is a **IMMINENT FIRE HAZARD** then that needs to be resolved before (or rather, **instead of**) doing anything else with the panel. If it turns out your panel is "OK" then we can work on the Sense problem.
Comment: I take it that you're in Canada?
Comment: Yes I'm in Canada.
Answer: Stab-Lok is a PROBLEM
See, for example, What can I do about a breaker that trips frequently on a Stab-Lok panel?
So first read up on Stab-Lok, post a picture of your panel (the pros will recognize it and tell you if it really is a fire hazard, etc.) and determine if this is a concern. If it is a real concern, then dealing with replacement is a much higher priority than hooking up the Sense monitor.
How it SHOULD Work
On many panels (I don't know if Stab-Lok is supposed to work this way or not), a true double (240V) breaker will always hit both legs. The exception is a double-stuff breaker, where it is really two-breakers-in-one. In that case, it normally only hits one leg, and the exception is if it can actually be 1/2 of one leg and 1/2 of the other leg. But that, as I understand it, is only on certain panels where you can have a quad == 4 in one, but really 4 in 2 - i.e., a double-space breaker that has 4 individual breakers, two on one leg, two on the other leg, with the result that the inner breakers can function together as a "double 240V breaker".
FIRST FIGURE OUT THE STAB-LOK!
Comment: Date says inspected 1991. Still reading about the issue and it's a little concerning. Thinking maybe I will contact a local electrician and just have the entire panel replaced.
Comment: "Inspected" can mean: "Inspected at time of initial installation" - which would mean nothing because at the time the hazards were not well known.
Comment: I will have a read on the Stab-lok issue to be sure it isn't a fire hazard. Hate the idea of having to replace the panel but better than the house burning down. I would think that it's not a problem since the panel has been inspected but because it's labeled inspected for the garage power maybe they didn't look into this panel.

As far as the Sense issue goes, I noticed an circuit image on the inside of the panel cover I pulled off and will look at that and post if I can make sense of it.
Comment: You don't know what that inspection means. The only way to be sure is to get someone familiar with the Stab-Lok problem to look at your panel. There is no room for "maybe" here. You must call an electrician.
Comment: Checking with an old buddy that is an electrician to see if he knows anything about the Stab-lok panels. If he doesn't I am going to see if I can find a local electrician that knows of this problem and do an inspection/review so find out if the panel should be replaced.
Answer: The answer from manassehkatz (not related, but we do know each other :-) ) is very important, but it doesn't actually tell you what you want to know.
If you have a voltage meter or multimeter, you can very easily find out whether the poles of this breaker are on the same phase or different phases. (Important: if you are using a multimeter, make sure it is set to voltage measurement, not one of the other settings, before you touch the probes to anything.)
To test, touch one meter probe to one breaker terminal and the other probe to the other terminal. If you read 240v, you are properly on both phases. If you read 0v, you have both on the same phase. You can do this same test on other two-pole breakers too to see what it should look like.
Comment: Which is probably what the Sense is doing internally. But a multimeter is a lot faster.
Answer: I did manage to figure out the Sense problem by looking at the specs diagram for the panel. It showed a set of 2 poles with one that used phase A and another that used phase B.
Sense issue is resolved but now I need to get this panel looked at and replace if electrician states it is a problem/fire hazard.
Comment: So what is the phase pattern on the stab lok?  AA BB AA BB ?  I've definitely had a 240v oven breaker installed on a single phase such that the outlet and clock worked but the heating elements didn't so the "a 240v breaker can't be installed wrong" isn't correct.


Turning a boolean function into a method? (python)

Question: I'm struggling with an assignment for my programming class. The question it gives is:

Write a Boolean function between that takes two MyTime objects, t1 and t2, as arguments, and returns True if the invoking object falls between the two times. Assume t1 <= t2, and make the test closed at the lower bound and open at the upper bound, i.e. return True if t1 <= obj < t2.
Turn the above function into a method in the MyTime class.

My code looks like this:
class MyTime:

  def __init__ (self, hrs=0, mins=0, secs=0):
    t_secs = hrs*3600 + mins*60 + secs
    self.hrs = t_secs // 3600 # Split in h, m, s
    left_over_secs = t_secs % 3600
    self.mins = left_over_secs // 60
    self.secs = left_over_secs % 60

    #print (t_secs)

  def increment(t, secs):
    t.seconds += secs
    while t.seconds >= 60:
        t.seconds -= 60
        t.minutes += 1

    while t.minutes >= 60:
        t.minutes -= 60
        t.hours += 1

  def __str__(self):
    return "{0}:{1}:{2}".format(self.hrs,self.mins,self.secs)

  def __lt__(self,t2):
    if self.hrs<t2.hrs:
      return True
    if t2.hrs<self.hrs:
      return False
    if self.hrs==t2.hrs:
      if self.mins<t2.mins:
        return True
      if t2.mins<self.mins:
        return False
    if self.mins==t2.mins:
      if self.secs<t2.secs:
        return True
      if t2.secs<self.secs:
        return False

  def __eq__(self,t2):
    return bool(self.hrs == t2.hrs and self.mins == t2.mins and self.secs == t2.secs)

  def __le__(self,t2):
    return bool(self.hrs <= t2.hrs and self.mins <= t2.mins and self.secs <= t2.secs)

  def __ge__(self,t2):
    return bool(self.hrs >= t2.hrs and self.mins >= t2.mins and self.secs >= t2.secs)

  def __ne__(self,t2):
    return bool(self.hrs != t2.hrs or self.mins != t2.mins or self.secs != t2.secs)

  def __add__(self,t2):
    h=self.hrs+t2.hrs
    m=self.mins+t2.mins
    s=self.secs+t2.secs

    while s > 59:
      s-=60
      m+=1
    while m>59:
      m-=60
      h+=1

    sum_t=MyTime(h,m,s)
    return sum_t

  def between(self, t1, t2, t3):
    if t1.hours < t2.hours and t2.hours < t3.hours:
      return True
    else:
      return False

and my main/running code looks like this:

from MyTime import MyTime

t1 = MyTime(1,3,30)
t2 = MyTime(1,4,16)
t3 = MyTime(3,4,26)

def between(self, t1, t2, t3):
    if t1.hours < t2.hours and t2.hours < t3.hours:
      return True
    else:
      return False

print(between(t1, t2, t3))
print(t2.between(t1, t3))

I keep getting a "TypeError: between() missing 1 required positional argument: 't3'" error but I'm confused as to how to fix it?
I originally had it submitted with the between statement commented out in the MyTime file and that worked somehow. I might've changed something else too, but I've been messing with it too long to remember. Please help I only have one chance to resubmit it and I'm stumped!
Comment: Your `__le__`, `__ge__`, etc. implementations are wrong. Your  `__lt__` had the right idea: you check the most significant units (hours) for a difference first, and only if they're equal do you continue on to break ties with the next smallest unit (minutes), and so on. By comparison, your `__le__` is saying something like "T1 is smaller than T2 only if its hours, minutes ***and*** seconds are ***all*** smaller". But that isn't the case. E.g. 10:59 is less than 11:00, even if its 59 minutes is greater than the 00 minutes.
Comment: Expanding on my prev comment: you only really need to implement `__lt__` and `__eq__`, and all the rest can be implemented _in terms of_ those two base methods. For example, `__le__(self, other)` can be implemented as `self.__lt__(other) or self.__eq__(other)`.
Comment: That's a weird assignment. *"the invoking object"*? What? How is the function supposed to find it? Inspect the call stack or other hackery?
Answer: Your current issie is that def between is a "free" function not associated as a method on the MyTime class. Your free function def between shouldn't have a self.
What happens is that when you call between(t1, t2, t3), the arguments are assigned in a way you didn't expect, as if you did:
print(between(self = t1, t1 = t2, t2 = t3, t3 = ... missing!))

What you want instead is to move and indent the entire between method to be in the class MyTime body, along side your other methods like you showed in your first big code block.
The issue then is that your method is taking in too many parameters. When you call it like t2.between(t1, t3), the arguments don't line up with the paramters as you expected:

The first parameter self is filled in with the receiver of the method call, t2.
The second parameter t1 is filled in with the first positional parameter of your method call, t1
The third parameter t2 is filled in with the second positional parameter of your method call, t3
The fourth parameter t3 is left unpopulated, because there is no third position argument in your method call.

As you see, t3 is excess and unused. What you want is something like:
class MyTime:
    # ...

    def between(self, start, end):
        if t1.hours < self.hours and self.hours < t2.hours:
            return True
        else:
            return False

However, you should consider renaming t1 and t2 for clarity. Perhaps start and end would be more clear:
class MyTime:
    # ...

    def between(self, start, end):
        if start.hours < self.hours and self.hours < end.hours:
            return True
        else:
            return False

From there, you might reconsider the way between only looks at the hours of the various times involved. You'll probably want start < self and self < end instead, so that it calls your custom <operator (__le__ method) to do the comparison (taking into account the minutes and seconds, not just the hours).
Comment: "*`def between` shouldn't have a `self`*": In that case, it should be decorated with `@staticmethod`.
Comment: @InSync I'm not so sure, this looks to be a free function outside the `MyTime`. Which now that I think about it... is the issue.
Comment: @InSync Just updated my answer. Can you please delete your comment so as to not pull OP off track? I think they intended this to be an instance method all along.
Comment: t1 and t2 are perfectly fine standard names for times, see for example [this](https://www.science-campus.com/physics/mechanics/kinematics/chapter2/kinematics_2_6_velocity.php). And the OP didn't make them up, they're specified in the given assignment. Better don't deviate from that. (Final code should probably just be `return t1 <= self < t2`, literally what the assignment said except for the variable name (I'd say Python standard trumps the assignment)).


Can I use '!!' in aliases or scripts?

Question: In the Terminal I can use !! which will reference my previous command. Is it possible to use this in an alias? I have tried it, but what happens is that the double exclamation marks are interpreted literally.
What I want to have possible is:

I enter some command
I type an alias that will include what was entered in step 1

If there is a solution using scripts that is also acceptable.
Comment: what is your main goal ?  add more options to last command ?
Comment: No my goal is to quickly type a long command I often use. In the middle of it is a long string that often is the previous command
Comment: it seems you want just `fc` command so it opens a text editor , because that is the easiest way to edit long commands. Let me add it to my post .  Also , maybe you could provide an example of command ?
Comment: Added an edit to my post
Comment: http://superuser.com/q/240180/337511
Answer: The command that lists the last executed command is fc -nl -1 . Using output substitution , we can add more parameters to the same content
$> ls /etc/passwd
/etc/passwd
$> $(fc -nl -1)  /etc/group
/etc/group  /etc/passwd
$>

Quoting , however, may be an issue with this approach
A very nice feature of fc is that if you just run fc command by itself, it will open text editor specified inFCEDIT variable (which you probably want stored in ~/.bashrc) and the contents of the line will be your last command. For your ease, I suggest you use nano as your text editor, but if you know vim  - even better.
For example, what if I need to edit qdbus org.ayatana.bamf  /org/ayatana/bamf/matcher org.ayatana.bamf.matcher.ActiveWindow Huge line, right ? But with fc, I can open vim and edit /org/ayatana/bamf/matcher , save, exit and it will run.
Answer: You can't use !! but ...
From the manual:

A useful alias to use with the fc command is r='fc -s', so that typing 'r cc' runs the last command beginning with cc and typing 'r' re-executes the last command.
Comment: So this will allow me to add something to the beginning of my last command. What about in the middle of it?
Answer: If you insist on using the !! history expansion syntax instead of fc (mentioned already), there is a way.
By default, history expansion is disabled for non-interactive shell sessions e.g. in scripts.
To enable history expansion in scripts enable the relevant shell options first:
set -o history
set -o histexpand

set -o histexpand can be written as set -H too.
Now the history expansion operations e.g. !! would work inside the script.

Can I use '!!' in aliases or scripts?


Problem in merging two sorted arrays using pointers

Question: I am trying to merge two sorted arrays using pointers. The third loop is working food upto first arr[5] but then show garbage values afterwards. is the sorting techniqure wrong or am I using pointers incorrectly?
#include<iostream>
using namespace std;

int main() {
    int arr1[] = { 1,3,4,6 };
    int arr2[] = { 2,3,4,5 };
    int n1 = 4;
    int n2 = 4;
    int arr3[10];
    int* endptr = &arr1[0];
    int* endptr2 = &arr2[0];
    int* endptr3 = arr3;
    int k = 0;

    while (endptr < &arr1[n1-1] &&endptr2  < &arr2[n2-1]) {
        if (endptr[0] < endptr2[0]) {
            endptr3[k++] = endptr[0];
            endptr++;
        }

        else {
            endptr3[k++] = endptr2[0];
            endptr2++;
        }
    }
    while (endptr < &arr1[n1 - 1]) {
        endptr3[k++] = endptr[0];
        endptr++;
    }

    while (endptr2 < &arr2[n2 - 1]) {
        endptr3[k++] = endptr[0];
        endptr2++;
    }
    cout << arr3[5];
}

I got the results up to first 6 elements and then get garbage values.
Comment: It should be `&arr1[n1]` (or more simply `arr1+n1`). Your version ignores the last element of each array.
Comment: `enptr[0]` is just `*endptr`. I would suggest to not mix pointer arithmetics and `[]` too much, but stick with one. in general `arr[i]` is the same as `*(arr + i)`
Comment: To be clear `endptr <= &arr1[n1-1]` would be ok, but if you are using `<` then it should be `endptr < &arr1[n1]`. And of course the reason you only get 6 values is that you are only considering the first three elements of each array,
Comment: In your last while loop you have `endptr3[k++] = endptr[0];` based on the variable naming I would expect this to be `endptr3[k++] = endptr2[0];`
Comment: what is "garbage" ? please include output  and expected output in the question
Comment: @john yep that was the problem, thanks
Comment: @user20716902 Yes that was a mistake, I corrected it thanks
Comment: The boundary conditions are completely wrong. If you take out a piece of paper, and work it out whether it should really be, for example, `endptr < &arr1[n1-1]` or `endptr < &arr1[n1]`, the results will surprise you.
Answer: The way you are using the pointers is negatively affecting your thought process.
Let's abstract it to a function to help make it cleaner:
void merge(
  int * first1, int * last1,  // elements of array1
  int * first2, int * last2,  // elements of array2
  int * dest )                // where to put sorted data

This is the "iterator" idiom used by C++ algorithms. first points to the first element. last points to one-past the last element. (And we assume that dest points to enough space to contain the results.) So:
int array1[] = { 1,3,4,6 };
int array2[] = { 2,3,4,5,7 };
int array3[9];  // enough room for array1+array2

merge(
  array1, array1+4,  // first array has 4 elements
  array2, array2+5,  // second array has 5 elements
  array3 );          // destination array has 4+5=9 elements

C++ actually gives us a couple of functions to get the first and last pointers to whatever underlying sequence container you've got:
merge(
  std::begin(array1), std::end(array1),
  std::begin(array2), std::end(array2),
  std::begin(array3) );

Now we can reconsider our merge algorithm.
void merge(...)
{
  // while both array1 and array2 have elements:
  while ((first1 != last1) and (first2 != last2))
  {
    if (*first2 < *first1)
      *dest++ = *first2++;
    else
      *dest++ = *first1++;
  }

  // if array1 has any leftover elements:
  while (first1 != last1)
    *dest++ = *first1++;

  // if array2 has any leftover elements:
  while (first2 != last2)
    *dest++ = *first2++;
}

In particular, notice:

We can easily check whether an array has elements by comparing the first and last pointers directly. When first == last, there are no elements, since last is one-past the end of the source array.
Comparison is simple enough. We could have written that as if (first2[0] < first1[0]) but that is less idiomatic than just using the * operator.
Copying a value is as simple as a dereference and increment on both sides of the assignment.
The three loops of the merge all work on a simple "are there elements left?" check.

Note also how we kept the test condition to a strict less-than comparison. That has ramifications for generic programming (for example, merge sorting in non-increasing order), but I'll leave it at that for today...


Why is Nokogiri giving me multiple results?

Question: I'm trying to parse an HTML string with Nokogiri but I'm getting some recursion issue and I can't figure out why.
Given these commands:
string =
Lancers were arranged.

Gabriel found himself partnered with Miss Ivors.

She leaned. He lit a candle.
         They followed him in silence, their feet falling in soft thuds on the thickly carpeted stairs.

body = Nokogiri::HTML(string)
result = []
body.traverse { |node| result << node }

I would expect an array of the above elements. Instead I get given this:
[#<Nokogiri::XML::DTD:0x3fde1f3d5274 name="html">
#<Nokogiri::XML::Text:0x3fde1e88d330 "Lancers were arranged. ">
#<Nokogiri::XML::Element:0x3fde1ea56a68 name="h3" children=[#<Nokogiri::XML::Text:0x3fde1e88d330 "Lancers were arranged. ">]>
#<Nokogiri::XML::Text:0x3fde1e88c764 "Gabriel found himself partnered with Miss Ivors.">
#<Nokogiri::XML::Element:0x3fde1e88cd04 name="div" children=[#<Nokogiri::XML::Text:0x3fde1e88c764 "Gabriel found himself partnered with Miss Ivors.">]>
#<Nokogiri::XML::Element:0x3fde1e88c0fc name="br">
#<Nokogiri::XML::Text:0x3fde1e88b9e0 "She leaned. He lit a ">
#<Nokogiri::XML::Text:0x3fde1eba6c60 "candle">
#<Nokogiri::XML::Element:0x3fde1e88b5f8 name="b" children=[#<Nokogiri::XML::Text:0x3fde1eba6c60 "candle">]>
#<Nokogiri::XML::Text:0x3fde1eba6454 ". They followed him in silence
their feet falling in soft thuds on the thickly carpeted stairs.">
#<Nokogiri::XML::Element:0x3fde1eba5f54 name="br">
#<Nokogiri::XML::Element:0x3fde1ea56f7c name="body" children=[#<Nokogiri::XML::Element:0x3fde1ea56a68 name="h3" children=[#<Nokogiri::XML::Text:0x3fde1e88d330 "Lancers were arranged. ">]>
#<Nokogiri::XML::Element:0x3fde1e88cd04 name="div" children=[#<Nokogiri::XML::Text:0x3fde1e88c764 "Gabriel found himself partnered with Miss Ivors.">]>
#<Nokogiri::XML::Element:0x3fde1e88c0fc name="br">
#<Nokogiri::XML::Text:0x3fde1e88b9e0 "She leaned. He lit a ">
#<Nokogiri::XML::Element:0x3fde1e88b5f8 name="b" children=[#<Nokogiri::XML::Text:0x3fde1eba6c60 "candle">]>
#<Nokogiri::XML::Text:0x3fde1eba6454 ". They followed him in silence
their feet falling in soft thuds on the thickly carpeted stairs.">
#<Nokogiri::XML::Element:0x3fde1eba5f54 name="br">]>
#<Nokogiri::XML::Element:0x3fde1ea575e4 name="html" children=[#<Nokogiri::XML::Element:0x3fde1ea56f7c name="body" children=[#<Nokogiri::XML::Element:0x3fde1ea56a68 name="h3" children=[#<Nokogiri::XML::Text:0x3fde1e88d330 "Lancers were arranged. ">]>
#<Nokogiri::XML::Element:0x3fde1e88cd04 name="div" children=[#<Nokogiri::XML::Text:0x3fde1e88c764 "Gabriel found himself partnered with Miss Ivors.">]>
#<Nokogiri::XML::Element:0x3fde1e88c0fc name="br">
#<Nokogiri::XML::Text:0x3fde1e88b9e0 "She leaned. He lit a ">
#<Nokogiri::XML::Element:0x3fde1e88b5f8 name="b" children=[#<Nokogiri::XML::Text:0x3fde1eba6c60 "candle">]>
#<Nokogiri::XML::Text:0x3fde1eba6454 ". They followed him in silence
their feet falling in soft thuds on the thickly carpeted stairs.">
#<Nokogiri::XML::Element:0x3fde1eba5f54 name="br">]>]>
#<Nokogiri::HTML::Document:0x3fde1f3d6084 name="document" children=[#<Nokogiri::XML::DTD:0x3fde1f3d5274 name="html">
#<Nokogiri::XML::Element:0x3fde1ea575e4 name="html" children=[#<Nokogiri::XML::Element:0x3fde1ea56f7c name="body" children=[#<Nokogiri::XML::Element:0x3fde1ea56a68 name="h3" children=[#<Nokogiri::XML::Text:0x3fde1e88d330 "Lancers were arranged. ">]>
#<Nokogiri::XML::Element:0x3fde1e88cd04 name="div" children=[#<Nokogiri::XML::Text:0x3fde1e88c764 "Gabriel found himself partnered with Miss Ivors.">]>
#<Nokogiri::XML::Element:0x3fde1e88c0fc name="br">
#<Nokogiri::XML::Text:0x3fde1e88b9e0 "She leaned. He lit a ">
#<Nokogiri::XML::Element:0x3fde1e88b5f8 name="b" children=[#<Nokogiri::XML::Text:0x3fde1eba6c60 "candle">]>
#<Nokogiri::XML::Text:0x3fde1eba6454 ". They followed him in silence
their feet falling in soft thuds on the thickly carpeted stairs.">
#<Nokogiri::XML::Element:0x3fde1eba5f54 name="br">]>]>]>]

Sorry for the length. Can anyone help me figure out why this happens? And/or how to prevent it?
Comment: Please paste the input and output HTML separately. Don't use a single-line string or a stringified object. It's hard to follow, and if you had done that I think you'd see the problem (`Element` objects include their children, even when stringified).
Answer: This happens because traverse calls the provided block on itself and all its children recursively. So it adds every node of your html string to the result array instead of just the top level nodes. The 'multiple results' you are seeing is a result of how inspect is defined for Nokogiri nodes. For example the 3rd element in the returned array represents the h3 node, but also prints all of its children, which includes the text node that is the 2nd element of the array.
If you want result to include a reference to every node in the document than this is the right way to do it. If you just want top level nodes use children
Answer: When you parse incomplete html, Nokogiri automatically adds doctype and html and body elements. You have to parse it like this to avoid this behavior:
body = Nokogiri::HTML::DocumentFragment.parse(your_html)

If you want result to be and array of elements excluding text nodes you can do this:
result = body.xpath('./*')

Then the result (converted to string for clarity) will be:
["
Lancers were arranged.
",
 "
Gabriel found himself partnered with Miss Ivors.
",
 "
",
 "candle",
 "
"]

Comment: Just tried it and it is not repeated, this is what I got ["text", "h3", "text", "div", "br", "text", "text", "b", "text", "br", "#document-fragment"]. Maybe the last element confuses you. It is the whole fragment you called traverse on.
Comment: `*` won't include text nodes. You could do something like `./*|./text()` but it's simpler to use `children` like @Alex Bullard says.
Comment: That helps half the issue, it seems. Significantly less repeating going on, but elements like the first `` are repeated twice.
Comment: That is _so_ close. The `xpath('./*')` cuts out everything _not_ in an element though. The problem with the HTML code is that it's automatically generated and I can't predict which paragraphs will be wrapped and which won't.


2-wire switch loop controlling 2 outlets - replacing with 3-wire to fix?

Question: I am in nearly this exact situation:
Can I use a switch loop to power a ceiling fan?
We are trying to install a fan, but instead of having a single duplex outlet on the same wall as the switch, we have 2 different duplex outlets on opposite sides of the room behind plaster walls.
This is the first time I've ever worked with a switch loop, and honestly, my brain is failing me. Can I replace the 14/2 romex between the closest outlet and the switch with 14/3, which should give me all of the conductors necessary to hook up the fan switch and fan? Or do I need to replace the wire between the two duplex outlets as well (as I said, the switch controls both of them)?
The first is probably something I can do with a spare saturday, a fish tape, and a 25' piece of 14/3. The second would require tearing down plaster through a good part of my wife's studio and more patching than I think we're really able to do right now.
Any help would be very much appreciated. Now I'm aware that several rooms in our house seem to be wired this way, and I'm thinking I have a mess on my hands. Especially because it doesn't look like any of the white wires have been marked as hot.
Edit due to confusion:
This diagram shows approximately how the wiring looks. The major differences would be, instead of having a lamp, there are 2 outlets. Both outlets are switched. Switch goes on, both outlets get power. Switch goes off, both outlets lose power.

What I believe I need to do is rewire the outlets and switch so they match this diagram which follows modern code:

These wiring diagrams belong to do-it-yourself-help.com. The original images can be found here: https://www.do-it-yourself-help.com/wiring_switches.html
What I need to know is if I have to include both of the outlets if I replace the 14-2 wire with 14-3? Can you install 14-3 half way through the switch loop?
Comment: It isn't clear from the description what the switch currently controls. Are the outlets switched, or is there a ceiling box that is switched?
Comment: Both outlets are switched. Switch goes on, both outlets get power. Switch goes off, both outlets lose power. I am trying to add a second switch into the same box that will be connected to a ceiling fan (similar to the other question).
Comment: Your two diagrams appear to be identical circuits; the only differences are (a) wire color conventions, and (b) carrying the neutral through to the switch box. Neither diagram shows a three-way switch setup, which is what you seem to be saying you have (two switches either of which can turn the fixture on or off). If you want to control the fan the way you now control the light, hook it up the way the light is hooked up. If you want separate control from the switchplates over the fan and its built-in light fixture, then you need to rewire to add another circuit.
Answer: The reference to a switch loop in the related question describes a pair of wires that are both hot or live. The white wire is serving as a black and should have a black marking or tape on it. The switch is serving as a break in the hot line.
Every operating device (like a fan or lamp) in standard wiring needs a hot line and a neutral line, and usually a ground, although that is not strictly necessary in all circumstances. In the wiring described in the other question, there was no neutral running through the switch box, but there had to be a neutral connected to the device itself, in the box that the fixture was attached to. The neutral wire is never switched, so only the hot lead was routed to the switch loop. Modern code requires that new switch circuits also have a neutral present, since some newer switch devices need a neutral to function.
Your situation may be different. On your circuit, one of the three boxes is closest (electrically) to the main panel. There is a live circuit line running either to one of the outlets or to the switch box. In either case the outlets you describe must have a neutral wire present as well as a hot wire.
If you want the fan to be switched on and off by the same switch as the outlets, you can simply add a wire from either outlet box to the fan location and connect all wires in parallel (black/white/ground).
If you want a separate switch for the fan, you need to tap into the power where the live circuit comes in to the room. It may be either of the outlets or it may be the switch box (if there is a neutral in that box). You need to tap into the unswitched hot, run that hot to a new switch and connect the neutral and ground in parallel. Then run the full cable from the new switch to the fan.
If you want to use separate hard wired switches for fan and light, run 14/3 from a switch box fed by the always hot line, using the two hots separately for the two features.
An alternative if you want separate switching is to run a full cable (14/2 or 12/2) directly to the fan from the box that has an unswitched hot. Use a fan that has a hand-held or wall mounted remote and wire the fan as always hot (no line switch). Then the remote controls whether power is going to the fan. This also simplifies installing a fan/light combination.
As to your other outlets, white wires are generally not hot unless used to connect to switches and should be so marked. Most white wires are neutral. You can test your outlets for correct wiring with a plug-in tester like this one.
.
If the tester reveals miswiring, you should consider calling in a pro. It also sounds as if you are not too familiar with wiring in general, so you may want to enlist the help of someone with a bit more experience until you become more confident. In any event be sure to turn of the circuit breakers before opening any box and confirm wire are not live with a non-contact tester like this one

<code> images and links are for illustration only, and not an endorsement of goods or sources
</code>
Comment: I've edited for clarity. I know for a fact that this is a switch loop. There is no functional neutral in the switch box. It's just a white wire, the same as shown in the diagram I've added. This is a house from the 1950's, so there's been a number of things I've had to update to bring up to code.
Answer: If I understand your question correctly - let me verify that first.
You have one switch controlling two outlets. You want to add a ceiling fan. It's not quite clear whether your ceiling fan is to also be controlled by the switch, but at this point that's pretty moot.
You currently have 14-2 supplying power to the first outlet box, where it breaks out into a switch loop before connecting to that outlet, then continuing on to the second outlet. The switch loop is wired with 14-2, and you have 14-2 running from that first (switched) outlet box to the second.
The switch loop's white wire is marked at both ends to indicate that it's used as a load-carrying conductor, in conformance with pre-2011 code, but you want to update that to a 14-3 instead so that both load-carrying conductors will be "colors" and a neutral is supplied to the switch.
Your question SEEMS to be one of whether 14-3 also needs to be run from that first switched outlet box to the second. If I'm correct, no - it doesn't, provided that the second outlet is to be switched; it can be driven entirely from the first switched outlet with 14-2.
Answer: It is quite interesting how not only the answers, in varying degrees, drift off-topic, but also how the question and or the premise conditions are clearly misunderstood at times, with responses that are unrelated to the question! Several aspects of the answers provided are excellent, but don't quite get to solving Matthew's dilemma. Yes, this is very late in the game, as in four years late! But I just tripped over it and thought others may also find it who have a similar situation and are looking for a useful answer.
First off, Matthew's accompanying diagrams throw a potential respondent off track if not considered only as representative of his situation. He said, "we have 2 different duplex outlets on opposite sides of the room", and, "Both outlets are switched. Switch goes on, both outlets get power. Switch goes off, both outlets lose power."  Ok, now we know that neither outlet is half-switched, as one respondent suggested; both outlets are fully switched -- power on, or power off.  Next, he said, "I am trying to add a second switch into the same box that will be connected to a ceiling fan."
And he said, "The second [option] would require tearing down plaster through a good part of my wife's studio and more patching than I think we're really able to do right now."
With that information we can provide a plausible and effective answer. His primary question is should he wire a new 3-wire cable in place of one or more of the existing 2-wire cables between the two existing outlets and up to the switch box. Answer: yes, but only if you want to maintain the switched outlets. Although he never said whether or not he wanted to do that, he did imply it by saying, "I am trying to add a second switch into the same box that will be connected to a ceiling fan."
This is where a bit of experiential intuition comes in handy. He wants to install just a ceiling fan, switched from the wall; in fact, from the same existing 1-gang switch box, as also implied by the information he provided. Given the conditions, and the fact that he does not want to engage in all the work necessary to run the total of three new 3-wire cable(s) (or add a second switch), and have to do all the plaster repairs, we can suggest the following.
Turn off the power; open up the two duplex outlets and the switch outlet; remove the switch; reconfigure the wiring at both duplex outlets such that both duplex outlets are no longer switched, rather, wired to be live all the time. This means simply connecting the two whites to the neutral side and the two blacks to the hot side of each of the two duplex and close them up.
Now the black at the switch box is a full-time, live hot wire, and the white at the switch is a "live" neutral wire.
Next, buy a light kit for the ceiling fan. Next, wire a new 3-wire up to the ceiling fan/light location from the existing switch box. Of course, install a fan-rated box support assembly.  And of course, connect/splice/terminate the EGC (Equipment Grounding Conductor), the bare copper wires, to the duplexes and the boxes and the switch, as and where required.
At the switch box, using a new duplex switch (two single pole switches on one device yoke, a "stacker" as it is sometimes called), connect the wires: first, splice the neutrals (the whites) together with a wirenut and fold them away. Observing the wiring diagram on the stacker switch, connect the black, full-time hot wire (coming from the last duplex receptacle where the wiring was reconfigured) to the "hot" or "line" terminal screw on the stacker. Next, connect the 3-wire black wire (going up to the fan/light) to either the top or bottom screw on the other side of the stacker; now connect the 3-wire red wire to either the top or bottom screw on the other side of the stacker.  Now there are two switch legs going up to the ceiling fan/light location. At the fan/light, connect the fan black wire to the 3-wire black wire, and the light wire, blue, to the 3-wire red wire. And of course connect the fan white wire to the white wire in the 3-wire cable. Now the fan/light has two separate and connected switch legs, to operate the fan and light independent of each other, and a neutral wire. Of course, in this scenario the pull chains on the fan will be used to control the fan speed, and to control the light dimming levels, if so equipped.
BONUS: instead of the stacker switch, buy a 1-gang dual control fan/light switch. It is highly recommended that this dual control switch device be manufactured by the fan manufacturer, OR, better yet, a combination fan/light control switch device manufactured by Lutron - they build them right, with 6 or 7 fan speeds and light dimming levels -- a bit pricey, but worth every penny. Now the fan speed and the light dim level can be controlled from the wall controller, all fitting in the existing 1-gang box.  What a package, nearly miraculous! And if there is access from above, probably no plaster cuts to repair, after running the new 3-wire from the existing switch box up to the new ceiling fan/light box. Another huge BONUS!! :)
For an inexperienced person this should take about eight hours, subject to attic access above to install the fan/light outlet box and fish the 3-wire down to the existing switch box. Don't forget to turn the power back on and enjoy the satisfaction of a job well done!!
Well, I hope I've done a good job explaining this and proof-reading it. I'll likely never be back to this particular post, but I do hope that someone will benefit from this oration. I am a nearly-retired Master Electrician with 45 plus years of experience in the residential electrical industry and hold a Class A Contractors License for nearly 30 years. I've done hundreds of very similar and successful installations. Cheers!
Comment: Hello, and welcome to Stack Exchange. Yes, there's a lot of good info here, but all the commentary gets in the way of people understanding your answer. Would you edit this down? Thanks.
Comment: Welcome to DIY.SE -- you raise lots of good points here, and don't worry about being a Stackromancer, we wear it as a [badge of pride](https://diy.stackexchange.com/help/badges/17/necromancer) around here :)
Answer: If you are adding a new ceiling fan with a light and currently only have switched outlets in that room ( I am assuming that you are installing a fan rated box properly supported in the ceiling) the outlets no longer need to be switched. At the outlet in your drawing you can remove the color markings from the White in the switch loop and re connect them white to white and black to black this will give you a hot and neutral at the switch box you can then run a 3 wire from the switch box to the fan light combination and switch them individually. Without more information I cannot tell you how to deal with the other switched outlet. PS Tell me if I am off base with what you are trying to do.
Comment: The NEC then and now allows for a switched outlet as an exception the rule requiring a switched ceiling light in living rooms, bedrooms etc. But the switched outlet cannot be one of the ones that need to be within 6 foot cord reach along usable wall space. That is why you find duplex outlets 1/2 switched. That is why I said if you are installing a new fan light combination switched at the wall you no longer need switched outlets in that room to comply with the code. They can be made hot all of the time.


How can I get a value from an array

Question: I am trying to solve this problem, I want to use these numbers one by one, but I cannot.
String a = "101";
char[] array = a.toCharArray();
for (int i = 0; i < array.length; i++) {
    // if i print array[i] it says 1 but in below,
    // it will give a reference. i want to get 1
    if (array[i] == 1) {
        System.out.print(1);
    } else {
        System.out.print(0);
    }

Comment: What do you mean by `it will give a reference`?
Comment: according to String a while i=0 , it has to print 1 but it don't print 1 @xdhmoore
Comment: I'm not 100% sure what happens when you compare a char with an int like in your if statement but I suspect that may be the problem.
Answer: Try this :
    String a="101";
    char [] array=a.toCharArray();
    for(int i=0; i<array.length;i++) {
          if(array[i]== '1'){
            System.out.println(1);
        }else {
            System.out.println(0);
        }
    }

Comment: thank you mate, what a bad mistake isn't it? :) i am sorry for this question. thank you again
Answer: You can index the array by doing array[...] for example if we wanted to get the value of the first element in our array we would do array[0] as indexing starts from zero.
You could update your code to the following!
String a = "101";
char[] array = a.toCharArray();
for (int i = 0; I < array.length; i++) {
    System.out.println(array[i]);
}

If you wanted to print out both the element at index i and the index i you could replace the println() above with System.out.println(i + " " + array[i]).
Hope I properly understood your issue and this helped!
Comment: thank you actually my main issue is i want to write a code like bitwase calculator  it was the just a part of my code. For example for OR statement.. my main aim is compare two array and decide if there is a 1 for two array's first numbers then write 1...
Comment: Ah I see, I misunderstood the question, looks like you made a simple mistake within your code by checking if the value is a number rather than a char.

How can I get a value from an array


TAOCP: Section 1.2.4 -> Q 23: An example to show the law is not correct

Question:
Question: Give an example to show that Law D is not always true if $r$ is not relatively prime to $s$.
Law D: If $r \perp s$, then $a \equiv b$ (modulo $rs$) if and only if $a \equiv b$ (module $r$) and $a \equiv b$ (modulo $s$).

Where $r, s, a, b$ are integers.
Suppose you have chosen numbers for $r$ and $s$, now let's say $a = krs + c$, for some integer $k$ and $c$.
Now we know $a \equiv c$ (modulo $rs$).
As $krs$ is multiple of $r$ and $s$ both, which implies
$a \equiv c$ (modulo $r$) and $a \equiv c$ (modulo $s$)
What I am doing wrong ?
Comment: I was talking about your spelling: T-A-O-C-P. Never heard it called "T-O-A-C-P" before.
Answer: One direction holds with no assumption on $r$ and $s$:

If $a\equiv b\pmod{rs}$ then $a\equiv b\pmod{r}$ and $a\equiv b\pmod{s}$

So if property D fails for $r$ and $s$ non coprime, you should be able to find particular values of $r$, $s$, $a$ and $b$ so that

$a\equiv b\pmod{r}$
$a\equiv b\pmod{s}$
$a\not\equiv b\pmod{rs}$

Can you find suitable $a$ and $b$ for $r=s=2$?
Comment: Suppose $a = 2$ and $b = 2$ then
$2 \equiv 0$ (mod $r$),
$2 \equiv 0$ (mod $s$) and
$2 \equiv 2$ (mod $rs$), but as it is $\equiv$, we can choose $b$ for the  $2 \equiv 0$ (mod $r$) and $2 \equiv 0$ (mod $s$) as $2$. Can't we ?
Comment: @Abhisek You're on the right track, but $a=2$ is good, whereas $b=2$ isn't: why not $b=0$, which is what you're actually using?
Comment: The $\equiv$ relation confused me($b = 2 \equiv 0 = b`$). We need to make sure the relation should satisfy for every $b$) not just one. Got it thanks


Empathy will not authorize facebook account

Question: Short and sweet:
I can not get Empathy to add facebook as an account.  At all.
It asks me to log into facebook (the firstname.lastname@example.com will not work here, I tried. Comes back as invalid, and yes I used the 'url' username) in a chrome browser (even had firefox as default when attempting this, same thing occured), and all I get is 'Success
Warning:  Treat the above url like your password' or something close.  And account settings still 'waits' for verification from facebook.
Anyone else fix this issue yet?  I've disabled secure browsing, account login notifications, logged out, removed ubuntu app from facebook.
Otherwise I'll just grab another chat for ubuntu.
Answer: Facebook Chat will stop working in Empathy and other third-party desktop instant messaging clients from April 30, 2015
At some point after April 30 — Facebook say API deprecation may take a few weeks — trying to connect to Facebook Chat using an application like Pidgin or Empathy will no longer work and will throw a connection error.
Although the (seemingly sudden) loss of a popular chat service will surprise desktop users it is not news to developers.
Facebook announced it would deprecate the XMPP Chat API that lets third-party applications 'connect' to Facebook chat way back in April of last year.
A replacement API for accessing Facebook Chat (or Messenger) has not been announced.
Source: http://www.omgubuntu.co.uk/2015/04/facebook-chat-api-empathy-pidgin-stop-working
In the meantime, in security settings in Facebook you can generate a special password for Jabber that will allow Empathy and Pidgin to work.
Answer: What's happened is facebook.com (well the chat) does not use https anymore.  Empathy wants to.  You have to manually edit the settings.  It's easy, but again you're connecting via http, so be on a trusted network.
Steps:

Close out empathy/account settings.
Open terminal (ctrl+alt+T or search terminal)
Enter this command:
sudo nano /usr/share/accounts/providers/facebook.provider

Look for the following line in the file:
<group name="user_agent">

Add this directly after that line:
<setting name="AllowedSchemes" type="as">['https','http']</setting>

Hit ctrl+X
Type yes or y, hit enter
Reboot your system
You should now be able to log into facebook from account settings.

Note: Copy the commands above exactly.  In otherwords /usr/ is the actual path, not to be replaced with your own username.
And again, you're now connecting over an unsecured/encrypted connection to facebook.  Use this only on a trusted network.
Comment: Ubuntu 13.04 has this option default. But still not working.
Comment: Not works in ubuntu 13.10


How to set Word wrap in label in Xamarin Android (native)?

Question: I have tried the below code for wrap the text inside the treeview in native android. But it doesn't work. Have anyone know how to wrap the text in label.
        android:ellipsize="end"
        android:width="0dip"
        android:maxLines="2"

could you please tell me how to wrap the text?
Answer: This line of code seems to be wrong:
android:width="0dip"

Maybe you wanted to fix the width using the layout_width attribute.
Instead of
android:ellipsize="end"
android:width="0dip"
android:maxLines="2"

do this
android:ellipsize="end"
android:layout_width="0dip"
android:maxLines="2"


Why is the gap between consecutive twin primes always a number of integers divisible by 3?

Question: For example: (5,6,7)8,9,10(11,12,13)
(227,228,229)230,231,232,233,234,236,237,238(239,240,241)
Comment: Because twin primes (except 3 and 5) will always be of the form $6k-1$ and $6k+1$, for some integer $k$.
Comment: @vadim123 you should post this as an answer
Answer: Every prime greater than 3 is of the form $6n\pm1$. Why? Hint: every number can be written as one of $6n, 6n+1, 6n+2, 6n+3, 6n+4, 6n+5$. Which of those have factors?
Bonus fun: What's special about $6$? Hint: look at the factors of the non-primes among $6n, 6n+1, 6n+2, 6n+3, 6n+4, 6n+5$. What if we try a different number that's the product of two small primes? Three small primes?


how to reverse an if condition in php?

Question: hi I am trying to see if i can reverse this if statement so that I can have an if condition which lists results only if the user session is not the user id.
I'm brand new to mysql and php and would really appreciate if someone could show me what i need to do
here's the if statement I'm trying reverse so if $user['id'] is not $_SESSION['user_id']
if ($user['id'] == $_SESSION['user_id']){

I've tried this: (doesn't work and brings up a syntax error)
if (!isset($user['id'] == $_SESSION['user_id'])){

Comment: What does this have to do with `mysql`?
Comment: Actually, there's nothing to do with mysql, but reversed condition : if ($user['id'] != $_SESSION['user_id']){
Comment: http://php.net/language.operators.comparison ...
Comment: != ? $user['id'] != $_SESSION['user_id']
Answer: This is fairly simple and actually basic PHP stuff:
if ($user['id'] != $_SESSION['user_id'] )
Answer: Just check using if condition
if(!$user['id']==$_SESSION['user_id'])

Comment: This isn't very readable, I would suggest changing to

    `if( $user['id'] != $_SESSION['user_id'] )`
Answer: In addition to Sturb's answer you can also reverse the variables:
if($_SESSION['user_id'] != $user['id'])

how to reverse an if condition in php?


Ultima 6 - who knows where to find the vortex cube

Question: I have surrendered to Lord Draxinusim and promised to give my life as a sacrife. Since then i can talk to the Gargoyles. I learned from the Book of Rituals that i can return the codex if i put the Moonstones inside the vortex cube and use the Lens from the Gargoyle (and yes - also use the Lens of the human, later i learned from the seer).

Question
how do i know where to find the vortex cube?
Note
of course i have read (in the oh-so-many walkthroughs) that the Cyclopses in ?Stonekeep? have the cube, but i have no idea why i should search for the cube right there! is there a hint, why it's in Stonekeep and not in the gargoyle realm?
Answer: The caretaker in the Hall of Knowledge mentions that the cube was stolen from the gargoyles by two humans thieves and that they were heard mentioning Stonegate as they fled.
This is the relevant line:
cham,vort,libr,huma: "To have three rooms here:" "To keep artifacts from the Underworld in the Human Chamber, to the east." "To keep valuable books in the Librum Chamber, to the west." "And to keep the Cube and the Lens in the Vortex Chamber, to the south."
cube: "To regret that that item is lost, stolen by human thieves years ago." "To have heard the humans mention the name Stonegate as they fled." "To have heard them say they would sail through Lost Hope Bay." "To know nothing more about its whereabouts."
So, once again, the expected plot would probably have you look in the Hall for the Cube, find out it is no longer stored there, ask for info and get the clue to Stonegate.
Comment: ok - i definitly talk too little with the characters in the game - instead of talking i rushed to the objects and ignored the keeper of the hall of knowledge - thank you very very much!!! all makes sense now!


Project reference - Type or namespace name 'Library' does not exist in the namespace; target framework matches (Asp.net)

Question: I have a project that references several other Projects in the solution. Project.Web references Project.Library; this reference has existed forever, but some changes have been made to Project.Library and now I'm getting the error "The type or namespace name 'Library' does not exist in the namespace 'Project' (are you missing an assembly reference?)"
I checked the target framework of all of my projects- Project.Web, Project.Library, RedirectModule, and SitecoreEloquaConnector - all of them are set to Target Framework = .NET Framework 4.5.2
I tried deleting the reference and readding it but I still get the error.
Comment: if all the projects are in a single solution, question..do they all share the same namespace? are there some classes that do not use namespace? can you show your code in regards to the namespace for those .. can you show the .cs file of the one where you are getting the error vs the ones that work..?
Answer: You should remove the references and add them manually.When you click add reference,choose browse and look for the library dll.After that rebuild solution,and it should work.


Tk_Init error: Can't find a usable tk.tcl in the following directories

Question: On my Ubuntu 20.04 I try to open "qdec" of "freesurfer" and get the following error:
<code>Tk_Init error: Can't find a usable tk.tcl in the following directories:
    /home/username/tcl8.4.6/tk8.4 /home/username/freesurfer/freesurfer/lib/tk8.4 /home/username/freesurfer/lib/tk8.4 /home/username/freesurfer/freesurfer/library /home/username/freesurfer/library /home/username/freesurfer/tk8.4.6/library /home/username/tk8.4.6/library

This probably means that tk wasn't installed properly.
</code>
the rest of freesurfer works (e.g. "freeview") and I am not able to find out how to fix this problem. I think I should somehow install tk8.4.6 in one of the directories it is searching for it or link the directory to an installed version, but I am not sure how to do it. Could someone help me?
edit: freesurfer is a neuroimaging toolbox and qdec is a specific programme of this toolbox. I attached the wiki of the toolbox and the page where I found out about the qdec gui.
freesurfer wiki: https://surfer.nmr.mgh.harvard.edu/fswiki
qdec introduction: https://surfer.nmr.mgh.harvard.edu/fswiki/FsTutorial/QdecGroupAnalysis_freeview
I installed freesurfer version freesurfer-linux-centos6_x86_64-7.2.0-20210720-aa8f76b
Comment: What are qdec and freesurfer? What was wrong with `tk` and `tcl` packages from official repository? Please make your question more reproducible.
Comment: According to this [FreeSurfer Setup and Configuration](https://surfer.nmr.mgh.harvard.edu/fswiki/SetupConfiguration_Linux) the installation should have come with its own tcl/tk distributions, located in `$FREESURFER_HOME/lib/tcltktixblt`. Do you see anything there?
Comment: @steeldriver: After installing freesurfer, I have several folders in the lib, but no tcltktixblt.. I found: $FREESURFER_HOME/lib/{ tcl, tktools, bem, images, qt, resource, vtk}
Answer: After inspecting my folders I realized, that freesurfer was looking in the lib path but not in lib/tktools so I copied everything from the lib/tktools folder into the lib folder, as I did not know how to change the folders it was searching. Now I can run the qdec gui.


Getting error while trying to install BadgeKit dependencies

Question: I try to install BadgeKit with this manual.
npm install dies with next npm-debug.log.
npm install --verbose 2>&1 | grep gyp return this.
Solution from topic «npm install fails on node-gyp rebuild (using puppet)» don't help me: --unsafe-perm don't did the trick.

Ubuntu 14.04.1 LTS (GNU/Linux 4.5.0-x86_64-linode65 x86_64)
$ node -v
v6.0.0

May you help me please?
Answer: Solution was to install via nvm v0.10.24


How do I find out the super projects of a git submodule?

Question: After a changing in a git submodule a manual searching is necessary to find out the main projects that track it. So, is there any way to know which remote super repos it is linked?
Comment: No. A git repository has no awareness of any projects using it as a submodule.
Answer: No, there is no way.  The main repo save references to submodules on .submodules files, but the submodules has NO references to parent repo. So, there is no way


Multi-threading synchronization using wide scope lock with WCF callbacks

Question: What I want to do is this--
I want to make a proxy call to a service and receive data on a separate thread through an asynchronous callback...the tricky part is that I want to make the foreground thread sleep until all of the data has been retrieved.
The reason I'm not using a synchronous method to do this, is because I'm creating an API for a WCF service that uses Paging and returns data in chunks.
I want my client to be able to use Paging, but I don't want to expose all of my Paging callbacks to my API...I want it to appear as though the API exposes a synchronous data retrieval method.
I've tried using a private static Semaphore (because it is thread agnostic,) that is accessible to the class methods and the callbacks, with a single unit capacity as a means to pause the execution.
First, I use a Semaphore.WaitOne() statement.
Then, I do a Proxy call in the foreground thread, and the service creates a thread that handles the data retrieval, and control is passed back to the client.
In the client, I immediately use a second Semaphore.WaitOne() statement.
This should pause the foreground thread execution, which it does.
Then, once the "Paging Completed" Callback is executed on a separate thread, I use Semaphore.Release()
But the foreground thread never traverses the second Semaphore statement, it stays locked and so the client freezes.
Any ideas what I am doing incorrectly, or is there another locking design that would be more effective?
Comment: We'll need to see your code, multithreading is difficult stuff (more so without anything to debug).
Comment: Is it at the first time when you run the routine that the freeze occurs or is this a subsequent run? Is the first Semaphore.WaitOne call just to reduce semaphore counter to 0?
Comment: @sixlettervariables:  My code is too immense (enterprise app) to show here to get a complete picture of the WCF interplay.  I was really trying to lay out a thought experiment to see if a better object was suited for the exercise.
Comment: @user377178:  You are correct.  To reduce the counter to 0.
Answer: If what you're trying to accomplish is having the foreground thread wait on data-gathering thread, you may want to consider using Tasks, which would allow you to easily accomplish what you've described here.
System.Threading.Tasks:
http://msdn.microsoft.com/en-us/library/dd235608.aspx
Some code:
<code>Task t = new Task(somethingToDo);
// Fire off the new task
t.Start();

// Wait for the task to finish...
t.Wait();

// Do something else...
</code>
Make sure to take a look at the details of t.Wait() in the documentation. There are some exceptions you will want to be ready for, in the event that your task fails.
Comment: Sounds good, remarkrm, I'll give it a shot.  In my research, I also found "EventWaitHandle", which looks pretty promising as well.  Thank you for your response.


Should (or even Can) I use epoxy to repair a previously PVA-glued load-bearing wood joint?

Question: I'm repairing damage on a wooden sleigh bed; specifically, to one of the two side pieces that support the Frame Slats (a.k.a. "the slats"!). It is the thin "edge" that is joined to the inside and bottom of each Long Rail (i.e. the bed's sides). I dunno if it has a name, but I'll refer to it as simply the Slat Support. The original join was regular "yellow" glue, supported by screws every 10.5".  Here's the non-broken left side (left and right being as seen from standing at the foot of the bed and looking towards the head) with a few slats supported on its Slat Support:

The damage is that on the right side (not shown in the above -- the position I was standing when I took the above shot), the Slat Support has separated from its Long Rail, at the Headboard end, to a length of about 24". Here is the break, held open by a ruler:

Given that this needs to bear a fair amount of load -- the Slat Support holds up the Frame Slats, the Frame Slats support the box spring, which supports the mattress, which supports the kid jumping up and down on it apparently!... -- can anyone recommend what glue I should use? As I say, the original join was regular "yellow" glue, but I'm wondering if should use epoxy for the repair.
I may also fill in the three affected screw holes and drill some new ones away from the damage. In addition, I intend to swap the left and right Long Rails so that the repair moves from being at the Headboard end and right side, to the Footboard end and left side.
But I think the glue is doing the most work here, so I want to make sure I get that part right.
Thanks!
Comment: I'd consider screwing a width of steel, or even angle iron to the bottom of the bed. Screws into both pieces of wood. If the glue has already failed, you are going to have a tough time making a stronger connection with a wood-failed glue-New Glue-failed glue-wood connection. A nice piece of steel covering the join and screwed to the two pieces should help a lot. If you go with the epoxy be sure to check the psi rating on the package. Get the strongest, even if it takes 24 hours to drive. I Find the 5 minute epoxies to be slightly better than hot glue.
Comment: Is it only the glue which has failed, or has the wood been torn apart in there where we can't see in the photo?
Comment: It's only the glue. The wood itself is substantially intact. The only exception is at the site of one of three affected support screws. You can see it at the top right of my second photo. But even there, the damage is to the *edge* of the rail, not to the glued surface, which is pretty much intact. (Incidentally: the reason the first screw, near the ruler in the shot, didn't create even more damage is because it sheared in half. So half of it is still in the rail. Hence me figuring I'll have to relocate at least _that_ supporting screw).
Comment: Is it possible to separate that lifted piece of wood from the other part? That would make the repair easier as it will involve removing the old glue, properly preparing the surfaces, and then using ordinary wood glue and clamps.
Comment: To be clear: "slat support" = part above the ruler; "rail" = part below, touching the carpet. So, if you mean can I separate the entire slat support from the entire rail, then no I don't think so. That was actually the first thing I tried. I loosened all the screws, expecting the slat support to just full off the rail, but it didn't. After a few hard tugs/taps I realized that the screws were only there in a supporting role. The main bond is glue. Or did you mean could I cut the slat support in two, separating the now-detached-from-the-rail portion from rest? Probably -- albeit scary :-)
Comment: I expect that someone with useful experience of fixing something similar will be along soon and be able to give a good answer. In the meantime, could you get photos of the part which isn't shown: "the right side (not shown in the above"? With a properly glued join, it is expected that the wood will fail before the glue.
Answer: I think you are over thinking this.
I made this exact same repair a month ago and I used wood glue, you could use construction adhesive. Sand both surfaces, and glue and clamp.
Add extra screws for strength, one every 8 inches ? .
No need to fill in counter sunk screw holes, with box spring/mattress in place that part of the frame in not seen.
Comment: "Overthinking" is my middle name.  I've proceeded just as you described. Of course I then had to decide *which* wood glue and so watched a few YouTube videos on the subject. I decided on TightBond III simply because when compared with the other two versions then other than shorter working time (which didn't matter in this case), and being double the price (but double $2.50 is still only an extra $2.50), it seemed superior in all other aspects. Thanks for the advice.


About rules in prolog . .

Question: In my program I have some rules like:
tellme(X) :- knows(X).
tellme(friends1(X)) :-  tellme(X).
tellme(friends2(X)) :-  tellme(X).
tellme(friends3(X)) :-  tellme(X).
.
.
.
tellme(friends25(X)) :- tellme(X).

Now this friends1, friends2, friends3 ..... are dependent on N which is a variable. Here, for example value of my N is 25. So is this possible to write a rule to generate these rules till N or do I have to manually write these rules for N times. Any suggestions or solutions are welcomed. Thank you very much for your attention.
Answer: You can generate any sort and amount of code in most modern Prolog environment using term expansion, with some help from the universal operator.  The following example works for SWI:
term_expansion(gen_tellme(N), Terms) :-
    findall((tellme(F) :- tellme(X)),
            (between(1, N, I), atom_concat(friend, I, Fi), F =.. [Fi, X]),
            Terms).

gen_tellme(25). % generates 25 copies of the tellme clause.

That said, embedding information into the predicate name, i.e., the friend number, is generally not a good design.  Why not rewrite the code using friend(N, X), where N is the number?
Comment: But it is giving me this error : ERROR: toplevel: Undefined procedure: gen_tellme/1 (DWIM could not correct goal)
Comment: @anilonwebs: You need to consult both predicates together in the same file.  The first define a term expansion rule and the second uses it.  "gen_tellme()" is expanded, it does not become a real predicate.  Don't try this from the prompt.  Put it in a file.
Comment: See first thing that the base case is missing i.e. the first rule in my question part. So I add that in a file. `tellme(X) :- knows(X).` , `knows(anil).` with your define rule. But when I make a query for `tellme(friends1(anil))` it gives me false result. I have wrote all code in a single file.
Comment: @anilowebs: It's a type: I wrote "friend" instead of "friends".
Answer: You may have some success with a binary functor friends(N,X) instead of one functor per N. You may want to change tellme and knows to take two arguments as well. (knows(X) has no immediate meaning to me, so I don't entirely get what you're after.)
If, for some reason, that's not what you want, you can make a new functor with something like (untested)
friends_functor(N, Functor) :-
    number(N),
    atom_concat(friend, N, Functor).

Then use asserta or assertz. I really don't see why you'd want to do this, though.

About rules in prolog . .


Knit to html will not execute b/c of error in line 70?

Question: I am trying to create a function that calculates for a numeric vector the difference between the observation and mean of the vector and apply it to an NHANES data frame. This is the suspected code giving an error:
library(NHANES)

deviation <- function(x)
  {sd(x) - mean(x)}

sapply(NHANES[1:6,], deviation)

And this is the error:
Quitting from lines 70-82
Error in var(if (is.vector(x) || is.factor(x)) x else as.double(x), na.rm = na.rm) :
  Calling var(x) on a factor x is defunct.
  Use something like 'all(duplicated(x)[-1L])' to test for a constant vector.
Calls: <Anonymous> ... eval -> eval -> sapply -> lapply -> FUN -> sd -> var
Execution halted

Anyone know what may be going on?
Answer: In the columns of NHANES there are factor columns which you can not apply arithmetic operations. That is the problem.
> str(NHANES[1:6,])
tibble [6 × 76] (S3: tbl_df/tbl/data.frame)
 $ ID              : int [1:6] 51624 51624 51624 51625 51630 51638
 $ SurveyYr        : Factor w/ 2 levels "2009_10","2011_12": 1 1 1 1 1 1
 $ Gender          : Factor w/ 2 levels "female","male": 2 2 2 2 1 2
 $ Age             : int [1:6] 34 34 34 4 49 9
 $ AgeDecade       : Factor w/ 8 levels " 0-9"," 10-19",..: 4 4 4 1 5 1
...

If you do sapply(NHANES[1:6, c(1,4)], deviation) for example, it works, since your are applying your function to numeric (actually to integer) data (ID and Age)


Use a TypeScript enum as an Angular template variable name with ngTemplateOutlet

Question: I have looked at questions like this one. But it doesn't quite answer my question. I want to bind the local variable name to the enum's value like in the following (heavily simplified) example:
In certain-state.component.ts:
export enum CertainState {
    VALID,
    INVALID
}

export class CertainStateComponent {
    // holder for the current state
    public state: CertainState;

    // store the actual enum in the instance of the class so that
    // it is available in the template
    public certainStates: typeof CertainState = CertainState;

    // below is the logic which sets the state
    ...
}

In certain-state.component.html:
<ng-container *ngTemplateOutlet="state_{{state}}"></ng-container>

// obviously this is invalid syntax but I want to demonstrate my intention
<ng-template #state_{{certainStates.VALID}}>VALID</ng-template>
<ng-template #state_{{certainStates.INVALID}}>INVALID</ng-template>

EDIT:
I think the solution is in the following answer: How to use a typescript enum value in an Angular2 ngSwitch statement. What do you guys think?
Answer: This is what CertainState enum really is:
(function (CertainState) {
    CertainState[CertainState["VALID"] = 0] = "VALID";
    CertainState[CertainState["INVALID"] = 1] = "INVALID";
})(CertainState = exports.CertainState || (exports.CertainState = {}));

It basically maps keys to indexes and vice versa.
So it should be typed like:
public state: number;
public certainStates: typeof CertainState = CertainState;

And if state name is supposed to be used, it can be looked up on enum:
<ng-container *ngTemplateOutlet="state_{{certainStates[state]}}"></ng-container>
<ng-template #state_{{certainStates[certainStates.VALID]}}>VALID</ng-template>

Or enum index can be used directly:
<ng-container *ngTemplateOutlet="state_{{state}}"></ng-container>
<ng-template #state_{{certainStates.VALID}}>VALID</ng-template>

Enums aren't the best choice for cases where a key may be used as a string, because they require extra lookup and don't allow strict typing. As explained here, plain object is generally a better choice for looser typing, and a namespace is good for stricter typing.
Answer: public certainStates: typeof CertainState = CertainState;

should be
public certainStates: any = CertainState;

or
public certainStates: {[s: number]: string } = CertainState;

Comment: Your solution throws "Type 'typeof CertainState' is not assignable to type 'CertainState'."
Comment: I updated my answer. See also https://stackoverflow.com/a/30785209/217408
Comment: Why so? `typeof CertainState` is valid type and should work as expected.
Comment: Seems to be passed as object, not as type in an assignment.


1.13 - Checking if player holds item with specific name

Question: Let's say that I want to teleport a player who doesn't hold a name tag called "abc" to X Y Z.
All I could come up with was [/data get entity @p SelectedItem.tag.display.Name] and I'm stuck here because I don't know how to compare such data (that is, if it's possible).
Comment: @Joachim For future reference, please don't try to use HTML tags unless necessary; markdown's way of new lines is a couple spaces.
Comment: @Frank Ah, okay, np. Why is that? For how they get parsed on other websites?
Comment: @Joachim As far as I know, it's just markdown's way of doing things.  Educated guess says it's easier for database storage.
Answer: you would definitely want to work with the /execute command. i myself am having issues working this out considering the weird text formatting they have since converting things that normally would be simple strings into JSON with 1.13, but the gist of it is this;
execute if entity @a[nbt={SelectedItem:{id:"<id>",display{Name:<a bunch of JSON formatting, size varies based on the item you want}}] run tp @a X Y Z


how to get first 100 prime numbers in python with no duplicate value?

Question: I am trying to get first 100 prime numbers using python, for that I have created a function and given one parameter to that function, I have tried below code,
<code># WAP to fund first 100 prime numbers
def getprimes(x):
primes = []

for a in range(1,10000):
    for b in range(2,a):
        if(a%b==0):
            break
        else:
            primes.append(a)
        if len(primes) == x:
            return primes

getprimes(100)  #function call
</code>
here I am getting first 100 prime numbers but with duplicate value, I want unique values, how can I do that?
Comment: Reduce your testset, from 10000 to e.g. 10. Further, learn how to step through your code with a debugger. You could then immediately determine when your code doesn't do what you'd expect it to do.
Comment: For *every combination of a and b* you are adding `a` to `primes` unless `b` divides `a`. That's not what you want to do.
Comment: E.g. `8` is not a prime, but when `b` is `3` `if(a%b==0)` is false, and so you execute `primes.append()`. Try to think of ways to alter the code to only record `a` as a prime if **all** values for `b` can't divide it.
Answer: Try this -
<code>def getprimes(x):
    primes = []

    for a in range(1,10000):
        isPrime = True
        for b in range(2,a):
            if(a%b==0):
                isPrime = False
        if isPrime:
            primes.append(a)

        if len(primes) == x:
            return primes

print(getprimes(100))
</code>
I think the problem was you were recording a prime every time you found a valid factor instead of just one for each prime.
Comment: just a little modification required here, the program says 1 is a prime number and it is not, so I just made the change in condition here, if(isPrime and a!=1).
Comment: [Formatting help](https://stackoverflow.com/help/formatting) ... [more Formatting](https://stackoverflow.com/editing-help) ... [Formatting sandbox](https://meta.stackexchange.com/questions/3122/formatting-sandbox)
Comment: Thanks for the help with the commenting @wwii - I was struggling as no matter what I did with the wysiwyg editor it would push either the first or last line of code out of the code block.


Is there an equivalent to PHP's `__FUNCTION__` in JavaScript?

Question: I'm looking for an equivalent to PHP's __FUNCTION__ in JavaScript, to allow me to get the name of the current function. For example:
function foo(){
    console.log(__FUNCTION__); // "foo" would be logged to the console
}

Is there a way to do this in JavaScript? Either with a magic variable similar to __FUNCTION__ or any other workaround? And, if there's not a way to currently achieve this, is it planned?
Comment: A workaround could be `arguments.callee.name`
Comment: @mori57 An example could be for the function to modify itself (as a property of an object), i.e. you need to run a test many times that takes a lot of computation, but after you've done it once you know the answer won't change so you want to short-cut to the result.
Comment: What @Bergi says sounds like the solution. With the limitation that [`Warning: The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/callee) - but I guess that has implications only if your code opts in to strict mode.
Comment: Another question might be why you need to know the name of the function? Depending on scope, the function name may be registered with the window object, it may be stuck inside a closure ... I'm just curious what use-case would require the name of the function in the first place to operate correctly? (I realize that there may **be** use-cases, I'm just curious if there might be another way of approaching your problem with a little more context.)
Comment: @mori57 It's for a tokenizer (where the state === function name). Specifically, to force the tokenizer to set the state to the current function in cases where it was changed (instead of having to store another variable). I ended up finding a different way of doing things, but I'm really curious to see if there's a way to achieve this for future purposes as well.
Comment: you'd be surprised how hard it is to google this.
Answer: You might get a reference to the currently executing function via the callee property of the arguments object. Notice that it is deprecated with ES5.1 strict mode.
From that, you can get the (non-standard) name of the function. Notice that this only works for function declarations and named function expressions (with the known bugs in IE), but not for anonymous functions as object properties:
var myObj = {
    method: function() { // unnamed!
        return arguments.callee.name || "anonymous";
    }
};
myObj.method(); // "anonymous"

I for myself use static strings in debugging / error statements, prepending the whole namespace(s) of the function to easily locate it in the code.