Text not appening at the head of the file

Question: I have the below code doing everything except what I want :-). The goal is simple, I am trying to add the text to appendtext variable at the top of each file present in the directory (and subdirectories), the script runs fine but the text is not getting appended. Where am I going wrong?
import os
import sys
import fnmatch
temp_fname = "temp_file"

appendtext="""Test string
"""
if len(sys.argv) < 2:
    sys.exit('Usage: test.py <build directory>')

for path,dirs,files in os.walk(sys.argv[1]):
    for fname in files:
        for pat in ['*.*']:
            if fnmatch.fnmatch(fname,pat):
                fullname = os.path.join(path,fname)
                with open(fullname, "r") as in_file:
                    with open(temp_fname, "w") as out_file:
                        out_file.write(appendtext)
                        for line in in_file:
                            out_file.write(line)
                os.rename(temp_fname, fullname)

Comment: "Append" means "add to end." What you want is to "prepend."
Comment: @FrancisAvila - problem is its not even appending the text at the end..if it works I can try to chagne to prepend
Comment: Does `print fnmatch.filter(files, pat)` produces anything?
Comment: @J.F.Sebastian - I updated the code that works now..but wondering there is a better way other than creatng a temp_fname
Comment: The pattern `*.*` means "any filename that has at least one period in it".  If you just want "any filename" to match, use the pattern `*`, as I did in my answer.  I will now edit my answer to explain why you need to create a temp file.
Comment: you could use `tempfile.NamedTemporaryFile(mode="w", delete=False)` instead of `open(temp_fname,'w')` and `shutil.copyfileobj()` instead of `for line ...` If you want to use binary file mode then make sure `appendtext` ends with `os.linesep`.
Answer: If you want the text at the top of the file, you should do something like this:
temp_fname = "temp_file"
# the next line doesn't work in Python 2.5, 2.6, or 3.0
with open(fullname, "r") as in_file, open(temp_fname, "w") as out_file:
    out_file.write(appendtext)
    for line in in_file:
        out_file.write(line)
os.rename(temp_fname, fullname)

Here is the above rewritten for Python 2.6:
temp_fname = "temp_file"
with open(temp_fname, "w") as out_file:
    with open(fullname, "r") as in_file:
        out_file.write(appendtext)
        for line in in_file:
            out_file.write(line)
os.rename(temp_fname, fullname)

We can do a little better than this. This always uses the same temporary filename ("temp_file") and that file will always be created in a single directory (the default directory when you run this).  What we really want is a temporary file, with a unique name, created in exactly the same directory as the file we will be editing.  Python provides us with a handy module called tempfile which creates temporary files.
By default, you just get an open file handle and you don't know the filename.  But we need to know the filename, so that after the temp copy is fully done, we can rename it to the original file name.  tempfile provides NamedTemporaryFile for cases like this.
Here is a complete program:
import fnmatch
import os
import sys
import tempfile

headertext = "# header text\n\n"

def want_this_file(fname):
    for pat in ['*']:
        if fnmatch.fnmatch(fname, pat):
            return True
    return False

def prepend_file(fullname, path):
    # with statement means temp file is written and closed at end of with
    with tempfile.NamedTemporaryFile(dir=path, delete=False) as out_file:
        with open(fullname, "r") as in_file:
                out_file.write(headertext)
                for line in in_file:
                    out_file.write(line)
        # before temp file is closed, get its name
        temp_fname = out_file.name
    # rename temp file to fullname, clobbering original
    os.rename(temp_fname, fullname)

start_directory = sys.argv[1]

for dirpath, dirnames, filenames in os.walk(start_directory):
    for fname in filenames:
        if want_this_file(fname):
            fullname = os.path.join(dirpath, fname)
            prepend_file(fullname, dirpath)

This answer uses the pattern "write a temp file, then rename the temp file to the original name".  This is the way you should do it.  It lets the code write the new version, and only when the new version is fully and successfully written, then does a single action to rename the new file to the old filename.  Thus, if anything goes wrong while trying to write the new version, the original file is left untouched.  This is a safe way to solve the problem.
We want to create the temp file in the same directory as the original file, so that the os.rename() operation will be trivially cheap.  On a Linux system, your system temp directory (/tmp) might be on its own partition, and if you just let tempfile create its temporary file there, then the rename operation might involve copying the data again!  If the temp file is in the same directory, the rename operation is always very fast and safe.
EDIT: Here is an improved version of the code.  This catches errors, and cleans up the temp file before re-raising the exception signalling the error.  Also, as J.F. Sebastian pointed out, the files should be opened in binary mode; this does that.
import fnmatch
import os
import shutil
import sys
import tempfile

file_patterns_to_match = ['*']

headertext = "# header text\n\n"
# make any newlines in headertext match the system line ending
headertext = headertext.replace('\n', os.linesep)

def want_this_file(fname):
    for pat in file_patterns_to_match:
        if fnmatch.fnmatch(fname, pat):
            return True
    return False

def prepend_file(fullname, path):
    # with statement means temp file is written and closed at end of with
    with tempfile.NamedTemporaryFile(dir=path, delete=False) as out_file:
        # get the name immediately
        temp_fname = out_file.name

        try:
            # use binary mode to avoid newline translations
            with open(fullname, "rb") as in_file:
                out_file.write(headertext)
                shutil.copyfileobj(in_file, out_file)
        except Exception:
            # on any error, clean up temp file and re-raise exception
            try:
                os.remove(temp_fname)
            except Exception:
                print("unable to clean up temp file: " + temp_fname)
                pass
            raise
    # rename temp file to fullname, clobbering original
    os.rename(temp_fname, fullname)

start_directory = sys.argv[1]

for dirpath, dirnames, filenames in os.walk(start_directory):
    for fname in filenames:
        if want_this_file(fname):
            fullname = os.path.join(dirpath, fname)
            prepend_file(fullname, dirpath)

Comment: steveha - am using pythong 2.6.5,its giving compilation error at with open(fullname, "r") as in_file, open(temp_fname, "w") as out_file:
                                       ^
SyntaxError: invalid syntax, is there a way we can do this without creating a temp file in python 2.6.5
Comment: You can do this without a temp file by reading the entire file into memory and then overwriting the file. *However*, a temp file is much safer and uses less memory. It is *impossible* to prepend to a file without writing out the whole file again.
Comment: I have updated this to show how to nest the `with` statements in Python 2.6.  The version that uses `tempfile.NamedTemporaryFile` already uses nested `with` statements and should work for you.
Comment: you should use either text or binary mode (use os.linesep for headertext in this case) for files everywhere otherwise newlines might be corrupted. shutil.copyfileobj and fnmatch.filter might simplify the code.
Comment: @J.F.Sebastian, those are excellent points.  I was already editing to make a new version that cleans up the temp file if any error occurs; I'll look at your suggestions now.
Comment: @J.F.Sebastian, `fnmatch.filter` doesn't seem like a good fit here, since the original code suggests a list of possible extensions to match.  `shutil.copyfileobj` replaces a simple two-line loop with one line, not a huge win, but might speed the code since it pushes the copying down into Python itself.  The temp file is opened in binary mode by default, and now I modified the code to open the input file in binary mode.  See updated code at end of answer.
Comment: for a list of patterns I'd use a combined regex instead. copyfileobj handles arbitrary large lines.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/22425/discussion-between-steveha-and-j-f-sebastian)
Comment: @steveha - Lets say I want to add one more feature to this like ..if the file has  a multiline comment where one-line matches the string "Test 2012, Test foundation. All tests",I want to delete the whole comment,not jsut the line...how difficult it is do  it?
Answer: I know your question is about your python script. But you can achieve this in a one liner in bash using perl.
sgeorge-mn:stack sgeorge$ cat file_0*
Hi - 1
Hi - 2
Hi - 3
Hi - 4
Hi - 5

sgeorge-mn:stack sgeorge$ find . -type f
./file_01.txt
./file_02.txt
./file_03.txt
./file_04.txt
./file_05.txt

sgeorge-mn:stack sgeorge$ find . -type f -exec  perl -pi -e 'print "Please donot add any comments \nThis is a header file.\nJust a test.\n" if $. == 1' {} \;

sgeorge-mn:stack sgeorge$ cat file_0*
Please donot add any comments
This is a header file.
Just a test.
Hi - 1
Please donot add any comments
This is a header file.
Just a test.
Hi - 2
Please donot add any comments
This is a header file.
Just a test.
Hi - 3
Please donot add any comments
This is a header file.
Just a test.
Hi - 4
Please donot add any comments
This is a header file.
Just a test.
Hi - 5

Comment: `find /start/dir -type f -exec sed -i '1i line to prepend' {} +`


If the function $\sqrt{x} \sin x$ is uniformly continuous on $\mathbb{R}$

Question: First confusion is $\sqrt x$ has a domain of $[0, \infty)$, how we can say anything on $\mathbb{R}$?
If for $[0, \infty)$ than it is a continuous function on $(0, \infty)$ but what about the point zero will it be uniformly continuous there are not?
Comment: could you  please frame your question better , it is hard to understand
Comment: It have limit $+\infty$.
Comment: Your first confusion is valid : clearly uniform continuity was meant only on the domain i.e. $[0,\infty)$. But it won't hold : as $x\to \infty$, try to use the fact that $\sqrt x \sin x$ is "too slopy". A higher slope means that points are close but their function values are far. Use the mean value theorem, our friend is certainly differentiable apart from $0$, which needs care.
Answer: Hint:
Take $x_n = n\pi$ and $y_n = n\pi + \frac{1}{\sqrt{n}}$ and show that $|y_n-x_n| \to 0$ but $|f(y_n) - f(x_n)|\not\to 0$ as $n \to \infty$.


Music Player in C# Does Tot Play The Song I Added Later

Question: I made an mp3 player in C#. If I select the songs at once, they automatically play one after the other, but when it comes to a song I added later, I get a "System.IndexOutOfRangeException" error. When I add music later, I want the song to play automatically one after the other, how can I do that?
string[] yol, dosya;
private void Btn_Muzik_Ekle_Click(object sender, EventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    ofd.Multiselect = true;
    if (ofd.ShowDialog()==System.Windows.Forms.DialogResult.OK)
    {
        dosya = ofd.SafeFileNames;
        yol = ofd.FileNames;
        for (int x = 0; x < dosya.Length; x++)
        {
            Lb_Muzik_Listesi.Items.Add(dosya[x]);
        }
    }
}

