Problem in query (PHP MYSQL UTF-8 )

Question: After reading the many tips here and elsewhere, I think I have finally made my GET query, PHP and MYSQL all talk utf8.  However, I cannot get a simple query to work where the string I'm matching contains non-ascii characters.  My (simplified) code is:
$link = mysql_connect("h", "u", "p") or die(mysql_error());
mysql_select_db("db", $link) or die(mysql_error($link));
mysql_set_charset("utf8", $link); //connection charset
$name = mysql_real_escape_string($_GET['first'], $link);
$query = sprintf("SELECT name, date FROM guestbook WHERE name='%s'", $name);
$result = mysql_query($query, $link) or die(mysql_error());
if (mysql_num_rows($result) == 0) {
...
}

If 'first' is ascii, then the query works, if it contains accented characters it does not.  When I print out the db (in an table generated by php) it looks just fine, as does viewing in it phpadmin.
What am I doing wrong?  Do I need to tell the '=' operator to use utf8?  Why?
Thanks
abo
Comment: Just because it looks fine, doesn't mean it's fine. What's the collation of the column `name`?
Answer: What's the character set of the table itself ?
Also, try running the following query just after connection:
SET NAMES UTF8;

Comment: It's not necessary because he uses mysql_set_charset.
Comment: So far as I can tell, everything is utf8. (What's the best way to verify this? Is there a query I can run?). Also the `mysql_set_charset` should do the `SET NAMES UTF8` step.
Comment: `CREATE TABLE `guestbook` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(20) NOT NULL DEFAULT '',
 `nname` varchar(20) NOT NULL DEFAULT '',
 `comments` text NOT NULL,
 `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=91 DEFAULT CHARSET=utf8 COMMENT='simple test table'`
Comment: Are you sure you are sending data as utf8 to the PHP script ? (e.g. did you added a `Content-Type: text/html; charset=utf-8` header or the equivalent meta tag ?)
Comment: Well, if I recall well if your tables used to be latin1 (for example) if you change the table collation to UTF-8, the columns that already exist do not change their collation, it only works for new columns. I think when you set the charset to the MySQL connection, it should take care of this (expect utf8 and internally search in latin1) but it worth trying to create a new clean table UTF8/utf8_general_ci (not utf8_bin), insert few rows and look them up to see if its fine.
Comment: Yes, I'm pretty sure.  I have also done a `mb_check_encoding($name, "UTF-8")` which reported `1`.
Comment: Veseliq - the table has always been utf8.
Comment: do a `select name from guestbook` from a trusted client; e.g. an utf-8 terminal, mysql client, "set names utf8", run the query.
Answer: Have you tried encoding the name as UTF-8 before the query?
$query = sprintf("SELECT name, date FROM guestbook WHERE name='%s'", utf8_encode($name));

If that doesn't do the trick, try utf8_decode. It sounds weird but I had weird cases where it did the trick.
Comment: No, that didn't help (either version)

Problem in query (PHP MYSQL UTF-8 )


Applying jQuery toggle function to each table

Question: I have three html tables on a webpage that are generated using a tornado framework.  When a user clicks on a table, I would like all rows of this table to toggle hidden / shown, except for the first and last rows of this table.  I am trying to use jQuery's each and toggle to accomplish this.
Fiddle here: https://jsfiddle.net/kauk975e/
$(".hidesomerows").each(function() {
  $(function(){
    $(function() {
      $('table').click(function() {
        console.log('click registered');
        $(this).parent().find("tr").not(":last").not(":first").toggle();
        console.log('why you no work?');
      });
    });
  });
});

When I click on the first table, it prints my two debug message to the console once for each table displayed, but doesn't hide the rows.  Nothing happens when I click on the second or third table.  What am I missing??
Answer: You don't need to use .parent(), as event handler is attached with TABLE element. the current element context this will refer it. So directly use .find() to target the TRs
$('table.hidesomerows').click(function() {
  $(this).find("tr").not(":last").not(":first").toggle();
});

$('table.hidesomerows').click(function() {
  $(this).find("tr").not(":last").not(":first").toggle();
});

      foo
      bar
      x
      y

       alpha
       alpha
      -20.0
      20.0

      beta
      beta
      124.390625
      -20.0

      gamma
      gamma
      124.390625
      -20.0

      total

       0
       -20

      foo
      bar
      x
      y

       alpha
       alpha
      -20.0
      20.0

      beta
      beta
      124.390625
      -20.0

      gamma
      gamma
      124.390625
      -20.0

      total

       0
       -20

      foo
      bar
      x
      y

       alpha
       alpha
      -20.0
      20.0

      beta
      beta
      124.390625
      -20.0

      gamma
      gamma
      124.390625
      -20.0

      total

       0
       -20

Comment: This worked.  Thank you!  Will select after the 8 min mark


Vue modify v-data-table column item templates in the parent component

Question: I'm using Vuetify and made a component including a v-data-table. How could I change the table column templates in the parent component?
Child component example:
<template>
  <v-card>
    <v-data-table :items="items" :headers="headers">

    </v-data-table>
  </v-card>
</template>

Parent component:
The item.id is just an example, I need a common solution for any kind of object field.
<template>
  <ChildComponent :items="items" :headers="headers">
    <template v-slot:item.id="{ item }">
      <v-chip> {{ item.id }} </v-chip>
    </template>
  </ChildComponent>
</template>

I guess I need dynamic slots but not really know how to use them in this case.
Comment: I think you're looking to create component [slots](https://vuejs.org/v2/guide/components-slots.html), specifically of the [named variety](https://vuejs.org/v2/guide/components-slots.html#Named-Slots).
Answer: Need to modify the ChildComponent on the following way:
<template>
  <v-card>
    <v-data-table :items="items" :headers="headers">
      <template
        v-for="header in headers"
        v-slot:[`item.${header.value}`]="{ item }"
      >
        <slot :name="[`item.${header.value}`]" :item="item">
          {{ getVal(item, header.value) }}
        </slot>
      </template>
    </v-data-table>
  </v-card>
</template>

The getVal method is for the nested item fields. Without it you can't use paths like item.author.name.
Answer: Try to create a scoped slot in the child component with item.id as name and pass item as scoped value :
   <v-data-table :items="items" :headers="headers">
       <template v-slot:item.id="{ item }">
         <slot :name="item.id" :item="item"></slot>
       </template>
    </v-data-table>

Comment: I need a common solution, the `id` field is just an example. When I iterate over the header values with `` that works, the only problem that every column template will be overriden instead of only one.
Comment: please update your question with these details in readable format
Comment: Found and posted the solution, it was a bit tricky.


Why do my gnomes not use wheelbarrows?

Question: I have about 15 Wheelbarrows in my Kingdom, yet my gnomes barely use them.
Is there a (hidden?) minimum skill requirement or anything? How can I make my Hauler Gnomes use more Wheelbarrows?
Comment: I'd love to answer this, but I could never figure this game out.  Sorry.
Comment: @MichaelDunfield I thought the same thing after seeing the title.
Answer: The wheelbarrow is still a bit bugged. Sometimes your gnomes keep loading by hand while there is a wheelbarrow available all the time. Suddenly they start to use it a couple of hauls only to return to hauling by foot again after a couple of runs. Here are some sources that describe your problem and others with the current wheelbarrow system:
http://forums.gnomoria.com/index.php?topic=5111.0
http://www.reddit.com/r/gnomoria/comments/1jgyog/wheelbarrow_weirdness/
Answer: Given the date of the question you should have the latest wheelbarrow fixes. They were introduced in 0.8.48 and received multiple fixes afterwards with the most recent one in 0.8.50.
You could search for wheelbarrow in the changelog to get more details on what work has been done on them.

Why do my gnomes not use wheelbarrows?


Will my parachute fail if I'm going too fast when I deploy it?

Question: I was going to put a whole back-story for this question here, but thought it'd be better as a Google+ post instead, for reasons that should be obvious to anyone who reads it.
So, during high velocity returns, is there a chance that a parachute will fail if the capsule is travelling too fast when it's deployed?  If so, what's the optimal speed/altitude range for deployment?
If speed is not the cause of these failures, what is, and how can I mitigate it?
I should also say that I'm using Mechanical Jeb.  For reasons explained in this question, I now always bring the MechJeb unit back with me.  In the case of the most recent failure, the MechJeb unit was positioned between the capsule and the parachute, something that had worked for me before.  But for my rendezvous mission, I used one of the radial mount options, keeping the (proper sized) parachute connected to the top of the capsule.
Comment: Possibly related: http://kerbalspaceprogram.com/forum/showthread.php/19914-Structural-failure-on-linkage-between-parachute-and-command-pod
Comment: @MBraedley Have you looked at the flight log after impact?  It won't (usually) tell you what *caused* a failure, but it should tell you where the failure is occurring, which might give some insight into your issue?
Comment: indeed, you should get something along the lines of "Structural failure on linkage between Mk16 Parachute and Mk1-2 Command Pod"
Comment: @pixel: Hmm, there is some useful information there that makes me think of another possibility. I've updated the question.
Comment: in one of my ships everything below the command pod breaks away.. which is fine by me as I don't need a separator.
Answer: TLDR: Yes, you will lose chutes from version 1.0.1
Kerbal Space Program has an advanced physics engine and while the planets of the Kerbol system are different to the Sol system, the mechanics are similar:
In real life a re-entering spacecraft is hitting air at huge speeds and that is heating the vessel. The chutes undergo huge stresses when deployed - both from aerodynamic pressure and heating. If these stresses are too great, the parachutes could simply tear off.
Version 1.0.1 of KSP brings this real life danger into the Kerbal universe. Now, if you're moving too fast when the chutes deploy, they can be "burned up". Or, even if you're not undergoing heating, the chutes can be destroyed due to aerodynamic pressures.
How can I avoid chute loss?
Not losing parachutes from heating is easy: Don't deploy them when your vessel is burning up. You can tell if the vessel is burning up by looking at it - is it on fire? Don't deploy chutes.
Not losing parachutes from aerodynamic stresses is also easy: Don't deploy (even partially) when you're going fast. How fast is "fast"? I've conducted some tests and it looks like 1000m/s is the magic number. Although it may change depending on atmospheric conditions.
Edit: After version 1.1 chutes can be destroyed going slower than 1000m/s. Look at the chute icon in the staging, it changes colour based on whether it's safe to deploy or not.
Comment: Thank you for posting this answer two years ago. But now with version 1.0 and the new aerodynamic system it seems to be quite outdated. Maybe you would like to revise it? I put a bounty of 50 points on this question.
Comment: Good edit to keep the answer actual.
Answer: The rule of meassure I use is to only deploy the parachute when below the speed of sound (330 m/sec). I tend to wait until 250 m/sec, but I've never had a parachtute ripped off when under 330 m/sec.
The parachute doesn't do much anyway until you hit 500-1500m (Kerbin) altitude (most videos on Youtube show 500m, I'm playing 0.19.1 and it's usually roughly 1350m for me.). If at that point you're still going faster than 330 m/sec; may Kerbal God have mercy on your poor Kerbals' souls...
Edit: I do not use MechJeb, so I have no idea of its weight. The figures above are for a pod (doesn't matter how many Kerbals) and a parachute. If it's heavier, I'd scale those numbers accordingly.
Comment: parachutes will start stabilising the flight path as soon as deployed AFAIK as drogue chutes, but won't fully open until 500m above ground level (which can be a ways up if you're landing in a mountain region).
Comment: Yep, but if you're still going too fast when deploying, it'll be ripped off. I haven't landed on a celestial body with an atmosphere other than Kerbin, so I'm not sure if variations in atmosphere (pressure, density, ...) will have an effect on those numbers.
Comment: +1 To jwenting regarding altitude. KSP's built-in altimeter shows ASL (above sea level - or, more precisely, above *mean* sea level) only. Parachute deployment happens based on AGL (above ground level) altitude except when over water (when "ground level" is effectively below sea level). I highly recommend getting MechJeb, which will help to show you the difference and makes a whole lot of other useful information and tools available.
Comment: Thank you for posting this answer two years ago. But now with version 1.0 and the new aerodynamic system it seems to be quite outdated. Maybe you would like to revise it? I put a bounty of 50 points on this question.
Comment: I've been anxious to play 1.0 (haven't had the chance), But I heard the latest update has made the lower atmosphere excessively soupy again. Might be some time, as I'd expect another patch to correct it in the near future. Generally speaking though, a dropping pod will be slowed down enough so you can deploy the parachute safely when close to the ground. There are currently some speed races towards the island off the coast that have people used parachutes as brakes at insane speeds, and they still don't rip off (plenty of them can be seen on http://www.reddit.com/r/kerbalspaceprogram )
Answer: Right clicking on the 'chute during flight it tells you if it is safe to deploy or not.
Answer: In 1.0.5 up, the chute symbols in the staging turn different colors depending on speed and the state of the chute. When you are going around 273 m/s, it is about the perfect time to deploy the chutes, and the symbol will look normal. Once deployed, the chute icon will turn yellow, and then once fully deployed will turn green. If you cut the chute, it will turn red. Hope this helps!


Can I use a 30 amp generator to power some parts of a 60 amp subpanel

Question: My main panel is in my basement and it has a 60 amp breaker that goes to a sub panel in my pole barn. The pole barn sub panel provides power for the pumps and blower motor of my outdoor woodstove.  Last winter I lost power for a week and had to run two extension cords from my 30 amp generator; one to the main panel in my basement to power the furnace and the other to the sub panel in the pole barn to power the woodstove.
I want to get a hookup for my generator so that I don't need all that sassafras if I ever lose power in the winter again.
While it would be easier to run the generator by the pole barn and backfeed the main panel, reading other questions makes me believe that is neither safe nor legal. So, I think I need to get a transfer switch or interlock kit setup on my main panel for the generator.  However, I still need to power the woodstove from the pole barn sub panel.
My question is, can I use a 30 amp generator connected to my main panel to power the 60 amp sub panel in my pole barn?  The only thing I want to power in the pole barn is the woodstove, which is on a 20 amp breaker in that sub panel.
References:
Is it reasonable to create a 30amp branch circuit for the purpose of feeding the panel from a generator?
Can I connect a portable generator to a subpanel to backfeed my house?
Answer: Yes, if you make sure to shut down enough things (if not, you'll trip breakers, so you are still good, from the safe and effective front.) I have a 40 amp manual generator interlock installed in a 200 amp panel. I neither need nor want a generator big enough to run everything at once, or automatic switching. I do want (and I have) the ability to power any one thing (or combination of things) that the generator can safely supply, without having to fool around with hack rewiring jobs under poor conditions or absurd extension cord tricks. That panel will eventually have a 100 amp feed to another building, and the generator input will be able to feed it (so long as the actual draw over there is controlled to be below the generator output, of course.)
Exactly what your options are will depend on exactly what your panels are, and what the panel maker has for approved interlock devices, but generically, it is possible. The legal and important safety end of "safe and legal" is having the interlock so you absolutely, positively, cannot backfeed power to the grid. The overcurrent part of safe will be taken care of by the generator output breaker and/or the panel input breaker for the interlock. Obviously the 60 amp breaker will be highly unlikely to trip if a 30 amp generator is feeding it - but if you draw 40 amps for some reason, the generator breaker will trip. The 60 amp rated wiring will of course be just fine with 30 or less amps running on it.
Answer: Having a panel that's rated for more amps than you're going to put through it isn't a problem. (Trying to put power through something that's rated for fewer amps is a big problem.)
For the rest, that's outside my expertise.
Comment: Generator salespeople do love to sell autostart generators and transfer panels where you have to pick all the loads to be powered by the generator in advance, and the generator has to be oversized so that it can run them all if blindly auto-started. There is no loss of safety (but a considerable  reduction in salespeople commissions and your costs) in using a simple interlock, if you are fine with having a power outage for a while, and manually controlling the loads while you are having a power outage so that you can use a smaller generator and not run everything at the same time.
Comment: Nothing unsafe nor illegal has been proposed. An unsafe and illegal method others have proposed in the past has been specifically discarded in advance and removed from consideration. The second part of your answer seems to be based on vague and baseless fears.
Comment: OK, edited to just make the statement. I absolutely admit to vague fears in this setup, baseless or not, despite being pretty comfortable with house wiring. I know my limits.
Comment: @Ecnerwal: True enough. Electrically, as long as the generator and the line are physically prevented from ever being connected to the house simultaneously, and you don't overload circuits or the generator, and either the generator's putting out true sine or none of your electronics will object to the higher frequencies, the system should work.  I'd still consider the interlock to be something a pro -- or at least someone who doesn't have to ask questions about it on the Web -- should handle installing, so I really am not comfortable going beyond that point.
Comment: While all three answers are applicable, this answer was first.
Answer: An interlock kit would certainly work, and be safe and legal. What's nice about them is that you can choose what is going to run before you connect the generator. Also, in cases like yours you can alternate loads so that you can run critical and non-critical loads, albeit not at the same time.
You CANNOT, as you already know, connect a generator to a sub-panel and backfeed a main panel.
Answer: Sure, feeding the generator into the main panel is no problem. You can install a proper interlock into the main panel (assuming that is possible), and that will automagically power the subpanel.   You won't have to do anything special. It will just happen.
After you install the interlocked generator breaker, run that out to an inlet.  Now if you don't want to pay $70 for an inlet, a poor man's inlet is simply 1 foot of cord coming out of a junction box with good and proper strain reliefs on the cord. Location should be chosen carefully to keep the cord out of the mud, snow and other threats.
Now, with a 30A generator I don't know whether it is a 120V generator or a 240V generator.  If it's only 120V, then you'll need to do some careful planning to make sure all your critical circuits are on the same pole of power.
-
As far as your problem of wanting the generator to be at the shed, there is no easy answer for that.  There is no legal way to have "2-way traffic" on a single feeder.  Because you would need to interlock the main breaker and the generator breaker, so what will you have? A 100 foot long Bowden cable? LOL Not gonna work.
Unfortunately the only advice I can give you is to run a second parallel feeder cable.  There's no better answer.  What you can do, though, is make sure it is aluminum to save a ton of money.  (or alternately recycle the original feeder to be the generator line, and make the feeder the aluminum.  6 AWG aluminum is good for 50A, or 2 AWG aluminum is 90A and large enough that even the most superstitious cities recognize that it is safe.


Recursive fractal square in wrong area

Question: I am writing code for a fractal square. I have the function to draw the square, and this what I get: click here
but this is what I am trying to achieve: click here.
I think my problem is not placing my coordinates correctly but I might be entirely wrong. Here is my code:
#setting up stuff Code by Angel M. Gonzalez
import turtle
window = turtle.Screen()
square = turtle.Pen()
square.speed(0)
square.penup()
square.goto(0,0)
square.pendown()
square.color("black", "red")

#defining my function to make what i want

def pattern(length, depth, x, y):
    square.goto(0,0)
    if depth > 1:
        square.begin_fill()
        square.forward(length)
        square.left(90)
        square.forward(length)
        square.left(90)
        square.forward(length)
        square.left(90)
        square.forward(length)
        square.end_fill()

        pattern(length/2.2, depth -1, 1,1)
        pattern(length/4.4, depth -1, 1.5,1.5)

#run my function
pattern(300, 4, 0,0)

#exit
turtle.exitonclick()

Like I said before, I don't know if the coordinates are being placed incorrectly here, or if I am completely missing something. I would say my function for the original square is fine.
Answer: Your approach to recursion is all wrong.  You can't use absolute positioning in your recursion:
square.goto(0,0)
...
pattern(length/4.4, depth -1, 1.5,1.5)

Everything has to be relative to where you are.  Also, to make a recursive drawing like this work, your recursive function should leave the turtle in the same state (position and heading) as it was when you entered the recursive function, so the caller knows where it stands.
For this design, you can't simply draw a square and then recurse, you need to be recursing at each corner of the square as you're drawing.
As a simpler, initial exercise, let's just draw the lines of this shape and ignore the fill.  This may not lead directly to a solution but will demonstrate the above principals:
from turtle import Turtle, Screen

def pattern(length, depth):

    if depth < 1:
        return

    # assume we're at the center of square, move to corner
    turtle.penup()
    turtle.backward(length / 2)
    turtle.left(90)
    turtle.backward(length / 2)
    turtle.right(90)
    turtle.pendown()

    for _ in range(4):
        pattern(length / 2.2, depth - 1)  # recurse at each corner
        turtle.forward(length)
        turtle.left(90)

    # return to center of square for the benefit of caller
    turtle.penup()
    turtle.forward(length / 2)
    turtle.left(90)
    turtle.forward(length / 2)
    turtle.right(90)
    turtle.pendown()

screen = Screen()
turtle = Turtle()
turtle.speed('fastest')

pattern(100, 4)

turtle.hideturtle()
screen.exitonclick()

OUTPUT

Now comes the problem of both filling these squares and making sure the upper right square in the pattern is always "tucked under".

Recursive fractal square in wrong area


Why Swift optional become zero?

Question: This is my custom Demo class:
class Demo: NSObject, NSCoding {
    var id: Int?

    override init() {
        super.init()
    }
    required init?(coder aDecoder: NSCoder) {
        self.id = aDecoder.decodeIntegerForKey("ID")
    }

    func encodeWithCoder(aCoder: NSCoder) {
        if let id = self.id{
            aCoder.encodeInteger(id, forKey: "ID")
        }

    }
}

Save I have create a object and save into NSUserDefaults like this:
let demo = Demo()
let archiveData = NSKeyedArchiver.archivedDataWithRootObject(demo)
        NSUserDefaults.standardUserDefaults().setObject(archiveData, forKey: "ff")

Debug result shows that it works good

Now I have picked the object from NSUserDefaults like this:
let retainData = NSUserDefaults.standardUserDefaults().objectForKey("ff") as! NSData
let retainDemo = NSKeyedUnarchiver.unarchiveObjectWithData(retainData) as! Demo

Now after debugging I have found:

Now check the difference between the two result. Previous one id value nil after pick the object from then the id value become zero. I have not made any change of the object. Just save into NSUserdefaults and pick reversely. What the reason behind this? How do I overcome the problem?
Answer: The reason is that decodeIntegerForKey does not return an optional Int. It returns an Int. So if ID is not present then it returns 0 which is usually the default value of a Int variable. You can fix this by checking the decoder has the ID object.
required init?(coder aDecoder: NSCoder) {
    if aDecoder.containsValueForKey("ID") {
        self.id = aDecoder.decodeIntegerForKey("ID")
    }
}

Why Swift optional become zero?


What do I need for a small drain in a basement sauna floor with poured concrete?

Question: I am installing a drain in a basement sauna. I am pouring 4 inches of concrete over an existing concrete floor. I need to fit the drain and pipe in that 4 inches. The drain will not be subject to a high flow like a shower, and will not be tied directly into the sewer. The drain will be about 3 feet or so from the output and I know it will need space to slope towards the outlet.
What exactly do I need to buy for the drain and pipe? Can I fit that in 4 inches of concrete? How do you pour concrete in around it?
Comment: what's  the outlet?
Comment: TBD but likely some sort of hose that gets pumped into a utility sink.
Answer: You will need a side outlet drain.
The dimensions is less than 3 inches high, so you have room to shim under the drain to get the 1/4" / foot slope that is recommended.
You did not state what the drain will terminate into, so you may or may not need a trap.
With the PVC pipe glued in place, add what shims are needed under the drain and tape the pipe in place to hold the unit while you pour the concrete. No need to anchor with screws or bolts.  Pour the concrete around the drain first and work out toward your forms and the drain will stay in place.


Pandas column replace $ and letter from rows

Question: I have a column with currency values. All have a leading '$' and some have a trailing F. Trying to remove the charcters using replace with pandas.
My data is:
$4.00F
$21.00
$6.00
$6.00
$5.50
$13.00
$4.60F

This is my code using replace. However, it removes no characters at all.
df["Price"].replace("^/$$[F]", "", regex=True)

Where is my regex incorrect?
Comment: You could use `.lstrip('$')` and `.rstrip('F')`, if it is possible to do so.
Answer: The ^/$$[F] pattern matches a string that starts with /, then makes sure the string ends right after / (twice) and then the regex engine searches for F (after the end of string). As you see, the pattern has no sense.
You can use
df["Price"] = df["Price"].str.replace(r"^\$|F$", "", regex=True)

This will remove a $ at the start and F at the end.
See the regex demo.
If you do not care where the $ and F are, you may use
df["Price"] = df["Price"].str.replace(r"[$F]+", "", regex=True)

See this regex demo where [$F]+ matches one or more F or $ chars.
Also, consider the classic pattern removing any chars other than digits and dots:
df["Price"] = df["Price"].str.replace(r"[^0-9.]+", "", regex=True)

See this regex demo.
Answer: In this instance you can simply avoid any regex and use .strip('$F'):
df['Price'] = df['Price'].str.strip('$F')

Answer: If you want to remove any character (not just '$' and 'F') that is not a number at the start and the end of your string:
>>> df['Price'].str.replace(r'^[^\d+]|[^\d+]$', '', regex=True)
0     4.00
1    21.00
2     6.00
3     6.00
4     5.50
5    13.00
6     4.60
Name: Price, dtype: object


How can I change an elements color when clicked a second time?

Question: I'm working on a like button for a website I'm making and I have a simple piece of JavaScript that changes the color to red when it is clicked, but how can I make the color alternate so if you click it again it goes back to black than changes to red again if you click it another time etc.

const btn = document.getElementById("like");

btn.addEventListener('click', function onClick() {
    btn.style.color = 'crimson';
});
Comment: `btn.style.color = btn.style.color == 'crimson' ? 'black' : 'crimson';`
Comment: Okay thank you for informing me so I know for next time. Also sorry I @ you I didn't realize at first you were the person I mentioned haha.
Comment: It's also worth noting that Johnny's suggestion may not work, since colours are often returned in `rgb()` format, regardless of the way in which they were set.
Comment: Thank you very much for your help. Would you mind posting this as an answer so I can mark it as solved?
Comment: @JohnnyMopp Setting inline styles is really the last resort when styling is needed. Instead, CSS classes should be used.
Comment: So I really should do what @ScottMarcus said?
Comment: Yes. Working with any inline code is discouraged as it makes the HTML more complicated, leads to duplication of code, makes it hard to override, and doesn't scale well.
Answer: Use the toggle method of the classList.
And, as a general rule, you should strive to avoid setting an "inline style" (element.style.xxx = xxx) as this creates a style for the element that can only be overridden by another inline style, leads to duplication of code, and therefore code that doesn't scale well. Instead, always try to work with  CSS classes.

document.getElementById("like").addEventListener('click', function() {
    this.classList.toggle("active");
});
.active { color:crimson; }
<button id="like">Like</button>
Comment: Of course. Thanks again.
Answer: you can follow this steps
First let's take a counter variable
let clickCount = 0;

Then add click event.Hare is your code:

const btn = document.getElementById("like");

            let clickCount = 0;
            btn.addEventListener("click", () => {
                clickCount++;

                if (clickCount > 1) {
                    btn.style.color = "red";
                }
            });
<button id="like">Like</button>
Comment: With this code, you have to press the button twice to get it to change color (because your `if` condition uses `>`, rather than `>=`. Also, once the color turns to red, it stays that way for all subsequent clicks, which is not what the OP is asking for. Really, there is no reason to write out this logic in the first place when `.classList.toggle()` exists.


Semantic web - sparql query

Question: I'v tried this query, it compiled and run. but it retrieve just the column names without their values. how can I retrieve their values ? is there any special method for that ?
String str = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>"+
    "PREFIX dbo: <http://dbpedia.org/ontology/>"+
    "PREFIX dbpprop: <http://dbpedia.org/property/>"+
    "PREFIX foaf: <http://xmlns.com/foaf/0.1/>"+
    "SELECT DISTINCT ?label ?abstract ?placeOfBirth"+
        "?birthPlace ?birthDate ?deathDate ?page ?thumbnail WHERE {"+
        "OPTIONAL {<http://dbpedia.org/resource/Neil_Simon> dbpprop:placeOfBirth ?placeOfBirth ; dbo:abstract ?abstract ; foaf:page ?page .}"+
        "OPTIONAL {<http://dbpedia.org/resource/Neil_Simon> dbpprop:placeOfBirth ?placeOfBirth ; dbpprop:birthPlace ?birthPlace ;}"+
        "OPTIONAL {<http://dbpedia.org/resource/Neil_Simon> dbpprop:placeOfBirth ?placeOfBirth ;  dbo:birthDate ?birthDate ;}"+
        "OPTIONAL {<http://dbpedia.org/resource/Neil_Simon> dbpprop:placeOfBirth ?placeOfBirth ;  dbo:deathdate ?deathDate ;}"+
        "OPTIONAL {<http://dbpedia.org/resource/Neil_Simon> dbpprop:placeOfBirth ?placeOfBirth ; dbo:thumbnail ?thumbnail .}"+
        "FILTER (LANG(?label) = 'en')"+
        "FILTER (LANG(?abstract) = 'en')}"+
    "LIMIT 1";

Comment: Note: There is no whitespace in your string between `?placeOfBirth` and `?birthPlace`
Comment: please, mark RobV's answer as correct (green tick), if it was helpful
Answer: If you get column names and no values then it likely means that there are no answers to your query.
Try removing parts of your query until you get an answer - the main parts to start with would be the FILTER clauses. You are filtering on variables that don't actually get bound in your query anywhere so they will always evaluate to false and result in no results
Comment: Thank you very much, your answer was helpful.
Comment: If you found RobV's answer helpful, maybe you should mark the answer as correct.

Semantic web - sparql query


composer update on PROD server

Question: There's always been a note in many Readmes of composer-based projects:

Never run composer update on production server

However, there are times that we want to run composer update on PROD servers to keep current (of course after a thorough test on local server). What's the best way to do that?
Answer: You should run on local server.
composer update

Next you should test application and add composer.lock to repository. And on PROD server you should run
composer install

Answer: composer update is checking if there are any new versions of the packages available within the limits of the versions given. This will unconditionally install new packages if they are eligible. After that you have to test.
composer install will install whatever is mentioned in the lock file, and if the currently installed packages are not the ones mentioned there, they will get uninstalled or updated.
Of course you want to "update" the prod application. But to update the packages, you run composer install which will update the packages to the TESTED state in the lock file - not to an UNTESTED state because newer versions did appear after you tested.

composer update on PROD server


Solve arithmetic question using calculus

Question: Thomaskutty is starting a new business. he knows that most business when they start run at loss. Thomaskutty  predict that in the first month he will lose \$2200, in the second he will loose \$1800 and in the third he will lose $1400 and this pattern will continue with each passing month (like arithmetic sequence where a=-2200 and d=400). Given the cumulative (running) total profit after n months is given by S(n)=n/2 (2a+(n-1)d) use calculus to determine:
a) The last month Emma will incur a net loss
b) The amount of loss during that month (given tn=a+(n-1)d)
c) The maximum cumulative loss (minimum cumulative profit) that Emma will experience
My working for this is quite stupid in my opinion. I try to work out these question by using the arithmetic sequence formula when we are asked to use calculus. I am not sure where to start to use calculus to solve this
Here is my working out:
a) $tn+(n-1)d$
= -2200 + (7-1)*400 = 200
Thus during the seventh month it will be the start of the positive.
-2200 + (6-1)*400 = -200
In the sixth month it will be the last month of a loss.
b) the loss on the last month will be \$-200.
c)The maximum cumulative loss by Emma will be
n/2 (2a+(n-1)d)
6/2 (2(-2200)+(6-1)*400 = \$-7200 loss
Is my working out for the answer correct and if they are how can I use calculus to solve the questions?
Answer: Since we are using a calculus method, let's use the function $p(t)=-2400+400t$.
I start with $-2400$ because averaged over a month, adds up to only $-2200$ negative.
a. $p(t)=0$, which means $t=6$. So her last month of net loss is the sixth month (she stops losing money at $t \geq 6$, which is the start of the seventh month.
b. $\displaystyle \int_5^6p(t)\,dt=-200$, or a $\$200$ loss. You can reaffirm this with the arithmetic sequence
c. The maximum cumulative loss is at the point where she stops losing money further, or at $t=6$. This amount is $\displaystyle \int_0^6 p(t)\,dt=-7200$, or a $\$7200$ loss.
Comment: Your answers are all correct, and this is a way to use calculus. The only part that I think is important is to use -2400+400t, that way it averages out to -2200,-1800,-1400 during each month,.
Comment: can you show me how you got -2400? Like how do we average over a month to get -2400
Comment: at the beginning of the 1ST month, she is losing at a rate of -2400 per month, but at the end of the month, she is losing at a rate of 2000 per month. this is not a constant rate. so if we average it, she is losing -2200 over the whole month
Comment: since she is losing 2200 in the first month, that 2200 has to be p(0.5)
Comment: Can you please explain this a bit further. i am having trouble how you get the value -2400. it would be appreaciated if you could show the working
Comment: okay so let's say i make $\$1$ the first hour, $\$3$ the second hour, $\$5$ the third hour, etc. the expression will *not* actually be $1+2x$. Why? Because I need to make an average of $\$1$/hour during the first hour. If we use the expression $0+2x$, i'll be making $\$0$/hour at first, then $\$2$/hour at the end of the first hour, which means for the WHOLE hour, i'll make $\$1$/hour on average


Quadratic formula problem $(x+2)^2-(2x+3)^2=0 $

Question: Solve $(x+2)^2-(2x+3)^2=0 $ using the quadratic formula.
I have tried expanding the brackets in both and then simplifying but I get an equation that I can't then factorise.
Can I have a method please?
Comment: Welcome to the site.  What have you tried?
Comment: You can compute the squares to get an ordinary quadratic equation.
Comment: I have tried expanding the brackets in both and then simplifying but I get an equation that I can't then factorise
Comment: You have some problem with signs. Remember, $a-(b+c)=a-b-c.$ Check it and use the standard formula $x=\frac{-b\pm \sqrt{b^2-4ac}}{2a}$ to solve it.
Comment: What equation have you obtained?
Comment: I got 3x^2-16x-11=o
Comment: Why use the quadratic formula for this? The possibilities are simply that $x+2$ equals either $2x+3$ or $-(2x+3)$, and this gives the two solutions in a quicker way.
Answer: If you want to use the quadratic formula, at first you must solve the parentheses. The you would have $x^2+4x+4-4x^2-12x-9=0 \Leftrightarrow -3x^2-8x-5=0$.
Using the quadratic formula(link) you get next results:
$$x=\frac{8+\sqrt{8^2-4(3)(5)}}{-6}=-5/3$$
$$x=\frac{8-\sqrt{8^2-4(3)(5) })}{-6}=-1$$
You could also solve the problem imposing that $|x+2|=|2x+3|$, but except that you do it graphically, this process is too complicated.
Answer: Note that you do not have to use the quadratic formula, although it certainly is an option. I have no idea why Zero point says this method is "too complicated." Realize that the original equation is equivalent to $$ (x+2)^2 = (2x+3)^2, $$ which is true if $\left|x+2\right|=\left|2x+3\right|$, and can be split up into two cases.
If $ x + 2 = 2x + 3 $, we get $ x = -1 $ and the statement is true.
If $ x + 2 = - \left( 2x + 3 \right) $, we get $ x = - \frac {5}{3} $, in which case the statement is also true.
So we have found our two solutions $ x \in \left\{ -1, - \frac{5}{3} \right\} $. $\Box$


100amp Sub Panel for 75ft - Anything else I need?

Question: to save myself some costs for adding a sub panel, I'm buying the cabling, sub panel, breakers, etc. NIM for an electrician to finish all the connections.  I'm going to run the cables, etc.  I'm wanting to add a sub-panel in my Garage (on other side of house from main breaker).  Primary reason is we bought a hybrid, and the charger I got is wanting 50 amp breaker (https://www.costco.com/juicebox-pro-40-amp-electric-vehicle-charging-station-evse-with-juicenet%2c-24-ft-cable.product.100397573.html).  I then would like to be able to add a shed off the garage in the future to run power tools as needed, possibly a heater, and run new outlets for holiday lights etc on the exterior.
Some Details:

My main Panel is 200 AMP
My distance is roughly 75ft from main to sub (this is about 7ft of play)
I'm adding a 100AMP sub-panel with main cut off at root (e.g. https://www.lowes.com/pd/Square-D-Homeline-40-Circuit-100-Amp-Main-Breaker-Plug-On-Neutral-Load-Center-Value-Pack/50311143)
Based on my research, I believe I can go #3 or #2 AWG, and I need red,   black, white, and ground.  Which I believe is also considered #2/3 with Ground.
Planning on fishing wire on the interior

My questions are:

What if we buy another hybrid, would you feel another charging station could be added?  I feel this could happen, but not for a few years, but want to size right
Does #2/3 w ground mean that it will have red, black, white, and
ground?  In my research the pictures don't always match what I think is correct.

Any suggestions on where to buy that size cable for reasonable price? e.g. is this ok?  I'm assuming the color is really better (https://www.wireandcableyourway.com/industrial-cable/tray-cable-thhn-pvc/thhn-pvc-tray-cable-with-ground/2-3c-thhn-pvc-tray-cable-with-ground.html)

Thanks for any help, this site has been informative, and I tried to find matching questions, but then most people don't respond when asked for more details.
Let me know if I missed anything.
Editing to add (thanks to Harper):
I've already been talking with Master Electrician and he has worked with me in the past when replacing the 200 amp because when we moved in it was an old Stab-Lok panel that I wanted to get out of the house.  In addition, permits have been pulled, but I need to adjust because they were going to be for the 200 AMP replacement and a direct line to the charging station.  I since had two things happen, hired a "pro" (licensed/insured) contractor to remodel the basement and he promptly said he would, then ignored running the cabling before drywall was done.  I then decided if I'm going to cut the drywall back open to run the wiring, I'll just add a larger panel and connect the charging station off of that.
Comment: @EdBeal That's Square D for ya. Never miss an opportunity to charge half again as much as Eaton and Siemens.
Comment: Buy your wires ***LAST***.
Comment: Chargers are continuous loads so if you want to use 2 at 40 amp your new 100 amp sub will be at full load. Since you plan on a second one get a bigger panel. I would go with at least a 125 amp , probably no larger as the 150 hom breakers are ~100$ Or close I had to purchase one a couple months back I was shocked at the price.
Comment: But I don't usually use hom, I do use QO as they are 100% rated not like the cheaper brands, just saying have to have apples to apples , most of the cheap contractor brands stop at 100/125, so I complain about the hom price but your brand preference, I can't find what this OP really needs other than square D.
Answer: Big enough subpanel
That's a 20-space panel. The 40 number is baloney. I'm glad you're getting a good size panel though
However, that panel has HOM's super-cheap 100A busing, which forecloses any possibility of going 125A at another time.  A panel that size should have 150A+ busing, man, Homeline lives up to its name. Consider also CH, BR, or Siemens. I don't recommend QO because the breakers are too expensive.
You do not need a main breaker in the subpanel if the garage is attached to the house.  "I want it so it'll trip first and save me a walk" does not work at all.
Electrician to finish
There are three things electricians do not like.

Finishing a job an amateur started, because the quality of work is usually a disaster and that requires the painful "you gotta pay me to redo it" conversation.
Using parts supplied by the customer, because noobs usually buy the wrong stuff, again ditto.
Being associated in any way with ninja work for which permits have not been pulled. It is embarrassing and invites the customer to sue for not mentioning the consequences of ninja work.

And frankly, much of what you want the electrician for - the careful eye - is part of the permit and inspection process.
Conduit, however...
One way to save a lot of electrician time is to pre-lay EMT metal conduit Take the time to learn to do conduit properly; so it's tip top and waiting for wires.  Also have the exact conduit length pre-measured, and have a pulling rope already in the conduit.  Lay it between the main panel and the new subpanel, and I would buy and mount same before calling the pro.
Use conduit at least 1 size larger than what the conduit fill calculator says you need, because that eases the pull.  And have access points at least twice as often as Code requires, every 90 or at most 180 degrees.
If you lay conduit, expect to use individual wires such as XHHW.  There are so few choices here that you could buy this in advance.
Wires
The cable you linked is the wrong stuff. (What'd I just say? :)
The correct wire colors for this circuit are black, black, black, because they are larger than 6 AWG and distributors don't want to stock multi-color wires in large sizes.  The ground should be green or bare #6 Cu, or black #4 Al. The wires should then be marked colors with colored electrical tape.
The correct wire size is #1 AWG Al for 100A or 1/0 AWG Al for 125A.  Very few people recommend copper for 100A feeder, other than people on sales commission. Besides, the lugs are aluminum, and why create a dissimilar metal problem?  Anyway, aluminum is no threat; the threat is failing to set the torque correctly.  That'll cause problems on Cu and Al equally.
You want XHHW x3 + gnd in conduit, or SER cable if direct-lain.  That's the Al equivalent of your chosen Cu, giving 125A. 100A cable is cheaper.
I'm stuck on 125A because the #2 Cu wires you proposed are good for 125A. The cost diff is very small, but you'll need a better panel.
Buy 2' more length than you ever thought you'd need.  I did that with some 1000 kcmil Cu at $10/foot (Al wouldn't fit in the conduit!) I almost bought six 15' pieces, but buying 16.66' saved our bacon.
Buying electrical
Don't buy wire online.  Buy it at your local electrical supply house, and tell them you're sick of overpaying at Home Depot (which they'll believe, because they secret-shopper Home Depot all the time, mostly to snare away any competent clerks). Check 2-3 on price to avoid the one that'll stiff you.
Once someone protested "I'm in eastern Oregon, I have to mail order." Really? Where do your local electricians get supplies? Turns out there was a Platt within 10 miles.
As a general rule, it is useless and futile to use online resources to price electrical gear.  The stuff is very low price, high weight and awkward sizes, which works very much against mail order.  People buy locally. Online sellers know they're dealing with noobs or the desperate, and price accordingly, padding prices even more to make their shipping charges seem not unreasonable. Some are bricks-and-mortar electrical supplies who post the "I don't wanna box it up and ship it" price online.
You just have to go locally.  On the most commodity things like 12/2 Romex big-box will loss-leader But on everything else, a friendly electrical supply will trounce them, often shockingly.  Price 4-11/16" square boxes at electrical supply vs big-box -  you'll never trust big-box again!
More power to you
A 100A panel can definitely support 2 charging stations that provision at 50A each. If you go 125A feeder you'll have headroom for a 50A and 70A Tesla charger.
Comment: I just talked to platt it's used to be company policy to only sell to people with accounts or licenses, today there are a few stores that still have that policy I just happen to have one , I called the second location in my area and they do sell to the public. I got this info from the 2nd store the first that I normally order from just said not unless I had an account so it may be a combination of old policy and or returns.
Comment: Unless their policy has changed Platt doesn't sell to the general public or my local store won't, when I moved here a few years ago I went in and they had to see my license before taking my order. I told the guy that was strange I have been purchasing from them for over 20 years and never remember having to show ID but I usually have stuff delivered. He said that was there policy if you are not putting it on an account. I will double check when they open as I need to order some stuff this morning.
Comment: @EdBeal I've never dealt with Platt, but occasionally with other places for network/telephone wiring, and I've never seen such a policy. **However**, I wouldn't be surprised if a particular store has had too many returns from homeowners getting the absolutely wrong stuff that they put a policy in place to weed them out.
Comment: Note that you want quadplex USE/RHH/RHW-2 for direct burial work (SER can't be buried at all, see 338.12(A) point 2)
Comment: @ThreePhaseEel I get very confused by USE/RHH etc. because all of it I find online is single-conductor. I can believe you can direct b**U**ry that, but I don't see how you'd run it unprotected across rafters and joists where you'd use SER.
Comment: @Harper-ReinstateMonica -- yeah, you can't run it exposed the way you can with SER, only direct buried or in conduit.  The multiplex USE/RHH/RHW-2 is often called by the name "mobile home feeder", by the way.
Comment: @ThreePhaseEel right, the stuff with a cloverleaf cross section. But is *that* okay in direct fixation on rafters and the like?  It seems like it's just four of the singles glued together.
Comment: @Harper-ReinstateMonica -- yeah, it's A-OK for direct burial, see 338.100 for details
Comment: @ThreePhaseEel I mean, is the MH feeder OK inside the home, stapled to ceiiling joists etc. like you'd cable SER?  It seems to have no outer jacket.
Comment: @Harper-ReinstateMonica -- it is not, USE cable is not allowed indoors.  (single-rated USE can't even be run indoors *inside conduit* -- mobile home feeder can be used in conduit because it's tri-rated USE/RHH/RHW-2)


How to use transition in show/hide

Question: I wrote code in the javascript (show/hide div). Now i wanna use attribute "transition" in CSS, but it doesn't work.
JavaScript in HEAD:
function show()
{
  document.getElementById('add-contact').style.display=\"block\";
  document.getElementById('add-contact-button').style.display=\"none\";
}
</script>

Div add-contact and add-contact-button:
Dodaj kontakt
  <form action=\"kontakty/dodaj\" method=\"post\" id=\"add-contact\" >
    ...
  </form>

Part CSS:
form#add-contact {
  float: right;
  width: 223px;
  height: auto;
  line-height: 27px;
  display: none;
  transition: height 500ms linear;
}

Comment: Why do you escape the quotes ?
Comment: The transition of course only works when the `height` property changes, not when you set the `display`.
Comment: I have got this code in echo().
Comment: when echo a script I recommend using both singlequotes and doublequotes.. singlequotes for your server script, then you can use as many doublequotes inside your string as you want to..
Answer: I see two major problems:

You can't transition the display property. You have to have it as a block from start, and just hide it with opacity: 0
You need to use the -webkit vendor prefix to make it work in Chrome and Safari.

See a working demo here: http://codepen.io/anon/pen/hwayD

How to use transition in show/hide


How to expose private git repo during docker build without including ssh key in image

Question: I'm trying to use the ADD command to expose a private git LFS repo during the docker build process but I keep getting errors:
------
> git://192.168.189.143/REPO/my-libs.git:
#37 0.761 Permission denied, please try again.
#37 0.819 Permission denied, please try again.
#37 0.883 firstname.lastname@example.com: Permission denied (publickey,password).
#37 0.885 fatal: Could not read from remote repository.
#37 0.885
#37 0.885 Please make sure you have the correct access rights
#37 0.885 and the repository exists.
------
failed to load cache key: failed to fetch remote email@example.com:REPO/my-libs.git: exit status 128

Here's the reference to the command:

My docker file looks like this:
# syntax=docker/dockerfile-upstream:master-labs
FROM ubuntu:18.04
ENV USER=markf78
USER ${USER}
WORKDIR /home/${USER}/temp
ADD firstname.lastname@example.com:REPO/my-libs.git /home/${USER}/temp

My build command on my MacOS X host is
docker build -t my-image --ssh default .

I am able to successfully clone from the terminal on the MacOS X host using my ed25519 SSH key.
Any ideas how to fix this? I realize there are other solutions available but this one seems the cleanest as it does not store my private key in the image.
Answer: Do not clone the repo inside the image build, you do not need to do that at all.
Just put the Dockerfile in the / of the repo (also commit it to the repo to have it version controlled), and COPY the repo files with a Dockerfile command inside the image: COPY . .
First dot is the source that is your current directory on your machine that is your git repo, second dot is the target, the working dir inside the image. You build the image and publish it, push it to a docker registry so others can pull it and start using it. If you want more complex stuff building and publishing with a help of a server, look up CI/CD techniques.
Comment: I need binary files from a git LFS repo that we want included in the image.
Comment: It doesn't really matter what you store in your git repo or any file host solution for building a docker image. I have never worked with Git LFS but you will need to checkout the files that are stored on remote to your local drive and do as I wrote. It doesn't matter if you pull the files from git with git pull or copy with ftp etc before issuing the docker build command. Also your local machine is the build machine, later you will want to put this workload to an actual build machine that is using some CICD tool (github, gitlab, azure pipelines or plain old jenkins etc).
Comment: The file image will contain files from multiple repos.
Comment: it doesn't matter. You do `git clone onerepo.git; git clone otherrepo.git;` and then in your Dockerfile you do `COPY onerepo somedirinimage` next line `COPY otherrepo someotherdirinimage`. and then call `docker build` This script will be your build script, it could be a job/step in a CICD pipeline.
Answer: RUN --mount=type=ssh git clone yourrepo

you need to run an ssh agent and add your private ssh key in it by ssh-add command
then run docker build with --ssh default


Transpose data from CSV

Question: I have an CSV with this pattern:
Column 1, Column 2, Column 3,
NAME 1, APP1, APP2
NAME 2, APP2
NAME 3, APP1, APP3

I would like to transpose this data and get this result
Column 1, Column 2, Column 3,
NAME 1, APP1
NAME 1, APP2
NAME 2, APP2
NAME 3, APP1
NAME 3, APP3

I would like to do it on excel or google sheets.
Any idea?
Answer: try:
=INDEX(QUERY(SPLIT(FLATTEN(A2:A&"×"&B2:C), "×"), "where Col2 is not null", ))

Transpose data from CSV


I can't get my wireless working on ubuntu 12.04. I have a Dell Inspiron 6400

Question: As above. I tried alot of the solutions i found in the forum but have had no success. Sorry i'm a bit of a newbie with linux!!
Comment: Tell us the model of your Wireless card by appending this command in your terminal:
lspci | grep Network
Comment: Welcome to Ask Ubuntu! We need more hardware information to help you, can you look at [this question](http://askubuntu.com/questions/14008/i-have-a-hardware-detection-problem-what-logs-do-i-need-to-look-into) and then edit your question adding the information.
Answer: I have that same laptop and had the same problem:

Connect to the internet using a modem or cable
Use the command sudo modprobe b43 and see the outcome.

If it doesn't work, open a terminal by opening the Dash and typing terminal and clicking on the terminal icon that appears. Then type:
sudo apt-get remove --purge bcmwl-kernel-source
sudo apt-get install firmware-b43-installer

Restart computer.(The change only take place when you restart.) Thanks to our friend Karl for this.


Condensation/moisture on AC Unit

Question: Is there any particular reason why there is so much moisture/condensation coming from this AC unit?

Added context: it rained the entire day before this photo was taken, but the unit is located underneath a deck. Furthermore, there is a piece of corrugated metal above the unit to prevent rain from falling on it.
Comment: Coming out of that retaining wall behind the unit?
Comment: https://www.conditionedairsolutions.com/water-around-air-conditioners-outside-unit/. This was a good read
Comment: @jsotola: so, is it your opinion that the water is not from the unit?
Comment: There should be a pvc  drain about 1 inch you could add on to it and divert the water away from the door on to the grass .
Comment: As for the drain  it should be a condensate trap drain with out it unit both sucks and blows air. and water sits and drains when the unit shuts off
Comment: Ya  if pad is touching wall  could see that looks like old stain
Comment: @Kris this is exactly the information I was looking for!
Answer: Moisture or condensation is a normal part of an AC system, the outside unit only has a little area that be cold, the larger line into the compressor is the suction line this line should be insulated as it will sweat and drip when the system is running, very little of the suction line should be exposed. The part that really generates the water is the inside unit. This is where the cooled high pressure Freon is released to low pressure by an orifice or thermostatic valve. This creates cold and pulled the moisture out of the air the moisture drips into a tray and is drained into the house water drains or outside which ever is easily done. In a humid climate , just after a rain the inside unit can easily create 10 gallons a day on a 5 ton system and this may be the source of the water if draining outside on the pad. The outside unit if creating very much at all needs more or some insulation added and this will increase efficiency saving $ and reducing moisture from the outside unit.

Condensation/moisture on AC Unit


New Zero-day exploit reportedly found affecting Linux/Android (CVE-2016-0728)

Question: Russia Today reports (20 January 2016) that there is a new zero-day exploit that has been discovered affecting Linux and all Linux-based OSes for computers and phones.
What is the deal; how does it affect Ubuntu; and when can we expect security updates that will close this security hole?
Comment: *When* ? as soon as possible, cannot give you specific date or time
Comment: which kernel is vulnerable and what mitigation to address the vulnerability?
Comment: More details here: http://www.networkworld.com/article/3023447/security/linux-zero-day-affects-most-androids-millions-of-linux-pcs.html AND http://perception-point.io/2016/01/14/analysis-and-exploitation-of-a-linux-kernel-vulnerability-cve-2016-0728/
Answer: It has been patched already.
Quoting the article:

[...] "Yevgeny Pats discovered that the session keyring implementation in the Linux kernel did not properly reference count when joining an existing session keyring. A local attacker could use this to cause a denial of service (system crash) or possibly execute arbitrary code with administrative privileges," reads today's Ubuntu Security Notice USN-2872-1 for Ubuntu 15.10. [...]

and

[...] patches are now available for the Ubuntu 15.10 (Wily Werewolf), Ubuntu 15.04 (Vivid Vervet), and Ubuntu 14.04 LTS (Trusty Tahr) distributions. [...]

and

[...] you are urged to upgrade the kernel packages to linux-image-4.2.0-25 (4.2.0-25.30) for Ubuntu 15.10 (Wily Werewolf), linux-image-4.2.0-1020-raspi2 4.2.0-1020.27 for Ubuntu 15.10 (Raspberry Pi 2), linux-image-3.19.0-47 (3.19.0-47.53) for Ubuntu 15.04 (Vivid Vervet), and linux-image-3.13.0-76 (3.13.0-76.120) for Ubuntu 14.04 LTS (Trusty Tahr). [...]

So users of the patched releases (15.10 / 15.04 / 14.04, and according to Canonical also 12.04) may (and should) upgrade right away by running:
sudo apt-get update && sudo apt-get dist-upgrade

and rebooting the computer afterwards.
Comment: @IWPCHI If you found this answer useful remember that [you may accept it as well](http://askubuntu.com/help/accepted-answer).
Comment: @IWPCHI Don't thank Kos!  **;-)** If this answer did help, just click the little grey **☑** under the number now turning it into beautiful green.  If you do not like the answer, click on the little grey down-arrow below the 0, and if you *really* like the answer, click on the little grey ☑ *and* the little up-arrow...  If you have any further questions, just [ask another one](http://askubuntu.com/questions/ask)!
Comment: Thanks for your reply!  We will pass along the info ASAP!
Answer: Just complementing @kos's nice answer:
The Zero day exploit (CVE-2016-0728) was found by the researchers at Perception Point.
It was introduced in 3.8 Vanilla Kernel. So the Ubuntu releases using kernel versions 3.8 or later are vulnerable. As @kos already mentioned, on a supported release you can just upgrade the kernel to install the patch:
sudo apt-get update && sudo apt-get dist-upgrade

How to Check the Vulenerability (taken from here):
Install libkeyutils-dev:
sudo apt-get install libkeyutils-dev

Copy this C program from github, written by the Perception Point team to test the exploit.
Save the codes in a file e.g. test_2016_0728.c and compile:
gcc test_2016_0728.c -o test_2016_0728 -lkeyutils -Wall

Run the compiled program as normal user:
./test_2016_0728 -PP1

It would take some time, if your kernel is vulnerable after the completion of the program you will see that your privilege has been escalated i.e. you have become root.
Comment: Too bad I had upgraded already or I definetly would have tested this!
Comment: @kos ummm...bad for you :P
Comment: Did you manage to reproduce the exploit? I didn't find anyone who did so far.
Comment: @Jakuje I upgraded my kernel before I came to read the perception point's article.. According to the article it is the way..
Comment: @Jakuje I'm testing the exploit on my Pi right now, which is running an unpatched version of Raspbian Jessie. It's running, but not much seems to be happening.
Comment: @HeatherBrown It would take time as it involves incrementing the 32 bit reference counter for keyring facility to 2^32..it would take about 30 minutes for a i7 machine..
Comment: I may have copied sobering wrong. I let it run for 27 hours on the pi 2 without getting past the "increfing" step. Unless that's the expected result for a patched system
Comment: @HeatherBrown "Increfing" is the first step where the counter is being exhausted by 2^32 values sequentially.. A pi is the worst thing you could test this on..you need to use a powerful machine, like i said a core i7 would need around 30 minutes or so..


Trying to install Netflix app

Question: I'm trying to install Netflix on my Playstation 3. I have been through the tutorial on the Netflix site without success. I'm going to "what's new" section and clicking on Netflix (using the X button) but nothing happens.
Is there any way to install it offline? Copying it to an USB stick and installing it from there?
Comment: What sort of issues are you having? Can you be more specific? Have you tried installing it through the icon under the "Video" tab on the PS3's XMB menu?
Answer: Strange that you have this problem. Might be some issue with PSN. Can you install other applications like Vudu or Hulu+?
Also you can try pointing the PS3 browser to www.netflix.com. I think it gives you an option to download it from there.

Trying to install Netflix app


Trying to install Varnish on Ubuntu 14.04 server LTS

Question: I'm attempting to install Varnish cache on Ubuntu 14.04 and getting this:
The following packages have unmet dependencies:
 varnish : Depends: libjemalloc1 (>=2.1.1) but it is not installable
           Depends: gcc but it is not installable
E: Unable to correct problems, you have held broken packages.

This is how I did it:
apt-get install apt-transport-https
apt-get install curl
curl https://repo.varnish-cache.org/ubuntu/GPG-key.txt | apt-key add -
echo "deb https://repo.varnish-cache.org/ubuntu/ trusty varnish-4.0" >> /etc/apt/sources.list.d/varnish-cache.list
apt-get update
apt-get install varnish

I just installed Trusty in a VMWare VM to do some testing with Nginx and Varnish. Any ideas on how to remedy?
Output from apt-cache policy libjemalloc1
libjemalloc1:
   Installed: (none)
   Candidate: (none)
   Version table:

Same output with
apt-cache policy gcc
Comment: [Edit] your question and add the output of `apt-cache policy libjemalloc1`
Comment: I have attempted to install 12.04.5 LTS as well with EXACTLY same results. WTH is going on here? I am following every freaking example on the internet but nothing...
Answer: libjemalloc1 is in the universe repositories
sudo apt-add-repository universe

gcc is in the main repositories
sudo apt-add-repository main

After that
sudo apt-get update
sudo apt-get install varnish

Comment: It's working. Great.


Converting Symbol Characters to HTML with VB.NET

Question: I'm trying to ensure that all characters which are not numeric, or alphabetic are converted to HTML code when submitted to my database.
With a bit of Googling, I have come up with this:
<code>Public Shared Function HTMLEncodeSpecialChars(text As String) As String
    Dim sb As New System.Text.StringBuilder()

    Dim i As Integer
    Dim charArray() As Char = text.ToCharArray()
    ' display contents of charArray
    For i = 0 To charArray.Length - 1
        sb.Append((String.Format("&#{0};", Asc(charArray(i)))) & ",")
    Next
    Return sb.ToString()
End Function
</code>
This successfully converts anything to HTML, but now I need to put some condition in there so it only does it where I need it to. ie; on any character which will either screw up my database entry, or screw up formatting when returned back to the screen as HTML (this database content is for product data for a website).
So for simplicity, I guess I want to convert only charcters which are not A-Z alphabetic or 1-0 numeric.
I could use isNumeric, but not sure how to detect alphabetic characters.
I've been Googling and found something which looked like it would work, but the logic/filtering was wrong.
So I figured I'd ask here :D
Answer: You haven't said why existing tools don't work for you, so you might not know about this:
HtmlEncode method in the System.Web namespace:

HTML encoding makes sure that text is displayed correctly in the
  browser and not interpreted by the browser as HTML.
Comment: Thanks, you're right I was not aware of that. The docs indicate that it's exactly what I need... trouble is, it doesn't seem to work! I'm trying to convert a string of HTML submitted by a form so that it can be inserted into my database. It's causing an error on apostrophes at the moment, should HtmlEncode convert apostrophes? EDIT; using .NET 2.0 if that make a difference
Comment: Additional; I've just had it output the result as text so I can see exactly what's happening. It does seem to be working, but still upsetting the submission to the database. A snippet of output is: `<table style="font-family: \u0027Times New Roman\u0027; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; ...` When I try to send this to my database using MySQL UPDATE, I get `there's an  error in your SQL near \u0027Times`
Comment: Ahh, a bit more Googling, gave me this http://www.velocityreviews.com/forums/t100026-htmlencode-with-apostrophes.html from which I have deduced that the apostrophe needs converting manually. Therefore `notes = HttpContext.Current.Server.HtmlEncode(Replace(notes, "'", "'"))` is working within my function :-)
Comment: @JamieHartnoll Glad to help! I'm not sure how you're doing your DB interaction, but I think using [SqlParameters](http://msdn.microsoft.com/en-us/library/yy6y35y8%28v=VS.80%29.aspx) would take care of the sanitizing it for you before you put it in the db... though it's been a long time since I've been in .NET 2.0. More discussion [at this question](http://stackoverflow.com/questions/3479434/sanitizing-sql-data)


I tried installing gksu but getting the following error.Someone help me to fix this

Question: sudo apt-get install gksu
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package gksu

Answer: You can try:
sudo apt-get update
sudo apt-get install gksu

If it doesnt solve your problem, you can try this link.
Comment: http://askubuntu.com/questions/314267/how-can-i-install-nautilus-gksu


Flask-WTF not validating

Question: I made a WTForms for my Flask Website however the it just wont validate. I have made other flask WTForms before and they all seemed to work but this one just wont work
forms.py
class UpdateForm(FlaskForm):
    picture = FileField('Update Profile Picture', validators=[FileAllowed(['jpeg', 'jpg', 'png'])])
    username = StringField("Username", validators=[], render_kw={"placeholder": f"Enter username"})
    email = StringField("Email", validators=[Email()], render_kw={"placeholder": "Enter email"})
    submit = SubmitField('Update')

    def validate_username(self, username):
        if username.data is not None:
            user = User.query.filter_by(username=username.data).first()
            if user:
                raise ValidationError('Username is already taken.')

    def validate_email(self, email):
        if email.data is not None:
            emailL = User.query.filter_by(email=email.data).first()
            if emailL:
               raise ValidationError('Email is already taken.')
            else:
                raise ValidationError('Enter a valid email.')

I have done these methods before but this one is really not working and its not even giving me an error.
routes.py
@app.route('/settings/edit-profile', methods=['POST', 'GET'])
def edit_profile():
    if not current_user.is_authenticated:
        flash('This process requires login.', 'failure')
        return redirect(url_for('login'))
    else:
        form = UpdateForm()
        if request.method == "POST" and form.validate_on_submit():
            print(form.username.data)
            print(form.email.data)
            pfp = url_for('static', filename=f'pfplib/{current_user.pfp}')
            return render_template("Settings/edit-profile.html", pfp=pfp, form=form)
        pfp = url_for('static', filename=f'pfplib/{current_user.pfp}')
        return render_template("Settings/edit-profile.html", pfp=pfp, form=form)

html file
<form method="POST" action="" enctype="multipart/form-data">
            {{ form.csrf_token }}
            {{ form.hidden_tag() }}

                            <input type="file">

                        {{ form.username.label(class="head-label") }}
                        {% if form.username.errors %}
                            {{ form.username(class="string-field") }}
                            {% print(error) %}

                                {{ error }}

                        {% else %}
                            {{ form.username(class="string-field", value=current_user.username) }}
                        {% endif %}

                        {{ form.email.label(class="head-label") }}
                        {{ form.email(class="string-field", value=current_user.email) }}

                {{ form.submit(class="btn-gradient submit-btn-1") }}

        </form>

Hope someone can help fast
THANKING u SOOO SOOO SOO MUCH IF you can find a fix
Comment: With 'updating', what exactly do you mean? Is it simply getting the information found in your form, as you are doing, or 'updating' a database?
Answer: I am not sure exactly what is causing your issue, but I think I have done a very similar thing to what you are trying to accomplish, so I can share with you what worked for me and hopefully it works for you too:
My Form Validation
class EditProfileForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    about_me = TextAreaField('About me', validators=[Length(min=0, max=250)])
    website_link = StringField('Link your website', validators=[Optional(), URL(message='This is not a valid link, make sure you enter the entire URL')])
    submit = SubmitField('Apply Changes')

    def __init__(self, original_username, *args, **kwargs):
        super(EditProfileForm, self).__init__(*args, **kwargs)
        self.original_username = original_username

    def validate_username(self, username):
        if username.data != self.original_username:
            user = User.query.filter(User.username.ilike(self.username.data)).first()
            if user is not None:
                raise ValidationError('This username is already taken')
            if ' ' in username.data:
                raise ValidationError('Your username may not contain spaces.')

Note: I did not have an email validation, but it would follow the same form as my username validation.
My routes.py
@app.route('/edit_profile/', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = EditProfileForm(current_user.username)
    if form.validate_on_submit():
        current_user.username = form.username.data
        current_user.about_me = form.about_me.data
        current_user.website = form.website_link.data
        db.session.commit()
        flash('Your changes have been saved.')
        return redirect(url_for('main.user', username = current_user.username))
    elif request.method == 'GET':
        form.username.data = current_user.username
        form.about_me.data = current_user.about_me

My relevant HTML
<form action="" method="post">
        {{ form.hidden_tag() }}

Change your profile picture

Change your password

            {{ form.username.label }}

            {{ form.username(size=32, id="usernameField") }}

            {% for error in form.username.errors %}
            {{ error }}
            {% endfor %}

            {{ form.about_me.label }}

            {{ form.about_me(cols=50, rows=4, id="aboutMeField") }}

            {% for error in form.about_me.errors %}
            {{ error }}
            {% endfor %}

            {{ form.website_link.label }}

            {{ form.website_link(size=32, id="websiteField") }}

            {% for error in form.website_link.errors %}
            {{ error }}
            {% endfor %}

{{ form.submit() }}

    </form>

From this I don't see many differences between are code, but there are a few that could be causing your issue.
1.I have an init function in my form
2. my query for user in my username_validation uses ilike which makes it case insensitive
3. I made data required on the username field, and just inputted the users current username as the default of the form, this meant I didn't need to check if there was data in the field, I just checked if the data matched the current username.
4. Our routes are slightly different, I just look for form.validate_on_submit(), but I imagine you are using your method for all of your forms that are working, so that's probably not where the problem is
5.Our displaying of error messages is different
So you can try to input some of the methods I used into your case and see if that helps at all.
It may also be useful to know what happens when you try to submit the form, does it submit no matter what is in the fields? or does it not submit at all? that might help find where the problem is.
I hope that helps, even just a bit, Sorry if it does not!
Answer: You could add the novalidate property in the html Form. Maybe the browsers validation is blocking your own.

Flask-WTF not validating


How to escape double-quotes in a double-quoted string literal

Question: This is weird, I can't figure it out :
<code>$query = "SELECT * FROM [master].[dbo].[TestTbl] WHERE Agentd_ID = "$_SESSION['agentid']" ";
</code>
I also tried:
<code> $query ='SELECT * FROM [master].[dbo].[TestTbl] WHERE Agentd_ID = "$_SESSION['agentid']" ';
</code>
I would really appreciate any help from you guys :D
Comment: What exactly is the problem you can't figure out?
Answer: You're probably looking for
<code>$query = "
    SELECT
        *
    FROM
        [master].[dbo].[TestTbl]
    WHERE
        Agentd_ID = \"{$_SESSION['agentid']}\"
";
</code>
BUT have a read of https://en.wikipedia.org/wiki/SQL_injection
and then look for the approriate encoding/escaping function for your database (t-sql?) and/or prepared statements with parameters.
see also:
http://docs.php.net/manual/en/language.types.string.php
http://docs.php.net/manual/en/language.types.string.php#language.types.string.parsing
Comment: great. thanks.. But I am having error now :/
This works a while ago, when I set Agent_ID = '1234', but when i tried the session you've said, this part got some errors:
while($record = sqlsrv_fetch_array($result,SQLSRV_FETCH_ARRAY){
Comment: Take a look at the error handling in http://docs.php.net/manual/en/function.sqlsrv-query.php#example-2378
Comment: No worries with regards to the sql-injection part, I'll cover it soon. :D
Comment: It works now, thank you very much sir, I owe you one :D, I just removed changed the " to ' and removed the / before the {
Thank you sir.


How do I level up my items now?

Question: So as of July 30th, some new updates were added, which means levelling has to go through the forge, with something about fire crystals I don't get.
I don't understand what exactly I'm supposed to do. Do I have to wait for the heat to fill up on the bar to use the crystals, or are the crystals a "quick" heat boost?
Having some clarification on how the new Forge works would be great, thanks!
Answer: You only need to visit a forge when an item has been fully heated for its current level.
There is a forge in Haven located on the hill near the alchemy machine, and to the right of the fountain.  This is a good place to perform your first forging, as there is an NPC at this location that offers some elaboration on how the forge works.
When you have an item that is ready to be leveled up, it will appear in an item selection menu.  After selecting the item, a dialog box will appear prompting you to give a number of "fire crystals" in exchange for the level-up.
The forge features something of a gambling mechanic whereby you can offer more fire crystals in exchange for a chance to skip a level completely, get a heat bonus, or to obtain a Forge Prize box.  This gambling mechanic is also useful if you want to guarantee a level-up, as there is a possibility that offering anything but the maximum (x3 the minimum, in my experience) amount of fire crystals will result in a failure.  In the event of a failure your fire crystals will be removed, but your item will still be fully heated and ready for forging.
Below is a list of fire crystals that can be obtained, and their appropriate star rating:
<code>☆☆☆☆☆ Cracked Fire Crystal
★☆☆☆☆ Dim Fire Crystal
★★☆☆☆ Warm Fire Crystal
★★★☆☆ Glowing Fire Crystal
★★★★☆ Shining Fire Crystal
★★★★★ Radiant Fire Crystal
</code>
These can be obtained in normal gameplay by breaking open boxes in the clockworks.  Playing on a harder difficulty setting will increase the odds of getting fire crystals and other items of the new "rarities" class.  I came across quite a few fire crystals playing Tier 3 on "Elite" difficulty, so unless you're really short on fire crystals there doesn't seem to be much point in offering up the minimum amount to the forge.

How do I level up my items now?


Getting step count from google fit

Question: I am using google fit for my application and trying to get the step count. The registration and authantication things are ok. Your google account comes up you select it and after that the google permission dialog appears and select yes. After that point the following method is called which uses the listener to register the live  updates from the step counter,the DataResource selection and so on. However the step count is a bit funny. Sometimes it goes like up and down. Maybe I don't use any of the recording things correct. Any advice please?
<code>    private void invokeFitnessAPIs() {

    // Create a listener object to be called when new data is available
    OnDataPointListener listener = new OnDataPointListener() {
        @Override
        public void onDataPoint(DataPoint dataPoint) {

            for (Field field : dataPoint.getDataType().getFields()) {
                Value val = dataPoint.getValue(field);
                updateTextViewWithStepCounter(val.asInt());
            }
        }
    };

    //Specify what data sources to return
    DataSourcesRequest req = new DataSourcesRequest.Builder()
            .setDataSourceTypes(DataSource.TYPE_DERIVED)
            .setDataTypes(DataType.TYPE_STEP_COUNT_DELTA)
            .build();

    //  Invoke the Sensors API with:
    // - The Google API client object
    // - The data sources request object
    PendingResult<DataSourcesResult> pendingResult =
            Fitness.SensorsApi.findDataSources(mClient, req);

    //  Build a sensor registration request object
    SensorRequest sensorRequest = new SensorRequest.Builder()
            .setDataType(DataType.TYPE_STEP_COUNT_CUMULATIVE)
            .setSamplingRate(1, TimeUnit.SECONDS)
            .build();

    //  Invoke the Sensors API with:
    // - The Google API client object
    // - The sensor registration request object
    // - The listener object
    PendingResult<Status> regResult =
            Fitness.SensorsApi.add(mClient,
                    new SensorRequest.Builder()
                            .setDataType(DataType.TYPE_STEP_COUNT_DELTA)
                            .setSamplingRate(1,TimeUnit.SECONDS)
                            .build(),
                    listener);

    // 4. Check the result asynchronously
    regResult.setResultCallback(new ResultCallback<Status>()
    {
        @Override
        public void onResult(Status status) {
            if (status.isSuccess()) {
                Log.d(TAG, "listener registered");
                // listener registered
            } else {
                Log.d(TAG, "listener not registered");
                // listener not registered
            }
        }
    });
  }

  // Update the Text Viewer with Counter of Steps..
  private void updateTextViewWithStepCounter(final int numberOfSteps) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(getBaseContext(), "On Datapoint!",
 Toast.LENGTH_SHORT);

            if(mFirstCount && (numberOfSteps != 0)) {
                mInitialNumberOfSteps = numberOfSteps;
                mFirstCount = false;
            }
            if(textView != null){
                textView.setText(String.valueOf(numberOfSteps));
            }
        }
    });
 }
 @Override
 protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putBoolean(AUTH_PENDING, authInProgress);
 }

 }
