text:
Q: how to stop a ball at a particular number in roulette wheel I'm creating a roulette game in WPF and C#.NET. I spin the wheel successfully but I'm stuck to get the specific value where the ball is stopping.
can anybody help me what kind of logic I can apply to get the value of either
I've created basic animation using Expression Blend (code below) how can I get the value where the ball is stopped.
 <Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="demo.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480">
<Window.Resources>
    <Storyboard x:Key="spinWheel">
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)" Storyboard.TargetName="canvas">
            <EasingDoubleKeyFrame KeyTime="0" Value="-0.056"/>
            <EasingDoubleKeyFrame KeyTime="0:0:1" Value="-89.871"/>
            <EasingDoubleKeyFrame KeyTime="0:0:2" Value="-179.468"/>
            <EasingDoubleKeyFrame KeyTime="0:0:3" Value="-269.405"/>
            <EasingDoubleKeyFrame KeyTime="0:0:4" Value="-360.488"/>
        </DoubleAnimationUsingKeyFrames>
        <DoubleAnimationUsingPath Duration="0:0:3.96" Source="X" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="ellipse">
            <DoubleAnimationUsingPath.PathGeometry>
                <PathGeometry Figures="M39.5,115 C39.5,218.55339 -44.446609,302.5 -148,302.5 C-251.55339,302.5 -335.5,218.55339 -335.5,115 C-335.5,11.446609 -251.55339,-72.5 -148,-72.5 C-44.446609,-72.5 39.5,11.446609 39.5,115 z"/>
            </DoubleAnimationUsingPath.PathGeometry>
        </DoubleAnimationUsingPath>
        <DoubleAnimationUsingPath Duration="0:0:3.96" Source="Y" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="ellipse">
            <DoubleAnimationUsingPath.PathGeometry>
                <PathGeometry Figures="M39.5,115 C39.5,218.55339 -44.446609,302.5 -148,302.5 C-251.55339,302.5 -335.5,218.55339 -335.5,115 C-335.5,11.446609 -251.55339,-72.5 -148,-72.5 C-44.446609,-72.5 39.5,11.446609 39.5,115 z"/>
            </DoubleAnimationUsingPath.PathGeometry>
        </DoubleAnimationUsingPath>
    </Storyboard>
</Window.Resources>
<Window.Triggers>
    <EventTrigger RoutedEvent="FrameworkElement.Loaded">
        <BeginStoryboard Storyboard="{StaticResource spinWheel}"/>
    </EventTrigger>
</Window.Triggers>

<Grid x:Name="LayoutRoot">
    <Canvas x:Name="canvas" Margin="22,62,248,26" RenderTransformOrigin="0.5,0.5">
        <Canvas.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform/>
                <TranslateTransform/>
            </TransformGroup>
        </Canvas.RenderTransform>
        <Ellipse x:Name="ellipse1" Fill="#FFF4F4F5" Stroke="Black" Height="354" Width="354"/>
        <Path Data="M308,44 L308,394.5" Fill="#FFF4F4F5" Stretch="Fill" Stroke="Black" Width="1" Height="351.5" Canvas.Left="179" Canvas.Top="1"/>
        <Path Data="M144,240 L495.5,240" Fill="#FFF4F4F5" Height="1" Stretch="Fill" Stroke="Black" Canvas.Left="1" Canvas.Top="176.5" Width="352.5"/>
        <TextBlock x:Name="one" Height="88" TextWrapping="Wrap" Text="1" Width="72" FontSize="64" Canvas.Left="75" Canvas.Top="64.5"/>
        <TextBlock x:Name="two" Height="88" TextWrapping="Wrap" Text="2" Width="72" FontSize="64" Canvas.Left="219" Canvas.Top="64.5"/>
        <TextBlock x:Name="three" Height="88" TextWrapping="Wrap" Text="3" Width="72" FontSize="64" Canvas.Left="219" Canvas.Top="200.5"/>
        <TextBlock x:Name="four" Height="88" TextWrapping="Wrap" Text="4" Width="72" FontSize="64" Canvas.Left="75" Canvas.Top="200.5"/>
    </Canvas>
    <Ellipse x:Name="ellipse" Fill="#FFFF2300" HorizontalAlignment="Right" Height="24" Margin="0,112,264,0" Stroke="Black" VerticalAlignment="Top" Width="24" RenderTransformOrigin="0.5,0.5">
        <Ellipse.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform/>
                <TranslateTransform/>
            </TransformGroup>
        </Ellipse.RenderTransform>
    </Ellipse>
</Grid>

A: Add an event handler on your storyboard
    <Storyboard x:Key="spinWheel" Completed="Storyboard_Completed">

Add names to your rotate transforms
    <RotateTransform x:Name="wheelAngle" />

In code behind do some maths and work out where the ball is from wheelAngle.Angle and ballAngle.Angle.


text:
Q: Handling several Azure Functions with same named DLL We are building a Azure Function App where we have 5 different functions with their separate bin folders (one for each function), but each bin contains a private assembly (dll) (although the code used to create that assembly is different) with the same name, as far as I understand as they all share the same Azure Function App domain at runtime which dll is loaded depends on the runtime and may cause the other functions to fail

