text:
Q: ASP.NET: Wrong event is fired when I click a LinkButton I have a "cart" Repeater, where every item has a couple of controls in it. The ones we're focusing on are two DropDownLists, a LinkButton and a TextBox. The lists are on one validation group and the button & textbox are on another.
Both lists have an OnSelectedIndexChanged event handler which does some calculations based on the selections in both DropDownLists. Both lists also have AutoPostBack="True".
The button has an OnClick handler which also does some calculations according to the number in the textbox.
I need the calculations to be updated immediately - so I added another data binding for the Repeater - on each event handler
The problem is - I can't get the value from the TextBox after I click on one of the DropDownLists. It always comes off as 1. In the background, the OnSelectedIndexChanged event handler fires first, and the buttons' OnClick will fires after it. That only happens after I change one of the lists - and it happens every time I click that button from that moment on. Before that - everything is normal on all controls.
What do you think? Below is some code (I hope it's not too much, I included everything that's taking part) - Thank you very much!
Here's the repeater template:
                <ItemTemplate>

<asp:DropDownList runat="server" ID="_selectSize" AutoPostBack="true" OnSelectedIndexChanged="selectChange" EnableViewState="true" TabIndex="<%#Container.ItemIndex%>" ValidationGroup="doNotValidate"></asp:DropDownList>

<asp:DropDownList runat="server" ID="_selectMaterial" AutoPostBack="true" OnSelectedIndexChanged="selectChange" EnableViewState="true" TabIndex="<%#Container.ItemIndex%>" ValidationGroup="doNotValidate"></asp:DropDownList>

<asp:TextBox runat="server" ID="_txtAmount" name="quantity_<%#Container.ItemIndex%>" ValidationGroup="vCart"></asp:TextBox>

<asp:LinkButton runat="server" CssClass="refresh" id="_refreshCart" ValidationGroup="vCart"></asp:LinkButton>

                </ItemTemplate>

The Repeater.DataBound():
Protected Sub rptCart_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptCart.ItemDataBound
    If e.Item.ItemType = ListItemType.AlternatingItem OrElse e.Item.ItemType = ListItemType.Item Then
        Dim OrderItem As ProxyMarket.Item = CType(e.Item.DataItem, ProxyMarket.Item)
        Dim btnRemoveProduct As LinkButton = CType(e.Item.FindControl("_removeProduct"), LinkButton)
        Dim btnRefreshCart As LinkButton = CType(e.Item.FindControl("_refreshCart"), LinkButton)
        Dim txtAmount As TextBox = CType(e.Item.FindControl("_txtAmount"), TextBox)
        Dim sizeSelect As DropDownList = CType(e.Item.FindControl("_selectSize"), DropDownList)
        Dim materialSelect As DropDownList = CType(e.Item.FindControl("_selectMaterial"), DropDownList)

        btnRemoveProduct.CommandName = OrderItem.ID
        btnRefreshCart.CommandName = OrderItem.ID
        txtAmount.Text = OrderItem.Units

        AddHandler btnRemoveProduct.Click, AddressOf removeProduct
        AddHandler btnRefreshCart.Click, AddressOf refreshCart

        sizeSelect.DataSource = sizeList
        sizeSelect.DataBind()
        sizeSelect.SelectedIndex = s
        materialSelect.DataSource = materialList
        materialSelect.DataBind()
        materialSelect.SelectedIndex = m
    End If
End Sub

Here is the DropDownLists event handler:
Protected Sub selectChange(ByVal sender As DropDownList, ByVal e As System.EventArgs)
    Dim listing As New PriceListing
    Dim ddl As DropDownList
    Dim selectedIndex As Integer

    If sender.ID = "_selectSize" Then
        For Each rptrItem As RepeaterItem In rptCart.Items
            ddl = CType(rptrItem.FindControl("_selectMaterial"), DropDownList)
            If ddl.TabIndex = sender.TabIndex Then Exit For
        Next

        For Each listing In artDecoPricing
            If listing.Size = sender.SelectedValue Then Exit For
        Next

        selectedIndex = ddl.SelectedIndex
        s = sender.SelectedIndex
    ElseIf sender.ID = "_selectMaterial" Then
        For Each rptrItem As RepeaterItem In rptCart.Items
            ddl = CType(rptrItem.FindControl("_selectSize"), DropDownList)
            If ddl.TabIndex = sender.TabIndex Then Exit For
        Next

        For Each listing In artDecoPricing
            If listing.Size = ddl.SelectedValue Then Exit For
        Next

        selectedIndex = sender.SelectedIndex
        s = ddl.SelectedIndex
    End If

    Select Case selectedIndex
        Case 0
            Cart.Order.Items(sender.TabIndex).PriceUnit = listing.Canvas
        Case 1
            Cart.Order.Items(sender.TabIndex).PriceUnit = listing.Acrylic
        Case 2
            Cart.Order.Items(sender.TabIndex).PriceUnit = listing.Framed
        Case 3
            Cart.Order.Items(sender.TabIndex).PriceUnit = listing.Alucobond
    End Select

    Cart.SaveOrder()

    s = sender.SelectedIndex
    m = selectedIndex

    rptCart.DataSource = Cart.Order.Items
    rptCart.DataBind()
End Sub

And finally, the LinkButton OnClick handler:
Protected Sub refreshCart(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim btnRefreshCart As LinkButton = CType(sender, LinkButton)
    Dim amountStr As String
    Dim amount As Integer

    amountStr = CType(btnRefreshCart.Parent.FindControl("_txtAmount"), TextBox).Text
    If IsNumeric(amountStr) Then
        amount = CDbl(amountStr)
    Else
        amount = -1
    End If
    amount = IIf(amount > 0, amount, -30)

    For Each Item As ProxyMarket.Item In Cart.Order.Items
        If Item.ID = btnRefreshCart.CommandName Then
            Item.Units = amount
            Cart.Edit_Product(btnRefreshCart.CommandName, amount)
            Exit For
        End If
    Next

    rptCart.DataSource = Cart.Order.Items
    rptCart.DataBind()
End Sub

Thank you :)

A: I found a solution!
Apparently this is happening because of a viewstate limitation in ASP.NET which causes the OnSelectedIndexChanged to fire on Page_Load regardless if the user actually selected a different value.
So when the event handler fires, I am checking whether it is the DropDownLists which called me or a different control - that prevents the event from firing when it doesn't need to - and keeps all event handling on the page intact:
Protected Sub selectChange(ByVal sender As DropDownList, ByVal e As System.EventArgs)
    Dim senderClientID = Page.Request.Params.Get("__EVENTTARGET")
    ' Run ONLY if the relevant select control was clicked,
    ' otherwise this is only fired because of ASP.NET limitations,
    ' and will screw up the original event:
    If senderClientID.IndexOf("_selectSize") <> -1 Or senderClientID.IndexOf("_selectMaterial") <> -1 Then
        'do stuff

A: I know this has already been answered but I was having a very similar problem, with a completely different solution and as this is the first post that appeared in google I thought I would add it here.
I had a link button and when clicking it, but only in IE9, it appeared to activate another button on the page and call it's event rather than it's own.
After much messing about and googling, I realised that it wasn't just my button that was activating the other button it was if I clicked anywhere in a particular section of my page.
I eventually found the problem after completely stripping down my page. It was this:

an empty label tag. Once deleted all was fine.


text:
Q: Setup firebase - Unity project - com.google.firebase.MessagingUnityPlayerActivity & MessageForwardingService Not found I am setting up firebase base project for Push notification , and my main activity extends UnityPlayerActivity.
From doc : enter link description here
If your custom activity extends UnityPlayerActivity you can instead extend com.google.firebase.MessagingUnityPlayerActivity , but not able to find this anywhere and  MessageForwardingService also
And not getting notification is application extends  UnityPlayerActivity

redpajama_set_name: RedPajamaStackExchange


text:
Q: Child level
* height issue I know it'll be sillest Question ever!!, but having a Query regarding the height of sub level
, i am not getting the full height of child  tag.

Home

About Us

About us A

About us A 1

About us A 2

About us A 3

Clients

Links A

Links C 1

Links B

Links B 1

Links B 2

Contact Us

level-2

level-2

level-2

CSS:
.nav {
 float: left;
 width: 100%;
}
.nav ul{
display:table;
margin: 0 auto;
    max-width: 1024px;
    width: 100%;

}
.nav > ul > li.level1{
   position:static;
}
.nav ul li {
 display: table-cell;
 transition: all 0.5s ease 0s;
 position: relative;
}
.nav li a {
 transition: all 0.5s ease 0s;
 display:block;
}
.nav > ul > li > a {
 background: #f5f5f5;
 border-right: 1px solid #000;
 box-sizing: border-box;
 display: block;
 padding: 10px;
}
.nav > ul > li:last-child > a {
 border-right: none;
}
 .nav {
 position: relative;
}
.nav.megaMenu > ul > li > ul{
 left: 0;
 position: absolute;
 right: 0;
 width: 100%;
 z-index:9;
 height:100%;
    background:red;
}
.nav.megaMenu > ul {
position: relative;
margin: 0 auto;
max-width: 1024px;
}
.nav.megaMenu li.level2 ul li {
width:100%;
}
.nav.megaMenu > ul li:hover ul {
visibility:visible;
}

