text:
Q: Wrong alignment of grids in stackpanel I do not understand why the alignment of my (generated) XAML code is wrong.
XAML:
<ScrollViewer>
        <StackPanel Orientation="Vertical">

            <HeaderedContentControl Header="innerer Ex-Schutz Anforderung">
                <Grid HorizontalAlignment="Stretch">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="5"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="5"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="5"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="5"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="5"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*"/>
                        <RowDefinition Height="*"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>

                    <Grid HorizontalAlignment="Stretch" Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="3">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="48"/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>

                        <Rectangle Grid.Column="0" Margin="0,0,2,0" Stretch="Fill" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" StrokeThickness="0" Stroke="Transparent" Fill ="#FFFFFF88"/>
                        <TextBlock Margin="5" Grid.Column="0" Text="IX02"/>
                        <TextBlock Grid.Column="1" VerticalAlignment="Center" Margin="0,0,5,0" Text="Ex-Zone"/>
                        <mvvmui:VmpEditor Grid.Column="2" DataContext="{Binding Data[This][]}" ShowCaption="False" WrapReadOnlyText="True"/>
                    </Grid>

                    <Grid HorizontalAlignment="Stretch" Grid.Row="0" Grid.Column="5" Grid.ColumnSpan="3">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="48"/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>

                        <Rectangle Grid.Column="0" Margin="0,0,2,0" Stretch="Fill" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" StrokeThickness="0" Stroke="Transparent" Fill ="#FFFFFF88"/>
                        <TextBlock Margin="5" Grid.Column="0" Text="IX04"/>
                        <TextBlock Grid.Column="1" VerticalAlignment="Center" Margin="0,0,5,0" Text="Ex-Gruppe"/>
                        <mvvmui:VmpEditor Grid.Column="2" DataContext="{Binding Data[This][0173-1---ADVANCED_1_1#01-ADN507#007/0173-1#01-ADR534#007/0173-1#02-AAR158#007/0173-1#02-AAR159#005/0173-1#02-AAQ920#005/0173-1#02-AAO370#004]}" ShowCaption="False" WrapReadOnlyText="True"/>
                    </Grid>

                    <Grid HorizontalAlignment="Stretch" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="3">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="48"/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>

                        <Rectangle Grid.Column="0" Margin="0,0,2,0" Stretch="Fill" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" StrokeThickness="0" Stroke="Transparent" Fill ="#FFFFFF88"/>
                        <TextBlock Margin="5" Grid.Column="0" Text="IX06"/>
                        <TextBlock Grid.Column="1" VerticalAlignment="Center" Margin="0,0,5,0" Text="Temp.klasse"/>
                        <mvvmui:VmpEditor Grid.Column="2" DataContext="{Binding Data[This][0173-1---ADVANCED_1_1#01-ADN507#007/0173-1#01-ADR534#007/0173-1#02-AAR158#007/0173-1#02-AAR159#005/0173-1#02-AAQ920#005/0173-1#02-AAO371#004]}" ShowCaption="False" WrapReadOnlyText="True"/>
                    </Grid>
                </Grid>
            </HeaderedContentControl>

            <HeaderedContentControl Header="äußerer Ex-Schutz Anforderung">
                <Grid HorizontalAlignment="Stretch">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="5"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="5"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="5"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="5"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="5"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*"/>
                        <RowDefinition Height="*"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>

                    <Grid HorizontalAlignment="Stretch" Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="3">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="48"/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>

                        <Rectangle Grid.Column="0" Margin="0,0,2,0" Stretch="Fill" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" StrokeThickness="0" Stroke="Transparent" Fill ="#FFFFFF88"/>
                        <TextBlock Margin="5" Grid.Column="0" Text="AX02"/>
                        <TextBlock Grid.Column="1" VerticalAlignment="Center" Margin="0,0,5,0" Text="Ex-Zone Umgebung"/>
                        <mvvmui:VmpEditor Grid.Column="2" DataContext="{Binding Data[CboProcessConnection].PropertyList[EPROutsideZone]}" ShowCaption="False" WrapReadOnlyText="True"/>
                    </Grid>

                    <Grid HorizontalAlignment="Stretch" Grid.Row="0" Grid.Column="5" Grid.ColumnSpan="3">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="48"/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>

                        <Rectangle Grid.Column="0" Margin="0,0,2,0" Stretch="Fill" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" StrokeThickness="0" Stroke="Transparent" Fill ="#FFFFFF88"/>
                        <TextBlock Margin="5" Grid.Column="0" Text="AX04"/>
                        <TextBlock Grid.Column="1" VerticalAlignment="Center" Margin="0,0,5,0" Text="Ex-Gruppe Umgebung"/>
                        <mvvmui:VmpEditor Grid.Column="2" DataContext="{Binding Data[CboProcessConnection].PropertyList[EPROutsideGroup]}" ShowCaption="False" WrapReadOnlyText="True"/>
                    </Grid>

                    <Grid HorizontalAlignment="Stretch" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="3">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="48"/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>

                        <Rectangle Grid.Column="0" Margin="0,0,2,0" Stretch="Fill" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" StrokeThickness="0" Stroke="Transparent" Fill ="#FFFFFF88"/>
                        <TextBlock Margin="5" Grid.Column="0" Text="AX06"/>
                        <TextBlock Grid.Column="1" VerticalAlignment="Center" Margin="0,0,5,0" Text="Temperaturklasse Umgebung"/>
                        <mvvmui:VmpEditor Grid.Column="2" DataContext="{Binding Data[CboProcessConnection].PropertyList[EPROutsideTempClass]}" ShowCaption="False" WrapReadOnlyText="True"/>
                    </Grid>
                </Grid>
            </HeaderedContentControl>
        </StackPanel>
    </ScrollViewer>

Here you can the the result:

Its not easy to see but the two yellow boxes on the right side should be exactly under each other. But the lower is a few pixels to the right.
Does anyone understand that?
Interestingly, when you enter a fixed width to the StackPanel (say, 1500), it works. But I do not want a fixed width.

A: You've got auto-width columns in separate grids. If you want columns in two different grids to be the same width, you have three options:

*

*Fixed size. That's lame and you don't want it.

*Put everything in one big grid.