A: Yes, for a single Function App, all your functions will run in the same app domain (for C#/F#/Node/Powershell). Therefore, you can't have multiple functions running concurrently that each load a different assembly with the same name.
Some of the supported languages are "out of proc" (e.g. BAT). When those functions are executed, they run in a separate process. However the drawback there are that a new process is spawned for each invocation, so you'd only want to use that for non high-throughput scenarios.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pass a pointer to the array of structure in another fuction I am trying to pass pointer to an array of structures to another function
#include<stdio.h>
#include<string.h>

typedef struct CovidData{
  char region[7];
  char towns[12];
  char race[12];
  int yearlyIncome;
  int members;
  int testedMembers;
  int testedPositive;
} CovidData;

void RandomDataGenerator(CovidData *data[] ,int count)
{
    for(int i=0;i<count;i++){
          memcpy(data[i]->region,"david",sizeof("david"));
          memcpy(data[i]->towns,"david",sizeof("david"));
          memcpy(data[i]->race,"david",sizeof("david"));
          data[i]->yearlyIncome=1000;
          data[i]->members=99;
          data[i]->testedMembers=88;
          data[i]->testedPositive=656;
    }
}

int main() {
    struct CovidData data[100];

    RandomDataGenerator(&data,2);
    for(int i=0;i<5;i++){
        printf("%s",data[i].region);
    }
}

But it throws an error while compiling in terminal with gcc
incompatible pointer types passing 'CovidData (*)[100]' to
parameter of type 'CovidData

A: CovidData *data[] is grouped as CovidData *(data[]), so it declares an array of pointers to CovidData. For a pointer to an array, you would use CovidData (*data)[].
However, we rarely pass a pointer to an array. Usually, it is sufficient and convenient merely to pass a pointer to the first element. Thus, you would declare the parameter as CovidData *data and pass it as RandomDataGenerator(data, 2).
If you did declare the parameter as a pointer to an array, you would not use it with data[i]->region. You would need *data to get the array before applying the subscript, and again you would need parentheses for correct grouping: (*data)[i]->region.

A: Change your function to void RandomDataGenerator(CovidData *data ,int count); and pass only the pointer to the first array element, like this RandomDataGenerator(data,2);
#include<stdio.h>
#include<string.h>

typedef struct CovidData{
  char region[7];
  char towns[12];
  char race[12];
  int yearlyIncome;
  int members;
  int testedMembers;
  int testedPositive;
} CovidData;

void RandomDataGenerator(CovidData *data ,int count)
{

    for(int i=0;i<count;i++){
          memcpy(data[i].region,"david",sizeof("david"));
          memcpy(data[i].towns,"david",sizeof("david"));
          memcpy(data[i].race,"david",sizeof("david"));
          (data+i)->yearlyIncome=1000;
          data[i].members=99;
          data[i].testedMembers=88;
          data[i].testedPositive=656;
    }

}

int main() {
    struct CovidData data[100];

    RandomDataGenerator(data,2);
    for(int i=0;i<5;i++){
        printf("%s\n",data[i].region);
    }
}


text:
Q: Efficient binary-search Out of the two different implementation of binary-search, which one is more efficient and why?
In general binary-search divide a sorted array to two, compare the target entry with operator < or > against the two divided part of array, and keep iterating until finished or found the target entry.
int a[8] = {1, 3, 4, 5, 7, 8, 9, 11};

1.
while ( size > 1)
{
    mid = low + (size/2);
    if (a[mid] > find)
    {
       size = mid - low;
    }
    else
    {
        size = size - (mid - low);
        low = mid;
    }
}

2.
while (low <= size)
{
    mid = (low + size)/2;
    if (a[mid] < find)
    {
        low = mid + 1;
    }
    else if (a[mid] > find)
    {
        size = mid - 1;
    }
    else
    {
        break;
    }
}

While searching 6, the first one, iterate as,
mid = 4 size = 4 low = 0
mid = 2 size = 2 low = 2
mid = 3 size = 1 low = 3
5

and the second one does one iterate more and taking next entry.
mid = 4 size = 3 low = 0
mid = 1 size = 3 low = 2
mid = 2 size = 3 low = 3
mid = 3 size = 3 low = 4
7

Which one is efficient?


text:
Q: How to handle GRUB configuration on a multi booted system? I just finished changing the boot order for GRUB2. I have three operating systems installed on the computer. I have Windows 8.1, Ubuntu Linux 15.04 and Mint Linux 17.2. I followed Marve's answer here: How do I change the GRUB boot order?
The thing is, it failed at first! I was booted into Ubuntu at the time I made the changes. I used the name reference like GRUB_DEFAULT='Windows 8' instead of index number, and I only worked with /etc/default/grub file. I then issued updated-grub and rebooted. I had Windows somewhere in the middle of the boot menu, Ubuntu at bottom, and Mint at the top. When the delay time ran out at the boot menu screen, Mint booted up, and not Windows.
Then I rebooted and booted back into Ubuntu to ensure my changes were still there in /etc/default/grub and they sure were. I also noticed I had a third grub~ file, along with my grub.bak backup file.
I then booted into Mint and made the same changes there, and rebooted. Sure enough, it worked! So I now have Windows selected by default at the boot menu screen and it boots up when time runs out. This is what I wanted.
But what bothers me is why I had to do this in Mint? Why did it not work in Ubuntu? Is this because I installed Mint after I installed Ubuntu? That's the only explanation I can think of. Is GRUB2 installed to more than one location? I remember that I had chosen to install the bootloader to the MBR during both system installations. Maybe it has something to do with the configuration files alone, and not the actual bootloader program? What if I had mounted the /etc to a dedicated partition? Would that make them share the configuration files? How about the /boot then?
There is another thing that bothers me with this setup, and it's the constant changing of the boot order and background colors and layout of the boot menu options for GRUB2. This seems to happen when either one of the operating systems gets an upgrade, or some major update that somehow requires updating the boot menu options. How can I avoid this? If I set the boot menu screen background to be blue, how can I prevent it from changing to purple the next morning when Ubuntu gets a new major update or upgrade?
In the linked answer above, have a look at the "troubleshooting" section. Here's an excerpt.

The Grub Customizer settings may work only from within the latest
  Linux/Ubuntu installation, the one that installed the Grub.

It looks like I may be onto something here. This might have to do with what I mentioned above. Is it not so? It sounds really silly that you would have to make changes only in the last installed Linux system. Be it that you use a GUI tool like GRUB Customizer or the command line tools and manual editing. Can someone more knowledgeable please shed some light on this issue?

A: If you have multiple installs using grub2, only one of them can be in MBR and controls booting. That usually is the last install. And you may have issues if you installed both originally to MBR of same drive. Grub remembers where it installed and a major update of grub will reinstall it. Or either or both installs may be updating grub. I like to document how system is booting with Summary report:
https://help.ubuntu.com/community/Boot-Info
On one install you use least you can unselect all install choices. But make sure other is in MBR as default boot first.
How do I prevent one of my partitions messing with Lubuntu Grub entries?

A: GRUB is designed to take over control of the initial stages of the boot process. This works fine on a single-boot system (Ubuntu only, say) or when dual-booting one GRUB-based OS (like Ubuntu) with Windows; but when you install two GRUB-based OSes (like Ubuntu and Mint), the two GRUBs will fight for control of the boot process.
Experienced multi-booters often take one of three approaches to manage this process:

*

*Give control to one distribution -- You can omit GRUB from one installation in order to give control to another. One way to do this is to tell the installer for the secondary distribution to not install GRUB. In the case of both Ubuntu and Mint, you can do this by booting the installer in its "try before installing" mode, launch a Terminal, and typing sudo ubiquity -b. The -b option tells the installer to omit GRUB. Once installed, this gets trickier. Personally, I've got a dummy grub-pc-3 package that contains nothing but a couple of empty directories. Its version number guarantees that it's "more recent" than any GRUB 2 pacakge, and so installing it causes GRUB to be removed and the system won't attempt to re-install GRUB (which may otherwise happen). This dummy-package approach is inelegant; I'm sure there's a better way to achieve the same effect, but I've never bothered researching it to figure out what it might be.

*Give control to a custom GRUB 2 -- You can remove GRUB 2 from both your installations and then set up a GRUB 2 that's independent of either one. This can make the system as a whole more robust against problems caused by deleting the distribution associated with GRUB 2 in the future, so this method is favored by people who multi-boot many distributions and who make frequent changes to those distributions. It requires a lot of GRUB 2 expertise to set it up, though.

*Abandon GRUB 2 in favor of something else -- This approach is like the preceding one, but instead of setting up a distribution-independent GRUB 2, you set up a distribution-independent non-GRUB boot loader. Under BIOS, possibilities include LILO, SYSLINUX, and GRUB Legacy. Under EFI, options include ELILO, SYSLINUX, rEFInd, and gummiboot/systemd-boot. All of these tools are easier to manually configure than GRUB 2, but most are harder than automatic GRUB 2 configuration (assuming automatic configuration works correctly -- as you've discovered, sometimes it doesn't!).

As with anything computer-related, understanding the tools and processes will help you control them. To that end, you should first figure out whether you're booting in BIOS/CSM/legacy mode or in EFI/UEFI mode. In Linux, this is easily done: Look for a directory called /sys/firmware/efi. If it's present, you've booted in EFI mode; if it's absent, you've probably booted in BIOS mode. If your Windows 8.1 was pre-installed, it almost certainly boots in EFI mode. BIOS-mode and EFI-mode booting are very different, so you should be sure to read up on the appropriate boot mode. (BIOS-mode booting is older, so a lot of older documentation doesn't even mention BIOS-vs.-EFI issues and just assumes BIOS-mode booting. EFI-mode documentation is usually quite explicit that it's about booting in EFI mode.)
For EFI-mode booting, I recommend you read the following references:

*

*Adam Williamson's blog post on how EFI-mode booting. This page provides basic background on how EFI-mode booting works.

*My own page on installing Linux to an EFI-based computer provides distribution-agnostic practical advice.

*My page on EFI boot loaders for Linux describes EFI-mode boot loaders in more detail.

*The Ubuntu community wiki entry on UEFI covers installing Ubuntu on an EFI-based system.

I don't happen to have specific recommendations for further reading on BIOS-mode booting handy.


text:
Q: Do I have to write all the possibilities? I made a memory game
Fishes (it's buttons ) display on the screen and stop,then other fishes ( a wrong fishes ) display on the stage.After a while stops all the scene and player make guess ( click ) right fishes.
For example if player clicked 2 false and 1 true button,or 2 true and 1 false, this results in a loss for the player.And if clicked true 3 fis then this results in a win for the player.
But problem is I have to write code for all possibilities.How can I do as simple.
var clicked1:Boolean = false;
var clicked2:Boolean = false;
var clicked3:Boolean = false;
var clicked4:Boolean = false;
var clicked5:Boolean = false;
var clicked6:Boolean = false;

btn1.addEventListener(MouseEvent.CLICK, fish1);
function fish1(event:MouseEvent):void
{

    clicked1 = true;
    checkButtonsone()
    }

btn2.addEventListener(MouseEvent.CLICK, redButton1a);
function redButton1a(event:MouseEvent):void
{

    clicked2 = true;
    checkButtonsone()
    }

btn3.addEventListener(MouseEvent.CLICK, redButton12);
function redButton12(event:MouseEvent):void
{

    clicked3 = true;
    checkButtonsone()
    }

btn4.addEventListener(MouseEvent.CLICK, redButton22);
function redButton22(event:MouseEvent):void
{

    clicked4 = true;
    checkButtonsone()
    }

btn5.addEventListener(MouseEvent.CLICK, redButton32);
function redButton32(event:MouseEvent):void
{

    clicked5 = true;
    checkButtonsone()
    }

btn6.addEventListener(MouseEvent.CLICK, redButton42);
function redButton42(event:MouseEvent):void
{

    clicked6 = true;
    checkButtonsone()
    }

//Check true and false

function checkButtonsone():void
var correctcombine = false;
var falsecombine1 = false;

{
if(clicked1 && clicked2 && clicked3 )
    {
    correctcombine = true;
    }

    {
    if(falsetiklandi && falsetiklandi && falsetiklandi){
       falsecombine1 = true;
    }

///Go to true or false

if(correctcombine == true)

            {
            gotoAndStop(3)
        }

        if(falsecombine1 == true)
        {
            gotoAndStop(2)
        }
}
}
}

A: You can change your code, so it becomes more easy in this way:
You can call the same event linked to different buttons and then you can evaluate the currentTarget property of event (passed as parameter)
btn1.addEventListener(MouseEvent.CLICK, changeClicked);
btn2.addEventListener(MouseEvent.CLICK, changeClicked);
btn3.addEventListener(MouseEvent.CLICK, changeClicked);
btn4.addEventListener(MouseEvent.CLICK, changeClicked);
btn5.addEventListener(MouseEvent.CLICK, changeClicked);
btn6.addEventListener(MouseEvent.CLICK, changeClicked);

function changeClicked(event:MouseEvent):void {
   switch(event.currentTarget.id) {
       case "btn1": {
           clicked1 = true;
           break;
       }
       case "btn2": {
           clicked2 = true;
           break;
       }
       case "btn3": {
           clicked3 = true;
           break;
       }
       case "btn4": {
           clicked4 = true;
           break;
       }
       case "btn5": {
           clicked5 = true;
           break;
       }
       case "btn6": {
           clicked6 = true;
           break;
       }
   }
    checkButtonsone();
}

You must overwrite your code with mine from your:
btn1.addEventListener(MouseEvent.CLICK, fish1);

until line before
//Check true and false

Further optimization can be instead use 6 different variables, you can use an Array or ArrayCollection or you can define an object where you can encapsulated your different click.
UPDATE
You can define an ActionScript object named (for example) QuizLevel as follow:
[Bindable]
public class QuizLevel {
    private var _levelNo:int;
    private var _value1:Boolean;
    private var _value2:Boolean;
    private var _value3:Boolean;
    private var _value4:Boolean;
    private var _value5:Boolean;
    private var _value6:Boolean;

    // Here you put getter and setter
}

When you start a new quiz level, you define your matrix.
If only three are true you have a QuizLevel object instantiated as follow:
levelNo = 1
value1 = true
value2 = true
value3 = true
value4 = false
value5 = false
value6 = false

In your MXML definition you can write (insteead of button, use check box and one only button to submit your choose)
I've created a s:WindowedApplication (by AIR but is the same for Flash Player and others) and I've defined a preinitialized event in the s:WindowedApplication

        import mx.controls.Alert;
        import mx.events.FlexEvent;
        [Bindable]
        private var quizLevel:QuizLevel = new QuizLevel();

        private var check1:Boolean = false;
        private var check2:Boolean = false;
        private var check3:Boolean = false;
        private var check4:Boolean = false;
        private var check5:Boolean = false;
        private var check6:Boolean = false;

        protected function windowedapplication1_preinitializeHandler(event:FlexEvent):void
        {
            quizLevel = new QuizLevel();
            quizLevel.levelNo = 1;
            quizLevel.value1 = true;
            quizLevel.value2 = true;
            quizLevel.value3 = true;
            quizLevel.value4 = false;
            quizLevel.value5 = false;
            quizLevel.value6 = false;
        }

        protected function changeClicked(event:MouseEvent):void
        {
            var checkBox:CheckBox = event.currentTarget as CheckBox;
            switch(event.currentTarget.id) {
                case "chk1":{
                    check1 = checkBox.selected;
                    break;
                }
                case "chk2":{
                    check2 = checkBox.selected;
                    break;
                }
                case "chk3":{
                    check3 = checkBox.selected;
                    break;
                }
                case "chk4":{
                    check4 = checkBox.selected;
                    break;
                }
                case "chk5":{
                    check5 = checkBox.selected;
                    break;
                }
                case "chk6":{
                    check6 = checkBox.selected;
                    break;
                }
            }

        }

        protected function btnSubmit_clickHandler(event:MouseEvent):void
        {
            var message:String = "";
            if (quizLevel.value1 == check1 &&
                quizLevel.value2 == check2 &&
                quizLevel.value3 == check3 &&
                quizLevel.value4 == check4 &&
                quizLevel.value5 == check5 &&
                quizLevel.value6 == check6) {
                message = "It'OK";
            } else {
                message = "You're wrong";
            }

            Alert.show(message);
        }

    ]]>