.nav > ul > li ul {
 visibility:hidden;
 z-index: 9;
 position: absolute;
}
.nav > ul > li.level1 ul li a {
 background: rgba(0, 0, 0, 0.2);
 border-bottom: 1px solid #000;
 box-sizing: border-box;
 color: #fff;
 display: block;
 margin-right: 1px;
 padding: 10px;
}

you can get the working demo @ here. at here when you hover on menu, you will find the red background coloured
 which contains sub children too, but the height of
 is not covering the height of full heirarchy. please help me for this!

A: Remove the absolute parent on child ul since the parent is already in absolute position.
.nav > ul > li ul {
 visibility:hidden;
 z-index: 9;
}

Demo: fiddle


text:
Q: Get Keys and Value from a single row SQL I can't get the keys and the values from a single row...
here's my code :
$tab_titres_fr=array();
$sql="SELECT * FROM recettes  WHERE recetteid = '$id' ";
$request = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($request);
$tab_titres_fr[]=json_encode($row);

foreach($tab_titres_fr as $key => $value) {

    echo   $keys." / ".$value."
" ;
}

A: $request = mysqli_query($db,$sql);
while($row = mysqli_fetch_assoc($request)){
$tab_titres_fr[]=json_encode($row);
}
foreach($tab_titres_fr as $key => $value) {

echo   $key." / ".$value."
" ;
}


text:
Q: How can I get variable to text from php to swift app I use this code and work perfect. I use swift. PHP is work fine.
I also try some other examples at this
I have 2 problems
first my responseString values turns in Optional("Success"). Why?
second is How can assign it on my button?
func makePostCall() {
        var request = URLRequest(url: URL(string: "MyURL/page.php")!)
        request.httpMethod = "POST"
        let postString = "id=login"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(error)")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")

            }

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(responseString)")
            self.lbl.text = responseString
        }
        task.resume()
        //return responseString

    }

A: You need to use DispatchQueue.main.async to work with UI from URLRequests. Also you need to use [weak self] to prevent reference cycle problem. At last, btn.setTitle(responseString, for: .normal) to set title for button state .normal. Here is correct answer!
func makePostCall() {
        var request = URLRequest(url: URL(string: "MyURL/page.php")!)
        request.httpMethod = "POST"
        let postString = "id=login"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) {[weak self] data, response, error in
            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(error)")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")

            }

            guard let responseString = String(data: data, encoding: .utf8) else {
                  return
            }
            print("responseString = \(responseString)")
            DispatchQueue.main.async {
                self?.lbl.text = responseString
                self?.btn.setTitle(responseString, for: .normal) // your button
            }
        }
        task.resume()
        //return responseString

    }


text:
Q: predictive model that includes previous predictions and models time dependence I'm trying to predict counts of dengue fever from climate and environmental data. I'm predicting total weekly counts of dengue and the data is time-series in one week intervals over the past 20 years.  I need to predict the next 10 years (dengue weekly counts is absent from that dataset). I'm using python and find that negative binomial regression, support vector regressor, and random forest regressor work fairly well, but they cannot account for the large outbreaks and contagiousness of the disease.
Does anyone know how to build a model that progressively predicts a new value while taking into account the previous prediction?
Thank you!

A: You can use iterative prediction to do so. You train a model for predicting one week in advance. Then you add your prediction computed with the model in your dataset and train an other model with the prediction as a feature.
For example, if you want to predict 4 weeks in advance, you will train 4 models, the last 3 containing the predictions computed before.
With this procedure, you will take into account the previous prediction but you will need to train n models if you want to predict n weeks in advance.
You can see my answer to a similar problem on stackoverflow (a little bit more elaborate) : https://stackoverflow.com/questions/42581545/machine-learning-algorithm-to-predict-next-value/42583196#42583196


text:
Q: How can I create an alert dialog based of my HashMap in Android Studio? I'm trying to display a set of questions based on their key values which are int 1-6, firstly I would generate a random number and then display the question corresponding to the number through an alert dialog with a simple response as "OK" to close the dialog box. I have tried to implement a simple alert dialog but they are way too confusing for me.
public void roll_the_dice(View view){

    HashMap dbreaker = new HashMap();
    dbreaker.put(1, "If you could go anywhere in the world, where would you go?");
    dbreaker.put(2, "If you were stranded on a desert island, what three things would you want to take with you?");
    dbreaker.put(3, "If you could eat only one food for the rest of your life, what would that be?");
    dbreaker.put(4, "If you won a million dollars, what is the first thing you would buy?");
    dbreaker.put(5, "If you could spaned the day with one fictional character, who would it be?");
    dbreaker.put(6, "If you found a magic lantern and a genie gave you three wishes, what would you wish?");

    Random r = new Random();
    int dbreakerNo = r.nextInt((6-1) + 1) + 1;

}

A: I'm not sure I correctly understand your problem and which part of implementation is confusing for you but here is code example where on button click is displayed random text in alert dialog. I hope this will help you.
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btnDice = findViewById(R.id.btn_dice);
    btnDice.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showAlertDialog(getRandomQuotation());

        }
    });

}

private void showAlertDialog(String quoatationToShow) {
    AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
    alertDialog.setTitle("Roll alert");
    alertDialog.setMessage(quoatationToShow);
    alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    alertDialog.show();
}

private String getRandomQuotation() {

    HashMap<Integer, String> dbreaker = new HashMap();
    dbreaker.put(1, "If you could go anywhere in the world, where would you go?");
    dbreaker.put(2, "If you were stranded on a desert island, what three things would you want to take with you?");
    dbreaker.put(3, "If you could eat only one food for the rest of your life, what would that be?");
    dbreaker.put(4, "If you won a million dollars, what is the first thing you would buy?");
    dbreaker.put(5, "If you could spaned the day with one fictional character, who would it be?");
    dbreaker.put(6, "If you found a magic lantern and a genie gave you three wishes, what would you wish?");

    Random r = new Random();
    int dbreakerNo = r.nextInt((6 - 1) + 1) + 1;
    return dbreaker.get(dbreakerNo);
}

}
activity_main.xml <-- that's your layout
    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_dice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Roll the dice!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>


text:
Q: Unable to find xpath "/html" (Capybara::ElementNotFound) I was implementing capybara for a app flow. I have features/step_definitions/anonymous_booking_steps.rb with two steps

*

*for just visiting the root path

*expecting an element in next step for the above page

I am getting this error:-
Unable to find xpath "/html" (Capybara::ElementNotFound)


text:
Q: Can I change CheckBox color in LongListMultiSelector? WP8 I need to change the color for the LongListMultiSelector's CheckBox in Windows Phone 8, because my background is white, this is possible?
Thanks.