*Put Grid.IsSharedSizeScope="True" on some common parent element of both grids, and add SharedSizeGroup="SomeArbitaryName" on the autosized columns that are sizing slightly differently in the two different child grids, and which are positioning the third columns differently as a result (that's the first column in each). This is the best solution in your case, I believe.


text:
Q: Trying to grok Linux quotas, where is the data stored? So all the tutorials and documentation for the Linux quota system has left me confused. For each filesystem with quotas enabled/on where is the actual quota information stored? Is it filesystem metadata or is it in a file?
Say user foo creates a new file on /home. How does the kernel determine whether user foo is below their hard limit? Does the kernel have to tally up quota information on that filesystem each time or is it in the superblock or somewhere else?
As far as I understand, the kernel consults the aquota.user file for the actual rules, but where is the current quota usage data stored? Can this be viewed with any tools outside repquota and the like? TIA!!
Update:
Thanks for the help. I had already read that mini-HOWTO. I am pretty clear on the usage of the user space tools. What I was unclear on is whether the usage data was ALSO in the file that stored per-user limits and you answered this with a yes.
From what I can tell, rc.sysinit runs quotacheck and quotaon on startup. The quotacheck program analyzes the filesystem, updates the aquota.* files. It then makes use of quota.h and the quotactl() syscall to inform the kernel of quota info.
From this point forward the kernel hashes that information and increments/decrements quota stats as changes occur. Upon shutdown, the init.d/halt script runs the quotaoff command RIGHT before the filesystems are unmounted. The quotaoff command does not appear to update the aquota.* files with the information the kernel has in memory. I say this because the {a,c,m}times for the aquota.user file are only updated upon a reboot of the system or by manual running the quotacheck command. It appears - as far as I can tell - that the kernel just drops it's up-to-date usage data on the floor at shutdown. This information is never used to update the aquota.* files. They are updated during startup by quotacheck(rc.sysinit). Seems silly to me since that updated info had already been collected by the kernel. So...in conclusion I am still not entirely clear on the methods. ;)

A:
For each filesystem with quotas enabled/on where is the actual quota information stored?

See e.g. the quotaon manpage. There will be files named .quota* in the filesystem root directory, which contain the necessary information (.quota.user,.quota.group, .quota.ops.user, .quota.ops.group).

Say user foo creates a new file on
  /home. How does the kernel determine
  whether user foo is below their hard
  limit? Does the kernel have to tally
  up quota information on that
  filesystem each time or is it in the
  superblock or somewhere else?

No, the kernel continually tracks fs usage, so it does not need to recalculate that on each allocation (which would be prohibitively expensive). It will do the calculation once when quotas are enabled, and then update that. The initial calculation is performed by quotacheck.

As far as I understand, the kernel
  consults the aquota.user file for the
  actual rules, but where is the current
  quota usage data stored? Can this be
  viewed with any tools outside repquota
  and the like? TIA!!

Quota information is stored in .quota* (see above). I'm not aware of any tools to generate quota usage reports, apart from repquota. But you should be able to generate most reports using/scripting repquota. Or you'll have to hack the source...
BTW:
The Quota mini-HOWTO give a good overview over the Linux quota system. It's a bit dated, but the fundamentals have not changed much.

A: From reading through your update it seems that you're wondering about why all the quota info the kernel has would be tossed when the machine is shut down instead of written to the aquota.* files.
Well, the kernel doesn't update the file on the fly since this would be expensive in terms of time.  Basically once quotas are enabled the kernel tracks usage in case a soft/hard limit is reached and it has to do something, this means that it's tracking this every time it has to allocate any fs blocks for any user/group on the system.  If it then had to update the aquota.* files while attempting to allocate fs blocks you could see where this would end up causing problems on even moderately busy systems, and it's not needed since the kernel is watching this for you and will log any transgressions for you, so you know to come run quotacheck.  Even the quota calculation can cause issues, which is why you have the tunable sysctl - dquot-max - and the reporting sysctl - dquot-nr - more info can be seen here:
http://www.mjmwired.net/kernel/Documentation/sysctl/fs.txt
As for the placement of quotacheck during the init process and not the halt process, it's all about time and how you think of things.  Usually when you halt a server you want it to go down, fast.  Not spend a bunch of time tabulating quotas, we're a lot more accustomed to init's taking longer.  Also, think of this process as init setting up the initial quota counts when the system started, rather than cleaning up as it's shutting down.  What if the FS's were mounted on another system without quotas enabled then restarted normally, you'd want to know where you're starting from everytime, and since you're going to init after every halt that's where it's setup.
Hope that helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Install older versions of tensorflow I am trying to install tensorflow 1.3.0 with the following setup:
python 3.6.3
pip 9.0.1
Windows 10 on x64

I have tried running
pip install https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow_jni-cpu-windows-x86_64-1.3.0-rc2.zip

but I get that
Command "python setup.py egg_info" failed with error code 1 in C:\Users\__\AppData\Local\Temp\pip-0dabbj1v-build\

and if I try
pip install tensorflow-1.3.0

I get
  Could not find a version that satisfies the requirement tensorflow-1.3.0 (from versions: )
No matching distribution found for tensorflow-1.3.0

Any idea how I might get this to work? Any idea/tip would be greatly appreciated!

A: Please Use the following command
pip install tensorflow==<version>

In your case for getting tensorflow 1.3.0, use it likewise
pip install tensorflow==1.3.0

A: In https://pypi.python.org/pypi/tensorflow/1.3.0, download .whl of the version you need and install it using pip.


text:
Q: Squeel iterating through an array with OR in Where block I have the following query in Squeel:
languages = where{ (name == 'English') |
 (name == 'Spanish')  |
 (name == 'German')  |
 (name == 'French')  |
 ...
}

Which works fine but I was wodering if there was a way to iterate through an array with those values to make it easier to add and remove languages. Say I created and array:
languages_array = %w[ English Spanish French ... ]

Is there any way to iterate with Squeel in a Where block?
I've tried everything I can think of without success.
Thanks.

A: I think this should work
where{name.in(languages_array)}

A: You don't need squeel for this type of query: where(name: languages_array) will do what you need - it'll translate to
WHERE name IN ('English', 'Spanish', 'French', ...)

which is probably what you need.


text:
Q: calculating probability of 3 successful rolls of 4+ on six 6 sided dice I am trying to calculate the probability of rolling a 4 or more on six 6 sided dice and have managed to get the probability of getting 1 successful 4+ via the equation:
$\frac{6^6-3^6}{6^6}=0.9844$
the problem I'm having is calculating the probability for 2 or 3 successful 4+ results.
can any one help me out?

A: The probability of exactly two 4+'s is $p_2 = \binom{6}{2}\cdot (1/2)^6$, and the probability of exactly three 4+'s is $p_3 = \binom{6}{3}\cdot (1/2)^6$. If you want there to be at least two 4+'s, for instance, the probability is $p_2+p_3+p_4+p_5+p_6$.

A: Let $S(i)$ be the rolls where die $i$ has a $4+$. Then
$$
\begin{align}
N(j)
&=\sum_{|A|=j}\left|\,\bigcap_{i\in A} S(i)\,\right|\\
&=\binom{6}{j}2^{-j}
\end{align}
$$
Then, according to the Generalized Inclusion-Exclusion Principle, we get the number of rolls in exactly $k$ of the $S(i)$ to be
$$
\begin{align}
\sum_{j=0}^6(-1)^{j-k}\binom{j}{k}N(j)
&=\sum_{j=k}^6(-1)^{j-k}\binom{j}{k}\binom{6}{j}2^{-j}\\
&=\sum_{j=k}^6(-1)^{j-k}\binom{6}{k}2^{-k}\binom{6-k}{j-k}2^{k-j}\\
&=\frac1{64}\binom{6}{k}
\end{align}
$$
which upon reflection is obvious without inclusion-exclusion. Inclusion-Exclusion would be more useful in the case of rolling $5+$ or $2+$.


text:
Q: UWP: BackgroundTask open App Mainpage Is it possible to open my app by my own backgroundtask?
when i have a backgroudtask in windows universal platform, can i start or open my app.mainpage from there?
my backgroundtask checks periodicaly the clipboard and if it gets an hit, then it should open my app.
does this work with uwp or is uwp again a no-go software ?
any soltutions or ideas therefore?

A: You can do that by a toast. Here is an example.
   var content =
        $@"
            <toast activationType='foreground' launch='args'>
                <visual>
                    <binding template='ToastGeneric'>
                        <text>Open app</text>
                        <text>Your clipboard is ready.Open app</text>
                    </binding>
                </visual>
                <actions>

                    <action content='ok' activationType='foreground' arguments='check'/>

                  <action activationType='system' arguments='dismiss' content='cancel' />

                </actions>
            </toast>";

        Windows.Data.Xml.Dom.XmlDocument toastDOM = new Windows.Data.Xml.Dom.XmlDocument();
        toastDOM.LoadXml(content);
        ToastNotification toast = new ToastNotification(toastDOM);
        var notifier = ToastNotificationManager.CreateToastNotifier();
        notifier.Show(toast);

And then if user press the ok button you must go in App.xaml.cs and handle that
 protected override void OnActivated(IActivatedEventArgs args)
    {
        if (args.Kind == ActivationKind.ToastNotification)
        {
            var toastArgs = args as ToastNotificationActivatedEventArgs;
            var arguments = toastArgs.Argument;

            if (arguments == "check")
            {
                Frame rootFrame = Window.Current.Content as Frame;
                if (rootFrame == null)
                {
                    rootFrame = new Frame();
                    Window.Current.Content = rootFrame;
                }
                rootFrame.Navigate(typeof(YOURPAGEHERE));
                Window.Current.Activate();
            }
        }
    }


text:
Q: How do I see previously installed versions of Flutter? I updated flutter, and it screwed everything up. There's lots of info out there on how to downgrade, but I'm not sure what I need to downgrade to.

A: in your pubspec.yaml file, search for below line. your number might be different.
environment:
  sdk: ">=2.16.0 <3.0.0"

the first number is your Dart version when you created your project if you didn't change it. for exp my dart version is 2.16.0.
Go to Flutter release notes page. go to announcement of every flutter version and see which flutter version use your Dart version.


text:
Q: Change grid layout depending on number of elements I have a wrapper that can have 1-5 elements.

I'd like to change the layout in which they're displayed depending on the number of them:

*

*1 element: 1x1, 33.3% width

*

*2 elements: 2x1, 33.3% width

*

*3 elements: 3x1, 33.3% width

*

*4 elements: 2x2, 50% width

*

*5 elements: 3x2, 33.3% width

How can I do this without JavaScript?
This is the Codepen for reference.

body {
  padding: 20px;
}

.wrapper {
  width: 500px;
  padding: 5px 10px;
  margin: 10px 0;
  border: 2px dashed #5f5f5f;
  display: flex;
  flex-wrap: wrap;
}

.element {
  font-family: Helvetica, sans-serif;
  background-color: #ededed;
  flex: 33.3%;
  max-width: 33.3%;
  margin: 10px 0;
}

.wrapper.with-4-elements .element {
  flex: 50%;
  max-width: 50%;
}

.wrapper-with-5-elements .element:nth(4),
.wrapper-with-5-elements .element:nth(5) {
  flex: 50%;
  max-width: 50%;
}

Element 1

Element 1

Element 2

Element 1

Element 2

Element 3

Element 1

Element 2

Element 3

Element 4

Element 1

Element 2

Element 3

Element 4

Element 5

A: You can do it like below using CSS grid:

.wrapper {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 5px;
  border: 1px solid;
  padding: 10px;
  margin: 10px;
}
.element {
  grid-column: span 2;
  height: 20px;
  background: red;
}
/* the case with 4 elements */
.element:first-child:nth-last-child(4),
.element:first-child:nth-last-child(4) ~ *{
  grid-column: span 3;
}

And with flexbox:

.wrapper {
  display: flex;
  flex-wrap: wrap;
  border: 1px solid;
  gap: 5px;
  padding: 10px;
  margin: 10px;
}
.element {
  flex: 0 0 calc((100% - 10px)/3); /* 10px = 2 * gap */
  height: 20px;
  background: red;
}
/* the case with 4 elements */
.element:first-child:nth-last-child(4),
.element:first-child:nth-last-child(4) ~ *{
  flex: 0 0 calc((100% - 5px)/2);
}


text:
Q: How to allow for a user to enable push notifications after blocking? I site I am working on asks the user (using firebase, js, and native chrome) if it is ok to send them push notifications. They may say no and click the little block button. Fine... that is great.
Is there a way I can provide them an easy button to be asked the same question again if they change their mind? Currently, Chrome asks if they want to allow or block. If the user indicates they want to block, but can a create a "Send me push notifications!" that re-requests this permission?

A: Answer: No.
If user block permission via native request you can't do anything with that. But you can show them instruction how to unblock push by open settings. But you need to offer something very very valuable to a user. And expect low conversion.
The best way to subscribe users is to give them value before subscribe and require additional action. Example: show them HTML dialog with info about subscription and HTML buttons "Yes" and "No". When a user clicks "Yes" — show him a real request. If a user clicks "No" just close the dialog.
Later you can give more value to users who clicked "No".
You can find best practices here


text:
Q: Screen Capture using Java Robot saves black image instead of original image I'm using Java ROBOT to make a screen capture. But it is saving the image as a plain black screen. I don't understand what's wrong with the code i'm using. Can anyone knows the issue i'm facing here
here is the code -
// generate the screen shot of the exception
     File tempFile = null;
            try {
                BufferedImage img = getScreenAsBufferedImage();
                tempFile = createTempFile();
                ImageIO.write(img, "jpg", tempFile);
                template.setScreenshot(tempFile);
            } catch (Exception e1) {
                // error creating screenshot
                log.error("Error creating image screenshot ", e1);
            }

private BufferedImage getScreenAsBufferedImage() {
        BufferedImage img = null;
        try {
            Robot r;
            r = new Robot();
            Toolkit t = Toolkit.getDefaultToolkit();
            Rectangle rect = new Rectangle(t.getScreenSize());
            img = r.createScreenCapture(rect);
        } catch (AWTException e) {
            e.printStackTrace();
        }
        return img;
    }

private static File createTempFile() {
        try {

            // create a temp file
            File temp = File.createTempFile("temp-file-name", ".jpg");
//            log.info("Temp file : " + temp.getAbsolutePath());
            return temp;

        } catch (IOException e) {

            e.printStackTrace();

        }

        return null;
    }

HybridTemplate.java
 public File getScreenshot() {
        return screenshot;
    }

    public void setScreenshot(File screenshot) {
        this.screenshot = screenshot;
    }

A: Try this code it's work fine after remove one line.. check in below commented line
File tempFile = null;
        try {
            BufferedImage img = getScreenAsBufferedImage();
            tempFile = createTempFile();
            ImageIO.write(img, "jpg", tempFile);
            //template.setScreenshot(tempFile); //problem in this line
        } catch (Exception e1) {
            // error creating screenshot
            //log.error("Error creating image screenshot ", e1);
        }
private BufferedImage getScreenAsBufferedImage() {
    BufferedImage img = null;
    try {
        Robot r;
        r = new Robot();
        Toolkit     t = Toolkit.getDefaultToolkit();
        Rectangle rect = new Rectangle(t.getScreenSize());
        img = r.createScreenCapture(rect);
    } catch (AWTException e) {
        e.printStackTrace();
    }
    return img;
}
private static File createTempFile() {
    try {
        // create a temp file
        File temp = File.createTempFile("temp-file-name", ".jpg");
        System.out.println(temp.getAbsolutePath());
       //log.info("Temp file : " + temp.getAbsolutePath());
        return temp;
    } catch (IOException e) {

        e.printStackTrace();
    }
    return null;
}
}