</code>
Answer: You are using different data types for data source and sensor request
Answer: Google Play Services 7.3 (released 4/28/2015) added a new method to the HistoryApi.readDailyTotal, which matches the step count on Google Fit official app and is easier to use.
<code>PendingResult<DailyTotalResult> result = Fitness.HistoryApi.readDailyTotal(fitnessApiClient, DataType.AGGREGATE_STEP_COUNT_DELTA);
DailyTotalResult totalResult = result.await(30, TimeUnit.SECONDS);
if (totalResult.getStatus().isSuccess()) {
    DataSet totalSet = totalResult.getTotal();
    steps = totalSet.isEmpty() ? -1 : totalSet.getDataPoints().get(0).getValue(Field.FIELD_STEPS).asInt();
}
</code>

Getting step count from google fit


How do I compile coffeescript (or run node tasks) from Objective C

Question: I want to compile coffeescript from my Mac OSX app, but I'm unsure how to go about doing this.  It seems like node tasks are heavily dependent on other libraries installed to the system.  How can I go about compiling coffeescript files from my app?
Comment: What have you tried so far? For example, have you tried to [launch the `coffee` command from Cocoa App](http://stackoverflow.com/questions/412562/execute-a-terminal-command-from-a-cocoa-app)? What was the outcome? Any error message?
Comment: So I tried packaging the coffee command inside my app, but it says "node not found".  I started including node binaries and that had more dependencies and it just felt like the wrong way to go about this.  I could use the one in my user path, but then it would only work for users with coffeescript installed on their system.
Comment: And by "including the binaries" i meant copying them directly into my xcode bundle.  If there's a proper way to pacakage up node scripts into cocoa apps that's what im looking for.
Answer: A couple ideas:

The 'Try Coffeescript' section on coffeescript.org compiles in the browser by including the coffeescript compiler as a javascript tag. You could do something like that in a UIKit WebView where you have control over the javascript execution.
PhoneGap/Codova based app
Make a request out to a node server or other js environment and return the compiled code via service call.

I'm not sure you've provided enough context for which one of these might work, but they are the first things that come to mind.


spaCy 3.0, installed files are different from the files in github repo

Question: I installed spaCy 3.0 on my ubuntu. I use ctrl+B to find the definition of class "sentencizer" which is in sentencizer.py file:
class Sentencizer(__spacy_pipeline_pipe.Pipe):
    """
    Segment the Doc into sentences using a rule-based strategy.

        DOCS: https://spacy.io/api/sentencizer
    """
    def from_bytes(self, bytes_data, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
        """
        Sentencizer.from_bytes(self, bytes_data, *, exclude=tuple())
        Load the sentencizer from a bytestring.

                bytes_data (bytes): The data to load.
                returns (Sentencizer): The loaded object.

                DOCS: https://spacy.io/api/sentencizer#from_bytes
        """
        pass
...

Why there is no content in the functions defined in sentencizer.py. In the spaCy github repo, there is no sentencizer.py file and the class "sentencizer" is defined in sentencizer.pyx:
class Sentencizer(Pipe):
    """Segment the Doc into sentences using a rule-based strategy.
    DOCS: https://spacy.io/api/sentencizer
    """

    default_punct_chars = ['!', '.', '?', '։', '؟', '۔', '܀', '܁', '܂', '߹',
            '।', '॥', '၊', '။', '።', '፧', '፨', '᙮', '᜵', '᜶', '᠃', '᠉', '᥄',
            '᥅', '᪨', '᪩', '᪪', '᪫', '᭚', '᭛', '᭞', '᭟', '᰻', '᰼', '᱾', '᱿',
            '‼', '‽', '⁇', '⁈', '⁉', '⸮', '⸼', '꓿', '꘎', '꘏', '꛳', '꛷', '꡶',
            '꡷', '꣎', '꣏', '꤯', '꧈', '꧉', '꩝', '꩞', '꩟', '꫰', '꫱', '꯫', '﹒',
            '﹖', '﹗', '!', '.', '?', '', '', '', '', '', '', '',
            '', '', '', '', '', '', '', '', '', '', '', '', '',
            '', '', '', '', '', '', '', '', '', '', '', '', '',
            '', '', '', '', '', '', '', '', '', '', '', '', '',
            '', '', '', '', '', '', '', '', '', '', '', '', '',
            '。', '。']

Why the installed files are different from the github repo? Thanks!
Comment: When you say you use ctrl+b to find the definition, what software are you using for that? Also, what's your full spaCy version - 3.0.3 or an earlier one?
Answer: When developing a Python library, small changes are saved in Git as they're made, but they're only released to PyPI when the maintainer intentionally makes a release. So it's normal for the files on your computer to be a little different from the files in a git repo, even if you have a very recent release.
I was really confused about the sentencizer.py code you posted, since there doesn't seem to have ever been a file with that name in spaCy, but it looks like that is a magic PyCharm feature - it's not showing you the actual source code, it's doing some sort of decompilation.
You noticed spaCy has the sentencizer.pyx file. That's compiled into a binary .so file that Python runs when you use the code. PyCharm is presumably working backwards from the .so file.


Redirect all resources (exe | dll | conf) from bin\Release to a common output folder

Question: I'm wondering if there is any MSBuild feature that allows us to redirect all resources (exe | dll | conf) from bin\Release to a common output folder for all projects based on Directory.build.propos / Directory.build.target.
Actually, I'm using the Azure DevOps pipeline task "copy files" but I'm not satisfied with the results because it copies some, 25000 files and the operation took 10 minutes.
Comment: Hi @Mselmi, could the answer help to meet your requirement? Thanks.
Comment: Hi @Mselmi, have you try following answer? Will appreciate if you could tell whether it works. Thanks.
Answer: Override the value of the OutDir property. This property is used in each project. The outputs of each project will be written to the OutDir. By overriding you can set the OutDir of all the projects to the common output folder, saving the time of making copies.
Create a Directory.build.props file in a folder that is a parent of all your project folders. In the Directory.build.props file, set a value for OutDir for a shared folder. You can conditionalize the property to be set only for Azure DevOps pipeline builds by testing for the TF_BUILD variable. TF_BUILD will exist and have a value of 'true' in a pipeline build.
e.g.

<Project>
  <PropertyGroup Condition="'$(TF_Build)' != '' and '$(TF_Build)'">
     <OutDir>$([MSBuild]::EnsureTrailingSlash('$(System.DefaultWorkingDirectory)'))sharedOutput</OutDir>
  </PropertyGroup>
</Project>

If there are already Directory.build.props files (and/or Directory.build.targets files), you can add an import at the beginning of each file to ensure the complete chain of files up the directory hierarchy is included.
e.g.

<Project>
  <Import Project="$([MSBuild]::GetPathOfFileAbove('$(MSBuildThisFile)', '$(MSBuildThisFileDirectory)../'))" />

  <PropertyGroup Condition="'$(TF_Build)' != '' and '$(TF_Build)'">
     <OutDir>$([MSBuild]::EnsureTrailingSlash('$(System.DefaultWorkingDirectory)'))sharedOutput</OutDir>
  </PropertyGroup>
</Project>


Do you think is it a good idea to keep the user on a same tab when refreshing the page?

Question: Do you think is it nice to have or necesary as user expects to stay in the same tab in a navigation when refreshing the page? Here is a demonstration and the link for the tabs:
Comment: Welcome to Stack Exchange. I have added a screenshot to your question to help clarify it. By tabs do you mean the dropdown menu items? If that is the case then they would not need to stay open if the user refreshes the page.
Comment: I see you have added a new screenshot. If the user refreshes the screen when the `Algermeen` tab is selected then yes, it should stay selected.
Comment: ok, thanks @MikePoole for adding the screenshot and your answer, but you don't expect a reset of the page when do yuo refresh a page???
Comment: That is correct. My view would be that the initial state of the page would have the tab selected so it should be like that when they refresh the page too.
Answer: It is important to keep the user where he is expected to be. Not all websites work like this but pages that go the extra step and allows the user to return to his initial state are a big plus.
Comment: In your opinion a user expects to stay at the same tab when refreshing the site?? thanks for your answer Cristian Negraia
Comment: @antonell of course. Why would you even think a user want to be re"directed" when the user re"fresh" the page? This is should be the 101 for every webdev, thats not really a UX secret.
Comment: It is not my opinion it is the norm.
Comment: If it is the norm and 101 for every webdev do you can show me a tab component of any CSS framework where it maintains the user at the same tab when refreshing the browser, I'm searching for that feature.
Comment: It is achieved with js, php or any other languages. Google mantain current tab on refresh.


iOS Enterprise app distribution helper that doesn't require UDIDs setting up

Question: I have an Enterprise Program account in the Apple developer program. Currently I'm using TestFlight to distribute an app, which still seems to require that the distribution profile contain each tester's UDID (even for Enterprise apps).
Are there any alternatives to TestFlight (aside from basic DIY placing of the files on a webserver somewhere) that will let me
a) distribute my Enterprise app without the UDID hassle,
b) still allow some control over who installs the app,
c) offer some features similar to TestFlight?
I've googled for this but it's tricky to formulate a search for these criteria.
Update
The Enterprise program forbids distribution of the app to anyone outside your own organisation. I'm curious if this would apply to a service such as TestFlight; this might exaplin the lack of such 3rd party services that can distribute your enterprise apps in the true enterprise fashion (as opposed to treating them as Ad Hoc where UDIDs are required still).
Answer: TestFlight now supports uploading of Enterprise builds (without any UDIDs associated). Maybe it always did! I was convinced for a long time it wasn't permitted, but I can't find anything to substantiate that now.
Answer: The "hassle" is caused not by TestFlight, but by Apple - the device will reject the application if it's not signed for it, so there is no service working without UDIDs.
ps. You could always jailbreak your devices and disable signature checking, but I'm not aware of any service which take advantage of this.
Comment: Enterprise signed apps are not required to contain the UDID of each device they run on! See, for example, http://stackoverflow.com/questions/5546581/how-to-distribute-ios-application-wirelessly-without-managing-udids-and-recompil


