text:
Q: Porting ionic sidemenu project to meteor I made an app using the ionic framework and would like to make it run on meteor.
The App is build on top of the sidemenu template you can create tying ionic start myApp sidemenu.
Here is the Git of the port or just
> git clone https://github.com/Xample/sidemenu-meteor
> cd sidemenu-meteor/
> meteor

How to do so ?

A: Create both projects:

ionic start ionicProject sidemenu
meteor create meteorProject

Reorganise the files:
All the important files within a ionicframework comes into a www folder start to reorganise them to fit with the meteor good practices.

*

*In the meteor root folder, create a client, server, css, and public folder

*Copy the ionicProject/www/css files into the meteorProject/css

*Copy all the js files, the main index.html and the templates files into the meteorProject/client folder

*All the other files which only needs to be served (images, audio, documents) must be put into the meteorProject/public folder

*The ionicProject/www/lib will be replaced by a meteor package. Do not include it.

*The meteorProject/server folder will remain empty

Now we need to ensure meteor will load the app.js file before the other one.

*

*Create the meteorProject/client/lib folder

*Move the app.js file into that one

You should have the following structure:
├── client
│   ├── controllers.js
│   ├── index.html
│   ├── lib
│   │   └── app.js
│   └── templates
│       ├── browse.html
│       ├── login.html
│       ├── menu.html
│       ├── playlist.html
│       ├── playlists.html
│       └── search.html
├── css
│   └── style.css
├── public
│   └── img
│       └── ionic.png
└── server

Import the meteor packages:
meteor add urigo:ionic

That one will include other dependent packages below:
  added mquandalle:bower at version 0.1.11
  added urigo:ionic at version 0.0.6
  added urigo:angular at version 0.4.8
  added urigo:angular-ui-router at version 0.6.1
  added tinytest at version 1.0.3

*

*bower package allows to use the bower package manager. Well basically it is a tool to allow easily include other packages using a description file (which might be used by angular but not packaged for meteor yet) you will likely be using it for installing ngCordova. No need for this sidemenu port btw

*ionic correspond to all the files we did not copied from the ionicProject/www/lib folder. Those are now included by default into your meteor project.

*angular is basically the same as for ionic. Angular is now included into your meteor project as well + the 'angular-meteor' which will be useful for bootstrapping the app.

*angular-ui-router same story but for the router. This will be mandatory to handle the url and forward them to the right page. It's a little bit like the Iron router but angular way and compatible

*tinytest is added per default, no real need for the port

Edit and port the files
index.html
- On meteor the header and the body are parsed and generated back by the framework. In short, meteor packs everything and generate the script and style files for you. Conversely if you wanted to just include a css or a js file through a  or  tag within the header / body, they will be dismissed by meteor. This is the reason why we are using packages instead of adding our script by ourselves. This to say, that most of the content of the index.html is now useless and needs to be removed. Even the  is not allowed by meteor because it will generate it for you as well…. Moreover, no attributes are allowed in the body. This might be problematic for bootstrapping our project with angularJS. The html files looks like this now:

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title>sidemenu-meteor</title>

        <ion-nav-view></ion-nav-view>

The templates files:
All the .html files not being into the server, public or private folder are loaded and packed into one big html by meteor. As meteor will search for and pack all the .html it will load but not include all the one within a <template> tag. All the files into the meteorProject/client/templates must be edited and encapsulated within a <template> tag bearing the name attribute such that we can easily find it back later on. For example the template browse.html will be packed such as:
<template name="browse.html">
... browse html file content ...
</template>

Repeat this step for all the templates.
app.js

*

*Open the file and add the manual bootstrap for angularJS, in this manner you manually add the ng-app tag on top of the document.

Meteor.startup(function ()
{
  angular.bootstrap(document, ['starter']);
});

Note: You need to do it once everything is loaded, for this reason we are doing it within the Meteor.startup function caller.

*

*Add the 'angular-meteor' package to your application, this will change the Angular delimiters to [[ and ]] instead of the regular conflicting with meteor's handlebars {{ and }}

angular.module('starter', ['angular-meteor','ionic', 'starter.controllers'])

*

*Replace the router's templateUrl path url references to something we can use with the loaded by meteor templates. Remember, we are not storing the templates into the meteorProject/public folder, therefore we cannot load them through templateUrl:'someUrl' you might do it but I do not recommend

templateUrl: "templates/menu.html", becomes template:UiRouter.template('menu.html'),
Repeat this step for all the states in the state provider.
controller.js

*

