问:
How to properly build a layout?
I'm kinda new with android programming and I can figure out many problems thanks to StackOverflow. But there's a thing where I keep struggle : Layouts.
I use DP as advised but it looks like it's not the ultimate solution.

See below, my XML code and what it what it looks like on my Nexus 5X :

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
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="com.example.damien.dartscorer.MainActivity"
android:clipToPadding="false">

<View
    android:layout_width="match_parent"
    android:layout_height="350dp"
    android:background="#b71c1c"/>
<ImageView
        android:id="@+id/mask"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="24dp"
        android:scaleType="fitCenter"
        android:src="@drawable/targe_mask"
        android:visibility="invisible"
        android:layout_marginBottom="280dp"/>

    <ImageView
        android:id="@+id/target"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="24dp"
        android:scaleType="fitCenter"
        android:src="@drawable/target"
        android:visibility="visible"
        android:layout_marginBottom="280dp"/>

    <TextView
        android:id="@+id/pointTextView"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_gravity="center_vertical|center_horizontal"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="15dp"
        android:layout_marginVertical="90dp"
        android:background="@drawable/pressed_button"
        android:fontFamily="sans-serif-medium"
        android:gravity="center"
        android:textColor="@android:color/white"
        android:textSize="20sp"
        android:visibility="invisible" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="315dp">

        <Space
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_weight="1">

        </Space>

        <Button
            android:id="@+id/button_x2"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/pressed_button"
            android:onClick="timesTwoClick"
            android:text="x2"
            android:textStyle="bold"
            android:textSize="18dp"
            android:textColor="#ffebee" />

        <Space
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_weight="1">

        </Space>

        <Button
            android:id="@+id/btn_25"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/halfb"
            android:elevation="9dp"/>

        <Space
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_weight="1">

        </Space>

        <Button
            android:id="@+id/btn_missed"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/zero" />

        <Space
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_weight="1">

        </Space>

        <Button
            android:id="@+id/btn_50"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/bull" />

        <Space
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_weight="1">

        </Space>

        <Button
            android:id="@+id/button_x3"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/pressed_button"
            android:onClick="timesThreeClick"
            android:text="x3"
            android:textStyle="bold"
            android:textSize="18dp"
            android:textColor="#ffebee" />

        <Space
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_weight="1">

        </Space>

    </LinearLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="230dp"
    android:layout_gravity="bottom">

    <TextView
        android:id="@+id/playerName1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="60dp"
        android:layout_marginTop="32dp"
        android:text="Player"
        android:visibility="visible"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/playerName2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="60dp"
        android:layout_marginTop="32dp"
        android:text="Player"
        android:visibility="visible"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/playerName3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/scoreC"
        android:layout_marginStart="60dp"
        android:text="Player"
        android:visibility="visible"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/playerName4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/scoreD"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="60dp"
        android:text="Player"
        android:visibility="visible"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/scoreA"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/playerName1"
        android:layout_marginStart="60dp"
        android:visibility="visible"
        android:textSize="18sp"
        android:text="Pts" />

    <TextView
        android:id="@+id/scoreB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_below="@+id/playerName2"
        android:layout_marginBottom="24dp"
        android:layout_marginEnd="60dp"
        android:visibility="visible"
        android:textSize="18sp"
        android:text="Pts" />

    <TextView
        android:id="@+id/scoreC"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="32dp"
        android:layout_marginStart="60dp"
        android:visibility="visible"
        android:textSize="18sp"
        android:text="Pts" />

    <TextView
        android:id="@+id/scoreD"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_marginBottom="32dp"
        android:layout_marginEnd="60dp"
        android:textSize="18sp"
        android:visibility="visible"
        android:text="Pts" />
</RelativeLayout>

<RelativeLayout
    android:id="@+id/winLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="gone">

    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#DD000000">

    </View>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="32dp"
        android:textColor="#FFEAED"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="150dp"
        android:id="@+id/winner" />

    <Button
        android:id="@+id/btn_replay"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_below="@+id/winner"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="140dp"
        android:background="@drawable/replay" />
    <Button
        android:id="@+id/btn_home"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_below="@+id/btn_replay"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"
        android:background="@drawable/home" />

</RelativeLayout>

</FrameLayout>
</code>```

As you can see on this second image, the layout sucks on a Pixel and yet, the screen don't have huge difference ! So how can I build something a minimum consistent ?

Also, I can't add elevation to my buttons and i don't really know why.

Thanks for helping,
Damien

答:
This is not how an Android XML layout should be, this code does not follow guidelines for UI development like parent and child elements. Please check some codes of XML layouts first then try developing with that.

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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"
    android:clipToPadding="false">
    <LinearLayout
        android:id="@+id/ll_top"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <View
            android:layout_width="match_parent"
            android:layout_height="350dp"
            android:background="#b71c1c"/>
    </LinearLayout>
    <TextView
        android:id="@+id/tv_1"
        android:layout_below="@+id/ll_top"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="20dp"
        android:text="Some data"/>
    <TextView
        android:layout_below="@+id/ll_top"
        android:layout_alignParentRight="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="20dp"
        android:layout_marginTop="20dp"
        android:text="some other data"/>
</RelativeLayout>
</code>```

this is a sample code just try this and stud it by changing parameters

Title: How to properly build a layout?

Body:
I'm kinda new with android programming and I can figure out many problems thanks to StackOverflow. But there's a thing where I keep struggle : Layouts.
I use DP as advised but it looks like it's not the ultimate solution.

See below, my XML code and what it what it looks like on my Nexus 5X :

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
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="com.example.damien.dartscorer.MainActivity"
android:clipToPadding="false">

<View
    android:layout_width="match_parent"
    android:layout_height="350dp"
    android:background="#b71c1c"/>
<ImageView
        android:id="@+id/mask"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="24dp"
        android:scaleType="fitCenter"
        android:src="@drawable/targe_mask"
        android:visibility="invisible"
        android:layout_marginBottom="280dp"/>

    <ImageView
        android:id="@+id/target"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="24dp"
        android:scaleType="fitCenter"
        android:src="@drawable/target"
        android:visibility="visible"
        android:layout_marginBottom="280dp"/>

    <TextView
        android:id="@+id/pointTextView"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_gravity="center_vertical|center_horizontal"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="15dp"
        android:layout_marginVertical="90dp"
        android:background="@drawable/pressed_button"
        android:fontFamily="sans-serif-medium"
        android:gravity="center"
        android:textColor="@android:color/white"
        android:textSize="20sp"
        android:visibility="invisible" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="315dp">

        <Space
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_weight="1">

        </Space>

        <Button
            android:id="@+id/button_x2"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/pressed_button"
            android:onClick="timesTwoClick"
            android:text="x2"
            android:textStyle="bold"
            android:textSize="18dp"
            android:textColor="#ffebee" />

        <Space
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_weight="1">

        </Space>

        <Button
            android:id="@+id/btn_25"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/halfb"
            android:elevation="9dp"/>

        <Space
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_weight="1">

        </Space>

        <Button
            android:id="@+id/btn_missed"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/zero" />

        <Space
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_weight="1">

        </Space>

        <Button
            android:id="@+id/btn_50"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/bull" />

        <Space
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_weight="1">

        </Space>

        <Button
            android:id="@+id/button_x3"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/pressed_button"
            android:onClick="timesThreeClick"
            android:text="x3"
            android:textStyle="bold"
            android:textSize="18dp"
            android:textColor="#ffebee" />

        <Space
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:layout_weight="1">

        </Space>

    </LinearLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="230dp"
    android:layout_gravity="bottom">

    <TextView
        android:id="@+id/playerName1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="60dp"
        android:layout_marginTop="32dp"
        android:text="Player"
        android:visibility="visible"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/playerName2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="60dp"
        android:layout_marginTop="32dp"
        android:text="Player"
        android:visibility="visible"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/playerName3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/scoreC"
        android:layout_marginStart="60dp"
        android:text="Player"
        android:visibility="visible"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/playerName4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/scoreD"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="60dp"
        android:text="Player"
        android:visibility="visible"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/scoreA"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/playerName1"
        android:layout_marginStart="60dp"
        android:visibility="visible"
        android:textSize="18sp"
        android:text="Pts" />

    <TextView
        android:id="@+id/scoreB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_below="@+id/playerName2"
        android:layout_marginBottom="24dp"
        android:layout_marginEnd="60dp"
        android:visibility="visible"
        android:textSize="18sp"
        android:text="Pts" />

    <TextView
        android:id="@+id/scoreC"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="32dp"
        android:layout_marginStart="60dp"
        android:visibility="visible"
        android:textSize="18sp"
        android:text="Pts" />

    <TextView
        android:id="@+id/scoreD"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_marginBottom="32dp"
        android:layout_marginEnd="60dp"
        android:textSize="18sp"
        android:visibility="visible"
        android:text="Pts" />
</RelativeLayout>

<RelativeLayout
    android:id="@+id/winLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="gone">

    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#DD000000">

    </View>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="32dp"
        android:textColor="#FFEAED"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="150dp"
        android:id="@+id/winner" />

    <Button
        android:id="@+id/btn_replay"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_below="@+id/winner"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="140dp"
        android:background="@drawable/replay" />
    <Button
        android:id="@+id/btn_home"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_below="@+id/btn_replay"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"
        android:background="@drawable/home" />

