问:
Add fixed tab bar pinned to top with scrolled content?
I tried this answer, but I could not achieve the same look & behavior as my current main activity.

What changes should I make to my existing main activity to add a fixed tab bar pinned to top with scrolled content like in the image below?

Here's a .GIF of my current main activity: i.stack.imgur.com/Yj0cv.gif

Here's a link to the full project called android: https://github.com/firebase/friendlychat/tree/master/android

Here's styles.xml:

```<code><resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="android:colorButtonNormal">@drawable/button_selector</item>
        <item name="colorButtonNormal">@drawable/button_selector</item>
        <item name="android:buttonStyle">@style/FriendlyButtonStyle</item>
    </style>

    <style name="FriendlyButtonStyle" parent="Widget.AppCompat.Button">
        <item name="android:textColor">@color/colorTitle</item>

    </style>
</resources>
</code>```

Here's activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.google.firebase.codelab.friendlychat.MainActivity">

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id">
    </com.google.android.gms.ads.AdView>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/messageRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/linearLayout"
        android:layout_below="@+id/adView"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/linearLayout">

        <ImageView
            android:id="@+id/addMessageImageView"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:src="@drawable/ic_add_black_24dp"/>

        <EditText
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/messageEditText"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="SEND"
            android:enabled="false"
            android:id="@+id/sendButton"
            android:layout_gravity="bottom"/>

    </LinearLayout>

    <ProgressBar
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/progressBar"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>
</code>```

答:
Just created behavior, what you want. Shouldn't be so complicated. So here is main XML for all Views. But I also have already created project for this sample, please write here, if I need to share full project.

SCREENS

MAIN XML

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:elevation="0dp">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/toolbar"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            android:scrollbars="none"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:layout_collapseMode="pin"
            app:tabMode="fixed" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>
</code>```

TO YOUR EXAMPLE

I share here another example, which should suite your code. I attached all view Ids for your examples. Check it.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:elevation="0dp">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <com.google.android.gms.ads.AdView
            android:id="@+id/adView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_below="@+id/toolbar"
            android:layout_centerHorizontal="true"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            ads:adSize="BANNER"
            ads:adUnitId="@string/banner_ad_unit_id"
            app:layout_collapseMode="pin"></com.google.android.gms.ads.AdView>

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/messageRecyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <LinearLayout
            android:id="@+id/linearLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom |center_horizontal"
            android:layout_marginBottom="100dp"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/addMessageImageView"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:src="@android:drawable/ic_dialog_alert" />

            <EditText
                android:id="@+id/messageEditText"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight="1" />

            <Button
                android:id="@+id/sendButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom"
                android:enabled="false"
                android:text="SEND" />

        </LinearLayout>

        <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|center_horizontal"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="100dp"
            android:layout_centerVertical="true" />

    </FrameLayout>

</android.support.design.widget.CoordinatorLayout>
</code>```

Body:
I tried this answer, but I could not achieve the same look & behavior as my current main activity.

What changes should I make to my existing main activity to add a fixed tab bar pinned to top with scrolled content like in the image below?

Here's a .GIF of my current main activity: i.stack.imgur.com/Yj0cv.gif

Here's a link to the full project called android: https://github.com/firebase/friendlychat/tree/master/android

Here's styles.xml:

<resources>

</resources>

Here's activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.google.firebase.codelab.friendlychat.MainActivity">

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id">
    </com.google.android.gms.ads.AdView>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/messageRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/linearLayout"
        android:layout_below="@+id/adView"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/linearLayout">

        <ImageView
            android:id="@+id/addMessageImageView"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:src="@drawable/ic_add_black_24dp"/>

        <EditText
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/messageEditText"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="SEND"
            android:enabled="false"
            android:id="@+id/sendButton"
            android:layout_gravity="bottom"/>

    </LinearLayout>

    <ProgressBar
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/progressBar"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

Body:
Just created behavior, what you want. Shouldn't be so complicated. So here is main XML for all Views. But I also have already created project for this sample, please write here, if I need to share full project.

SCREENS

MAIN XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:elevation="0dp">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/toolbar"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            android:scrollbars="none"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:layout_collapseMode="pin"
            app:tabMode="fixed" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

TO YOUR EXAMPLE

I share here another example, which should suite your code. I attached all view Ids for your examples. Check it.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:elevation="0dp">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <com.google.android.gms.ads.AdView
            android:id="@+id/adView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_below="@+id/toolbar"
            android:layout_centerHorizontal="true"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            ads:adSize="BANNER"
            ads:adUnitId="@string/banner_ad_unit_id"
            app:layout_collapseMode="pin"></com.google.android.gms.ads.AdView>

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/messageRecyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <LinearLayout
            android:id="@+id/linearLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom |center_horizontal"
            android:layout_marginBottom="100dp"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/addMessageImageView"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:src="@android:drawable/ic_dialog_alert" />

            <EditText
                android:id="@+id/messageEditText"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_weight="1" />

            <Button
                android:id="@+id/sendButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom"
                android:enabled="false"
                android:text="SEND" />

        </LinearLayout>

        <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|center_horizontal"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="100dp"
            android:layout_centerVertical="true" />

    </FrameLayout>

</android.support.design.widget.CoordinatorLayout>


来源: stackexchange

问:
How to swap two variables without using a third variable?
Can you swap the values of two variables without using a third variable as a temporary placeholder?</p>

答:
You can directly try for:

```<code>a, b = b, a
</code>```

It is a canonical way to exchange the value without using a third variable.

ContentLicense: CC BY-SA 4.0

Body:
You can directly try for:

a, b = b, a

It is a canonical way to exchange the value without using a third variable.


问:
Javascript hoisting
I am learning javascript hoisting feature, and find the following codes are really confusing:

```<code>var a = 1;
function b() {
    a = 10;
    return;
    function a() {}
}
b();
alert(a);
</code>```

The output is 1. As far as I know, because of hoisting, the codes above are equivalent to

```<code>var a;
function b() {
    function a() {}
    a=10;
    return;
}
a=1;
b();
alert(a);
</code>```

What happens when a function and a variable has the same name a?

答:
If we omit  function a() {}, then the value of the global a will be assigned from inside the function b()

```<code>var a = 1;
function b() {
  a = 10;
}
b();
console.log(a); // 10
</code>```

Using function a() {} inside the function b() will have the same effect as if we declared var a=10;
This will limit the scope of a to inside the function b() and won't bleed outside its scope.

```<code>var a = 1;
function b() {
  var a = 10;
}
b();
console.log(a); // 1
</code>```

Here is an easy read article on Hoisting:
https://medium.com/@bouguerra_70679/hoisting-464979b60282

ContentLicense: CC BY-SA 3.0

Title: Javascript hoisting

Body:
I am learning javascript hoisting feature, and find the following codes are really confusing:

var a = 1;
function b() {
    a = 10;
    return;
    function a() {}
}
b();
alert(a);

The output is 1. As far as I know, because of hoisting, the codes above are equivalent to

var a;
function b() {
    function a() {}
    a=10;
    return;
}
a=1;
b();
alert(a);

What happens when a function and a variable has the same name a?

Body:
If we omit  function a() {}, then the value of the global a will be assigned from inside the function b()

var a = 1;
function b() {
  a = 10;
}
b();
console.log(a); // 10

Using function a() {} inside the function b() will have the same effect as if we declared var a=10;
This will limit the scope of a to inside the function b() and won't bleed outside its scope.

var a = 1;
function b() {
  var a = 10;
}
b();
console.log(a); // 1

Here is an easy read article on Hoisting:
https://medium.com/@bouguerra_70679/hoisting-464979b60282


问:
why it float left is not working and these codes
my question is that why float left is not working under these codes
when i use them all the result just display on single div and other 7 where showing under that div at same place so please tell me what is the solution of this prob

```<code><div class="tv_l" style="top:1465px;
left:10px;

position:absolute;

width:1690px;
height:10px;
border-radius:3px/3px;
padding-right:10px;
padding-top:px;
border-left:10px;">

<hr>
</div>

<?php