</fx:Script>
<s:VGroup width="100%" height="100%">
    <s:CheckBox id="chk1" label="Choose #1" click="changeClicked(event)" />
    <s:CheckBox id="chk2" label="Choose #2" click="changeClicked(event)" />
    <s:CheckBox id="chk3" label="Choose #3" click="changeClicked(event)" />
    <s:CheckBox id="chk4" label="Choose #4" click="changeClicked(event)" />
    <s:CheckBox id="chk5" label="Choose #5" click="changeClicked(event)" />
    <s:CheckBox id="chk6" label="Choose #6" click="changeClicked(event)" />
    <s:Button id="btnSubmit" label="Submit" click="btnSubmit_clickHandler(event)" />
</s:VGroup>

A: var buttons:Array = [fish1,fish2,fish3,fish4,fish5,fish6];
var correct:Array = [true,true,true,false,false,false];
var answers:Array = [false,false,false,false,false,false];
var clicksLeft:int = 3;

for each (var aButton:InteractiveObject in buttons)
{
    aButton.addEventListener(MouseEvemt.CLICK, onButton);
}

function onButton(e:Event):void
{
    var aButton:InteractiveObject = e.currentTarget as InteractiveObject;
    var anIndex:int = buttons.indexOf(aButton);

    // Remove click handler to avoid unnecessary handling.
    aButton.removeEventListener(MouseEvemt.CLICK, onButton);

    // Check answers.
    answers[anIndex] = true;

    clicksLeft--;

    if (clicksLeft > 0)
    {
        return;
    }

    var aWrong:Boolean = false;
    var aComplete:Boolean = true;

    for (var i:int = 0; i < correct.length; i++)
    {
        if (answers[i] != correct[i])
        {
            if (answers[i])
            {
                // answers[i] == true and correct[i] == false
                aWrong = true;
            }
            else
            {
                // answers[i] == false and correct[i] == true
                // That means all correct buttons are not pressed yet.
                aComplete = false;
            }
        }
    }

    if (aWrong)
    {
        // User failed case.
    }
    else if (aComplete)
    {
        // User win case.
    }
}


text:
Q: Is there a reason why Potterverse has no dwarfs? Potter world has dragons, trolls, goblins and elves.
But what's missing is one of the other main races of any good role-playing game swords-and-sorcery world - dwarfs (their niche seemingly being filled by goblins).
Is there any good reason?
I'd strongly prefer a canon or JKR answer, though strong reasoning from source is OK (but not unsourced Wikia entries or random speculations).

A: There are dwarves in Potterverse, they don't seem to be very prevalent though. Professor Lockhart sent them around dressed as Cupid on valentines day, and they tackled Harry to sing to him.
Here is the quote:

Lockhart clapped his hands and through the doors to the entrance hall marched a dozen surlylooking dwarfs. Not just any dwarfs, however. Lockhart had them all wearing golden wings and
  carrying harps.

A: The licensed tie-in book Fantastic Beasts and Where to Find Them: Character Guide specifically refers to the elevator assistant ("Red") as a dwarf.

However, in the final screenplay he's referred to as a goblin.

Newt and Tina reach an elevator. The doors open to reveal Red, a
  goblin bellboy.

A: Harry also mentions "raucous dwarfs" in The Prisoner of Azkaban, just after his first night in the leaky cauldron.

Harry ate breakfast each morning in the Leaky Cauldron, where he liked watching the other guests: funny little witches from the country, up for a day's shopping; venerable-looking wizards arguing over the latest article in Transfiguration Today ; wild-looking warlocks, raucous dwarfs and, once, what looked suspiciously like a hag, who ordered a plate of raw liver from behind a thick woollen balaclava.
HARRY POTTER AND THE PRISONER OF AZKABAN | Chapter 4 | The Leaky Cauldron

It's entirely possible they aren't a race unto themselves, though source seems to imply they are, and seem never to have gotten on the bad side of major Wizarding wars. They may in fact be wizards themselves

A: As firmly stated by J.K.Rowling, she tried to reimagine a universe almost completely based off British folklore. I think what she said on Pottermore about Vampires also apply for Dwarves:

Although vampires exist in the world of Harry Potter [...] they play no meaningful part in the story. The vampire myth is so rich, and has been exploited so many times in literature and on film, that I felt there was little I could add to the tradition. In any case, vampires are a tradition of Eastern Europe, and in general I tried to draw from British mythology and folklore when creating adversaries for Harry. (emphasis mine)

Dwarves are a fairly recent fantasy topos, being essentially re-introduced for the first time since Viking age by Tolkien in his Lord of the Rings saga, and adopted since then by almost every high fantasy writer.
Rowling was different: she tried to invent her own universe drawing autonomously from myth and folklore, not secondarily from other literary sources.
In real world mythology we almost never hear of Dwarves in the fantasy sense, but extremely often we hear of Goblins or Elf-like creatures. Things like the Brazilian Curupira, the German Kobold and the irish Leprechaun seems all to be derived from the same stock of mythological Little People, a myth so ancient that we found it widespread in all human cultures. In this context the Norse Dwarf is just a local representative of this ancestral lore, while "Goblin" is a more generic catch-all term for all these entities (while still retaining a bit of britishness  to it).


text:
Q: Simple local extension model extend problem I wan't to extend local extension model with this existing config.xml:
<config>
    <modules>
        <Smartwave_All>
            <version>1.0.0</version>
        </Smartwave_All>
    </modules>
    <global>
        ...
        <models>
            <core>
                <rewrite>
                    <layout>Smartwave_All_Model_Core_Layout</layout>
                </rewrite>
            </core>
            <all>
                <class>Smartwave_All_Model</class>
            </all>
        </models>
        ...
    </global>
</config>

This is the file which I wan't to extend with my public function (app/code/local/Smartwave/All/Model/Core/Layout.php):
<?php
class Smartwave_All_Model_Core_Layout extends Mage_Core_Model_Layout
{ ...

Ok, now here are my extension files(app/etc/modules/SampleCompany_Test.xml):
<?xml version="1.0"?>
<config>
    <modules>
        <SampleCompany_Test>
            <active>true</active>
            <codePool>local</codePool>
            <depends>
                <Smartwave_All/>
            </depends>
        </SampleCompany_Test>
    </modules>
</config>

And my config.xml (app/code/local/SampleCompany/Test/etc/config.xml):
<?xml version="1.0"?>
<config>
    <modules>
        <SampleCompany_Test>
            <version>0.1</version>
        </SampleCompany_Test>
    </modules>
    <global>
        <models>
            <smartwave_all>
                <rewrite>
                    <core_layout>SampleCompany_Test_Model_Layout</core_layout>
                </rewrite>
            </smartwave_all>
        </models>
    </global>
</config>

And of course my Layout.php (app/code/local/SampleCompany/Test/Model/Layout.php):

class SampleCompany_Test_Model_Layout extends Smartwave_All_Model_Core_Layout
{
    public function myNewFunction()
    {
        ...
    }
}

I can't get this to work. Main problem is because Smartwave All is rewriting Mage/Core/Model/Layout.php core file and it is in conflict with my other extension which do the same (rewrites Layout.php). Now I wan't to extend Smartwave All instead of core Layout.php.
Thanks for any suggestions on this.

A: The problem here is that you're declaring your Smartwave_All models like this:
<all>
     <class>Smartwave_All_Model</class>
</all>

But you're doing the rewrite like this:
<smartwave_all>
   <rewrite>
        <core_layout>SampleCompany_Test_Model_Layout</core_layout>
   </rewrite>
</smartwave_all>

Where it should be:
<all>
   <rewrite>
        <core_layout>SampleCompany_Test_Model_Layout</core_layout>
   </rewrite>
</all>

Or the other way around you can change your models declaration like this:
<smartware_all>
     <class>Smartwave_All_Model</class>
</smartware_all>


text:
Q: Interchange data between TabActivity and its sub-Activities. Possible? I have a list of locations saved in the TabActivity. The TabActivity has 2 sub-activities: a map and a list. So i want to get the location-list to the sub-activities to show them there. I know that i can commit some data with the intent, but i always want to commit the data to the current showing sub-activity if the list changes.
Is there a possiblity to do this?
For further details, please ask me.
Thanks a lot,
joe

A: Yes it is possible, You can have access to the sub activities of TabActivity.
You can get the current active Activity like this way:
say you have a Button(typically other than TabIndicators) somewhere in TabActivity which call doSomeAction() in its onClick() to refresh or change your Sub-Activity contents. You will do it this way:
//this method is in TabActivity
public void doSomeAction(View button)
{
    Activity currentAct = this.getLocalActivityManager().getCurrentActivity();
    int index = getTabHost().getCurrentTab();
    if(index == 0)
    {
        MyListAct listAct = (MyListAct)currentAct; //MyListAct or any other Sub Activity
        listAct.refreshList(); // refreshList() may be a method to refresh Activity
    }
    //else you can check for the other Activity
}

A: I would suggest to create a static global data container and commit your changes into that object (you could clear and setup it with the aid of the main activity life cycle). But make sure you don't leak any heavy resources, especially a context reference.


text:
Q: Rookie coder: main() missing 1 required positional argument: 'self'? This is my first coding class (and first time on the site) and I'm working on a class project. I can't seem to get my code to run correctly. I'm getting 2 errors and I've spent the last 2 hours trying to figure them out. Was wondering if this site would be willing/able to help me out. Code in reply message.
Traceback (most recent call last):
  File "C:\Users\Art\PycharmProjects\pythonProject1\main.py", line 69, in <module>
    class Conversion:
  File "C:\Users\Art\PycharmProjects\pythonProject1\main.py", line 123, in Conversion
    main()
TypeError: main() missing 1 required positional argument: 'self'

class Conversion:
    def say_hello(self):
        print("Hello! I'm a Conversion:", self)

    def main(self):
        task = Conversion()
        task.say_hello()