</RelativeLayout>

</FrameLayout>

As you can see on this second image, the layout sucks on a Pixel and yet, the screen don't have huge difference ! So how can I build something a minimum consistent ?

Also, I can't add elevation to my buttons and i don't really know why.

Thanks for helping,
Damien

Body:
This is not how an Android XML layout should be, this code does not follow guidelines for UI development like parent and child elements. Please check some codes of XML layouts first then try developing with that.

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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"
    android:clipToPadding="false">
    <LinearLayout
        android:id="@+id/ll_top"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <View
            android:layout_width="match_parent"
            android:layout_height="350dp"
            android:background="#b71c1c"/>
    </LinearLayout>
    <TextView
        android:id="@+id/tv_1"
        android:layout_below="@+id/ll_top"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="20dp"
        android:text="Some data"/>
    <TextView
        android:layout_below="@+id/ll_top"
        android:layout_alignParentRight="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="20dp"
        android:layout_marginTop="20dp"
        android:text="some other data"/>
</RelativeLayout>

this is a sample code just try this and stud it by changing parameters


来源: stackexchange

问:
Regex find string after key inside qoutes
Input:

blalasdl8ujd "key":"value", blblabla asdw
  "alo":"ebobo",blabla"www":"zzzz"

or

blalasdl8ujd key [any_chars_here] "value", blabla asdw
  "alo":"ebobo", bla"www":"zzzz"

I'm tring to extract value having only key and knowing that value is covered with "

Following regex key.*"(.*?)" returns the last match covered with " ("zzzz").
I need to fix it to return first.

https://regex101.com/r/CDfhBT/1

答:
Check this:

```<code>.*(\"key\":\"(\w*)\")
</code>```

Using the group 2:

https://regex101.com/r/66ikH3/2

ContentLicense: CC BY-SA 3.0

Body:
Check this:

.*(\"key\":\"(\w*)\")

Using the group 2:

https://regex101.com/r/66ikH3/2


问:
How to get the tab bar height in a Xamarin.Forms page
I'm displaying an image within my content pages such that its height is a fixed percentage of the page height. I do this using a grid with star unit row height. However, when the content pages are placed within a TabbedPage, the total grid height seems to be that of [the screen minus the tab bar height], so as a consequence, the image appears a bit shorter.

If I could access the tab bar height within my content pages, it would be a simple adjustment to the percentage.

Question:

1) How do I get the tab bar height within a content page?

2) Is there a better way to achieve the desired result?

答:
Edited:

I would suggest you to get the screen size and calculate the percentage based on screen size and use the variable value instead of proportional value, in this way, you could use other the layout other than AbsoluteLayout, but I am using AbsoluteLayout for my example:

```<code>protected override void OnAppearing()
        {
            var imageWidth = this.Width;
            var imageHeight = this.Height * 0.25;
            AbsoluteLayout.SetLayoutBounds(image, new Rectangle(0, 0, imageWidth, imageHeight));
            AbsoluteLayout.SetLayoutFlags(image, AbsoluteLayoutFlags.None);
        }
</code>```

*** In my test, when I used AbsoluteLayout proportional method

AbsoluteLayout.LayoutBounds = "0,0,1,0.25"
  AbsoluteLayout.LayoutFlags="All"

the outcome of both image size will have
  slightly different If the page use with or without Tabbedpage

So I suggest to use code behind to get the image size based on the [screen height * percentage].

TabbedPage

XAML:

```<code><?xml version="1.0" encoding="utf-8"?>
<TabbedPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:AbsoluteLayoutExample" x:Class="AbsoluteLayoutExample.AbsoluteLayoutExamplePage">

    <ContentPage x:Name="MyPage" Title = "Page 1">
        <AbsoluteLayout>
           <Image x:Name="image" Source="icon.png" Aspect="AspectFill" />
        </AbsoluteLayout>
    </ContentPage>

    <ContentPage Title = "Page 2">
        <Label Text="Hello" />
    </ContentPage>

</TabbedPage>
</code>```

CodeBehind:

```<code>protected override void OnAppearing()
{
    var imageWidth = this.Width;
    var imageHeight = this.Height * 0.25;
    AbsoluteLayout.SetLayoutBounds(image, new Rectangle(0,0,imageWidth,imageHeight));
    AbsoluteLayout.SetLayoutFlags(image,AbsoluteLayoutFlags.None);
}
</code>```

Content Page only:

XAML:

```<code><?xml version="1.0" encoding="utf-8"?>
<ContentPage Padding="0,20,0,0"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:ContentPageWidthAndHieght"
    x:Class="ContentPageWidthAndHieght.ContentPageWidthAndHieghtPage">
    <AbsoluteLayout>
         <Image x:Name="image" Source="icon.png" Aspect="AspectFill"/>
    </AbsoluteLayout>
</ContentPage>
</code>```

Code-Behind:

```<code>protected override void OnAppearing()
{
    var imageWidth = this.Width;
    var imageHeight = this.Height * 0.25;
    AbsoluteLayout.SetLayoutBounds(image, new Rectangle(0, 0, imageWidth, imageHeight));
    AbsoluteLayout.SetLayoutFlags(image, AbsoluteLayoutFlags.None);
}
</code>```

Body:
Edited:

I would suggest you to get the screen size and calculate the percentage based on screen size and use the variable value instead of proportional value, in this way, you could use other the layout other than AbsoluteLayout, but I am using AbsoluteLayout for my example:

protected override void OnAppearing()
        {
            var imageWidth = this.Width;
            var imageHeight = this.Height * 0.25;
            AbsoluteLayout.SetLayoutBounds(image, new Rectangle(0, 0, imageWidth, imageHeight));
            AbsoluteLayout.SetLayoutFlags(image, AbsoluteLayoutFlags.None);
        }

*** In my test, when I used AbsoluteLayout proportional method

AbsoluteLayout.LayoutBounds = "0,0,1,0.25"
  AbsoluteLayout.LayoutFlags="All"

the outcome of both image size will have
  slightly different If the page use with or without Tabbedpage

So I suggest to use code behind to get the image size based on the [screen height * percentage].

TabbedPage

XAML:

<?xml version="1.0" encoding="utf-8"?>
<TabbedPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:AbsoluteLayoutExample" x:Class="AbsoluteLayoutExample.AbsoluteLayoutExamplePage">

    <ContentPage x:Name="MyPage" Title = "Page 1">
        <AbsoluteLayout>
           <Image x:Name="image" Source="icon.png" Aspect="AspectFill" />
        </AbsoluteLayout>
    </ContentPage>

    <ContentPage Title = "Page 2">
        <Label Text="Hello" />
    </ContentPage>

</TabbedPage>

CodeBehind:

protected override void OnAppearing()
{
    var imageWidth = this.Width;
    var imageHeight = this.Height * 0.25;
    AbsoluteLayout.SetLayoutBounds(image, new Rectangle(0,0,imageWidth,imageHeight));
    AbsoluteLayout.SetLayoutFlags(image,AbsoluteLayoutFlags.None);
}

Content Page only:

XAML:

<?xml version="1.0" encoding="utf-8"?>
<ContentPage Padding="0,20,0,0"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:ContentPageWidthAndHieght"
    x:Class="ContentPageWidthAndHieght.ContentPageWidthAndHieghtPage">
    <AbsoluteLayout>
         <Image x:Name="image" Source="icon.png" Aspect="AspectFill"/>
    </AbsoluteLayout>
</ContentPage>

Code-Behind:

protected override void OnAppearing()
{
    var imageWidth = this.Width;
    var imageHeight = this.Height * 0.25;
    AbsoluteLayout.SetLayoutBounds(image, new Rectangle(0, 0, imageWidth, imageHeight));
    AbsoluteLayout.SetLayoutFlags(image, AbsoluteLayoutFlags.None);
}


问:
How do I create a row combining certain values of previous rows in R?
In my data, I have some lines that represent results from a repeated test. Only certain values are captured in the repeat. What I'd like to do is to create a new row with the repeat values but pulling from the initial test if the repeat values are NA or blank.

E.g. for,

```<code>Patient ID   Initial/Repeat   Value    Value 2   Accept/Reject
A1                   Initial      95        NA          Reject
A1                    Repeat      NA        80          Accept
A2                   Initial      80        70          Accept
</code>```

I'd like to tranform into:

```<code>Patient ID   Initial/Repeat   Value    Value 2   Accept/Reject
A1                    Repeat      95        80          Accept
A2                   Initial      80        70          Accept
</code>```

Thank you.

答:
I have also found tools within the tidyverse also accomplish the job. It's a little slower than zoo but offers better readability and requires fewer packages to be loaded.

```<code>library(tidyverse)

df <- df %>%
  group_by(Patient_ID) %>%
  fill(names(df), .direction = "down") %>%
  filter(row_number() == n())
</code>```

Body:
In my data, I have some lines that represent results from a repeated test. Only certain values are captured in the repeat. What I'd like to do is to create a new row with the repeat values but pulling from the initial test if the repeat values are NA or blank.