$link = mysqli_connect("localhost" , "***" ,"***" , "***");
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
 exit();
} else {
    echo "";
}
?>
<?php
$result = mysqli_query($link, "SELECT * FROM **** ORDER BY RAND()
LIMIT 8" )
or die(mysqli_error());
while($row = mysqli_fetch_array( $result )){
?>;

<div class="son_s_p" style="top:1957px;
left:12px;
-webkit-box-shadow:0 3px 8px rgba(0, 0, 0, .25);
position:inherit;
background:white;
width:190px;
height:240px;
border-radius:3px/3px;
padding-right:10px;
padding-top:px;
border-left:10px;
text-align:center;
float:left;

">

 <img src="../lu/music/tumb/<?php echo $row['img']; ?>"style="width:198px; height:148px;"  >
<br>

 <?php echo $row['name']; ?><br><br>

 <div id="son_s_p" style="top:218px;
left:px;

position:absolute;

border-radius:3px/3px;
padding-right:10px;
padding-top:px;
border-left:10px;
text-align:justify;">

 <?php echo $row['time']; ?>    <span class="time&type" style="top;10px;"><?php echo $row['type']; ?></span>

</div>
</div>

<?php
}
?>
</code>```

with using position

without using position data will go top and top do not work

答:
Your question was unclear, however I have cleaned up your code so that the div .tv_l is to the left of the div .son_s_p and its content:

.tv_l {
  border-radius: 3px/3px;
  padding-right: 10px;
  border-left: 10px;
  border: 1px solid;
  float: left;
}

.son_s_p {
  -webkit-box-shadow: 0 3px 8px rgba(0, 0, 0, .25);
  background: white;
  width: 190px;
  height: 240px;
  border-radius: 3px/3px;
  padding-right: 10px;
  border-left: 10px;
  text-align: center;
  float: left;
}

#son_s_p {
  border-radius: 3px/3px;
  padding-right: 10px;
  padding-top: px;
  border-left: 10px;
  text-align: justify;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tv_l">
   <hr>
</div>

<?php
$link = mysqli_connect("localhost" , "***" ,"***" , "***");
if (mysqli_connect_errno()) {
   echo mysqli_connect_error();
   exit();
}else{
   echo "";
}

$result = mysqli_query($link, "SELECT * FROM **** ORDER BY RAND()
LIMIT 8")
or die(mysqli_error());
while($row = mysqli_fetch_array( $result )){
?>

<div class="son_s_p">
   <img src="../lu/music/tumb/<?php echo $row['img']; ?>" style="width:198px; height:148px;">
   <br>
   <?php echo $row['name']; ?>
   <br>
   <br>
   <div id="son_s_p">
      <?php echo $row['time']; ?>
      <span class="time&type" style="top;10px;"><?php echo $row['type']; ?></span>
   </div>
</div>

<?php } ?></code>```

Body:
my question is that why float left is not working under these codes
when i use them all the result just display on single div and other 7 where showing under that div at same place so please tell me what is the solution of this prob

<?php

$link = mysqli_connect("localhost" , "***" ,"***" , "***");
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
 exit();
} else {
    echo "";
}
?>
<?php
$result = mysqli_query($link, "SELECT * FROM **** ORDER BY RAND()
LIMIT 8" )
or die(mysqli_error());
while($row = mysqli_fetch_array( $result )){
?>;

 <img src="../lu/music/tumb/<?php echo $row['img']; ?>"style="width:198px; height:148px;"  >

 <?php echo $row['name']; ?>

 <?php echo $row['time']; ?>    <?php echo $row['type']; ?>

<?php
}
?>

with using position

without using position data will go top and top do not work

Body:
Your question was unclear, however I have cleaned up your code so that the div .tv_l is to the left of the div .son_s_p and its content:

.tv_l {
  border-radius: 3px/3px;
  padding-right: 10px;
  border-left: 10px;
  border: 1px solid;
  float: left;
}

.son_s_p {
  -webkit-box-shadow: 0 3px 8px rgba(0, 0, 0, .25);
  background: white;
  width: 190px;
  height: 240px;
  border-radius: 3px/3px;
  padding-right: 10px;
  border-left: 10px;
  text-align: center;
  float: left;
}

#son_s_p {
  border-radius: 3px/3px;
  padding-right: 10px;
  padding-top: px;
  border-left: 10px;
  text-align: justify;
}

<div class="tv_l">
   <hr>
</div>

<?php
$link = mysqli_connect("localhost" , "***" ,"***" , "***");
if (mysqli_connect_errno()) {
   echo mysqli_connect_error();
   exit();
}else{
   echo "";
}