NameError: global name "total" is not defined, but it is

Question: Every time I run my code, it tells me that total is not defined. I have it defined in support.py, which is then imported into stopping.py. I've looked for similar cases, but I can't see why it's telling me this. Please help!
This is stopping.py
from support import *

def main():

    def get_info():
      amplitude = float(input("Amplitude of the sine wave (in feet): "))
      period = float(input("Period of the sine wave (in feet): "))
      sign = float(input("Distance to the stop sign (in feet): "))
      nobrake = float(input("Distance needed to stop without using hand brakes (in feet): "))
      step = 9
      return amplitude, period, sign, nobrake

    get_info()

    get_distance(0, 0, 155.3, 134.71)

    print("Distance to the stop sign (in feet): 155.3")
    print("Distance needed to stop without using hand brakes (in feet): 350.5")
    print("Length of the sine wave: ", total)

main()

This is support.py
import math

def get_sine_length(amplitude, period, x_distance, step):
  x = 0.0
  total = 0.0
  last_x = 0
  last_y = 0
  while x <= x_distance + (step / 2):
     y = math.sin(2 * math.pi / period * x) * amplitude
     dist = get_distance(last_x, last_y, x, y)
     #print("distance from (", last_x, ",", last_y, ") to (", x, ",", y, ") is", dist)
     total = total + dist
     last_x = x
     last_y = y
     x = x + step
 return total

