How to take guess a word by its letter in js

Question: as the title says I'm making a little game, but it doesn't guess the word, I don't know why. I've added a word so people would have to guess it, using letters and if the letter is equal to any letter on the word it would replace the _.
<!Doctype html>

    <title>Story</title>

    <form name="F">
        <input type="text" name="gword" class="wordi">
        <input type="text" name="t" class="in2">
        <input type="button" name="b" value="do" onclick="doGetWord()" class="bi">
        <input type="button" name="b2" value="do" onclick="doGuess()" class="bi2">

    </form>

Can you help me figure out what the error is? I just can't find it but I think it has something to do with the document.getElementById("dword").value.charAt(i) = dummy.
Thanks in Advance!!
Comment: Where do you specify which word has to be guessed? Also, I don't know which javascript tutorial are you following, but you should not use the `window` object like you do in your code. There are simple arrays in javascript.
Comment: semi-colons separate statements you're making to your Browser. If you don't supply them the Browser guesses. You should always supply them.
Comment: What does your `console.log` say?
Comment: No errors at all on it.
Comment: Also you're missing about half your semicolons .. This is bad practice and  can also confuse JavaScript ..
Comment: dword is div, right? Div does not have value property, use textContent....
Comment: the word that has to be guessed is the variable word. And I didn't really knew how to use the window thing. Could u help me out with this one?
Comment: but aren't semicolons useless in js? xD
Comment: yes sir, dword is the div, and thanks for the advise.
Comment: Oh okay, I did not know that, thanks a lot. Do you know what's wrong with the rest of my code?
Comment: @zfrisch is right. There are so many things wrong about your code I really don't know where to start. I will simply recommend  this book: http://eloquentjavascript.net/   Just be aware that wherever you are learning JS from, is full of bad practices, so take your time and get a decent knowledge of the basics before you try to write complex programs. PS: just saying that because you seem to have fun with but you can save yourself lots of headaches if you start right.  Also: read Stack Overflow.  ;)
Answer: You don't need var before variables here
function doGetWord(){
            var word = F.gword.value;
            var wLength = word.length;

As the idea is to save this values in scope of parent function.
And you might replace the letters like this
const letters = document.getElementById("dword").textContent.split('');
letters[i] = dummy;
document.getElementById("dword").textContent = letters.join('');

You are using bad variable names and a lot of global variables, it might be a good practice to work of this. I recommend reading a book on general programming, something like https://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670 and something more specific to javascript (to get the concept of scopes) https://www.manning.com/books/secrets-of-the-javascript-ninja

    <!DOCTYPE html>

        <title>Story</title>

        <form name="F">
          <input type="text" name="gword" class="wordi" />
          <input type="text" name="t" class="in2" />
          <input type="button" name="b" value="do" onclick="doGetWord()" class="bi" />
          <input type="button" name="b2" value="do" onclick="doGuess()" class="bi2" />

        </form>

Comment: your does kinda work but it still has the _. Could u please remove them and also explain what did you change? Thanks.
Comment: Thank you very much, but how do I remove the "_" from the word after it has been guessed?
Comment: I've updated the answer. The changes were made in `doGuessWord`
Comment: Omg, thank you so much for everything, ur post was very useful :=).
Answer: Here are some hints on your code (among other things):

It's always better to use semi-colons (as noted by zfrisch).
You don't need more than one $(document).ready(function() { .. }).
Strings are immutable, so you cannot change them directly. You have to turn them into char arrays first (as in Bsalex answer).
Don't declare local variables with the same names as global variables, because the local ones will hide the globals.
To read the text content of a div element, use its textContent property instead of value. (see Bsalex answer)
Don't declare a local variable without var/let/const keywords (like this ws = new Array(wLength)), or it'll become a global variable.

Happy Coding!
Comment: Oh thank you very much for your time, and for what you just said. By the way could you explain number 2? pls, thanks xD
Comment: @ThecheesiestChannel It means, you can simply place both statements of (`$("input.in2").hide()` and `$("input.bi2").hide()`) in a single `$(document).ready(function(){..})`, instead of two.
Comment: oh ok tyty ahah xD


SmsManager keeps retrying to send SMS on HTC Desire

Question: In my app I need to send SMS, so I use the following code
final String SMS_REQUEST_OK = "SMS_REQUEST_OK";
String m_sms_message = String.format("sample text");
String m_dest_number = "some number";

Intent SMSInfo = new Intent(SMS_REQUEST_OK);
SMSInfo.putExtra("msg", m_sms_message);
SMSInfo.putExtra("num", m_dest_number );
PendingIntent sentPI = PendingIntent.getBroadcast(m_context, 0,
                   SMSInfo, PendingIntent.FLAG_CANCEL_CURRENT);

m_context.registerReceiver(new BroadcastReceiver(){
    @Override
    public void onReceive(Context arg0, Intent arg1) {
        switch (getResultCode()){
            case Activity.RESULT_OK:
                Toast.makeText(m_context, String.format(
                    m_context.getResources().getString(R.string.sms_success),
                    arg1.getExtras().getString("msg"),
                    arg1.getExtras().getString("num")),
                    Toast.LENGTH_LONG).show();
                break;
            default:
                Toast.makeText(m_context, String.format(
                    m_context.getResources().getString(R.string.sms_error),
                    arg1.getExtras().getString("msg"),
                    arg1.getExtras().getString("num")),
                    Toast.LENGTH_LONG).show();
                break;
    }
}
}, new IntentFilter(SMS_REQUEST_OK));

SmsManager.getDefault().sendTextMessage(
    m_dest_number,
    null,
    m_sms_message,
    sentPI,
    null);

I expect it to try to send SMS one time, and then show Toast message with result of this operation. It works fine if SMS is sent successfully, however if it's not it keeps retrying to send it, judging on lots of Toast messages (it occurs on HTC Desire (S), testing it on Samsung doesn't get this behaviour - Toast with error is shown once).
So - is it how SmsManager should behave and how to avoid it (so that it try to send SMS only one time)?
edit I forgot to mention - it happens if getResultCode() returns 133404, haven't tested it on other errors
edit2 According to this, 133404 is htc-specific error, which means temporary failure and device will retry automatically, untill, eventually, proper result code is received and broadcast is sent. However, no SmsManager-documented broadcast is received within resonable time. So the question remains - is there a way to stop this retry attempts?
Answer: Just to summarize what I've found out: according to android documentation, expected behaviour of sendTextMessage() is only one attempt to send message, and broadcasting result afterwards. However, some HTC devices keep retrying to send message, broadcasting "temporary error" code after each attempt. So if app is only checking whether result code is "successfull" or not (as lots of sms applications on android market seem to do), it will mark message as unsent and stop listenning to it (which suits expected behaviour of sendTextMessage() function), which may lead to marking message unsent, when actually it was sent successfully in later attempt.
What's worse is that documented code might never be sent - so, if you get one of HTC "temporary codes" (133404 or 133179, there might be more however) message status is indetermined - it might be sent some time later, or might never be sent. So as it seems to me you can only determine message status by keeping listening for broadcast until you get proper result code (which may never be sent), or judging on delivery broadcast.
Comment: is there any way to force and HTC device not to try and resend but to just fail gracefully?
Comment: Can you provide me with a reference or a link explaining this issue in details?


NoDecodeDelegateForThisImageFormat Error reading .png file with ImageMagick

Question: I am trying to use ImageMagick to load a Mesh's (made in Blender) texture from using the ASSIMP library. The Mesh has a single material and a single texture.
I was attempting to follow two tutorials: Tutorial38 and Tutorial22.
The below code block is where it has problems;
<code>bool Texture::Load()
{
    try {
        m_pImage = new Magick::Image(m_fileName); /* RIGHT HERE IT OCCURS */
        m_pImage->write(&m_blob, "RGBA");
    }
    catch (Magick::Error& Error) {
        std::cout << "Error loading texture '" << m_fileName << "': " << Error.what() << std::endl;
        return false;
    }

    glGenTextures(1, &m_textureObj);
    glBindTexture(m_textureTarget, m_textureObj);
    glTexImage2D(m_textureTarget, 0, GL_RGBA, m_pImage->columns(), m_pImage->rows(), 0, GL_RGBA, GL_UNSIGNED_BYTE, m_blob.data());
    glTexParameterf(m_textureTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(m_textureTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    return true;
}
</code>
It almost immediately exits the Try-Catch with the current error:
"Error loading texture, 'Resources/white.png': myproject.exe: NoDecodeDelegateForThisImageFormat 'Resources/white.png' error/constitute.c/ReadImage/550
As far as I can determine ImageMagick is installed properly, I've attempted numerous times to compile it by hand but I always end up with Unresolved External errors with the new libs (they seem to be 2-3 mb bigger than the ones included with the Project).
The versions attempted:
ImageMagick-6.6.5-10
ImageMagick-6.6.0
ImageMagick-6.8.9
ImageMagick-windows zip from their instructions page.
A big problem I have when attempting the self installer binaries is that they don't include both the Release Candidate AND the Debug lib's, when the code requires both; while the source versions I compile as mentioned aren't correct and result in Unresolved External errors or don't otherwise clearly deposit their Include and Lib folders.
I've contacted the developer of the tutorial but the only thing he's said so far is that I might have the wrong version of ImageMagick installed and is incompatible with the version he includes... Without saying which version the correct one would be.
Edit - 1:
-Attempted installation/reinstallation of libpng from Here No change.
Comment: Do you have `libpng` installed as well?  http://www.imagemagick.org/script/formats.php
Comment: When I type identify -list format it's listed as native/read/write, it should be installed I think, I'll try to see if I can reinstall it but it does the same error for jpg and any other file format.
Comment: Perhaps installing delegates might fix it, but unfortunately there doesn't appear to be any instructions for a lay person; attempting to compile libpng just results in over a hundred compiler errors of not being able to find the correct files.
Answer: Well, embarrassingly I found the solution after three+ months of elaborate torture, and it was to switch the compiler to "Release" mode instead of "Debug". I no longer complains and perfectly loads the texture I had.
Not working in "Debug" mode seems like either a bug with ImageMagick or a bug with Visual Studios 2010, I think I'll file a bug report.


How to create aws iot Thing with Thing Type using Android SDK

Question: i am creating a thing using android sdk with "CreateThingRequest". But i am unable to create with Thing Type. In java i found "public CreateThingRequest withThingTypeName(String thingTypeName)" method, but i have not seen anything related to this in android. Can anyone suggest me to create Thing with Thing Type.
Answer: If you upgrade to the latest iot sdk, this should be solved there. Thing type name is present in the create thing request in iot-sdk version 2.4.3.
Ref: Github
Answer: <code>public void createThings(final Map < String, String > attributes) {

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {

                CreateThingRequest createThingRequest = new CreateThingRequest();
                createThingRequest.setThingName(certificateId);
                AttributePayload attributePayload = new AttributePayload();
                attributePayload.setAttributes(attributes);
                createThingRequest.setAttributePayload(attributePayload);
                CreateThingResult createThingResult = mIotAndroidClient.createThing(createThingRequest);
                Log.i("Thing Mesage", createThingResult.getThingArn());
                if (onInitializeMqtt != null)
                    onInitializeMqtt.onInitializeDone(true);
            } catch (Exception e) {
                Log.e(LOG_TAG,
                    "Exception occurred when generating new private key and certificate.",
                    e);
                onInitializeMqtt.onInitializeDone(false);
            }
        }
    }).start();

}
</code>