$result = mysqli_query($link, "SELECT * FROM **** ORDER BY RAND()
LIMIT 8")
or die(mysqli_error());
while($row = mysqli_fetch_array( $result )){
?>

<div class="son_s_p">
   <img src="../lu/music/tumb/<?php echo $row['img']; ?>" style="width:198px; height:148px;">
   <br>
   <?php echo $row['name']; ?>
   <br>
   <br>
   <div id="son_s_p">
      <?php echo $row['time']; ?>
      <span class="time&amp;type" style="top;10px;"><?php echo $row['type']; ?></span>
   </div>
</div>

<?php } ?>


问:
I am unable to understand below php Function code -
How it will print hello - If hello is true, then the function must print hello, but if the function doesn’t receive hello or hello is false the function must print bye.</p>

```<code><?php
function showMessage($hello=false){
  echo ($hello)?'hello':'bye';
}
?>
</code>```

答:
You are using ternary operator inside function, which will check the type of variable true or false. By default $hello variable type will be false.

So below code will be check if variable type is true then prine 'hello' else ternary operator will be print 'bye'.

It is same as like below

```<code>if($hello==true){
    echo 'hello';
}else{
   echo 'bye';
}
</code>```

Body:
How it will print hello - If hello is true, then the function must print hello, but if the function doesn’t receive hello or hello is false the function must print bye.

<?php
function showMessage($hello=false){
  echo ($hello)?'hello':'bye';
}
?>

Body:
You are using ternary operator inside function, which will check the type of variable true or false. By default $hello variable type will be false.

So below code will be check if variable type is true then prine 'hello' else ternary operator will be print 'bye'.

It is same as like below

if($hello==true){
    echo 'hello';
}else{
   echo 'bye';
}


问:
How to display a web page in navigation-bar app?
I am currently creating an android application in which I use the location and 2 symbol Id's of the user to create an aprs comressed packet, and I need in one screen to ask the user for input and show him the content of the packet.

But I also need to display a web page, therefore I need to know if it is possible to use web interface to display a web page in a navigation bar application ? (the type of the app was decided since I need one screen for input and output and one screen for the web page).

答:
you can use Chrome Custom Tabs
link</p>

Body:
you can use Chrome Custom Tabs
link


问:
Entity Framework: table without primary key
I have an existing DB with which I would like to build a new app using EF4.0

Some tables do not have primary keys defined so that when I create a new Entity Data Model, I get the following message:

The table/view TABLE_NAME does not have a primary key defined
and no valid primary key could be inferred. This table/view has
been excluded. To use the entity, you will need to review your schema,
add the correct keys, and uncomment it.

If I want to use them and modify data, must I necessarily add a PK to those tables, or is there a workaround so that I don't have to?

答:
This maybe to late to reply...however...

If a table does't have a primary key then there are few scenarios that need to be analyzed in order to make the EF work properly. The rule is: EF will work with tables/classes with primary key. That is how it does tracking...

Say, your table
1. Records are unique: the uniqueness is made by a single foreign key column:
2. Records are unique: the uniqueness are made by a combination of multiple columns.
3. Records are not unique (for the most part*).

For scenarios #1 and #2 you can add the following line to DbContext module OnModelCreating method:
modelBuilder.Entity().HasKey(x => new { x.column_a, x.column_b }); // as many columns as it takes to make records unique.

For the scenario #3 you can still use the above solution (#1 + #2) after you study the table (*what makes all records unique anyway). If you must have include ALL columns to make all records unique then you may want to add a primary key column to your table. If this table is from a 3rd party vendor than clone this table to your local database (overnight or as many time you needed) with primary key column added arbitrary through your clone script.


问:
Update data frame values as per multiple where condition using numpy
I want to change DateWork['Variable'] values as per multiple where conditions and update in  DateWork['Date']

If Frequency=3 and len(Variable)=6 then replace M with "-0" and update in DateWork['Date']
If Frequency=3 and len(Variable)=7 then replace M with "-" and update in DateWork['Date']

DataFrame: DateWork

```<code>Frequency Variable      Date
3         1950M2        1950-02-01
3         1950M3        1950-03-01
2         1950-07-01    1950-07-01
3         1950M9        1950-09-01
2         1950-10-01    1950-10-01
3         1950M10       1950-10-01
</code>```

My code:

```<code>DateWork.loc[DateWork['Date']] = np.where(((DateWork['Frequency'] == 3) & (DateWork['variable'].str.len() == 6)), 'M', '-0',  DateWork['Date'])
DateWork.loc[DateWork['Date']] = np.where(((DateWork['Frequency'] == 3) & (DateWork['variable'].str.len() == 7)), 'M', '-',  DateWork['Date'])
DateWork.loc[DateWork['Frequency'] == 3, 'Date'] = DateWork.loc[DateWork['Frequency'] == 3, 'variable'] + '-01'
</code>```

This gives error:

TypeError: where() takes at most 3 arguments (4 given)

答:
Your error is raised because you were passing one extra argument to np.where, you can check the documentation about this method, link is below. also once, this problem gets fixed, the way you wrote your code makes the last np.where call update and replace all the ones before, so they need to be "nested" in order to work properly.

I also provided a solution without np.where should you request it.

Solution with numpy.where:

```<code># where frequenct == 3 and len(variable) == 6, we put variable and replace M with -0, if that's not
# the case, we search where frequency == 3 and len(variable) == 7 and put variable while replacing M with -
# else we just put Variable
DateWork['Date'] = np.where((DateWork['Frequency'] == 3) & (DateWork['Variable'].str.len() == 6), DateWork['Variable'].str.replace('M','-0'),
                       np.where((DateWork['Frequency'] == 3) & (DateWork['Variable'].str.len() == 7), DateWork['Variable'].str.replace('M','-'), DateWork['Variable']))

# we add first day date where frequency == 3
DateWork.loc[DateWork['Frequency'] == 3, 'Date'] = DateWork.loc[DateWork['Frequency'] == 3, 'Date'] + '-01'
</code>```

Solution with pandas.dataframe.loc:

```<code># where frenquency == 3 and len(variable) == 6, in date we put variable and replace M with -0
DateWork.loc[(DateWork['Frequency'] == 3) & (DateWork['Variable'].str.len() == 6),'Date'] = DateWork['Variable'].str.replace('M','-0')

# where frequency == 3 and len(variable) == 7, in date we put variable and replace M with -
DateWork.loc[(DateWork['Frequency'] == 3) & (DateWork['Variable'].str.len() == 7),'Date'] = DateWork['Variable'].str.replace('M','-')

# where frequency == 2, in date we simply put variable
DateWork.loc[DateWork['Frequency'] == 2,'Date'] = DateWork['Variable']

# where frequency == 3, in date we add first day date.
DateWork.loc[DateWork['Frequency'] == 3, 'Date'] = DateWork.loc[DateWork['Frequency'] == 3, 'Date'] + '-01'
</code>```

Body:
I want to change DateWork['Variable'] values as per multiple where conditions and update in  DateWork['Date']

If Frequency=3 and len(Variable)=6 then replace M with "-0" and update in DateWork['Date']
If Frequency=3 and len(Variable)=7 then replace M with "-" and update in DateWork['Date']

DataFrame: DateWork

Frequency Variable      Date
3         1950M2        1950-02-01
3         1950M3        1950-03-01
2         1950-07-01    1950-07-01
3         1950M9        1950-09-01
2         1950-10-01    1950-10-01
3         1950M10       1950-10-01

My code:

DateWork.loc[DateWork['Date']] = np.where(((DateWork['Frequency'] == 3) & (DateWork['variable'].str.len() == 6)), 'M', '-0',  DateWork['Date'])
DateWork.loc[DateWork['Date']] = np.where(((DateWork['Frequency'] == 3) & (DateWork['variable'].str.len() == 7)), 'M', '-',  DateWork['Date'])
DateWork.loc[DateWork['Frequency'] == 3, 'Date'] = DateWork.loc[DateWork['Frequency'] == 3, 'variable'] + '-01'

This gives error:

TypeError: where() takes at most 3 arguments (4 given)

Body:
Your error is raised because you were passing one extra argument to np.where, you can check the documentation about this method, link is below. also once, this problem gets fixed, the way you wrote your code makes the last np.where call update and replace all the ones before, so they need to be "nested" in order to work properly.

I also provided a solution without np.where should you request it.

Solution with numpy.where:

# where frequenct == 3 and len(variable) == 6, we put variable and replace M with -0, if that's not
# the case, we search where frequency == 3 and len(variable) == 7 and put variable while replacing M with -
# else we just put Variable
DateWork['Date'] = np.where((DateWork['Frequency'] == 3) & (DateWork['Variable'].str.len() == 6), DateWork['Variable'].str.replace('M','-0'),
                       np.where((DateWork['Frequency'] == 3) & (DateWork['Variable'].str.len() == 7), DateWork['Variable'].str.replace('M','-'), DateWork['Variable']))

# we add first day date where frequency == 3
DateWork.loc[DateWork['Frequency'] == 3, 'Date'] = DateWork.loc[DateWork['Frequency'] == 3, 'Date'] + '-01'

Solution with pandas.dataframe.loc:

# where frenquency == 3 and len(variable) == 6, in date we put variable and replace M with -0
DateWork.loc[(DateWork['Frequency'] == 3) & (DateWork['Variable'].str.len() == 6),'Date'] = DateWork['Variable'].str.replace('M','-0')

# where frequency == 3 and len(variable) == 7, in date we put variable and replace M with -
DateWork.loc[(DateWork['Frequency'] == 3) & (DateWork['Variable'].str.len() == 7),'Date'] = DateWork['Variable'].str.replace('M','-')

# where frequency == 2, in date we simply put variable
DateWork.loc[DateWork['Frequency'] == 2,'Date'] = DateWork['Variable']

# where frequency == 3, in date we add first day date.
DateWork.loc[DateWork['Frequency'] == 3, 'Date'] = DateWork.loc[DateWork['Frequency'] == 3, 'Date'] + '-01'


问:
Servlet redirect error/ jsp cannot load css
I'm having some issues to redirect to an HTML page via servlet.

I have an index.jsp and index.htm page in the same directory.

When i use the following code my servlet redirects to the jsp page fine, but if i change it to index.htm i cannot redirect and get this error on the browser (mozilla)

"Firefox has detected that the server is redirecting the request for this address in a way that will never complete."

```<code>response.setHeader("Location", "/portal/index.jsp");
response.setStatus(HttpServletResponse.SC_FOUND);
</code>```

The reason I want to redirect to the htm page instead of jsp page is because when i redirect to the jsp page, none of my css gets loaded..which is a whole other problem itself.

I have been spending some days now trying to find a solution but I am not getting anywhere. If anyone has any advice to either of the issues i will be so greatful. Thank You.

答:
You can used

response.sendRedirect("pangename.jsp");

RequestDispatcher rd=request.getRequestDispatcher("pagename.jsp");

 rd.forward(request, response);

Body:
I'm having some issues to redirect to an HTML page via servlet.

I have an index.jsp and index.htm page in the same directory.

When i use the following code my servlet redirects to the jsp page fine, but if i change it to index.htm i cannot redirect and get this error on the browser (mozilla)

"Firefox has detected that the server is redirecting the request for this address in a way that will never complete."

response.setHeader("Location", "/portal/index.jsp");
response.setStatus(HttpServletResponse.SC_FOUND);

The reason I want to redirect to the htm page instead of jsp page is because when i redirect to the jsp page, none of my css gets loaded..which is a whole other problem itself.

I have been spending some days now trying to find a solution but I am not getting anywhere. If anyone has any advice to either of the issues i will be so greatful. Thank You.


答:
As far as i could understand you should use 'WebView' to show webpage, further you can use interfaces to communicate between web page JavaScript code and android code.
Please refer following links :
https://developer.android.com/reference/android/webkit/WebView.html

https://developer.android.com/guide/webapps/webview.html

Title: How to display a web page in navigation-bar app?

Body:
I am currently creating an android application in which I use the location and 2 symbol Id's of the user to create an aprs comressed packet, and I need in one screen to ask the user for input and show him the content of the packet.

But I also need to display a web page, therefore I need to know if it is possible to use web interface to display a web page in a navigation bar application ? (the type of the app was decided since I need one screen for input and output and one screen for the web page).


问:
Maximum POST Variables PHP?
I am submitting 5 stings to PHP from HTML

I get an error on goDaddy (Internal Server error) when i try and pass 5 strings  BUT  it works for 4 strings.
I cannot figure out the problem. Is there a maximum amount of POST variables that can be passed?
I works for 4 strings, and when i add another string i get an error.
Godaddy support team was useless was on the phone with them for Hours.
The coding works fine on WAMP!

HTML

```<code><form action="login.php" method="post">

  <input type="text" name="username" placeholder="Username"/>
  <input type="password" name="password" placeholder="Password"/>
  <input type="text" name="clientID" id="client_id" value="" />
   <input type="text" name="redirect" id="redirect_uri" value="" />
    <input type="text" name="webstate" id="stateValue" value="" />

  <button>Login</button>
</form>
</code>```

PHP

```<code>$myusername=$_POST['username'];
$mypassword=$_POST['password'];
$client_id=$_POST['clientID'];
$redirect_uri=$_POST['redirect'];
/*$state=$_POST['webstate']; */  <---- When i add this line it Shows
                                       Internal Server Error

echo "Username: ".$myusername. "<br />";
echo "Client ID: ".$client_id. "<br />";
echo "Redirect URL: ".$redirect_uri. "<br />";
/*echo "State: ".$state. "<br />"; */ <--- I commented this becouse it
                                           useless
</code>```

答:
there is no maximum amount of POST request
Your code Is Ok, I tried it and it works perfectly
i just added one line to check the POST values

```<code>if ($_SERVER['REQUEST_METHOD'] == 'POST') {

$myusername = $_POST['username'];
$mypassword = $_POST['password'];
$client_id = $_POST['clientID'];
$redirect_uri = $_POST['redirect'];
$state = $_POST['webstate'];

echo "Username: ".$myusername. "<br />";
echo "Client ID: ".$client_id. "<br />";
echo "Redirect URL: ".$redirect_uri. "<br />";
echo "State: ".$state. "<br />";
}
</code>```

If the problem still appears try a different host

Title: Maximum POST Variables PHP?

Body:
I am submitting 5 stings to PHP from HTML

I get an error on goDaddy (Internal Server error) when i try and pass 5 strings  BUT  it works for 4 strings.
I cannot figure out the problem. Is there a maximum amount of POST variables that can be passed?
I works for 4 strings, and when i add another string i get an error.
Godaddy support team was useless was on the phone with them for Hours.
The coding works fine on WAMP!

HTML

<form action="login.php" method="post">

  <input type="text" name="username" placeholder="Username"/>
  <input type="password" name="password" placeholder="Password"/>
  <input type="text" name="clientID" id="client_id" value="" />
   <input type="text" name="redirect" id="redirect_uri" value="" />
    <input type="text" name="webstate" id="stateValue" value="" />

  <button>Login</button>
</form>

PHP

$myusername=$_POST['username'];
$mypassword=$_POST['password'];
$client_id=$_POST['clientID'];
$redirect_uri=$_POST['redirect'];
/*$state=$_POST['webstate']; */  <---- When i add this line it Shows
                                       Internal Server Error

echo "Username: ".$myusername. "
";
echo "Client ID: ".$client_id. "
";
echo "Redirect URL: ".$redirect_uri. "
";
/*echo "State: ".$state. "
"; */ <--- I commented this becouse it
                                           useless

Body:
there is no maximum amount of POST request
Your code Is Ok, I tried it and it works perfectly
i just added one line to check the POST values

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

$myusername = $_POST['username'];
$mypassword = $_POST['password'];
$client_id = $_POST['clientID'];
$redirect_uri = $_POST['redirect'];
$state = $_POST['webstate'];

echo "Username: ".$myusername. "<br />";
echo "Client ID: ".$client_id. "<br />";
echo "Redirect URL: ".$redirect_uri. "<br />";
echo "State: ".$state. "<br />";
}