*just replace the template dependency of the modal. From:
$ionicModal.fromTemplateUrl('templates/login.html', {
to
$ionicModal.fromTemplateUrl('login.html', {
This is again to ensure the template is found correctly. Note that for some reason we have been able to load the templateUrl using the template name. It's still a mystery to me, probably a meteor package port have added this sugar…
playlists.html (but possibly other files)
Edit all the files and replace all the {{ occurrences to [[ and }} to ]]
Basically in this example you will only have to edit playlists.html
Last step
At this stage you should be able to run the ionic sidemenu project under meteor. There is only one thing missing. As you can remember, we changed the delimiters {{}} -> [[]]. Unfortunately, some of the ionic directives are using the regular {{}} delimiters and expect them to be functional. Therefore while adding a <ion-item href="myPath"> this is compiled to something like  so… now if you click on a menu, the href will be wrong and you will not be redirected to the right page… To fix this, a workaround is to embed the <ion-item> within your own  tag. I'm still looking for a better solution…. Still to do so, just refactor all your ion-item such that:
    <ion-item nav-clear menu-close href="#/app/search">

becomes encapsulated in

    <ion-item nav-clear menu-close >
      Search
    </ion-item>

Dependencies
Last thing, meteor will try to minify your javascript during the deployment, doing so you might break the angular code if it is not using the array notation. Just refactor all your methods putting your methods into an array. Read the guide for more information. An alternative is to avoid meteor to minify the code deploying using --debug meteor deploy --debug your-project.meteor.com
To get this tutorial:
> git clone https://github.com/Xample/sidemenu-meteor
> cd sidemenu-meteor/
> meteor


text:
Q: Existence of a left adjoint to tensor product implies projectivity Let $S$ and $R$ be two (not necessarily commutative) $k$-algebras for $k$ a field. If I have a $S$-$R$ bimodule $_SM_R$, I can form the functor $_SM_R\otimes_R (-):R\text{Mod} \rightarrow S\text{Mod}$. Similarly, I can form $(-)\otimes_S {_SM_R}$ to get a functor from $\text{Mod}S \rightarrow \text{Mod}R$. If there are left adjoints to these tensor product functors, I want to show that $M$ must be projective and finitely generated over $R$ and $S$ respectively. Does anyone know any sources that might contain such an argument?

A: I believe I have worked out an argument: We want the functor $F:R\text{Mod}\rightarrow S\text{Mod}$ by $_S M_R \otimes_R (-)$. By tensor-hom duality, this functor is always a left adjoint so in particular it is right exact. If this functor is also a right adjoint, then it must be left exact which means that $M$ is flat as an $S$-module. In the case that I'm interested in, $R$ is the algebra $A^e$ and $M$ is $A$ as a $k-A^e$ bimodule where $k$ is some ground field. $A$ being flat over $A^e$ as a right module is equivalent to $A$ being separable as a $k$-algebra.

redpajama_set_name: RedPajamaStackExchange


text:
Q: At least n Spades in $14$ cards Standard $52$-card deck. $14$ randomly chosen cards.
Total number of Combinations: $C_{52}^{14}$.
The question is: what is the probability of having at least $n$ Spades with the dealt $14$ cards?
When $n=1$, my reasoning is to calculate the $p$ of missing the spades altogether and subtract the result from $1$, so the answer would be:
$$p(S>=1)=1-\frac{C_{39}^{14}}{C_{52}^{14}}$$
When $n=2$, can I use the same method "allowing" just one spade to appear in missing combinations, thus:
$$p(S>=2)=1-\frac{C_{40}^{14}}{C_{52}^{14}}$$
If I use the same logic for "at least 10 spades":
$$p(S>=10)=1-\frac{C_{48}^{14}}{C_{52}^{14}}$$
However, calculations showed me the unbelievably high result $(0.73)$ so I am sensing a mistake somewhere, please check my method and advise.
Thanks to all contributing to my answers, I am still earning my privilege to rate your posts.

A: You correctly determined the total number of ways that you can select $14$ cards from a deck of $52$ cards:
$$\mathcal{N}=\binom{52}{14}=1768966344600$$
We can in general calculate the number of ways that you can select $n$ spades and $14-n$ non-spades as follows:
$$N_{n}=\binom{13}{n}\binom{39}{14-n}$$
So, the number of ways to get combinations of cards such that there is "at least" $n$ spades, where $n \in \{0,\dots,13\}$ is:
$$N=\sum_{k=n}^{13}\binom{13}{k}\binom{39}{14-k}$$
So if we want at least $10$ spades then:
$$N=\sum_{k=10}^{13}\binom{13}{k}\binom{39}{14-k}=24246300$$
So we have the probability of selecting one of these combinations:
$$P=\frac{N}{\mathcal{N}}=\frac{24246300}{1768966344600} = 1.37065 \times 10^{-5}$$

A: Your calculation for $P(S\geq 1)$ is correct.
Your calculation for $P(S\geq 2)$ is incorrect. Your approach of calculating $P(S<2)$ and then taking $P(S\geq 2) = 1-P(S<2)$ is correct, but you did not calculate $P(S<2)$ correctly. $C(40, 14)$ is the number of ways that you can select $14$ cards out of a deck containing, for example, all non-spades and the king of spades. You need to multiply this number by the number of spades you can select.


text:
Q: Access CasperJS variable from evaluate method I am trying to scrape a website. I have a website where it has a select element,  so after selecting the element, another select box appears dynamically and so on.
Either I can use waitForSelector method, but I don't know the id of the dynamic element before hand, or I can use wait to wait for a few seconds.
But, for dynamically loaded content, the page will send an ajax request. I use the functions onResourceRequest and onResourceReceived to keep a count, such that whenever a resource is requested I increment the count and after the event reource.received or onResourceError I could decrement the count and check iff the count is 0, I will move forward or else wait for requests to be completed.
But I scrape the page using evaluate method and the variable on which I increment and decrement count is in CasperJS context. How should I access the variable declared in CasperJS from evaluate function, so that I could check whether all the requests hava been finished or not.

A: Since evaluate() is sandboxed, you can't directly access variables defined outside. There are multiple ways to pass data out of the page context (console message, alert, page.onCallback, evaluate() result), but there is only one way to pass data in and that is by directly passing it to evaluate() as an argument.
The question is how you can pass it in so that your script makes sense.
Pass it every time
Whenever you do something in the page context that requires that variable, you can pass it in. This might not work as expected when you do a lot of asynchronous work before using that information as it can be stale at that time.
Proactively put it into the page context
Whenever that count changes, you can put that information into the page context onto the global scope:
// do this inside of the `reource.received` and `onResourceError` events
casper.evaluate(function(count){
    window._myCount = count;
}, count);

Then whenever you need to use that information inside of the page context you just need to access it as it already there in window._myCount.

You can more or less freely nest steps such as waitForSelector():
casper.waitForSelector(selector1, function(){
    var dynamicId = this.evaluate(function(){
        ...
        return dynId;
    });
    this.waitForSelector("#" + dynamicId);
});

casper.then(function(){
    // this is only executed when the previous `"#" + dynamicId` was found
});


text:
Q: Gaussian measures from a finite dimensional space to an infinite dimensional space It's well known that the characteristic function of a gaussian measure $\mu$ on $\mathbb{R}^d$ is given by:
$$
\hat{\mu}(\xi)=\int_{\mathbb{R}^d}exp(i\xi . x)\mu (dx),\qquad  \xi \in \mathbb{R}^d
$$
but when we move to an infinite dimensional space; let's say a Banach space $X$ the formula becomes:
$$
\hat{\mu}(f)=\int_{X}exp(if(x))\mu (dx),\qquad  f\in X^*
$$
My question is how such formula has been derived ? what analysis leads to this standing on the finite dimensional result ?
Thank you for your time.


text:
Q: Adding image/icon before site's title/logo in nav-bar with Zurb's foundation 4 I'm using Foundation for a project and I'm trying to add a small icon right before "SITENAME" in the top left corner.
I've tried this css:
.top-bar .name h1 a:before {
    background-image: url('images/logo.png');
    background-size:18px 18px;
    background-repeat: no-repeat;

}

but it doesn't seem to work. the image path is correct.
Here's the html:

SITENAME

How can I add a simple icon/image without hacking into foundation.css?

A: If you are going to use the pseudo elements to show an image, you need to set content to '' (empty string), manually set the width and height, and set the display to either inline or inline-block.
Like this:
.top-bar .name h1 a:before {
    background-image: url('images/logo.png');
    background-repeat: no-repeat;
    content: "";
    display: inline-block;
    height: 18px;
    margin-right: 10px;
    position: relative;
    width: 18px;
}

See a live demo here: http://plnkr.co/edit/ZeEBrfG2IchhqiNv5iWd?p=preview


text:
Q: Create a new instance of a type from a variable Okay, so I have a dictionary of types int and Tile. I have a class called TileManager that I'm designing to return a NEW instance of a certain tile. Right now this is what I have.
public class TileManager
{
    private Dictionary<int, Tile> _registeredTiles = new Dictionary<int, Tile>();

    public Tile GetNewTile(int id)
    {
        // Here, I need to return a new instance of the tile at the given key. I want
        // something like this: return new _registeredTiles[id].GetType();
    }
    . . .
}

The problem is, I can't just create a new Tile class, because it will be holding different classes other than tiles (it will be holding children of Tile).

A: The simplest solution would be to use Activator.CreateInstance();
You can pass it a type and an array of constructor arguments if required:
return (Tile)Activator.CreateInstance(_registeredTiles[i].GetType());


text:
Q: Why is WPF DataGrid showing a class name in the header? I have created a custom style for my WPF datagrid by overriding its control template - nothing unusual, just copied the original template and modified it. Unfortunately, when the grid is drawn, the fully qualified class name of my ViewModel is showing up in the header (the ViewModel happens to be the DataContext of the UserControl that contains the DataGrid). Using Snoop, I have narrowed down which element in the template is showing this class name:
<DataGridColumnHeadersPresenter
 Grid.Column="1"
 Name="PART_ColumnHeadersPresenter"
 Visibility="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=HeadersVisibility, Converter={x:Static DataGrid.HeadersVisibilityConverter}, ConverterParameter={x:Static DataGridHeadersVisibility.Column}}"/>

The visual tree for this part looks like this:
PART_ColumnHeadersPresenter (DataGridColumnHeadersPresenter)
    (Grid)
        headerBorder (DataGridHeaderBorder)
            (Border)
                (TextBlock)

It is this text block that contains the class name! So the questions are

*

*Why does the Border need a TextBlock?

*Why is the TextBlock initialized with the class name of the DataContext?

*Is there a property at the DataGrid level that controls the conent of this TextBlock?

P.S. To answer the comment below, I am specifying proper paths for the ItemSource and also for each column:
<DataGrid
    ItemsSource="{Binding Path=Orders, Mode=TwoWay}"
    AutoGenerateColumns="False"
    IsReadOnly="True">
    <DataGrid.Columns>
        <DataGridTextColumn
            Header="Creation Time"
            Binding="{Binding Path=CreationTime}"
            CellStyle="{StaticResource LeftAlignedCellStyle}"
            SortMemberPath="CreationTime">
        </DataGridTextColumn>
        ...
    </DataGrid.Columns>
</DataGrid>

I don't see any place where I must bind the TextBlock for the column header border. Don't even know how it makes sense!
Based on Avatar's comment, I am sharing my entire template. See below:
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Classic">

    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Brushes.xaml"/>
    </ResourceDictionary.MergedDictionaries>

    <!-- ColumnHeader Gripper Style -->
    <Style x:Key="ColumnHeaderGripperStyle" TargetType="{x:Type Thumb}">
        <Setter Property="Width" Value="8"/>
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Cursor" Value="SizeWE"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Thumb}">
                    <Border Padding="{TemplateBinding Padding}"
                            Background="{TemplateBinding Background}">
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <!-- DataGridColumnHeader Style -->
    <Style x:Key="DataGridColumnHeaderStyle" TargetType="{x:Type DataGridColumnHeader}">
        <Setter Property="VerticalContentAlignment" Value="Center" />
        <Setter Property="Background" Value="{StaticResource HeaderBackgroundBrush}"/>
        <Setter Property="Foreground" Value="{StaticResource HeaderForegroundBrush}"/>
        <Setter Property="BorderBrush" Value="{StaticResource HeaderBorderBrush}" />
        <Setter Property="BorderThickness" Value="0,1,0,1" />
        <Setter Property="FontFamily" Value="Trebuchet MS" />
        <Setter Property="FontSize" Value="12" />
        <Setter Property="FontWeight" Value="Bold" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
                    <Grid>
                        <themes:DataGridHeaderBorder
                            x:Name="headerBorder"
                            SortDirection="{TemplateBinding SortDirection}"
                            IsHovered="{TemplateBinding IsMouseOver}"
                            IsPressed="{TemplateBinding IsPressed}"
                            IsClickable="{TemplateBinding CanUserSort}"
                            Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Padding ="{TemplateBinding Padding}"
                            SeparatorVisibility="{TemplateBinding SeparatorVisibility}"
                            SeparatorBrush="{TemplateBinding SeparatorBrush}">
                            <Border BorderBrush="{StaticResource HeaderInnerBorderBrush}"
                                    BorderThickness="0,1,0,0">
                                <TextBlock
                                    Text="{Binding}" Margin="7,0,7,0"
                                    SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                    VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                    HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" />
                            </Border>
                        </themes:DataGridHeaderBorder>

                        <Thumb x:Name="PART_LeftHeaderGripper"
                               HorizontalAlignment="Left"
                               Style="{StaticResource ColumnHeaderGripperStyle}"/>
                        <Thumb x:Name="PART_RightHeaderGripper"
                               HorizontalAlignment="Right"
                               Style="{StaticResource ColumnHeaderGripperStyle}"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter TargetName="headerBorder" Property="Background"
                                    Value="{StaticResource HeaderHighlightedBackgoundBrush}" />
                        </Trigger>
                        <Trigger Property="IsPressed" Value="True">
                            <Setter TargetName="headerBorder" Property="Background"
                                    Value="{StaticResource HeaderPressedBackgroundBrush}" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <!-- Right Aligned DataGridColumnHeader Style-->
    <Style x:Key="RightAlignedColumnHeaderStyle"
           TargetType="{x:Type DataGridColumnHeader}"
           BasedOn="{StaticResource DataGridColumnHeaderStyle}">
        <Setter Property="HorizontalContentAlignment" Value="Right"/>
    </Style>

    <!-- Center Aligned DataGridColumnHeader Style-->
    <Style x:Key="CenterAlignedColumnHeaderStyle"
           TargetType="{x:Type DataGridColumnHeader}"
           BasedOn="{StaticResource DataGridColumnHeaderStyle}">
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
    </Style>

    <!-- DataGridRowHeader Gripper -->
    <Style x:Key="RowHeaderGripperStyle" TargetType="{x:Type Thumb}">
        <Setter Property="Height" Value="8"/>
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Cursor" Value="SizeNS"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Thumb}">
                    <Border Padding="{TemplateBinding Padding}"
                            Background="{TemplateBinding Background}"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <!-- DataGridRowHeader Style -->
    <Style x:Key="{x:Type DataGridRowHeader}"
           TargetType="{x:Type DataGridRowHeader}">
        <Setter Property="Background" Value="{StaticResource HeaderBackgroundBrush}" />
        <Setter Property="BorderBrush" Value="{StaticResource HeaderBorderBrush}" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGridRowHeader}">
                    <Grid>
                        <themes:DataGridHeaderBorder
                            x:Name="headerBorder"
                            IsSelected="{TemplateBinding IsRowSelected}"
                            IsHovered ="{TemplateBinding IsMouseOver}"
                            IsPressed="{TemplateBinding IsPressed}"
                            Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="1,0,1,1"
                            Padding ="{TemplateBinding Padding}"
                            Orientation="Horizontal"
                            SeparatorVisibility="{TemplateBinding SeparatorVisibility}"
                            SeparatorBrush="{TemplateBinding SeparatorBrush}">
                            <Border BorderBrush="{StaticResource HeaderInnerBorderBrush}"
                                    BorderThickness="0,1,0,0">
                                <StackPanel Orientation="Horizontal">
                                    <ContentPresenter
                                        SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                        VerticalAlignment="Center"/>
                                    <Control
                                        SnapsToDevicePixels="false"
                                        Visibility="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, Path=(Validation.HasError), Converter={StaticResource bool2VisibilityConverter}}"
                                        Template="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, Path=ValidationErrorTemplate}" />
                                </StackPanel>
                            </Border>
                        </themes:DataGridHeaderBorder>

                        <Thumb x:Name="PART_TopHeaderGripper"
                               VerticalAlignment="Top"
                               Style="{StaticResource RowHeaderGripperStyle}"/>
                        <Thumb x:Name="PART_BottomHeaderGripper"
                               VerticalAlignment="Bottom"
                               Style="{StaticResource RowHeaderGripperStyle}"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter TargetName="headerBorder" Property="Background"
                                    Value="{StaticResource HeaderHighlightedBackgoundBrush}" />
                        </Trigger>
                        <Trigger Property="IsPressed" Value="True">
                            <Setter TargetName="headerBorder" Property="Background"
                                    Value="{StaticResource HeaderPressedBackgroundBrush}" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <!-- DataGridElement Styles -->
    <Style x:Key="DataGridElementStyle" TargetType="{x:Type FrameworkElement}">
        <Setter Property="VerticalAlignment" Value="Center" />
        <Setter Property="Margin" Value="7 0 7 0" />
    </Style>
    <Style x:Key="LeftAlignedElementStyle" TargetType="{x:Type FrameworkElement}" BasedOn="{StaticResource DataGridElementStyle}">
        <Setter Property="HorizontalAlignment" Value="Left" />
    </Style>
    <Style x:Key="CenterAlignedElementStyle" TargetType="{x:Type FrameworkElement}" BasedOn="{StaticResource DataGridElementStyle}">
        <Setter Property="HorizontalAlignment" Value="Center" />
    </Style>
    <Style x:Key="RightAlignedElementStyle" TargetType="{x:Type FrameworkElement}" BasedOn="{StaticResource DataGridElementStyle}">
        <Setter Property="HorizontalAlignment" Value="Right" />
    </Style>

    <!-- DataGridCell Styles -->
    <Style x:Key="DataGridCellStyle" TargetType="{x:Type DataGridCell}">
        <!-- Remove blue highlight when cell is selected -->
        <Setter Property="Background" Value="Transparent" />
        <!-- Don't change text color when cell is selected -->
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=Foreground}"/>
            </Trigger>
        </Style.Triggers>
    </Style>

    <Style x:Key="LeftAlignedCellStyle" TargetType="{x:Type DataGridCell}" BasedOn="{StaticResource DataGridCellStyle}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGridCell}">
                    <Grid Background="{TemplateBinding Background}">
                        <ContentPresenter Style="{StaticResource LeftAlignedElementStyle}" />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <!-- Center Aligned DataGridCell Style -->
    <Style x:Key="CenterAlignedCellStyle" TargetType="{x:Type DataGridCell}" BasedOn="{StaticResource DataGridCellStyle}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGridCell}">
                    <Grid Background="{TemplateBinding Background}">
                        <ContentPresenter Style="{StaticResource CenterAlignedElementStyle}" />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <!-- Right Aligned DataGridCell Style -->
    <Style x:Key="RightAlignedCellStyle" TargetType="{x:Type DataGridCell}" BasedOn="{StaticResource DataGridCellStyle}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGridCell}">
                    <Grid Background="{TemplateBinding Background}">
                        <ContentPresenter Style="{StaticResource RightAlignedElementStyle}" />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <!-- SelectAllButton ControlTemplate -->
    <ControlTemplate x:Key="SelectAllButtonTemplate" TargetType="{x:Type Button}">
        <Grid>
            <Rectangle x:Name="Border" SnapsToDevicePixels="True"
                       Stroke="{StaticResource HeaderBorderBrush}"
                       Fill="{StaticResource HeaderBackgroundBrush}" />
            <Border SnapsToDevicePixels="True" Margin="1,1,1,0"
                    BorderBrush="White" BorderThickness="0,1,0,0" />
            <Polygon x:Name="Arrow"
                     HorizontalAlignment="Right"
                     VerticalAlignment="Bottom"
                     Margin="8,8,3,3"
                     Opacity="0.15"
                     Fill="Black"
                     Stretch="Uniform"
                     Points="0,10 10,10 10,0" />
        </Grid>
        <ControlTemplate.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter TargetName="Border" Property="Fill"
                        Value="{StaticResource HeaderHighlightedBackgoundBrush}" />
            </Trigger>
            <Trigger Property="IsPressed" Value="True">
                <Setter TargetName="Border" Property="Fill"
                        Value="{StaticResource HeaderPressedBackgroundBrush}" />
            </Trigger>
            <Trigger Property="IsEnabled" Value="False">
                <Setter TargetName="Arrow" Property="Visibility" Value="Collapsed" />
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>

    <!-- DataGrid Style -->
    <Style x:Key="{x:Type DataGrid}" TargetType="{x:Type DataGrid}">
        <Setter Property="Background" Value="{StaticResource DefaultControlBackgroundBrush}"/>
        <Setter Property="Foreground" Value="{StaticResource DefaultControlForegroundBrush}"/>
        <!-- Remove border around the grid -->
        <Setter Property="BorderBrush" Value="{x:Null}" />
        <Setter Property="BorderThickness" Value="1" />
        <Setter Property="HorizontalGridLinesBrush" Value="{StaticResource GridLineColorBrush}" />
        <Setter Property="VerticalGridLinesBrush" Value="{StaticResource GridLineColorBrush}" />
        <Setter Property="AlternatingRowBackground" Value="{StaticResource AlternateRowBackgroundBrush}" />
        <Setter Property="ColumnHeaderStyle" Value="{StaticResource DataGridColumnHeaderStyle}"/>
        <!-- This is needed to force DG to have a non-default value.  Otherwise the DGR.DetailsVisibility cannot have a value of VisibleWhenSelected by default. -->
        <Setter Property="RowDetailsVisibilityMode" Value="VisibleWhenSelected" />
        <Setter Property="ScrollViewer.CanContentScroll" Value="true"/>
        <!-- Turn off row headers by default. -->
        <Setter Property="HeadersVisibility" Value="Column" />
        <Setter Property="GridLinesVisibility" Value="Horizontal" />
        <Setter Property="ColumnHeaderHeight" Value="32" />
        <Setter Property="RowHeight" Value="32" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGrid}">
                    <Border
                        Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        SnapsToDevicePixels="True"
                        Padding="{TemplateBinding Padding}">
                        <ScrollViewer Focusable="false" Name="DG_ScrollViewer">
                            <ScrollViewer.Template>
                                <ControlTemplate TargetType="{x:Type ScrollViewer}">
                                    <Grid>
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="Auto"/>
                                            <RowDefinition Height="*"/>
                                            <RowDefinition Height="Auto"/>
                                        </Grid.RowDefinitions>

                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="Auto"/>
                                            <ColumnDefinition Width="*"/>
                                            <ColumnDefinition Width="Auto"/>
                                        </Grid.ColumnDefinitions>

                                        <!--Left Column Header Corner -->
                                        <Button
                                            Command="{x:Static DataGrid.SelectAllCommand}"
                                            Width="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=CellsPanelHorizontalOffset}"
                                            Focusable="false"
                                            Visibility="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=HeadersVisibility, Converter={x:Static DataGrid.HeadersVisibilityConverter}, ConverterParameter={x:Static DataGridHeadersVisibility.All}}"
                                            Template="{StaticResource SelectAllButtonTemplate}"/>
                                        <!--Column Headers-->
                                        <DataGridColumnHeadersPresenter
                                            Grid.Column="1"
                                            Name="PART_ColumnHeadersPresenter"
                                            Visibility="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=HeadersVisibility, Converter={x:Static DataGrid.HeadersVisibilityConverter}, ConverterParameter={x:Static DataGridHeadersVisibility.Column}}"/>

                                        <!--DataGrid content-->
                                        <ScrollContentPresenter x:Name="PART_ScrollContentPresenter" Grid.Row="1" Grid.ColumnSpan="2" CanContentScroll="{TemplateBinding CanContentScroll}" />

                                        <ScrollBar
                                            Grid.Row="0" Grid.RowSpan="2" Grid.Column="2" Name="PART_VerticalScrollBar"
                                            Orientation="Vertical"
                                            Maximum="{TemplateBinding ScrollableHeight}"
                                            ViewportSize="{TemplateBinding ViewportHeight}"
                                            Value="{Binding Path=VerticalOffset, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}"
                                            Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}"/>

                                        <Grid Grid.Row="2" Grid.Column="1">
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Path=NonFrozenColumnsViewportHorizontalOffset}"/>
                                                <ColumnDefinition Width="*"/>
                                            </Grid.ColumnDefinitions>
                                            <ScrollBar
                                                Grid.Column="1"
                                                Name="PART_HorizontalScrollBar"
                                                Orientation="Horizontal"
                                                Maximum="{TemplateBinding ScrollableWidth}"
                                                ViewportSize="{TemplateBinding ViewportWidth}"
                                                Value="{Binding Path=HorizontalOffset, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}"
                                                Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"/>
                                        </Grid>
                                    </Grid>
                                </ControlTemplate>
                            </ScrollViewer.Template>
                            <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
                        </ScrollViewer>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsGrouping" Value="true">
                <Setter Property="ScrollViewer.CanContentScroll" Value="false"/>
            </Trigger>
        </Style.Triggers>
    </Style>