How can I change textview after clicking on active and deactive buttons in my program?

Question: I have two buttons naming "Active" and "Deactive" and a TextView. when I click on "Active" button it must send an SMS containing "CMDSAD_ON"message to a phonenumber, and set "Enable" to my TextView and when clicking on "Deactive" button, it must send "CMD_OFF" and set "Disable" to the same TextView.
But when I run it, it only sets "disable" to the textview and it won't change whenever I click the buttons and it even set it before sending the SMS. I don't you how I can solve its problems.
Thanks
   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //intent to filter for SS message received.
        intentFilter = new IntentFilter();
        intentFilter.addAction("SMS_RECEIVED_ACTION");

       // Button2 is the id of "Active button" and Button4 is the id   of "Deactive button".

        Button button1 = (Button) findViewById(R.id.button2);
        button1.setOnClickListener(this);
        Button button2 = (Button) findViewById(R.id.button4);
        button2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.button2:

                String mymsg = "CMDSAD_ON";
                String thenumber = "916722";
                sendMsg (thenumber, mymsg);

            case R.id.button4:
                String msg = "CMDSAD_OFF";
                String phonenumber = "916722";
                sendNackMsg(phonenumber, msg);

            default:
            }}

and sendNackMsg function is similar to sendMsg except the last lind which change the textview to "disable"( -> Textstatus.setText("disable");)
public void sendMsg (String thenumber, String mymsg){
        String SENT = "Message sent";
        String DELIVERED = "Message delivered";

        SmsManager smsManager = SmsManager.getDefault();

        Context curContext = this.getApplicationContext();

        PendingIntent sentPending = PendingIntent.getBroadcast(curContext,
                0, new Intent("SENT"), 0);

        curContext.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "Sent.",
                                Toast.LENGTH_LONG).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Not Sent: Generic failure.",
                                Toast.LENGTH_LONG).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "Not Sent: No service (possibly, no SIM-card).",
                                Toast.LENGTH_LONG).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Not Sent: Null PDU.",
                                Toast.LENGTH_LONG).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Not Sent: Radio off (possibly, Airplane mode enabled in Settings).",
                                Toast.LENGTH_LONG).show();
                        break;
                }
            }
        }, new IntentFilter("SENT"));

        PendingIntent deliveredPending = PendingIntent.getBroadcast(curContext,
                0, new Intent("DELIVERED"), 0);

        curContext.registerReceiver(
                new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context arg0, Intent arg1) {
                        switch (getResultCode()) {
                            case Activity.RESULT_OK:
                                Toast.makeText(getBaseContext(), "Delivered.",
                                        Toast.LENGTH_LONG).show();
                                break;
                            case Activity.RESULT_CANCELED:
                                Toast.makeText(getBaseContext(), "Not Delivered: Canceled.",
                                        Toast.LENGTH_LONG).show();
                                break;
                        }
                    }
                }, new IntentFilter("DELIVERED"));

        PackageManager pm = this.getPackageManager();

        if (!pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) &&
                !pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
            Toast.makeText(this, "Sorry, your device probably can't send SMS...", Toast.LENGTH_SHORT).show();
        } else{
            smsManager.sendTextMessage("9167227450", null, "CMDSAD_ON_1234", sentPending, deliveredPending);
        setContentView(R.layout.activity_main);
        TextView Textstatus = (TextView) findViewById(R.id.Textstatus);
        Textstatus.setText("enable");}
    }

public void sendNackMsg(String phonenumber, String msg) {
        String SENT = "Message sent";
        String DELIVERED = "Message delivered";

        SmsManager smsManager = SmsManager.getDefault();

        Context curContext = this.getApplicationContext();

        PendingIntent sentPending = PendingIntent.getBroadcast(curContext,
                0, new Intent("SENT"), 0);

        curContext.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "Sent.",
                                Toast.LENGTH_LONG).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Not Sent: Generic failure.",
                                Toast.LENGTH_LONG).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "Not Sent: No service (possibly, no SIM-card).",
                                Toast.LENGTH_LONG).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Not Sent: Null PDU.",
                                Toast.LENGTH_LONG).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Not Sent: Radio off (possibly, Airplane mode enabled in Settings).",
                                Toast.LENGTH_LONG).show();
                        break;
                }
            }
        }, new IntentFilter("SENT"));

        PendingIntent deliveredPending = PendingIntent.getBroadcast(curContext,
                0, new Intent("DELIVERED"), 0);

        curContext.registerReceiver(
                new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context arg0, Intent arg1) {
                        switch (getResultCode()) {
                            case Activity.RESULT_OK:
                                Toast.makeText(getBaseContext(), "Delivered.",
                                        Toast.LENGTH_LONG).show();
                                break;
                            case Activity.RESULT_CANCELED:
                                Toast.makeText(getBaseContext(), "Not Delivered: Canceled.",
                                        Toast.LENGTH_LONG).show();
                                break;
                        }
                    }
                }, new IntentFilter("DELIVERED"));

        PackageManager pm = this.getPackageManager();

        if (!pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) &&
                !pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CDMA)) {
            Toast.makeText(this, "Sorry, your device probably can't send SMS...", Toast.LENGTH_SHORT).show();
        } else{
            smsManager.sendTextMessage("09167227450", null, "CMDSAD_OFF_1234", sentPending, deliveredPending);
            setContentView(R.layout.activity_main);
            TextView Textstatus = (TextView) findViewById(R.id.Textstatus);
            Textstatus.setText(disable);}
    }

Answer: You did not apply break statement on your onClick. That's why it always goes throw your last case and set disable to your TextView. Check this :
 @Override
public void onClick(View v) {

    switch (v.getId()) {

        case R.id.button2:

            String mymsg = "CMDSAD_ON";
            String thenumber = "916722";
            sendMsg (thenumber, mymsg);
            break;

        case R.id.button4:
            String msg = "CMDSAD_OFF";
            String phonenumber = "916722";
            sendNackMsg(phonenumber, msg);
            break;
        default:
            break;
        }
  }

Comment: Thanks I tried your suggestion but in this case, just the "Active button" works properly and the "Deactive button" is not even clickable(when I click on it, nothing happens)
Answer: Here your are setting a fixed text on Both buttons click
Use this condition on your buttonOnCLick and apply break; statement after all of  your button click.
Use same as these condition on your both button click and just change this
 String mymsg = "CMDSAD_ON";
    String thenumber = "916722";
    sendMsg (thenumber, mymsg);

On Your button4 Click
       String msg = "CMDSAD_OFF";
            String phonenumber = "916722";
            sendNackMsg(phonenumber, msg);

Replace your message code as you do before in both conditions this is for button2 click
    if(myTargetButton.getText().toString.equalsIgnoreCase("active")){

    myTargetButton.setText("Disable")
    String mymsg = "CMDSAD_ON";
    String thenumber = "916722";
    sendMsg (thenumber, mymsg);

    }else if(myTargetButton.getText().toString.equalsIgnoreCase("Disable")){

    myTargetButton.setText("Enable")
    String mymsg = "CMDSAD_ON";
    String thenumber = "916722";
    sendMsg (thenumber, mymsg);

    }

 TextView Textstatus = (TextView) findViewById(R.id.Textstatus);
    Textstatus.setText("فعال");}

Change it and use text from your method like:
TextView Textstatus = (TextView) findViewById(R.id.Textstatus);
        Textstatus.setText(mymsg);}

Hope it works for you.
Comment: Thanks I changed it but the result is the same:(
Comment: I added the rest of my code to my question. Any suggestions or advice  would be greatly appreciated:)
Comment: Thanks a lot for your reply... Sorry that i didn't get what you meant,ّI am new to android, would you please write your code more simply?
Comment: @RozeWinslet Check my answer hope your problem fixed by this
Comment: Thanks... but in this case none of the buttons are clickable.


Difference between Skimmer and Rocketeer?

Question: There was an update and a new tank was added to Diep.io on 12/22/2017. It's called Rocketeer and branches off Destroyer.
What are the differences between Rocketeer and Skimmer? They look very similar.

Rocketeer

Skimmer
Answer: It's different as they have different paths of missiles following behind the big bullet. Also, Rocketeer is much smaller and easier to be damaged
Answer: According to the wiki:
Skimmer

A similar design to the Hunter but with wider Cannons, this tank has a Deployer and shoots a Destroyer Bullet with two Small Cannons attached at its back flanks. However, the main Bullet's damage is significantly decreased. These bullets are known as missiles. As of press (Keyboard) time, only this tank and the Rocketeer use missiles.

