What happens if the server closes the socket first?

Question: Here is the situation: I have 2 machines, A and B. A listens to a port p. B creates a socket s1 and connects to p. A accepts the connection in socket s2. For now, A and B can communicate with each other through the socket.
However, if I kill the program in A and then restart this program some time later, B doesn't know because it hasn't sent any data to A during this period. Now B begins to write data to A through s1. What will happen next? Why?
Actually I found the write call did not fail but A still didn't get the data. What's more, if I put s1 in epoll device, I found the event returned by epoll_wait is EPOLLERR | EPOLLHUP after the call to write. Why?
Unfortunately, under this situation, it seems to lose the data since the `write' call didn't fail but A couldn't get the data. Any solutions?
Comment: B should get `EPIPE` for failed `write`. How do you know `write` didn't fail? Some sample code + output will be helpful.
Comment: In general, you can't rely on the lack of an error on a write to indicate that data has been transmitted.  You need to check for errors on close.  This is true of writing to disk as well as to a socket.
Answer:
When you kill a program having established sockets, it will send RST to all other end. so B should receive RST on s1, and all future call on s1 will return error. But some firewall may filter out the RST packet, you can check the RST packet with tcpdump.
If B doesn't receive the RST packet in step1, when it continues sending other packets (write) to A, A will reply with RST packet, and all future call on B will return error once B receive this RST.
If B doesn't receive the RST packet in step2 too, after a certain time (write timeout), B will drop the connection, and all future call on B will return error.

You can see, write call seldom return error, it returns success if the packet is send, doesn't care whether the remote end receives the packet.
in your situation, you don't get EPOLLHUP as soon as you call epoll_wait, but after received RST or write timeout
Comment: Thanks, in fact B did not try to receive any packet from A since it played a role of `sending module`. In this situation, I can't rely on `write` to ensure data transmitting
Answer: If the other end of a socket has been closed, it's actually made readable, and a read (or recv) call will return zero indicating that the socket on the other end has been gracefully closed.
Comment: Thanks, I've put this socket into epoll device and wait for EPOLLIN. Then it immediately returns after the server closes itself.
Answer: You wrote to a disconnected stream (even if your machine didn't know it was disconnected.   Since you say "accepts the connection", I assume you're setting up a TCP connection between two machines.)
If you were talking UDP, there's no Listen/Connect/Accept, and the data would be sent to whatever is listening at the addr/port.  But you're not talking UDP. [edit to spell out the conclusion:] You're writing data into a dead connection (and at some point it will be clear the connection is dead, now that you've tried to use it).  Writing data doesn't tell you if the other side has received the data, success tells you it has queued the data to send.


How long do you keep your customers logged in? (sessions and authentication)

Question: I was curious how long do you think we should keep users logged in before they're required to sign in with username and password again?
I was wondering if there's any resources or studies done to show that there's been better user experience when keeping users logged in longer vs shorter.
Comment: It depends. One factor is what is exposed when logged in: bank account? photos? ability to buy things? the ability to just see non-personal things? Editing your question with more details would get you better answers.
Answer: The length of a user staying logged in until they are automatically logged out depends on the sensitivity of the data. While it is perfectly fine for a bank to sign out their users after 5 or 10 minutes of idling, this would be a very frustrating experience for a social network or online shop.
There is no direct rule and for as far as I know not even a study about the session length, as it highly depends on your platform and what the users are supposed to do. The question you should be asking is, how important is the user data security to you?
This will lead you to the question "how short do you keep your customers logged in?". And more important than the time is, how you should logout your users. Instead of using a direct time-span, it should be an idle time, like banks are using it. But that last part is just me philosophing around.
I attached you a some links that might help you.

Deconstructing the Poor Design of a Well-Intentioned Microinteraction
SSA Accessibility Best Practices Library - Timeout
Session Timeout – another useless Security Brainchild?
Answer: I think as long as possible, without posing a security risk. You should make some rules and consistently improve upon them. Like start with @marvinpoo recommended idle time. Then you can add later on check for impossible behaviour like requesting two pages within microseconds, change of location within a browsing session(use this with grain of salt as mobile networks keep changing I.P), too many 404s.
I think you should also learn from big names like facebook and google. They take more than just time in consideration. They hardly ever log you out. When you are accessing something sensitive ask for password again, but not log them out. Only log them out after days of inactivity. You could refresh authentication token at every 24 hours with 30 days of expiry, and then ask for password again when they access something sensitive(of course with some validity period).


Login to twitter app for multiple users with twitteroauth

Question: Im making an app where users can comment to website. Soo far i came up with.
$sporocilo = $_POST["sporocilotw"];
$sporocilo2 = $sporocilo . " #vetercek";

require_once 'twitteroauth.php';

define('CONSUMER_KEY', 'XXXXXXXXXXXXXXXXXXXXX');
define('CONSUMER_SECRET', 'XXXXXXXXXXXXXXXXXXXXXXXXXx');
define('ACCESS_TOKEN', 'XXXXXXXXXXXXXXXXx-XXXXXXXXXXXXXXXXX');
define('ACCESS_TOKEN_SECRET', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');

$toa = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);

$query = array(
  "status" => $sporocilo2,
  "display_coordinates" => "false"
);

$results = $toa->post('statuses/update', $query);

What this does is post a tweet. The problem is that the user who sends it is always the same (app). How could i make login page or something similar so users would post tweets with their own names ?
Answer: Nope it does not work that way.
The CONSUMER_KEY , CONSUMER_SECRET , ACCESS_TOKEN & ACCESS_TOKEN_SECRET corresponds to the current account/app. You cannot impersonate it. They are different for each and every account/app.
You can do tweets on your page , on other's walls , retweet only from this account , you can't use other account as you need the above mentioned credentials which will be a different one.
Answer: I got it working using these files
http://runnable.com/UnUq8RFIGS9NAAA0/twitter-update-status-for-php-twitteroauth-and-oauth


jQuery - Trigger element when enters div

Question: I am trying to develop a script where the header clones as soon as it enters the targeted div without using the function fromTop. Thank you:)
$(document).ready(function() {
    var $header = $(".header"),
    $clone = $header.before($header.clone().addClass("clone"));

    $(window).on("scroll", function() {
      var fromTop = $(window).scrollTop();
      $("body").toggleClass("down", (fromTop > 490));
    });
});

I have also made a jsFiddle - https://jsfiddle.net/Lng9cf7v/2/
Answer: This code finds the current distance between the navbar and the div where you want the navbar to be cloned. Once the distance between the two are 0px or less (navbar is on top or below the div), the navbar is then displayed by adding the .down class. toggleClass() was causing jitteriness with the navbar, so I used addClass() and removeClass() instead.
$(window).on("scroll", function() {

    var cloneArea = $('.other-div').offset().top;
    var fromTop = $(window).scrollTop();

    if ((fromTop - cloneArea >= 0) && ($("body").hasClass("down") == false)) {

        $("body").addClass("down");

    } else if ((fromTop - cloneArea < 0) && ($("body").hasClass("down") == true)) {

        $("body").removeClass("down");

    }

});

working demo: https://jsfiddle.net/kkdaily/rp0dhvuv/
Comment: You are a true lifesaver :) Thank you so much!


PSN plus: Once games are free, are they free forever?

Question: I know that with the Playstation plus membership, they will away free games every month and giving away different games every month. So, I were to get a free game, then a month later, that same game isn't considered a "free" ps+ game, will I still have it?
Scenario:
--June 2013--
Uncharted 3 is free for ps+ members
2 months later
--August 2013--
(Hypothetically) Uncharted 3 ISN'T offered as free for ps+ members anymore
So, if I downloaded, installed, played, etc. Uncharted 3 while it was free, will I have still owned Uncharted 3 even AFTER August 2013 when they stop offering it to ps+ members?
Also note, that during this time, my ps+ membership has NOT expired.
Answer: Yes, it will still be playable if you still have PS+ membership.
Source: own experience with Plants vs. Zombies
EDIT:
As Fluttershy says, it will only work if you "purchase" the game
Comment: The free one. You'll know it's yours when the little shopping bag appears.
Comment: Note that it only works if you've "purchased" the free game. So always make sure to do that.
Comment: @Fluttershy when you say "purchase", do you mean the normal retail price or "free" price?


User isn't authenticated till the next page request

Question: I have this following mvc application
The problem is when Im trying to assign profile values:
<code>            // Attempt to register the user
            MembershipCreateStatus createStatus = MembershipService.CreateUser(model.Email, model.Password);

            if (createStatus == MembershipCreateStatus.Success)
            {
                //Adding role
                MembershipService.AddDefaultRole(model.Email);

                FormsService.SignIn(model.Email, false /* createPersistentCookie */);

                //Add other initial profile data
                HttpContext.Profile["FirstName"] = model.FirstName; //PROBLEM
                HttpContext.Profile["LastName"] = model.LastName; //PROBLEM

                return RedirectToAction("List", new { area = "", controller = "Requests" });
            }
            else
            {
                ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
            }
</code>
Inside FormsService.SignIn(model.Email, false):
<code>    public void SignIn(string email, bool createPersistentCookie)
    {
        if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");

        FormsAuthentication.SetAuthCookie(email, createPersistentCookie);
    }
</code>
How come after calling FormsAuthentication.SetAuthCookie, User isn't yet authenticated?
I'm getting an error b.c. im trying to assign some profile value to anonymous user .
Any idea?
Answer: When you set a cookie, it's added to the Response, but the IsAuthenticated bool is set from the Request.  After setting the authentication and setting up your session variables, you should redirect to another page, like the home page or the original request.
Comment: That makes sense. Do you know any easy way to update profile value before the next request then?  or should I store the values temporarily and save it on the next page request? What's the proper way of doing it?
Comment: Do you need to? in your initialization event, if the user is authenticated but does not have profile information, I would think that's the time to load it up, but I've never used the built-in profile manager, it never suited my needs.


JavaFX how to make ScrollPane content grow horizontally when using FXML?

Question: This is normal horizontal grow of my GridPane:

But when i wrap GridPane in ScrollPane:

I would like to keep vertical scroll feature of ScrollPane, but allow my GridPane to grow horizontally in ScrollPane. Is it possible? I tried setting HBar Policy to NEVER, but it only hides HBar. Thanks in advance.
Minimal example in code (which seems working):
Stage stage = new Stage();
ScrollPane sp = new ScrollPane();
sp.setFitToHeight(true);
sp.setFitToWidth(true);
GridPane gp = new GridPane();

TextField tf1 = new TextField();
TextField tf2 = new TextField();
TextField tf3 = new TextField();
TextField tf4 = new TextField();

gp.getColumnConstraints().add(new ColumnConstraints(10, 100, 1000, Priority.ALWAYS, HPos.CENTER, true));
gp.getColumnConstraints().add(new ColumnConstraints(10, 100, 1000, Priority.ALWAYS, HPos.CENTER, true));
gp.getRowConstraints().add(new RowConstraints(10, 20, 1000, Priority.ALWAYS, VPos.CENTER, true));
gp.getRowConstraints().add(new RowConstraints(10, 20, 1000, Priority.ALWAYS, VPos.CENTER, true));
gp.getRowConstraints().add(new RowConstraints(10, 20, 1000, Priority.ALWAYS, VPos.CENTER, true));

gp.add(tf1, 0, 0);
gp.add(tf2, 1, 0);
gp.add(tf3, 0, 1);
gp.add(tf4, 0, 2);

sp.setContent(gp);

stage.setScene(new Scene(sp));
stage.show();

My example in FXML (which does not work):
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>

<ScrollPane fitToHeight="true" fitToWidth="true" xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1">
   <content>
      <GridPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0">
        <columnConstraints>
          <ColumnConstraints hgrow="ALWAYS" maxWidth="1000.0" minWidth="10.0" prefWidth="100.0" />
          <ColumnConstraints hgrow="ALWAYS" maxWidth="1000.0" minWidth="10.0" prefWidth="100.0" />
        </columnConstraints>
        <rowConstraints>
          <RowConstraints maxHeight="1000.0" minHeight="10.0" prefHeight="20.0" vgrow="ALWAYS" />
          <RowConstraints maxHeight="1000.0" minHeight="10.0" prefHeight="20.0" vgrow="ALWAYS" />
          <RowConstraints maxHeight="1000.0" minHeight="10.0" prefHeight="20.0" vgrow="ALWAYS" />
        </rowConstraints>
         <children>
            <TextField />
            <TextField GridPane.columnIndex="1" />
            <TextField GridPane.rowIndex="1" />
            <TextField GridPane.rowIndex="2" />
         </children>
      </GridPane>
   </content>
</ScrollPane>

Comment: A [mre] would be useful.
Comment: Does doing `scrollPane.setFitWidth(true)` work?
Comment: @Slaw Both `.setFitWidth()` and `.setFitHeight()` are set to `true`, so no.
Comment: @Slaw, it seems the OP has done the work to make their question more inline with SO standards. I guess you closed it. Can you consider undoing that please?
Comment: @julien.giband "I guess you closed it" – I'm not one of the three that voted to close (though I realize you can't see that yet, due to rep).
Comment: @Slaw sorry for the bother then, just tried to make a guess
Answer: It works this way if you set the fitToWidth property of your ScrollPane to true.
Of course your GridPane must be able to grow, so you need to make sure that its prefWidth/maxWidth properties don't prevent that, same for at least one of its columns.
Sample FXML (tested in SceneBuilder):
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<ScrollPane fitToWidth="true" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="410.0" prefWidth="518.0" xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1">
   <content>
      <GridPane hgap="6.0" vgap="4.0">
        <columnConstraints>
          <ColumnConstraints fillWidth="false" hgrow="SOMETIMES" maxWidth="-Infinity" minWidth="-Infinity" />
          <ColumnConstraints hgrow="SOMETIMES" minWidth="-Infinity" prefWidth="300.0" />
        </columnConstraints>
        <rowConstraints>
          <RowConstraints minHeight="150.0" prefHeight="30.0" vgrow="SOMETIMES" />
          <RowConstraints minHeight="150.0" prefHeight="30.0" vgrow="SOMETIMES" />
          <RowConstraints minHeight="150.0" prefHeight="30.0" vgrow="SOMETIMES" />
        </rowConstraints>
         <children>
            <Button mnemonicParsing="false" text="Button" />
            <Button mnemonicParsing="false" text="Button" GridPane.rowIndex="1" />
            <Button mnemonicParsing="false" text="Button" GridPane.rowIndex="2" />
            <TextField GridPane.columnIndex="1" />
            <TextField GridPane.columnIndex="1" GridPane.rowIndex="1" />
            <TextField GridPane.columnIndex="1" GridPane.rowIndex="2" />
         </children>
      </GridPane>
   </content>
</ScrollPane>

Comment: Yeah, this was my problem. I set `maxWidth` to `USE_PREF_SIZE` in SceneBuilder, which results in adding `maxWidth="-Infinity"` in `GridPane` tag.


Can you encounter an Unown not in the 28 Unown species?

Question: I encountered an Unown and I don't remember it in the 28 unknown species so fast in Pokémon Gold.
Comment: Welcome to Arqade! Can you be more clear on what you are asking? I could instantly tell that is the Unown for the letter B
Comment: What's "so fast" here? It's hard to tell what you're asking
Answer: Yes that Unown exists and is correct.
Here you have a image with all 28 forms that the Unowns can have:

As you can see that Unown is the second one, Unown B.
Comment: Thank you. If you think my answer answers your question, please mark it as valid, with the tick on the left. Thank you!
Comment: It is also should be noted that in Gen 2 each of the 4 puzzle releases different Unown to be caught


Why is villager breeding failing in a village?

Question: I have a village of four villagers. There are about ten beds in the village.

When I feed two of the villagers, they start showing heart particles, but then the breeding fails with cloud particles. Can villagers have a problem pathfinding to a bed behind closed door?
Comment: Possible duplicate of [Why won't my villagers breed](https://gaming.stackexchange.com/questions/188494/why-wont-my-villagers-breed)
Answer: The beds might not be close enough, or there might not be enough free space above them for the baby to jump.

[They] can produce a baby only if they have their own beds plus an available bed for the baby, and the beds have two empty blocks above them (there needs to be room for the baby to jump on the bed). If the population cap is met, or the beds are obstructed, angry particles appear above their heads (along with the heart particles), preventing them from mating.
Minecraft Gamepedia
Answer: Villagers are annoying. They use some odd methods of pathfinding that don't always work.

Take 3 villagers FAR away from the original village
Build up a villager breeder (Tango Tek makes a good one on that)
Done!

I honestly would not use the original village
Comment: I wanted to breed them in a more natural manner. I've seen the villager breeder designs, but they ruin the purpose of having a nice village.
Answer: If you don't want to use the villager breeders, give each villager exactly 32 carrots (or bread and so on). Make sure they have at least 4 beds within the same room. (you can change their bed, but that will help with the pathfinding issue)
Hope this helps!


Screen tearing reappeared after updating form 19.10 to 20.04 (GeForce GTX 1050 Ti Mobile)

Question: I am using an MSI GL62M 7REX laptop which has a GeForce GTX 1050 Ti Mobile graphics card. When I was using Ubuntu 19.10, I was able to deal with screen tearing in the following way:

Similarly to this answer, I opened the terminal and typed sudo gedit /etc/default/grub which opened gedit with the following contents:

# If you change this file, run 'update-grub' afterwards to update
# /boot/grub/grub.cfg.
# For full documentation of the options in this file, see:
#   info -f grub -n 'Simple configuration'

GRUB_DEFAULT=0
GRUB_TIMEOUT_STYLE=hidden
GRUB_TIMEOUT=10
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
GRUB_CMDLINE_LINUX=""

# Uncomment to enable BadRAM filtering, modify to suit your needs
# This works with Linux (no patch required) and with any kernel that obtains
# the memory map information from GRUB (GNU Mach, kernel of FreeBSD ...)
#GRUB_BADRAM="0x01234567,0xfefefefe,0x89abcdef,0xefefefef"

# Uncomment to disable graphical terminal (grub-pc only)
#GRUB_TERMINAL=console

# The resolution used on graphical terminal
# note that you can use only modes which your graphic card supports via VBE
# you can see them in real GRUB with the command `vbeinfo'
#GRUB_GFXMODE=640x480

