text:
Q: Messed up bluetooth configuration, cannot see or connect to bluetooth devices After a glitch, I tried reinstalling my bluetooth packages (Like attempting to uninstall bluetooth in device manager in Windows) and hcitool scan brings up the error:
Device is not available: No such device"

After "sudo service bluetooth restart I get:
Job for bluetooth.service failed because the control process exited with error code. See "systemctl status bluetooth.service" and "journalctl -xe" for details.

Output:
● bluetooth.service - Bluetooth service
   Loaded: loaded (/lib/systemd/system/bluetooth.service; enabled; vendor preset: enabled)
  Drop-In: /etc/systemd/system/bluetooth.service.d
           └─override.conf
   Active: failed (Result: exit-code) since Mon 2016-02-01 14:59:53 MST; 5min ago
     Docs: man:bluetoothd(8)
  Process: 7249 ExecStartPost=/usr/sbin/chmod o+rw /var/run/sdp (code=exited, status=203/EXEC)
  Process: 7248 ExecStart=/usr/lib/bluetooth/bluetoothd --compat (code=exited, status=0/SUCCESS)
 Main PID: 7248 (code=exited, status=0/SUCCESS)
   Status: "Quitting"

Feb 01 14:59:53 will-Lenovo-Edge-15 systemd[1]: Starting Bluetooth service...
Feb 01 14:59:53 will-Lenovo-Edge-15 bluetoothd[7248]: Bluetooth daemon 5.35
Feb 01 14:59:53 will-Lenovo-Edge-15 systemd[7249]: bluetooth.service: Failed ...
Feb 01 14:59:53 will-Lenovo-Edge-15 systemd[1]: bluetooth.service: Control p...3
Feb 01 14:59:53 will-Lenovo-Edge-15 bluetoothd[7248]: Starting SDP server
Feb 01 14:59:53 will-Lenovo-Edge-15 bluetoothd[7248]: Terminating
Feb 01 14:59:53 will-Lenovo-Edge-15 bluetoothd[7248]: Stopping SDP server
Feb 01 14:59:53 will-Lenovo-Edge-15 systemd[1]: Failed to start Bluetooth se....
Feb 01 14:59:53 will-Lenovo-Edge-15 systemd[1]: bluetooth.service: Unit ente....
Feb 01 14:59:53 will-Lenovo-Edge-15 systemd[1]: bluetooth.service: Failed wi....
Hint: Some lines were ellipsized, use -l to show in full.

How do I fix this? (Ubuntu 15 with Gnome shell, on a Lenovo Edge 15)

A: /etc/systemd/system/dbus-org.bluez.service and changing this line
ExecStart=/usr/lib/bluetooth/bluetoothd to this
ExecStart=/usr/lib/bluetooth/bluetoothd --compat
and then restarting Bluetooth like this
sudo systemctl daemon-reload
sudo systemctl restart bluetooth

and you'll also have to change permissions on /var/run/sdp
sudo chmod 777 /var/run/sdp


text:
Q: What does the tsconfig option "lib" do? I have an existing project that has this line in tsconfig.json:
lib:["2016", "DOM"]

What is the purpose of this?
The only info I could find is this:

Specify library file to be included in the compilation. Requires
  TypeScript version 2.0 or later.

What does that mean?

A: This is a new typescript 2 feature and so it still lacks documentation, but you can read about it in the What's new in Typescript 2.0:

with --lib you can specify a list of built-in API declaration groups
  that you can chose to include in your project. For instance, if you
  expect your runtime to have support for Map, Set and Promise (e.g.
  most evergreen browsers today), just include --lib
  es2015.collection,es2015.promise. Similarly you can exclude
  declarations you do not want to include in your project, e.g. DOM if
  you are working on a node project using --lib es5,es6.

There's also a list of the API groups that are supported and a very short example in that link.

redpajama_set_name: RedPajamaStackExchange


text:
Q: setEntries of MultiSelectListPreference in Activity I've a problem and don't know the way out of it at the moment. I hope someone could help me with my issue.
I want to let the user check, which contacts he want to add to a preference.
The preference is needed for sending sms to the given contacts.
I initialize my MultiSelectListPreference in a xml like this:
<MultiSelectListPreference
     android:key="sourcecontacts"
     android:entries="@array/contacts"
     android:entryValues="@array/contacts"
     android:title="@string/source_contact"
     />

In my Activity I have an OnPreferenceClickListener which should call the method manageContacts() if the MultiSelectListPreference is clicked.
In this method I want to read any contacts of the device and put them into the MultiSelectListPreference that the user can mark those contacts, which should be inserted into the SharedPrefs.
Now my problem is, that I add the entries to the ListPreference but in the UI I can't see any entries.
Do I have to reload the View or the component?
I look forward to helpful answers.
You'll find my manageContact method below:
private void manageContacts() {
    if (entryValues == null || entries == null || entries.length <= 1
        || entryValues.length <= 1) {
        Cursor contacts = getContentResolver().query(Contacts.CONTENT_URI,
            null, null, null, Contacts.DISPLAY_NAME);
        startManagingCursor(contacts);
        entryValues = new CharSequence[contacts.getCount()];
        entries = new CharSequence[contacts.getCount()];
        int ix = 0;
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        Cursor cursor = getContentResolver().query(
            uri,
            new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER,
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone._ID }, null,
            null,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
        cursor.moveToFirst();
        while (cursor.isAfterLast() == false) {
            String contactNumber = cursor
                .getString(cursor.getColumnIndex(
                    ContactsContract.CommonDataKinds.Phone.NUMBER));
            String contactName = cursor
                .getString(cursor.getColumnIndex(
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            if (contactNumber != null && !contactNumber.isEmpty()) {
                entries[ix] = contactName;
                entryValues[ix] = contactNumber;
                ix++;
            }
            cursor.moveToNext();
        }
        cursor.close();
        cursor = null;
    }
    MultiSelectListPreference sourceContacts = (MultiSelectListPreference)
            getPreferenceScreen().findPreference("sourcecontacts");
    MultiSelectListPreference targetContacts = (MultiSelectListPreference)
            getPreferenceScreen().findPreference("targetcontacts");
    if (entries != null && entryValues != null && entries.length >= 1
        && entryValues.length >= 1) {
        sourceContacts.setSelectable(true);
        targetContacts.setSelectable(true);
        sourceContacts.setEntries(entries);
        sourceContacts.setEntryValues(entryValues);
        targetContacts.setEntries(entries);
        targetContacts.setEntryValues(entryValues);
    } else {
        sourceContacts.setSelectable(false);
        targetContacts.setSelectable(false);
    }
}


text:
Q: Adding new entry in ComboBox (on a form) (Excel VBA) into catalogue that is "stored" in another sheet I will try to explain what i'm struggling with.
**This is my "set-up" -> **I have a ComboBox in an Excel Form that is linked to a list of items that is stored on another sheet. So for now people can select items that are stored on that sheet in the ComboBox.
My question is, can a new entry in my ComboBox (so an item that is not in my list on the other sheet) be automatically added to my excel sheet "list of items" when entered in the ComboBox?
I can't find any info about this on Youtube or other webpages. Or don't know what to look for.


text:
Q: How do I consolidate local commits into one per file before a git push? Been using git for a little bit now, but only the basic features.
In order to switch to Textmate and keep the cool local history feature that Eclipse had, I did this. Which is working great.
But now I'm working on a team with a private github repository. I don't want to pollute the team with my full local history of useless commits.
I know there are some tools to edit my commits, but:

git rebase -i
You asked me to rebase without telling me which branch you want to
  rebase against,
SNIP

What branch? :)
So I'm wondering if you have tips on how to manage all this. I'd like to combine all commits for one file into one commit max. And edit the message so it says something useful.
Thanks!

A: git rebase -i

expects you tell it what range of commits to work on. The most common use is
git rebase -i HEAD~4

which would allow you to "edit" the last 4 commits in the current checked out branch.
I'm not sure why you would want to do this "per file". Also, 'rebase -i' will give you headaches if you have merges in there. From what I can infer, you can do this:
Set the current commit to be at the start of your changes, but keep the working directory as is.
git reset --mixed HEAD~10

This would move you back to where you started if you had 10 commits for your changes. "mixed" will ensure that you don't stage any of those changes and the index is clean.
Then, commit changes to each individual file:
git add path/to/one/of/the/files/file.txt
git commit -m "added feature X to file.txt"

repeat for the rest of the files. Inspect along the way with git status.
When you push, you may need to add the -f option (--force) if you already pushed some of those commits. If others were working off of those commits, let them know you did this. They will have to rebase their changes.


text:
Q: How to set the http.server module to use a custom 404.html page? I want to change the default 404 page of the python3 module http.server to a custom 404.html page, so it will redirect the client to that page.
I have confirmed the 404.html works, but putting a 404.html in the web root doesn't help.
Any solution?


text:
Q: How to unpack two points with \foreach Some one could explain why this unpacking rule does not work?
    \foreach \x / \y in {(2.0,3.0) / (2.0,5.0), (2.0,3.0) / (2.0,5.0), (2.0,3.0) / (2.0,5.0)}
    {
        \draw \x -- \y;
    }

A: The special handling of coordinates only applies where the first character in an item is a (. In that case, everything up until the first ) is read as part of one value. So the coordinates before the / are OK, but those after the / need to be enclosed in curly brackets. (See page 902 of the manual.)
In addition, the parser doesn't seem to like some of the spaces and you need something like the following.
\documentclass[border=10pt,tikz]{standalone}
\begin{document}
\begin{tikzpicture}
  \foreach \x / \y in {(2.0,3.0)/{(2.0,5.0)}, (2.0,3.0)/{(2.0,5.0)}, (2.0,3.0)/{(2.0,5.0)}}
  {
    \draw \x -- \y;
  }
\end{tikzpicture}
\end{document}


text:
Q: My app Stopped Working When I Added TextChangedListener I'm trying a simple Android application which has a EditText field.
The App worked just fine until I added a TextChangedListener to the EditText. The app keeps stopping, and when I remove the Listener, it just works like nothing happened.
Any ideas about this problem?

A: Please check you EditText that you initialise properly then call TextChangedListener.
editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                //Do what ever you want
            }
        });


text:
Q: How do I create "double-struck" square brackets in math mode? I am writing some proofs using LaTeX, and following the standard procedure in the ConTeXt, I need to write something as follows:

However, I have no idea how to create the "double bracket", like the one includes x := y + z...
Could anyone give me some help on this?

A:
\documentclass[a4paper,12pt]{article}

\usepackage{stmaryrd}

\begin{document}

\begin{equation}
  f_Z\llbracket  x: y z t   \rrbracket
\end{equation}

\end{document}

A: Use \llbracket and \rrbracket from fourier package (for example) for those doubled bracket symbols.
\documentclass{article}

\usepackage{mathtools}
\usepackage{fourier}

\begin{document}
 $ f_{Z} \llbracket x \coloneqq y + z\rrbracket (\sigma) = [ x \mapsto Z ] (\sigma)$

\end{document}

