text:
Q: Is initrd.img (grub's "Loading initial ramdisk ...") slowing down my boot? I'm on an SSD where file fragmentation shouldn't matter that much anyway but I noticed "loading initial ramdisk ..." message in grub is taking longer that I think it should. It lasts about 7 seconds before Plymouth runs. Plymouth itself only takes about 3 seconds (it would be nice if it started sooner and lasted longer though). Then lightdm / greeter screen comes up over a 2 to 3 seconds.
So I did a little experimenting and ran filefrag -v /boot/init* and noticed my kernel 4.4.0-53 seems overly fragmented:
File size of /boot/initrd.img-4.4.0-53-generic is 49027703 (11970 blocks of 4096 bytes)
 ext:     logical_offset:        physical_offset: length:   expected: flags:
   0:        0..       3:    4351562..   4351565:      4:
   1:        4..    4095:    2334720..   2338811:   4092:    4351566:
   2:     4096..    8191:    2330624..   2334719:   4096:    2338812:
   3:     8192..   10239:    2355200..   2357247:   2048:    2334720:
   4:    10240..   11969:    2408448..   2410177:   1730:    2357248: last,eof

I'm curious how a fragmented initrd.img will impact booting performance. Is it worth defragging?
Of course I'm always open to suggestions for making initrd.img smaller and faster as well.
Note: Besides the mSata SSD and full-size SSD my laptop has a full-size HDD that contains Ubuntu 14.04 so I'm interested in defragging initrd.img in general, not just for SSD. The current boot session is from the mSata SSD though which is limited to SATA II speeds unlike the full-size drives which are on SATA III bus.
EDIT 1: - systemd Boot Chart
As per comments below I've included the systemd-bootchart which is generated by modifying grub kernel parameters with:
GRUB_CMDLINE_LINUX_DEFAULT="splash vt.handoff=7 kaslr init=/lib/systemd/systemd-bootchart"

The boot chart is saved to: /run/log/bootchart-20161224-1801.svg. I had to use gimp to open and export it in .jpg format at 75% quality to make it fit in Ask Ubuntu's 2.1 MB limit. The exported file is shown below:

Notice the 9 second delay at the begining. The "normal" delay of 7 seconds for "Loading initial ramdisk ..." message in grub is now about 10 seconds. The extra time likely attributable to systemd-bootchart overhead.
EDIT 2: RAM and cgroups
As per comments (requests) below RAM and cgroups from /var/log/syslog are included in this edit.
Output from free -m:
$ free -m
              total        used        free      shared  buff/cache   available
Mem:           7843        3167         820        1574        3854        2740
Swap:          7999           4        7995

Note that SWAP is only used for testing OOM Killer and can be erased. Indeed technically it shouldn't be on an SSD in the first place.
Output from grep cgroup < /var/log/syslog.1:
$ grep cgroup < /var/log/syslog.1
Dec 24 15:22:50 dell kernel: [    0.000000] Initializing cgroup subsys cpuset
Dec 24 15:22:50 dell kernel: [    0.000000] Initializing cgroup subsys cpu
Dec 24 15:22:50 dell kernel: [    0.000000] Initializing cgroup subsys cpuacct
Dec 24 15:22:50 dell kernel: [    0.011642] Initializing cgroup subsys io
Dec 24 15:22:50 dell kernel: [    0.011645] Initializing cgroup subsys memory
Dec 24 15:22:50 dell kernel: [    0.011651] Initializing cgroup subsys devices
Dec 24 15:22:50 dell kernel: [    0.011653] Initializing cgroup subsys freezer
Dec 24 15:22:50 dell kernel: [    0.011655] Initializing cgroup subsys net_cls
Dec 24 15:22:50 dell kernel: [    0.011657] Initializing cgroup subsys perf_event
Dec 24 15:22:50 dell kernel: [    0.011659] Initializing cgroup subsys net_prio
Dec 24 15:22:50 dell kernel: [    0.011662] Initializing cgroup subsys hugetlb
Dec 24 15:22:50 dell kernel: [    0.011664] Initializing cgroup subsys pids
Dec 24 15:22:50 dell kernel: [    6.204710] cgroup: new mount options do not match the existing superblock, will be ignored
Dec 24 15:23:33 dell kernel: [    0.000000] Initializing cgroup subsys cpuset
Dec 24 15:23:33 dell kernel: [    0.000000] Initializing cgroup subsys cpu
Dec 24 15:23:33 dell kernel: [    0.000000] Initializing cgroup subsys cpuacct
Dec 24 15:23:33 dell kernel: [    0.010846] Initializing cgroup subsys io
Dec 24 15:23:33 dell kernel: [    0.010849] Initializing cgroup subsys memory
Dec 24 15:23:33 dell kernel: [    0.010855] Initializing cgroup subsys devices
Dec 24 15:23:33 dell kernel: [    0.010857] Initializing cgroup subsys freezer
Dec 24 15:23:33 dell kernel: [    0.010860] Initializing cgroup subsys net_cls
Dec 24 15:23:33 dell kernel: [    0.010861] Initializing cgroup subsys perf_event
Dec 24 15:23:33 dell kernel: [    0.010864] Initializing cgroup subsys net_prio
Dec 24 15:23:33 dell kernel: [    0.010867] Initializing cgroup subsys hugetlb
Dec 24 15:23:33 dell kernel: [    0.010868] Initializing cgroup subsys pids
Dec 24 15:23:33 dell kernel: [    7.338815] cgroup: new mount options do not match the existing superblock, will be ignored
Dec 24 15:45:25 dell kernel: [    0.000000] Initializing cgroup subsys cpuset
Dec 24 15:45:25 dell kernel: [    0.000000] Initializing cgroup subsys cpu
Dec 24 15:45:25 dell kernel: [    0.000000] Initializing cgroup subsys cpuacct
Dec 24 15:45:25 dell kernel: [    0.010844] Initializing cgroup subsys io
Dec 24 15:45:25 dell kernel: [    0.010847] Initializing cgroup subsys memory
Dec 24 15:45:25 dell kernel: [    0.010853] Initializing cgroup subsys devices
Dec 24 15:45:25 dell kernel: [    0.010855] Initializing cgroup subsys freezer
Dec 24 15:45:25 dell kernel: [    0.010857] Initializing cgroup subsys net_cls
Dec 24 15:45:25 dell kernel: [    0.010859] Initializing cgroup subsys perf_event
Dec 24 15:45:25 dell kernel: [    0.010861] Initializing cgroup subsys net_prio
Dec 24 15:45:25 dell kernel: [    0.010864] Initializing cgroup subsys hugetlb
Dec 24 15:45:25 dell kernel: [    0.010866] Initializing cgroup subsys pids
Dec 24 15:45:25 dell kernel: [    5.977461] cgroup: new mount options do not match the existing superblock, will be ignored
Dec 24 16:09:31 dell kernel: [    0.000000] Initializing cgroup subsys cpuset
Dec 24 16:09:31 dell kernel: [    0.000000] Initializing cgroup subsys cpu
Dec 24 16:09:31 dell kernel: [    0.000000] Initializing cgroup subsys cpuacct
Dec 24 16:09:31 dell kernel: [    0.010848] Initializing cgroup subsys io
Dec 24 16:09:31 dell kernel: [    0.010852] Initializing cgroup subsys memory
Dec 24 16:09:31 dell kernel: [    0.010858] Initializing cgroup subsys devices
Dec 24 16:09:31 dell kernel: [    0.010860] Initializing cgroup subsys freezer
Dec 24 16:09:31 dell kernel: [    0.010862] Initializing cgroup subsys net_cls
Dec 24 16:09:31 dell kernel: [    0.010864] Initializing cgroup subsys perf_event
Dec 24 16:09:31 dell kernel: [    0.010866] Initializing cgroup subsys net_prio
Dec 24 16:09:31 dell kernel: [    0.010870] Initializing cgroup subsys hugetlb
Dec 24 16:09:31 dell kernel: [    0.010871] Initializing cgroup subsys pids
Dec 24 16:09:31 dell kernel: [    6.663158] cgroup: new mount options do not match the existing superblock, will be ignored
Dec 24 18:00:44 dell kernel: [    0.000000] Initializing cgroup subsys cpuset
Dec 24 18:00:44 dell kernel: [    0.000000] Initializing cgroup subsys cpu
Dec 24 18:00:44 dell kernel: [    0.000000] Initializing cgroup subsys cpuacct
Dec 24 18:00:44 dell kernel: [    0.011644] Initializing cgroup subsys io
Dec 24 18:00:44 dell kernel: [    0.011647] Initializing cgroup subsys memory
Dec 24 18:00:44 dell kernel: [    0.011654] Initializing cgroup subsys devices
Dec 24 18:00:44 dell kernel: [    0.011656] Initializing cgroup subsys freezer
Dec 24 18:00:44 dell kernel: [    0.011658] Initializing cgroup subsys net_cls
Dec 24 18:00:44 dell kernel: [    0.011660] Initializing cgroup subsys perf_event
Dec 24 18:00:44 dell kernel: [    0.011662] Initializing cgroup subsys net_prio
Dec 24 18:00:44 dell kernel: [    0.011665] Initializing cgroup subsys hugetlb
Dec 24 18:00:44 dell kernel: [    0.011667] Initializing cgroup subsys pids
Dec 24 18:00:44 dell kernel: [    6.388658] cgroup: new mount options do not match the existing superblock, will be ignored
Dec 24 18:01:33 dell kernel: [    0.000000] Initializing cgroup subsys cpuset
Dec 24 18:01:33 dell kernel: [    0.000000] Initializing cgroup subsys cpu
Dec 24 18:01:33 dell kernel: [    0.000000] Initializing cgroup subsys cpuacct
Dec 24 18:01:33 dell kernel: [    0.010850] Initializing cgroup subsys io
Dec 24 18:01:33 dell kernel: [    0.010854] Initializing cgroup subsys memory
Dec 24 18:01:33 dell kernel: [    0.010860] Initializing cgroup subsys devices
Dec 24 18:01:33 dell kernel: [    0.010862] Initializing cgroup subsys freezer
Dec 24 18:01:33 dell kernel: [    0.010864] Initializing cgroup subsys net_cls
Dec 24 18:01:33 dell kernel: [    0.010866] Initializing cgroup subsys perf_event
Dec 24 18:01:33 dell kernel: [    0.010868] Initializing cgroup subsys net_prio
Dec 24 18:01:33 dell kernel: [    0.010871] Initializing cgroup subsys hugetlb
Dec 24 18:01:33 dell kernel: [    0.010873] Initializing cgroup subsys pids
Dec 24 18:01:34 dell kernel: [   12.036550] cgroup: new mount options do not match the existing superblock, will be ignored

Note this log contains multiple boots.
Edit 3 - Speed improved.
After implementing the Q&A answer I wrote  (How can I set up a password for the 'rm' command?) where a wrapper script password protects the rm command, boot speed has doubled.
Here's the new graph:

A: I don't think defragging is your problem, but you could do this...
In terminal...

*

*type man update-initramfs # to learn more about this command.

*then type sudo update-initramfs -c # to create a new file from scratch.

*then type reboot


text:
Q: R loop until condition is met Working on a project in R, I got stuck somewhere.
Those are my data:

r <- 0.001
a <- 0.386
b <- 0.799

yp <- b*df$x+a
sse <- ((df$y-yp)^2)*0.5
a <- a-r*sum(-(df$y-yp))
b <- b-r*sum(-(df$y-yp)*df$x)

How can I find the number of iterations until SSE error is 0.0001?

A: You could do a while loop that stores the sum of squared errors in a vector for each iteration. The loop stops when the sum of squares stops falling, at which point we should have an accurate a and b, and the number of iterations is given by the length of the sse vector.
df <- data.frame(x=c(1.0,2.1,2.2,3.5,5.3,5.4,6.5,7.4),
                 y=c(4,4,4,5,5,6,8,8))

r <- 0.001
a <- 0.386
b <- 0.799

yp  <- b * df$x + a
sse <- sum(((df$y - yp)^2))

while(TRUE)
{
  a <- a - r * sum(-(df$y - yp))
  b <- b - r * sum(-(df$y - yp) * df$x)
  yp <- b * df$x + a
  sse <- c(sse, sum((df$y - yp)^2))
  if(tail(sse, 1) >= sse[length(sse) - 1]) break
}

To see the results, we can do:
cat('iterations: ', length(sse), '\n Intercept = ', a, '\n Slope = ', b, '\n')
#> iterations:  9152
#>  Intercept =  2.691678
#>  Slope =  0.6726519

And we can see that our results are correct (to the first six decimal places) by running an lm:
coef(lm(y~x, df))
#> (Intercept)           x
#>   2.6916789   0.6726517

Created on 2022-03-15 by the reprex package (v2.0.1)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Conforming to protocols - Bug? I have two protocols and views that conform to them. One view compiles and the other does not. Could this be a bug or has the syntax changed?
I also get this error on top of "does not conform to protocol of the 2nd error" Could this be related?

Protocols
protocol RecipeComponent: CustomStringConvertible {
    init()
}

protocol ModifyComponentView: View {
    associatedtype Component
    init(component: Binding<Component>, creationAction: @escaping (Component) -> Void)

}

The first view compiles and conforms..
import SwiftUI

struct ModifyIngredientView: ModifyComponentView {

    @Binding var ingredient: Ingredient
    let createAction: ((Ingredient) -> Void)

    //@Environment(\.dismiss) private var dismiss

    init(component: Binding<Ingredient>, creationAction: @escaping (Ingredient) -> Void) {
        self._ingredient = component
        self.createAction = creationAction
    }

    var body: some View {

        VStack{
            Form{
                TextField("Ingredient", text: $ingredient.name)
                Stepper(value: $ingredient.quantity, in: 1...100, step: 0.5) {
                    HStack{
                        Text("Quantity:")
                        TextField("Quantity", value: $ingredient.quantity, formatter: NumberFormatter.decimal)
                            .keyboardType(.numbersAndPunctuation)
                    }
                }
                Picker(selection: $ingredient.unit) {
                    ForEach(Ingredient.Unit.allCases, id: \.self) {unit in
                        Text(unit.rawValue)
                    }
                } label: {
                    HStack {
                        Text("Unit")
                        Spacer()
                        //Text(ingredient.unit.rawValue)
                    }
                }
                .pickerStyle(DefaultPickerStyle())
                HStack {
                    Spacer()
                    Button("Save") {
                        createAction(ingredient)
                        //dismiss()
                    }
                    Spacer()
                }

                }

            }
        }
    }

extension NumberFormatter {
    static var decimal: NumberFormatter {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter
    }
}

struct ModifyIngredientView_Previews: PreviewProvider {

    @State static var emptyIngredient = Ingredient()

    static var previews: some View {
        NavigationView {
            ModifyIngredientView(component: $emptyIngredient) { ingredient in
                print(ingredient)
            }
        }.navigationTitle("Add Ingredient")
    }
}

The 2nd does not........
import SwiftUI

struct ModifyDirectionView: ModifyComponentView {

    @Binding var direction: Direction
    let createAction: ((Direction) -> Void)

    init(component: Binding<Direction>, createAction: @escaping (Direction) -> Void) {
        self._direction = component
        self.createAction = createAction
    }

    private let listBackgroundColor = AppColor.background
    private let listTextColor = AppColor.foreground

    //@Environment(\.presentationMode) private var mode

    var body: some View {
        Form {
            TextField("Direction Description", text: $direction.description)
                .listRowBackground(listBackgroundColor)
            Toggle("Optional", isOn: $direction.isOptional)
                .listRowBackground(listBackgroundColor)
            HStack {
                Spacer()
                Button("Save") {
                    createAction(direction)
                    //mode.wrappedValue.dismiss()
                }
                Spacer()
            }.listRowBackground(listBackgroundColor)
        }
        .foregroundColor(listTextColor)
    }
}

struct ModifyDirectionView_Previews: PreviewProvider {
    @State static var recipe = Recipe.testRecipes[0]

    static var previews: some View {
        NavigationView {
            ModifyDirectionView(component: $recipe.directions[0]) { direction in
                print(direction)
            }
        }
    }
}

A: just change the parameter name of the init of the second view from createAction to creationAction, as it is declared in the protocol


text:
Q: static variable - undefined reference Today I encountered a liking problem with static variable/function. First let me show you the code:
Trace.h
class Trace : public QObject
{
    Q_OBJECT

public:
    explicit Trace(QObject *parent = 0);
    static void setLogFilePath(QString path)
    {
         logFilePath = path;
    }
    QString getLogFilePath();

private:
    static QString logFilePath;
};

#endif // TRACE_H

Trace.cpp
// includes.. constructors..

QString Trace::getLogFilePath()
{
    return logFilePath;
}

On Linux, I can compile this class to generate a dynamic library without any problem. On windows, I can't, I have an undefined reference to logFilePath.
I know that with TEMPLATE = app I have to define my static variables in the main, but with a library I don't think so but I'm not sure.
I saw that on windows, if put the implementation in the header file like this:
Trace.h
QString Trace::getLogFilePath()
{
     return logFilePath;
}

There is no liking error.
1) Why is there a difference like this between Linux and Windows ? (Same Qt version).
2) Is using static variable in dynamic library a good thing or not ? (I can overcome this problem with a file, maybe it's better).
Thanks in advance.

A: The problem with the linking is in both, the logFilePath variable and the getLogFilePath() function.
When you have moved the function from the .cpp file to the header file, then you have placed all the class in the header file, making it available to any compilation unit. Doing this you are NOT using the dynamic library, you are just using your class definition found in the header file.
In order to be able to generate a dynamic library with your class hidden in the .cpp file, and only having available the header file, you need to tell the linker to "search the class in external libraries". This is done by including the __declspec(dllexport) and __declspec(dllimport) to the class definition.
You have more information here:
How to implement a class counter in DLL?
Also, ALL the static variables MUST be instantiated somewhere outside de .h file. This is done, as stated by vahancho, by declaring it in the .cpp file. It is not requiered to be the main.cpp file, it should be the .cpp file corresponding to your class definition file.
Best regards,
Ruben


text:
Q: Does windows server 2012 place any special restrictions on cscript.exe or OLE DB provider? I have a simple script
Set Connection = CreateObject("ADODB.Connection")
Connection.Open("DSN=dsn; UID=userid; PWD=password")
queryString = "SELECT * FROM SSW_RECORD"
set RS = Connection.Execute(queryString)
Wscript.Echo("hello, world!")
If NOT(RS.EOF) or NOT(RS.BOF) Then
    Do While NOT(RS.EOF)
        Wscript.Echo(RS("SSW_ORDER_NO"))
    Loop
End If

It works on my machine (completely unmodified). However, when I try to deploy it to the production server, I get test.vbs(2, 1) Microsoft OLE DB Provider for ODBC Drivers: Unable to open connection to server.
Also, not sure if I should ask this on SuperUser instead.

A: Connection.Open("DSN=dsn; UID=userid; PWD=password")

Looks like you aren't providing a connection string that it can use.  I'm assuming it defaults to localhost on your machine where you have a server hosted.
Might be why it isn't working on another machine.


text:
Q: Binding a ComboBox I have an ObservableCollection of JobTitles that I want to bind to a ComboBox. Using binding through XAML I've had no luck, so I've ended up doing this;
foreach (PresetModel jobTitle in JobTitles)
{
    var _newItem = new ComboBoxItem();
    _newItem.Content = jobTitle.Text;
    _newItem.Tag = jobTitle.ID;
    jobTitleComboBox.Items.Add(_newItem);
}

This actually does add all of the JobTitles to the ComboBox (further than I got with bindig) however now the issue is that when the user selects an Employee, who has a JobTitle, I want to select the relevant JobTitle in the ComboBox.
Ideally I'd do this;
jobTitleComboBox.Text = currentUser.JobTitle;
However this does not work. I only have access the Employees JobTitle text, not the ID of the title which I don't think helps. How can I display the relevant job title for the Employee?

A: If you have a collection named: JobsCollection. And on this collection you have JobId, JobName ...etc attributes. Then, on your XAML you could simply write:
ComboBox ItemsSource="{Binding JobsCollection}" DisplayMemberPath="JobName"

So,
DisplayMemberPath -> Which property you want to show on the Combobox list
Binding -> The name of the ObservableCollection you want to bind.
Edit: How XAML Element would look like
<ComboBox ItemsSource="{Binding JobsCollection}"
          SelectedItem={Binding SelectedItemName}
          DisplayMemberPath="JobName" />

A: Set your required selected item index:
     jobTitleComboBox.SelectedItem = jobTitleComboBox.Items[1];


text:
Q: testing firebase function with jest Since two days I am trying to understand and write a test for my firebase function. For that test I just want to use the framework Jest. https://jestjs.io/
export const updateTipsPerFixture = functions.firestore.document('users/{userId}').onUpdate((change) => {
    const beforeTips: Tip[] = change.before.data() !== undefined ? change.before.data().tips : [];
    const afterTips: Tip[] = change.after.data() !== undefined ? change.after.data().tips : [];

    if (JSON.stringify(beforeTips) === JSON.stringify(afterTips)) {
        return new Promise(resolve => resolve('equal'));
    }

    if (afterTips.length === beforeTips.length) {
        return new Promise(resolve => resolve('same length'));
    }

    if (beforeTips.length < afterTips.length) {
        return new Promise(resolve => resolve('afterTips.length is longer'));
    }

    return false;
});

Even after I read the Jest docu and cannot figure out how to mock/stub the firebase function module for my use case.
This is as far as I came. Yes, not really far.
describe('updateTipsPerFixture', () => {
    test('it should return true when tips are equal', () => {
        expect(updateTipsPerFixture).toEqual(new Promise(resolve => 'equal'));
    });
});

How should I write the test and mock the firebase module?

A: The solution I found is pretty easy and nice. The function can be tested by calling the function run() and passing some data. See example:
describe('updateTipsPerFixture', () => {
    test('it should return true when tips are equal', () => {
        const mockedData = {
            before: {
                data(): FirebaseFirestore.DocumentData | undefined {
                    return {tips: [{fixtureId: 123, teamId: 123} as Tip]}
                }
            },
            after: {
                data(): FirebaseFirestore.DocumentData | undefined {
                    return {tips: [{fixtureId: 123, teamId: 123} as Tip]}
                }
            }
        } as Change<DocumentSnapshot>;

        const actual = updateTipsPerFixture.run(mockedData, null);

        return expect(actual).resolves.toEqual('equal');
    });
});


text:
Q: How to generate provably fair dice rolls in C#? I looked into provably fair random numbers, and came across this website: https://dicesites.com/provably-fair
First off, what class should be used for the server sided hash? There are so many hash algorithms like SHA512, SHA256 or SHA384Cng and I do not understand the difference between them.
Second off, what method would be used to convert from the unhashed seed to the hashed seed, and what method would be used to take the string for the seed provided by the user into account during the hash creation. Also, is the nonce simply added at the end of the string provided by the user in order to prevent duplicate hashes?
Third off, I do not understand why the hashed server seed is originally a SHA256 hash but is later used to calculate a HMAC SHA512 hash.
Lastly, what would be used to convert the first 5 characters of the final generated hash to a roll number?
I have had no luck in finding any examples of any random number generators that use a server seed and client seed, only things like System.Security.Cryptography.RandomNumberGenerator.

A: The page you link to describes the process, however I will try to go in to more detail and provide a C# example.
First there are two hashings that happen. One general hash to prove that the server is not changing the server key as you gamble, this hash is not secret and is given to the player at the start of play. There is also a keyed hash (called a HMAC) to actually generate the dice rolls and uses a combination of the server key, the data the user provided, and a number that counts up.
Here is the process that happens:

*

*The server generates a secret key for the play session and sets a counter to 0.

*SHA256 is used on the key to generate a hash, this hash is given to the player. This hash is not used in any math to generate the dice rolls, it is only used for verification by the player.

*The player requests a dice roll and provides a phrase to be used in the generation of the number.

*The server uses a SHA512-HMAC using secret key as the key then the string the user provided plus "-" plus the number of the counter set in step 1 to generate a hash.

*The server increments the counter by 1, this is done because the same server key is used every time and if the same user string was used it would just generate the same number over and over.

*The server takes the first 21 bits of the hash generated, converts it to a int, it then checks to see if the int is larger than 999999 if it is it keeps repeating till it finds a number that is not over 999999.

*It takes the number from step 6 and does number%(10000)/100.0 on it to get a floating point number.

*That floating point number is returned to the user.

*Either repeat starting at step 3 for a new roll or continue to step 10.

*The player signals the play session is over. The server returns the secret key to the user and restarts at step 1.

The user once he gets the secret key from step 10 can hash it using SHA256 and check that he gets the same hash he was told at the start of the play session. He can then re-do all the steps the server did now that he has the secret key and verify that the server did not fake any dice rolls.
How to do this in code:
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace SandboxConsole
{
    public class Result
    {
        public Result(string hmacMessage, float roll)
        {
            HmacMessage = hmacMessage;
            Roll = roll;
        }

        public string HmacMessage { get; }
        public float Roll { get; }
    }

    class FairDiceRollServer
    {
        private byte[] _serverKey;
        private ulong _nonce;

        public byte[] StartSession()
        {
            if (_serverKey != null)
                throw new InvalidOperationException("You must call EndSession before starting a new session");

            //Generate a new server key.
            using (var rng = RandomNumberGenerator.Create())
            {
                _serverKey = new byte[128];
                rng.GetBytes(_serverKey);
            }
            _nonce = 0;
            //Hash the server key and return it to the player.
            using (var sha = SHA256.Create())
            {
                return sha.ComputeHash(_serverKey);
            }
        }

        public Result RollDice(string userKey)
        {
            if(_serverKey == null)
                throw new InvalidOperationException("You must call StartSession first");
            if(_nonce == ulong.MaxValue)
                throw new InvalidOperationException("Ran out of Nonce values, you must start a new session.");

            using (var hmac = new HMACSHA256(_serverKey))
            {
                float? roll = null;
                string message = null;
                while (roll == null)
                {
                    message = userKey + "-" + _nonce;
                    _nonce++;

                    var data = Encoding.UTF8.GetBytes(message);
                    var hash = hmac.ComputeHash(data);
                    roll = GetNumberFromByteArray(hash);
                }
                return new Result(message, roll.Value);
            }
        }

        private float? GetNumberFromByteArray(byte[] hash)
        {
            var hashString = string.Join("", hash.Select(x => x.ToString("X2")));
            const int chars = 5;
            for (int i = 0; i <= hashString.Length - chars; i += chars)
            {
                var substring = hashString.Substring(i, chars);
                var number = int.Parse(substring, System.Globalization.NumberStyles.HexNumber);
                if(number > 999999)
                    continue;
                return (number % 10000) / 100.0f;
            }
            return null;
        }

        public byte[] EndSession()
        {
            var key = _serverKey;
            _serverKey = null;
            return key;
        }
    }
}

Example of it in use
using System;
using System.Linq;

namespace SandboxConsole
{
    class Program
    {
        private int _test;
        static void Main(string[] args)
        {
            var server = new FairDiceRollServer();
            var hash = server.StartSession();
            Console.WriteLine(string.Join("", hash.Select(x => x.ToString("X2"))));
            for (int i = 0; i < 10; i++)
            {
                var roll = server.RollDice("My Key");
                Console.WriteLine("Message: {0} Result: {1}", roll.HmacMessage, roll.Roll);
            }
            var key= server.EndSession();
            Console.WriteLine(string.Join("", key.Select(x => x.ToString("X2"))));
            Console.ReadLine();
        }

    }
}

Using the published information about the algorthom used, the information returned by RollDice and the key given to the user returned from EndSession the user can re-create all dice rolls and prove the server truly did a random generation (thanks to the user provided data in the roll the server was not allowed to choose) and not some faked pre-chosen key that is guaranteed to cause a loss.


text:
Q: Live action series or movie with kids sucked into a video game I have this very vague memory of watching some live action series or movie (can't remember which), where these kids got sucked into a video game/computer. I remember that there was this strange blue CG sprite and that at one point a boy spelled "HELP" on the floor with sticks inside the game so the outside would notice.
I must have seen it around 2005–6, but my teacher showed it to me, so it may have been older. So I think it may have been educational in some way, but I can't remember how. I also remember a kid using a crayon and paper to figure out what some stone said but that may be from something else. I am aware this is incredibly vague — but it was definitely live action.

A: Bearing in mind that your teacher showed it to you, I reckoned it might have been an educational programme, and googled the BBC's "Look and Read" series to try to find a match:
"Zzaap and the Word Master" was originally broadcast in 2001. Wikipedia's synopsis reads:

Josie and Peter get transported into an educational computer game at their school. Once inside they discover that the game is being controlled by the evil Victor Virus who is intent on finding a way to take over the world. The children, assisted in the real world by Simon and Frances, must stop Virus by completing the various levels of the game.

You mention "a strange blue CGI-like sprite". There's an image at https://www.amazon.co.uk/zzaap-Word-Master-Look-Read/dp/0563541075
which does indeed show such a sprite interacting with two of the children.
Also, to quote your original post - "I also remember a kid using a crayon and paper to figure out what some stone said" - This sort of thing would happen quite often in Look and Read.
I've found a Youtube link -

 - so you can check it out for yourself.

A: Could it possibly be Spy Kids 3D: Game Over?

Carmen's caught in a virtual reality game designed by the Kids' new nemesis, the Toymaker. It's up to Juni to save his sister, and ultimately the world.

It features children being pulled into a video game. It was released in 2003 so it's from around the same time. Additionally, it's live action with CGI components and the players trapped in the game are aided by the outside world. However, this film doesn't, to my recollection, feature a blue sprite, the spelling of 'help' with sticks, or the crayon rubbing.

A: The only strictly matching point is that it's a live action series involving kids pulled into a video game, and it's around the right timeframe, but could it be the 2003 Australian series, Pirate Islands?

Kate Redding, a sister of Nicholas and Sarah, is playing a new computer game called Pirate Islands, which has been created by her father. After Sarah tampers with the computer scanner, lightning strikes the house, and the scanner goes wild, zapping the three siblings inside the computer game. After teleporting inside the game, Kate meets Mars, the main character of the video game. Blackheart, the pirate captain, takes the siblings aboard the pirate ship and threatens to walk them off the plank, Mars climbs aboard and cuts the rope, causes the sails to fall against the pirates, the siblings escape and attempt to find their scanner, only to be cornered by the pirates and drop it into Blackheart's grasp, who uses it unknowingly to zap his crew-mate, causing him to pixelate and melt.
Kate discovers that users are transported between islands in the game through icons, after jumping inside, she ends up on castaway island only to find that Carmen, the second in command, has stolen all the items from Kate's bedroom. The pirates arrive and chase the gang off the island, causing Sarah to trip against a tree trunk which triggers a secret entrance inside the tree, which contains stairways up towards a hidden treehouse, the gang store their few belongings and decide to call this place their new home.

Nothing in the plot on Wikipedia mentions spelling out "help" with sticks, or getting a rubbing from a stone to discover engravings, but it seems like it would be within the genre.
Trailer

Found by searching for tv series kids pulled into videogame -cartoon, which brought me to TV series about children ending up in father's computer game on this site.

A: Most likely a cartoon called Zixx.

Zixx is an Intergalactic Network (simplified as the Network) agent who has crash landed onto Earth with her partner Flanngo. As luck would have it, Earth also happens to be a hotbed of activity for the evil Onccalon and the Hargokk Empire. Zixx has no intention of letting him win, so she and Flanngo need to find a way to access the Network and make sure they can get to the next level of the Keep before Onccalon's henchmen do.
...
Zixx and Flanngo need to find a way into the Keep, a trans-dimensional antimatter field (a cyber dimension resembling a video game), the last legacy of the ancient Gaanth race, the leaders of the Network (reminiscent of Tron). The difference is that death is permanent if they die in the keep. Reluctantly accepting the help of earthlings, Adam and Griff, the four need to move fast and finish level one of the Keep, to do so they will need to recover the six fragments of a crystal that are scattered throughout the level. When the crystal is whole and combined with the crystal base, it shows the map to the three neuropods buried deep within the level that, when solved, show the path to the next level. They must accomplish all of this before Onccalon's henchman Deeth does.

A: Is it possibly Adventures in Dinosaur City?
From Wikipedia:

Adventures in Dinosaur City (known as Dinosaurs The Movie in Europe) is a 1991 television film directed by Brett Thompson. The film stars Omri Katz, Tiffanie Poston, Shawn Hoffman, Rob Sherwood, Patrick Labyorteaux, and David Jolliffe.

The story involves a trio of teenagers, named Timmy (Omri Katz), Jamie (Tiffanie Poston), and Mick (Shawn Hoffman), who enjoy watching their favorite TV show which features anthropomorphic dinosaurs. Wanting to watch it on a better screen, Timmy, the youngest of the three, suggests that they try watching it on his father's screen in his laboratory. The moment they turn it on, a vortex sucks the three into the TV screen, and into their favorite show.
Upon entering the new world, the trio comes across a flightless Dimorphodon named Forry (Rob Sherwood). Reluctant, his knowledge of Dinosaur City proves useful as he guides the three to Tar Town where they join up with a Tyrannosaurus named Rex (Patrick Labyorteaux) and a Triceratops named Tops (David Jolliffe), two dinosaur freedom fighters willing to ignite a revolution against the villain, Mr. Big (Patrick Labyorteaux) and his caveman henchmen "The Rockies".

A: You're looking for Super Human Samurai Syber-Squad


text:
Q: Specifying a javaagent within the jar file to be run I'm developing an OpenJPA application (no webserver, regular java se app). In order to make OpenJPA work with my application, I need to set the openjpa-all-2.3.0.jar as a javaagent.
java -cp ... -javaagent:/full/path/to/openjpa-all-2.3.0.jar -jar app.jar

As I am packaging the openjpa.jar within the app.jar anyway, I am now wondering how it is possible to specify the javaagent, as a jar within my application jar file.
This didn't work
java -cp ".;.\app.jar" -javaagent:openjpa-all-2.3.0.jar pckg.Main

A: There's no way to do it.
The JVM does not look at the classpath to find the specified agent; it is expecting a file path, and you also cannot specify file paths inside jar files.
JDK-4648386 is the related feature request, and was closed Won't Fix after 18 years.
However, what you can do is write code to copy the agent jar from a classpath resource to a temporary file, and then attach it to the current running JVM. The ByteBuddy Agent library provides tooling to do this.


text:
Q: Write data in a column using CSV module in python I have written my beautiful soup code to create ouput in the following format
Quatermass 2
Ghostbusters
Life of Brian

I'd now like to write this into a csv file. However the only csv write function I'm familiar with is write_row. When I use this it prints only the last 'title_content' object I scrape ie ->Life of Brian
My python code is
from bs4 import BeautifulSoup
import requests
import re
import csv

html = ['table.html']

with open("table.html", "r") as f:
    contents = f.read()

outputfilename = 'row_writer.csv'
print(outputfilename)

outputfile = open(outputfilename, 'w')          #wb = write and binary - indicates file open for writing in binary
writer = csv.writer(outputfile)
writer.writerow(['Title'])

soup = BeautifulSoup(contents, "lxml")
for name in soup.find_all("td", {"width": "41%"}, string=re.compile(r'^(?!Title$)')):
    title_content = ((name).get_text())
    print(title_content)

writer.write_row([title_content])

Can anyone help with a way to write my entire content into a csv column please?
HTML

            Title

            Quatermass 2

            Title

            Ghostbusters

            Title

            Life of Brian

A: It looks like the titles all are with the tag . so what you can do is create a list of the text with that tag, then convert to a table that is written to file using pandas. You can also do it with writer, but I like using pandas as you can manipulate the tables as needed.
html = '''

            Title

            Quatermass 2

            Title

            Ghostbusters

            Title

            Life of Brian	'''

import pandas as pd
from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')
titles = soup.find_all('strong')

titles_list = [each.text for each in titles ]

df = pd.DataFrame(titles_list, columns=['Title'])

df.to_csv('output.csv', index=False)

Output:
print (df)
           Title
0   Quatermass 2
1   Ghostbusters
2  Life of Brian


text:
Q: Ajax Post to Controller Action Cross domain I have a form on "website A" which posts to "website B".  Code included Below.
I can't get a success or a return message from my destination domain.
Any suggestions? what am I doing wrong?
<script type="text/javascript">

$.fn.serializeObject = function()
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           if (!o[this.name].push) {
               o[this.name] = [o[this.name]];
           }
           o[this.name].push(this.value || '');
       } else {
           o[this.name] = this.value || '';
       }
   });
   return o;
};