# Uncomment if you don't want GRUB to pass "root=UUID=xxx" parameter to Linux
#GRUB_DISABLE_LINUX_UUID=true

# Uncomment to disable generation of recovery mode menu entries
#GRUB_DISABLE_RECOVERY="true"

# Uncomment to get a beep at grub start
#GRUB_INIT_TUNE="480 440 1"

I edited GRUB_CMDLINE_LINUX_DEFAULT="quiet splash" to GRUB_CMDLINE_LINUX_DEFAULT="quiet splash nvidia-drm.modeset=1" and saved the file.
Typing nvidia-smi gave back the following details:

Thu May 14 12:39:03 2020
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 435.21       Driver Version: 435.21       CUDA Version: 10.1     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 105...  Off  | 00000000:01:00.0 Off |                  N/A |
| N/A   51C    P0    N/A /  N/A |    247MiB /  4042MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1180      G   /usr/lib/xorg/Xorg                            45MiB |
|    0      1717      G   /usr/lib/xorg/Xorg                           105MiB |
|    0      1972      G   /usr/bin/gnome-shell                          89MiB |
+-----------------------------------------------------------------------------+

Now I knew that the main version of my Nvidia driver was 435 which I needed for the next step.
According to this instruction (post #5), I created a .conf file in /etc/modprobe.d/ which contained the following line: options nvidia_435_drm modeset=1.
After that, I ran sudo update-initramfs -u and rebooted my machine.
sudo cat /sys/module/nvidia_drm/parameters/modeset then returned Y and the problem was fixed.

After my upgrade to Ubuntu 20.04, these options are still the same. The kernel parameter is still intact and the .conf file in /etc/modprobe.d/ still exists. Furthermore, the number of the Nvidia driver is still correct but screen tearing reoccurs.
Trying to edit the Nvidia X Server Settings does not help because the look like this:

This was the reason why I tried the other solution described here which worked for me.
What can I do to fix this problem using Ubuntu 20.04?
Answer: I was able to solve the problem by selecting the most recent driver 440 (the following picture is from this source; that is why there is a different GeForce GTX model displayed):

Then, I edited the .conf file by replacing options nvidia_435_drm modeset=1 with options nvidia_440_drm modeset=1 and restarted the computer.


JMeter: the same UUID between several samplers

Question: How can a Jmeter thread group with several HTTP requests uses the same UUID value per thread?
I've tried to create 'user defined variables' element with ${__UUID} and java preprocessor with vars.put("uuid", UUID.randomUUID().toString()); (independently)

but every http request in the same thread using its own UUID.
Answer: Move the java PreProcessor as the child of the first HTTP Request(start session) and then call it as ${uuid} in all requests to get only one UUID value.
Another option is without code: Add User Parameters as PreProcessor of the first HTTP Request(start session) with Name as uuid2 and Value ${__UUID()} and you can use ${uuid2} to get only one UUID value.
Comment: Yes, this is the solution. Just one addition from my side. There is one checkbox "Update Once per Iteration" which you have to check for this to work. This might have changed based on the jmeter version etc.
Answer: JMeter Variables are local and individual for each thread (see ThreadLocal concept for details) so in order to create a random GUID structure you need:

Execute this function only once (optional, but nice to have). For instance it can be done using If Controller with condition set to something like:
${__groovy(ctx.getThreadNum() == 0 && vars.getIteration() == 1)}

Make function execution result available to all JMeter Threads. There are multiple ways of doing it, the easiest is converting it to JMeter Property via setProperty() function
Refer to the generated GUID using __P() function as ${__P(uuid,)} where required

This way you will be able to access the same GUID value from different threads or even thread groups.
Demo:
Answer: you cannot reuse the generated ${__UUID}, but you can always generate it via JavaScript function (it allows to reuse the result):
${__javaScript(function s4(){return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);} s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();, var_for_reuse)}