If using the whole fourier package is too much, importing symbols might be an option: Import one symbol from `fourier`
Here's the version with import of the symbols (code copied from fourier.sty)
\documentclass{article}

\usepackage{mathtools}
\DeclareFontEncoding{FML}{}{}%
\DeclareFontSubstitution{FML}{futm}{m}{it}%
\DeclareFontEncoding{FMS}{}{}
\DeclareFontSubstitution{FMS}{futm}{m}{n}
\DeclareFontEncoding{FMX}{}{}
\DeclareFontSubstitution{FMX}{futm}{m}{n}
\DeclareSymbolFont{symbols}{FMS}{futm}{m}{n}%
\DeclareSymbolFont{largesymbols}{FMX}{futm}{m}{n}%

\DeclareMathDelimiter{\llbracket}{\mathopen}{symbols}{153}{largesymbols}{133}
\DeclareMathDelimiter{\rrbracket}{\mathclose}{symbols}{154}{largesymbols}{134}

\begin{document}
$ f_{Z} \llbracket x \coloneqq y + z\rrbracket (\sigma) = [ x \mapsto Z ] (\sigma)$

\end{document}

Please note the difference between the regular symbols f, x etc. from the screen shots.

A: In addition to the fourier and stmaryd packages, the mathabx package also provides "double-struck" square brackets; the macro names are \ldbrack and \rdbrack, respectively.

\documentclass{article}
\usepackage{mathabx} % for `\ldbrack` and `\rdbrack` macros
\begin{document}
$ f_{Z} \ldbrack x := y + z\rdbrack (\sigma) = [x\mapsto Z]\sigma$
\end{document}

A: If you do not want mathabx to replace the default symbol fonts, you can define commands only for the symbols, which are extensible, with this code:
\documentclass{article}
\usepackage{mathtools}

\DeclareFontFamily{U}{matha}{\hyphenchar\font45}
\DeclareFontShape{U}{matha}{m}{n}{ <-6> matha5 <6-7> matha6 <7-8>
matha7 <8-9> matha8 <9-10> matha9 <10-12> matha10 <12-> matha12 }{}
\DeclareSymbolFont{matha}{U}{matha}{m}{n}
%
\DeclareFontFamily{U}{mathx}{\hyphenchar\font45}
\DeclareFontShape{U}{mathx}{m}{n}{ <-6> mathx5 <6-7> mathx6 <7-8>
mathx7 <8-9> mathx8 <9-10> mathx9 <10-12> mathx10 <12-> mathx12 }{}
\DeclareSymbolFont{mathx}{U}{mathx}{m}{n}

\DeclareMathDelimiter{\ldbrack} {4}{matha}{"76}{mathx}{"30}
\DeclareMathDelimiter{\rdbrack} {5}{matha}{"77}{mathx}{"38}

\begin{document}

    \[ f_{Z} \bigl\ldbrack x \coloneqq y + z\bigr\rdbrack(\sigma) = [x\mapsto Z]\sigma \]

\end{document}

Also,  do  not use :=: the colon is not centred on the math axis. With the standard fonts, mathtools defines a \coloneqq command, wich produces a correct version.


text:
Q: Work with XML file that is recieved from AWS (Amazon webservice) I have a button on my Form in C# , when a user clicks on it an XML file received from AWS (Amazon WebService). I want to process this received XML file with xml stylesheet. Should I save this XML in local and then work with that? Or what is the best solution for my scenario?

A: You can load your xml from response stream in XDocument and create XPathNavigator object in-memory. Then you could use overloaded Transform() method to perform stylesheet applying in-memory too.
Example here


text:
Q: Writing to a file and simultaneously reading it to create a race condition in nodejs I'm trying to write to a file and simultaneously read it. I am able to write data to the file but the unable to read from it. No error is thrown when I do this and only the End event is being called on the read file stream.
I recently read that we cannot have race conditions in JS as it is single-threaded and race conditions are only created due to bad designs in a program. So, I tried to fiddle around and tried to create a race condition. I was expecting node to throw some error but came across this unexpected output.

const readFile = fs.createReadStream('./1GB.bin');
const writeFile = fs.createWriteStream('./test.bin');
const read = fs.createReadStream('./test.bin');

readFile.pipe(writeFile);

try {
    read.on('data', data => {
        console.log("data!", data.length);
    })

    read.on('end', _ => {
        console.log("END!");
    })

    read.on('error', err => console.log("Phatt gaya!"))
}
catch (err) {
    console.log("CAN't read 2nd file!");
}

Expected Result: Throw an error on trying to read the file
Actual Result: No error is thrown and only the End event is triggered
Does anyone have any idea on why is it functioning like this?
Link to the race condition article in case someone is interested:
[https://blog.raananweber.com/2015/06/17/no-there-are-no-race-conditions-in-javascript/]

A: The above behavior is happening because writeStream erases the content of the file and then read stream gets the file as empty which in turn triggers the End event on the read stream.


text:
Q: Kill the docker container if the JVM processes running inside dies I am new to Docker, and I was trying out a particular scenario for which I do not find any solution online or on forums.
The detail on my setup is such that, I am using Docker 17.12 on Linux with a compose setup. I have a container that contains a Java process. As a program functionality, we shut down the running Java program based on a few conditions, so as to avoid further damage to the data and consistency of our program. Once detected that the Java program has gone down, we manually bring it up by doing docker stack deploy.
Is there any functionality/signal/setting available in Docker which will kill the container (self-destroy or self-rm) once it detects that the Java program running within it has shut down?

A: If properly set up, the container is the JVM process. Keep in mind that containers are nothing but processes that have been contained in terms of resource usage as well as isolated in terms of filesystem and Linux namespaces.
So, make sure you start the container by running Java in your entrypoint and/or command configuration, rather than using a process manager like systemd as might be the case in your setup.
This usually looks something like this in the Dockerfile:
FROM openjdk:14
COPY /build/libs/your-application.jar ./
CMD java -jar your-application.jar


text:
Q: Assigning one variable to another in Bash ip="192.168.1.1"

if [ -n "$(ip = 192.168.1.1)" ];
then
IPADDR=$(ip addr show |grep 'inet '|grep -v 127.0.0.1 |awk '{print $2}'| cut -d/ -f1)
else
"${ip}"="${IPADDR}"
fi
echo "${IPADDR}"

Im trying to assigning ip="192.168.1.1" to variable IPADDR
the error im geting atm is
Object "=" is unknown, try "ip help".
./test: line 7: 192.168.1.1=: command not found

A: Here ...

if [ -n "$(ip = 192.168.1.1)" ];

... you are executing the command ip, passing arguments = and 192.168.1.1, and capturing its standard output.  These are not valid arguments for that command, so ip emits an error message to its standard error, but nothing to its standard output.
The test [ -n "$(ip = 192.168.1.1)" ] evaluates whether the captured output is non-empty, so this test fails, and consequently, the else block is executed.  Here ...

"${ip}"="${IPADDR}"

... is not a variable assignment but rather a command, because the text to the left of the = is not (just) an identifier.  The IPADDR variable is unset or null, so that expands to 192.168.1.1=.  The shell reports that there is no command of that name.
It's hard to be sure what you were really trying to accomplish, but going with the question title, if you want to assign a value to a variable then the syntax is
variable_name=value

The variable_name must be an identifier.  The value is subject to expansion and quote removal, but not word splitting, so either of these would work for what you appear to be trying to do
ip="${IPADDR}"

or
ip=${IPADDR}

.  With that said, the code does not make sense, because it does not assign a value to variable IPADDR before attempting that assignment.
Earlier, it is possible that you meant
if [ "$ip" != 192.168.1.1 ]

... which tests whether the value of variable $ip, considered as a string, is equal to the string 192.168.1.1.  Even then, however, the code does not make sense overall.


text:
Q: selenium bug when trying to locate a link based on text Okay, so I'm trying to pull links from Craigslist. Specifically I'm trying to find links of class=result-title such as
NICE 2 BR NEAR BOSTON COLLEGE-  HT/HW INCLUDED - ON COMM AVE 9/1

but for some reason the following code
        address = driver.find_elements_by_class_name('result-title')[i].text
        address2 = driver.find_element_by_partial_link_text(address).text
        url3 =url2+address2
        print(url3)
        driver.get(url3)

Does not work.
For example, if it found the previous html link, address2 would somehow end up being NICE 2 BR NEAR BOSTON COLLEGE-  HT/HW INCLUDED - ON COMM AVE 9/1, even though it should be /gbs/fee/6023288599.html
Does anyone know what I'm doing wrong?

A: What you can do here is :
Instead of getting the text of the web element, you can get an attribute value of href to get /gbs/fee/6023288599.html in the address2.
So,
address2 = driver.find_element_by_partial_link_text(address).text

needs to be changed to
address2 = driver.find_element_by_partial_link_text(address).get_attribute('href')

I hope this helps.


text:
Q: running linux command from java, error 500, Cannot run program No such file or directory im trying to send an email with a Linux command from Java, i admit i don't know much about Linux but i think iv'e tried everything and i'm just really confused, if someone could shed some light for it would be great
i export the application to a war file and upload it to a linux server (CentOS)
so here's what i'm doing: i'm triggering the code from a servlet with the browser
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String cmd = "mail -s \"Test Email\" my@email.com < /usr/share/apache-tomcat-7.0.42/webapps/slots_dashboard/alert_mail.txt";

    //String cmd = "whoami"; //returns tomcat

    ProcessBuilder pb = new ProcessBuilder(cmd);
    Process proc = pb.start();

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

    BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

    String s = null;

    while ((s = stdInput.readLine()) != null) {
        resp.getWriter().println(s);
    }

    while ((s = stdError.readLine()) != null) {
        resp.getWriter().println(s);
    }
}