A: Selenium Robot with Chrome Driver
public static void main(String[] args) throws IOException, AWTException {

        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("http://searchsoa.techtarget.com/definition/stickiness");
//http://www.theedublogger.com/2012/11/08/how-to-add-a-link-to-a-specific-location-in-a-post-or-page/
        driver.manage().window().maximize();
        JavascriptExecutor jse = (JavascriptExecutor)driver;
        Long clent_height = (Long) jse.executeScript("return window.document.documentElement.clientHeight");

        // AWT Toolkit For Window
        java.awt.Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle winSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
        int taskBarHeight = screenSize.height - winSize.height;
        System.out.println("Screen : "+screenSize.height +","+screenSize.width);
        int yaxis =   (int) (screenSize.getHeight() - (taskBarHeight + clent_height.intValue()));
        Robot robot = new Robot();
            int x = 0, y = yaxis;
            int width = (int) screenSize.getWidth(), height = (int) screenSize.getHeight();
         Rectangle area = new Rectangle(x, y, width, height-taskBarHeight-y);
         BufferedImage bufferedImage = robot.createScreenCapture(area);
         ImageIO.write(bufferedImage, "jpg", new File("D:\\Yash\\Robot.jpg"));

         driver.quit();

    }


text:
Q: Dynamic Method with Fragments I am creating an application and use a DrawerActivity.
This DrawerActivity has the onNavigationItemSelected() method.
The question I have is, can I create a method like
public void select(Fragment fragment) {
    FragmentTransaction transaction = menuActivity.getSupportFragmentManager().beginTransaction();

    transaction.replace(R.id.fragment_container, fragment);
    transaction.addToBackStack(null);

    transaction.commit();
}

