Immutable objects are thread safe, but why?

Question: Lets say for example, a thread is creating and populating the reference variable of an immutable class by creating its object and another thread kicks in before the first one completes and creates another object of the immutable class, won't the immutable class usage be thread unsafe?
Creating an immutable object also means that all fields has to be marked as final.

it  may  be necessary  to  ensure  correct  behavior if a reference to
a newly created instance is passed from one thread to another without
synchronization

Are they trying to say that the other thread may re-point the reference variable to some other object of the immutable class and that way the threads will be pointing to different objects leaving the state inconsistent?
Comment: No. Each thread is creating a distinct instance of an immutable object. I see  no thread risk at all.
Comment: [Does Immutability Really Mean Thread Safety?](https://dzone.com/articles/do-immutability-really-means)
Comment: +No, the immutable model can **contain a non-thread-safe method** (do a logic which expected to run synchronized + this method not change the internal state of the immutable model)
Answer: Actually immutable objects are always thread-safe, but its references may not be.
Confused?? you shouldn't be:-
Going back to basic:
Thread-safe simply means that two or more threads must work in coordination on the shared resource or object. They shouldn't over-ride the changes done by any other thread.
Now String is an immutable class, whenever a thread tries to change it, it simply end up creating a new object. So simply even the same thread can't make any changes to the original object & talking about the other thread would be like going to Sun but the catch here is that generally we use the same old reference to point that newly created object.
When we do code, we evaluate any change in object with the reference only.
Statement 1:
String str = "123"; // initially string shared to two threads
Statement 2:
str = str+"FirstThread"; // to be executed by thread one
Statement 3:
str=str+"SecondThread";  // to be executed by thread two
Now since there is no synchronize, volatile or final keywords to tell compiler to skip using its intelligence for optimization (any reordering or caching things), this code can be run in following manner.

Load Statement2, so str = "123"+"FirstThread"
Load Statement3, so str = "123"+"SecondThread"
Store Statement3, so str = "123SecondThread"
Store Statement2, so str = "123FirstThread"

and finally the value in reference str="123FirstThread" and for sometime if we assume that luckily our GC thread is sleeping, that our immutable objects still exist untouched in our string pool.
So, Immutable objects are always thread-safe, but their references may not be. To make their references thread-safe, we may need to access them from synchronized blocks/methods.
Comment: @Akki No, ArrayList cannot be considered thread-safe unless we take care of the concurrency manually using things like synchronization. You are considering two references here, that's why it seems like it is thread-safe, which can be true for any other class. What we are discussing over here is immutability with thread safety and ArrayList is not immutable (unless you have used Collections.unmodifiableList).
Comment: Consider a collection, ArrayList of string, ArrayList l = list1; l = list2; where list1 and list2 are already created before, so with first statement l points to list1 and with second it points to list2, so I guess ArrayList is also thread safe but it's reference is not thread safe ?......Let me know what am I missing here
Answer: In addition to other answers posted already, immutable objects once created, they cannot be modified further. Hence they are essentially read-only.
And as we all know, read-only things are always thread-safe. Even in databases, multiple queries can read same rows simultaneously, but if you want to modify something, you need exclusive lock for that.
Answer:
Immutable objects are thread safe, but why?

An immutable object is an object that is no longer modified once it has been constructed. If in addition, the immutable object is only made accessible to other thread after it has been constructed, and this is done using proper synchronization, all threads will see the same valid state of the object.

If one thread is creating populating the reference variable of the immutable class by creating its object and at the second time the other thread kicks in before the first thread completes and creates another object of the immutable class, won't the immutable class usage be thread unsafe?

No. What makes you think so? An object's thread safety is completely unaffected by what you do to other objects of the same class.

Are they trying to say that the other thread may re-point the reference variable to some other object of the immutable class and that way the threads will be pointing to different objects leaving the state inconsistent?

They are trying to say that whenever you pass something from one thread to another, even if it is just a reference to an immutable object, you need to synchronize the threads. (For instance, if you pass the reference from one thread to another by storing it in an object or a static field, that object or field is accessed by several threads, and must be thread-safe)
Comment: Note that the part about "only made accessible after construction" can be made trivial by using final fields only (and since the object is immutable no reason not do). The java memory model gives all the [guarantees](http://java.sun.com/docs/books/jls/third_edition/html/memory.html#66562) we need if we avoid some obvious mistakes.
Comment: Yes doing something like `someCollection.add(this)` and co are exactly the obvious mistakes we have to avoid (but then I think it's common knowledge that leaking this from the constructor is almost always broken for other reasons as well). Even if the leaking instruction is the *last* one in the constructor, the guarantees do **not** apply (see 3rd paragraph for this).
Comment: @Voo: I don't think it's quite that fool-proof. Final fields are required to be assigned when the constructor completes, but it's quite possible for the constructor to store `this` into an object accessible by another thread before assigning all final fields.
Comment: Interesting, thanks for pointing out the special significance of constructor completion.
Answer: Thread safety is data sharing safety, And because in your code you make decisions based on the data your objects hold, the integrity and deterministic behaviour of it is vital. i.e
Imagine we have a shared boolean instance variable across two threads that are about to execute a method with the following logic

If flag is false, then I print "false" and then I set the flag back to true.
If flag is true, then I print "true" and then I set the flag back to false.

If you run continuously in a single thread loop, you will have a deterministic output which will look like:
false - true - false - true - false - true - false ...
But, if you ran the same code with two threads, then, the output of your output is not deterministic anymore, the reason is that the thread A can wake up, read the flag, see that is false, but before it can do anything, thread B wakes up and reads the flag, which is also false!! So both will print false... And this is only one problematic scenario I can think of... As you can see, this is bad.
If you take out the updates of the equation the problem is gone, just because you are eliminating all the risks associated with data sync. that's why we say that immutable objects are thread safe.
It is important to note though, that immutable objects are not always the solution, you may have a case of data that you need to share among different threads, in this cases there are many techniques that go beyond the plain synchronization and that can make a whole lot of difference in the performance of your application, but this is a complete different subject.
Immutable objects are important to guarantee that the areas of the application that we are sure that don't need to be updated, are not updated, so we know for sure that we are not going to have multithreading issues
You probably might be interested in taking a look at a couple of books:
This is the most popular: http://www.amazon.co.uk/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601/ref=sr_1_1?ie=UTF8&qid=1329352696&sr=8-1
But I personally prefer this one: http://www.amazon.co.uk/Concurrency-State-Models-Java-Programs/dp/0470093552/ref=sr_1_3?ie=UTF8&qid=1329352696&sr=8-3
Be aware that multithreading is probably the trickiest aspect of any application!
Answer: Immutability doesn't imply thread safety.In the sense, the reference to an immutable object can be altered, even after it is created.
<code>//No setters provided
class ImmutableValue
{

     private final int value = 0;

     public ImmutableValue(int value)
     {
          this.value = value;
     }

     public int getValue()
     {
          return value;
     }
}

public class ImmutableValueUser{
  private ImmutableValue currentValue = null;//currentValue reference can be changed even after the referred underlying ImmutableValue object has been constructed.

  public ImmutableValue getValue(){
    return currentValue;
  }

  public void setValue(ImmutableValue newValue){
    this.currentValue = newValue;
  }

}
</code>
Answer: Two threads will not be creating the same object, so no problem there.
With regards to 'it may be necessary to ensure...', what they are saying is that if you DON'T make all fields final, you will have to ensure correct behavior yourself.


How to get all contacts merged with given contact

Question: I'm trying to show a list of contacts along with the photo associated to them, but I see most of the contacts without the photo although they do have a photo when I go to the phone's (SG2) default contact list. I figured that this is because some of those contacts are actually merged, and the picture comes from the (raw?) contact that is not displayed in the list, so the question is - how do I get all the contacts merged with a given contact? I tried to play with the SQLite, but I can't find any column that will uniquely identify merged contacts.
From code perspective, I started with this method:
protected Bitmap getImageByContactId(final Context appContext, final String strContactId)
    {
        Bitmap bmContactImage = null;
    Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(strContactId));
    Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);

    InputStream image = null;
    try {
        image = appContext.getContentResolver().openInputStream(photoUri);
        bmContactImage = BitmapFactory.decodeStream(image);

        try {
            image.close();
        } catch (IOException e ) {
            e.printStackTrace();
        }

    } catch (FileNotFoundException e1) {
        // This can be ignored because the Uri is generic and photo may not really exist
    }

    return bmContactImage;
}

but this only returned photos associated to the "original" contact that matched the original search criteria (in my case - the contact id) - not if the picture was associated to a contact linked to the original contact.
I was hoping to make something like the following work, if I could only get the (raw?) id of the contacts linked/associated/merged with the original contact, but I can't seem to find a way to find those "other" contacts...
public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
    Uri uri = Uri.parse(String.format("content://com.android.contacts/contacts/%s", id));
    InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
    if (input == null) {
        return null;
    }
    return BitmapFactory.decodeStream(input);
}

Bottom line - what I'm trying to do is to show a photo of a contact, regardless whether it is from the contact matching the search criteria - or any of the contacts merged with that contacts - and any solution will be appreciated!
Thanks!
Comment: If you post your code it would be easier to try and assist you...
Answer: (I got here from our facebook page..)
here is how I get all contacts from my content resolver:
public void addContactsMultiple()
{
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);
     if (cur.getCount() > 0) {
           String id="";//Contact ID
           String name="";//Contact Name
           id = "";
           id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
           name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
           if(Integer.parseInt
           (cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
               //Getting the Contact Image
               if(cur.getString(cur
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI)) !=  null)
               {
                   imagePath = cur
                      .getString(cur
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
               }
               else {imagePath="none";}//If there is no contact image
          }

       }
       cur.close();
       }

In my code you get the image URI and than put it in your Contact object, than you can use
      ImageView image = (ImageView)findViewById(R.id.image)
      image.setImageURI(Uri.parse(imagePath));

or you can use Picasso Image Loader:
Picasso
and than use this code:
           Picasso.with(context)
           .load(imagePath)
           .skipMemoryCache()
           .into(image );

