How to make a query on nested keys in a Firebase Realtime Database?

Question: I'm trying to build a leaderboard for my users inside my realtime db.
That's the structure of my db:
_firebase_db_url {
  users: {
     user1: {
        displayName: "name",
        ...some_other_infos...
        games: {
           game1: {
               lastScore: 123,
               timePlayed: 120
           },
           game2: {
               lastScore: 456,
               timePlayed: 360
           },
           ...
        }
     }
  },
  games: {
      0 : {
         "id": "game1",
         "description": "..."
      },
      1 : {
         "id": "game1",
         "description": "..."
      },
      ...
}

What I'm trying to do is making a query on the db to get max 10 player ordered by lastScore on a certain game.
I've tried so far:
db.ref('/users')
  .orderByChild(`lastScore`)
  .limitToFirst(10)
  .get()
  .then((val) => console.log(val.val()));

This prints my users but not ordered by game scores
I've also tried to make a loop on all games and then the query on the db:
   db.ref('/games')
     .get()
     .then(
       (result) => {
         const gamesList = result.val();
         const gamesIdsArray = []
         Object.values(gamesList)
           .forEach(game => {
               gamesIdsArray.push(game.id)
           })
         return gamesIdsArray;
       }).then(   // Once I got entirely my array filled with the games ID, I proceed
         (gamesIdsArray) => {
            gamesIdsArray.forEach(gameId => {
            db.ref('/users')
              .orderByChild(`lastScore`)
              .limitToFirst(10)
              .get()
              .then((val) => console.log(val.val()))
            })
         }
       )

This prints for the number of games all my users not ordered by games. (It prints the users also if them don't have the specific game obj: if I'm looping on game5 the query prints 10 users including users that don't have the filed game5 inside their games section).
Other tries:
 db.ref('/users')
   .child('games')
   .child(`${req.userId}/games/${gameId}`) //passing the userId inside my https.onRequest() function
   .orderByChild(`lastScore`)
   .limitToFirst(10)
   .get()
   .then((val) => console.log(val.val()))

Still nothing useful
db.ref('/users/{userId}/games{gameId}/lastScore')
   .orderByChild(`lastScore`)
   .limitToFirst(10)
   .get()
   .then((val) => console.log(val.val()))

Still nothing useful
I've also included in my realtime db rules all the .indexOn I've tried so far.
Nothing helped.
What am I doing wrong?
What should I try?
Should I switch to Firestore to keep user data?

[ EDITED ]
I've slightly edited my db set as follows based on Frank's answer:
db {
    users: {
        "user1": {
            name: "name1",
            ... some other infos
        },
        "user2": {
            name: "name2",
            ... some other infos
        },
        ...
    }
    games: {
        "game1": {
            "user1": {
                bestScore: 123
            },
            "user2": {
                bestScore: 234
            }
        },
        "game2": {
            "user1": {
                bestScore: 765
            },
            "user2": {
                bestScore: 543
            }
        }
    }

}

Query that prints the users but not ordered:
db.ref("games")
  .child(gameId) //getting my gameId var from request.data.gameId from my onCall function
  .orderByChild("bestScore")
  .once('value', (res) => {
      console.log(res.val())
      return res.val()
   })

And still getting the users not ordered
Comment: What do you mean by "on a certain game"?
Comment: @AlexMamo as you see in my database I want to make a leaderboard for each game (game1, game2 and so on)
Comment: Can you share the snapshot of your db ?
Comment: Your database structure is will not scale and for your current query to be excuted correctly you will need index on `lastScores` field according to this [answer](https://stackoverflow.com/a/53302804/20239914) as your `lastScores` resides inside a dynamic node which cannot be indexed statically you will have to change your db structure as explained in that answer. Hope it helps.
Comment: @RohitKharche of which query?
Comment: @nico_1512 Your 2nd query is getting failed because you need index to be made on `bestScore` which you can do as follows : "games" : { ".indexOn" : ["bestScore"] } inside the database.rules file.
Comment: @RohitKharche I already have the `.indexOn` in my db rules
Comment: @RohitKharche in the edited section
Answer: You're combining data of multiple entity types (users, and game scores) under your users branch, which goes against Firebase's guidance on structuring data, specifically the section on keeping the data structure flat.
To allow your query, add an additional top-level node, where you track the scores of various users for a specific game. Something like this:
game_user_scores: {
  "game1": {
    "user1": {
      lastScore: 123,
      timePlayed: 120
    },
    ...
  },
  "game2": {
    "user1": {
      lastScore: 456,
      timePlayed: 360
    },
    ...
  },
  ...
}

Now you can query the top scorers for a specific game with:
db.ref("users")
  .child("game_user_scores/game1")
  .orderByChild("lastScore")
  .limitToFirst(10)

Your second problem is caused by the fact that you use val() immediately on the result. That gets the result as a JSON value, and there's no room for ordering information in that.
To process the results in order, use the built-in forEach method of the snapshot you get back:
((res) => {
  res.forEach((snapshot) => {
    console.log(snapshot.val())
  });
})

Comment: @frankvonpuffelen checl my update please
Comment: thanks so much! I've solved the problem with the same code form another answare (also made by you)


Removing posted by admin date from a contact form

Question: I am making a contact form in Drupal with using panels but in contact form it is showing posted by admin date. I want to remove these two things as shown in image.
Comment: What widgets are you using in panels?  Did you create a node just for the heading or are you using custom panel content?
Answer: There are multiple ways you can do it

For all content of same content type

Go to the content type for which you want to hide Author info.
Scroll down to see the tabs at the bottom and select Display settings.
Uncheck Display author and date information.
Save content type

For Single Node

Go to node.tpl.php and search for $submitted
Give below condition for you case
<code>if ( arg(0) == 'node' AND is_numeric(arg(1)) AND arg(2) == FALSE AND arg(1)==7) {  print $submitted; }
</code>


What can be said about these ratios of third and first derivatives?

Question: Let's say that we have function $u:\mathbb R_0\to \mathbb R$ with $u'(x)>0$, $u''(x)<0$, $u'''(x)>0$, $\lim_{x\to 0} u'(x) = \infty, \lim_{x\to 0}u'(x) = 0$.
Take $x_1 < x_2$. Does $$\frac{u'''(x_1)}{u'''(x_2)}\leq  \frac{u'(x_1)}{u'(x_2)}$$ always hold?
Thanks, I'm lost here.
Comment: ... and how can $\lim_{x \to 0} u'(x)$ be both "inf" (I assume $\infty$ and $0$?
Comment: What do you mean by R_0?
Comment: I would guess that this is from the positive reals to the reals and the second limit is as $x \to \infty$
Comment: For some basic information about writing math at this site see e.g. [here](http://meta.math.stackexchange.com/questions/5020/), [here](http://meta.stackexchange.com/a/70559/155238), [here](http://meta.math.stackexchange.com/questions/1773/) and [here](http://math.stackexchange.com/editing-help#latex).
Answer: No, the ratio $u'''/u'$ need not be monotone. Since there is no restriction on the fourth derivative, nothing prevents us from adding a spike to $u'''$ that will destroy its monotonicity without violating any other constraints.
More concretely, let $u$ be a function as in the statement. Let  $$v(x)=u(x)+  \delta \epsilon^3 \sin (2\pi \epsilon^{-1}x)\chi_{[1\le x\le 1+\epsilon]} \tag1$$
Ignoring insufficient smoothness* at $1$ and $1+\epsilon$, we see that $v$, $v'$ and $v''$ are within $\delta\epsilon $ of the corresponding $u$ derivatives. Also, $v'''-u''' $ is of order $\delta$. Fix $\delta$ small enough so that $v'''$ is positive. Now make $\epsilon$ very small. The added term in (1) has huge 4th derivative (first positive, then negative), and this makes  $v'''$ non-monotone.
(*) Instead of one period of sine function, one should use a smoother compactly supported function, such as convolution of one period of sine with a smooth bump function.


Does Hyper-V support SCSI Pass-through discs in a Server 2003 R2 VM?

Question: I'm running into some difficulties getting pass-through disks to be accessible to a Hyper-v server 2003 r2 virtual machine.
Host OS : Server 2008 R2 full w/Hyper-V role
Guest OS : Server 2003 R2 (Windows Home Server)
The guest's OS disk is a pass-through disk on the IDE controller (not the best solution, but I can live with it).
My storage disks will be pass-through disks on the SCSI controller. I'm able to see all of the disks that I'll be using for the VM on the host without issue.
The problem that I'm having is that I can't seem to get the guest OS to be able to 'see' the storage drives (as pass-through disks on the SCSI controller).
Here's what I'm doing :

On the host, the storage drive is set to 'Offline' just like the OS disk (this is required for pass-through to work).
In the VM, the storage drive is on the SCSI controller.
Hyper-V Integration Tools are installed in guest.

That's as far as I'm able to get. I don't see the drive in Computer Management, or in Windows Explorer (I've tried with an unformatted disk, as well as after formatting a partition). I am able to see a removable device that lists the disk's model number in the Guest, but I can't seem to access the storage. (I get an entry in Device Manager that needs drivers, but nothing on the Integration Tools disc works..)
Trouble-shooting steps I've tried :

If put the pass-through drive on the IDE controller, I can see it in the Guest.
If put the storage drive 'Online' in the host and create a VHD on it on the SCSI controller, I can see it in the Guest. I suppose I could create a fixed-size VHD that consumes the entire disk, but I'd rather not have that overhead.
I've also extracted the contents of the Integration Tools drivers (x86 and amd64) and tried pointing the disk controller to each of those, with no luck.

Can anyone offer suggestions as to how I can get this to work properly?
Answer: I suspect the disk is just offline in the guest.  Did you go do Disk Manager in the VM and bring it on line?
I have to say, though, it's not worth bothering with.  I'll bet that if you try to measure the performance overhead of putting fixed VHD on your disk and assigning that to the VM, you won't be able to tell the difference.  And if you use the VHD, you can migrate the VM more easily.  You can back it up.  Etc.
Comment: The disk isn't listed in Disk manager on the VM, all I see is the original OS disk. There's no prompt to initialize or anything like that (as happens with the two other ways that work mentioned above...)
Comment: mostly likely the problem is the disk is online on the host os!
Comment: also why are you using pass thru quite sure you won't gain a thing by doing this.
Comment: It says quite clearly in the question "On the host, the storage drive is set to 'Offline' just like the OS disk (this is required for pass-through to work)."
I'd appreciate any other suggestions...
Comment: I meant "offline in the guest," as I've changed the text above to read.  Is the VM SCSI driver installed?  Do you see it in the VM?  Perhaps you don't see your disk because the driver that exposes it isn't present.
Comment: I've tried installing every drive on the integration tools without any luck (that's why I had to do the manual extraction mentioned in the question). I don't see any indication of the drive at all in the VM.
I'm starting to think that the lack of visibility may have something to do with both the OS and storage drives being in a disk enclosure (I have a similar setup for another VM that's not seeing this behaviour).
I don't understand how that can make sense though since the host is able to see both drives without any issues. (Why would the VM need additional drivers to access the disks?..)
Answer: Yes, it does support SCSI pass-through.
I tried some different disk configurations and it seems as though my inability to see the disk in the VM via the SCSI controller was related to the fact that it was in a USB3 enclosure (along with the host disk). This worked fine for IDE pass-through though, and both disks were always visible in the host, so I'm still not sure quite what the problem was.
I could have also done as Jake suggested and used a VHD occupying the entire disk, but I'm looking for a situation were I have direct access to the storage (ie, not through a VHD).
I'm responding simply so that if someone else winds up here via searching, it might help them along.


Mount Block Device in LXD

Question: I have been experimenting with LXD on Ubuntu Server 16.04 and i'm trying to figure out how to mount a linux block device from the host in the container. I was able to successfully add the device using the command:
lxc config device add test sdb1 unix-block path=/dev/sdb1
When i attach to the container and run ls /dev/ i can see that sdb1 exists but i am unable to mount it within the container.
I have tried running mount /dev/sdb1 testdir/ but I get the error:
mount: permission denied
Am I setting this up correctly? If so how would I mount inside to container?
Answer: the container usually maps its UIDs on top of the hosts UID 100000 (which would map to the UID of the containers "root" user), so I guess you need to make sure this uid is on the host system allowed to mount the block device.
EDIT
perhaps this blog helps you with the problem: http://www.forshee.me/2016/02/22/container-mounts-in-ubuntu-1604.html
Comment: Would allowing a non sudo user to do mounts be insecure? Is there a better way for the host to share or passthrough a block device?
Comment: Thank you for your reply, i have actually come across the article you put in your edit before. I have not tried it but it looks like it would work, unfortunately its not the solution im looking for. Currently i think the best way to achieve what im looking for is through a shared folder between the host and container using ` lxc config device add test share disk source=/mnt/drive path=/mnt/drive`
Comment: I do use the shared folder as well. Although the same limitations apply to them: you need to chown the folder/files to uid 100000 so they are owned by the containers root user. Within the container you can then (as root) do a chown to the user that needs access to the folder.

Mount Block Device in LXD


How to add profile fields on Ubercart 3 checkout page?

Question: I used to use the uc_profile module to add user profile fields to the D6/Ubercart 2 checkout page, but I cannot find a suitable solution for that same functionality in D7/UC3. Can anyone guide me toward an alternative solution? I need to add things like "birthday" and "shoe size" to the checkout page, and I need those items to be displayed on the users' profiles.
Thanks!
Answer: You can try out the Extra Fields Checkout Pane module.

This modules allows an administrator to define additional (billing and shipping) address fields (i.e. VAT) as well as custom order fields in Ubercart e-commerce suite. These fields will be available during checkout process and in order handling pages.
Comment: Hello. Link-only answers are not considered good answers on Stack Exchange. Could you at least add a quote from module's page, quoting part that shows it might, indeed, be a solution for OPs needs?
Comment: Thanks for the suggestion, Imran. Unfortunately, I don't believe this module meets my requirement of having those fields show up in the user's profile.
Comment: @hockey2112, did you get solution to this problem? I am also looking for the same.
Comment: Sorry, I honestly cannot recall. I want to believe that I did not find a suitable solution, unfortunately.


Android AlarmManager setExact() is not exact

Question: I need to plan sheduled task every 10 minutes.
As in Lollipop and higher version setRepeating() is inexact, I use setExact() and (on alarm firing) I set new exact alarm in 10 minutes.
private void setAlarm(long triggerTime, PendingIntent pendingIntent) {
        int ALARM_TYPE = AlarmManager.ELAPSED_REALTIME_WAKEUP;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(ALARM_TYPE, triggerTime, pendingIntent);
        } else {
            alarmManager.set(ALARM_TYPE, triggerTime, pendingIntent);
        }
    }

triggerTime is calculated SystemClock.elapsedRealtime() + 600_000;
When alarm fires, firstly I plan new one, only after that I run my sheduled task.
setAlarm();
mySheduledTask;

I do have WAKE_LOCK permission in my manifest.
When I test this on Android 4 - it works perfect (deviation might be 12-15 milliseconds).
But when I run app on Xiaomi Redmi Note 3 Pro (5.1.1) - deviation can be up to 15 seconds!
For example, I see in my log file: first run was at 1467119934477 (of RTC time), second - at 1467120541683. Difference is 607_206 milliseconds, not 600_000, as it was planned!
What am I missing? What is a way to simulate behaviour of system alarm (it's the most close usecase that can describe my tack)?
PS. I use IntentService for PendingIntent = PendingIntent.getService(context, 0, myIntent, 0);
Answer: The OS chooses how the alarms will work, with consideration of the time you've specified. Because of that, when the phone gets into a 'semi-sleep' mode, it won't necessary use the resource at the time you wish it to. Basically, it waits for 'windows' that the OS opens for it, and only then the alarm you want to run will run, that's why you're experiencing time gaps.
This was introduced on Marshmallow OS and will continue on Nougat OS as well, as part of Google trying to improve the device's battery.
Here's the thing, you have 2 options:

Accept the time delays (but maybe consider using JobScheduler which is more recommended and will save you battery).
Use setExactAndAllowWhileIdle which might cause you battery issues (use this carefully, too many alarms will be bad for your battery).
This method isn't repeating, so you have to declare the next job to be run at the service which the pendingIntent opens.

If you choose option 2, here's the start:
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
int ALARM_TYPE = AlarmManager.RTC_WAKEUP;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
    am.setExactAndAllowWhileIdle(ALARM_TYPE, calendar.getTimeInMillis(), pendingIntent);
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
    am.setExact(ALARM_TYPE, calendar.getTimeInMillis(), pendingIntent);
else
    am.set(ALARM_TYPE, calendar.getTimeInMillis(), pendingIntent);

Comment: Oh, I need to show sort of message to the user: "Sorry you haven't heard an alarm and did not get up on time, because exact alarm triggering will cause battery issues".
Comment: Good point, thanks. But the problem is on Lollipop, not on Marshmellow. Also, how system alarm is working (it works good, at the time it was planned)?
Comment: In second `if` Lollipop should be substituted with Kitkat.
Comment: . Mr google, when I say exact I really mean EXACT, what's really the point of calling setExact... if it's not exact. Damn it.
Comment: @Dus the third case is not exact because apps having targetSdkVersion 19 or later will treat set as inexact on devices having 18 and earlier. So, how to get exact alarm on pre-Kitkat devices with targetSdkVersion 25?
Comment: Recommending JobScheduler for an alarm clock app? Why?
Comment: This solution does not work for Lolipop (which the question was about). Lollipop is version API version 22, setExactAndAllowWhileIdle is API 23
Comment: I'm using `setExactAndAllowWhileIdle` (on API level 28) but I do get inexact times. Strangely enough, most often these seem to be rounded to minutes: I set 5 min intervals, but I get 6, 10 or even 30, while very rarely "random" values. Anyone knows why this strange behaviour?
Answer: You can call the method from support.v4:
AlarmManagerCompat.setExact(...);

The internal implementation contains checks by sdk version.
Answer: Probably a possible workaround could be something like this:
you schedule the Alarm about 1 minute before the expected time, than you use a Handler.postDelayed to cover the remaining time.
Here you can find an example of this kind of implementation.
The activity just set-up the first alarm:
public class MainActivity extends AppCompatActivity {

    private static int WAIT_TIME = 60*1000; //1 minute
    public static int DELAY_TIME = 10*60*1000; // delay between iterations: 10min
    public static String UPDATE_TIME_KEY = "update_time_key";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setAlarm(this,(new Date().getTime())+DELAY_TIME);
    }

    public static void setAlarm(Context context, long delay) {

        long fireDelay = delay-WAIT_TIME;
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        sharedPreferences.edit().putLong(UPDATE_TIME_KEY,delay).apply();

        Intent startIntent = new Intent(context, UpdateReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, startIntent,PendingIntent.FLAG_UPDATE_CURRENT );
        AlarmManager alarmManager = (AlarmManager) context.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        int ALARM_TYPE = AlarmManager.RTC;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(ALARM_TYPE, fireDelay, pendingIntent);
        } else {
            alarmManager.set(ALARM_TYPE, fireDelay, pendingIntent);
        }
    }

}

than the receiver continues the loop:
public class UpdateReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, Intent intent) {
        Log.e("RECEIVED","RECEIVED");
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        long fireTime = sharedPreferences.getLong(MainActivity.UPDATE_TIME_KEY, (new Date()).getTime());

        long fireDelay  =(fireTime-(new Date().getTime())>0)?fireTime-(new Date().getTime()):0;

        (new Handler()).postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.e("RECEIVED","PERFORMED");
                MainActivity.setAlarm(context,(new Date()).getTime()+MainActivity.DELAY_TIME);
            }
        },fireDelay);

    }

}

I hope it helped.
Comment: Interesting solution, upvoted it. But it's quite hacky, will use it only as a last resort. Thanks!
Comment: It's an interesting approach but what if your initial alarm doesn't fire ?
Answer: To answer the question on the system alarm...
Android's stock Alarm Clock/Desk Clock app uses a combination of setAlarmClock and setExactAndAllowWhileIdle.
The following code is used to update notifications:
final PendingIntent operation = PendingIntent.getBroadcast(context, 0,
    AlarmStateManager.createIndicatorIntent(context), flags);
final AlarmClockInfo info = new AlarmClockInfo(alarmTime, viewIntent);

alarmManager.setAlarmClock(info, operation);

While at the same time the following code is used to schedule the actual alarm:
if (Utils.isMOrLater()) {
    // Ensure the alarm fires even if the device is dozing.
    alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
} else {
    alarmManager.setExact(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent)
}

The Pending intent set in setExactAndAllowWhileIdle triggers the alarm while setAlarmClock's intent is then simply ignored.

Android Googlesource
Comment: Welcome to the world of Android, the world where even Google developers have to hack their way through.
Comment: I don't see the first part. Where is it exactly?
Comment: @androiddeveloper https://android.googlesource.com/platform/packages/apps/DeskClock/+/master/src/com/android/deskclock/alarms/AlarmStateManager.java#235
Comment: But how do you see that the second is called after the other? They are in different functions, and I don't see them being called on after another.
Comment: @androiddeveloper the code isn't easy to follow, but it all starts with `registerInstance()` which sets the alarm state (which eventually calls the second bit of code) and updates notifications (the first bit of code).
Comment: Did it work for you though? I've noticed that in some cases, either it doesn't get triggered, or that I don't wait enough to see it. Please check this: https://stackoverflow.com/q/60079472/878126
Comment: @androiddeveloper it did work at the time I posted this answer, but I haven't tested it with the latest Android version.
Comment: Can you please try now? You can do it on emulator. It also has the same issue
Answer: From android documentation of AlarmManager

Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.

Also while using setExact() :

The alarm will be delivered as nearly as possible to the requested trigger time.

So its still not guaranteed that setExact will be Exact.
Comment: I did read the documentation. Ok, then how does alarm on device works? It works good, without any deviations.
Answer: You can try use AlarmManager.setAlarmClock maybe it can help you.
Another thing you need to check which type of BroadcastReceiver you are using, it will be better to use WakefulBroadcastReceiver
Btw you need to change logic for work with Alarm Manager for support Android M, you can you something like this:
if(Build.VERSION.SDK_INT < 23){
    if(Build.VERSION.SDK_INT >= 19) {
        setExact(...);
    } else {
        set(...);
    }
} else {
    setExactAndAllowWhileIdle(...);
}

Comment: Its written that setAlarmClock is like setExact, so I don't think, that switching will help much. About WakefulBroadcastReceiver - it's interesting, will try it, for now I'm using service.
Comment: WakefulBroadcastReceiver is deprecated now.


Run stored procedure for each row of a table

Question: I have a table that look something like this
value_1  value_2  value_3
---------------------------
   1        2        3
   4        5        6
   7        8        9
   ...     ...     ...

and I need to run a stored procedure for every row of this table, something like
foreach value_1, value_2, value_3 from my_table
exec spProcedure value_1, value_2, value_3

Is there a way to do this?
Comment: from another stored procedure or in a program?
Comment: just an sql query to run in SQL Management studio
Comment: Possible duplicate of [SQL - Call Stored Procedure for each record](https://stackoverflow.com/questions/2077948/sql-call-stored-procedure-for-each-record)
Answer: You can use a cursor:
DECLARE @value1 INT,
        @value2 INT,
        @value3 INT

DECLARE cursorElement CURSOR FOR
            SELECT  value_1, value_2, value_2
            FROM    table

OPEN cursorElement
FETCH NEXT FROM cursorElement INTO @value1, @value2, @value3

WHILE ( @@FETCH_STATUS = 0 )
BEGIN
    exec spProcedure @value1, @value2, @value3

    FETCH NEXT FROM cursorElement INTO @value1, @value2, @value3
END
CLOSE cursorElement
DEALLOCATE cursorElement

Answer: Another way:
DECLARE @MemoryTable table (
    RowID int,
    value_1 int,
    value_2 int,
    value_3 int
)

INSERT INTO @MemoryTable
SELECT ROW_NUMBER() OVER (ORDER BY value_1) AS RowID, * FROM SampleTable

DECLARE @ctr INT
DECLARE @MaxRownum INT

DECLARE @val1 INT
DECLARE @val2 INT
DECLARE @val3 INT

SET @ctr = 1
SET @MaxRownum = (SELECT COUNT(1) FROM @MemoryTable)

WHILE @ctr <= @MaxRownum
BEGIN

    SELECT @val1 = value_1,
           @val2=value_2,
           @val3=value_3
    FROM @MemoryTable
    WHERE RowID = @ctr

    exec spProcedure @val1, @val2, @val3

    SET @ctr = @ctr + 1
END


Limit sup/inf $(\frac{1}{n+1}-1)^n$

Question: My suggestion was that $$\varlimsup_{n \to \infty}(\frac{1}{n+1}-1)^n=1$$ and $$\varliminf_{n \to \infty}(\frac{1}{n+1}-1)^n=-1$$ by looking at the even/odd subsequence since obviously $\lim_{n \to \infty}(\frac{1}{n+1}-1)= -1$.
But can I just conclude that $\lim_{n \to \infty}a_n^{2n}=1$ when $\lim_{n \to \infty}a_n=-1$? I feel like that's not very mathematical. I didnt find any rule or anything that would allow that.
Thanks!
Answer: $$x_n=(\frac{1}{n+1}-1)^n=(-1)^n(1-\frac{1}{n+1})^n=(-1)^n(1-\frac{1}{n+1})^{n+1} \frac{1}{1-\frac{1}{n+1}}$$
So $\limsup_nx_n=\frac{1}{e}$ and $\liminf_nx_n=-\frac{1}{e}$
Comment: wow would have never thought of that thx!

Limit sup/inf $(\frac{1}{n+1}-1)^n$


How To Make Token Works On Field Label?

Question: I've created a custom content type and I have a field which referencing a views (Using Viewfield Module). Now I want to alter the field label using [current-page:title] token, But Token isn't working on field label.
I've tried [current-page:title] on field label, But the token is just print out not value.
How can I Use token on Field label?
Answer: These two articles might help you out:
https://www.drupal.org/node/1299662
(From this article)
The Token module for Drupal 7 currently provides support for basic-level field tokens like [node:field_my_image_field] and [node:field_node_reference_field].
Customizing field token output
Sometimes the field tokens may not output as desired. To change how they are output, you must perform the following steps:
Enable the 'Token' custom display setting.
Go to the "Manage display" of the entity type and bundle for which token you are trying to change. For example, to change how fields on Article nodes are displayed in tokens, go to admin/structure/types/manage/article/display. Expand the Custom display settings fieldset at the bottom of the page, click the "Tokens" checkbox, and then click the Save button.
https://www.drupal.org/node/2261729
(From this article)
The labels are not part of the field and are not intended to be. The style renders the field and label separately. In the vast majority of use cases, you do not want the label. If you do, you can rewrite the original field to include the label, or include the label as you like.
Comment: Though these might answer the question, please include the relevant parts from these resources in your answer in case the links go down. Thanks.

How To Make Token Works On Field Label?


How to expand equations with more number of bracket operations?

Question: How can I solve and expand the equation which have more number of  brackets ? Since opening and performing the operation on single brackets becomes a tedious task. Is there any other method which can be used to expand  the equations and finding the values of coefficients fast ? For eg.
$s(s+2)(s+4)(s+8)(s+10)$
Comment: Um... looks like the works been done for you.  $s(s+2)(s+4)(s+8)(s+10)$ is as simple as it gets.  Expanding things out makes things more *complicated*, not simpler, and *harder* to solve.  (This one has roots of $s = 0, -2, -4, -8, -10$.  I solved that just by looking at it.  No pencil, paper, or brain cells)  But if you mean how to expand.  Just do it step by step.  $s(s+2)(s+4)(s+8)(s+10) = s(s^2+6s+8)(s+8)(s+10)= s(s^3 + 6s^2 + 8s + 8s^2 + 48s + 64)(s+10)=s(s^3 +14s^2 +56s +64)(s+10)$ etc.  No easy way.  Just do it.
Answer: First of all, expanding things out is not simplifying.  It's complicating.  You simplify things by breaking them down into brackets; not getting rid of brackets.  And you solve things by making brackets.
So $s(s+2)(s+4)(s+8)(s+10)$ is as simple as it gets and it's trivial to solve the roots at $s = 0,-2,-4,-8,-10$.
You are asking how to expand
So $s(s+2)(s+4)(s+8)(s+10) =(s+0)(s+2)(s+4)(s+8)(s+10) s^5 + as^4 + bs^3 + cs^2 + d^s + e$ and we just have to figure out what $a,b,c,d,e$ are.
$e = 0*2*4*8*10 = 0$
$d = 0*2*4*8 + 0*2*4*10 + 0*2*8*10 + 0*4*8*10 + 2*4*8*10 = 2*4*8*10$.
Oh... let's ignore the 0.  It's trivial.
$c = 2*4*8 + 2*4*10 + 2*8*10+4*8*10$
$b = 2*4+2*8 + 2*10 + 4*8 + 4*10 + 8*10$
$a = 2+4+8+10$
Basically the coefficient of $s^k$ is the sum of all products of $n-k$ of the terms.
Easier example:  $(x+ 1)(x-1)(x+3) = x^3 + bx^2+ cx + d$ and
$b = 1-1+3 = 3$
$c = 1*(-1) + (1*3) + (-1*3) = -1$
and $d = 1*(-1)*3 = -3$
so $x^3 -x^2 - 3x -3$ and indeed
$(x+1)(x-1)(x+3) = (x^2 + 1*x -1*x -1*1)(x+3)= (x^2 + [1-1]x + [-1*1])(x+3)=$
$x^3 + [1-1]x^2 + [-1*1]x + 3x^2 + 3[1-1]x + 3[-1*1] =$
$x^3 + (1-1+3)x^2 + ((-1*1)+(3*1)+(3*-1))x + 3*-1*1$
Answer: Please keep from now on this central statement in mind:

If your equation is given in the form $$ \prod_{k=1}^n(x-a_k) = (x-a_1)(x-a_2)...(x-a_n) $$ the
  solutions are $a_1, a_2, ..., a_n$.

Why? Well, the 'solutions' are those $x$ for which the equation becomes 0. So if $x$ becomes one of those $a_1, a_2, ..., a_n$ at least one of these elements of the product becomes $0$ and therefore the hole product.
As mentioned before: Your equation is already in the perfect form to easily see the solutions!


Where can I find Heegner's proof?

Question: Where can I read a corrected up to date version of Heegner's solution of the class 1 problem of Gauss?
Comment: you can check the references at http://en.wikipedia.org/wiki/Stark%E2%80%93Heegner_theorem
Comment: It is a good idea if you also add tags corresponding to the topic that you're looking for references because for example some people subscribe to receive email notifications when a question with certain tag is asked, so you may get more help.
Answer: The wikipedia entry for Kurt Heegner contains a reference to an article by Harold Stark where he adresses the gap on the original proof and presents an outline of Heegner's argument.
Heegner's original article (cited in the wikipedia entry) seems to be available in SpringerLink if you have access to it.
Another nice reference which you would like to consult is David Cox's excellent book Primes of the form $x^2 + ny^2$. In section 12 of that book you can find a proof under the entry E. Imaginary Quadratic Fields of Class Number 1. I hope this helps.
Comment: @quanta I find Stark's comment at the end of the article to be quite amazing, where he says that the class number 1 problem could have been solved just at the start of the 20th century if Weber had made one more observation in his book.
Comment: +1 for mention of Cox's book **Primes of the form $x^2 + ny^2$**, a favorite of mine.
Comment: Stark said "It is frequently stated that my proof and Heegner's proof are the
same. The two papers end up with the same Diophantine equations, but I invite
anybody to read both papers and then say they give the same proof!"
Answer: There is an article of Birch from 1969, titled Weber's class invariants, in which he proves, using basic class field theory and CM theory, various facts originally due to Weber, but whose proof was in doubt.  These are facts that Heegner cited in his proof, and Birch observes that one reason Heegner's proof was doubted.   Given this, it seems that Birch's article will be a useful companion when reading Heegner's argument.

Where can I find Heegner's proof?


How to manage separation of concerns when using ServiceStack AutoQuery

Question: I am having some issues with how to organise my AutoQuery code. My project structure currently looks like:
/Project
/Project.ServiceInterface
  Service.cs
/Project.Logic
  Manager.cs
  /Types
    DbModel.cs
/Project.ServiceModel
  Request.cs
  /Types
    DtoModel.cs

With this setup, the ServiceModel has no knowledge of the Logic models. Because of this, I can't make a request query like QueryDb<DbModel, DtoModel> without essentially duplicating all my DbModel objects in my ServiceModel or adding a dependency to Logic in ServiceModel. I also have custom AutoQuery service implementations and inside those I want to be able to leverage code that has been written using my DbModels elsewhere.
Does anyone have any recommendations or relevant examples? I feel like I'm approaching this problem incorrectly and making it more complex than need be. Thanks.
Answer: Auto Query lets you create Services by defining a Request DTO as such all Types it references must also be the ServiceModel Assembly, so you'd either need to move the Data Models your AutoQuery Services references to your ServiceModel project or annotate your DTO so that it can be used by OrmLite to query your RDBMS Table where it can use the [Alias] attribute where names differ and the [Ignore*] attributes depending on whether the property should exist in OrmLite or Serialization, e.g:
[Alias("MyTable")]
public class MyDto
{
    [Alias("DbName")]
    public string DtoName { get; set; }

    [Ignore]
    public string IgnoredInOrmLite { get; set; }

    [IgnoreDataMember]
    public string IgnoredInSerialization { get; set; }
}

Otherwise you're not going to be able to use Auto Query and would need to create Custom Services whose internal implementation makes use of your Data Models where they're hidden from your public Services Contract.
Personally I'd recommend moving the Data Models you need to your ServiceModel Assembly (that continues to use the same Namespace as your other DataModels) as OrmLite DataModels are POCOs that like DTOs typically don't need any additional references other than the impl-free ServiceStack.Interfaces.


What are the facets of the Tridiagonal Birkhoff $d$-polytope $\Omega^t_{d+1}$?

Question: The Birkhoff $d$-polytope $\Omega_{d+1}$ is the convex polytope in $\mathbb{R}^{d+1}$ $\times$ $\mathbb{R}^{d+1}$ of doubly stochastic matrices:
•   All matrices contained in $\Omega_{d+1}$ have non-negative entries;
•   All matrices contained in $\Omega_{d+1}$ have column and row sums equal to 1; and
•   $\Omega_{d+1}$ has $(d+1)^2$ facets given by the equations $\{A|a_{ij} = 0; 1 \le i,j \le d+1\}$
The Tridiagonal Birkhoff polytope $\Omega^t_{d+1}$ is a face of the Birkhoff polytope $\Omega_{d+1}$, such that matrix entries off the main diagonal, superdiagonal and subdiagonal are zero.
What are the facets of the Tridiagonal Birkhoff $d$-polytope $\Omega^t_{d+1}$?
Comment: Why are you using HTML to format mathematical expressions instead of $\LaTeX$?
Comment: I thought I was using LaTeX. Edits to improve the format are welcome.
Comment: Please review my edit to ensure that I haven't introduced errors.
Comment: Looks good to me!
Answer: Every point of $\Omega_{d+1}^t$ is of the form
$$
A = \begin{bmatrix}
1 - \mu_1 & \mu_1 & 0 & 0 & \cdots & 0 \\
\mu_1 & 1 - \mu_1 - \mu_2 & \mu_2 & 0 & \cdots & 0 \\
0 & \mu_2 & 1 - \mu_2 - \mu_3 & \mu_3 & \cdots & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\
0 & 0 & \cdots & \mu_{d-1} & 1 - \mu_{d-1} - \mu_d & \mu_d \\
0 & 0 & \cdots & 0 & \mu_{d} & 1 - \mu_d
\end{bmatrix}
$$
where
each $\mu_i \geq 0$ and
$\mu_i + \mu_{i+1} \leq 1$ for $1 \leq i \leq d - 1$.
The facet-defining equalities are $\mu_i = 0$ ($d$ of these)
and $\mu_i + \mu_{i+1} = 1$ ($d-1$ of these.)
(This is for $d \geq 2$. For $d = 1$, the facets are $\mu_1 = 0$ and $\mu_1 = 1$.)
I found this description in G. Dahl, "Tridiagonal doubly stochastic matrices," Linear Algebra and its Applications 390 (2004) 197–208.


Google Cloud Run (fully managed): Custom domain mapping not possible

Question: When I try to map a custom domain to my service I get: "Failed to create a domain mapping: Creating domain mappings is not allowed in europe-west3". Google Run seems to be pretty useless for many use cases if it can't be mapped to custom domains, so I wonder if it is really not possible or this is an error or I have to enable something before this feature can be used.
Answer: According to the official documentation :
Mapping custom domains

You can use a custom domain rather than the default address that Cloud
Run provides for a deployed service.
To use a custom domain for a service, you map your service to the
custom domain, then update your DNS records. You can map a service to
a domain, such as example.comor to a subdomain, such as
subdomain.example.com.

It is not possible to map custom domains to Cloud Run (fully managed) services in
<code>asia-east2
asia-northeast2
asia-northeast3
asia-southeast1
asia-southeast2
asia-south1
australia-southeast1
europe-west2
**europe-west3**
europe-west6
northamerica-northeast1
southamerica-east1
</code>
Comment: What a pity! Thanks, this information is missing in the German version of the docs by now.
Comment: Ok it's not possible, but why? and what are we uspposed to do if we're not in one of those zones?
Comment: any info when it become available on those zones?


Find integers a and b congruent to mod

Question: Can anyone give me a hint of how to solve this equation
Find integers $a$ and $b$ such that $a + b ≡ a - b \bmod 5$.
I did not go over this in my class. Kindly help me on how to solve this one. Thanks
Comment: The question is equivalent to : find $a,b$ so that $5 $ divides $a+b-a+b=2b$, so take $a$ as arbitrary and $b$ as a multiple of $5$
Comment: $a$ can be anything but $b \equiv 0\ (\text {mod}\ 5).$
Answer: Subtracting $a$ from both sides and adding $b$ gives
$$2b\equiv 0\mod{5}$$
$$\therefore b=5k$$
For $k\in \mathbb{Z}$. $a$ can take any value in $\mathbb{Z}$ as the equivalence does not depend on $a$.
Answer: Here's a start: note that what you have written implies that $b=0 \text{ (mod 5)}$. To see this, recall that what it means to be equal to some residue mod 5 is that $a+b = a-b + 5k$ for some $k\in\mathbb{Z}$. Normal arithmetic reveals that $2b=5k$, which means that $b$ has to be divisible by 5. See if you can figure it out from here!
Answer: You could write the congruence in equation form as follows
$$
a+b\equiv a-b\ \bmod 5 \Rightarrow a+b=a-b+k\cdot 5, \ \ k\in\mathbb{Z}
$$
which is equivalent to
$$
2b=k\cdot 5 \Rightarrow 2b\equiv 0 \ \bmod 5.
$$
Now, you can divide here by $2$ since it is relative prime to $5$
so you only need to define $b$ for a such congruence to hold and $b$ should be divisible by  $5$ so $b\in\{5, 15, -10 \}$ just to name a few.

Find integers a and b congruent to mod


Indirect binding of variables to values through an if condition.

Question: Define a function $f$ by,
$$f(x, y) = \text{if } x = y \text{ then } x \text{ else } f(x-1, y) $$
Then what are the possible values for $z$ in,
$$ \exists a: a\in\mathbb{Z} \wedge z  = \frac{a}{f(5, a)} $$
This isn't exactly difficult. Just weird. It is designed to mess with your thinking in a few ways. I'll be interested to see what you think.
Comment: $$\text{If } a\leq y\land a\ne 0\land a\in\mathbb{Z};\;\dfrac{a}{f(5,a)}=1$$
Comment: Why the $a \le y$? The $ a \ne 0 $ avoids the divide by zero. But does this invalid division invalidate the whole expression? The question is more about how you reason about it. 1 is the answer but why? And how do you reason about the infinite recursion?
Comment: It's $a\leq 5$ the limitation. I wrote it wrong. Because if $a=6$ then the iteration never ends. Indeed $x$ decreases each step and will never be $6$ or more.  The actual solution is $$\text{If } a\leq 5\land a\ne 0\land a\in\mathbb{Z};\;\dfrac{a}{f(5,a)}=1$$
Comment: @ Raffaele I think you understand it.
Answer: We don't know the value of $a$ in,
$$ \exists a: a\in\mathbb{Z} \wedge z  = \frac{a}{f(5, a)} $$
But there does exist some value. I think of this as,
$$ a = 0 \wedge a\in\mathbb{Z} \wedge z  = \frac{a}{f(5, a)} $$
or
$$ a = 1 \wedge a\in\mathbb{Z} \wedge z  = \frac{a}{f(5, a)} $$
or
... for all the real numbers.
This is an uncountably infinite number of lines of math. Hard to iterate through.
So let's leave it unbound, in our thinking. It has a value and we will decide what it is later.
But we first come across it in the numerator, and we don't know the value yet. Let's look at $f(5, a)$. $f$ is defined recursively and we could rearrange it. But the peculiar structure doesn't help us.
$$f(5, a) = \text{if } 5 = a \text{ then } x \text{ else } f(4, a) $$
The $5=a$ doesn't give us any constraint on $a$. The condition could be true or false. We need consider both cases. If it is true,
$$a=5 \wedge f(5, a) = 5 \wedge z = 1$$
So that is one solution. If false, then $f(5, a) = f(4, a)$.
$$a=4 \wedge f(4, a) = 4 \wedge z = 1$$
... all the way down till we get to, $ f(5, a) = f(0, a) $
$$a=0 \wedge f(0, a) = 0 \wedge z = \frac{0}{0}$$
But dividing by zero is illegal. The result is undefined.
And there is still the possibility that a is not equal to 0. Which heads off to infinity , but always giving the same value $z = 1$.
So what does it mean to have a zero divide by zero in here. $a = 5$ gives a perfectly good value for z. If we only wanted one solution, we might have stopped there. Does the existence of the zero divide by zero, invalidate that value?
The question is designed to test the strange way that the if condition binds a parameter to a function to a value, as one possibility. For me this question raises questions about how we reason about math.


You toss two coins. This action costs $5$. For each head tossed, you get $2$. If you win (at least one head tossed) you also get your $5$ back.

Question: You toss two coins. This action costs $ \$ 5$. For each head tossed, you get $\$2$. If you win (at least one head tossed) you also get your $\$5$ back. What is the expected profit of a round? What should be the sum of the award of winning so that the game is fair (no trend of someone winning or losing)?
At this point I have calculated the possible scenarios:

1/4 - two heads
1/4 - two tails
1/2 - one head, one tail

Hence, you have
$$
\left(\frac{1}{4} \ \text{chance of winning} \ (\$5+\$2+\$2- \$5)\right) \times \left( \frac{1}{2} \ \text{chance of winning} \ (\$5+\$2- \$5) \right) \times \left( \frac{1}{4} \ \text{chance of winning} \  (\$0 - \$5) \right)$$-.
Comment: You should have addition signs rather than multiplication signs between each pair of parentheses since the three events are mutually exclusive.
Comment: I think you mean $+$ instead of $*$ in your last sentence. Otherwise, you have exactly written out how to calculate the expected profit of the game. It's unclear what you mean by "the sum of the award of winning" in you second question though.
Comment: This is what happens when you don't take the trouble to ensure that your question is reasonably formatted: someone comes along and formats it for you, and while doing so they change a $+$ to $\times$ and make it slightly worse (in that respect) than it was before. I recommend you go over the edited post and make sure everything there is exactly how you want it--notably those multiplication signs.
Comment: You get $2$ what?
Comment: Typesetting hint: to display dollar signs, put a backslash in front: `\$5` gives \$5. Otherwise, everything between your dollar signs is interpreted as a mathematical expression.
Answer: You are almost right. But recalling the expectation definition : $E(X) = \sum p(X) X$ you should rather write
$$ \frac{1}{4} \times  (\$5+\$2+\$2- \$5) + \frac{1}{2}  \times (\$5+\$2- \$5)  + \frac{1}{4}\times  (\$0 - \$5) $$
Answer: Your computation of the expected return is correct.  Probably the sum to award question means to replace $2$ with some number to make the expected return $0$.  Just replace $2$ by $x$ in your expected return expression, set it to zero, and solve the resulting equation.


Separable extensions and simple roots

Question: An element $\alpha\in \mathbb F$ is algebraic w.r.t a field extension $\mathbb E\subset \mathbb F$ if it's the root of some polynomial over $\mathbb E$.
One can prove the sum, product, and inverse of algebraic elements are also algebraic. Hence TFAE:

The extension consists entirely of algebraic elements.
The extension is generated by algebraic elements, i.e by roots of polynomials over the base field. Thus every element upstairs is a rational function in a root of a polynomial downstairs.

An element $\alpha\in \mathbb F$ is separable w.r.t a field extension $\mathbb E\subset \mathbb F$ if its minimal polynomial is separable.
Question 1. Is an element separable iff it's a simple root of a polynomial defined over the base field? (A separable element satisfies this property, but what about the converse?)
One can also prove the sum, product, and inverse of separable elements are separable.
Question 2. In light of the above, are the following conditions equivalent for?

The extension consists entirely of simple roots of polynomials over the base fied.
The extension is generated by simple roots of polynomials over the base field. Thus every element upstairs is a rational function in a simple root of a polynomial downstairs.
Answer: Question 1: The answer is yes, because the roots of an irreducible polynomial $f\in\mathbb{E}[X]$ possess equal multiplicities. This can be shown using formal derivatives.
If now $\alpha$ is a simple root of the polynomial $g\in\mathbb{E}[X]$, consider the minimal polynomial $f$ of $\alpha$. It divides $g$, hence has $\alpha$ as a simple root. Consequently all roots of $f$ are simple.
Question 2: The answer is yes.
Comment: For Q1, I don't follow: we want to show $\mu _\alpha\in \mathbb E [x]$ is separable. This means its discriminant is invertible, or (equivalently) that all its roots in its initial splitting algebra (or a splitting field) are simple. You have shown that all roots of the irreducible $\mu_\alpha\in \mathbb E [x]$ in $\mathbb E$ have the same multiplicity and are therefore simple. Why does this prove separability? It seems to leave the possibly missing roots unaddressed.
Comment: "All roots have the same multiplicity" is supposed to mean "all roots in an algebraic closure of $\mathbb{E}$ have the same multiplicity".

Separable extensions and simple roots


changing listbox items order

Question: I have a ListBox with font library in it. I need to change order of 2 items by clicking my 'Edit' button, first font with last font.
Answer: If you want to swap two items with each other, you can use the Exchange() method:
if (ListBox1->Items->Count > 1)
    ListBox1->Items->Exchange(0, ListBox1->Items->Count-1);

changing listbox items order


Set theory - induction - countable sets

Question: need help with the following question:
Let $S \subseteq P(\mathbb N)$ be defined inductively so that:

$\mathbb N \in S$
for all$ ~ a \in \mathbb N \Longrightarrow \mathbb N\setminus\{a\}\in S$
for all $A,B \in S \Longrightarrow A\cap B \in S$

Prove that if $A\subseteq \mathbb N~ $ and $~ \mathbb N $ \ $A$ is finite then $A \in S$
thanks!
Comment: Wouldn't $S \subseteq \mathbb{N}, \mathbb{N} \in S$ imply that $\mathbb{N} \in \mathbb{N}$?
Comment: it was supposed to be $P(\mathbb N)$ , i fixed it
Answer: You can prove it by induction on $\#(\mathbb{N}\setminus A)$:

If $\#(\mathbb{N}\setminus A)=0$, then $A=\mathbb N$ and therefore $A\in S$.
Let $n\in\mathbb N$ and suppose that $\#(\mathbb{N}\setminus A)=n\implies A\in S$. Then, if $\#(\mathbb{N}\setminus A)=n+1$, take $a\in(\mathbb{N}\setminus A)$ and let $A^\star=A\cup\{a\}$. Then $\#(\mathbb{N}\setminus A^\star)=n$ and therefore $A^\star\in S$. So,$$A=A^\star\cap(\mathbb{N}\setminus\{a\})\in S$$
Comment: why when $ |A| = n \longrightarrow \mathbb N \setminus A = \mathbb N$ ?
Comment: @bliblo I've edited my answer. I hope that everything is clear now.
Comment: but you havent proved that $A \in S$
Comment: @bliblo I don't understand your objection. I proved by induction on $\#A$ that, for every finite set $A$, $\mathbb{N}\setminus A\in S$. In order to do that, I proved that the statement is true when $\#A=0$ and then I proved that **if** the statement is true when $\#A=n$, **then** it is true when $\#A=n+1$. What is your objection exactly?
Comment: You need to prove that $A \in S $ not that $\mathbb N \setminus A \in S $
Maybe i understood your proof wrong but i see that you've proved that $\mathbb N \setminus A \in S$
Comment: @bliblo What do you think now?
Comment: Looks good, thank you!
Comment: @bliblo If my answer was useful, perhaps that you could mark it as the accepted one.
Answer: If $B\subset\mathbb N$ is finite, then there exists a unique $n\in\mathbb N$, such that $|A|=n$ and a bijection $f:\{0,1,2,\ldots,n-1\}\to A$.
In Set Theory $0=\varnothing$ and $n=\{0,1,\ldots,n-1\}$.
Let
$$
J=\{k\in n: f[k]\in S\}
$$
We want to show that $J=n$.
Clearly, $f[0]=\mathbb N\in S$. If $J\ne n$, then there exists a least $m\le n$, such that $f[m]\not\in S$. But this also means that $m>0$ and $f[m-1]\in S$
Note that
$$
f[m]=f[m-1]\cup\{f(m)\}
$$
and
$$
\mathbb N\setminus f[m]=(\mathbb N\setminus f[m-1])\cap(\mathbb N\setminus \{f(m)\})
$$
But $\mathbb N\setminus f[m-1],\,\mathbb N\setminus \{f(m)\}\in S$, and thus $\mathbb N\setminus f[m]\in S$. Contradiction.

Set theory - induction - countable sets


Render Array for hook_field_formatter_view not displaying

Question: I'm updating this question on the suggestion of the initial provided answer.
When trying to render out the content of my custom field, outputting the data into a custom theming function to render on to the page when using the suggested method is resulting in the theming function being ignored, even when attempting to output just static strings of text or using the devel module to test it, nothing happens, the code is updated as below
/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$element = array();
  foreach ($items as $delta => $item) {
    if ($file = file_load($item['image'])) {
      list($hours, $mins, $secs) = explode(':', $item['time']);
      $time = ((3600 * $hours) + (60 * $mins) + $secs);
      $element[$delta] = array(
        '#theme' => 'mymodule_formatter',
        '#image' => (array) $file,
        '#time' => $time,
        '#comment' => $item['comment'],
      );
    }
  }
return $element;
}

Hook and Theming function
/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return array(
    'mymodule_formatter' => array(
      'variables' => array('variables' => array()),
      'file' => 'theme_mymodule.inc',
    ),
  );
}

In the theme_mymodule.inc file
/**
 * Returns HTML for a MyModule.
 */
function theme_mymodule_formatter($variables) {
  $output = t('test');

  return $output;
}

I think I'm a little confused about the naming of the theme hook, when I was copying the image module, the #theme variable was just declared as 'image_formatter' but the function named was 'theme_image_formatter', I'm wondering if I've declared my theme hook wrong.
--Previous question--
Im trying to write my own custom field in my own module, I've written the field setup, and it's accepting and evaluating data fine, that's all good. I'm struggling to grasp what I need to do when trying to write my own theming output function. As an example to the parts of code I'm working on:
/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$element = array();
  foreach ($items as $delta => $item) {
    if ($file = file_load($item['image'])) {
      list($hours, $mins, $secs) = explode(':', $item['time']);
      $time = ((3600 * $hours) + (60 * $mins) + $secs);
      $variables = array(
        'image' => (array) $file,
        'time' => $time,
        'comment' => $item['comment'],
      );
      $element[$delta] = theme('mymodule_formatter', $variables);
    }
  }
return $element;
}

And my theming function
/**
 * Returns HTML for a MyModule.
 */
function theme_mymodule_formatter($variables) {
  $item = $variables['image'];
  $image = array(
    'path' => $item['uri'],
  );

  if (isset($item['attributes'])) {
    $image['attributes'] = $item['attributes'];
  }

  if (isset($variables['image_style'])) {
    $image['style_name'] = $variables['image_style'];
    $output = theme('image_style', $image);
  }
  else {
    $output = theme('image', $image);
  }

  return $output;
}

Now this returns the correct HTML for my image, so it actually returns a string like

However this doesn't actually render on my page, it doesn't come back with an error, it just doesn't show anything.
When I change my $element[$delta] line in my hook_field_formatter_view() function to say
$element[$delta] = array('#markup' => theme('mymodule_formatter', $variables));

By putting the element into a '#markup' array, it does actually render the image, however I don't want to just throw everything into a '#markup' array if that's not the proper way of doing it.
Answer: To add markup that's already been prepared to a render array, you would indeed use #markup. There's nothing wrong with using it where appropriate.
However, since you're preparing the markup in the same function anyway, you may as well use the render array version of the call to theme(), e.g.
$element[$delta] = array(
  '#theme' => 'mymodule_formatter',
  '#image' => $image,
  '#another_var' => 'foo',
);

It provides better structure, makes it easier for other modules to alter if necessary, and is better for caching.
Comment: That was the format the image module was written, so that was what I initially tried to mimic, however I've just tried using that method and it doesn't appear to be picking up my theme function anymore, even why I try to just output test text, it's not noticing the theme_mymodule_formatter function anymore
Comment: That snippet should be more or less identical to `$element[$delta]['#markup'] = theme('mymodule_formatter', $variables);`...if one works the other should too. Might be an idea to update the question with the code you're using now, maybe there have been other modifications?
Comment: Ok, i'll edit the question and the title shortly
Answer: Right I've managed to work it out, I've done some additional reading on the render array information Clive posted in his answer, and followed the examples module slightly to realise what I'd done wrong. I'll mark the other answer as correct because what I actually wanted to know was what the correct method was for outputting the data
My problem was with this data
/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return array(
    'mymodule_formatter' => array(
      'variables' => array('variables' => array()),
      'file' => 'theme_mymodule.inc',
    ),
  );
}

Declaring the array in this way means the function is expecting an array called 'variables' as it's only parameter, so you need to declare any parameter it will receive first, so that they can then be passed properly.
/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return array(
    'mymodule_formatter' => array(
      'variables' => array(
        'image' => NULL,
        'comment' => NULL,
        'time' => NULL,
      ),
    ),
  );
}

Anyone having similar troubles I would suggest reading the 'render arrays' link in the other answer, and following the information in that.
Answer: Having never read properly about render arrays one issue related to this was driving crazy.
My theme function was receiving null values in the $variable arguments.
This was my formatter view:
function my_videotype_field_formatter_view ($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = [];
  $settings = $display['settings'];
  foreach ($items as $delta => $item) {
    $element[$delta] = [
      '#theme' => 'my_video_player',
      '#item' => $item,
      '#settings' => $settings,
      '#entity_type' => $entity_type,
      '#entity' => $entity,
    ];
  }
  return $element;
}

And my theme declaration:
function my_videotype_theme ($existing, $type, $theme, $path) {
  $theme = [];
  $theme['my_video_player'] = [
    'variables' => [
      '#item' => NULL,
      '#settings' => [],
      '#entity_type' => NULL,
      '#entity' => NULL,
    ],
    'file' => 'includes/my_video.theme.inc',
  ];
  return $theme;
}

As it turns out (after reading this thread) the hash is actually important... so vars are passed with hash to signal they are data in render arrays, but are actually stripped of the hash to evaluate... (hard to explain). So the theme declaration expects variables=>[item=>value] not variables=>[item=>#value] as declared in the render array. Thus the correct theme declaration would be:
function my_videotype_theme ($existing, $type, $theme, $path) {
      $theme = [];
      $theme['my_video_player'] = [
        'variables' => [
          'item' => NULL,
          'settings' => [],
          'entity_type' => NULL,
          'entity' => NULL,
        ],
        'file' => 'includes/my_video.theme.inc',
      ];
      return $theme;
    }

The other strange thing is that when calling theme through function, not render array:
$u=theme('my_video_player',['#item'=>$item,'#settings' => $settings]);

It would work even with the hash on the theme declaration... confusing.


Selecting Ruby gems at run-time based on configuration

Question: We're writing a Rails app that we want to be able to talk to any of several external data repositories via a uniform adapter interface, and we'd like to be able to add more later just by writing new implementations of that adapter interface (cf. ActiveRecord adapters).
Any one installation of the app will only need one adapter running, and we don't want to have to rev the code or even the Gemfile whenever we introduce a new adapter. Assuming we write each adapter as a standalone gem, what's the proper way to incorporate just one adapter gem at runtime, based on configuration?
Comment: I had a similar question that come-up. My scenario is different though and goes like this. We have an older version of a library (in a gem) that we want to upgrade. However, this gem participates in a critical part of our externally consumed API and we cannot update it at once and want to migrate clients to the new gem one by one. We don't want to stand up an entirely separate version of the API for this either (overkill). Are there practical strategies for this? @david-moles
Comment: @ShyamHabarakada Personally, I would stand up two versions of the API (with something in front of them to direct clients to one or the other). I absolutely would not trust that I could load two versions of one gem into the same Ruby application and safely switch between them for any given request. But this seems like a question for [softwareengineering.stackexchange.com](https://softwareengineering.stackexchange.com).
Comment: Yes @david-moles you are right that we cannot trust this. Thanks
Answer: Normally in Rails, you can only access gems that are listed in the Gemfile; Bundler enforces this. However that doesn't stop you from loading gems manually.
If your adapter gems are installed in a well-known location, then loading an adapter gem could be as simple as this:
$LOAD_PATH << "/path/to/adapters/my_adapter/lib"
require "my_adapter"

Where "my_adapter" is something you discover at runtime via configuration.
Answer: Put your configuration in the environment, as you're probably already doing.
For example, I use the dotenv gem.
Set an environment variable to your adapter gem name.
The result is an ENV var that Rails can access, such as:
ENV["adapter"] #=> "my_custom_gem_name"

Use the environment to pick the adapter, e.g. in your Rails config:
require ENV['adapter']

This presumes your gem name is the same as the require name. If your gem name is different, use the require name.
When you deploy a new adapter, you can put it anywhere on the Rails load path. Or you can adjust the Rails load path as you like e.g. adding a path to $LOAD_PATH.
An example of how to adjust the load path:
# /config/application.rb
module MyApp
  class Application < Rails::Application
  $LOAD_PATH << "/path/to/custom/gem"
  require("my_custom_gem_name")
  …

For example, put the gem code in ./lib, or install the gem into ./vendor or systemwide, using any tool you like such as scp or rsync or ansible, thus bypassing the typical bundle command.
You won't need to update the Gemfile.
Comment: Bundler, which Rails uses, restricts the load path to _not_ include system-installed gems, unless they are mentioned in the Gemfile.  If you put it into local app `./lib/` or `./vendor`, then you're modifying source code (I think?) and might as well just add it to the Gemfile as normal, what are you gaining?  I guess you could put the gem somewhere custom system-wide (not normal `gem install`), and custom add it to your apps load path?  Or wait, you're going to manually scp it into your app's dir, but not commit it to your vcs? I guess you _can_....
Comment: In my experience bundler sets a load path, but does not retrict it thereafter; i.e. I can edit the load path as I like within the app. What he's gaining is not needing to rev the Gemfile. He could use a system `gem install` (or not). He could choose to commit the code to a VCS (or not). My team does something similar using torrents to distribute gems, rather than bundler, because torrents are so much faster.
Comment: True, it doesn't restrict it after, it just takes the usual system gem location off the load path. I guess you could put it back...  or maybe less confusingly install your gems somewhere other than the system location and point to them there (no idea if this is less confusing or not actually, heh)
Answer: I don't think there's a good way to do quite exactly what you ask. Part of the bundler system (that's what uses Gemfiles) is that only gems mentioned in your gemfile (and their dependencies) are available to your app, it is isolated to only them.  If this sounds like a bad thing, we could have a long conversation about the pre-bundler dependency management problems that this system has successfully solved.
Option 1 -- what are you worried about anyway? There is probably no downside to including all the possible gems in your Gemfile, even if a given installation will only use one. If using Rails, you will want to make sure these gems are not require'd on launch.  (If not using Rails, this might not be neccesary, as other environments don't necessarily ask bundler to require all gems on boot (which is wise), but won't hurt).
So all the gems will get installed in every installation, yes, but only the one you want to use will be loaded, when you issue the require at runtime -- you'll still want to do this on application load, perhaps in response to an ENV variable, to avoid any concurrency or load time weirdness.  Anyway, the unused gems will just be sitting there on disk un-loaded. How big a downside is having them installed but not used? How much are you willing to increase the confusingness of your setup to get rid of this downside?
Option 1 is what I'd do.
Option 2 -- separate Gemfiles. Another option is preparing a separate Gemfile for each type of setup. Gemfiles are just ruby code, so you could have one 'base' gemfile including common gems, and then a separate Gemfile for each type of setup, which uses ruby to load/include the base gemfile and then adds the setup-specific gems.  You'd give each Gemfile a separate name, Gemfile_adapter1 or whatever.
You're going to have to commit something to your source when you add support for a new adapter type, aren't you? Where does this adapter come from? I don't understand how you could do it without revising any code. Anyway, adding a new Gemfile for that adapter type when you add a new adapter doesn't seem like a huge barrier, but I dunno.
You can launch Rails specifying which of these gemfiles to use with the BUNDLE_GEMFILE env variable:  BUNDLE_GEMFILE=./Gemfile_one rails server. And in every other command you do that will use the Gemfile. BUNDLE_GEMFILE=./SOME_GEMFILE bundle install. BUNDLE_GEMFILE=./SOME_GEMFILE RAILS_ENV=production bundle exec rake assets:precompile. If you use capistrano that's doing some of these things for you, figure out how to make sure cap uses the right BUNDLE_GEMFILE when it executes it. Figure out how to make your app server do that when it launches your app. Etc.
This will work out fine -- but is going to end up being a pain to keep track of and make sure it's working right in your entire devops stack.
I suppose you could even generate the Gemfiles at install time, instead of having them in your source repo, for even more confusing situation and another thing that can go wrong and be confusing to debug! (I wouldn't).
I'd consider this Option 2, but would prefer option 1 unless there were really good reasons it wasn't going to work.
Option 3 -- Don't use Bundler. You could abandon bundler and gemfiles entirely. Maybe, if you can convince Rails to do this somehow. It might be hard to convince Rails to do this.
If you could, you are in a situation where you have to install all your gems on your deploy system by hand, making sure they are the right versions and figuring out what versions are compatible with what other versions, and that no more recent versions you don't want are installed.
Then, at runtime, you just need to require all the gems you want, and the app will get the most recent version of that gem installed on the system.
I would never, ever, ever, do this. I don't know if you can get Rails to do it, but even if you could, I remember the dependency hell from before Bundler existed, and would never want to go back.
Comment: _You're going to have to commit something to your source when you add support for a new adapter type, aren't you?_ -- I shouldn't have to, because I'm not "adding support for a new adapter type" to the application, I'm just creating (in a separate gem) another class that responds to the methods the application expects for an adapter.
Comment: How does your app know to use the gem?  The name of it, or where to load it from, which adapter to choose?  Okay, figure out some way to do that using just ENV variables to tell it the name of the gem it should load, and conventions for what the class name inside that gem is, and all constructed dynamically?   Me, I would not want to go back to the pre-Bundler days where the dependency tree was not built, checked for consistency, and frozen in a Gemfile.lock.  If you can figure out a way to, maybe based on Matt's answer... I predict you'll independently re-discover why bundler is a good idea.
Comment: The class of problem that arose in pre-Bundler days, for example, is when your new gem uses dependency Widgetizer but only version 1.x and won't work with Wigetizer 2.x, but your app (or some existing dependency of it) needs Wigetizer 2.x.... and this is revealed by a mysterious exception that takes you an hour to figure out that's what's going on. And you have trouble controlling which version of Widgetizer actually gets loaded anyway, it depends on what gems are installed on the system-wide level. But if you want to try that path, Matt Brictson's solution seems like a direction.
Comment: So how does ActiveRecord do it? You don't need to edit a gemfile and re-bundle your application (or somebody else's application that you're just running) to switch databases, you just edit your `database.yml`. If you're  using something other than Postgres/MySQL/SQLite, say Oracle or DB2 for some reason, you install some extra gems. It's not rocket surgery. Or am I missing something?
Comment: In a Rails app, you _do_ add the gems for the particular database connectors you need to your Gemfile and rebundle. If you switch from mysql to postgres, you usually remove the mysql gem from your gemfile and add the postgres gem. The actual ActiveRecord adapters are _all_ [included with ActiveRecord](https://github.com/rails/rails/tree/master/activerecord/lib/active_record/connection_adapters), you get all of them AR supports out of the box included. If you want something else, you might install an extra gem--AND add it to your Gemfile and rebundle. It's not going outside the Gemfile at all.
Comment: If you want to add gem dependencies without editing the Gemfile, that's not what Rails/ActiveRecord does.  You actually DO need to edit a  gemfile and re-bundle (bundle install) your app to add or change dependencies, if you need a gem that wasn't already in your Gemfile (or a dependency in the gemspec of a gem in your Gemfile).

(I do really like 'rocket surgery' as a phrase though, heh)


When static global variable are created in C++

Question: I know that global variables are created in declaration order for same compilation unit and creation order is not defined between multiple compilation units.
I've read some time ago that global variables are created before any code from the compilation unit where they are defined is called. Is this defined by the standard?
Example:
file1.cpp
int f1v1 = f1_1();
int f1v2 = f1_2();

void f1(){...}

int f1_1(){...}
int f1_2(){...}

file2.cpp
static int f2v1 = f2_1();
static int f2v2 = f2_2();

int f2_1(){...}
int f2_2(){...}

main.cpp
#include "file1.h"
#include "file2.h"

int main()
{
    f1();

    return 0;
}

Is in this case guaranteed by the standard that f1_1() is called before f1_2() and before f1()? Is guaranteed by the standard that f2_1() and f2_2() are called at all as no function defined in file2.cpp is called and f2v1 and f2v2 are not visible outside file2.cpp?
EDIT:
Is the behavior specified by the standard when file1.cpp is compiled in lib1 and file2.cpp is compiled in lib2?
Comment: You may find this http://stackoverflow.com/questions/12321401/dynamic-initialization useful
Comment: Note: whether `static` or only effects the *linkage* of the variable, its initialization is identical.
Comment: @MatthieuM. I wanted to make it clear the variables are not used (accessed from other place)
Answer: Based on [basic.start.init]:
f1_1() is guaranteed to execute before f1_2() (para.2: "Variables with ordered initialization defined within a single translation unit shall be initialized in the order of their definitions in the translation unit.").
Both are guaranteed to execute before f1() (para.4: "If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first odr-use (3.2) of any function or variable defined in the same translation unit as the variable to be initialized.").
About f2_1() and f2_2(), [basic.stc.static]para.2 says "If a variable with static storage duration has initialization or a destructor with side effects, it shall not be eliminated even if it appears to be unused, ...". This would imply they are guaranteed to be called if they contain side effects.
Answer: If I'm understanding your question right, C++ guarantees the initialization order of variables by order of declaration within one compilation unit (i.e. a cpp file). The order of initialization across compilation units is undefined.
In the process of compilation, the f2_* functions according to the standard would be called, even though functions in file2.cpp are not ran. But if the compiler is smart enough, it can omit them entirely if it determines that the resulting program would act as if it had complied with the standard. (i.e. if it can guarantee beyond the shadow of the doubt that there would be no difference in behavior between a program with and a program without these functions being called)


Migrate into Multi-value Checkbox from CSV

Question: Update: Turns out typos suck. But added an answer to this as well, in case anyone ever stumbles upon this...
I'm running into a bit of an issue using Migrate API. I thought I had a fairly simple use-case, but am unable to actually find an example for this particular instance.
I have a CSV I'm importing, utilizing the migrate_source_csv module. My migration was working just fine, but now I need to add a field_dealer_type field. This field is a multivalue checkbox. In the CSV, it's represented in a single dealer_type column, separated by commas (I've also tried other delimiters with no success).
A couple example rows of my CSV would look like:
id,name,city,dealer_type
1,Sample Location,Cool City,"trucks,motorcycles"
2,Another Location,Second City,trucks

The CSV is well-formatted, wrapping the dealer_type column in quotes when necessary.
However, I'm not able to get these to import properly into my nodes. I've verified the values through the CSV are valid options in the field definition as well (trucks, motorcycles).
I've started with the explode plugin, as other examples use that as well, but I know I'm missing a follow-up processing. I've seen example using Taxonomy and entity_generate, but that doesn't fit my use-case. I also have the migrate_plus module installed, for clarity.
langcode: en
status: true
dependencies: {  }
id: dealers_csv
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags: null
migration_group: default
label: 'Import Dealers'
source:
  plugin: csv
  path: sites/default/files/dealer_locations.csv
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  keys:
    - id
  column_names:
    -
      id: 'Unique Id'
    -
      name: 'Dealer Name'
    -
      city: City
    -
      dealer_type: 'Dealer Type'
process:
  title: name
  type:
    plugin: default_value
    default_value: dealer_location
  field_dealer_name: name
  field_dealer_city: city
  field_dealer_type:
    plugin: explode
    limit: 2
    delimeter: ','
    source: dealer_type
destination:
  plugin: 'entity:node'

Answer: Turns out typos can send you down a completely misguided rabbit hole!
Within the explode plugin, the property should be delimiter, not delimeter (incorrect spelling).
After that switch, things are working great.
Yay.


When I click the "Replay" button only the GameScene.sks runs, not the GameScene.swift... How do I get both to play at the same time?

Question: New to Stackoverflow so sorry if I posted it wrong! Thanks
My App is a maze game with a time limit, once the time hits 0 the game ends and it goes to a game over screen (separate swift file), this consists of a "Replay" button which when pressed only shows the gamescene.sks file and not the gamescene.swift file (therefore none of the functions work). Is there a way to show both?
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
            for touch: AnyObject in touches {
                let location = touch.locationInNode(self)
                let node = self.nodeAtPoint(location) //1
                if node.name == "replay" { //2

                    let reveal : SKTransition = SKTransition.flipHorizontalWithDuration(1)
                    let scene = GameScene(size: self.size)
                    scene.scaleMode = .AspectFill
                    self.view?.presentScene(scene, transition: reveal)

                    let reveal2 : SKTransition = SKTransition.flipHorizontalWithDuration(1)
                    let sksScene = SKScene(fileNamed: "GameScene.sks")
                    sksScene!.scaleMode = .AspectFill
                    self.view?.presentScene(sksScene!, transition: reveal2)

                }
            }
        }

Answer: You need to ensure you're using your GameScene subclass when loading your GameScene.sks
let skView = self.view as SKView!
let transition = SKTransition.flipHorizontalWithDuration(0.5)
let scene = GameScene(fileNamed:"GameScene") as GameScene!
scene.scaleMode = .AspectFill
skView.presentScene(scene, transition: transition)

You only need to use presentScene once :]


Can't create directory named "mysql" in subversion repository

Question: I have a particular problem with subversion.
Environment: subversion (1.6.12dfsg-6), apache2 (2.2.16-6+squeeze7) + mod dav_svn.
I can't create a directory named "mysql" or "testmysql" or add and commit a file named "mysql.txt" in my repository.
There are many references to "subversion PROPSET 403 forbidden" problems in google and so on.
But I can use all functions of subversion. I can also create a directory named "hugo" or "test". My repository works properly.
Only "mysql" doesn't work.
The following errors occur:
The server encountered an unexpected return value (403 Forbidden) in response to the
request for MKCOL »/svn/repository/!svn/wrk/8123484e-8890-412d-92ed-62ceabcd4189
/etc/mysql" returned

/var/log/apache2/access.log
192.168.178.200 - - [time] "OPTIONS /svn/repository/etc HTTP/1.1" 401 6156 "-" "SVN/1.6.12 (r955767) neon/0.29.3"
192.168.178.200 - user1 [time] "OPTIONS /svn/repository/etc HTTP/1.1" 200 1028 "-" "SVN/1.6.12 (r955767) neon/0.29.3"
192.168.178.200 - user1 [time] "MKACTIVITY /svn/repository/!svn/act/6564e2e2-19be-4a09-bcb6-61a1cfb097e8 HTTP/1.1" 201 676 "-" "SVN/1.6.12 (r955767) neon/0.29.3"
192.168.178.200 - user1 [time] "PROPFIND /svn/repository/etc HTTP/1.1" 207 676 "-" "SVN/1.6.12 (r955767) neon/0.29.3"
192.168.178.200 - user1 [time] "CHECKOUT /svn/repository/!svn/vcc/default HTTP/1.1" 201 692 "-" "SVN/1.6.12 (r955767) neon/0.29.3"
192.168.178.200 - user1 [time] "PROPPATCH /svn/repository/!svn/wbl/6564e2e2-19be-4a09-bcb6-61a1cfb097e8/157 HTTP/1.1" 207 580 "-" "SVN/1.6.12 (r955767) neon/0.29.3"
192.168.178.200 - user1 [time] "PROPFIND /svn/repository/etc HTTP/1.1" 207 564 "-" "SVN/1.6.12 (r955767) neon/0.29.3"
192.168.178.200 - user1 [time] "CHECKOUT /svn/repository/!svn/ver/157/etc HTTP/1.1" 201 692 "-" "SVN/1.6.12 (r955767) neon/0.29.3"
192.168.178.200 - user1 [time] "MKCOL /svn/repository/!svn/wrk/6564e2e2-19be-4a09-bcb6-61a1cfb097e8/etc/mysql HTTP/1.1" 403 596 "-" "SVN/1.6.12 (r955767) neon/0.29.3"
192.168.178.200 - user1 [time] "DELETE /svn/repository/!svn/act/6564e2e2-19be-4a09-bcb6-61a1cfb097e8 HTTP/1.1" 204 165 "-" "SVN/1.6.12 (r955767) neon/0.29.3"

Has anyone seen this before?
Thanks for any advice.
Answer: It sounds like you have something in your apache config that is refusing such URLs with "mysql" in them. Have you looked thoroughly through your configuration? Try grep for "mysql" in there.
Comment: What a stupid mistake. `RewriteRule mysql - [NC,F,L]`. I thought I had corrected all theses files. Thank you.


apache2 osx virtual host serving same directory

Question: In httpd.conf
Listen 127.0.0.1:80

ServerName testsite.com:80
DocumentRoot /usr/share/web
<Directory /usr/share/web>
// usual stuff from documentation
</Directory>

Include httpd-vhost is uncommented
in httpd-vhost.conf
NameVirtualHost *
<VirtualHost *>
  DocumentRoot "/usr/share/web/a"
  ServerName www.testsite.com
  ServerAlias testsite.com
</VirtualHost>

<VirtualHost *>
  DocumentRoot "/usr/share/web/b"
  ServerName site.testsite.com
  ServerAlias site
</VirtualHost>

in /etc/hosts
127.0.0.1 localhost testsite.com www.testsite.com site.testsite.com
if I goto site.testsite.com, testsite.com www.testsite.com
I get served the page from /usr/share/web
Thanks
Answer: In httpd.conf, you're specifically listening on port 80, but your virtual hosts are not specifying a port.
Change to the following:
NameVirtualHost *:80

and in each of your VirtualHost containers:
<VirtualHost *:80>

Also, you're defining the same ServerName in httpd.conf and httpd-vhost.conf -- I recommend changing the one in httpd.conf to something else.


Remove Directory recursively

Question: I wrote a custom remove function in PHP. The function call is used recursively, but when calling the function, I get an error output:
// custom delete directory function
function deleteDirectory($dir) {
    if (!file_exists($dir)) return true;
    if (!is_dir($dir) || is_link($dir)) return unlink($dir);
    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') continue;

        // THIS IS LINE 32 LIKE MENTIONED IN THE ERROR
        if (!$this->deleteDirectory($dir . "/" . $item)) {

             // THIS IS LINE 33 LIKE MENTIONED IN THE ERROR
            chmod($dir . "/" . $item, 0777);
            if (!$this->deleteDirectory($dir . "/" . $item)) return false;
        };
    }

    // THIS IS LINE 37 LIKE MENTIONED IN THE ERROR
    return rmdir($dir);
}

function cleanup() {
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->workFolder), RecursiveIteratorIterator::CHILD_FIRST);
    foreach ($files as $name => $fileObject) {
        if (is_file($name)) {
            unlink($name);
        } else if (is_dir($name)) {
            system("/bin/chmod -R 0777 $name");
            $this->deleteDirectory($name);
        }
    }
    $this->deleteDirectory($this->workFolder);
}

I tried the approach with "$this->deleteDirectory()"
but now I receive a totally different error:
Warning: rmdir(/tmp/533aab0362830/.) [function.rmdir]: Invalid argument in /usr/www/users/kontug/api.medifaktor.de/webservice/passkit/class/Pass.php on line 37

Warning: rmdir(/tmp/533aab0362830/../.ICE-unix) [function.rmdir]: Operation not permitted in /usr/www/users/kontug/api.medifaktor.de/webservice/passkit/class/Pass.php on line 37

Warning: chmod() [function.chmod]: Operation not permitted in /usr/www/users/kontug/api.medifaktor.de/webservice/passkit/class/Pass.php on line 33

Warning: rmdir(/tmp/533aab0362830/../.ICE-unix) [function.rmdir]: Operation not permitted in /usr/www/users/kontug/api.medifaktor.de/webservice/passkit/class/Pass.php on line 37

Comment: Function is part of a class: missing `$this->` or static reference.
Comment: Where you call the function ?
Comment: And what's on line 32 of `/webservice/passkit/class/Pass.php`?
Comment: You should debug step by step (`var_udmp($dir)`)
Comment: I tried the var_dump, but without any outcome. I thought about the "operation not permitted", but I set the chmod to 0777 before.
Comment: possible duplicate of [A recursive remove directory function for PHP?](http://stackoverflow.com/questions/1407338/a-recursive-remove-directory-function-for-php)
Comment: I think you have an issue with PHP language. What the `$dir` print at the beginning of the method ? Throw an Exception if `$dir` is empty. Maybe you don't have the right permission on the folder so you're not able to use the `chmod()`.
Answer: If the function belongs to a class then it should be called like this
$this->deleteDirectory($dir . "/" . $item)

instead of
deleteDirectory($dir . "/" . $item)

Comment: yes, we would call it a method, but php does not say 'method' in error's, or in class definition. So the term 'function' is a bit amibuous here. So in fact @Dikesh is (most probably) right in his suggestion.
Comment: If it were part of a class, wouldn't it be a "method"?
Comment: Yes you are right @ghoti

http://stackoverflow.com/questions/4841605/what-is-a-difference-between-a-method-and-a-function
Answer: When you use classes you must call the method as $this->methodName().
Below is snipped which worked for me.
You can try this.  If it gives permission error then you can add chmod function.
Remember you can not traverse a directory if you don't have read permission.  So set the permission first.
   function deleteDirectory($dir) {
        if (!file_exists($dir)) return true;
        if (!is_dir($dir)) return unlink($dir);
        foreach (scandir($dir) as $item) {
            if ($item == '.' || $item == '..') continue;
            if (!$this->deleteDirectory($dir.DIRECTORY_SEPARATOR.$item)) return false;
        }
        return rmdir($dir);
    }

Comment: I believe after setting the permission from terminal your issue will be solved. Hope so. Best Luck.
Comment: I tried this method you suggested: and inserted the following line after "foreach" and before the first if statement: chmod($dir . "/" . $item, 0777); But this is not accepted by the script
Comment: I mean if you are trying to access a directory outside the /var/www (i.e root of execution) folder. Then from terminal set the permission. Not from the code. In code don't set permission in recursive function.
Comment: ah okay. I am creating dynamically temp folders with the sys_get_temp_dir() function. How can I set the permission to them?
Comment: Rather than I'll say use something like this before calling the deleteDirectory method. system("/bin/chmod -R $mod $dir");
Comment: This seems to work, but I still get an error for the line:
return rmdir($dir); (Invalid Argument, and operation not permitted);

Warning: rmdir(/tmp/533ab2ea4a033/.) [function.rmdir]: Invalid argument in /usr/www/users/kontug/api.medifaktor.de/webservice/passkit/class/Pass.php on line 35

Warning: rmdir(/tmp/533ab2ea4a033/../.ICE-unix) [function.rmdir]: Operation not permitted in /usr/www/users/kontug/api.medifaktor.de/webservice/passkit/class/Pass.php on line 35
Comment: Operation not permitted means you are running the command as www-data user. You have to be root or any other user if you want access to other directories you can try this "sudo /bin/chomod..." if you are on ubuntu this will run it as root.
Comment: This error is just because user www-data don't have permission to delete those files and directories. Use that system function with sudo set permission and then call delete method.
Comment: just one more question! :) The "sudo /bin/chmod" can be called within PHP?
Comment: yes it can be called in php it will make a System call but I'll say first try without sudo. More info about exec, system is here http://stackoverflow.com/questions/732832/php-exec-vs-system-vs-passthru
Comment: I just tried the call without sudo, but still no difference..Sorry. I don't want to bug you! I just edited the question: The cleanup() method. Is this correct?
Comment: Use sudo then because current user doesn't have enough permission to modify it.
Comment: I did this as well:

system("sudo /bin/chmod -R 0777 $files");

But still no change.. I am really sorry I am not up to speed here :)
Comment: Do I call the system function at the right place at all?
Comment: not $files it should be parent of directory eg. /temp. So it will recursively set the permission.
Comment: put the system function immediately after opening cleanup function.
Comment: it will look like this function cleanup(){ system("/bin/chmod -R 0777 $this->workFolder"); ...
Comment: So I tried this: function cleanup() {system("/bin/chmod -R 0777 $this->workFolder"); (...)}  But still the same message.
Comment: ohh.. then try this system("/usr/bin/sudo /bin/chmod -R 0777 $this->workingFolder");
Comment: You won't believe it Vivek... still no change.... I still get the Operation not permitted
Comment: hmm... from terminal are you able to set the permission? change the $this->working folder to a constant like /temp then try
Comment: I don't seem to have access by terminal to the server... I think I don't have root access

Remove Directory recursively


$p(x,y)\in\mathbb{R}[x,y]$ and $\forall x,y\in\mathbb{R}$ we have $p(x-1,y-2x+1)=p(x,y)$. prove $\exists f\in\mathbb{R}[x]$ so that $p(x,y)=f(y-x^2)$

Question: hint only

$p(x,y)\in\mathbb{R}[x,y]$ and $\forall$ $x,y\in\mathbb{R}$ we have $p(x-1,y-2x+1)=p(x,y)$.
prove $\exists$ $f\in\mathbb{R}[x]$ so that $p(x,y)=f(y-x^2)$

my attempt :
if $p(x,y)=f(y-x^2)$ then $p(x,x^2)=f(0)=c$ (this should be correct)
according to the assumption of the problem $p(x,x^2)=p(x-1,(x-1)^2)$ so if
$g(x)=p(x,x^2)$ then $g(x)=g(x-1)$ therefor it is clear that $p(x,x^2)=g(x)=c$ (c is constant)
now $$p(x,y)=(y-x^2)p_1(x,y)+r(x)$$
then $$p(x,x^2)=r(x)$$
but we know that $p(x,x^2)=c$ so $r(x)=c$
now $$p(x,y)=p(x-1,y-2x+1)$$
$$(y-x^2)p_1(x,y)+c=(y-2x+1,(x-1)^2)p_1(x-1,y-2x+1)+c$$
$$(y-x^2)\big(p_1(x-1,y-2x+1)-p_1(x,y)\big)=0$$
if $x^2\not=y$ then $p_1(x-1,y-2x+1)=p_1(x,y)$
if $x^2=y$ .....?
Comment: It suffices to show that $p(x,y)$ depends only on $y-x^2,$ i.e. if $y-x^2=v-u^2$ then $p(x,y)=p(u,v).$
Comment: @RyszardSzwarc That would be enough to show there is a function $f$. You need some more argumentation to show that $f$ is actually a polynomial.
Comment: EDIT: deleted, is probably more explicit of a hint than appropriate
Comment: @Arthur Sorry, I was not familiar with the notation $\mathbb{R}[x,y].$ Clearly the conclusion does not hold for any function. So it suffices to show that $p(x,y)=(y-x^2)q(x)+c.$ Then $q$ is a polynomial.
Comment: @RyszardSzwarc $P(x,y)=(y-x^2)p_1(x,y)+c_0=(y-x^2)\big((y-x^2)p_2(x,y)+c_1\big)+c_0=\dots=c_n(y-x^2)^n+c_{n-1}(y-x^2)^{n-1} + \dots + c_1(y-x^2)+c_0=f(x-y^2)$

and we're done for $x^2\not=y$
Comment: @farnoodgholampoor Yes, that what I meant. See the answer below.
Comment: For what it's worth, the solution I was thinking (which I thought was what Ryszard was getting at) was: $p(x, x^2+l) = p(x-1, (x-1)^2+l)$ and similarly as in the asker's approach, it follows that $p(x, x^2+l) = f(l)$ for some function $f$. Then a substitution gives $p(x, y) = f(y - x^2)$. And plugging in $x=0$ implies that $f$ is a polynomial.
Answer: Let $T(x,y)=(x-1,y-2x+1).$ Then $p\circ T=p.$ For $g(x,y)=y-x^2$ we have $g\circ T=g.$ Following OP let
$$p(x,y)=g(x,y)p_1(x,y)+r(x)\qquad (1)$$ Then
$$p(x,y)=(p\circ T)(x,y)=g(x,y)(p_1\circ T)(x,y)+r(x-1) \quad (2)$$ Subtracting $(1)$ and $(2)$ implies that  $r(x)-r(x-1)$ is divisible by $g(x,y)=y-x^2,$ i.e. $r$ is a constant.
We thus have
$$p(x,y)=g(x,y)p_1(x,y)+r$$ and $p_1(x,y)={p(x,y)-r\over g(x,y)}.$ Therefore $p_1\circ T=p_1.$ We can repeat the same procedure to $p_1(x,y)$ and so on. More formally we can apply the induction argument with respect to the degree of $y.$ Eventually we obtain
that $p(x,y)=a_n(y-x^2)^n+\ldots +a_1(y-x^2)+a_0.$
Answer: Since $p_1$ satisfies the same condition as $p$ for all $y\ne x^2$ then it satisfies this condition for all $x,y$ and thus $p_1(x,y) = f_1(y-x^2)$ for some polynomial $f_1$ by induction on the degree. So $p(x,y)= f(y-x^2)$ for some polynomial $f$.


How to type define a bound this

Question: I'm using a library with a function that takes a callback, and then (frustratingly) calls callback = (callback || noop).bind(this). In the callback, I need to grab this:
    kurento_utils.WebRtcPeer.WebRtcPeerSendonly(options, function (error: any) {
        if ( error ) {
            return on_error(error);
        }
        let webRTC_peer = this;  // kurento_utils binds 'this' to the callback
                       // ^^^^ error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.

        webRTC_peer.generateOffer((error: string | undefined, offer: string) => {

...

TypeScript is (understandably) unhappy with this situation, at least when the noImplicitThis flag is enabled.
I have no idea how to properly type annotate this.
Answer: You can add a this parameter to the function. This parameter will not be emitted to Javscript, and will be just for the benefit of the compiler so it can correctly type this witing the function:
 kurento_utils.WebRtcPeer.WebRtcPeerSendonly(options, function (this:WebRtcPeer, error: any) {
      let webRTC_peer = this; // this will be of type WebRtcPeer
 }

Or if you also control the WebRtcPeerSendonly you could specify that the function it takes as a parameter will have a certain this passed to it and type inference will work for this just as any other parameter:
class WebRtcPeer {
    WebRtcPeerSendonly(options: any, fn: (this: WebRtcPeer, error: any) => void) {

    }
}

new WebRtcPeer().WebRtcPeerSendonly({}, function(error){
    let webRTC_peer = this; // this will be of type WebRtcPeer
})

Comment: I'd read about adding an extra `this` parameter, but I must've missed that it isn't emitted to Javascript. Thanks for enlightening me!

How to type define a bound this


Help finding an explicit solution to this ODE

Question: I have the following ODE:
$$\dot{r}=(r-r^{3})\sin^{2}(\theta)$$
I have been trying to find an explicit solution for $r$, with little success. I have tried separating variables but then get stuck trying to make it explicit. Any suggestions? Thanks.
Comment: Is $theta$ an independent variable that is also satisfying some DE, or is it a constant?
Comment: @JoshB. I assume the OP means $\frac{dr}{d\theta}$ by $\dot{r}$, especially as one of the tags is polar coordinates.
Answer: $$\frac{dr}{d\theta}=(r-r^3)\sin^2\theta$$
Separating the variables:
$$\int\frac{1}{r-r^3}dr=\int\sin^2\theta d\theta$$
First, let's focus on the integral on the left hand side.
$$\begin{align}
\int\frac{1}{r-r^3}dr&=\int\frac{1}{r(1-r)(1+r)}dr=\int\frac{1}{r}+\frac{1}{2(1-r)}-\frac{1}{2(1+r)}dr\\
&=\ln\lvert r\rvert-\frac{1}{2}\ln\lvert1-r\rvert-\frac{1}{2}\ln\lvert1+r\rvert+C\\
&=\frac{1}{2}\ln\left\lvert\frac{r^2}{1-r^2}\right\rvert+C\\
&=\frac{1}{2}\ln\left\lvert\frac{r^2-1+1}{1-r^2}\right\rvert+C=\ln\left\lvert\frac{1}{1-r^2}-1\right\rvert+C\end{align}$$
Now for the right integral.
$$\int\sin^2\theta d\theta=\frac{1}{2}\int1+\cos 2\theta d\theta=\frac{1}{2}\theta+\frac{1}{4}\sin2\theta+D$$
Hence,
$$\ln\left\lvert\frac{1}{1-r^2}-1\right\rvert=\theta+\frac{1}{2}\sin2\theta+C_1$$
And now we can rearrange to find $r^2$, and thus find $r$.

I hope that helps. If you have any questions please don't hesitate to ask :)


Node.js, Express, MongoDB stack: want response to stay on same page

Question: I have written a one-page app using Node and Express. This page has several sections, each with a form on it. I POST the data from each form to Mongo, but would like to find a response that stays on the same page, and without refreshing the page. Here is my router code:
/* POST data to visitorSessionsTest collection */

router.post('/datasubmit', function(req, res) {

    // Set internal DB variables
    var db = req.db;

    // Get form values.
    var questionId = req.body.questionId;
    var visitorData = req.body.visitorData;

    // Set collection
    var collection = db.get('visitorSessionsTest');

    // Submit to the DB
    collection.insert({
        "questionId" : questionId,
        "visitorData" : visitorData
    }, function (err, doc) {
        if (err) {
            // If it failed, return error
            res.send("There was a problem adding the information to the database.");
        }
        else {
            // what can go here?

        );
        }
    });
});

Even better would be to have the response write innerHTML to a div in the appropriate section on that page reflecting that the data was collected.
UPDATE Client-side code begins in Jade, but the relevant part amounts to a series of forms with inputs, like this:
<form id="data-submit" name="datasubmit" method="post" action="/datasubmit">
<button name="visitorData" value="16" type="submit" onclick="showMessage(0)">16</button>
....

Comment: You may want to use ajax. Call the post/get through ajax. Once the response received, utilize i.e jquery to update the div with the response
Answer: Sounds like you want to read up on RESTful API's a bit; there's a lot of common approaches to this kind of thing that aren't node-specific.
That said, what I'd do in your place is to send a 201 ("Created") response, along with a copy of the object created including whatever is needed to navigate to it later (e.g. the ID if your GET routes are based on the object ID).
res.status(201).send({id:doc._id, whatever:else, you:want});

Answer: The reason it redirects is because of  type="submit" on the button. If you remove that and submit the form just through ajax express won't route to the next page