Rocketeer

The Rocketeer fires bullets with a Machine Gun Barrel on it's back, propelling the bullet forward. These too are missiles, as above.
Answer: The difference between the Skimmer and the Rocketeer is that they shoot different missiles, as said in Damek's answer. Another difference between these two tanks is that a rocketeer's missile can have low bullet penetration and still survive after going through a tank. I've also heard that the rocketeer's missiles can shoot through the base camps in teams, unlike the skimmer and other tanks in diep.io.
Hope this helped!
Answer: Skimmer shoots mini Flank Guards.
Rocketeer shoots mini Machine Guns.


TinyButStrong magnet tag shows in output docx

Question: Hi my colleague and I has been trying to get the TinyButStrong plugin openTBS to create some docx files.
We have a live system which creates some RTF files, with data from MySQL. We want to change this to docx, use openTBS. A couple of super users then in Word manage the templates.
We have a problem with creating the files, as we need to remove a line, if data isn't present.
If we in the Word template do
<w:p>[*fieldname*;magnet=w:p]*some kind of text*</w:p>

it hiddes the line if fieldname contains no data, and if if contains data, it will show the line. GREAT :-)
The problem is, that it also shows <w:p> and </w:p> when it contains data, and we don't like that.
How do we get it to stop showing these tags?
Answer: The TBS parameter ope=minv is done for thus purpose: it performs the magnet behavior but keep the field invisible (minv stands for magnet invisible).
So the solution is:
<w:p>[*fieldname*;magnet=tbs:p;ope=minv]*some kind of text*</w:p>

By the way, magnet=tbs:p is better than magnet=w:p because your template stays compatible when converted to another other format (LibreOffice).
Comment: I have now changed it to
[onshow.r477;magnet=tbs:p;ope=minv] ekskl. Moms2: [onshow.r505a] [onshow.r525]
but it still shows
Comment: What are the `` in your template ? is that text that you can read in your template when you edit it with Ms Word, or does it means the invisible inner XML ?
Comment:  is the surrounding tag, that should control if a line should be shown or not. We have taken it from some documentation on the web.

But yes, we have typed it in the Word template, and can see it in there.
Maybe that is the problem, it's not working as a inner XML ,but if so how do we do that?
Comment: Yes, your usage can bring confusion and will probably not work as you expect. The tage `` is used by Ms Word in order to delimitate  a paragraph in the inner XML stored in the DOCX. But when you type the same string in your document using Ms Word, a different string is stored in the XML. The stored string for `` is ``. OpenTBS can find and manipulate the inner XML entities, but not the one you've typed. It seems to me that your `` tags are simply useless, I think you can omit them.
Comment: Well we found somewhere an example showing it with  and , and we just copied it and tried to refit it to our needs. But we much worked on a corrupt document, because we tried it on a another docx and now it works as expected. We could even remove the  and  tags.


Android: How to read a string from input stream via bluetooth connection?

Question: I am making an app where I need to have my PC and phone communicate via Bluetooth. I have gotten the app and my PC to successfully connect, and my app is receiving an input stream when I send "Hello World" from my PC. However, I cannot seem to figure out how to get a readable string from my input stream. Here is the code I have so far:
private static class BluetoothAcceptThread extends Thread {
        private final Context CONTEXT;
        private final BluetoothAdapter BLUETOOTH_ADAPTER = BluetoothAdapter.getDefaultAdapter();
        private final BluetoothServerSocket BLUETOOTH_SERVER_SOCKET;
        private final java.util.UUID UUID;

        public BluetoothAcceptThread(Context context, java.util.UUID uuid) {
            this.CONTEXT = context;
            this.UUID = uuid;

            BluetoothServerSocket tmp = null;
            try {
                tmp = BLUETOOTH_ADAPTER.listenUsingRfcommWithServiceRecord(
                        CONTEXT.getString(R.string.app_name), UUID);
            } catch (IOException e) {
                e.printStackTrace();
            }
            BLUETOOTH_SERVER_SOCKET = tmp;
        }