    if __name__ == "__main__":
        main()

Note: The original code has been removed, but feel free to look at it in the edit history. This is an MRE provided by wjandrea.

A: It looks like you indented the last section wrong and added a self parameter to main for some reason (edit: apparently your IDE did that). Your code should look like this:
class Conversion:
    ...

def main():
    ...

if __name__ == "__main__":
    main()  # on a separate line only for readability

A: Looks like you're thinking like Java, where all functions like main() must be part of a class, but Python doesn't have that restriction, and plain functions are the norm.
In this case, you have code trying to call main(), but the function is defined within the class, so it would be called as self.main() - if that was what you should be doing, which in this case is not.


text:
Q: Apache / Httpd.conf - How do I set an Option that applies to all VirtualHosts? How do I set all docroots to FollowSymLinks? I have a bunch of virtual host entries and don't want to modify each one.
Edit: I added 'Options +FollowSymLinks' in .htaccess and httpd.conf but I still receive 403 (Forbidden) errors :(. I even tried following SymLinks on twitter, but that didn't work either. http://twitter.com/SymLinks

A: If your virtual hosts are all under the same directory then just put it in a <Directory> section outside of all <virtualHost> sections.

A: Try this in the main configuration, you may can do it only for /www or something like that
<Directory />
Options +FollowSymLinks
</Directory>


text:
Q: How to update an array item in React? I am working with a legacy database, where is there no unique index number for each row. Still, I want to have the ability to update items a row. I created a child component, which has a form, to update a row. I am able to identify the index number of the row. And then I move the updated values, and the index number, up to the parent. I'm trying to update the state at the parent level.
My problem is that I am unable to update the state at the parent level.
Here are portions of my code:
//Gifts is a js file with json
import { Gifts } from "./Gifts";

const Main = (props) => {

    const [gifts, setGifts] = useState(Gifts);

    const handleEditSubmit = (values) => {
        console.log(values);
        setGifts(gifts =>
            {const list = gifts.map((gift, index) => {
                if (index === values.index) {
                    delete values.index;
                    return values;
                } else {
                    return gift;
                }
            });
            console.log(list);
            return (
                {list}
            )
            });
        console.log(gifts);
    };
    return(

                <GiftDisplay gifts={gifts}
                    onFormSubmit={handleGiftCreate}
                    onEditSubmit={handleEditSubmit}
                    />

    );
};

I have another function, called handleGiftCreate, which works just fine.
When I check the output of console.log(list), the output is correct. The list has the updated row. But when I check console.log(gifts), I see that the state has not updated.
Initial state of the fourth row is
    {
        "AutoId": 4263,
        "ID": 0,
        "Year": 2021,
        "Date": "2020-12-31T00:00:00.000Z",
        "Transaction": "Gift",
        "AmountOld": 0,
        "Deposit": "PayPal",
        "Amount": 20
    }

Notice that the initial state Amount is 20.
The values - input to the handleEditSubmit - is
{index: 4, AutoId: 2810, ID: 0, Year: 2021, Date: '2020-12-31T00:00:00.000Z', …}
Amount: "2588"
AutoId: 2810
Date: "2020-12-31T00:00:00.000Z"
Deposit: "PayPal"
ID: 0
Transaction: "Gift"
Year: 2021

Notice that the Amount is updated to 2588.
Fourth item of console.log(list) is
Amount: "2588"
AutoId: 2810
Date: "2020-12-31T00:00:00.000Z"
Deposit: "PayPal"
ID: 0
Transaction: "Gift"
Year: 2021

Note that the amount updated properly in list.
The result of console.log(gifts), however, is
Amount: 25
AmountOld: 0
AutoId: 2810
Date: "2020-12-31T00:00:00.000Z"
Deposit: "PayPal"
ID: 0
Transaction: "Gift"
Year: 2021

The state did not update! Please help!

A: So I changed handleEditSubmit to have parenthesis around gifts, as in setGifts((gifts) => {. And it worked. I'm still not quite sure why these parenthesis were needed.
    const handleEditSubmit = (values) => {
        //console.log(values);
        setGifts((gifts)=>
            {const list = gifts.map((gift, index) => {
                if (index === values.index) {
                    delete values.index;
                    return values;
                } else {
                    return gift;
                }
            });
            console.log(list);
            return (
                list
            )
            });
    };


text:
Q: How do I integrate my R graph/file into Java's Swing? I used JSwing to make a pretty looking GUI that lets me enter some information, that when I hit a button, adds that information to a .csv file.
I have an R file that converts said .csv file into a pretty pi chart to look at, with labels and the like. The goal is to get the graph I made in R to show up in my GUI in its own little box or section. I'd like to note that the graph is meant to be dynamic, changing if I add information, so I can't just grab a picture of the graph and save it.
Is there a java library of some kind that lets me literally import my R file into my JSwing app or something similar? Maybe an R interpreter or something where I copy paste my code from R into some weird object's method or something, similar to how some libraries allow you to straight up type an SQL statement and pass it. Anything that actually gets the job done will do.

A: You can do this with FastR. Following example may be exactly what you are looking for: https://github.com/graalvm/examples/tree/master/fastr_javaui


text:
Q: Adding new moodle UI elements according to the onchange event of a select element I'm new in moodle and I always programmed at client-side. I think maybe I'm missing something because of that reason. I need to provide the user with diverse UI elements, according to what he selects in a combo. So I was thinking in writing the lements according to a strategy (design pattern). From an object in the mod_form.php, I was trying to execute something like this:
$this -> _form  -> addElement('select', 'displayStrategy', get_string('displayStrategy', 'xForum'), $displayStrategy, array('onchange' => 'javascript: function loadStrategy(selVal){

$.ajax({
 type: "POST",
 url: "../mod/xForum/action/displayStrategy.php",
 data: { class: selVal }
}).done(function( msg ) {
 console.log("Strategy was executed");
});
}; loadStrategy(this.value);') );

That is being executed and the log is printed in the console, but the content in displayStrategy.php is never executed, a "loading" effect is added to the current view and a last problem is I also need to call a function in the same object that is writting the UI ( the one in mod_form.php that executes all the $this -> _form  -> addElement(...))
Can you give me a hand? How can I execute those methods according to the strategy?
Thanks a lot!

A: My answer is similar to Andres Ramos's answer
First, add a separate js file in your PHP  file to write your JS function.
require_js("./class-section.js");

In this file write below, encodeURI for sending space too.
function fetchSectionsfromclassName() {
        var class= $('#id_user_create_grade').val();
        $('#id_user_create_section').load('getter.php?className=' + encodeURI(class));
}

Now above function requires a getter.php file So create a new gettter.php file where you will fetch section from className. I have a table lo_sections in database that has two column 'class' and 'section'.
In getter.php write this
<?php
require_once("../config.php");
global $DB;

// Get the parameter
$className = $_GET['className'];
if($className) {
    $sections =  $DB->get_records('lo_sections', array('class' => $className));
    foreach ($sections as $key => $value) {
        echo "<option value=".$value->section.">" .$value->section . "</option>";
    }
}

In your PHP file where you want to add two dropdowns write this
here the first dropdown is for class and second for a section like (A, B, C)
$attributes =  array('onchange' => 'javascript:fetchSectionsfromclassName()');
$defaultOption = array("NA" => "NA");
$mform->addElement('select', "user_create_class", 'class', $this->options, $attributes);
$mform->addElement('select', 'user_create_section', 'Section', $defaultOption);

A: I did the following to achieve this:

*

*Put your script on a separate document and call it within your file_form.php:
// Get data dynamically based on the selection from the dropdown
$PAGE->requires->js(new moodle_url('/blocks/mymodulename/js/myscript.js'));

*The file myscript.js has the ".change" functions to identify when the "select" was changed and ".load" to get the data from the file getter.php passing the parameter from the select that changed. Also notice the prefix #id_ before departmentid and studentid, if you inspect the elements, that's how the are actually called.
window.onload = init;

function init() {

    // When a select is changed, look for the students based on the department id
    // and display on the dropdown students select
    $('#id_departmentid').change(function() {
        $('#id_studentid').load('getter.php?departmentid=' + $('#id_departmentid').val());
    });

}

*On the getter.php file, capture the parameter sent through $_GET method, do your query and echo your results. So file getter.php would look like this:
<?php
require_once("../../config.php");
global $DB;

// Get the parameter
$departmentid = optional_param('departmentid',  0,  PARAM_INT);

// If departmentid exists
if($departmentid) {

    // Do your query
    $query = 'SELECT * FROM {table_without_prefix} WHERE departmentid = ' . $departmentid;
    $student_arr = $DB->get_records_sql($query, null,  $limitfrom=0,  $limitnum=0);

    // echo your results, loop the array of objects and echo each one
    echo "<option value='0'>All Students</option>";
    foreach ($student_arr as $student) {
        echo "<option value=".$student->id.">" . $student->fullname . "</option>";
    }

}
?>

*Finally your file_form.php would have the 2 selects, one with the options, and the other with where you need to show the results.
$mform->addElement('select', 'departmentid', "Select Department", $department_array);
$student_array = array("All Students");
$mform->addElement('select', 'studentid', "Select Student", $student_array);

Also, make sure to add the following function so you can properly read the data when using $form->get_data();
function get_data(){
    global $DB;

    $data = parent::get_data();

    if (!empty($data)) {
        $mform =& $this->_form;

        // Add the studentid properly to the $data object.
        if(!empty($mform->_submitValues['studentid'])) {
            $data->studentid = $mform->_submitValues['studentid'];
        }

    }

    return $data;
}

*Here is a quick video of the results: http://screencast.com/t/KDtiWzDN
I hope it helps!


text:
Q: angular2 : Reusing common component twice on the same page How would be able reuse one component twice with different model on the same page, if it would be different slides?
Example:

<component [(model)]="model1"></component>
<component [(model)]="model2"></component>

A: You can use the ngFor.
ts file:
var models = [model1, model2];

Html file:
<div *ngFor="let mod of models">
      <component [(model)]="mod"></component>
   </div>

A: In my solution were problem with not unique ids of radioGroup's elements
if use twice component you have to remember that elements in different radioGroup's  have ti have different id's other way you have deadlock of model on the 2nd, 3rd, etc.


text:
Q: How to output the following equation? What is the code to produce the following?

A: Load amsmath and amssymb packages.
On preamble:
\DeclareMathOperator*{\med}{med}

Then:
\[ \operatorname{MC}(F) = \med_{x_1 \leqslant m_F \leqslant x_2} h(x_1,x_2) \]

MWE
\documentclass{article}
\usepackage{amsmath,amssymb}

\DeclareMathOperator*{\med}{med}

\begin{document}

\[ \operatorname{MC}(F) = \med_{x_1\leqslant m_F \leqslant x_2} h(x_1,x_2) \]

\end{document}

ps. note that the font is not the same. I used the default one.


text:
Q: I would like to calculate the following limit: $\lim_ {n \to \infty} {\left( {n\cdot \sin{\frac{1}{n}}} \right)^{n^2}}$ I would like to calculate the following limit: $$\lim_ {n \to \infty} {\left( {n\cdot \sin{\frac{1}{n}}} \right)^{n^2}}$$
or prove that it does not exist. Now I know the result is $\frac{1}{\sqrt[6]{e}}$, but I am having trouble getting to it. Any ideas would be greatly appreciated.

A: Detailed derivation, using Taylor expansions (you will need $\sin x = x-\frac{x^3}{6} + o(x^3)$ and $\ln(1+x) = x + o(x)$, for $x\to 0$):

*

*Rewrite the quantity in the (more convenient) exponential form:
$$
\left(n\sin \frac{1}{n}\right)^{n^2} = e^{n^2 \ln\left(n\sin \frac{1}{n}\right)}
$$

*Use the Taylor expansion of $\sin$ around $0$ (as $\frac{1}{n}\to 0)$:

 $$\left(n\sin \frac{1}{n}\right)^{n^2} = e^{n^2 \ln\left(n\left(\frac{1}{n}-\frac{1}{6n^3}+o\left(\frac{1}{n^3}\right)\right)\right)}= e^{n^2 \ln\left(1-\frac{1}{6n^2}+o\left(\frac{1}{n^2}\right)\right)}$$

(I am hiding the computations to give only the hint, but place your mouse over the gray area to reveal them)

*

*Use the Taylor expansion of $\ln(1+x)$ around $0$ on the result (as now $\frac{1}{6n^2}\to 0)$:

$$\left(n\sin \frac{1}{n}\right)^{n^2} = e^{n^2 \left(-\frac{1}{6n^2}+o\left(\frac{1}{n^2}\right)\right)}= e^{-\frac{1}{6}+o\left(1\right)} $$

*This gives you the limit:
$$
e^{-\frac{1}{6}+o\left(1\right)} \xrightarrow[n\to\infty]{} e^{-\frac{1}{6}}
$$
where all $o(\cdot)$'s are taken with regard to $n$ going to $\infty$.

A: $$
\left( {n\cdot \sin{\frac{1}{n}}} \right)^{n^2}
= e^{n^2 \log (n\sin(1/n))}
$$
now
$$
\log (\sin(x)/x) = \log\frac{x - x^3/6 + o(x^3)}{x}
= \log(1-x^2/6+o(x^2)) = -x^2/6 + o(x^2)
$$
hence
$$
e^{n^2 \log (n\sin(1/n))} = e^{n^2 (-\frac{1}{6n^2}+o(1/n^2))} = e^{-1/6 + o(1)} \to e^{-1/6}
$$


text:
Q: Java Recursion output May I know why the output is 2 1 0 for this instead of 2
public class recur {
  public static void count(int index) {

    if(index < 2) {
      count(index+1);
    }
    System.out.println(index);
  }

  public static void main(String args[]) {
    recur.count(0);
  }
}

A: Here is how the flow works:

*

*index == 0, calls count(1)

*index == 1, calls count(2)

*index == 2; prints 2 AND this iteration of count() returns to step #2, and continues to the next step in count(), which is System.out.println(i), which prints 1

*same as step #3, return from count and continue with System.out.println(i). At this point, value of i is 0

A: Because your count method calls itself.  When you call count(0) it hits the if block and calls count(1).  That also enters the if block and calls count(2).  2 is not < 2 so it doesn't enter the if block and prints "2", then exits.  At that point you are back where you called count(1), so it exits the if block and prints 1, then exits that method invocation.  Now you are back where you started in the original method call to count(0).  This too leaves the if block and prints 0, then exits and we return to the main method.

A: Whenever index < 2, the count() method recurses on itself, passing count+1 in the recursive call. After the recursive call to count(index+1) returns, execution continues with the call to System.out.println() for the current value of index. This occurs after the recursive call has completed (and has generated its own output).
The key point is that making a recursive call does not stop execution of the remainder of the method; it just defers it until the recursive call returns.


text:
Q: How to enable Code First Entity Framework Migrations for Windows Azure when publishing from source control? I have a project that I am publishing to Azure automatically through source control. I have configured azure to have a proper connection string for the entity framework context. I need to automatically run the migrations against azure database associated with the website.
I know there is an option in the publish dialog, but I need to manually add whatever magic goes into the web.config to tell azure to apply the migrations. What is required to have azure run migrations from source control and if this is not possible is there another way?
I am using EF 6.

A: You need is to configure your context to Migrate on run. You need to do this only once per running process so a static constructor on the context is a pretty decent place to put it
static MyContext()
{
    Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Data.Migrations.Configuration>());
}

Also make sure a connection string is configured in Azure.
If you are using automatic migrations (which is a bad idea in a deployed site) then you will also need those enabled

A: To run such migration scripts I'd recommend using Azure WebJobs:
http://www.hanselman.com/blog/IntroducingWindowsAzureWebJobs.aspx
Azure WebJobs, is a scheduler for running scripts like .bat, .exe, etc. it basically works like cron on UNIX machines but offers intuitive and easy to use UI. So for @Romoku case, he could create console app. That uses EF 6.0 and all that .Net offers to schedule his migrations and track logs of the opearations. It works on the same machine and environment that website is running on.


text:
Q: Observe object change in other ViewController in RxSwift I have a ViewController with a UICollectionView and its elements are bound and cells created via:
 self.viewModel.profileItems.bind(to: self.collectionView.rx.items){ (cv, row, item) ...

I also react to the user taps via:
self.collectionView.rx.modelSelected(ProfileItem.self).subscribe(onNext: { (item) in
        if(/*special item*/) {
            let xVC = self.storyboard?.instantiateViewController(identifier: "x") as! XViewController
            xVC.item = item
            self.navigationController?.pushViewController(xVC, animated: true)
        } else {
            // other generic view controller
        }
    }).disposed(by: bag)

The property in the xViewController for item is of Type ProfileItem?. How can changes to item in the XViewController be bound to the collectionView cell?
Thanks in advance

A: Your XViewController needs an Observable that emits a new item at the appropriate times... Then realize that this observable can affect what profileItems, or at least your view model, emits.
let xResult = self.collectionView.rx.modelSelected(ProfileItem.self)
    .filter { /*special item*/ }
    .flatMapFirst { [unowned self] (specialItem) -> Observable<Item> in
        let xVC = self.storyboard?.instantiateViewController(identifier: "x") as! XViewController
        xVC.item = item
        self.navigationController?.pushViewController(xVC, animated: true)
        return xVC.observableX // this needs to complete at the appropriate time.
    }

self.collectionView.rx.modelSelected(ProfileItem.self)
    .filter { /*not special item*/ }
    .bind(onNext: { [unowned self] item in
        // other generic view controller
    }
    .disposed(by: bag)

Now you need to feed xResult into your view model.


text:
Q: c# List group by name and date calculate sum and average to List> If I have a class:
public class Custom
{
   public Custom()
   {

   }

   public DateTime TargetDate { get; set; }
   public string Name { get; set; }
   public decimal Price { get; set; }
   public decimal Value { get; set; }
}

List<Custom> customItems = new List<Custom>();

the list above can contain any number of items that can be called same or differently. The items can be in any day, even multiple items called the same on one specific date.
How can I use linq to group the list by name and date, and calculate sum for property Price and average for property Value.
So basically, the result should be a List> and properties calculated as such for each grouping name + date.
This is what I tried so far.
var aggdata = customItems.GroupBy(t => new { t.Name, t.TargetDate.Date })
              .ToDictionary(t => t.Key.Name, t => t.Sum(x => x.Price));

But I'm missing the average and date values in the dictionary.
The result should be like this:
"TargetDate", "01.01.2015"
"Name", "SomeName"
"Value", "123"   // Average of values
"Price", "1234"  // Sum of price values

.........

A: You can project to an anonymous object with all of the properties that you need. That dictionary projection will be problematic if you have that name across multiple dates. You'll probably want to project to Lookup instead. That allows you to have multiple keys.
var aggdata = customItems.GroupBy(t => new { t.Name, t.TargetDate.Date })
          .ToLookup(t => t.Key.Name, t => new {
              Date = t.Key.Date,
              Average = t.Average(x => x.Value),
              Sum = t.Sum(x => x.Price)
          });

A: This works for me:
var query =
    from ci in customItems
    group ci by new { ci.TargetDate, ci.Name } into gcis
    select new Custom()
    {
        TargetDate = gcis.Key.TargetDate,
        Name = gcis.Key.Name,
        Price = gcis.Sum(x => x.Price),
        Value = gcis.Average(x => x.Value),
    };

List<Custom> results = query.ToList();

With this sample data:
List<Custom> customItems = new List<Custom>()
{
    new Custom() { TargetDate = DateTime.Now.Date, Name = "Foo", Price = 1m, Value = 2m, },
    new Custom() { TargetDate = DateTime.Now.Date, Name = "Foo", Price = 2m, Value = 4m, },
    new Custom() { TargetDate = DateTime.Now.Date, Name = "Bar", Price = 3m, Value = 8m, },
};

I get these results:


text:
Q: Испанский словарь для Postgres Подскажите, где найти испанский словарь для настройки полнотекстового поиска на Postgre? Если у кого есть актуальная ссылка, поделитесь пожалуйста.

A: Нашел испанский словарь тут - https://github.com/sbosio/rla-es


text:
Q: How to subscribe to public YUM repository in Oracle Linux I would like to subscribe to the following Oracle yum repository so I can install virtual box guest additions packages.
https://yum.oracle.com/repo/OracleLinux/OL7/developer/x86_64/index.html
Where can I find the .repo file URL in order for me to add this to my Oracle Linux subscription list?
Edit: I am already subscribed to the Oracle public yum repo
[root@localhost yum.repos.d]# yum repolist
Loaded plugins: langpacks, ulninfo
repo id               repo name                 status
ol6_UEK_latest/x86_64 Latest Unbreakable Enterprise Kernel for Oracle Lin   820
ol6_latest/x86_64     Oracle Linux 7Server Latest (x86_64)                 11,323
ol7_UEKR5/x86_64      Latest Unbreakable Enterprise Kernel Release 5 for     108
ol7_latest/x86_64     Oracle Linux 7Server Latest (x86_64)                11,688
repolist: 23,939

[root@localhost yum.repos.d]# yum search vbox
Loaded plugins: langpacks, ulninfo
============================== N/S matched: vbox ===============================
isdn4k-utils-vboxgetty.x86_64 : ISDN voice box (getty)

Name and summary matches only, use "search all" for everything.

A: On the same web server there is a page which describe very well the process.

To configure CentOS, Red Hat Enterprise Linux or Scientific Linux with
  Oracle Linux yum server:
To convert your system to Oracle Linux, see these instructions for switching from CentOS. To install individual packages from Oracle
  Linux yum server, begin by importing the Oracle Linux GPG key based on
  these instructions. Then, download and copy the appropriate yum
  configuration file in place, by running the following commands as
  root:
Oracle Linux 7

# cd /etc/yum.repos.d
# wget https://yum.oracle.com/public-yum-ol7.repo
Oracle Linux 7 for ARM (aarch64)

# cd /etc/yum.repos.d
# wget https://yum.oracle.com/aarch64/public-yum-ol7.repo
Oracle Linux 6

# cd /etc/yum.repos.d
# wget https://yum.oracle.com/public-yum-ol6.repo
Oracle Linux 5

# cd /etc/yum.repos.d
# wget https://yum.oracle.com/public-yum-el5.repo
Oracle Linux 4, Update 6 or Newer
# cd /etc/yum.repos.d
# mv Oracle-Base.repo Oracle-Base.repo.disabled
# wget https://yum.oracle.com/public-yum-el4.repo

By default, the latest repository is enabled. If you want to change the default, you can enable an alternative repository by
  editing the yum configuration file.
          Open the yum configuration file in a text editor
          Locate the section in the file for the repository want to enable, e.g. [public_ol6_addons]
          Change enabled=0 to enabled=1

A: I fixed this by adding the entry manually into the yum.conf file.
This Oracle blog helped


text:
Q: STM32F303 code gets stuck in SysTick Exception Handler I am working with a STM32F303 microcontroller with a Nucleo board and my code gets stuck in the SysTick_Handler routine of the startup_stm32f303xe.s file. (My code is based on an example Nucleo project, but rebuilt from scratch for learning purposes).
This post suggests that I need to set the Systick Interrupt to higher priority, which I did and doesn't fix the problem. This post suggests that the Systick Exception occurs when the system timer reaches 0... but I don't think I am using the system timer in my code.
In debug view with some breakpoints, I can see that the code executes to the two GPIO_TogglePin functions, after which it goes into the exception handler.
How can I prevent the program from causing the Systick Exception?
Here is my code:
int main(void) {

    HAL_Init();
    SystemClock_Config();
    LED2_GPIO_CLK_ENABLE();
    __HAL_RCC_GPIOA_CLK_ENABLE();

    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;

    GPIO_InitStruct.Pin = LED2_PIN;
    HAL_GPIO_Init(LED2_GPIO_PORT, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_8;
    HAL_GPIO_Init(LED2_GPIO_PORT, &GPIO_InitStruct);

    HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
    // Also tried HAL_InitTick(0);

    while(1) {

        HAL_GPIO_TogglePin(LED2_GPIO_PORT, LED2_PIN);
        HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_8);

        // Project code
    }
}

void SystemClock_Config(void) {
    RCC_ClkInitTypeDef RCC_ClkInitStruct;
    RCC_OscInitTypeDef RCC_OscInitStruct;

    /* HSI Oscillator already ON after system reset, activate PLL with HSI as source */
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_NONE;
    RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
    RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
    RCC_OscInitStruct.PLL.PREDIV = RCC_PREDIV_DIV2;
    RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16;
    RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
    Error_Handler();
    }

    /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2
 clocks dividers */
    RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK
        | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2);
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
    RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) {
    Error_Handler();
    }

}

A: The ST HAL requires the systick for operation.
It increments the system tick you can use via HAL_GetTick(), it is incremented in the SysTick_Handler() via HAL_IncTick();.
It will be configured by HAL_SYSTICK_Config somewhere in the HAL.
You don't get stuck there. It just gets called every 1 ms.
If you do get stuck in the systick handler, there could be something wrong with the vector table. Eg: the address for SysTick_Handler at the position for something else.
Check the IABR registers when halted.
4.2.6 Interrupt Active Bit Registers.


text:
Q: Nullified terms of this polynomial? This the polynomial:
$6 + 3x - 5y + 7xy -8x^2 + 3y^2 + 4x^2y - 7xy^2 + 9x^3 - 5x^4 + 8y^4x$
I would like to know which terms are there (so that I will form the complete polynomial, with zero as a coefficient for these terms).
For example, in this polynomial:
$-5 + y + 9x + yx^2$
I know that the "complete" polynomial is:
$-5 + y + 9x + 0xy + 0x^2 + yx^2$
Notice how the "complete" polynomial bounds the "hidden" terms by its "max" term.

A: If there are terms $x^i y^j$ where $i \le n_x, j \le n_y$ then there
are a total of $(n_x+1)(n_y+1)$ terms.

A: copper.hat's answer is very reasonable (and in particular matches your example of total degree 3).
But be careful - there are other, very sound systems. The "true" answer is: "it depends". More precisely, which terms are missing depends on the monomial order of your underlying polynomial ring, which for many applications is irrelevant and, thus, unspecified. Also, for some (many) standard monomial orders, it could well be infinitely many terms.
If I want to stress the fact that the polynomial is, say, quadratic in $x$ and linear in $y$, like in your template, I'd use the $i\le n_x, j \le n_y$ rule as proposed, but also order the terms and parenthesise as $$x^2 (a_{21}y+a_{20}) + x (a_{11}y + a_{10}) + a_{00}$$ for clarity and to make sure that my intentions come across.
Otherwise -- and in particular for a rather dense polynomial -- my natural choice would be not to use any terms where the total degree of the monomial exceeds the total degree of the original polynomial, and I'd order the terms by total degree and, in case of ties, lexicographically.
In your example, the total degree is 5, and I would fill in all $x^iy^j$ with $i+j \le 5$, as in copper.hat's comment - that's only 21 instead of 25 terms.


text:
Q: Graph Not Showing Up When Using Google Colabratory I'm trying to plot a shear force graph in Google Colabratory using numpy and matplotlib.pyplot, and it's not showing up in the output section. My code is as follows:
import matplotlib.pyplot as plt
import numpy as np

# Create the graphu
x = np.linspace(0, d_OA + d_AB + d_BC, 1000)
V_xy = np.zeros_like(x)
for idx, loc in enumerate(x):
    if loc < d_OA:
        V_xy[idx] = R_oy
    elif ((loc >= d_OA) and (loc < d_OA + d_AB)):
        V_xy[idx] = R_oy - T_A*np.sin(theta_A)
    elif ((loc >= d_OA + d_AB) and (loc < d_OA + d_AB + d_BC)):
        V_xy[idx] = R_oy - T_A*np.sin(theta_A) - W*np.sin(theta_B)
    else:
        V_xy[idx] = R_oy - T_A*np.sin(theta_A) - W*np.sin(theta_B) + R_cy
    V_xy[0] = 0

# Plot the graph
plt.plot(x, V_xy, '-')
plt.grid(True)
plt.xlabel('x / m')
plt.ylabel('Vxy / N')

If anyone can help out, I'd really appreciate it.

A: I found the issue! I was running without %matplotlib inline right after import matplotlib.pyplot as plt.


text:
Q: Why "Content-Length" header is removed when HTTP response is compressed (GZIP)? Why Content-Length header is removed when HTTP response is compressed using GZIP?
When I set the response headers like:
response.setHeader("Content-Encoding", "gzip");
response.setContentLengthLong(46464);

the Content-Length header is not sent by the GlassFish4 server. My question is - why it is removed?
I'm using java Servlet/3.1.
Response header:
Server: GlassFish Server Open Source Edition  4.1
X-Powered-By: Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition  4.1  Java/Oracle Corporation/1.8)
Date: Sat, 28 Nov 2015 19:36:53 GMT
Accept-Ranges: bytes
Connection: keep-alive
Keep-Alive: timeout=1800
Content-Disposition: inline;filename*=utf-8''big-buck-bunny_traixler.webm
ETag: big-buck-bunny_traixler.webm-2165175-1448346083000
Cache-Control: private,max-age=604800
Last-Modified: Tue, 24 Nov 2015 06:21:23 GMT
Content-Encoding: gzip

response.setContentLengthLong(46464); is set after compressed data written to byte array (thus you know compressed data length), and before compressed data are written to output stream and flushed.
Also - Content-Type header is removed...


text:
Q: Download game with electron / detect game version with electron I have to build a game launcher with electron. I have two questions:

*

*Which way to download file from client (angularjs)? ftp? http?

*how can I detect the game version to update it?

A: With electron you can use all the APIs Node.js have additional to the APIs Chrome have.
So you can Download the game useing ftp or http like you would do in Node.js or use Ajax ($http).
For saveing you can use the normal file system, and for the version you can use the filesystem or localstorage.
Here is a snippet to save the game:
const http = require('http');
const fs   = require('fs');
const app  = require('remote').require('app');

var file = fs.createWriteStream(app.getDataPath() + "externalFiles/game.zip");
var request = http.get("http://dl.example.com/game.zip", response => {
  response.pipe(file);
});

on the server you can simply have a request returning the version or the hash of the latest version, and if that changes it will download the game again.


text:
Q: How to prevent my ID from duplicating I have an edit button which I can click, this will fetch the desired JSON file and shows it back in my CMS side. However when I click on the edit function all works fine and good untill I add a new exercise. when I click on the green + button, instead of incrementing the ID (where it left, for example 2, so the ID of the third one should be 3) it starts with 0. and therefore I have double ID with ID 0 and so on. I have a delete button that should delete the exercise field based on its ID. So when I have 2 exercise fields with both ID 0 it will target the first one instead of targetting the targetted exercise field.
It cannot recognize I already had exercise fields with certain IDs and therefore just starts all over with ID 0.
a picture for you to see:

See how they both have ID 0?
So what I am trying to achieve is the next thing: They should all keep their IDs, and whenever I append a new exercise field it should keep on incrementing instead of having the IDs duplicate.
How my delete button looks like:
function getRemoveBtnExercise(target, i){
  var RemoveExerciseBtn = $('', {
      'class': 'btn btn-danger'
   }).on('click', function(){
   console.log($('.eblock').prop('id'))
        $('#' + target).remove();
   }).html('');

   return RemoveExerciseBtn;
}

how the eBlock looks like:
function getExerciseBlock(i, data){
  var eBlock = $('
',{
    'id': i,
    'class': 'col-md-6 eBlock well'
  });

  data = data || {
    word: '',
    syllables: ['','','','']
  };

  console.log(data.syllables);

  $(eBlock).append(
    getRemoveBtnExercise(i),
    getAudioBtn(i),
    getWordInput(i, data.word),
    getWordPartInput(i, data.syllables)
    );

  return eBlock;
}

In case this is useful code, how the green add button for new exercise fields is:
$(document).ready(function() {
  var id = 0;
  var addOpdracht = $('', {
    'class': 'btn btn-success',
    'id': 'addOpdracht'
  }).on('click', function() {
    $('#my_form').append(getExerciseBlock(id));
    $(".exerciseGetWordInput_" + id).focus().select();
    id++;
    exerciseAudioInput++;
  }).html('');

  $('#my_form').append(addOpdracht);
  $('#my_form').append(getExerciseTitle());
});

A: You could just generate a unique string, for example using Math.random() (which results something like this: 0.1459432599412), and then encode it in base64 to make it legal html id.
function generateId() {
}

Of course it's not guaranteed to be unique, but it's fairly improbable.
PS: If you need further access to those ids, you can encapsulate it in a dedicated object that can generate new ids, and allow you to get old ones.
class Identifiers {
    construct() {
        this.ids = [];
    }
    getNext() {
        const id = this.getRandomId();
        this.ids.push(id);
        return id;
    }
    getRandomId() {
        return btoa(Math.random());
    }
    getId(id) {
        return this.ids.indexOf(id);
    }
}

and you could use it like so
const ids = new Identifiers();
const first = ids.getNext(); // MC41MjQyMTE5MTMyNDIyOTY0
const second = ids.getNext(); // MC41NzI4MTk3MjE2MjU3NjYy
// ...
ids.getId(first); // 0 (because it was first)

A: In the snapshot above, have you added all the three exercises using the javascript code, or the first 2 were pre-added, and you added the third one using the javascript?
Because in that case, it will start from id = 0 only, you must start the id count one plus the number of exercises already available.
UPDATE:
Let's say you keep the exercises in the div tag with class="exercise-box"
And you have, 5 exercises when the page loads,

...

...

...

...

...

Then you can add the following in your javascript code, if you are using jQuery,
var numItems = $('div.exercise-box').length;

And then initialise your var id = numItems + 1;
and keep the remaining code as it is.
Seeing your code, you can use eBlock in place of exercise-box, as you have included that class in the div.

A: Store it in the wrapper and increment it each time perhaps.
Original edit:

$(document).ready(function() {
  // get a reference to the form cache that to avoid multiple DOM hits
  var myform = $('#my_form');
  // this stores the value, I assume none existed before here...
  myform.data("myid",0);
  var addOpdracht = $('', {
    'class': 'btn btn-success',
    'id': 'addOpdracht'
  }).on('click', function() {
    // get last the stored value on the click event
    var id =  $('#my_form').data("myid");
    $('#my_form').append(getExerciseBlock());
    $(".exerciseGetWordInput_" + id).focus().select();
    exerciseAudioInput++;
  }).html('');

  myform.append(addOpdracht);
  myform.append(getExerciseTitle());
});

function getExerciseBlock(data){
  // get the last stored value and add 1 to it
  var myid = $('#my_form').data("myid") + 1;
  // store the new value back in there.
  $('#my_form').data("myid",myid )
  var eBlock = $('
',{
    'id': myid,
    'class': 'col-md-6 eBlock well'
  });