Therefore I would only pass the desired Fragment. In the past I used to have houndreds of lines of code and want to change this now. It is a flexible method I wish to create if you want so. The example above does not work because it expects a clear object, but I hope you get the point of my question.
Thanks for your attention :)

A: You will always need to map every menu item id to a specific fragment.
In order to avoid long switch case statements you could use a design pattern like Abstract Factory Pattern with reflection.
Some sample code
public class FragmentFactory {
    private Map<Integer, Class<? extends Fragment>> menuItemFragments;

    public FragmentFactory() {
        menuItemFragments = new HashMap<>();
        menuItemFragments.put(R.id.fragment_main, MainFragment.class);
        menuItemFragments.put(R.id.fragment_about, AboutFragment.class);
        menuItemFragments.put(R.id.fragment_settings, SettingsFragment.class);
    }

    public Fragment getFragmentById(int menuItemId) {
        Class<? extends Fragment> fragmentClass = menuItemFragments.get(menuItemId);
        if(fragmentClass == null) throw new NullPointerException("fragment not found");
        try {
            return fragmentClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("failed to construct fragment", e);
        }
    }
}

Than in onNavigationItemSelected you do the following:
 private FragmentFactory mFragmentFactory = new FragmentFactory();

 public boolean onNavigationItemSelected(MenuItem menuItem) {
        Fragment fragment = mFragmentFactory.getFragmentById(menuItem.getItemId());
        select(fragment);

        return true;
 }


text:
Q: Grails + Bootstrap: Can't get modal to "unhide" I'm trying to use Bootstrap 3 with Grails and have gotten the basics down.  I'm using the twitter-bootstrap plugin and installed it per instructions.  Basic things seem to be working fine (I even installed a template), but for the life of me I can't figure out how to get a modal to pop-up with a "processing.../ please wait" message when I submit a form.  I've included the following div in my main.gsp to setup the modal:

     <g:layoutBody/>

Processing...

                        Please Wait...

In a separate .gsp file containing the page contents, I have a form that includes the following g:actionSubmit tag, as well as a plain button tag for testing purposes:
<g:form class="form-horizontal" url="[action:'search', controller:'personSearch']" method="PUT" >
        <g:render template="form"/>

                <g:actionSubmit class="btn btn-primary"
                                action="search"
                                value="${message(code: 'search.label', default: 'Search')}"
                                data-toggle="modal"
                                data-target="#pleaseWaitDialog"/>

                <button class="btn btn-primary" data-toggle="modal" data-target="#pleaseWaitDialog">
                     Start Process...
                </button>

    </g:form>

Neither button actually gets the modal to pop-up.  What am I missing?

A: DOH!  Figured it out. The main.gsp file I had was importing JS file from the bootstrap template I downloaded.  For whatever reason, the bootstrap.min js file used in that template wasn't working properly.  When I took out references to that js file and instead used the
    <asset:javascript src="application.js"/>

tag to import the grails application.js file, which imports the bootstrap js:
//= require bootstrap

That fixed everything!


text:
Q: Parse string with regular expression using JavaScript Need help with regular expression in JavaScript
I have a semicolon delimited string of hyperlinks:
 "Asthma;  Alzheimer's Disease; Depression"

I need to remove below part of the string using regular expression:
" Alzheimer's Disease"

Any help would be appreciated.
Thanks,

A: Since I have no clue to why or what you're trying to accomplish the regex may not work. Next time, please give us some context. It helps us and you. The other thing is try to show what you've tried yourself so we don't just repeat the same suggestion you've already tried.
Anyway here's a simple regex that will do this, but technically you could just do a replace to remove the occurrences of the string you provided.
]+onclick="RemoveValue\('Alzheimer's Disease'[^"]+">[^<]+(?:;\s)?

Regex Demo
For the JS side it should look something similar to this:
var str = "Asthma;  Alzheimer's Disease; Depression";

var re = /]+onclick="RemoveValue\('Alzheimer's Disease'[^"]+">[^<]+<\/a>(?:;\s)?/gi;
var reOutput = str.replace(re, "");
console.log(reOutput);

Fiddle Demo - Check console window.


text: Q: How to use leaflet map without internet connection(Offline Mode), preferably in Angular I have made an application on Disaster Management using Angular 8 for which I have used Leaflet maps. Now, my professor wants me to run the application without having access to the internet. Is there any way I can use Leaflet maps in offline mode in Angular? I am taking the current position(Lat-Long) of the user and showing it on leaflet maps?


text:
Q: How to include a long underscore before the \question command? i am working with a simple question but i can't include underline before the \question.
Code
documentclass{myclass}

\newcommand{\line}{\begin{tabular}{p{2cm}}
\\[-.35em]
\hline
\end{tabular}
 }

 \begin{questions}
 \question What is the color of your shirt? \line

\end{questions}

Output:

*

*What is the color of your shirt? __
but i'm trying to make something like this by:
Output:
__ 1.What is the color of your shirt?
How can I create this?

A: Assuming the questions environment is that of the exam class: Redefine \questionlabel.
\documentclass{exam}

\renewcommand{\questionlabel}{\rule{1cm}{0.4pt}\thequestion.}

\begin{document}

\begin{questions}
\question\label{q:test} What is the color of your shirt?
\end{questions}

See question~\ref{q:test}.

\end{document}

A: like spaces, drawn rules (e.g. \hline) get ignored at the beginning of a line, so you need to put a "stopper" in front if you want it to be output.  add \leavevmode before \hdline.


text:
Q: Android how can i get thumb image of video file from gallery I need to show the selected video file from gallery in my listview.
I have successfully fetched the uri of video file but i am not able to get the thumb image of video file. Here is the code i have used for fetching image of video file from uri, but is causes the app to crash. Is there any other way to get image of video file..? please assist me if it can be achieved in any other way....
public static String getFileMetaData(Context context,String uri){
        Uri queryUri = Uri.parse(uri);
        // Get relevant columns for use later.
        String[] projection = {
                MediaStore.Files.FileColumns._ID,
                MediaStore.Files.FileColumns.DATA,
                MediaStore.Files.FileColumns.DATE_ADDED,
                MediaStore.Files.FileColumns.MEDIA_TYPE,
                MediaStore.Files.FileColumns.MIME_TYPE,
                MediaStore.Files.FileColumns.TITLE
        };
// Return only video and image metadata.
        String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
                + MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE
                + " OR "
                + MediaStore.Files.FileColumns.MEDIA_TYPE + "="
                + MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;

        CursorLoader cursorLoader = new CursorLoader(
                context,
                queryUri,
                projection,
                selection,
                null, // Selection args (none).
                MediaStore.Files.FileColumns.DATE_ADDED + " DESC" // Sort order.
        );

        Cursor cursor = cursorLoader.loadInBackground();
        int columnIndex = cursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA);

        Log.d("MyTag","***************** : " + cursor.getString(columnIndex));

        cursor.close();
        return null;
    }