$(document).ready(function(){
    $("#submit").bind("click", function(){

        //turn form into json
        var formData = $("#digForm").serializeObject();
        var jsonData = JSON.stringify(formData);

        alert(jsonData);

        $.ajax({
            url: URL,
            data: jsonData,
            dataType: 'jsonp',
            cache: false,
            success: function (data) {
                alert(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                                alert(errorThrown);
                            }
        });
    })
});
</script>

Here is the controller:
[HttpPost]
public ActionResult Index(string submission)
{
    SubmissionModel model = new SubmissionModel();

    //validate everything we need is here
    var serializer = new JavaScriptSerializer();

    // get json data from url
    var json =  submission;
    var submissionData = serializer.Deserialize<SubmissionModel>(json);

    model.SiteID = submissionData.SiteID;
    model.FirstName = submissionData.FirstName;
    model.LastName = submissionData.LastName;
    model.Email = submissionData.Email;
    model.Comments = submissionData.Comments;
    model.Like = submissionData.Like;
    model.Dislike = submissionData.Dislike;
    model.SubmitDate = DateTime.Now;
    db.Submissions.Add(model);
    db.SaveChanges();

    return View();
}

A: you are using json but for cross browser ajax posts you should be using jsonp
http://forums.asp.net/t/1780255.aspx/1

A: Needed to do it like this:
$.ajax({
    url: URL,
    data: {submission: jsonData},
    dataType: 'jsonp',
    cache: false,
    success: function (data) {
        alert(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert(errorThrown);
    }
});

A: I ran into similar problems in the past.
With the risk of teaching grandma to suck eggs....
First, regarding the diagnosis of the problem
I am pretty sure this IS a same-origin-policy problem, because these result is not getting a success or error message, which is very typical.
What you COULD to in order to diagnose it, is to use firebug on firefox, and look at the http requests/responses themselves. Over there you WILL see the response, because this is before it is being filtered out by the browser.
Regarding the solution.
Like Anthony said, you CAN use jsonp. JsonP is actually a hack that works around the same-origin-policy by hiding the data as if it was a JS function.
I usually use getJson instead of ajax() for that.
http://api.jquery.com/jQuery.getJSON/
And I set it to use jsonp manually, by adding "callback=AnyName" to the post parameters.
Also, I cannot see your server B's response code, but the json data needs to be encapsulated with AnyName();  so if your json data is {json, data}, your response should be AnyName({json,data});


text:
Q: How to call a subdirectory of the current working directory correctly with glob I want to search all files in a subdirectory of my current working directory, this is part of a bigger code where I choose different subfolders and make some manupulations of files in them. But I don't want to call the whole file path each time.:
import glob
import os

os.chdir("C:/Users/John")
for i in glob.glob("/subfolder/**"):
   print(i)

So if there is something in subfolder this code should print it. But somehow glob.glob can't finde the folder

A: You have added / in front of subfolder which is not directly accessible. Try removing it. This code works for me.
import glob
import os

os.chdir("C:/Users/John")
for i in glob.glob("subfolder/**"):
   print(i)

A: I don't understand...
You want display the files of your subfolder ?
import glob
import os

os.chdir("C:/Users/John")
for e in glob.glob("./your_subfolder_name/*"):
   print(e)

This display all the files in the folder :
C:/Users/John/your_subfolder_name


text:
Q: Azure Active Directory Integration with Custom RBAC We have our own web application which performs access control based on the username and associated roles defined locally and maintained in the local database
I need to integrate our application with "Azure AD" to avail single sign-on (SSO) so that with the same user-name, we can integrate and access other SaaS applications as well.  I think I can achieve this with "Azure ADAL APIs" and "Graph APIs".
However, I would like to understand how to define custom user attributes and roles for "Azure AD" to share the attributes and roles with our application upon authentication. This is required for our web application to provide Access Control ( based on user id and role) without defining roles locally. I am not sure how to achieve this?.
Please let me know if it is feasible and what is the best option to achieve the same.

A:
I would like to understand how to define custom user attributes and
  roles for "Azure AD" to share the attributes and roles with our
  application upon authentication. This is required for our web
  application to provide Access Control ( based on user id and role)
  without defining roles locally.

You need to look at the Application Roles related functionality with Azure AD to implement your custom RBAC. It should most probably provide you what you're looking for.
On a side note, I've seen cases where people chose to do some authorization logic based on which groups the users belonged to. This is just information and not something you need to do.
I'm sharing samples related to both, Roles and Groups in this answer, but definitely look at Application Roles first and once you understand them clearly, you can decide to use Application Roles, Groups or a combination of both Roles and Groups (very possible) for your Authorization strategy.
Application Roles
Microsoft Documentation - Application Roles
Purpose - These roles are defined in the Application Manifest for an application that your organization is developing and that is registered in your Azure Active Directory. These roles are very specific to your application and can be used in application's code to implement Authorization logic for the authenticated users.
Sample Application (that uses this concept and does what you're looking for) -
Authorization in a web app using Azure AD application roles & role claims
Quick Explanation
1) Once you register your application with Azure AD, you can define custom roles (specific to your application) by editing the application manifest (JSON) in Azure AD.
Here's a sample JSON of what application role definition would look like:
"appRoles":
[
  {
    "allowedMemberTypes": [
      "User"
    ],
    "description": "Creators can create Surveys",
    "displayName": "SurveyCreator",
    "id": "1b4f816e-5eaf-48b9-8613-7923830595ad",
    "isEnabled": true,
    "value": "SurveyCreator"
  },
  {
    "allowedMemberTypes": [
      "User"
    ],
    "description": "Administrators can manage the Surveys in their tenant",
    "displayName": "SurveyAdmin",
    "id": "c20e145e-5459-4a6c-a074-b942bbd4cfe1",
    "isEnabled": true,
    "value": "SurveyAdmin"
  }
]

2) You will be able to assign these roles to Users/Groups/applications through Azure Portal or programmatically. (you could control the allowed member types for roles)
3) Now when the end users sign in to your application, the incoming Azure AD token will provide you a collection of role claims (based on whatever roles are assigned to the user) and you can take authorization decisions in your application.
if (context.User.HasClaim(ClaimTypes.Role, "Admin")) { ... }