As You can see, I don't use BitMaps or decodeStream.
You only need the uri of the photo (which directs your image to the Android gallery)
if you get several contacts from the same name you can use this code to marge them:
//(mContactList) is the ArrayList of contacts object I have created)
 HashSet<Contact> hs = new HashSet<Contact>();
        hs.addAll(mContactList);
        mContactList.clear();
        mContactList.addAll(hs);

this code will delete duplications
with a little adjustments you can get the image uri to the contact it belongs..
come back if you have more questions.


Diode circuit problem

Question:
I've come across the following problem:
I need to figure out what the voltage is over every element. I already know that only diode 3 is on and that diode 2 and 4 are off. But how do I determine the voltage? Do I need to use KVL? And how?
Comment: Well if they are ideal diodes with no voltage drops and no allowance for reverse current, you could just remove D2 and D4 and turn D3 into a wire. Then it's easy from there.
Comment: This is an unusual homework question as OP asks _how_ to find the solution, has thought about a possible way to solve it, but is not quite sure how to use the method.
Answer: D3 conducts and creates a diode drop above ground (0.7v), the current will flow in series through R1+R2+R3 (total 430ohms). The total voltage across this resistor is 5V - 0.7V = 4.3V. Ohm's law: 4.3V/430ohms = 10mA
Comment: Welcome to EE.SE, Rob. We generally don't solve homework questions but give pointers to the OPs to help them. In this case it may have been enough to suggest that the OP redraws the circuit with the reverse biased diodes removed.
Answer: Since you have mentioned that D3 is ON and rest are OFF. What you can do is --
You can apply KVL across the loop V1-R1-R2-R3-D3 to obtain the current. Once you have the current, you can find the voltage in any part of the circuit.
For obtaining voltage across diodes (say D2), you can obtain voltages at both of its terminals separately using the obtained current from the above mentioned calculation and then subtract them.
i.e. V(D2+) = v1 -I*(R1+R2+R3) or you can just consider the drop across the diode D3 (i.e. 0.7V usually).
Similarly, V(D2-) = v1-I*R1.
Now, voltage across diode D2 would be V(D2) = V(D2+) - V(D2-)
Similarly, you can find the voltage across any component used in your circuit.
Answer:
Current will flow as shown. Once you find the current path you can analyze it as if D2 and D4 were not there. Then you need to find the voltage drop across D3 and account for it. The resulting equation looks like this
I = (5- 0.7)/(100+180+150)

VR1= 100 I
VR2= 180 I
VR3 =150 I
Comment: Please elaborate on why this is the case. Please use proper puncuation.

Diode circuit problem


Fix crack in small blackboard

Question: I had a small slate blackboard in a wooden frame that had a 1/4-1/2 crack in it-enough to see through the crack on other side. Any recommendations on best way to fix this.
Answer: The traditional way to join rock together is mortar.  But I assume you want to continue using this as a blackboard.  What I would try doing is removing the slate from the frame, and remove any kind of backing so that you just have the 2 pieces of slate that are each side of the crack.  Then run a bead of black epoxy on the crack and push them together.  You will have to probably make a fixture of some kind for clamping.  Use a slow hardening epoxy and clean it off the front of the slate.  I would also lay it face down on glass so that the pieces are flat while it's hardening.

Fix crack in small blackboard


Debug shell script in IntelliJ 9

Question: Is it possible to debug a shell script in IntelliJ IDEA 9.0.3.  I hava a shell script that calls a java program.  I would like to set a breakpoint in this java program and debug through it.  I hava a Bash plugin for IntelliJ and have set the breakpoint in the program but it doesn't stop at the breakpoint.
Thanks,
Tom
Answer: You can use Remote Debug to debug the Java program which you run from the shell script. IDEA will suggest you the list of JVM options, add them inside the shell script where you call Java VM. If suspend is enabled, the app will wait for IDEA debugger connection so that you can connect and start the debug session and stop on the breakpoints.
It's not possible to debug the shell script itself in IDEA.
Comment: There is an way now? In 2018?
Answer: Just run the Java program in IntelliJ.  What do you need the bash script for?  Let IntelliJ run your Java program and let it provide the environment and inputs that bash is giving it.
If you do that your breakpoints will work just fine.

Debug shell script in IntelliJ 9


Profit from biomass gasification patent

Question: The inventors are named and the organization is a non profit. who will eventually profit from this patent if it is granted?
Answer: The organization could sell the patent, license it, or otherwise collect revenue from it.
Being a non-profit doesn't mean they can't make money, it means that the company uses surplus revenues to achieve its goals rather than distributing them as profit or dividends.
The Denver Zoological Foundation can quite happily make money from this patent, if and when it issues: http://www.google.com/patents/CA2827105A1?cl=en

Profit from biomass gasification patent


Maintaining session data in Python Flask

Question: I have a client which sends JSON data to a server. This JSON data contains a budget and epsilon value. The server receives the data and checks if the used_budget is None or in other words, if that is the first request from the client. If so, it initializes the used_budget to 0.0.
The condition is every time the client sends a JSON payload, the epsilon value is added to the used_budget and the used_budget is compared with budget. If the used_budget is less than budget then the server queries a database and returns some result to the client else the server should stop accepting requests from the client.
Problem: When I am sending an initial request from a client, a new session is initialized and epsilon is added. The server returns the result to the client as expected. BUT, when I send another request from the client, instead of treating it as a same session, the server initializes a new session and the used_budget value is set to 0.0 again. The condition checking never occurs.
This is the server side code:
class GetParams(Resource):
    def get(self):

    client_request = json.loads(list(dict(request.args).keys())[0])  # Stores the request in JSON format
    budget = client_request['budget']
    epsilon = client_request['epsilon']
    used_budget = session.get('used_budget')  # used_budget used a session variable

    # If Client sends the first request then initialize used_budget to 0.0
    if used_budget == None:
        set_used_budget()

    # Check if client has budget for sending queries for a session
    if (session['used_budget'] < float(budget)):
        session['used_budget'] = session.get('used_budget') + float(epsilon)
        result = write_file(client_request)  # Write request to file and store the returned query result
        print("used budget " + str(session['used_budget']))
        return result # Return the query result to the client
    else:
        error_message = "Budget exceeded - Cannot process queries"
        return error_message

api.add_resource(GetParams, '/data')  # Route for get()
if __name__ == '__main__':
    app.run(port='5890', threaded=True)

Here is the client side code:
# Client sends this data in url
data = {
    'query': 'SELECT count(*) FROM accounts',
    'epsilon': '1.0',
    'budget': '2.0',
}

# Localhost url
url = 'http://127.0.0.1:5890/data'

# Client sends Get request
 session = requests.Session()

resp= session.get(url, params=json.dumps(data))

# Client prints the data returned by the server in JSON
print(resp.json())

# Client prints the response code
print(resp)

The code works fine when I run it from a browser (i.e., sessions are maintained when I use two different browsers) but a new session is started when I ping the server from the client using an IDE. Can anyone tell me what am I doing wrong over here?
Answer: This is happening because flask session works little differently.
The session data is passed to the client along with the response and stored on client as session cookie. When you send the request from browser, browser attached the session cookie to the new request. Such is not the case when you are making a request any request using IDE client. The IDE client is not maintaining any session cookie hence every time a new session is getting created.


Any economical quantitative electrostatics experiments for the university level?

Question: I'm seeking for some safe experiments for undergraduates in the electrostatics context.
We have a Van-de-Graaff generator in our fundamental physics lab but this kind of devices are useful for demonstration, Can they be used for quantitative experiments?
Comment: Quantitative high voltage measurements are very tough. I wouldn't go there. You could basically build a simulated "electrostatic" system with low voltages and high capacitance instead of the usual Faraday cups etc., but that would be an analog computer mimicking the physics of charge transfer. You might as well simulate that on the computer.  In any case you are not teaching metrology but basic physics.
Answer: I assume you have already considered using a cathode ray tube, right?  If not, you can apply a constant/static electric field and deflect the electron beam, which is a nice example of electrostatics.  The electron will undergo constant acceleration and the problem can be nicely linked with the equations used in kinematics from the previous semester.  You can also have the students estimate the force of gravity on the electrons to show that it is negligibly small compared to the applied electric field, which they can test by setting the applied field to zero to see no deflection of the electron beam.
I suppose one could also work with static electricity by using the typical examples of rubbing glass with silk or amber with wool.  Then take the charged object and bring it close to an electric field detector (or just have it attract/repel some object of the opposite/same charge).


Two iPhone Apps with same code base