        @Override
        public void run() {
            while (true) {
                BluetoothSocket socket = null;
                try {
                    System.out.println("Accepting incoming connections");
                    socket = BLUETOOTH_SERVER_SOCKET.accept();
                    System.out.println("Found connection!");
                } catch (IOException e) {
                    System.out.println(1);
                    e.printStackTrace();
                }

                if (socket != null) {
                    manageConnectedSocket(socket);
                }

                try {
                    assert socket != null;
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        public void cancel() {
            try {
                BLUETOOTH_SERVER_SOCKET.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void manageConnectedSocket(BluetoothSocket socket) {
            try {
                InputStream inputStream = socket.getInputStream();
                while(inputStream.read() == -1) {
                    inputStream = socket.getInputStream();
                }
                String string = CharStreams.toString( new InputStreamReader(inputStream, "UTF-8"));
                System.out.println(string);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

In case it is relevant, here is the test code I am running from my PC:
import bluetooth
import pydbus

def list_connected_devices():
    bus = pydbus.SystemBus()
    mngr = bus.get('org.bluez', '/')

    mngd_objs = mngr.GetManagedObjects()
    connected_devices = []
    for path in mngd_objs:
        con_state = mngd_objs[path].get('org.bluez.Device1', {}).get('Connected', False)
        if con_state:
            addr = mngd_objs[path].get('org.bluez.Device1', {}).get('Address')
            name = mngd_objs[path].get('org.bluez.Device1', {}).get('Name')
            connected_devices.append({'name': name, 'address': addr})

    return connected_devices

def main():
    address = list_connected_devices()[0]["address"]
    uuid = "38b9093c-ff2b-413b-839d-c179b37d8528"
    service_matches = bluetooth.find_service(uuid=uuid, address=address)

    first_match = service_matches[0]
    port = first_match["port"]
    host = first_match["host"]

    sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    sock.connect((host, port))
    message = input("Enter message to send: ")
    sock.send(message)

if __name__ == '__main__':
    main()

EDIT:
Tried using the solution suggested by Sajeel by using IO utils, and I am getting the error:
W/System.err: java.io.IOException: bt socket closed, read return: -1
W/System.err:     at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:550)
        at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:88)
        at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:291)
        at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:355)
        at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:181)
        at java.io.InputStreamReader.read(InputStreamReader.java:184)
        at java.io.Reader.read(Reader.java:140)
        at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2369)
W/System.err:     at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2348)
        at org.apache.commons.io.IOUtils.copy(IOUtils.java:2325)
        at org.apache.commons.io.IOUtils.copy(IOUtils.java:2273)
        at org.apache.commons.io.IOUtils.toString(IOUtils.java:1041)
        at com.example.app.BluetoothSyncService$BluetoothAcceptThread.manageConnectedSocket(BluetoothSyncService.java:278)
        at com.example.app.BluetoothSyncService$BluetoothAcceptThread.run(BluetoothSyncService.java:251)

EDIT 2:
I motherflipping got it! Here is the code that got it to work:
public void manageConnectedSocket(BluetoothSocket socket) {
        try {
            InputStream inputStream = socket.getInputStream();
            while(inputStream.available() == 0) {
                inputStream = socket.getInputStream();
            }
            int available = inputStream.available();
            byte[] bytes = new byte[available];
            inputStream.read(bytes, 0, available);
            String string = new String(bytes);
            System.out.println(string);

        } catch (IOException e) {
            e.printStackTrace();
        }

Comment: Does this answer your question? [How do I read / convert an InputStream into a String in Java?](https://stackoverflow.com/questions/309424/how-do-i-read-convert-an-inputstream-into-a-string-in-java)
Answer: Finally figured out the solution. You need to create a Byte Array of the same length of the inputstream's available bytes, then call the .read() method of the inputstream. The input stream will then write the bytes it received to the byte array, which you can then decode into a string.
public void manageConnectedSocket(BluetoothSocket socket) {
        try {
            InputStream inputStream = socket.getInputStream();
            while(inputStream.available() == 0) {
                inputStream = socket.getInputStream();
            }
            int available = inputStream.available();
            byte[] bytes = new byte[available];
            inputStream.read(bytes, 0, available);
            String string = new String(bytes);
            System.out.println(string);

        } catch (IOException e) {
            e.printStackTrace();
        }

Answer: Try
 String str = IOUtils.toString(inputStream, StandardCharsets.UTF_8);

In order to use IOUtils.toString() add the following things
In build.gradle app module
    implementation group: 'commons-io', name: 'commons-io', version: '2.5' //Add this line

After that import
import org.apache.commons.io.IOUtils;

Comment: I tried using IOUtils and I am getting the error that I listed in my edit. Suggestion?
Comment: try .available instead of .read like this
`while(inputStream.available() == 0);`
Comment: I did that and I still get errors. It appears that it throws the error when my Python code terminates. Maybe it is a problem with the way my PC is sending the data?
Comment: then try by putting the python code in an infinite loop and check whether the app still throws the same error or not
Comment: I got it now! I just had to read the inputstream into a byte array and then convert it to a string. If you're curious about my solution, you can check my latest edit! Thank you for your help!
Comment: Put that latest edit in an 'answer' and mark this post as `Solved` by accepting that one


How to use static abstract class as a callback in Java?

Question: I'm trying to figure out how I can use a static abstract class as a callback. I'm looking at Android's documentation here and here. The first link is a CameraManager which has a method called openCamera. This method requires an instance of the static abstract callback class StateCallback.
My main question is, how does a static class as a callback provide me anything useful? For example, what I want to do is store the CameraDevice locally from the onOpened callback, but from what I know about static members in C# (I'm a C# dev), this would not be possible because static members cannot access non-static members.
I must not understand something about Java... Or is this an intended consequence of the API design?
Thanks in advance.
Comment: *That class* is static. Your class needn't be.
Answer: You need to extend it and create a new class that implements those methods, and pass that into the call.  Because Java is all references, any parameter can be passed an object that derives from that class as well.
Also a static class in Java just means that it doesn't have a link to its parent object hidden inside of it.  It makes it easier for the GC to collect instances.  static in C#!=static in Java != static in C++ != static in C.  Heck staic in most of those languages mean different things depending on where its used.
Comment: They have a default implementation for 1 or more functions and don't want you to have to rewrite or copy it?
Comment: Ok, that makes sense. Any idea why they didn't just use an interface?


Run the AlgoTrader in Eclipse

Question: I am trying to run the AlgoTrader in Eclipse but I get two errors
The only problem now is when I run the SimulationStarter class I get the following error:
1989-12-31 23:00:00,000 DEBUG RuleServiceImpl initialized service provider: BASE
1989-12-31 23:00:00,000 DEBUG RuleServiceImpl deployed module market-data on service provider: BASE
1989-12-31 23:00:00,000 DEBUG RuleServiceImpl deployed module current-values on service provider: BASE
1989-12-31 23:00:00,000 DEBUG RuleServiceImpl deployed module trades on service provider: BASE
1989-12-31 23:00:00,000 DEBUG RuleServiceImpl deployed module portfolio on service provider: BASE
1989-12-31 23:00:00,000 DEBUG RuleServiceImpl deployed module performance on service provider: BASE
1989-12-31 23:00:00,000 DEBUG RuleServiceImpl deployed module algo on service provider: BASE
1989-12-31 23:00:00,000 DEBUG RuleServiceImpl deployed module ib-market-data on service provider: BASE
1989-12-31 23:00:00,000 DEBUG RuleServiceImpl deployed module ib-trades on service provider: BASE
Exception in thread "main" com.algoTrader.service.SimulationServiceException: Error performing 'SimulationService.simulateWithCurrentParams()' --> com.algoTrader.service.SimulationServiceException: Error performing 'SimulationService.runByUnderlayings()' --> com.algoTrader.service.RuleServiceException: Error performing 'RuleService.initServiceProvider(String strategyName)' --> com.espertech.esper.client.EPException: esper-mov.cfg.xml not found
    at com.algoTrader.service.SimulationServiceBase.simulateWithCurrentParams(SimulationServiceBase.java:246)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.orm.hibernate3.HibernateInterceptor.invoke(HibernateInterceptor.java:111)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at com.sun.proxy.$Proxy12.simulateWithCurrentParams(Unknown Source)
    at com.algoTrader.starter.SimulationStarter.main(SimulationStarter.java:29)
Caused by: com.espertech.esper.client.EPException: esper-mov.cfg.xml not found
    at com.espertech.esper.client.Configuration.getResourceAsStream(Configuration.java:928)
    at com.espertech.esper.client.Configuration.getConfigurationInputStream(Configuration.java:784)
    at com.espertech.esper.client.Configuration.configure(Configuration.java:767)
    at com.algoTrader.service.RuleServiceImpl.handleInitServiceProvider(RuleServiceImpl.java:81)
    at com.algoTrader.service.RuleServiceBase.initServiceProvider(RuleServiceBase.java:86)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.orm.hibernate3.HibernateInterceptor.invoke(HibernateInterceptor.java:111)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at com.sun.proxy.$Proxy14.initServiceProvider(Unknown Source)
    at com.algoTrader.service.SimulationServiceImpl.handleRunByUnderlayings(SimulationServiceImpl.java:139)
    at com.algoTrader.service.SimulationServiceBase.runByUnderlayings(SimulationServiceBase.java:216)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.orm.hibernate3.HibernateInterceptor.invoke(HibernateInterceptor.java:111)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at com.sun.proxy.$Proxy12.runByUnderlayings(Unknown Source)
    at com.algoTrader.service.SimulationServiceImpl.handleSimulateWithCurrentParams(SimulationServiceImpl.java:183)
    at com.algoTrader.service.SimulationServiceBase.simulateWithCurrentParams(SimulationServiceBase.java:242)
    ... 14 more

I am able to run the MOV strategy in the cmd but I have been stuck here for a very long time!
If anyone has any ideas or suggestions they would be much appreciated as this is very important for me and I have tried everything I could think of.
Comment: I have had the same problem with eclipse and could not resolve it. I think you can run the open source version only in the comand prompt and you need the enterprice version in order to run it in eclipse.
Answer: For the first problem you can solve it when you add the  after the build.
<build>
    <pluginManagement>

    </pluginManagement>
</build>

The second one seems quite complex. Everyone that can solve it is machine
Answer: You are probably trying to run SimulationStarter inside the project algotrader-code. However to run the simulation you need to run it inside the algotrader-mov project

(source: algotrader.ch)
Hope this helps!

Run the AlgoTrader in Eclipse


How to get current user in forms?

Question: I have a form in my Django project. In this form I can assign person.
This is my form:
class AssignForm(forms.ModelForm):
    user = forms.ModelChoiceField(
        queryset=UserProfile.objects.filter(is_active=True)
        label=_(u'User')
    )

    class Meta:
        model = Customer
        fields = ('user',)

I want to add another filter in this form. It is company. I get a list of all users in this form but I want to just listing the users that belongs to current user's company.
So it should be :
queryset=UserProfile.objects.filter(is_active=True, company = current_user.company)

But I cannot get requests from forms. How can I handle it?
Comment: Please share your `UserProfile` and `Company` model.
Answer: You have to pass the request.user from views.py in order to get it in the form. In your form write this __init__ function and pass the user from your views.py and you can get the user. You can access the user as self.user in your form
class AssignForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.get('user')
        kwargs.pop('user')

In your views.py call the form like below
form = AssignForm(user=request.user)

Answer: You override the constructor of the form with:
class AssignForm(forms.ModelForm):
    user = forms.ModelChoiceField(
        queryset=UserProfile.objects.filter(is_active=True)
        label=_(u'User')
    )

    def __init__(self, *args, user=None, **kwargs):
        super().__init__(*args, **kwargs)
        if user is not None:
            self.fields['user'].queryset = UserProfile.objects.filter(
                is_active=True, company__userprofile=user
            )

    class Meta:
        model = Customer
        fields = ('user',)
Then in the view you pass the logged in user:
from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    if request.method == 'POST':
        form = AssignForm(request.POST, request.FILES, user=request.user)
        # …
    else:
        form = AssignForm(user=request.user)
    # …

How to get current user in forms?


iterating of properties goes into infinite loop

Question: I written a script to iterate over the properties of an object using Object.keys() method. But when I ran, it goes into infinite loop.
var employee = {
  "firstName" : "Krishna",
  "lastName" : "Majety",
  "age" : 29,
  "address" : {
    "city" : "Bangalore",
    "area" : "Marthalli"
  }
}

function printProperties(object, objectName, tab){
  var props = Object.keys(object);

  for(i = 0; i < props.length; i++){
    property = props[i];

    if(object[property] instanceof Object){
      printProperties(object[property], objectName+"."+property, "  " + tab);
    }else{
       console.log(tab + objectName + "." + property + " => " + object[property]);
    }
  }
}

printProperties(employee, "employee", "")

It would be great, if any one explain the reason of this behaviour.
Comment: Thank you for the help...:)
Answer: Your loop iterator and property variables are globally scoped, so a nested object will reset them. The fix is to scope with let or var, or use an array method like forEach and skip the iterator entirely.
for (let i = 0; ...
  let property = props[i];


Spinner issue on samsung galaxy s3

Question: Im using samsung galaxy s3 to test my application, I have three edittext and one spinner. whenever i click the spinner, it clears the edittext value of three edittext, and after clicking item from the spinner, i get the valuo of edit text.
For below version of android, spinner will display like dialog, covers maximum screen. But in the Android 4.0, its like drop down, and its also clears the edittext data.
How to fix this issue?
<code>    spRejectionCode = (Spinner) findViewById(R.id.spRejection);
    ArrayAdapter<String> adapterNo = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item,Constants.rejectioncode);
    adapterNo.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spRejectionCode.setAdapter(adapterNo);
</code>
Comment: Can you post a code so we could analyze it?
Comment: It would be better if you show your code (where problem is occuring )
Comment: see my edit, why down vote for this question?
Comment: And im not doing anything in onItemClick Listener
Answer: It is not the issue , in earlier version the spinner looks like dialog and now in android 4.0 onwards it looks like drop down , so don't worry about the look and feel of spinner.
Comment: ya, spinner looks good, i want to know why it clears the edittext values?
Comment: @kumaand can you please show your onItemClick Listener code ?
Comment: just get the value from spinner, append it. not doing anything in edittext.

Spinner issue on samsung galaxy s3


Help diagnosing a GFCI that instantly trips. Did I nick a wire with a screw?

Question: I noticed that there were no GFCI outlets in the kitchen of my house and decided to add some. I installed one at the outlet closest to the sink but when I turned the power back on the GFCI tripped instantly. I checked the wiring and it was good. I replaced the GFCI receptacle for another new one and had the same issue. I disconnected the load side of the receptacle and the issue went away telling me that there was a problem downstream of the outlet.
I put the non-GFCI outlet back in by the sink and moved the GFCI outlet to the next receptacle downstream. The results were exactly the same. I kept moving the GFCI downstream until the GFCI wouldn't trip when I turned the power back on.
Between the last place the GFCI trips and the first place it doesn't, I had installed some shelves a while back. There were no problems when I did it. I figure now that if I had hit a wire, it would've been pretty dramatic. I drilled a small hole in the drywall to snake in a camera, but it's an outside wall and there was too much insulation to see anything.

I can't think of anything else to test, but it's hard for me to believe I hit a wire and didn't know about it. I'm hesitant to open up the wall so I'm hoping somebody has an idea as to what else might be the cause.
Comment: Could try a GFCI just before the shelves again, but only put hot/neutral on the load.  Don't attach ground.   If it doesn't trip, indicates the ground is part of the problem (rather than it leaking through a random other wire or pipe or something).
Comment: Are there any red wires in the receptacle circuit? Do you have to turn off 2 breakers or a double breaker to de-energize the circuit?
Comment: Usually hitting a wire with a nail/screw is not that exciting.  Touching that nail with your other hand grounded can be.  If you drove a nail in, most likely it is not between the hot and ground, instant breaker trip.
Answer: Since the GFCI is tripping in the next-to-last position, it seems to think there is some leakage.
With the power off, and the downstream from that position disconnected, I might put multimeter on the downstream wire at that point (especially between hot and ground) and see if it reads anything other than completely open.  If it shows a resistance, you know there's a real problem with the wiring.
Or, could try GFCI there without the downstream ground connected to anything (just to see if it insta-trips, not permanently).  If it doesn't trip, then the leakage is happening through that conductor and not some other random path.
Any chance the run is straight enough that the wires could be pulled without opening up?  Might be able to pull a new segment if so.
Could also put in 4 GFCI outlets, with that segment not connected to any of the loads. But I'd probably worry about why that segment is tripping.
Comment: "Or, could try GFCI there without the downstream ground connected to anything (just to see if it insta-trips, not permanently). If it doesn't trip, then the leakage is happening through that conductor and not some other random path."

Just tried it, still trips.

I don't have a multimeter atm or I'd try to test resistance.
Comment: Hmm then whatever leakage it finds is not through the ground, but something else.  That's pretty odd, and would be harder to test with a meter. Any chance of pulling the wire?


where do elements go under multiplication in a graded module?

Question: Assume that $M = \bigoplus_{n = 0}^\infty M_n$ is a graded $A$-module, where $A = \bigoplus_{n = 0}^\infty A_n$ is a graded ring. We have by definition $A_m M_n \subset M_{m + n}$. Does this mean that for $a \in A_1$, $x \in M_1$ we have for instance $(0, a, 0, ...) \cdot (0, x, 0, ...) = (0, 0, ax, 0, ...)$? This seems quite odd to calculate.
Would this then mean that for $a \in A_2$, $x_i \in M_i$ we have $$(0, 1, a, 0, 0, ...) \cdot (0, x_1, x_2, 0, 0, ...) = (0, 0, x_1, x_2 \cdot a x_1, ax_2, 0, 0, ...)$$ (I assumed that two elements going to the same $M_i$ would again be multiplied.)
Thanks for any help!
Answer: You just apply the distributive property. The element $\alpha=(0,a,b,0,0,\dotsc)$ is just $a+b$ and $\xi=(0,x_1,x_2,0,0,\dotsc)$ is $x_1+x_2$; then
$$
\alpha\xi=(a+b)(x_1+x_2)=ax_1+ax_2+bx_1+bx_2=
(0,0,ax_1,ax_2+bx_1,bx_2,0,0,\dotsc)
$$
because $ax_1$ has degree $2$, $bx_2$ has degree $4$ and both $ax_2$ and $bx_1$ have degree $3$.
It's no different at all than when you multiply polynomials and reduce alike terms.
Comment: great, thanks! I guess one should always bear the polynomials in mind, when dealing with graded rings.


MySQL Removing trailing linebreaks from a column

Question: I want to remove trailing line breaks from my MySQL column.
trim() only removes whitespaces but I also want to remove trailing linebreaks.
Could anyone suggest?
Comment: possible duplicate of [Does the MySQL TRIM function not trim line breaks or carriage returns?](http://stackoverflow.com/questions/281724/does-the-mysql-trim-function-not-trim-line-breaks-or-carriage-returns)
Answer: You can replace these directly from SQL by matching "\r" at the end, then replacing that "\r".
Example:
UPDATE Person SET firstName = REPLACE(firstName, '\n', '')
where firstName LIKE '%\n'

or
UPDATE Person SET firstName = REPLACE(firstName, '\r', '')
where firstName LIKE '%\r'

Comment: Will not only replace trailing, could be devastating in text fields.
Comment: This removes all instances of the escape characters, not just the trailing. This will also not work if there is a trailing whitespace.
Answer: Just ran into this problem, and took care of it like this.
UPDATE table_name SET col_name = REPLACE(TRIM(TRAILING ' ' FROM col_name),
                                         TRIM(TRAILING '\r' FROM col_name),
                                         TRIM(TRAILING '\n' FROM col_name))

This will remove new lines (\n), carriage returns (\r), and whitespace.
Comment: this code actually replaces carriage returns (\r) to new lines (\n). big difference.
Answer: This will remove all escape characters:
TRIM(TRAILING '\\' FROM (REPLACE(REPLACE(REPLACE(column_name, '\n', ' '), '\r', ' '), '\\', ' ')))

Comment: The above code works but after making a small change. I had to put an extra "\" before `\n`, so my code looks: `TRIM(TRAILING '\\' FROM (REPLACE(REPLACE(REPLACE(column_name, \\n', ' '), '\r', ' '), '\\', ' ')))
`
Answer: Depending on OS, carriage return will either be "\r\n" or just "\n". It will not be always "\r\n".
The correct way to sanitize this would be to first remove whitespace that would come after the newlines. Then remove newline escape characters then the whitespace that may be present before the newlines.
UPDATE table SET column = TRIM(TRAILING ' ' FROM TRIM(TRAILING '\r' FROM TRIM(TRAILING '\n' FROM TRIM(TRAILING ' ' FROM column))));

This will not work for more complex cases where there are nested trailing spaces and new lines. You will need regular expression replacement for it which is not available in all db versions.
UPDATE table SET column = REGEXP_REPLACE(column, '[ \\r\\n]*$', '');

Answer: I use the following queries to replace unwanted characters (spaces, breaks, etc.) from database content with a space.
The SQL's removed the following characters from the "fieldName" field:

tabulator \t "CHAR(9)" replaced by spaces "CHAR(32)",
new line \n "CHAR(10)" replaced by spaces "CHAR(32)",
carriage return \r "CHAR(13)" replaced by spaces "CHAR(32)",
double spaces "CHAR(32)+CHAR(32)" replaced by spaces "CHAR(32)",
and trimmed at the end!

This ist my favorite:
UPDATE  tableName
SET     fieldName = TRIM(REGEXP_REPLACE(fieldName, '[[:space:]]+', CHAR(32))) -- the same as '\s+')
WHERE 1;

This runs on thousands of records in milliseconds. :)
First I used the following query which does the same thing:
UPDATE  tableName
SET     fieldName = TRIM(
                  REPLACE(
                    REPLACE(
                      REPLACE(
                        REPLACE(fieldName, CHAR(9), CHAR(32)),
                        CHAR(13), CHAR(32)),
                      CHAR(10), CHAR(32)),
                    CONCAT(CHAR(32), CHAR(32)), CHAR(32))
                  )
WHERE 1;

Then I used the following query which does the same thing:
Inspired by Joel Karunungan, the following query does the same:
UPDATE  tableName
SET     fieldName = TRIM(REGEXP_REPLACE(REGEXP_REPLACE(fieldName, '[\\t\\r\\n]', ' '), '\\s+', ' '))
WHERE 1;

But now the top one runs in milliseconds.
Answer: Try something like this:
REPLACE(FIELD,'\r\n',' ')

Answer: Another vote for Wallack's idea, but more specifically:
Update YOURTABLENAME set YOURCOLUMNNAME = replace(YOURCOLUMNNAME, '\r\n','')

Essentially this should replace carriage returns and breaks with nothing.
Good luck.
Comment: this code replaces `First{linebreak}Second` to `FirstSecond`
Comment: This is missing the removal of whitespaces
Answer: Based on EternalHour's answer:
UPDATE TABLE_NAME SET `COLUMN_NAME` = TRIM(TRIM(TRAILING '\r' FROM TRIM(TRAILING '\n' FROM TRIM(`COLUMN_NAME`))))

this one removes trailing \r\n one by one, so either it is a newline or a carriage return or both, it will be stripped, and also removes whitespaces before and after the process.
Answer: For simplicity you can assume in most cases than the characters are some combination of whitespace, \r, \n or \r\n so trim them in order:

UPDATE table_name SET col_name = TRIM(TRAILING ' ' FROM TRIM(TRAILING '\r' FROM TRIM(TRAILING '\n' FROM col_name)))
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


cph.plot(): how to make it bigger?

Question: I need some help to make my cph plot bigger, but unfortunately, it seems like figsize can't be applied on this plot! Can somebody help me please?
I'm using Jupyter Notebook on pandas!
cph.plot()
Here the problem is that the plot function actually plots my features, but they are too much so their names overlap and I can see nothing! I need the plot to be bigger!
Comment: Hi! Can you include a code example? My first intuition is that the `figsize` argument cannot be given to the `plot` function, but must be passed to the `figure` function.
Answer: Seems like cph.plot() calls matplotlib.pyplot.plot in the back-end. By default, Matplotlib uses the last created figure, so creating a figure with your specified width and height should do the trick:
import matplotlib.pyplot as plt

# 8, 12 => width and height in inches
plt.figure(figsize=(8, 12))
cph.plot(/*your params here*/)

See if this works.
Answer: you can try the following command:
import seaborn as sns
sns.set(rc={'figure.figsize':(18,10)})
cph.plot()

cph.plot(): how to make it bigger?


Properties and ref return values in D

Question: Testing the following in D
import std.stdio;

struct S
{
    int _val;
    @property ref int val() { return _val; }
    @property void val(int v) { _val = v; writeln("Setter called!"); }
}

void main()
{
    auto s = S();
    s.val = 5;
}

yields "Settter called!" as the output.
What rule does the compiler use to determine whether to call the first or the second implementation?
Answer: Here you are providing two @property methods, one accepts an argument, the other does not. When doing s.val = 5;, what you're actually doing is s.val(5), but as val is a @property you can write it as a property rather than a method call (see http://d-programming-language.org/function.html#property-functions). From s.val(5) the compiler can do standard overload resolution - see http://d-programming-language.org/function.html#function-overloading.
Comment: True, but his first @property method returns a `ref int`, so the compiler could also do something like `auto a = val(); a = 5`. It actually **does** that with **dmd v2.054** with the original code - the first implementation is called. And if you switch the lines with the implementations in the source file, the setter is called... So it seems currently dmd simply calls the first implementation in the source file.

Properties and ref return values in D


Standard Cartesian Plane

Question: I have posted before.
But I had a question,
Is the **standard, ** used cartesian coordinate plane this:

Where the vertical axis represents $f(x) = y$ and the horizontal axis represents $x$?
I was wondering because in evaluation of
$$I = \int_{-\infty}^{\infty} e^{-x^2} dx$$
We take:
$$I = \int_{-\infty}^{\infty} e^{-y^2} dy$$
Then we take $I^2$.
Are you then using $f(y) = e^{-y^2}$ or just changing $x \to y$ ?? So $y$ is the independent variable?
Comment: The vertical axis is the set of points $(x,y) \in \mathbb{R}^2$ such that $x=0$. The set of points such that $y=f(x)$ represents a curve in the $xy$ plane. Would it make you feel better if we wrote $$I = \int_{- \infty}^{+ \infty} e^{-t^2} \, dt$$ and $$I = \int_{- \infty}^{+ \infty} e^{- w^2} \, dw?$$ We use $x$ and $y$ because of inertia in switching to polar coordinates. In the example I gave we can write $t = r \cos(\theta), w = r \sin(\theta)$, but for some reason some people aren't comfortable with that and think only $x$ and $y$ can be written in polar coordinates.
Comment: But the problem is, when you **combine** it, when it becomes an iterated integral, then do you have a $3D$ plot of the curve? It becomes $e^{-(t^2 + w^2)}$ but you cant have a $3D$ plot because the nor $w$ nor $t$ are the vertical axis in the 2D graph.
Comment: It's no longer a curve, it becomes a surface.
Comment: Exactly, how? Given: http://en.wikipedia.org/wiki/File:Cartesian_coordinate_system_handedness.svg

Then one of the axes **must** be $y$ for example, and one of the axes **must** be $x$ for it to be a 3D system, and a surface.?
Comment: @MarkFantini, do you see? In the 3D plane there is a seperate $xy$ plane, so if we have $e^{-(x^2 + y^2)}$ there then the issue would be that either $y$ is a **dependent** variable for $x$ or either $x$ is a **dependent** variable for $y$.
Comment: @MarkFantini, if you do not mind please take a look at the comments here (I wrote): http://math.stackexchange.com/questions/1093322/change-of-freebound-variables-in-integration/1093336?noredirect=1#comment2228979_1093336   and if you will kindly answer the question i asked in the comments
Answer: What you appear to be looking at is
the usual way to evaluate $I=\int_{-\infty}^{\infty} f(x)\;dx$
where $f(x)=e^{-x^2}.$
We show that
$$\begin{eqnarray}
I^2 &=& \left(\int_{-\infty}^{\infty} f(x)\;dx\right)
\left(\int_{-\infty}^{\infty} f(y)\;dy\right)\\
&=& \int_{-\infty}^{\infty}\int_{-\infty}^{\infty} f(x) f(y)\;dx\;dy \\
&=& \int_{-\infty}^{\infty}\int_{-\infty}^{\infty} g(x,y)\;dx\;dy.
\end{eqnarray}$$
That is, instead of doing a single integration of the single-variable
function $f$, we do a double integration of the two-variable function $g$,
where $g(x,y)=e^{-(x^2+y^2)}.$
Then we change variables to polar coordinates in order to put
the integral in a form that's much easier to evaluate.
While we can make a simple and reasonably complete graph of $y = f(x)$
in the $x,y$-plane consisting of one or more simple curves
that pass the "vertical line" test
(at least for reasonable functions $f$ such as the functions one uses for most practical purposes),
we cannot graph a multivariable function $g(x,y)$ that way,
because $g(x,y)$ assigns a value to every point in its domain,
in this case every point in the plane.
There are various other ways of plotting $g(x,y)$, but they involve
different techniques such as three-dimensional visualization,
contour lines, or other techniques to indicate that the function does
not just have a single value for any given $x$, but rather has a value for
every combination of $x$ and $y$.
I am reminded of this question, which is different from yours
but also hinges on the confusion that can occur if one tries to apply
principles of graphing single-variable functions
to a problem concerning a multiple-variable function.
Both single-variable and multiple-variable functions can be related
to the same $x,y$-coordinate plane, but they relate to that plane
in very different ways.
Comment: I do not understand some things here.How does $f(x)f(y) = g(x,y)$ $x$ and $y$ are collinear points on the axis.
Comment: In $\int_{-\infty}^{\infty} f(x)\;dx$, the symbol $x$ is a name for the variable of integration. It is not a point, though sometimes it is helpful to relate values of $x$ to labeled points on the $x$-axis of a graph. The notation $g(x,y)$ in the equations is there merely to remind us that when we set up the double integral, the integrand is a function of _two_ variables instead of just one.
Comment: It is a new function right? you didnt **transform** the single variable functions into one, you created a **new** function, in that form? Also, **the formal reason why we can change is because these are BOUND variables right?** By **definition** we are allowed to change the variables: http://en.wikipedia.org/wiki/Free_variables_and_bound_variables
Comment: Yes, $g$ is a new function. And yes, it is important that in these integrals, $x$ and $y$ are bound variables.
Comment: Okay, so how does $x^2+ y^2 = r^2$ when converting it into polar?
Comment: There's a general theorem covering changes of variables in multiple integrals, and a formula (derived from that theorem) for the transformation described by $x = r \cos\theta$, $y=r\sin\theta$. We apply that formula. Visualizing $r,\theta$ as polar coordinates can be informative if you can "get" the right visualization, but it's not a necessary part of the mathematics.

Standard Cartesian Plane


How to prove that supremum belongs to the set?

Question: Theorem Suppose $S$ is an ordered set with the least-upper-bound property, $B \subset S$, $B$ is not empty, and $B$ is bounded below. Let $L$ be the set of all lower bounds of $B$. Then $\alpha = \sup L$ exists in $S$, and $\alpha = \inf B$.
I have proved the existence of $\sup L = \alpha$.
Question I am not able to prove that $\alpha = \inf B$?
Rudin has provided the following explanation - "If $\gamma < \alpha$ then $\gamma$ is not an upper bound of $L$, hence $\gamma \notin B$. It follows that $\alpha \leq x$ for every $x \in B$. Thus $\alpha \in L$."
Question I am not able to follow this argument? Specifically, shouldn't $\alpha < x$ for every $x \in B$?
Comment: Not necessarily true that $\alpha <x$, because the set $B$ could possibly contain the infimum of $S$, which is it's own infimum. It is always safer (and correct) to say $\alpha \leq  x$.
Answer: If $\gamma \lt \alpha$, then $\gamma$ is less than the least upper bound of $L$, hence $\gamma$ is not an upper bound of $L$. But since $L$ is the set of all lower bounds of $B$, we see that every $ x \in B$ is an upper bound of $L$, because every $x \in B$ is greater than any of the lower bounds of B. Since $\gamma$ is not an upper bound of $L$, $\gamma \not\in B$.
We also have stated that every $x \in B$ is an upper bound of $L$. Since $\alpha$ is the least upper bound of $L$, $\alpha \le x$ for all $  x \in B$.


Heated flooring under subfloor

Question: I'm trying to make the best of a bad situation here.
New (old) house + slow drain + airhead teenage daughter = flooded 2nd floor bathroom.
It flooded so bad that the ceiling in my entryway underneath partially collapsed.  I was in the process of removing the damaged sheetrock when my wife saw the underside of the floor and asked if we could heat the floors since they were exposed.
We don't have heat in that bathroom (Apparently code doesn't require heat in bathrooms in New Jersey), so it would be nice.  But I can't imagine effective radiant heating through tile + subfloor.  Is it possible? If so, should I be using a hot water system or electric.  I've installed electric systems embedded in mortar but I'b be a bit intimidated about having them exposed to oxygen, and against the subfloor.
Answer: I had an embedded electric floor heater in my basement on concrete.  The builder put it in to "take the edge off" and then put laminate flooring over the subfloor with the heating.  What I think might be relevant to your situation was that the heat felt quite different than it did in the washroom where they used tile.  It still made the room warmer overall but it took much longer to warm up and the floor itself never felt as warm as the tile did.
I think what you'll find is that the heat will transfer up into your washroom, but it won't be as warm/efficient as it would be if it were embedded in your tile.  If the heat doesn't transfer well, what might happen is the thermostat you have to install might never reach temperature to shut off.  In which case you'd just have to turn it on and off when you needed it and maybe plan a bit ahead, which is what we ultimately did with ours in our kids room at night(bedrooms were in the lower level).
Comment: Hello, and welcome to Home Improvement. Thanks for the answer; keep 'em coming. And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to contribute here.
Answer: I have hydronic radiant heat between the joists under my 2nd story tiled bathroom floor (subfloor + 1/2 CBB + 1/4" marble tile).  It works fine.  I did staple a kind of radiant barrier about halfway down the joist - basically reflective mylar.  Not sure how much that helps, but it was cheap & easy.
Comment: Interesting,  Was it copper or pex? what/where was the heat source? Did you have an independent boiler for this? Gravity fed or did you use a pump?
Comment: Pex - dedicated circuit off a boiler, pumped

Heated flooring under subfloor


Is it correct to convert the object to the string type before converting to the int type?

Question: I have an event handler that works when a certain element is clicked. Is it correct to convert the object to the string type before converting to the int type?
This is my code:
<code>private void selectLanguage(object sender, EventArgs e)
{
int language = Convert.ToInt32((sender as PictureBox).Tag.ToString());
}
</code>
Comment: I suggest you use the [Int32.TryParse Method](https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-6.0) to help if the `Tag` is not a valid `int`. In addition, I assume the posted code is simply an example since the posted code does not really do anything with the `Tags` `int` value.
Comment: If the Tag Element has integer values only then you can directly convert it to int.
Comment: Tag values has object type elements
Comment: I want to know if it is possible to do without a ToString() method
Comment: It will work at compile time - but at runtime your `Tag` property may be null or it may be a type other than int or string. Take @JohnG 's advice and use TryParse and add error handling for if the parse doesn't result in an int
Comment: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-6.0
Comment: _"I want to know if it is possible to do without a ToString() method"_ .... The `Tag` is technically an `Object`, however you can "cast" it to a `string` without errors… . I have to ask… why is using the `ToString()` method undesirable?
Comment: `if (...Tag is int i) ...` If you assigned an int, then it should still be there?
Comment: @DCAggie you want to say that if i "cast" it to `int` without "casting" to `string` it will be errors?
Comment: @IslomMakhsudov I'm saying that there will be errors if you call `.ToString()` if `Tag` is `null` or if `Tag` is an object who's string representation isn't something `Convert.ToInt32` can't handle. Convert can also result in `0` being returned when input is null which may be misleading. Use null checking ( `Tag?.ToString()` ) and check the bool return of TryParse to avoid these pitfalls. I've put together a fiddle to demonstrate https://dotnetfiddle.net/62jukE
Answer: no problem, You should to learn the ctrl-prop
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


What determines operational task replacement cost?

Question: Patch 0.12.12.15.4 introduced a method to reroll operational tasks, usually resulting in a different task. The patch notes do clarify that subsequent replacements will be more expensive (emphasis mine):

Added the ability to replace an operational task in the trader quest
menu. The replaced task will be considered failed. The cost of each
subsequent replacement will increase until the task's completion timer
runs out

Last week, my first replacement was about 40k rubles, the second somewhere in the 100k rubles area, the third about 250k rubles. Today my first replacement is 30k, the second closer to 3M:

The exact amounts are likely changing depending on the base value of the task in question, which in turn appears to be based off my completion history and/or level. But the continuous, now 100-fold increase, only starting with the second replacement per day, seems to be a separate pattern.
Something is adding to my cost well beyond those replaced task's completion timer. Is there any consistent logic behind cost modifiers and their expiry?
Answer: This has been resolved for PMC operational tasks at some point in June, and has now also been fixed for the since newly introduced Scav tasks for the 2022-07-01 hotfix.

Adjusted the Scav operational task replacement cost.

Now each consecutive reroll only increases the cost by around 20%, resetting as the previously replaced task timers run out.


What becomes unlocked after finishing the main story?

Question: I beat the main story and now I am back in Lucis to complete all of the side content and explore the world. In the post-game chapter, a few things become unlocked and I have currently discovered

 The Regalia Type F and Adamantoise Hunt

What all becomes unlocked once you completed the main story?
Answer: The major things that are unlocked in the post-game are as follows:
Extra areas in side dungeons:
Once you have completed the 'Defeat the monster in the inner sanctum' quests of the 8 major dungeons, you'll get a quest which gives you a key to unlock the doors at the end of these dungeons and you will be able to venture further, as described here.

If you're an avid explorer there's a good chance you'll bump into several of these mysteriously locked doors when completing various dungeons progressing through the game. Sadly however, these remain locked until you've completed the entire story – 15 chapters. Once you've completed the game you can initiate a special quest that rewards you with the Dungeon Seal Key – the special item needed to unlock the doors inside FF15's dungeons.

Legendary weapons:
In Lestallum, talking to Randolph will start the questline for legendary weapons. The first quest you will get is A Legend is Born.
More hunts:
In addition to the Adamantoise hunt that you mentioned, there are other hunts, as referenced in this post, which implies that there are a lot more hunts available after completing the main story.

Not the hunts... I think I'm on day 4 of nothing but hunts... so many loading screens....

The Regalia Type-F:
As you've mentioned in the question, you are able to unlock the Regalia Type-F, which allows you to fly instead of drive on the ground. The Regalia Type-F is the only way to access certain areas, such as the Pitioss Ruins.
New Game+:
As mentioned by @DavidYell in the comments, completing the main story will allow you to carry your save into New Game+. Many things carry over from your New Game playthrough. The full details about New Game+ are fleshed out in detail in this Q&A.

As an aside, there are also plans for multiple DLC packs in the future, which will add content for you to do after completing the game (though story completion is not likely to be a requirement).
Comment: New Game+ is probably the most obvious thing you get after completing the game.
Comment: @DavidYell, completely forgot about NG+, whoops. Added that into the answer (and gave you credit)
Comment: I always wondered how to open those special doors in the dungeons... I found about 4 before beating the game


Operation not allowed on IsolatedStorageFileStream

Question: I am reading XML file from Internet. I am writing it to isolated storage and I like to read  it after that.Here is the code
  IsolatedStorageFile isf=IsolatedStorageFile.GetUserStoreForApplication();
    private void findNearestButton_Click(object sender, RoutedEventArgs e)
    {

        findCity(isf);
    }

  private void findCity(IsolatedStorageFile isf)
    {
       filePath = AppResource.exchangeOfficesFile;

            if (!isf.FileExists(filePath.ToString()))
            {
                takeXMLOnLine(isf,filePath);
            }
            parseXMLfile(isf,filePath);

    }

 private void takeXMLOnLine(IsolatedStorageFile isf, string filePath)
    {
        System.Uri targetUri = new System.Uri(AppResource.exchangeOfficesURI);
        WebClient client = new WebClient();
        client.DownloadStringAsync(targetUri);
        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);

    }

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        using (IsolatedStorageFileStream rawStream = isf.OpenFile(filePath, FileMode.Create))
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.ConformanceLevel = ConformanceLevel.Auto;
            using (XmlWriter writer = XmlWriter.Create(rawStream, settings))
            {
                string xmlResponse = e.Result.ToString();
                xmlResponse = xmlResponse.Replace("<", "<");
                xmlResponse = xmlResponse.Replace(">", ">");
                writer.WriteString(xmlResponse);
                // Write the XML to the file.
                writer.Flush();
            }

        }
    }

 private void parseXMLfile(IsolatedStorageFile isf, string filePath)
    {

            using (IsolatedStorageFileStream str = isf.OpenFile(filePath, FileMode.Open, FileAccess.Read))
            {
                StreamReader reader = new StreamReader(str);
                string line;

                while ((line = reader.ReadLine()) != null)
                {

                    MessageBox.Show(line);

                }
                reader.Close();
            }

}
When I run the code I get Operation not allow on IsolatedStoreageFileStream error at this line
  using (IsolatedStorageFileStream str = isf.OpenFile(filePath, FileMode.Open, FileAccess.Read))

Could somebody help me?
Comment: Is there already a file with that name in existence, in isolated storage?
Comment: No there isn't. I run my app with one file name and !fileExist() is always true.
Answer: Try something like this:
using (IsolatedStorageFile rootStore = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream(filePath,
                    System.IO.FileMode.Open, rootStore))
    {
        ... whatever you do with the file goes here
    }
}

Answer: If the file path has a sub directory, see if the directory exists. That could cause this problem.
Comment: It is not a subdirectory I have created it in IsolatedStorage
Answer: Does the file exist when you try to read it? It looks like if the file doesn't exist, you start the download process (but do not wait for completion) and then try to read it.
So instead, something like:
private void findCity(IsolatedStorageFile isf)
{
    filePath = AppResource.exchangeOfficesFile;

    if (!isf.FileExists(filePath.ToString()))
    {
        takeXMLOnLine(isf,filePath);
    }
    else
    {
        parseXMLfile(isf,filePath);
    }
}

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    using (IsolatedStorageFileStream rawStream = isf.OpenFile(filePath, FileMode.Create))
    {
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.ConformanceLevel = ConformanceLevel.Auto;
        using (XmlWriter writer = XmlWriter.Create(rawStream, settings))
        {
            string xmlResponse = e.Result.ToString();
            xmlResponse = xmlResponse.Replace("<", "<");
            xmlResponse = xmlResponse.Replace(">", ">");
            writer.WriteString(xmlResponse);
            // Write the XML to the file.
            writer.Flush();
        }
    }

    parseXMLfile(isf,filePath);
}

Comment: It always says that the file does not exist and try to download it again and there is ObjectDisposeException was unhandled while creating the file...
Comment: I always check on button click if the file exist. If the file doesn't exist I use a function to download it.After that I call function for reading from the file. The problem is that I usually get Operation not allowed on IsoaltedStorageFileStream Exception. I delete the function for reading from the code and call only the writing first, and run the program there isn't any exception.Then I write again the function for reading and it works. Why the first way doesn't work?
Comment: Yes, but you don't wait for the download to complete, so your code is trying to read from a file that doesn't exist - if you compare with the versions I'd suggested, it calls back later, if it had to cue a download.


How to use Team: Signin with VSCode

Question: I am running into an error message which I don't understand while trying the following commande:
Team: Signin
It used to work back then but now I have an error message.
Error message picture

Info:

Version: 1.44.2 (user setup)
Commit: ff915844119ce9485abfe8aa9076ec76b5300ddd
Date: 2020-04-16T16:36:23.138Z
Electron: 7.1.11
Chrome: 78.0.3904.130
Node.js: 12.8.1
V8: 7.8.279.23-electron.0
OS: Windows_NT x64 10.0.18363

I can provide more informations if needed, thank you in advance.
Answer: According to the tag of the question, you are using TFVC version control. With TFVC, the extension uses information about the current workspace to determine how to connect to Azure DevOps Services (or your Team Foundation Server). Workspaces can be created using the Visual Studio IDE, Eclipse or with the JetBrains IDEs (e.g, Android Studio, IntelliJ).
Note: At this time, you will need to have a local TFVC workspace already available on your local machine. More information about the difference between the two types (and how to determine which one you're using) can be found here.
In order to provide TFVC support in Visual Studio Code, the extension relies on the use of a TF command line client. Therefore, you will need to have one already installed and configured. TFVC support will not work without an available command line client.
About sign in :  In order for the extension to be activated, a repository folder must be opened. The extension won't be activated if only a single file in the repository is opened.
You can refer to Team Foundation Version Control (TFVC) Support for details.
In addition, here is a detailed guide that describes how to solve the error you encountered. In this guide, the old version of the azure repo extension(Visual Studio Team Services) is used. Please view step 16.
Comment: Sorry for the late response, you've been very helpful and I managed to fix my issue with your help and the documentation provided.
Thank you very much !

How to use Team: Signin with VSCode


How to change/re-write git history to include original versions of files, unavailable at time of git init

Question: I have started using git to store unix config file changes.
If I start with a system that has already been configured I would like to add the original versions of the files from the distibution into the beginning of the git history so that I can neatly see the changes to these. I intend to reinstall each package on the system one-by-one to get the original config files; store them in git; restore my version of the config file (perhaps using git); then commit the changed version of the file.
Can git do this neatly?
Answer: You are going to have multiple problems:

First, in order to track a file with git, you need to put it into a repository. Configuration files are scattered around your file system, so you cant just put them all into one repository.
Second, some configuration files may change even if their content stays the same. Think of an .xml file that gets read and written again. The structure may have changed, even though it actually contains the same content.
Comment: 1) I am puting them in a repository, that part works file. 2) If a file changes, I want to know about it.
Comment: Then, you can do want you want to do. Just commit your current configs. Then you can reinstall/download/restore the default configs and commit them too. Rebase the commit with the current configs onto the default config commit. Check it out and you have your configs back.
Comment: Can you give a detailed example please. I am not getting the commands in the right order I think. I would like my diffs to show that I applied my changes to the default configs, rather than the other way around.


getting data from non activity class implementing sensoreventlistener

Question: Sorry for the stupid question but i'm new to android and i can't find a solution.
In brief, i have a class with a sensoreventlistener and i want to use data received from sensors in the main activity. I tried but with no success
Here my code:
public class Lis{

SensorManager MagSensorManager;
SensorManager ACCSensorManager;
Sensor magnetometer;
Sensor Accelerometer;
Callback cb =null;
float [] magvec =new float[3];
float [] lin =new float[3];

Lis(Context context, Callback cb)
{

    MagSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
    ACCSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);

    ACCSensorManager.registerListener(listener,Accelerometer, SensorManager.SENSOR_DELAY_GAME);
    MagSensorManager.registerListener(listener,magnetometer, SensorManager.SENSOR_DELAY_GAME);
    this.cb=cb;
}
SensorEventListener listener = new SensorEventListener() {

    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // TODO Auto-generated method stub

}
public void onSensorChanged(SensorEvent event) {

    switch (event.sensor.getType())
    {
    case Sensor.TYPE_MAGNETIC_FIELD:
         magvec = event.values.clone();
         break;
    case Sensor.TYPE_LINEAR_ACCELERATION:
         lin = event.values.clone();
         break;

    }

            SensorManager.getRotationMatrix(Ri, I, lin, magnetic);
        SensorManager.getOrientation(Ri, orientat);
                orientat[0] = (float) Math.toDegrees(orientat[0]);
            cb.azvalue(orientat[0]);

}
}

};

 public interface Callback {
        void azvalue(float azim);

    }

}

public class MainActivity extends Activity implements Lis.Callback{
    TextView tbX;

    Lis listen;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tbX = (TextView)findViewById(R.id.textView1);
        listen=new Lis(this,this);
    }

    @Override
    protected void onPause() {
        super.onPause();

    }
    public void azvalue(float azim)
    {
        tbX.setText("azimuth"+azim);
    }

}
Where am i wrong? If i try to run the apk i get only the default text from tbX textview and not "azimuth"+value.
Thanks in advance.
Comment: use a handler for this purpose
Answer: SensorManager MagSensorManager;
SensorManager ACCSensorManager;

You need only one SensorManager
SensorManager mSensorManager;

In the constructor
Lis(Context context, Callback cb)
{

    mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);

    // You need to initialize these value, otherwise you pass in null
    // and onSensorChanged would not be called as in your case.
    magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    Accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

    mSensorManager.registerListener(listener,Accelerometer, SensorManager.SENSOR_DELAY_GAME);
    mSensorManager.registerListener(listener,magnetometer, SensorManager.SENSOR_DELAY_GAME);
    this.cb=cb;
}


Outlet with both black and white wires hot , only three wires in outlet. my tool plugged in says wired correctly but does not work why?

Question: I have a outlet with a single cable coming into it. It has white, black, and ground. The outlet was not working and says wired correctly. When took it out the black and white wires have power on them. How can I solve the problem?
Comment: How are you testing?  With a multimeter should have 120 between hot and white and hot and ground(bare/green).  White and ground should be 0.  Possible it is wired to be a 240 volt outlet(maybe bad) then white to ground should also be 120.
Comment: Please revise your post to include the information you've provided in comments. Take the [tour] to see why your question needs to stand on its own with enough detail for us to answer. As it is, it's incomplete.
Comment: i unhooked the wires and just used a pen volt tester that beeps showing power on the white and black wire
Comment: its a double breaker  that goes to the basement/tanning bed it says on the breaker box but the outlet is upstairs above the basement. I  recently bought the house
Comment: Depending on the tester, they might show power if the wires are close enough(a few inches) together.  Depending on how it it is wired to the double breaker it might be 240 or two 120v circuits.  Some people should not be near wires, so get a half decent multimeter and see if you can test better.  Turn off breaker for now.
Comment: Make sense now, they was running another outlet off a 240v tanning bed outlet id say. I have a multimeter at home but ill check it, THANKS
Comment: what is the voltage on the screws when the appliance is turned on?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Since it comes off a 240V breaker, it's probably a 240V outlet.
The sure sign is if the two wires on the breaker are black and white.
If that is wired to a standard/common NEMA 5-15 receptacle, that is VERY bad and I would go after the seller's insurer to replace the equipment that just got fried and for an electrician to go over the whole house looking for more negligence.
Here's the deal with outlets.

Quite often, nitwits wire up a 240V circuit and then attach it to a standard NEMA 5-15 outlet because they can't be bothered to reach into the next bin over for a 6-15 or 6-20.  This is grossly negligent of course.
These 240V outlets are usually run with common /2  black-white cable, but you're supposed to re-mark the white wire red or black to indicate it is a hot wire.
However it is permissible to run them with /3 black-white-red cable.
If it's been run with /2 cable, neutral does not exist and there is no way to get 120V out of it while also getting 240V out of it.
/3 cable will allow both 120V and 240V loads to be tapped off of it.
Comment: "Quite often, nitwits wire up a 240V circuit and then attach it to a standard NEMA 5-15 outlet" - [I replaced a 240V outlet with a 120V outlet and my microwave went bang!](https://diy.stackexchange.com/questions/228080/why-would-replacing-this-240-v-outlet-with-a-120-v-outlet-trip-my-breaker)
Answer: You can have live wires to the outlet itself secured by the screws of the outlet and yet the slots of the outlet be worn out.   So as you plug something, the slots on the outlet may not grab the male plug nice and tight.
You can even have correct reading by your meter probs inserted into the outlet slots and yet when you plug something into the outlet may not make good contact.
So make sure the wires are nice and secure feeding the outlet and the outlet slots are grabbing good.
Another interesting test is to plug something into the outlet and leave the plug just a tat out and then check the plug  fingers for power.  If that is good, then whatever you are pluging to the outlet is bad and there is nothing wrong with the outlet.
Now that you know.
Hope this helps.
Take good care.


Function works only for first div

Question: I've got 2 same divs and function like below. My question is, why this work only with first dedicate__wrapper ?
When I click on the second one, nothing happened, no errors in console.
        $(document).ready(function() {
            $(".dedicate__wrapper").on('click', function() {
                        var el2 = document.querySelector(".dedicate__wrapper");
                        var el3 = document.querySelector(".config_submit");

        if (el2.classList.contains('step1')) {
                el3.classList.remove('disable');
              } else {
                      el3.classList.add('disable');
              }
            });

        });

I tried to do add another click event, but nothing helps me. Do You have any ideas ?
Comment: I would start debugging by looking into the fact that var el2 = document.querySelector(".dedicate__wrapper"); gives you TWO results. Your if is likely always false.
Comment: `querySelector` picks only a single element. Use jQuery to get all the elements in this case, jQuery will correctly iterate through all the elements, otherwise you've to do it in your code.
Answer: This specifically refers to the first matching element in the DOM:
var el2 = document.querySelector(".dedicate__wrapper");

In this case, if the element you're looking for is the one you clicked then within the jQuery click handler that's simply this.  For example:

$(".dedicate__wrapper").on('click', function() {
  var el2 = this;

  if (el2.classList.contains('step1')) {
    console.log('if block');
  } else {
    console.log('else block');
  }
});

first

second

Or, to make further use of jQuery:

$(".dedicate__wrapper").on('click', function() {
  if ($(this).hasClass('step1')) {
    console.log('if block');
  } else {
    console.log('else block');
  }
});

first

second

If you have additional elements to identify relative to the clicked element, then starting from $(this) you can traverse the DOM to find that specific element relative to the clicked element.
Answer: document.querySelector returns single element, so your conditions are applied to the first found DOM element.
You will always get first matching el2 and el3
For half code you are using plain js and for another half you are using jQuery
I would rewrite with something like this
$(document).ready(function() {
  $(".dedicate__wrapper").on('click', function() {
    var $el2 = $(this);
    var $el3 = $($(this).find(".config_submit"));//your logic here to find single config_submit

    if ($el2.hasClass('step1')) {
      $el3.removeClass('disable');
    } else {
      $el3.addClass('disable');
    }
  });
});

pseudo fiddle here: https://jsfiddle.net/nitinjs/528x0syo/17/

Function works only for first div