A: In order to do that you have to first edit the ItemContainerSyle by right clicking on the longlistselector from document outline in visual studio and then choose  Edit Additional Style -> Edit ItemContainerSyle -> Create Empty
Then you have to replace the setters for the generated template with the original setter code from codeplex.
the following setters code centers the check boxes and makes then grey:
<Style.Setters>
        <Setter Property="Background" Value="{StaticResource PhoneAccentBrush}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="toolkit:LongListMultiSelectorItem">
                    <Grid MinHeight="52">
                        <Grid.Resources>
                            <ExponentialEase EasingMode="EaseIn" Exponent="8" x:Key="ExponentialEaseIn"/>
                            <QuadraticEase EasingMode="EaseOut" x:Key="QuadraticEaseOut"/>
                        </Grid.Resources>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="SelectionEnabledStates">
                                <VisualStateGroup.Transitions>
                                    <VisualTransition x:Name="ClosedToExposed"
                                                  From="Closed" To="Exposed"
                                                  GeneratedDuration="0:0:0.30">
                                        <Storyboard>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)"
                                                                       Storyboard.TargetName="OuterHintPanel">
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.0" Value="0.0" EasingFunction="{StaticResource QuadraticEaseOut}"/>
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.30" Value="1.0" EasingFunction="{StaticResource QuadraticEaseOut}"/>
                                            </DoubleAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualTransition>
                                    <VisualTransition x:Name="ExposedToClosed"
                                                  From="Exposed" To="Closed"
                                                  GeneratedDuration="0:0:0.30">
                                        <Storyboard>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)"
                                                                       Storyboard.TargetName="OuterHintPanel">
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.0" Value="1.0" EasingFunction="{StaticResource QuadraticEaseOut}"/>
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.30" Value="0.0" EasingFunction="{StaticResource QuadraticEaseOut}"/>
                                            </DoubleAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualTransition>
                                    <VisualTransition x:Name="ExposedToOpened"
                                                  From="Exposed" To="Opened"
                                                  GeneratedDuration="0:0:0.30">
                                        <Storyboard>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)"
                                                                       Storyboard.TargetName="SelectBox">
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.0" Value="-58" EasingFunction="{StaticResource ExponentialEaseIn}"/>
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.15" Value="0" EasingFunction="{StaticResource ExponentialEaseIn}"/>
                                            </DoubleAnimationUsingKeyFrames>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)"
                                                                       Storyboard.TargetName="Presenter">
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.0" Value="24" EasingFunction="{StaticResource ExponentialEaseIn}"/>
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.15" Value="86" EasingFunction="{StaticResource ExponentialEaseIn}"/>
                                            </DoubleAnimationUsingKeyFrames>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)"
                                                                       Storyboard.TargetName="OuterHintPanel">
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.0" Value="1.0" EasingFunction="{StaticResource QuadraticEaseOut}"/>
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.30" Value="0.0" EasingFunction="{StaticResource QuadraticEaseOut}"/>
                                            </DoubleAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                                       Storyboard.TargetName="SelectBox">
                                                <DiscreteObjectKeyFrame KeyTime="0:0:0.0" Value="Visible"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.IsHitTestVisible)"
                                                                       Storyboard.TargetName="OuterHintPanel">
                                                <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="False"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.IsHitTestVisible)"
                                                                       Storyboard.TargetName="InnerHintPanel">
                                                <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="False"/>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualTransition>
                                    <VisualTransition x:Name="ClosedToOpened"
                                                  From="Closed" To="Opened"
                                                  GeneratedDuration="0:0:0.15">
                                        <Storyboard>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)"
                                                                       Storyboard.TargetName="SelectBox">
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.0" Value="-58" EasingFunction="{StaticResource ExponentialEaseIn}"/>
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.15" Value="0" EasingFunction="{StaticResource ExponentialEaseIn}"/>
                                            </DoubleAnimationUsingKeyFrames>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)"
                                                                       Storyboard.TargetName="Presenter">
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.0" Value="24" EasingFunction="{StaticResource ExponentialEaseIn}"/>
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.15" Value="86" EasingFunction="{StaticResource ExponentialEaseIn}"/>
                                            </DoubleAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                                       Storyboard.TargetName="SelectBox">
                                                <DiscreteObjectKeyFrame KeyTime="0:0:0.0" Value="Visible"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.IsHitTestVisible)"
                                                                       Storyboard.TargetName="OuterHintPanel">
                                                <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="False"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.IsHitTestVisible)"
                                                                       Storyboard.TargetName="InnerHintPanel">
                                                <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="False"/>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualTransition>
                                    <VisualTransition x:Name="OpenedToClosed"
                                                  From="Opened" To="Closed"
                                                  GeneratedDuration="0:0:0.15">
                                        <Storyboard>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)"
                                                                       Storyboard.TargetName="SelectBox">
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.0" Value="0" EasingFunction="{StaticResource ExponentialEaseIn}"/>
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.15" Value="-58" EasingFunction="{StaticResource ExponentialEaseIn}"/>
                                            </DoubleAnimationUsingKeyFrames>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)"
                                                                       Storyboard.TargetName="Presenter">
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.0" Value="86" EasingFunction="{StaticResource ExponentialEaseIn}"/>
                                                <EasingDoubleKeyFrame KeyTime="0:0:0.15" Value="24" EasingFunction="{StaticResource ExponentialEaseIn}"/>
                                            </DoubleAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                                       Storyboard.TargetName="SelectBox">
                                                <DiscreteObjectKeyFrame KeyTime="0:0:0.15" Value="Collapsed"/>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualTransition>
                                </VisualStateGroup.Transitions>
                                <VisualStateGroup.States>
                                    <VisualState x:Name="Closed"/>
                                    <VisualState x:Name="Exposed">
                                        <Storyboard>
                                            <DoubleAnimation Storyboard.TargetProperty="(UIElement.Opacity)"
                                                         Storyboard.TargetName="OuterHintPanel"
                                                         Duration="0" To="1.0"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="Opened">
                                        <Storyboard>
                                            <DoubleAnimation Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)"
                                                         Storyboard.TargetName="SelectBox"
                                                         Duration="0" To="0"/>
                                            <DoubleAnimation Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)"
                                                         Storyboard.TargetName="Presenter"
                                                         Duration="0" To="86"/>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                                       Storyboard.TargetName="SelectBox">
                                                <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="Visible"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                                       Storyboard.TargetName="OuterCover">
                                                <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="Visible"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <DoubleAnimation Storyboard.TargetProperty="(UIElement.Opacity)"
                                                         Storyboard.TargetName="OuterHintPanel"
                                                         Duration="0" To="0.0"/>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.IsHitTestVisible)"
                                                                       Storyboard.TargetName="OuterHintPanel">
                                                <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="False"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.IsHitTestVisible)"
                                                                       Storyboard.TargetName="InnerHintPanel">
                                                <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="False"/>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup.States>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Grid HorizontalAlignment="Stretch">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="Auto"/>
                            </Grid.ColumnDefinitions>
                            <Grid Grid.Column="0" HorizontalAlignment="Stretch" primitives:ClipToBounds.IsEnabled="True">
                                <ContentPresenter x:Name="Presenter">
                                    <ContentPresenter.RenderTransform>
                                        <CompositeTransform TranslateX="24"/>
                                    </ContentPresenter.RenderTransform>
                                </ContentPresenter>
                            </Grid>
                            <Rectangle x:Name="InnerHintPanel" Grid.Column="0" Width="24"
                                   Height="{TemplateBinding HintPanelHeight}"
                                   HorizontalAlignment="Left"
                                   Fill="Transparent"
                                   StrokeThickness="0">
                                <Rectangle.RenderTransform>
                                    <CompositeTransform TranslateX="24"/>
                                </Rectangle.RenderTransform>
                            </Rectangle>
                            <ContentControl x:Name="InfoPresenter" Grid.Column="1"
                                        VerticalAlignment="Top"
                                        Content="{TemplateBinding ContentInfo}"
                                        ContentTemplate="{TemplateBinding ContentInfoTemplate}"/>
                        </Grid>
                        <Rectangle x:Name="OuterHintPanel" Width="24"
                               HorizontalAlignment="Left"
                               Height="{TemplateBinding HintPanelHeight}"
                               Fill="{TemplateBinding Background}"
                               StrokeThickness="0" Opacity="0.0"/>
                        <Grid x:Name="OuterCover" IsHitTestVisible="True"
                          Visibility="Collapsed" Background="Transparent"/>
                        <Canvas HorizontalAlignment="Left">
                            <CheckBox x:Name="SelectBox" VerticalAlignment="Center" Margin="12,0,0,0" Visibility="Collapsed"
                                  IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected, Mode=TwoWay}" BorderBrush="#FF4B4B4B" Foreground="#FF424242" Style="{StaticResource CheckBoxStyleGrey}">
                                <CheckBox.RenderTransform>
                                    <CompositeTransform TranslateX="-58"/>
                                </CheckBox.RenderTransform>
                            </CheckBox>
                        </Canvas>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style.Setters>

