Where is this second Playstation Vita?

Question: So i was on the Account Management web page looking at the Devices section and it appears i have 2 Playstation Vita's registered however i only own 1.

I do have a Playstation TV which the OS looks like a Vita and i have 2 Vita Memory Cards. is there any documentation that indicates if one of these get misidentified as a second Playstation Vita on the web page?
If not there is a way for me to id this 2nd Vita without having to deactivate both from the website? i want to avoid deactivating the system i'm currently playing in case if there is any sort of time delay before i can reactivate (as i have some downloaded games and DLC on both memory cards)
Comment: As far as I understand the TV literally is a Vita. I'll look for some confirmation on this and post an answer if I find it
Comment: There's no activation delay.
Comment: And your second Vita IS the TV. If you deactivate it, you deactivate the PSTV
Answer: PSTV (PS Vita TV, in Asia) shares the same exact OS with PlayStation Vita.
The only difference between the consoles is that Vita TV has a white list for "TV allowed Vita games". In fact, many Vita games have been "enhanced" to work with PSTV.
There was a hack for VTV to play not allowed games for PS Vita, but the flaw allowing it has been patched through software update.
So, the answer to your question is:
The PS TV (or Vita TV) is basically a screen-less Vita. It is detected by the server as a PlayStation Vita, and that's why you see two Vitas.
You are allowed to have two devices between Vitas/PSTVs, so there is no point to deactivating one.
If for some reason you NEED to deactivate one of them, the best way to do it IS NOT from the Account web page, but from the console itself:
Access the HomeScreen open the "Settings" app and browse into PlayStation Network settings. The menu will be pretty much self-explanatory.
With this method, theoretically you could do it as frequently as you wish (be careful just not to do it too often, unless you wish Sony to suspect fraudulent activity and close your account).
Note: Remember that you can only deactivate ALL of your devices from the web once every six months, and that kind of deactivation is only meant for people losing or damaging their console. It doesn't involve console doing anything, until it connects to the internet, of course.
Answer: This is probably your PSTV, but you should verify.
In your PSTV, Go to Settings on the home screen. Then select Playstation Network and navigate to System Activation. You should be able to verify that this device is active. I would recommend doing this on your Vita as well.
If this accounts for both your PSVita and PSTV, you're good to go. If one of these devices is not activated your PSN account may have been compromised. I would highly recommend switching your password and using your remote deactivation (deactivates ALL systems on your account. You can easily reactivate them on the system itself, but the remote deactivate can be done once every 6 months).

Where is this second Playstation Vita?


Failed to create a partition on Windows for a Dual Boot

Question: Used disk management to shrink the volume of my primary partition C drive, but it only allows me to shrink it by a couple dozen megabytes for an unallocated partition. I  tried turning off bitlocker and device encryption but it still doesn't allow me to shrink my C drive enough.
Comment: Are you using Windows tools to shrink partition? What version of Windows? If problems, try temporarily disabling system restore, pagefile, (in advanced settings in computer properties) and hibernate option (in power management). Don't forget to turn them on back later.
Comment: I turned off System Restore and then was able to shrink the volume! Thanks for the competent advice, oldfred
Comment: I don't see the check mark to click to accept the answer.
Comment: You have to put an @ in front of the name to notify the person.  There is no answer (yet), so no way to accept it;^)  You can answer your own question, and accept it after  a bit.
Comment: @MaureenMoore The large gray checkmark to accept the answer is to the left and beside the answer. The checkmark changes color from gray to green when it is clicked.
Answer: Are you using Windows tools to shrink partition?
What version of Windows?
Be sure to have good backups before any system change. And create Windows repair/recovery flash drive, just in case. Best to have both Windows & Ubuntu repair tools current & available at all times.
If problems, try temporarily disabling system restore, pagefile, (in advanced settings in computer properties) and hibernate option (in power management). Don't forget to turn them on back later.


Is my syntax off or am I just doing this entirely wrong?

Question: var1= grep "$1" ./[FILE] | wc -l
if [ -s ./[FILE] ] && [ "$var1" -eq 1 ]

then
echo "it worked"

fi

I'm trying to get var1 to have an integer value by using the command:
 grep "$1" ./[FILE] | wc -l

I'm not sure if it is actually setting the value to the one that I assume the command is outputting because in my echo "$var1" it is echoing the value I expect. However, in my if statement:
if [ -s ./[FILE] ] && [ "$var1" -eq 1]

I continually get an illegal number error.
Comment: You can't use HTML tags like `` in shell scripts.
Comment: Can you not just show your script ? Instead of giving snippets of lines?
Comment: It's actually not a very large script, as it only needs to search a file to make sure that it contains a string(userid) and then output another string(the person's name).
Answer: You're probably better off just doing
var1=$(grep -c "$1" ./[FILE])

-c, --count
         Only a count of selected lines is written to standard output.

Answer: With regards to this:
var1= grep "$1" ./[FILE] | wc -l
if [ -s ./[FILE] ] && [ "$var1" -eq 1 ]

In shell scripting you can't have spaces on either side of the = in an assignment. The way that first line reads, you are running grep after assigning an empty string to var1. I suspect your intention was to capture the output of wc and assign that value to var1, which would be, as pointed out in another answer:
var1=$(grep "$1" ./[FILE] | wc -l)

However, as also pointed out, you can skip the wc part by changing that to
var1=$(grep -c "$1" ./[FILE])

One additional observation - if your [FILE] is zero-sized, grep isn't going to find anything, anyways, so there's really no need for that whole if ... && ... construct. Instead, those two lines could simply be:
if (( $(grep -c "$1" ./[FILE]) == 1 ))
then
  echo "it worked"
....

If the echo bit is one single command, that can even be shortened to this:
(( $(grep -c "$1" ./[FILE]) == 1 )) && echo "it worked"

Comment: The point of this exercise is to understand how if statements work in shell scripting, but yeah that's also a possibility. Thanks I didn't know about the space thing beforehand.


Using argparse.subparser with boolean values

Question: I've read through the Python argparse documentation several times and must be missing something huge.  I'm trying to add a makefile like syntax onto my cli tool, but despite the --help flag showing me the expected behavior the execution of it errors out:

test.py

import argparse
import os

def main():
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()

    make_subparser = subparsers.add_parser("make")
    make_subparser.add_argument("update", action="store_false", help="Runs all make targets")
    make_subparser.add_argument("clean", action="store_false", help="Cleans up everything done previously")

    args = parser.parse_args()

    if args.update:
        os.system("touch test.txt")

    elif args.clean:
        os.system("rm test.txt")

    else:
        print("Bad args, see: python test.py make --help.")

if __name__ == "__main__":
    main()

Then in my terminal:
$> python test.py make --help
usage: test.py make [-h]

positional arguments:
  update      Runs all make targets

$> python test.py make update
usage: test.py [-h] {make} ...
test.py: error: unrecognized arguments: update
$> # this should make a file
$>
$> python test.py make clean
usage: test.py [-h] {make} ...
test.py: error: unrecognized arguments: clean
$> # this should delete the file

This works fine if I swap out the action="store_false" for action="store_true", but there's a dozen make commands so I only want to run the one that the user adds in the cli, if they try to enter any more it should exit.
Comment: I'm not familiar with `make` but I am with `argparse`. Could you expand the example with some more possible arguments to make it clear what you want to achieve? ATM I think you want an argument with `options`
Comment: The source of the error is escaping me, but note that having an argument *named* `update` doesn't mean you are restricted to *providing* the value `update` on the command line.
Comment: Sure, the functionality can be anything, but in general if I type `python test.py make X` I want to run some python code under `if args.x == True`.
Comment: `store_true` and `store_false` only make sense with `flagged` (`optionals`) arguments.  With `store_false`, ` --clean` flag would set `args.clean` to `False`, otherwise it would `True`.
Answer: In the POSIX (and POSIX adjacent) world, boolean arguments are handled as flags which are passed via the command line as --argument. What you want isn't boolean arguments (and that isn't how Make treats them either), it's simply a variable number of positional arguments, i.e. having arity *:
make_subparser.add_argument('targets', nargs='*')

This would be closest to how Make operates. However, from your command line it looks more like what you actually want is nested subcommands.
Comment: You're absolutely correct I was trying to do this with subcommands.  This cli already has some extra functionality using subparsers so I wanted to tack on a `make` simulator, and when I say boolean I meant "if the argument is present then I want to execute this code, else do nothing"
Answer: Instead of separate boolean flags, use single argument target which allows a restricted set of values.
make_subparser.add_argument("target", choices=['update', 'clean'], help="Runs all make targets")

if args.target == "update":
    ...
elif args.target == "clean":
    ...

No else is needed, because any attempt to pass something other than update or clean will cause an error in parse_args, before args.target ever gets set.
Comment: This definately solves the problem, however now I lose the nice help descriptions, there's going to be about a dozen choices  each with a DAG behind it.


Replacing an LED Driver

Question: I've got a failed LED driver that I need to replace.  It's a 25W constant-current model (260mA, 28-87V), and finding an exact replacement for this part appears to be nearly impossible.
What are the key considerations to keep in mind when choosing a suitable alternative driver?
For instance, is it more important to match on wattage, or current, or both (or neither), and how does changing each one affect the performance of the light (if at all)?  If the only local part I can source is a 20W (650mA, 20-36V) driver, would that be workable or completely useless?  Or would it be better to import a part from overseas that does 25W (300mA, 54-80V)?  Or must I stay exactly on spec with the original driver?
And do I need to stick with a single ~25W driver, or could a pair of 12W drivers be expected to do the trick?  Because for whatever reason, the LED panel itself has two inputs (and the driver that came with it has two outputs; see the photos below if this sounds confusing) while most LED drivers you can buy only have a single output.
For reference, the driver looks like this:

Note that there are two output connectors, with the blue wire on one connector going to the driver's 'LED -' output and the brown wire on the other connector going to the driver's 'LED +' output.  The alternate wire on each connector is just spliced directly to the other connector.  I'm unsure if this has implications for whether or not it would be possible to use two 12W drivers in parallel
The LED assembly itself looks like this:

What's the best approach for getting this thing illuminating again?
Comment: fwiw google bft-8-25w brings up an exact replacement, first hit. You need to buy a lot of 10 but they are only 2.50ea.
Answer:
It's a 25W continuous-current model (260mW, 28-87V)

No it isn't. You need to be careful about the details.

constant-current not continuous-current
260 mA, not mW.

is it more important to match on wattage, or current, or both (or neither)

All are important but the most important is that the current be close to 260 mA. LEDs need a constant-current. You could choose a lower current and the LEDs would produce less light (fewer lumens, less brightness). If you chose a higher current driver the LEDs would have a shorter life, in the worst case, seconds.
It would be prudent to choose a driver capable of at least 87V and at least 25W. It doesn't hurt to be higher (so long as it is a constant-current driver set to the correct current). It shouldn't be less (though the old driver should have been specified to run comfortably well-inside its limits).
If you have a similar light fitting that is still working, it might be useful to measure the output voltage while the light is on. Alternatively measure the forward voltage across one LED and multiply it by the number of LEDs in series in each ring (look at tracks on reverse, they might be several serial chains in parallel).
If there is one chain of 24 LEDS, each 3V, you need a driver capable of >= 72VDC.
If there are two parallel chains of 12 LEDs, each 2V, you need a driver capable of >= 24VDC.