Change one column's value during a select - Sql

Question: I have following query:
Select * from Students

which retrieves: Id, Name, Class, and School.
I want, no matter what the value of Class is, to just get back Class = 10. Is there a way to do this in sql query?
Comment: your table structure would be helpfull.
Answer: Just substitute 10 if you want 10 for each row
 Select Id, Name, 10 as class, School from Students

If you mean conditionally
 Select * from Students WHERE Class = 10

Answer: You can do
select id, name, '10' as class, School
from students
to get back a 10 in the class column regardless of what the actual stored class value is.


Has image been saved?

Question: I've written a function to determine whether an image file has been saved or not. It relies on a try / catch for the path name.
hasImageBeenSaved()

function hasImageBeenSaved()
{
    var n = app.activeDocument.name;
    try
    {
        var myPath = app.activeDocument.path;
        alert(myPath);
        return true;
    }
    catch(e)
    {
        alert(n + " has not been saved");
        return false;
    }
}

Scripting in Photoshop normally entails working with saved images or images that will get saved after being altered. Functionally the above is fine; but I'm sure there's a more elegant solution. Any ideas?
Answer: I found out a one liner
alert( app.activeDocument.saved);

However, under further investigation it doesn't take into account a newly created document.

Has image been saved?


JDBC prepared statement vs hibernate session transaction readonly operations

Question: I'm working on a project where there are a lot of readonly operations (like in select) written with the help of prepared statements but other operations are with hibernate transactions.
I know the reason of a transaction is because is somesort of failproof if you make multiple modifications to the database. So if one fails, there is a transaction rollback.
But I don't know what is the best to use for readonly operations: when should i use a prepared statement over a hibernate transactions and vice-versa ?
Answer: Prepared statements and transactions have different scopes.
You should use prepared statements to prevent SQL Injection and make your code more readable, secure and reusable.
You use transactions to controll transactionality (commit and rollbacks), set timeouts, isolation levels and lock modes.
Of course you should use both when necessary.
Maybe you find useful this links:
Transactions for read-only DB access?
Advantages of using prepared statements over normal mysqli statements?
Answer: I'm not exactly sure I agree with using raw JDBC PreparedStatement for read-only SELECT operations and delegate to Hibernate for everything else.  Hibernate is capable of supporting both native SQL queries along with read-only operations.
One of the biggest reasons to use Hibernate over raw JDBC is that you can take part in using the out-of-the-box first-level cache support.  This is great even for read-only operations where you may issue multiple select-clauses which may need to load the same relation or entity.
Additionally, you can also then take part in introducing a second-level cache provider.  Ehcache or Infinispan are great cache providers which allow Hibernate to store the query-cache and entity caches locally, allowing for faster result-set processing.
Beyond that, it also allows all code which generates queries to be a bit more consistent.  You always interact with Hibernate and choose whether to use raw native SQL or not.  You may even be able to move away from native SQL and just use HQL/JPQL too allowing the application to become less database dependent and more agnostic.


What to do when we see cross-posts from Stack Overflow?

Question: Periodically I see an exact duplicate that has been posted on Stack Overflow, and then here.
Should these be flagged as exact duplicates?
Comment: I have created a [filter](http://stackexchange.com/filters/22660/drupal-questions) to find duplicate questions asked on both the sites.
Answer: You can flag the question that has been asked on Stack Overflow, and report the link to the exact duplicate asked on Drupal Answers.


Core data fetching and getting an accurate object count

Question: I'm coding in iOS 6.1 and working with Core Data.
I have an entity; call it NextID.
When I establish my connection to Core data, the NextID.sqlite file is created when I do the addPersistentStoreWithType step.
At this point, I have an essentially empty database.
Then I create a fetch query and run it against the Entity and I get a fetchedResultsController back.
I count the objects held by the fetchedResultsController and get a zero, as I'd expect.
Then I create and initialize a new object for the NextID entity.
As a test, I count again with fetchedResultsController.count and get a zero again which is right, I think.
Then I save my context.
And then I test again with fetchedResultsController.count - and get a zero again.
Now I'm puzzled.
Then I read the following about the fetchedObjects:
"The results array reflects the in-memory state of managed objects in the controller's managed object context, not their state in the persistent store. The returned array does not, however, update as managed objects are inserted, modified, or deleted."
That seems like a contradictory statement to me.   "The results array reflects the in-memory state of managed objects in the controller's managed object context" and "The returned array does not, however, update as managed objects are inserted, modified, or deleted." seem to me to be at cross purposes.
But regardless, I'm thinking that if I want to get an accurate count when I do a fetchedResultsController.count, then I need to save and then re-fetch before I ask for an up-to-date count.
I'm also thinking, because of what I've read elsewhere, that this will not be an expensive thing to do as doing a fetch operation is not the same as actually loading all the objects fetched into memory because those physical loads into memory only happen as they are needed.
Am I on the right track here and thinking about these things in a reasonable manner?
Comment: possible duplicate of [core data: \[NSFetchedResultsController -fetchedObjects\], will this method reflect object change?](http://stackoverflow.com/questions/13391934/core-data-nsfetchedresultscontroller-fetchedobjects-will-this-method-reflec)
Answer: Going to drive a wooden stake through this one's heart.  I think my question is answered here.  Thanks, all.
Answer: use magical record if you are new to core data. its easy to integrate:
here are tutorials: http://ablfx.com/blog/article/2
http://yannickloriot.com/2012/03/magicalrecord-how-to-make-programming-with-core-data-pleasant/#sthash.GNErDSr8.8VBBav02.dpbs
Comment: MagicalRecord uses the same NSFetchedResultsController as a "plain" Core Data app, so this does not answer the question.
Answer: Edit:
What Gallymon said. Period.

What Gallymon said, and: the NSFetchedResultsController has delegate methods notifying you of new/updated/deleted items/sections. Those might either help you or confuse you even more (I am aiming for the first :) ).
Comment: The FRC delegate methods *are* mentioned in the link given by Gallymon  :-)


How do I check if my outlet's ground and neutral are connected correctly?

Question: When we moved to a new house I noticed a strangely wired up outlet:

For this outlet, I am really suspicious whether the grounding is messed up and mixed up with the Neutral.
Normally Neutral and the Live wires are the thicker ones right? If that is the case this outlet is violating that and the whole houses ground connections will have leaking voltage right?  When I measured some of the grounded equipment I saw the line's tester's light is turning on and saw some nonzero voltages(for example my PC case).
Apparently to save one outlet somebody directly used that outlet and extended a wire into the balcony which feeds the central heating boiler of the house. If the wiring is wrong how is the breaker not tripping? Isn't this extremely dangerous the boiler sending its current back from the ground path?
-- To be sure, how do I find out if I have a Neutral-Ground mix-up fault?
On a side note, will this bother other electronics?
For example I have a long 10M  HDMI cable monitor. This monitor loses sync everytime someone turns ON an on-wall lamp switch at our home. ( Loses sync and blanks for a few seconds and turns back on after ). Can this probable fault be a reason why this is happening?
For reference the German standard for electrical wiring (my country uses the same Page 14-15  of : [this IEC related document]
2  ):
Comment: you may be in a country that does not use a neutral ... an electrician from your country is very likely to read your question on the home improvement site
Comment: if the neutral and ground are bonded at the breaker panel, then that is exactly what a continuity buzzer will do
Comment: @KoolBreeze Your link is to a description of US wiring. OP's installation is not using US wiring colours so isn't there.
Comment: Neutral and ground are to connected together only at the main panel, nowhere else, not at outlets, switches, lights or sub panels.  I think Europe changed their colour scheme years ago, so you will need to see the old colours to see if black was used as neutral or ground, think bare or green with/out colour is the only colour for ground everywhere.
Comment: @NerdyNerdie You need to tell us which country this installation is in if you want help. Whilst the boiler cable uses modern IEC colours the fixed wiring doesn't use either new or old German wiring colours.
Comment: @NerdyNerdie But Neutral and Earth **must** be connected together, so it's not only normal, it's mandatory. It would be not at the socket but somewhere upstream in the electrical system. Are you sure it was a qualified electrician? Maybe you should get another.
Comment: It's quite unclear which wires are input to outlet, and which are output to somewhere else. What is the white cable with blue/brown/yellow-green?
Comment: @Justme  White cable goes to feed the boiler.  Yellow-Green is standard for its Ground connection.  Brown has to be its Live wire. Blue has to be Neutral.       Blue coming out from the wall, on the other hand, is Live - ( the color standard is different there)
Comment: @jsotola  Isn't this the electrical engineering section? I want to learn how one detects if the GND and Neutral is mixed up or not. Without breaking any more things of course. I don't want to directly switch those wires and try since I don't know the extent of the danger.   They both stand at 0V normally but since I don't have a GFCI breaker, this doesn't create a direct red-flag  that sth is connected wrong.  A GFCI breaker would definitely pop up if you mix GND and Neutral.
Comment: @jsotola  My country uses European standard.  Earlier I called an electrician . He just tried to make a connectivity check (with a multimeter) and said something somewhere is wrong in wiring of the house.   Connectivity check  everywhere on every outlet showed/shows GND and Neutral is shorted (Buzzer beeps).
Comment: you really need to provide a link to your country's electrical code so that it can be examined
Comment: This website might help you understand house wiring a bit better. Unless you already know more than this. http://hyperphysics.phy-astr.gsu.edu/hbase/electric/hsehld.html#:~:text=The%20standard%20U.S.%20household%20wiring,the%20other%20is%20swinging%20negative.
Comment: @NerdyNerdie You already knew something was wrong with the wiring of the house ***before*** you called in an electrician. You didn't know why. But you knew you had to be right about that fact given your observations and what you know to be reasonable expectations. The electrician merely confirmed your suspicions, which only means you are probably not insane since another conscious and hopefully more informed individual arrived at a similar conclusion. But you learned nothing new. A helpful answer will require specific details. You will need to open your hand. No other way. And even then...
Comment: @jsotola I found some IEC related document about the electrical code and appended it to the question .  But it seems shallow for my purposes.  Page 14-15 https://www.legrandgroup.com/sites/default/files/Documents_PDF_Legrand/Nos_solutions/Guide_International_standards_EN.pdf
Comment: @Justme  Let me ask this way: Even when the breaker is popped OFF, is this the case? (i.e., Earth and Neutral being bonded)
Comment: @KoolBreeze  I think this is US standard. How different this is from the German standard?  (240V receptacle and two hot wires is not the case in the German one.)   I can see the Neutral and Earth bond there.
Comment: @jsotola So even if Earth and Neutral are mixed up it is okay?  But then why does the standard even require the need to split Earth and GND - 2 wires instead of 1 everywhere?
Comment: I think only someone with very local knowledge will know if blue for hot, black for neutral and thinner black for ground is normal and correct for your location.  And you are more likely to get that by finding an electrician's forum in your local language and region.  In general, to tell if ground and neutral are mixed up .... if you have an RCD it should break ... unless the wires are mixed up there too.  If not, you have to disconnect wires at the panel and take voltage and continuity tests.
Comment: Having worked in a couple of countries I can tell you that the the electrons don't care what color the insulation is. Is a ground larger or smaller than a neutral ? Not in the smaller sizes they are usually the same in smaller cables as the sizes get larger the neutral a normally current carrying conductor can be larger than the ground but tithing says that it has to be larger being the same size s fine and if larger it would be silly. As for your cord to the boiler green/yellow is the ground or earth, blue is the neutral and brown is the hot but DIY may not have known and electrons don't care
Comment: A simple way to answer this is with a question. Do you have an RCD? If you do and are not tripping out when the boiler is running don't sweat it. In the UK I know color codes have changed over the years but if electrically correct who cares unless you want to update everything.
Comment: Do the two black wires and the accompanying blue go to another receptacle? Are the three wires on lower right coming from the panel (consumer unit)? Does the "boiler" plug into this receptacle? Perhaps the three wires going to upper left should all be reconnected: blue for neutral, heavier black for hot and smaller black for earth. Then makesure the next receptacle is wired consistently
Comment: @crip659 besides this not being the case in the OPs case, this statement is not quite correct. in old german installations (pre 73) you often have what is called "klassische nullung" where only one PEN is fed to each outlet etc.
Answer: Neutral is not Earth
They are completely different wires with completely different jobs.  Neutral is the normal everyday path for return current. Earth is a fault catcher, it only flows current when a fault of some kind is happening (and stops as soon as current trips the circuit breaker or RCD/GFCI).
Putting active daily current on earth is out of the question.
I see you using 'GND' to describe "Ground" as you call it, which tells me you've cut your teeth in small electronics.  That is a completely different world.  In electronics there is no proper earthing, and "GND" is simply the negative/Vss/backplane/common that is wired to everything as the common return loop... which would make it more like AC mains "neutral".
I gather you're from the Euro-system of wiring, which means, you call that thing EARTH.  That is a relief: over in North America we call it "Ground" which makes it much harder to RE-train electronics folks.   So keep calling it EARTH, or at least as "safety ground" as a different thing from GND.
I never call it GND, and I'm a Yankee.
Also unlike electronics, neutral is not "common" either.  In AC mains we are running the wires at hard ampacity limits all the time, which means, each live supply wire MUST have a dedicated neutral wire that returns only its current. We can't be careless and treat neutral like a common/backplane, because then, 1 neutral might end up returning current for 2-3 live wires, and it would be overloaded! Neutrals don't have circuit breakers - they don't need breakers if wired correctly.  (even on an RCBO, the neutral goes through the RCBO for RCD sensing, but does not have its own overcurrent detector).
Earths are yellow/green
Or straight green, or bare.  This is a world standard and is largely effective outside the old Soviet bloc.  Even the Yankees agree on it!
Very much unlike neutral, all earth wires should be tied together in all locations.  Since earth doesn't carry current except during fault conditions, we don't need to worry so much about thermal overloads from continuously carrying high current.  Service current is never on earth.
Find out about local legacy neutral and earth colors
I've never heard of a country where they used the same color for both neutral and earth at the same time.  However there have been changes.

Modern Euro/3-continent standard: Light blue for neutral, brown for live
Au, NZ and old UK standard: Black for neutral, red for live
Americas standard: White for neutral, black for live

So you will need to ask local experts for the old wire colors, and see if that explains what you see.
Prepare for the possibility that your old work was done before earthing became a standard, and there may be no earth at all.  Also, some locations used metal conduit for wires, and in that case the metal conduit is typically a valid earth!
Test the neutral by isolating it
Neutral has an equipotential bond with earth, either at the panel/consumer unit or on the power company side of it.  This is to keep voltages at a reasonable voltage and to suppress transformer leaks, lightning etc.  It also gives a current path for fault current to complete its circuit.    Do not treat this as a license to treat them as equal or to tie them together elsewhere!
Once you know which circuit you are dealing with, and can identify the circuit breaker that turns it off... if you are qualified to do so, you can go into the breaker panel (consumer unit).  From the circuit breaker you can identify the circuit's live wire, and then identify the circuit's neutral.  With the breaker off, you can disconnect the neutral from the breaker or neutral bar.
Now there should be no connection between neutral and earth.
With the circuit breaker off, live+neutral (together) should be isolated from earth.
You can also try energizing the circuit with neutral disconnected.  In that case, on a properly isolated circuit,

neutral will be isolated if all loads are off (a DVM will show a phantom voltage of a fraction of normal voltage).
if any loads are turned on, neutral will snap to line voltage (e.g. 230V) in all locations. That is one reason the neutral wire is insulated.
All loads should be inoperative. If you find a load that is working, it is bootlegging neutral from earth.

If you find yourself with an earth wire which is not plainly marked (e.g. it is the wrong color, or the former earth color is now a neutral color etc.), then wrap it with green or yellow/green electrical tape at the least.  That is not authorized by the electrical code, but it will make it clear what it's being used for.  Identify the wire carefully and always mark both ends of a wire the same, at the same time.
Comment: @JimStewart I prefer to isolate wires and test them individually and definitively.  There aren't shortcuts.
Comment: Harper would you agree with suggesting that this poster switch the two black wires "and see what happens"? Surely the heavier black wire is meant to be current carrying in normal operation the thicker one should be on the neutral contact.
Comment: Do the two black wires and the accompanying blue go to another receptacle? Are the three wires on lower right coming from the panel (consumer unit)? Does the "boiler" plug into this receptacle? Perhaps the three wires going to upper left should all be reconnected: blue for neutral, heavier black for hot and smaller black for earth. Then makesure the next receptacle is wired consistently.
Comment: Also, German domestic wiring is three-phase, and although brown is the commonest colour for "live", black and grey are also "live".
Answer: An RCD in circuit should have tripped, had neutral and ground got swapped in the outlet in question.
Here's a way to check for the swap.

Switch off the main incoming 2-pole circuit breaker. That would isolate the line and neutral from the house wiring.

Check for continuity between the neutral point of that outlet and earth point of another.

Then check for continuity between the earth point of that outlet and the neutral point of another.

A positive result in the above two checks would confirm the swap.
Comment: @Jim Stewart - Yes, Jim, in Europe, with single phase 240 V power, the main incoming 2-pole circuit breaker disconnects both the line and the neutral. The neutral and earth are not bonded at the consumer unit.
Comment: So in Europe with single phase 240 V power, the main incoming circuit breaker is 2-pole, i.e., it disconnects both the neutral and the hot from the incoming power lines? Are the neutral and the earth bonded together in the consumer unit or near to it? On which side of the main breaker are the neutral and earth bonded?
Comment: I have two breakers. One inside my house and the other one at the apartment entrance  (kWh counter for electricity bills).   Is the latter (external one) definitely the  "main incoming 2-pole circuit breaker" you described?   Can I confirm it is really "2-pole" by looking at it and finding part numbers/etc. ?
Comment: Hi NerdyNerdie, A 2-pole circuit breaker will have 2 incoming and 2 outgoing wires.
Comment: IMPORTANT: The OP appears to be in Germany.  Domestic wiring in Germany is _not_ "single phase 240V", it is _three_ phase.
Answer: NOTE THIS IS A WRONG ANSWER
As per comments, this tester does NOT show ground/neutral issues.   Leaving for future readers.

There are a bunch of devices available for testing a 3 pin power socket.
Often called receptacle/socket tester or less nice "idiot box/tester" they're a simple plug-in unit that shows if all three wires are correct from the front.  There's no more risk from using these than from plugging in a cable, compared to pushing probes into places hence the "idiot" term.
Example unit, though they come in many designs, they all have 3 neons and a chart to decode the lights.  Mine's round.
 US sockets