  data = data || {
    word: '',
    syllables: ['','','','']
  };

  console.log(data.syllables);

  $(eBlock).append(
    getRemoveBtnExercise(myid),
    getAudioBtn(myid),
    getWordInput(myid, data.word),
    getWordPartInput(myid, data.syllables)
    );

  return eBlock;
}

I added this CRUD example to get you started, not perfect and not 100% what you have (I had no insight into some things) but functional in adding, removing, editing rows to a list with buttons)

$(document).ready(function() {
  // create row on startup
  let newdata = {
    name: "name-ready",
    title: "Titlenew",
    audio: "Pete Sings the blues"
  };
  addNewRow(newdata);
});
$('#editor')
  .on('click', '.addnew', function(event) {
    let ed = $(event.delegateTarget);
    let newdata = getCurrentValues(ed);
    addNewRow(newdata);
  })
  .on('click', '.removeme', function(event) {
    alert('I would call some remove thing');
  })
  .on('click', '.saveme', function(event) {
    let ed = $(event.delegateTarget);
    ed.find('.showediting').addClass('disabled');
    let id = saveEditRow(ed);
    //  alert('I would save somewhere id:' + id);
  })
  .on('click', '.clearme', function(event) {
    let ed = $(event.delegateTarget);
    let storeFirst = true;
    clearValues(ed, storeFirst);
  })
  .on('click', '.cancelme', function(event) {
    let ed = $(event.delegateTarget);
    restoreValues(ed);
    let row = $('#exercises').find('.row.edit-active');
    row.removeClass('edit-active');
  });