I'm unsure if this has implications for whether or not it would be possible to use two 12W drivers in parallel

You are right, the two rings of LEDs are independent. You could use two 250mA 12W drivers.

What's the best approach for getting this thing illuminating again?

Google for "25W 250mA LED driver"
The usual electronics distributors have parametric search
Answer: You've never worked with LEDs before, eh?   Think about what you assume about every other electronic device, ever:

it has a specified amount of voltage it needs
the device internally controls itself as to how much current it draws
with multiple devices, you connect them in parallel
your power supply must deliver correct voltage, with capacity for at least that much current.

All that goes out the window with LEDs.  If you give them constant voltage, they explode, because they can't control themselves.  Current must be externally regulated, as in a ballast, except they call it a driver. The correct current may occur at a range of voltages, but not too wide a range, +/- 15% or so.
Since constant-current is the critical factor, and LEDs are basically indestructible, it is most design-efficient to wire them in series.
Think it through.
This is really different thinking.
The series wiring
Ok it needs constant current, self regulates for voltage, series connection and the power supply must deliver potentially a range of voltages to hit that current.
Ok now the series wiring makes sense: items in series have exactly the same current, so you can control all their currents precisely from one driver.
Now the driver's labeling totally makes sense, the wild range of voltage but the precisely narrow current range.  260ma is the correct current, the end.
Here's what bugs me,  with 30LEDs in the outer ring and 24 in the inner, and they're in series, that's 54... Unless they are red, voltage per LED is typically 3 volts, so I'd expect 162V give or take.  That's too high for the driver.  It's possible inside each ring they are wired in series-parallel in sets of 2 or 3, see if you can easily divine this from the PCB traces, don't wreck it.
The driver
That driver is a bucking converter, taking a high voltage and lowering it.  From the "printed on a 90's plotter font" markings, and lack of UL/CSA/TUV stamp (CE is not that), this is generic "fell off a truck in Shanghai" Cheese junk, which suggests maybe the lamp is too.  I wouldn't put it past our Pacific Rim buddies to use an out-of-spec part. Overvoltage is less damaging than overcurrent, so you can usually get away with it.
So while 260ma is a sure thing, there's a real question as to the practical voltage of this thing, which may impact selection of a driver.  I would pursue that further, by putting the smaller ring on a CC/CV bench power supply, setting it for 10ma, turning up the voltage until it starts to light, and turn it off before it overheats without its heat sink.  It won't light at all until it's within 20-30% or so of its rated voltage.  Running a 260ma LED chip on 10ma is fine, in fact it's the best way to dim them.  Whatever voltage you hit is in the ballpark, e.g. If it's 60V (2.5V per LED) that would indicate they are all in series and all 3V devices as expected.
If the inner ring is all in series, the outer ring will be too.
Selecting that driver
Now you have a definite current (260ma) and a rough range of voltage (162V or 81V or whatever you found).  Go shopping and find your driver.  You might find that exact driver on AliExpress (Cheese junk supermall) but I would aim for a better vendor, especially if the voltage was out of spec.  I would try electronics shops like Muser or Digi-Key.  Read data sheets carefully.

Replacing an LED Driver


Is it possible to call a function of a subclass from parent class?

Question: class A(object):
    def xx():
        # do something

    def yy():
        # do something

class B(A):
    def func():
        # do something

# How to make it possible?
a = A()
a.func()

Now I want to add func() to class A, however I CANNOT change class A, so I created a subclass of A and add func() to the subclass. How can I call func() from A instance?
I tried to initiate with class B, however, there are many instances, so I need to change many many locations. Is there a better way to do it? Ideally with class A.
# This works, however, I need to change A() to B() everywhere.
# Are there easy ways to do it without changing A() to B()?
a = B()
a.func()

Comment: Why CANNOT change A?
Comment: There are many ways to change a class in Python. If you explain what you are trying to achieve and why you think you cannot change the class, you may get other answers.
Answer: You could use setattr() (doc):
class A:
    def xx(self):
        print('xx')

    def yy(self):
        print('yy')

class B(A):
    def func(self):
        print('func')

setattr(A, 'func', B.func) # or setattr(A, B.func.__name__, B.func)

a = A()
a.func()

Prints:
func

Comment: Or simply `A.func = B.func`?
Answer: You can't do such thing because class B inherits from Class A not the reverse, so you can use B.xx() but you can't use A.func().
For more information about inheritance in Python, look here
As Andrej said, you can use setattr() method to define new attribute for class A.
Look here for more information about setattr() method.


TOKEN endpoint returns invalid_client without client secret

Question: I am having difficulty with the authorization code flow in Amazon Cognito. The workflow that I am trying to build is the following:

A user authenticates with the built-in Cognito UI.
Cognito redirects back with the authorization code.
I send the code to server where it's exchanged for tokens using /oauth2/token endpoint.

I have created a client without client secret. I authenticate using the Cognito UI, get back the code, then send the following with Postman:
URL: https://MY-DOMAIN/oauth2/token
Method: POST
Headers:
Content-Type: application/x-www-form-urlencoded
Body:
  grant_type=authorization_code&
  client_id=<my-client-id>&
  code=&
  redirect_uri=<my-redirect-url>

I do not use Authorization since there's no client secret.
In return I receive:
Code: 400
Body: { "error": "invalid_client" }

The app client is allowed authorization code grant in the AWS Cognito console.
Comment: I also faced that kind of issue. The problem was creating client with client_secret. You should create your client by "Generate client secret" option unchecked. Because Authorization code flow works client side that means your client must be created with public typed. That works perfectly.
Comment: @Магнайбаяр Ганзориг annswer is correct and should be an accepted answer
Comment: Any luck on this? I'm having the same problem
Comment: I repeated the same steps after some while and they worked. I do not know/remember exactly why, probably missed something initially. But if you attach the screenshot from your postman/another utility that you are using, I can check what might be wrong.
Comment: I finally gave up and created a new Cognito Client App with a secret, and things started working for me as well.
Answer: Does not seem to be mentioned anywhere in the docs though,
If you have created the client app with client_secret you should add the client_secret to the params for it to work.
curl -X POST \
'https://<Cognito User Pool Domain>/oauth2/token?
grant_type=authorization_code&
code=8a24d2df-07b9-41e1-bb5c-c269e87838df&
redirect_uri=http://localhost&
client_secret=xcxxxs2r234XXXXXX&
client_id=55pb79dl8gm0i1ho9hdrXXXXXX' \
-H 'Accept-Encoding: gzip, deflate' \
-H 'Content-Type: application/x-www-form-urlencoded'

Or you need to create the app with "generate client_secret" = false.
Also By default, user pools generates a client secret for your app.
Comment: This worked for me! I had an app with client secret but i was not passing it so it was giving me error! Thanks a lot
Answer: The problem is with Authorization header.
When using client without client secret Authorization header is not required.
Example:
curl -X POST \
'https://<Cognito User Pool Domain>/oauth2/token?
grant_type=authorization_code&
code=8a24d2df-07b9-41e1-bb5c-c269e87838df&
redirect_uri=http://localhost&
client_id=55pb79dl8gm0i1ho9hdrXXXXXX&scope=openid+email' \
-H 'Accept-Encoding: gzip, deflate' \
-H 'Content-Type: application/x-www-form-urlencoded'

Comment: Thanks this information was missing in my postman configuration to retrieve the access token.
In postman there is an dropdown option "Client Authentication" with "Send as Basic Auth header" or "Send client credentials in body".
When it was added to the header I got "invalid_client" too.
But I don't have client credentials with my OAuth2 flow.
Request body `grant_type=authorization_code&code=<code>&redirect_uri=&code_verifier=&client_id=&client_secret=`
Comment: Yessss ! This is it. Thanks a lot
Comment: Can you expand a bit on this answer - perhaps some code?
Comment: Updated with example.
Comment: agree with @h-kippo. While what is posted as the answer is not wrong but this is not the right answer. his answer below is the right one.
Answer: I would comment on the other solutions, but not enough rep yet.
As some additional information to anyone who comes across this issue in the future:

Not only is the Authorization header not required... it's Not Allowed.

Saying "Not Required" led me to believe it was optional. In fact, if you pass that along the request, I found that the response would often be as described by OP:
Code: 400
Body: { "error": "invalid_client" }

Comment: Notice that AWS presented this with Postman: https://www.youtube.com/watch?v=WgvVxKf2CFc

I tried it without the Client Secret, and I had the same HTTP 400 mentioned in this Post. So, there are two possibilities:
1. Postman was not sending the Authorization header when they recorded that video
2. The service did not care about it back then, but it does now
Comment: This was my exact issue trying to make a login request through Postman as Postman defaults to using the authorization header. If you change the `Client Authentication` option from the default (`Send as Basic Auth Header`) to `Send client credentials in body` it works.
Answer: I was having a similar issue that was resolved by setting Client Authentication from the default "send as basic Auth header" to "Send client credentials in body".
Comment: That one worked!
Answer: I had a similar issue when working with Cognito on iOS (not amplify) but I figured it out that I needed to actually send nil (for swift).
I'm not sure if that will help your situation but here's what I have in Swift:
@objc func config(_ call: CAPPluginCall) {
    let appClientId = "myclientid";
    let scopes = Set<String>(["openid", "email"]);
    let signInRedirectUri = "com.myappurl://signin";
    let signOutRedirectUri = "com.myappurl://signout";
    let webDomain = "https://[myappdomain].auth.us-east-2.amazoncognito.com";

    // NOTICE my nil here for appClientSecret, if I used "" it would throw the error you are seeing
    let config = AWSCognitoAuthConfiguration(appClientId: appClientId, appClientSecret: nil, scopes: scopes, signInRedirectUri: signInRedirectUri, signOutRedirectUri: signOutRedirectUri, webDomain: webDomain);

    AWSCognitoAuth.registerCognitoAuth(with: config, forKey: "AWSCognito")
    call.resolve()
}

It may not answer the situation you have exactly but this is what worked for me to remove the horrible error invalid_client.
Comment: I was using Python and Flask-AWSCognito, and I had to set the env var `AWS_COGNITO_USER_POOL_CLIENT_SECRET` to `None`:
```app.config['AWS_COGNITO_USER_POOL_CLIENT_SECRET'] = None```
Answer: In the comments of the question you mention:

repeated the same steps after some while and they worked.