If the problem still appears try a different host


问:
Google App Script: extract data from a XML file
I need to pull this XML structure to a Google spreadsheet,

```<code><directory>
    <fieldset>
        <field id="displayName">Display name</field>
        <field id="firstName">First name</field>
    </fieldset>
    <employees>
        <employee id="200">
            <field id="displayName">Donald Duck</field>
            <field id="firstName">Donald</field>
        </employee>
    </employees>
</directory>
</code>```

I've pulled all the <field id>, but I need just the <employee id> and I don't know how to do, pardon me I haven't any knowledge on XML so please help me.

```<code>function ImportXML() {

   var url = "https://api.Fake.com/employees/directory";
   var response = UrlFetchApp.fetch(url, params);

    var xml = response.getContentText();
    var doc = XmlService.parse(xml);
    var root = doc.getRootElement();

    logChildren(doc.getRootElement().getChildren());

 function logChildren(elements){

    var ss = SpreadsheetApp.getActiveSpreadsheet();

    var sheet = ss.getSheets()[0];

    for (var i = 0; i < elements.length; i++) {

    var range = sheet.getRange(1,i+1);

    range.setValue(elements[i].getText());

    if(elements[i].getContentSize() > 1){
    var children = elements[i].getChildren();

    logChildren(children);
    }
     }
      }
</code>```

Thanks for your help.

答:
Check this document regarding reading a specific node using appscript

getChild(name)

Gets the first Element node with the given name and no namespace that
  is an immediate child of this Element node. If there is no such node,
  this method returns null.

Parameters

Name  Type    Description name    String  the name of the child Element node
  Return

Element — the Element node, or null if there is no immediate child
  Element node with the given name and no namespace

Use this working example as your guide.

```<code>  function readSpecificNode() {
  var url = 'https://www.w3schools.com/xml/books.xml';
  var xml = UrlFetchApp.fetch(url).getContentText();
  var document = XmlService.parse(xml);
  var entries = document.getRootElement().getChild('book').getChild('title').getAttribute('lang').getValue();
  Logger.log(entries);
}
</code>```

Just do not forget to change the url to your designated xml and the getChild element from 'book', 'title' and 'lang' to 'directory', 'employees', 'employee' then setting the getAttribute to 'id' so it would fit your desired output.

Body:
I need to pull this XML structure to a Google spreadsheet,

<directory>
    <fieldset>
        <field id="displayName">Display name</field>
        <field id="firstName">First name</field>
    </fieldset>
    <employees>
        <employee id="200">
            <field id="displayName">Donald Duck</field>
            <field id="firstName">Donald</field>
        </employee>
    </employees>
</directory>

I've pulled all the <field id>, but I need just the <employee id> and I don't know how to do, pardon me I haven't any knowledge on XML so please help me.