A: Fixed this problem with some changes. Actually my problem was the file path that i had given is wrong.I have been giving the Uri got from gallery,
    now i had changed the code for getting the real path from Uri and
    then applied them to ThumbnailUtils for creating thumb image.
Uri uri = Uri.parse(uri);
String mUri = AppUtils.getRealPathFromURI(mActivity,uri,"VIDEO");
mImageSend.setImageBitmap(ThumbnailUtils.createVideoThumbnail(
                            mUri, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND));

public static String getRealPathFromURI(Context context,Uri contentURI,String type) {

        String result  = null;
        try {
            Cursor cursor = context.getContentResolver().query(contentURI, null, null, null, null);
            if (cursor == null) { // Source is Dropbox or other similar local file path
                result = contentURI.getPath();
                Log.d("TAG", "result******************" + result);
            } else {
                cursor.moveToFirst();
                int idx = 0;
                if(type.equalsIgnoreCase("IMAGE")){
                    idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                }else if(type.equalsIgnoreCase("VIDEO")){
                    idx = cursor.getColumnIndex(MediaStore.Video.VideoColumns.DATA);
                }else if(type.equalsIgnoreCase("AUDIO")){
                    idx = cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
                }
                result = cursor.getString(idx);
                Log.d("TAG", "result*************else*****" + result);
                cursor.close();
            }
        } catch (Exception e){
            Log.e("TAG", "Exception ",e);
        }
        return result;
    }

A: From the video file uri first you have to get filepath of video file then from filepath you can generate video thumb.
You can get thumbnail using createVideoThumbnail method of ThumbnailUtils class like this.
video_imageview.setImageBitmap(ThumbnailUtils.createVideoThumbnail(selectedVideoFilePath, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND));

In which selectedVideoFilePath is video file path. You can get file path using this.
String selectedVideoFilePath = GetFilePathFromDevice.getPath(this, videoFileUri);

You can use GetFilePathFromDevice class to get filepath from given Uri.
GetFilePathFromDevice.java
@SuppressLint("NewApi")
public final class GetFilePathFromDevice {

    /**
     * Get file path from URI
     *
     * @param context context of Activity
     * @param uri     uri of file
     * @return path of given URI
     */
    public static String getPath(final Context context, final Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}

I hope it helps!


text:
Q: Spring Data JPA Subquery Objects matching Spring Security User I am trying to extract a count of "mutual friends" when I fetch a User annotated with @Entity, preferably without having to iterate over all paginated results and query for the appropriate values.
This means that for any given user the result maybe different depending on whom is reading the database. Basically the following query:
select count(friendship) from Friendship friendship where
        friendship.owner.id = user_id and friendship.friend in
        (SELECT f.friend FROM Friendship f where f.owner.id = current_user_id)

Where user_id is the user being selected and current_user_id is logged in user.
The user whom should be compared is the Principle as defined by Spring Security, and SpEL format: ?#{principle}
I found out that @Formula is hibernate and does not apply SpEL, so I would have to use @Query.
I can not think of an efficient way to do this, save possibly defining a new database table (I'm using Postgresql) and updating it when friendships are updated.
Here is a basic look at what my friendship entity is like:
@Entity
@Table(name = "friendship")
public class Friendship {

@Id
private Long id;

@ManyToOne
@JoinColumn(name="owner_id", referencedColumnName = "id", nullable = false, updatable = false)
private User owner;

@ManyToOne
@JoinColumn(name="friend_id", referencedColumnName = "id", nullable = false, updatable = false)
private User friend;

Each new "friendship" gets two of these records created so I can easily query any user's friend-list.


text:
Q: Getting child element in XAML by type I have xaml button like so:
      <Button Click="SyncToDeviceToggle_OnClick">
                            <Button.Template>
                                <ControlTemplate>
                                    <Image Source="Img/kin.png" Height="25"/>
                                </ControlTemplate>
                            </Button.Template>
                        </Button>

Code behind:
private void SyncToDeviceToggle_OnClick(object sender, RoutedEventArgs e)
{
    var image = ??//I want to get the child image element in the button without having to search for it by name specified in name="something"
}

In javascript i would just do
     button.getElementsByTagName("image")[0];

A: You could assign a name to the Image control and then access it by means of the FindName method of the Button's Template:
<ControlTemplate>
    <Image x:Name="image" Source="Img/kin.png" Height="25"/>
</ControlTemplate>

...
private void Button_Click(object sender, RoutedEventArgs e)
{
    var control = (Control)sender;
    var image = control.Template.FindName("image", control) as Image;
}

A: private void Button_Click(object sender, RoutedEventArgs e)
{
        Button button = sender as Button;
        DependencyObject child = VisualTreeHelper.GetChild(button, 0);
        Image image = child as Image;
        //Now you can access your image Properties
}

A:     <Button Click="SyncToDeviceToggle_OnClick" Margin="0,224,0,302">
            <Button.Background>
                <ImageBrush ImageSource="Img/kin.png" x:Name="MyBrush"/>
            </Button.Background>
        </Button>

If done in this way, you can directly access MyBrush by its direct name in the .cs file.


text:
Q: Gradle robolectric project works on OSX computer but not on Linux I'm using the same version of Gradle, 1.7 jdk thus not exactly the same version.
The main complain of the testing is :

java.lang.NoClassDefFoundError:
  org/apache/maven/artifact/ant/DependenciesTask Caused by:
  java.lang.ClassNotFoundException:
  org.apache.maven.artifact.ant.DependenciesTask

I've tried to clean gradle cache in order to re download all dependencies.
Also i've tried to clean the project.
This didn't work.
What variables can affect the execution of a gradle test ?
To me there is:

*

*Gradle itself

*Java version of the sdk

*Internet connections problems

What else can be interfering ? Are plugin versions platform dependant ?
Executing task ':robolectric-tests:test' (up-to-date check took 0.432 secs) due to:
  Output file /home/ec2-user/repositories/MyProject/robolectric-tests/build/test-results has changed.
  Output file /home/ec2-user/repositories/MyProject/robolectric-tests/build/reports/tests has changed.
  Output file /home/ec2-user/repositories/MyProject/robolectric-tests/build/test-results/binary/test has changed.
Starting process 'Gradle Test Executor 1'. Working directory: /home/ec2-user/repositories/MyProject/robolectric-tests Command: /usr/java/jdk1.7.0_72/bin/java -Djava.security.manager=jarjar.org.gradle.process.internal.child.BootstrapSecurityManager -Dfile.encoding=UTF-8 -Duser.country=ES -Duser.language=ca -Duser.variant -ea -cp /home/ec2-user/.gradle/caches/2.3/workerMain/gradle-worker.jar jarjar.org.gradle.process.internal.launcher.GradleWorkerMain 'Gradle Test Executor 1'
Successfully started process 'Gradle Test Executor 1'
Gradle Test Executor 1 started executing tests.
Gradle Test Executor 1 finished executing tests.

com.tubtale.MyProject.robolectrictests.tests.RobTMyAndroidClassTest > testWhenActivityCreatedHelloTextViewIsVisible2 FAILED
    java.lang.NoClassDefFoundError: org/apache/maven/artifact/ant/DependenciesTask

        Caused by:
        java.lang.ClassNotFoundException: org.apache.maven.artifact.ant.DependenciesTask

com.tubtale.MyProject.robolectrictests.tests.RobTMyAndroidClassTest > testWhenActivityCreatedHelloTextViewIsVisible FAILED
    java.lang.NoClassDefFoundError: org/apache/maven/artifact/ant/DependenciesTask

2 tests completed, 2 failed
Finished generating test XML results (0.217 secs) into: /home/ec2-user/repositories/MyProject/robolectric-tests/build/test-results
Generating HTML test report...
Finished generating test html results (0.11 secs) into: /home/ec2-user/repositories/MyProject/robolectric-tests/build/reports/tests
:robolectric-tests:test FAILED
:robolectric-tests:test (Thread[main,5,main]) completed. Took 4.005 secs.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':robolectric-tests:test'.
> There were failing tests. See the report at: file:///home/ec2-user/repositories/MyProject/robolectric-tests/build/reports/tests/index.html

* Try:
Run with --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':robolectric-tests:test'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:306)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:29)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:80)
    at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:33)
    at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:24)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:36)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
    at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:51)
    at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:169)
    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:237)
    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:210)
    at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)
    at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:206)
    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)
    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
    at org.gradle.launcher.Main.doAction(Main.java:33)
    at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
    at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:54)
    at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:35)
    at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