private void Lb_Muzik_Listesi_SelectedIndexChanged(object sender, EventArgs e)
{
    //This Is Where I Got The Error
    OynatmaEkranı.URL = yol[Lb_Muzik_Listesi.SelectedIndex];
    OynatmaEkranı.Ctlcontrols.play();

    try
    {
        var file = TagLib.File.Create(yol[Lb_Muzik_Listesi.SelectedIndex]);
        var bin = (byte[])(file.Tag.Pictures[0].Data.Data);
        Pb_Muzik_Kapak.Image = Image.FromStream(new MemoryStream(bin));
    }
    catch
    {

    }
}

private void Zamanlayıcı_Tick(object sender, EventArgs e) //Timer
{
    if (OynatmaEkranı.playState==WMPLib.WMPPlayState.wmppsPlaying)
    {
        Pb_Muzik.Maximum=(int)OynatmaEkranı.Ctlcontrols.currentItem.duration;
        Pb_Muzik.Value = (int)OynatmaEkranı.Ctlcontrols.currentPosition;
        try
        {
            Lbl_Muzik_Sure.Text = OynatmaEkranı.Ctlcontrols.currentPositionString;
            Lbl_Muzik_Bitis.Text = OynatmaEkranı.Ctlcontrols.currentItem
                .durationString.ToString();
        }
        catch
        {

        }
    }

    if (Pb_Muzik.Value==Pb_Muzik.Maximum)
    {
        if (Lb_Muzik_Listesi.SelectedIndex<Lb_Muzik_Listesi.Items.Count-1)
        {
            Lb_Muzik_Listesi.SelectedIndex = Lb_Muzik_Listesi.SelectedIndex + 1;
        }
    }
}

Comment: In Btn_Muzik_Ekle_Click, you must clear your ListBox items or Add extra items to yol. Now, you add extra items to ListBox but not add extra items to yol, you are replacing yol array.
Answer: You can avoid this problem managing your data in the ListBox. Create a class with your required info (the file and the name):
public class MuzikItem
{
    public MuzikItem(string file)
    {
        this.Text = System.IO.Path.GetFileNameWithoutExtension(file);
        this.Url = file;
    }

    public string Text { get; set; }
    public string Url { get; set; }

    public override string ToString()
    {
        // This is the text to show in ListBox
        return this.Text;
    }
}

Add items to the ListBox using this class:
foreach (var file in ofd.FileNames)
{
    var item = new MuzikItem(file);
    Lb_Muzik_Listesi.Items.Add(item);
}

And use it:
var item = Lb_Muzik_Listesi.SelectedItem as MuzikItem;
if (item != null)
{
    OynatmaEkranı.URL = item.Url;
    OynatmaEkranı.Ctlcontrols.play();

    try
    {
        var file = TagLib.File.Create(item.Url);
        var bin = (byte[])file.Tag.Pictures[0].Data.Data;
        Pb_Muzik_Kapak.Image = Image.FromStream(new MemoryStream(bin));
    }
    catch
    {
    }
}

You try to get the selected item as a MuzikItem (all your items are of this class so this return null only when no item is selected) and with this, you have the Url.
UPDATE
I like manage this things with events. In your Ticks methods:
if (Pb_Muzik.Value == Pb_Muzik.Maximum)
{
    OnSongFinished();
}

And create a method to manage this event:
private void OnSongFinished()
{
    if (Lb_Muzik_Listesi.SelectedIndex < Lb_Muzik_Listesi.Items.Count - 1)
    {
        Lb_Muzik_Listesi.SelectedIndex = Lb_Muzik_Listesi.SelectedIndex + 1;
    }
    else
    {
        // Stop the player
        OynatmaEkrani.Ctlcontrols.stop();
    }
}

Comment: So how can I stop the song when it reaches the final index? It still takes the last song of the playlist I added as the last index, and it doesn't take the song I added later as the last index. I used this                                                                                if (Lb_Muzik_Listesi.SelectedIndex==Lb_Muzik_Listesi.Items.Count-1 & Pb_Muzik.Value==Pb_Muzik.Maximum)
            {
                OynatmaEkrani.Ctlcontrols.stop();
            }
Comment: I update my answer but your code seems ok.


Getting an attribute value from an XML node in Swift

Question: I am trying to get the value of an attribute in an XML Node in swift.  The following is a code example.  I don't see any way of getting the value as no properties or methods seem to allow for this.
for word in dictionary.words {
    let xpath = "/strongsdictionary/entries/entry[greek[@unicode='" + word.word + "']]/pronunciation"
    do {
        let xmlnode = try document?.nodes(forXPath: xpath )
        // Need to get value of attribute named 'strongs' from the node here.
    } catch {
        debugPrint("Error finding xpath path.")
        break
    }
}

Comment: This is for macOS.
Comment: Is this for macOS or iOS?
Answer: xmlnode is an array of XMLNode. Iterate the array of nodes. If your xpath returns elements, then cast each node to an XMLElement. From the element you can get the its attributes.
let xmlnodes = try document?.nodes(forXPath: xpath)
for node in xmlnodes {
    if let element = node as? XMLElement {
        if let strongsAttr = element.attribute(forName: "strongs") {
            if let strongs = strongsAttr.stringValue {
                // do something with strongs
            }
        }
    }
}

You can combine the three if let into one but the above is easier to debug.
Comment: Thanks so much!  Your an ace.  That did the trick.  It was not that obvious to me from reading the scetchy documentation.
Comment: Glad to help. Please don't forget to accept an answer that properly answers your question. Click the checkmark to the left of the answer.
Answer: An attribute is just another node. Change your XPath expression to find it:
let xpath = "/strongsdictionary/entries/entry[greek[@unicode='" + word.word + "']]/pronunciation/@strongs"

The .nodes method returns a list of nodes. Make sure the list is not nil and has one node:
    // Get value of attribute named 'strongs'
    if let xmlnode = try document?.nodes(forXPath: xpath ), xmlnode.count == 1 {
        print(xmlnode[0].objectValue)
    }

Comment: I could find it that way but I couldn't figure out how to get the value out of it.  Thanks for the help.


Pointer arithmetic confusion or weird behavior

Question: When the following has run, I get _pfloatPos and _charPos being different:
    float* const _pData = new float[0x50000000];

    float*  const _floatPos = _pData + 0x400000B0;
    char*   const _charPos = ((char*)_pData) + 0x400000B0 * 4;

    if ((char*)_floatPos !=  _charPos)
    {
        throw "Derp.";
    }

Maybe I've got brain fog and missed something basic. The two addresses should be the same, right?
I looked at the disassembly. 1000002C0h is 4 * 0x400000B0 . For the second one it seems to have been truncated at some point.
        float*  const _floatPos = _pData + 0x400000B0;
00007FF7CE48F6E2  mov         rax,1000002C0h
00007FF7CE48F6EC  mov         rcx,qword ptr [_pData]
00007FF7CE48F6F0  add         rcx,rax
00007FF7CE48F6F3  mov         rax,rcx
00007FF7CE48F6F6  mov         qword ptr [_floatPos],rax
        char*   const _charPos = ((char*)_pData) + 0x400000B0 * 4;
00007FF7CE48F6FA  mov         rax,qword ptr [_pData]
00007FF7CE48F6FE  add         rax,2C0h
00007FF7CE48F704  mov         qword ptr [_charPos],rax

I am using visual Studio 2017 Version 15.9.2, but I'm not sure about the version of the compiler.
Answer: The two integer literals 0x400000B0 and 4 are each only given 4 bytes (even in x86-64), and so multiplying them causes an overflow.
Appending L's doesn't change anything. Appending LL's makes them 64-bit, and solves the problem. But my solution will be to use std::int64_t for ints from now on.

Test:
#include <iostream>
#include <cassert>
using namespace std;

int main()
{
    { // plain literals
        float* const _pData = 0;
        float* const _floatPos = _pData + 0x400000B0;
        char* const _charPos = ((char*)_pData) + 0x400000B0 * 4;

        assert((char*)_floatPos != _charPos);
    }

    { // append L
        float* const _pData = 0;
        float* const _floatPos = _pData + 0x400000B0L;
        char* const _charPos = ((char*)_pData) + 0x400000B0L * 4L;

        assert((char*)_floatPos != _charPos);
    }

    { // append LL
        float* const _pData = 0;
        float* const _floatPos = _pData + 0x400000B0L;
        char* const _charPos = ((char*)_pData) + 0x400000B0LL * 4LL;

        assert((char*)_floatPos == _charPos); // success
    }
}

Answer: You need 0x400000B0 * 4L or the multiplication will overflow.


Graphics problems with applications

Question: For some reason, I've got some graphical issues sometimes. Mostly with AbiWord, LibreOffice (and OpenOffice.org), and Wine applications. I've added some screenshots below t oclarify a bit.
This is not a problem that recently popped up. As a matter of fact, I've always had it since Ubuntu 8.10, and there never came an update to fix it. I'm currently using Linux Mint 10 (based upon Ubuntu 10.10), but as I already said, that doesn't really say much as I'va also had this problem with Linux Mint 8, Ubuntu 8.10, Ubuntu 9.04, Ubuntu 9.10 and Ubuntu 10.04. It was never a big problem, as I rarely used any text processing programs. But recently, I'm starting to use them more and more, and it's really annoying being unable to work because of this problem. When I first open an application, everything looks normal, then after a while (when I highlight, click, ... an item) they'll suddenly screw up. This also happens when I move or resize the window. Sometimes when this happens, I can just minimize the window, and when i restore it, sometimes it will be gone (for a few seconds at least) or it will have changed positions.
I'm using the nvidia-current graphics card driver. But I have also always had this problem on my old computer, wich used... I think nvidia-96.
Screenshots