function ImportXML() {

   var url = "https://api.Fake.com/employees/directory";
   var response = UrlFetchApp.fetch(url, params);

    var xml = response.getContentText();
    var doc = XmlService.parse(xml);
    var root = doc.getRootElement();

    logChildren(doc.getRootElement().getChildren());

 function logChildren(elements){

    var ss = SpreadsheetApp.getActiveSpreadsheet();

    var sheet = ss.getSheets()[0];

    for (var i = 0; i < elements.length; i++) {

    var range = sheet.getRange(1,i+1);

    range.setValue(elements[i].getText());

    if(elements[i].getContentSize() > 1){
    var children = elements[i].getChildren();

    logChildren(children);
    }
     }
      }

Thanks for your help.

Body:
Check this document regarding reading a specific node using appscript

getChild(name)

Gets the first Element node with the given name and no namespace that
  is an immediate child of this Element node. If there is no such node,
  this method returns null.

Parameters

Name  Type    Description name    String  the name of the child Element node
  Return

Element — the Element node, or null if there is no immediate child
  Element node with the given name and no namespace

Use this working example as your guide.

  function readSpecificNode() {
  var url = 'https://www.w3schools.com/xml/books.xml';
  var xml = UrlFetchApp.fetch(url).getContentText();
  var document = XmlService.parse(xml);
  var entries = document.getRootElement().getChild('book').getChild('title').getAttribute('lang').getValue();
  Logger.log(entries);
}

Just do not forget to change the url to your designated xml and the getChild element from 'book', 'title' and 'lang' to 'directory', 'employees', 'employee' then setting the getAttribute to 'id' so it would fit your desired output.


问:
I sat primary key on name varchar it accepts one null value
I sat primary key on name varchar it accepts one null value

It acts like unique constraint.

What's the problem?

答:
I think you;re missing some details in ques but if you set any column to PK it doesn't allow null values into it. </p>

<p>But, Usually we will not set Primary Key constraint on anything(name column here) which are having a meaning in the system and instead have something like ID or GUID as primary key. </p>

Body:
I think you;re missing some details in ques but if you set any column to PK it doesn't allow null values into it.

But, Usually we will not set Primary Key constraint on anything(name column here) which are having a meaning in the system and instead have something like ID or GUID as primary key.


问:
implement change value on drag (like you do in Photoshop)
I am brainstorming on how to change value of a text on drag over. Basically, you drag to the left, value decreased. You drag to the right -> value increases.

This functionality is implemented in Adobe Products. Check this image:

http://i.imgur.com/9QeoUNx.png

Note that on drag only the value changes. I do not move the element in any way so JQuery UI draggable doesn't seem to be an option.

This is the starter(almost empty) template:

https://codepen.io/anon/pen/owadRe

```<code><div class="drag">123</div>

.drag{
  cursor: ew-resize;
}
</code>```

How would you create such functionality?

答:
There's plugins that do this if you Google it, but really it's just a matter of constantly getting the mouse's x position in relation to the clicked element then updating the value by that distance (or some transformation of that distance).

Below is a pretty unrefined and quick example using jquery.

$(".drag").on('mousedown', e => {
  // get initial value
  let val = parseInt($('.drag').text());
  $('body, .drag').toggleClass('dragging');
  // check mousemove
  $('body').on('mousemove', e => {
    let xinit = $('.drag').offset().left; // element x position
    let xfin = e.pageX; // mouse x position
    let dVal = Math.floor(val + (xfin - xinit));
    $('.drag').text(dVal);
  });
  // remove mousemove when done clicking
  $('body').on('mouseup', e => {
    $('body, .drag').toggleClass('dragging');
    $('body').off('mousemove');
  })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body, html{
  width : 100%;
  height : 100%;
  display : flex;
  align-items : center;
  justify-content : center;
  background-color : yellow;
}
body.dragging{
  cursor : ew-resize;
}
.drag {
  cursor: ew-resize;
    -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none
}</code>```

123

```

Body:
I am brainstorming on how to change value of a text on drag over. Basically, you drag to the left, value decreased. You drag to the right -> value increases.

This functionality is implemented in Adobe Products. Check this image:

http://i.imgur.com/9QeoUNx.png

Note that on drag only the value changes. I do not move the element in any way so JQuery UI draggable doesn't seem to be an option.

This is the starter(almost empty) template:

https://codepen.io/anon/pen/owadRe

123

.drag{
  cursor: ew-resize;
}

How would you create such functionality?

Body:
There's plugins that do this if you Google it, but really it's just a matter of constantly getting the mouse's x position in relation to the clicked element then updating the value by that distance (or some transformation of that distance).

Below is a pretty unrefined and quick example using jquery.

$(".drag").on('mousedown', e => {
  // get initial value
  let val = parseInt($('.drag').text());
  $('body, .drag').toggleClass('dragging');
  // check mousemove
  $('body').on('mousemove', e => {
    let xinit = $('.drag').offset().left; // element x position
    let xfin = e.pageX; // mouse x position
    let dVal = Math.floor(val + (xfin - xinit));
    $('.drag').text(dVal);
  });
  // remove mousemove when done clicking
  $('body').on('mouseup', e => {
    $('body, .drag').toggleClass('dragging');
    $('body').off('mousemove');
  })
})

body, html{
  width : 100%;
  height : 100%;
  display : flex;
  align-items : center;
  justify-content : center;
  background-color : yellow;
}
body.dragging{
  cursor : ew-resize;
}
.drag {
  cursor: ew-resize;
    -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none
}

<body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <div class="drag">123</div>
</body>


问:
Drawing sprite with additional alpha channel
I can draw image with alpha channel fine,
but can't modify alpha channel via color parameter.

Tried this:

```<code>d3dImage->Begin(D3DXSPRITE_ALPHABLEND|D3DXSPRITE_SORT_DEPTH_BACKTOFRONT|D3DXSPRITE_DO_NOT_ADDREF_TEXTURE);
</code>```

I'm using sprite to render rectangle and images:

```<code>void DrawRect(float x, float y, int width, int height, DWORD color)
{
    imgPosition.x = x;
    imgPosition.y = y;

    imgSize.left = 0;
    imgSize.right = width;
    imgSize.top = 0;
    imgSize.bottom = height;

    d3dImage->Draw(texWhite, &imgSize, NULL, &imgPosition, color);
}
</code>```

答: Works with 8-bit textures only.</p>

Body:
I can draw image with alpha channel fine,
but can't modify alpha channel via color parameter.

Tried this:

d3dImage->Begin(D3DXSPRITE_ALPHABLEND|D3DXSPRITE_SORT_DEPTH_BACKTOFRONT|D3DXSPRITE_DO_NOT_ADDREF_TEXTURE);

I'm using sprite to render rectangle and images:

void DrawRect(float x, float y, int width, int height, DWORD color)
{
    imgPosition.x = x;
    imgPosition.y = y;

    imgSize.left = 0;
    imgSize.right = width;
    imgSize.top = 0;
    imgSize.bottom = height;

    d3dImage->Draw(texWhite, &imgSize, NULL, &imgPosition, color);
}

Body: Works with 8-bit textures only.


问:
Can not get the js file in using requirejs
I'm trying to build client project using requireJs.
But when I published it on the nginx server, an error occurred.
This is my project directory structure

when it ran here, the browser threw a js error.

```<code>require(['config/require.conf'], function(){
    'use strict';
    require(['src/common/js/pageloader'], function(pageloader){
        pageloader();
    })
})
</code>```

js error:

GET http://localhost:8011/src/homepage/config/require.conf.js  require.js:1961

It seems like the error occurred because I use the relative path (lack of '/').

However, I add the slash as prefix of directory('/config/require.conf').
As a result, when the browser ran here, requirejs didn't add the suffix ".js" for the js file(config/require.conf.js).

Another error occurred~

```<code> GET http://localhost:8011/config/require.conf 404 (Not Found)
</code>```

What should I do for the error? Thanks.

答:
You can pass two things in the dependency list of a require call:

A module name. This is the default. When you pass a module name, RequireJS will convert the name to a path using baseUrl, paths, map, etc. from your RequireJS configuration.

A path. RequireJS considers that you are passing a path if the dependency: a) begins with '/', (which is your case), b) contains an HTML query (e.g. 'foo?bar=1'), c) ends with the .js extension, d) specifies a protocol (e.g. https://).

In this case, RequireJS uses the path as-is, without using its configuration to transform it, and it does not automatically add a .js extension to it.

Your usage is the 2nd case so you have to add .js to your path so that RequireJS can find your file:

```<code>require(['/config/require.conf.js'], function() {
</code>```

Body:
I'm trying to build client project using requireJs.
But when I published it on the nginx server, an error occurred.
This is my project directory structure

when it ran here, the browser threw a js error.

require(['config/require.conf'], function(){
    'use strict';
    require(['src/common/js/pageloader'], function(pageloader){
        pageloader();
    })
})

js error:

GET http://localhost:8011/src/homepage/config/require.conf.js  require.js:1961

It seems like the error occurred because I use the relative path (lack of '/').

However, I add the slash as prefix of directory('/config/require.conf').
As a result, when the browser ran here, requirejs didn't add the suffix ".js" for the js file(config/require.conf.js).

Another error occurred~

 GET http://localhost:8011/config/require.conf 404 (Not Found)

What should I do for the error? Thanks.

Body:
You can pass two things in the dependency list of a require call:

A module name. This is the default. When you pass a module name, RequireJS will convert the name to a path using baseUrl, paths, map, etc. from your RequireJS configuration.

A path. RequireJS considers that you are passing a path if the dependency: a) begins with '/', (which is your case), b) contains an HTML query (e.g. 'foo?bar=1'), c) ends with the .js extension, d) specifies a protocol (e.g. https://).

In this case, RequireJS uses the path as-is, without using its configuration to transform it, and it does not automatically add a .js extension to it.

Your usage is the 2nd case so you have to add .js to your path so that RequireJS can find your file:

require(['/config/require.conf.js'], function() {


问:
How to change user in Yii2
I am using an API into a Yii2 app, and so Yii::$app->user is null.

Can I manually set Yii::$app->user?

All exmaples I have foun involved editing a user, not setting a user.

答:
If you want log an user you could try getting and identity this way and log the user

```<code>  / find a user identity with the specified username.
  // note that you may want to check the password if needed

  $identity = User::find()-where(['username' => $username])->one();

  // logs in the user
  Yii::$app->user->login($identity);
</code>```

http://www.yiiframework.com/doc-2.0/guide-security-authentication.html

Title: How to change user in Yii2

Body:
If you want log an user you could try getting and identity this way and log the user

  / find a user identity with the specified username.
  // note that you may want to check the password if needed

  $identity = User::find()-where(['username' => $username])->one();

  // logs in the user
  Yii::$app->user->login($identity);

http://www.yiiframework.com/doc-2.0/guide-security-authentication.html


问:
How does load csv create relations in neo4j?
I am using the following commands to load data from a csv file into Neo4j. The input file is large and there are millions of rows.
While this query is running I can query for the number of nodes and check the progress. But once it stops creating nodes, I guess it moves on to creating relations. But I am not able to check the progress of this step.

I have two doubts:

Does it process the command for each line of file, i.e. create the nodes and relations etc. for each source line??

Or it creates all the nodes in one shot and then creates the relations.

Anyways I want to monitor the progress of the following command. It seems to get stuck after creating the nodes and when I try to query for number of relations I get 0 as output.

I created a constraint on the key attribute.

```<code>CREATE CONSTRAINT ON (n:Node) ASSERT n.key is UNIQUE;
</code>```

Here is the cypher that loads the file.

```<code>USING PERIODIC COMMIT
LOAD CSV FROM "file:///data/abc.csv" AS row
MERGE (u:Node {name:row[1],type:row[2],key:row[1]+"*"+row[2]})
MERGE (v:Node {name:row[4],type:row[5], key:row[4]+"*"+row[5]})
CREATE (u) - [r:relatedTo]-> (v)
SET r.type = row[3], r.frequency=toint(trim(row[6]));
</code>```

答:
For every row of your CSV file, Neo4j is doing the cypher script, ie. :

```<code>MERGE (u:Node {name:row[1],type:row[2],key:row[1]+"*"+row[2]})
MERGE (v:Node {name:row[4],type:row[5], key:row[4]+"*"+row[5]})
CREATE (u) - [r:relatedTo]-> (v)
 SET r.type = row[3], r.frequency=toint(trim(row[6]))
</code>```

Due to using periodic commit, every 500 lines (the default value), a commit is done.

You can only see  changes in your graph, when Neo4j have finished to parse 500 lines.

But your script is not optimized, you are not using the constraint with the merge.

You should consider this script instead:

```<code>USING PERIODIC COMMIT
LOAD CSV FROM "file:///data/abc.csv" AS row

MERGE (u:Node {key:row[1]+"*"+row[2]})
  ON CREATE SET u.name = row[1],
                u.type = row[2]

MERGE (v:Node {key:row[4]+"*"+row[5]})
  ON CREATE SET v.name = row[4],
                v.type = row[5]

CREATE (u)-[r:relatedTo]->(v)
 SET r.type = row[3], r.frequency=toint(trim(row[6]));
</code>```

Cheers

Body:
I am using the following commands to load data from a csv file into Neo4j. The input file is large and there are millions of rows.
While this query is running I can query for the number of nodes and check the progress. But once it stops creating nodes, I guess it moves on to creating relations. But I am not able to check the progress of this step.

I have two doubts:

Does it process the command for each line of file, i.e. create the nodes and relations etc. for each source line??

Or it creates all the nodes in one shot and then creates the relations.

Anyways I want to monitor the progress of the following command. It seems to get stuck after creating the nodes and when I try to query for number of relations I get 0 as output.

I created a constraint on the key attribute.

CREATE CONSTRAINT ON (n:Node) ASSERT n.key is UNIQUE;

Here is the cypher that loads the file.

USING PERIODIC COMMIT
LOAD CSV FROM "file:///data/abc.csv" AS row
MERGE (u:Node {name:row[1],type:row[2],key:row[1]+"*"+row[2]})
MERGE (v:Node {name:row[4],type:row[5], key:row[4]+"*"+row[5]})
CREATE (u) - [r:relatedTo]-> (v)
SET r.type = row[3], r.frequency=toint(trim(row[6]));

Body:
For every row of your CSV file, Neo4j is doing the cypher script, ie. :

MERGE (u:Node {name:row[1],type:row[2],key:row[1]+"*"+row[2]})
MERGE (v:Node {name:row[4],type:row[5], key:row[4]+"*"+row[5]})
CREATE (u) - [r:relatedTo]-> (v)
 SET r.type = row[3], r.frequency=toint(trim(row[6]))

Due to using periodic commit, every 500 lines (the default value), a commit is done.

You can only see  changes in your graph, when Neo4j have finished to parse 500 lines.

But your script is not optimized, you are not using the constraint with the merge.

You should consider this script instead:

USING PERIODIC COMMIT
LOAD CSV FROM "file:///data/abc.csv" AS row

MERGE (u:Node {key:row[1]+"*"+row[2]})
  ON CREATE SET u.name = row[1],
                u.type = row[2]

MERGE (v:Node {key:row[4]+"*"+row[5]})
  ON CREATE SET v.name = row[4],
                v.type = row[5]

CREATE (u)-[r:relatedTo]->(v)
 SET r.type = row[3], r.frequency=toint(trim(row[6]));

Cheers


问:
Where is the error in the react?
I built the file using commands:

browserify -t reactify js/app.js -o js/build.js

When starting in the browser, an error occurs:

```<code>build.js:196 Uncaught TypeError: React.render is not a function
    at Object.2.react (build.js:196)
    at s (build.js:1)
    at e (build.js:1)
    at build.js:1
</code>```

How to fix it?

答: render is no longer part of 'react'. If you want to render to a DOM element, import render from 'react-dom'.

Title: Where is the error in the react?

Body:
I built the file using commands:

browserify -t reactify js/app.js -o js/build.js

When starting in the browser, an error occurs:

build.js:196 Uncaught TypeError: React.render is not a function
    at Object.2.react (build.js:196)
    at s (build.js:1)
    at e (build.js:1)
    at build.js:1

How to fix it?


问:
Echo $ in Javascript
i am trying to echo a string in java script like this

```<code>    echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('User registeration Complete \n User Number: $account_number\n First Name: $first_name\n Last Name: $last_name')
window.location.href='index.html';
</SCRIPT>");
</code>```

Challenge i have is I want it to echo an assigned variable say $name='Samil'; and it prints the $name on Javascript alertbox.

答:
Try this:

```<code>echo"
<SCRIPT LANGUAGE='JavaScript'>
   window.alert('User registeration Complete \n User Number: ".$account_number."\n First Name: ".$first_name."\n Last Name: ".$last_name."')
   window.location.href='index.html';
</SCRIPT>
";
</code>```

Note: The language attribute on script tags is deprecated and should be type="text/javascript"

Title: Echo $ in Javascript

Body:
i am trying to echo a string in java script like this

    echo ("");

Challenge i have is I want it to echo an assigned variable say $name='Samil'; and it prints the $name on Javascript alertbox.

Body:
Try this:

echo"
<SCRIPT LANGUAGE='JavaScript'>
   window.alert('User registeration Complete \n User Number: ".$account_number."\n First Name: ".$first_name."\n Last Name: ".$last_name."')
   window.location.href='index.html';
</SCRIPT>
";

Note: The language attribute on script tags is deprecated and should be type="text/javascript"


问:
Property xxx is type-mismatched
I'm trying to build simple CRUD application using Grails. I'm absolutely new to this framework. My CRUD table has few properties, connected to a local database and it works so well except it can't load pictures in it. I get a error that it's type mismatched. How to solve it?

My controller class is below:

```<code>class Person
{
    int id
    String name
    String address
    byte[] profilePic
}

static constraints
{
    profilePic maxSize :204800
}

static mapping
{
    table 'all_users'
    version false
    columns
    {
        id column: 'id'
        name column: 'name'
        address column: 'address'
        profilePic column: 'profilepic'
    }
}
</code>```

答:
Domain Code

```<code>class Person
{
    int id
    String name
    String address
    String profilePic
}

static mapping
{
    table 'all_users'
    version false
    columns
    {
        id column: 'id'
        name column: 'name'
        address column: 'address'
        profilePic column: 'profilepic'
    }
}
</code>```

Controller Code

```<code>def save(){
        def person = new Person(params)
        person.save flush: true, failOnError: true
        redirect action: "show", id: person.id
        def downloadedfile= request.getFile('profilePic')
        String profilePic = "D:/Your Grails Applications/grails-app/assets/images/" + person.name + ".jpg"
        downloadedfile.transferTo(new File(profilePic))
    }
</code>```

View Code

```<code><input type="file" name="profilePic"/>
</code>```

Title: Property xxx is type-mismatched

Body:
I'm trying to build simple CRUD application using Grails. I'm absolutely new to this framework. My CRUD table has few properties, connected to a local database and it works so well except it can't load pictures in it. I get a error that it's type mismatched. How to solve it?

My controller class is below:

class Person
{
    int id
    String name
    String address
    byte[] profilePic
}

static constraints
{
    profilePic maxSize :204800
}

static mapping
{
    table 'all_users'
    version false
    columns
    {
        id column: 'id'
        name column: 'name'
        address column: 'address'
        profilePic column: 'profilepic'
    }
}

Body:
Domain Code

class Person
{
    int id
    String name
    String address
    String profilePic
}

static mapping
{
    table 'all_users'
    version false
    columns
    {
        id column: 'id'
        name column: 'name'
        address column: 'address'
        profilePic column: 'profilepic'
    }
}

Controller Code

def save(){
        def person = new Person(params)
        person.save flush: true, failOnError: true
        redirect action: "show", id: person.id
        def downloadedfile= request.getFile('profilePic')
        String profilePic = "D:/Your Grails Applications/grails-app/assets/images/" + person.name + ".jpg"
        downloadedfile.transferTo(new File(profilePic))
    }

View Code

<input type="file" name="profilePic"/>


问:
lxml objectify does not call constructors for custom element classes
lxml.objectify does not seem to call the constructors for my custom element classes:

```<code>from lxml import objectify, etree

class CustomLookup(etree.CustomElementClassLookup):
    def lookup(self, node_type, document, namespace, name):
        lookupmap = { 'custom' : CustomElement }
        try:
            return lookupmap[name]
        except KeyError:
            return None

class CustomElement(etree.ElementBase):
    def __init__(self):
        print("Made CustomElement")

parser = objectify.makeparser()
parser.set_element_class_lookup(CustomLookup())
root = objectify.parse(fname,parser).getroot()
</code>```

Suppose the file being parsed is

```<code><custom />
</code>```

I would like this to print "Made CustomElement", but it does not. Can I make it call the constructor?

How is it possible for an instance of the CustomElement class to be created without the constructor being called?

```<code>>>> isinstance(root,CustomElement)
True
</code>```

答:
From the lxml docs:

Element initialization

There is one thing to know up front.
  Element classes must not have an
  __init___ or __new__ method. There should not be any internal state
  either, except for the data stored in
  the underlying XML tree. Element
  instances are created and garbage
  collected at need, so there is no way
  to predict when and how often a proxy
  is created for them. Even worse, when
  the __init__ method is called, the
  object is not even initialized yet to
  represent the XML tag, so there is not
  much use in providing an __init__
  method in subclasses.

Most use cases
  will not require any class
  initialisation, so you can content
  yourself with skipping to the next
  section for now. However, if you
  really need to set up your element
  class on instantiation, there is one
  possible way to do so. ElementBase
  classes have an _init() method that
  can be overridden. It can be used to
  modify the XML tree, e.g. to construct
  special children or verify and update
  attributes.

The semantics of _init()
  are as follows:

It is called once on
  Element class instantiation time. That
  is, when a Python representation of
  the element is created by lxml. At
  that time, the element object is
  completely initialized to represent a
  specific XML element within the tree.

The method has complete access to the
  XML tree. Modifications can be done in
  exactly the same way as anywhere else
  in the program.

Python representations
  of elements may be created multiple
  times during the lifetime of an XML
  element in the underlying C tree. The
  _init() code provided by subclasses must take special care by itself that
  multiple executions either are
  harmless or that they are prevented by
  some kind of flag in the XML tree. The
  latter can be achieved by modifying an
  attribute value or by removing or
  adding a specific child node and then
  verifying this before running through
  the init process.

Any exceptions
  raised in _init() will be propagated
  throught the API call that lead to the
  creation of the Element. So be careful
  with the code you write here as its
  exceptions may turn up in various
  unexpected places.

ContentLicense: CC BY-SA 2.5

Body:
lxml.objectify does not seem to call the constructors for my custom element classes:

from lxml import objectify, etree

class CustomLookup(etree.CustomElementClassLookup):
    def lookup(self, node_type, document, namespace, name):
        lookupmap = { 'custom' : CustomElement }
        try:
            return lookupmap[name]
        except KeyError:
            return None

class CustomElement(etree.ElementBase):
    def __init__(self):
        print("Made CustomElement")

parser = objectify.makeparser()
parser.set_element_class_lookup(CustomLookup())
root = objectify.parse(fname,parser).getroot()

Suppose the file being parsed is

<custom />

I would like this to print "Made CustomElement", but it does not. Can I make it call the constructor?

How is it possible for an instance of the CustomElement class to be created without the constructor being called?

>>> isinstance(root,CustomElement)
True


问:
How can I change default python shell version?
I am using Windows 10, and I have python 2.7 and 3.6 installed. I want to open a .py file in IDLE 3.6, but when I try to open it, it opens in 2.7. How can I change the default?</p>

答:
To make the python-2x or python-3x as default python IDLE, you need to change the environment variable, if you define the path for n versions of python, you will be able to use that particular version by typing that version in cmd.

See the superuser answer here for step by step instruction


问:
Mongoose NodeJS Schema with array of ref's
I know there is allot's of answers about it but still I didn't quite get the idea.
I have CourseSchema:

```<code>const CourseSchema = new Schema({
course_name: String,
course_number: {type: String, unique : true },
enrolledStudents:[{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Student' }]
});
</code>```

And a StudentSchema:

```<code>const StudentSchema = new Schema({
first_name: String,
last_name: String,
enrolledCourses:[{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'CourseSchema'
    }]
});
</code>```

I want to reffer enrolledStudents at CourseSchema with a student, and enrolledCourses at StudentSchema with a course.

```<code>router.post('/addStudentToCourse', function (req, res) {
Course.findById(req.params.courseId, function(err, course){
    course.enrolledStudents.push(Student.findById(req.params.studentId, function(error, student){
        student.enrolledCourses.push(course).save();
    })).save();
});
});
</code>```

but when posting I get an error:

TypeError: Cannot read property 'enrolledStudents' of null

Ok so after readying Query-populate I did that:

```<code>router.post('/addStudentToCourse', function (req, res) {

    Course.
    findOne({ _id : req.body.courseId }).
    populate({
        path: 'enrolledStudents'
        , match: { _id : req.body.studentId }
    }).
    exec(function (err, course) {
        if (err) return handleError(err);
        console.log('The course name is %s', course.course_name);
    });
});
</code>```

And when i'm hitting POST on postman I get on the console:

The course name is intro for cs

but it is loading for ever and later on console I get:

POST /courses/addStudentToCourse - - ms - -

答:
You are missing the populate instruction. For example:

see more about it here

```<code>Course.
  findOne({ courseId : req.params.courseId }).
  populate('enrolledStudents').
  exec(function (err, course) {
    if (err) return handleError(err);
    console.log('The course name is %s', course.name);

  });
</code>```

It is working by using the ref field that "knows" how to populate withput using the push syntax.  it is like a foreign key population.

Just call the populate method on the query and an array of documents will be returned in place of the original _ids. you can learn more on the internals of the populate methods in the official docs

Body:
I know there is allot's of answers about it but still I didn't quite get the idea.
I have CourseSchema:

const CourseSchema = new Schema({
course_name: String,
course_number: {type: String, unique : true },
enrolledStudents:[{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Student' }]
});

And a StudentSchema:

const StudentSchema = new Schema({
first_name: String,
last_name: String,
enrolledCourses:[{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'CourseSchema'
    }]
});

I want to reffer enrolledStudents at CourseSchema with a student, and enrolledCourses at StudentSchema with a course.

router.post('/addStudentToCourse', function (req, res) {
Course.findById(req.params.courseId, function(err, course){
    course.enrolledStudents.push(Student.findById(req.params.studentId, function(error, student){
        student.enrolledCourses.push(course).save();
    })).save();
});
});

but when posting I get an error:

TypeError: Cannot read property 'enrolledStudents' of null

Ok so after readying Query-populate I did that:

router.post('/addStudentToCourse', function (req, res) {

    Course.
    findOne({ _id : req.body.courseId }).
    populate({
        path: 'enrolledStudents'
        , match: { _id : req.body.studentId }
    }).
    exec(function (err, course) {
        if (err) return handleError(err);
        console.log('The course name is %s', course.course_name);
    });
});

And when i'm hitting POST on postman I get on the console:

The course name is intro for cs

but it is loading for ever and later on console I get:

POST /courses/addStudentToCourse - - ms - -

Body:
You are missing the populate instruction. For example:

see more about it here

Course.
  findOne({ courseId : req.params.courseId }).
  populate('enrolledStudents').
  exec(function (err, course) {
    if (err) return handleError(err);
    console.log('The course name is %s', course.name);

  });

It is working by using the ref field that "knows" how to populate withput using the push syntax.  it is like a foreign key population.

Just call the populate method on the query and an array of documents will be returned in place of the original _ids. you can learn more on the internals of the populate methods in the official docs


问:
why it float left is not working and these codes
my question is that why float left is not working under these codes
when i use them all the result just display on single div and other 7 where showing under that div at same place so please tell me what is the solution of this prob

```<code><div class="tv_l" style="top:1465px;
left:10px;

position:absolute;

width:1690px;
height:10px;
border-radius:3px/3px;
padding-right:10px;
padding-top:px;
border-left:10px;">

<hr>
</div>

<?php

$link = mysqli_connect("localhost" , "***" ,"***" , "***");
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
 exit();
} else {
    echo "";
}
?>
<?php
$result = mysqli_query($link, "SELECT * FROM **** ORDER BY RAND()
LIMIT 8" )
or die(mysqli_error());
while($row = mysqli_fetch_array( $result )){
?>;

<div class="son_s_p" style="top:1957px;
left:12px;
-webkit-box-shadow:0 3px 8px rgba(0, 0, 0, .25);
position:inherit;
background:white;
width:190px;
height:240px;
border-radius:3px/3px;
padding-right:10px;
padding-top:px;
border-left:10px;
text-align:center;
float:left;

">

 <img src="../lu/music/tumb/<?php echo $row['img']; ?>"style="width:198px; height:148px;"  >
<br>

 <?php echo $row['name']; ?><br><br>

 <div id="son_s_p" style="top:218px;
left:px;

position:absolute;

border-radius:3px/3px;
padding-right:10px;
padding-top:px;
border-left:10px;
text-align:justify;">

 <?php echo $row['time']; ?>    <span class="time&type" style="top;10px;"><?php echo $row['type']; ?></span>

</div>
</div>

<?php
}
?>
</code>```

with using position

without using position data will go top and top do not work

答:
It looks like you are using absolute positioning on your DIVs. Floats cannot work that way. Use this instead:

```<code>position: static;
float: left;
</code>```

If I were you I would first try to get it to work with pure HTML and CSS with some dummy data, before hooking it up to the database.

Here's an example of how you can achieve floating with divs, in contrast to your approach:

https://jsfiddle.net/19zrr99n/

Body:
my question is that why float left is not working under these codes
when i use them all the result just display on single div and other 7 where showing under that div at same place so please tell me what is the solution of this prob

<?php

$link = mysqli_connect("localhost" , "***" ,"***" , "***");
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
 exit();
} else {
    echo "";
}
?>
<?php
$result = mysqli_query($link, "SELECT * FROM **** ORDER BY RAND()
LIMIT 8" )
or die(mysqli_error());
while($row = mysqli_fetch_array( $result )){
?>;

 <img src="../lu/music/tumb/<?php echo $row['img']; ?>"style="width:198px; height:148px;"  >

 <?php echo $row['name']; ?>

 <?php echo $row['time']; ?>    <?php echo $row['type']; ?>

<?php
}
?>

with using position

without using position data will go top and top do not work

Body:
It looks like you are using absolute positioning on your DIVs. Floats cannot work that way. Use this instead:

position: static;
float: left;

If I were you I would first try to get it to work with pure HTML and CSS with some dummy data, before hooking it up to the database.

Here's an example of how you can achieve floating with divs, in contrast to your approach:

https://jsfiddle.net/19zrr99n/


问:
jq: slicing array based on argument
I am trying to slice an array in jq where the end index is passed as an argument from the shell (bash):

```<code>end_index=7
cat obj.json | jq --arg eidx $end_index, '.arr[0:$eidx]'
</code>```

This works as expected when the index is hard-coded

```<code>cat obj.json | jq '.arr[0:7]'
</code>```

but in the example at the top, I get an error message

```<code>jq: error (at <stdin>:0): Start and end indices of an array slice must be numbers
</code>```

I suspect this might be to do with how jq handles variable substitution within the slice operator [:], but none of my attempts to solve the problem, e.g. by enclosing the variable name in curly braces .arr[0:${eidx}], has worked.

答:
When you pass an argument via --arg it is treated as a string, not an int:

--arg name value:

This option passes a value to the jq program as a predefined variable. If you run jq with --arg foo bar, then $foo is available in the program and has the value "bar". Note that value will be treated as a string, so --arg foo 123 will bind $foo to "123".

From the docs (emphases added)

so it would seem that you cannot use --arg to pass a value to be used in a slice.  In this example, you could just use the shell expansion though:

```<code>jq ".arr[0:$end_index]" obj.json
</code>```

the double quotes will have the shell expand your variable before passing it to jq (though other expansions will happen to, so make sure you mean them to happen.

Title: jq: slicing array based on argument

Body:
I am trying to slice an array in jq where the end index is passed as an argument from the shell (bash):

end_index=7
cat obj.json | jq --arg eidx $end_index, '.arr[0:$eidx]'

This works as expected when the index is hard-coded

cat obj.json | jq '.arr[0:7]'

but in the example at the top, I get an error message

jq: error (at <stdin>:0): Start and end indices of an array slice must be numbers

I suspect this might be to do with how jq handles variable substitution within the slice operator [:], but none of my attempts to solve the problem, e.g. by enclosing the variable name in curly braces .arr[0:${eidx}], has worked.

Body:
When you pass an argument via --arg it is treated as a string, not an int:

--arg name value:

This option passes a value to the jq program as a predefined variable. If you run jq with --arg foo bar, then $foo is available in the program and has the value "bar". Note that value will be treated as a string, so --arg foo 123 will bind $foo to "123".

From the docs (emphases added)

so it would seem that you cannot use --arg to pass a value to be used in a slice.  In this example, you could just use the shell expansion though:

jq ".arr[0:$end_index]" obj.json

the double quotes will have the shell expand your variable before passing it to jq (though other expansions will happen to, so make sure you mean them to happen.


问:
Generating jasper report by using method call in grails
I know,By using <g:Jasper> tag I can generate report in grails but I want to save the report generated directly to a folder,mostly using method, iss any of you have any Idea regarding this

答:
I hope you are asking to save jasper generated report to a file. This is easy. You can obtain report content (as byet array) from jasper. Then just save the content to a file. An example is given below-</p>

```<code>JasperService jasperService;

def saveReport(GrailsParameterMap params, Locale locale, List<DataModel> models) {
    // Prepare data
    List searchReportSheet = new ArrayList();
    LinkedHashMap<String, Object> searchSheetMap;
    models.each {
        searchSheetMap = new LinkedHashMap<String, Object>();
        searchSheetMap.put("key", it.keyValue);
        ...............
        ...............
        searchReportSheet.add(searchSheetMap);
    }

    // Call jasper for generate report
    def reportDef = jasperService.buildReportDefinition(params, locale, [data: searchReportSheet]);

    // Save to File
    def content = reportDef.contentStream.toByteArray();
    FileOutputStream fileOuputStream = new FileOutputStream(fileDest)
    fileOuputStream.write(content);
}
</code>```

Body:
I hope you are asking to save jasper generated report to a file. This is easy. You can obtain report content (as byet array) from jasper. Then just save the content to a file. An example is given below-

JasperService jasperService;

def saveReport(GrailsParameterMap params, Locale locale, List<DataModel> models) {
    // Prepare data
    List searchReportSheet = new ArrayList();
    LinkedHashMap<String, Object> searchSheetMap;
    models.each {
        searchSheetMap = new LinkedHashMap<String, Object>();
        searchSheetMap.put("key", it.keyValue);
        ...............
        ...............
        searchReportSheet.add(searchSheetMap);
    }

    // Call jasper for generate report
    def reportDef = jasperService.buildReportDefinition(params, locale, [data: searchReportSheet]);

    // Save to File
    def content = reportDef.contentStream.toByteArray();
    FileOutputStream fileOuputStream = new FileOutputStream(fileDest)
    fileOuputStream.write(content);
}


问:
How can I make Woocommerce Product Gallery Thumbnail Vertical
I am working on a woocommerce site. But can't make the product thumbnails align vertical.
I used woozoom plugin & all the thumbnails are in a 'jcarousel-wrapper'.</p>

答:
Cairo Web Design's solution works for the default installation, but if you are using the WooCommerce Storefront Power Pack extension, you need 3 additional pieces:

To the filters that change the column count, add a priority so they fire later.

Add additional elements to each CSS rule. See CSS below.

Add another css rule that moves the magnification icon to the left side. Otherwise, it covers the first thumbnail after vertically stacking.

Make a plugin or paste this into functions.php and it should work for installations that use the PowerPack Extension.

```<code>/*Based on Solution from Rodolfo Melogli*/

/* --- PHASE 1, make the gallery thumbnail column count 1 (not 3 or 4 )---  */
add_filter( 'woocommerce_product_thumbnails_columns', 'dk_single_gallery_columns', 99 );
function dk_single_gallery_columns() {
 return 1;
}

// Do it for the Storefront theme specifically:
add_filter( 'storefront_product_thumbnail_columns', 'dk_single_gallery_columns_storefront', 99 );
function dk_single_gallery_columns_storefront() {
 return 1;
}

/* --- END PHASE 1 --- */

/* --- PHASE 2 add CSS --- */
add_action('wp_head','dkAddVertGalleryCSS');
function dkAddVertGalleryCSS() {

 echo '<style>
        @media (min-width: 0px) {
        /* Make image width smaller to make room to its right */
        .single-product div.product .images .woocommerce-main-image, .flex-viewport {
            width: 85%;
            float: left;
        }

        /* Make Gallery smaller width and place it beside the image */
        .single-product div.product .images .thumbnails, ol.flex-control-nav.flex-control-thumbs {
            width: 15%;
            float: left;
            margin-top: 40px !important;
        }

        /* Style each Thumbnail with width and margins */
        .single-product div.product .images .thumbnails a.zoom, ol.flex-control-nav.flex-control-thumbs a.zoom {
            width: 90%;
            float: none;
            margin: 0 0 10% 10%;
        }

        /* Move the zoom tool to the left side to accommodate the gallery thumbs (otherwise it covers the first thumbnail */
        .single-product div.product .woocommerce-product-gallery .woocommerce-product-gallery__trigger {
            left: .875em !important;
        }

        }
    </style>';

}

/* --- END PHASE 2 --- */
</code>```

Body:
Cairo Web Design's solution works for the default installation, but if you are using the WooCommerce Storefront Power Pack extension, you need 3 additional pieces:

To the filters that change the column count, add a priority so they fire later.

Add additional elements to each CSS rule. See CSS below.

Add another css rule that moves the magnification icon to the left side. Otherwise, it covers the first thumbnail after vertically stacking.

Make a plugin or paste this into functions.php and it should work for installations that use the PowerPack Extension.

/*Based on Solution from Rodolfo Melogli*/

/* --- PHASE 1, make the gallery thumbnail column count 1 (not 3 or 4 )---  */
add_filter( 'woocommerce_product_thumbnails_columns', 'dk_single_gallery_columns', 99 );
function dk_single_gallery_columns() {
 return 1;
}

// Do it for the Storefront theme specifically:
add_filter( 'storefront_product_thumbnail_columns', 'dk_single_gallery_columns_storefront', 99 );
function dk_single_gallery_columns_storefront() {
 return 1;
}

/* --- END PHASE 1 --- */

/* --- PHASE 2 add CSS --- */
add_action('wp_head','dkAddVertGalleryCSS');
function dkAddVertGalleryCSS() {

 echo '<style>
        @media (min-width: 0px) {
        /* Make image width smaller to make room to its right */
        .single-product div.product .images .woocommerce-main-image, .flex-viewport {
            width: 85%;
            float: left;
        }

        /* Make Gallery smaller width and place it beside the image */
        .single-product div.product .images .thumbnails, ol.flex-control-nav.flex-control-thumbs {
            width: 15%;
            float: left;
            margin-top: 40px !important;
        }

        /* Style each Thumbnail with width and margins */
        .single-product div.product .images .thumbnails a.zoom, ol.flex-control-nav.flex-control-thumbs a.zoom {
            width: 90%;
            float: none;
            margin: 0 0 10% 10%;
        }

        /* Move the zoom tool to the left side to accommodate the gallery thumbs (otherwise it covers the first thumbnail */
        .single-product div.product .woocommerce-product-gallery .woocommerce-product-gallery__trigger {
            left: .875em !important;
        }

        }
    </style>';

}

/* --- END PHASE 2 --- */


问:
django no matching url with parameters
When the login process is complete, I am trying to redirect the user to their profile page, I am passing the user id to the url, although I get the below error.

Reverse for 'index' with arguments '(2,)' not found. 1 pattern(s) tried: [u'profiles/profile/(?P/d+)/$']

login redirect

```<code>return redirect('profiles:index',user.id)
</code>```

url expression

```<code> url(r'^profile/(?P<user_id>/d+)/$', views.index, name='index'),
</code>```

login view

```<code>def Login(request):
    form = LoginForm()
    regForm = SignUpForm()

    if request.method == 'POST':
        user = authenticate(username=request.POST['login_username'], password=request.POST['login_password'])

        if user is not None:
            login(request, user)
            if 'next' in request.POST:
                return redirect(request.POST['next'])
            #print '----------------------'
            #print user.id
            return redirect('profiles:index',user.id)
        else:
            return render(request, 'index.html',{'error':'The username and password didnt match','form':form,'regForm':regForm})
    else:
         return render(request, 'index.html',{'form':form,'regForm':regForm})
</code>```

Main url

```<code>from django.contrib import admin

from authentication import views
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^$', views.index, name="index"),
        url(r'^authentication/', include('authentication.urls')),
        url(r'^emails/', include('emails.urls')),
        url(r'^profiles/', include('profiles.urls')),
    ]
</code>```

答:
using below code:</p>

```<code>url(r'^profiles/', include('profiles.urls', namespace='profile')), # add namespace to your route
</code>```

Title: django no matching url with parameters

Body:
When the login process is complete, I am trying to redirect the user to their profile page, I am passing the user id to the url, although I get the below error.

Reverse for 'index' with arguments '(2,)' not found. 1 pattern(s) tried: [u'profiles/profile/(?P/d+)/$']

login redirect

return redirect('profiles:index',user.id)

url expression

 url(r'^profile/(?P<user_id>/d+)/$', views.index, name='index'),

login view

def Login(request):
    form = LoginForm()
    regForm = SignUpForm()

    if request.method == 'POST':
        user = authenticate(username=request.POST['login_username'], password=request.POST['login_password'])

        if user is not None:
            login(request, user)
            if 'next' in request.POST:
                return redirect(request.POST['next'])
            #print '----------------------'
            #print user.id
            return redirect('profiles:index',user.id)
        else:
            return render(request, 'index.html',{'error':'The username and password didnt match','form':form,'regForm':regForm})
    else:
         return render(request, 'index.html',{'form':form,'regForm':regForm})

Main url

from django.contrib import admin

from authentication import views
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^$', views.index, name="index"),
        url(r'^authentication/', include('authentication.urls')),
        url(r'^emails/', include('emails.urls')),
        url(r'^profiles/', include('profiles.urls')),
    ]

Body:
using below code:

url(r'^profiles/', include('profiles.urls', namespace='profile')), # add namespace to your route


答:
Change your sequence of ' and ":

```<code>echo ('
<SCRIPT LANGUAGE="JavaScript">
   window.alert("User registeration Complete \n User Number: '.$account_number.'\n First Name: '.$first_name.'\n Last Name: '.$last_name.'")
   window.location.href="index.html";
</SCRIPT>
');
</code>```

Title: Echo $ in Javascript

Body:
Change your sequence of ' and ":

echo ('
<SCRIPT LANGUAGE="JavaScript">
   window.alert("User registeration Complete \n User Number: '.$account_number.'\n First Name: '.$first_name.'\n Last Name: '.$last_name.'")
   window.location.href="index.html";
</SCRIPT>
');