You'd need to test every wall-plate at a minimum, and every socket on every wall plate would be wise.  Fortunately a test is super quick.
The "idiot" name is imprecise - these are cheap, easy to use and interpret, and form a useful quick tool in the electrician/handiperson's toolbox.
Comment: But the question is whether or not the neutral and ground are mixed up, and these socket testers are completely useless for that purpose, right? If the ground and neutral _are_ mixed up, then these will say that the wiring is correct, even though it's not.
Comment: Is there a Euro wiring equivalent?
Comment: Agree with @TannerSwett - this tool will identify many types of incorrect wiring, but getting a reading of "correct" does not actually rule out certain types of bad wiring. You'll note the tool doesn't have a readout for "GRD/NEU REV", since it can't tell. If one suspects a ground/neutral swap, this tool won't help at all to confirm or refute that, and could actually mislead you into thinking the wiring is correct, since that's what the readout will say either way.
Comment: The picture is definitely for US (clearly NEMA 5-15 plug). I know UK is different, not sure how much different. A quick search on Amazon UK finds a *lot* of definite junk, quite a bit of US stuff and some maybes. For example, https://www.amazon.co.uk/Labgear-Socket-Tester-Electrical-Neutral/dp/B07PXN6C44/ref=sr_1_45?crid=YEPMAMJYU2SD&keywords=receptacle+tester&qid=1652761002&sprefix=receptacle+tester%2Caps%2C141&sr=8-45 looks like it may be actually safe and functional. But someone who knows UK stuff could probably confirm/deny.
Comment: @manassehkatz-Moving2Codidact https://www.screwfix.com/p/kewtech-kewcheck-103-13a-socket-tester-230v-ac/45558 is another candidate. Screwfix has physical stores, so more likely their products are properly licensed
Comment: @manassehkatz-Moving2Codidact very likely yes.  Mine's for NZ/Au sockets, pictured one seems to be US sockets.
Comment: @NuclearHoagie I was gonna argue, but you're totally right.   Should this answer be deleted as incorrect, or left to show it is wrong?  I've added a title now.
Answer: Blue = hot, Black = neutral
Appears it was used in Czechoslovakia (mid 1970's for unearthed fixed wiring) and never used anywhere else on the globe.
This standard seems to be messy. The contemporaneous standard for earthed fixed wiring included both:
Blue = hot, Brown = neutral, Black = earth
Black = hot, Blue = neutral, Green/Yellow = earth
There is no easy way to diagnose a swapped neutral and earth.

Plug in detectors are unable to detect neutral-earth swap.
Earth and neutral should be bonded on the house side of the disconnect switch. So opening this switch will not help to resolve a fault)

Two relatively non-intrusive tests:

If there is a RCB, RCBO, ELD on this circuit and it is not tripping then the wiring is ok. These detect either the balance between currents into hot and out of neutral, or the presence of a current on the earth.
If a clip on current meter is available then it may be possible at the switchboard to compare current in hot with current in neutral.

Other tests involve disconnecting wires at the switchboard and should be done by an electrician.


How do I get apt links to work with Google Chrome

Question: I was reading another question on ask-ubuntu, where I encountered an apt link. Intrigued, I clicked on it, expecting my browser to launch the software center, only to get a page saying "You don't seem to be running Ubuntu".
Browser: Google Chrome 12.0.742.0 dev
the link I clicked on apt.ubuntu.com/p/hardinfo
Thanks for the help.
Comment: That seems odd. When I click on an apt-link, I get a request from Google Chrome to run `xdg-open apt:packagename`. Doing so then asks me whether I want to install said package. (Same Chrome version)
Answer: What you need to do is to use Chromium not Chrome. This is because Chrome doesn't include Ubuntu in it's useragent but Chromium does.
The easiest way to do this and keep the dev channel, is to use the PPA.
Of course this isn't ideal, hopefully in the near future a new version of apt.ubuntu.com will be released that works with Chrome.
Comment: fluteflute, thanks for the clarification. I will stick with Google chrome for now, but at least I understand the problem. Thanks again
Comment: I would use Chromium if the tabs didn't make my system crash when I try to splice them into their own window. Google-chrome doesn't crash, or crash the entire system. :|


Computing the percentage of values in an array

Question: I have the following array:
[ratings] => Array
 (
      [0] => 3
      [1] => 3
      [2] => 2
      [3] => 3
      [4] => 3
      [5] => 1
      [6] => 3
      [7] => 4
      [8] => 5
 )