(I've done the blur myself, so that's not the issue, the problem is that blue crap)
Comment: What video card are you using?
Comment: @bgvaughan NVidia Quadro NVS 110M
Comment: What theme are you using? I've had similar issues when I used dark themes
Comment: Mix of Shiki-Wise and  Mint-X-Metal.
Comment: Do you have the same trouble if you switch to the Ambiance or Radiance themes?
Comment: @bgvaughan Don't know. I haven't got these themes. However, on my previous PC I used the default Ubuntu 10.04 theme (Ambience?), and the same problem occured there?
Comment: No'one with a solution? >.<
Comment: If scottl's answer is the right one you might be able to solve it with the mentioned workaround.
Answer: It's a known bug in the nvidia drivers. Unfortunately, since you're using proprietary drivers, there is no way of getting this bug fixed except by maybe complaining on nvnews.net (where some nvidia reps hang out).
So the solution is to use the workaround listed in the bug report, or to switch to the free drivers.
And next time you're buying graphics hardware, remember nvidia's buggy drivers.. :-P
Comment: It came with this laptop. And I experienced that ATI's drivers can be far more buggy than NVIDIA's. As far as I know I'm am using the free driver.... (the one jockey recommended me). Anyway, I'll take a look at the workaround and see if it works.
Comment: Jockey only recommends non-free drivers. And AMD and Intel both actively develop Free drivers :-)
Comment: Then... wich are the free ones? The ones it used by default when my distro installation was finished? Anyway, I'm going to give you the bounty as there doesn't really seem to be a working solution for this problem, and you seem to have correctly identified the problem.
Comment: Yes, the drivers installed by default are the free nouveau drivers. Nvidia doesn't support open-source software, so nouveau doesn't have the 3D performance that the proprietary driver offers. A recent performance comparison between the two drivers is here: http://www.phoronix.com/scan.php?page=article&item=nouveau_linux3
Answer: I am using Mint18.6, and the DAW reaper , and some of the UI of the plugins dont show correctly , with wine1.6, it appears to be ok in eOS with wine-rt2.0.1.
Installing wine-rt 2:2.0.1 in Mint Mate 18.3 solved the problem.
Answer: What version of Java are you using (specifically, is it the latest)? If you're using openJDK, have you tried using Sun Java (and purging OJDK)? I can't speak for AbiWord, and your "Wine programs" is too vague, but I know LO/OO.o runs on Java, and Java issues sometimes manifest as UI issues. Since Java isn't dependent on the OS, it could explain why your issue persists through distros.
Comment: `$ apt version sun-java6-jre`: `6.24-1build0.10.10.1`|
`$ apt version openjdk-6-jre`: `6b20-1.9.7-0ubuntu1`
Comment: Try purging one of them. It's possible that having both installed is causing conflicts. (Since OpenJDK usually is installed by itself in Ubuntu, I'd go with purging it and trying Sun Java alone.)
Comment: Urk... You gotta be kididng me xD It seems to be solved. I'll see if it's really solved by using the programs for a (few) day(s), and then I'll award the bounty. Anyway, I installed OpenJDK for running Java games, as Sun Java seems to be a disaster. Do you happen to know a solution for that as well? Is there some kind of way to choose wich version of Java should be used for LibreOffice, ...? The strange thing is that as far as I know, Wine and AbiWord don't use Java :p
Comment: Nope, it's not solved. As sometimes happens, it takes a while before the trouble starts.
Comment: Wine itself doesn't use Java that I know of, but whether an application does depends on the application. Saying that Wine does or doesn't use Java is kind of like saying Wine does or does not use DirectX (vs OpenGL). Wine technically doesn't use either of them, but the applications that run under Wine might.
Comment: As for LibreOffice/OO.o and Java, there's a "Java" menu in the Preferences that should list out the runtime libraries it detects. You might be able to remove all but one and force it to use a certain runtime that way.

Graphics problems with applications


error ubxtool : failed to import gps,check PYTHONPATH

Question: I want to use ubxtool.
jhkim@***:~$ ubxtool

ubxtool: failed to import gps, check PYTHONPATH

gpsd-3.21 , ubuntu 18.04
How do I solve it?
Comment: As you built this yourself, can you please post the contents of the `ubxtool` file so we can see what we are dealing with? Thanks!
Answer: There are some clues that ubxtool is available only since Ubuntu 20.04 LTS, with gpsd-3.20.
So you have to backport it manually from 20.04 LTS to 18.04 LTS by following the method below:
sudo apt-get build-dep gpsd
sudo apt-get install build-essential dpkg-dev python3-all-dev python3-all-dbg dh-apparmor dh-exec asciidoc

cd ~/Downloads
wget http://archive.ubuntu.com/ubuntu/pool/universe/s/scons/scons_3.1.2-2_all.deb
sudo apt-get install ./scons_3.1.2-2_all.deb

mkdir -p ~/Downloads/gpsd
cd ~/Downloads/gpsd

wget http://archive.ubuntu.com/ubuntu/pool/main/g/gpsd/gpsd_3.20.orig.tar.xz
tar -xf gpsd_3.20.orig.tar.xz
cd gpsd-3.20
wget http://archive.ubuntu.com/ubuntu/pool/main/g/gpsd/gpsd_3.20-8ubuntu0.2.debian.tar.xz
tar -xf gpsd_3.20-8ubuntu0.2.debian.tar.xz
mv gpsd_3.20-8ubuntu0.2.debian.tar.xz ../

dpkg-buildpackage -uc -us

sudo apt-get install ../*gps*.deb

And as the result you will get ubxtool with its python binding:

$ ubxtool -V
ubxtool: Version 3.20

Comment: Thank you but  I have a problem. this command" $ ubxtool  -V " ->" ubxtool: ERROR: need gps module version 3.21, got 3.20"
Comment: I would suggest to remove yours 3.21 with some kind of `sudo make uninstall` inside its source code and retry with my method.
Comment: I removed my gpsd 3.21 version . You said, remove some kind of **sudo make uninstall** inside its source code. how to remove it?
Comment: I mean "inside source code" *directory*.


Can other forms of avoiding damage block the "Phase Shift" achievement?

Question: On a recent playthrough on easy using the Stealth Cruiser; Layout 1 The Nesasio, I tried to unlock the "Phase Shift" achievement. This achievement requires that you avoid 9 points of damage in a single cloak, to this end I fully upgraded and powered the Cloak system and used it just as I saw a lot of damage coming from an enemy ship that I counted to total more than 9, but the achievement didn't ding. I even completely dodged the third stage power surge of the boss with a cloak which should have totaled 12 damage. (I got my high score off this run though :P )
This made me think that maybe the game thought I didn't avoid 12 points of damage using only Cloak, as my fully upgraded shields and engines may have helped avoid some, most likely the shields. Did I not receive the achievement because my shields would have taken off most of that or my engines alone would have saved me?
I really want this achievement to unlock the Stealth Cruiser Layout 2 as I have found that Tactical Approach is influenced more heavily by luck (A Hazard being your only possible route at times.)
Comment: You could test this by deactivating shields and removing your pilot from the helm (without auto-pilot) just before cloaking.
Comment: Removing power to engines is an easier way to eliminate all dodging
Comment: Yeah I thought removing my other defensive systems might help, I just didn't want to try this on one of my early playthroughs with this ship because if it all went pear-shaped that there Boss would have lowered my self esteem. Thanks
Answer: For best results, you need lots of incoming damage; asteroids count.
Here's how I unlocked that achievement:

Fully-upgraded Cloak (of course)
Find a late-game enemy with lots of weapons (preferably burst lasers) in an asteroid field.
Cloak when just about everything is firing, and hope that all of that incoming damage (plus a few asteroids) is enough.

Shields don't affect this achievement; you're looking for misses, not simply damage avoided. I'm not sure if having a naturally-high dodge (i.e., engines + skill) affects this achievement, but my wild guess is that the game is simply looking for a dodge-while-cloaked, rather than a dodge-due-to-cloak-evasion-bonus-only.
Answer: Doesn't seem possible to get this achievement currently.
 Used on Flagship wave3, with the cloak up: 3 missiles, 3 laser rounds AND the power surge laser spray all missing in one go. Didn't work.
Repeated with 0 shields on. Didn't work.
Removed engine power to prevent dodging, resulted in only a 60% dodge chance from the cloak alone, which resulted in pretty much every single projectile hitting at once and the entire ship filled with flames. Twice. 60% dodge my ass.
Something is definitely bugged with it at the moment.
Comment: Yes I realise this now, when I did eventually get it it seems like a random moment just cloaking at the start of a reasonably strong enemy ship encounter.
Comment: If you don't have a pilot/autopilot and powered engines, your chance of dodge is 0% - regardless of other bonuses
Answer: Actually, since I've had this problem too, I'd like to share my 5c on the question asked by OP:

other forms of damage prevention doesn't count as long as the shots still miss, since evasion is proc'ing before almost everything else (shields/Zoltan Shields/resistance etc) except Defense Drones (and possibly other drones if you're [un]lucky), which block the shots preventing the evasion at all!
your piloting/engines bonuses actually help you with getting this one, since you don't automatically get 100% evasion with cloak, but only +60%; it's imperative to get at least 40% base evasion before cloak to maximize the chance of getting this cheevo.
the achievement is 100% gettable ATM, I don't know what was the case with it 2 years ago, but now you can 100% get it, and it's not bugged - but see below
you actually can and should get it on wave 3 of Rebel Flagship - only bear in mind that it takes some time and luck to get it
remember that misses before full shield activation doesn't count here and misses after the activation basically won't happen (since cloak stops weapon fire, it could only happen with asteroids) - that's the obvious reason why you rather won't be able to get it on every single try (and why you - and me too! - didn't get it on the first try)

The best way to get it is to actually:

approach Rebel Flagship 3 (easy difficulty with AE disabled comes to mind if you're not an FTL vet),
permanently disable Triple Leto Missile Launcher, since it's the only weapon capable of punching through the shields and posing a real risk for cheevo grinding (preferably by using a boarding party but fire bombs or concentrated laser fire works wonders here too), but leave the Heavy Triple Burst Laser intact - and remember to leave at least 1 crew member alive (AI!),
remember that Hull Repair Drone, high base evasion and 4 shields are helpful on every difficulty above easy, but you can manage getting easy cheevo with just an almost-full HP ship and 3 shields with a bit of luck; mitigating the risk of Mind Control on AE is important too, but you should probably try getting this achievement with AE disabled anyway,
wait for the Power Surge, as soon as you see the Flagship shooting the surge but before they enter your ship view activate evasion,
rinse, repeat until Cheevo Get. This will happen most probably when the burst is timed with regular Heavy Triple Burst Laser shot.

The only thing that made me wonder is the fact that Power Surge actually uses 8 shots - I can't recall, but if every of them is 1 damage only, you actually have to have the surge timed with regular 3x Flagship Laser to be able to evade 9 damage. Alternatively, the description could be simply wrong in that it requires 9 shots evaded, not 9 damage (although I seriously doubt that); that would be the reason it's a bit harder to get this cheevo than to simply wait for RF 3 Power Surge.
Alternatively, you can get the asteroid field with some late-game enemy (as pointed out by Paul Marshall), although I'd say it's actually the harder way, since a) asteroid fields ain't that common in the endgame, b) there's only a slight chance you'll be able to encounter a ship with so high damage output in one burst, other than the mentioned Rebel Flagship
more info (although it's been mostly already stated here): http://ftl.wikia.com/wiki/Phase_Shift


Quick code to get a WPF Visual to DirectX Texture (performance wise)

Question: Well, the problem is simple, I have something rendered on a WPF Visual. I want to get it to on a DirectX Texture. At present, I using the following code to get the job done.
var bmp = new System.Windows.Media.Imaging.RenderTargetBitmap(bound.Width, bound.Height, 96, 96, System.Windows.Media.PixelFormats.Pbgra32);
bmp.Render(drawingVisual);
var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));
Texture texture = new Texture(dxDevice, bound.Width, bound.Height, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default);
using (MemoryStream ms = new MemoryStream())
{
    encoder.Save(ms);
    ms.Seek(0, SeekOrigin.Begin);
    Surface privateSurface = texture.GetSurfaceLevel(0);
    SurfaceLoader.FromStream(privateSurface, ms, Filter.None, Color.MediumAquamarine.ToArgb());
    ms.Close();
}
return texture; // our prepared texture

But it's somewhat slow, in an obvious manner. Can you guys suggest something which could possibly make it quicker?
[EDIT] I tried to load the data using CopyPixels(), but it throws D3DXERR_INVALIDDATA exception.
RenderTargetBitmap bmp = GetBitmap();
// copy into a byte array
int stride = bmp.PixelWidth * 4;
byte[] data = new byte[bmp.PixelHeight * stride];
bmp.CopyPixels(data, stride, 0);

// create texture
using (MemoryStream ms = new MemoryStream(data))
{
    ms.Seek(0, SeekOrigin.Begin);

    if (dxDevice != null)
    {
        // next line throws D3DXERR_INVALIDDATA exception
        texture = TextureLoader.FromStream(dxDevice, ms);
    }
}

[EDIT] Ok, so here's how I managed to do it.
RenderTargetBitmap bmp = GetBitmap();
// copy into a byte array
int stride = bmp.PixelWidth * 4;
byte[] data = new byte[bmp.PixelHeight * stride];
bmp.CopyPixels(data, stride, 0);

// create texture
Texture texture = new Texture(dxDevice, bound.Width, bound.Height, 1, Usage.SoftwareProcessing, Format.A8R8G8B8, Pool.Managed);
Surface privateSurface = texture.GetSurfaceLevel(0);
var graphicsStream = privateSurface.LockRectangle(LockFlags.None);
graphicsStream.Write(data);
privateSurface.UnlockRectangle();

Answer: Yes. You can still use RenderTargetBitmap. But instead of encoding it to PNG and reading in Direct3D, you can call CopyPixels on your RenderTargetBitmap and then write the pixels directly to your texture. Should be much faster!
// render the visual, just like you did
var bmp = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Default, null);
bmp.Render(visual);

// get the pixels
var pixels = new int[width * height];
bmp.CopyPixels(pixels, 4 * width, 0); // each line consists of 4*width bytes.

And now, depending on the exact API you use (SlimDX? Something else?) you need to lock your texture, and write the data in the pixels array to the texture.
Comment: FromStream doesn't do what you think. It tries to load a known file format, not raw texture data. If you are using SlimDX, the correct thing to do is texture.GetSurfaceLevel(0), lock the surface and write the pixels directly to the surface.
Comment: Updated my question. I did try to do what you suggested but it throws D3DXERR_INVALIDDATA exception. Anything else you wanna suggest?
Comment: Well, I thought so. Thanks for pointing me to the 'right' API. I'll give it a try and let you know.
Comment: I could use LockRectangle() only on texture from Pool.Managed with Usage.SoftwareProcessing. Any idea why? BTW just updated my question with what I did based on your suggestion. Thanks a lot Alex!


Issue with Hybrid Azure AD join of Windows 7 devices

Question: I am trying to do Hybrid Azure Ad join of Windows 7 devices but while trying to enable Hybrid Azure Ad join in AD connect the check box for Supported Windows Downlevel domain-joined devices is disabled.Hybrid Azure AD join of Windows 10 devices are working fine.
Any suggestions why it is disabled.
Answer: In almost all cases if you can not enable an option it means it is not support.


Rails migration delete row

Question: I'm trying to run a migration to delete two rows in the database. Here's the migration file ...
class RemoveMenuItem < ActiveRecord::Migration
  def up
    MenuItem.delete(name: "Validation Settings")
    MenuItem.delete(name: "Identifier Lookup")
  end

  def down
    MenuItem.create(name: "Validation Settings", type: "MenuItem", actionable_item_id: 89, actionable_items_count: 0, sequence: 20)
    MenuItem.create(name: "Identifier Lookup", type: "MenuItem", actionable_item_id: 89, actionable_items_count: 0, sequence: 30)
  end
end

... but I'm getting this error ...
PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "id"
LINE 1: ...ERE "actionable_items"."type" IN ('MenuItem') AND "id"."name...
                                                             ^
: DELETE FROM "actionable_items" WHERE "actionable_items"."type" IN ('MenuItem') AND "id"."name" = 'Validation Settings'/Users/kweihe/.rvm/gems/ruby-2.1.6/gems/activerecord-3.2.22/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'

Comment: Aren't migration used for modifying database schema? And you are actually dealing with database data. For this, I think you should use schema file!
Answer: Deletes require an identified record to work. Try this:
 def up
      MenuItem.find_by(name: "Validation Settings").delete
      ....

I agree with the commenter though - this doesn't seem like something you necessarily want in your migrations. Probably better in a seed file.
Answer: SOLUTION
class RemoveActionableItems < ActiveRecord::Migration
  class ActionableItem < ActiveRecord::Base
    attr_accessible :actionable_item, :name, :sequence, :type
  end
  def up
    validation_settings = MenuItem.find_by_name("Validation Settings")
    identifier_lookup = MenuItem.find_by_name("Identifier Lookup")
    compliance = InsightReportMenuItem.find_by_name("Compliance")
    validation_settings.delete unless validation_settings.nil?
    identifier_lookup.delete unless identifier_lookup.nil?
    compliance.delete unless compliance.nil?
  end

  def down
    MenuItem.create :name => "Validation Settings", :type => "MenuItem"
    MenuItem.create :name => "Identifier Lookup", :type => "MenuItem"
    InsightReportMenuItem.create :name => "Compliance", :type => "InsightReportMenuItem"
  end
end

Rails migration delete row


Disabling a script once target location is reached?

Question: How can I have my enemy disable a script once it reaches target player? I want to reference this script called casting under my GameManager in my code and disable it but I'm unsure how to write the function for when target location is reached.
public float lookRadius = 40f;

Transform target;
UnityEngine.AI.NavMeshAgent agent;

Rigidbody theRigidBody;

void Start()
{
    target = PlayerManager.instance.player.transform;
    agent = GetComponent<UnityEngine.AI.NavMeshAgent>();
}

void Update()
{
    float distance = Vector3.Distance (target.position, transform.position);
    if (distance <= lookRadius)
    {
        agent.SetDestination (target.position);

        if (distance <= agent.stoppingDistance)
        {
            FaceTarget ();
        }
    }
}

void FaceTarget()
{
    Vector3 direction = (target.position - transform.position).normalized;
    Quaternion lookRotation = Quaternion.LookRotation (new Vector3 (direction.x, 0, direction.z));
    transform.rotation = Quaternion.Slerp (transform.rotation, lookRotation, Time.deltaTime * 5f);
}

// Use this for initialization
public void OnObjectSpawn ()
{
    //myRender = GetComponent<Renderer> ();
    theRigidBody = GetComponent<Rigidbody>();
}

void OnDrawGizmosSelected()
{
    Gizmos.color = Color.red;
    Gizmos.DrawWireSphere (transform.position, lookRadius);
}

Answer: You need to obtain the gameobject that has the script, get the script on that gameobject, and disable.
if (distance < 1f) // or some distance
{
    Gameobject mygo = GameObject.Find("GameManager"); // or some other method to get gameobject.
    mygo.GetComponent<casting>().enabled = false;
}

Comment: Thanks. Also, how will I detect when target is reached? do I add a function called `public void TargetReached()`?
Comment: you already have the `distance` between the transform and your target. pick a value for how close you need to be.


dynamic resizing of iframe for cross domain servers without access

Question: My object is to  remove the scrollbars of an iframe for cross domain servers, which I don't have access to.

Page A has an iframe which displays contents of an external server
The content is not fixed, its height changes with time so I can not fix the height, it has to be dynamic.
It has to be handled with JavaScript. I have a list of objects corresponding to the users selection. When a different selection is made, different content types are shown.

I have tried to a solution with postMessage, but it does not solve the problem as I don't have access to the server. I was thinking more of a view, which resizes the iframe when the page is loaded.
Answer: You can't. There is no way to determine the size of a page in a cross-domain iframe without explicit support from scripts running on that page. Since you've already said that you can't modify that page, there's no way to do this.
Comment: i was thinking more of a automatic script on a separate thread which will adjust the view after page is loaded....
i am new to this , is there a kind of view to handle it?
Comment: No. Nothing you do on your page can get the size of a page in a cross-domain frame. Threads have nothing to do with it.


error trap user input - Bash script loop

Question: Im trying to error trap a user input.
-I need the user to enter a file name.
-some users are entering the full url and that kills the rest of the script.

so if the users enters http:// i want the script the give an error message and make them enter just the file name.

-this needs to repeat every time the user enters the url.

if they enter the file name then the rest of the script executes.

this is what i have so far. if the user enters the url once it works, but if he enters it wrong twice it will execute the rest of the script
#!/bin/bash
read -p "Enter File : " string

if [[ $string -ne *"http://"* ]];
then
s3cmd get s3://backup/domain.com/$string

elif [[ $string -ne *"http://"* ]];
echo "You entered the full URL, enter on the file name"
read -p "Enter File : " string

then

s3cmd get s3://backup/domain.com/$string

else
    echo "rest of script"
fi

Answer: If you can detect that the user entered a full URL, then why not simply strip the prefix and avoid bothering the user with that?
http_prefix="http://"
if
  [[ $string =~ ^$http_prefix(.*) ]]
then
  string=${BASH_REMATCH[1]}
fi

The =~ operator works inside Bash double backet tests.  It matches an extended regular expression, and matched sub-expressions (what is inside parentheses) are put in the BASH_REMATCH array, with the first sub-expression at index 1.  If the match fails then the test returns a non-zero value and, in that case, the string stays as it was.
Please note that this does not ensure the URL is valid, only that it does not begin with "http://", so I would say this is more of a toy example than production-ready code.


Without refresh the page how to display the values from database using ajax/jQuery

Question: After inserting data into the database through jQuery/ajax, while fetching values from database without refresh the page how to display the database values using codeigniter?

This is my code:
Script:

Controller:
public function buyer_communication() {

        $result1 = $this->Profile_model->fetch_Data($product_id);

        $Userid = $this->session->userdata('id');
        $result3 = $this->session->userdata('tt');
        $data4 = array(
            'message' => $this->input->post('message'),
            'supplier_id' => $this->input->post('suppid'),
            'product_id' => $this->input->post('proid'),
            'Customer_id' => $this->input->post('custid'),
            'From' => $result3,
        );

        $this->Profile_model->buyer_insert($data4);

        redirect('welcome/buyermessageview?id=' . $product_id);
    }

Model:
function buyer_insert($data4) {
        $this->db->insert('communication', $data4);
        return ($this->db->affected_rows() != 1) ? false : true;
    }

Form:
<form class="form-horizontal" method="POST" id="personal-info"  role="form" action="#">

                                    <input type ="hidden" name="suppid" id="suppid" value="<?php echo $row->supplier_id; ?>" class="form-control" />
                                    <input type ="hidden" name="proid" id="proid" value="<?php echo $row->product_id; ?>" class="form-control" />
                                    <input type ="hidden" name="custid" id="custid" value="<?php echo $row->Customer_id; ?>" class="form-control" />

                                    <input id="message" name="message" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." />

                                        <button class="btn btn-primary btn-sm" id="submit-p" name="submit-p">Send</button>

                        </form>

Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/145687/discussion-between-maruthi-prasad-and-pavan-baddi).
Comment: https://stackoverflow.com/questions/44305553/inserting-data-in-to-database-using-jquery-ajax-i-am-not-getting-ant-error-but-v/44305849 are you two working on the same thing, by any chance? Keep it to one question on the same issue, preferably. And also please ask your friend to accept the other answer, since it solved the original problem. Anyway, you haven't described this properly. What's going wrong with your code? At which point does it fail? What errors have you got, if any? What behaviour is wrong?
Comment: P.S. Why, in the ajax, are you manually extracting the values from the form fields, when you could just serialise the whole form? `data: $(this).serialize()` should work instead of all those repetitive variable declarations. https://api.jquery.com/serialize/
Comment: after insert values to database while fetching values from database without refresh the page values should be display in form.
Comment: form code also i added just once refer and suggest me
Comment: @Maruthi Prasad here is the `CRUD` click on the links below  [link 1](https://ibb.co/fUFg5v)   ,  [link 2](https://ibb.co/i1F3JF) , [link 3](https://ibb.co/mRZVyF)  in codeigniter. tell me is this what you want
Comment: @PavanBaddi link 3,above i shown one image,in text field i enter some text and  click the send button,without refresh the page enter message should be display in that page only.
Comment: @PavanBaddi are you got my problem
Comment: @PavanBaddi  i want to redirect the above shown image page(buyermessageview)  in ajax success message
Comment: @Maruthi Prasad here is the screen shots  [link](https://ibb.co/czQykv) . `NOTE: this does not include the session vars it is just a small example`. tell me is this what you wanted
Comment: @PavanBaddi exactly like that i want
Comment: @Maruthi Prasad but when you press the send btn it does not refresh but loads the data through ajax
Answer: @Maruthi Prasad here is the code.. [IN CODE IGNITER]
HTML view code with jquery script
views\profile_view.php
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      <form method="post" id="personal-info">
            <input id="message" name="message" type="text" class="form-control input-sm chat_input" placeholder="Write your message here..." />
            <button type="submit" class="btn btn-primary btn-sm" id="submit-p" name="submit-p">Send</button>
      </form>

CONTROLLER CODE:
controllers\Profile_cntrl.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
header('Access-Control-Allow-Origin: *');
class Profile_cntrl extends CI_Controller {
    function __construct(){
        parent::__construct();

        $this->load->model('profile_model');
        $this->load->helper(array('url','html','form'));
    }

    public function index()
    {
        $this->load->view('profile_view');
    }

    public function get_data(){
        $query = $this->profile_model->buyer_communication();

        echo json_encode($query);
    }

    public function insert_data(){
        $arr = array(
            'message'=>$this->input->post('message')
        );

        $sql = $this->profile_model->buyer_insert($arr);

        $op = "data insert id :".$this->db->insert_id();

        if($sql == true){
            $reponse = array(
                'Status'=>'true',
                'report'=>$op
            );
            echo json_encode($reponse);
        }
        else
        {
            $op = "Failed to insert data";

            $reponse = array(
                'Status'=>'false',
                'report'=>$op
            );
            echo json_encode($reponse);
        }
    }
}
?>

Model code:
models\Profile_model.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Profile_model extends CI_model {

    public function buyer_communication(){
        $sql = $this->db->get('communication');
        $sql = $sql->result_array();
        return $sql;
    }

    public function buyer_insert($arr){
        return $query = $this->db->insert('communication',$arr);
    }
}
?>

Feel free to ask questions


Using indoor only power adapter outside

Question: I'm setting up a mineralization unit for my pool. The unit came with a 12V1A power adapter which says Indoor Use Only on it. At the same time, the instructions say that the unit should be powered using an outlet that's wired directly into the timer for the pool pump, so that it only operates when the pump is cycling the water. I'm having an electrician add an outlet with a weatherproof cover. My question is, is having the power supply protected by a weatherproof box the same as using it indoors? I imagine the box protects against moisture. But what about heat and humidity? I cant seem to find a similar power adapter that would be rated for outdoors.
Comment: Can you get a different power adapter for the unit?
Answer: Those waterproof covers are only rainproof. They are open at the bottom for the cords to go through so they are not moisture and humidity proof. Outdoor rated cords have a heavier, much heavier, insulation to protect them from the outdoor environment, sun, UV, animals,etc. The male and female ends are also insulated heavier and are of higher quality. Connecting to a weatherproof box is not the same as indoor use and if the outlet is outdoors, it will have to be GFCI protected.
Comment: I agree with Jack although I use those wall warts in my shop I would not want one used outside around the pool unless I had some more protection than an in use cover especially around water / pool chemicals.
Comment: @EdBeal Good point about the pool chemicals.

Using indoor only power adapter outside


Can I set a value in localstorage to be binary true?

Question: My code does a check like this:
if (localStorage.isAuthenticated == true) {
   $scope.template = $scope.templates[1];
} else {
   $scope.template = $scope.templates[0];
}

Can someone tell me if this is valid. If not then how can I set it to true or false?
Also how can I check if localStorage.isAuthenticated is not set. In that case I want the setting to be $scope.templates[1].
Comment: Local storage can only store strings. Your boolean will be converted to a string on set, you will have to convert it back on get.
Comment: Have you tried it?  What happened when you ran this code?
Answer: Just use JSON.parse:
localStorage.isAuthenticated = true;

if (localStorage.isAuthenticated && JSON.parse(localStorage.isAuthenticated )) {
   //great
}

I use the && to check if the value is undefined. If localStorage.isAuthenticated returns undefined because it's not set, you get a false back.
Comment: What happens if the value has not been set ?
Comment: u can check that in the if. I've updated the response
Answer: No, you cant
because localstorage supports only string, not boolean
 you can check this link http://www.acetous.de/152/localstorage-sessionstorage-arrays-und-objekte-speichern

UPDATE:
 if(localStorage.getItem("key")==null)
         localStorage.setItem("key","true");
 console.log(localStorage.getItem("key"));//return "true"

Comment: Thanks. But how can I check if it is not set ?
Comment: @marifemac if not set you will get `null`


Adobe Connect App with Wine 5.0 on Ubuntu 18.04

Question: I need to use Adobe Connect App for meetings. Unfortunately, I cannot use the normal browser "way", but have to use the desktop application from https://helpx.adobe.com/adobe-connect/connect-downloads-updates.html to be able to be a moderator of a meeting.
According to Adobe ("Please note that although there is currently no application for Linux, users on Linux (Ubuntu, Red Hat and OpenSUSE)") there is no app for Linux.
Therefore, I installed Wine 5.0 ob my Ubuntu 18.04 and downloaded the Adobe Connect app for Windows.
Problem: I can start the connect.exe of the app with Wine. However, after entering the URL for the meeting and clicking on "Continue" nothing happens. (It just loads for a long time)
Any suggestions or ideas are really appreciated!
(I saw a similar question (Adobe connect and ubuntu 18.04) which asks for the app with PlayOnLinux. Since I use Wine without a graphical frontend and this frontend may be the reason why the app crashes on the other question, I opened my question. However, if the app works with PlayOnLinux, my question can probably be closed.)
Comment: According to [WineHQ](https://appdb.winehq.org/objectManager.php?sClass=application&iId=10270) Adobe connect has "Garbage" level of support. You can't run it on linux.
Answer: You don't need Wine to connect to Adobe Connect sesssions on Linux. you just need to switch your browser's user-agent from Linux to Windows ... (and preferably open it in Firefox; Works better in my experience.)
1- Install "User-Agent Switcher and Manager" or any other "User-Agent switcher" Addon/Extension on your web browser.
2- Switch your browser's User-Agent to a Windows based one.
(e.g. if you are using Firefox on Linux, change it to "Firefox on Windows"; and if you are using Chrome on Linux, change it to "Chrome on Windows".)

Voila, you can now access Adobe Connect sessions through your web browser on Linux, without getting bothered by Adobe about why you don't have the already EOL Flash plugin installed!
Comment: Since I asked the question I a) switch to another distro and b) didn't had to use the app again. So I cannot try out your solution. However, as I stated I needed to use the app to be moderator of a meeting. One cannot be a moderator in the browser app (at least at the time of my question). Therefore you're solution to switch user-agent in the browser is not answering my question. But perhaps it will work now, if the browser app now allows being moderator on browser.
Comment: To share your screen you need to install the Adobe Connect plugin, witch only works on Windows and Mac
Answer: Not all apps work with Wine and some work but they are extremely buggy. Don't you have Windows. If you don't your best choice seems to be to try and use a different app for the meetings.
Comment: This is an unhelpful answer. As stated I need to use this app - it's not my decision. Also, don't you think I'd use Windows if I'd had it?


Are all Z-moves guaranteed to hit?

Question: Seeing as how I'm only allowed to use one Z-move per battle, I haven't had much experience with them. However, I've noticed that I've never missed a Z-move. Are all Z-moves guaranteed to hit? Does the accuracy of the base move influence it and I've just been lucky all this time?
Answer: Damaging Z-Moves don't make accuracy checks
Similar to moves such as Swift, all damaging Z-Moves skip the accuracy check, meaning they not only have 100% accuracy, but also ignore changes to the user's Accuracy stat and the target's Evasion stat. Furthermore, Z-Moves can even hit a target through Protect and similar moves, though they only deal 1/4 their usual damage in that case.
Status Z-Moves simply add an extra effect to the normal move, rather than creating an entirely new move. It sounds like the extra effect from being a Z-Move applies before the normal effects of the move, so they presumably always work, but the normal effects of the move would still be subject to accuracy if the original move was (e.g. Z-Toxic would always give +1 stage Defense, but might fail to badly poison the target).
Source: http://www.serebii.net/sunmoon/zmoves.shtml
Comment: You can discover the actual accuracy of Z-status moves using a move with a low accuracy (i.e. Sing has 55%) and Normalium Z.
Comment: @pinckerman I would have done so if I actually had the game. =P
Comment: Same here, LOL.
Comment: I'd just like to add that Z-Status Moves break through Taunt, as well...

Are all Z-moves guaranteed to hit?


How can I do Gaussian elimination of a $32 \times 32$ bit matrix?

Question: I have been looking at how to reverse the sigma operation in the sha256 hash and in several places I have seen that you have to make a $32 \times 32$ bit matrix and then solve it with Gaussian elimination.
On this same page I have found this question that is quite well formulated and well answered but I cannot finally understand how it does the elimination. How to solve a system of 32 XOR equations via Gaussian Elimination?
I have spent several days trying to understand and I have been seeing how to solve the elimination and I manage to understand it with a smaller matrix with its unknowns as in this other question how to solve system of linear equations of XOR operation?
In the first link, start with the following matrix.
0:  0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 | 0
1:  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 | 1
2:  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 | 1
3:  1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 | 1
4:  0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 | 0
5:  0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 | 0
6:  0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 | 0
7:  1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 | 1
8:  0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 | 1
9:  0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 | 0
10: 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 | 1
11: 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 | 0
12: 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 | 1
13: 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 | 0
14: 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 | 0
15: 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 | 0
16: 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 | 0
17: 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 | 0
18: 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 | 1
19: 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 | 0
20: 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 | 0
21: 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 | 1
22: 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 | 0
23: 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 | 0
24: 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 | 1
25: 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 | 1
26: 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 | 1
27: 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 | 0
28: 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 | 0
29: 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 | 1
30: 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 | 1
31: 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 | 0

I understand that the bit part on the right 01110001101010000010010011100110, is the output of the sigma operation.
But where does the bit 00000000000000100000000001000000 part with which it does the right rotates come from?
The first link is a part of the question owner's total question and if we follow the link it leaves,(Reverse SHA-256 sigma0 function within complexity of O(n)?) it takes us to stack overflow where the answer marked as correct contains a series of hexadecimal numbers called "sigma0 singleton inverses" that I would like know that they are ignored and create new doubts as if they are constant values, or if they are obtained from another operation... If so, I would like to know what operation it is
I mean this part : sigma0_singleton_inverses = [0x185744e9, 0x30ae89d2, 0x615d13a4, 0xdaed63a1, 0x9cd03a8e, 0x08fdcc39, 0x11fb9872, 0x23f730e4, 0x5fb92521, 0xbf724a42, 0x57ee6948, 0xafdcd290, 0x76b358ec, 0xf531f531, 0xc36917ae, 0xb78f9679, 0x4615d13e, 0x947ce695, 0x19a4740f, 0x2b1facf7, 0x4e681d07, 0x84877ee7, 0x385344eb, 0x70a689d6, 0xf91a5745, 0xc36917af, 0xb78f967b, 0x4615d13a, 0x8c2ba274, 0x290afdcd, 0x4a42bf73, 0x94857ee6 ]
What do these "sigma singleton inverse" values mean?
I don't know if I posted the question in the right place since it contains topics about cryptography, mathematics and programming and I didn't know where to post it. If I made a mistake putting it in this section, tell me so I can correct it and publish it in the correct place.
Answer: I would like just to illustrate the excellent answer by Joriki by displaying the inverse matrix, illustrating two facts :

that indeed the binary (or hexadecimal) codes of the rows have to be read in the backward direction.

that constracting with the initial matrix, its inverse (on the right) has a weird structure... The only special feature one can recognize on it is its symmetry with respect to the second diagonal shared with ( = inherited from) the initial matrix.

Fig. 1 : The initial matrix and its inverse.
Check for example that the second row of the inverse is (when read backwards)
$(0011)(0000)(1010)(1110)(1000)(1001)(1101)(0010)$
$ \ \ \ \ \ 3 \ \ \ \ \ \ \ \ \ 0 \ \ \ \ \ \ \ \ \ a \ \ \ \ \ \ \ \ \ e \ \ \ \ \ \ \ \ \  8  \ \ \ \ \ \ \ \ \   9  \  \ \ \ \ \ \ \ \  d  \ \ \ \ \ \ \ \ \   2$
Comment: Sorry for taking so long to respond, I appreciate the time in making an illustration, that was just what I was asking for earlier to have a visual image. This certainly makes my doubt and what I am facing even clearer.
Answer: The matrix is slightly confusing in that the bits are arranged in reverse order, least significant first, so that the right shift/rotate becomes left shift/rotate. Each row is the result of applying the $\sigma_0$ function to a $32$-bit word with a single bit set. For instance, the first row shows the result of applying it to the word with only the $0$-th bit set. The right rotate by $7$ produces a $1$ in the $25$-th bit, the right rotate by $18$ produces a $1$ in the $14$-th bit, and the right shift by $3$ shifts the $1$ bit beyond the end of the word and thus doesn't contribute in this case. You can see how it first becomes relevant in row $3$, which is the result of applying $\sigma_0$ to a word with the $3$rd bit set, because here the right shift by $3$ shifts that bit into the $0$-th bit.
The "singleton inverses" are the rows of the inverse matrix; for instance, the $0$-th entry in that array, $185744\mathrm E9_{16}=00011000010101110100010011101001_2$, is the result of applying the inverse operation to a word with only the $0$-th bit set. So they've inverted the binary matrix and provided the rows of the inverse, so you can apply the inverse operation as shown in the code there, "adding" (i.e. XORing) up the contributions for the bits, adding in the value in the array whenever the corresponding bit is set in the word to be inverted.
Comment: No problem, it was just if you could. Thanks to you I have been able to see the problem even more clearly. If I have any more questions, I will create another question.
Comment: @JeanMarie That's the post I put in my question to clarify what I'm trying to do.
Comment: First of all, thank you very much for taking the time to answer this question and to review and understand the others in the links.
I understood perfectly the part of the singleton inverses and in the part of the matrix, thanks to you now I have a clearer vision of what is going on in it and I can understand the sudden appearance of the 1 in the third row, but what does it mean that the first row shows the result with the 0 set?
Comment: If you don't mind, with an example I think it would help me. For example what would be the matrix and the input if I have the following 32 bits as output? 1111000111111111111111111100011110000000
To add, I found this page that has a very similar matrix, is it a coincidence? http://www.chrisjones.id.au/Invert/index.html
Comment: @jefreyitbhernandezrodriguez: I'm not sure whether I understand your first question, "what does it mean that the first row shows the result with the $0$ set?". If you mean the $0$ at the very end of the row labeled "$0$:", I thought you said in the question that you understand that this is the desired output for which we want to find the input – there's not more to it than that; it's just the $0$th bit of the output we want to reverse in this example. On your next question: the matrix doesn't depend on the output being reversed; it's entirely determined by the hash function.
Comment: @jefreyitbhernandezrodriguez: I don't really feel like carrying out the computation for you; it's the same for every given output. If you want to do the computation for lots of outputs, it may make sense to actually invert the matrix so you just have to multiply the outputs with the inverse. If you only need it for a couple of outputs, it's probably more efficient to solve the system using Gaussian elimination. If there's a specific part of that you don't understand, feel free to ask again. About that other page: Why should it be a coincidence? They're doing exactly the same sort of thing.
Comment: I just posted a representation of the inverse matrix.
Comment: Have you seen this question about the very same matrix and its answer I have just noticed : https://math.stackexchange.com/q/4060086/305862 ?
Comment: Sorry for having not made the connection.


Sort list according to elements in sublist

Question: I have a simple list composed of several sublists like so:
a = [[4, 3, 2, 1], [5, 8, 7, 6], [12, 11, 10, 9]]

I need to sort this according to the elements in the sublist a[1] in descending order so it will like like this:
sorted_a = [(3, 2, 1, 4), (8, 7, 6, 5), (11, 10, 9, 12)]

I've tried using sorted:
sorted_a = sorted(a, key=lambda x: -x[2])

but it returns:
[[12, 11, 10, 9], [5, 8, 7, 6], [4, 3, 2, 1]]

which is not what I need at all.
Comment: I need to sort all the sublists following the sorting done in sublist `a[1]`. So if the elements in this sublist are arranged in a given way, the elements in all the other sublists should be re-arranged too in the same way. I'm sorry if I explained myself poorly.
Comment: Is it `a[1]` or `a[2]`?
Comment: I'm sorting all the sublists rearranging `a[1]` in descending order.
Comment: but you are also sorting a[0] and a[2] in ascending order ?
Answer: So you actually want to sort the sublists?
zip(*sorted(zip(*a), key=lambda x: -x[1]))

Answer: Perhapse this is what you're looking for:
a = [[4, 3, 2, 1], [5, 6, 7, 8], [12, 11, 10, 9]]
[sorted(list) for list in a]

Returns: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
Or, if you additionally want to sort by the first element:
a = [[4, 3, 2, 1], [12, 11, 10, 9], [5, 6, 7, 8]]
sorted([sorted(list) for list in a], key=min)

Also returns: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
Answer: This sounds confusing ;-)  From the comments, it sure sounds like you want to take the permutation that would reverse-sort a[1], and apply that permutation to all sublists.  Well, any 1-liner for that would be insanely obscure.  So here's a straightforward way to do that:
a = [[4,3,2,1], [5,6,7,8], [12,11,10,9]]
# compute the permutation needed to reverse-sort a[1]
decorated = [(v, i) for i, v in enumerate(a[1])]
decorated.sort(reverse=True)
perm = [i for v, i in decorated]
for sublist in a:
    sublist[:] = [sublist[i] for i in perm]
print a

Comment: I apologize for the confusing question, I try to strip things down to the fundamentals and sometimes I overdo it. It may seem like I want to revert because I happened to write the sublist `a[1]` in ascending order but it's not really what I need. I'll try to make this more clear in the question.


Can I speed up the wait time between username changes?

Question: I set my Minecraft username to a name I don't like. I don't want to wait the full 30 days to change it back or to something different. So is there ANY way I can speed up the 30 day wait?
Comment: @KingsleyZhong No, the question is Minecraft related, and Minecraft questions are (with few exceptions) on-topic. It might not be about the game itself, but it is still a question that relates to gaming, if that makes sense.
Comment: I'm not very sure, but something tells me that this is a bit off topic.
Comment: @MageXy Gotcha, I wasn't sure because some question that is similar got flagged as off topic so I was just wondering. Thanks though!
Answer: As per the official help topic, you can change your username once ever 30 days. Your original username is kept on hold for 37 days, which means you have one extra week to change back if you made a mistake when you first changed it. However, you must wait 30 days between name changes. This cannot be avoided or sped up.
Answer: Like mentioned before, you can only change your username once every 30 days. Other people can not change it to your old nickname until 37 days after your change. Here is the article
If you would like to change your username temporarily before the 30 days you have several options:

You can use this mod if you want to change it client side (singleplayer)

Good luck!
Comment: Please do not include links to hacked clients/servers. We don't want to encourage piracy.
Comment: I don't think it's good to mention hacked clients at all. At best, it provides a search topic for people who want to pirate. Even "legitimate" hacked clients are avenues for spyware and viruses. I think it's best to avoid them.
Comment: If you know its a hacked client, and you know they're not good to use...why is it in your answer?
Comment: @MageXy If I did something like "these options are not encouraged" but... and not include the links. I understand your point, I just finished reading the stuff at help center.
Comment: @MageXy I know, I have personally worked with them for various reasons and they are not good to use. I'm just going to edit the answer so that it actually adds something.


How to make prediction on Keras Text classification?

Question: I've trained a model with this reference: https://www.tensorflow.org/tutorials/keras/text_classification_with_hub
Here is my code:
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds

train_data, validation_data, test_data = tfds.load(
    name="imdb_reviews",
    split=('train[:60%]', 'train[60%:]', 'test'),
    as_supervised=True)

train_examples_batch, train_labels_batch = next(iter(train_data.batch(10)))

embedding = "https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1"
hub_layer = hub.KerasLayer(embedding, input_shape=[],
                        dtype=tf.string, trainable=True)
hub_layer(train_examples_batch[:3])

model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1))

model.summary()

model.compile(optimizer='adam',
    loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
    metrics=['accuracy'])

history = model.fit(train_data.shuffle(10000).batch(512),
    epochs=20,
    validation_data=validation_data.batch(512),
    verbose=1)

results = model.evaluate(test_data.batch(512), verbose=2)

model.save("imdb_model.h5")

I've saved the model as imdb_model.h5. I want to make a prediction on a custom text. For example "The best movie, I have ever seen". How can I do it?
Answer: You can use
model.predict(["This is the best movie I have ever seen"])

Comment: What is the result float meaning?
Comment: A high number means likely and a low number means unlikely. If you want you can wrap it in a sigmoid function to get a percentage between 0 and 1.


How can I add wine programs to the right click context menu?

Question: How can someone automatically add wine programs (such as Microsoft Office) to the right click context menu? In my case specifically the software is installed via play on linux.
For example, when a user right clicks on a *.doc file, they have the choice of "Open with Libre Office" and "Open with Microsoft Word".
P.S I have done this before on a previous installation but I can't remember exactly how.
Comment: https://help.ubuntu.com/community/Wine may be useful
Answer: If you have a previous version of Ubuntu (not 11.10) you can right click the file, select Properties and in the Open With tab you can search the option to write you custom application. For example, if you know Microsoft Word can open a doc using this line (I don't use msword so I don't really know if the follow command will work, it's just an example):
<code>wine msword mydoc
</code>
then, you put that line in the custom application box.
If you're using 11.10 that's not possible (why?), so you should look this. That way you can add any application to the Open With option, including wine.
Hope it helps.
Best regards,


Azure Mobile App Service not picking up routes

Question: I have a project which I created via File > New > Project > Azure Mobile App
I've added routes to my HttpConfiguration in the ConfifgureMobileApp() method.
The code looks like this. Not in particular the line config.Routes.MapHttpRoute(...).
    private static void ConfigureMobileApp(IAppBuilder app, ContainerBuilder builder)
    {
        var config = new HttpConfiguration();
        builder.RegisterModule(new WebApiModule(config));
        var container = builder.Build();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        //For more information on Web API tracing, see http://go.microsoft.com/fwlink/?LinkId=620686
        config.EnableSystemDiagnosticsTracing();
        config.Filters.Add(new CultureThreadingAttribute());
        config.Routes.MapHttpRoute("DefaultApi", "api/{culture}/{controller}/{id}", new { id = RouteParameter.Optional });
        new MobileAppConfiguration()
            .AddTablesWithEntityFramework()
            .MapApiControllers()
            .ApplyTo(config);
        MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings();
        if (string.IsNullOrEmpty(settings.HostName))
        {
            // This middleware is intended to be used locally for debugging. By default, HostName will
            // only have a value when running in an App Service application.
            app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions
            {
                SigningKey = ConfigurationManager.AppSettings["SigningKey"],
                ValidAudiences = new[] { ConfigurationManager.AppSettings["ValidAudience"] },
                ValidIssuers = new[] { ConfigurationManager.AppSettings["ValidIssuer"] },
                TokenHandler = config.GetAppServiceTokenHandler()
            });
        }

        app.UseAutofacWebApi(config);
        app.UseAutofacMiddleware(container);
    }

But this route is not getting picked up. In my middleware, I've taken the {System.Web.Routing.RouteData} object from the OwinContext.Environment dictionary, and it contains no routes.
I am using https://learn.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-dotnet-backend-how-to-use-server-sdk, and in particular, I'm following the advice of that article by mapping the route before making the call to ApplyTo(config).
Also, my action filter CultureThreadingAttribute, which changes the locale of the thread based on the culture coming in from the route, is failing to get picked up.
I suspect that there are multiple HttpConfiguration objects running around in my app. Is there a way to fix this?
Answer: The route for your culture and the route for MobileApps APIs are conflicting with one another likely.  Debugging the route handler will confirm it.  Set a breakpoint and take a look at the route table as a call comes in.
There is nothing magical about the [MobileAppController] attribute - it just enforces the ZUMO-API-VERSION.  You can remove the .MapApiControllers() element and use regular ASP.NET MVC routing for your API controllers.  This will simplify your API route definitions.
Comment: Thanks Adrian.

I added a NuGet reference to Microsoft.AspNet.WebApi.WebHost, and replaced the contents of `ConfigureMobileApp` with
`GlobalConfiguration.Configure(c => Configure(app, builder, c))`. That meant that the route was picked up, and my RouteValueDictionary now contains the correct values (culture = "en-GB", controller = "Provider", id = {}). But the controller is not even being instantiated.
Comment: I have to be honest: I can't wait until all of this goes to .NET Core.
Comment: At least the problem is no longer Mobile Apps, but a straight MVC issue :-)
Comment: I'll update my post, and maybe add an answer, once I've worked out how to fix this.
Comment: I think this was a PIBKAC. I added a handler, and it turned out I needed a binding redirect on my server side. I don't think this is relevant to most people, so I may delete this question shortly.


Xamarin 4.0.13 Layout Renderer failed

Question: I get the error "Connection to the layout renderer failed. This may be caused by a misconfiguration of Java. Please close and open the file again" after update to 4.0.13. This is error log:
<code>Error: Could not find or load main class Files\Android\android-sdk\tools\lib\ant-tasks.jar;C:\Program
ERROR [2013-10-13 10:47:56Z]: Connection failed
System.Exception: Java process failed to start
   at Xamarin.AndroidDesigner.JavaProcessConnection.DoConnect()
ERROR [2013-10-13 10:47:58Z]: Could not update jumplists
System.InvalidOperationException: The file type is not registered with this application.
   at Microsoft.WindowsAPICodePack.Taskbar.JumpList.AppendCustomCategories()
   at Microsoft.WindowsAPICodePack.Taskbar.JumpList.Refresh()
   at MonoDevelop.Platform.JumpList.UpdateJumpList()
   at MonoDevelop.Platform.JumpList.OnUpdateTimerEllapsed(Object sender, EventArgs args)
</code>
Xamarin should test carefully before release update package. I wish I didn't update to 4.0.13.
Comment: Solution is reinstall 4.0.12 update package which was located at C:\Users[Your User name]\AppData\Local\XamarinStudio-4.0\Cache\TempDownload.
Comment: If you are getting this issue at the start of 2015 the resolution seems to be uninstall pre 1.8 JDKs and install JDK 1.8 64 bit. http://forums.xamarin.com/discussion/30818/connection-to-the-layout-renderer-failed-after-updating-to-5-7 http://stackoverflow.com/questions/19426993/layout-renderer-failed-error-in-xamarin/28276331#28276331
Comment: possible duplicate of ["layout renderer failed" error in xamarin](http://stackoverflow.com/questions/19426993/layout-renderer-failed-error-in-xamarin)
Comment: I am having the very same issue but don't have the older update package... So what do I do now?
Comment: You can download from here:
http://download.xamarin.com/studio/Windows/XamarinStudio-4.0.12-3.msi
Answer: I think this was resolved. for me I kept getting this error randomly but if you face it just open android sdk manager from visual studio
TOOLS > ANDROID > Android SDK Manager
Comment: And then? after opening Android SDK Manager, what should I do?

Xamarin 4.0.13 Layout Renderer failed


Retrieving information with Python's urllib from a page that is done via __doPostBack()?

Question: I'm trying to parse a page that has different sections that are loaded with a Javascript __doPostBack() function.
An example of a link is: javascript:__doPostBack('ctl00$cphMain$ucOemSchPicker$dlSch$ctl03$btnSch','')
As soon as this is clicked, the browser doesn't fetch a new URL but a section of webpage is updated to reflect new information.
What would I pass into a urllib function to complete the operation?
Answer: javascript:__doPostBack('...

(Urgh. That's a sad and nasty approach.)
A simple general-purpose approach for finding URLs whose logic is buried in JavaScript is to run the page normally, with a network debugger on (eg. Firebug's 'Net' tab, or Fiddler). By monitoring the request made when you click, you can see what URL and what POST request body parameters are to be passed.
You'll need to use the data argument of urlopen to send POST request bodies.
Comment: That'll do it for me! You're great!


Why is this mySQL UPDATE not making changes?

Question: I know nothing about mySQL. A friend and I are struggling with this tiny bit of code.
Background:
I'm trying to solve an issue I have with character encoding on my WordPress database. My original WordPress database is wordpress, and the modified database is wordpress2 (which exists largely as a copy of the original). I want to select the post_content of a single entry in wordpress, convert it to utf8, and insert it into the corresponding row in wordpress2.
The Script:
update wordpress2.wp_posts wp2
   set wp2.post_content = (select convert(wp.post_content using utf8)
                             from wordpress.wp_posts wp
                            where wp.ID = wp2.ID )
 where wp2.ID = 789;

When run:
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1  Changed: 0  Warnings: 0

Why isn't this changing any rows? What do we need to do to make it do so?
Thank you.
Comment: Are you sure the values are not the same already?
Comment: "matched 1, changed 0" implies the row already has the value it would be changed to. An update does not actually occur if the new value does not differ from the old one.
Comment: Maybe the sub-query needs an alias as well.
Comment: Oops, @zerkms is correct. The two values were already the same. I suppose, in hindsight, that should have been obvious.
Answer: The answer, as @zerkms first pointed out in the comments above, was that the values were already identical.


How can I separate glued wooden flooring planks?

Question: I have had a 20mm thick wooden floor laid and due to a plumbing problem have to take it up again and re-lay. The fixer glued the tongue and groove together with PVA which I now need to separate, clean and re-fix. There is about 50square metres of this flooring.
Comment: What's your plumbing problem? This could be a XY problem. Perhaps there is a solution which does not involve breaking up your floor. Plumbers can be very creative.
Comment: Welcome to [woodworking.se]. If you'll take the [tour], you'll see that not only is this a Question & Answer site (where it's expected that you actually ask a question), but you'll learn that the more details you can provide us, the better. Is this a real wood floor or a laminate/vinyl type floor? How long ago was the floor installed?  You can [edit] your question to update it. It's unlikely you'll be able to "unglue" the floor, but this info will help inform an answer about how to pull it up and repair it afterwards.
Comment: Ouch!  I assume this is solid wood (laminate /engineered wood tends to be thinner and not really T&G).  What is lying on (joists, another wooden floor, concrete, battens on concrete, etc.)?  How is it attached to whatever it is lying on (glued, nailed, just floating)?  Whereabouts is the plumbing issue?  Do the pipes run parallel to the planks, or cross-wise.  Please edit your question to provide these details.
Comment: It is possible to remove and replace planks in the middle of a wooden floor. The guy I hired to do that used a router. Most likely you don't need to remove the entire floor.
Answer: I've successfully separated wooden furniture glued with PVA using a heat-gun - but it probably works only for thinner pieces - and you have to use lower setting, otherwise you'll not only burn the wood, but the wood may also break down and release pitch or tar, which is definitelly not a good thing. Perhaps try with the same glue on some offcuts of the same/similar wood to see if it works and how high you can go with the temperature..
Answer: PVA can be dissolved with vinegar ("cleaning/industrial vinegar", not the cooking stuff).
And heating the vinegar makes it work even better.
(See also this question on the Bricks StackExchange about separating Lego bricks glued together with PVA.)
Unfortunately it would soak (and maybe warp) the wood.
And probably cause serious discoloration as well.
So the flooring might be a write-off anyway...
So to me that would be a last resort.
If you have access from below that floor (another floor or basement below it?) it may be better (and cheaper) to access the plumbing from below, even if you have to cut open the ceiling to get at it.
Re-doing a drywall or plaster ceiling would most likely be cheaper than a new hardwood floor.


How to fetch Reddit post from a scraped csv

Question: I have a csv file with Reddit ID. In first column there may be 2-6 ids but in second column there is always 2 IDs. I have to write a script so that i can fetch the posts from IDs for the both column.

Your help will be much appreciated.
Answer: So first of all you need to read that file.
import csv
with open('yourfilename.csv', mode ='r') as file:
csvFile = csv.reader(file)

Taken from here
Next you would want to split each column to a list, so that you can scrape multiple ids
idList = []
for line in csvFile: # loop each line
  for columns in line: # loop each column
    for element in columns.split(' '): # loop each element
      idList.append(element)

print(idList)

Taken from here
Comment: From your solution i will get a list, But i need to keep the csv file as it is. So the rows and columns needs to be intact, as i will do further processing on the csv file.


browser displays images bigger than original size

Question: my web site displays images bigger than their original size.
The images are 20% bigger than the original created with photoshop (for example), if an image's width is 200px, the browser display is 240px.
So all my images are blured.
Do you know why?
Comment: Yes, it is 100%, if I resize down to 80% everything has the right size...
Comment: can you update your question with some sample code so that i can analyse it because it is highly improbable that image appears 20% larger. Didi you check all of your css code for zoom property?
Comment: Didi you checked your browser settings? is it on 100% ?
Comment: does your css have zoom property defined on html or body tag?
Comment: no, it hasn't zoom property
Comment: did you solve the problem? If not, then can you please share your code on github or jsfiddle ?
Comment: ok, I've done it
Comment: I had the same problem. I had  Settings  > Ease of Access > Display > Make text bigger. Unfortunately this seems to affect my image. Maybe a bug? Maybe because the image is a screenshot with text and Windows is enlarging it on purpose?

Anyway, if I scale the text back to 100% all the images appear normal again.
Answer: I've found the solution!
Windows 10 has the default setting of dpi seted to 125%  (search dpi into serach box and then look at "update text app and other elements"), this increase the dimension of everything in my monitor, so the images into my web site are bigger of 25%.
Comment: I'm not sure this is the case. Changing the DPI to 100% reduces both the browser and explorer (or photoshop) ones. Still different sizes.
Comment: I'm testing it and might post a new question later after sorting out the tests... In the mean time of someone read this and knows why... I created an image with 640px width. I upload the image, it looked bigger on browsers. If I download the image back, it's back to 640px width. If I take screenshot, it's still bigger (around 800+px)... Why? It's a new monitor and I played with the DPI settings as well but as I mentioned it reduces/enlarges everything, while the problem here is that the image is larger on browsers only (not on explorer/pic viewer or photoshop). Browsers are of course at 100%.
Comment: This is old but I am having this issue right now. When I upload an image that is high quality to my site, the image on the site looks to be much larger, as if it is scaled up, and it's blurry. When I download that same image, it's fine again on the computer. I tried playing with the screen DPI and putting on 100% which helped, but isn't ideal because the screen becomes way too small, but, that did make everything more consistent. It's just not the ideal solution. Ideally, the windows 11 image app would scale with the rest of the screen, then it will all be consistent.
Answer: Here are a part of my code:
First of all in the head tag I have this meta tags:
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1.0,user-scalable=1, height = device-height" />

My css hasn't any zoom or similar, and my html is like this:

The width of this image is 250px and in photoshop it looks like perfect, but in browser (chrome or firefox is the same) it looks bigger and blured, but, if I zoom down the browser to 80%, the image is perfect
Answer: I also had my Chrome browser displaying larger than my picture viewer app. As Daniele said. My display settings in windows were scaled to 125%. When I changed the display scale to 100%, the picture viewer app still showed the same picture size while only changing the scale of buttons and other display elements. So perhaps it's helpful info that the scale of my display does not change the image display size but everything else. The browser on the other hand is entirely changed by the system display scale. I even found that http://whatismyscreenresolution.net/ read my screen size too small according to my system display scale being set larger.


How do I uninstall Vivado on Ubuntu 19.04?

Question: I recently installed Vivado 2019.1 on Ubuntu by running sudo ./xsetup. I didn't pay attention where Vivado was installed, so by default it was installed in /tools/Xilinx/Vivado. Because of that, I can't run the application there. Therefore, I decided to uninstall it. I run ./xsetup -Uninstall but it gives me the error as below.
Exception in thread "main" java.lang.NullPointerException
at java.base/java.io.File.<init>(Unknown Source)
at com.xilinx.installer.gui.panel.summary.SummaryPanel.b(Unknown Source)
at com.xilinx.installer.gui.panel.summary.UninstallerSummaryPanel.<init>(Unknown Source)
at com.xilinx.installer.gui.r.a(Unknown Source)
at com.xilinx.installer.gui.InstallerGUI.D(Unknown Source)
at com.xilinx.installer.gui.InstallerGUI.e(Unknown Source)
at com.xilinx.installer.api.InstallerLauncher.main(Unknown Source)

I googled it and also checked here but couldn't find out what to do.
Comment: You could change the permissions to launch it from there.
Comment: I tried that one before trying to uninstall. I got the following error:           application-specific initialization failed: couldn't load file "librdi_commontasks.so": libtinfo.so.5: cannot open shared object file: No such file or directory
%
Comment: Welcome to AskUbuntu! You say "it was installed in /tools/Xilinx/Vivado. Because of that, I can't run the application there." and this is why you decided to uninstall it. Why do you think you can't run it from the default location? Please [edit] the output of `ls -l /tools/Xilinx/Vivado` into your question. Thank you for helping us help you!
Comment: What about using `sudo`for the uninstall too - as you did for install ?
Comment: I tried that one as well, no changes...
Answer: Vivado is looking for a specific library called libtinfo.so.5.  The package can be found in Ubuntu repositories at packages.ubuntu.com.
The so.5 indicates this is the 5th version of the libtinfo library.  This version might not be installed on your system. libdri_commontask.so needs this library to be installed in a specific place.
I had the same issue on Ubuntu 19.04 trying to use Vivado 2019.1 SDK.  I got it working by running the following commands in a terminal:
sudo apt update
sudo apt install libtinfo-dev
sudo ln -s /lib/x86_64-linux-gnu/libtinfo.so.6 /lib/x86_64-linux-gnu/libtinfo.so.5

Comment: Welcome to AskUbuntu! Can you explain how this answers the question asked?
Answer: On 20.04
sudo apt install libtinfo5


Best method for ordering information in a form

Question: Is there a good method for deciding on layout and order of information in a complex form ?
For example - deciding how to order many customer details in a CRM system.
Should the main criteria for order of layout be by importance? By frequency of use? Or by order of use?
I know they are all important but is there a proven method to organize the form?
Comment: **Web Form Design** *by Luke Wroblewski* has all the answers :) [![Web Form Design by Luke Wroblewski](https://i.stack.imgur.com/d5F8O.png)](https://i.stack.imgur.com/d5F8O.png)
Answer: I believe you're providing the answer yourself – if the information is both important and frequently used, it should be placed at the forefront of the form. This would make it more practical for those who will be operating or consulting it.
There are various components that can assist in organizing the information effectively. Tabs or accordions can be utilized after the primary data to categorize the remaining details, such as birth information, address, and contact information.
Before you delve further into your design process, I strongly recommend reaching out to the individuals who will be using this tool. Understanding their workflow and how they interact with the information will provide valuable insights for the appropriate design. Remember that, as a UX professional, your primary responsibility is to comprehend the user's needs before taking on the wireframes.
Lastly, despite having proven methods, your user should always have the final say. You could conduct a benchmark analysis on the organization of other CRM tools (hopefully you've already done this) to see the order they use. However, it's equally crucial to examine how your users are using these tools and what their primary pain points are. Considering the effort involved, it might be more worthwhile to engage with your own users for feedback and insights.
Answer: With my experiance in designing complex PLM systems and enterprise applications, I came across the below points for best-form designs -

Group Relevant information and name the border group for better identity eg:  Basic Details, Order Preferences, Order Details, etc

Use Tabber or Accordion to create sections so the user can focus on one step at a time.

Provide Table view and card view both for better user experience with data sorting options.