Groups
Groups can have multiple users or other groups as members. Again management of groups is possible through Azure Portal or programmatically.
NOTE: Groups are totally independent of your application, i.e. Azure AD groups can and do exist to serve a purpose of grouping members even without your application. Application Roles on the other hand are very specific to your application, they don't mean much to anyone except your application.
Sample app which makes decisions based on Groups
Authorization in a web app using Azure AD groups & group claims

A: You've marked this SAML so I assume you want to do this via a custom SAML application?
If so, you need to provision Azure AD via the Graph API from your custom repository.
If Azure AD does not have the attribute you need, create an extension attribute.
In the SAML connection, you can configure what attributes are passed (this includes roles).
Note: the ADAL libraries are for OpenID Connect, not for SAML.


text:
Q: How would I solve for a?
"Solve for a such that the above function is continuous from -infinity to +infinity"
I am struggling with this problem because a is only present in one of the parts of the function and if I set the above part of the function to -4, it is undefined.
Any help?

A: HINT: $$2x^3+9x^2+11x+28=(x+4)(2x^2+x+7)$$


text:
Q: What assembler would be best fit to program an OS from scratch, with execution performance prioritized? I am not fit to program an OS under any circumstances, but this is hypothetical.
I want to create a simple operating system from almost absolute scratch in assembly language. With great ambitions in mind, I want it to be as optimized as possible for execution. I also want the code to be fairly portable for multiple architectures (especially x86 and x64 interchangeably). I feel a bit minimalist, so lets toss out software "bloat".
What I am looking for is an assembler that can fit this criteria. Obviously, I want one that is decently documented officially or unofficially, and I need it to be decently well-known (I.E. I don't want "ΣASM" found in the middle of the internet Sahara.)

A: Under the circumstances you specify, NASM would probably be the best choice. It's reasonably well documented, fairly widely used and heavily tested. It's also one of the few that can directly produce raw binary output files, where most require that you jump though hoops with the linker to get that. This isn't so much an issue for the OS proper as it is for the bootloader, but (for whatever reason) most who work on an OS themselves also write at least a few toy bootloaders as well.

A: You are contradicting yourself greatly.  Optimizing for execution on x86 is not possible, each family can/does execute the same binary at dramatically different speeds, esp if you are going to jump between 32 bit and 64 bit.  If your goal is speed on an x86 do not write in asm, use C, then let the compiler optimize for the platform it happens to be on.  for large projects you are not going to be able to compete with the compiler.  For short compiler generated code sequences, yes, sure you can sometimes hand assemble something better/faster.  for x86 the compiler is likely to do a better job at average good speed on an x86 than you are.  Bloat doesnt necessarily come from the compilers or language but from the design and implementation in whatever language chosen.  Very very easy to have bloated asm as bloated C or other.
Second, if you are writing in assembly language.  How much of this code is instructions and how much do you expect to be assembler specific directives and other nuances?  You can at least attempt to write somewhat portable asm that works on different assemblers using a minimum number of directives shared by those assemblers, the rest being instructions.  x86 unfortunately has problems here as well, there is the intel vs at&t syntax problem to start with then the byte ptr and near/far items to tell the assembler which flavor of a particular instruction which even limited to intel syntax may not be portable from one x86 assembler to another.  You can get a raspberry pi for $25 or a beaglebone for $90.
x86 assembly is dreadful at best, decades of band-aids on top of band-aids (starting with the original which was predecessor+bandaids).  If you feel the need to do a good sized assembly project, (vs something more useful like C) esp if speed is your goal, then choose a better processor and instruction set.  I dont know the size of your project.  If small enough then thumb or thumb2 or arm or avr or msp430, if larger then arm or mips.  Sadly enough for most of those you would probably go with gnu binutils.  For x86 if you really think you need to use that instruction set and that hardware for this, I agree with Jerry, go with nasm.


text:
Q: Color binning on Bayer sensor Is there a difference between doing binning on a Bayer sensor before or after the ADC with respect to spatial information lost?
How the debayering works should not matter, Assuming the same method is used for both ways.
A:

*

*Horizontal 2x1 binning before ADC by adding up pixels of same color

*debayering of the binned Bayer pattern.

B:

*

*Debayering

*Binning by adding adjacent pixels horizontally.

Is there any advantage of A over B except lower noise?
In the end, I think the same spatial information is lost. Meaning information from the same originally neighboring sensor pixels ends up in any given final image pixel.

A: From a purely MTF (Modulation Transfer Function) point of view the operations you describe are identical. Adding the same pixels in the analog domain or the digital domain will give you the same spatial results with it's blurring, Moire fringes and other artifacts.
In terms of noise it very much depends upon how well you are digitizing the signal.
A CCD bins by summing charge, the noise will increase by \$\sqrt{N}\$ and the signal will increase by \${N}\$.  The ADC noise floor will be the same so this signal will be readily digitized, at the risk of running out of head room on the ADC (the bright parts of the scene will clip).  Assuming the ADC was setup to digitize the right level of noise it will only get better.  Binning in the analog domain can potential increase your frame rate.
Summing after digitization is more convenient since it is simply a memory access to get the same colors  gathered together.  There is less supporting circuitry and certainly less analog circuitry with analog storage elements.  the mathematics for the SNR is very similar in this case, the main difference here is that if your digitization level does not include enough of the noise floor then when you do the summing in the digital domain the noise patterns may be very unpleasant.  Because you are sampling at the what the ADC resolution is, this thresholding can increase the noise in the digital domain.  However, if the the noise level is sufficiently higher than the ADC noise then it will look the same as the analog domain.
All things being equal, the digital domain is easiest and less expensive.

A: Most answers to your questions are here :
https://link.springer.com/article/10.1186/1687-6180-2012-125
See the pictures also.
No it is not the same to do binning before or after. The binning is not done the same way at all. Before : 4x4. After : 2x2.
Demosaicing then DS should be better. As the pictures confirm.


text:
Q: OCUnit Test Case Issue I am working OCUnit Test case
- (NSDictionary*)Event:(EventBase*)event
{
    [self doesNotRecognizeSelector:_cmd];
    return nil;
}

I found this method to write the test case
In my Test Case Class i pass the event value valid,invalid and nil for the above method
-(void)testEventNil{

NSDictionary *t_Dict;
EventClass *t_EventClass = [[EventClass alloc]init];
t_Dict = [t_EventClass Event:nil];
STAssertNil (t_Dict, @"Return nil");
}

-(void)testEventNil{

NSDictionary *t_Dict;
NSMutableDictionary *invalid;
[invalid setObject:@"1324" forKey @"Number"];
EventClass *t_EventClass = [[EventClass alloc]init];
t_Dict = [t_EventClass Event:];
STAssertNil (t_Dict, @"Return nil");
}

-(void)testEventvalid{

NSDictionary *t_Dict;
NSMutableDictionary *invalid;
[invalid setObject:@"WorkNameEvent" forKey @"EventNameKey"];
EventClass *t_EventClass = [[EventClass alloc]init];
t_Dict = [t_EventClass Event:];
STAssertNotNil (t_Dict, @"Return nil");
}

Its gives me error unrecognized selector sent to instance
Can any one advice me for fixing the issue
@All
Thanks in advance

A: Your code has multiple errors. I can't make sense of it.
You are trying to test a method that is designed to throw an error. Maybe it is intended to be overriden? The only possible test as it is now is
EventClass *event = [EventClass new];
STAssertThrows([t_EventClass Event:nil],@"Should throw an error.");

When you write: t_Dict = [t_EventClass Event:]; you are not passing any parameter to the Event: method.
This doesn't work either:
NSMutableDictionary *invalid;
[invalid setObject:@"WorkNameEvent" forKey @"EventNameKey"];

because you didn't initialize the dictionary. That is,
NSMutableDictionary *invalid = [NSMutableDictionary new];

The convention in Objective-C is to name methods and variables using camel case, in this case event: instead Event:, and dic instead t_Dic.


text:
Q: handling zeros in pandas DataFrames column divisions in Python What's the best way to handle zero denominators when dividing pandas DataFrame columns by each other in Python? for example:
df = pandas.DataFrame({"a": [1, 2, 0, 1, 5], "b": [0, 10, 20, 30, 50]})
df.a / df.b  # yields error

I'd like the ratios where the denominator is zero to be registered as NA (numpy.nan). How can this be done efficiently in pandas?
Casting to float64 does not work at level of columns:
In [29]: df
Out[29]:
   a   b
0  1   0
1  2  10
2  0  20
3  1  30
4  5  50

In [30]: df["a"].astype("float64") / df["b"].astype("float64")
...

FloatingPointError: divide by zero encountered in divide

How can I do it just for particular columns and not entire df?

A: You need to work in floats, otherwise you will have integer division, prob not what you want
In [12]: df = pandas.DataFrame({"a": [1, 2, 0, 1, 5],
                                "b": [0, 10, 20, 30, 50]}).astype('float64')

In [13]: df
Out[13]:
   a   b
0  1   0
1  2  10
2  0  20
3  1  30
4  5  50

In [14]: df.dtypes
Out[14]:
a    float64
b    float64
dtype: object

Here's one way
In [15]: x = df.a/df.b

In [16]: x
Out[16]:
0         inf
1    0.200000
2    0.000000
3    0.033333
4    0.100000
dtype: float64

In [17]: x[np.isinf(x)] = np.nan

In [18]: x
Out[18]:
0         NaN
1    0.200000
2    0.000000
3    0.033333
4    0.100000
dtype: float64

Here's another way
In [20]: df.a/df.b.replace({ 0 : np.nan })
Out[20]:
0         NaN
1    0.200000
2    0.000000
3    0.033333
4    0.100000
dtype: float64

A: Just for completeness, I would like to add the following way of division that uses DataFrame.apply like:
df.loc[:, 'c'] = df.apply(div('a', 'b'), axis=1)

In full:
In [1]:
df = pd.DataFrame({"a": [1, 2, 0, 1, 5, 0], "b": [0, 10, 20, 30, 50, 0]}).astype('float64')

def div(numerator, denominator):
  return lambda row: 0.0 if row[denominator] == 0 else float(row[numerator]/row[denominator])

df.loc[:, 'c'] = df.apply(div('a', 'b'), axis=1)

Out[1]:
      a     b         c
0   1.0   0.0  0.000000
1   2.0  10.0  0.200000
2   0.0  20.0  0.000000
3   1.0  30.0  0.033333
4   5.0  50.0  0.100000
5   0.0   0.0  0.000000

This solution is slower than the one proposed by Jeff:
df.loc[:, 'c'] = df.apply(div('a', 'b'), axis=1)
# 1.27 ms ± 113 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

df.loc[:, 'c'] = df.a/df.b.replace({ 0 : np.inf })
# 651 µs ± 44.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

A: Normally when dividing by zero in Panda the value is set to infinite (np.inf). To avoid infinite values, use divide and replace, e.g.
df['one'].div(df['two']).replace(np.inf, 0)

See:

*

*Handling division by zero in Pandas calculations

*dropping infinite values from dataframes in pandas?

A: To spell out the different behavior of pandas for columns of different dtypes, note that pandas supports division by zero for columns with numeric dtype (such as float and int64) by returning a result of inf, but for columns of object type, it raises a ZeroDivisionError exception.
See my answer to a related question for examples.


text:
Q: How to set currentUser emailVerified: true in the browser (replace actual email verification)? I want to let the users to verify their email by entering the code after signing up that they would receive. (to replace email verification)
What should be the way to set the "emailVerified" current user's object property to true?
if (userCodeInput === verificationCode) {

    currentUser.updateProfile({
    emailVerified: true,
    displayName: "name changed"

    }).then(function() {
    // Update successful.
    }).catch(function(error) {
    // An error happened.
    });
}

works for displayName but not for emailVerified.

A: This probably can be done in the admin-sdk, but not on the client sdk.
https://firebase.google.com/docs/auth/admin/manage-users#update_a_user
Which makes sense since user should not have the power to bypass the verification flow, but admins should.


text:
Q: Gradle - compileJava - remove compile Warnings We use Gradle 2.1 and java plugin. During compileJava different warnings occur, for example:
warning: [options] bootstrap class path not set in conjunction with -source 1.7
Note: ../SomeClass.java uses or overrides a deprecated API.

We know what they mean but won't fix them (don't ask, other thread :)  Is there a way to avoid these messages somehow? They disturb the output a lot:
:project1:compileJava
warning: [options] bootstrap class path not set in conjunction with -source 1.7
Note: SomeClass.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 warning
:project1:processResources
:project1:classes
:project1:jar
:project2:compileJava
warning: [options] bootstrap class path not set in conjunction with -source 1.7
1 warning
:project2:processResources
:project2:classes
:project2:jar
:project2:war

Isn't is possible for example to redirect the stderr stream during compileJava so that we can grep out the warnings?
Or is there another way?

A: try this:
tasks.withType(JavaCompile) {
    options.warnings = false
}

A: Try adding:
options.compilerArgs += '-Xlint:-deprecation'

A: No answer posted so far that currently works (Gradle 4.0.1), so here's what does work:
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"

A: I think it really depends on the warnings. For the warnings I was getting, this worked:
    tasks.withType(JavaCompile) {
        options.compilerArgs += ["-nowarn", "-XDenableSunApiLintControl"]
    }

Sanity restored.


text:
Q: StructureMap Constructor Injection without Interface? I'm setting up a MVC project.  It looks like this
EfDbContext : IDbContext { ... }

MyStuff : IMyStuff { ... }

MyService : IMyService {
   List<things> GetSomething(IDbContext context, IMyStuff stuff) { ... }
}

MyController : Controller {
   ActionResult MyAction(IMyService service) { ... }
}

I use StructureMap.MVC to resolve all the constructor dependencies, plus setter injection for auditing and logging in custom ActionFilters.  The only thing I have to manually specify in the IoC is the connection string for IDbContext, everything else just automagically worked!
Until I read some articles that says, it smells to have 1:1 ratio between class and interface.  My application is quite simple, there will never be different implementation of IMyStuff or IMyService.  The only reason I have them is so that they can be injected and unit tested (I used Rhino but start to like NSubstitue).
Is there way I can get rid of the interface and inject the concrete class directly?  So it looks like
GetSomething(IDbContext context, MyStuff stuff) {}
MyAction(MyService service) {}

Of course, I still want all the convention based auto wiring with StructureMap, so I don't have to specify them one by one.
Thanks.


text:
Q: Symfony2: Show IP as string and save IP as INT I have an Entity in Symfony called Ip and I save my IP address as integer - I use the IP as primary key, too.
But when I display and enter the IP in a form or list I want to convert it to a IP, e.g. 127.0.0.1 is saved as 2130706433.
I created the forms with the CRUD generator.
My entity comes here:
<?php

namespace IS\ClearanceBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * IS\ClearanceBundle\Entity\Ip
*/
class Ip
{
/**
 * @var bigint $ip
 */
private $ip;

/**
 * @var integer $high
 */
private $high;

/**
 * @var string $hoster
 */
private $hoster;

/**
 * @var datetime $scandate
 */
private $scandate;

/**
 * @var integer $id
 */
private $id;

/**
 * @var IS\ClearanceBundle\Entity\Clearance
 */
private $clearance;

public function __construct()
{
    $this->clearance = new \Doctrine\Common\Collections\ArrayCollection();
}

/**
 * Set ip
 *
 * @param bigint $ip
 */
public function setIp($ip)
{
    $this->ip = $ip;
}

/**
 * Get ip
 *
 * @return bigint
 */
public function getIp()
{
    return $this->ip;
}

/**
 * Set high
 *
 * @param integer $high
 */
public function setHigh($high)
{
    $this->high = $high;
}

/**
 * Get high
 *
 * @return integer
 */
public function getHigh()
{
    return $this->high;
}

/**
 * Set hoster
 *
 * @param string $hoster
 */
public function setHoster($hoster)
{
    $this->hoster = $hoster;
}

/**
 * Get hoster
 *
 * @return string
 */
public function getHoster()
{
    return $this->hoster;
}

/**
 * Set scandate
 *
 * @param datetime $scandate
 */
public function setScandate($scandate)
{
    $this->scandate = $scandate;
}

/**
 * Get scandate
 *
 * @return datetime
 */
public function getScandate()
{
    return $this->scandate;
}

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Add clearance
 *
 * @param IS\ClearanceBundle\Entity\Clearance $clearance
 */
public function addClearance(\IS\ClearanceBundle\Entity\Clearance $clearance)
{
    $this->clearance[] = $clearance;
}

/**
 * Get clearance
 *
 * @return Doctrine\Common\Collections\Collection
 */
public function getClearance()
{
    return $this->clearance;
}
}

And here is my Controller:
<?php

namespace IS\ClearanceBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use IS\ClearanceBundle\Entity\Ip;
use IS\ClearanceBundle\Form\IpType;

/**
* Ip controller.
*
* @Route("/ip")
*/
class IpController extends Controller
{
/**
 * Lists all Ip entities.
 *
 * @Route("/", name="ip")
 * @Template()
 */
public function indexAction()
{
    $em = $this->getDoctrine()->getEntityManager();

    $entities = $em->getRepository('ISClearanceBundle:Ip')->findAll();

    return array('entities' => $entities);
}

/**
 * Finds and displays a Ip entity.
 *
 * @Route("/{id}/show", name="ip_show")
 * @Template()
 */
public function showAction($id)
{
    $em = $this->getDoctrine()->getEntityManager();

    $entity = $em->getRepository('ISClearanceBundle:Ip')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Ip entity.');
    }

    $deleteForm = $this->createDeleteForm($id);

    return array(
        'entity'      => $entity,
        'delete_form' => $deleteForm->createView(),        );
}

/**
 * Displays a form to create a new Ip entity.
 *
 * @Route("/new", name="ip_new")
 * @Template()
 */
public function newAction()
{
    $entity = new Ip();
    $form   = $this->createForm(new IpType(), $entity);

    return array(
        'entity' => $entity,
        'form'   => $form->createView()
    );
}

/**
 * Creates a new Ip entity.
 *
 * @Route("/create", name="ip_create")
 * @Method("post")
 * @Template("ISClearanceBundle:Ip:new.html.twig")
 */
public function createAction()
{
    $entity  = new Ip();
    $request = $this->getRequest();
    $form    = $this->createForm(new IpType(), $entity);
    $form->bindRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('ip_show', array('id' => $                                                                            entity->getId())));

    }

    return array(
        'entity' => $entity,
        'form'   => $form->createView()
    );
}

/**
 * Displays a form to edit an existing Ip entity.
 *
 * @Route("/{id}/edit", name="ip_edit")
 * @Template()
 */
public function editAction($id)
{
    $em = $this->getDoctrine()->getEntityManager();

    $entity = $em->getRepository('ISClearanceBundle:Ip')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Ip entity.');
    }

    $editForm = $this->createForm(new IpType(), $entity);
    $deleteForm = $this->createDeleteForm($id);

    return array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    );
}

/**
 * Edits an existing Ip entity.
 *
 * @Route("/{id}/update", name="ip_update")
 * @Method("post")
 * @Template("ISClearanceBundle:Ip:edit.html.twig")
 */
public function updateAction($id)
{
    $em = $this->getDoctrine()->getEntityManager();

    $entity = $em->getRepository('ISClearanceBundle:Ip')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Ip entity.');
    }

    $editForm   = $this->createForm(new IpType(), $entity);
    $deleteForm = $this->createDeleteForm($id);

    $request = $this->getRequest();

    $editForm->bindRequest($request);

    if ($editForm->isValid()) {
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('ip_edit', array('id' => $                                                                            id)));
    }

    return array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    );
}

/**
 * Deletes a Ip entity.
 *
 * @Route("/{id}/delete", name="ip_delete")
 * @Method("post")
 */
public function deleteAction($id)
{
    $form = $this->createDeleteForm($id);
    $request = $this->getRequest();

    $form->bindRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getEntityManager();
        $entity = $em->getRepository('ISClearanceBundle:Ip')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Ip entity.'                                                                            );
        }

        $em->remove($entity);
        $em->flush();
    }

    return $this->redirect($this->generateUrl('ip'));
}

private function createDeleteForm($id)
{
    return $this->createFormBuilder(array('id' => $id))
        ->add('id', 'hidden')
        ->getForm()
    ;
}
}

And here the form:
 <?php

 namespace IS\ClearanceBundle\Form;

 use Symfony\Component\Form\AbstractType;
 use Symfony\Component\Form\FormBuilder;

 class IpType extends AbstractType
 {
 public function buildForm(FormBuilder $builder, array $options)
 {
    $builder
        ->add('ip')
        ->add('high')
        ->add('hoster')
        ->add('scandate')
        ->add('clearance','entity', array('class'=>'IS\ClearanceBundle\Entity\Clearance', 'property'=>'id','required'=>false, 'multiple'=>true))
    ;
}

public function getName()
{
    return 'is_clearancebundle_iptype';
}
}

Thanks for any help!

A: IMO if you want do it, you should use data transformer http://symfony.com/doc/current/cookbook/form/data_transformers.html and implement __toString for your entity IP.
EDIT:
Created sample at gist: https://gist.github.com/3086241


text:
Q: Anonymous type broken after linq select I've got a strange problem with an anonymous type. Lets jump right into my code:
var anon = new[]
{
    new { Var1 = 20, Var2 = 40, Var3 = 70 },
    new { Var1 = 25, Var2 = 45, Var3 = 75 }
};

// found should be of type { int Var1, int Var2, int Var3 }
var found = anon.Select(x => x).Where(x => x.Var1 == 25);

var test = found.Var1 // <-- not defined error here

Quite easy question:
Why cant I access Var1 after using a linq select?
Sorry for this topic, couldnt think of a better description for this.

A: Because Where returns you IEnumerable<>, not a single element.
You can use First or FirstOrDefault to get first element.
found.First().Var1

A: Where returns an IEnumerable and is used for 0-n results.
If you'll always have 1 result you want Single.
If you'll have 0-1 results you want SingleOrDefault.
If you'll have 1-n results you want First.
If you'll have 0-n results you want FirstOrDefault.

A: I don't have a C# compiler on this machine, but probably its because found is an Iterable of the anonymus type. Try use anon.Select(x => x).Where(x => x.Var1 == 25).First() or anon.Select(x => x).Where(x => x.Var1 == 25).FirstOrDefault(). Also, i am pretty sure you dont need the select, you could just use anon.Where(x => x.Var1 == 25).First()


text:
Q: Sound not working on MacBook Air mute box is checked and greyed out My audio on my MacBook Air is not working. When I go into System Preferences and go to Sound, the mute box is checked and greyed out. My Mac can't play anything including iTunes and YouTube, even system sounds such as the sound when you send an email.
I have reset the NVRAM and repaired the disk using Disk Utility. I also went into Terminal and ran sudo killall coreaudiod but that didn't work either.
When I turn on the laptop it doesn't make a startup chime like it normally would. My headphone jack does not have a red light in it and it shows I have no audio output or input.

A: Devon, I did some investigating on the apple support site and found this.

1) Delete both files in YourHardDrive->Library->Preferences->Audio -> (both .plist files in this folder)
com.apple.audio.DeviceSettings.plist
com.apple.audio.SystemSettings.plist

2) Make sure to empty your trash.

3) Reboot

Let us know if this works!

Apple Support Reference: https://discussions.apple.com/message/23538716#23538716

A: I had precisely this problem with a MacBook Air. The Air was propped on its side and dropped onto the floor. Afterwards the sounds controls were greyed out.
The problem is that the cable between the sound card and the motherboard had loosened. I opened up the laptop, removed the cable and re-attached it. The problem went away.


text:
Q: Integral convergence of (-1) floor Question:
does this integral converge? $\int _0^\infty (-1)^{\lfloor x^2 \rfloor}dx$
Thoughts:
We tried using Cauchy to prove divergence. We don't know if that's true or not.

A: We have
$$k\le x^2<k+1\iff \sqrt k\le x<\sqrt{k+1}$$
so
$$\int_0^\infty(-1)^{\lfloor x^2 \rfloor}dx=\sum_{k=0}^\infty\int_{\sqrt{k}}^{\sqrt{k+1}}(-1)^kdx=\sum_{k=0}^\infty(-1)^k(\sqrt{k+1}-\sqrt k)=\sum_{k=0}^\infty\frac{(-1)^k}{\sqrt{k+1}+\sqrt k}$$
and the last sum is convergent by Leibniz theorem.


text:
Q: JavaFX VBox Layout I have written a code using VBox as layout. I want the button to appear at the top row, and then draw 2 horizontal lines which should be at y=200 and 300 in the 400x400 scene. But the output shows the lines at different co-ordinates I give it.
I understand this is because of the Layout I am defining. My question is this:
1) Can I somehow draw lines at true co-ordinates keeping the same layout?
2) If not, which javafx layout would be best for this operation?
3) Assuming there is a MenuBar instead of that button, then which layout would be most suitable?
package practise;

import java.util.Random;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.stage.Stage;

public class Practise extends Application {

    private int c = 0;

    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        VBox root = new VBox();

        Group group = new Group();

        final Line l1 = new Line(0,200,400,200);
        final Line l2 = new Line(0,300,400,300);

        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
                }
            }
        );

        l1.setStroke(Color.YELLOW);
        l1.setStrokeWidth(2);
        l1.setLayoutX(0);
        l1.setLayoutY(0);
        l2.setStroke(Color.YELLOW);
        l2.setStrokeWidth(2);
        l2.setLayoutX(0);
        l2.setLayoutY(0);

        group.getChildren().add(l1);
        group.getChildren().add(l2);
        root.getChildren().add(btn);
        root.getChildren().add(group);

        Scene scene = new Scene(root, 400, 400, Color.WHITE);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

A: If you want set absolute positions you should use an AnchorPane.
Only change VBox to AnchorPane and will work.

A: 1) Yes this is possible. Setting the managed property to false results in the parent not layouting the child. This won't make the next node being positioned below the line though.
Button btn = new Button();
VBox root = new VBox();

final Line l1 = new Line(0, 200, 400, 200);
final Line l2 = new Line(0, 300, 400, 300);

l1.setManaged(false);
l2.setManaged(false);

btn.setText("Say 'Hello World'");
btn.setOnAction((ActionEvent event) -> {
    System.out.println("Hello World!");
});

l1.setStroke(Color.YELLOW);
l1.setStrokeWidth(2);
l2.setStroke(Color.YELLOW);
l2.setStrokeWidth(2);
root.getChildren().addAll(btn, l1, l2, rect);

2)
GridPane
allows to specify constraints on the row size.
Button btn = new Button();
Rectangle rect = new Rectangle(400, 10);
GridPane root = new GridPane();
root.getRowConstraints().add(new RowConstraints(200));

final Line l1 = new Line(0, 0, 400, 0);

btn.setText("Say 'Hello World'");
btn.setOnAction((ActionEvent event) -> {
    System.out.println("Hello World!");
});

l1.setStroke(Color.YELLOW);
l1.setStrokeWidth(2);
root.addColumn(0, btn, l1, rect);

SplitPane
could do this too with some adjustments.
Button btn = new Button();
Rectangle rect = new Rectangle(400, 10);

// wrap contents in resizeable Nodes
SplitPane root = new SplitPane(new Pane(btn), new Pane(rect));

// place divider in the middle
root.setDividerPositions(0.5);
root.setOrientation(Orientation.VERTICAL);
root.getStyleClass().add("line-split");
root.getStylesheets().add(getClass().getResource("style.css").toExternalForm());

root.skinProperty().addListener((observable, oldValue, newValue) -> {
    // don't allow resizing
    newValue.getNode().lookupAll(".split-pane-divider").stream().forEach(divider -> divider.setDisable(true));
});

btn.setText("Say 'Hello World'");
btn.setOnAction((ActionEvent event) -> {
    System.out.println("Hello World!");
});

CSS

.line-split .split-pane-divider {
    -fx-min-height: 2;
    -fx-max-height: 2;
    -fx-background-color: yellow;
}

3) MenuBar is a Node too. There seems to be no reason to treat it differently to a Button.


text:
Q: Uncaught SyntaxError: unexpected token: ':' Estoy revisando un proyecto que se creó en el 2016. Revisando el código el depurador de Firefox me señala que hay un error:

   Uncaught SyntaxError: unexpected token: ':'
       jQuery 14
       verlistadoa http://localhost/aam/vistas/js/funcion_cal_a.js:11
       jQuery 7
       verlistadoa http://localhost/aam/vistas/js/funcion_cal_a.js:8
       <anonymous> http://localhost/aam/vistas/js/funcion_cal_a.js:3

Revisé el archivo y las líneas donde me marca el error y si digamos que encontré una omisión sobre la referencia que me indica Firefox.

$(document).ready(function(){
    verlistadoa()

})
function verlistadoa(){

            $.post("libsfile/list_cal_cat_a.php", {
            }, function(data){
              $("#calCategoriaA").html(data);
            });
}

una vez revisada la documentación modifiqué el script en base a este señalamiento:

$(document).ready(function(){
    verlistadoa();  <<-- se añadio el ;

})
function verlistadoa(){

            $.post("libsfile/list_cal_cat_a.php", {
            }, function(data){
              $("#calCategoriaA").html(data);
            });
}

Sin embargo me sigue señalando lo mismo.
¿Me podrían echar la mano a identificar donde se supone que hace falta añadir otra ;? porque de verdad estoy como se dice que se tiene una  "ceguera de taller".


text:
Q: Saving the response of $.get as a variable function foobar(){
    $.ajaxSetup ({cache: false});
    var response = $.get("http://mysite.com/return.php")
    document.write(response);
}

I'm trying to save the response from this as a variable. How can I do that?

A: $.get is an asynchronous AJAX call - your document.write line is going to execute long before the server even sends you a response.
If you want to access the return value, you'll need to do it in a callback, like so:
$.get('/return.php', function(response) {
  document.write(response);
});

A: You wont be able to do that unless you use $.ajax with the async option set to false. Otherwise, the callback used for AJAX will execute after the document is closed for writing, and you'll overwrite your entire page.
Instead, use load to dump obligatory HTML into the page asynchronously.

A: $.get provides a success() function for handling the response...
function foobar(){
    var response = null;
    $.ajaxSetup ({cache: false});
    $.get("http://mysite.com/return.php").success(function(respText) {
            response = respText;
            document.write(response);
    });
}

A: You can use the $.load() function for this as this is it's intended purpose
See http://api.jquery.com/load/
From the manual:
This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched element to the returned data. This means that most uses of the method can be quite simple:
$('#result').load('ajax/test.html');


text:
Q: How many vtables gets created in below program? I have seen few exmples showing vtables concepts in stackoverflow but given examples are only for single class, when we derived class from two abstract classes then how many vtables will be created for that class?
class A {
 public :
         virtual void func_1() = 0;
};

class B {
 public :
         virtual void func_2() = 0;
};

class C : public A, public B {
  public :
          void func_1()
          {
            cout << "func_1" << endl;
          }
          void func_2()
          {
            cout << "func_2" << endl;
};

In above example how many vtables will be there for class C, and will class A and class B have any vtables??

A: In this specific case, C has one vtable and A and B have none.  You can see this for yourself by out-of-lining C's member functions, so that the vtable will actually be emitted, and correcting the other compile errors:
extern "C" int puts(const char *);

struct A { virtual void func_1() = 0; };
struct B { virtual void func_2() = 0; };

struct C : A, B
{
  void func_1();
  void func_2();
};

void C::func_1() { puts("func_1"); }
void C::func_2() { puts("func_2"); }

... compiling to an object file, and then looking at the symbols:
$ gcc -c test.cc
$ nm test.o | c++filt
                 U puts
0000000000000000 T C::func_1()
000000000000001a T C::func_2()
0000000000000033 T non-virtual thunk to C::func_2()
0000000000000000 V typeinfo for A
0000000000000000 V typeinfo for B
0000000000000000 V typeinfo for C
0000000000000000 V typeinfo name for A
0000000000000000 V typeinfo name for B
0000000000000000 V typeinfo name for C
0000000000000000 V vtable for C
                 U vtable for __cxxabiv1::__class_type_info
                 U vtable for __cxxabiv1::__vmi_class_type_info

The compiler can prove that only the basic vtable for C is necessary because none of the classes have data or nontrivial constructors, and because A and B can't be instantiated directly.  In the general case, there might be multiple vtables for all three classes.  The exact rules for when multiple vtables are necessary are very complicated and I'm not going to try to summarize them here.  They are spelled out in the "Itanium" C++ ABI, sections 2.5 and 2.6, but they probably won't make much sense if you're not accustomed to reading standardese and deeply familiar with the dark corners of C++; unfortunately I am not aware of any good overview of this for beginners.  (It's been historically assumed that either you don't care or you are already an expert.)  ("Itanium" is in quotes above because the spec was written with Itanium in mind, but the design was then adopted very widely.  Unless you're using MSVC, you are probably getting this C++ ABI.)  (To illustrate just how dark these dark corners are: I helped write this ABI spec, and yet I have no freaking idea why GCC thinks it needs to emit a "non-virtual thunk to C::func_2".)

A: The only way to know for sure is to compile it and look, but in this case it's a virtual certainty that there will only be 1 vtable (maybe even 0 if you don't export the class). If either of the base classes weren't abstract the answer would be different depending on the compiler.


text:
Q: asp.net overwriting files simultaneously I have an asp.net website with a C# code-behind that, when processing, writes to a log file in the App_Data folder of the website, and also generates PDF files.  Using StreamWriter class.  Users prepare their data on one page, then hit a button which takes them to another page that does all of the data processing.  The data is passed over from the first page to the second using Session variables.
My issue is that when two users hit the button to process the data simultaneously, one of the users will eventually get a "Cannot write to a closed log file" error, and the other will process through normally.
Each file name is unique.  I have a database sequence number in the file name, so the files will never overlap.
What's strange is, data that is to be written in one file will appear in the other user's file, and it will be omitted from the proper user's file.
I don't know if this is a StreamWriter issue, an IIS issue, a session issue, or something else.


text:
Q: Allow specific file in htaccess that is rewriting all subdirectories Not sure if I titled my question accurately.  I have a directory structure like this:
example.com/edit/43424242/
Where the number at the end is not actually a folder.  It's really just a variable that I want to use at the /edit/index.php directory.
I tried using this in my .htaccess file at the root directory:
RewriteEngine ON
RewriteRule %{QUERY_STRING} ^$
RewriteRule ^edit/(.*)/?$ edit/index.php?var=$1 [NC,L]

But that didn't work because it messes up my AJAX post to another file in that directory /edit/post.php
So I thought maybe I need to modify my .htaccess file so that I can still retrieve the subdirectories as a variable and still be able to use post.php or perhaps modify .htaccess so that it allows index.php to communicate with post.php.
Any ideas?

A: RewriteRule %{QUERY_STRING} ^$

It is not enough for check for empty query string as it will not prevent this rule affecting serving real files and directories.
You may use this rule:
RewriteEngine ON

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^edit/([\w-]+)/?$ edit/index.php?var=$1 [NC,L,QSA]


text:
Q: how to check modified function formals In my neverending quest to break things,
consider:
gbar<-function(x,y,x,a) x+2*y-4*a
Error: repeated formal argument 'x' on line 1

R properly checks my defined function for illegal formals.
But if I manually foul things up:
 ffoo<-function(x,y,a) x+2*y-4*a
formals(ffoo)<-c(x=7, formals(ffoo))

Then I'll only find out under certain circumstances that something is invalid.
ffoo(3,4,5,6) will execute properly (although probably not giving me the answer I expected), as will ffoo(y=3,a=2); whereas ffoo(x=5,y=3,a=2) will throw an error about ambiguous argument names.
So: is there any base-R or advanced utility package with a function to do 'sanity' checking on the formals of an existing function?

A: Edit:
If you simply want to check for duplicated arguments, you can do this:
any(duplicated(names(formals(ffoo))))
# [1] TRUE

As Hadley mentions in his second comment below, dput() isn't guaranteed to give you a good/complete representation of a function, so there may be functions for which the approach described in my original answer (left in place below) fails.

Original answer:
As is hinted at in the C code pointed to by Andrie, this is apparently a check that R performs while parsing (not evaluating) a call to function(). That's why you were able to circumvent the check with your call to formals<-, and it's why the following (for example) also avoids getting checked. In both cases, the function is modified/created without parsing a call to function().
eval(call("function", formals(ffoo), body(ffoo)))
# function (x = 7, x, y, a)
# x + 2 * y - 4 * a

R's parsing machinery isn't typically exposed in user-visible R functions, so I'd guess there's no ready-made function R function to perform this check. You could, though, perform the exact same set of checks that R does when you source the expression or enter it at a at a command line by converting the function definition to its character representation and then attempting re-parse it yourself.
Here's the general idea:
parse(text = capture.output(dput(ffoo)))
# Error in parse(text = capture.output(dput(ffoo))) :
#   repeated formal argument 'x' on line 1

To wrap the check up as a function do something like this:
isParseableFunction <- function(x) {
    tryCatch(is.function(x) &
             is.expression(parse(text = capture.output(dput(x)))),
             error = function(e) FALSE)
}

isParseableFunction(data.frame)
# [1] TRUE
isParseableFunction(mean)
# [1] TRUE
isParseableFunction(ffoo)
# [1] FALSE
isParseableFunction(99)
# [1] FALSE


text:
Q: Deleted CRUD Table Facade.class still being generated: how to remove? I removed a table from my Derby database, re-generated the 'Entity classes from database' and regenerated the CRUD files in Netbeans 7.0.1 but it keeps generating a Facade.class file for the deleted table: 'SEARCH_CRITERIA_TBL'.
I have deleted everything I can find related to the CRUD and done a clean and rebuild but it insists on regenerating the file:
\NetBeansProjects\Server\build\web\WEB-INF\classes\JSFBeans\SearchCriteriaTblFacade.class
The project compiles but the server fails to start with the following error:

Blockquote
  WARNING: Exception while starting bundle com.sun.enterprise.osgi-adapter [154]
  org.osgi.framework.BundleException: Activator start error in bundle com.sun.enterprise.osgi-adapter [154].
      at org.apache.felix.framework.Felix.activateBundle(Felix.java:1751)
      at org.apache.felix.framework.Felix.startBundle(Felix.java:1622)
      at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:915)
      at org.jvnet.hk2.osgimain.Main.start(Main.java:140)
      at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:640)
      at org.apache.felix.framework.Felix.activateBundle(Felix.java:1700)
      at org.apache.felix.framework.Felix.startBundle(Felix.java:1622)
      at org.apache.felix.framework.Felix.setActiveStartLevel(Felix.java:1077)
      at org.apache.felix.framework.StartLevelImpl.run(StartLevelImpl.java:264)
      at java.lang.Thread.run(Thread.java:619)

Caused by: java.lang.ClassFormatError: Absent Code attribute in method that
    is not native or abstract in class file JSFBeans/SearchCriteriaTblFacade

at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at org.glassfish.web.loader.WebappClassLoader.findClass(WebappClassLoader.java:920)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1430)
at com.sun.enterprise.deployment.annotation.impl.ModuleScanner.getElements(ModuleScanner.java:247)
at com.sun.enterprise.deployment.archivist.Archivist.processAnnotations(Archivist.java:541)
at com.sun.enterprise.deployment.archivist.Archivist.readAnnotations(Archivist.java:433)
at com.sun.enterprise.deployment.archivist.Archivist.readAnnotations(Archivist.java:420)
at com.sun.enterprise.deployment.archivist.Archivist.readRestDeploymentDescriptors(Archivist.java:396)
at com.sun.enterprise.deployment.archivist.Archivist.readDeploymentDescriptors(Archivist.java:373)
at com.sun.enterprise.deployment.archivist.Archivist.open(Archivist.java:238)
at com.sun.enterprise.deployment.archivist.Archivist.open(Archivist.java:247)
at com.sun.enterprise.deployment.archivist.Archivist.open(Archivist.java:208)
at com.sun.enterprise.deployment.archivist.ApplicationFactory.openArchive(ApplicationFactory.java:148)
at org.glassfish.javaee.core.deployment.DolProvider.load(DolProvider.java:162)
at org.glassfish.javaee.core.deployment.DolProvider.load(DolProvider.java:79)
at com.sun.enterprise.v3.server.ApplicationLifecycle.loadDeployer(ApplicationLifecycle.java:612)
at com.sun.enterprise.v3.server.ApplicationLifecycle.setupContainerInfos(ApplicationLifecycle.java:554)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:262)
at com.sun.enterprise.v3.server.ApplicationLoaderService.processApplication(ApplicationLoaderService.java:362)
at com.sun.enterprise.v3.server.ApplicationLoaderService.postConstruct(ApplicationLoaderService.java:185)
at com.sun.hk2.component.AbstractWombImpl.inject(AbstractWombImpl.java:174)
at com.sun.hk2.component.ConstructorWomb$1.run(ConstructorWomb.java:87)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.hk2.component.ConstructorWomb.initialize(ConstructorWomb.java:84)
at com.sun.hk2.component.AbstractWombImpl.get(AbstractWombImpl.java:77)
at com.sun.hk2.component.SingletonInhabitant.get(SingletonInhabitant.java:58)
at com.sun.hk2.component.LazyInhabitant.get(LazyInhabitant.java:107)
at com.sun.hk2.component.AbstractInhabitantImpl.get(AbstractInhabitantImpl.java:60)
at com.sun.enterprise.v3.server.AppServerStartup.run(AppServerStartup.java:236)
at com.sun.enterprise.v3.server.AppServerStartup.start(AppServerStartup.java:128)
at com.sun.enterprise.module.bootstrap.Main.launch(Main.java:457)
at com.sun.enterprise.module.bootstrap.Main.launch(Main.java:401)
at org.jvnet.hk2.osgiadapter.HK2Main.start(HK2Main.java:125)
at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:640)
at org.apache.felix.framework.Felix.activateBundle(Felix.java:1700)
... 9 more

Searches of the net only tell me what the 'JSF from Entity Classes' does not how it works internally. No doubt I am searching on the wrong terms...
Does anyone know where the Facade.classes create data is kept or can anyone tell me what terms I need to search on to find out? I have searched the entire project and found no reference to 'SearchCriteriaTbl' or 'SEARCH_CRITERIA_TBL'. I have manually deleted the SearchCriteriaTblFacade.class file, but it still reappears when the project is cleaned and rebuilt.
Kind thanks in advance.

A: Workaround: I re-inserted the deleted table into the database, regenerated the entity classes and CRUD files, and recompiled. Then removed the table again, re-created the entity classes from database and re-did CRUD creation. I then did a refactor delete rather than a normal delete of the unneeded files. After about three clean and recompiles it eventually sorted itself out and is now working.


text:
Q: [WSO2][ESB] Validation Mediator giving problems although on-fail element has children I have configured the following validate mediator in my project:
            <validate>
            <schema key="gov:custom/testReg/AddressId.json"/>
            <resource key="gov:custom/testReg/AddressId.json" location="default_location"/>
            <on-fail>
                <payloadFactory description="failureResponse" media-type="json">
                    <format>{
                                                   "StatusCode": 0,
                                                   "ErrorCode": "801001",
                                                   "ErrorDescription": "Invalid request parameters, some fields are empty"
                                     }
                    </format>
                    <args/>
                </payloadFactory>
                <respond description="failureResponse"/>
            </on-fail>
        </validate>

Yet when I save the API Resource, it throws the following error:
A non-empty <on-fail> child element is required for the <validate> mediator

I have tried to ignore the errors and proceed to build the project and deploy it however there were errors in the server after it was deployed.
Can some one help me out on this one.
Thanks in advance.