Now the check box will appear as grey but the actual ticks inside will still be white (since they inherit from the mobile's resources).
What you can do is edit the check box style as well with the same way.
The following code will make the tick grey:
<Style x:Key="CheckBoxStyleGrey" BasedOn="{StaticResource PhoneRadioButtonCheckBoxBase}" TargetType="CheckBox">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="CheckBox">
                <Grid Background="Transparent" HorizontalAlignment="Left">
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="MouseOver"/>
                            <VisualState x:Name="Pressed">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="CheckBackground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneRadioCheckBoxPressedBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="IndeterminateMark">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneButtonBasePressedForegroundBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Disabled">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="CheckBackground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Fill" Storyboard.TargetName="IndeterminateMark">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                        <VisualStateGroup x:Name="CheckStates">
                            <VisualState x:Name="Checked">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="CheckMark">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Visible</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Unchecked"/>
                            <VisualState x:Name="Indeterminate">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility" Storyboard.TargetName="IndeterminateMark">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Visible</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <Grid Margin="{StaticResource PhoneTouchTargetLargeOverhang}">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="32"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <Grid Grid.Column="0" VerticalAlignment="Top">
                            <Border x:Name="CheckBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{StaticResource PhoneBorderThickness}" Background="{TemplateBinding Background}" HorizontalAlignment="Left" Height="32" IsHitTestVisible="False" VerticalAlignment="Center" Width="32"/>
                            <Rectangle x:Name="IndeterminateMark" Fill="{StaticResource PhoneRadioCheckBoxCheckBrush}" HorizontalAlignment="Center" Height="16" IsHitTestVisible="False" Visibility="Collapsed" VerticalAlignment="Center" Width="16"/>
                            <Path x:Name="CheckMark" Data="M0,123 L39,93 L124,164 L256,18 L295,49 L124,240 z" FlowDirection="LeftToRight" HorizontalAlignment="Center" Height="21" IsHitTestVisible="False" Stretch="Fill" StrokeThickness="3" StrokeLineJoin="Round" Visibility="Collapsed" VerticalAlignment="Center" Width="23" Fill="{StaticResource PhoneChromeBrush}"/>
                        </Grid>
                        <ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Grid.Column="1" Foreground="{TemplateBinding Foreground}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="12,0,0,0" Padding="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Grid>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


text:
Q: Shorten lines where they meet I have one line with multiple features that I split into separate lines based on features. Now, the two lines that have separate features meet since they were one line before. What I want to do now is to make a gap between these two lines of a certain size. Any idea how to do it in QGIS?
See the place where they meet? I need to get a gap there of 10m from each side.

A: You can use a Geometry expression like so:
line_substring(
    $geometry,
    10,
    length($geometry) - 10
)

If it is for visualisation purposes only, you can make a Geometry Generator symbol layer:

Result
The thinner line is the original geometry, the thicker overlay is the result of the expression.

If you need to make a new data layer, you can use the same expression with the Geometry by Expression tool.


text:
Q: How to reflow Bootstrap span with Angularjs? I'm new to Angularjs and have no intuition for how to do what I want.
I have a section that displays a bunch of properties.  If the model doesn't contain the property, that item is removed via AngularUi's ui-if like so.

Prop1: {{ model.Prop1 }}

Prop2: {{ model.Prop2 }}

Prop3: {{ model.Prop3 }}

Prop4: {{ model.Prop4 }}

What I want to do is, for example, if two properties are empty, make the bootstrap spans span6 instead.  Basically I want it to split the span12 evenly for the properties that actually have data and remove the others.  ui-if takes care of removing empty properties from the dom nicely, but now how do I adjust the span<x>'s?

A: You could use ng-class or you simply interpolate the class attribute:

Prop1: {{ model.Prop1 }}

And in controller you would do:
$scope.number = 6;

Of course, the logic to set $scope.number would be more complex than just setting it, and should reside in a Controller.


text:
Q: Will including all the angular2 bundles in index.html make imports get data from memory instead of requesting it from the server again? I'm starting out with angular 2, coming from angular 1, which I'm very happy with (outstanding performance all around).
I got the quickstart going with a node backend and abysmal performance (40 seconds to fully load the page in firefox and over 500 requests!). I seriously thought of going back to angular 1 and staying there until angular 3 comes out (i.e. forever).
I searched around and aside from webpack, I found another interesting bit of information: Apparently, if you load all the bundles in the index.html file, the import statements no longer request each file from the server, but get their data from memory. That sounded great! I got all the relevant, minified bundles I could find into index.html and performance improved a good deal (I got ~10s in firefox and 3s in chrome). Still a far cry from angular 1.
Also, I still see over 500 requests of about 7mb total size... so, I'm wondering, are these still requesting the files from the server or are they actually getting the data from memory?
If they are getting their data from memory why are the requests still there and how can I check where they are getting it from?
If they are still requesting the data from the server, one file at a time, how can I force them to get it from memory (or wherever those bundles are stored clientside) when available?
Also, is there anything else I can do to improve performance? (aside from minifying everything into one file/using webpack)
Here is my index.html file:
<html>
<head>
<title>Angular 2 QuickStart</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--<link rel="stylesheet" href="styles.css">-->

<base href="/">

<!-- 1. Load libraries -->
<!-- Required polyfills, in order -->
<script src="es6-shim/es6-shim.min.js"></script>
<script src="angular2/es6/dev/src/testing/shims_for_IE.js"></script>
<script src="angular2/bundles/angular2-polyfills.min.js"></script>
<script src="systemjs/dist/system.js"></script>
<script src="rxjs/bundles/Rx.min.js"></script>
<script src="angular2/bundles/angular2.min.js"></script>
<script src="angular2/bundles/router.min.js"></script>
<script src="angular2/bundles/http.min.js"></script>

<script src="angular2-cookie/bundles/angular2-cookie.min.js"></script>

<script src="lodash/lodash.min.js"></script>
<!-- 2. Configure SystemJS -->
<script>
    System.defaultJSExtensions = true;
    System.import('main').then(null, console.error.bind(console));
</script>
</head>
<!-- 3. Display the application -->
<body>
    <app>Loading...</app>
</body>

I'm exposing node_modules along with the public directory, so this all works just fine.

A: OK, I got it loading nice and fast. The trick, apparently, is to configure systemjs before loading your angular2 stuff; I just do it before loading anything else, like so:
<html>
<head>
    <title>Angular 2 QuickStart</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <base href="/">
    <link rel="stylesheet" href="app/style.css">

    <!-- 1. Load libraries -->
    <!-- Configure SystemJS -->
    <script src="systemjs/dist/system.js"></script>
    <script>
        System.config({ defaultJSExtensions: true });
    </script>

    <!-- Angular libraries -->
    <script src="es6-shim/es6-shim.min.js"></script>
    <script src="angular2/es6/dev/src/testing/shims_for_IE.js"></script>
    <script src="angular2/bundles/angular2-polyfills.min.js"></script>
    <script src="rxjs/bundles/Rx.min.js"></script>
    <script src="angular2/bundles/angular2.min.js"></script>
    <script src="angular2/bundles/router.min.js"></script>
    <script src="angular2/bundles/http.min.js"></script>
    <script src="angular2-cookie/bundles/angular2-cookie.min.js"></script>

    <!-- Other libraries -->
    <script src="lodash/lodash.min.js"></script>

    <!-- 2. Configure SystemJS -->
    <script>
        System.import('main').then(null, console.error.bind(console));
    </script>
</head>
<!-- 3. Display the application -->
<body>
<app>Loading...</app>
</body>
</html>

And there she goes!


text:
Q: leaks tool doesn't report memory leak on os x I am trying to learn how to use leaks tool from the command line, here is my code that should produce a leak on NSString:
#import <Foundation/Foundation.h>
#import <unistd.h>

int main(int argc, const char *argv[])
{
    NSString *string = [[NSString alloc] init];

    pid_t pid = getpid();
    NSLog(@"pid: %d", pid);

    string = nil;
    [NSThread sleepForTimeInterval:20];

    return 0;
}

I learned that leaks refreshes itself every 10 seconds (not sure if this is true, but I set the interval to 20 seconds).
This should produce leaks because it is not in auto release pool and also I compiled with -fno-objc-arc for "safety".
I tried to run leaks [pid] multiple times with no leaks reported. What am I doing wrong here?
Also, I am a command line fan and really want to be able to use something similar to valgrind, which doesn't support os x 10.8 very well. It is annoying that I have to put sleep in my code in order to use leaks tool.
Can anyone please shine some lights here?

A: NSString *string = [[NSString alloc] init];

returns a shared instance of an empty string (and multiple calls return the same instance).
The Foundation framework keeps a reference to this shared instance, therefore
 there is no memory leak.
The same behaviour can be observed with other immutable classes (NSArray, NSDictionary).
If you replace your line with
NSMutableString *string = [[NSMutableString alloc] init];

then you will see a memory leak.

A: *

*If you use ARC there's no leak.

*The empty string ([[NSString alloc] init]) is most definitely a shared/reused instance. The system has to keep a reference to the shared instance, so leaks would (correctly) not report it.

A better test would be to use a custom object. Then you can be sure that there is no magic involved.
#if __has_feature(objc_arc)
#error This leaks test only works when ARC is off
#endif

@interface Orphan : NSObject @end
@implementation Orphan @end

// in main, create an object without keeping a reference to it:
[Orphan new];


text:
Q: Conceptual differences between Flash CS5 and Flash builder 4 What are the conceptual differences between Adobe Flash CS5 and Flash Builder 4? Both seem to be equally useful for authoring actionscript enabled rich interactive apps both internet and desktop. What is the difference in principle of programming when using these two tools apart from that the UI is represented in Flash Builder in mxml?

A: One of the main difference is the target user. Flash CS is traditionally aimed at designers, whilst FlashBuilder is aimed at developers.
Most people generally agree that Flash CS should be used for designing graphic assets whilst FB would be use for the logic or programming of these assets.
It is generally accepted that Flash CS sucks as an IDE , so programmers tend to use other options such as FDT , FlashDevelop or Textmate to name a few, but there are other options.
This being said, the type of tools offered by both platforms differs greatly and one of the most powerful option is simply to use both, depending of course on your type of projects.
Game development for instance would be an ideal candidate.
As for mxml & FlashBuilder , please note that this only applies if you use the Flex framework. It is possible to develop pure Actionscript projects with FB, in which case your UI design could be done in Flash CS and brought into FB via the use of SWCs.
Finally , Adobe has greatly facilitated the workflow when using both platforms, it's not yet ideal but progress has been made.


text:
Q: RethinkDB: .get() with just part of the uuid? Let's say this is the uuid of one of my documents in RethinkDB: 594a64ab-b78b-4838-a79f-318020a352a9
Normally, to retrieve the document, I do:
r.db("databasename").table("tablename").get('594a64ab-b78b-4838-a79f-318020a352a9')
Is there some way I can achieve the same thing with only some prefixing portion of the uuid? e.g. I want to do this:
r.db("databasename").table("tablename").getByPrefix('594a64ab-b78b')
Is this possible?

A: Another solution, including all the steps:
1/ Create test table
r.table('foo').insert([
  {foo: 1},
  {foo: 2},
  {foo: 3},
  {foo: 4},
  {foo: 5}
])

2/ List table content
r.table('foo')

Output:
[
  {"foo":4,"id":"3c6873af-0dfc-41d3-99ad-894bab981635"},
  {"foo":1,"id":"302baaa5-1443-408c-bb58-7970e71129ac"},
  {"foo":2,"id":"ca5ff9c2-8079-4a19-9cfc-4e7b0a834555"},
  {"foo":5,"id":"aabb6c38-710a-444c-a4ae-b8ee14b5e802"},
  {"foo":3,"id":"4fc2e6e8-9434-4fa9-831b-4208bc82fd35"}
]

3/ Create secondary index
r.table('foo').indexCreate('id_prefix', function(d){
  return d('id').slice(0, 13)
})

4/ List index content
r.table('foo').distinct({index:'id_prefix'})

Output:
["302baaa5-1443","3c6873af-0dfc","4fc2e6e8-9434","aabb6c38-710a","ca5ff9c2-8079"]

5/ Use the index to find the document(s) with prefix "4fc2e6e8-9434"
r.table('foo').getAll("4fc2e6e8-9434", {index:'id_prefix'})

Output
[{"foo":3,"id":"4fc2e6e8-9434-4fa9-831b-4208bc82fd35"}]

This is a longer setup and solution, BUT, on a table of for example several millions docs, it can really make it faster.

A: You can do use this but it is slow though:
r.db("databasename").table("tablename")
  .filter(r.row('id').match('^594a64ab-b78b')))