</ResourceDictionary>

A: The default template for DataGridColumnHeadersPresenter looks something like this:
<ControlTemplate TargetType="{x:Type DataGridColumnHeadersPresenter}">
    <Grid>
        <DataGridColumnHeader IsHitTestVisible="False"
            Name="PART_FillerColumnHeader"/>
        <ItemsPresenter />
    </Grid>
</ControlTemplate>

The ItemsPresenter will create a DataGridColumnHeader for each column, but the template also includes a single DataGridColumnHeader that stretches across the entire grid to act as a background.  It has no content, so it normally just draws the border in the appropriate theme.
However, your DataGridColumnHeader template includes a TextBlock instead of a ContentPresenter, so it will render the DataContext as a string whether or not it is also the content.  Try using a ContentPresenter instead of a TextBlock:
<Border BorderBrush="{StaticResource HeaderInnerBorderBrush}"
        BorderThickness="0,1,0,0">
    <ContentPresenter
        Margin="7,0,7,0"
        SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
        VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
        HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" />
</Border>


text:
Q: ASP.NET whitespace or %20 in URL Good day, everyone.
I found strange behavior within ASP.NET engine when it handles non-existent URL with whitespace.
When we have normal URL like this one: https://stackoverflow.com/questions/tagged1/c%23
we get normal custom 404 page as was intended by developers (if any).
But here's the bug. Just add some white space like this:https://stackoverflow.com/questions/tagged /c%23
and you'll see nasty ASP.NET 404 error page. Whether such a page should ever be displayed is another story. I've already made some heavy googling, made debugging research, and I can say that in this situation all custom handlers are ignored, global application class (Application_Error in global.asax) are just not reached. Actually, I don't see how can this situation be handled by ASP.NET. Any ideas?
Just as a note, this behavior is related to ASP.NET and ASP.NET MVC (as show on StackOverflow.com example). I tried other sites and found that even Microsoft.com falls into this category (see this: http://www.microsoft.com/en/us%20/default.aspx). Also, we can replace whitespace with %20 sequence with no better result.

A: Workaround is found.
HttpException is thrown with 'Error executing child request for pageName.aspx' message.
First of all, ASP.NET can't find requested page or route. Then exception is thrown from System.Web.CachedPathData.GetVirtualPathData (actually, from System.Web.CachedPathData.GetConfigPathData, but GetVirtualPathData makes things clear).
Then if we have any error handler, it provides some actions and tries to do something. Here we usually have Server.Transfer or Request.Redirect that moves user to page 404 or more common error page. But. In current situation HttpException is thrown anyway and we get ASP.NET error page. And in this situation Server.ClearError and Server.RewritePath can help: exception is not thrown this way. BUT! Such error handling crashes normal business logic exceptions thrown by our application.
And to resolve new trouble we have to use if/else depending on whether we receive HttpException (so we use ServerRewrite with ClearError) or some exception from our own code. But again, that's good if you provide your own exception classes, but what if not...
Anyway, I consider this a very strange case, especially that Application_Error handler is ignored whilst other application code is still executed.
Edit
As code-way was not the best selection (we can only guess that we have THIS error when exception Message is empty and InnerException is null) the better solution lies within ISAPI rewriter with rule like (\s+(\.aspx).*)|(\s+/) to custom 404 page. Here we catch all requests like /somePage .aspx and /somePath /. When we have whitespace not preceding .aspx or slash but within page name or path part we don't have mentioned problem.

A: Isn't it just that the request never reaches the asp.net pipeline. If you set up error documents in IIS, wouldn't they be displayed instead of the "nasty page" ?


text:
Q: Using springdoc-openapi in combination with openapi-generator-maven-plugin Our REST API is documented using OpenAPI V3. Documentation annotations are used in the controllers which generate an OpenAPI specification which is displayed using a Swagger UI page. Recently we switched to developing endpoints by writing the specification first. The OpenAPI V3 specification isn't generated but written by hand and used to generate interfaces for the controllers and to generate the data transfer objects. The generated classes are available in the REST API project through a dependency. However, while the generated classes are annotated with the same documentation annotations as the 'old' controllers they don't show up in the Swagger UI documentation page. Not even when the dependency package is scanned explicitly using the springdoc.packages-to-scan option.
Is the springdoc-openapi-ui dependency not able to recognize and display documentation from annotations that are in classes in a dependency?
springdoc-openapi-ui version 1.6.14 and openapi-generator-maven-plugin version 6.2.1 are used as the project runs Java 11. My understanding is that the latest version of Springdoc, springdoc-openapi-ui version 1.6.14, uses/requires Spring Boot 3 which in turn requires Java 17 or higher.


text:
Q: Is arrayName.length a property of an object? if so which object? The confusing part for me is the dot notation. The dot notation is used for accessing property values of an object, which is also used in finding a length of an array
const numbers =[23,45,76,78];
console(numbers.length);


text:
Q: Attaching maven-exec-plugin to initialize I am trying to attach an exec process to a maven build. I want to build a secondary dependency (that is actually a Clojure project build with maven) every time I build the maven project.
Currently, I have the pom.xml below, but the exec process is just not running. The maven documentation is not that much help.
<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.1</version>
  <executions>
    <execution>
      <id>compile-with-lein</id>
      <phase>initialize</phase>
      <goals>
        <goal>exec</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <executable>lein</executable>
    <commandlineArgs>install</commandlineArgs>
    <workingDirectory>../nrepl-clojure</workingDirectory>
  </configuration>
</plugin>


text:
Q: statusCode property not set AFJSONRequestOperation I am using the following code to make a http request and get json response back from a server. However when I look at the response's statusCode, I get the error that statusCode property is not set. What needs to be done to set the statusCode property in response.
NSString * my_url_string = @"http://link-to-my-server";
NSURL *url = [NSURL URLWithString:my_url_string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
       if (response.statusCode == 200){
        //I GET AN AERROR THAT statusCode IS NOT SET

A: Error notwithstanding, AFNetworking already made the check for a successful status code with its success/failure completion block distinction. That is to say, unless you want to differentiate between different successful status codes (200, 201, 204, etc.), you don't need to do this check yourself.


text:
Q: yAxis control for stacked bar chart I have been looking online and in the source code of Chart.js to find a way to use the stacked bar chart without stacking (summing) the values.
Example:
My data points are 1, 2, 2.5, 3, 4 for the stacked bar.  The chart y axis by default will sum that up to 12.5 (standard stacked bar behaviour).
What I would like is that each stack only go to its literal value, not the summed value.
In the example above, I would expect stack 1 to go to 1 on the y, 2 to 2 and so on until 4.
Is this possible OTB? Or will I need to write a custom chart renderer to achieve the desired result.
Note: The sequences will always be in order, and never have duplicates.

A: Found the solution.  I had set stacked on both x and y axes where all I needed to do was stack on the x axes.


text:
Q: Increment versionCode and versionName from gardle.build(app) for any productVariant This is the code of gradle.build(app) right now :
    defaultConfig {
      applicationId "com.moveeasy.yourbrokerage"
      multiDexEnabled true
      minSdkVersion 22
      targetSdkVersion 30
      versionCode 25
      versionName "1.19.0"
    }
    productFlavors {
        moveeasy {
            //Updated on 21-7-2021[8 and 1.6]
            applicationId "com.moveeasy.yourbrokerage"
            minSdkVersion 22
            targetSdkVersion 29
            versionCode 17
            versionName "1.15"
            signingConfig signingConfigs.release
        }
}

My fastlane code is as below :
           android_set_version_code(
               version_code: versionCode,
               gradle_file: "app/build.gradle"
           )

           android_set_version_name(
               version_name: versionName,
               gradle_file: "app/build.gradle"
           )

So, now problem is this code is increases the code and name from defaultConfig only. I want to increase it from productVariant/moveeasy. What is the solution?

A: will there another way your can change version and version code via manifest file.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="org.test"
    android:versionCode="115"
    android:versionName="11.33">

A: Below is the fastlane code to increment versionCode:
lane :incrementVersion do
      path = '../app/build.gradle'
      vc = /versionCode\s+(\d+)/
      vn = /versionName\s+\"(\d+.\d+.\d+)\"/

      # Reading build.gradle file to get versionName and versionCode
      gradleFile = File.read(path)
      versionCode = gradleFile[vc, 1].to_i
      gradleFile[vc, 1] = (versionCode + 1).to_s

      newGradleFile = File.new(path, 'w')
      newGradleFile.write(gradleFile)
      newGradleFile.close
end


text:
Q: Slim Basic Authentication Good day everyone!
I have a working slim code here with slim-basic-auth and when I go to a restricted directory, this shows up:

Everything works, but what I wanted to do is to redirect it to my login page instead of showing a popup login box. Here is my login page:

My slim code:
$pdo = new \PDO("mysql:host=localhost;dbname=databasename", "username");
$app->add(new \Slim\Middleware\HttpBasicAuthentication([
    "path" => "/main",
    "realm" => "Protected",
    "authenticator" => new PdoAuthenticator([
        "pdo" => $pdo,
        "table" => "accounts",
        "user" => "accountUsername",
        "hash" => "accountPassword"
    ]),
    "callback" => function ($request, $response, $arguments) use ($app) {
        return $response->withRedirect('/main/contacts');
    }

When I try to login using the popup login box, it works but I really want to redirect it to my login page instead of that.
Any help would be much appreciated.

A: The middleware implements HTTP Basic Access Authentication. Authentication dialog is triggered via response header. It is up to the browser vendor to decide how credentials are asked. Most browsers use the popup login dialog you described.
What you are trying to do is a bit unorthodox way of using HTTP Basic Authentication. However you can suppress the login dialog by removing the WWW-Authenticate header from the response. Note the you need at least version 2.0.2 for this to work.
$app->add(new \Slim\Middleware\HttpBasicAuthentication([
    "path" => ["/main"],
    "authenticator" => new PdoAuthenticator([
        "pdo" => $pdo,
        "table" => "accounts",
        "user" => "accountUsername",
        "hash" => "accountPassword"
    ]),
    "error" => function ($request, $response, $arguments) {
        return $response
            ->withRedirect("/auth/login")
            ->withoutHeader("WWW-Authenticate");
    }
]));

However with code above you still have to set the Authentication: Basic request header somehow. One way to do is using an AJAX request.
$.ajax({
   url: "http://example.com/auth/login",
   username: $("username").val(),
   password: $("password").val(),
   success: function(result) {
     alert("Authorization header should now be set...");
   }
});

A: At this point it looks like you're not trying to use the Http Basic Authenticator but rather a normal login process so you'll need to use sessions and such.
A very simple example is adding this close to the bottom of your middleware stack.(meaning it will be executed first as it will be at the top of the stack)
$middleware = function (Request $request, Response $response, $next) {

    if (!isset($_SESSION['__user'])) {
        //don't interfere with unmatched routes
        $route = $request->getAttribute('route');
        if ($route && !in_array($route->getName(), ['login'])) {
            return $response->withStatus(403)->withHeader('Location', $this->router->pathFor('login'));
        }
    }

    return $next($request, $response);
};
$app->add($middleware);

Looking at the HttpBasicAuthentication middleware it will always send the WWW-Authenticate header making your login form useless as it will trigger the auth pop-up.


text:
Q: Subclipse unable to commit: "Operation not permitted" I installed SVN and have it running as a daemon (Ubuntu 11.04). I've successfully commited the repo from command line but anytime I try to commit through subclipse I get the following error:
org.tigris.subversion.javahl.ClientException: Operation not permitted
svn: Can't remove '/home/dave/share/workspace/project/.svn/tmp/entries'
svn: Can't remove file '/home/dave/share/workspace/project/.svn/tmp/entries': Operation not permitted

org.tigris.subversion.javahl.ClientException: Operation not permitted
svn: Can't remove '/home/dave/share/workspace/project/.svn/tmp/entries'
svn: Can't remove file '/home/dave/share/workspace/project/.svn/tmp/entries': Operation not permitted

I tried recursively unsetting the sticky bit as I saw that was a fix on a thread a while back. I also switched my java within Eclipse > Team > SVN from JavaHL to SVNKit but that didn't work either. Anyone experience this before and can help?

A: Please chekc the following scenarios
1) Could it be the case that the command line tool uses a newer version, than the SubClipse does?
2) Check whether you have update the latest trunk state, before you commit
3) Are you using the same user/password in subclipse than in the command tool

A: Double check that the file is not in use. I use Process Explorer to find if any programs have a handle on my files, but just logging out and in again (or restarting) also works as a brute-force approach if you don't mind the hassle.

A: It's a known bug with VirtualBox shared folders. Apart from moving it outside the shared folder, another workaround it to use git-svn (install with sudo apt-get install git-svn, it doesn't come with standard git) to clone it automatically into a git repo.
Once git-svn is installed, you can use the command git svn clone http://my-svn-repo local-folder to clone a SVN repo without this error.


text:
Q: how to select the last inserted record in table in SQL Hello I am  trying to create a relatively simple trigger that when an employee is inserted to my table certified (which is where my many-to-many relationship is located, each employee can be certified for more than one jobs and each job can be done by more than one employees)
I would like the trigger to check if including the inserted record the employee is now certified in more than 3 jobs to give him a 10% raise.
This is what I tried first but then i realized that what i have done affects the whole table:
create trigger raise
on certified
after insert
as
begin
update employees set salary = salary + (salary*0.1)
where (select count(job_id) from certified where empid = (select empid from
inserted) group by empid)>3
end

My question is how is it possible to get only the last inserted record?

A: The last inserted record is inside "inserted" table.
I think this update below will solve the problem. Remember that you should only increase the salary in the first time the certified jobs increase above 3. You shoudn't increase the salary for the 5th or 6th certified job.
update employees set salary=salary + (salary*0.1)
where empid in
(select empid from certified where empid in
  (select empid from inserted) and (select count(job_id)
    from certified b
    where b.empid=certified.empid)=3+
        (select count(job_id) from inserted
            where inserted.empid=certified.empid)
)

Remember to also build a delete trigger. However, as a developer, I wouldn't build this business rule in triggers.


text:
Q: How can we add an application to startup remotely (Linux) I have an application which executes on a remote Linux system. How can I add this application to startup of that remote system from my local linux system. I know the path of executable (application) on remote system.
I searched a lot on different sources but didnt get any idea ?
Edit: What am I doing is:

*

*I have developed a desktop-application (using qt).

*I have loaded this application on remote system (using libssh).

*I am able to execute this application remotely.

*Now, I want to add this application to startup of that system remotely (stucked here).
Any Idea how to complete 4th step ??

A: *

*Create Executable.desktop file (on local machine)

*Open ssh connection and get remote machine root access

*Copy this Executable.desktop file to "etc/xdg/autostart" on remote system  (using ssh and commonds )

*Reboot the remote system (using ssh and commonds )

Note: The solution will work if we know the location of executable/application on remote system


text:
Q: Gem file with git remote failing on heroku push I have the following line in my gemfile:
gem 'client_side_validations', :git => "git@github.com:Dakuan/client_side_validations.git", :branch => "master", ref: '2245b4174ffd4b400d999cb5a2b6dccc0289eb67'

The repo it's pointing at is public and I can run bundle install / update locally just fine. When I try to push to Heroku I get the following error:

   Fetching git@github.com:Dakuan/client_side_validations.git
   Host key verification failed.
   fatal: The remote end hung up unexpectedly
   Git error: command `git clone 'git@github.com:Dakuan/client_side_validations.git' "/tmp/build_1xa9f06n4k1cu/vendor/bundle/ruby/1.9.1/cache/bundler/git/client_side_validations-56a04875baabb67b5f8c192c6c6743df476fd90f" --bare --no-hardlinks` in directory /tmp/build_1xa9f06n4k1cu has failed.

!
   !     Failed to install gems via Bundler.
   !
   !     Heroku push rejected, failed to compile Ruby/rails app

Anyone got any ideas about what's going on here?

A: Use this GitHub URL instead: git://github.com/Dakuan/client_side_validations.git
The git@github.com:… URL is the writable SSH version, which requires authentication with an SSH key connected to a GitHub account that has write access to the repository.
The git://github.com/… URL is the public, read-only version.
Since the gem you're using is in a public GitHub repository, you can also use this shorthand in your Gemfile:
gem 'client_side_validations', :github => 'Dakuan/client_side_validations'

See the Bundler Git documentation for more information.

A: A late second answer, as I ran into some confusing output from Heroku's build logs which stumped me for a while.
If you have multiple Github hosted gems in your Gemfile, and one of them is inaccessible (in my case, I had accidentally pointed to a private repo of mine), the build logs throw an error like Username not found or Repository not found for all the Github hosted gems - even those that are available.


text:
Q: Issues disabling/enabling multiple inputs in JQuery I have a form with an "OR" condition that either dims/disables 3 input fields or 1 input field depending on if there are entries in each.
I'm having a lot of trouble with inconsistent results with this--namely when the user tabs through inputs--and could really use some help.
The code that's problematic is:
$(document).ready(function() {
  $("#firstInitial,#lastName,#memberNo").blur(function() {
      if ($(this).val() != '')
          $("#datepicker").attr("disabled", "disabled").addClass("disabledStyle").val('');
      else
          $("#datepicker").attr("disabled", "").removeClass("disabledStyle");

  });

});
I'm trying to dim/disable a datepicker field when there's an entry in either firstInitial, lastName, or memberNo, or any combination of those three--and undisable datepicker if entries are removed in these.  What's happening is tabbing through these breaks everything and causes inconsistent results.
Is there another technique I could try?
Thanks.

A: I'm not sure I understood all of your question, but if you name your html elements using class="someName" instead of id="someName", then you have access to the "." JQuery syntax.
$(".someClass").someMethod() will apply the method to all elements declaring this class in their attributes.
I'm not certain if it's atomic though...

A: If you're seeing problems in FireFox, the following may be helpful.  (hint: set autocomplete=off)
Bug With Firefox - Disabled Attribute of Input Not Resetting When Refreshing


text:
Q: How to resolve #hyperledger-Composer V0.14 unmarshalling error I have just moved from V0.13.2 to V0.14.2 and am now getting following error in event processing. The error appears to be in the composer-client code, not mine. Any ideas on resolving? Events are still being posted and processed by my app, so my code still appears to work, but the presence of these error messages is troubling and their volume is overwhelming my console window.
error: [EventHub.js]: on.data - Error unmarshalling transaction= TypeError: Cannot read property 'getSerializer' of null
    at events.forEach (<path>Z2B_Master/Chapter12/node_modules/composer-client/lib/businessnetworkconnection.js:483:73)
    at Array.forEach (native)
    at HLFConnection.connection.on (<path>Z2B_Master/Chapter12/node_modules/composer-client/lib/businessnetworkconnection.js:482:29)
    at emitOne (events.js:96:13)
    at HLFConnection.emit (events.js:188:7)
    at ChainCodeCBE.ccEvent.eventHubs.(anonymous function).registerChaincodeEvent [as onEvent] (<path>Z2B_Master/Chapter12/node_modules/composer-connector-hlfv1/lib/hlfconnection.js:231:22)
    at <path>Z2B_Master/Chapter12/node_modules/fabric-client/lib/EventHub.js:810:12
    at Set.forEach (native)
    at EventHub._processChainCodeOnEvents (<path>Z2B_Master/Chapter12/node_modules/fabric-client/lib/EventHub.js:808:14)
    at ClientDuplexStream.<anonymous> (<path>Z2B_Master/Chapter12/node_modules/fabric-client/lib/EventHub.js:311:10)

This error is not present using identical code in V0.13.
All events are emitted via a single function in the sample.js file. A transaction calls the function as in the following example:
/**
 * create an order to purchase
 * @param {org.acme.Z2BTestNetwork.CreateOrder} purchase - the order to be processed
 * @transaction
 */
function CreateOrder(purchase) {
    purchase.order.buyer = purchase.buyer;
    purchase.order.amount = purchase.amount;
    purchase.order.financeCo = purchase.financeCo;
    purchase.order.created = new Date().toISOString();
    purchase.order.status = JSON.stringify(orderStatus.Created);
    return getAssetRegistry('org.acme.Z2BTestNetwork.Order')
        .then(function (assetRegistry) {
            return assetRegistry.update(purchase.order)
            .then (function (_res)
            {
                z2bEmit('Created', purchase.order);
                return (_res);
            }).catch(function(error){return(error);});
        });
}

Each transaction calls the z2bEmit function with a unique _event string.
function z2bEmit(_event, _order)
{
    var method = 'z2bEmit';
    var factory = getFactory();
    var z2bEvent = factory.newEvent(ns, _event);
    z2bEvent.orderID = _order.$identifier;
    z2bEvent.buyerID = _order.buyer.$identifier;
    emit(z2bEvent);
    return
}

_order is a defined asset in the cto file, _event is a defined event in the cto file.
The client side code has a single routine, executed once, to set up monitoring:
/**
 * Register for all of the available Z2BEvents
 * @param {express.req} req - the inbound request object from the client
 * @param {express.res} res - the outbound response object for communicating back to client
 * @param {express.next} next - an express service to enable post processing prior to responding to the client
*/
exports.init_z2bEvents = function (req, res, next)
{
    var method = 'init_z2bEvents';
    if (bRegistered) {res.send('Already Registered');}
    else{
        bRegistered = true;
        let _conn = svc.createAlertSocket();
        let businessNetworkConnection;
        businessNetworkConnection = new BusinessNetworkConnection();
        // following line added to deal with eventListener error message that more eventListeners needed to be added
        businessNetworkConnection.setMaxListeners(50);
        return businessNetworkConnection.connect(config.composer.connectionProfile, config.composer.network, config.composer.adminID, config.composer.adminPW)
        .then(() => {
            businessNetworkConnection.on('event', (event) => {_monitor(svc.al_connection, svc.f_connection, event); });
            res.send('event registration complete');
        }).catch((error) => {
            console.log(method+' business network connection failed'+error.message);
            res.send(method+' business network connection failed'+error.message);
        });
    }
}

The connectionProfile is 'hlfv1'
and a single monitor routine, which figures out what kind of event has been posted and then uses a web socket to send that info to a browser so that an alert icon can be posted or updated. A shortened version of that function follows. _conn _f_conn continue to work correctly. The _event information is being passed in and continues to parse correctly. The eventhub.js messages appear on every alert, irrespective of how long the program runs.
/**
 * _monitor
 * @param {web.socket} _conn - web socket connection for general alerts
 * @param {web.socket} _f_conn - web socket for finance alerts
 * @param {org.acme.z2bNetwork.Event} _event - the event just emitted
 *
 */
function _monitor(_conn, _f_conn, _event)
{
    var method = '_monitor';
    console.log(method+ ' _event received: '+_event.$type+' for Order: '+_event.orderID);
    var event = {};
    event.type = _event.$type;
    event.orderID = _event.orderID;
    event.ID = _event.buyerID;
    _conn.sendUTF(JSON.stringify(event));

    switch (_event.$type)
    {
        case 'Created':
        break;
        case 'Bought':
        case 'PaymentRequested':
            event.ID = _event.sellerID;
            _conn.sendUTF(JSON.stringify(event));
            event.ID = _event.financeCoID;
            _f_conn.sendUTF(JSON.stringify(event));
        break;
        case 'Ordered':
        case 'Cancelled':
        case 'Backordered':
            event.ID = _event.sellerID;
            _conn.sendUTF(JSON.stringify(event));
            event.ID = _event.providerID;
            _conn.sendUTF(JSON.stringify(event));
        break;
        default:
        break;
    }

}

A: While unable to determine the root cause of this problem, it has gone away with the release of (and upgrade to) hyperledger-composer V0.15.2.


text:
Q: Github workflow recommends archive before upload. How do I do that? Warning: There are over 10,000 files in this artifact, consider creating an archive before upload to improve the upload performance
I have a boilerplate Angular app and use GitHub as a repository to upload to an Azure App Service.
I receive the title message. How do I add in the Angular project code that I want the artifacts to be archived before upload? At the current rate it would take me 45 minutes to publish an app update.
There is this post https://github.community/t/upload-artifact-dir-is-very-slow/173738/2 that provides a solution but I'm not sure how I would go about it?
EDIT:
An update.
I actually wrote the conditional so I could get past the upload artifact.
uses: actions/upload-artifact@v2
  if: failure()
  with:
    name: node-app
    path: .


text:
Q: Linking images to routes in Laravel I'm working on laravel php framework , I've a simple question ,
While using blade template engine , I normally use html helper functions
to render forms , links or whatever so .
Now when i try to put a link to specific route , i usually to like that :
{{ HTML::link_to_route('author','TheAuthor')) }}

First parameter takes the route , and the second one takes the string that will appear ,
To make it simpler that code will produce :
TheAuthor

Now I want to replace TheAuthor with an image ,
What can i do ?

A: I know this is not the answer you want to hear - but you cannot pass any image via link_to_route.
The problem is the output from the HTML class is escaped automatically. So if you try to pass this:
{{ HTML::link_to_route('author','')) }}

it comes out like this:
<img src="http://laravel3.dev/assets/images/image.jpg" alt="icon" />

which will just be text on the screen - no image. Instead you need to use URI::to_route('author') and generate the link yourself. So make a helper a like this (not tested):
function link_to_route_image($route, $image)
{
   $m = ''
      . ''.$image.''
      . '';
   return $m;
}

A: Or you can use {{route}}
Ex:

A: It may become tedious if you are doing this all over the place, but in isolated spots the best way to handle this would actually be to wrap your entire link_to_* method call in HTML::decode.
{{ HTML::decode(HTML::link_to_route('author','')) }}

There's nothing you can do from the inside of the function (such as wrapping the "title" portion in decode) because the cleaning is happening within the function call, but if you decode the entire link it will render the html properly.


text:
Q: Using puppet hash for epp templates I have next code in erb template:
<% if @proxy_cache_path.is_a?(Hash) -%>
<% @proxy_cache_path.sort_by{|k,v| k}.each do |key,value| -%>
  proxy_cache_path        <%= key %> keys_zone=<%= value %> levels=<%= @proxy_cache_levels %> max_size=<%= @proxy_cache_max_size %> inactive=<%= @proxy_cache_inactive -%>
<% end -%>

How to porting it for epp template? Im find very low information for it. Please help.

A: Here's how you can do that:
Showing an example class and how to declare both an ERB and EPP template for comparison:
# manifests/init.pp
class foo () {
  $proxy_cache_path = {
    'apples'  => 1,
    'bananas' => 2,
  }
  $proxy_cache_levels = 2
  $proxy_cache_max_size = 2
  $proxy_cache_inactive = 2

  # Showing use of ERB:
  file { '/foo':
    ensure  => file,
    content => template('foo/mytemplate.erb')
  }

  # Showing use of EPP, which requires an explicit parameters hash:
  file { '/bar':
    ensure  => file,
    content => epp('foo/mytemplate.epp', {
      'proxy_cache_path'     => $proxy_cache_path,
      'proxy_cache_levels'   => $proxy_cache_levels,
      'proxy_cache_max_size' => $proxy_cache_max_size,
      'proxy_cache_inactive' => $proxy_cache_inactive,
    }),
  }
}

Corrected* contents of the ERB file for comparison:
# templates/mytemplate.erb
<% if @proxy_cache_path.is_a?(Hash) -%>
<% @proxy_cache_path.sort_by{|k,v| k}.each do |key,value| -%>
  proxy_cache_path        <%= key %> keys_zone=<%= value %> levels=<%= @proxy_cache_levels %> max_size=<%= @proxy_cache_max_size %> inactive=<%= @proxy_cache_inactive -%>
<% end -%>
<% end -%>

(*The code in the question is missing the closing end.)
Contents of EPP file:
# templates/mytemplate.epp
<%- | Hash[String, Integer] $proxy_cache_path, Integer $proxy_cache_levels, Integer $proxy_cache_max_size, Integer $proxy_cache_inactive | -%>
<% include stdlib -%>
<% $proxy_cache_path.keys.sort.each |$key| { -%>
  proxy_cache_path        <%= $key %> keys_zone=<%= $proxy_cache_path[$key] %> levels=<%= $proxy_cache_levels %> max_size=<%= $proxy_cache_max_size %> inactive=<%= $proxy_cache_inactive -%>
<% } -%>

Things to note about the EPP template file content:
1)  The parameters and their types are defined on the first line of the template. Use of this line is optional, but good practice.
2)  Since we declared the types on the first line, it is unnecessary and redundant to test if $proxy_cache_path is a Hash.
3)  We need to include stdlib in order to access the functions keys and sort. This is different to Ruby (ERB) where these methods are built-in to the language.
4)  I simplified the code relative to the Ruby (ERB) because Puppet (EPP) has no sort_by function - and actually there was no need to use it in the ERB either, which could be re-written as:
<% if @proxy_cache_path.is_a?(Hash) -%>
<%   @proxy_cache_path.sort.each do |key,value| -%>
  proxy_cache_path        <%= key %> keys_zone=<%= value %> levels=<%= @proxy_cache_levels %> max_size=<%= @proxy_cache_max_size %> inactive=<%= @proxy_cache_inactive -%>
<%   end -%>
<% end -%>

Finally some tests:
# spec/classes/test_spec.rb:
require 'spec_helper'

describe 'foo', :type => :class do
  it 'content in foo should be the same as in bar' do
    foo = catalogue.resource('file', '/foo').send(:parameters)[:content]
    bar = catalogue.resource('file', '/bar').send(:parameters)[:content]
    expect(foo).to eq bar
  end
end

And the tests pass.
See docs here.


text:
Q: How can I find the volume of this strange body? I need to calculate the volume of a body using multiple integrals. The body's boundary is defined by a surface whose formula is
$$0 \leq z \leq c \cdot \sin\left(\pi \sqrt{{{x^2} \over{a^2}} + {{y^2} \over{b^2}}}\right)$$
where $a$, $b$ and $c$ are some positive parameters.
The problem is that I have no idea what this body looks like. It's the first time I'm meeting sinus function in multitple integrals and it totally confuses me. I've tried to use the most popular substitutes, such as cylindrical and spherical coordinates, but it didn't help at all.
Thanks for any help!

A: If I understand this problem correctly, it is a matter of recognizing the elliptical coordinates inside the sine.  Thus, if we let
$$x=a k \cos{t}$$
$$y=b k \sin{t}$$
where $k \in [0,1]$ and $t \in [0,2 \pi]$.  In this way, $z \in [0,c \sin{(\pi k)}]$. Then the integral may be written as
$$a b \int_0^{2 \pi} dt \, \int_0^1 dk \, k \, \int_0^{c \sin{(\pi k)}} dz $$
Note that I made use of the Jacobian to effect the coordinate change.

A: For $a = b = c = 1$, the surface looks like this

However, the surface intersects the $z = 0$ plane

Hence, the body is not connected. The volume of each component can be computed using polar coordinates. This volume is $\infty$.


text:
Q: Rails 4 mensagens de erro traduzidas, trocar nome do model e atributos Olá, estou iniciando em rails e estou apanhando para tratar as mensagens de erros em pt-BR. Estou usando MongoDB/Mongoid para a camada de banco de dados.
Possuo um model user, com atributos name, email e password.
Baixei a gem 'rails-i18n', e o arquivo pt-BR.yml do diretório oficial do github.
As mensagens estão OK, porém, no botão cadastrar está escrito "Criar User", as mensagens de erro ficam como "Name não pode ficar em branco".
Gostaria de traduzir o nome do model e os seus atributos. Pelo que vi é feito diretamente no arquivo pt-BR.yml. O meu esta na estrutura abaixo, porém ainda não funciona.
    pt-BR:
      activerecord:
        models:
          user:
            one: "Usuário"
            other: "Usuários"
        attributes:
          user/name: "Nome"
          user/email: "E-mail"
          user/password: "Senha"
          user/password_confirmation: "Senha Confirmação"
      date:
        abbr_day_names:
        - Dom
        - Seg
        - Ter
        - Qua
        - Qui
        - Sex
        - Sáb
        abbr_month_names:
        -
        - Jan
        - Fev
        - Mar
        - Abr
        - Mai
        - Jun
        - Jul
        - Ago
        - Set
        - Out
        - Nov
        - Dez
        day_names:
        - Domingo
        - Segunda
        - Terça
        - Quarta
        - Quinta
        - Sexta
        - Sábado
        formats:
          default: ! '%d/%m/%Y'
          long: ! '%d de %B de %Y'
          short: ! '%d de %B'
        month_names:
        -
        - Janeiro
        - Fevereiro
        - Março
        - Abril
        - Maio
        - Junho
        - Julho
        - Agosto
        - Setembro
        - Outubro
        - Novembro
        - Dezembro
        order:
        - :day
        - :month
        - :year
      datetime:
        distance_in_words:
          about_x_hours:
            one: aproximadamente 1 hora
            other: aproximadamente %{count} horas
          about_x_months:
            one: aproximadamente 1 mês
            other: aproximadamente %{count} meses
          about_x_years:
            one: aproximadamente 1 ano
            other: aproximadamente %{count} anos
          almost_x_years:
            one: quase 1 ano
            other: quase %{count} anos
          half_a_minute: meio minuto
          less_than_x_minutes:
            one: menos de um minuto
            other: menos de %{count} minutos
          less_than_x_seconds:
            one: menos de 1 segundo
            other: menos de %{count} segundos
          over_x_years:
            one: mais de 1 ano
            other: mais de %{count} anos
          x_days:
            one: 1 dia
            other: ! '%{count} dias'
          x_minutes:
            one: 1 minuto
            other: ! '%{count} minutos'
          x_months:
            one: 1 mês
            other: ! '%{count} meses'
          x_seconds:
            one: 1 segundo
            other: ! '%{count} segundos'
        prompts:
          day: Dia
          hour: Hora
          minute: Minuto
          month: Mês
          second: Segundo
          year: Ano
      errors:
        format: ! '%{attribute} %{message}'
        messages:
          accepted: deve ser aceito
          blank: não pode ficar em branco
          present: deve ficar em branco
          confirmation: não é igual a %{attribute}
          empty: não pode ficar vazio
          equal_to: deve ser igual a %{count}
          even: deve ser par
          exclusion: não está disponível
          greater_than: deve ser maior que %{count}
          greater_than_or_equal_to: deve ser maior ou igual a %{count}
          inclusion: não está incluído na lista
          invalid: não é válido
          less_than: deve ser menor que %{count}
          less_than_or_equal_to: deve ser menor ou igual a %{count}
          not_a_number: não é um número
          not_an_integer: não é um número inteiro
          odd: deve ser ímpar
          record_invalid: ! 'A validação falhou: %{errors}'
          restrict_dependent_destroy:
            one: "Não é possível excluir o registro pois existe um %{record} dependente"
            many: "Não é possível excluir o registro pois existem %{record} dependentes"
          taken: já está em uso
          too_long: ! 'é muito longo (máximo: %{count} caracteres)'
          too_short: ! 'é muito curto (mínimo: %{count} caracteres)'
          wrong_length: não possui o tamanho esperado (%{count} caracteres)
          other_than: "deve ser diferente de %{count}"
        template:
          body: ! 'Por favor, verifique o(s) seguinte(s) campo(s):'
          header:
            one: ! 'Não foi possível gravar %{model}: 1 erro'
            other: ! 'Não foi possível gravar %{model}: %{count} erros.'
      helpers:
        select:
          prompt: Por favor selecione
        submit:
          create: Criar %{model}
          submit: Salvar %{model}
          update: Atualizar %{model}
      number:
        currency:
          format:
            delimiter: .
            format: ! '%u %n'
            precision: 2
            separator: ! ','
            significant: false
            strip_insignificant_zeros: false
            unit: R$
        format:
          delimiter: .
          precision: 3
          separator: ! ','
          significant: false
          strip_insignificant_zeros: false
        human:
          decimal_units:
            format: ! '%n %u'
            units:
              billion:
                one: bilhão
                other: bilhões
              million:
                one: milhão
                other: milhões
              quadrillion:
                one: quatrilhão
                other: quatrilhões
              thousand: mil
              trillion:
                one: trilhão
                other: trilhões
              unit: ''
          format:
            delimiter: .
            precision: 2
            significant: true
            strip_insignificant_zeros: true
          storage_units:
            format: ! '%n %u'
            units:
              byte:
                one: Byte
                other: Bytes
              gb: GB
              kb: KB
              mb: MB
              tb: TB
        percentage:
          format:
            delimiter: .
            format: "%n%"
        precision:
          format:
            delimiter: .
      support:
        array:
          last_word_connector: ! ' e '
          two_words_connector: ! ' e '
          words_connector: ! ', '
      time:
        am: ''
        formats:
          default: ! '%a, %d de %B de %Y, %H:%M:%S %z'
          long: ! '%d de %B de %Y, %H:%M'
          short: ! '%d de %B, %H:%M'
        pm: ''

A: Tente assim amigo:
activerecord:
  models:
    user: Usuário
attributes:
  user:
    name: "Nome"
    email: "E-mail"
    password: "Senha"
    password_confirmation: "Senha Confirmação"

A: Como estou usando Mongoid, não deve ser usado o activerecord, logo o código fica da seguinte for
pt-BR:
  mongoid:
    models:
      user:
        one: "Usuário"
        other: "Usuários"
    attributes:
      user:
        name: "Nome"
        email: "E-mail"
        password: "Senha"
        password_confirmation: "Senha Confirmação"
...


text:
Q: Отличия между получением значения из Extras Обратил внимание, что есть три способа получения значения из Extras:
    someInt = getIntent().getIntExtra("KEY", 0);
    someInt = getIntent().getExtras().getInt("KEY");
    someInt = (int) getIntent().getExtras().get("KEY");

Чем принципиально отличаются эти способы? Если в последнем можно получить что угодно и тут различие еще понятно, то какое различие между первым и вторым способом?

A: Если зайти и посмотреть исходники то можно увидеть следующий код:
public int getIntExtra(String name, int defaultValue) {
    return mExtras == null ? defaultValue :
        mExtras.getInt(name, defaultValue);
}

public Bundle getExtras() {
    return (mExtras != null)
            ? new Bundle(mExtras)
            : null;
}

Оба элемента работают с объектом mExtra, тип которого Bundle. Первый вариант вернет дефолтное значение если этот объект не установлен, а второй копию объекта mExtra.
У объекта Bundle метод getInt(String key, int defaultValue) имеет следующую релизацию
public int getInt(String key, int defaultValue) {
    unparcel();
    Object o = mMap.get(key);
    if (o == null) {
        return defaultValue;
    }
    try {
        return (Integer) o;
    } catch (ClassCastException e) {
        typeWarning(key, o, "Integer", defaultValue, e);
        return defaultValue;
    }
}

а метод get(String key) следующую:
@Nullable
public Object get(String key) {
    unparcel();
    return mMap.get(key);
}

Оба они работают с объектом mMap, только первый метод сразу преобразует результат в int либо вернет дефолтное значение, в то время, как второй возвращает тип Object, который придется кастовать вручную.
Исходя из реализации данных методов видно, что метод getIntExtra(String name, int defaultValue) является "шорткатом" относительно других методов. Так же он более безопасен, т.к. вы не получите NullPointerException либо ClassCastException


text:
Q: how to submit form by GET method using js I'm trying to pass values in the url through js but getting the error below
Uncaught RangeError: Maximum call stack size exceeded
    at String.replace (<anonymous>)

Javascript
$(document).on('submit','#adminProductFilter',function () {
            var category_id = $('#category').val();
            var prdouct_name = $('#productName').val();
            var link = '{{url('/admin/products?:id')}}';
            var url = link.replace(':id',"categories_id="+category_id+"&product="+prdouct_name);
            $(this).attr('action',url);
            $('#adminProductFilter').submit();
        });

Form.php
<form class="form-inline form-validate" enctype="multipart/form-data" id="adminProductFilter">
                        {{csrf_field()}}

{{ trans('labels.FilterByCategory/Products') }}:

                        <select class="form-control" name="categories_id" style="width: 100%" id="category">
                            <option value="">{{ trans('labels.SelectCategory') }}</option>
                            @foreach ($results['subCategories'] as  $key=>$subCategories)
                                <option value="{{ $subCategories->id }}"
                                    @if(isset($_REQUEST['categories_id']) and !empty($_REQUEST['categories_id']))
                                        @if( $subCategories->id == $_REQUEST['categories_id'])
                                            selected
                                        @endif
                                    @endif
                                >{{ $subCategories->name }}</option>
                            @endforeach
                        </select>

                        <input type="text" name="product" class="form-control" id="productName"
                            @if(isset($_REQUEST['product']) and !empty($_REQUEST['product']))
                                value="{{ $_REQUEST['product'] }}"
                            @endif
                         placeholder="Products">

                      <button type="submit" class="btn btn-success">{{ trans('labels.Search') }}</button>
                      {{ trans('labels.ClearSearch') }}
                    </form>

Route.php
Route::get('/products', 'AdminMasterProductsController@products');

When i click submit button it is showing url in the form action but the form is not getting submitted.
I just wanted to submit the form and get the result.
Please Help.

A: You can change the attribute of submit button to 'button', give it an id.
<form class="form-inline form-validate" enctype="multipart/form-data" id="adminProductFilter">
                        {{csrf_field()}}

{{ trans('labels.FilterByCategory/Products') }}:

                        <select class="form-control" name="categories_id" style="width: 100%" id="category">
                            <option value="">{{ trans('labels.SelectCategory') }}</option>
                            @foreach ($results['subCategories'] as  $key=>$subCategories)
                                <option value="{{ $subCategories->id }}"
                                    @if(isset($_REQUEST['categories_id']) and !empty($_REQUEST['categories_id']))
                                        @if( $subCategories->id == $_REQUEST['categories_id'])
                                            selected
                                        @endif
                                    @endif
                                >{{ $subCategories->name }}</option>
                            @endforeach
                        </select>

                        <input type="text" name="product" class="form-control" id="productName"
                            @if(isset($_REQUEST['product']) and !empty($_REQUEST['product']))
                                value="{{ $_REQUEST['product'] }}"
                            @endif
                         placeholder="Products">

                      <button type="button" id='btn-submit' class="btn btn-success">{{ trans('labels.Search') }}</button>
                      {{ trans('labels.ClearSearch') }}
                    </form>

And submit through event click.
$("#btn-submit").click(function(){
         var category_id = $('#category').val();
            var prdouct_name = $('#productName').val();
            var link = '{{url('/admin/products?:id')}}';
            var url = link.replace(':id',"categories_id="+category_id+"&product="+prdouct_name);
            $("#adminProductFilter").attr('action',url);
            $('#adminProductFilter').submit();
})


text:
Q: compositeCollection DataContext false warning, renaming issue I try to bind a ListBox.ItemsSource to a CompositeCollection containing three CollectionContainers. Each CollectionContainer is bound to a ObservableCollection in my ViewModel.
Because the CompositeCollection does not know my DataContext, i set the Source to a "Proxy" which is a FrameworkElement that knows my DataContext.
 <CollectionContainer Collection="{Binding DataContext.Dampings, Source={x:Reference Proxy}}" />
 <CollectionContainer Collection="{Binding DataContext.Angles, Source={x:Reference Proxy}}" />
 <CollectionContainer Collection="{Binding DataContext.Selectors, Source={x:Reference Proxy}}" />

This works as expected at runtime, althought it does show a warning at design time on DataContext:
Cannot resolve Property 'DataContext' in data context of type 'object'.
Is there a way to solve this designtime issue as the renaming is not applied to my Bindings as the designer cann't resolve them properly?


text:
Q: create-react-app: how to use https but with signed cert? I've seen the quite useful answer here: create-react-app: how to use https instead of http?
BUT
I'm not sure of the details on how to get this to work with a properly signed SSL cert.
Which version/format of the cert should I be using? PEM, or DER
I've seen some mention that you need to somehow combine the Issuing CA.cer and Root CA.cer (which I also have) into the PEM file. Is this correct?
Also, I'm using yarn and not npm, trying to use the following:
HTTPS=true SSL_CRT_FILE=QA_SSL_Cert.cer SSL_KEY_FILE=server.key yarn react-scripts start
The server starts, but I get the NET::ERR_CERT_AUTHORITY_INVALID error when I try to connect. (Without enabling HTTPS=true the app itself runs just fine.)

A: What you are doing is essentially correct. It seems that you are missing your chain of trust (probably because you haven't combined the Issuing CA.cer and Root CA.cer).
What you need to do is take the text from your signed SSL certificate, and append Issuing CA.cer and Root CA.cer, in that order, to the bottom.
Example (Chain certificate):
My SSL Certificate
Intermediate SSL Certificate (Issuing CA)
Root SSL Certificate (Root CA)
Each of the lines should be one after the other on separate lines (no empty lines between them).


text:
Q: Timeout command breaks command that expects input I need to execute a command with timeout so it's killed after X time.
I have done tests and it only works when typed in the terminal directly, when in a bash script it seems to not handle the user input like it's not "receiving it"

A: I found a solution looking at the man page. You need to use timeout --foreground 120s to have your command accept user input when executed in a bash script.


text:
Q: aggregate in multilevel index I have a dataframe that has two level column indices. I need to have different aggregation functions on two keys (columns). However, I received an error on my code. How can I aggregate on multiple columns in multilevel dataframe.
dic1 = {('count', 'N.A.'): {Period('1993-01', 'M'): 0,
  Period('1993-02', 'M'): 0,
  Period('1993-03', 'M'): 0},
 ('count', 'No'): {Period('1993-01', 'M'): 1,
  Period('1993-02', 'M'): 1,
  Period('1993-03', 'M'): 1},
 ('count', 'Yes'): {Period('1993-01', 'M'): 0,
  Period('1993-02', 'M'): 0,
  Period('1993-03', 'M'): 0},
 ('sum', 'N.A.'): {Period('1993-01', 'M'): nan,
  Period('1993-02', 'M'): nan,
  Period('1993-03', 'M'): nan},
 ('sum', 'No'): {Period('1993-01', 'M'): 6.5820000000000007,
  Period('1993-02', 'M'): 131.1865,
  Period('1993-03', 'M'): 133.31049999999999},
 ('sum', 'Yes'): {Period('1993-01', 'M'): nan,
  Period('1993-02', 'M'): nan,
  Period('1993-03', 'M'): nan}}

df1 = pd.DataFrame(dic1)

df1.to_timestamp(how='end').groupby(pd.TimeGrouper('A') ).agg(
{'count':['max', 'min', 'median', 'last'] ,
 'sum':['mean', 'max' , 'last']} )

error:  KeyError: 'sum'

A: A kind of hacky way to do this is to pull out all the count and sum columns respectively:
In [11]: agg_dict = {col: ['mean', 'max' , 'median', 'last'] for col in df1.columns[df1.columns.get_level_values(0) == "count"]}

In [12]: agg_dict.update({col: ['mean', 'max' , 'last'] for col in df1.columns[df1.columns.get_level_values(0) == "sum"]})

In [13]: g = df1.to_timestamp(how='end').groupby(pd.TimeGrouper('A') )

In [14]: g.agg(agg_dict)
Out[14]:
            sum                                                       count
           N.A.                  No                      Yes           N.A.                   No                  Yes
           mean max last       mean       max      last mean max last  mean max median last mean max median last mean max median last
1993-12-31  NaN NaN  NaN  90.359667  133.3105  133.3105  NaN NaN  NaN     0   0      0    0    1   1      1    1    0   0      0    0

A: You could flatten the column MultiIndex before grouping:
df1 = pd.DataFrame(dic1)
df2 = df1.to_timestamp(how='end')
df2 = df2.rename_axis(['operation', 'YN'], axis=1)
df3 = df2.stack(level='YN').reset_index('YN')
# operation     YN  count       sum
# 1993-01-31  N.A.      0       NaN
# 1993-01-31    No      1    6.5820
# 1993-01-31   Yes      0       NaN
# 1993-02-28  N.A.      0       NaN
# 1993-02-28    No      1  131.1865
# 1993-02-28   Yes      0       NaN
# 1993-03-31  N.A.      0       NaN
# 1993-03-31    No      1  133.3105
# 1993-03-31   Yes      0       NaN

Once you've moved the YN column index level into a column (by calling
stack/reset_index), you can approach the problem in the usual way:

import numpy as np
import pandas as pd
Period = pd.Period
nan = np.nan

dic1 = {('count', 'N.A.'): {Period('1993-01', 'M'): 0, Period('1993-02', 'M'): 0, Period('1993-03', 'M'): 0}, ('count', 'No'): {Period('1993-01', 'M'): 1, Period('1993-02', 'M'): 1, Period('1993-03', 'M'): 1}, ('count', 'Yes'): {Period('1993-01', 'M'): 0, Period('1993-02', 'M'): 0, Period('1993-03', 'M'): 0}, ('sum', 'N.A.'): {Period('1993-01', 'M'): nan, Period('1993-02', 'M'): nan, Period('1993-03', 'M'): nan}, ('sum', 'No'): {Period('1993-01', 'M'): 6.5820000000000007, Period('1993-02', 'M'): 131.1865, Period('1993-03', 'M'): 133.31049999999999}, ('sum', 'Yes'): {Period('1993-01', 'M'): nan, Period('1993-02', 'M'): nan, Period('1993-03', 'M'): nan}}

df1 = pd.DataFrame(dic1)
df2 = df1.to_timestamp(how='end')
df2 = df2.rename_axis(['operation', 'YN'], axis=1)
df3 = df2.stack(level='YN').reset_index('YN')

grouped = df3.groupby([pd.TimeGrouper('A'), 'YN'])
result = grouped.agg(
    {'count':['max', 'min', 'median', 'last'],  'sum':['mean', 'max' , 'last']})
result = result.unstack('YN')
print(result)

yields
            sum                                                      count  \
           mean                 max               last                 max
YN         N.A.         No Yes N.A.        No Yes N.A.        No Yes  N.A.
1993-12-31  NaN  90.359667 NaN  NaN  133.3105 NaN  NaN  133.3105 NaN     0

           ...
           ...      min        median        last
YN         ... Yes N.A. No Yes   N.A. No Yes N.A. No Yes
1993-12-31 ...   0    0  1   0      0  1   0    0  1   0


text:
Q: Understanding the logic of WaitGroups I'd like to understand if my logic around WaitGroups is correct and to see if there is a more efficient way of structuring my code. The aim is to perform the tasks as fast as possible.
My code populates a _urls channel which is populated via stdin. Then I'm spinning up two WaitGroups, one which reads from this _urls channel, and the other which reads from a _downloads channel, which is fed from a goroutine in the first WaitGroup.
Essentially the code looks like this:
    // declare channels
    _urls := make(chan string)
    _downloads := make(chan string)

    // first waitgroup with 2 goroutines
    var wg sync.WaitGroup
    for i := 0; i < concurrency; i++ {

        wg.Add(2)

        go func() {
            defer wg.Done()
            for url := range _urls {
                // perform GET request and inspect the responseBody
            }

        }()

        go func() {
            defer wg.Done()
            for url := range _urls {
                // perform a HEAD request to look for a certain file
                // if the file exists, send to the _downloads channel
                _downloads <- url
            }
        }()
    }

    // second waitgroup with 1 goroutine
    var dwg sync.WaitGroup
    for i := 0; i < concurrency; i++ {

        dwg.Add(1)

        go func() {
            defer wg.Done()
            for url := range _downloads {
                // perform the download
            }
        }()
    }

My concern is around whether this is an efficient way to feed the _downloads channel, or would it make more sense to just perform the download within the first WaitGroup.

A: I did something similar to this with the worker pool pattern, https://gobyexample.com/worker-pools.  Probably the right direction if you are looking to maximizing concurrency.
It abstracts jobs using go interfaces, so it could be a HEAD, GET, Download, or whatever else happens to make sense in the future.  A scheduler sends jobs to a dispatcher that manages the worker pool and sends results back.
Here is a link to the README and code.
It uses wait groups to track the number of active workers, not jobs. Workers execute a for {} loop and only exit when they read true from a done channel.  In this case, the use of the wait group is for a graceful shutdown.  In your example, many of the workers could be doing long downloads.  So your shutdown logic could wait for N jobs to be left before shutting down.
It may be overkill for your use cases.