def get_distance(a, b, c, d):
   dx = c - a
   dy = d - b
   dsquared = dx**2 + dy**2
   result = math.sqrt(dsquared)

Comment: in support.py, `total` is a local variable
Comment: Post the actual exception so we can see when it occurs.
Comment: Where is `get_sine_length()` called after all?
Answer: total is local to get_sine_length. Since you're returning it, to get to it you call get_sine_length and store the result.
The problem doesn't actually have anything to do with the import really. It would be the same if the function definition for get_sine_length was in stopping.py. Variables defined inside functions (inside a def someFunc():) are only accessible to that function unless you force them to be global. Most of the time, however, you shouldn't declare global variables just to access normally local vars from outside a function - that is what returning is for.
This example shows the general issue you're running into. I'm hesitant to call it a problem, because it is actually an important language feature of python (and many other programming languages).
>>> def func():
...     localVar = "I disappear as soon as func() is finished running."
...
>>> print localVar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'localVar' is not defined
>>> func()
>>> print localVar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'localVar' is not defined

Think of a function as a machine that takes in certain inputs and outputs others. You generally don't want to open up the machine- you just want to put the inputs in and get the output.
Comment: Did any of my edits help? Although it would work, don't make `total` a global variable; instead, run `get_sine_length` and capture the result in a variable.
Comment: Even though I've imported support.py into stopping.py? Would I just define total as global to make it work?