text:
Q: How to create restful api in rails3? How to create restful api in rails?
gem 'rails-api'

if i use rails-api gem is it create a restfull api? if no which gem should I use to create restful api?

A: Grape gem is excellent for building REST Api's! See the link:
https://github.com/intridea/grape


text:
Q: How can I get the MapView.Marker to display on react-native-maps I am having some trouble with a piece of react-native-maps code. The map displays fine but I cannot get the markers to display. I tried hardcoding the markers to my initial region. I am not getting any errors. I have also tried zooming out completely and the markers do not show anywhere.
this.state = {
        peepsLocations: [
            {
                rotation: 78,
                position:{
                    latitude: 26.12241,
                    longitude: -80.14238,
                }

            }, {
                rotation: 90,
                position:{
                    latitude: 26.12235,
                    longitude: -80.14638,
                }

            }, {
                rotation: 10,
                position: {
                    latitude: 26.12231,
                    longitude: -80.14338,
                }
            },
        ]
    };

    this.initialRegion = {
        latitude: 26.12231,
        longitude: -80.14338,
        latitudeDelta: .00922,
        longitudeDelta: .00421
    }
}

componentDidMount(){
    this._onRegionChange.call(this, this.initialRegion)
}

render() {
    return (
        <View style={styles.container}>
            <MapView
                provider="google"
                initialRegion={this.initialRegion}
                style={styles.fullScreenMap}/>
            {
                this.state.peepsLocations.map((peepLocation, i) => (
                    <MapView.Marker
                    key={i}
                    coordinate={peepLocation.position}
                    title={`peep ${i}`}
                    description={`peepLocation.rotation.toString() this peep is ...`}
                    >

                    </MapView.Marker>
                ))
            }

        </View>
    );
}

A: Simple mistake really that I did not spot initially. I closed the MapView before returning the Markers. It wasn't until I stepped away for a few hours and went back with a new strategy that I saw the problem.
Thanks for your patience and helping a noob.


text:
Q: Explorer ignores ParseDisplayName in Shell Namespace Extension I am writing a Shell Namespace Extension.
How may I force explorer to access (and open) items that are not enumerated with IShellFolder::EnumObjects by typing their parsing name in the address bar?

I have seen SFGAO_NONENUMERATED flag which I believe is used to mark such items (so in theory it should be possible, otherwise why do one need this flag?). I don't want to use SFGAO_HIDDEN or SFGAO_SYSTEM because such items could be seen nevertheless.
I am expecting explorer to call IShellFolder::ParseDisplayName with absolute or at least relative path to the item requested. But instead it is calling IShellFolder::ParseDisplayName only for the first segment of the parsing name (basically the first folder's parsing name). After this explorer queries content of each sub folder via IShellFolder::EnumObjects and calls IShellFolder::GetDisplayNameOf to get both display and parsing name of each item enumerated.
Based on this comment from Raymond Chen I understood that it is normal for explorer to rely on both display and parsing names to retrieve the item requested in the address bar. But the biggest issue here is that my items (that I want to obtain) are not enumerated. So explorer does not know about their existence.


text:
Q: How does Entity Framework store referenced data in the database? Let's say there is an object called parent which has a reference to another object called child as a property. After creating set of parent objects in a DbContext, I save one of them into the database. When I ask for the said object from the database, I also receive his child property. I cannot find where the children are stored. How does this mapping work?
public class Route
{
    public Guid Id { private set; get; }
    public Clue[] Clues { private set; get; }
}

CreateTable(
                "dbo.Routes",
                c => new
                    {
                        Id = c.Guid(nullable: false),
                    })
                .PrimaryKey(t => t.Id);


text:
Q: How can I have the SQL connection string in one place? Currently I have the SQL connection string in every form in my application, like this:
Dim cnx As New SqlConnection("Server = SERVERNAME\SQLSERVEREXPRESS; " &
                             "Database = DatabaseName; " &
                             "Trusted_Connection = True;")
Dim cmd As SqlCommand
Dim sdr As SqlDataReader

The problem is when I need to change it, I have to do it in every form in the application. What are some better ways to do this?
Thanks!
EDIT
I ended up using Christopherous 5000 answer translated to VB.NET:
Public Shared Function GetConnectionString(name As String) As String
    Dim connectionString = ConfigurationManager.ConnectionStrings(name)

    If connectionString Is Nothing OrElse String.IsNullOrEmpty(connectionString.ConnectionString) Then
        Throw New ConfigurationErrorsException(String.Format("No connection string for '{0}' found", name))
    End If

    Return connectionString.ConnectionString
End Function

A: You should use the web.config file to store connection string (these can be encrypted if needed)
I use a helper class with this static method when needing a connection;
public static string GetConnectionString(string name)
        {
            var connectionString = ConfigurationManager.ConnectionStrings[name];

            if (connectionString == null || string.IsNullOrEmpty(connectionString.ConnectionString))
                throw new ConfigurationErrorsException(string.Format("No connection string for '{0}' found", name));

            return connectionString.ConnectionString;
        }

A: App.config or Web.config depending on project would make sense.  If you won't be keeping your compiled code private than you'd want to bake your own implementation.  Accessing database connection string using app.config in C# winform


text:
Q: In C are malloc(256) and malloc(sizeof(char)*256) equivalent? I see that people often write C code such as:
char *ptr = malloc(sizeof(char)*256);

Is that really necessary? The standard says that sizeof(char)==1 by definition, so doesn't it make sense just to write:
char *ptr = malloc(256);

A: The issue should not even exist. You should adopt a more elegant idiom of writing your malloc's as
ptr = malloc(N * sizeof *ptr)

i.e. avoid mentioning the type name as much as possible. Type names are for declarations, not for statements.
That way your mallocs will always be type-independent and will look consistent. The fact that the multiplication by 1 is superfluous will be less obvious (since some people find multiplication by sizeof(char) annoying).

A: They're equivalent, but it's good to remain consistent. It also makes it more explicit, so it's obvious what you mean. If the type ever changes, it's easier to find out what code needs to be updated.

A: That may be true, but it's only true for that specific case of char.
I personally think it's good form to use the malloc(sizeof(char) * 256) form, because someone changing the type, or copying the code for a similar purpose with a different type may miss the subtleties of that case.

A: Yes, C defines sizeof(char) to be 1, always (and C++ does as well).
Nonetheless, as a general rule, I'd advise something like:
char *ptr = malloc(256 * sizeof(*ptr));

This way, when your boss says something like: "Oh, BTW we just got an order from China so we need to handle all three Chinese alphabets ASAP", you can change it to:
wchar_t *ptr // ...

and the rest can stay the same. Given that you're going to have about 10 million headaches trying to handle i18n even halfway reasonably, eliminating even a few is worthwhile. That, of course, assumes the usual case that your chars are really intended to hold characters -- if it's just a raw buffer of some sort, and you really want 256 bytes of storage, regardless of how many (of few) characters that may be, you should probably stick with the malloc(256) and be done with it.

A: While there's nothing technically wrong with writing sizeof(char), doing so suggests that the author is not familiar with C and the fact that sizeof(char) is defined as 1. In some projects I've worked on, we actually grep for instances of sizeof(char) as an indication that the code might be low-quality.
On the other hand, ptr = malloc(count * sizeof(*ptr)); is a very useful documentation and bug-avoidance idiom, and makes sense even if sizeof(*ptr) is 1. However, it needs to be preceded by if (count > SIZE_MAX/sizeof(*ptr)) { /* handle overflow */ } or you have a serious bug. This can be especially relevant when allocating arrays of wchar_t or complex structures of the same length as an input string, for example when converting a UTF-8 string to wchar_t string or building a DFA to match the string.

A: Yes, they are technically equivalent. It's just a matter of style - using sizeof for every allocation makes you less likely to miss it when you really do need it.


text:
Q: Physics journals that focus on expository work As the title says, I'm looking for journals that focus on expository work in Physics. What I mean is that the journal is less focused on communication between professionals and more on disseminating knowledge to the wider physics community, including students. For example Physical Review Letters are a great series of journals, but their terse length limits combined with their prestige means that most of the articles are meant for a narrow group of professionals studying a very specific topic. It would be nice to read a peer-reviewed journal that you are able to really dive into and come out with a new comprehension of topics you might not have fully understood before. I've found that the American Journal of Physics is pretty good in this regard. I'm wondering if there are any others.

A: *

*Reviews of Modern Physics has been created exactly with that scope, as you can see in the link. Feynman's article on the path integral approach, for example, was published on this journal.

*Physics Reports is similar to Rev. Mod. Phys. albeit the article submission is by invitation only.

*Reports on Progress in Physics is another one.

A: The American Association Institute of Physics (AIP; the parent organization of the APS and AAPT among others) publishes The Physics Teacher, which publishes articles on pedagogy and exposition.
Their blurb reads:

Dedicated to the strengthening of the teaching of introductory physics at all levels, The Physics Teacher provides peer-reviewed materials to be used in the classrooms and instructional laboratories. It includes:
Innovative physics demonstrations; New ways of doing lab experiments; Ideas for presenting difficult concepts more clearly; Suggestions for implementing newer technology into teaching; Historical insights that can enrich the physics course and Book and film reviews.

A: I'm not sure if this is what you're looking for, but physics news websites, like phys.org and nature news are really good for "exposition" of different topics. I'm a PhD student in physics and I use phys.org and nature news and views (http://www.nature.com/subjects/physics#news-and-views) to have a non-technical source for other physical subjects and if I'm interested in a more technical and in depth treatment I'll check out the peer reviewed papers associated with those articles.


text:
Q: Batch size, Epoch, and iteration in a many-to-one RNN I am having trouble defining mainly the batch size when it comes to a many-to-one RNN.
I have been looking at the following article: https://medium.com/@erikhallstrm/hello-world-rnn-83cd7105b767
This is on a many-to-many RNN, but still the definition of the batch puzzles me.
What is the batch size when it comes to a many-to-one RNN?
This would probably answer my other two confusions on epoch and iteration.

A: In the example you link, a sequence is a vector of shape (N,), since a sequence contains N binary numbers.
If instead of numbers, the items forming the sequence were vectors, each sequence would have shape (N, item_size).
RNNs process several sequences at the same time, in parallel. This is what we call a batch. The number of sequences processed in parallel is the batch_size, and the shape of the input to the RNN will be (batch_size, N).
In the many-to-one scenario, the batch size is the same. The only thing that changes is the output shape, because instead of producing an output of size (batch_size, N), it will be just (batch_size,) (or (batch_size, 1)) since each sequence will be mapped to a single output.
To summarize, the batch size is the number of sequences processed in parallel, so there is no difference between the many-to-many and many-to-one cases.
Regarding your confusion with epoch/iteration, an epoch usually refers to iterating over the whole training dataset once, while iteration refers to processing a single batch to do one SGD step.


text:
Q: How to read error62 in strace log? I am trying to read an output of strace log.
I got this line:
write(3, "Error. The program should receiv"..., 62Error. The program should receive a single argument. Exiting.
) = 62

Can you help me to read this line? What "62Error" means?

A:
What "62Error" means?

This strace output was probably got mixed with program output.
62 part should be from strace output and Error part should be from program output. Normally strace output should be:
write(3, "Error. The program should receiv"..., 62) = 62

And program output should be:
Error. The program should receive a single argument. Exiting.

Try to separate strace output from program output with -o option:
strace -o filename program


text:
Q: Retrieving Order details using id The shopping cart app I'm building using Rails 4.1 has an order_type model with the schema:
create_table "order_types", force: true do |t|
    t.string   "order_name"
    t.integer  "max_limit"

This belongs to the Orders model. Users can pick the order type from the new order page and I use collection select to display this. The order_type_id is saved to each order that's created. The order controller.rb:
class OrdersController < ApplicationController
    def new
        @order = Order.new
        @item = @order.items.build
    end

    def index
        @orders = Order.all
    end

    def show
        @order = Order.find(params[:id])
            @items = Item.where(:order_id => @order.id)
    end

    def create
        @order = current_user.orders.new(order_params)
        respond_to do |format|
            if @order.save
                OrderMailer.order_submission(@order).deliver
                format.html { redirect_to @order, notice: 'Order Submitted.' }
                format.json { render :show, status: :created, location: @order }
            else
                format.html { render :new }
                format.json { render json: @order.errors, status: :unprocessable_entity }
            end
        end
    end

Here's the collecton select used in the form:

                <%= f.label :order_type_id %>

                <%= f.collection_select(:order_type_id, OrderType.all, :id, :order_name, prompt: true, class: "form-control")  %>

I would like to retrieve and display the Order Type details based on the order_type_id that's stored. How do I do this?

A: <%= @order.order_type %>

Will get you the OrderType associated with that particular order.  Then it is just:
<%= @order.order_type.order_name %>

To retrieve an attribute on the OrderType.

A: You can write a function in ApplicationHelper for example : get_order_type_details_by_id(order_type_id) and simply return the order details. You can directly call that helper function from any view templates. As functions defined in ApplicationHelper is accessible in all views.
Or you can use association for getting the order details


text:
Q: MySql return type for extract function Can anyone tell me what would be the type that is returned from MySQL for an extract function
My query would look something like this:
select extract(month from logged_ts) from process_log limit 10;
I want to know the type of month returned , is it Integer or Long
when i tried to check the types by following query
select extract(hour from '2016-01-01 05:15:30') as hh,
       extract(minute from '2016-01-01 05:15:30') as min,
       extract(second from '2016-01-01 05:15:30') as sec,
       extract(year from '2016-01-01 05:15:30') as yyyy,
       extract(month from '2016-01-01 05:15:30')as mm,
       extract(day from '2016-01-01 05:15:30') as dd;

desc extract_time_tbl;

I am getting this result:
Output:
    hh   int(2)
    min  int(2)
    sec  int(2)
    yyyy int(4)
    mm   int(2)
    dd   int(2)

I want to know whether the type  would be the same each time i query.

A: All the sql select method return a result resource, in loosely meaning you can call this a table or multi diamentiona array. When there is only one element in the result, e.g,
Select count(id) from table

Or
SELECT EXTRACT(WEEK FROM "2017-06-15");

The return type is one cell table. Use you scripting language to read the result resource (the table) and parse the data.
If you are using php, the following pseudo code can be a help
$res = mysqli_query("SELECT EXTRACT(MONTH FROM "2017-06-15");");
$ar = mysqli_fetch_row($res);
$val = $ar[0];

The data type of value will be string but you can convert it to any of your choice if you know it will be. In the above case the $val will be 6.


text:
Q: relation between etcd/zookeeper/consul and other configuration management tools like chef/puppet/..? Just according my high level understanding, both groups (for eg., etcd and puppet) do distributed configuration management, am I right or wrong?  Or is it that puppet uses etcd internally? If so, an example may help.
Regards,
Seenu.

A: Although Chef/Puppet and etcd/zookeeper/consul both can be used to build your infrastructure and for service discovering, the services and solution they offer are quite different. They are not confronted solutions and in fact can be used simultaneously, because the services they provide are different.

*

*The IT automation tools (i.e.: Chef/Pupper/Ansible...) provide a full stack to deploy, provision and manage you infrastructure. They offer solutions to keep information about your architecture (eg.: which machines provide some services), this is only a small piece in the puzzle. This information is updated and used only during the convergence of a node, and not should be used for a very dynamic infrastructure.

*etcd/zookeeper/consul are K/V distributed stores with some differences in implementation and service provided, but very similar in concept. They provide mechanism for service discovery, and fast update of this information. They don't provide a full stack to deploy and configure your infrastructure, although they can be used as part of a stack to achieve this goal, working with other tools (i.e.: confd, consul-template, scripts, or chef/puppet/ansible...). etcd/zookeeper/consul are solutions designed thinking in very dynamic infrastructure and provide an easy interface to keep you services configuration updated in any moment, but you will need other tools to automate all your infrastructure.


text:
Q: CXF DynamicClientFactory efficiency I need to generate Java client for web service. I have two choices to do that one is use Apache CXF DynamicClientFactory class and the other is use JAX-WS Dispatch API.
From CXF documentation I understood that DynamicClientFactory class will generate the web service SEI, data classes at runtime (using wsdl2Java tool). If I want to call any web service method I need to load the appropriate data class name and I needs to set the parameter using reflection like follows.
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client client = dcf.createClient("people.wsdl", classLoader);

Object person = Thread.currentThread().getContextClassLoader().loadClass("com.acme.Person").newInstance();

Method m = person.getClass().getMethod("setName", String.class);
m.invoke(person, "Joe Schmoe");

client.invoke("addPerson", person);

In the above code Person class is generated at runtime by CXF and reflection is used to set the property values.
My question here is: if I want to set 20 parameter values, then I needs to make 20 reflection call to do that. Is this an efficient way to do that? Or is there any alternative? Or is better to use Dispatch API from JAX-WS? Please help me.


text:
Q: Multiplyr and prophet for parallel grouped prediction: Error in checkForRemoteErrors(lapply(cl, recvResult)) I am willing to make parallel predictions using multidplyr and prophet. Consider the following data
library(tidyr)
library(dplyr)
library(multidplyr)
library(prophet)

ds = as.Date(c('2016-11-01', '2016-11-02', '2016-11-03', '2016-11-04',
            '2016-11-05', '2016-11-06', '2016-11-07', '2016-11-08',
            '2016-11-09', '2016-11-10', '2016-11-11', '2016-11-12',
            '2016-11-13', '2016-11-14', '2016-11-15', '2016-11-16',
            '2016-11-17', '2016-11-18', '2016-11-19', '2016-11-20',
            '2016-11-21', '2016-11-22', '2016-11-23', '2016-11-24',
            '2016-11-25', '2016-11-26', '2016-11-27', '2016-11-28',
            '2016-11-29', '2016-11-30', '2016-11-01', '2016-11-02',
            '2016-11-03', '2016-11-04', '2016-11-05', '2016-11-06',
            '2016-11-07', '2016-11-08', '2016-11-09', '2016-11-10',
            '2016-11-11', '2016-11-12', '2016-11-13', '2016-11-14',
            '2016-11-15', '2016-11-16', '2016-11-17', '2016-11-18',
            '2016-11-19', '2016-11-20', '2016-11-21', '2016-11-22',
            '2016-11-23', '2016-11-24', '2016-11-25', '2016-11-26',
            '2016-11-27', '2016-11-28', '2016-11-29', '2016-11-30'))

y = c(15, 17, 18, 19, 20, 54, 67, 23, 12, 34, 12, 78, 34, 12, 3, 45, 67, 89, 12, 111, 123, 112, 14, 566, 345, 123, 567, 56, 87, 90, 45, 23, 12, 10, 21, 34, 12, 45, 12, 44, 87, 45, 32, 67, 1, 57, 87, 99, 33, 234, 456, 123, 89, 333, 411, 232, 455, 55, 90, 21)

group = c("A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A",
          "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A",
          "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B",
          "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B")

df = data.frame(ds, group, y)

Although I am able to make per-group sequential predictions using
df %>%
  group_by(group) %>%
  do(predict(prophet::prophet(.), prophet::make_future_dataframe(prophet::prophet(.), periods = 7)))

I am not being able to parallelize it. I have tried so far with the partition and collect commands as suggested here
multidplyr::cluster_library(cluster, "prophet")

df %>%
  partition(group) %>%
  do(predict(prophet::prophet(.), prophet::make_future_dataframe(prophet::prophet(.), periods = 7))) %>%
  collect()

Which gives me an error
Error in checkForRemoteErrors(lapply(cl, recvResult)) :
  2 nodes produced errors; first error: 'data' must be of a vector type, was 'NULL'
In addition: Warning message:
group_indices_.grouped_df ignores extra arguments

Or like following
multidplyr::cluster_library(cluster, "purrr")
multidplyr::cluster_library(cluster, "prophet")

df %>%
  partition(group) %>%
  mutate(m = purrr::map(data, prophet::prophet)) %>%
  mutate(future = purrr::map(m, prophet::make_future_dataframe, period = 7)) %>%
  mutate(forecast = purrr::map2(m, future, predict)) %>%
  collect()

Which gives me the following error
Error in checkForRemoteErrors(lapply(cl, recvResult)) :
  2 nodes produced errors; first error: Evaluation error: `.x` is not a vector (closure).
In addition: Warning message:
group_indices_.grouped_df ignores extra arguments

Thus, I am lost on how to proceed. Any suggestion is more than welcome. Thank you in advance.
Ps.: Here is my sessionInfo()
> sessionInfo()
R version 3.3.3 (2017-03-06)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Debian GNU/Linux buster/sid

locale:
 [1] LC_CTYPE=C                 LC_NUMERIC=C
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] purrr_0.2.2.2         bindrcpp_0.2          prophet_0.1.1
[4] Rcpp_0.12.12          multidplyr_0.0.0.9000 dplyr_0.7.2
[7] tidyr_0.6.3