the error i get is:
HTTP Status 500 - Cannot run program "mail -s "Test Email" my@email.com < /usr/share/apache-tomcat-7.0.42/webapps/slots_dashboard/alert_mail.txt": error=2, No such file or directory
if i change the command to whoami i get tomcat in the response, i even went to the servers computer and tried the command from there and there was no problem. guys, please help :(

A: Don't know if that the reason, but all the examples I've seen on how to use ProcessBuilder use a list of strings as arguments to the constructor (a string per parameter), instead of one long string with the entire command.
Maybe it's worth trying something like:
ProcessBuilder pb = new ProcessBuilder("mail", "-s", "\"Test Email\"", "my@email.com", "<", "/usr/share/apache-tomcat-7.0.42/webapps/slots_dashboard/alert_mail.txt");

I'm shooting in the dark here, obviously. But worth a shot.

A: It might be that your tomcat user doesn't have access to that file. Did you use the same username when trying that command manually?


text:
Q: C++ declaring variable inside if statement I have a really basic problem in c++, I'm reading a tab separated file and I want to declare an array with the dimension if the number of fields the file has (work with different files with different widths) so I need to read the first line and count the number of fields, I tried this:
while(getline(t, line));{
...
if(!flag)
{int array[size][5];
flag=1}
...
}

But then I get the error:
error:  'array' was not declared in this scope
I understand it is because the scope of the variable is in the if loop, is there any way to declare a null array and resize it? Or will I have to use pointers?

A: The size of an array must be a compile-time constant. Use a std::vector if you want a dynamically-sized array.
Other issues with your code:

*

*Remove the semicolon after the while, or your loop body will only be executed once after the whole file is read.

*Add a semicolon after flag=1.

A: You are writing C++, so why not use a std::vector<std::vector<int> >? If possible (here it is) try not to use raw pointers.

A: Pointers will be the way to go...

A: int array[size] possible just in C99.
In C++ plain-C array sizes should be compile-time constant.


text:
Q: How does a Shibboleth SP configure IdP metadata files without any downtime in the Shibboleth service? I am curious how Service Providers of Shibboleth avoid downtime in their Shibboleth Service when installing/updating Metadata files within their configuration. I have seen a few websites offer the functionality for users to upload their own Metadata files and have access to SSO almost immediately - how is this possible?
For some context, this is currently what I have to do:

*

*Add a new XML Metadata file to C:\opt\shibboleth-sp_metadata

*Add a new "MetadataProvider" element to C:\opt\shibboleth-sp\etc\shibboleth\shibboleth2.xml

*Open Windows services and restart the "Shibboleth Daemon (Default)" service. Whilst the service is restarting, users are unable to login via SSO with an error message present on screen suggesting the Shibboleth service is currently unavailable

*After 5-10 minutes have passed, the SSO Service is started and ready to be used

Fortunately I am lucky enough to have multiple servers which I can take offline in order to avoid downtime for users, but I am curious that if I had just 1 server how would I avoid downtime for users when I am required to configure/update metadata files for new clients?
My goal for this question is to be able to understand how others are able to configure/update the Shibboleth environment without causing any downtime for users. I really want to achieve automation of configuring new metadata files as opposed to having to do this task manually.
Any tips/pointers will be very much appreciated. Thanks!

A:
I am curious that if I had just 1 server how would I avoid downtime for users when I am required to configure/update metadata files for new clients?

I believe the shibboleth SP has the ability to reload metadata files from a specific folder, such that it would auto-load and auto-configure itself if it sees modified/new metadata in that directory.
You could potentially look into FolderMetadataProvider, or its preferred alternative, LocalDynamicMetadataProvider.
Per the docs,

The LocalDynamicMetadataProvider fetches metadata from a local source dynamically as needed. The deployer is responsible for populating the local source with data, which may be done while the metadata provider is running. New metadata will be seen automatically the first time it is requested. The LocalDynamicMetadataProvider (added in V3.3.0) is used with local metadata.


text:
Q: Visual Studio: Custom code highlighting based on regex As my application supports some paranoid debug level (every data assignment, every step in the code is written to a log destination), my code is littered with logging calls in some methods, e.g.
logger.Log(LogLevel.Debug, 0, "Initializing i18n...");
Lang.Language = SystemInfo.Language;
Logger.Log(LogLevel.Debug, 0, "Default system language: " + Lang.Language);
string[] languageFiles = Directory.GetFiles(ClientEnvironment.LanguagePath);
Logger.Log(LogLevel.Debug, 0, "Initializing local language files...");

As you can see, there are only two "real" code lines. This makes the code somewhat hard to read. I wonder whether I can specify some custom code formatting rule within Visual Studio to let the logging lines appear in a soft gray text color, instead of the default text color. This would lead to an implicit highlighting of the "real" code lines, resulting in a more readable code.
I need something like:
If statement starts with "logger.Log", set foreground color to gray.

Do you know any plugins which could archieve such a behaviour?
Thank you in advance.

A: altrue.CustomColoring extension allows to set custom foreground color based on simple regular expressions. Restart Vs Code after installing it, it won't work correctly without restart.

https://marketplace.visualstudio.com/items?itemName=altrue.CustomColoring

A: Edit: This is not an appropriate answer to the poster's question, but I cannot delete it because StackOverflow won't allow the accepted answer to be deleted.
This Visual Studio extension will do just what you want:

*

*VSColorOutput - A Visual Studio extension to colorize your build and debug output
You can specify regular expressions for custom output window colorization.


text:
Q: Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document I am getting element is not attached to the page document error for the above code. Moreover I want to know how to handle elements which 'appear' as a result of an action on the target page.
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.irctc.co.in/eticketing/loginHome.jsf");
    driver.manage().window().maximize();
    driver.findElement(By.linkText("Sign up")).click();

    //Verify whether the navigation is to the correct page
    String title=driver.getTitle();
    if (title.equals("IRCTC Next Generation eTicketing System")){
    driver.findElement(By.id("userRegistrationForm:userName")).sendKeys("abcdef");
    driver.findElement(By.linkText("Check Availability")).click();

    WebElement text=driver.findElement(By.xpath(".//*[@id='userRegistrationForm:useravail']"));
    boolean availability=text.isDisplayed();
    try {if(availability==true){
    System.out.println("The user id is available. Please enter other details to complete registration");
    }}

    catch (NoSuchElementException e){
    System.out.println("The user id is not available. Please enter a different user ID.");
    }
    }
    else
    System.out.println("You are on a wrong page");

    }
    }

A: You need to create a custom wait to handle the element that will appear because of an action. So technically speaking, you are waiting for an expected condition to be true.
private void waitForElement(String element) {
 WebDriverWait wait = new WebDriverWait(Driver, 10); // Wait for 10 seconds.
 wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(element)));
 WebElement element = driver.findElement(By.xpath(element));
 element.click(); // The element is now present and can now be clicked
}

In the above code you know the string / xpath of the element. You can pass it into this method and will wait for 10 seconds for the execpected conditon to become true. When it is true, the element can then be clicked.

A: Rather than catching an exception, the preferred way is to use .findElements() (plural) and then check for empty. If the collection is empty, the element doesn't exist on the page. If it exists, grab .get(0) and use it.
I added a few other optimizations to your code. I would do something more like this.
driver.get("http://toolsqa.com/automation-practice-table/");
driver.findElement(By.linkText("Sign up")).click();

// Verify whether the navigation is to the correct page
if (driver.getTitle().equals("IRCTC Next Generation eTicketing System"))
{
    driver.findElement(By.id("userRegistrationForm:userName")).sendKeys("abcdef");
    driver.findElement(By.linkText("Check Availability")).click();

    List<WebElement> text = driver.findElements(By.id("userRegistrationForm:useravail"));
    if (!text.isEmpty())
    {
        // element found
        if (text.get(0).isDisplayed())
        {
            System.out.println("The user id is available. Please enter other details to complete registration");
        }
    }
    else
    {
        // element NOT found
        System.out.println("The user id is not available. Please enter a different user ID.");
    }
}
else
{
    System.out.println("You are on a wrong page");
}

If you perform some action and then need to wait for an element to appear, you can use WebDriverWait. An example is below that waits for a BUTTON to be visible and clicks it.
By buttonLocator = By.id("theButtonId");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement button = wait.until(ExpectedConditions.visibilityOfElementLocated(buttonLocator));
button.click();

There are many other options under ExpectedConditions that you should check out in the docs linked.


text:
Q: Using unsafe C# to take a pointer to a ushort array and write it to disk (create file) I have a *ushort that points to an array of dimensions x * y of 16 bit values, I would like to be able to write that to disk without copying to managed space, is that possible?

A: Try this - I've created an extension method on Stream that will write a pointer to shorts.  It has the downside of allocating and copying the memory and the major added downside of huge chunks of unsafe code.  It does, however, work as you would expect.  I set up a managed array and then got a pointer to it to simulate getting an ushort * from unmanaged code.
using System;
using System.IO;
using System.Runtime.InteropServices;

namespace UnsafeWriting
{
    class Program
    {
        static void Main(string[] args)
        {
            ushort[] someArray = new ushort[20];
            for (int i = 0; i < 20; i++) { someArray[i] = (ushort)i; }

            using (FileStream stm = new FileStream("output.bin", FileMode.Create))
            {
                unsafe
                {
                    fixed (ushort* dataPtr = &someArray[0])
                    {
                        stm.Write(dataPtr, someArray.Length);
                    }
                }
            }
        }
    }

    public static class Extensions
    {
        public static unsafe void Write(this Stream stm, ushort* data, int count)
        {
            count *= 2;
            byte[] arr = new byte[count];
            Marshal.Copy(new IntPtr(data), arr, 0, count);
            stm.Write(arr, 0, count);
        }
    }
}

If you don't like the allocate and copy, then you can do this instead:
public static unsafe void Write(this Stream stm, ushort* data, int count)
{
    count *= 2;
    byte* b = (byte*)data;
    for (int i = 0; i < count; i++)
    {
        stm.WriteByte(*b++);
    }
}

which also works as expected, except in this case you're adding the overhead of a method invocation for every byte.  The underlying file system streams buffer, so it won't be too much overhead, but it's still there.
Don't ask me what would happen on a big endian processor (are there any that run .NET?) in either case.
EDIT - for grins I ran FileStream through Reflector to look at the underlying code and FileStream itself buffers both the Write() and WriteByte() calls, so I see no reason to use anything but the WriteByte version.  The buffersize that is hard-coded into FileStream is 4K.

A: You could use WriteFile using P/Invoke, but why make the simple complicated?

A simple solution would be to copy the frames to managed memory using, for example, Marshal.Copy, and then write it to  a file with a FileStream.


text:
Q: splinter click button with no attributes I'm using splinter to try and click a button that has no attributes. The html code in developer tools is
<div class="numeric">
     <button>0</button>
     <button>1</button>
     <button>...</button>
     <button>9</button>
</div>

that executes a jquery.
My code looks like this
browser.find_by_css("numeric").find_by_text("0").first.click()

However I am getting that numeric is not found. I have also tried #numeric as well.

A: That's not really the css for the div class.
You could try to find it by xpath using this:
browser.find_by_xpath("//div[contains(@class, 'numeric')]")


text:
Q: Microsoft JScript runtime error: Object doesn't support property or method 'dialog' I am using an .ascx user control where i populating employee data along with employee picture.
while on clicking employee picture i want to display a dialog where i want to have one text field and a text box for input from user. Click event is firing fine but with dialog it gives me the error of "Microsoft JScript runtime error: Object doesn't support property or method 'dialog'". Could please anyone help me to populate a dialog with a text field and text box. I am really new to the JQUERY and struggling to get it work.
In the following code snippet i have added a dialog code from one of the example i found online.
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="OpenAccessDataProvider,a4a794260c0b4440b466f75d11146db8.ascx.cs" Inherits="SitefinityWebApp.SfCtrlPresentation.OpenAccessDataProvider_a4a794260c0b4440b466f75d11146db8" %>
<%@ Register TagPrefix="sf" Namespace="Telerik.Sitefinity.Web.UI.PublicControls.BrowseAndEdit" Assembly="Telerik.Sitefinity" %>
<%@ Register TagPrefix="sf" Namespace="Telerik.Sitefinity.Web.UI.ContentUI" Assembly="Telerik.Sitefinity" %>
<%@ Register TagPrefix="sf" Namespace="Telerik.Sitefinity.Web.UI.Comments" Assembly="Telerik.Sitefinity" %>
<%@ Register TagPrefix="sf" Namespace="Telerik.Sitefinity.Web.UI.Fields" Assembly="Telerik.Sitefinity" %>
<%@ Register TagPrefix="sf" Namespace="Telerik.Sitefinity.Web.UI" Assembly="Telerik.Sitefinity" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>