E.g. for,

Patient ID   Initial/Repeat   Value    Value 2   Accept/Reject
A1                   Initial      95        NA          Reject
A1                    Repeat      NA        80          Accept
A2                   Initial      80        70          Accept

I'd like to tranform into:

Patient ID   Initial/Repeat   Value    Value 2   Accept/Reject
A1                    Repeat      95        80          Accept
A2                   Initial      80        70          Accept

Thank you.

Body:
I have also found tools within the tidyverse also accomplish the job. It's a little slower than zoo but offers better readability and requires fewer packages to be loaded.

library(tidyverse)

df <- df %>%
  group_by(Patient_ID) %>%
  fill(names(df), .direction = "down") %>%
  filter(row_number() == n())


问:
How do you make javascript code execute *in order*
Okay, so I appreciate that Javascript is not C# or PHP, but I keep coming back to an issue in Javascript - not with JS itself but my use of it.

I have a function:

```<code>function updateStatuses(){

showLoader() //show the 'loader.gif' in the UI

updateStatus('cron1'); //performs an ajax request to get the status of something
updateStatus('cron2');
updateStatus('cron3');
updateStatus('cronEmail');
updateStatus('cronHourly');
updateStatus('cronDaily');

hideLoader(); //hide the 'loader.gif' in the UI

}
</code>```

Thing is, owing to Javascript's burning desire to jump ahead in the code, the loader never appears because the 'hideLoader' function runs straight after.

How can I fix this? Or in other words, how can I make a javascript function execute in the order I write it on the page...

答:
One of the best solutions for handling all async requests is the 'Promise'.

The Promise object represents the eventual completion (or failure) of an asynchronous operation.

Example:

```<code>let myFirstPromise = new Promise((resolve, reject) => {
  // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
  // In this example, we use setTimeout(...) to simulate async code.
  // In reality, you will probably be using something like XHR or an HTML5 API.
  setTimeout(function(){
    resolve("Success!"); // Yay! Everything went well!
  }, 250);
});

myFirstPromise.then((successMessage) => {
  // successMessage is whatever we passed in the resolve(...) function above.
  // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
  console.log("Yay! " + successMessage);
});
</code>```

Promise

If you have 3 async functions and expect to run in order, do as follows:

```<code>let FirstPromise = new Promise((resolve, reject) => {
    FirstPromise.resolve("First!");
});
let SecondPromise = new Promise((resolve, reject) => {

});
let ThirdPromise = new Promise((resolve, reject) => {

});
FirstPromise.then((successMessage) => {
  jQuery.ajax({
    type: "type",
    url: "url",
    success: function(response){
        console.log("First! ");
        SecondPromise.resolve("Second!");
    },
    error: function() {
        //handle your error
    }
  });
});
SecondPromise.then((successMessage) => {
  jQuery.ajax({
    type: "type",
    url: "url",
    success: function(response){
        console.log("Second! ");
        ThirdPromise.resolve("Third!");
    },
    error: function() {
       //handle your error
    }
  });
});
ThirdPromise.then((successMessage) => {
  jQuery.ajax({
    type: "type",
    url: "url",
    success: function(response){
        console.log("Third! ");
    },
    error: function() {
        //handle your error
    }
  });
});
</code>```

With this approach, you can handle all async operation as you wish.

ContentLicense: CC BY-SA 2.5

Body:
Okay, so I appreciate that Javascript is not C# or PHP, but I keep coming back to an issue in Javascript - not with JS itself but my use of it.

I have a function:

function updateStatuses(){

showLoader() //show the 'loader.gif' in the UI

updateStatus('cron1'); //performs an ajax request to get the status of something
updateStatus('cron2');
updateStatus('cron3');
updateStatus('cronEmail');
updateStatus('cronHourly');
updateStatus('cronDaily');

hideLoader(); //hide the 'loader.gif' in the UI

}

Thing is, owing to Javascript's burning desire to jump ahead in the code, the loader never appears because the 'hideLoader' function runs straight after.

How can I fix this? Or in other words, how can I make a javascript function execute in the order I write it on the page...

Body:
One of the best solutions for handling all async requests is the 'Promise'.

The Promise object represents the eventual completion (or failure) of an asynchronous operation.

Example:

let myFirstPromise = new Promise((resolve, reject) => {
  // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
  // In this example, we use setTimeout(...) to simulate async code.
  // In reality, you will probably be using something like XHR or an HTML5 API.
  setTimeout(function(){
    resolve("Success!"); // Yay! Everything went well!
  }, 250);
});

myFirstPromise.then((successMessage) => {
  // successMessage is whatever we passed in the resolve(...) function above.
  // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
  console.log("Yay! " + successMessage);
});

Promise

If you have 3 async functions and expect to run in order, do as follows:

let FirstPromise = new Promise((resolve, reject) => {
    FirstPromise.resolve("First!");
});
let SecondPromise = new Promise((resolve, reject) => {

});
let ThirdPromise = new Promise((resolve, reject) => {

});
FirstPromise.then((successMessage) => {
  jQuery.ajax({
    type: "type",
    url: "url",
    success: function(response){
        console.log("First! ");
        SecondPromise.resolve("Second!");
    },
    error: function() {
        //handle your error
    }
  });
});
SecondPromise.then((successMessage) => {
  jQuery.ajax({
    type: "type",
    url: "url",
    success: function(response){
        console.log("Second! ");
        ThirdPromise.resolve("Third!");
    },
    error: function() {
       //handle your error
    }
  });
});
ThirdPromise.then((successMessage) => {
  jQuery.ajax({
    type: "type",
    url: "url",
    success: function(response){
        console.log("Third! ");
    },
    error: function() {
        //handle your error
    }
  });
});

With this approach, you can handle all async operation as you wish.


问:
Matcher for JSONPath expression to find order of fields
I have an API that returns a JSON object that will be displayed in a UI. The order of the fields in the object matters because the UI wants to display the fields in that order. I want to write a unit test to ensure the order of the fields in the object is correct. My API response looks like this:

```<code>{
    "data": {
        "field1": "value1",
        "field2": "value2"
     }
}
</code>```

Using spring boot's MockMvc library, I want to write an expression like this to validate that the fields are coming back in order:

```<code>.andExpect(jsonPath("$.data"), is("field1=value1, field2=value2")
</code>```

Obviously, the above doesn't work but I'm not sure what type of Matcher I should be using to try and validate that the fields are in order.

答:
I couldn't find a Hamcrest matcher that compares the order of the fields, but it is easy enough to write your own. Note that the result of the JSON path expression will give you a LinkedHashMap so all you need is a Matcher that takes in a LinkedHashMap and compares it to the given object, entry by entry in order. Converting the map to a List of entries and using the equals method of List does the trick since List will compare items in order.

Here's how the matcher looks:

```<code>private class OrderedMapMatcher extends BaseMatcher<Map<String, String>> {

    private LinkedHashMap<String, String> expected;

    public OrderedMapMatcher(LinkedHashMap<String, String> expected) {
        this.expected = expected;
    }

    @Override
    public boolean matches(Object o) {
        if (!(o instanceof LinkedHashMap)) {
            return false;
        }
        LinkedHashMap actual = (LinkedHashMap) o;
        List<Map.Entry<String, String>> expectedList = new ArrayList<>(expected.entrySet());
        List actualList = new ArrayList(actual.entrySet());
        return expectedList.equals(actualList);
    }

    @Override
    public void describeTo(Description description) {
        description.appendText(expected.toString());
    }
}
</code>```

And here's how the assertion looks:

```<code>LinkedHashMap<String, String> expectedData = new LinkedHashMap<>();
expectedData.put("field1", "value1");
expectedData.put("field2", "value2");

// mockMvc ResultActions code would be here
.andExpect(jsonPath("$.data", new OrderedMapMatcher(expectedData)));
</code>```

Body:
I have an API that returns a JSON object that will be displayed in a UI. The order of the fields in the object matters because the UI wants to display the fields in that order. I want to write a unit test to ensure the order of the fields in the object is correct. My API response looks like this:

{
    "data": {
        "field1": "value1",
        "field2": "value2"
     }
}

Using spring boot's MockMvc library, I want to write an expression like this to validate that the fields are coming back in order:

.andExpect(jsonPath("$.data"), is("field1=value1, field2=value2")

Obviously, the above doesn't work but I'm not sure what type of Matcher I should be using to try and validate that the fields are in order.

Body:
I couldn't find a Hamcrest matcher that compares the order of the fields, but it is easy enough to write your own. Note that the result of the JSON path expression will give you a LinkedHashMap so all you need is a Matcher that takes in a LinkedHashMap and compares it to the given object, entry by entry in order. Converting the map to a List of entries and using the equals method of List does the trick since List will compare items in order.

Here's how the matcher looks:

private class OrderedMapMatcher extends BaseMatcher<Map<String, String>> {

    private LinkedHashMap<String, String> expected;

    public OrderedMapMatcher(LinkedHashMap<String, String> expected) {
        this.expected = expected;
    }

    @Override
    public boolean matches(Object o) {
        if (!(o instanceof LinkedHashMap)) {
            return false;
        }
        LinkedHashMap actual = (LinkedHashMap) o;
        List<Map.Entry<String, String>> expectedList = new ArrayList<>(expected.entrySet());
        List actualList = new ArrayList(actual.entrySet());
        return expectedList.equals(actualList);
    }

    @Override
    public void describeTo(Description description) {
        description.appendText(expected.toString());
    }
}

And here's how the assertion looks:

LinkedHashMap<String, String> expectedData = new LinkedHashMap<>();
expectedData.put("field1", "value1");
expectedData.put("field2", "value2");

// mockMvc ResultActions code would be here
.andExpect(jsonPath("$.data", new OrderedMapMatcher(expectedData)));


问:
Multiple different conditions and if statments within a loop
I want to assign different letters from A:U to a new column vector according to some conditions that depend on a different column that takes the numbers 1:99.

I came up with the following solution, but I want to write it more efficiently.

```<code>for (i in 1:99){

  if (i %in% 1:3 == T  ){
    id<-which(H07_NACE$NACE2.Code==i)
    H07_NACE$NACE2.Sectors[id]<-"A"
  }

   .............

    if (i %in% 45:60 == T  ){
      id<-which(H07_NACE$NACE2.Code==i)
      H07_NACE$NACE2.Sectors[id]<-"D"
    }
      .....................

     if (i == 99  ){
id<-which(H07_NACE$NACE2.Code==i)
H07_NACE$NACE2.Sectors[id]<-"U"
  }

}
</code>```

In the previous code I skipped multiple other line which essentially do the same thing. Notice that conditions changing all the time within this loop that I created and are of two types. One is for example of the type i %in% 45:60 == T and the other of the type 'i == 99 '

My original code has multiple such ifs within this loop so any help on how I can write it more efficiently or compactly will be appreciated.

答:
Here's two tidyverse examples, though I'm not completely certain what the original poster is really asking for.

```<code>library(tidyverse)

data.frame(NACE2.Code = sample(99, replace = TRUE)) %>%
  mutate(Sectors = ifelse(NACE2.Code %in% 1:3, "A",
                          ifelse(NACE2.Code %in% 45:60, "D",
                                 ifelse(NACE2.Code ==99, "U", NA))))

data.frame(NACE2.Code = sample(99, replace = TRUE)) %>%
  mutate(Sectors = case_when(NACE2.Code %in% 1:3 ~ "A",
                             NACE2.Code %in% 45:60 ~ "D",
                             NACE2.Code ==99 ~ "U")) %>%
  drop_na
</code>```

Body:
I want to assign different letters from A:U to a new column vector according to some conditions that depend on a different column that takes the numbers 1:99.

I came up with the following solution, but I want to write it more efficiently.

for (i in 1:99){

  if (i %in% 1:3 == T  ){
    id<-which(H07_NACE$NACE2.Code==i)
    H07_NACE$NACE2.Sectors[id]<-"A"
  }

   .............

    if (i %in% 45:60 == T  ){
      id<-which(H07_NACE$NACE2.Code==i)
      H07_NACE$NACE2.Sectors[id]<-"D"
    }
      .....................

     if (i == 99  ){
id<-which(H07_NACE$NACE2.Code==i)
H07_NACE$NACE2.Sectors[id]<-"U"
  }

}

In the previous code I skipped multiple other line which essentially do the same thing. Notice that conditions changing all the time within this loop that I created and are of two types. One is for example of the type i %in% 45:60 == T and the other of the type 'i == 99 '

My original code has multiple such ifs within this loop so any help on how I can write it more efficiently or compactly will be appreciated.

Body:
Here's two tidyverse examples, though I'm not completely certain what the original poster is really asking for.

library(tidyverse)

data.frame(NACE2.Code = sample(99, replace = TRUE)) %>%
  mutate(Sectors = ifelse(NACE2.Code %in% 1:3, "A",
                          ifelse(NACE2.Code %in% 45:60, "D",
                                 ifelse(NACE2.Code ==99, "U", NA))))

data.frame(NACE2.Code = sample(99, replace = TRUE)) %>%
  mutate(Sectors = case_when(NACE2.Code %in% 1:3 ~ "A",
                             NACE2.Code %in% 45:60 ~ "D",
                             NACE2.Code ==99 ~ "U")) %>%
  drop_na


问:
Local Pip install not able to import any classes within the package
I have a python package which I built from

```<code>python setup.py sdist
</code>```

The package name is : Yify

I installed this using

```<code>pip3 install .
</code>```

After this when I open the python3 interpreter and import Yify , it imports successfully but it doesn't seem to include the main python file inside the dist_packages/Yify directory .

Here is the folder structure :-

```<code>├── dist
│   └── Yify-1.0.tar.gz
├── get-pip.py
├── LICENSE
├── README.rst
├── requirements.txt
├── setup.cfg
├── setup.py
├── Yify
│   ├── __init__.py
│   ├── venv
|   ├── Yify.py
</code>```

The Yify.py contains yify class .
When i do

```<code>import Yify
Yify.yify()
</code>```

It gives me 'yify' not found error ! .

hOW TO fix it ?

Here is the setup.py contents:-

```<code>import platform
from setuptools import setup

install_requires = ['bs4' , 'urllib3' ]

setup(
    name='Yify',
    packages = ['Yify'] ,
    version = 'v1.0',
    description = '''
    This Module is used to get the Top seeded torrents at any given time and get the entire movie details and ratings .
    Its also useful to search for any movie using different parameters and obtain their magnet link or torrent file of any prefered quality.
''' ,
    author = 'Natesh M Bhat' ,
    url = 'https://github.com/nateshmbhat/Yify-Python',
    author_email = 'nateshmbhatofficial@gmail.com' ,
    # download_url = 'https://github.com/nateshmbhat/pyttsx3/archive/v2.6.tar.gz',
    keywords=['yify','torrent-python' , 'movie-torrent' , 'torrent' , 'pyyify' , 'Yify' , 'yify torrent' , 'yify download' , 'download yify' , 'yifyer'  , 'yifypy' , 'torrent download' , 'movie torrent' , 'movie downloader', 'movie finder'],
    classifiers = [] ,
    install_requires=install_requires
)
</code>```

Also When I directly go into the python3.6 distpackages/Yify folder and execute python3 from there. Everything works fine .

Also dir(Yify) return only the below fields

```<code>dir(Yify)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
</code>```

答:
__init__. must be called __init__.py.

When you do import Yify you only import Yify/__init__.py, not Yify/Yify.py unless it's imported in __init__.py.

To fix you import do: from Yify import Yify. That way you really import Yify/Yify.py.

Body:
I have a python package which I built from

python setup.py sdist

The package name is : Yify

I installed this using

pip3 install .

After this when I open the python3 interpreter and import Yify , it imports successfully but it doesn't seem to include the main python file inside the dist_packages/Yify directory .

Here is the folder structure :-

├── dist
│   └── Yify-1.0.tar.gz
├── get-pip.py
├── LICENSE
├── README.rst
├── requirements.txt
├── setup.cfg
├── setup.py
├── Yify
│   ├── __init__.py
│   ├── venv
|   ├── Yify.py

The Yify.py contains yify class .
When i do

import Yify
Yify.yify()

It gives me 'yify' not found error ! .

hOW TO fix it ?

Here is the setup.py contents:-

import platform
from setuptools import setup

install_requires = ['bs4' , 'urllib3' ]

setup(
    name='Yify',
    packages = ['Yify'] ,
    version = 'v1.0',
    description = '''
    This Module is used to get the Top seeded torrents at any given time and get the entire movie details and ratings .
    Its also useful to search for any movie using different parameters and obtain their magnet link or torrent file of any prefered quality.
''' ,
    author = 'Natesh M Bhat' ,
    url = 'https://github.com/nateshmbhat/Yify-Python',
    author_email = 'nateshmbhatofficial@gmail.com' ,
    # download_url = 'https://github.com/nateshmbhat/pyttsx3/archive/v2.6.tar.gz',
    keywords=['yify','torrent-python' , 'movie-torrent' , 'torrent' , 'pyyify' , 'Yify' , 'yify torrent' , 'yify download' , 'download yify' , 'yifyer'  , 'yifypy' , 'torrent download' , 'movie torrent' , 'movie downloader', 'movie finder'],
    classifiers = [] ,
    install_requires=install_requires
)

Also When I directly go into the python3.6 distpackages/Yify folder and execute python3 from there. Everything works fine .

Also dir(Yify) return only the below fields

dir(Yify)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']


问:
Javascript - why is this undefined?
The alert at the start shows "undefined", why?

The alerts come in this order:

"success!"

"Data" (what it should be)

"undefined"

I read through multiple threads, the problem was always that ajax was asynchronous, so the data was not defined when it was accessed, but in my case the data is there, the alert in my function shows the data BEFORE the other alert where it is undefined!

Very grateful for any help!

I got this code

```<code>var data = getData("");
alert(data);            <<<<<<< UNDEFINED

function getData(fileName) {

    $.ajax({
        async:false,
        type: "GET",
        url: "breastCancer.csv",
        dataType: "text",
        success: function (data) {
            var arrData = processData(data);
            alert("success!");
            alert(arrData);      <<<<< WORKS GREAT
            return arrData;
        },
    });

}

function processData(data) {

    var arrData = CSVToArray(data);

    dimensions = arrData[0];
    var objects = [];

    objects[0] = dimensions;

    for (var i = 1; i < arrData.length; i++){
        objects[i] = new Object();

        for (var j = 0; j < dimensions.length; j++){
            objects[i][dimensions[j]] = arrData[i][j];
        }
    }

    return objects;
}
</code>```

To clarify, I know asynchronous is the way to go for user experience, but this page just has to show data from this call, so its okay for me to wait for it.

答:
You need to return it from the function itself.

```<code>function getData(fileName) {

    $.ajax({
        async:false,
        type: "GET",
        url: "breastCancer.csv",
        dataType: "text",
        success: function (data) {
            var arrData = processData(data);
            alert("success!");
            alert(arrData);      <<<<< WORKS GREAT
            return arrData;
        },
    });

}
</code>```

^ This returns the data within getData. But getData doesn't do anything with it: such as returning it.

```<code>function getData(fileName) {
    var ourData = "";
    $.ajax({
        async:false,
        type: "GET",
        url: "breastCancer.csv",
        dataType: "text",
        success: function (data) {
            var arrData = processData(data);
            ourData = arrData;
        },
    });
    return ourData;
}
</code>```

This returns the data from getData to whatever calls that function.

edit: also, don't use async:false. Your browser won't capture any events happening until that AJAX completes. The benefit of asynchronous JS is that...we can! And in this case should.

Title: Javascript - why is this undefined?

Body:
The alert at the start shows "undefined", why?

The alerts come in this order:

"success!"

"Data" (what it should be)

"undefined"

I read through multiple threads, the problem was always that ajax was asynchronous, so the data was not defined when it was accessed, but in my case the data is there, the alert in my function shows the data BEFORE the other alert where it is undefined!

Very grateful for any help!

I got this code

var data = getData("");
alert(data);            <<<<<<< UNDEFINED

function getData(fileName) {

    $.ajax({
        async:false,
        type: "GET",
        url: "breastCancer.csv",
        dataType: "text",
        success: function (data) {
            var arrData = processData(data);
            alert("success!");
            alert(arrData);      <<<<< WORKS GREAT
            return arrData;
        },
    });

}

function processData(data) {

    var arrData = CSVToArray(data);

    dimensions = arrData[0];
    var objects = [];

    objects[0] = dimensions;

    for (var i = 1; i < arrData.length; i++){
        objects[i] = new Object();

        for (var j = 0; j < dimensions.length; j++){
            objects[i][dimensions[j]] = arrData[i][j];
        }
    }

    return objects;
}

To clarify, I know asynchronous is the way to go for user experience, but this page just has to show data from this call, so its okay for me to wait for it.

Body:
You need to return it from the function itself.

function getData(fileName) {

    $.ajax({
        async:false,
        type: "GET",
        url: "breastCancer.csv",
        dataType: "text",
        success: function (data) {
            var arrData = processData(data);
            alert("success!");
            alert(arrData);      <<<<< WORKS GREAT
            return arrData;
        },
    });

}

^ This returns the data within getData. But getData doesn't do anything with it: such as returning it.

function getData(fileName) {
    var ourData = "";
    $.ajax({
        async:false,
        type: "GET",
        url: "breastCancer.csv",
        dataType: "text",
        success: function (data) {
            var arrData = processData(data);
            ourData = arrData;
        },
    });
    return ourData;
}

This returns the data from getData to whatever calls that function.

edit: also, don't use async:false. Your browser won't capture any events happening until that AJAX completes. The benefit of asynchronous JS is that...we can! And in this case should.


问:
Are C compilers like gcc smart enough to bit shifts in place?
Unlike assembly code, in C there is no way to bit shift a value in place. To shift the bits in variable an assignment must always be performed:

```<code>x = x << 3;
</code>```

Are compilers like gcc smart enough to realize that this is an in-place bit shift and compile it like this:

```<code>shl x, 3
</code>```

or will the compiler put the result first in a register, then move it back into x (which would require two extra unnecessary instructions).

答:
Any good compiler with optimization turned on will handle bit shifts efficiently.

Compilers will keep small objects in registers when feasible and efficient and will not store them to memory even if you write assignment statements, until they are forced to by circumstances.

Additionally, it is not desirable on typical modern processors to try to shift the bits of a value in memory. Generally, memory hardware does not have any capability to manipulate stored values. To change the value of something in memory, it must be moved to the processor (loaded), changed, and moved back (stored). Whether this is done in one instruction or several is not generally an indication of how fast or efficient it is, because the processor still has to do the individual load, shift, store operations, and the performance of those is highly dependent on the processor model.

Except in exceptional programming situations, you should not be worrying about performance at this level.

Body:
Unlike assembly code, in C there is no way to bit shift a value in place. To shift the bits in variable an assignment must always be performed:

x = x << 3;

Are compilers like gcc smart enough to realize that this is an in-place bit shift and compile it like this:

shl x, 3

or will the compiler put the result first in a register, then move it back into x (which would require two extra unnecessary instructions).


问:
SonarQube scan across multiple branches
Scenario: 3 branches in a repository:

'master' -> 'prod' branch which gets pushed to production

'devBranch A' - a development branch - assume single developer

'devBranch B' - a dev branch, same as above.

We have SonarQube (6.x) for static code analysis in a Jenkins CI/CD pipeline kicked off by the creation of a pull request in BitBucket. We use Git Jenkins plugin. Right now, Git is, upon creation of a pull request, doing a checkout from BitBucket as such:

```<code>Checking out Revision cdd7cc6fa787d111bbc6afef2728fa3353aab499 (origin/feature/TestTuesday)
</code>```

I am trying to ensure that only the code from the specific pull request in that specific branch - and not all commits in any branch matching the pattern "origin/feature/*" is analysed by SonarQube - trying to ensure we never get every commit in all branches that match our Git Jenkins plugin 'branch specifier'

So how do I: ensure SonarQube scans only the code in a specific pull request as opposed to all changes in branches that match the branch specifier pattern.

thanks

EDIT: I was tempted to delete this question as I don't feel I've articulated this issue I'm trying to solve in a way that is actually technically relevant...

When the Jenkins/Git plugin checks out that code, it is actually checking out the correct code - that Revision is the Head commit in the repo from which the PR originated... so... this is doing what is expected.

Previously, another issue had been the correct paths to the source code for sonarqube analysis: they needed to be relative to the workspace for the Jenkins job...

Summary: instead of deleting this question, I'm just clarifying my poor wording and giving a brief follow up for anyone who may find any of this edifying.

答:
Considering you know which branch to pull, you can do

```<code>$ git fetch
$ git diff <branch>...origin/<branch>.
</code>```

This will give you only the commits which will be pulled.
Note down the list of changes and pass it to sonar-scanner (or any other client you are using) to include only the files mentioned.

Something like this :

```<code>sonar-scanner -Dsonar.inclusions=<Comma-delimited list of files>
</code>```

Now, since you are using a plugin to pull from git, what I suggest is, before the pull starts, do a git log and get old commit SHA, do a git pull, get new commit SHA. Using old and new SHAs, do a git diff/git log to fetch the list of files which have changes.

Title: SonarQube scan across multiple branches

Body:
Scenario: 3 branches in a repository:

'master' -> 'prod' branch which gets pushed to production

'devBranch A' - a development branch - assume single developer

'devBranch B' - a dev branch, same as above.

We have SonarQube (6.x) for static code analysis in a Jenkins CI/CD pipeline kicked off by the creation of a pull request in BitBucket. We use Git Jenkins plugin. Right now, Git is, upon creation of a pull request, doing a checkout from BitBucket as such:

Checking out Revision cdd7cc6fa787d111bbc6afef2728fa3353aab499 (origin/feature/TestTuesday)

I am trying to ensure that only the code from the specific pull request in that specific branch - and not all commits in any branch matching the pattern "origin/feature/*" is analysed by SonarQube - trying to ensure we never get every commit in all branches that match our Git Jenkins plugin 'branch specifier'

So how do I: ensure SonarQube scans only the code in a specific pull request as opposed to all changes in branches that match the branch specifier pattern.

thanks

EDIT: I was tempted to delete this question as I don't feel I've articulated this issue I'm trying to solve in a way that is actually technically relevant...

When the Jenkins/Git plugin checks out that code, it is actually checking out the correct code - that Revision is the Head commit in the repo from which the PR originated... so... this is doing what is expected.

Previously, another issue had been the correct paths to the source code for sonarqube analysis: they needed to be relative to the workspace for the Jenkins job...

Summary: instead of deleting this question, I'm just clarifying my poor wording and giving a brief follow up for anyone who may find any of this edifying.

Body:
Considering you know which branch to pull, you can do

$ git fetch
$ git diff <branch>...origin/<branch>.

This will give you only the commits which will be pulled.
Note down the list of changes and pass it to sonar-scanner (or any other client you are using) to include only the files mentioned.

Something like this :

sonar-scanner -Dsonar.inclusions=<Comma-delimited list of files>

Now, since you are using a plugin to pull from git, what I suggest is, before the pull starts, do a git log and get old commit SHA, do a git pull, get new commit SHA. Using old and new SHAs, do a git diff/git log to fetch the list of files which have changes.


问:
Function and Pointer Interaction
I am VERY new to C programming. I have a function which will take a pointer to  a string as input and print the reverse of that string. When I invoke that function in the main method, it outputs junk. I think it might be a problem with how I am using pointers.

My code is:

```<code>    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    #define MAX_LEN 100

    void reverse(char* str)
    {
        int i, j;
        int temp;
        int length;
        length = strlen(str);
        i= 0;
        j=(length-1);
        while (i<j){
          temp=str[i];
          str[i] = str[j];
          str[j]=temp;
          i++;
          j--;
       }
        printf("Your reversed string is: ");
        for (i=0; i<length; i++){
          printf("%d", str[i]);
       }
       printf("\n");
    }

int main()
    {
        char mystring[MAX_LEN+1];
        printf("Enter the string. \n");
        scanf("%s", mystring);
        printf("%s", mystring);
        printf("\n");
       reverse(mystring);
    }
</code>```

and the output is:

Enter the string.

  help

  help

  Your reversed string is: 112108101104

答:
printf("%c", str[i]); You printed the ascii values earlier. Use %c specifier to print the characters.

For example, you can see that in ascii-chart

```<code>112 108 101 104
 p   l   e    h
</code>```

Or even more easily you could have done this

printf("%s",str);

Title: Function and Pointer Interaction

Body:
I am VERY new to C programming. I have a function which will take a pointer to  a string as input and print the reverse of that string. When I invoke that function in the main method, it outputs junk. I think it might be a problem with how I am using pointers.

My code is:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    #define MAX_LEN 100

    void reverse(char* str)
    {
        int i, j;
        int temp;
        int length;
        length = strlen(str);
        i= 0;
        j=(length-1);
        while (i<j){
          temp=str[i];
          str[i] = str[j];
          str[j]=temp;
          i++;
          j--;
       }
        printf("Your reversed string is: ");
        for (i=0; i<length; i++){
          printf("%d", str[i]);
       }
       printf("\n");
    }

int main()
    {
        char mystring[MAX_LEN+1];
        printf("Enter the string. \n");
        scanf("%s", mystring);
        printf("%s", mystring);
        printf("\n");
       reverse(mystring);
    }

and the output is:

Enter the string.

  help

  help

  Your reversed string is: 112108101104

Body:
printf("%c", str[i]); You printed the ascii values earlier. Use %c specifier to print the characters.

For example, you can see that in ascii-chart

112 108 101 104
 p   l   e    h

Or even more easily you could have done this

printf("%s",str);


问:
How to do reverse search and find particular character in nth place and delete characters after that
Actual:

```<code>ABCDEFGHIJ_CPW_ABC_KT_#ABCD_ABCDEFGH_ABCDEFGHIJKL L01_10_18_2017_02_53_22_015_10_244_36_7.xml
</code>```

Need:

```<code>ABCDEFGHIJ_CPW_ABC_KT_#ABCD_ABCDEFGH_ABCDEFGHIJKL L01.xml
</code>```

Want to delete everything upto .xml from 11th "_" from reverse.

This is a sample file name format. I have like 10-15K files in a directory. And I need to rename/change all the files. Basically need to delete from "_"(after L01) to ".".

答:
In this method each underscore separated token is joined in tail string, but when the number of joined tokens reach a given number (11 in this example), the first token is also removed from the string; the final result is have the 11 last tokens in tail string. After that, such last tokens are removed from original input string.

```<code>@echo off
setlocal EnableDelayedExpansion

set "input=ABCDEFGHIJ_CPW_ABC_KT_#ABCD_ABCDEFGH_ABCDEFGHIJKL L01_10_18_2017_02_53_22_015_10_244_36_7.xml"

echo Input ="%input%"
set n=11
set "tail="
for %%a in ("%input:_=" "%") do (
   if !n! gtr 0 (
      set "tail=!tail!%%~a_"
   ) else (
      set "tail=!tail:*_=!%%~a_"
   )
   set /A n-=1
)
set "output=!input:_%tail:~0,-1%=!.xml"
echo Output="%output%"
</code>```

In shorter form:

```<code>@echo off
setlocal EnableDelayedExpansion

set "input=ABCDEFGHIJ_CPW_ABC_KT_#ABCD_ABCDEFGH_ABCDEFGHIJKL L01_10_18_2017_02_53_22_015_10_244_36_7.xml"

echo Input ="%input%"
set n=11
set "tail="
set "aux=%input%_"
set "token=%aux:_=" & (if !n! gtr 0 (set "tail=!tail!!token!_") else set "tail=!tail:*_=!!token!_") & set /A n-=1 & set "token=%"
set "output=!input:_%tail:~0,-1%=!.xml"
echo Output="%output%"
</code>```

In this simpler method the number of the separating underscore is calculated and used to eliminate the section after that from the original string. However, this method only works when the number of tokens to preserve is less than 32:

```<code>@echo off
setlocal EnableDelayedExpansion

set "input=ABCDEFGHIJ_CPW_ABC_KT_#ABCD_ABCDEFGH_ABCDEFGHIJKL L01_10_18_2017_02_53_22_015_10_244_36_7.xml"

echo Input ="%input%"
set n=-11
for %%a in ("%input:_=" "%") do set /A n+=1
for /F "tokens=%n%* delims=_" %%a in ("%input%") do set "output=!input:_%%b=!.xml"
echo Output="%output%"
</code>```

Body:
Actual:

ABCDEFGHIJ_CPW_ABC_KT_#ABCD_ABCDEFGH_ABCDEFGHIJKL L01_10_18_2017_02_53_22_015_10_244_36_7.xml

Need:

ABCDEFGHIJ_CPW_ABC_KT_#ABCD_ABCDEFGH_ABCDEFGHIJKL L01.xml

Want to delete everything upto .xml from 11th "_" from reverse.

This is a sample file name format. I have like 10-15K files in a directory. And I need to rename/change all the files. Basically need to delete from "_"(after L01) to ".".

Body:
In this method each underscore separated token is joined in tail string, but when the number of joined tokens reach a given number (11 in this example), the first token is also removed from the string; the final result is have the 11 last tokens in tail string. After that, such last tokens are removed from original input string.

@echo off
setlocal EnableDelayedExpansion

set "input=ABCDEFGHIJ_CPW_ABC_KT_#ABCD_ABCDEFGH_ABCDEFGHIJKL L01_10_18_2017_02_53_22_015_10_244_36_7.xml"

echo Input ="%input%"
set n=11
set "tail="
for %%a in ("%input:_=" "%") do (
   if !n! gtr 0 (
      set "tail=!tail!%%~a_"
   ) else (
      set "tail=!tail:*_=!%%~a_"
   )
   set /A n-=1
)
set "output=!input:_%tail:~0,-1%=!.xml"
echo Output="%output%"

In shorter form:

@echo off
setlocal EnableDelayedExpansion

set "input=ABCDEFGHIJ_CPW_ABC_KT_#ABCD_ABCDEFGH_ABCDEFGHIJKL L01_10_18_2017_02_53_22_015_10_244_36_7.xml"

echo Input ="%input%"
set n=11
set "tail="
set "aux=%input%_"
set "token=%aux:_=" & (if !n! gtr 0 (set "tail=!tail!!token!_") else set "tail=!tail:*_=!!token!_") & set /A n-=1 & set "token=%"
set "output=!input:_%tail:~0,-1%=!.xml"
echo Output="%output%"

In this simpler method the number of the separating underscore is calculated and used to eliminate the section after that from the original string. However, this method only works when the number of tokens to preserve is less than 32:

@echo off
setlocal EnableDelayedExpansion

set "input=ABCDEFGHIJ_CPW_ABC_KT_#ABCD_ABCDEFGH_ABCDEFGHIJKL L01_10_18_2017_02_53_22_015_10_244_36_7.xml"

echo Input ="%input%"
set n=-11
for %%a in ("%input:_=" "%") do set /A n+=1
for /F "tokens=%n%* delims=_" %%a in ("%input%") do set "output=!input:_%%b=!.xml"
echo Output="%output%"


问:
Limit ScaleTransform to a maximum height and width
Is there a way to limit ScaleTransform to a maximum height and width?

I have a Viewbox with a background Image set to stretch to "None".  In this Viewbox I also have a ItemsControl presenting smaller images on a Canvas.  Since the background image can be chosen by operator, the image can vary in pixel size, and the operator therefore need to be able to scale the smaller images accordingly.

But if the scaling factor is either set very large on a medium sized background image, or the background image has a small size, the ItemsControl images end up overflowing the container and blocking other functionality.

So how can I set a limit to the ScaleTransform?

XAML:

```<code><Viewbox Grid.Column="1">
    <Grid>
        <Image Source="{Binding Path=BackgroundImage}" Stretch="None" />
        <ItemsControl ItemsSource="{Binding Path=ThrusterCollection}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemContainerStyle>
                <Style TargetType="{x:Type ContentPresenter}">
                    <Setter Property="Canvas.Bottom" Value="{Binding Path=CanvasYPosition}" />
                    <Setter Property="Canvas.Left" Value="{Binding Path=CanvasXPosition}" />
                    <Setter Property="LayoutTransform">
                        <Setter.Value>
                            <ScaleTransform ScaleX="{Binding Path=ParentRovIllustration.ThrusterImageScale}"
                                            ScaleY="{Binding Path=ParentRovIllustration.ThrusterImageScale}" />
                        </Setter.Value>
                    </Setter>
                    <Setter Property="ContentTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <Image Source="{Binding Path=ThrusterImage}" />
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ItemsControl.ItemContainerStyle>
        </ItemsControl>
    </Grid>
</Viewbox>
</code>```

Screenshot:

答:
Based on Clemens' comment, doing the limitation in code worked fine.  I just calculated a maximum scaling value for the slider, based on the smaller images (thrusters) at maximum being scaled to half the background image width.  This ended up being my solution.

C#:

```<code>private string _backgroundImageFilePath;
public string BackgroundImageFilePath {
    get { return _backgroundImageFilePath; }
    set {
        SetNotify(ref _backgroundImageFilePath, value);
        try {
            BackgroundImage = new BitmapImage(new Uri(BackgroundImageFilePath));
        }
        catch (FileNotFoundException) {
            BackgroundImage = ImageNotFoundBitmapImage;
        }
        catch (Exception) {
            BackgroundImage = ImageInvalidBitmapImage;
        }
        ThrusterImageMaximumScale = BackgroundImage.Width / (2 * RovIllustrationThruster.VerticalThrusterBitmapImage.Width);
        ThrusterImageMaximumScale = Math.Round(ThrusterImageMaximumScale, 1);
        if (ThrusterImageScale > ThrusterImageMaximumScale) {
            ThrusterImageScale = ThrusterImageMaximumScale;
        }
        ConfigurationHandler.IsDirty = true;
    }
}
</code>```

Body:
Is there a way to limit ScaleTransform to a maximum height and width?

I have a Viewbox with a background Image set to stretch to "None".  In this Viewbox I also have a ItemsControl presenting smaller images on a Canvas.  Since the background image can be chosen by operator, the image can vary in pixel size, and the operator therefore need to be able to scale the smaller images accordingly.

But if the scaling factor is either set very large on a medium sized background image, or the background image has a small size, the ItemsControl images end up overflowing the container and blocking other functionality.

So how can I set a limit to the ScaleTransform?

XAML:

<Viewbox Grid.Column="1">
    <Grid>
        <Image Source="{Binding Path=BackgroundImage}" Stretch="None" />
        <ItemsControl ItemsSource="{Binding Path=ThrusterCollection}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemContainerStyle>

            </ItemsControl.ItemContainerStyle>
        </ItemsControl>
    </Grid>
</Viewbox>

Screenshot:

Body:
Based on Clemens' comment, doing the limitation in code worked fine.  I just calculated a maximum scaling value for the slider, based on the smaller images (thrusters) at maximum being scaled to half the background image width.  This ended up being my solution.

C#:

private string _backgroundImageFilePath;
public string BackgroundImageFilePath {
    get { return _backgroundImageFilePath; }
    set {
        SetNotify(ref _backgroundImageFilePath, value);
        try {
            BackgroundImage = new BitmapImage(new Uri(BackgroundImageFilePath));
        }
        catch (FileNotFoundException) {
            BackgroundImage = ImageNotFoundBitmapImage;
        }
        catch (Exception) {
            BackgroundImage = ImageInvalidBitmapImage;
        }
        ThrusterImageMaximumScale = BackgroundImage.Width / (2 * RovIllustrationThruster.VerticalThrusterBitmapImage.Width);
        ThrusterImageMaximumScale = Math.Round(ThrusterImageMaximumScale, 1);
        if (ThrusterImageScale > ThrusterImageMaximumScale) {
            ThrusterImageScale = ThrusterImageMaximumScale;
        }
        ConfigurationHandler.IsDirty = true;
    }
}


问:
v-for removes margins in bulma
for example I have a simple figure in bulma like this

```<code><figure>
<img src="https://bulma.io/images/placeholders/128x128.png">
<img src="https://bulma.io/images/placeholders/128x128.png">
<figcaption>
Some Caption
</figcaption>
</figure>
</code>```

You see some space between which is great.

Now when I want to display the images by using vue and displaying it with a v-for, then those margins disappear...

does anyone know why? I recognized that the css selector like nth child does not work anymore when I apply vue and v-for... but I dont know how to solve that...

update: the same thing happens to the h1 tag!

Here is a fiddle explaining it also very good:
https://jsfiddle.net/fbp1yhyu/2/

答:
It is because your original example has a white space (new line and tabs) character between the two images, however Vue is not placing a white space character between the imgs in the v-for.

Original markup:

```<code><img ...> <img ...>
</code>```

Resulting VueJS markup using which uses :

```<code><img ...><img ...>
</code>```

THe following code adds the space back in, however it is a slightly larger space. The   is a white space character. Hope this helps!

```<code><template v-for="image in garden.images">
      <img :src="image">
</template>
</code>```

And you can reproduce the same issue in the original markup without vue by removing the new line after the first image:

```<code><img src="https://bulma.io/images/placeholders/128x128.png"><img src="https://bulma.io/images/placeholders/128x128.png">
</code>```

h1 Tag issue

It appears to be due to the following css. The original code has 2 h1 elements that are siblings, whereas the vue code has the second h1 is not a sibling of the first h1 since it is in a div.

CSS (defined in bulma)

```<code>.content h1:not(:first-child) {
    margin-top: 1em;
}
</code>```

Original HTML:

```<code><h1>Bulma without VUE</h1>
<h1>Project 1</h1>
</code>```

Vue Html:

```<code><h1>Bulma with VUE</h1>
<div v-for="garden in gardens">
    <h1>{{garden.name}}<h1>
    ...
</div>
</code>```

Title: v-for removes margins in bulma

Body:
for example I have a simple figure in bulma like this

Some Caption

You see some space between which is great.

Now when I want to display the images by using vue and displaying it with a v-for, then those margins disappear...

does anyone know why? I recognized that the css selector like nth child does not work anymore when I apply vue and v-for... but I dont know how to solve that...

update: the same thing happens to the h1 tag!

Here is a fiddle explaining it also very good:
https://jsfiddle.net/fbp1yhyu/2/

Body:
It is because your original example has a white space (new line and tabs) character between the two images, however Vue is not placing a white space character between the imgs in the v-for.

Original markup:

<img ...> <img ...>

Resulting VueJS markup using which uses <img v-for="..." src="...">:

<img ...><img ...>

THe following code adds the space back in, however it is a slightly larger space. The   is a white space character. Hope this helps!

<template v-for="image in garden.images">
      <img :src="image">&nbsp;
</template>

And you can reproduce the same issue in the original markup without vue by removing the new line after the first image:

<img src="https://bulma.io/images/placeholders/128x128.png"><img src="https://bulma.io/images/placeholders/128x128.png">

h1 Tag issue

It appears to be due to the following css. The original code has 2 h1 elements that are siblings, whereas the vue code has the second h1 is not a sibling of the first h1 since it is in a div.

CSS (defined in bulma)

.content h1:not(:first-child) {
    margin-top: 1em;
}

Original HTML:

<h1>Bulma without VUE</h1>
<h1>Project 1</h1>

Vue Html:

<h1>Bulma with VUE</h1>
<div v-for="garden in gardens">
    <h1>{{garden.name}}<h1>
    ...
</div>


问:
Sending a button response to fb messenger via api.ai
I have started playing with diaglofFlow a.k.a api.ai with fb messenger integration.

I defined an intent which current returns 3 responses. 2 text responses and 1 custom payload.

the 2 text responses comes just fine but the custom payload which is suppose to return a button is not.

the custom payload looks like

```<code>{
  "recipient": {
    "id": "1234"
  },
  "message": {
    "attachment": {
      "type": "template",
      "payload": {
        "template_type": "button",
        "text": "What do you want to do next?",
        "buttons": [
          {
            "type": "web_url",
            "url": "https://www.messenger.com",
            "title": "Visit Messenger"
          }
        ]
      }
    }
  }
}
</code>```

Also, please note that the recipient id is something i am not sure how it should be provided. the fb documentation says it should be number of the recipient. I do not know how i am going to get that?

答:
actually this works</p>

```<code>{
 "facebook": {
   "attachment": {
   "type": "template",
   "payload": {
     "template_type": "button",
     "text": "What do you want to do next?",
     "buttons": [
      {
        "type": "web_url",
        "url": "https://www.messenger.com",
        "title": "Visit Messenger"
      }
     ]
   }
 }
}
}
</code>```

Body:
I have started playing with diaglofFlow a.k.a api.ai with fb messenger integration.

I defined an intent which current returns 3 responses. 2 text responses and 1 custom payload.

the 2 text responses comes just fine but the custom payload which is suppose to return a button is not.

the custom payload looks like

{
  "recipient": {
    "id": "1234"
  },
  "message": {
    "attachment": {
      "type": "template",
      "payload": {
        "template_type": "button",
        "text": "What do you want to do next?",
        "buttons": [
          {
            "type": "web_url",
            "url": "https://www.messenger.com",
            "title": "Visit Messenger"
          }
        ]
      }
    }
  }
}

Also, please note that the recipient id is something i am not sure how it should be provided. the fb documentation says it should be number of the recipient. I do not know how i am going to get that?

Body:
actually this works

{
 "facebook": {
   "attachment": {
   "type": "template",
   "payload": {
     "template_type": "button",
     "text": "What do you want to do next?",
     "buttons": [
      {
        "type": "web_url",
        "url": "https://www.messenger.com",
        "title": "Visit Messenger"
      }
     ]
   }
 }
}
}


问:
How to make separate config file for sms sending
I have done a sms sending code in codeigniter. It is worked successfully. But actually i want to make a config file so that i will not write the username, password, senderid on each page.

Here is my code below. First i have done a library file for sms sending.

Sms.php

```<code><?php
class SMS
{
    function SendSMS($url)
    {
        if(function_exists('curl_init'))
        {
            $ch = curl_init();
            $timeout = 60;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch, CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_0);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_TIMEOUT,$timeout);
            $data = curl_exec($ch);
            if($data === FALSE){
                throw new Exception(curl_errno($ch));
            }
            curl_close($ch);
            return $data;
        }
        else
        {
            return false;
        }
    }
}
?>
</code>```

Again for sms sending i am writting code in each controller something like this.

```<code>$sms_username = "GAPSMS";
$sms_password = "GAPSMS";
$sms_senderid = "GAPSMS";
$sms_mobile = $mobile;
$sms_message  = urlencode('Your One Time Password for transaction is: '.$otp);
$sms_api = "http://sendsms.sandeshwala.com/API/WebSMS/Http/v1.0a/index.php?username=$sms_username&password=$sms_password&sender=$sms_senderid&to=$sms_mobile&message=$sms_message&reqid=1&format={json|text}";
$this->sms->SendSMS($sms_api);
</code>```

This much below code i want to write in a config file in such a way so that i can write this once and then can use in every controller to send sms.

```<code>$sms_username = "GAPSMS";
$sms_password = "GAPSMS";
$sms_senderid = "GAPSMS";
</code>```

答:
UPDATED

In CodeIgniter, libraries can have their own configuration file. Let's change your library a bit:

```<code><?php
class Sms
{
    private $_username = 'GAPSMS'; // default value
    private $_password = 'GAPSMS'; // default value
    private $_senderid = 'GAPSMS'; // default value

    /**
     * Class constructor so the config
     * file is loaded.
     */
    public function __construct($config = array())
    {
        if ( ! empty($config))
        {
            foreach ($config as $key => $val)
            {
                $this->{"_".$key} = $val;
            }
        }
    }

    function send($mobile, $message)
    {
        if(function_exists('curl_init'))
        {
            $url = 'http://sendsms.sandeshwala.com/API/WebSMS/Http/v1.0a/index.php?username='.$this->_username.'&password='.$this->_password.'&sender='.$this->_senderid.'&to='.$mobile.'&message='.$message.'&reqid=1&format={json|text}';
            $ch = curl_init();
            $timeout = 60;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch, CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_0);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_TIMEOUT,$timeout);
            $data = curl_exec($ch);
            if($data === FALSE){
                throw new Exception(curl_errno($ch));
            }
            curl_close($ch);
            return $data;
        }
        else
        {
            return false;
        }
    }
}
</code>```

Then go create the config file application/config/sms.php inside which you put:

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');

$config['username'] = 'GAPSMS';
$config['password'] = 'GAPSMS';
$config['senderid'] = 'GAPSMS';
// End of file.
</code>```

Now whenever the library is loaded, and config file is loaded as well as values are set, everything should work just fine. And the rest of the code would be:

```<code>// Load the library and simply pass mobile number and message.
$this->load->library('sms');
$data = $this->sms->send('0123456789', 'Hello, this is the message');
</code>```

Body:
I have done a sms sending code in codeigniter. It is worked successfully. But actually i want to make a config file so that i will not write the username, password, senderid on each page.

Here is my code below. First i have done a library file for sms sending.

Sms.php

<?php
class SMS
{
    function SendSMS($url)
    {
        if(function_exists('curl_init'))
        {
            $ch = curl_init();
            $timeout = 60;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch, CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_0);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_TIMEOUT,$timeout);
            $data = curl_exec($ch);
            if($data === FALSE){
                throw new Exception(curl_errno($ch));
            }
            curl_close($ch);
            return $data;
        }
        else
        {
            return false;
        }
    }
}
?>

Again for sms sending i am writting code in each controller something like this.

$sms_username = "GAPSMS";
$sms_password = "GAPSMS";
$sms_senderid = "GAPSMS";
$sms_mobile = $mobile;
$sms_message  = urlencode('Your One Time Password for transaction is: '.$otp);
$sms_api = "http://sendsms.sandeshwala.com/API/WebSMS/Http/v1.0a/index.php?username=$sms_username&password=$sms_password&sender=$sms_senderid&to=$sms_mobile&message=$sms_message&reqid=1&format={json|text}";
$this->sms->SendSMS($sms_api);

This much below code i want to write in a config file in such a way so that i can write this once and then can use in every controller to send sms.

$sms_username = "GAPSMS";
$sms_password = "GAPSMS";
$sms_senderid = "GAPSMS";

Body:
UPDATED

In CodeIgniter, libraries can have their own configuration file. Let's change your library a bit:

<?php
class Sms
{
    private $_username = 'GAPSMS'; // default value
    private $_password = 'GAPSMS'; // default value
    private $_senderid = 'GAPSMS'; // default value

    /**
     * Class constructor so the config
     * file is loaded.
     */
    public function __construct($config = array())
    {
        if ( ! empty($config))
        {
            foreach ($config as $key => $val)
            {
                $this->{"_".$key} = $val;
            }
        }
    }

    function send($mobile, $message)
    {
        if(function_exists('curl_init'))
        {
            $url = 'http://sendsms.sandeshwala.com/API/WebSMS/Http/v1.0a/index.php?username='.$this->_username.'&password='.$this->_password.'&sender='.$this->_senderid.'&to='.$mobile.'&message='.$message.'&reqid=1&format={json|text}';
            $ch = curl_init();
            $timeout = 60;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch, CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_0);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_TIMEOUT,$timeout);
            $data = curl_exec($ch);
            if($data === FALSE){
                throw new Exception(curl_errno($ch));
            }
            curl_close($ch);
            return $data;
        }
        else
        {
            return false;
        }
    }
}

Then go create the config file application/config/sms.php inside which you put:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$config['username'] = 'GAPSMS';
$config['password'] = 'GAPSMS';
$config['senderid'] = 'GAPSMS';
// End of file.

Now whenever the library is loaded, and config file is loaded as well as values are set, everything should work just fine. And the rest of the code would be:

// Load the library and simply pass mobile number and message.
$this->load->library('sms');
$data = $this->sms->send('0123456789', 'Hello, this is the message');


问:
JavaScript - Adding two numbers (which still strings) in one textbox
I'm currently making a bot for some reason, i wanted to add a command that will do math when some user typed <command> 1 + 2 and bot will answers 3. And when it's <command> 2 * 3, it will reply 6. (Let's just use textbox for this case, if I typed 1 + 2 in textbox, theres an alert that shows "3").

My question is, is it possible, by any chance to make this kind of command?
If so, I'd like to know how. Since I've learned a little about JavaScript RegEx and i think if i use it, it'll work out.

答:
There's a lot of things you could do. You could eval the input, but this isn't good if you want to let other people use it (since it will execute any valid JavaScript).

The best approach I think, is to make a command for each action. Example:

```<code>add 2 2 // 4
sub 2 2 // 0
mul 2 2 // 4
div 2 2 // 1
</code>```

Here's a function that will run the add command, you can add switch cases for sub, div, and mul.

```<code>function run(input) {
    input = input.split(" ");
    switch (input[0]) {
        case "add":
            return parseInt(input[1]) + parseInt(input[2]);
            break;
     }
}
</code>```

if you don't want to make your bot this way, then it becomes very complicated. You either have to eval the input, but first validate that the input isn't something bad. Or you can build your own expression parser, which is also very hard.

ContentLicense: CC BY-SA 4.0

Body:
There's a lot of things you could do. You could eval the input, but this isn't good if you want to let other people use it (since it will execute any valid JavaScript).

The best approach I think, is to make a command for each action. Example:

add 2 2 // 4
sub 2 2 // 0
mul 2 2 // 4
div 2 2 // 1

Here's a function that will run the add command, you can add switch cases for sub, div, and mul.

function run(input) {
    input = input.split(" ");
    switch (input[0]) {
        case "add":
            return parseInt(input[1]) + parseInt(input[2]);
            break;
     }
}

if you don't want to make your bot this way, then it becomes very complicated. You either have to eval the input, but first validate that the input isn't something bad. Or you can build your own expression parser, which is also very hard.