Question: I want to create two iphone apps with very similar code base. The only differences will be some settings and the UI skin. Instead of creating two xcode project and copy the all the code over. Is there a better way to set this up? for better maintainability? 95% of the code are the same.
Answer: Yes, you can do that. You should not create two XCODE projects as you are already guessing.
For differences in your code for each version, you can use C preprocessor directives. <code>#ifdef</code> and related commands.
For differences in the UI, you can create multiple targets, each one using different XIB files if you want.
For settings differences, you can also create multiple targets, each one using different .info files.
Check out this and this blog entries on using multiple targets within XCODE.
Answer: Add two targets to the same project. Give them different Info.plists (see the "Info.plist" build setting; they do not have to be added to the target); an easy way is to do FooApp-Info.plist and BarApp-Info.plist.
Put "skinnable" resources in app-specific directories, which you add to Xcode. "Get Info" on the directory in Xcode, click "targets", and make sure that only the correct target includes each set of resources).
(You could give files for different "skins" different filenames, but that can easily become unmanageable, and doesn't work for stuff like Default.png which has a fixed name.)

Two iPhone Apps with same code base


why does current flow thru a mosfet contrary to SPICE results

Question: SPICE simulations with LTSPICE showed no current flows thru drain & source of an enhancement n-channel MOSFET with using its SPICE model - yet hooking up 5v 2A power supply across an actual device (IRLB3034PBF) yields full current flow with nothing hooked up to the gate, another words no voltage into the gate, it was entirely not attached. Is SPICE incorrect about current flow?
Comment: Did you measure Vgs?
Answer: A MOSFET's gate is floating and well-insulated thanks to the oxide layer between the gate and channel. As a result, when it is completely disconnected, Vgs may very well be anything depending on handling and other effects. You could have very well deposited enough charge on the gate for the transistor to turn on, merely while handling it. It is almost never correct for the gate of your MOSFETs to be truly floating unless you are doing something highly specialized, such as producing flash memory. You should find that, when the gate is driven in a sensible manner, then SPICE and experimentation will roughly agree.
SPICE just sees the small capacitance and leaves the gate potential at its initial conditions unless influenced to do otherwise.
Comment: @user9762541 That's good to know but it doesn't really make your inquiry very clear. That's completely expected if your ground lug shares potential with the FET's source.
Comment: I usually use floating outputs and the ground lug didnt help, I realized the current diminished only after the source and gate had the same ground reference which was not even earth ground reference.
Comment: Would grounding the gate via the earth ground power supply lug diminish Ids current flow?
Comment: @user9762541 It depends on how the MOSFET is connected. Is it a low-side switch? High-side switch? Some other topology? The parameter that matters is the voltage between gate and source (Vgs), and you haven't specified what the FET's source pin  is actually tied to. For an enhancement-type nFET, positive Vgs tends to cause the FET to conduct, while Vgs = 0 causes Ids to go to nearly zero when other conditions (temperature, Vds) are within the FET's absolute maximum ratings.
Comment: I verified, the ground lug effectively discharges the gate and the current diminishes, if touch the gate with my fingers or something similar the current goes to maximum then diminishes agian if I discharge it with the earth ground reference.


Why does the voltage of my Buck converting SMPS drop when a load is added at the output?

Question: I am building a DC-DC buck converting circuit from first principle with no on chip solution. Output Voltage must be 5vdc with a max current @500mA. input is 20+-4vDc. The problem that I am having is that my output voltage is 7.5vdc once bread boarded, but a 5vdc is required. I can solve this by increasing pull up resistance to the TIP122G but there is still a problem of the 5vdc output not being constant and dropping when a load is added. I think this my be due to my feedback circuit but I'm not sure as to what the problem may be and what I should change in it. Saw tooth generator has a frequency of 50kHz.
Comment: Could you show a photo of the construction? Breadboarding a switcher is not easy. I need more time to study this but at first glance: your ICs don't seem to be decoupled, and 1N4007 is too slow for this application.
Comment: Building a discrete differential amplifier, with an ancient 741 at that, is going to be anything but accurate, you are at the grim mercy of component tolerances. Note that the LM393 has an open collector output.
Comment: Try evaluating at 100mA and at 500mA Iload. If ZERO LOAD, the switcher needs to be on for ZERO time.
Comment: A few quick observations... you have a maximum of 12.5mA to power three ICs, your 741 is going to have trouble with inputs that close to its negative supply and if you're going to drop about 12V across your "switching" transistor you might as well drop the other 3V as well and make it a linear regulator!
Answer: The main problem is the 741 op-amp - you appear to be powering it from a 7.5 volt zener diode yet, if you read the 741 data sheet the implied minimum supply voltage is 10 volts. See table 7.2 in the uA741 data sheet. Try using a modern device and not this crappy dinosaur. Think "rail-to-rail".
Also, I don't see any decouplers on the op-amp power rail.
Answer:
Q5's base is driven from 9.1V through high valued resistors, therefore it cannot saturate properly.
Switching will also be extremely slow due to the 10k base drive. There is no way this schematic will work.
1N4007 is way too slow
741 should be replaced with something more modern
There is no overcurrent protection
C5 is way too low
etc

You should scrap the entire schematic and use a proper, modern, MOSFET-based DC-DC solution (or an integrated, ready-made one, which you can purchase for a few bucks these days).


Is it safe to measure 220Vrms@50Hz on DSO directly?

Question: I borrowed my friend's DSO to complete my project(Hantek DSO5072), but on scope it says CAT II/400V. So is it safe to measure 220Vrms@50Hz with it?
Comment: The more important question may be *why* you want to measure this, as a lot of the reasons get into territory which can easily become unsafe for you and/or the tool.  Exactly what point in what circuit are you hoping to measure, and what are you hoping to learn from that measurement?  Given that is a non-isolated, mains-powered scope, how will the circuit of interest relate to the mains ground?
Comment: You are switching 350V DC. What if there is some ringing in your circuit? The voltage could go above 400V in that case.
Comment: I had a project to make VFD(prototype) where i get harmonics on output and becomes unstable on load change. At these point i have 350Vdc line, that switched by IGBTs. So i want to see the whats actually going on and where is the problem.

I thought it says 400Vdc so i can measure voltage directly. And measuring voltage by stepdown transformer is not a good choice as the output differentiate.
Answer: I see several "scary" elements in your question.
This isn't your DSO, you should use it only to measure "safe" (low voltage) things. When in doubt: only things that are battery powered.
CAT II/400V says something about what the oscilloscope can handle at its inputs. It doesn't tell you anything about your safety.
Also: Why would you need to measure mains voltage?
If that really is your goal, measure the output of a power adapter that outputs a low value AC voltage (so not DC) of 15 V AC for example. These are rare nowadays but were more common 20 years ago.
The issue is that the oscilloscope has inputs that are grounded on one side. Grounded meaning connected to Earth, assuming it is connected to the mains properly, so using a cable with Earth and using a proper Earthed socket. If you then would "measure the mains" there's a large chance that you will get a big spark when you connect the scope. And if you're lucky the Ground Fault detection (if that is present in your house and working) will switch off the mains power.
If you're unlucky you can connect the mains to the scope and then your scope could be mains live meaning you will get an electric shock when you touch it.
You should watch EEVBlog Dave Jones' video on this subject: How NOT To Blow Up Your Oscilloscope
After your added comment: you might need a high voltage probe specifically designed for these kinds of measurements. Most of these are quite expensive, often more than the listed price of your friend's scope.
Comment: *Luckily in my home there's not proper grounding* So you'd rather have a faulty device use **your body** for a ground current. OK, your choice. And what I describe is not a grounding **fault** it is how it is intended to work. That you wave all safety measures away as if they're insignificant shows **lack of respect for high voltage** and that worries me. But again, that's your choice.
Comment: Ok i understand how grounding can be a fault while measuring mains. Luckily in my home there's not proper grounding. So grounding fault is not issue. As you say measuring mains voltage is dangerous than how come this youtuber measures 167Dc rectified with no problem.
Comment: https://youtu.be/sI5Ftm1-jik
Comment: That YouTube video is from ElectroBOOM's channel, he's an EE just like me. He zaps himself for our entertainment (and the views of course). The stuff he does isn't safe but he **knows what he's doing**. He might have a mains isolation transformer hidden under his table so that he can have some control over how much current flows when he gets zapped.
Comment: @user3785133 _"Luckily in my home there's not proper grounding."_ - "Luckily" is the opposite of the word I'd use...
Answer: Generally, no, especially if you don't have a good ground setup or don't understand about mains wiring (such as the difference between ground and neutral for example) and general knowledge of line voltage safety.
220V AC is actually over 600V peak-to-peak (+/- 311V), pretty close to the limit of your friend's scope. Your line voltage may actually be 230V, and maybe even higher than that, say by 10%, so as high as 253Vrms. That's 358V peak!
At that voltage all it would take is a spike from some other source, like a switch opening to a motor, light ballast, or some other inductive load to fry the scope input.
Then there's the question of grounding. The scope probe ground is the scope frame ground. If you just connect it across the line you have a 50-50 chance of connecting line voltage to ground- popping the breaker if you're lucky, but certainly doing bad things to the scope. How do you know? That business about neutral and ground I mentioned earlier: you need to understand this.
TL; DR version: no, it's not safe.


Efficiency of a Carnot machine, in which, some of its extreme points are in the region of liquid transition to steam

Question: I need to calculate the efficiency of a Carnot machine, in which, some of its extreme points are in the region of liquid transition to steam with the works, differences of energy and heats of each section.
I'm not very sure how start this, so any help is welcome!
Comment: Can you describe your particular Carnot cycle in more detail?
Comment: You are asking questions about a Carnot cycle as a two phase steam power cycle. I suggest you google "the Carnot cycle as a two phase power cycle" and click on the mit.edu hit. Then, if you still don't understand it, come on back. Good luck.
Answer: A Carnot engine is defined as a heat engine process that absorbs heat isothermally at two temperatures, $T_{1}>T_{2}$, with the transitions between those two temperatures being adiabatic (so that no heat is exchanged).  The efficiency $\eta$ is defined to be the fraction of the heat $Q_{1}$ the system takes in while at $T_{1}$ that is converted to work $W$; that is $\eta=W/Q_{1}$.  By energy conservation (the First Law of Thermodynamics), the total heat taken in at $T_{1}$ must be equal to the work $W$ plus the heat expelled at the lower temperature $T_{2}$.  (Remember that while the system is transitioning between the two temperatures, no heat flows in or out.)  Therefore $Q_{1}=W+Q_{2}$, and the efficiency can be related to the ratio of heat flows $\eta=1-Q_{2}/Q_{1}$.
What is particularly amazing about a Carnot engine is that this efficiency can be expressed in terms of just the temperatures $T_{1}$ and $T_{2}$, rather than the exchanged heats $Q_{1}$ and $Q_{2}$.  This is very helpful because it is generally much easier to measure the temperature at which the system is operating than the heat transfer.  This allows you to avoid the difficulties of dealing with the equation of state, provided you know the upper and lower operating temperatures.  (There is a complication, since the equation of state also determines what the adiabatic paths between $T_{1}$ and $T_{2}$ are, but there are ways to make the paths very nearly adiabatic without detailed calculations; the system can be thermally isolated, so that no heat transfer is possible; or the adiabatic paths may be traversed very quickly, so that there is no time for appreciable heat transfer.)
For an isothermal process, the heat exchanged is (by the Second Law of Thermodynamics) $\Delta Q=T\Delta S$, in terms of the entropy $S$.  No entropy enters of leaves the system except during the isothermal processes at $T_{1}$ and $T_{2}$; and no entropy is ever generated, since the whole Carnot cycle is reversible.  Therefore, the entropy changes $\Delta S_{1}$ and $\Delta S_{1}$ appearing in $Q_{1}=T_{1}\Delta S_{1}$ and $Q_{2}=T_{2}\Delta S_{2}$ are equal:  $\Delta S_{1}=\Delta S_{2}$.  An amount of entropy is absorbed by the system at the high temperature $T_{1}$, and an equal amount is expelled at the low temperature $T_{2}$.  This allows us to express the key quantity $Q_{2}/Q_{1}$ that appears in the efficiency in terms of the relatively easily measured temperatures; and the final formula is $\eta=1-T_{2}/T_{1}$.  The efficiency of the Carnot engine depends only on its two operating temperatures, not on anything else.


About the integral closure of a DVR inside a galois extension of function field with two variables

Question: Edit:
I see my mistake now (murphy),
w(X + Y) = min(w(X), w(Y)) only when the valuations are not the same.
I have the following algebraic problem, which I encountred after thinking about blowups.
My problem is as follows:
let $k$ be a field, and let $k(X, Y)$ be the field or rational functions over $k$ in $X,Y$.
letting $S_1 = S_1(X,Y) = X + Y$ and $S_2 = S_2(X,Y) = X Y$ be the symmetric polynomials in $X,Y$. we can form the subfield $k(S_1, S_2) \subset k(X,Y)$.
Now, let $R = k(\frac{S_2}{S_1})[S_1]_\mathfrak{p} \subset k(S_1,S_2)$ where $
\mathfrak{p} = (S_1)$ is the ideal generated by $S_1$. (i.e. $R$ is the localization of $k(\frac{S_2}{S_1})[S_1]$ at $\mathfrak{p}$)
and let $A$ be its integral clousre inside $k(X,Y)$. (elements of $A$ are elements of $k(X,Y)$ which are integral over $R$)
we have the following image:
$\require{AMScd}$
\begin{CD}
A @>>> k(X,Y)\\
@AAA  @AAA\\
R @>>> k(S_1, S_2)
\end{CD}
Now, I have a good reason to believe that:

R is a DVR, with uniformizator $S_1$ (and also $S_2$)
A is a DVR - as the integral closure of a DVR inside a finite (even galois) field extension.(with valuation $w$ that extends the valuation of $R$

$X, Y$ are roots of the polynomial $(T-X)(T-Y) = T^2 - S_1T + S_2$ which is integral over $R$, hence $X,Y$ are in $A$. since $S_1$ and $S_2$ differ by a unit, they share the same valuation under $w$ and we get the following set of equalities:
$min(w(X), W(Y)) = w(S_1) = w(S_2) = w(X) + w(Y)$
which implies either that $w(X) = w(Y) = 0$ or that one of them is $-\infty$ both are impossible.
What am I missing?
I encountred the problem after thinking about the following picture:
let $C = A_k^1$. we have a morphism $C^2 \rightarrow C^{(2)}$ where $C^{(2)}$ is the symmetric product.
blowing up the symmetric product at the point $P=(0,0)$ we get the following diagram:
$\require{AMScd}$
\begin{CD}
Z @>>> Bl_{(0,0)}(C^{(2)})\\
@VVV  @VVV\\
P @>>> C^{(2)}
\end{CD}
the local ring at the generic point of $Z$ is $R$, which lives inside the function field of $C^{(2)}$. (this is also why I believe it is indeed a DVR, because $Z$ is of codim 1)
and A is the integral closure inside the function field of $C^{2}$
The above is obviously a contradiction, and after thinking for a while, I can't find my mistake, and would love to get some help :)
Answer: $w(S_2)=w(S_1) = 1$
Both $X,Y$ are roots of $T^2-S_1 T+u S_1$ with $u=S_2/S_1$, this polynomial is Eisenstein at $(S_1)$ so $w(X)=w(Y)=1/2$


How to create a stablecoin pegged with gold (a gold-backed token) using ERC20

Question: How to create a stablecoin pegged with gold basically a gold-backed token using ERC20, example 1Token = 1mg gold, what are the essential functions or steps need to take care, our customer is planning to reserve some value of gold in Gold contracts, if there is a sample contract that would be fine.
Answer: The smart contract wouldn't know about the gold. You would create a usual ERC20 token, including mint and burn functions that only you can use.
You would also have a vault of gold in a building with armed guards.
When someone puts gold in the vault, you call the mint function to create some tokens on the chain. When someone takes the gold out of the vault, you call the burn function to delete the tokens. If they don't have the tokens, you don't let them take the gold from the vault.
Every month or two, you get an auditing company to count the amount of gold you have, check that it is really gold, and compare this to the number of tokens minted. You publish this report on your website and theirs, so that people know you aren't lying about the amount of gold you have.
Comment: Thank you for your reply, but it's not cleared my requirement , i will give some more details here... basically we want to create a ERC20 token, an utility token that always mapped with stable value here with 1mg of gold value, so user who owns a token will have value of 1mg of gold.  So how to create a token with have such stable value as like other stable coins like USDT which mapped with 1 USD always.  Customer is ready to reserve some gold value in custodian account/contract. Please let me know
Comment: @PrabhakaranRajagopal You have to promise that anyone who has a token can give you the token and they can pick up 1mg of gold from your office or you will mail it to them. And people have to believe you.
Comment: i don't think it make sense, since we going to develop an dApp and we want to reward tokens (ERC20) to our communities and those tokens should have some stable value (like a stablecoin 'paxg') that's it..
Comment: @PrabhakaranRajagopal PAXG works because they promise anyone who has a token can go to their office and get some gold (actually I think it is more complicated but they can still do it). Maybe your smart contract can have some PAXG, so anyone who has a token can go to the smart contract's office (the blockchain) and get some PAXG, then they can go to PAXG's office and get some gold?


ASUS ROG GL752VW Ubuntu installation issues

Question: I use ASUS ROG GL752VW laptop with 960M series Nvidia Geforce graphics card. I tried both nomodeset and nouveau.modeset=0 to install Ubuntu 16.04 but it shows GRUB error in the last part of installing Ubuntu. How can i install Ubuntu 16.04 perfectly in my laptop?
Thank you.
Answer: having the same laptop model, this worked for me:
Installation of Ubuntu 16.04 from a USB drive freezes
try adding either "acpi=off" or "acpi=force" in the GRUB menu then you should be able to boot from the live USB
Answer: I have the same notebook and I couldn't for the life of me install Ubuntu as a second OS alongside Windows.
So what I did is:

disable Secure Boot in BIOS
boot the USB drive in UEFI
install Ubuntu 18.04 with Erase Disk option
re-enable Secure Boot in BIOS (I did this because I used to receive and error along the lines of "UEFI db could not be loaded/found" and this solved it)
at this point I still had major problems with booting into Ubuntu, but at least I could get to the GRUB loader so I booted Ubuntu in Recovery Mode
I used a terminal to modify the GRUB and I set acpi=off

After that last step it worked like a charm.
Another piece of information I can give you regarding that installation error about grub (something about grub-efi-amd64) is that one way to solve this is by creating another partition of ~500-1000 mb as an EFI Filesystem Partition as per this video: https://www.youtube.com/watch?v=OMCfS8CDW0c&t=321s
I have to warn you though, this completely messed up my computer. After doing this I couldn't get any OS to boot and got an error message similar to "Please restart and choose a proper boot media...".
PS: I am a complete newbie to Ubuntu/Linux, I've just thrown my two cents in the hopes that it could help.


Push Notification in Titanium Android Application

Question: I have my Titanium Application for Android and now I want to implement Push Notification for Android in Titanium. I have my back-end service which get all notifications for me but I don't have knowledge about Google Cloud Messaging and what are the relation between them (i.e Push Notification and GCM). Please Provide me guidelines and way how to do it. Thanks in Advance!
Answer: Doing push notifications with Titanium is probably going to require a 3rd party service, most, if not all, are subscription fee based.
I've been looking to this myself for some planned future projects using either Titanium or Apache Cordova(Phone Gap).
The most popular recommendation I've been getting is Urban Airship It looks like they have some pretty nice features, but I haven't looked much further into it than that.
Answer: For Titanium, you can use this module (Open Source): https://github.com/liccowee/Google-Cloud-Messaging--Titanium-.
In examples, you see how to implement it in your app.


Integer Polynomial Perfect Square Question

Question: Let $f(x)\in \mathbb{Z}[x] - \mathbb{Z}$ with all roots distinct in $\mathbb{C}$. I need to show that for infinitely many $n\in\mathbb{Z}$ we have $f(n)$ is not a perfect square. Any help would be greatly appreciated :)
Comment: I don't know if this will work, but if $r$ is a quadratic residue mod $m$ and you find one solution to $f(n) \equiv r \pmod{m}$ then all $r+km$ satisfy your condition.
Answer: Consider the polynomial $F(x,y)=y^2-f(x)$. It is obviously irreducible since $f$ is square-free in $\mathbb{Q}[x,y]$ and thus we can apply Hilbert's Irreducibility Theorem to obtain an infinitude of $x_i$ such that $y^2-f(x_i)=0$ is irreducible or equivalently $f(x_i)\ne{}n^2,\forall{}n\in\mathbb{N}$. This means that the infinite $f(x_i)$ we found are not perfect squares.
Comment: Do you know a more elementary proof by any chance?
Comment: Sadly nothing comes to mind
Answer: According to this https://mathoverflow.net/q/224881 it is a "well-known" fact that if $f(n)$ is a perfect square for every integer $n$, then $f(x)$ is a perfect square (as a polynomial.)  Since the roots of your polynomial are distinct, it can't be a perfect square, so there exists an integer $m$ such that $f(m) = b$ is not a perfect square.
Then, according to this https://math.stackexchange.com/a/646135/362009 there exists a prime $p$ for which $b$ is a quadratic non-residue.  Then for any integer $k$ we have $f(m+kp) \equiv f(m) \equiv b \pmod{p}$ and so we have infinitely many integers for which $f(n)$ can't be a square.
Comment: The Davenport, Lewis & Schinzel results are also [mentioned on this site.](https://math.stackexchange.com/a/1157825/242)


how do we create turtle geometry in three.js?

Question: We are trying to create a simple programming environment that lets people generate 3D forms (it's inspired by the Scratch project).  We'd like it to work in a "turtle geometry" fashion, where a creature (we call it the beetle, by analogy to the logo turtle) moves around the 3D space, and can leave objects along the way that take on its position and orientation.
We are currently using Three.js.  While you can move and rotate objects, it's not clear how to create the effect we want, where translations and rotations "accumulate" and can be applied to new objects. We'd also like to store a stack of these matrices to push and pop.
Here's a specific example.  The user of our system would create a program like this (this is pseudocode):
repeat 36 [
  move 10
  rotate 10
  draw cube
]

The idea is that the beetle would move around a circle as it executes this program, leaving a cube at each position.
Is this possible using Three.js? Do we need to switch to pure WebGL?
Comment: Obligatory link: http://stackoverflow.com/questions/1003841/how-do-i-move-the-turtle-in-logo
Comment: What would `rotate 10` mean in a 3D context?  About which axis and point?  Nice project though.
Answer: You might have a look at
http://u2d.com/turtle_js/index.html
It uses JavaScript systax though.
And it does not have a feedback in case of errors. The turtle just does nothing.
Answer: The requirements sound fairly high-level. There is no reason you would need the low-level access of raw webgl. A higher-level library like three.js, or another, would do just fine.
As @Orbling pointed out, you'd need to figure out rotation for 3D; e.g.
rotateX 10

(rotate 10 degrees counterclockwise around x axis), or
turnLeft 10

(rotate 10 degrees counterclockwise around current up vector).


Capacitor in DC DC converter

Question: As part of my circuit, I need to step down voltage from +15V to +-12V. For this purpose, I am using Traco TEN 20-2422WIN. I was going through its application note when I saw that they because of EMI, advice to connectC3 and C4 between input and output. Can anyone elaborate on possible reasons for this
Comment: EMI == black magic
Comment: Ha every time I get embroiled in something EMI-related at work, I do my best to shift myself on to literally any other project :)  My advice?  Copy the application circuit and don't worry too much about it!
Comment: @Selvek Care to decode the magic tricks?
Answer:
C3,4 1000pF is much smaller Z than the input and output Z yet lower ESR. It it is a form of differential input and output negative feedback to lower the output impedance with rising frequency within driver's bandwidth that works for this unit. So it affects some f>>1/RC for abrupt load changes.

Pulsed high current loads can lead to transients on both output and input.  Most often these transients cause interference on the sensor cables due to common mode unbalanced impedance in micro or milliohms between Vout and Ground frame.
The input you show for AC is called a "Line Filter" and for DC often called a BALUN to balance unbalanced differential power or signals by raising the series impedance and cross-winding connections to then cancel so the differential impedance is low but Zcm is high thus less stray EMI current to nearby inputs or cables.
The output cap must follow the OEM's recommendation and is often distributed to each load with single or multiple parts to stored surge energy and thus reduce stray current loops and voltage spikes.
By the way, your converter boosts voltage on the output to 24V split (dual 12) outputs, so current must be increased on the input to consume the same power (V*I) plus losses.
More detailed answers may be researched on PSU EMC or EMI reduction for power supplies for electromagnetic compatibility. (EMC)
Comment: 1000pF is much smaller than the loads, but it is a form of negative feedback to lower the output impedance with rising frequency within driver's bandwidth that works for this unit. So it affects some f>>1/RC for abrupt load changes
Comment: if a step load is I then dV/dt=Ic/C is the slew rate  of the voltage spike and this <10us transient is best buffered by additional output caps as required with ultra low ESR. Each application can differ, so OEM Application Notes is best start.
Comment: If your load is more or less constant then it is not always needed but may help reduce ripple noise to desired levels.  e.g. 270 µF max  with xx mOhm ESR
Comment: Regarding the 'step down ', my  mistake. Regarding your answer, I understood the first two paragraphs but not the one regarding the output cap, but I'll do more reading in detail as you advised
Comment: I understood your point but can't the purpose of delivery energy during load transient (and limiting dv/dt) be also served with a low ESR cap between +- Vout and com? Why connect between Vin and Vout. Is it because of the ability to store higher energy in those caps due to more voltage difference between output and input (and hence can be done with a smaller cap). Let me know if I have got it all wrong
Comment: @ Tony EE Can you give more details on this negative feedback effect?
Answer: This is how I'm envisioning those two OUT_IN capacitors C6 and C8:

simulate this circuit – Schematic created using CircuitLab

Capacitor in DC DC converter


When working with polyurethane glue, how long does one have to clamp the components?

Question: I am going to be building some shutters for one of our windows and because of its location, planned on using polyurethane glue, specifically Dap Polyurethane Construction Adhesive. Each shutter will be made of four five-inch boards, dowelled and glued together. They will be clamped in two dimensions, one to compress the individual boards together and the other to keep the shutter flat. Each of the shutters is 76½ inches long and twenty inches wide.Once the glue is applied to the boards, dowels, and holes, the clamping process will probably take several minutes. How much time do I have to get everything together before the glues is too dry?Edit: I am planning on using five clamps to hold the boards together and two to keep the whole thing flat.Edit 2: The boards are pressure treated.
Comment: This is the stuff in a rigid plastic tube, dispensed with a caulking gun correct? If so wrong thing for this application. Construction adhesives aren't really suitable as wooden joinery adhesives because they're so thick. Assuming your joinery is well cut (tight joints) you'd actually be better off using standard polyurethane glue, e.g. the original Gorilla glue.
Comment: @Graphus, these shutters are going to be installed on a side of our house that gets full afternoon sun and the brunt of winter storms. As far as I could tell this stuff was the best for this application. I have a table saw on which to cut the boards, so the joints should be tight.
Comment: This basically isn't a woodworking adhesive. The product description and relevant data make it clear it's intended for flashing etc. Any standard adhesive sold for exterior use would be preferable.
Answer: As a more general answer, all glues will include directions/instructions which will specify the working/open time (how long you have to get everything aligned and clamped), the amount of time to remain clamped and a full cure time.
These times are approximates as temperature and humidity can play a role in the overall time, so assume the times given are for average temperatures and humidity values.  Usually warmer temperatures mean faster cure times.
You should pick a glue that has appropriate times for your specific project needs.
Comment: I read the instruction on the tube and don't see anything about working time.
Comment: If not on the label them a quick google turns up http://www.dap.com/media/73592/polyurethane-sealants.pdf.   "Product is tack free in 3-6 hours and will achieve full cure in 4-7 days, depending on joint depth,
temperature and humidity. "
Comment: I too found that same PDF, but unless I'm totally blind, I don't find anything in it that specifies open time. There's some stuff about tack-free time and cure but nothing about how quickly one's work has to be clamped.
Comment: @BillOertell it's not glue, it's construction adhesive...


Magento 2.0.2 Upgrade: Sorry, we can't take that action right now

Question: I get this message when I try to upgrade my Magento 2.0.2
Sorry, we can't take that action right now.

Cronjobs works, no migration tool
Repositories already in composer.json file and no data migration tool
Logged in and key saved
Answer: As soon as you used composer without the web wizard once to install Magento or extensions, the web wizard does not work anymore.
Solution: Switch to the command line and update using composer. To see how that works, read How to update Magento2 using composer
Answer: Are you upgrading from the admin?
Have you added your public & private key from your Magento Connect acc?


How to determine the age of an old galaxy?

Question: Recently a galaxy A1689B11 was discovered, having an age of 11 billion years. How that age was determined? News sources reported that some cutting edge technology with gravitational lensing was used. Can anyone explain the exact procedure?
Answer: When the article speaks of the "age", what it means is that we are seeing that galaxy as it was a long time ago. We are seeing it as a very young galaxy. The galaxy is very far away, so light has taken a long time to reach us from the galaxy. The light from the galaxy is 11 billion years old. We measure the age of the galaxy by finding its distance from us.
To find the distance we use the Hubble Law, which states that the further away a galaxy is, the faster it moves away from us, due to the expansion of the universe. And we can measure the speed that the galaxy is moving away from us because when an object moves very fast, the light from that object becomes shifted towards longer wavelengths (red-shifted). By measuring light that is known to have a fixed wavelength when not red shifted, we can find the speed of the galaxy accurately, and then use the Hubble Law to find the distance, and hence the age of the galaxy. (source)
A1689B11 has a redshift z=2.54 which corresponds to a light travel time of 11.1 billion years
Gravitational lensing makes the galaxy brighter, so it can be observed at these immense distances, it isn't directly used for finding the distance, but without gravitational lensing, the galaxy wouldn't be visible.
Comment: @Gauti : it's like you see a movie made in 2008, and there's very young child called Abe in the movie. You know Abe is now at least 11 years old. You haven't actually measured his age, you've inferred it from something else.
Comment: I think you may be confusing the age of the galaxy, with the age of the light that is coming from the galaxy. See my edit.
Comment: finding distance is alright. But what is the relation between distance & age of galaxy ? Can you explain lucidly. I did not completely get hold of the paper. Thank You
Comment: @JohnDuffield : so this age for galaxy is lower limit.  Thanks


Script to assign and remove arbitrary secondary IPs to an interface

Question: I'm trying to figure out how to write a script that will let me arbitrarily assign and remove a secondary IP address to a system.  I'm most comfortable with batch scripting, so I'd rather focus on solutions for that, if it's possible.
I'm pretty sure I've figured out how to take user input and use it to configure a new IP address and gateway.
The batch script below is written for an interface named "LAN".
SET /P NEW-IPADDR="Enter IP:"
SET /P NEW-MASK="Enter Subnet Mask:"
SET /P NEW-GW="Enter Gateway:"
netsh interface ip add address name=LAN addr=%NEW-IPADDR% mask=%NEW-MASK% gateway=%NEW-GW% gwmetric=0
PAUSE

The PAUSE is inserted to allow an opportunity to check for errors in netsh before the console window automatically exits.
I'm sure the script could use some extra statements for error checking (to work around empty user inputs, or validate that inputs match the pattern of an IP address).  But what I'm worried about figuring out right now, is how to clear previously-set secondary IP addresses.
One easy option would be to just set the script to clear all IPs every time, and have a line pre-written that automatically sets up the primary IP before prompting for the secondary.  Ideally though, I'd like the script to only be working on secondary IPs.
Option two is to change the last line of the above script to the following:
ECHO "Secondary IP address configured.  Press any key to remove secondary IP."
PAUSE
netsh interface ip delete address name=LAN addr=%NEW-IPADDR% gateway=%NEW-GW%

However, that requires trusting that the script will not be abnormally terminated during the PAUSE.  Not exactly something you can really rely upon.
Another option would be to have the script store the secondary IPs that it configures somewhere permanent, so that it can pull the values later and only work with those.  It's easy enough to get the values into permanent storage (ECHO "%NEW-IPADDR%" > SecondaryIP.txt && ECHO "%NEW-MASK%" >> SecondaryIP.txt && ECHO "%NEW-GW%" >> SecondaryIP.txt) but now I have two problems:

I don't know how to get the data out of that text file, in a way that's usable by the batch script.  (I'm sure this can easily be fixed.)
This relies upon the script being the only thing that touches the secondary IP.  A bit more trustworthy than the script exiting normally, but still not quite 100%.

The ideal option would be a script that can recognize a "Primary IP" as opposed to a "Secondary IP" and only work on the latter.  Is there a way to do this?
I need a method that's compatible with a standard Windows XP build or later, with little to no usage of third-party tools.  Although I'd rather do this in batch, I'm also interested in learning more about PowerShell and it is installed on the systems where I'll be using this.  So, PowerShell-based solutions are welcome also.
Answer: I can't come up with a complete answer, but this may help put you in the right direction.
You could use netsh from PowerShell to dump the current configuration..
netsh interface ipv4 dump >C:\netsh.txt

This should give you something like this:
# ----------------------------------
# IPv4 Configuration
# ----------------------------------
pushd interface ipv4

reset
set global icmpredirects=enabled
add route prefix=0.0.0.0/0 interface="WAN" nexthop=192.168.1.1 publish=Yes
set subinterface interface= subinterface=ethernet_6 mtu=1492
add address name="WAN" address=192.168.1.200 mask=255.255.255.0
add address name="WAN" address=192.168.1.210 mask=255.255.255.0

popd
# End of IPv4 configuration

You can do 'grep' and 'sed'-like operations on the resulting text file, using the information here.  This is the bit that I cannot detail without spending more time on it, because as you can see above, the lines for the addresses have an identical format.  Your script will have to grep both the address lines to variables, and you will only sed the second variable.
You can then run the edited configuration script with..
netsh exec C:\netsh.txt

Note that ipconfig will show both new and old configuration data until you reboot, but it should appear correctly in the GUI, I think.


Passing GeoNodes attribute to Shader frame offset

Question: I am trying to pass a geometry nodes output attribute (an integer) to the shader editor to control the offset of an image sequence.
I have succesfully done this to pass the attribute and change , ie: the color in the shader.
But, As the image sequence offset does not have an input...
I have tried to do so using Drivers... but I am missing something about how to pass the attribute to the frame offset
I havent found any answer searching..
any help?
regards
Comment: I have managed to pass the value of the output from the Group Output (an integer) by copying the Drivers and pasting in the shader editor (bpy.data.node_groups['Geometry Nodes'].nodes['Group Output'].inputs[2].default_value ). BUT, this only udates the value if I change the value manually in the within geonodes. If I plug the valur to another integer socket that changes , then it does not update.... ¿Why?
Comment: Image sequence offset is the same for all shader pixels, you cannot use a different image for different parts of the surface (that's why the value is not a socket). If you need that, a better option would be an image atlas and offsetting UVs.
If you just want a single image and drive the offset with GN, you could encode the value in a vertex position, use an Empty with a location constraint, add a vertex group to make it follow a single vertex. The Empty location can then be the input for a driver in your shader node, extracting the offset value again. Convoluted but it works.
Comment: I just want to change the whole image for the whole object using the sequence. What I dont understand, is why it works if I insert by hand the FRAMES value in the group output, and it does not work if I use an integer node or any other variable node.
Comment: When you read the value from the group output node it's a fixed number in the node tree, whereas the geometry nodes output is a (temporary) mesh. You can't get the result of the nodes math from the node tree itself. It's like the difference between reading source code and actually executing that code.

I'll see if i can make a quick example for using the node result in a driver ...
Comment: Ah.. curious.... so.. how to pass a value? I have tested a similar setup to pass the color and a material to the saher and it works....  difficult to get the concept. Thanks
Answer: How to expose geometry nodes result as driver inputs:

Compute some value in geometry nodes. In this case it's going to be a frame offset, so I calculate some integer number.
The mesh only has a single vertex. You could output multiple values in different vertices, but for simplicity I'll stick to 1 vertex only.

Add the mesh vertex to a Vertex Group.
Add an Empty object. This will be the thing that the driver can actually use.
Add a Copy Location constraint to the Empty. Set the single-vertex-mesh as target and the vertex group. Now the Empty will follow the position of our single vertex, which in turn encodes the frame value we want to output.

Finally add a driver to the image sequence node as before. Use the Empty object's X position as the driver variable. Now you can change the values in geometry nodes, the Empty will follow the vertex position, and the driver will change the sequence offset accordingly.
Comment: Thank you. I willstudy this setup and try with mine. Thanks


Why are 5 runs awarded if the ball hits the helmet?

Question: Why are 5 runs awarded if the ball hits the helmet behind the wicket-keeper?
Is it mandatory to keep helmet in ground? To avoid 5 extra runs, can fielding team  keep the helmet outside the ground?
Comment: I'll not post this as an answer until I can confirm it is as fact but I will speculate the following:  The ball has been obstructed so a penalty is given.  5 runs is between the 4 and 6 that can be awarded for reaching the boundary so 5 fits nicely as an "arbitary" amount.  Like I say, I need to confirm this.
Comment: To clarify, if the batsman hits the ball first onto the helmet (that is on the ground behind the keeper) is that 5 penalty runs or 5 runs to the batsman who may have reached the boundary?
Comment: @John It is 5 penalty runs, scored as extras, which do not go towards the batsman's personal score. The ball is then dead, so no boundary can then be scored from it. However, any runs completed before it hits the helmet would be counted, as well as any run in progress.
Answer: It is given as a penalty for stopping or obstructing the course of the ball.
Comment: I think these are strange objections. If you want a 'why' then the question has no answer. Why is hitting the ball the boundary given 4 runs, and hitting it over given 6? It just is.
Comment: But why *five* and not, say, eight or twelve?
Comment: This doesn't really answer the question. The question is "Why?" and you say "Because it is."
Comment: Why "five"..? All penalty runs are 5. Eg. if a batsman runs on the danger area of the pitch five runs is awarded to the opposition team.
Comment: But why did the ruling body choose *five runs?* They could have picked eight! Or twelve! Or seventeen! What significance is 5? Is 5 the average number of runs a person can make in the same bowl? Is 5 just easier for a ref to count?
Comment: The answer is, the helmet obstructs the course of the ball. which is illegal in cricket.
Comment: @Aarthi 4 runs for a boundary , 5 runs for penalty  are all defined by crickets ruling  body.
Answer: The 5 run penalty was first introduced in 1798: Penalty of 5 runs if a fielder stopped the ball with his hat. Why 5 and not some other number? We can only assume the law makers felt that 6 was too harsh and 4 too lenient.
Answer: I rekon its because A 6 has to be over the rope on the full without touching the field.  So if the ball hits the helmet on the ground it was never gunna make the rope without touching. So 5 is the highest it can be, 4 for a boundry u could of scored plus an extra 1 for the obstruction.
Answer: It is regarded as a penalty. And has been approved as the law of game.
Comment: This doesn't give any more information than the other answer, and neither answers the actual question: why five runs?


Does WebDriverJS/WebDriverIO promises make javascript the language of choice for Selenium?

Question: I don't believe any other Selenium-compatible language supports promises which seems like a game-changer when it comes to dealing with waits.  Since no other Selenium-compatible language supports this, why would anyone use another language?
Comment: Today, almost every language that can interact with Selenium has (composable) futures & promises (see [Wikipedia](https://en.wikipedia.org/wiki/Futures_and_promises#List_of_implementations)). For instance, Java provides [`CompletableFuture`](https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/CompletableFuture.html).
Comment: I just saw that promises are actually part of the WebDriverJS API, which is probably what you are talking about and indeed unique. [Here](http://blog.scottlogic.com/2015/03/04/webdriverjs-and-promises.html) is a related blog post in case someone else gets confused as well.
Comment: Niels writes in his answer that support for promises will be removed in future versions, IIUC. Maybe developers will learn in time that trying to subvert standards with proprietary extensions does not work that well long term.
Answer: TL;DR: convenience of programmers not the only deciding factor when selecting the implementation language.

Promises are necessary when programming page events and response to asynchronous AJAX calls.
But for browser automation testing (which is supposed to mimic user's interaction with a page), they are not necessary at all. User usually initiates an action, waits for the results, and then initiates another action depending on the results. User rarely starts two different actions simultaneously.
So for mimicking the user, rich library of waits is more helpful, like Python's ExpectedConditions.
Also, asynchronous processing is much harder to reason about.
Because debugging code is twice as hard as writing it, if you write code as clever as you can, by definition you are unable to debug it :-)
So promises are clever and necessary evil for GUI developers, but for test automation they add superfluous complexity. Asynchronicity adds value for GUI, but in test automation, maintainability and code flexibility is much more important, IMHO (to deliver reliable tests for a lower cost).
Also, JavaScript is far from preferred language for many teams, and if you have few thousands test written and maintained for your application in different language, there is little value of throwing it all out of the window and start with JavaScript. For team starting on a green field, limiting to single language for both GUI development and automated tests might make sense, but for legacy projects - not so much.
And Python is also excellent language (superior to JavaScript, IMHO) to automate text parsing, system administration etc, which are important part of test automation. I do not see benefits of switching all these tasks to JavaScript.
JavaScript is slowly improving, and it is likely here to stay for GUI development for a long time, but Python is likely the closest language to the one programmers will be using 100 years from now: read The Hundred Year Language by Paul Graham who coined the term "blub paradox" - btw this article is promoting Lisp, not Python, but also worth a read.
I am not rejecting promises (it is a clever concept and very useful for even-driven programming), but reliability of automated tests requires different concepts, like data-driven programming.
Our GUI developers are creating some unit tests in Protractor, but we feel that Python is better fit for most of the other test automation tasks.
Another aspect: duplication of effort is acceptable if quality is extra important, like in aviation: many aviation components use two sets of processor, from different manufacturers and programmed by two different teams in two different languages, to detect subtle misunderstanding in requirements, undetected errors in CPU, interfaces, etc. In such situation, using different language for testing would be not just an option, but a requirement. In a similar way, one of my friend was using C++ (for speed) when writing Wall Street trading algorithms, but scripting language for testing them (for productivity). I hope nuclear power stations are handled like this too, but have no personal experiences with it :-)
Answer:
Why would anyone use another language?

Documentation and number of answered questions on sites like stackoverflow. Languages like Java give much better search results. We use JavaScript and WebDriverJS, but sometimes it is hard to find an answer when you are stuck.

Promises are a game-changer when it comes to dealing with waits

Yes, but not per se a positive one. Promises could lead to deep nesting or you have to add the await/async keyword everywhere. It adds an extra complexity to coding that most test engineers do not have a good understanding of, although this is getting better due to the increased use of modern JS frameworks in teams.
To handle the new complexity the WebDriverJS team added a promise manager, which they are now going to remove in the near future.
Personally I think a procedural flow for tests is fine and maybe even better, because it is easier to grasp. Just like Peter described in his answer. Users do not do their actions async on a website. They click and wait.
Comment: Thanks about the interesting link about future promise manager removal. +1. I agree with you completely that procedural flow is easier to grasp mentally, so it leads to more manageable test which work as expected also **after many changes**. Maybe developers will learn sometimes that  **no single technology is a silver bullet**. It is easier to grasp for old hands, who've seen buzzwords come and go. :-)


Convey some message to all users

Question: Is it possible to write a shell script that enables any user (may not be root) to set a message(e.g. "Download on progress do not turn off" etc.) which will be conveyed like pop-up message (zenity or notify-send) to all other users. If any user is not there at the time of throwing the message they must get it on login or unlocking their screen.
Answer: Nice question. Will give just an half answer... just a seed to see if someone can prepare something starting on this. I have tested this in my system, two users (ubuntu and romano, the two administrators).
I go to a VC and log in as ubuntu --- then I run
sudo sudo -u romano DISPLAY=:0.0 zenity --warning

(the first sudo switch to superuser, the second sudo execute zenity as the user romano)
from a virtual console, the message will appear in "romano" graphical environment.
I suppose that with a bit of mangling the output of w to get the DISPLAY and the users and looping over them it would be possible to have a working solution. Non-graphical connected users can be informed using wall.
I see really difficult to do that without superuser privileges, tough.
Comment: Yes,that will not work on non logged in users. For them I suppose something should be added to system startup files... For example checking the existence of a file and showing its contents. Tricky.
Answer: If you don't find a direct solution, problems like this can be solved by creating a (simple, in this case) daemon program that runs with elevated privileges and runs when the system starts.
Then, a regular user user can put a file somewhere the daemon will see it or send the daemon a message and the daemon can then do whatever action required elevated privileges.
You just have to be careful what input the daemon accepts so you don't open any security holes in your system.
There is an almost unlimited variety of things that can happen when you pass an unedited character string to a bash script running with elevated privileges! For that reason alone, it would be much better if your daemon were written in a language such as Python where you can do whatever you want to an incoming string before the system gets any chance to interpret/execute its contents.
For users logging in, you can probably add a few lines to /etc/profile which tell the daemon to issue any messages the user needs to see. If you do that, you should probably also do something to avoid unnecessary repetitions when the user logs in again. That's more work, but will keep alerts from turning into nagware.
Answer: I think what I did is really a bad way to do things. Anyway it works upto a certain level. Any suggestion to improve the script or a better script is always welcome. I tried to do this with the help of the answers given by Rmano and Joe.
I have created a file at /home/message.txt which has permission -rw-rw-rw- so that any user (may not member of sudo gropu) can write their message in it. I have written two scripts both having permissions -rwxr-xr-x

/usr/bin/msg_on_login.sh  to pass the message to the users on their login
/usr/bin/msgpass.sh to pass the message to the users who are on their system (screen may be locked)

msg_on_login.sh
#!/bin/bash

m=`who | grep tty | wc -l`
# how many users are logged in
num=`expr $m - 1`
# it helps to send the message to exact display in case one or more user is already logged in
if [ `wc -w /home/message.txt| gawk '{print $1}'` -gt 1 ] && [ $num -gt 0 ]
    then
        DISPLAY=:$num.0 zenity --info --text="`cat /home/message.txt`" &
    elif [ `wc -w /home/message.txt| gawk '{print $1}'` -gt 1 ]
        then
            zenity --info --text="`cat /home/message.txt`" &
    else
        exit 0
fi

and add this line "/usr/bin/msg_on_login.sh" at the end of /etc/profile and change permission of /usr/bin/msg_on_login.sh to -rwxr-xr-x. Then the script will run each time any user login and he will get the message.
msgpass.sh
#!/bin/bash
m=`who | grep tty | awk '{print $1}' | sort | uniq | wc -l`
min=0
max=`expr $m - 1`
array=(`who | grep tty | awk '{print $1}'`)
for num in `seq $min $max`
do
if [ `wc -w /home/message.txt| gawk '{print $1}'` -gt 1 ]
then
    sudo sudo -u ${array[num]} DISPLAY=:$num.0 zenity --info --text="`cat /home/message.txt`" &
else
    exit 0
fi
done
echo 0 > /home/message.txt

change permission of /usr/bin/msgpass.sh to -rwxr-xr-x.
Cons

If any user login from a virtual terminal he will get an error message. To handle that situation is tricky. As such a situation was not intended so I skipped that part.
Say 1st user (who loged in before 2nd user) logout the system then msgpass.sh stumbles over and gives error.
To run msgpass.sh you need to have member of sudo group.
I am also finding a way to run the script as non-root user.

Note

Need help to remove first two cons.
Comment: For the first con: you can probably check if the variable $DISPLAY exists and is set --- if not, you are not in a graphic session. Something on the line of `[ x$DISPLAY = x ] && exit` or something similar...

Convey some message to all users


How were djinn traditionally depicted in pre-Islamic Arabic myth?

Question: Today, many people are aware of "genies" as beings from Arabic myth, mostly thanks to Disney's Aladdin. Other works of fantasy have often co-opted djinn as creatures in their worlds.
But Disney's depiction of a genie is, shall we say, cartoonish, and surely does not resemble the djinn of Arabic mythology. How were they traditionally depicted (in terms of their physical portrayal)? Textual sources and art would both be helpful here.
Comment: I think they were invisible, or when not so, able to change shape which is going to make art hard to find.
Answer: I'm drawing my information for this answer from my reading of the doctoral dissertation of Amira El-Zein, titled "The Evolution of the Concept of the Jinn from Pre-Islam to Islam".  I have attempted to summarize extremely briefly a few salient bits, particularly from pages 65-98.  However, as it turns out, this topic is actually fairly complex, so giving it a read would be recommended: The Evolution of the Concept of the Jinn from Pre-Islam to Islam.

Jinn is a classification of a number of different types of supernatural being.  They may be either good or bad, and there is no clear demarcation between types of jinn as either strictly good or strictly evil.
They could appear as pure spiritual beings, as stand ins for angels or demons, as indicated by Ibn Manẓūr, in "Lisān al-ʿArab"

The people of the Jahiliyyah called angels-peace be upon them-jinn because they were invisible from sight

They could also be tangible creatures, particularly with animal-like characteristics, as stated by "The Encyclopedia of Religion and Ethics"

...were not pure spirits, for they were often represented as hairy and often as having the form of an ostrich or a snake."

Four specific types of Jinn are detailed as significant in the pre-islamic world:

Ghūl - Quoting Al-Jāḥiẓ "Every supernatural creature that takes diverse forms".  They seem to appear in many different forms, often animalistic, and can appear and disappear "like the light of a torch".  They (and generally any jinn, it appears) leave a physical corpse behind when killed, thus the poem by Ta'abbata Sharran:

I spent the night leaning on her, waiting for the morning to see what I caught.  Then I found two eyes in an ugly head, similar to the head of a cat with a forked tongue.

Si'lah - The difference between this and the former is not clear to me.  They seem to be more sneaky and clever.  A story exists of a one marrying and bearing human children.  Possible other differences may be that they are active during the day, instead of at night, or that the Se'lah is female, and the Ghūl male.  neither seems to be universally respected though.
Shiqq - A man with only half of a body, and will beat a human to death if encountered.  Again, from Al-Jāḥiẓ:

There, a shiqq appeared to him.  He had only one hand, one eye, one leg.  They recited poetry to each other, then they hit each other, and both of them fell dead.

Shaytān - They are noted for being smart, cunning and powerful.  And generally rebellious.  May or may not be a loan word from Hebrew, but still not necessarily evil.
ʻIfrīt, Qutrub and Mārid - Not well-known in pre-islamic time.
Comment: +1 for linking this doctoral dissertation - I'm looking forward to reading it!
Answer: In Islamic theology, jinn are said to be creatures with free will, made from smokeless fire by Allah as humans were made of clay, among other things.
From Wikipedia

They are usually invisible to humans, but humans do appear clearly to jinn, as they can possess them.

Clearly, this contradicts the existence of depictions of jinn.
However, jinn are classified into three:

ghūl (غول)

A ghul or ghoul is said to be a desert dwelling, shape shifting demon. It is said to commonly take the appearance of a hyena. Legends about the ghul inform that the ghul takes the appearance of whatever it last devoured.

ifrīt (عفريت)

An ifrit is an enormous winged creature of fire, either male or female, who lives underground and frequents ruins.

siʿlā

They are said to be the female creatures that fall under the jinn category. However, they're immutable in shape and appear in the guise of an attractive young woman.
Answer: In oral legends, I've heard, Djinn were humanoids with goat hoofs who disliked salt. (only the hoofs, not legs or lower parts like fauns)
They are not trully invisible but live in a sort of parrallel world a bit like islandic fae. they co-exist, or occupy the same space as humans so there are sometimes interactions, including cross-species marriages. In some legends they have knowledge of treasures but in others they are just like us.
I also remember another type with is similar to nagas, they are woman headed great snakes that can slide upright thought the desert. Don't ask for references, this is from stories I vaguely remember from childhood.
I think that one of the problems is that these terms are wiledly used in arabic for various supernatural phenomenon. djins are also blamed for possessions, hauntings and mental illnesses.
Ghul is also a broad term that emcompasses beasts, monsters, scary things or any frightning uncontrolable entity.
The surest way to hunt down the pre-islamic roots is through Jewish, Babylonian, and Assyrian mythology.
Answer: Some ancient Egyptian images were worked into later mythology in the area (Bes, for instance.)
A source for "Less-than-deities" in ancient Egypt is Egyptologist Kasia Szpakowska's DemonThings blog. It might be worth checking.
Answer: Yes, djinn and this huge number of descriptions of them existed long before Mohammad so he had a lot of choice in saying his take on the matter. These creatures, however, were not mentioned in the Bible- not in the Torah, the Zabur or the injil .. nor elsewhere in the Tanakh.  And even had the Bible been translated into Arabic before the coming of Mohammad, there was no such description or name "djinn" in either Hebrew or Greek. Actually it is clear that the idea of djinn is strictly PAGAN in nature and has nothing to do with the only God Who had already given His teaching on the matter in previous scriptures. The closest match is that there were obedient angels who remain His servants and the fallen angels, the servants of Shaitan
 For your reference and research, please see:Revelations 12:4; 2 Peter 2:4; Isaiah 14:12 ... or just look this all up on the internet... this site is petty good- https://www.thoughtco.com/who-are-fallen-angels-demons-123840
One last point .... No. the Bible had not been translated into Arabic before the coming of Islam
These "djinn ... are very bad  ..
 keep them away by asking God's intervention


How to install Ubuntu on a hard drive with bad blocks?

Question: I have a problem with my laptop,in which I'd had windows xp. That XP crashed and I couldn't restore it with the Install CD. So, I placed Ubuntu 11.10 install on a Pendrive, searched for some bad blocks(less than 500), hard drive had a entire format  and everything looks fine but the progress bar hangs about 20% and the install didn't finish over night? What should I do?
Comment: To me it sounds like more then maybe just bad blocks, the OS should be smart enough itself to know to ignore them when installing... maybe there is something wrong with the read write head, or the bearings on the platters... I don't know you didn't specify if it is SSD or not, so I am assuming it isn't the only way to fix these two problems would be to install a new hard drive... This would make sense why Windows Crashed, and couldn't be recovered though...
Answer: After writing the digression below, it occurred to me that I should probably also mention why I wrote it.
Any form of sector write or read error on a drive should be viewed as a potential warning. The drive could be failing. Certainly if a drive is reporting as many as 500 bad blocks, I would dig deeper into this before installing anything on the drive.
As I mentioned below, you can use Ubuntu Disk Utility from a Live CD/USB to examine the drive's SMART attributes. If the drive only has few pending reads, you can fill the drive with zeros to force the sectors to be remapped and then do another Ubuntu install.
But watch the drive carefully for further signs of failure and don't save anything critical on it unless it is also backed up. If the drive continues to show sector errors, consider shopping for a replacement drive. Soon.
Just my opinion of course, for whatever it's worth.

These days it is hard to be certain what the phrase bad blocks actually means. In the pre-deluvian days of computing ... say 15 years or more ago ... it could refer to a list the operating system kept of sectors on a hard drive which the drive reported to be, well, bad.
All relatively recent drives now do this sort of tracking internally in their firmware and operating systems no longer need to track such things.
This Wikipedia article on Bad Sectors seems to be a reasonable overview. The key points being:

While the hard drive will automatically attempt to remap a bad sector, it typically only does this when a write fails. Read errors are reported to the OS and logged in the drive's S.M.A.R.T. data, but the sector is not remapped.
The standard way to force the drive to remap all bad sectors is to write to every byte on the drive. Typically one fills all the sectors with 0x00.
If a drive has reported one or more bad sectors, it is possible that the drive may be approaching failure. The drive's S.M.A.R.T. data should be examined, especially the following S.M.A.R.T. attributes
   0x05  Reallocated Sectors Count (How many sectors were remapped)
   0xC5  Current Pending Sector Count (How many sectors waiting to be remapped)

You can use an Ubuntu Live CD or USB to do these things.
After booting the Live CD/USB, open the Disk Utility application either with the GUI by searching for it with Dashor by running the command palimpsest & in a terminal. Select the disk in the left sidebar and then use the SMART Status function to retrieve and view the drive's S.M.A.R.T. attributes.
The  dd command command can be used from a terminal window in a Live CD/USB session to fill a drive with zeros. For example, the command below will write 0x00 to every sector on drive /dev/sda
sudo dd if=/dev/zero bs=1M of=/dev/sda

Of course, depending on the size of the drive this could take many hours to complete.
If you are curious, there are many more "tricks" one can use with dd. Have a look at the answers to this question on serverfault. I especially like this trick for periodically displaying the progress of a dd command.
Comment: [An anonymous user says](http://askubuntu.com/suggested-edits/10146): "I've used irrational John's advice and install had finished. Now SMART shows 2 bad blocks less than before. Everything looks fine. If anything bad is hapens I let you know. Thanks a lot."
Answer: BEST ADVICE (rather than solution)
If the hard drive is currently stable, and not deteriorating, then a low-level format will map any "bad sectors" to be unused.  The BIOS, HDD controller, and OS should be able to handle any "slow deterioration" after that.
What you are describing could be more serious, and/or a bad controller.
I would strongly suggest getting the laptop checked out, or (at least) getting a test tool that will stress test the drive and show it "stable" or still getting worse ..
Answer: I'm using intensively three hd's with bad blocks since years without any problems. The oldest is over ten years old, the newer ones 5 or 6 years. I think those bad blocks are anoying, if you loose date but david6 thought of low level format seems the best idea for me.
You should install/use that reformated disk and have a regular look at the smart-data of your drive (eg. bad blocks, relocated blocks). Smart-data isnt absolutely reliable but give a good overview of the health status. If you use your reformated disk and you don't see increased bad blocks/relocations, then youre on the lucky side. If you find segnicant more bad blocks or reports a remaining life-time then i would change the drive - its about to die.
BTW: After low-level formating the drive it is NOT necessary to run "badblocks" or such utilities. The drives firmware will handle this without user interaction. When the operating system tries to write to one of those bad blocks, the firmware will silently relocate the bad block.
Answer: You must exclude bad blocks on file system before you begin.
Boot from LiveCD and run this command (assuming that your target partition is sda1):
fsck -M -cc /dev/sda1

This command will check file system on partition /dev/sda1 and will exclude bad blocks from usage. Option -M tells to not check mounted filesystem.
Note: this command will not remap bad blocks on hard drive! It works only for target file system. If you want to remap bad blocks you can do that with Windows chkdsk /f /r command.
After that you may run install but you have to chose manual disk partitioning during setup.
Answer: I did install Ubuntu on a net-top containing bad blocks at the start of the drive so during the partitioning stage I put the '/' partition at the END of the drive (it gives you that option), also the separate '/home' partition at the END also but I shrank it so that It was 30gb smaller than the leftover space to skip the bad sectors.
The install worked fine although if the drive contains bad sectors then it may slowly get worse and is time for a replacement HD...


Fix Linux home default permissions

Question: I broke my home directory and file permissions by moving to and from drives etc. How do I restore default permissions on my home directory?
Comment: https://unix.stackexchange.com/questions/315799/default-permissions-on-linux-home-directorys
Answer: You could run as root these commands, where user is the user's name:
sudo chown -R user /home/user

And if necessary:
find /home/user -type f -exec chmod 0664 {} \;
find /home/user -type d -exec chmod 0775 {} \;

The later will destroy permissions such as execute, which you will need
to add manually as required. Presumably, these permissions were already
lost after being copied to external filesystems that didn't support them.
Comment: running the chmods above might not work as you run the first command with sudo and if the files are not owned or accessible by user "user" if we suppose the use "user" is logged in. and no only it will not restore execute access, it will even destroy it - it will REMOVE the execute bit from all files. and we don't know what is broken. so maybe a plain `sudo chown -R user /home/user` will fix the OP's issue.
Comment: @Zina: Right - I modified my answer.

Fix Linux home default permissions


How can I show numbers as percentages in CartoDB?

Question: I would like to format numbers as percentages in cartodb. What are the best functions to display numbers with decimals, comma separators or percentages?
Answer: There is no 'percentage' type so you need to use a string
You can do this by taking a numeric column and concatenating || with a %.
SELECT percent_column::text || '%' FROM table

You can also format the number first if you need, for example, multiply a decimal by 100 or round to sig digits,
SELECT round(percent_column * 100, 2)::text || '%' FROM table

For including commas, it is the same, you must turn numeric columns into strings. You could use this example,
SELECT TO_CHAR(76543210.98, '999G999G990D00')

Which was provided here, https://stackoverflow.com/questions/3360752/how-to-set-thousend-separator-for-postgresql
or more generically
SELECT TO_CHAR(number_column, '999G999G990D00') FROM table