<telerik:RadListView ID="dynamicContentListView" ItemPlaceholderID="ItemsContainer" runat="server" EnableEmbeddedSkins="false" EnableEmbeddedBaseStylesheet="false">
    <LayoutTemplate>

            <asp:PlaceHolder ID="ItemsContainer" runat="server" />

    </LayoutTemplate>

        <ItemTemplate>

                <sf:DetailsViewHyperLink ID="DetailsViewHyperLink" TextDataField="Title" runat="server" />

           <sf:AssetsField ID="AssetsField1" runat="server" DataFieldName="Picture" />
           <sf:SitefinityLabel ID="SitefinityLabel1" runat="server" Text='<%# Eval("Designation")%>'  WrapperTagName="div" HideIfNoText="true" CssClass="sfitemShortTxt" />
          <sf:SitefinityLabel ID="SitefinityLabel2" runat="server" Text='<%# Eval("CompanyName")%>' WrapperTagName="div" HideIfNoText="true" CssClass="sfitemShortTxt" />
          <sf:AssetsField ID="AssetsField2" runat="server" DataFieldName="Documents"/>

    </ItemTemplate>
</telerik:RadListView>

<sf:Pager id="pager" runat="server"></sf:Pager>

Regards.

A: Got it working guys. Just added a div that is for dialog and than from picture click just called the div. Also, added a JQuery.noConflict(); to prevent any conflicts between Sitefinity and JQuery libraries. Following is the code snippet

Please enter your email address: <input type="text" name="emailAddress" style="width:300px;" />

<asp:TextBox ID="txtBox" runat="server"></asp:TextBox>

<asp:Button ID="Button1" runat="server" Text="Button" CausesValidation="False"
        onclick="Button1_Click" />

A: In my case, jquery files are not loaded properly. So what I did are:
1) Opened the page at Chrome
2) Selected the Developer tools from the menu or Ctrl+Shift+I
3) Clicked on Network to see all.

A: I had the same issue. problem was I had loaded 2 Jquery files. jquery-1.8.3.js and jquery-1.4.1.js . so there was a conflict. after removing jquery-1.4.1.js file . it worked smoothly.


text:
Q: SEO for one page site I am going to create a new website and I am thinking to make the whole website as one page like
http://www.demdous.com/examples/html/laboratory/2/
 so is that will be a problem with Search Engine Optimization ?
Is it preferably to make the website multiple page instead of one page or it make no sense ? In the future google will be able to divide it like

A: You should read through this documentation and make sure you can accommodate google's ajax requirements before you get start. If you can't, you may want to consider pages that make round trip requests to the server.
https://developers.google.com/webmasters/ajax-crawling/docs/getting-started

A: I'd question why you want to make it a single page site like the example you provided.
Is it a stylistic choice? A matter of simplicity? That said, SEO will still largely be about the content of your site, quality links back to your site, and your social media presence.
As long as you're paying attention to these factors (as well as technical concerns like optimizing for HTML5 and Ajax) you should be fine.


text:
Q: Need atomic addition operation code on Solaris(sparc architecture) I need atomic operation code equivalent to following:
__asm__ __volatile__ (
                    " lock;\n"
                    " addl %1, %0; \n"
                    " movl %0, %%eax"
                    : "=m"(a), "=a" (c)
                    : "ir"(b)
                    );

(Adding two variables a and b and output stored in both a and c on Linux)
Equivalent to above is needed on Solaris(Sparc architecture).
Is there anyone to help me out?

A: This article should answer all of your questions in depth and even provides code: http://developers.sun.com/solaris/articles/atomic_sparc/
You may need to re-format it a little in terms of inline assembly, but other than that, should be good to go.


text:
Q: How do you convert a Future to a js.Promise in Scala.js? Since JavaScript doesn't have Futures (at least, not as a standard, as far as I know) but Futures are very prevalent in Scala code (including mine), it would be great to know how to convert from Future[A] to a js.Promise[A] when providing APIs in for consumption in JavaScript.
Is there an existing library function for this?

A: There is a library function for that.
import scala.scalajs.js.JSConverters._

val future: Future[A] = ...
val promise: js.Promise[A] = future.toJSPromise


text:
Q: Error with registration token in FCM with Cloud Functions I have deployed the following JavaScript to Firebase Cloud Function but I am constantly getting the following error even though I know that there is a token saved under the path specified.
The idea is to trigger a notification to device when a new message is written to the database, it then fetches the registration token which is then used to try and send a notification to the user.

Error: Registration token(s) provided to sendToDevice() must be a non-empty string or a non-empty array.

JS Function:
exports.notifyNewMessage = functions.database.ref('/messages/{pushId}/{message}').onCreate((snap, context) => {
  const message = snap.val();
  const fromId = message['fromId'];
  const toId = message['toId'];
  const messageTxt = message ['message'];
  const imageUrl = message ['imageUrl'];

  return admin.database().ref('/fcmtokens/' + toId + '/registration-tokens').once('value').then((userTok) => {

    const registrationTokens = userTok.val()

    console.log(registrationTokens);

    return admin.database().ref('/users' + fromId).once('value').then((userDoc) => {

      const senderName = userDoc.firstName //get('firstName')

      const notificationBody = (imageUrl === "") ? "You received a new image message." : messageTxt

        //build media messages notification
        const payload = {
            notification: {
              title: senderName + " sent you a message",
              body: messageTxt
            },
            data: {
              SENDER_NAME: senderName,
              SENDER_ID: fromId

            }//end data
        }//end payload

        //send message
        return admin.messaging().sendToDevice(registrationTokens, payload).then( response => {
          const stillRegisteredTokens = registrationTokens

          response.results.forEach((result, index) => {
                    const error = result.error
                    if (error) {
                        const failedRegistrationToken = registrationTokens[index]
                        console.error('blah', failedRegistrationToken, error)
                        if (error.code === 'messaging/invalid-registration-token'
                            || error.code === 'messaging/registration-token-not-registered') {
                                const failedIndex = stillRegisteredTokens.indexOf(failedRegistrationToken)
                                if (failedIndex > -1) {
                                    stillRegisteredTokens.splice(failedIndex, 1)
                                }
                            }
                    }
                })//end forEach

                return admin.database().ref("fcmtokens/" + recipientId).update({
                    registrationTokens: stillRegisteredTokens
                })//end update

        })//end sendToDevice

    })//end return-then

  })//end return-then

});

This is my fcmtokens database structure node:
"fcmtokens" : {
    "dBQdpR7l1WT2utKVxdX2" : {
      "registration-tokens" : {
        "c4PSCAUAg5s:Yw95DyVxwElE88LwX7" : true
      }
    }
  }

Question update:
The update database part of my function above is creating a separate branch called registrationTokens of all active tokens. I want to overwrite and update the current token under registration-tokens instead?
return admin.database().ref("fcmtokens/" + recipientId).update({
                        registrationTokens: stillRegisteredTokens
                    })//end update

Image showing the new registrationTokens branch being created.