I stumbled upon the same or similar problem. The solution for me was not to use a previously signed-in session. I had to sign out or open an incognito/private browser session and sign in again to resolve the issue.
All the parameters in the question are valid according to the documentation.
Answer: I had same situation:
Code: 400
Body: { "error": "invalid_client" }
Like other friends mentioned, App client created with client_secret need client_secret in API call then it works


Modify file contents based on Windows' version

Question: I want to add few lines in a text file based on os name. A pseudocode example:
os==windows 7 then open file c:\1.txt else open file c:\2.txt

I want to add some  static text to that  text file and save the text file.
How do I do that in batch script? My pseudocode attempt:
FOR /F "delims=" %i IN ('ver') DO set osver=%i
echo %osver%

if %osver% == "Microsoft Windows [Version 6.1.7601]"

set filepath == C:\1.txt and open 1.txt file and add text" abc "
else
set filepath == C:\2.txt and open 2.txt file and add text " abc"

Comment: Well I can tell you made no effort at learning the syntax for any of those commands. You can read the help file for any command by typing the command name followed by a forward slash and question mark. set /?
Answer: Do not over complicate it by creating variables, else you might need delayedexpansion
@echo off
for /f "tokens=2 delims=[]" %%i in ('ver ^| more +1') do (
  if "%%i"=="Version 10.0.17134.228" echo abc >> "C:\1.txt"
  if "%%i"=="Version 6.1.7601" echo abc >> "C:\2.txt"
)

We split away version X.X.X.X only as we want to match as little as possible. Then simply do if and echo to the relevant file.
For more on the above commands, see from cmdline for /? and if /?
You need to copy the above code into a text file and save it as a file with a .cmd or .bat extension. Please do not call it ver.bat or ver.cmd as ver is a system command. Call it something like my_version_script.cmd instead.
Comment: it works find but my requirement is to add the text to the file not for entire text replacement
Comment: Add what text to the file? You did not specify, but I gave exactly that. Do you want to excho the actual version to the file?
Comment: i have static text which contains two lines , so i have to add these two lines to 1.txt or 2 txt based on os
Comment: So that is what I did... replace lines `echo some text` and `echo some other text` with `echo your static text` your static text
Comment: I edited it with `abc` to show where you should place your static text.
Comment: your code working fine ,but my 1.txt is already contails some text so i have to add the static lines to that file. but the script you mentions is replacing all the contents of the file with the static text.
Comment: @naveen then you did not look at my edit, I added double redirect `>>` Please copy the code and try again.


Responsive button images

Question: this is my first post here. I am beginning my journey with css and html. I'm struggling with putting two responsive images next two each other that would act as buttons. What I am trying to get at is that all content is displayed on single page (without scrolling) and that the no matter the size of the screen it is always filled. Then with portrait mode on mobile screens it would display after each other.
This is how far I got already: http://test.fulfeal.co.uk/shop-intro/
I can't figure out whether it is to do with image size (the actual image is going to be a picture) or maybe with corresponding div sizes.
Thank you in advance for any help!
Answer: In order for the images to take up the full page height, first make sure that you have the following:
html, body {
  height: 100%;
}

This will make sure your content can actually take up the full height of the page. Then, your images should also have their height set to 100%.
For the images to show up on top of each other for mobile, you'll need to use css media queries and then set the images to display: block; width: 100%.

Responsive button images


send Session Description from node server to client

Question: Do I need to use a websocket to send JSON data to my client? (it's a tiny session description)
Currently my client-side code sends a session description via XHR to my Node.js server. After receipt, my node server needs to send this down to the other client in the 'room'.
I can achieve this using socket.io, but is it possible to do anything a bit faster/ more secure, like XHR for example?
Comment: I'm not sure I correctly understood your question...well for my all WebRTC experiments...I'm using Pubnub (websocket, socket.io etc) .... https://webrtc-experiment.appspot.com/ ... I found Pubnub is faster and seems good and easy....I do all things in HTML file...no need to worry about server (like node.js !!)....I know node.js is easy...I love it too...but for WebRTC experiments...we should focus on WebRTC JavaScript APIs...to build something better....
Comment: My project aims to have minimal dependancies - for this reason I am not hosting it on appspot, so I don't benefit from the channel API, nor do I wish to rely on pubnub or pusher...

It's good to see your experiments, though. :)

My question is simple: If I have sent a session description (via XHR) to my server from client a, which is the optimal method for sending it to client b?
Comment: For your information, I'm not using Google App Engine Channel APIs...As I said, my experiments are HTML-only!...which can be hosted on any server (even on codepen.io!!)....XHR is better for signalling but there are many chances for failure...also you've to make so many requests!!!....it is true that my experiments are dependent upon PubNub...but this is the only dependency....when you use JQuery...you are dependent upon JQuery!...I use Pubnub for leaving server outside and playing with RTCWeb JS APIs...personally I prefer socket.io over XHR for signalling
Comment: Happy new year, Muaz!

I assumed you were using channel API due to your use of appspot... I think pubnub is a bit like a wrapper for sockets?? I just don't like to be so dependant on a service like pusher or pubnub - I like to understand, and control every aspect of my system.

I think you only need to exchange session descriptions to allow p2p connection... According to this [http://www.youtube.com/watch?feature=player_detailpage&v=E8C8ouiXHHk#t=1008s] I will only need each client to send 1 XHR and receive 1 XHR... That seems doable?
Comment: I want my system to be as good or better than the channel API, if at all possible... Being written using Node, it already has an advantage (channel api uses python). I will release my code as an open source system. :)
Comment: I've never tried HTML5 Server Sent Events....these may be helpful to you!
Comment: wow, they do look pretty interesting. Thanks!
Answer: If you just want to receive the offer from the other side and nothing else, I would suggest you to try HTML5 Server Sent Events.
But this may bring problems due to different browsers support, so I would use a simple long pooling request. Since you only want to get the SDP offer, the implementation is pretty simple.
Answer: No, you don't need to use the WebSocket API to send JSON data from client to client via a server, but unless you use Google's proprietary App Engine Channel APIs, then the WebSocket API is probably your best choice.
Also, please keep in mind that you're not only sending session descriptions, but also candidate info (multiple times) as well as other arbitrary data that you might need to start/close sessions, etc.
As far as I know, the WebSocket API is the fastest solution (faster than XHR) for signalling because all the overhead involved with multiple HTTP requests is non-existent after the initial handshake.
If you want to code things yourself, I'd start reading the latest WebSocket draft and learning how to code the WebSocket server-side script yourself or else you will pretty much have to rely on a WebSocket library like Socket.IO or a proprietary solution like Google's App Engine Channel APIs.
Answer: How about using the 303 HTTP status code?
The first client send the session description to resource X, the server acknowledges the receipt and responds with a 303 status code that points to a newly created resource Y that accumulates other clients session descriptions.
The first client polls resource X until it changes.
The second client send its session description to resource A, the server acknowledges the receipt and updates resource Y. The first client notices the update with the next poll and will now have the second client's session information.


Changing h1 content by using if statement in Javascript

Question: I want to change the content of h1 by using if statement in Javascript, is there a way to make Javascript variable read the content of h1?

bebe

Comment: So you're correctly _setting_ the contained text here: `document.getElementById('tae').innerHTML = 'my moon'`. But for whatever reason you're _getting_ the contained text _without_ the `.innerHTML`?! By the way, the _recommended_ approach is to use the [`textContent`](//developer.mozilla.org/en/docs/Web/API/Node/textContent) property in both cases.
Answer: You need to use innerText to do it
var baby = document.getElementById('tae').innerText;

bebe

Comment: [`textContent`](//developer.mozilla.org/en/docs/Web/API/Node/textContent) makes more sense than [`innerText`](//developer.mozilla.org/en/docs/Web/API/HTMLElement/innerText); it's more intuitive and doesn't do any CSS processing.
Comment: textContent is way faster then innerText. However, a Regex would have been simpler in this case.


Pulling wire through Sealtight/LiquidTight?

Question: I'm going to make my final run from my 50 amp hot tub panel disconnect to the hot tube using about 20' of 3/4" Sealtight/LiquidTight.
Is there a best way to pull 4 #6 wires through this type of conduit? I assume probably a fish tape would be my best option.
Comment: Using anything you have on hand, like a vacuum cleaner and a string (or a fish tape). I'm not sure what problem you're facing.
Answer: I use fish tapes for long flex pulls.
Tapes make the job easier.
As it is a snug fill it probably a bit tough for a novice to do a push but if you tape the ends together tightly and do not tangle the conductors push a foot and as pushing twist the flex.
with each push have the flex out straight and if it starts to bind a snapping action like a bull whip (but not as extreme).
it will usually go you may need to straighten the piece out and continue until the end comes out
With the end put that end on and finish pulling the wires through then connect the ends I do this all the time without a tape but use a tape if it won't go.
I don't waste time blowing or sucking "a mouse" through the flex. Note that a mouse is the trade name of pulling a string through pipe and they don't work well in flex because of the ribs.
Answer: Hollow braided rope, by preference - usually polypropylene, but just because that's the most common hollow braided rope around.
Vacuum it in, or vacuum a string in and pull the rope in with the string.
Expand the braid to go over your wires, and stagger the ends of the wires by a few inches so the attachment tapers, as opposed to the "lump" you get when all 4 wires are lined up exactly. Tape the rope end to the wire bundle throughly with good electrical tape.
Alternatively, you can buy a pulling grip which is essentially a short section of metal braid with a loop to tie or splice your pulling rope to.
20 feet of liquidtight (at 37+% fill) will probably be a miserable pull. You'll likely want a quart of pulling lube (only use AFTER the taping on is complete)
A fish tape does nothing particularly useful for you, and is harder to grab than rope. You can use one, but I don't recommend it.
Having someone else push as you pull is helpful, (they can also apply more pulling lube as needed.)
Comment: Gotta agree completely with Ecnerwal. Suck a rope thru with a shop vac and tape up the wires like he said.  I've found it helpful to tape something like a thin disposable shopping bag to give the vacuum more surface area to grab onto.   I've used fish tapes before and really don't like them....much prefer a rope. A pulling grip also works well...it's like a Chinese finger trap!
Comment: As a pro I would disagree if you are having trouble pulling with a tape and that nice big plastic housing a string or rope will shred your hands and flex is difficult even with the correct tool to suck a line through compared to a tape , but I would probably push it any way.


Trouble with multiple definitions of node

Question: The model is syntactically correct, I loaded the data but when I compile, I get this error :  "multiple definitions of node z". I don't know how to solve it
<code> model{

    ...
    for(i in 1:r){
      for(j in 1:r){
        z[i,j] <- ((step(x[i,j]-0)*1) + (1-step(x[i,j]-0)*(-1)))/2
      }
    }

    # (zij +1)/2
    for (j in 1:r) {
        for (i in 1:r) {
            z[i, j] ~ dbern(p[j])
        }
    }
    ...

}
</code>
Some help would be appreciated.
Answer: You have defined multiple parts if z twice. BUGS does not allow you to overwrite z (or any other node) in the same model, i.e. you can only write one of z~ or z<- once.


Determine if the function $f$ is even, odd or neither given the graph of $f$

Question: The following picture is a graph of a function $f$. I am to determine whether the function is even, odd, or neither. I reasoned that $f$ is odd, because if the graph is rotated $\pi$ radians, the graph is reproduced perfectly. The graph is clearly not even, because it is not symmetrical with respect to the vertical axis. However, the solution states that $f$ is neither even or odd, and I do not understand why.
Answer: You're right that the graph has a symmetry - if you rotate about a certain point on the $y$-axis, you preserve the graph. Algebraically, it has the property:
$$f(x)=2c-f(-x)$$
where $c=f(0)$ is the intersection of the graph and the $y$-axis. The condition of oddness is more strict, however, it demands:
$$f(x)=-f(-x)$$
meaning the function must have this rotational symmetry about the origin, not about some arbitrary point. Note that oddness implies $f(0)=0$.
Comment: For parity, the definition of *evenness* is:
$$f(x)=f(-x)$$

By the way, looking at your plot, I think you have a cubic function, not a sinusoid. However, assuming that $f(x)=\sin(x)+y_0$, your statements still hold:

$$f(x)=\sin(x)+y_0$$
$$f(-x)=\sin(-x)+y_0=-\sin(x)+y_0$$
$$f(x) \neq f(-x) \rightarrow not ~ even$$
$$f(x) \neq -f(-x) \rightarrow not ~ odd$$
Comment: Why do you have $2c$ instead of just $c$ if $c$ represents the intersection of the graph with the $y$-axis?
Comment: @BenedictVoltaire I wrote it that way since if you want to "reflect" a value $x$ across a mirror at $c$, the resulting value is $2c-x$. More algebraically, note that at $f(0)$ this identity says $f(0)=2c-f(0)$ so rearranging gives $2f(0)=2c$.
Answer:
"I reasoned that $f$ is odd, because if the graph is rotated $\pi$ radians, the graph is reproduced perfectly."

It sounds like you were rotating around  the $y$-intercept.  To test for oddness, you always want to rotate around the origin.  A quick test for non-oddness is to look at the origin.  If the graph doesn't go through the origin, the function is not odd.  If the graph does go through the origin then the function may or may not be odd.  It is in this case that you'll need to check the rotation of $\pi$ radians.
Comment: Yep. So, the function $x\mapsto f(x) -f(0)$ is odd


How to parse the division of two very large numbers into a double?

Question: I have a geometric algorithm which takes as input a polygon. However, the files I am supposed to use as input files store the coordinates of the polygons in a rather peculiar way. Each file consists of one line, a counterclockwise sequence of the vertices. Each vertex is represented by its x and y coordinates each of which is written as the quotient of two integers int/int. However, these integers are incredibly large. I wrote a program that parses them from a string into long long using the function std::stoll. However, it appears that some of the numbers in the input file are larger than 2^64.
The output coordinates are usually quite small, in the range 0-1000. How do I go about parsing these numbers and then dividing them, obtaining doubles? Is there any standard library way of doing this, or should I use something like the boost library?
Comment: @1201ProgramAlarm You will always loose some precision if the result of the division is not exactly representable by relevant data types.
Comment: Boost has a multiprecision library, which can work with very large integers. Another option might be to insert a decimal point into that numbers and parse them as doubles. If you insert it at the same place (counting from right), the result of division will be the same (up to rounding).
Comment: @DanielLangr Trying to parse them as doubles will lose precision, creating errors in the converted number.
Comment: Maybe look into [GMP](https://gmplib.org/).
Comment: (a) Show examples. Show the largest numerator and the largest denominator you have. If you have any information about how large the numbers could be, aside from the data you already have, show that. (b) How accurate do you need the output coordinates to be? If they are just numbers 0 to 1000, and they are pixel coordinates, so they are integers, then `double` has more than enough precision that almost all quotients will map to the correct pixel. But if they are used for something else, how does accuracy affect the computation?
Answer: If you are after a ratio of two large numbers as string, you can shorten the strings:
"194725681173571753193674" divided by "635482929374729202" is the same as
"1947256811735717" divided by "6354829293" to at least 9 digits (I just removed the same amount of digits on both sides). Depending on the needed precision, this might be the simplest solution. Just remove digits before converting to long long.
Comment: Nice! Pretty clever.
Answer: You can parse the inputs directly into a long double I believe. However, that approach will introduce precision errors. If precision is important, then avoid this.
A general solution for precise results is to represent the large integer with an array of integers where one integer represents the lower order bytes, next integer represents the larger bytes etc. This is generally called arbitrary precision arithmetic.

Is there any standard library way of doing this

No, other than basic building blocks such as vector for storing the array.

or should I use something like the boost library?

That's often a good place to start. Boost happens to have a library for this.


Send data to controller on ui.select angular

Question: i'm trying to select a value from dropdown list and get the data from corresponded select id in angularJs
i have came up with angular-ui/ui-select directives
<ui-select ng-model="customer" theme="selectize">
     <ui-select-match placeholder="Customer List">{{$select.selected.Name}}</ui-select-match>
        <ui-select-choices repeat="customer in customers | filter: $select.search">

        </ui-select-choices>
</ui-select>

on my controller i have get customer method
$scope.setActiveCustomer = function(customer) {
  customersService.getCustomers(customer).then(function(response) {
    $scope.selectedCustomer = response;
  });
};

my problem is

once i select the customer which event should i use for fire
setActiveCustomer (like onchange or something). when i use ng-click
event fired many time because ng-click using to control activate.

other thing is how can i set initial value for ui-select ?

thanks
Answer: According to the ui-select FAQ, your ng-model expression should have a . in it, for example:
<ui-select ng-model="model.customer" theme="selectize">

To set the initial value, you could just set the property specified in the ng-model, so in your controller:
$scope.model = {
  customer: $scope.customers[0] // set the initial selected option
};

For the onchange event, you could use $scope.$watch() like this:
$scope.$watch('model.customer', function (customer) {
  $scope.setActiveCustomer(customer);
});

Hope this helps.
Comment: Hi runTarmit solved my first problem amazingly but still i'm stucked with second one
Comment: Do you mean setting an initial value?
Comment: yep. initial value not assign as expected!!
Comment: Could you please show how use set the `$scope.model.customer`? Is the `$scope.customers` available at that time?
Comment: yes it's available but when it bind to select ui it's only shows [object Object]
i have check those objects using firebug it shows initial binded object was  `[Object { Id=1, Name="FirstOne"}]` but it should be something like  `Object { Id=1511, Name="FirstOne", $$hashKey="00H"}`


Hatcher A.1 , difficulty in understanding a certain step

Question: In hatcher (algebraic topology) proposition A.1 page 520 in the appendix section, I don't see why we have $\phi_{\alpha}^{-1}(S)$ necessarily closed in $\partial D_{\alpha}^n$, once we have this I can see why $$\Phi_{\alpha}^{-1}(S)$$ contains at most one more point and is thus closed, but I struggle to understand the first part.
Here is the proposition for reference:
Comment: @porridgemathematics Then you should write an answer to your own question.
Comment: Is $\phi_\alpha$ the edge-gluing map and $\Phi_\alpha$ the cell map of cell $\alpha$?
Comment: Sorry, so hatcher has defined $\Phi_{\alpha}$ as the composition $D_{\alpha}^n \hookrightarrow X^{n-1} \coprod \coprod_{\alpha} D_{\alpha}^n \rightarrow X^n \hookrightarrow X$ where the first arrow is the canonical inclusion, the second arrow is the quotient map and the third arrow the canonical inclusion. Therefore I think $\phi_{\alpha}$ is the same map restricted to the boundary (although this was only  defined in hatcher as a map $\partial{D_{\alpha}^n} \rightarrow X^{n-1}$ when constructing the $n$-skeleton)
Comment: Oh, I think I resolved my confusion, the map hatcher is talking about is just the edge gluing map composed with the inclusion $X^{n-1} \hookrightarrow X$, and its preimage of $S$ is closed because $S \cap X^{n-1}$ is closed and it is continuous.
Comment: Yes! I will do so soon :)
Answer: The map given by the attaching map $\partial D_{\alpha}^n \rightarrow X^{n-1}$ composed with the inclusion $X^{n-1} \hookrightarrow X$ is equal to the map $\Phi_{\alpha}$ restricted to $\partial D_{\alpha}^n$. Therefore this maps preimage on the set $S$ is necessarily closed, as we assumed that $S \cap X^{n-1}$ is closed inductively.


Is it possible to play FIFA 2015, 4v4 on 2 Consoles?

Question: I've the following situation: My friends and I, we're 8 in total, want to play Fifa 15 4v4. I know that the Playstation 4 just supports 4 controllers and thats why we think about a 2 console + 2 TV's setup, so 4 players per console.
So my question is: Is it possible or is there a game mode available were we could play such a setup?
Update:
After I got the first answer I've to add that I know that the only way to play on 2 consoles would be through the psn online features. So we did not plan to play on Lan. We just want to sit in the same room with 2 consoles and play against each other over psn.
Comment: Other than the PS4 supporting 4 controllers, does FIFA 15 support 4 players on a single console as well? (Not sure myself) Just because the console supports it doesn't mean the game does also (it can support *up to* that amount of players, if the game devs choose to implement it)
Comment: yes fifa 15 supports 4 players local and up to 22 online see http://blog.hmv.ie/wp-content/uploads/2014/09/FIFA-PS4.jpg
Answer: FIFA, like 99% of console games, does not support LAN. So no, you can not do that. I don't know the game very well so I am assuming that you can't play online as a group of 4 otherwise you would have just done that.
Comment: The problem here is, that i would need exactly the same setup and atm i haven't 2 consoles and 8 ppl at my home. However it is possible to play 2v2 on 2 consoles the mode is called co-op seasons but i dont know if it's possible to play 4v4 too thats why I ask. Btw nobody was talking about an issue.
Comment: I updated my question however nobody was talking about Lan.
Comment: If you weren't asking about LAN then how is this even an issue? I do not actually know how the online works in FIFA but since you play the game you should know... Can you play online as a group of 4? Either you should know or you should be able to just try it and find out. Can you invite another group to a game? Again you should either know or be able to just try and find out. If the question wasn't about LAN then I don't really understand why you bothered to ask it.
Comment: You don't need another console to attempt to go online with your console and a group of 4... If it doesn't work then clearly you can't do it.


Faucet Removal Problem

Question: I need to replace my kitchen faucet but have never seen one like this before. My sink is a 4 hole, but this seems to be all one assembly. I does have a sprayer on it also, which is the hose with the nut.
Comment: Hello, and welcome to Stack Exchange. A picture of the top portion of the faucet would be helpful.
Answer: Remove the hose attachment at point A as shown below.
Then remove the hex nuts from the threaded pipe at the point B.
These two steps will free up the U shaped washer and plastic spacer under it and allow the central faucet assembly to become loose.

You may also have to remove the fastener at the location shown at the lower portion of your photo. There may actually be two of these to remove, one in each of the faucet holes for faucet types that mount into separate holes. These two additional fasteners typically hold a decorative plate above in place the covers these holes in cases where a single handle style faucet is used.
Comment: Just want to thank you so much for this. I took a picture, put it through Google Lens, it brought me here, and your answer helped me get it out of there fairly easily. You make a great difference by taking the time to do a great answer like this. Thanks!

Faucet Removal Problem


Swift 3 NSDictionary to Dictionary conversion causes NSInvalidArgumentException

Question: I have just converted my project from Swift 2.2 to 3.0, and I'm getting a new exception thrown in my tests.  I have some Objective C code in one of my tests which reads in some JSON from a file:
+ (NSDictionary *)getJSONDictionaryFromFile:(NSString *)filename {
    /* some code which checks the parameter and gets a string of JSON from a file.
     * I've checked in the debugger, and jsonString is properly populated. */

    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
    return jsonDict;
}

I'm calling this from some Swift code:
let expectedResponseJSON = BZTestCase.getJSONDictionary(fromFile: responseFileName)

This works just fine most of the time, but I have one JSON file which causes the error:
failed: caught "NSInvalidArgumentException", "-[__NSSingleObjectArrayI enumerateKeysAndObjectsUsingBlock:]: unrecognized selector sent to instance 0x608000201fa0"

The strange thing about this is that the error is generated after the getJSONDictionaryFromFile method returns and before expectedResponseJSON in the Swift code is populated.  To me, this seems to say that it's the conversion from an NSDictionary to Dictionary which is the problem.  The offending JSON file is this one:
[
  {
    "status": "403",
    "title": "Authentication Failed",
    "userData": {},
    "ipRangeError": {
      "libraryName": "Name goes here",
     "libraryId": 657,
      "requestIp": "127.0.0.1"
    }
  }
]

If I remove the outermost enclosing [], this error goes away.  I can't be the only person using an array as the top level entity of a JSON file in Swift 3, am I doing something wrong?  What can I do to get around this error?
Comment: Of course you can use an array as the top-level JSON object. But then you must treat it as an array, not as a dictionary.
Answer: As is referenced in the comments, the problem is that getJSONDictionaryFromFile returns an NSDictionary * and my JSON input is an array.  The only mystery is why this used to work in Swift 2.2!  I ended up changing expectedResponseJSON to be an Any?, and rewrote my Objective C code in Swift:
class func getStringFrom(file fileName: String, fileExtension: String) -> String {
    let filepath = Bundle(for: BZTestCase.self).path(forResource: fileName, ofType: fileExtension)
    return try! NSString(contentsOfFile: filepath!, usedEncoding: nil) as String
}

class func getJSONFrom(file fileName: String) -> Any? {
    let json = try! JSONSerialization.jsonObject(with: (getStringFrom(file: fileName, fileExtension: ".json").data(using: .utf8))!, options:.allowFragments)
    return json
}

As a note to anyone who might cut and paste this code, I used try! and filepath! instead of try? and if let... because this code is used exclusively in tests, so I want it to crash as soon as possible if my inputs are not what I expect them to be.


SQL Replacing a Null value with 0 within a Pivot

Question: I have this query,
Select * From
(Select
    S.EmployeeID As [Employee ID],
    E.Name,
    YEAR([Date]) As [Year],
    DATENAME(MONTH, [Date]) As [Month],
    IsNull(SUM(Amount), 0) As TotalAmount
    From Sales S Left Outer Join Employee E
    On S.EmployeeID = E.EmployeeID
    Group By
    S.EmployeeID,
    E.Name,
    YEAR([Date]),
    DATENAME(MONTH, [Date])) As MonthlySale
Pivot(SUM(TotalAmount)
    For Month In ([January],[February],[March],[April],[May],
                  [June],[July],[August],[September],[October],
                  [November],[December])) As MyPivot

Which returns this table (Example Table),
+--+---------+-----+------+-------+
|ID|  Name   |Year |Jan   |Feb    | Exc
+--+---------+-----+------+-------+
|1 |John Doe |2014 |Null  |Null   | Exc
+--+---------+-----+------+-------+
|2 |Jane Doe |2014 |Null  |Null   | Exc
+--+---------+-----+------+-------+

How can I change those null values to 0s, I tried IsNull but to no avial, any ideas?
Comment: You'll have to do the replacement in the final select list.  So `Select id, Name, Year, IsNull(Jan, 0), etc`...
Answer: Ended up using,
Select [Employee ID], Name, @Year As [Year],
IsNull(January, 0)  As January,  IsNull(February, 0)  As February,  IsNull(March, 0)      As March,
IsNull(April, 0)    As April,    IsNull(May, 0)       As May,       IsNull(June, 0)       As June,
IsNull(July, 0)     As July,     IsNull(August, 0)    As August,    IsNull(September, 0)  As September,
IsNull(October, 0)  As October,  IsNull(November, 0)  As November,  IsNull(December, 0)   As December
From

Answer: with cte as
(

Select * From
(Select
    S.EmployeeID As [Employee ID],
    E.Name,
    YEAR([Date]) As [Year],
    DATENAME(MONTH, [Date]) As [Month],
    IsNull(SUM(Amount), 0) As TotalAmount
    From Sales S Left Outer Join Employee E
    On S.EmployeeID = E.EmployeeID
    Group By
    S.EmployeeID,
    E.Name,
    YEAR([Date]),
    DATENAME(MONTH, [Date])) As MonthlySale
Pivot(SUM(TotalAmount)
    For Month In ([January],[February],[March],[April],[May],
                  [June],[July],[August],[September],[October],
                  [November],[December])) As MyPivot

)
select *, coalesce(Januar, 0) from cte

Comment: You don't need the CTE to do this, they can do it in the `Select * From` - the CTE is completely unnecessary.
Comment: @sdrzymala But why introduce additional code that serves absolutely no purpose?
Comment: Yes, it's true, but CTE should not have any performance influance.


How to clear all the routes to reduce the amount of memory?

Question: Fot isnstance, in case someone don't care about closing routes, then how much spase can take navigation stack?
And is there a method or way to clean up all the navigation stack to clear some space?
For example if someone doing many pushes
Navigator.push...
Navigator.push...
Navigator.push...
Navigator.push...
Navigator.push...
Navigator.push...
Navigator.push...
Navigator.push...
...
// and at some point he would like to dismiss it all
[Navigator.cleanUp()] // for example

Answer: In order to clear all the routes, and leave only the first you can use the Navigator.popUntil method. Like this:
Navigator.of(context).popUntil((route)=> route.isFirst);
// Pops routes until the current route's isFirst getter equals to true
// (until the current route is the first route

Comment: Does it work the way like, for instance the routes were:

`route0 > route1 > route2 > route3 > route2 > route3 > route4`
// and then
`Navigator.of(context).popUntil((route)=> route.isFirst);`

then the current route (and the only one) will be `route0` ?
right?


Is there a ASP.NET Core 2 serilog sink for ActiveMq

Question: I am working on a project and i need a Serilog sink for ActiveMq. I was not able to find this specific sink for ASP.NET Core 2. I need information does this sink already exists or do i need to create my implementation.
Answer: Looks like it doesn't exist. So you would need to roll something yourself. You can try writing a custom Sink, or use the Periodic Batching Sink and plug in ActiveMQ there.
If you want to try to implement a periodic batching sink you can look to this test for reference:
https://github.com/serilog/serilog-sinks-periodicbatching/blob/dev/test/Serilog.Sinks.PeriodicBatching.Tests/Sinks/PeriodicBatching/PeriodicBatchingSinkTests.cs


Hasse invariant of quaternions over $\mathbb{Q}_p$

Question: I am trying to compute the Hasse invariant of the quaternion algebra over $\mathbb{Q}_p$. I denote this algebra by $H$, and I'm assuming $p\equiv 3\pmod{4}$.
So, $\mathbb{Q}_p(i)$ is an unramified extension of $\mathbb{Q}_p$ and it splits $H$. The Frobenius element $\sigma$ in $Gal(\mathbb{Q}_p(i)/\mathbb{Q}_p)$ is (obvisouly) defined by $\sigma(i)=-i$.
The element $j$ of $H$ is an element such that $\sigma(x)=jxj^{-1}$ for every $x\in\mathbb{Q}_p(i)$.
So, the Hasse invariant of $H$ is $\operatorname{ord}(j) + \mathbb{Z}$. Now, $\operatorname{ord}$ is defined on $H$ by $\operatorname{ord}(\alpha)=\frac{1}{2}v_p(\alpha\cdot\overline{\alpha})$. In particular, $\operatorname{ord}(j)=\frac{1}{2}v_p(1)=0$.
So, the Hasse invariant of $H$ is $0$, but this is wrong! I would "guess" it should be $\frac{1}{2}$, and anyway, zero is already mapped to by $\mathbb{Q}_p$ itself.
What am I doing wrong?
Comment: When you say "the" quaternion algebra over $\mathbb{Q}_p$, do you mean Hamilton's $(-1,-1)$ quaternion algebra?  There are two quaternion algebras over $\mathbb{Q}_p$ up to isomorphism.
Comment: @ThomTyrrell: I meant Hamilton's quaternions, yes. I already resolved the problem in my answer. Thank you.
Answer: Your $H$ is not a division algebra, it is isomorphic to $M_2(\mathbb{Q}_p)$. So, you got the Hasse invariant of $\mathbb{Q}_p$, which is indeed zero.
With $p=2$, we would actually get a division algebra.


Adobe flash player privacy settings

Question: Concerned with my privacy and the abuse that today every single company of jerks exert upon it I decided to switch from win 7 to Ubuntu but being a newbie (ubuntu is so much different!) I can't find where are settings.sol and mms.cfg stored. In windows the first is in users/app data/roaming/macromed/sys and the second one (64 bit) in windows/syswow64/macromed/flash. I read that setting the mms.cfg file correctly can prevent flash based websites from spying on you so I wanna set that right in ubuntu. Any help appreciated!
Answer: To find these files, you can use these commands in a terminal:
locate settings.sol
locate mms.cfg

settings.sol is located at (where $USER is your username)
/home/$USER/.macromedia/Flash_Player/macromedia.com/support/flashplayer/sys/settings.sol

mms.cfg seems not to exist...
Answer: While the contents of mms.cfg depend on your needs, you may create such a file in /etc/adobe or in ~/.adobe if it doesn't already exist.
Useful links include:

https://wiki.debian.org/FlashPlayer (with a sample mms.cfg)

and

http://sources.gentoo.org/cgi-bin/viewvc.cgi/gentoo-x86/www-plugins/adobe-flash/files/mms.cfg which is extensively commented.

Manipulating settings.sol seems more complicated but it is discussed here: https://unix.stackexchange.com/a/82802/15760
You could also look at Getting Rid of Nasty Adobe Flash Cookies the Cool Linux Way for advice offered in 2009.
On my system, I see this:
[11:15 AM] ~ $ locate settings.sol
/home/vasa1/.config/google-chrome/Default/Pepper Data/Shockwave Flash/WritableRoot/#SharedObjects/CFJHX928/macromedia.com/support/flashplayer/sys/settings.sol
/home/vasa1/.config/google-chrome/Default/Pepper Data/Shockwave Flash/WritableRoot/#SharedObjects/CFJHX928/macromedia.com/support/flashplayer/sys/#s.ytimg.com/settings.sol
/home/vasa1/.macromedia/Flash_Player/macromedia.com/support/flashplayer/sys/settings.sol
/home/vasa1/.macromedia/Flash_Player/macromedia.com/support/flashplayer/sys/#s.ytimg.com/settings.sol
[11:16 AM] ~ $

Note that running the file command on these files shows that they are data. But part two of Carla Schroder's link suggests that you can get rid of them interactively using:
find -iname '*.sol' -ok rm "{}" \;

I tried that command and it still works in 2014; find may take a little while before you see anything on your terminal screen.

Adobe flash player privacy settings


How to unlock the M55-Argus Rifle as a pre-order on Mass Effect 3?

Question: I had pre-ordered Mass Effect 3 on Origin and as a pre-order you got a bonus rifle. How do I go about unlocking it. I have completed the campaign and not found the rifle.
I have an unlock code from EA in my inbox however I cant find anywhere to input the code in the game?
Any ideas?
Thanks
Comment: possible duplicate of [How do I get my pre-order bonus content?](http://gaming.stackexchange.com/questions/55882/how-do-i-get-my-pre-order-bonus-content)
Comment: As a console owner, I received an email with the unlock code.
Comment: And I must not have been 100% awake, as I didn't see you also received that email.
Answer:
I have an unlock code from EA in my inbox however I cant find anywhere to input the code in the game?

This is because you don't input it in the game. To quote my answer from this question:

The easiest way is to just plug it into the origin key box.

This is what I did, and it worked seamlessly.
This video shows how.
Answer: There should have been a card included in the Origin Omni-blade box with a code to unlock the M55-Argus (not your online pass code on the back of the manual, it's on a separate card). It is only available for download via the EA servers, you do not find it in game.
When I per-ordered Origin they forgot to put it in the box, so if it's not there go back to the store you bought if from and they will arrange to get one for you.
If it seems like too much hassle, don't bother.  The M55 is powerful but the recoil is horrendous and IMO it is the most worthless gun in the game.
Comment: I dont have a box, I bought this as a digital copy!
Comment: I just had another look at my box and it says 'Omniblade edition' not 'Origin' so that's my bad.  Perhaps you should check with your vendor because from what I have read it differs from retailer to retailer.
Comment: Origin I bought it on :S


Forms: Subcategory based on Category using ASP.NET Core MVC Razor page & Local Database

Question: I am trying to make a form using two drop-down select menus: one to select the category, the other to select a subcategory. I am trying to make it so the subcategory options are based on which category they select first.
This is my subcategory model :
public class SubCategory
    {
        [Key]
        public int ID { get; set; }

        [Required]
        [StringLength(20)]
        public string Name { get; set; }

        [ForeignKey("Category")]
        public int CatID { get; set; }

        public virtual Category Category { get; set; }
        public virtual ICollection<Expense> Expenses { get; set; }
    }

My controller:
 public IActionResult Create()
        {
            //dropdown-category
            var categoryList = (from category in _context.Categories
                                select new SelectListItem()
                                {
                                    Text = category.Name,
                                    Value = category.ID.ToString()
                                }).ToList();
            categoryList.Insert(0, new SelectListItem()
            {
                Text = "----Select----",
                Value = String.Empty
            });
            ViewBag.CategoryList = categoryList;

            //dropdown-subcat
            var subCategoryList = (from subCategory in _context.SubCategories
                                   join category in _context.Categories
                                   on subCategory.CatID equals category.ID
                                   where subCategory.CatID == category.ID
                                   select  new SelectListItem()
                                   {
                                       Text = subCategory.Name,
                                       Value= subCategory.ID.ToString()
                                   }).ToList();
            ViewBag.SubCategoryList = subCategoryList;

            return View();
        }

and my view:

                Category
                <select asp-for="CatID"
                        class="form-control"
                        id="cID"
                        asp-items="@(new SelectList(ViewBag.CategoryList,"Value","Text"))">

                </select>

                 SubCategory
                <select asp-for="SubCatID"
                        class="form-control"
                        id="scID"
                        asp-items="@(new SelectList(ViewBag.SubCategoryList, "Value", "Text"))"></select>

I know I might need some javascript to make this function. However, I'm not sure how to compare the category value with my local database.
Comment: What do you mean `how to compare the category value with my local database`?Where you want to compare?
Comment: @YiyiYou in my javascript function, I would like to get the value of my category and compare it with my subcategory table (local database) and if it matching then display all the subcategory
Answer: Try to use ajax to compare category with subcategory table ,and return the data of all the subcategory.
<select asp-for="CatID"
                        class="form-control"
                        id="cID"
                        asp-items="@(new SelectList(ViewBag.CategoryList,"Value","Text"))" onchange="check(this)>

                </select>

js:
function check(t) {
            $.ajax({
                type: "GET",
                url: 'xxx?CatID=' + $(t).val(),
                success: function (data) {
                    $.each(data, function (index, value) {
                        var text1 = '<option value=' + value.value + '>' +
                            value.text +'</option>';
                        $("#SubCatID").append(text1);
                    });
                },
                error: function (result) {
                    alert("error occured");
                }
            });
        }

action:
public List<SelectListItem> xxx(int CatID){
    //compare CatId with subcategory table  here ,and return data of subcategorys
}


Libraries/Algorithms for complex if/else problems in C#

Question: I have to implement a questionnaire engine, where each answer to a single question can end up in a completely different result.
So, if we have 10 question with 10 answers each, we'd have a 10 to the power of 10 possibilities.
This should be something like a scripted-AI i guess...
So, what kind of rule engine or implementation method would I use for a problem like this?
I guess this kind of algorithm is a little bit too straightforward?
<code>if (x==1)
  if (y==1)
  {
    if (z==1 || z==2)
      // do sth
    if (z==3)
      // do sth different
   }
</code>
Thanks for any advice on this.
Answer: There are libraries that can be used to implement this form of "rules engine".
For example, Windows Workflow Foundation allows basic rules to be determined via FlowDecision activities and other related classes.
Other alternatives are rules engines, such as Drools.Net.
That being said, for simple routines like above, I'd recommend trying to refactor your algorithm to avoid lots of criteria.  By pushing this into multiple methods, you could create a series of clean conditions that would be much simpler to follow.


$2\alpha(\alpha-1)+\ln( \alpha)=0$

Question: Let $f$ be a function defined by :
$$\forall x\in(0,+\infty)\quad f(x)=x+\dfrac{1}{2}\dfrac{\ln(x)}{x} $$
calculate $f^{-1}(1)$
let $\alpha \in(0,+\infty) $ such that $f^{-1}(1)=\alpha$ then
$f(\alpha)=1 \implies 2\alpha(\alpha-1)+\ln( \alpha)=0$
i'm stuck here i can't solve this equation i know that the solution is $1$
could we solve determinate inverse function of f i.e. $f^{-1}$
Comment: i think you can not calculate $$f^{-1}(x)$$ in an explicit form
Comment: `i know that the solution is 1` That's correct, and $f(1)=1$ can be easily verified by direct substitution. This implies $f^{-1}(1)=1$ which answers the question as posted.
Comment: that's what i thought
Answer: For this special case, you can solve by elimination:
$$
\begin{align}
& 2\alpha(\alpha-1)+\log(\alpha)=0 \implies \log(\alpha)=2\alpha(1-\alpha) \\[2mm]
& \text{Let }\space g(\alpha)=\log(\alpha) \quad\&\quad h(\alpha)=2\alpha(1-\alpha) \\[2mm]
& \qquad \begin{cases} \alpha \,\in\, ]0,1[ &\Rightarrow\quad g(\alpha)=\log(\alpha) \lt0 \,,\space\space h(\alpha)=2\alpha(1-\alpha) \gt0 \\ \alpha \,\in\, ]1,+\infty[ &\Rightarrow\quad g(\alpha)=\log(\alpha) \gt0 \,,\space\space h(\alpha)=2\alpha(1-\alpha) \lt0 \end{cases} \\[2mm]
& \qquad \implies \color{red}{g(\alpha) \ne h(\alpha) \space\colon\space \alpha \,\in\, ]0,+\infty[\,-\,\{1\}} \\[2mm]
& \text{Remaining only }\space \color{red}{\alpha=1} \Rightarrow g(1)=\log(1)=0 \space\&\space h(1)=2\times1(1-1)=0 \\[2mm]
& \quad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\color{white}{\text{.}}
\end{align}
$$

$2\alpha(\alpha-1)+\ln( \alpha)=0$


How to install the i386 version of R on ubuntu?

Question: How to install the i386 version of R on ubuntu?
I already have the x64 version installed on the server, but I need the 32-bit version to use a library that is on the same version.
Comment: I don't know and can't research it now but maybe there is some workaround using multiarch (https://help.ubuntu.com/community/MultiArch) . Just an idea.
Comment: @lebatsnok I have only one library in the R application that is on i386 (32-bit) version, the R and Ubuntu are on the 64-bit version, do not know how to multiarch can help me.
Answer: I would recommend installing VirtualBox, and running a 32 bit Ubuntu version in that. This is much more straightforward than trying to run 32 bit software on a 64 bit OS. When you have the 32 bit OS installed, you can simply add this repository to your sources.list, and install the binary version of R.
Comment: Install a virtual machine just to compile a library of application? Be the best alternative?
Comment: The problem is that you need to run the 32 bit version of R to use a 32 bit version of a library. For that, you might need 32 bit versions of certain libraries that R needs, etc, etc. In addition, the 32 bit libraries can pollute your installation if you are not careful. Installing a separate OS in a VM provides a relatively straightforward solution, that separates the 32 bit stuff from the 64 bit.


Easy way to export multiple data.frame to multiple Excel worksheets

Question: I am surprised to find that there is no easy way to export multiple data.frame to multiple worksheets of an Excel file? I tried xlsx package, seems it can only write to one sheet (override old sheet); I also tried WriteXLS package, but it gives me error all the time...
My code structure is like this: by design, for each iteration, the output dataframe (tempTable) and the sheetName (sn) got updated and exported into one tab.
for (i in 2 : ncol(code)){
        ...
        tempTable <- ...
        sn <- ...
        WriteXLS("tempTable", ExcelFileName = "C:/R_code/../file.xlsx",
              SheetNames = sn);
}

I can export to several cvs files, but there has to be an easy way to do that in Excel, right?
Comment: You are wrong about **xlsx**. There is a `createSheet` function, which allows you to create new sheets, and then write to them, in a loop. Additionally, the equivalent functions in **XLConnect** are vectorized, allowing for writing a list of data frames to multiple sheets.
Comment: @joran, createSheet is used with addDataFrame not write.xlsx? I saw that earlier in the doc but couldn't figure out the whole process.
Answer: You can write to multiple sheets with the xlsx package. You just need to use a different sheetName for each data frame and you need to add append=TRUE:
library(xlsx)
write.xlsx(dataframe1, file="filename.xlsx", sheetName="sheet1", row.names=FALSE)
write.xlsx(dataframe2, file="filename.xlsx", sheetName="sheet2", append=TRUE, row.names=FALSE)

Another option, one that gives you more control over formatting and where the data frame is placed, is to do everything within R/xlsx code and then save the workbook at the end. For example:
wb = createWorkbook()

sheet = createSheet(wb, "Sheet 1")

addDataFrame(dataframe1, sheet=sheet, startColumn=1, row.names=FALSE)
addDataFrame(dataframe2, sheet=sheet, startColumn=10, row.names=FALSE)

sheet = createSheet(wb, "Sheet 2")

addDataFrame(dataframe3, sheet=sheet, startColumn=1, row.names=FALSE)

saveWorkbook(wb, "My_File.xlsx")

In case you might find it useful, here are some interesting helper functions that make it easier to add formatting, metadata, and other features to spreadsheets using xlsx:
http://www.sthda.com/english/wiki/r2excel-read-write-and-format-easily-excel-files-using-r-software
Comment: Is it just me, or does sheet 2 simply write over sheet 1 when one uses this code?
Comment: @EcologyTom I switched from `xlsx` to `openxlsx` a while back, as I find it much more intuitive and it also avoids the java dependency.
Comment: Add `row.names=FALSE` to remove row names.
Comment: it seems like this solution does not work, sheet 2 writes over sheet 1
Comment: This solution seems to work for some but not others. As for me, it also overwrites sheet1 instead of generating separate sheet(s). The solution given by EcologyTom and Syed work for me.
Comment: `xlsx` doesn't take care of the numbers in the first row R putting there. `openxlsx` remove them.
Comment: Yes, the java dependency forced me to make the same switch. Although the code is a little longer it is pretty straightforward. For a method with `openxlsx` version 4.0 see my supplementary answer below.
Comment: @NewBee I get two separate sheets when I use the code in the answer.
Comment: @eipi10 what version of the package are you using? I am getting the same result as @NewBee with sheet 2 overwriting sheet 1. Using the second example I'm even more confused because when I run `sheet = createSheet(wb,"Sheet 1")` I get the error `Error in as.vector(x, "character") : cannot coerce type 'environment' to vector of type 'character'`.
Comment: I'm using xlsx 0.6.5; rJava 0.9-13; R 4.0.3. Computer is running macOS 10.15.6 (Catalina). I should point out that it's been a few years since I used xlsx in my own work. I switched to openxlsx to avoid java dependency pain. I also find openxlsx's syntax more intuitive for formatting output.
Comment: @Macosso I just ran the code on my Mac and it writes two separate worksheets. My system is the same as listed in my previous comment.
Answer: You can also use the openxlsx library to export multiple datasets to multiple sheets in a single workbook.The advantage of openxlsx over xlsx is that openxlsx removes the dependencies on java libraries.
Write a list of data.frames to individual worksheets using list names as worksheet names.
require(openxlsx)
list_of_datasets <- list("Name of DataSheet1" = dataframe1, "Name of Datasheet2" = dataframe2)
write.xlsx(list_of_datasets, file = "writeXLSX2.xlsx")

Comment: Thanks, `openxlsx::write.xlsx` is the way to go... I was saving 11 sheets, each a 20,000x10 dataframe, done is a couple seconds while `xlsx::write.xlsx` errored out after appending the second sheet with `java.lang.OutOfMemoryError: Java heap space`
Comment: I have used these packages and I think the `openxlsx` is the quickest as its c++. `XlConnect` will eat your RAM. You might want to do some benchmarking between `xlsx` and `openxlsx`
Comment: Another advantage of that packge is that it take care of the R-numbering in the first row.
Comment: I needed to add the parameter `append=TRUE` to write.xlsx to make it write several sheets at once to one Excel file
Comment: Lovely! I created my list as part of a loop, and just had to initialize it (`list_of_dfs <- list()`) and then fill it, using temp_key and temp_df constructed during the loop (`list_of_dfs[[temp_key]] = temp_df`) . It was also very fast in writing, despite the 16 sheets I needed to create!

Has anyone witnessed problems with memory during creation?
Comment: I have a similar problem resulting in a lot of sheets and I would like an option that automatically creates dataframes (based on dplyr's group_by function), and subsequently creates multiple sheets in an excel workbook. Is this possible?
Comment: This solution looked nice, but the package `openxlsx` seems uninstallable - I had problems with both CRAN and `conda` manager, in both cases it failed to install/load the package due to missing library `libicui18n.so.64` (Ubuntu 18.04 with R installed from conda). On the other hand `xlsx` worked flawlessly.
Comment: Using `openxlsx` ended up being the way to go for me.  `xlsx` failed to append worksheets even when `append=TRUE`.  Using the instructions above, I was able to seamlessly stitch together 17 sheets with 40k rows each in a single Excel workbook.
Answer: There's a new library in town, from rOpenSci: writexl

Portable, light-weight data frame to xlsx exporter based on
  libxlsxwriter. No Java or Excel required

I found it better and faster than the above suggestions (working with the dev version):
library(writexl)
sheets <- list("sheet1Name" = sheet1, "sheet2Name" = sheet2) #assume sheet1 and sheet2 are data frames
write_xlsx(sheets, "path/to/location")

Comment: Thanks! This worked where openxlsx didn't (I can't install rtools at work).
Comment: Which version do you use for this? The default cran download doesn't support multiple sheets (yet): ' Error in writexl::write_xlsx(list(...  :
  Argument x must be a data frame or list of data frames '
Comment: As I wrote, the dev version.
Comment: @JarkoDubbeldam: I installed mine from cran and multiple sheets do work for me (R 3.3.0). Check if the objects inside your list are data.frames.
Comment: this is one really works. couldn't install xlsx in r.
Answer: Many good answers here, but some of them are a little dated. If you want to add further worksheets to a single file then this is the approach I find works for me. For clarity, here is the workflow for openxlsx version 4.0
# Create a blank workbook
OUT <- createWorkbook()

# Add some sheets to the workbook
addWorksheet(OUT, "Sheet 1 Name")
addWorksheet(OUT, "Sheet 2 Name")

# Write the data to the sheets
writeData(OUT, sheet = "Sheet 1 Name", x = dataframe1)
writeData(OUT, sheet = "Sheet 2 Name", x = dataframe2)

# Export the file
saveWorkbook(OUT, "My output file.xlsx")

EDIT
I've now trialled a few other answers, and I actually really like @Syed's. It doesn't exploit all the functionality of openxlsx but if you want a quick-and-easy export method then that's probably the most straightforward.
Answer: I'm not familiar with the package WriteXLS; I generally use XLConnect:
library(XLConnect)
##
newWB <- loadWorkbook(
  filename="F:/TempDir/tempwb.xlsx",
  create=TRUE)
##
for(i in 1:10){
  wsName <- paste0("newsheet",i)
  createSheet(
    newWB,
    name=wsName)
  ##
  writeWorksheet(
    newWB,
    data=data.frame(
      X=1:10,
      Dataframe=paste0("DF ",i)),
    sheet=wsName,
    header=TRUE,
    rownames=NULL)
}
saveWorkbook(newWB)

This can certainly be vectorized, as @joran noted above, but just for the sake of generating dynamic sheet names quickly, I used a for loop to demonstrate.
I used the create=TRUE argument in loadWorkbook since I was creating a new .xlsx file, but if your file already exists then you don't have to specify this, as the default value is FALSE.
Here are a few screenshots of the created workbook:
Comment: I haven't used XLConnect, very detailed example, thanks!
Comment: You're welcome - I've found it to be a very useful package. There's a pretty good [vignette on CRAN](http://cran.r-project.org/web/packages/XLConnect/vignettes/XLConnect.pdf) that details some of the main features, with a nice example in section 4 demonstrating how to write R plots into a worksheet.
Answer: I regularly use the packaged rio for exporting of all kinds. Using rio, you can input a list, naming each tab and specifying the dataset. rio compiles other in/out packages, and for export to Excel, uses openxlsx.
library(rio)

filename <- "C:/R_code/../file.xlsx"

export(list(sn1 = tempTable1, sn2 = tempTable2, sn3 = tempTable3), filename)

Comment: Wish there was a way on SO to supplant highly-upvoted but now-outdated answers. They were right when they posted, but this is almost certainly the best way to do this now.
Answer: Incase data size is small, R has many packages and functions which can be utilized as per your requirement.
write.xlsx, write.xlsx2, XLconnect also do the work but these are sometimes slow as compare to openxlsx.
So, if you are dealing with the large data sets and came across java errors. I would suggest to have a look of "openxlsx" which is really awesome and reduce the time to 1/12th.
I've tested all and finally i was really impressed with the performance of openxlsx capabilities.
Here are the steps for writing multiple datasets into multiple sheets.
 install.packages("openxlsx")
 library("openxlsx")

    start.time <- Sys.time()

    # Creating large data frame
    x <- as.data.frame(matrix(1:4000000,200000,20))
    y <- as.data.frame(matrix(1:4000000,200000,20))
    z <- as.data.frame(matrix(1:4000000,200000,20))

    # Creating a workbook
    wb <- createWorkbook("Example.xlsx")
    Sys.setenv("R_ZIPCMD" = "C:/Rtools/bin/zip.exe") ## path to zip.exe

Sys.setenv("R_ZIPCMD" = "C:/Rtools/bin/zip.exe") has to be static as it takes reference of some utility from Rtools.
Note: Incase Rtools is not installed on your system, please install it first for smooth experience. here is the link for your reference: (choose appropriate version)
https://cran.r-project.org/bin/windows/Rtools/
check the options as per link below (need to select all the check box while installation)
https://cloud.githubusercontent.com/assets/7400673/12230758/99fb2202-b8a6-11e5-82e6-836159440831.png
    # Adding a worksheets : parameters for addWorksheet are 1. Workbook Name 2. Sheet Name

    addWorksheet(wb, "Sheet 1")
    addWorksheet(wb, "Sheet 2")
    addWorksheet(wb, "Sheet 3")

    # Writing data in to respetive sheets: parameters for writeData are 1. Workbook Name 2. Sheet index/ sheet name 3. dataframe name

    writeData(wb, 1, x)

    # incase you would like to write sheet with filter available for ease of access you can pass the parameter withFilter = TRUE in writeData function.
    writeData(wb, 2, x = y, withFilter = TRUE)

    ## Similarly writeDataTable is another way for representing your data with table formatting:

    writeDataTable(wb, 3, z)

    saveWorkbook(wb, file = "Example.xlsx", overwrite = TRUE)

    end.time <- Sys.time()
    time.taken <- end.time - start.time
    time.taken

openxlsx package is really good for reading and writing huge data from/ in excel files and has lots of options for custom formatting within excel.
The interesting fact is that we dont have to bother about java heap memory here.
Answer: tidy way of taking one dataframe and writing sheets by groups:
library(tidyverse)
library(xlsx)
mtcars %>%
  mutate(cyl1 = cyl) %>%
  group_by(cyl1) %>%
  nest() %>%
  ungroup() %>%
  mutate(rn = row_number(),
         app = rn != 1,
         q = pmap(list(rn,data,app),~write.xlsx(..2,"test1.xlsx",as.character(..1),append = ..3)))

Answer: I had this exact problem and I solved it this way:
library(openxlsx) # loads library and doesn't require Java installed

your_df_list <- c("df1", "df2", ..., "dfn")

for(name in your_df_list){
  write.xlsx(x = get(name),
             file = "your_spreadsheet_name.xlsx",
             sheetName = name)
}

That way you won't have to create a very long list manually if you have tons of dataframes to write to Excel.
Comment: I don't know why this  is overwriting the first worksheet
Comment: This does overwrite the sheet, I and others have faced the issue as well. Look here -https://stackoverflow.com/questions/57278418/openxlsxwrite-xlsx-overwriting-existing-worksheet-instead-append
Answer: For me, WriteXLS provides the functionality you are looking for. Since you did not specify which errors it returns, I show you an example:
Example
library(WriteXLS)
x <- list(sheet_a = data.frame(a=letters), sheet_b = data.frame(b = LETTERS))
WriteXLS(x, "test.xlsx", names(x))

Explanation
If x is:

a list of data frames, each one is written to a single sheet
a character vector (of R objects), each object is written to a single sheet
something else, then see also what the help states:

More on usage
?WriteXLS

shows:
`x`: A character vector or factor containing the names of one or
     more R data frames; A character vector or factor containing
     the name of a single list which contains one or more R data
     frames; a single list object of one or more data frames; a
     single data frame object.

Solution
For your example, you would need to collect all data.frames in a list during the loop, and use WriteXLS after the loop has finished.
Session info

R 3.2.4
WriteXLS 4.0.0
Comment: This package will work but IMHO I would try avoid the dependency of perl (as I would try to avoid the dependency of Java with `xlsx`) since it makes it more difficult to set-up
Answer: I do it in this way for openxlsx using following function
mywritexlsx<-function(fname="temp.xlsx",sheetname="Sheet1",data,
                  startCol = 1, startRow = 1, colNames = TRUE, rowNames = FALSE)
{
  if(! file.exists(fname))
    wb = createWorkbook()
  else
   wb <- loadWorkbook(file =fname)
  sheet = addWorksheet(wb, sheetname)

  writeData(wb,sheet,data,startCol = startCol, startRow = startRow,
          colNames = colNames, rowNames = rowNames)
  saveWorkbook(wb, fname,overwrite = TRUE)
}

Comment: loadWorkbook is key here for opening existing files
Comment: Also if one wants to write formulas to excel then there is different function named writeFormula, in addition once you write formula the file needs to be refreshed or reopened then saved and then closed in excel. demo is given here [link(https://stackoverflow.com/questions/46914303/openxlsx-not-able-to-read-from-xlsx-file-in-r/51376514#51376514)
Answer: I do this all the time, all I do is
WriteXLS::WriteXLS(
    all.dataframes,
    ExcelFileName = xl.filename,
    AdjWidth = T,
    AutoFilter = T,
    FreezeRow = 1,
    FreezeCol = 2,
    BoldHeaderRow = T,
    verbose = F,
    na = '0'
  )

and all those data frames come from here
all.dataframes <- vector()
for (obj.iter in all.objects) {
  obj.name <- obj.iter
  obj.iter <- get(obj.iter)
  if (class(obj.iter) == 'data.frame') {
      all.dataframes <- c(all.dataframes, obj.name)
}

obviously sapply routine would be better here
Answer: for a lapply-friendly version..
library(data.table)
library(xlsx)

path2txtlist <- your.list.of.txt.files
wb <- createWorkbook()
lapply(seq_along(path2txtlist), function (j) {
sheet <- createSheet(wb, paste("sheetname", j))
addDataFrame(fread(path2txtlist[j]), sheet=sheet, startColumn=1, row.names=FALSE)
})

saveWorkbook(wb, "My_File.xlsx")

Comment: Could you add some description to this answer to provide context for how this answers the question?


With javascript how can I identify the HTML tag?

Question: I had another question similar to this but the answers seemed to miss out that I was trying to find the  tag and modify it.
They suggested:
elem.className = elem.className.replace(/\blight\b/," dark ");

But with javascript how can I get the  tag as the elem variable?
Answer: to get  tag you could just do:
var elem = document.getElementsByTagName("html")[0];

or
var elem = document.querySelector("html");

or
var elem = document.body.parentNode;

Comment: Perfect !  What about the suggestion above document.querySelector('html') is that also valid? I have not seen that before.
Comment: Yes it is valid in "modern" browsers.
Comment: @Marilou: https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelector.
Answer: The following code returns the html element
document.documentElement

Answer: var htmlTag = document.getElementsByTagName("html")[0]


transfeer object between activities

Question: I`m trying to parse an object from my my main activity to a new activity that starts when the user clicks a button. I've seached the internet and found how to parse primative types and custom made classes that implements parceble or serilizable, but can't find any information on how to transfeer a raw object.
I'll write psuedo-code of what I`m trying to achive below:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    loadConnectInfo();
    View connectButton = findViewById(R.id.connectButton);
    connectButton.setOnClickListener(this);
}

public void onClick(View v) {
    switch (v.getId()) {
        case R.id.connectButton:
            Intent i = new Intent(this, NewClass.class);
            Socket s = connect();  // this is the object I want to parse to to "NewClass"
            startActivity( i);
            break;
    }

Answer: You can't pass an object that is neither serializable nor parcelable between activities this way. What you probably want to do in this case is make your code that manages and interacts with the socket into a service and bind to that service in all the activities that need to use it.
Answer: Sometimes when I had to pass variable from one class to another I've used static variables in class which I deliver some objects. This will work but it is not recommended way to pass object in Android and you don't have guaranty that will work always.. Here you should check if your delivered object is not null of course.
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.connectButton:
            Intent i = new Intent(this, NewClass.class);
            Socket s = connect();  // this is the object I want to parse to to "NewClass"
            //Here using static field of class you pass variable to NewClass
            //You can access this value in NewClass like that: NewClass.StaticSocket
            //Warning: This is not a standar android scheme but I tested and it works
            //with Date object
            NewClass.StaticSocket = s;
            startActivity( i);
            break;
    }

On second activity:
public void onCreate(Bundle savedInstanceState) {
        Log.i("StaticVar","NewClass.StaticSocket: "+ NewClass.StaticSocket.toString());

Comment: I prefeer not to use static variables but +1 for working solution
Answer: There are already other posts about this:
What's the best way to share data between activities?
BTW, be careful: objects like sockets are not meant to be shared by bundles through the intent because they shouldn't be serialized.  Maybe using a global state, like a singleton does it for you.

transfeer object between activities


How can I measure how much memory consume my java application

Question: It is very important to know that how much memory can consume my java application e.g. how much RAM and CPU speed.
Comment: Hi please refer this link,hope your doubt will clear.
https://stackoverflow.com/q/37916136/9502833
Comment: Why ROM ? Could you explain any scenario?
Answer: You can monitor the memory usages and also the number of threads used for your application by profilers.
There are many profilers are available, Below I have given few famous profilers which have been used across.

JProfiler
YourKit
Java VisualVM
Eclipse profiler -
Memory Analyzer | JVM Monitor
Netbeans Profiler


Computational complexity of a algorithm

Question: Algorithm 1. STACKSTUFF(n)
Input: Integer n
1) Let S = an empty Stack
2) Let X = -1
3) For i = 1 to 2n
4) S.Push(i)
5) End For
6) For i = 1 to n
7) Let X = S.Pop()
8) End For
Output: The contents of X

1) What is this algorithm written in pseudo code doing?

To my understanding, S.Push(i) adds item i on top of stack S. X = S.Pop() removes the item from the top of stack S and assigns it to X.
2) What is the computational complexity O(n) for algorithm 1, STACKSTUFF?

I believe the answer would be: O(3n)
The first loop would be 2n and the second for loop n, so 2n+n=3n.
Or... Would the answer just be O(n^2) since all we would have to do would be n*n?
3) If n > 0 then what is returned by the algorithm? What about n < 1

a) 2n
b) -1
c) n-1
d) n+1
e) None of the above

This last bit really confuses me. From my understanding, if n was always greater than 0, the algorithm would always return n+1, and if n was always less than 1, the algorithm would return n-1. However this is pure guess work...
If I thought about this logically, then let's say n was 3 for example. Since the first For loop is  1 to 2n, then this would mean that we would end up with the following stack S={1,2,3,4,5,6} as it added every number up to double n into S. The second For loop then pops 3 numbers so X ends up looking like this X={6,5,4}. If I am correct there... Should I assume that this was just a trick question and the answer is e, none of the above?
I just wanted to make sure my understanding here was correct before I continued studying. Thanks for any help.
Answer: 1) The algoritm adds 1..2n to a stack, then pops n elements. Meaning that 1..n is left in the stack and the last popped element remains in X.
2) You are correct. The algoritm has complexity: 2 + (2n * 1) + (n * 1) = 3n + 2 = O(3n) = O(n).
3) The algoritm as storing the last popped element in X and then returning X and the last popped element is n + 1, so the answer should be d) n+1.
EDIT
Explanation on 3:
if n > 0:
X := -1
push 2n to the stack
stack = {1, 2, .. n, n + 1, ..., 2n}
pop n elements from the stack and store the popped element in X
first iteration:
   X := stack.pop()
   stack = {1, 2, .. n, n + 1, ..., 2n - 1}
   X = 2n
... until we have popen n numbers.
stack = {1, 2, .. n}
X = n + 1

if n < 1
X := -1
because n < 1 we won't do any iterations in the loops
so X will not change and still be -1

Comment: I believe it means n > 0 first and then  n < 1, so we would answer the question twice
Comment: I hope this isn't too much trouble, but can you please explain how you got n+1 for the first answer and -1 for the second? I want to make sure I understand how to answer this question, thanks!
Comment: Added some explanation in the answer
Comment: Thanks a lot, I was really thinking about this question in the wrong way but I finally have a better grasp on it thanks to you
Comment: Sorry just had a quick question, if n is less than 1, why do we not do any iterations in the loops? Lets say for example n = -5. Can the loop not run for 1 to -5 iterations? Is this true for all negative numbers?

Computational complexity of a algorithm