loaded via a namespace (and not attached):
 [1] bindr_0.1            magrittr_1.5         munsell_0.4.3
 [4] lattice_0.20-35      colorspace_1.3-2     R6_2.2.2
 [7] rlang_0.1.1          extraDistr_1.8.6     plyr_1.8.4
[10] tools_3.3.3          parallel_3.3.3       grid_3.3.3
[13] gtable_0.2.0         StanHeaders_2.16.0-1 lazyeval_0.2.0
[16] assertthat_0.2.0     tibble_1.3.3         rstan_2.16.2
[19] gridExtra_2.2.1      ggplot2_2.2.1        codetools_0.2-15
[22] inline_0.3.14        glue_1.1.1           stringi_1.1.5
[25] scales_0.4.1         stats4_3.3.3         pkgconfig_2.0.1
[28] zoo_1.8-0


text:
Q: Access remote database failed,"(1045,Access denied for user......)" local machine environment:

*

*centos 6.7

*python 2.7.10

*Flask-MySQLdb 0.2.0

*local ip: 112.25.76.72

*remote ip: 221.228.203.203

Both of the code run on local Machine;
when I access the remote database in local python command line environment like this:
>>>import MySQLdb
>>>conn = MySQLdb.connect(host="221.228.203.203",user="test_user",passwd="test_passwd",db="test_db",charset="utf-8")

it access successfully,but when I write these code into a python script login.py:
import MySQLdb

conn = None

try:
    conn = MySQLdb.connect(host="221.228.203.203",user="test_user",passwd="test_passwd",db="test_db",charset="utf-8")
    cur = conn.cursor()

except Exception,e:
    print e

finally:
    if conn:
        conn.close()

then execute "python login.py" in the terminal,it access failed,the error info is :
(1045, "Access denied for user 'test_user'@'112.25.76.72' (using password: YES)")
Why? Their python environment is the same.
if you can solve it,please help me.

A: You should check the configurations of your user in the database server. It will be stored in database mysql.
You can get the list of users with:
SELECT user, host FROM mysql.user;

You shouldn't delete the user test_user@localhost. You can try to execute it on your database server
CREATE USER 'test_user'@'%' IDENTIFIED BY 'test_passwd'
GRANT ALL PRIVILEGES ON *.* TO 'test_user'@'%'  WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON *.* TO 'test_user'@'localhost'  WITH GRANT OPTION;


text:
Q: Wrong sizes for block reduction in CUDA? I was checking out this sum_reduction.cu example and tutorial and noticed that for certain problem sizes it doesn't work e.g. it works with problem size n=2000 but not with n=3000. Apparently it always work with problem sizes that are multiple of the block size but neither the tutorial nor the example code states so. The question is, does this reduction algorithm only works for certain problem sizes? the example they chose N=256k which is even, a power of two and also multiple of the block size 512.
For self containment I paste the most important bits of (a template version of) the code here:
template<typename T>
__global__ void kernelSum(const T* __restrict__ input, T* __restrict__ per_block_results, const size_t n) {
    extern __shared__ T sdata[];

    size_t tid = blockIdx.x * blockDim.x + threadIdx.x;

    // load input into __shared__ memory
    T x = 0.0;
    if (tid < n) {
        x = input[tid];
    }
    sdata[threadIdx.x] = x;
    __syncthreads();

    // contiguous range pattern
    for(int offset = blockDim.x / 2; offset > 0; offset >>= 1) {
        if(threadIdx.x < offset) {
            // add a partial sum upstream to our own
            sdata[threadIdx.x] += sdata[threadIdx.x + offset];
        }
        // wait until all threads in the block have
        // updated their partial sums
        __syncthreads();
    }

    // thread 0 writes the final result
    if(threadIdx.x == 0) {
        per_block_results[blockIdx.x] = sdata[0];
    }
}

and to invoke the kernel:
// launch one kernel to compute, per-block, a partial sum
block_sum<double> <<<num_blocks,block_size,block_size * sizeof(double)>>>(d_input, d_partial_sums_and_total, num_elements);

// launch a single block to compute the sum of the partial sums
block_sum<double> <<<1,num_blocks,num_blocks * sizeof(double)>>>(d_partial_sums_and_total, d_partial_sums_and_total + num_blocks, num_blocks);

To my understanding if the problem size is smaller than the block reduction this statement T x = 0.0; ensures that the element is zeroed out and thus should work but it doesn't?
UPDATE: I am sorry the float/double thing was a typo while preparing the question and not the real problem.

A: *

*The code you have posted is not consistent, as your templated kernel
is called kernelSum but you are invoking something called
block_sum.

*Furthermore, I don't believe your usage of the templated kernel
function could possibly be correct as written:
block_sum<double> <<<num_blocks,block_size,block_size * sizeof(float)>>>(d_input, d_partial_sums_and_total, num_elements);
           ^                                                     ^
           |  these types are required to match                  |

The kernel template is being instantiated with type double.  Therefore it is expecting enough shared memory to store block_size double quantities, based on this line:
extern __shared__ T sdata[];

But you are only passing half of the required storage:
block_size * sizeof(float)

I believe that's going to give you unexpected results.

*The reduction as written does expect that the block
dimension is a power of 2, due to this loop:
// contiguous range pattern
for(int offset = blockDim.x / 2; offset > 0; offset >>= 1) {

This is not likely to be an issue on the first kernel call, because you are probably choosing a power of two for the number of threads per block (block_size):
block_sum<double> <<<num_blocks,block_size,...

However, for the second kernel call, this will depend on whether num_blocks is a power of two, which depends on your grid calculations, which you haven't shown:
block_sum<double> <<<1,num_blocks,...

*Finally, the first kernel launch will fail if num_blocks exceeds the limit for your device.  This may happen for very large data sets but probably not for size 3000, and it depends on your grid calculations which you haven't shown.
Item 3 above is a difficult requirement to satisfy on the fly for arbitrary vector sizes.  Therefore I would suggest an alternate reduction strategy to handle arbitrary sized vectors.  For this I would suggest that you study the CUDA reduction sample code and presentation.
Here's a complete program, mostly based on the code you have shown, that has the above issues addressed, and seems to work for me for a size of 3000:
#include <stdio.h>
#include <stdlib.h>
#define DSIZE 3000
#define nTPB 256

template<typename T>
__global__ void block_sum(const T* __restrict__ input, T* __restrict__ per_block_results, const size_t n) {
    extern __shared__ T sdata[];

    size_t tid = blockIdx.x * blockDim.x + threadIdx.x;

    // load input into __shared__ memory
    T x = 0.0;
    if (tid < n) {
        x = input[tid];
    }
    sdata[threadIdx.x] = x;
    __syncthreads();

    // contiguous range pattern
    for(int offset = blockDim.x / 2; offset > 0; offset >>= 1) {
        if(threadIdx.x < offset) {
            // add a partial sum upstream to our own
            sdata[threadIdx.x] += sdata[threadIdx.x + offset];
        }
        // wait until all threads in the block have
        // updated their partial sums
        __syncthreads();
    }

    // thread 0 writes the final result
    if(threadIdx.x == 0) {
        per_block_results[blockIdx.x] = sdata[0];
    }
}

int main(){

  double *d_input, *d_partial_sums_and_total, *h_input, *h_partial_sums_and_total;

  int num_elements=DSIZE;
  int block_size = nTPB;
  int num_blocks = (num_elements + block_size -1)/block_size;
  // bump num_blocks up to the next power of 2
  int done = 0;
  int test_val = 1;
  while (!done){
   if (test_val >= num_blocks){
     num_blocks = test_val;
     done = 1;}
   else test_val *= 2;
   if (test_val > 65535) {printf("blocks failure\n"); exit(1);}
   }

  h_input = (double *)malloc(num_elements * sizeof(double));
  h_partial_sums_and_total = (double *)malloc((num_blocks+1)*sizeof(double));

  cudaMalloc((void **)&d_input, num_elements * sizeof(double));
  cudaMalloc((void **)&d_partial_sums_and_total, (num_blocks+1)*sizeof(double));

  double h_result = 0.0;
  for (int i = 0; i < num_elements; i++) {
    h_input[i] = rand()/(double)RAND_MAX;
    h_result += h_input[i];}

  cudaMemcpy(d_input, h_input, num_elements*sizeof(double), cudaMemcpyHostToDevice);
  cudaMemset(d_partial_sums_and_total, 0, (num_blocks+1)*sizeof(double));

// launch one kernel to compute, per-block, a partial sum
  block_sum<double> <<<num_blocks,block_size,block_size * sizeof(double)>>>(d_input, d_partial_sums_and_total, num_elements);

// launch a single block to compute the sum of the partial sums
  block_sum<double> <<<1,num_blocks,num_blocks * sizeof(double)>>>(d_partial_sums_and_total, d_partial_sums_and_total + num_blocks, num_blocks);

  cudaMemcpy(h_partial_sums_and_total, d_partial_sums_and_total, (num_blocks+1)*sizeof(double), cudaMemcpyDeviceToHost);

  printf("host result   = %lf\n", h_result);
  printf("device result = %lf\n", h_partial_sums_and_total[num_blocks]);
}

For brevity/readability, I have dispensed with error checking in the above code.  When having difficulty with a cuda code, you should always do proper cuda error checking.
Also, in the future, you will make it easier for others to help you if you post a complete code to demonstrate what you are doing, as I have done above.


text:
Q: Anaconda/OpenCV: Installing with Tracking features Hopefully someone can point me in the right direction here.
I'm using the latest release of Anaconda (Python 2.7). I would like to use it with OpenCV with the tracking features. I've tried various versions of the cv2.pyd file including 3.0, 3.1, 3.2, 3.3 and 3.4. However, the examples I've found use one of the following commands which are not found in the module.
tracker = cv2.Tracker_create(tracker_type)

or
tracker = cv2.TrackerKCF_create()

The usage of either of these depends which OpenCV version is being used. However, neither of them work, both with the following error.
'module' object has no attribute 'Tracker_create / or TrackerKCF_create'

All of the other features in OpenCV seem to work fine.
Is the cv2.pyd file I'm extracting from the Windows OpenCV install limited to certain features?
If I use the following in the Anaconda Prompt
conda install -c menpo opencv3

it installs the tracking features I need. However, it installs v3.1 of OpenCV which is known to have bugs with the tracking features. Ideally I wan't v3.4 of OpenCV.
Any help would be appreciated.

A: If you're using Anaconda then it would be wise to use it's environment management tools. Create an environment.yml file with the following contents:
environment.yml using conda-forge/opencv & python 3.6
name: opencv-env      # any name for the environment
channels:
- conda-forge
dependencies:         # everything under this, installed by conda
- python=3.6
- opencv=3.4
- pip:                # everything under this, installed by pip
  - future

environment.yml using pip/opencv-python & python 3.6
name: opencv-env      # any name for the environment
channels:
- defaults
dependencies:         # everything under this, installed by conda
- python=3.6
- pip:                # everything under this, installed by pip
  - future
  - opencv-python>=3.4

How to install the environment?
conda create --force -f environment.yml
How to activate the environment?
source activate opencv-env
Once you've activated the environment, you can check the version of opencv.


text:
Q: Android Virtual Device (AVD) displays a black screen on start
My Android Virtual Device (AVD) displays an id of zero on the first run on the screen's bezel i.e 0:emulator-name. See screenshot above.
After 4-5 runs of the same virtual device it displays the expected id i.e 5558:emulator-name.
But previous instances of the same AVD will be running with black screen displays and they tend to consume system resources slowing down my entire machine.
My system specifications are as follows:-
AMD A8-4500 Quad-Core
8GB RAM
running Kali Linux 64bit Gnome; a Debian distro.


text:
Q: Put retrofit object to other activity in Kotlin As I mentioned in the title, I am trying to send an object named "service" that I use in MainActivity to OtherActivity, but I was not successful.
Constant.kt
class Constants {

companion object{
    const val BASE_URL = "http://10.0.2.2:8080/customer/"
}
}

RetrofitInstance.kt
object RetrofitInstance {

private var retrofit: Retrofit? = null

fun getClient(username: String, password : String): Retrofit {

    val client =  OkHttpClient.Builder()
        .addInterceptor(BasicAuthInterceptor(username,password))
        .build()

    val gson = GsonBuilder().apply {
        setLenient()
        registerTypeAdapter(Date::class.java,
                JsonDeserializer<Date> { json, typeOfT, context ->
                    if(json.asJsonPrimitive.isNumber) {
                        Date(json.asJsonPrimitive.asLong * 1000)
                    } else {
                        null
                    }
                })
    }.create()

    if (retrofit == null)
        retrofit =  Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()

    return retrofit as Retrofit
}
}

SimpleApi.kt
interface SimpleApi : Serializable{

@GET("list")
fun productList(): Call<MutableList<Product>>

@GET("api/data")
fun test(@Header("Authorization") autHeader: String): Call<String>

@GET("testc")
fun testCustomer(): Call<String>

@GET("cars")
fun getCars(): Call<List<Car>>

}

Create "service" in MainActivity.kt
    val service = RetrofitInstance.getClient(username,password).create(SimpleApi::class.java)

Create "Intent" in MainActivity.kt
                val intent = Intent(this@MainActivity,OtherActivity::class.java)
                intent.putExtra("service", service as Serializable)
                startActivity(intent)

Get "intent" in OtherActivity.kt
val service = (intent.getSerializableExtra("service") as? SimpleApi)!!

A: You can change your RetrofitInstance like below
object RetrofitInstance {

    private var api: SimpleApi? = null

    fun createInstance(username: String, password: String): SimpleApi {
        val client = OkHttpClient.Builder()
                .addInterceptor(BasicAuthInterceptor(username, password))
                .build()

        val gson = GsonBuilder().apply {
            setLenient()
            registerTypeAdapter(Date::class.java,
                    JsonDeserializer<Date> { json, typeOfT, context ->
                        if (json.asJsonPrimitive.isNumber) {
                            Date(json.asJsonPrimitive.asLong * 1000)
                        } else {
                            null
                        }
                    })
        }.create()

        if (api == null)
            api = Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build()
                    .create(SimpleApi::class.java)

        return api
    }

    fun getInstance() : SimpleApi {
        return api!!
    }
}

on your MainActivity call createInstace function to create your api instance. Other activities can call RetrofitInstance.getInstance() to get api.


text:
Q: Mini Ajax File Upload Form not working on opera
Mini Ajax File Upload Form not working on opera.

I just download and test it with Firefox and Chrome and its work fine. Can anyone know how to make this for opera browser?
Download Mini Ajax File Upload Form http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/

A: In Mini Ajax File Upload Form there is a file input that styled as display none. And costume button has been designed as browse button. This button click fires actual file input click event. So actual file input must be hidden from the user. Opera just can't identify this hidden element. So do these steps.

*

*Style container of file input as position:relative; overflow:hidden

*Style file input as Display:block; position:absolute; top:-50; left:0

This style will hide the file input. I have try this. Its works