What would be the best and fastest way to get the the percentage of each rating. For example there are 9 ratings now, and 5 ratings of "3", so the percentage of rating "3" is 55.55%.
Comment: [array_count_values()](http://php.net/manual/en/function.array-count-values.php) and count() thats 90% of the work - go do the rest.
Comment: Wow, didn't know about array_count_values(). Excelent function! Thanks.
Answer: although he probably has something already, this is what I came up with.
<?php
$array = array(3,3,2,3,3,1,3,4,5);

function array_avg($array, $round=1){
    $num = count($array);
    return array_map(
        function($val) use ($num,$round){
            return array('count'=>$val,'avg'=>round($val/$num*100, $round));
        },
        array_count_values($array));
}

$avgs = array_avg($array);

/*
 * You can access any average/count like:
 * echo "The count of 3 is: {$avgs[3]['count']}";
 * echo "The average of 3 is: {$avgs[3]['avg']}";
 */

echo '
'.print_r($avgs,1).'
';

Output:
Array
(
    [3] => Array
        (
            [count] => 5
            [avg] => 55.6
        )

    [2] => Array
        (
            [count] => 1
            [avg] => 11.1
        )

    [1] => Array
        (
            [count] => 1
            [avg] => 11.1
        )

    [4] => Array
        (
            [count] => 1
            [avg] => 11.1
        )

    [5] => Array
        (
            [count] => 1
            [avg] => 11.1
        )
)

http://codepad.viper-7.com/yD9CQm
Comment: would it be hard to modify the function in order to return the percentage, and the count? For example, for rating "3", the percentage is 55.6 and the count is 5.
Comment: @Psyche updated. now returns an array for each number with the count and avg.
Answer: function findPercentage($r, $ratings){
    $arr = array_count_values($ratings);
    return $arr[$r]/count($ratings) * 100;
}

Comment: Could you provide some explanation for your code? You know this site is not really a coding contest, we try to help people here.
Answer: As commented, you can make use of the array_count_values and process with count with a simple iteration.
In my code-example I wrap this into a function of it's own:
$ratings = [3,3,2,3,3,1,3,4,5];

$percentages = function($ratings) {
    $total = count($ratings);
    $percentages = [];
    foreach(array_count_values($ratings) as $value => $count) {
        $percentages[$value] = $count / $total;
    }
    return $percentages;
};

print_r($percentages($ratings));

Output (Demo):
Array (
    [3] => 0.55555555555556
    [2] => 0.11111111111111
    [1] => 0.11111111111111
    [4] => 0.11111111111111
    [5] => 0.11111111111111
)

I hope this demonstrates it fairly well. And again (for the fun):
print_r($percentages(array_map('strval', $percentages($ratings))));

(array_count_values() can only count STRING and INTEGER values)
Output:
Array (
    [0.55555555555556] => 0.2
    [0.11111111111111] => 0.8
)

Answer: $avg = array_sum($a)/count($a)
in Javascript:
var a = [1,2,3,4,5,6];
var avg = a.reduce(function(a,b){ return a+b })/a.length;

Comment: ok, but where did the OP say anything about javascript? may as well give him the answer in Fortran
Comment: thought it can be useful ... Yes I can give it in Pascal, C, C++, C#, Perl and even in SmallTalk and Assembeler for at least 20 processors  and in SQL too :) no joke! do you think PHP solution is fine? If Yes vote up please, not down :)
Answer: // $ratings is your array

function findPercentage($r, $ratings){
$count = 0; // count number of particular ratings
    foreach ($ratings as $i){
        if ($i == $r) $count++;
}

return $count/count($ratings) * 100;

}

example:
echo findPercentages(3, $ratings);

Answer: $rating = array(3, 3, 5, 5, 3, 4);

$value = 0;
foreach ($rating as $i) {
    $value += $i;
}
$percentage = $value / count($rating);

echo $percentage;

==
UPDATE
I wrote small test:
$rating = array();

echo "create array".PHP_EOL;

for ($i = 0; $i < 100000; $i++) {
    $rating[] = rand(1, 5);
}

echo "foreach algorithm: ".PHP_EOL;
$time = microtime();

$value = 0;
foreach ($rating as $i) {
    $value += $i;
}
$percentage = $value / count($rating);

echo $percentage.PHP_EOL;
echo "time is ".(microtime() - $time).PHP_EOL;

echo "array_sum algorithm: ".PHP_EOL;
$time = microtime();

$avg = array_sum($rating)/count($rating);
echo "time is ".(microtime() - $time).PHP_EOL;

and result:
create array
foreach algorithm:
2.99924
time is 0.017117
array_sum algorithm:
time is 0.002819

Answer: use algorithm that wrote user @Reflective, use function array_sum


Why do designers not work remotely?

Question: This is something id like to try in the future.
But looking through job openings its not something you commonly see, if at all? Why is this?
Comment: It's not something I commonly see for any job position, at all. In my experience companies rather not have you work remotely in any position, but it can often be discussed.
Comment: I would argue it is pretty common in the tech industry. I've mainly seen it for developers and project managers more than anything. Developers especially it is pretty common. Stack Overflow is full of remote working jobs for developers.
Answer: You usually need to communicate a lot with the people involved with the product (devs, product owners). And working remotely makes it harder to quickly get feedback on your wireframes and ask questions.
Comment: In my opinion face-to-face always wins. I found a nice discussion on this on [designernews](https://www.designernews.co/stories/84421-why-would-you-want-to-work-remote-as-a-designer).
@JaneDoe1337 I think we are talking about full-time remote. If you just work remote 1d/week then you can postpone all the "communication-heavy" activities to your on-site days.
Comment: Working remotely does not make it harder to quickly get feedback on wire frames and ask questions. It does force you to be more careful about how you formulate questions. In principle, remote does make it easier to ignore your teammates' requests, but when management provides some kind of framework - eg by directing the project feedback via Github or Redmine issues or somewhere central for all to see vs just letting it all happen offline in Slack or in the office kitchen, then it becomes obvious if someone is not communicating. It's a communication problem, not a remote work problem.
Comment: In a world of slack, scrum, invision and video calls I don't find that a very good reason to not work remotely. I work remotely one day a week, like almost everyone on my team and we have no issues communicating at all.
Comment: I was thinking the same thing as JaneDoe1337. Could that not just be solved with good communication processes and the right tools and software?
Comment: @Nash personally I've never heard of full time remote unless you do freelancing so I assumed OP meant partially.
Answer: Most designers find remote work challenging in some way and a lot of companies hire just project-based or part-time for a remote position. I worked 10 years remote, in some cases even full-time, for 6 months+ collaborations.
For me was a natural choice because I wanted to stay in my city and I didn't find a job at the level I wanted to do design.
From experience, I can tell some reasons I liked more to work onsite at some point:

It is easier to "steal" some tricks and methods from colleagues if they are in the same room with you;
You need to have already experience in design and the ability to learn without help;
Some people aren't cut out for the remote life. If you're a people person, remote may not be for you. Sometimes it is really boring to communicate just in writing;
Some people are more creative when they work alone, some needs to be in teams, brainstorming together;
The company that hires you needs to have a remote culture and provide you the support you need to receive all the specs for the projects (tools, online meetings, methods, techniques);
Answer: First of all, full time remote-friendly jobs in general just aren't that common. Many remote employees weren't actually hired as such but transitioned or negotiated into it. A friend of mine has been doing it full time for six years now, five years after negotiating for 2 days a week and just building up trust.
There are many great companies that do hire full-time remote designers. InVision, Harvest, Automattic, SurveyMonkey, Zapier, Basecamp and others are very much remote-friendly but then those are companies that do many other things differently besides their policy of where people physically work. Stack Overflow I think is another.
Remote work means work performance has to be managed primarily as a function of individual output, something corporate America's legions of "peter principle" jobbers don't want.
Secondly, designer jobs in general are less common than developer jobs, at least in my experience. Even small enterprises seem to have developers up the yin-yang and few or no designers.
A recent Jeff Sauro article suggests a lopsided ratio of like 20:1 developers to designers:

(Tangent - as you can imagine, finding a remote user researcher position is like finding a needle in a haystack.)
In sum: I don't think there's a remote- specific phenomenon here.
Answer: It's an interesting question. In my experience at startups, large corporates and freelance, being in the office is preferable, in part because random conversations can lead to solutions or other directions for a specific problem. Also, not everyone is great at typing, and services like Skype/Zoom can be exercises in frustration when they don't work properly (bad wifi connection on either end, etc.). I just don't believe that email/chat/video are adequate substitutions for face-to-face discussion. But of course the occasional WFH day shouldn't be too much of a problem.
That said, and to kind of counter my own argument, Invision (www.invisionapp.com) employees are almost entirely remote. I say "kind of counter" because I'm not sure that their product delivery has been particularly timely or of super high quality recently...
Answer: Speaking from experience, the prep time needed for team design activities (ideation, synthesis, etc) is much higher than for activities where everyone is there on location. It is true that tools are getting better, but everyone has to be trained on using those tools. Once everyone is on the same page as far as tools and prep work, I really don't see why remote design should not be utilized more often. People also say that remote office workers feel more lonely due to not being on location, but I say thats BS. I work in the office with cube mates, and hardly anyone chats with each other. I think it is the culture and people, and not being on location that determines whether remote work actually works.

Why do designers not work remotely?


How to implement Restful design to request webpage stored for magnolia

Question: I have a question concerning how to implement restful design to request webpage stored in magnolia JCR.
For example,
I have a list page called itemList [www.example.com/itemList], which contains a list of item.
And i have a item page [www.example.com/itemList/item/1], which is a child page of itemList (which can be seen in the PAGES app).
If i want to get item with ID no.1, just like other restful design, just use URL [www.example.com/itemList/item/1], and it will return whole page of item with item no.1 data (which i need to store the ID and pass it to the JAVA custom module in template script to get the data)
But here is the problem,
as i study in the magnolia documentation, like
https://documentation.magnolia-cms.com/display/DOCS57/How+to+create+a+custom+Java-based+REST+endpoint
it just tell about create rest endpoint and get the JSON data back as for manuplation.
And i got stuck at how to achieve my goal, may i have some suggestions?
Thanks a lot for any help. ORZ
Answer: Actually in Magnolia you don't need to create a custom endpoint for that, you can use the pre-defined ones which are sufficient to achieve what you want. Have a look  at https://documentation.magnolia-cms.com/display/DOCS57/REST+API
Let me know if that covers what you need or any other extra questions that should you have.
Hope that helps,
Cheers,


Are we using American or British English for tag wikis?

Question: As a Brit my natural tendency is obviously to go with British English but I was just editing the Webform tag excerpt and I was torn between using "personalised", or "personalized". The latter is already included in the main tag wiki so I didn't know whether to change both to British, change both to American, or leave the one that's already there alone and updated just the excerpt to use British English.
I know it's of very little importance but are there any official Stack Exchange guidelines on this?
Comment: Doesn't this question also apply to questions, answers, comments, chats and what not? Consider editing your question accordingly if you think it does. and by the way, "as somebody born in the land where Drupal was born", I'm not sure which one to use, but I'd like to see some official statement about it. My best bet is like this: the SE family of site is USA "inspired" (sometimes I get chocked by some of its rules, but you accept them, try to avoid them or otherwise you better quit), so it seems to me that its language should match that also, no?
Answer: I didn't find any official reference on Meta Stack Overflow, but in this answer to What's the deal with retagging from UK English to US English, Marc Gravell says:

A related issue is "correcting" the language in the title/body. In the case of the question in hand, the UK term seems entirely correct. In general, I have to concede (and I'm UK) that the US mis-spellings have become the standard. Much like the accidental referer/referrer. We're stuck with color etc, and too many "z"s to be helpful, but such is life ;-p

There are other differences between American and British English, such as the usage of punctuation in quotes.
I would say that it is preferable being constant in the used spelling, and as for the what noted from Marc Gravell, I would choose the American English spelling.
Comment: Yep, you're right. Apparently the standard is to use US-English for tags. For questions/answers there is no standard as such. This is endorsed by Jeff Atwood so I think is the definitive answer http://meta.stackexchange.com/questions/23869/what-should-the-standard-spelling-be-british-or-us


Boats keep breaking in my canal

Question: I have a canal that is 4 wide, and 1 block deep.  The entire canal is made of source blocks and completely level.  Unfortunately my boats keep breaking after only travelling a 50-60 blocks when I try to navigate the canal, and I don't really understand why.
Does my canal need to be deeper, wider?  What can I do to keep boats from breaking constantly?
Comment: That's odd; assuming there aren't any blocks jutting out and all of the water blocks are sources, it should be fine. Maybe upload your save or a video of you traveling through it?
Comment: I don't even bother with boats.  They seem pretty buggy right now.
Comment: Are you hitting the side at all, or does it just break when you're in the middle?
Comment: (Edit) Woops, Nick T beat me to it...
Comment: @Kevin Y, The break even when I am in the middle.  I suspect, but have no confirmation, that it may have something to do with latency and SMP.
Comment: Ahh, SMP is probably to blame then. I tried setting up an [EATS Road](http://gaming.stackexchange.com/questions/19929/what-is-the-best-way-to-connect-islands-together-in-minecraft/19993#19993) on an SMP server and the boats keep breaking as well.
Comment: Controlling the boats feels ... weird
Answer: You have mentioned that you are on SMP so my guess is that you are lagging to the point where you bump into a wall.
A possible solution would to make the walls wider as boats are extremely fragile.
Boats are also pushed by water currents so it might keep the boat from bumping if you make water currents so I suggest that you make water flowing in the direction you want to travel rather than just creating still water everywhere.

Boats keep breaking in my canal


Loading DataTable Into ReportViewer

Question: I have a datatable that I am filling from a sql adapter.  I am able to get it to successfully show in a datagridview but when I try to do a reportviewer it doesn't work correctly.
<code>DataTable dt = new DataTable();
dt.TableName = "SwipeReport";
da.Fill(dt);

reportViewer1.Reset();
reportViewer1.ProcessingMode = ProcessingMode.Local;
reportViewer1.LocalReport.ReportEmbeddedResource = "POC1.SwipeReport.rdlc";
reportViewer1.LocalReport.DataSources.Clear();
reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("SwipeReport", dt));
reportViewer1.RefreshReport();
</code>
I don't believe I'm setting up the report embedded resource correctly as I get a "report is not specified" when it's supposed to fill the reportviewer window. Did I implement this correctly?
Answer: Hope this helps
<code>        // create a new report from the created CrystalReport
        GeneralSupportRpt myDataReport = new GeneralSupportRpt();

        // set the data source of the report
        myDataReport.SetDataSource(dataTable);

        // set the report source of the created "crystalReportViewer"
        // component to the created report

        ReportViewer.ReportSource = myDataReport;
</code>
Comment: Thanks for the help!

Loading DataTable Into ReportViewer


Substring between two different characters?

Question: I'm looking for a way to get a substring in php. Given string is:
"abc/def/ghi/name.extension"
I only want to have 'name', and the number of forward slashes is not known and not the same number either. Tried it with substring, but I get stuck in the elimination of the /
Anyone an idea how to solve this?
Help is greatly appreciated!
Comment: STOP answering 5 is enough only one of them is any good
Comment: Duplicate of https://stackoverflow.com/q/2183486/134824
Comment: This should be closed as a duplicate anyway rather than answering something that has already been answered.
Answer: You can use pathinfo:
$str = "abc/def/ghi/name.extension";
$name = \pathinfo( $str, \PATHINFO_FILENAME );

Answer: Try this. First split the string into an array with explode () and then split the last element by the dot.
$a = 'abc/def/ghi/name.extension';
$b = explode ('/', $a);
$b = $b[count ($b) - 1];
$c = explode ('.', $b)[0];

Answer: You can try this for filename.
$filename = pathinfo("abc/def/ghi/name.extension", PATHINFO_FILENAME);
echo $filename;

and this for file extension.
$ext = pathinfo("abc/def/ghi/name.extension", PATHINFO_EXTENSION);
echo $ext;


Is this onClick JavaScript event is not accepting in POST section?

Question: I am writing a blog post on my WordPress website and I need show following HTML code:
<button type="button" onclick="getData()">Get Data</button>

Now, if I press the preview button then it's showing me Post Not Found Error message. Very strange? If I change the onClick to something else then it's working. So I think the issues on the onClick event.
If you can then try to post above HTML code in your WordPres Blog Post editor and then press preview button :(
Can you tell me how can I solve it?
Thank You.
Updated:
Maybe I can't explain my question properly :(
I have a WordPress blog website where I am writing a tutorial about HMTL and CSS. You know if you write a tutorial blog you need to show some textual code to the user, right?
Yes, I am doing the same thing. I need to write above HMTL code as textual version but when I press the preview button it's showing me Not Found Error Message.
Note: It's not an actual JS function.
I have another code that's showing perfectly on the blog page. Check this image.
Comment: Please provide a [mcve].
Comment: Please add code of fruntion getData
Comment: What does the function getData()? Edit ur post so we can help you out
Comment: I don't think that I need to write more code because I just want to write a Blog Post using WordPress where I need to write an HTML code. So when I write that HTML it's showing me Not Found Error Message on the front-end. That's I am requesting you to try the above code in your WordPress Blog Post then you can understand. I have tried another WP site too :(
Answer: You can do this by this way please check below code example I have given.

$(document).ready(function(){
  $("#getData").click(function(){
    //Do some action
  });
});

<button type="button" id="getData">Get Data</button>
Comment: Maybe, I am wrong and I can not explain my question properly :( I am writing a blog post about HTML and JavaScript in my WordPress Tutorial Blog where I need to write the above HTML code in the POST Editor Box. Not an actual function.
Comment: So in this case you can add your html and JS code in blog's "Text" section not "Visual" section.
I hope this will solve your issue.
Comment: Get Data
Comment: Add this code in your wordpress page this will show button code instead of actual button.
Comment: I write that code in visual section but still same error :(
Comment: Not the visual section you have to write that into "Text" section of wordpress editor
Comment: Unfortunately, Same error. If you have a WordPress website then can you try it by yourself ?
Comment: https://www.isitwp.com/how-to-display-code-in-wordpress-posts-and-pages/
Comment: I am using this plugin: Crayon Syntax Highlighter to post the code but no luck :(
Comment: I think above solutions should work. Provide credentials if you can so I can check.
Comment: let me disabled few plugins first.


A box with 3 red balls and 2 white balls. 3 balls taken randomly with replacement,

Question: A box containing 3 red balls and 2 white balls. A ball is taken randomly and with replacement. This is done 3 times.

What is the probability that exactly one red ball is obtained?
Probability at least 1 red ball is obtained?

Attempt
For the first part, the possibilities are: red ball at 1st draw, red ball at 2nd draw, or red ball at 3rd draw. The probabiity for each is $p = \frac{3}{5} \frac{2}{5} \frac{2}{5}$, so the answer is $3 \times p$.
For the second part, possibilities are: 1 red ball taken, 2 red balls taken, or 3 red balls taken. probability of 2 red balls taken is: $3 \times \frac{3}{5} \frac{3}{5} \frac{2}{5}$. So answer is:
$$ \left( 3 \times \frac{3}{5} \frac{2}{5} \frac{2}{5} \right) + \left( 3 \times \frac{3}{5} \frac{3}{5} \frac{2}{5} \right) + \frac{3}{5}\frac{3}{5}\frac{3}{5} $$
Comment: Yes.  The second can also be calculated as the probability not all samples are white, i.e. $1- \frac{2}{5} \frac{2}{5} \frac{2}{5}$
Answer: Both parts are correct. As regards the second one, it is  easier to evaluate the complement:  the probability that at least one red ball is obtained is $1$ minus the probability that all the three balls are white, namely
$$1-\left(\frac{2}{5}\right)^3.$$


Program that compresses and decompresses a string in Java

Question: I need this code to compress and decompress a string given by the user, to compress the user will type either "java compression -c" or just "java compression". To decompress, it will be "java compression -d". Any help would be appreciated. It will now compile and run; however, when you type in the string it will only print out compress and not the compressed string.
import java.util.*;
public class practice
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        String originalString = scan.nextLine();
        String compressedString = "";
        int index = 0;
        int numReps = 0;
        char nextChar = ' ';
        if (args.length==0 || args[0].equals("-c"))
        {
            System.out.println("compress");
            String s = scan.next();
            compress(originalString);
            System.out.println(compressedString);
        }
        else if (args[0].equals("-d"))
        {
            System.out.println("decompress");
            decompress(compressedString);
        }
        else
        {
            System.out.println("Error! Unknown mode.");
        }

    }

    public static void compress(String originalString)
    {
        int index = 0;
        int numReps = 0;
        char nextChar = ' ';
        while (index < originalString.length())
        {
            numReps = 0;
            char c = originalString.charAt(index);
            if (!Character.isDigit(c))
            {
                nextChar = c;
                index++;
            }
            else
            {
                while (Character.isDigit(c))
                {
                    int temp = Integer.parseInt(""+c);
                    numReps = temp;
                    index++;
                    if (index >= originalString.length()) break;
                    c = originalString.charAt(index);
                }
                for (int i =0; i<numReps; i++)
                {
                    System.out.println(nextChar);
                }
            }
        }
    }

    public static void decompress(String compressedString)
    {
        int index = 0;
        int numReps = 0;
        char nextChar = ' ';

        while (index < compressedString.length())
        {
            numReps = 0;
            char c = compressedString.charAt(index);
            if (!Character.isDigit(c))
            {
                nextChar = c;
                index++;
            }
            else
            {
                while (Character.isDigit(c))
                {
                    int temp = Integer.parseInt(""+c);
                    numReps = (numReps*10) + temp;
                    index++;
                    if (index >= compressedString.length()) break;
                    c = compressedString.charAt(index);
                }
                for (int i =0; i<numReps; i++)
                {
                    System.out.println(nextChar);
                }
            }
        }
    }
}

Comment: Are you getting an error. If yes, show us the error
Comment: BTW any reason you are ending `while` loops in your code like here `while (index < input.length());`
Comment: @Prateek That's how my tutor was telling me to do it.(He couldn't figure this out either.) Are the extra () after length not needed?
Comment: Depends on what `input` is. If it is an array then you have to use `.length` because length is a property of array; but if it is `String` then use `length()` as `length()` is a method of `String` Class
Comment: @Prateek I changed some stuff in the code, does this look better?
Comment: @Prateek It compiles now, but I get the error message listed above.
Comment: Read accepted solution to this question http://stackoverflow.com/questions/7485670/error-could-not-find-or-load-main-class
Comment: (1) Don't add the `.java` extension when you're running a Java program.  (2) Spell `practice` correctly.
Comment: @Prateek I don't know what a classpath is
Comment: @gdhc Then read about it
Comment: @gdhc21 Which IDE are you using - might be time to learn about debuggers...
Answer: You have forgotten the type argument for your method definitions:
public static void decompress(compressedString)

Should be
public static void decompress(String compressedString)

Or even better
public static void decompress(final String compressedString)

Comment: What's the difference between the two? Also, can you see anything else wrong with the program?
Comment: @gdhc21 `final` declares the method parameter immutable; it's just good practice.
Answer: There are two things going wrong in your code(As far as I can see):-

public static void decompress(compressedString) should actually be public static void decompress(**String** compressedString). You have to tell the method that the argument it is going to receive is of String type.
In your compress and decompress methods you have while (index < input.length());. Check ; at the end. Do you really want that. You will never execute the while loop because you are terminating it before it even begins.


Selenium find specific link out of multiple same named links

Question: so the situation is I have a bunch of posts in a column with a message and a delete link next to each message (the message and link share an element). I want to be able to match the text of the message with a predetermined text, then have Selenium click the delete link next to that post's message. Is this possible?

Test message
    Edit Delete

Delete this message
    Edit Delete

The number behind the edit and delete in the link is like an id for that message
Comment: Please add the HTML.  What you're describing is likely very possible using xpath.
Comment: Hi, and welcome to Stack overflow. As @Richard has pointed out - it's hard to help you without you giving us some representative HTML for us to look at. So if you can - please edit your question and give us just a little more to work with. Otherwise we'll be forced to give you an equally vague answer, like "just choose the right one with xpath" ;) Here's a guide to how to write a good example case http://stackoverflow.com/help/mcve
Answer: That sounds pretty much possible.
Your post seems to look like
<Element>
    <Message> some message text </Message>
    <DeleteLink/>
</Element>

So, you would simply have to loop over each of the posts, match the message text, and click the delete link if a match is found.
Answer: As bit said, you can loop over each of the posts doing :
List<WebElement> list = driver.findElements(By.cssSelector(".element .message"));

for(int i = 0 ; i< list.size() ; i++){
    String message = list.get(i).getText();
    if(message.contains("whatever_you_want"){
        // Here you click on the corresponding delete link
        driver.findElements(By.cssSelector(".element .deleteLink")).get(i).click();
    }
}

Note that as I don't know how your HTML looks like, I've taken class names for css Selectors, based on bit answer


How to determine the Mock and injectMock objects in mockito?

Question: I am beginner with Mockito  framework, and i have some problems in determining the mocked and injected mocks objects, Actually I have the following structure in my project.
//WebService Interface

Interface WebService{
    @Gateway(...)
    public x call1(parameters);
}

//Class that implements another interface

Class A implements interfaceA{

@Autowired
WebService WS;

    public void M1(){
    .....
        WS.call1(parameters);
    .....
    }

}

//Test Class
@Mock
@Autowired
WebService WS;

@InjectMock
@Autowired
A a;

@Before
setup(){
    MockitoAnnotations.initMocks(this);
}

@Test
@Rollback(true)
@Transactional
public void Test() {

    when(WS.call1(parameters)).thenReturn(x);
    actualResult = a.M1();
    assertNotNull(actualResult);
    verify(WS, Mockito.times(1)).call1(parameters);
}

Are the Mocked and injected mock objects chosen correctly?
And if yes, i keep getting this exception message:
Wanted but not invoked:
WS.call1(
    ........
);
Actually, there were zero interactions with this mock.
Answer: You are using @Mock and @Autowired together. This doesn't make sense. You either mock or autowire your beans. Remove Autowiring
@Mock
WebService WS;

@InjectMock
A a;


Are there any open source OAuth 2 providers/servers for internal use

Question: I really want to host my own private OAuth 2 server/provider for internal use.  I would perfer an open source solution.
I can't seem to find any.  Either I am trying to do something dumb or I am not looking in the right place...
Answer: oauth2-php


Problem with authentication in REST WCF

Question: I have developed REST WCF and set binding following way in web.config
<bindings>
  <webHttpBinding>
    <binding name="secureBasic">
      <security mode="TransportCredentialOnly">
        <transport clientCredentialType="None" />
      </security>
    </binding>
  </webHttpBinding>
</bindings>

<serviceBehaviors>
    <behavior name="ServiceBehaviour" >
      <serviceCredentials>
        <userNameAuthentication customUserNamePasswordValidatorType="RestService.CustomUsernamePasswordValidator, RestService"
                            userNamePasswordValidationMode="Custom" />
      </serviceCredentials>
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>

  </serviceBehaviors>

And in CustomUsernamePasswordValidator.cs file i have authenticate user by following way
namespace RestService
{
public class CustomUsernamePasswordValidator : UserNamePasswordValidator
{
    public override void Validate(string userName, string password)
    {
        if (!AuthenticateUser(userName, password))
            throw new SecurityTokenValidationException("Invalid Username or Password");
    }

    private bool AuthenticateUser(string userName, string password)
    {
        if (userName == "myaddon" && password == "mypassword")
        {
            return true;
        }
        else
            return false;
    }
}
}

Now problem is that it is running nice when i will use this service from same project but confused that why this call would not occurred for validation?
Also when i test my heroku manifest addon file from ruby commnad propmpt it give me error of
Failed Authentication !! I think this is issue of my REST WCF Application.
Please anyone can help me to solve this issue if anyone know very well about WCF and authentication.
Thanks
Arun.
Comment: Do you get any error message? You should perhaps change your password after posting it here :)
Comment: Authentication failed in Ruby command prompt.. Thanks for your suggestion.
Comment: Please make your question title more informative: http://meta.stackexchange.com/questions/10647/writing-good-titles/10648#10648
Answer: Finally i have handle custom authentication using WebOperationContext directly and skip the Web.Config settings.

Problem with authentication in REST WCF


Doubled form validation button (iOS)

Question: I have asked myself this question a few times lately.
Should I put a validation button at the right-hand corner of the header and another at the bottom of the form ?
The right-hand button is useful when the keyboard is open, but is not very visible and does not give the impression of a principal button. While the bottom button is pretty clear and reminds of a website interface, but  is not visible while the keyboard is open.
I often see both cases.
So, is it really disturbing to put two confirmation button ? Or should I make a choice taking into account the amount of form fields that open the keyboard ?
Thanks you by advances.
Answer: I wouldn't recommend using the same button twice in a layout. Adapt to the platform (iOS in this case) common pattern if there is no preference.
Don't make the user think. When some of your users see both buttons it will create them confusion "Is this button the same one as the other? Do both perform the same action?" Even if they ignore these doubts or are sure of the answer and continue you should try to avoid the question in the first place.

Doubled form validation button (iOS)


Cross project Endpoint access - GCP

Question: Currently I have 2 projects
Project A
- App engine is deployed with open api Endpoint.
I have able to access endpoint with the service account created in project A
Open api's
<code>    security:
  - google_id_token: []
  - api_key: []

securityDefinitions:
  # This section configures basic authentication with an API key.
  api_key:
    type: "apiKey"
    name: "key"
    in: "query"
      google_id_token:
        authorizationUrl: ""
        flow: "implicit"
        type: "oauth2"
        x-google-issuer: "https://accounts.google.com"
        x-google-jwks_uri: "https://www.googleapis.com/oauth2/v3/certs"
</code>
Issue is when i am trying to sing in Project B service account to use project A endpoint
Error:
<code> "Permission iam.serviceAccounts.signBlob is required to perform this operation on service account"
</code>
And i am not able to find any role related to "singBlob"
Answer: In order to sign data with IAM, the service account passed to the API needs to have certain permissions. When obtaining this error you need to go to the IAM and admin page of the GCP console, and assign the

Service account token creator role

to the service account in question.

Cross project Endpoint access - GCP


If e.value = null or blank then leave blank

Question:  var timestamp = e.values[0];
  var recipientName = e.values[1];
  var firstLineOfAddress  = e.values [2];
  var secondLineOfAddress = e.values[3];
  var thirdLineOfAddress = e.values[4];
  var postcode = e.values [5];
  var recipientEmail = e.values[6];
  var todaysDate = e.values[7];
  var invoicenNumber = e.values[8];
  var dueDate = e.values[9];
  var item1Description  = e.values [10];
  var item1Qty = e.values [11];
  var item1UnitPrice  = e.values [12];
  var item1Amount = e.values[13];

  var templateFile = DriveApp.getFileById("1VjJI3VUNSJDQuv8NsgSfSugIfi3c_ev4cGpbk5_LQ3I");
  var templateFolder = DriveApp.getFolderById("1MsmTVhosVz0S4Nquz2qMr-SZtYZYyV9S");

  var copy = templateFile.makeCopy(recipientName, templateFolder);
  var doc = DocumentApp.openById(copy.getId());

  var body = doc.getBody();

  body.replaceText("{{RECIPIENT NAME}}", recipientName);
  body.replaceText("{{FIRST LINE OF ADDRESS}}", firstLineOfAddress);
  body.replaceText("{{SECOND LINE OF ADDRESS}}", secondLineOfAddress);
  body.replaceText("{{THIRD  LINE OF ADDRESS}}", thirdLineOfAddress);
  body.replaceText("{{Postcode}}",postcode);
  body.replaceText("{{EMAIL}}",recipientEmail);
  body.replaceText("{{DATE}}",todaysDate);
  body.replaceText("{{REF}}", invoicenNumber);
  body.replaceText("{{DUEDATE}}", dueDate);
  body.replaceText("{{desc1}}", item1Description);
  body.replaceText("{{qty1}}", item1Qty);
  body.replaceText("{{unitprice1}}", item1UnitPrice);
  body.replaceText("{{amount1}}", item1Amount)

  doc.saveAndClose();

}

Im still learning googleappscript/java so apologies for sounding dumb. Im using a form to produce a invoice however I would like the variable of e.values[10] to be able to be cleared from the doc it produces if left blank.
So if e.value is blank then it body.replace text should replace it with nothing. If e.value is filled in then body.replace text should fill in with the appropriate response.
Any ideas how I can do this?
Comment: add your code into an if statement? if e.value not blank, then execute these following codes?
Answer: Each submission in form always contains timestamp. So when a user leave a question in blank, the value of it in e.values is just empty. It will produce something like this: [3/4/2022 5:50:53, , , , , , , , , , , , ].
Empty values works in body.replaceText() and not produce error. Hence you don't need to change anything in your code.
In case you have null value in your e.values, which can be done by editing the content of e.values, just append a ||'' next to the replacement string.
Your code should look like this:
body.replaceText("{{RECIPIENT NAME}}", recipientName||'');
body.replaceText("{{FIRST LINE OF ADDRESS}}", firstLineOfAddress||'');
body.replaceText("{{SECOND LINE OF ADDRESS}}", secondLineOfAddress||'');
body.replaceText("{{THIRD  LINE OF ADDRESS}}", thirdLineOfAddress||'');
body.replaceText("{{Postcode}}",postcode||'');
body.replaceText("{{EMAIL}}",recipientEmail||'');
body.replaceText("{{DATE}}",todaysDate||'');
body.replaceText("{{REF}}", invoicenNumber||'');
body.replaceText("{{DUEDATE}}", dueDate||'');
body.replaceText("{{desc1}}", item1Description||'');
body.replaceText("{{qty1}}", item1Qty||'');
body.replaceText("{{unitprice1}}", item1UnitPrice||'');
body.replaceText("{{amount1}}", item1Amount||'')


Kotlin http4k : how to get a json field from the body of a Response?

Question: Below is shown the body of a Response of an http4k JavaHttpClient :
    '{"Hash":"QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH","Size":0,"CumulativeSize":6,"Blocks":0,"Type":"file"}
Which Kotlin module can be used to extract the values of the Fields "Hash" "Size" "Blocks" "Type" ?
Answer: You need to add one of the supported JSON modules:
<code>// Argo:
implementation group: "org.http4k", name: "http4k-format-argo", version: "188.8.131.52"

// Gson:
implementation group: "org.http4k", name: "http4k-format-gson", version: "188.8.131.52"

// Jackson:
implementation group: "org.http4k", name: "http4k-format-jackson", version: "22.214.171.124"

// Klaxon:
implementation group: "org.http4k", name: "http4k-format-klaxon", version: "220.127.116.11"

// Moshi:
implementation group: "org.http4k", name: "http4k-format-moshi", version: "22.214.171.124"

// KotlinX Serialization:
implementation group: "org.http4k", name: "http4k-format-kotlinx-serialization", version: "22.214.171.124"
</code>
Then you could extract the fields in a similar way:
<code>import org.http4k.core.Response
import org.http4k.core.Status
import org.http4k.format.Jackson.asJsonObject

val body = """
{"Hash":"QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH","Size":0,"CumulativeSize":6,"Blocks":0,"Type":"file"}
""".trimIndent()

val response = Response(Status.OK).body(body)

response.bodyString().asJsonObject().let {
    require(it.get("Hash").textValue() == "QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH")
    require(it.get("Size").intValue() == 0)
    require(it.get("CumulativeSize").intValue() == 6)
    require(it.get("Blocks").intValue() == 0)
    require(it.get("Type").textValue() == "file")

    println(it.get("Hash").textValue())
}
</code>
Some documentation is available here: https://www.http4k.org/api/org.http4k.format/-json/
Answer: Use Klaxon
build.gradle.kts :
<code>   implementation("com.beust:klaxon:5.0.1")
</code>
kotlin module :
<code>   import com.beust.klaxon.Klaxon
   data class MyData(val name: String)

   val result = Klaxon().parse<MyData>("""
       { "name": "John Doe",}
   """)
  val name = result?.name
</code>
gives "John Doe"


"Coming Soon" error

Question: I recently got MCSM for the PS4. Upon attempting to play Episode 2, it shows a message Coming Soon on it, despite Episode 2 existing for quite some time now. Upon going to Episodes, and trying to download, it says Purchased & Coming Soon. How do I fix it? The game is at it's latest version. Will I need an MCSM account to be able to fix it?
Comment: Have you tried reinstalling the game? it may just need some kind of download, or something failed
Comment: @dakre18 I could try. But I would like to keep that to a worst case, since it takes a long time. Are there any other suggestions that you could have?
Comment: Not off the top of my head, but that's why I asked instead of put it as an answer.
Comment: @dakre18 Ok. I might just go with that redownload and I will report back once I can
Comment: [This](https://www.youtube.com/watch?v=zONnsUXO6jA) was what you're talking about right?
Comment: Did you play Episode 1?
Answer: Did you complete Episode 1? As Telltale says, you need to complete The Order of the Stone so you can play Episode 2. If that doesn't work, try the following:

Reinstall the game.
Get a new disk and play the game (You won't start all over again. The progress is stored in the system of your PlayStation, not the disk. The disk is only for playing the game, not storing the data. It would've been more of a problem is data is stored inside the disk).
Log in (or sign up if you don't have an account) to Telltale if you haven't. This may cause a problem with the Episodes.
Turn off the game and PS4 and then return it on and play the game.

Okay now if those don't work, go to the Telltale website and ask them about the issues you have in support. They will work on the bug or give you a solution I don't have: https://www.telltalegames.com/community/categories/support
Answer: I had this problem but on PS3 turned out it was a region free disc but was still an United States copy (I'm in uk). I had to create a new psn account and set this one to US as location this then let me download the episodes 2-5 through the main menu of the game, then installed via PlayStation 3 home screen then changed back to my regular PSN account started story mode and they where there installed to play, I also deleted all my previous update and game save files before starting story mode on my US psn account not sure if this was necessary or not, I determined the disc region by its age rating dirrferent style to uk, hope this helps took all day to figure out

"Coming Soon" error