text:
Q: Center placeholder text in TextBox I have multiple TextBoxes in my XAML-Page.
<TextBox Name="TxtCompanyId" PlaceholderText="FirmaId" Height="40" Margin="5" TextAlignment="Center"   />

The TextAlignment="Center" property only centers the text of the TextBox and not the placeholdertext/hint text. Is there a way to center both?

A: You can surely modify the defalut style and set PlaceholderTextContentPresenter's horizontal alignment to Center:
<ContentControl x:Name="PlaceholderTextContentPresenter" Grid.ColumnSpan="2" Content="{TemplateBinding PlaceholderText}" Foreground="{ThemeResource SystemControlPageTextBaseMediumBrush}" IsHitTestVisible="False" IsTabStop="False" Margin="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" Grid.Row="1" HorizontalAlignment="Center"/>

The complete modified style:
<Page.Resources>
    <Style x:Key="MyTextBoxStyl" TargetType="TextBox">
        <Setter Property="MinWidth" Value="{ThemeResource TextControlThemeMinWidth}"/>
        <Setter Property="MinHeight" Value="{ThemeResource TextControlThemeMinHeight}"/>
        <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}"/>
        <Setter Property="Background" Value="{ThemeResource SystemControlBackgroundAltHighBrush}"/>
        <Setter Property="BorderBrush" Value="{ThemeResource SystemControlForegroundChromeDisabledLowBrush}"/>
        <Setter Property="SelectionHighlightColor" Value="{ThemeResource SystemControlHighlightAccentBrush}"/>
        <Setter Property="BorderThickness" Value="{ThemeResource TextControlBorderThemeThickness}"/>
        <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
        <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
        <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Hidden"/>
        <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Hidden"/>
        <Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False"/>
        <Setter Property="Padding" Value="{ThemeResource TextControlThemePadding}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TextBox">
                    <Grid>
                        <Grid.Resources>
                            <Style x:Name="DeleteButtonStyle" TargetType="Button">
                                <Setter Property="Template">
                                    <Setter.Value>
                                        <ControlTemplate TargetType="Button">
                                            <Grid x:Name="ButtonLayoutGrid" BorderBrush="{ThemeResource TextBoxButtonBorderThemeBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{ThemeResource TextBoxButtonBackgroundThemeBrush}">
                                                <VisualStateManager.VisualStateGroups>
                                                    <VisualStateGroup x:Name="CommonStates">
                                                        <VisualState x:Name="Normal"/>
                                                        <VisualState x:Name="PointerOver">
                                                            <Storyboard>
                                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="GlyphElement">
                                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAccentBrush}"/>
                                                                </ObjectAnimationUsingKeyFrames>
                                                            </Storyboard>
                                                        </VisualState>
                                                        <VisualState x:Name="Pressed">
                                                            <Storyboard>
                                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonLayoutGrid">
                                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAccentBrush}"/>
                                                                </ObjectAnimationUsingKeyFrames>
                                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="GlyphElement">
                                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAltChromeWhiteBrush}"/>
                                                                </ObjectAnimationUsingKeyFrames>
                                                            </Storyboard>
                                                        </VisualState>
                                                        <VisualState x:Name="Disabled">
                                                            <Storyboard>
                                                                <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="ButtonLayoutGrid"/>
                                                            </Storyboard>
                                                        </VisualState>
                                                    </VisualStateGroup>
                                                </VisualStateManager.VisualStateGroups>
                                                <TextBlock x:Name="GlyphElement" AutomationProperties.AccessibilityView="Raw" Foreground="{ThemeResource SystemControlForegroundChromeBlackMediumBrush}" FontStyle="Normal" FontSize="12" FontFamily="{ThemeResource SymbolThemeFontFamily}" HorizontalAlignment="Center" Text="" VerticalAlignment="Center"/>
                                            </Grid>
                                        </ControlTemplate>
                                    </Setter.Value>
                                </Setter>
                            </Style>
                        </Grid.Resources>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="*"/>
                        </Grid.RowDefinitions>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="HeaderContentPresenter">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseLowBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BackgroundElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledTransparentBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BorderElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="BorderElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseLowBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledChromeDisabledLowBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="PlaceholderTextContentPresenter">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledChromeDisabledLowBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Normal"/>
                                <VisualState x:Name="PointerOver">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="BorderElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightChromeAltLowBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundHoverOpacity}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Focused">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="PlaceholderTextContentPresenter">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlPageTextChromeBlackMediumLowBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BackgroundElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlBackgroundChromeWhiteBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundFocusedOpacity}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="BorderElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAccentBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlForegroundChromeBlackHighBrush}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="RequestedTheme" Storyboard.TargetName="ContentElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="Light"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                            <VisualStateGroup x:Name="ButtonStates">
                                <VisualState x:Name="ButtonVisible">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="DeleteButton">
                                            <DiscreteObjectKeyFrame KeyTime="0">
                                                <DiscreteObjectKeyFrame.Value>
                                                    <Visibility>Visible</Visibility>
                                                </DiscreteObjectKeyFrame.Value>
                                            </DiscreteObjectKeyFrame>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="ButtonCollapsed"/>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Border x:Name="BackgroundElement" Background="{TemplateBinding Background}" Grid.ColumnSpan="2" Margin="{TemplateBinding BorderThickness}" Opacity="{ThemeResource TextControlBackgroundRestOpacity}" Grid.Row="1" Grid.RowSpan="1"/>
                        <Border x:Name="BorderElement" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Grid.ColumnSpan="2" Grid.Row="1" Grid.RowSpan="1"/>
                        <ContentPresenter x:Name="HeaderContentPresenter" Grid.ColumnSpan="2" ContentTemplate="{TemplateBinding HeaderTemplate}" Content="{TemplateBinding Header}" Foreground="{ThemeResource SystemControlForegroundBaseHighBrush}" FontWeight="Normal" Margin="0,0,0,8" Grid.Row="0" Visibility="Collapsed" x:DeferLoadStrategy="Lazy"/>
                        <ScrollViewer x:Name="ContentElement" AutomationProperties.AccessibilityView="Raw" HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}" HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}" IsTabStop="False" IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}" IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}" IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}" Margin="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" Grid.Row="1" VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}" VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}" ZoomMode="Disabled"/>
                        <!--Here below we modify the horizontal alignment-->
                        <ContentControl x:Name="PlaceholderTextContentPresenter" Grid.ColumnSpan="2" Content="{TemplateBinding PlaceholderText}" Foreground="{ThemeResource SystemControlPageTextBaseMediumBrush}" IsHitTestVisible="False" IsTabStop="False" Margin="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" Grid.Row="1" HorizontalAlignment="Center"/>
                        <Button x:Name="DeleteButton" BorderThickness="{TemplateBinding BorderThickness}" Grid.Column="1" FontSize="{TemplateBinding FontSize}" IsTabStop="False" Margin="{ThemeResource HelperButtonThemePadding}" MinWidth="34" Grid.Row="1" Style="{StaticResource DeleteButtonStyle}" Visibility="Collapsed" VerticalAlignment="Stretch"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <TextBox Name="TxtCompanyId" PlaceholderText="FirmaId" Height="40" Margin="5" TextAlignment="Center" Style="{StaticResource MyTextBoxStyl}"/>
</Grid>


text:
Q: Accessing custom objects in DomainService from client I am using Domain Service to fetch data from database from Silverlight Client.
In DomainService1.cs, I have added the following:
[EnableClientAccess()]
public class Product
{
    public int productID;
    public string productName;
    public List<Part> Parts = new List<Part>(); //Part is already present in Model designer
}

In DomainService1 class I added a new method to retrive a collection of the custom class object:
[EnableClientAccess()]
 public class DomainService1 : LinqToEntitiesDomainService<HELPERDBNEWEntities1>
 {
     ...
        public List<Product> GetProductsList(...)
        {
            List<Product> resultProducts = new List<Product>();
            ...
            return resultProducts;
        }
 }

From the silverlight client I am trying to access that method:
DomainService1 ds1 = new DomainService1();
var allproductList = ds1.GetProductsList(...);
ds1.Load<SLProduct>(allproductList).Completed += new EventHandler(Load_Completed); //Not correct usage

However it is not the correct way to call the new method. The reason I added a new class Product in DomainServices.cs is to have an efficient grouping. I cannot achieve the same using the model classes auto-generated by the entity framework.
How call I call the new method from the client?

A: I believe there is a similar question with an answer here:
Can a DomainService return a single custom type?
Also, here is some discussion about the overall problem of adding custom methods in a Domain Service:
http://forums.silverlight.net/t/159292.aspx/1

A: While I don't know what you mean by "it is not the correct way to call the new method", or if you're getting any errors, I thought maybe posting some working code might help.
My POCO
    public class GraphPointWithMeta
{
    [Key]
    public Guid PK { get; set; }
    public string SeriesName { get; set; }
    public string EntityName { get; set; }
    public double Amount { get; set; }

    public GraphPointWithMeta(string seriesName, string entityName, double amount)
    {
        PK = Guid.NewGuid();
        SeriesName = seriesName;
        EntityName = entityName;
        Amount = amount;
    }

    // Default ctor required.
    public GraphPointWithMeta()
    {
        PK = Guid.NewGuid();
    }
}

A method in the domain service (EnableClientAccess decorates the class)
        public IEnumerable<GraphPointWithMeta> CallingActivityByCommercial()
    {
        List<GraphPointWithMeta> gps = new List<GraphPointWithMeta>();
        // ...
        return gps;
    }

Called from the Silverlight client like
ctx1.Load(ctx1.CallingActivityByCommercialQuery(), CallingActivityCompleted, null);

client call back method
        private void CallingActivityCompleted(LoadOperation<GraphPointWithMeta> lo)
    {
        // lo.Entities is an IEnumerable<GraphPointWithMeta>
    }

A: I am not sure if your Product class is an actual entity or not.  From the way it is defined, it does not appear to be an entity.  My answer is assuming it is not an entity.  You will need to apply the DataMemberAttribute for your Product properties, and you wouldn't load the product list - load is for Entity Queries (IQueryable on the service side).  You would just invoke it like this (client side):
void GetProductList( Action<InvokeOperation<List<Product>>> callback)
{
    DomainService ds1 = new DomainService();
    ds1.GetProductsList(callback, null);//invoke operation call
}

And the domain service's (server side) method needs the InvokeAttribute and would look like this:
[EnableClientAccess]
public class MyDomainService
{
    [Invoke]
    public List<Product> GetProductList()
    {
        var list = new List<Product>();
        ...
        return list;
    }
}

And here is how your Product class might be defined (if it is not an entity):
public class Product
{
   [DataMember]
   public int productID;
   [DataMember]
   public string productName;
   [DataMember]
   public List<Part> Parts = new List<Part>(); // you might have some trouble here.
                           //not sure if any other attributes are needed for Parts,
                           //since you said this is an entity; also not sure if you
                           //can even have a list of entities or it needs to be an
                           //entity collection or what it needs to be.  You might
                           //have to make two separate calls - one to get the products
                           //and then one to get the parts.
}

Like I said, i am not sure what Product inherits from... Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Transition functions of trivial vector bundle I have a question on trivial vector bundles. The question is as follows:

Can we characterize the transition functions of a trivial vector
  bundle in some way?

To be very concrete: suppose we have a vector bundle $E$, say of rank $3$, on an algebraic variety $X$ (or manifold if you prefer), and  we look at trivial sub-bundles $0\to F\to E$ of rank $2$. What can we say about the transition functions of $F$ if we know those of $E$?
In this particular circumstance, we do have $3\times 3$ matrices at hand, and we want to produce $2\times 2$ matrices. The question is which ones are good.
At the beginning, I thought I could extend an argument of pure linear algebra: if we have an exact sequence of vector spaces $0\to V\to W\to W/V\to 0$, we can complete a basis $(e_1,e_2)$ of $V$ to a basis $(e_1,e_2,e_3)$ of $W$, so that $W\to W/V$ is represented by the row vector $e_3$ and $V\to W$ by the $3\times 2$ matrix containing $e_1,e_2$ written as columns. This didn't bring me anywhere, even because I can't figure how to use the triviality hypothesis.

A: Vector bundle is trivial iff the transition functions have the form $g_{ij}=g_{i}g_{j}^{-1}$ where $g_i \in {\rm{GL}}(n,\mathcal{O}_{U_i})$.
Composite the trivilization with $g_i^{-1}$ we get another trivilization and the new transition functions are $g_{ij}\equiv{1}$.

A: A bundle is trivial if and only if the cocycle of its transition functions becomes cohomologous to the trivial cocycle $1$ after suitable refinement of the covering on which the transition functions are defined.  I don't think one gets any additional information from knowing that the trivial bundle $F$ in question is a subbundle of a larger (possibly nontrivial) bundle $E$.  Also, it is not true in general that a basis of sections for a subbundle can be extended globally to a basis for a larger bundle.


text:
Q: what is settings in elastic search I am very new to elastic search. I need to know what is settings in the index.is it optional? what happens if we don't include it and what happens if we don't include shards in settings.

A: If you're new to Elasticsearch, it's important that you understand the basic terminologies of Elastic search first.
cluster – An Elasticsearch cluster consists of one or more nodes and is identifiable by its cluster name.
node – A single Elasticsearch instance. In most environments, each node runs on a separate box or virtual machine.
index – In Elasticsearch, an index is a collection of documents like the database in mysql.
shard – Because Elasticsearch is a distributed search engine, an index is usually split into elements known as shards that are distributed across multiple nodes. Elasticsearch automatically manages the arrangement of these shards. It also rebalances the shards as necessary, so users need not worry about the details.
replica – By default, Elasticsearch creates five primary shards and one replica for each index. This means that each index will consist of five primary shards, and each shard will have one copy.
Settings are generally used to define the overall architecture of your application. It differs based on the requirement of the application.
It contains the number of shards, no of Replica sets, etc. This information is helpful to design our Elastic according to the need of the application as below:
{
    "settings" : {
        "index" : {
            "number_of_shards" : 3,
            "number_of_replicas" : 2
        }
    }
}

For further clarification you can visit the official documentation of Elastic community, that is very well written here.
Setting in ElasticSearch


text:
Q: New notification coming below old notification in the tray I have two notifications. Upon posting the 1st notification, it comes on the top of the tray. When I post the 2nd notification, it comes below the first notification. Ideally it should come on top of the first notification. I am using same priority for both notifications.
TargetSdkVersion =26, CompileSdkVersion = 26 and Support Library Version = 26.1.0
Please check the code.
int firstNotifyId = 1;
String channelId = "Default";

final NotificationCompat.Builder firstBuilder = new NotificationCompat.Builder(this, channelId)
    .setContentTitle("Creating First Notification")
    .setContentText("Creating First Notification")
    .setPriority(NotificationManager.IMPORTANCE_MAX)
    .setWhen(System.currentTimeMillis())
    .setSmallIcon(R.drawable.notification_icon);

int secondNotifyId = 2;
final NotificationCompat.Builder secondBuilder = new NotificationCompat.Builder(this,channelId)
    .setContentTitle("Creating Second Notification")
    .setContentText("Creating Second Notification")
    .setPriority(NotificationManager.IMPORTANCE_MAX)
    .setWhen(System.currentTimeMillis())
    .setSmallIcon(R.drawable.notification_icon);

findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    mNotificationManager.notify(firstNotifyId, firstBuilder.build());
  }
});

findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    mNotificationManager.notify(secondNotifyId, secondBuilder.build());
  }
});

Checked on Android 6 and Android 7.1. and found that the behavior is same.

A: (I do not have enough points to put this in a comment)
The notifications are being issued based on OnClick event.
In the question you have not mentioned about the sequence of the button clicks.
Can you share an image of how the buttons have been placed? Are button1 and button2 on different activity pages or are they placed in the same layout?
Is there possibility of user clicking button 2 first? Please share more what the app looks like in a video, or probably rest of the code.


text:
Q: How to keep exactly one file in a directory? I have recovered files and currently they have this structure:
root/MD5_of_file1/file1
root/MD5_of_file2/file2
...
root/MD5_of_filen/filen

Obviously, duplicates are now in the same folder. The filename contains no information, just the block number at which it was found during the recovery.
I want to flatten the structure, keeping only one file for each MD5. How could I do this efficiently ?
Just to be clear, here are some actual data:
feceee0fc150d191c5fd48ca6acee2f6
feceee0fc150d191c5fd48ca6acee2f6/f225407559.odt
feceee0fc150d191c5fd48ca6acee2f6/f94654911.odt
e905bb0a76c0055a2be1b8285d39c715
e905bb0a76c0055a2be1b8285d39c715/f0702423.odt
e905bb0a76c0055a2be1b8285d39c715/f26479232.odt
e905bb0a76c0055a2be1b8285d39c715/f3084695.odt

I want to flatten to something like this:
f225407559.odt
f0702423.odt

but there are no guarantees that filenames are distinct. Files could easily be renamed to the corresponding MD5 of their content, which is already computed, as it is the name of the folder in which they currently are.

A: for i in *(/); do  mv $i/*([1]) $i.odt;  rm -rf $i; done

It's using zsh glob qualifier: *([1]) selects the first file in alphanumerical order

A: In two steps:
perl-rename 's;/([^/]*)/[^/]*$;/\1_file;' foo/**/*
rmdir foo/**/

Example:
$ tree foo
foo
├── e905bb0a76c0055a2be1b8285d39c715
│   ├── f0702423.odt
│   ├── f26479232.odt
│   └── f3084695.odt
└── feceee0fc150d191c5fd48ca6acee2f6
    ├── f225407559.odt
    └── f94654911.odt

2 directories, 5 files
$ perl-rename -n 's;/([^/]*)/[^/]*$;/\1_file;' foo/**/*
foo/e905bb0a76c0055a2be1b8285d39c715/f0702423.odt -> foo/e905bb0a76c0055a2be1b8285d39c715_file
foo/e905bb0a76c0055a2be1b8285d39c715/f26479232.odt -> foo/e905bb0a76c0055a2be1b8285d39c715_file
foo/e905bb0a76c0055a2be1b8285d39c715/f3084695.odt -> foo/e905bb0a76c0055a2be1b8285d39c715_file
foo/feceee0fc150d191c5fd48ca6acee2f6/f225407559.odt -> foo/feceee0fc150d191c5fd48ca6acee2f6_file
foo/feceee0fc150d191c5fd48ca6acee2f6/f94654911.odt -> foo/feceee0fc150d191c5fd48ca6acee2f6_file
$ perl-rename 's;/([^/]*)/[^/]*$;/\1_file;' foo/**/*
$ rmdir foo/**/
rmdir: failed to remove 'foo/': Directory not empty
$ tree foo
foo
├── e905bb0a76c0055a2be1b8285d39c715_file
└── feceee0fc150d191c5fd48ca6acee2f6_file

0 directories, 2 files

Another way, using find, sort and awk:
find foo -type f |
  sort -k2,2 -u -t/ |
  awk -F/ -v OFS=/ '{path=$0; file=$NF; NF--; cmd = "cp " path " " $0 "_" file;  ; system(cmd); system("rm -r "$0)}'

Example:
$ find foo -type f | sort -k2,2 -u -t/ | awk -F/ -v OFS=/ '{path=$0; file=$NF; NF--; cmd = "cp " path " " $0 "_" file;  ; print cmd; print "rm -r "$0}'
cp foo/e905bb0a76c0055a2be1b8285d39c715/f3084695.odt foo/e905bb0a76c0055a2be1b8285d39c715_f3084695.odt
rm -r foo/e905bb0a76c0055a2be1b8285d39c715
cp foo/feceee0fc150d191c5fd48ca6acee2f6/f225407559.odt foo/feceee0fc150d191c5fd48ca6acee2f6_f225407559.odt
rm -r foo/feceee0fc150d191c5fd48ca6acee2f6
$ find foo -type f | sort -k2,2 -u -t/ | awk -F/ -v OFS=/ '{path=$0; file=$NF; NF--; cmd = "cp " path " " $0 "_" file;  ; system(cmd); system("rm -r "$0)}'
$ tree foo
foo
├── e905bb0a76c0055a2be1b8285d39c715_f3084695.odt
└── feceee0fc150d191c5fd48ca6acee2f6_f225407559.odt

0 directories, 2 files


text:
Q: "Extra argument 'foo' in call" OR "'[NSObject : AnyObject]!' is not a subtype of 'Dictionary'" I've read all the "extra argument in call" posts I can find, but am still banging my head against this one. I have a method that looks like this:
// Objective-C
+ (void)get:(NSString *)url params:(NSDictionary *)params completion:(NetworkCompletion)completion

// Swift autocomplete
GenericWebService.get(url: String!, params: [NSObject : AnyObject]!, completion: (([NSObject : AnyObject]!, NSError!) -> Void)!)

My first attempt to use this method in Swift looks like this...
GenericWebService.get("", params: ["foo":"bar"], completion: {
    (responseDictionary: Dictionary, connectionError: NSError) -> Void in
        // foo
    })

...and yielded the error Extra argument 'params' in call
So I tried to provide a better type match for params ([NSObject:AnyObject])...
let params: [NSObject:AnyObject] = ["foo":"bar"]
GenericWebService.getURL("", params: params, completion: {
    (responseDictionary: Dictionary, connectionError: NSError) -> Void in
        // foo
    })

...which yields '[NSObject : AnyObject]!' is not a subtype of 'Dictionary<Key, Value>'
What boneheaded mistake am I making? :)

A: I believe your second error is complaining about the type of your completion block, not the type of the params parameter. This works for me:
GenericWebService.get("", params: ["foo": "bar"], completion: {
    (a: [NSObject: AnyObject]!, b: NSError!) in
})

A: The problem lies with the closure argument.  If you make the parameters match exactly, it works:
GenericWebService.get("", params: ["foo":"bar"]) {
    (responseDictionary: [NSObject:AnyObject]!, connectionError: NSError!) -> Void in
    // foo
}

But rather than explicitly type them, it may be easier just to leave Swift to do it for you:
GenericWebService.get("", params: ["foo":"bar"]) {
    responseDictionary, connectionError in
    // foo
}

A: In a playground, I found that this syntax also compiles correctly:
GenericWebService.get("", params: ["foo" : "bar"], completion: {
        (responseDictionary _: [NSObject : AnyObject]!, connectionError _: NSError!) -> Void in
    })


text:
Q: parsing un structured logs in to dataset in flink I have some logs like below
2021-08-16 16:56:37 info [614289000000000020ab22baa4a1cfb7,4c8b36453209aef4] -- [main] c.g.c.uservalidatorfactoryimpl - {"userid": "1", "msg": "action", "status": "rcvd"}
2021-08-16 16:56:38 info [614289000000000020ab22baa4a1cfb7,4c8b36453209aef4] -- [main] c.g.c.uservalidatorfactoryimpl - {"userid": "1", "msg": "response", "status": "processed"}

I need to read this from the file and convert to dataset which looks something like below
2021-08-16 16:56:37,[614289000000000020ab22baa4a1cfb7,4c8b36453209aef4],  1 , action , rcvd
2021-08-16 16:56:38,[614289000000000020ab22baa4a1cfb7,4c8b36453209aef4],  1 , response , processed

 val dataset = env.readTextFile("text.log")
    dataset.print()

Since the log file is not structured, is it possible to parse and clean the logs into CSV format using any of the flink APIS?
it will be really helpful if someone can through light on any other best way convert in to csv format so that it can be loaded for further processing?

A: Flink has integrated RowCsvInputFormat to read csv format files, and supports setting the file path and csv schema information
Path PATH = new Path("an/ignored/file/");
String fileContent = "abc|def|ghijk\nabc||hhg\n|||\n||";

TypeInformation[] fieldTypes =
        new TypeInformation[] {
            BasicTypeInfo.STRING_TYPE_INFO,
            BasicTypeInfo.STRING_TYPE_INFO,
            BasicTypeInfo.STRING_TYPE_INFO
        };

RowCsvInputFormat.Builder builder =
        RowCsvInputFormat.builder(new RowTypeInfo(fieldTypes), PATH).setFieldDelimiter('|');
RowCsvInputFormat format = builder.build();

env.createInput(format).print()


text:
Q: How to fix 'An unexpected error has occurred. Please try again(7515006A)' at Google Play Store Application Publish I get the error message: PlayStore App Publish

An unexpected error has occurred. Please try again. (7515006A)"

when I try to upload .aab or .apk on Google play Console to create a new release. I don't what that means and please kindly assist how to fix that.
Error Image:

The loading keep showing and never stop

A: It's because of the new Google Play Console. Try one of the following

*

*Clear Browser Caches and try again

*If the 1st method not working try to upload in Incognito windows

Thanks

A: There seems to be an issue with the new Google Play Console UI.
An alternative approach to the one Zi Sar K Nar suggested is to switch to the old console UI. You can do this by navigating from:

Drawer > Use classic Play Console

Sadly, Google is killing the old console as from November 2, 2020. Hopefully, the bugs on the new console would be fixed before then.

A: Encountered a similar issue today except the code listed was 55E6FBB1.
I went back to the "Dashboard" tab and saw that it actually was uploaded despite the error, so check this before you start clearing caches.


text:
Q: no preview for ContentVersion when inserting from Apex I'm using the following code to generate ContentVersion.
    String title = 'sample file.txt';
    ContentVersion contentVersion = new ContentVersion(
            VersionData = Blob.valueOf(jsonBodyPretty),
            Title = title,
            ContentLocation = 'S',
            PathOnClient = title
    );

    insert contentVersion;

But when I try to preview it from Salesforce 'No Preview is Available'.
If I download file and re-upload - everything is ok.
Have someone was able to create Previews from Apex for ContentVersion?

A: you need the contentDocumentID for the preview, after insert the contentVersion get the ContentDocumentId
Id cdID = [SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id =: contentVersion.Id].ContentDocumentId;
I hope this help you.


text:
Q: ubuntu 16.04 shows red exclamation mark on printer I am not able to print anything from ubuntu 16.04 machine. It is showing red exclamation mark as shown in the image. Machine is connected with printer via LAN.
When I click on add (+) button then my printer does not show in network printer option. See image.
Please suggest some workaround.


text:
Q: SublimeLinter not working I installed SublimeLinter for sublime text 3. After install i add the following code in my user settings
 "sublimelinter": true,
        "sublimelinter_executable_map": {
            "php": "D:/xampp/xampp/php/php.exe"
        },

but php code not linting.
Thanks for help!

A: Please read the entire SublimeLinter documentation, especially the sections on installation and settings. SublimeLinter itself is only a framework for linters. The linters themselves are distributed as independent Sublime Text 3 plugins.
For PHP, the most popular linter is SublimeLinter-php, which uses php -l for linting. Install it via Package Control, then read through the settings documentation for full details on how to configure the linter. I'm not sure where you got the settings you mentioned in your question, but they are incorrect. If you open Preferences -> Package Settings -> SublimeLinter -> Settings-User you'll find that most of the settings are already there. The documentation describes how to set the path to php.exe, and set everything else up. The initial setup process does take some time, but performed correctly you shouldn't have any issues going forward.

A: Just to help if someone have the same problem.
I made it work this way (Sublime Text 3):

*

*Go to Preferences > Package Settings > Sublime Linter > Settings

*Add this code on Settings-User with your php.exe path

// SublimeLinter Settings - User
{
    "paths": {
        "windows": ["C:\\wamp\\bin\\php\\php7.2.14"]
    }
}

For example if you're using wamp with php7.2.14
Take a look at the documentation site


text:
Q: Difference between class_name and source I am really confused about the difference between class_name and source options of has_many.
For class_name, it is said on the API doc that:

Specify the class name of the association. Use it only if that name can't be inferred from the association name. So has_many :products will by default be linked to the Product class, but if the real class name is SpecialProduct, you'll have to specify it with this option.

And for source:

Specifies the source association name used by has_many :through queries. Only use it if the name cannot be inferred from the association. has_many :subscribers, through: :subscriptions will look for either :subscribers or :subscriber on Subscription, unless a :source is given.

It seems that these two options have the same function, that is, to specify the class name of the association, except that source is only used for has_many :through, and class_name can be set in every has_many association.
If so, why it is necessary for has_many to have these two options with the very similar functions? Why just use class_name only to specify all the association name?
I searched in many places but could not find the answer. I also read Rails: difference between :source => ?? and :class_name => ?? in models ,but it still does not explain why it is necessary for the existences of both class_name and source.
Thanks in advance.

A: The key point is class_name specify the class name of the association where source specifies the source association name.
Example:
lass User < ActiveRecord::Base
  has_many :listing_managers
  has_many :managed_listings, through: :listing_managers, source: :listing
end

class Listing < ActiveRecord::Base
  has_many :listing_managers
  has_many :managers, through: :listing_managers, source: :user
end

class ListingManager < ActiveRecord::Base
  belongs_to :listing
  belongs_to :user
end

On the above code example user is class_name. When we are declaring has_many :managers, through: :listing_managers then rails is expecting there is either manager or managers association with in ListingManager . Since we want to use user association for creating managers we have to tell it to rails that make managers association using ListingManager's user association.
Here is another example that use class_name option
class User < ActiveRecord::Base
  has_many :listing_managers
  has_many :listings, through: :listing_managers
end

class Listing < ActiveRecord::Base
  has_many :listing_managers
  has_many :managers, through: :listing_managers
end

class ListingManager < ActiveRecord::Base
  belongs_to :listing
  belongs_to :manager, class_name:"User"
end

On the above code we are declaring belongs_to :manager association on ListingManager but there is no model named manager that's why we have to set class_name option. Now, since we have manager association on
ListingManager we don't need to set source option on Listing that we  had to do on first example.
Hope above will help someone.


text:
Q: How do I parse parameters submitted by a form in Nickel.rs? I'm building a web application with Rust and Nickel.rs.  I have a route which submits a form with a POST request.
I would like to be able to use the request data (the data returned from the form), but I'm not sure how to go about it.
// This works and prints 'email=bar&password=foo'
// but how do I get the values separately?
router.post("/login", middleware! { |request, response|
    let mut body = String::new();
    request.origin.read_to_string(&mut body).unwrap();
    format!("{}", body)
});

A: I found a solution which works for now, although I don't know if it is the "right" solution.
extern crate url;
use url::*;

use std::collections::HashMap;

router.post("/login", middleware! { |request, response|
    let mut body = String.new();
    request.origin.read_to_string(&mut body).unwrap();

    let mut data = HashMap::new();
    for (key, value) in form_urlencoded::parse(body.as_bytes()) {
        data.insert(key, value);
    }

     println!("{:?}", data) # {'password': 'bar', 'email': 'far'}
});

A: I would do it this way:
router.post("/login", middleware! { |request, response|
    let form_body = try_with!(response, request.form_body());
    let user = form_body.get("username").unwrap_or_default();
    let pass = form_body.get("password").unwrap_or_default();
    ...
}

I wish I knew what response is doing in that try_with! though.


text:
Q: Problem using 1:M -> M:1 in Entity Framework I've set up a relational db using MSSQL and I'm trying to use the Entity Framework to talk to it, but I'm having some issues. (This is my first EF project).
I'm able to insert data in both the Machines table and the Contacts table using:
_db.AddToMachines(new Machine { MachineModelId = 0, Owner = "Test", SerialNo = "34242341" });
_db.SaveChanges();

But how can I add Contacts to the Machine?

A: Your Machines entity should have a navigation property called Contacts and vice versa. Just add the objects to these properties.
Example:
var machine = new Machine { MachineModelId = 0,
                            Owner = "Test", SerialNo = "34242341" };
var contact = new Contact { ... };
machine.Contacts.Add(contact);

_db.AddToMachines(machine);
_db.SaveChanges();

This should insert a new entry in the Machines table, a new entry in the Contacts table and a new entry in the MachineContacts table referencing the new entries in the two other tables.


text:
Q: Camel routing with custom method Im trying to route an object based on three different criteria.
My questions are:
1)why if I have the i.e. routing the object goes to one of the filters in a random way and not linear?
2)how should I do it if this does not work (the example), if I do it with "choice" and "when", can I use a custom method to route? like im using in filter in this example
Many thanks
Example shown:
camelContext.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {

    from("activemq:cfes.queue").filter().method(CustomCamelFilter.class, "methodOne")
        .to("file://c:/u01/tomcat_conf/folder1");

    from("activemq:cfes.queue").filter().method(CustomCamelFilter.class, "methodTwo")
        .to("file://c:/u01/tomcat_conf/folder2");

    from("activemq:cfes.queue").filter().method(CustomCamelFilter.class, "methodThree")
        .to("file://c:/u01/tomcat_conf/folder3");

A: It is incorrect to use the .filter() pattern here, when it seems you indeed should use the .choice() pattern instead, like this:
.choice()
    .when(method(MyBean.class, "methodOne")).log("HELLO1")
    .when(method(MyBean.class, "methodTwo")).log("HELLO2")
    .when(method(MyBean.class, "methodThree")).log("HELLO3")
    .otherwise().log("OOPS!")
.end()


text:
Q: skip and limit function not work in rails rake file Hi am learner of rails and mongodb. i am doing application on rails with mongodb as backend.
am having huge content of data to retrieve on single request at the time am having error is "cursor error", for that i used a trick is to partition of all data to small content. on that concept am having a bug, my code is to separate
     competitionsAry = NFL_Competition.where(sdi_sport_id: teamSdi_Sport_id)

 puts "Total competitions:" + competitionsAry.count.to_s // it has 2330 count on this step

      execCount = competitionsAry.count / 100

      if competitionsAry.count % 100 != 0

          execCount += 1

      end

      execCount.times do |ctr|

        skipValue = ctr + 100

        competitions = competitionsAry.skip(skipValue).limit(100)

 puts "Now the competition length is: " + competitions.length.to_s // here also same amount of 2330 data

i know "competitions = competitionsAry.skip(skipValue).limit(100)" here is the problem.
   skip and limits functions are not working. even i tried "competitions = NFL_Competition.skip(skipValue).limit(100)" no result what am exception can anyone help how to solve this and how to use skip and limit function on rails. thank you in advance.

A: ya i got it i used ruby array slice concept in this by that.
competitions = competitionsAry[skipValue,100]


text:
Q: How do I run a selenium test case using Jenkins, on a mac? Following this tutorial :https://www.softwaretestinghelp.com/integration-of-jenkins-with-selenium-webdriver/
Its windows based and I am using a mac.
I have my test case written in java.
It works fine when run using eclipse but I want to configure a build on jenkins to run it.
Can someone help me?
The steps in the lesson don't work for me.
I have tried creating a shell file to run it but I am a bit unsure on how to do so.

A: I managed to solve it using Maven!
Just follow this tutorial as there is no point in me repeating these steps.
https://www.guru99.com/maven-jenkins-with-selenium-complete-tutorial.html
Thanks


text:
Q: agent.auth before each test in a describe block The following works:
describe('My App', function() {
  describe('when logged in', function() {
    it('should allow registered user to make a thing', function(done) {
      agent.post('/make-a-thing')
      .auth('testusername', 'validuserpass')
      .send({thingName:'mythingname'})
      .expect(201)
      .end(function(err, res) {
        if (err) return done(err);
        res.body.should.have.property('thingUrl').and.to.match(/thing\/[0-9a-f]+$/);
        done();
      });
    });
  });
});

Now, if I want to add more and more tests to the "when logged in" block, I don't want to repeat the .auth('testusername', 'validuserpass') line every time. I should put the auth code in the beforeEach, because that's what beforeEach is for.
So I tried this:
describe("My App", function() {

  describe('when logged out', function() {
    it('should disallow anonymous user from doing things', function(done) {
      agent.post('/do-things')
      .send({thingName:'mythingname'})
      .expect(403)
      .end(function(err, res) {
        if (err) return done(err);
        done();
      });
    });
  });

  describe('when invalid user', function() {
    beforeEach(function(done) {
      agent.auth('invalidusername', 'invaliduserpass');
      done();
    });

    it('should disallow unrecognized user from doing things', function(done) {
      agent.post('/do-things')
      .send({thingName:'mythingname'})
      .expect(403)
      .end(function(err, res) {
        if (err) return done(err);
        done();
      });
    });
  })

  describe('when logged in', function() {
    beforeEach(function(done) {
      agent.auth('testusername', 'validuserpass');
      done();
    });

    it('should allow registered user to make a thing', function(done) {
      agent.post('/make-a-thing')
      .send({thingName:'mythingname'})
      .expect(201)
      .end(function(err, res) {
        if (err) return done(err);
        res.body.should.have.property('thingUrl').and.to.match(/thing\/[0-9a-f]+$/);
        done();
      });
    });

    it('should require name attribute to create a thing', function(done) {
      agent.post('/make-a-thing')
      .send({notaname:'notathingname'})
      .expect(409)
      .expect('Content-Type', /json/)
      .end(function(err, res) {
        if (err) return done(err);
        done();
      });
    });
  });

});

What happens is agent.auth is not defined. I think the auth method is defined in the result of auth.post.
Is there a way to do this?

A: For the record, here's what I did to solve this. I modified supertest's agent object and the Request prototype. agent now has a method called auth which causes Request.end to call auth first before ending, then reverts Request.end back to its original state.
configure.js
var app = require('app'),
    supertest = require('supertest');

// global
agent = supertest.agent(app);

(function(Request) {
  'use strict';

  (function(_end) {
    agent.auth = function() {
      var authArgs = arguments;
      Request.end = function() {
        var endArgs = arguments;
        var endResult = _end.apply(this.auth.apply(this, authArgs), endArgs);
        Request.end = _end;
        return endResult;
      };
      return agent;
    };
  })(Request.end);
})(agent.post('').constructor.prototype);

app-test.js
describe("My App", function() {

  describe('when logged out', function() {
    it('should disallow anonymous user from doing things', function(done) {
      agent.post('/do-things')
      .send({thingName:'mythingname'})
      .expect(403)
      .end(function(err, res) {
        if (err) return done(err);
        done();
      });
    });
  });

  describe('when invalid user', function() {
    beforeEach(function(done) {
      agent.auth('invalidusername', 'invaliduserpass');
      done();
    });

    it('should disallow unrecognized user from doing things', function(done) {
      agent.post('/do-things')
      .send({thingName:'mythingname'})
      .expect(403)
      .end(function(err, res) {
        if (err) return done(err);
        done();
      });
    });
  })

  describe('when logged in', function() {
    beforeEach(function(done) {
      agent.auth('testusername', 'validuserpass');
      done();
    });

    it('should allow registered user to make a thing', function(done) {
      agent.post('/make-a-thing')
      .send({thingName:'mythingname'})
      .expect(201)
      .end(function(err, res) {
        if (err) return done(err);
        res.body.should.have.property('thingUrl').and.to.match(/thing\/[0-9a-f]+$/);
        done();
      });
    });

    it('should require name attribute to create a thing', function(done) {
      agent.post('/make-a-thing')
      .send({notaname:'notathingname'})
      .expect(409)
      .expect('Content-Type', /json/)
      .end(function(err, res) {
        if (err) return done(err);
        done();
      });
    });
  });

});

My tests are run like this, so the configure script is executed first:
mocha tests/configure.js tests/*-test.js


text:
Q: How to use secondary user actions with to improve recommendations with Spark ALS? Is there a way to use secondary user actions derived from the user click stream to improve recommendations when using Spark Mllib ALS?
I have gone through the explicit and implicit feedback based example mentioned here : https://spark.apache.org/docs/latest/mllib-collaborative-filtering.html that uses the same ratings RDD for the train() and trainImplicit() methods.
Does this mean I need to call trainImplicit() on the same model object with a RDD(user,item,action) for each secondary user action? Or train multiple models , retrieve recommendations based on each action and then combine them linearly?
For additional context, the crux of the question is if Spark ALS can model secondary actions like Mahout's spark item similarity job. Any pointers would help.

A: Disclaimer: I work with Mahout's Spark Item Similarity.
ALS does not work well for multiple actions in general. First an illustration. The way we consume multiple actions in ALS is to weight one above the other. For instance buy = 5, view = 3. ALS was designed in the days when ratings seemed important and predicting them was the question. We now know that ranking is more important. In any case ALS uses predicted ratings/weights to rank results. This means that a view is really telling ALS nothing since a rating of 3 means what? Like? Dislike? ALS tries to get around this by adding a regularization parameter and this will help in deciding if 3 is a like or not.
But the problem is more fundamental than that, it is one of user intent. When a user views a product (using the above ecom type example) how much "buy" intent is involved? From my own experience there may be none or there may be a lot. The product was new, or had a flashy image or other clickbait. Or I'm shopping and look at 10 things before buying. I once tested this with a large ecom dataset and found no combination of regularization parameter (used with ALS trainImplicit) and action weights that would beat the offline precision of "buy" events used alone.
So if you are using ALS, check your results before assuming that combining different events will help. Using two models with ALS doesn't solve the problem either because from buy events you are recommending that a person buy something, from view (or secondary dataset) you are recommending a person view something. The fundamental nature of intent is not solved. A linear combination of recs still mixes the intents and may very well lead to decreased quality.
What Mahout's Spark Item Similarity does is to correlate views with buys--actually it correlates a primary action, one where you are clear about user intent, with other actions or information about the user. It builds a correlation matrix that in effect scrubs the views of the ones that did not correlate to buys. We can then use the data. This is a very powerful idea because now almost any user attribute, or action (virtually the entire clickstream) may be used in making recs since the correlation is always tested. Often there is little correlation but that's ok, it's an optimization to remove from the calculation since the correlation matrix will add very little to the recs.
BTW if you find integration of Mahout's Spark Item Similarity daunting compared to using MLlib ALS, I'm about to donate an end-to-end implementation as a template for Prediction.io, all of which is Apache licensed open source.


text:
Q: Why I have StackOverflow in DFS? I'm trying to implement a DFS algorithm in c++. I use it to answer the question: "are two vertexes connected or not?", but something went wrong.
Sometimes the program gives correct answer, sometimes crashes with 0xC00000FD code. I've google it and know now, that is a StackOverflow error.
Here's the code:
const int N = 4;                     // The minimal example I've know is a graph with 4 vertexes.
std::vector<int> graph[N];           // Our graph
int start = 0;                       // The start vertex
int finish = N - 1;                  // The finish vertex

bool dfs(int old, int v) {           // The DFS function
    if (v == finish)
        return true;
    bool ans = false;
    for (int u : graph[v]) {
        if (u != old)
            ans |= dfs(v, u);
    }
    return ans;
}

void init_graph_ok() {               // With this graph all works fine
    graph[0] = { 1 };
    graph[1] = { 2 };                // 0 (st) -- 1 -- 2 -- 3 (fin)
    graph[2] = { 3 };
    graph[3] = {};
}
void init_graph_bad() {              // With this graph I have StackOverflow
    graph[0] = { 1, 2 };
    graph[1] = { 2, 0 };             // 0 (st) -- 1 -- 2 -- 3 (fin)
    graph[2] = { 0, 3 };             // ^--------------^
    graph[3] = {};
}

int main() {
    init_graph_bad();
//  init_graph_ok();
    std::cout << dfs(-1, 0);
}

A: This is because your code is visiting a particular node more than once, because of which your code runs into an infinite recursion.
Because of the infinite recursive calls, the stack memory gets filled up completely and finally results into a stack overflow error.
Solution: Allow every node to be visited almost once by using a visited array as follows:
const int N = 4;                     // The minimal example I've know is a graph with 4 vertexes.
std::vector<int> graph[N];           // Our graph
int start = 0;                       // The start vertex
int finish = N - 1;                  // The finish vertex

bool visited[N+1];

bool dfs(int old, int v) {           // The DFS function

    if(visited[v]){
        return true;
    }
    visited[v] = true;

    if (v == finish)
        return true;

    bool ans = false;

    for (int u : graph[v]) {
        if (u != old)
            ans |= dfs(v, u);
    }

    return ans;
}

void init_graph_ok() {               // With this graph all works fine
    graph[0] = { 1 };
    graph[1] = { 2 };                // 0 (st) -- 1 -- 2 -- 3 (fin)
    graph[2] = { 3 };
    graph[3] = {};
}
void init_graph_bad() {              // With this graph I have StackOverflow
    graph[0] = { 1, 2 };
    graph[1] = { 2, 0 };             // 0 (st) -- 1 -- 2 -- 3 (fin)
    graph[2] = { 0, 3 };             // ^--------------^
    graph[3] = {};
    memset(visited, false, N+1);
}

int main() {
    init_graph_bad();
//  init_graph_ok();
    std::cout << dfs(-1, 0);
}

PS: Do not worry about cycles, as this logic will take care of cycles as well.


text:
Q: Uniform convergence to show an integral I struggled with the following question, and would like to know how to do it correctly.
The exponential function is defined by $e^x = \sum_{n=0}^{\infty}\frac{x^n}{n!}$.  Assuming that $\lim_{N\to\infty} \sum_{n=0}^N \frac{x^n}{n!}$ converges uniformly on every interval of the form $[-M,M]$, show that $\int_0^x e^t\ dt = e^x - 1$.
My strategy that I believe was incorrect was to say since $f_n \rightarrow f$ is uniformly convergent then $\int f_n=\int f$
Then I said because of this, $\lim_{n\to\infty}\sum_{n=0}^{\infty} \int_{0}^{x} \frac{t^n}{n!}dt=\int_{0}^{x}e^{x}dx=e^{x}-1$ but I realize I have not really "shown" anything.
Well, what is the correct way to solve this problem?

A: $\int_0^x\sum_{n=0}^N \frac{t^n}{n!}dt=\sum_{n=0}^N \frac{x^{n+1}}{(n+1)!}=\sum_{n=0}^{N+1}\frac{x^n}{n!}-1\to e^x-1$
The convergence is uniform on any finite interval.


text:
Q: How to increase button height i am trying to change the height of two buttons as you can see on the very bottom of the screen. I placed them in a row since i need the side by side and placed that row in a sized box so i can set the width and height for the buttons to fill.
They fill up the width but whenever i try to change the height it keeps giving a render layout error. Does the "Expanded" widget not work for height?
import 'package:/styles/style.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class RelationshipPreferences extends StatelessWidget {
  const RelationshipPreferences({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: SizedBox(
        width: width,
        height: height,
        child: Stack(
          children: [
            Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomLeft,
                  colors: [Color(0xFF1F1F1F), Color(0xFF1F1F1F)],
                ),
                image: DecorationImage(
                  image: AssetImage("lib/assets/images/topbig.png"),
                  alignment: Alignment.topCenter,
                ),
              ),
            ),
            Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('lib/assets/images/toptop.png'),
                  alignment: Alignment.topCenter,
                ),
              ),
            ),
            Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('lib/assets/images/top.png'),
                  alignment: Alignment.topCenter,
                ),
              ),
            ),
            Positioned(
              top: 70.0,
              left: 30.0,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                mainAxisSize: MainAxisSize.max,
                children: [
                  InkWell(
                    onTap: () {},
                    child: Container(
                      decoration: BoxDecoration(),
                      child: ClipRRect(
                        // borderRadius: BorderRadius.circular(10.0),
                        child: Image.asset('lib/assets/images/bluetick.png',
                            width: 40.0, height: 40.0),
                      ),
                    ),
                  ),
                  Text(
                    "━━━━━",
                    style: TextStyle(color: kcPrimaryColor),
                  ),
                  InkWell(
                    onTap: () {},
                    child: Container(
                      decoration: BoxDecoration(),
                      child: ClipRRect(
                        // borderRadius: BorderRadius.circular(10.0),
                        child: Image.asset('lib/assets/images/purplewatch.png',
                            width: 40.0, height: 40.0),
                      ),
                    ),
                  ),
                  Text(
                    "━━━━━",
                    style: TextStyle(color: kcMediumGreyColor),
                  ),
                  InkWell(
                    onTap: () {},
                    child: Container(
                      decoration: BoxDecoration(),
                      child: ClipRRect(
                        // borderRadius: BorderRadius.circular(10.0),
                        child: Image.asset('lib/assets/images/numba3.png',
                            width: 40.0, height: 40.0),
                      ),
                    ),
                  ),
                  Text(
                    "━━━━━",
                    style: TextStyle(color: kcMediumGreyColor),
                  ),
                  InkWell(
                    onTap: () {},
                    child: Container(
                      decoration: BoxDecoration(),
                      child: ClipRRect(
                        // borderRadius: BorderRadius.circular(10.0),
                        child: Image.asset('lib/assets/images/numba4.png',
                            width: 40.0, height: 40.0),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Positioned(
                top: 130.0,
                left: 25.0,
                child: Row(
                  children: [
                    Text(
                      "Profile",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 15.0,
                        fontWeight: FontWeight.bold,
                        fontFamily: 'Montserrat',
                      ),
                    ),
                    SizedBox(
                      width: 40,
                    ),
                    Text(
                      "Relationship",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 15.0,
                        fontWeight: FontWeight.bold,
                        fontFamily: 'Montserrat',
                      ),
                    ),
                    SizedBox(
                      width: 40,
                    ),
                    Text(
                      "animals",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 15.0,
                        fontWeight: FontWeight.bold,
                        fontFamily: 'Montserrat',
                      ),
                    ),
                    SizedBox(
                      width: 40,
                    ),
                    Text(
                      "Profile Pic",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 15.0,
                        fontWeight: FontWeight.bold,
                        fontFamily: 'Montserrat',
                      ),
                    )
                  ],
                )),
            Positioned(
              top: 200,
              right: 60,
              child: Align(
                alignment: Alignment.center,
                child: Text(
                  'Choose Your Relationship Status',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20.0,
                    fontWeight: FontWeight.bold,
                    fontFamily: 'Montserrat',
                  ),
                ),
              ),
            ),
            Positioned(
              top: 240,
              right: 40,
              child: Align(
                alignment: Alignment.center,
                child: SizedBox(
                  child: Center(
                    child: Text(
                      'You can change this afterwards if you get lucky',
                      style: ktsMediumGreyBodyText,
                    ),
                  ),
                ),
              ),
            ),
            Positioned(
              top: 270,
              right: 180,
              child: Align(
                alignment: Alignment.center,
                child: SizedBox(
                  child: Center(
                    child: Text(
                      '...or unlucky!',
                      style: ktsMediumGreyBodyText,
                    ),
                  ),
                ),
              ),
            ),
            Positioned(
              bottom: 50,
              child: SizedBox(
                width: width,
                height: 90,
                child: Row(
                  children: [
                    Expanded(
                      child: TextButton(
                        onPressed: () {},
                        child: Text("Back"),
                        style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all<Color>(
                                Colors.transparent),
                            foregroundColor: MaterialStateProperty.all<Color>(
                                kcPrimaryColor)),
                      ),
                    ),
                    Expanded(
                      child: TextButton(
                        onPressed: () {},
                        child: Text("Next"),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Code i am talking about within the file:
            Positioned(
              bottom: 50,
              child: SizedBox(
                width: width,
                height: 90,
                child: Row(
                  children: [
                    Expanded(
                      child: TextButton(
                        onPressed: () {},
                        child: Text("Back"),
                        style: ButtonStyle(
                            backgroundColor: MaterialStateProperty.all<Color>(
                                Colors.transparent),
                            foregroundColor: MaterialStateProperty.all<Color>(
                                kcPrimaryColor)),
                      ),
                    ),
                    Expanded(
                      child: TextButton(
                        onPressed: () {},
                        child: Text("Next"),
                      ),
                    ),
                  ],
                ),
              ),
            ),

A: Instead of using SizedBox in Row i used SizedBox for each of the two buttons and that sorted the issue, here is the code:

 Positioned(
              bottom: 50,
              child: Row(
                children: [
                  SizedBox(
                    height: 60,
                    width: width / 2,
                    child: TextButton(
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => MusicPreferences()),
                        );
                      },
                      child: Text("Back"),
                      style: ButtonStyle(
                          shape:
                              MaterialStateProperty.all<RoundedRectangleBorder>(
                            RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(18.0),
                            ),
                          ),
                          backgroundColor: MaterialStateProperty.all<Color>(
                              Colors.transparent),
                          foregroundColor:
                              MaterialStateProperty.all<Color>(kcPrimaryColor)),
                    ),
                  ),
                  SizedBox(
                    height: 60,
                    width: width / 2,
                    child: TextButton(
                      style: ButtonStyle(
                          shape:
                              MaterialStateProperty.all<RoundedRectangleBorder>(
                            RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(18.0),
                            ),
                          ),
                          backgroundColor:
                              MaterialStateProperty.all<Color>(kcPrimaryColor),
                          foregroundColor:
                              MaterialStateProperty.all<Color>(Colors.white)),
                      onPressed: () {},
                      child: Text("Done"),
                    ),
                  ),
                ],
              ),
            ),


text:
Q: Why does pylab always plot to the last created figure? I tried to create 2 figures at the same time.  I thought I could plot into each figure by specifying the desired axis as shown in the code below, but all of the data goes into the last created figure (here, fig2).
import matplotlib.pylab as pl

fig1 = pl.figure(figsize=(5, 5))
gs1 = pl.GridSpec(4, 4)

fig2 = pl.figure(figsize=(5, 5))
gs2 = pl.GridSpec(4, 4)

for axis_counter in range(11):
    ax = pl.subplot(gs1[axis_counter])
    ax.plot([0, 10], [0, 10])

When I run this nothing plots in the fig1 axes, it all goes into the fig2 axes even though I'm explicitly calling gs1 here.  I imagine pylab is latching onto the last created figure, but that behavior does not make sense.

A: My recommendation is to never use pylab.
If your in an interactive console session, pyplot is ok. But really, you should use the object-oriented interface. That means:

*

*importing pyplot

*create a figure either directly or with axes via (pyplot.subplots)

*operate on those figures and axes directly.

In your case, this means:
from matplotlib import pyplot

fig1 = pyplot.figure(figsize=(5, 5))
gs1 = fig1.add_gridspec(4, 4)

fig2 = pyplot.figure(figsize=(5, 5))
gs2 = fig2.add_gridspec(3, 3)

for axis_counter in range(11):
    ax = fig1.add_subplot(gs1[axis_counter])
    ax.plot([0, 10], [0, 10])

ax = fig2.add_subplot(gs2[3])
ax.plot([0, 10], [0, 10])


text:
Q: Why i can't make this generic repository to work ? What wrong? I have this generic repository.
 /// <summary>
/// Implémentation de base d'un dépositoire pour Entity Framework.
/// </summary>
/// <remarks>Entity Framework 4.1</remarks>
/// <typeparam name="TEntite">Entité spécifique.</typeparam>
public abstract class RepositoryBase<TEntity, TKey> : IRepository<TEntity>, IDisposable
    where TEntity : EntityBase<TKey>
    where TKey : class
{
    private readonly IContext _context;
    private ObjectContext _objectContext;
    private IObjectSet<TEntity> _objectSet;

    protected RepositoryBase(IContext context)
    {
        _context = context;
        _objectContext = _context.GetObjectContext();
        _objectSet = _objectContext.CreateObjectSet<TEntity>();
    }

    /// <see cref="IRepository.cs"/>
    public IEnumerable<TEntity> GetAll(Expression<Func<TEntity, object>> sortExpression)
    {
        if (sortExpression == null)
            sortExpression = x => x.Id;
        return _objectSet.OrderBy(sortExpression).AsEnumerable();
    }

    /// <see cref="IRepository.cs"/>
    public IEnumerable<TEntity> GetAll(int maximumRows, int startRowIndex, Expression<Func<TEntity, object>> sortExpression)
    {
        if (sortExpression == null)
            sortExpression = x => x.Id;
        return _objectSet.OrderBy(sortExpression).Skip(startRowIndex).Take(maximumRows).AsEnumerable();
    }

    /// <see cref="IRepository.cs"/>
    public TEntity SelectByKey(TKey key)
    {
        if (key == null)
            throw new ArgumentNullException("La clé était NULL! Une clé est nécessaire pour récupérer un entité.");
        return _objectSet.SingleOrDefault(x => x.Id == key);
    }

Here the specific implementation...

public class ProductRepository : RepositoryBase<Product, int>, IProductRepository
{
    public ProductRepository(IContext context)
        : base(context)
    { }

    /// <see cref="IProductRepository.cs"/>
    public Product GetByName(string name)
    {
        return base.First(x => x.Name == name);
    }

    /// <see cref="IProductRepository.cs"/>
    public IEnumerable<Product> FindProduct(Specification<Product> specification)
    {
        throw new System.NotImplementedException();
    }
}

When i create a specific repository.. it say that Tkey must be a reference type but why ? Is there a way to make this generic repository work ? TKey was used in order to make the method SelectByKey accept a key type.
Edit #1:
If i remove the constrain then i have another problem... TKey cannot be compared with TKey using == as lambda expression in my SelectByKey method.
Edit #2:
Tried to use Equals and the syntax seem to be ok.
Edit #3:
Equals crash at runtime.. saying Tkey (which seem to be a System.Object) can't use equals which doesnt seem logic since object have the equal method. I currently doesn't have access to the real code but i did some test with this code below..
class Program
{
    static void Main(string[] args)
    {
        Test<TestEntity, int> t = new Test<TestEntity, int>();
        t.TestMethod(5);
    }
}

class Test<TEntity, TKey>
    where TEntity : Entity<TKey>
{
    public Test()
    { }

    public TestEntity TestMethod(TKey id)
    {
        List<TestEntity> testEntity = new List<TestEntity>();
        testEntity.Add(new TestEntity(5));
        return testEntity.SingleOrDefault(x => x.Id.Equals(id));
    }
}

class Entity<TKey>
{
    public TKey Id { get; set; }
}

class TestEntity : Entity
{
    public TestEntity(int id)
    {
        Id = id;
    }
}

class Entity : Entity<int>
{
}

And it seem to work pretty well. So i will try later tonight.
Edit #4
Alright the exception i get is Canoot create a constant value of type "System.Object". Only primary types such int32, string and guid are supported by this context.

A: In your repository declaration
public abstract class RepositoryBase<TEntity, TKey> : IRepository<TEntity>, IDisposable
    where TEntity : EntityBase<TKey>
    where TKey : class
{

you have specified the class constraint which will only allows reference types. See
http://msdn.microsoft.com/en-us/library/d5x73970%28v=vs.80%29.aspx

where T : class
The type argument must be a reference type, including any class,
  interface, delegate, or array type. (See note below.)

Remove the : class constraint to allow any type.
Unless you're engaged in a learning exercise, I would not try to build your repository from scratch. I would leverage off what others have done. When I wrote a repository framework, I wanted a GetById method that would work with primary keys of varying types (although not multiple column primary keys). When writing it, I found the following two posts especially helpful:
C# LINQ to SQL: Refactoring this Generic GetByID method
http://goneale.com/2009/07/27/linq-to-sql-generic-repository/

A:
it say that Tkey must be a reference type but why ?

You have the constraint:

where TKey : class

Do you need the constraint? What key types do you want to support?

A: Adding
where TKey : IEquatable<TKey>

Should fix the problem and allow you to use Equals syntax.

A: If you take a look at guid or int metadata by using f12 key, you'll se that it implement:
public struct int: IFormatable, IComparable, IComparable<int>, IEquatable<int>
public struct Guid: IFormatable, IComparable, IComparable<Guid>, IEquatable<Guid>

then the constraint will be :
public interface IRepository<TEntity, TKey>
  where TEntity: class, IEntity<TKey>
  where TKey: struct, IFormatable, IComparable, IComparable<TKey>, IEquatable<TKey>

and IEntity interface must be like this:
public interface IEntity<TKey> where TKey: struct, IFormatable,
                               IComparable, IComparable<TKey>, IEquatable<TKey>

but the operator == still not working for me, but the Equals method works as we expect, still searching for a solution for the equality operator.


text:
Q: React sorting of the array relative to type I have a json file with data. from this file I want to ask questions and the type of question. the structure is to look like this: there is a category name + picture, and then a list of questions.
This is my component that renders the list of questions.
import React from 'react';
import { sortBy } from 'lodash';
import QuestionsListItem from './QuestionListItem';

const images = require.context('../../img', true);
const imagePath = (name) => images(name, true);

const QuestionsList = ({ questions }) => {
  const questionListItem = questions && questions.questions ?
    sortBy(questions.questions, ['type']).map((question) => (
      <>
        {
          const sortType = (question) => {
            if(question.type==='science') {

{question.type}

            }
          }
        }
        <QuestionsListItem
          key={question.id}
          type={question.type}
          question={question}
        />
      </>
    )) : null;
  return (

        { sortType }
        { questionListItem }

  );
};

At the beginning, I want to sort the array with a type, then I want to map it, then I want to render the type, if type ===" since " show the appropriate text and picture. At this element I get the error Parsing error: Unexpected token and points toconst sortType = (question) => {.... I do not know how to do it in React to get the effect I want. Where to insert the code responsible for type and category image rendering?
thanks in advance :)

A: You defined the function sortType in the JSX part of your file. This isn't allowed.
Moreover, in your sortType function, you must return JSX, and when you call your function, you must give it the question as argument.
Here would be the correct code:
import React from 'react';
import { sortBy } from 'lodash';
import QuestionsListItem from './QuestionListItem';

const images = require.context('../../img', true);
const imagePath = (name) => images(name, true);

const QuestionsList = ({ questions }) => {

  const sortType = (question) => {
    if(question.type==='science') {
      return (<>

{question.type}

      </>)
    }
  }

  const questionListItem = questions && questions.questions ?
    sortBy(questions.questions, ['type']).map((question) => (
      <QuestionsListItem
        key={question.id}
        type={question.type}
        question={question}
      />
    )) : null;
  return (

        { sortType(question) }
        { questionListItem }

  );
};


text:
Q: classname is missing I have my java file under org/myorg
  package org.myorg;
  import java.io.*;
  import java.util.*;
  import java.net.*;
  import org.apache.hadoop.fs.*;
  import org.apache.hadoop.conf.*;
  import org.apache.hadoop.io.*;
  import org.apache.hadoop.mapred.*;
  import org.apache.hadoop.util.*;

  public class Write{
    public static void main (String [] args) throws Exception{
            try{
                    Path pt=new Path("hdfs:localhost:8020/user/jfor/out/abc");
                    FileSystem fs = FileSystem.get(new Configuration());
                    BufferedWriter br=new BufferedWriter(new OutputStreamWriter(fs.create(pt,true)));
                                               // TO append data to a file, use fs.append(Path f)
                    String line;
                    line="Disha Dishu Daasha";
                    System.out.println(line);
                    br.write(line);
                    br.close();
            }catch(Exception e){
                    System.out.println("File not found");
            }
    }
}

I compiled it using
 javac -classpath hadoop-0.20.1-dev-core.jar org/myorg/Write.java

from the parent directory of org.
Write.class is created under org/myorg
I run it using
java org.myorg.Write
from the parent directory of org
It says
 Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hadoop/fs/FSDataOutputStream
    at java.lang.Class.getDeclaredMethods0(Native Method)

But i downloaded jar from this link. This link says FSDataOutputStream class is present.
What could be the reason?

A: You don't have the classpath set for execution - you have it set during compile:
Windows:
java -cp .;hadoop-0.20.1-dev-core.jar org.myorg.Write

UNIX:
java -cp .:hadoop-0.20.1-dev-core.jar org.myorg.Write

You have to specify the classpath (-cp) to include the current directory, in your case, as well as the hadoop jar file.

A: You have to give the exact path where the jar is present
java -cp .:give_the_path_to_the_jar org.myorg.Write

for Example if it is present in my desktop
java -cp .:/home/neeraj/Desktop/hadoop-0.20.1-dev-core.jar org.myorg.Write

.  represent the current directory

Note : These above example is for linux(ubuntu) , if you need to use in Windows than you have to use ; instead of :


text:
Q: Calculate $\int_{0}^t (0.3(1+x)^3+0.7)^{-1/2}\,dx$ The following integral cannot be expressed in elementary terms:

$\displaystyle\int_{0}^t \frac{1}{\sqrt{0.3(1+x)^3+0.7}}\,dx$
  with $t>0$ real.

What are possible techniques for approaching this kind of integral, and how do they apply to this concrete case?

A: The integral you posted cannot be evaluated in terms of elementary functions. You will need either elliptic integrals, hypergeometric series, or incomplete beta functions to express it.

Hypergeometric series: It is quite simple, really, but there are a few details that we have to pay attention to: Basically, it all relies upon expanding the integrand into its binomial series, then switching the order of summation and integration. The trick is that, in order for that to happen, the new variable has to be lesser than $1$ in absolute value. Notice that we can rewrite the integrand as $~\sqrt{\dfrac{10}7}\cdot\bigg(1+\dfrac37u^3\bigg)^{-1/2}~$ where u is $x+1$, and the new limits of integration are $1$ and $t+1$. Or $\sqrt{\dfrac{10}3}~u^{-3/2}\bigg(1+\dfrac73u^{-3}\bigg)^{-1/2}$ with the same limits in place. The former expression works for the case $|u|\le\sqrt[3]{\dfrac73}$ , and the latter when $|u|\ge\sqrt[3]{\dfrac73}$ . The whole idea is to place the relation of $\sqrt[3]{\dfrac73}>1$ with respect to $t+1$, and to break up the interval of integration accordingly $($if necessary$)$, then to employ the appropriate formula on each such subinterval.

Incomplete beta functions:
First, factor the free term outside the radical sign, then let $u=x+1$, and $v=\dfrac37u^3.~$ Finally, let $w=\dfrac1{v+1}$ . You will see the expression of the $($incomplete$)$ beta function slowly emerging from the mist of successive substitutions.


text:
Q: Express route Cannot get a file in views folder I am fairly new to programming, and am struggling with trying to get the recipe.ejs file to show. I cannot seem to create a route from recipe.js properly to get the recipe.ejs file and render it. Any help would be greatly appreciated.
/routes/recipe.js
    var express = require('express');
var router = express.Router();

/*GET recipe page*/
router.get('/', function(req, res, next) {
    res.render('recipe');
});

module.exports = router;

**app.js**

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var recipeRouter = require('./routes/recipe');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/recipe', recipeRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

A: Try with this proved snippet:
package.json
server.js
views/hello.ejs

server.js
var express = require('express');
var app = express();
app.get("/", function(req, res) {
  res.render("hello.ejs");
});
app.listen(2708, function() {
  console.log("server is listening!!!");
});

hello.ejs
<h1>Hello EJS World </h1>

package.json
{
  "name": "first-express-app",
  "description": "an example of using Express",
  "private": true,
  "version": "0.0.1",
  "dependencies": {
    "ejs": "^3.1.3",
    "express": "4.17.1"
  },
  "scripts": {
    "start": "node server"
  },
  "main": "quote"
}

If it works, you could use to compare it with your complex implementation to find the error.


text:
Q: Script to find functions in a C program I am trying to find solution to this following problem:
Given the directory structure:
project/
bridge/
    mysql_bridge.c
    postgres_bridge.c

My code should retrieve all functions in .c files from root folder and all the c programs in its subdirectories*:

*

*mysql_bridge.c

*postgres_bridge.c

My script should output "Unable to find any source files" if no source files were encountered.
Specifically, the only source files that should be search for are .c files (headers are ignored)
I want to use a command line argument as the root of the project. Following are the scenarios:
Example 1:
./findfn.sh project_1
project_1/ever/jump.c:
void logical_jump(int loc)
int ngoto()

project_1/indent/handle.c:
FILE* figure_out_this(char* name)
void kill_all()

project_1/mac.c:
void some(void)
int super_function(int xx, int ya)

project_1/test.c:
void this_function()

Example 2: Bad directory
./findfn.sh file
file is not a directory

Example 3: Unable to find functions
./findfn.sh project_2
Unable to find any functions

A: A C source file is difficult to parse, just like other structured data files. It's better to use a parser that knows about the language's syntax than to try to handle it oneself.
Assuming you have Exuberant Ctags installed as ectags:
find top-dir -type f -name '*.[ch]' -exec ectags -x --c-kinds=f {} ';' >table

This will find all .c and .h files in or under top-dir and create the file table.  The contents of table will look something like (with top-dir being . in this example)
GetTimeSeed      function    373 ./src/bayes.c    void GetTimeSeed (void)
InitializeMrBayes function    443 ./src/bayes.c    int InitializeMrBayes (void)
PrintHeader      function    821 ./src/bayes.c    void PrintHeader (void)
ReinitializeMrBayes function    838 ./src/bayes.c    int ReinitializeMrBayes (void)
main             function    101 ./src/bayes.c    int main (int argc, char *argv[])
readline_completion function    359 ./src/bayes.c    char **readline_completion (const char *text, int start, int stop)

(etc.)
This output format should easily be parsed with e.g. awk to get exactly the format you want.