Caused by: org.gradle.api.GradleException: There were failing tests. See the report at: file:///home/ec2-user/repositories/MyProject/robolectric-tests/build/reports/tests/index.html
    at org.gradle.api.tasks.testing.Test.handleTestFailures(Test.java:1118)
    at org.gradle.api.tasks.testing.Test.executeTests(Test.java:549)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:63)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:218)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:211)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:200)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:585)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:568)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
    ... 44 more

BUILD FAILED

A: The selected answer is correct, and also applies when upgrading Gradle from 2.2.1 to 2.3 on OSX. If you don't add the dependency for testCompile 'org.apache.maven:maven-ant-tasks:2.1.3' then Robolectric tests will fail when the Gradle version is 2.3.
Also noteworthy is that I have a separate module for my Robolectric tests, so I added the new dependency to the build.gradle file in my Robolectric module, NOT my Android app module.
Just got a new Mac, so my old Mac & new Mac are side by side, while I configure the new one. I used Homebrew to build up my new Mac, and wasn't aware that Gradle 2.3 had just been released... That's why the Robolectric tests worked on my old Mac (with Gradle 2.2.1) but not on my new Mac (with Gradle 2.3).

A: I also ran into this issue on Linux but not OSX. I found a work-around by adding

org.apache.maven:maven-ant-tasks:2.1.3

to my 'testCompile' dependencies.
dependencies {
  repositories {
    mavenCentral()
  }
  testCompile 'junit:junit:4.12'
  testCompile 'org.apache.maven:maven-ant-tasks:2.1.3'
  testCompile 'org.robolectric:robolectric:2.4'
  testCompile 'org.mockito:mockito-all:1.9.5'
}

I don't know why maven-ant-tasks isn't getting fetched on linux. It appears to be a valid dependency of robolectric.