A: Given your data structure, this code:
admin.database().ref('/fcmtokens/' + toId + '/registration-tokens').once('value').then((userTok) => {
  const registrationTokens = userTok.val()

Leads to registrationTokens being:
{
  "c4PSCAUAg5s:Yw95DyVxwElE88LwX7" : true
}

You then call sendToDevice with:
return admin.messaging().sendToDevice(registrationTokens, payload).then( response => {

But if you look at the reference documentation for `sendToDevice, it says:

registrationTokens
Array of string
An array of registration tokens for the devices to which to send the message.

And clearly your registrationTokens is not an array, but just an object.
To convert it to an array use Object.keys():
  const registrationTokens = Object.keys(userTok.val())


text:
Q: Rails 3 fields_for - sort order gets lost I am using Rails 3.0.3 with ruby 1.9.2p0.
In my profiles_controller (edit function) I have this call
@profile = Profile.find(params[:id])
@profile_items = @profile.profile_items.order("pos")

to get the @profile_items in the correct order, sorted on "pos".
In the _form.html.erb I have the following
<% @profile_items.each do |pi| %>
  <%= pi.pos %> |
<% end %>
<%= f.fields_for :profile_items do |f2| %>
  <%= render 'profile_item_fields', :f => f2 %>
<% end %>

The 3 first lines are test code to show that the @profile_items are in the correct order.
But when they are rendered they have lost the sorted order!
Now I have search a lot for an answer and I think this must be a common "trap" to
fall into.
Thankful for any help...

A: According to the Rails Documentation for fields_for, you can also specify the record object after the record name.
So something like this should work...
<%= f.fields_for :profile_items, @profile_items do |f2| %>
  <%= render 'profile_item_fields', :f => f2 %>
<% end %>

A: This can be accomplished with a default_scope on the nested model:
class YourModel < ActiveRecord::Base
  belongs_to :other_model
  default_scope { order(:name) }
end


text:
Q: TSQL JOIN two tables in one big table I need to JOIN table A and table B in one big table. In each table I have (id,brand,power).
Table A
id | brand | power
-------------------
 1 |   BMW |   500
 2 | SKODA |   220
 3 |PORSCHE|   450

Table B
id | brand | power
-------------------
 1 |    BMW|   500
 2 |  SKODA|   220
 4 |FERRARI|   600
 5 | HUMMER|   350

The result should be:
  | A.brand | A.power | B.brand | B.power
------------------------------------------
1 | BMW     |     500 | BMW     |     500
2 | SKODA   |     220 | SKODA   |     220
3 | PORSCHE |     450 | null    |    null
4 | null    |    null | FERRARI |     600
5 | null    |    null | HUMMER  |     350

Here is what I have tried but it doesn't seem to work.
SELECT
A.id,A.brand,A.[power],B.brand,B.[power]
FROM A
FULL JOIN B on A.id = B.id

Any help?

A: You should use the complete sentence:
SELECT
A.id,A.brand,A.power,B.brand,B.power
FROM tableA A
FULL OUTER JOIN tableB B on A.id = B.id

A: I know this is a brute force, but it works for the time being:
SELECT a.id,
       a.brand,
       a.[power],
       b.brand,
       b.[power]
FROM   a
       LEFT OUTER JOIN b
                    ON a.id = b.id
UNION
SELECT id,
       NULL AS brand,
       NULL AS power,
       brand,
       power
FROM   b
WHERE  id NOT IN (SELECT id
                  FROM   a)


text:
Q: Uncaught reference error: image not defined When I run this in google chrome (or any other browser) I get the error
    Uncaught ReferenceError: image is not defined
Here is the code:
<!doctype html>

<title>Play Pixel Draw</title>

Pixel Draw!

Click on the white squares to change that square blue. Make whatever you want!

Javascript:
function changeImage() {
var square = document.getElementById('first');
if (image.src.match("square1.png")) {
    image.src = "squareblue1.jpg";
} else {
    image.src = "square1.png";
}
}

Assuming that all of the pictures are in the right place, how can I fix this?

A: There is no reference to an image variable in the code below - it is, as the error suggests, not defined.
function changeImage() {
    var square = document.getElementById('first');
    if (image.src.match("square1.png")) {
        image.src = "squareblue1.jpg";
    } else {
        image.src = "square1.png";
    }
}

All you have to do is change the square variable to image, I assume.
function changeImage() {
    var image = document.getElementById('first');
    if (image.src.match("square1.png")) {
        image.src = "squareblue1.jpg";
    } else {
        image.src = "square1.png";
    }
}


text:
Q: How to prove that the following function is monotonically increasing? $$f(x) =  \frac{\sqrt{x}\int_a^1 e^{-xs} s^{b+1}~ \mathrm{d}s}{\int_a^1 e^{-xs} s^{b} ~\mathrm{d}s}:\left]0,+\infty\right[\ \to \mathbb{R} $$
where $0 < a < 1$ and $b > 0.$
By applying elementary rules of differentiation I can only prove that the function is monotonically increasing in $\left]\ 0,\frac{1}{1-a}\ \right]$
But I need to prove that it is monotonically increasing in $\left]\ 0,+\infty\ \right[$

A: Your conjecture is incorrect. In particular, for $a=b=1/10$ we have $f'(5)=-0.00561\ldots<0$.


text:
Q: How to change existing triggers to be with 'not for replication' in merge replication in SQL Server? How to make a script that will change all triggers in a database to be NOT FOR REPLICATION? Is there a system procedure for it or we need to parse its definition and inject NOT FOR REPLICATION?

A: Yes, manually, but first I would try this way:
proc [dbo].[db_compare_make_trigger_NOT_FOR_REPLICATION_sp]
as

declare cur cursor fast_forward for
select st.name, definition, is_disabled, OBJECT_NAME(parent_id)
from sys.triggers st join
    sys.sql_modules sm on st.object_id = sm.object_id
where is_ms_shipped = 0
    and is_not_for_replication = 0
    and parent_id > 0

declare @name nvarchar(127), @definition nvarchar(max), @is_disabled bit, @table nvarchar(127)

open cur

fetch next from cur into @name, @definition, @is_disabled, @table

while @@FETCH_STATUS = 0
begin
    declare @sql nvarchar(max) = null

    declare @name_bckp nvarchar(127) = '__' + @name + N'_' + replace(replace(replace(replace(CONVERT(nvarchar,getdate(), 126), '-', '_'), ':', '_'), '.', '_'), 'T', '_')
    PRINT @NAME + ' ON ' + @table
    set @sql = dbo.RegExReplace(@definition, 'AS\s+BEGIN', ' NOT FOR REPLICATION' + CHAR(13) + CHAR(10) + 'AS' + CHAR(13) + CHAR(10) + 'BEGIN')
    if charindex('NOT FOR REPLICATION', @sql) = 0
        set @sql = dbo.RegExReplace(@definition, 'AS\s+SET NOCOUNT ON', ' NOT FOR REPLICATION' + CHAR(13) + CHAR(10) + 'AS' + CHAR(13) + CHAR(10) + 'SET NOCOUNT ON')
    if charindex('NOT FOR REPLICATION', @sql) > 0
    begin try
        --BCKP it
        exec sys.sp_rename @NAME, @name_bckp
        set @definition = 'DISABLE TRIGGER [' + @name_bckp + '] ON [' + @table + ']'
        execute sp_executesql @definition
        --create it
        execute sp_executesql @sql
        --set previous state
        if @is_disabled = 1
            set @definition = 'DISABLE TRIGGER [' + @NAME + '] ON [' + @table + ']'
        else
            set @definition = 'ENABLE TRIGGER [' + @NAME + '] ON [' + @table + ']'
        execute sp_executesql @definition
        set @definition = 'DROP TRIGGER [' + @name_bckp + ']'
        execute sp_executesql @definition
        print 'DONE!'
    end try
    begin catch
        declare @msg nvarchar(4000) = ERROR_MESSAGE()
        declare @esv int = error_severity()
        declare @est int = error_state()
        declare @lin int = error_line()

        insert into db_log (dateCreated, msg, Level, State, Line, additional)
        values(getdate(), @msg, @esv, @est, @lin, @NAME)
        print 'ERROR check db_log: ' + @msg
    end catch

    fetch next from cur into @name, @definition, @is_disabled, @table
end
close cur
deallocate cur

And remained triggers I would do manually.
for this to work you will need:
CLR Assembly RegEx Functions for SQL Server


text:
Q: Installing Windows7 on a laptop that was on Windows8, then on Ubuntu I bought a laptop, it came with windows 8. Horrible.
So I installed Ubuntu. Then I couldn't access windows 8 anymore. So I played around and ended up deleting my windows 8.
I reinstalled the whole thing from scratch, only with Ubuntu this time.
Now, I want to install a "fresh" copy of windows 7 on another partition.
I created a bootable usb stick, but it won't load. It always goes straight to GRUB.
I did the boot-repair.
Well, now, I could pick someone's brain.
Thanks :) and Merry Xmas and Happy holidays!!

A: If your laptop is trying to boot from the hard drive ignoring the bootable USB drive, then either 1) USB drive is not set as highest-prority boot device in BIOS setup; 2) the USB drive isn't actually "bootable".

A: Try another bootable program on the same pen or make a win7 DVD and try to boot from it.
So you can narrow down the problem


text:
Q: Is the phrase "fitting (someone) in (to a schedule)" all right to use or is there a better way to say this? fit (someone) in (to a schedule)
Is this phrase useful for scheduling meetings and appointments. When you're talking to someone with a busy schedule, you may have to ask them to "fit you in". "Fitting you in" means fitting you into their schedule. You can imagine a schedule book with each meeting or appointment taking up a block of time. If the person has enough room to add your appointment between two other appointments, then you say that they could "fit you in".
I guess it's an idiom, but it doesn't seem as though this is the best way to ask for someone to "pencil you in."

A: The phrase is ok to use.
You could use:
I can schedule you for (Date/Time) or
We can schedule a meeting for (Date/Time)
to be more formal.

A: A more idiomatic way (and more appropriate/self-evident in case of a busy schedule) is to use squeeze instead of fit.

Can you squeeze me into your schedule?

TFD(idioms):

squeeze into
v.
  1. To manage to make room or time for someone or something in some tight space or schedule by or as if by exerting pressure:
  The
  dentist can squeeze you into her schedule next week.
The American Heritage® Dictionary of Phrasal Verbs. Copyright © 2005
  by Houghton Mifflin Harcourt Publishing Company. Published by Houghton
  Mifflin Harcourt Publishing Company. All rights reserved.


text:
Q: AdvancedDatagrid with itemEditor: Value disappears when clicked I'm trying to use a ComboBox as itemEditor in an AdvancedDatagrid. Both the grid and the comboBox fills up correctly with values. But when I click in a cell the value disappears. Do I need to set more properties to make this work, or do I have to write my own itemEditor that copies the value to and from the itemEditor?
Full code:
<?xml version="1.0"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx"
               initialize="initCB();">

<fx:Script>
    <![CDATA[
        import mx.collections.*;
        [Bindable] public var stateArray:ArrayCollection;

        public function initCB():void {
            stateArray=new ArrayCollection([{label:"AL", data:"Montgomery"},
                                      {label:"AK", data:"Juneau"},
                                      {label:"AR", data:"Little Rock"}]);
        }

        [Bindable] public var initDG:ArrayCollection = new ArrayCollection([{etikett:'NY', tekst:"New York"}, {etikett:'CA', tekst:"Los Angeles"}]);
    ]]>
</fx:Script>

<mx:AdvancedDataGrid id="gridIntMapping" y="24" left="10" right="605" height="166" editable="true" dataProvider="{initDG}">
    <mx:columns>
            <mx:AdvancedDataGridColumn width="130" dataField="etikett" headerText="Skjema referanse" editorDataField="text">
                <mx:itemEditor>
                    <fx:Component>
                        <mx:ComboBox editable="true" dataProvider="{outerDocument.stateArray}" labelField="label"/>
                    </fx:Component>
                </mx:itemEditor>
            </mx:AdvancedDataGridColumn>
    </mx:columns>
</mx:AdvancedDataGrid>

A: Set data.etikett to combobox text. like following:
<mx:ComboBox editable="true" dataProvider="{outerDocument.stateArray}" labelField="label" text="{data.etikett}" />

It will display text when you click.


text:
Q: How to aggregate two Strings and a List into a single byte[] and then extract them I need to aggregate 2 Strings and a List into a single byte[] in order to send it through the network (using a special library that has a function send(byte[]).
Then, on the other end, I need to get the 3 different objects back.
I've done an ugly implementation of it, but it is very slow. Basically, what I do is
        public byte[] myserializer(String dataA, String dataB, List<byte[]> info) {

        byte[] header = (dataA +";" + dataB + ";").getBytes();

        int numOfBytes = 0;
        for (byte[] bs : info) {
            numOfBytes += bs.length;
        }

        ByteArrayOutputStream b = new ByteArrayOutputStream();
        ObjectOutputStream o;
        try {
            o = new ObjectOutputStream(b);
            o.writeObject(info);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        byte[] data = b.toByteArray();

        int length = header.length + data.length;
        byte[] headerLength = (new Integer(header.length)).toString()
                .getBytes();
        byte[] pattern = ";".getBytes();
        int finalLength = headerLength.length + pattern.length + length;

        byte[] total = new byte[finalLength];enter code here
        total = // Copy headerLength, header and total into byte[] total

        return return;

In essence I'm creating kind of a frame that looks like this
      HEADER                    INFO

(-----------------------------------------------)(----------------------------------)
HEADER_LENGHT;DATA_A;DATA_B;SERIALIZED_LIST_OBJECT
Then, on the receiver side, I do the inverse process and that's "all". This works, but it is PRETTY inefficient and ugly.
Suggestions? Best practices? Ideas?
Oh...just one note more: this have to work for J2SE and Android too
Thanks so much in advanced!!

A: Write it all to a ByteArrayOutputStream, with an ObjectOutputStream around it to serialize the Strings and the List, and then call the method that turns the BAOS into a byte[] array. At the other end, do the inverse.
Or define a serializable object that contains the {String, String, List} tuple and just serialize that with ObjectOutputStream, and deserialize that with ObjectInputStream. Much simpler.
Or just do three sends. TCP is a byte stream, there are no boundaries between the messages, the bytes all arrive sequentially. If you want to conserve writes to the network, interpose a BufferedOutputStream and flush it after writing the List.

A: Here is a simplistic method of serializing an array of bytes and deserialize it on the other side. Note that the method only accept one argument of type List<byte[]> and since your argument dataA and dataB are of type String, you can simply assume that the two first byte[] elements in the list are those two argument. I believe that this is a lot faster than object serialization through an ObjectOutputStream and will be faster to deserialize on the other side as well.
public class ByteListSerializer {
static private final int INT_SIZE = Integer.SIZE / 8;

    static public void main(String...args) {
        ByteListSerializer bls = new ByteListSerializer();

        // ============== variable declaration =================
        String dataA = "hello";
        String dataB = "world";
        List<byte[]> info = new ArrayList<byte[]>();
        info.add(new byte[] {'s','o','m','e'});
        info.add(new byte[] {'d','a','t','a'});
        // ============= end variable declaration ==============

        // ======== serialization =========
        info.add(0, dataA.getBytes());
        info.add(1, dataB.getBytes());
        byte[] result = bls.dataSerializer(info);

        System.out.println(Arrays.toString(result));

        // ======== deserialization ========
        List<byte[]> back = bls.dataDeserializer(result);

        String backDataA = new String(back.get(0));
        String backDataB = new String(back.get(1));
        back.remove(0);
        back.remove(0);

        // ============ print end result ============
        System.out.println(backDataA);
        System.out.println(backDataB);
        for (byte[] b : back) {
            System.out.println(new String(b));
        }
    }

    public byte[] dataSerializer(List<byte[]> data) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteBuffer lenBuffer = ByteBuffer.allocate(4);

        try {
            for (byte[] d : data) {
                lenBuffer.putInt(0, d.length);
                out.write(lenBuffer.array());
                out.write(d);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // wrap this
        byte[] dataBuffer = new byte[out.size() + 4];
        lenBuffer.putInt(0, out.size());
        System.arraycopy(lenBuffer.array(), 0, dataBuffer, 0, 4);
        System.arraycopy(out.toByteArray(), 0, dataBuffer, 4, out.size());

        return dataBuffer;
    }

    public List<byte[]> dataDeserializer(byte[] data) {
        if (data.length < INT_SIZE) {
            throw new IllegalArgumentException("incomplete data");
        }

        ByteBuffer dataBuffer = ByteBuffer.wrap(data);
        int packetSize = dataBuffer.getInt();

        if (packetSize > data.length - INT_SIZE) {
            throw new IllegalArgumentException("incomplete data");
        }

        List<byte[]> dataList = new ArrayList<byte[]>();
        int len, pos = dataBuffer.position(), nextPos;

        while (dataBuffer.hasRemaining() && (packetSize > 0)) {
            len = dataBuffer.getInt();
            pos += INT_SIZE;
            nextPos = pos + len;
            dataList.add(Arrays.copyOfRange(data, pos, nextPos));

            dataBuffer.position(pos = nextPos);
            packetSize -= len;
        }

        return dataList;
    }
}

The frame is constructed as
     - 4 bytes: the total bytes to read (frame size = [nnnn] + 4 bytes header)
    |      - 4 bytes: the first chunk size in bytes
    |     |          - x bytes: the first chunk data
    |     |         |
    |     |         |           - 4 bytes: the n chunk size in byte
    |     |         |          |         - x bytes: the n chunk data
    |     |         |          |        |
    |     |         |          |        |
[nnnn][iiii][dddd....][...][iiii][dddd...]

The example above will output
[0, 0, 0, 34, 0, 0, 0, 5, 104, 101, 108, 108, 111, 0, 0, 0, 5, 119, 111, 114, 108, 100, 0, 0, 0, 4, 115, 111, 109, 101, 0, 0, 0, 4, 100, 97, 116, 97]
hello
world
some
data

Note that the frame format is formed of byte[] chunks so as long as you know the order of the chunks, you can use these methods with virtually any set of data.


text:
Q: Python Telegram Bot not commiting rows to sqlite I've got a working python telegram bot in one python file (ltcbot). It does reply and recognizes commands. I also have another file with a sqlite db routine (ltcpool).
When ltcpool is executed directly it runs smoothly, however when I call it the 'record' function from the bot file, doesn't commit data to sqlite, albeit prints out the index. I have no idea why it may behave this way, please any tips would be appreciated.
Here is the bot file:
import telegram
import ltcpool

TOKEN = "****"
SERVER = '****'

def send(msg='', chat_id=-***, token=TOKEN):
    """
    Send a message to a telegram user or group specified on chatId
    chat_id must be a number!
    """
    bot = telegram.Bot(token=token)
    bot.sendMessage(chat_id, msg)

def status(update, context):
    ltcpool.record()
    update.message.reply_text(ltcpool.getStatus())

def htel(update, context):
    update.message.reply_text('Check how it\'s going on ltcpool.')

def echo(update, context):
    update.message.reply_text(
        '/help')

def tbot():
    updater = Updater(TOKEN, use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("help", htel))
    dp.add_handler(CommandHandler("status", status))

    dp.add_handler(MessageHandler(Filters.text, echo))
    updater.start_webhook(
        listen="0.0.0.0",
        port=5002,
        url_path='bot_checkltc',
        webhook_url=f'https://{SERVER}/bot_checkltc'
    )

    # updater.bot.deleteWebhook()
# stuff to run always here such as class/def

def main():
    pass

if __name__ == "__main__":
    # stuff only to run when not called via 'import' here
    tbot()

Here is the db handler:
import pytz
import requests
import json
import sqlite3
import datetime
import ltcbot

api_key = "cc83832ca104d78ed304a7c0aa947c54"

table = """CREATE TABLE if not exists "workers" (
        "worker" TEXT,
        "check_time" timestamp,
        "connected" INTEGER,
        "hash_rate" REAL,
        "hash_rate_24h" REAL,
        "valid_shares" INTEGER,
        "stale_shares" INTEGER,
        "invalid_shares" INTEGER,
        "rewards" REAL,
        "rewards_24h" REAL,
        "last_share_time" INTEGER,
        "reset_time" INTEGER
);
"""

class DatabaseManager(object):
    def __init__(self, db):
        self.conn = sqlite3.connect(db)
        self.conn.execute('pragma foreign_keys = on')
        self.conn.commit()
        self.cur = self.conn.cursor()

    def query(self, qry, vars):
        self.cur.execute(qry, vars)
        self.conn.commit()
        return self.cur

    def __del__(self):
        self.conn.close()

def getdata():
    url = requests.get(
        f'https://www.litecoinpool.org/api?format=json&api_key={api_key}')
    data = json.loads(url.text)
    return data

def record():
    data = getdata()
    dt = datetime.datetime.now(pytz.timezone('Asia/Bishkek'))
    db = DatabaseManager('ltcpool.sqlite')
    # Create table if not exists
    db.query(table, '')

    for index, worker in data['workers'].items():
        print(index)
        db.query("Insert into workers values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                 (index, dt,
                  worker['connected'],
                  worker['hash_rate'],
                  worker['hash_rate_24h'],
                  worker['valid_shares'],
                  worker['stale_shares'],
                  worker['invalid_shares'],
                  worker['rewards'],
                  worker['rewards_24h'],
                  worker['last_share_time'],
                  worker['reset_time']))

def getStatus():
    db = sqlite3.connect('db.sqlite')

    online = 0
    offline = 0
    hashrate = 0
    avg_hashrate = 0
    status = f'''

    Online: {online}
    Offline: {offline}

    '''

    return status

def main():
    pass

if __name__ == "__main__":
    # stuff only to run when not called via 'import' here
    record()
    # ltcbot.send()


text:
Q: The whole file icon is not visible in javafx tableview I have a JavaFX tableview in which I'm listing files and their properties, including the ICON of the file. My problem is that a part of the icon is missing.
I don't know how to describe it completely so I included an image below.

My tableview is to the right and windows explorer is to the left.
Here is the code:
@Override
public void updateItem(ImageIcon imageIcon, boolean empty){
    if (imageIcon != null){
        // I have tried adding minimum width and height too
        HBox box= new HBox();

        // JavaFX scene imageview
        ImageView imageView = new ImageView();
        // Have tried with and without setFitHeight
        imageView.setFitHeight(16);
        imageView.setFitWidth(16);

        // This line prints: 16 16
        System.out.println(imageIcon.getIconWidth() + " " + imageIcon.getIconHeight());

        // Create BufferedImage of the imageicon
        BufferedImage bi = new BufferedImage(
                imageIcon.getIconWidth(),
                imageIcon.getIconHeight(),
                BufferedImage.TYPE_INT_ARGB);
        Graphics g = bi.createGraphics();

        imageIcon.paintIcon(null, g, 0, 0);
        g.dispose();

        // BufferedImage to fxImage
        Image fxImage = SwingFXUtils.toFXImage(bi, null);

        imageView.setImage(fxImage);

        box.getChildren().addAll(imageView);
        setGraphic(box);
    }
}

Thanks.
UPDATE
I have google around some more and i copied an example directly and pasted into a new project, and the same thing happened with the icons. In the example, the user was probably using windows 7 by judging the look of the icons, so maybe this is just the way it looks in windows 8. It was the code in the answer at the bottom with a picture: www.stackoverflow.com/questions/28034432/


text:
Q: Problem creating a properties file This is what I finally ended up doing. It works great but could probably use some fine tuning.
File file = new File("C:/Users/Mike Home/Desktop/"+fileName+".properties");
FileInputStream inStream = null;
FileOutputStream outStream = null;
Properties config = new Properties();

        try{
            if (file.exists()){//Checks if it exists.
            inStream = new FileInputStream(file);
                if (inStream.available() >= 0){//Cheacks if it has anything in it.
                    config.load(inStream);
                    System.out.println(config);
                }
            }

            config.setProperty(property , score);//New property
            outStream = new FileOutputStream(file);
            config.store(outStream, "Property");//Names the Properties that are in the file Property
            config.list(System.out);//Prints out all the properties.

        } catch (IOException ioe){//Handles any problems
            System.out.println("You just pooped the pants");
        } finally{//Closes both input and output Streams if they are open
            try {
                if(inStream != null)
                    inStream.close();
                if (outStream != null)
                    outStream.close();
            } catch (IOException e) {
            }
        }
}

I have two sets of code. One that just writes a property to a file and one that is a bit more in depth. I think they should both be writing the fill if it doesn't exist but only one of them does. Here is each code with some extras. I'm just using the console right now and I'm just messing around so its not flashy at all.
private void properties() {
    System.out.println("What would you like to name the .properties file?");
    sTest.stringReader();
    String fileName =sTest.getString();// This will be the name of the file.
    System.out.println("What property would you like to change?");
    sTest.stringReader();
    String property= sTest.getString();
    System.out.println("What would you like to change the " + property + " to?");
    sTest.stringReader();
    String score = sTest.getString();

        try {
            File file = new File("C:/Users/Mike Home/Desktop/"+fileName+".properties");
            FileInputStream inStream = new FileInputStream(file);
            Properties config = new Properties();
            config.load(inStream);
            // Create a new property
            config.setProperty(property , score);
            FileOutputStream outStream = new FileOutputStream(file);
            config.store(outStream, "Property");
            inStream.close();
            outStream.close();
            config.list(System.out);
        } catch (IOException ioe){
            System.out.println("Chould not write file.");
        }
}

And here is the one that just writes a property without adding any thing to it. This method is the one that creates the file but I feel that "File file = new File" should do it for both. But then again feelings don't account for much when programming. I'd love an explanation. Thanks.
private void myWrite() {
    System.out.println("What would you like to name your file?");
    sTest.stringReader();
    String fileName =sTest.getString();// This will be the name of the file.
    System.out.println("What would you like to put in you file?");
    sTest.stringReader();
    String letsWrite = sTest.getString();
        try {
            File file = new File("C:/Users/Mike Home/Desktop/"+fileName+".properties");
            FileOutputStream fileStream = new FileOutputStream(file);
            write(fileStream, letsWrite);
        } catch (IOException ioe){
            System.out.println("Could not write file" + ioe);
        }
    }

Redo on the code with your help:
System.out.println("What would you like to change the " + property + " to?");
    sTest.stringReader();
    String score = sTest.getString();

    try {
        File file = new File("C:/Users/Mike Home/Desktop/"+fileName+".properties");
        FileInputStream inStream = new FileInputStream(file);
        Properties config = new Properties();
        config.load(inStream);
        inStream.close();
    } catch (IOException ioe){
        System.out.println("Chould not read file.");
    }

    try{
        File file = new File("C:/Users/Mike Home/Desktop/"+fileName+".properties");
        FileOutputStream outStream = new FileOutputStream(file);
        Properties config = new Properties();
        config.setProperty(property , score);
        config.store(outStream, "Property");
        outStream.close();
    } catch (IOException ioe){
        System.out.println("Chould not write file.");
    }

It throws the IOException but it does write the file. How would I close it in a finally block? I haven't used those yet. How do you just load the file first? I'm still working on it I just wanted to get this to you while you were still on. Thanks for your help.
I'm still not getting this very well. I have put in notes of what I think everything is doing. I'll be asking my friend later tonight what is going on but he is more of a MatLab guy.
File file = new File("C:/Users/Mike Home/Desktop/"+fileName+".properties");//new instance of these file
    FileInputStream inStream = null; //Creates variable out side my try block
    FileOutputStream outStream = null;//Creates variable out side my try block
    Properties config = new Properties();//Creates variable out side my try block
    try {
        inStream = new FileInputStream(file); //Loads the file to the Input Stream
        config.load(inStream); //Loads the config with what was in the inStream.

    } catch (IOException ioe){//Handles any problems
        System.out.println("Chould not read file.");
    }

    try{
        //inStream = new FileInputStream(file);//Do I need to do this again?
        //config.load(inStream);// Do I need to do this again?

        //Creates a new property
        config.setProperty(property , score);

        outStream = new FileOutputStream(file); // Preps the outPut stream to write to the file
        config.store(outStream, "Property");//Names the Properties that are in the file Property
        config.list(System.out);//Prints out all the properties.
    } catch (IOException ioe){//Handles any problems
        System.out.println("Chould not write file.");
    } finally{//Closes both input and output Streams
        try {
            inStream.close();//It says these need to be in a try/catch block also.
        } catch (IOException e) {
        }
        try {
            outStream.close();
        } catch (IOException e) {
        }
    }

A: A File object represents a file path. Creating a File instance doesn't create a file on the file system. Opening an FileOutputStream and writing to it is the operation which creates the file on the file system.
Your first code snippet tries to read and write from/to a file at the same time. You should read from the file, close the input stream, and then open an output stream, write and close the output stream. Reading from a file if it doesn't exist will throw an IOException, so you have to handle this possibility. And any input/output stream should always be closed in a finally block.

A: The code throws an IOException because config.load() reads from the file. But since you are handling the exception, the code does not fail at that point and continues to write to the file. If you first write to the file and then read from it, you would not get the exception. You could load the file first, if the file had data on it.
    File file = new File("C:/Users/Mike Home/Desktop/"+fileName+".properties");
    FileInputStream inStream = new FileInputStream(file);
    if(inStream.available() > 0){
        Properties config = new Properties();
        config.load(inStream);
    }
    inStream.close();

The above code reads only if there is data in the stream and so it will not throw an exception


text:
Q: RabbitMQ python worker script using 100% CPU I worte this python script which acts as an RPC server by modifying the default RPC example in  RabbitMQ tutorial found here. It runs fine in my laptop. But when i run it in an amazon ec2 High CPU Medium Instance with these specs :

1.7 GiB of memory
5 EC2 Compute Units (2 virtual cores with 2.5 EC2 Compute Units each)
350 GB of instance storage

It takes up 100% CPU. Although my laptop with almost the same config runs this with less than 4% CPU use.I run this in Ubuntu-12.04 in both my laptop and amazon.
Here is my code

    #!/usr/bin/env python
    import pika
    import commands
    import socket
    import base64

    connection = pika.BlockingConnection(pika.ConnectionParameters(
             host='localhost'))
    channel = connection.channel()
    channel.queue_declare(queue='rpc_queue')
    def on_request(ch, method, props, body):
        #print body
        body = base64.b64decode(body)
        print body
        run = commands.getoutput(body)
        response = socket.gethostname()
        print response
        ch.basic_publish(exchange='',
                        routing_key=props.reply_to,
                        properties=pika.BasicProperties(correlation_id = \
                                                      props.correlation_id),
                        body=str(response))
        ch.basic_ack(delivery_tag = method.delivery_tag)
    channel.basic_qos(prefetch_count=1)
    channel.basic_consume(on_request, queue='rpc_queue')
    print " [x] Awaiting RPC requests"
    channel.start_consuming()

How can i fix this ?

A: Finally found the problem. It was a bug in Pika, i got this information from rabbitmq's mailing list. I had installed pika through pypi. pip install pika.
To fix this i uninstalled pika
pip uninstall  pika
and reinstalled it from git
pip install git+https://github.com/pika/pika.git.
And that solved it.


text:
Q: Searching for substrings in large text document? I have a large text file that I need to search for certain substrings and I would like to use the speed-up that TextSearch gives. Unfortunately, with TextSearch queries will only match entire words:
f = Export["~/test.txt", "1234 1234"];
TextSearch[CreateSearchIndex@f, SearchQueryString["*23*"]]

I'd prefer not to use StringCases as it is very slow on the large document. Is there some way around this?

A: You may use SearchQueryString in TextSearch.
f = Export["~/test.txt", "helloworld"];
TextSearch[CreateSearchIndex@f, SearchQueryString["hello*"]]

Hope this helps.


text:
Q: _tkinter.TclError: couldn't connect to display ":0" in plot I'm plotting a graph to observe the gaussian distribution.
Code:
import random
import matplotlib.pyplot as plt

nums = []
mu = 100
sigma = 50

for i in range(100):
    temp = random.gauss(mu, sigma)
    nums.append(temp)

plt.plot(nums)
plt.show()

but when I run it, error comes with:
No protocol specified
No protocol specified
Traceback (most recent call last):
  File "hello.py", line 12, in <module>
    plt.plot(nums, temp)
  File "/home/pablo/environments/my_env/lib/python3.7/site-packages/matplotlib/pyplot.py", line 2823, in plot
    return gca().plot(
  File "/home/pablo/environments/my_env/lib/python3.7/site-packages/matplotlib/pyplot.py", line 2351, in gca
    return gcf().gca(**kwargs)
  File "/home/pablo/environments/my_env/lib/python3.7/site-packages/matplotlib/pyplot.py", line 730, in gcf
    return figure()
  File "/home/pablo/environments/my_env/lib/python3.7/site-packages/matplotlib/pyplot.py", line 676, in figure
    **kwargs)
  File "/home/pablo/environments/my_env/lib/python3.7/site-packages/matplotlib/pyplot.py", line 298, in new_figure_manager
    return _backend_mod.new_figure_manager(*args, **kwargs)
  File "/home/pablo/environments/my_env/lib/python3.7/site-packages/matplotlib/backend_bases.py", line 3490, in new_figure_manager
    return cls.new_figure_manager_given_figure(num, fig)
  File "/home/pablo/environments/my_env/lib/python3.7/site-packages/matplotlib/backends/_backend_tk.py", line 859, in new_figure_manager_given_figure
    window = tk.Tk(className="matplotlib")
  File "/usr/lib/python3.7/tkinter/__init__.py", line 2023, in __ init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: couldn't connect to display ":0"


text:
Q: Flutter Firebase login error but still being logged in? EDIT: The login functions is somehow called twice, once with the correct credentials and the other time the email and password String are empty.
This weird hack seems to fix it, but I cannot see why the login function is called twice:
if (email.isEmpty && password.isEmpty) {
  return;
}

I have a weird problem that is caused by Firebase-Auth, I believe. Quick summary of the process:

*

*User logs in normally, then authenticates with the local_auth package using biometrics

*If that is successful, the login credentials (email, password) are stored on the device using FlutterSecureStorage

*Then, on every new app startup, the user will be prompted with the local_auth and if that is successful, I call the login method with the credentials read from the device.

Here comes the error: I get a FirebaseAutException with the error message: given String is empty or null, but then I am being logged in, even though there was an error.
This is the login code:
  void login({required String email, required String password}) async {
    try {
      final _result = await _auth.signInWithEmailAndPassword(
        email: email.trim(),
        password: password.trim(),
      );
      if (_result.user != null) {
        print("HERE1");
        if (!_result.user!.emailVerified) {
          Get.to(() => EmailVerificationScreen());
        }
        if (!await credentialsSaved) {
          Get.to(
            () => BiometricsPage(
              email: email.trim(),
              password: password.trim(),
            ),
          );
        }
        Get.find<UserController>().setUser = await Database().getUser(
          _result.user!.uid,
        );
        loggedIn.value = true;
      }
    } on FirebaseAuthException catch (e) {
      print("HERE2");
      Get.snackbar(
        "Error logging in",
        e.message!,
        snackPosition: SnackPosition.BOTTOM,
        snackStyle: SnackStyle.FLOATING,
        margin: EdgeInsets.all(10),
      );
    }
  }

The print statements occur in the following order:

*

*HERE1

*HERE2

EDIT: After a few tries, I saw that sometimes the print-order was exactly the other way around :/
This is the code I use for retrieving the credentials from the device:
void checkLocalBiometrics() async {
    if (await credentialsSaved) {
      var localAuth = LocalAuthentication();
      bool canCheckBiometrics = await localAuth.canCheckBiometrics;
      if (canCheckBiometrics) {
        var didAuthenticate = await localAuth.authenticate(
          localizedReason: "-----------------",
          biometricOnly: true,
          stickyAuth: true,
        );
        if (didAuthenticate) {
          var secureStorage = FlutterSecureStorage();
          var storedEmail = await secureStorage.read(key: "email");
          var storedPassword = await secureStorage.read(key: "password");
          login(email: storedEmail!, password: storedPassword!);
        }
      }
    }
  }

This is the credentialsSaved method:
Future<bool> get credentialsSaved async {
    var secureStorage = FlutterSecureStorage();
    var storedEmail = await secureStorage.read(key: "email");
    return storedEmail != null;
  }

I can guarantee that the result of the secureStorage.read(...) is not null since I check that in the credentialsSaved method. What am I missing here?

A: I finally found the solution. Turns out that the LoginButton I was using in my LoginPage has an open issue about functions being called twice. (rounded_login_button bug). Can't believe that that was it all the time..


text:
Q: I'd like to know why a function executes fine when called from x but not when called from y When called from archive(), readcont(char *filename) executes fine! Called from runoptions() though, it fails to list the files "archived"! why is this?
The program must run in terminal. Use -h as a parameter to view the usage.
This program is written to "archive" text files into ".rldzip" files.
readcont(char *x) should show the files archived in file (*x)
a) Successful call
Use the program to archive 3 text files:
rldzip.exe a.txt b.txt c.txt FILEXY -a
archive() will call readcont and it will work showing the files archived after the binary FILEXY will be created.
b) Unsuccessful call
After the file is created, use:
rldzip.exe FILEXY.rldzip -v
You can see that the function crashes!
I'd like to know why is this happening!
/*
   Sa se scrie un program care:
   a) arhiveaza fisiere
   b) dezarhiveaza fisierele athivate
 */
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>

struct content{
  char *text;
  char *flname;
}*arc;

FILE *f;

void readcont(char *x){
  FILE *p;

  if((p = fopen(x, "rb")) == NULL){
    perror("Critical error: ");
    exit(EXIT_FAILURE);
  }
  content aux;
  int i;
  fread(&i, sizeof(int), 1, p);
  printf("\nFiles in %s \n\n", x);
  while(i-- >1 && fread(&aux, sizeof(struct content), 1, p) != 0)
    printf("%s \n", aux.flname);
  fclose(p);
  printf("\n\n");
}

void archive(int argc, char **argv){
  int i;

  char inttext[5000], textline[1000];
  //Allocate dynamic memory for the content to be archived!
  arc = (content*)malloc(argc * sizeof(content));
  for(i=1; i< argc; i++)
  {
    if((f = fopen(argv[i], "r")) == NULL){
      printf("%s: ", argv[i]);
      perror("");
      exit(EXIT_FAILURE);
    }
    while(!feof(f)){
      fgets(textline, 5000, f);
      strcat(inttext, textline);
    }
    arc[i-1].text = (char*)malloc(strlen(inttext) + 1);
    strcpy(arc[i-1].text, inttext);
    arc[i-1].flname = (char*)malloc(strlen(argv[i]) + 1);
    strcpy(arc[i-1].flname, argv[i]);
    fclose(f);
  }
  char *filen;
  filen=(char*)malloc(strlen(argv[argc])+1+7);
  strcpy(filen, argv[argc]);
  strcat(filen, ".rldzip");
  f = fopen(filen, "wb");
  fwrite(&argc, sizeof(int), 1, f);
  fwrite(arc, sizeof(content), argc, f);
  fclose(f);
  printf("Success! ");
  for(i=1; i< argc; i++)
  {

    (i==argc-1)? printf("and %s ", argv[i]) : printf("%s ", argv[i]);
  }
  printf("compressed into %s", filen);
  readcont(filen);
  free(filen);
}
void help(char *v){
  printf("\n\n----------------------RLDZIP----------------------\n\nUsage: \n\n Archive n files: \n\n%s $file[1] $file[2] ... $file[n] $output -a\n\nExample:\n%s a.txt b.txt c.txt output -a\n\n\n\nView files:\n\n %s $file.rldzip -v\n\nExample:\n %s fileE.rldzip -v\n\n", v, v, v, v);
}
void runoptions(int c, char **v){
  int i;
  if(c < 2){
    printf("Arguments missing! Use -h for help");
  }
  else{
    for(i=0; i<c; i++)
      if(strcmp(v[i], "-h") == 0){
        help(v[0]);
        exit(2);
      }
    for(i=0; i<c; i++)
      if(strcmp(v[i], "-v") == 0){
        if(c != 3){
          printf("Arguments misused! Use -h for help");
          exit(2);
        }
        else
        {
          printf("-%s-", v[1]);
          readcont(v[1]);
        }
      }
  }
  if(strcmp(v[c-1], "-a") == 0)
    archive(c-2, v);
}

main(int argc, char **argv)
{
  runoptions(argc, argv);

}

A: After taking the liberty to reindent your code, one problem stands out right away: runoptions makes the call to readcont only in the case when -v is found in the argument list. And the call is hardcoded to v[1]. Maybe you wanted v[i]?

A: After looking briefly.  I believe that where you are invoking readcont in runoptions()  you want readcont( v[i + 1] ) not readcont(v[1])


text:
Q: How to create a timer and background service who make call to a get location()(latitude and longitude) after every 5 min
Possible Duplicate:
How to fetch the Current Location in Every 1 min of Interval?

iam creted on working location class and another sendsms class
now I need to create background service with the help of timer to send sms current location after every 5 min

A: Why can't you do some research on your problem. Its very simple to get solution for such an easy question.
And don't ask same question multiple times
How to get location after every 5 minutes?.
Anyway still if you are unable to find it out, I could help my level best
Just you have following ways to do this,

*

*Through Background running Service.

*

*Create a Service that registers Location Listener.

*Create an alarm , when Service get called and set your alarm time frequency.

*Create a Broadcast Receiver for receive your alarm intent.

*After fetching location unregister your Location Listener.

*When you feel , no need to fetch location then stop the Service.

Sample codes  will be very lengthy, So You can get easily examples for following in web,

*

*Creating a Service

*Create an alramIntent and register for BroadCast Receiver

*Create a BroadCast Receiver and register it with an alarm Action.

*Implementing Location Listener.

*Through Timer with Runnable Thread,

*Create a Timer.

*Schedule the Timer with TimerTask run method. You can schedule initial start time duration and periodic interval call time delay too.

*Invoke Runnable interface when scheduled time occurs.

*Make sure the Runnable Interface runs on UI Thread by this.runOnUIThread(your_runnable_interface)

*In Runnable run() method, register your LocationListener for updates

*And do unregister in onLocationChanged() after processed your new location.

*When you feel , no need to receive location then cancel the Timer.

Here is an example for Timer using,
//Declared Globally in class
Timer timer;
//Timer follows here

timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
callRunnableMethod();
}
},Set your initial start time, Set your time delay for interval);

//callRunnableMethod() goes here

private void callRunnableMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.

context or this .runOnUiThread(Location_Runnable);
}

//Location_Runnable goes here

private Runnable Location_Runnable = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
//Do something to the UI thread here

Just start calling or request for updates with your location listener here.
}
};

//Once you decided to stop the periodic location fetching then do cancel your timer,

timer.cancel();

A: Use the LocationListener and request position updates as detailed here to get location updates. I think you need a context to do that but I hope this tutorial on location updates will help.
http://www.vogella.com/articles/AndroidLocationAPI/article.html


text:
Q: EclipseCDT/VNC/Ubuntu 8.04 eclipse not starting I'm not sure if I set this up properly.  I want to start Eclipse CDT on my Ubuntu 8.04 install using X11 through VNC.
When I try to run eclipse through vnc viewer command line using ./eclipse it hangs for a few seconds then fails.  No error message is output on the command line.
Is there a startup error log or some place I can look to find out what's happening? Or am I doing this wrong?
Ok I've verified that the problem is eclipse.
Is there some kind of version clash here?
desktop: ubuntu desktop 8.04 lts
kernel: 2.6.24-22-generic
CDT 7.0.2 for Eclipse Helios
jre1.6.0_24

When I do ./eclipse it just hangs for a few seconds and I get no error at all. I also don't know if there is a log file that would store startup errors. Is anyone familiar with this kind of problem?
My eclipse.ini is the default file with the -vm argument added,
-startup
plugins/org.eclipse.equinox.launcher_1.1.1.R36x_v20101122_1400.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_1.1.2.R36x_v20101019_1345
-product
org.eclipse.epp.package.cpp.product
--launcher.defaultAction
openFile
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vm
/home/shwick/ghostDev/java/jre1.6.0_24/bin/java
-vmargs
-Dosgi.requiredJavaVersion=1.5
-XX:MaxPermSize=256m
-Xms40m
-Xmx384m

I booted into my ubuntu 10 partition on my windows machine, did the exact same thing installing eclipse 3.6 helios with jre 1.6 and eclipse ran fine.
Right now I need to know how to get a description of the error that is occurring even though it is not output to the command line or ubuntu's system log /var/log/messages.
./eclipse just hangs and then returns to the command line

A: I know it's an old post, but I had the same sort of problem, and have found the error log in Eclipse/configuration/*.log files :
!MESSAGE Application error
!STACK 1
java.lang.UnsatisfiedLinkError: Cannot load 64-bit SWT libraries on 32-bit JVM
    at org.eclipse.swt.internal.Library.loadLibrary(Library.java:260)
    at org.eclipse.swt.internal.Library.loadLibrary(Library.java:240)
    at org.eclipse.swt.internal.C.<clinit>(C.java:21)

In my case I had not installed the x64 version of the JDK on the box.


text:
Q: R Namespace conflcit between plotly and ggplot2 (last_plot) I am developing a new r package that has a lot of visualisation in it. The problem occurs when I'm running CMD check. There's a conflict between plotly and ggplot2 for the function last_plot.
Warning: replacing previous import 'ggplot2::last_plot' by 'plotly::last_plot' when loading 'Package'
Which is normal since I'm using with roxygen:
#' @import ggplot2
#' @import plotly

Now I know that I could use importFrom or :: but it would be extremely tedious to list all the ggplot2 and plotly function I used just for one function conflict.
So I would like to know if there is any way to import all function but one (in this case last_plot). Is it possible or shall I stick to the good practice with importFrom and ::?


text:
Q: Display External Google Sheet in a sidebar I am trying to make an app script add-on that creates a sidebar to display the content of an external google sheet that corresponds to the selected cell of the active sheet.
I have tried to use
var html = HtmlService.createHtmlOutput('Page')
SpreadsheetApp.getUi()
.showSidebar(html);

this displayed a sidebar and the actual code of the Html file but didn't have the desired effect.


text:
Q: Laravel how to do a subquery/custom relationship query for hasMany I have this problem where I am grouping by account_name and ad_name, but there are records that have the same account_name and ad_name while having different ad_ids(which I use for my relationship connection) - so I end up not connecting all my records.
 ...

        $selectList = [
            DB::raw("any_value(ad_id) as ad_id"),
            DB::raw("ad_name"),
            ...
        ];

        $query = Facebook::query()
            ->with(['cake:subid_1,price'])
            ->select($selectList)
            ->groupBy('ad_name', 'account_name');

      ...

This is how my relationship looks like:
    public function cake()
    {
        return $this->hasMany(Cake::class, 'subid_1', 'ad_id');
    }

and this is the underlying query it produces:

But what I think would actually solve my problem, would be something a query like this:
SELECT `price`,
       `subid_1`
FROM `cake_performance_data`
WHERE `cake_performance_data`.`subid_1` IN
    (SELECT ad_id
     FROM cake_performance_data
     WHERE ad_name IN ($arrayOfAdNames))

Can I somehow make this query using eloquent or actually any other solutions to achieve the same end goal would be good.

A: I assume you have $adNames in the context, right now your code does not include it.
You can filter eager loading with() using and key value syntax. Secondly you can use a sub query in WhereIn() passing a closure.
->with(['cake' => function ($query) use ($adNames) {
    $query->whereIn('subid_1', function ($query) use ($adNames) {
        $query->select(['ad_id'])
            ->from((new Cake)->getTable())
            ->whereIn('ad_name ', $adNames);
    });
}]);