$('#exercises')
  .on('displaydata', '.row.eBlock', function() {
    let data = $(this).data('rowdata');
    $(this).find('.title').html(data.title);
    $(this).find('.name').text(data.name);
    //TODO: $(this).find('.audio').text(data.audio);
  });

function saveEditRow(ed) {
  let data = getCurrentValues(ed);
  restoreValues(ed);
  // console.log(data);
  let row = $('#exercises').find('.row.eBlock.edit-active');
  data.rowid = row.data('rowid');
  row.removeClass('edit-active');
  row.data('rowdata', data);
  row.trigger('displaydata');
  return data.rowid;
}

function getCurrentValues(ed) {
  let currentdata = {
    name: ed.find('.editname').val(),
    title: ed.find('.edittitle').val(),
    audio: ed.find('.editaudio').val()
  };
  return currentdata;
}

function getRowValues(ed, row) {
  let currentdata = row.data('rowdata');
  return currentdata;
}

function storeValues(ed) {
  let en = ed.find('.editname');
  let et = ed.find('.edittitle');
  let ea = ed.find('.editaudio');
  en.data('lastvalue', en.val());
  et.data('lastvalue', et.val());
  ea.data('lastvalue', ea.val());
}

function setValues(ed, data) {
  let en = ed.find('.editname');
  let et = ed.find('.edittitle');
  let ea = ed.find('.editaudio');
  en.val(data.name);
  et.val(data.title);
  ea.val(data.audio);
}

function restoreValues(ed) {
  let en = ed.find('.editname');
  let et = ed.find('.edittitle');
  let ea = ed.find('.editaudio');
  en.val(en.data('lastvalue'));
  et.val(et.data('lastvalue'));
  ea.val(ea.data('lastvalue'));
}

function clearValues(ed, storeFirst = true) {
  if (storeFirst) {
    storeValues(ed);
  }
  let en = ed.find('.editname');
  let et = ed.find('.edittitle');
  let ea = ed.find('.editaudio');
  en.val('');
  et.val('');
  ea.val('');
}

function addNewRow(data) {
  let exercises = $('#exercises');
  let rowId = exercises.data("excersiseid") + 1;
  exercises.data("excersiseid", rowId);
  data.rowid = rowId;
  let igp = $("
");
  let iga = $("
");
  let addColumns = 5;
  let row = newRowGroup(rowId, addColumns);
  row.data("rowdata", data);
  row.find('.eItem').first()
    .removeClass('col').wrap(igp)
    .html(getEditBtnExercise(rowId, data));
  row.find('.eItem').eq(1)
    .html(getExerciseName(rowId, data.name));
  row.find('.eItem').eq(2)
    .html(getExerciseTitle(rowId, data.title));
  row.find('.eItem').eq(3)
    .removeClass('col').wrap(iga)
    .html(getAudioBtn(rowId, data.audio));
  row.find('.eItem').last()
    .removeClass('col').wrap(iga)
    .html(getRemoveBtnExercise(rowId));
  exercises.append(row);
}

function getExerciseTitle(rowId, title) {
  var titleEl = $('', {
    'class': 'title row-title'
  }).on('click', function() {
    var id = $(this).closest('.row.eBlock')
      .data('rowid');
  }).text(title);
  return titleEl;
}

function getExerciseName(rowId, name) {
  var nameEl = $('', {
    'class': 'name row-name'
  }).on('click', function() {
    var id = $(this).closest('.row.eBlock')
      .data('rowid');
  }).text(name);
  return nameEl;
}

function newRowGroup(rowid, addColumnsCount, addClasses = false) {
  let eBlock = $('
', {
    class: 'row eBlock well input-group ',
    id: 'eblock-' + rowid
  }).data("rowgroupid", rowid);
  // create column we will clone and add to row
  let colcls = 'eItem ';
  if (addClasses) {
    colcls = colcls + 'col-md';
  }
  let props = {
    class: colcls,
    text: ""
  };
  let newcol = getCol(props);
  for (var c = 0; c < addColumnsCount; c++) {
    newcol.clone().appendTo(eBlock);
  }
  return eBlock;
}

function getCol(props) {
  let newcol = $('

', {
      class: 'col'
    })
    .addClass(props.class)
    .text(props.text);
  return newcol;
}
$('#addnew').on('click', function() {});

function getEditBtnExercise(rowId, data) {
  var edit = $('<button/>', {
    'class': 'btn btn-success btn-sm editrow',
    'id': 'edit_' + rowId
  });
  edit.on('click', function() {
    let row = $(this).closest('.row.eBlock');
    row.addClass('edit-active');
    let id = $(this).data('rowid');
    let editor = $('#editor');
    storeValues(editor);
    editor.find('.showediting').removeClass('disabled');
    let data = row.data('rowdata');
    setValues(editor, data);
    // console.log(data);

  }).html('');
  edit.data('rowid', rowId);
  return edit;
}

function getRemoveBtnExercise(myid) {
  var removeOpdracht = $('<button/>', {
    'class': 'btn btn-danger btn-sm',
    'id': 'removeOpdracht_' + myid
  }).on('click', function() {
    $(this).closest('.row').remove();
  }).html('');
  return removeOpdracht;
}

function getExerciseBlock(data) {
  var exercises = $('#exercises');
  var myid = exercises.data("excersiseid") + 1;
  $('#exercises').data("myid", myid);
  let eBlock = $('
', {
    'id': "eblock-" + myid,
    'class': 'container eBlock well'
  });

  data = data || {
    word: '',
    syllables: ['', '', '', '']
  };
  eBlock.append(
    getRemoveBtnExercise(myid),
    getAudioBtn(myid),
    getWordInput(myid, data.word),
    getWordPartInput(myid, data.syllables)
  );

  return eBlock;
}

function getAudioBtn(myid, audioname) {
  var audio = $('<button/>', {
    'class': 'btn btn-primary btn-sm audio row-audio',
    'id': 'audio_' + myid
  }).data("audioname", audioname).on('click', function() {
    let audioName = $(this).data("audioname")
    playAudio(audioName);
  }).html('');
  return audio;
}

function playAudio(audio) {
  alert('Requested: ' + audio);
}
#exercises {
  border: solid lime 1px;
}

#exercises .row {
  border: solid white 2px;
}

#exercises .row.edit-active {
  border: solid blue 2px;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet">

      <button class="btn btn-primary btn-sm showediting disabled" type="button"></button>
      <button class="btn btn-success btn-sm addnew" type="button"></button>

    <input type="text" class="form-control editname" placeholder="" aria-label="" aria-describedby="basic-addon1" value="changeme name">
    <input type="text" class="form-control edittitle" placeholder="" aria-label="" aria-describedby="basic-addon1" value="New Title">
    <input type="text" class="form-control editaudio" placeholder="" aria-label="" aria-describedby="basic-addon1" value="Walters Blues">

      <button class="btn btn-warning btn-sm clearme" type="button"></button>
      <button class="btn btn-light btn-sm cancelme" type="button"></button>
      <button class="btn btn-primary btn-sm saveme" type="button"></button>

Note for this function it might be best to change to use the newly create value: so it matches that newly created - note I am not 100% sure what the class .exerciseGetWordInput_ thing really is about
.on('click', function() {
    $('#my_form').append(getExerciseBlock());
    $(".exerciseGetWordInput_" + $('#my_form').data("myid")).focus().select();
    exerciseAudioInput++;
  })


text:
Q: Create 3D kernels with Pytorch: Is there a simple way for large kernels? I would like to test multiple kernels for convolution in 3D space. Here k is a 7x7x7 cross kernel, where the voxel in the middle of the kernel equals 1 and all other voxels in the wings equal -1. This way of assigning k is messy and time-consuming. Any ideas to make it more clear and simple?
tensor([[[[[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  1.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]],

          [[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  1.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]],

          [[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  1.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]],

          [[ 0.,  0.,  0., -1.,  0.,  0.,  0.],
           [ 0.,  0.,  0., -1.,  0.,  0.,  0.],
           [ 0.,  0.,  0., -1.,  0.,  0.,  0.],
           [-1., -1., -1.,  1., -1., -1., -1.],
           [ 0.,  0.,  0., -1.,  0.,  0.,  0.],
           [ 0.,  0.,  0., -1.,  0.,  0.,  0.],
           [ 0.,  0.,  0., -1.,  0.,  0.,  0.]],

          [[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  1.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]],

          [[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  1.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]],

          [[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  1.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]]]]])

A: You can do so with column and row assignments, given kernel_size, in your case 7. Keep in mind that the shape of a nn.Conv3d layer weight is (out_channels=n_filters, in_channels, kernel_size_depth, kernel_size_height, kernel_size_width).
>>> n = kernel_size // 2
>>> k = torch.zeros(1,1,*(kernel_size,)*3) # define zero tensor

>>> k[...,n,n,:] = -1 # middle column at middle depth
>>> k[...,n,:,n] = -1 # middle row at middle depth
>>> k[...,n,n] = 1    # middle point at all depths


text:
Q: mysqli bind_param not returning correct data but the query is correct I have this small piece of code.
echo $token;

$selstmt=$conn->Prepare("SELECT UserID FROM USER WHERE Token LIKE ?");
$selstmt->bind_param('s', $token);
echo $token;
$selstmt->execute();
$selstmt->store_result();
$selstmt->bind_result($userid);
$selstmt->fetch();
echo $userid;
$selstmt->close();

If I remove the bind_param and directly insert the value in the prepare statement, the query works fine. I echo the value of token twice to check if the value is changed but the $token is same and the value is there. So why is this not working?

A: This may work for you, if you include the % signs
$sql  = 'SELECT UserID FROM USER WHERE Token LIKE ?';
$stmt = $conn->prepare($sql);
$stmt->execute(array("%$token%"));
#$result = $stmt->fetch();


text:
Q: New App 404 - Very Basic Setup - URL Exists I have created a new Facebook app.  Whenever I visit the canvas page (https://apps.fac...) I get redirected to the Facebook 4oh4 page.
The canvas URL is set to: https://mgnewmedia.com/brandgame/
Which you will see is as basic as it could possibly be, yet I still get a 404.
I have used the debug tool, which does read it fine.  I have checked the URL on other Internet connections and on other Facebook accounts, all 404.  The app's canvas page is: https://apps.facebook.com/brandgame/
I have deleted the app and re-added it with no luck.  I have also tried putting sample apps in place incase it's 404'ing due to no SDK being present, but that's not the case either.
I have a full, valid SSL certificate in place on the hosting, as you can see.  I run several apps on here already with no such issues.
Full list of settings below:
App ID/API Key:
**
App secret:
**
App Namespace:
brandgame
Canvas Page:
https://apps.facebook.com/brandgame/
Canvas URL:
https://mgnewmedia.com/brandgame/
Secure Canvas URL:
https://mgnewmedia.com/brandgame/
Canvas FBML/iframe:
iframe
Contact Email:
**
Support Email Address:
**
App Description:

A: If you havent changed anything it will just be the delay in the setup as everything seems to be working fine here?
Can provide screenshot's if you want?

A: This was a bug with Facebook, it was listed on their Bug list tracker shortly after I posted this.  It has not yet been resolved, but a work around has been posted.  Essentially you add the app, rename it, then rename it back, waiting 20mins or so between each step.
It's worth noting that this doesn't affect everyone making apps, only certain accounts.  I assume this is down to data centre allocation, or something such like.


text:
Q: Proof of the fact that $\ln(a) = f '(0)$ for $f(x) = a^x$? Looking over notes from class today and wanted to know if there is any type of proof for the fact that $\ln(a) = \lim_{h\to0}(a^h-1)/h$, which is just $f '(0)$ for any function of the form $f(x) = a^x$. I see that it simply is the case but where's the "mathy" proof of it? Thanks.

A: Hint:
Use the definition
$$f'(0)=\lim_{h\to 0}\frac{f(0+h)-f(0)}{h}
\\=\lim_{h\to 0}\frac{a^h-1}{h}\\=\lim_{h\to 0}\frac{e^{\ln a^h}-1}{h}\\=\lim_{h\to 0}\frac{e^{h\ln a}-1}{h}\\=\lim_{h\to 0}\frac{1+h\ln a+\cdots-1}{h}=\ln a$$

A: First use the commonly known limit "$\lim \frac{e^h-1}{h}$", that is:
$$1 = \lim_{x \rightarrow 0} \frac{e^x - 1}{x}
\\ = \lim_{\log(a)x \rightarrow 0} \frac{e^{\log(a)\cdot x} - 1}{\log(a)\cdot x}
\\ = \lim_{x \rightarrow 0} 1/\log(a)\cdot \frac{a^x - 1}{x}$$
and so $f'(0) = \log(a)$ by the definition of the derivative.

A: Look at it this way: $$f(x)=a^x \implies f'(x)=a^x \ln a$$ this follows from the fact that of $y=a^x$ then $\ln y =x \ln a$ and so $1/y \cdot y' = \ln a \implies y'=a^x \ln a$. So we proved the derivative in other words (using the definition of $e$ as the exponential function base which has a derivative equal to the function itself).
There is another way to go about finding this derivative, which is to use the definition of the derivative: $$f(x)=a^x \implies f'(x)= \lim_{h\rightarrow 0} \frac{a^{x+h}-a^x}{h}=\lim_{h \rightarrow 0} \frac{a^x(a^h-1)}{h}=a^x \cdot \lim_{h \rightarrow 0} \frac{a^h-1}{h}$$ Now set the two derivatives equal to one another: $$a^x \ln a = a^x \cdot \lim_{h \rightarrow 0} \frac{a^h-1}{h} \implies \ln a= \lim_{h \rightarrow 0} \frac{a^h-1}{h}$$


text:
Q: Store CSPC and UPC Codes in Rails What the best way to store CSPC and UPC codes are in Rails? I used integers with SQLite, but had overflow issues when moving to production. I've since switch to strings, but am not sure if a better generic datatype (needs to support SQLite, MySQL and PostgreSQL).
Thanks.

A: Strings are a solid choice when you need generic like in your case. You should be fine.

A: In the project I am currently working on, we do not use rails, we use .NET and SQL server, we have it stored in two formats, nvarchar (or varchar in your case) and a bigint.


text:
Q: Background image and div positioning? I have the following structure:

… etc

I'm trying to display a background image that will show the full height of the image, but not force the page to scroll as a result of it but that will scroll with the page content.
I've placed a #bgimage div after the opening tag of the #container div and I've tried the following CSS:

*

*position:fixed + height:100% - displays the full height of the image but doesn't scroll with the page content

*position:absolute + height:100% - scrolls with the page but cuts off the image where the page content ends

*position: absolute + height:1000px - displays the full image but forces the page to scroll
Any idea?
Thanks

A: Set the background on the body itself. CSS3 allows you to set multiple backgrounds in case you already got one. Although this doesn't work in IE8 and before.
[edit]
Since that doesn't work in your page, try to make the bgimage div a container for your page content without specifying an exact height. Set the min-height to 100%.
That way, it should size to the page content. It will always reach to the bottom of the window, and it won't force scrollbars when they're not needed. The min-height causes the div to fill the window in case the content is smaller than the window height.

A: Use background-attachment: fixed; it will scroll with the page.


text:
Q: Calculating the average of value in group of cells I have an Excel sheet in this format.

You can see that there are groups of dates, and there is a column Present with boolean values. I want to find the percentage of Yes in the Present field. If this was SQL, I would have done easily. I have a few questions in Excel.

*

*Is this feasible?

*What kind of formula should I use?

*Should I use macros for these or just formulae would do?

*Will I be able to fill the column automatically, without I merging cells each and every time manually?

I had played around with COUNTIF and SUMIF, but didn't work for me. Please help. Thanks in advance.

A: You will need to use one COUNTIF and one COUNTIFS
In the first cell containing the percentage for instance, you could use:
=COUNTIFS(A:A,A2,B:B,"YES")/COUNTIF(A:A,A2)

Assuming that 1-May-13 is in A2 and Yes is in B2.
COUNTIFS uses multiple criteria. Here, it counts only if the date in A1 is 1-May-13 and the value in B2 is Yes.
The COUNTIF just counts the number of times the date appears.
You can then format the column as a percentage.
It will be difficult I think with the merging and unmerging cells though.