text:
Q: How to show that the image of a certain projective embedding is an algebraic curve? I found the following claim in a paper by Griffiths and Harris :
Start with a complex torus $\mathbb{C}/\Lambda$. The vector space of meromorphic functions having period lattice $\Lambda$ and a pole of order at most $n$ at $u=0$ has dimension $n$ (a consequence of Abel's theorem). Given a basis $f_1, f_2, \ldots , f_n$ of this vector space, the mapping
$F(u) = [f_1(u), \ldots, f_n(u)]$
induces a projective embedding $\mathbb{C}/\Lambda  \rightarrow \mathbb{P}^{n-1}$ whose image is easily proved to be a smooth algebraic curve of degree $n$. Thus, for $n=3$ we have a plane cubic, for $n=4$ the intersection of two quadrics in $\mathbb{P}^3$, etc.
I am trying to figure out why this statement is true. For the case $n=3$, you can choose the Weierstrass functions as a basis $(1,\wp,\wp')$ and they satisfy a polynomial equation of degree three, but that is nowhere near as general as the statement they make and I wouldn't say that it is "easily" proved.

A: Denote the given map by $\phi: \mathbb C/\Lambda \to \mathbb P^{n-1}$.
Let $H$ be a hyperplane in $\mathbb P^{n-1}$, cut out by the equation
$a_1 X_1 + \cdots + a_n X_n = 0$.
The preimage
$\phi^{-1}(H)$ is then equal to the subset of points of $\mathbb C/\Lambda$ satisfying the equation $a_1 f_1 + \cdots a_n f_n = 0$.
First of all, since $n \geq 3$, Riemann--Roch says that given any two points
$u$ and $v$ of $\mathbb C/\Lambda$, we may choose the $a_i$ so that
$u$ lies in $\phi^{-1}(H)$ while $v$ does not.  This implies that $\phi$
is injective.  (Note that here and below I am being a little careless about analyzing what happens at the point $u = 0$ here, where we have to modify the formula for
$\phi$; I'll leave these details to you.)
In fact, Riemmann--Roch also implies that we can choose $H$ so that
$a_1 f_1 + \cdots a_n f_n$ vanishes precisely to first order at any given point $u$.  This show that the image of $\phi$ is smooth at $\phi(u)$; since $u$ was arbitrary, we see that the image of $\phi$ is smooth, and hence that $\phi$ is an embedding onto its image.  (I have just sketched the verification that $\phi$ "separates points and tangent vectors", which is the standard condition to check that a map defined in the manner of $\phi$ is a projective embedding; this is discussed e.g. in Hartshorne Chapter 2, Section 7, and also --- in the specific
case of curves --- in the part of Chapter 4 that discusses projective embeddings of curves.)
Since $\mathbb C/\Lambda$ is compact, its image is a closed analytic submanifold of $\mathbb P^{n-1}$, which is then necessarily algebraic (by Chow's theorem if you like, although you could also prove this directly, by showing ----- by Riemann--Roch or by direct elementary arguments --- that the $f_i$ necessarily satisfy lots of algebraic relations among themselves, indeed so many that the image of $\phi$ is cut out by algebraic equations.  A more systematic way to describe the situation is to note that $\mathbb C/\Lambda$ has a unique structure of a projective algebraic
curve --- e.g. the one coming from the Weierstrass equation arising from the case $n = 3$ --- and with respect to this structure, the $f_i$ are rational funtions; the map $\phi$ is then a morphism of algebraic varities from $\mathbb C/\Lambda$ to $\mathbb P^{n-1}$; since its source is projective, its image is necessarily a closed algebraic subvariety.)
Now all that remains is to compute the degree of the image of $\phi$.  For this, we have to compute the number of intersection points of this image with a generic hyperplane $H$.  That is, we need to determine the size of $\phi^{-1}(H)$.  But this is the number of zeroes of $a_1 f_1 + \cdots + a_n f_n$.  Since this function has a pole of order $n$ (at least if $a_n \neq 0$, which is the
generic situation), it has $n$ zeroes, which will be distinct genericaly,
and so $\phi^{-1}(H)$ is generically of order $n$.
Thus the image of $\phi$ has degree $n$.

If you're not used to these sort of computations, you may want to look at
some of the examples and discussion of Chapter 4 of Hartshorne.  What I just did above is the standard way of analyzing projective embeddings of curves, and in  that sense it is easy (once you know how it goes).


text:
Q: Shopify String Replace Array not working I am new to shopify but upon my research... this code should work.
{% assign dcor = "decor, decors, Decor, Decors" | split: ", "%}
{% assign dcors = "décor, décors, Décor, Décors" | split: ", "%}
{{ product.title | replace: 'dcor', 'dcors' }}

But no luck at all.

A: Nope. Won't work. You can't match/replace elements from arrays. You have to manually replace each variation
{% assign dcor = "decor, decors, Decor, Decors" | split: ", "%}
{% assign dcors = "décor, décors, Décor, Décors" | split: ", "%}
{% assign d = dcor.size | minus: 1 %}
{% for i in (0..d) %}
{% assign title = product.title | replace: dcor[i],dcors[i] %}
{% endfor %}
{{ title }}


text:
Q: Formatting print function with list comprehensions I am trying to write a code where it formats the list comprehension function [print('{:<15} ${:<4f}'.format(Timeframes[counter],x)) for counter,x in enumerate(Compounding)] so that it will print the expected output. I am trying to print the values of Compounding and Non_Compounding on the same row but the Print Function that i am trying to do does not work. How would I be able to run it like the Expected Output?
Code:
import numpy as np

Timeframes = ['Last Month:', 'Three Months:', 'Six Months:', 'Last Year:', 'Last Two Years:', 'Entirety:']
Compounding = np.array([97.44704833566995, 77.20626280482892, 232.04635122144302, 424.5742707027069, 4076.195731389482, 28513.877490504994])
NonCompounding = np.array([98.7019108522086, 79.00055035682558, 198.89764228943147, 268.25878090471525, 514.6930939260048, 938.811329948405])

print("\t\tCompounding ")
[print('{:<15} ${:<4f}'.format(Timeframes[counter],x)) for counter,x in enumerate(Compounding)]
print("\n\t\tNon Compounding: ")
[print('{:<15} ${:<4f}'.format(Timeframes[counter],x)) for counter,x in enumerate(NonCompounding)]

Print Function:
[print('{:<15} ${:<4f}\t\t${:<4f}'.format(Timeframes[counter],x,y)) for counter,x,y in enumerate(Compounding,NonCompounding)]

Output
                Compounding
Last Month:     $97.447048
Three Months:   $77.206263
Six Months:     $232.046351
Last Year:      $424.574271
Last Two Years: $4076.195731
Entirety:       $28513.877491

                Non Compounding:
Last Month:     $98.701911
Three Months:   $79.000550
Six Months:     $198.897642
Last Year:      $268.258781
Last Two Years: $514.693094
Entirety:       $938.811330

Expected Output:
                Compounding        Non Compounding
Last Month:     $97.447048         $98.701911
Three Months:   $77.206263         $79.000550
Six Months:     $232.046351        $198.897642
Last Year:      $424.574271        $268.258781
Last Two Years: $4076.195731       $514.693094
Entirety:       $28513.877491      $938.811330

A: Use zip() to loop over the lists in parallel.
for timeframe, compound, noncompound in zip(TimeFrames, Compounding, NonCompounding):
    print(f'{timeframe:<15} ${compound{:<4f} ${noncompund:<4f}')

There's no need for a list comprehension. print() doesn't return anything, so you're just creating a list full of None. And you're not assigning the resulting list anywhere.


text:
Q: VueJS 2/Bootstrap 4 - Prevent a focus on element from bootstrap 4's data-toggle event Using VueJS2 and Bootstrap 4, I created a custom directive to interact with the changes that occurs with Bootstrap 4 radio button group. The problem occurs that when you update the data for bootstrap 4, the element component gets focused, which is fine if the page is small. But if the page is long and scrollable, this becomes a burden.
The below code is copied and modified based from the following example:
https://getbootstrap.com/docs/4.0/components/buttons/#checkbox-and-radio-buttons
<div class="btn-group btn-group-sm" data-toggle="buttons" v-radio="oType">
    <label class="btn btn-outline-dark active">
        <input type="radio" name="oType" value="0" /> Pressure
    </label>
    <label class="btn btn-outline-dark">
        <input type="radio" name="oType" value="1" /> Vacuum
    </label>
</div>

I created the following vue custom directive (radio.js):
Note: the problem is not on bind, the problem is only with the inserted/updated hooks, which are exactly the same code copied.
export default {
    inserted: function (el, binding, vnode) {
        var btns = $(el).find('.btn');
        var radioGrpName = $(btns[0]).find('input')[0].name;
        $("input[name='" + radioGrpName + "'][value='" + binding.value + "']").closest('.btn').button('toggle');
    },
    bind: function (el, binding, vnode) {
        var btns = $(el).find('.btn');
        btns.each(function () {
            $(this).on('click', function () {
                var v = $(this).find('input').get(0).value;
                (function set(obj, str, val) {
                    str = str.split('.');
                    while (str.length > 1) {
                        obj = obj[str.shift()];
                    }
                    return obj[str.shift()] = val;
                })(vnode.context, binding.expression, v);
            })
        })
    },
    update: function (el, binding, vnode, oldnode) {
        var btns = $(el).find('.btn');
        var radioGrpName = $(btns[0]).find('input')[0].name;
        $("input[name='" + radioGrpName + "'][value='" + binding.value + "']").closest('.btn').button('toggle');
    }
}

The problem is, if I have the bootstrap 4 radio button group somewhere down the page, and I have a user set some kind of input data that automatically changes the data for the radio button, this triggers the buttons('toggle') from the directive (using either the insert or update hooks), focusing on the element, making a big jump in the html page. Users would have to scroll back up to continue where they left off.
The way the radio button above interacts with data changed is by a computed property:
computedProperty: {
    oType: {
        get: function () {
            return this.oType;
        },
        set: function (value) {
            this.oType = value
        }
    }
}

So how do you prevent a focus from happening on the element?

A: So I traced the problem to bootstrap.js, and during the trigger of data-toggle, it caused the problem to occur. So in radio.js, I switched this line:
$("input[name='" + radioGrpName + "'][value='" + binding.value + "']").closest('.btn').button('toggle');

and mimicked the look & feel:
$(el).children('.btn').removeClass('active');
$("input[name='" + radioGrpName + "'][value='" + binding.value + "']").closest('.btn').addClass('active');
$("input[name='" + radioGrpName + "'][value='" + binding.value + "']").prop('checked', true);


text:
Q: Compartilhando conteúdo de aplicativo feito em Intel XDK no Facebook Olá!
Eu criei um aplicativo em HTML5 + JQuery Mobile no Intel XDK, que será para android (e quem sabe app para FB). Nele, baseado em dados, tem uma espécie de pontuação (ele não é um jogo) e queria colocar uma opção para compartilhar essa pontuação no Facebook. Já tentei ler as referencias do Facebook sobre isso, mas não entendi.
Desde já, obrigado.


text:
Q: Variance in a Bernoulli distribution. I'm having trouble understanding the definition of variance of a Bernoulli distribution. I thought that the variance was the sum of the squared absolute values of each data point's distance from the mean divided by the number of distributions. However, I see a different definition of the variance for Bernoulli distributions:

In general, it is useful to think about a Bernoulli random variable as
  a random process with only two outcomes: a success or failure. Then we
  build our mathematical framework using the numerical labels 1 and 0
  for successes and failures, respectively. If p is the true
  probability of a success, then the mean of a Bernoulli random variable
  X is given by:
$$ \mu = E[X] = P(X = 0) * 0 + P(X = 1) * 1 $$
  $$ = (1   p) ⇥ 0 + p ⇥ 1 = 0 + p = p $$
Similarly, the variance of X can be computed:
$$ \sigma ^2 = P(X = 0)(0 - p)^2 + P(X = 1)(1 - p)^2 $$
$$ p = (1 - p)p^2 + p(1 - p)^2 $$
$$ = p(1 - p) \ $$

What is going on above? That doesn't seem like the standard definition of variance. Why are we taking the probability of $X = 0$ and multiplying it by the squared difference of p from 0?

A: I suspect you are confusing sample variance with variance. Taking the average squared deviation is an estimator of $\text{Var}(X)$, not  $\text{Var}(X)$ itself.
Variance is defined as
$$
\mathbb E[(X-\mu)^2]
$$
where $\mu = \mathbb E [X]$. In the case of Bernoulli $\mu = p$, so you immediately get
$$
\mathbb E[(X-p)^2] = \mathbb P(X = 0)(0-p)^2 + \mathbb P(X = 1)(1-p)^2
$$


text:
Q: Create f# class which implements interface using another interface Let's say I have the following interface ICreateEnumeratorCollection which uses another interface IEnumerable:
open System.Collections

type ICreateEnumeratorCollection =

     abstract member Enumerators : IEnumerable [] with get, set

I'm having a tough time creating a class which implements this interface in a generic way:
type ExampleClass<'a when 'a :> IEnumerable> (enum : #IEnumerable []) =

     let mutable internalEnum = enum

     interface ICreateEnumeratorCollection with
          member this.Enumerators
              with get ()     = internalEnum
              and set (enum)  = internalEnum <- enum

Trying to instantiate this class is a mess as the compiler is not able to implicitly infer the type implementing IEnumerable.
let myList = Array.singleton ["bla"]

let listDoesNotMatchIEnumerable =
    ExampleClass
        (
            myList
        )

let cantInferType =
    ExampleClass
        (
            myList
            |> Array.map (fun x -> x :> IEnumerable)
        )

let worksButIsAlotOfOverhead =
    ExampleClass<string list>
        (
            myList
            |> Array.map (fun x -> x :> IEnumerable)
        )

Is there a way to define this class in a way which allows the compiler to infer the type using IEnumerable?

A: Your class signature specifies that the enum parameter is of a generic type - i.e. it's not just an array of IEnumerable, no. It's an array of some type that implements IEnumerable. That's what the hash sign does.
As far as I understand from your further snippets, this is what you actually wanted: you wanted your class to take an array of any list-ish things as parameter.
But here's the problem: if you have an array of 't where 't implements IEnumerable, it's not at all the same as an array of IEnumerable.
For illustration:
let x : (int list) [] = [||]
let y : IEnumerable [] = x // Compiler error: cannot

So when you try to return enum from the Enumerators, the return type of Enumerators must be an array of IEnumerable, and since the compiler can't convert array of some unknown 't to an array of IEnumerable, it assumes that 't must itself be IEnumerable. Hence the warning you get.
To fix this, assuming you don't want to change the API, you will have to map and cast each element down to IEnumerable:
          with get ()     = internalEnum |> Array.map (fun x -> x :> _)

But then the next problem you'll see is with set, and this one is more serious. Think about it: what if your class works with, say, lists (which do implement IEnumerable), but then you try to assign it arrays? Or strings (which are also IEnumerable). You can't do that: the type of internalEnum doesn't match.
And here's the next question to ask: do you really need your class to be generic? It looks to me like you're not actually using that generic-ness except in the constructor for some syntactic convenience. But syntactic convenience doesn't have to come from a constructor, you can make your class non-generic, and then just have a convenience function for creating it:
type ExampleClass (enum : IEnumerable []) =

     let mutable internalEnum = enum

     interface ICreateEnumeratorCollection with
          member this.Enumerators
              with get ()     = internalEnum
              and set (enum)  = internalEnum <- enum

let mkExampleClass (enums: #IEnumerable []) =
    ExampleClass(enums |> Array.map (fun x -> x :> _))

Usage:
let listDoesNotMatchIEnumerable =
    mkExampleClass myList

A: Your enum parameter is fixed as IEnumerable [] as that's what required for the interface property.
While you can treat e.g. a string list [] as an IEnumerable [] (due to the fact arrays are covariant in .NET), it's really not advisable as you'd be able to stick an int list in there, which would throw an exception. e.g. imagine this code:
let list1 : string list [] = Array.singleton ["bla"]
let list2 : IEnumerable [] = list1 |> box |> unbox
list2.[0] <- [1] :> IEnumerable

The third line compiles, but throws an ArrayTypeMismatchException at runtime because the underlying type is string list [].
So, armed with the knowledge above you can make your API work as you want - you need can cast the argument to IEnumerable []. I'm not sure it's a great idea for the reasons outlined above: the IEnumerable [] returned by your property can easily throw exceptions when mutated because it's pretending to be something it's not.
type ExampleClass<'a when 'a :> IEnumerable> (enum:'a []) =

    let mutable internalEnum = enum |> box |> unbox

    interface ICreateEnumeratorCollection with
      member this.Enumerators
          with get ()     = internalEnum
          and set (enum)  = internalEnum <- enum

let result =
    ExampleClass myList

Or, a safer, create a new array with the correct type:
let mutable internalEnum = enum |> Array.map (fun x -> x :> IEnumerable)

But as the interface itself isn't generic, I'm not sure the implementation should be. For example, you might create an ExampleClass<string list>, but the result is something that has a property of type IEnumerable [], which is not generic - you could take the Enumerators property from an ExampleClass<string list> and set it to the same property on an ExampleClass<int list>. While that works, I'm not sure it makes a lot of sense.
It probably more sensible to have a generic factory function that creates an instance of a non-generic type:
type ExampleClass (enum) =

     interface ICreateEnumeratorCollection with
          member val Enumerators = enum with get, set

     static member Create (source:seq<#IEnumerable>) =
         let array = source |> Seq.cast<IEnumerable> |> Array.ofSeq
         ExampleClass array

let result =
    ExampleClass.Create myList

The Create function just requires a sequence of something that implements IEnumerable. It then casts each item and creates an array, which can then be used in your implementation.


text:
Q: Javascript function needed for jquery post method My jQuery
 let name = document.getElementById("Name").value;
  let code = document.getElementById("Code").value;
  let type = document.getElementById("ProductTypeId").value;

$.ajax({
   url: "/Home/jQueryAddComment",
   type: "POST",
   dataType: "html",
   data: json,
   success: function(data){
      //var message = data.Message;
      alert(data);
      $('.CommentSection').html(data);
   }
}

I need to convert my jQuery to pure Javascript function using fetch. It is a post method with html return. Is it possible using fetch.
Edit:
Below is the get method of my Javascript:
    fetch(url + "?" + o)
        .then(function (response) {
            //check if it is redirected to custom error page
            if (response.redirected && response.url.indexOf("/Error") > 0) {
                response.text().then(function (html) {
                    debugger
                    window.location.href = response.url;
                });
            } else {
                response.text().then(function (html) {
                    document.getElementById('view-all').innerHTML = html;
                });
            }
        })
        .catch(function (err) {

            console.log('Fetch Error', err);
        });

A: fetch also accepts a second argument which is a literal object containing information pertaining to the request - such as Request method, mode, headers, and POST BODY.
Straight from Mozilla docs:
var data = { name: "justin", code: "SDF", type: "some-type" };

fetch(url, {
   method: 'POST', // *GET, POST, PUT, DELETE, etc.
   mode: 'cors', // no-cors, *cors, same-origin
   cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
   credentials: 'same-origin', // include, *same-origin, omit
   headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
   },
   body: JSON.stringify(data) // body data type must match "Content-Type" header
});

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch