问:
Android - Unable to fix the Toolbar in a Collapsing Toolbar layout
I am currently using CollapsingToolbar Layout in the upper portion of my layout. I want to collpase a particular portion (LinearLayout only) and keep the toolbar fixed on the top. I was able to fix the Toolbar position on top in another project and keep it from collapsing. However, for some reason, I am not able to fix the position of my toolbar. Any help will be appreciated. Here is my the XML of the layout:

```<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:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/profile_coordinate_layout"
>

<android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <android.support.design.widget.CollapsingToolbarLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|enterAlways"
        android:layout_gravity="fill_vertical"
        android:fitsSystemWindows="true"
        app:layout_collapseMode="pin"
        app:expandedTitleMarginStart="?actionBarSize"
        app:contentScrim="?colorPrimary"
        >

        <!--|||||||||||||||||||||||||||||||||||||||||||||||||-->
        <!--|||||||||||||||Collection Profile and about||||||-->
        <!--|||||||||||||||||||||||||||||||||||||||||||||||||-->
        <LinearLayout
            android:id="@+id/ll_header"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="?actionBarSize"
            android:orientation="vertical"
            app:layout_collapseMode="pin"
            android:background="@drawable/gradient_feed_bg"
            >
            <include
                layout="@layout/item_collection_profile" />
        </LinearLayout>

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?actionBarSize"
            android:background="@drawable/dark_primary_no_radius"
            app:layout_collapseMode="pin"
            android:elevation="@dimen/margin_4dp"
            >
            <include layout="@layout/action_bar_collection_profile"/>
        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    ></android.support.v4.view.ViewPager>
</android.support.design.widget.CoordinatorLayout>
</code>```

I am loading another fragment on the ViewPager. and I am using the following code to load the toolbar.

```<code>findViewById(R.id.toolbar). setBackgroundResource(R.drawable.dark_primary_no_radius);
setSupportActionBar((android.support.v7.widget.Toolbar)findViewById(R.id.toolbar));
</code>```

And here is UPDATED the result:

As you can see, in the second image, toolbar collapsed on the top. Any help will be highly appreciated.

Thank you.

答:
You need to use the   app:layout_collapseMode="pin" in Toolbar only.
 Remove this from other components like the LinearLayout and CollapsingToolbarLayout.

```<code><android.support.design.widget.AppBarLayout
android:id="@+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<android.support.design.widget.CollapsingToolbarLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
  app:layout_scrollFlags="scroll|exitUntilCollapsed"
    android:layout_gravity="fill_vertical"
    android:fitsSystemWindows="true"
    app:expandedTitleMarginStart="?actionBarSize"
    app:contentScrim="?colorPrimary"
    >

    <!--|||||||||||||||||||||||||||||||||||||||||||||||||-->
    <!--|||||||||||||||Collection Profile and about||||||-->
    <!--|||||||||||||||||||||||||||||||||||||||||||||||||-->
    <LinearLayout
        android:id="@+id/ll_header"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?actionBarSize"
        android:orientation="vertical"
      app:layout_collapseMode="parallax"
        android:background="@drawable/gradient_feed_bg"
        >
        <include
            layout="@layout/item_collection_profile" />
    </LinearLayout>

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        android:background="@drawable/dark_primary_no_radius"
        app:layout_collapseMode="pin"
        android:elevation="@dimen/margin_4dp"
        >
        <include layout="@layout/action_bar_collection_profile"/>
    </android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
</code>```

Body:
I am currently using CollapsingToolbar Layout in the upper portion of my layout. I want to collpase a particular portion (LinearLayout only) and keep the toolbar fixed on the top. I was able to fix the Toolbar position on top in another project and keep it from collapsing. However, for some reason, I am not able to fix the position of my toolbar. Any help will be appreciated. Here is my the XML of the layout:

<?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:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/profile_coordinate_layout"
>

<android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <android.support.design.widget.CollapsingToolbarLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|enterAlways"
        android:layout_gravity="fill_vertical"
        android:fitsSystemWindows="true"
        app:layout_collapseMode="pin"
        app:expandedTitleMarginStart="?actionBarSize"
        app:contentScrim="?colorPrimary"
        >

        <LinearLayout
            android:id="@+id/ll_header"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="?actionBarSize"
            android:orientation="vertical"
            app:layout_collapseMode="pin"
            android:background="@drawable/gradient_feed_bg"
            >
            <include
                layout="@layout/item_collection_profile" />
        </LinearLayout>

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?actionBarSize"
            android:background="@drawable/dark_primary_no_radius"
            app:layout_collapseMode="pin"
            android:elevation="@dimen/margin_4dp"
            >
            <include layout="@layout/action_bar_collection_profile"/>
        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

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

I am loading another fragment on the ViewPager. and I am using the following code to load the toolbar.

findViewById(R.id.toolbar). setBackgroundResource(R.drawable.dark_primary_no_radius);
setSupportActionBar((android.support.v7.widget.Toolbar)findViewById(R.id.toolbar));

And here is UPDATED the result:

As you can see, in the second image, toolbar collapsed on the top. Any help will be highly appreciated.

Thank you.

Body:
You need to use the   app:layout_collapseMode="pin" in Toolbar only.
 Remove this from other components like the LinearLayout and CollapsingToolbarLayout.

<android.support.design.widget.AppBarLayout
android:id="@+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<android.support.design.widget.CollapsingToolbarLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
  app:layout_scrollFlags="scroll|exitUntilCollapsed"
    android:layout_gravity="fill_vertical"
    android:fitsSystemWindows="true"
    app:expandedTitleMarginStart="?actionBarSize"
    app:contentScrim="?colorPrimary"
    >

    <!--|||||||||||||||||||||||||||||||||||||||||||||||||-->
    <!--|||||||||||||||Collection Profile and about||||||-->
    <!--|||||||||||||||||||||||||||||||||||||||||||||||||-->
    <LinearLayout
        android:id="@+id/ll_header"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?actionBarSize"
        android:orientation="vertical"
      app:layout_collapseMode="parallax"
        android:background="@drawable/gradient_feed_bg"
        >
        <include
            layout="@layout/item_collection_profile" />
    </LinearLayout>

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        android:background="@drawable/dark_primary_no_radius"
        app:layout_collapseMode="pin"
        android:elevation="@dimen/margin_4dp"
        >
        <include layout="@layout/action_bar_collection_profile"/>
    </android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>


来源: stackexchange

问:
run a specific line from a csv file depending on user input
How do you run a specific line from a csv file depending on user input.
My code asks the user to input the problem with their phone, if the user inputs water has spilled the keyword water or spilled will be identified and a   solution stored in the csv will be printed. However i stored many solutions there for different keywords.</p>

答:
First re-write your dataset as:

```<code>'turn', 'on', 'off'
put it on charger
'small', 'text'
go on settings.
...
</code>```

Then search for the problem and print the next line.

```<code>problems = input("What is the problem?")

with open("/path/myfile.csv") as myfile:
    file = iter(myfile.readlines())
    for line in file:
        if any(word in line for word in problems.split()):
            print(next(file))
            break
</code>```

ContentLicense: CC BY-SA 3.0

Body:
First re-write your dataset as:

'turn', 'on', 'off'
put it on charger
'small', 'text'
go on settings.
...

Then search for the problem and print the next line.

problems = input("What is the problem?")

with open("/path/myfile.csv") as myfile:
    file = iter(myfile.readlines())
    for line in file:
        if any(word in line for word in problems.split()):
            print(next(file))
            break


问:
Semicolon after closing curly bracket in PHP
I am writing a script to make chunks of a text and send it via SMS. Earlier today i was reviewing some code to split the string in chunks and i saw something I've never seen before. I'm talking about the ";" right after the "}" at the en of the snippet.

Why this colon? i know it works but i don't know if it adds some semantics or some instruction to the interpreter, anybody know what is this for?

```<code>while(1)
{
    $length = (strlen($output)+strlen($words[$i]));
    if($length>$new_max)
    {
        if(count($words) > 0)
        {
            $out_array[] = $output;
            $output = '';

        }
        else
        {
            break;
        }
    }
    else
    {
        $output = $output." ".$words[$i];
        ++$i;
    };
};
</code>```

EDIT: Looks clear that the semicolons as well as multiple semicolons together has no effect over the result, but, do you know if it has some effect to the interpreter? is it doing some task (internally) when it parses it?

答:
Some people use //endwhile or //endif to signal where it came from.  Others put semi-colons after the braces. Both techniques are harmless and just comes down to the developer.

I'd hazard a guess that this programmer doesn't trust their own coding, also is coding in a text-book way without style - the brace positions, the inconsistent spacing, and the while(1) is just ... recommend not doing that.

ContentLicense: CC BY-SA 2.5

Body:
I am writing a script to make chunks of a text and send it via SMS. Earlier today i was reviewing some code to split the string in chunks and i saw something I've never seen before. I'm talking about the ";" right after the "}" at the en of the snippet.

Why this colon? i know it works but i don't know if it adds some semantics or some instruction to the interpreter, anybody know what is this for?

while(1)
{
    $length = (strlen($output)+strlen($words[$i]));
    if($length>$new_max)
    {
        if(count($words) > 0)
        {
            $out_array[] = $output;
            $output = '';

        }
        else
        {
            break;
        }
    }
    else
    {
        $output = $output." ".$words[$i];
        ++$i;
    };
};

EDIT: Looks clear that the semicolons as well as multiple semicolons together has no effect over the result, but, do you know if it has some effect to the interpreter? is it doing some task (internally) when it parses it?


问:
PopUpWindow is getting truncated when used with ListView Item
I have a ListView in which I have to update the item depending on the user status.
User can update the status by clicking on it and PopupWindow is displayed. But when user clicks on last item on ListView then PopupWindow is getting truncated.

Thanks

答:
Answering my question.
I have figured out how android PopupWindow works.
If we don't give width or height for the popupwindow i.e; wrap_content or match_parent the placing is not calculated.
If we give the width or height of popupwindow then PopupWindow checks if it can fit with the given anchor and if Yes it draws below the anchor otherwise it is adjusted.

What I have done is given a width to popupwindow and created.

Problem Solved

Thanks to me ;)


问:
Haskell GADTs - making a type-safe Tensor types for Riemannian geometry
I want to make a type safe implementation of Tensor calculus in Haskell using GADT's, so the rules are:

Tensors are n-dimentional metrices with indecies that can be 'upstairs' or 'downstairs' eg:  - is a Tensor with no indecies (a scalar),  is a Tensor with one 'upstairs' index,  is a tensor with a bunch of 'upstairs' and 'downstairs' indecies

You can ADD tensor of the same type, meaning they have the same indecies signature. the 0th index of the first tensor is of the same type(upstairs or downstairs) as the 0th index of the second tensor and so on...

  ~~~~ OK

  ~~~~ NOT OK

You can MULTIPLY tensors and get bigger tensors, with the indecies concatenated:

So I want that the type-checker of Haskell wouldn't allow me to write code that doesn't follow those rules, It wouldn't compile otherwise.

Here is my attempt using GADTs:

```<code>{-# LANGUAGE GADTs #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE TypeOperators #-}

data Direction = T | X | Y | Z
data Index = Zero | Up Index | Down Index deriving (Eq, Show)

plus :: Index -> Index -> Index
plus Zero x = x
plus (Up x) y = Up (plus x y)
plus (Down x) y = Down (plus x y)

data Tensor a = (a ~ Zero) => Scalar Double |
                forall b. (a ~ Up b) => Cov (Direction -> Tensor b) |
                forall b. (a ~ Down b) => Con (Direction -> Tensor b)

add :: Tensor a -> Tensor a -> Tensor a
add (Scalar x) (Scalar y) = (Scalar (x + y))
add (Cov f) (Cov g) = (Cov (\d -> add (f d) (g d)))
add (Con f) (Con g) = (Con (\d -> add (f d) (g d)))

mul :: Tensor a -> Tensor b -> Tensor (plus a b)
mul (Scalar x) (Scalar y) = (Scalar (x*y))
mul (Scalar x) (Cov f) = (Cov (\d -> mul (Scalar x) (f d)))
mul (Scalar x) (Con f) = (Con (\d -> mul (Scalar x) (f d)))
mul (Cov f) y = (Cov (\d -> mul (f d) y))
mul (Con f) y = (Con (\d -> mul (f d) y))
</code>```

But i'm getting:

```<code>Couldn't match type 'Down with `plus ('Down b1)'
    Expected type: Tensor (plus a b)
      Actual type: Tensor ('Down b)
    Relevant bindings include
      f :: Direction -> Tensor b1 (bound at main.hs:28:10)
      mul :: Tensor a -> Tensor b -> Tensor (plus a b)
        (bound at main.hs:24:1)
    In the expression: (Con (\ d -> mul (f d) y))
    In an equation for `mul':
        mul (Con f) y = (Con (\ d -> mul (f d) y))
</code>```

What is the problem?

答:
plus is just a function on values of type Index

```<code>>>> plus Zero Zero
Zero
>>> plus Zero (Up Zero)
Up Zero
</code>```

so it can't appear in a type signature, as things are. You want to use the 'promoted' type where Zero, Up Zero etc. are types. Then you can write a type function and everything compiles.

```<code>{-# LANGUAGE GADTs #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}

data Direction = T | X | Y | Z
data Index = Zero | Up Index | Down Index deriving (Eq, Show)

-- type function Plus
type family Plus (i :: Index) (j :: Index) :: Index where
  Plus Zero x = x
  Plus (Up x) y  = Up (Plus x y)
  Plus (Down x) y = Down (Plus x y)

-- value fuction plus
plus :: Index -> Index -> Index
plus Zero x = x
plus (Up x) y = Up (plus x y)
plus (Down x) y = Down (plus x y)

data Tensor (a :: Index) where
  Scalar :: Double -> Tensor Zero
  Cov :: (Direction -> Tensor b) -> Tensor (Up b)
  Con :: (Direction -> Tensor b) -> Tensor (Down b)

add :: Tensor a -> Tensor a -> Tensor a
add (Scalar x) (Scalar y) = (Scalar (x + y))
add (Cov f) (Cov g) = (Cov (\d -> add (f d) (g d)))
add (Con f) (Con g) = (Con (\d -> add (f d) (g d)))

mul :: Tensor a -> Tensor b -> Tensor (Plus a b)
mul (Scalar x) (Scalar y) = (Scalar (x*y))
mul (Scalar x) (Cov f) = (Cov (\d -> mul (Scalar x) (f d)))
mul (Scalar x) (Con f) = (Con (\d -> mul (Scalar x) (f d)))
mul (Cov f) y = (Cov (\d -> mul (f d) y))
mul (Con f) y = (Con (\d -> mul (f d) y))
</code>```

There was no ambiguity in Plus but I could have use the disambiguating tick ' to signal that I was dealing with the type level Zero, Up etc.

```<code>type family Plus (i :: Index) (j :: Index) :: Index where
  Plus 'Zero x = x
  Plus ('Up x) y  = 'Up (Plus x y)
  Plus ('Down x) y = 'Down (Plus x y)
</code>```

TypeOperators would permit you to write a + b rather than Plus a b above.

```<code>type family (i :: Index) + (j :: Index) :: Index where
  Zero + x = x
  Up x + y  = Up (x + y)
  Down x + y = Down (x + y)
</code>```

Body:
I want to make a type safe implementation of Tensor calculus in Haskell using GADT's, so the rules are:

Tensors are n-dimentional metrices with indecies that can be 'upstairs' or 'downstairs' eg:  - is a Tensor with no indecies (a scalar),  is a Tensor with one 'upstairs' index,  is a tensor with a bunch of 'upstairs' and 'downstairs' indecies

You can ADD tensor of the same type, meaning they have the same indecies signature. the 0th index of the first tensor is of the same type(upstairs or downstairs) as the 0th index of the second tensor and so on...

  ~~~~ OK

  ~~~~ NOT OK

You can MULTIPLY tensors and get bigger tensors, with the indecies concatenated:

So I want that the type-checker of Haskell wouldn't allow me to write code that doesn't follow those rules, It wouldn't compile otherwise.

Here is my attempt using GADTs:

{-# LANGUAGE GADTs #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE TypeOperators #-}

data Direction = T | X | Y | Z
data Index = Zero | Up Index | Down Index deriving (Eq, Show)

plus :: Index -> Index -> Index
plus Zero x = x
plus (Up x) y = Up (plus x y)
plus (Down x) y = Down (plus x y)

data Tensor a = (a ~ Zero) => Scalar Double |
                forall b. (a ~ Up b) => Cov (Direction -> Tensor b) |
                forall b. (a ~ Down b) => Con (Direction -> Tensor b)

add :: Tensor a -> Tensor a -> Tensor a
add (Scalar x) (Scalar y) = (Scalar (x + y))
add (Cov f) (Cov g) = (Cov (\d -> add (f d) (g d)))
add (Con f) (Con g) = (Con (\d -> add (f d) (g d)))

mul :: Tensor a -> Tensor b -> Tensor (plus a b)
mul (Scalar x) (Scalar y) = (Scalar (x*y))
mul (Scalar x) (Cov f) = (Cov (\d -> mul (Scalar x) (f d)))
mul (Scalar x) (Con f) = (Con (\d -> mul (Scalar x) (f d)))
mul (Cov f) y = (Cov (\d -> mul (f d) y))
mul (Con f) y = (Con (\d -> mul (f d) y))

But i'm getting:

Couldn't match type 'Down with `plus ('Down b1)'
    Expected type: Tensor (plus a b)
      Actual type: Tensor ('Down b)
    Relevant bindings include
      f :: Direction -> Tensor b1 (bound at main.hs:28:10)
      mul :: Tensor a -> Tensor b -> Tensor (plus a b)
        (bound at main.hs:24:1)
    In the expression: (Con (\ d -> mul (f d) y))
    In an equation for `mul':
        mul (Con f) y = (Con (\ d -> mul (f d) y))

What is the problem?

Body:
plus is just a function on values of type Index

>>> plus Zero Zero
Zero
>>> plus Zero (Up Zero)
Up Zero

so it can't appear in a type signature, as things are. You want to use the 'promoted' type where Zero, Up Zero etc. are types. Then you can write a type function and everything compiles.

{-# LANGUAGE GADTs #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}

data Direction = T | X | Y | Z
data Index = Zero | Up Index | Down Index deriving (Eq, Show)

-- type function Plus
type family Plus (i :: Index) (j :: Index) :: Index where
  Plus Zero x = x
  Plus (Up x) y  = Up (Plus x y)
  Plus (Down x) y = Down (Plus x y)

-- value fuction plus
plus :: Index -> Index -> Index
plus Zero x = x
plus (Up x) y = Up (plus x y)
plus (Down x) y = Down (plus x y)

data Tensor (a :: Index) where
  Scalar :: Double -> Tensor Zero
  Cov :: (Direction -> Tensor b) -> Tensor (Up b)
  Con :: (Direction -> Tensor b) -> Tensor (Down b)

add :: Tensor a -> Tensor a -> Tensor a
add (Scalar x) (Scalar y) = (Scalar (x + y))
add (Cov f) (Cov g) = (Cov (\d -> add (f d) (g d)))
add (Con f) (Con g) = (Con (\d -> add (f d) (g d)))

mul :: Tensor a -> Tensor b -> Tensor (Plus a b)
mul (Scalar x) (Scalar y) = (Scalar (x*y))
mul (Scalar x) (Cov f) = (Cov (\d -> mul (Scalar x) (f d)))
mul (Scalar x) (Con f) = (Con (\d -> mul (Scalar x) (f d)))
mul (Cov f) y = (Cov (\d -> mul (f d) y))
mul (Con f) y = (Con (\d -> mul (f d) y))

There was no ambiguity in Plus but I could have use the disambiguating tick ' to signal that I was dealing with the type level Zero, Up etc.

type family Plus (i :: Index) (j :: Index) :: Index where
  Plus 'Zero x = x
  Plus ('Up x) y  = 'Up (Plus x y)
  Plus ('Down x) y = 'Down (Plus x y)

TypeOperators would permit you to write a + b rather than Plus a b above.

type family (i :: Index) + (j :: Index) :: Index where
  Zero + x = x
  Up x + y  = Up (x + y)
  Down x + y = Down (x + y)


问:
How to use d3 v4 with Polymer 2.0 classes?
How can d3.js (v4) be used with a Polymer 2.0 element?

Or how to use a library inside a class that already extends another class?

Trying to create a polymer d3 element to take advantage of polymer's two-way data binding and d3's syntax and functions.  So that the data can be bound to a polymer property and passed to the d3.data() function?

Currently declaring d3 in the class returns undefined.  Does the class need to be instantiated with d3 as a parameter?  It seemed to work with Polymer 1.0.  Another approach was to create a function outside of the class and call that but it's ugly.   It would be nice to just use d3 inside the class.

Or is there a cleaner better way?

eg.

```<code><script src="../../bower_components/d3/d3.js"></script>
var d3 = d3;
debugger; // hits this breakpoint first, and d3 is defined here and below
<dom-module id="my-app">
  <template>
     <svg id="svg"></svg>
  </template>
  <script>
    class MyApp extends Polymer.Element {
      static get is() { return 'my-app'; }
      static get properties() {
        return {
          data: {
            type: Object,
            observer: '_dataChanged'
          }
        }
      }

      ready: {
        var d3 = d3;  // when it breaks here on the above breakpoint this is defined
        debugger;  // when it hits this breakpoint 2nd, d3 is undefined here and outside the class; what happened? how to scope it in?
      }

      _dataChanged(newValue, oldValue): {
        var circle = d3.select(this.$.svg).data(newValue).enter().append(circle);  //d3 undefined(! how to define?)
      }

    }
    window.customElements.define(MyApp.is, MyApp);
  </script>
</dom-module>
</code>```

Body:
How can d3.js (v4) be used with a Polymer 2.0 element?

Or how to use a library inside a class that already extends another class?

Trying to create a polymer d3 element to take advantage of polymer's two-way data binding and d3's syntax and functions.  So that the data can be bound to a polymer property and passed to the d3.data() function?

Currently declaring d3 in the class returns undefined.  Does the class need to be instantiated with d3 as a parameter?  It seemed to work with Polymer 1.0.  Another approach was to create a function outside of the class and call that but it's ugly.   It would be nice to just use d3 inside the class.

Or is there a cleaner better way?

eg.

var d3 = d3;
debugger; // hits this breakpoint first, and d3 is defined here and below
<dom-module id="my-app">
  <template>
     <svg id="svg"></svg>
  </template>

</dom-module>

Body:
window.d3 is the way as you're loading the script in the global scope. You can load any external script asynchronously or synchronously.

To load it synchronously, just place the <script> tag in the <head>.

To load it asynchronously, you can add an load event listener to the <script> tag to do subsequent stuff when the load is completed.


问:
Proxy Error while installing express using npm
When I am trying to install express by npm getting below error.

D:\testing node>npm install express -l

```<code>npm WARN package.json testnode@1.0.0 No description
npm WARN package.json testnode@1.0.0 No repository field.
npm WARN package.json testnode@1.0.0 No README data
npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\
node_modules\\npm\\bin\\npm-cli.js" "install" "express" "-l"
npm ERR! node v4.0.0
npm ERR! npm  v2.14.2
npm ERR! code ECONNREFUSED
npm ERR! errno ECONNREFUSED
npm ERR! syscall connect

npm ERR! Error: connect ECONNREFUSED 103.245.222.162:443
npm ERR!     at Object.exports._errnoException (util.js:837:11)
npm ERR!     at exports._exceptionWithHostPort (util.js:860:20)
npm ERR!     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1060:14)
npm ERR!  { [Error: connect ECONNREFUSED 103.245.222.162:443]
npm ERR!   code: 'ECONNREFUSED',
npm ERR!   errno: 'ECONNREFUSED',
npm ERR!   syscall: 'connect',
npm ERR!   address: '103.245.222.162',
npm ERR!   port: 443,
npm ERR!   parent: 'testnode' }
npm ERR!
npm ERR! If you are behind a proxy, please make sure that the
npm ERR! 'proxy' config is set properly.  See: 'npm help config'

npm ERR! Please include the following file with any support request:
npm ERR!     D:\testing node\npm-debug.log
</code>```

Although I have removed proxy too but even after that getting the same
Tried running npm as administrative

答:
Change your proxy setting using
set http_proxy=http://hostname:port</p>

Body:
When I am trying to install express by npm getting below error.

D:\testing node>npm install express -l

npm WARN package.json testnode@1.0.0 No description
npm WARN package.json testnode@1.0.0 No repository field.
npm WARN package.json testnode@1.0.0 No README data
npm ERR! Windows_NT 6.1.7601
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\
node_modules\\npm\\bin\\npm-cli.js" "install" "express" "-l"
npm ERR! node v4.0.0
npm ERR! npm  v2.14.2
npm ERR! code ECONNREFUSED
npm ERR! errno ECONNREFUSED
npm ERR! syscall connect

npm ERR! Error: connect ECONNREFUSED 103.245.222.162:443
npm ERR!     at Object.exports._errnoException (util.js:837:11)
npm ERR!     at exports._exceptionWithHostPort (util.js:860:20)
npm ERR!     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1060:14)
npm ERR!  { [Error: connect ECONNREFUSED 103.245.222.162:443]
npm ERR!   code: 'ECONNREFUSED',
npm ERR!   errno: 'ECONNREFUSED',
npm ERR!   syscall: 'connect',
npm ERR!   address: '103.245.222.162',
npm ERR!   port: 443,
npm ERR!   parent: 'testnode' }
npm ERR!
npm ERR! If you are behind a proxy, please make sure that the
npm ERR! 'proxy' config is set properly.  See: 'npm help config'

npm ERR! Please include the following file with any support request:
npm ERR!     D:\testing node\npm-debug.log

Although I have removed proxy too but even after that getting the same
Tried running npm as administrative


问:
Bootstrap table inside other table | Fix the height of table
I have little problem in my web page. I use bootstrap 4 and in table box I set  inside other table as in the picture below. How to make the height of table inside the same as the hieght of the box (td)?

html:

```<code><table class="table table-bordered">
   <tbody>
      <tr>
         <td>REVERT</td>
         <td>
            <table class="table" style="height: 100%">
               <tbody>
                  <tr>
                     <td>Name</td>
                     <td>LONG TEXT</td>
                  </tr>
               </tbody>
            </table>
         </td>
      </tr>
   </tbody>
</table>
</code>```

Browser:

答:
This question has been asked many times before, but I'll answer it specifically for your scenario. It's not an issue of removing padding/margins.

In order to get a 100% height table, it's container must also be 100% height. So in this case set the containing td to height: 100%...

Demo on Codeply

```<code>       <td>REVERT</td>
       <td style="padding:0;height: 100%;">
           <table class="table" style="height: 100%">
                <tbody>
                     <tr>
                        <td>Name</td>
                        <td>LONG TEXT</td>
                     </tr>
                </tbody>
           </table>
       </td>
</code>```

Body:
I have little problem in my web page. I use bootstrap 4 and in table box I set  inside other table as in the picture below. How to make the height of table inside the same as the hieght of the box (td)?

html:

         REVERT

                     Name
                     LONG TEXT

Browser:

Body:
This question has been asked many times before, but I'll answer it specifically for your scenario. It's not an issue of removing padding/margins.

In order to get a 100% height table, it's container must also be 100% height. So in this case set the containing td to height: 100%...

Demo on Codeply

       <td>REVERT</td>
       <td style="padding:0;height: 100%;">
           <table class="table" style="height: 100%">
                <tbody>
                     <tr>
                        <td>Name</td>
                        <td>LONG TEXT</td>
                     </tr>
                </tbody>
           </table>
       </td>


问:
Circular Queue Array
Hi everyone i am trying to implement a circular array, but something is not exactly right. I am not sure if is in the add method or display. When you run the debugger, the numbers are there but i cant get them in order. Please could you have a look and give me a feedback. Thank you.

```<code>public static void main (String[] args)
{
    Scanner input = new Scanner (System.in);
    Queue q1 = new Queue();
    int choice = 0;

    do
    {
        System.out.println ("Menu:");
        System.out.println ("1: Add");
        System.out.println ("2: Remove");
        System.out.println ("3: Display");
        System.out.println ("4: Exit");

        System.out.print ("\nChoice: ");
        choice = input.nextInt ();

        switch ( choice )
        {
            case 1:
                System.out.print ("\nEnter a number: ");
                int num = input.nextInt ();
                q1.add (num);
                break;
            case 2:
                q1.remove ();
                break;
            case 3:
                q1.display ();
                break;
            case 4:
                System.out.println ("Good Bye");
                break;
            default:
                System.out.println ("Wrong choice!");
                break;
        }

    } while ( choice != 4 );

}
</code>```

}

public class Queue
{

```<code>private final int SIZE;
private int first;
private int last;
private int[] q;

public Queue ()
{
    SIZE = 5;
    q = new int[ SIZE ];
    first = 0;
    last = 0;
}

public boolean isFull ()
{
    return last == SIZE;
}

public boolean isEmpty ()
{
    return last == first;
}

public void add (int x)
{
    if (  ! isFull () )
    {
        q[ ( first + last ) % q.length ] = x;
        last ++;
    } else
    {
        System.out.println ("\nThe queue is full!");
    }
}

int remove ()
{
    int x = 0;
    if (  ! isEmpty () )
    {
        x = q[ first ];
        first = ( first + 1 ) % q.length;
        last --;
    } else
    {
        System.out.println ("The queue is empy");
    }
    return x;

}

public void display ()
{
    if (  ! isEmpty () )
    {
        for ( int i = first; i < SIZE; i ++ )
        {
            System.out.println (q[ i ]);
        }

    } else
    {
        System.out.println ("The queue is emptry");
    }
}
</code>```

答: add() should only update last. remove() should only update first. add() needs to prevent the queue from going full, or the code needs to use a count of elements in the queue to check if the queue is full (versus empty, since last == first if either empty or full), in which case add() needs to prevent queue overflow. add() could return a code to indicate if add() was successful (no overflow) or if it failed (overflow). add() could optionally return a third code value to indicate that the queue was previously empty, in case some special action is needed when a queue goes from empty to non-empty.

Title: Circular Queue Array

Body:
Hi everyone i am trying to implement a circular array, but something is not exactly right. I am not sure if is in the add method or display. When you run the debugger, the numbers are there but i cant get them in order. Please could you have a look and give me a feedback. Thank you.

public static void main (String[] args)
{
    Scanner input = new Scanner (System.in);
    Queue q1 = new Queue();
    int choice = 0;

    do
    {
        System.out.println ("Menu:");
        System.out.println ("1: Add");
        System.out.println ("2: Remove");
        System.out.println ("3: Display");
        System.out.println ("4: Exit");

        System.out.print ("\nChoice: ");
        choice = input.nextInt ();

        switch ( choice )
        {
            case 1:
                System.out.print ("\nEnter a number: ");
                int num = input.nextInt ();
                q1.add (num);
                break;
            case 2:
                q1.remove ();
                break;
            case 3:
                q1.display ();
                break;
            case 4:
                System.out.println ("Good Bye");
                break;
            default:
                System.out.println ("Wrong choice!");
                break;
        }

    } while ( choice != 4 );

}

}

public class Queue
{

private final int SIZE;
private int first;
private int last;
private int[] q;

public Queue ()
{
    SIZE = 5;
    q = new int[ SIZE ];
    first = 0;
    last = 0;
}

public boolean isFull ()
{
    return last == SIZE;
}

public boolean isEmpty ()
{
    return last == first;
}

public void add (int x)
{
    if (  ! isFull () )
    {
        q[ ( first + last ) % q.length ] = x;
        last ++;
    } else
    {
        System.out.println ("\nThe queue is full!");
    }
}

int remove ()
{
    int x = 0;
    if (  ! isEmpty () )
    {
        x = q[ first ];
        first = ( first + 1 ) % q.length;
        last --;
    } else
    {
        System.out.println ("The queue is empy");
    }
    return x;

}

public void display ()
{
    if (  ! isEmpty () )
    {
        for ( int i = first; i < SIZE; i ++ )
        {
            System.out.println (q[ i ]);
        }

    } else
    {
        System.out.println ("The queue is emptry");
    }
}


问:
Custom factorial function not working as expected
Here is a simple factorial calculator. I have called the function factorial with three different arguments to test it. For some reason, the function is not returning the expected values:

```<code>#include <iostream>
using namespace std;

int factorial(int a) {
  int result = 1;
  for (int i = 0; i < a; i++) {
    result *= result + 1;
  }
  return result;
}

int main() {
  cout << factorial(4) << endl; // returns 1806, expected 24
  cout << factorial(5) << endl; // returns 3263442, expected 120
  cout << factorial(6) << endl; // returns -1461943274, expected 720
  return 0;
}
</code>```

答:
The problem is in your factorial function, you are adding 1 why ? You should start your loop from i=1 to i<=a and multiply i instead of +1,

By mathematics definition Factorial of n = n*(n-1)*(n-2)...3.2.1

You can modify your code like this

```<code>int factorial(int a) {
    int result = 1;
    for (int i = 1; i <=a; i++) {
        result = result * i;
    }
    return result;
}
</code>```

Or you can use recursive function

```<code>int factorial(int a) {
    if (a == 1)
        return 1;
    else
        return a * factorial(a - 1);
}
</code>```

Body:
Here is a simple factorial calculator. I have called the function factorial with three different arguments to test it. For some reason, the function is not returning the expected values:

#include <iostream>
using namespace std;

int factorial(int a) {
  int result = 1;
  for (int i = 0; i < a; i++) {
    result *= result + 1;
  }
  return result;
}

int main() {
  cout << factorial(4) << endl; // returns 1806, expected 24
  cout << factorial(5) << endl; // returns 3263442, expected 120
  cout << factorial(6) << endl; // returns -1461943274, expected 720
  return 0;
}

Body:
The problem is in your factorial function, you are adding 1 why ? You should start your loop from i=1 to i<=a and multiply i instead of +1,

By mathematics definition Factorial of n = n*(n-1)*(n-2)...3.2.1

You can modify your code like this

int factorial(int a) {
    int result = 1;
    for (int i = 1; i <=a; i++) {
        result = result * i;
    }
    return result;
}

Or you can use recursive function

int factorial(int a) {
    if (a == 1)
        return 1;
    else
        return a * factorial(a - 1);
}


问:
How can i know what is the release of osCommerce?
how can i know what is the release of osCommerce? is the release written in any file of the package?

Regards

Javi

答:
in

```<code>includes/application_top.php
</code>```

there should be something like:

```<code>// define the project version
  define('PROJECT_VERSION', 'osCommerce 2.2-MS2');
</code>```

Body:
in

includes/application_top.php

there should be something like:

// define the project version
  define('PROJECT_VERSION', 'osCommerce 2.2-MS2');


问:
TableView binding and Object HAS-A relation
I have the following classes

```<code>Class Car{
  private StringProperty type;

  //+setters and getters
}

Class Person{
  private Car car;

  private StringProperty name;

  //+setters and getters
}
</code>```

And I have tableView TableView<Person>. In this tableView I have two columns - Person Name and Car Type.

This is how I build column for Person Name

```<code>TableColumn<Person,String> column=new TableColumn("Person Name");
column.setCellValueFactory(data->data.getValue().getName());
</code>```

You can see, there can be two changes with Car in class Person. First of all a person can get another car, and secondly car can change its type.

How can I build column Car Type and bind to "these two changes"

答:
First of all you should add ObjectProperty<Car> to your Person class to make car Observable. Then your binding will look like following:

```<code>carTypeName.setCellValueFactory(data ->
                Bindings.createStringBinding(
                        () -> data.getValue().getCar().get().getType().get(),
                                data.getValue().getCar(),
                                data.getValue().getCar().get().getType()));
</code>```

This means that your cell will display new Car.type value each time either Person.car or Person.car.type is changed. (If Person.car can be null you might need to add additional null checks.)

Body:
I have the following classes

Class Car{
  private StringProperty type;

  //+setters and getters
}

Class Person{
  private Car car;

  private StringProperty name;

  //+setters and getters
}

And I have tableView TableView<Person>. In this tableView I have two columns - Person Name and Car Type.

This is how I build column for Person Name

TableColumn<Person,String> column=new TableColumn("Person Name");
column.setCellValueFactory(data->data.getValue().getName());

You can see, there can be two changes with Car in class Person. First of all a person can get another car, and secondly car can change its type.

How can I build column Car Type and bind to "these two changes"

Body:
First of all you should add ObjectProperty<Car> to your Person class to make car Observable. Then your binding will look like following:

carTypeName.setCellValueFactory(data ->
                Bindings.createStringBinding(
                        () -> data.getValue().getCar().get().getType().get(),
                                data.getValue().getCar(),
                                data.getValue().getCar().get().getType()));

This means that your cell will display new Car.type value each time either Person.car or Person.car.type is changed. (If Person.car can be null you might need to add additional null checks.)


问:
Jquery scrollTop does not work with $(Window).animate()
I know a similar question has been asked and answered here - jQuery .scrollTop(); + animation.

I was trying to understand why if I try this-

```<code> $(window).animate({scrollTop:300},500)
</code>```

The page does not scroll.

However, if I try the below one as suggested in an earlier SO question, it works fine -

```<code> $('html,body').animate({scrollTop:300},500).
</code>```

What's more confusing is, if I just try the following (without any animation), it works fine -

```<code>$(window).scrollTop(300);
</code>```

Can someone please help to understand what I am getting wrong here?

答: Because the scrollTop property works with(scrolls) the elements inside the window(html, body etc.) and not the window itself.</p>

Body:
I know a similar question has been asked and answered here - jQuery .scrollTop(); + animation.

I was trying to understand why if I try this-

 $(window).animate({scrollTop:300},500)

The page does not scroll.

However, if I try the below one as suggested in an earlier SO question, it works fine -

 $('html,body').animate({scrollTop:300},500).

What's more confusing is, if I just try the following (without any animation), it works fine -

$(window).scrollTop(300);

Can someone please help to understand what I am getting wrong here?


问:
why is my for loop executing an extra time in UNIX environment?
I wrote a code that worked perfectly fine, however, once I externalized the code and transferred the code to a UNIX environment like Puttty or the MAC system console, I get an anomaly. I have a for loop that executes one extra time and it's weird. Here is a picture of the report

and sorry, I'm not too sure how I can enter my code in here because my #define's become overly large when I look at the preview.

This is a link to all the source files if it is necessary to view all of them

the maxEmployee.h header file only contains #define MAXEMP 40

This is the main function:

```<code>#include <stdio.h>
#include "maxEmployee.h"

extern void InitializeAccumulators(float* totDefr, float *totPayRate, float *totRegHrs, float *totOvtHrs, float *totGross, float *totFed, float *totSt, float *totSSI, float *totNet); //3.1 Prototype

extern void InputEmployeeData(char ln[][10+1], char fn[][10+1], float hr[], float pRate[], float defr[], int i); //3.2 Prototype

extern void CalculateGross(float hr[], float pRate[], float reghr[], float ovthr[], float gross[], int i); //3.3 Prototype

extern void calculateTaxes(float gross[], float defr[], float ft[], float st[], float ssit[], int i); //3.4 Prototype

extern void CalculateNetPay(float gross[], float defr[], float ft[], float st[], float ssit[], float netPay[], int i); //3.5 Prototype

extern void CalculateTotAvg(float pRate[], float reghr[], float ovthr[], float gross[], float ft[], float st[], float ssit[], float netPay[], float defr[], int i, float *totDefr, float *totPayRate, float *totRegHrs, float *totOvtHrs, float *totGross, float *totFed, float *totSt, float *totSSIT, float *totNet,
    float *avgDefr, float *avgPayRate, float *avgRegHrs, float *avgOvtHrs, float *avgGross, float *avgFed, float *avgSt, float *avgSSIT, float *avgNet); //3.6 Prototype

extern void PrintReportSummary(char fn[][10+1], char ln[][10+1], float pRate[], float reghr[], float ovthr[], float gross[], float ft[], float st[], float ssit[], float netPay[], float defr[], int i, float totDefr, float totPayRate, float totRegHrs, float totOvtHrs, float totGross, float totFed, float totSt, float totSSIT, float totNet,
    float avgDefr, float avgPayRate, float avgRegHrs, float avgOvtHrs, float avgGross, float avgFed, float avgSt, float avgSSIT, float avgNet); //3.7 Prototype

int main(void)

{ // 3.0
    char ln[MAXEMP][10 + 1], fn[MAXEMP][10 + 1]; //last name and first name
    float hr[MAXEMP], pRate[MAXEMP], defr[MAXEMP], gross[MAXEMP], reghr[MAXEMP], ovthr[MAXEMP]; // hour, payrate, deferred, gross, regular hour, over time hours
    float ft[MAXEMP], st[MAXEMP], ssit[MAXEMP]; //calculate taxes
    float netPay[MAXEMP];

    float totDefr, totPayRate, totRegHrs, totOvtHrs, totGross, totFed, totSt, totSSIT, totNet;
    float avgDefr, avgPayRate, avgRegHrs, avgOvtHrs, avgGross, avgFed, avgSt, avgSSIT, avgNet;
    int i, yesno = 1;

    InitializeAccumulators(&totDefr, &totPayRate, &totRegHrs, &totOvtHrs, &totGross,
        &totFed, &totSt, &totSSIT, &totNet); //call 3.1
    for (i = 0; i < MAXEMP && yesno == 1; i++)
    {
        InputEmployeeData(ln, fn, hr, pRate, defr, i); //call 3.2
        CalculateGross(hr, pRate, reghr, ovthr, gross, i); //call 3.3
        calculateTaxes(gross, defr, ft, st, ssit, i); //call 3.4
        CalculateNetPay(gross, defr, ft, st, ssit, netPay, i); //call 3.5
        printf("Do you have another employee you wish to enter? (1 = Yes, 0 = No) ");
        scanf("%d", &yesno);
    }
    CalculateTotAvg(pRate, reghr, ovthr, gross, ft, st, ssit, netPay, defr, i, &totDefr, &totPayRate, &totRegHrs, &totOvtHrs, &totGross, &totFed, &totSt, &totSSIT, &totNet, &avgDefr, &avgPayRate, &avgRegHrs, &avgOvtHrs, &avgGross, &avgFed, &avgSt, &avgSSIT, &avgNet); //call 3.6

    PrintReportSummary(fn, ln, pRate, reghr, ovthr, gross, ft, st, ssit, netPay, defr, i, totDefr, totPayRate, totRegHrs, totOvtHrs, totGross, totFed, totSt, totSSIT, totNet, //call 3.7
        avgDefr, avgPayRate, avgRegHrs, avgOvtHrs, avgGross, avgFed, avgSt, avgSSIT, avgNet);

    fflush(stdin), getchar(); // hold screen

    return 0;

}
</code>```

This is the PrintReportSummary sub function:

```<code>> #include <stdio.h>
> #include <string.h>
> #include "maxEmployee.h"
>
> #define REPORTHEADERFORMAT "\n%-20s%16.2f%18.2f%18.2f%18.2f%18.2f%18.2f\n%54.2f%36.2f%18.2f\n"
> #define REPORTHEADERTOT "\nTotals%30.2f%18.2f%18.2f%18.2f%18.2f%18.2f\n%54.2f%36.2f%18.2f\n"
> #define REPORTHEADERAVG "\nAverages%28.2f%18.2f%18.2f%18.2f%18.2f%18.2f\n%54.2f%36.2f%18.2f\n"
>
> void PrintReportSummary(char fn[][10+1], char ln[][10+1], float
> pRate[], float reghr[], float ovthr[], float gross[], float ft[],
> float st[], float ssit[], float netPay[], float defr[], int i, float
> totDefr, float totPayRate, float totRegHrs, float totOvtHrs, float
> totGross, float totFed, float totSt, float totSSIT, float totNet,
>   float avgDefr, float avgPayRate, float avgRegHrs, float avgOvtHrs,
> float avgGross, float avgFed, float avgSt, float avgSSIT, float
> avgNet); //3.7 Prototype
>
> void PrintReportSummary(char fn[][10+1], char ln[][10+1], float
> pRate[], float reghr[], float ovthr[], float gross[], float ft[],
> float st[], float ssit[], float netPay[], float defr[], int i, float
> totDefr, float totPayRate, float totRegHrs, float totOvtHrs, float
> totGross, float totFed, float totSt, float totSSIT, float totNet,
>     float avgDefr, float avgPayRate, float avgRegHrs, float avgOvtHrs, float avgGross, float avgFed, float avgSt, float avgSSIT, float
> avgNet) //3.7 {
>
>   char fullname[MAXEMP][20+1];
>
>   printf("Employee            Pay     Reg Hrs       Gross          Fed        SSI
> Net\n");  printf("Name                Rate        Ovt Hrs       Pay            State
> Defr            Pay\n");
>     printf("==============================================================================================================================");
>
>   for (int k = 0; k <= i; k++)    {   strcpy (fullname[k], ln[k]);
>   strcat(fullname[k], ", ");  strcat(fullname[k], fn[k]);
>
>   printf(REPORTHEADERFORMAT, fullname[k], pRate[k], reghr[k], gross[k],
> ft[k], ssit[k], netPay[k], ovthr[k], st[k], defr[k]);     }
>   printf(REPORTHEADERTOT, totPayRate, totRegHrs, totGross, totFed,
> totSSIT, totNet, totOvtHrs, totSt, totDefr);  printf(REPORTHEADERAVG,
> avgPayRate, avgRegHrs, avgGross, avgFed, avgSSIT, avgNet, avgOvtHrs,
> avgSt, avgDefr); }
</code>```

This is my make file:

```<code>dataReport.exe: main.o InitializeAccumulators.o InputEmployeeData.o CalculateGross.o calculateTaxes.o CalculateNetPay.o CalculateTotAvg.o PrintReportSummary.o
    g++ main.o InitializeAccumulators.o InputEmployeeData.o CalculateGross.o calculateTaxes.o CalculateNetPay.o CalculateTotAvg.o PrintReportSummary.o -o dataReport.exe

main.o: main.cpp maxEmployee.h
    g++ -c main.cpp -o main.o

InitializeAccumulators.o: InitializeAccumulators.cpp
    g++ -c InitializeAccumulators.cpp -o InitializeAccumulators.o

InputEmployeeData.o: InputEmployeeData.cpp
    g++ -c InputEmployeeData.cpp -o InputEmployeeData.o

CalculateGross.o: CalculateGross.cpp
    g++ -c CalculateGross.cpp -o CalculateGross.o

calculateTaxes.o: calculateTaxes.cpp taxrates.h
    g++ -c calculateTaxes.cpp -o calculateTaxes.o

CalculateNetPay.o: CalculateNetPay.cpp
    g++ -c CalculateNetPay.cpp -o CalculateNetPay.o

CalculateTotAvg.o: CalculateTotAvg.cpp
    g++ -c CalculateTotAvg.cpp -o CalculateTotAvg.o

PrintReportSummary.o: PrintReportSummary.cpp maxEmployee.h
    g++ -c PrintReportSummary.cpp -o PrintReportSummary.o

clean:
    rm *.o dataReport.exe
</code>```

So then my question is how do I fix this? I've been stuck on this for a couple days now...

答:
In main you loop 1 time, so the variable "i" has a value of 1 at the end of the for loop.

In PrintReportSummary you use the following loop:

```<code>for (int k = 0; k <= i; k++)
</code>```

Substitute 1 for i gives:

```<code>for (int k = 0; k <= 1; k++)
</code>```

So the loop body is executed 2 times. The behaviour should be the same in windows so you might re-test that :)
Furthermore, if you input 40 records, or you set MAXEMP to 1 and input 1 record, the program will crash or show undefined behaviour at the second for loop, cause it would access elements out of bounds from your arrays.

Solution: change <= to <.

To clean up the code a little you could use structs instead of that many function arguments :)

Body:
I wrote a code that worked perfectly fine, however, once I externalized the code and transferred the code to a UNIX environment like Puttty or the MAC system console, I get an anomaly. I have a for loop that executes one extra time and it's weird. Here is a picture of the report

and sorry, I'm not too sure how I can enter my code in here because my #define's become overly large when I look at the preview.

This is a link to all the source files if it is necessary to view all of them

the maxEmployee.h header file only contains #define MAXEMP 40

This is the main function:

#include <stdio.h>
#include "maxEmployee.h"

extern void InitializeAccumulators(float* totDefr, float *totPayRate, float *totRegHrs, float *totOvtHrs, float *totGross, float *totFed, float *totSt, float *totSSI, float *totNet); //3.1 Prototype

extern void InputEmployeeData(char ln[][10+1], char fn[][10+1], float hr[], float pRate[], float defr[], int i); //3.2 Prototype

extern void CalculateGross(float hr[], float pRate[], float reghr[], float ovthr[], float gross[], int i); //3.3 Prototype

extern void calculateTaxes(float gross[], float defr[], float ft[], float st[], float ssit[], int i); //3.4 Prototype

extern void CalculateNetPay(float gross[], float defr[], float ft[], float st[], float ssit[], float netPay[], int i); //3.5 Prototype

extern void CalculateTotAvg(float pRate[], float reghr[], float ovthr[], float gross[], float ft[], float st[], float ssit[], float netPay[], float defr[], int i, float *totDefr, float *totPayRate, float *totRegHrs, float *totOvtHrs, float *totGross, float *totFed, float *totSt, float *totSSIT, float *totNet,
    float *avgDefr, float *avgPayRate, float *avgRegHrs, float *avgOvtHrs, float *avgGross, float *avgFed, float *avgSt, float *avgSSIT, float *avgNet); //3.6 Prototype

extern void PrintReportSummary(char fn[][10+1], char ln[][10+1], float pRate[], float reghr[], float ovthr[], float gross[], float ft[], float st[], float ssit[], float netPay[], float defr[], int i, float totDefr, float totPayRate, float totRegHrs, float totOvtHrs, float totGross, float totFed, float totSt, float totSSIT, float totNet,
    float avgDefr, float avgPayRate, float avgRegHrs, float avgOvtHrs, float avgGross, float avgFed, float avgSt, float avgSSIT, float avgNet); //3.7 Prototype

int main(void)

{ // 3.0
    char ln[MAXEMP][10 + 1], fn[MAXEMP][10 + 1]; //last name and first name
    float hr[MAXEMP], pRate[MAXEMP], defr[MAXEMP], gross[MAXEMP], reghr[MAXEMP], ovthr[MAXEMP]; // hour, payrate, deferred, gross, regular hour, over time hours
    float ft[MAXEMP], st[MAXEMP], ssit[MAXEMP]; //calculate taxes
    float netPay[MAXEMP];

    float totDefr, totPayRate, totRegHrs, totOvtHrs, totGross, totFed, totSt, totSSIT, totNet;
    float avgDefr, avgPayRate, avgRegHrs, avgOvtHrs, avgGross, avgFed, avgSt, avgSSIT, avgNet;
    int i, yesno = 1;

    InitializeAccumulators(&totDefr, &totPayRate, &totRegHrs, &totOvtHrs, &totGross,
        &totFed, &totSt, &totSSIT, &totNet); //call 3.1
    for (i = 0; i < MAXEMP && yesno == 1; i++)
    {
        InputEmployeeData(ln, fn, hr, pRate, defr, i); //call 3.2
        CalculateGross(hr, pRate, reghr, ovthr, gross, i); //call 3.3
        calculateTaxes(gross, defr, ft, st, ssit, i); //call 3.4
        CalculateNetPay(gross, defr, ft, st, ssit, netPay, i); //call 3.5
        printf("Do you have another employee you wish to enter? (1 = Yes, 0 = No) ");
        scanf("%d", &yesno);
    }
    CalculateTotAvg(pRate, reghr, ovthr, gross, ft, st, ssit, netPay, defr, i, &totDefr, &totPayRate, &totRegHrs, &totOvtHrs, &totGross, &totFed, &totSt, &totSSIT, &totNet, &avgDefr, &avgPayRate, &avgRegHrs, &avgOvtHrs, &avgGross, &avgFed, &avgSt, &avgSSIT, &avgNet); //call 3.6

    PrintReportSummary(fn, ln, pRate, reghr, ovthr, gross, ft, st, ssit, netPay, defr, i, totDefr, totPayRate, totRegHrs, totOvtHrs, totGross, totFed, totSt, totSSIT, totNet, //call 3.7
        avgDefr, avgPayRate, avgRegHrs, avgOvtHrs, avgGross, avgFed, avgSt, avgSSIT, avgNet);

    fflush(stdin), getchar(); // hold screen

    return 0;

}

This is the PrintReportSummary sub function:

> #include <stdio.h>
> #include <string.h>
> #include "maxEmployee.h"
>
> #define REPORTHEADERFORMAT "\n%-20s%16.2f%18.2f%18.2f%18.2f%18.2f%18.2f\n%54.2f%36.2f%18.2f\n"
> #define REPORTHEADERTOT "\nTotals%30.2f%18.2f%18.2f%18.2f%18.2f%18.2f\n%54.2f%36.2f%18.2f\n"
> #define REPORTHEADERAVG "\nAverages%28.2f%18.2f%18.2f%18.2f%18.2f%18.2f\n%54.2f%36.2f%18.2f\n"
>
> void PrintReportSummary(char fn[][10+1], char ln[][10+1], float
> pRate[], float reghr[], float ovthr[], float gross[], float ft[],
> float st[], float ssit[], float netPay[], float defr[], int i, float
> totDefr, float totPayRate, float totRegHrs, float totOvtHrs, float
> totGross, float totFed, float totSt, float totSSIT, float totNet,
>   float avgDefr, float avgPayRate, float avgRegHrs, float avgOvtHrs,
> float avgGross, float avgFed, float avgSt, float avgSSIT, float
> avgNet); //3.7 Prototype
>
> void PrintReportSummary(char fn[][10+1], char ln[][10+1], float
> pRate[], float reghr[], float ovthr[], float gross[], float ft[],
> float st[], float ssit[], float netPay[], float defr[], int i, float
> totDefr, float totPayRate, float totRegHrs, float totOvtHrs, float
> totGross, float totFed, float totSt, float totSSIT, float totNet,
>     float avgDefr, float avgPayRate, float avgRegHrs, float avgOvtHrs, float avgGross, float avgFed, float avgSt, float avgSSIT, float
> avgNet) //3.7 {
>
>   char fullname[MAXEMP][20+1];
>
>   printf("Employee            Pay     Reg Hrs       Gross          Fed        SSI
> Net\n");  printf("Name                Rate        Ovt Hrs       Pay            State
> Defr            Pay\n");
>     printf("==============================================================================================================================");
>
>   for (int k = 0; k <= i; k++)    {   strcpy (fullname[k], ln[k]);
>   strcat(fullname[k], ", ");  strcat(fullname[k], fn[k]);
>
>   printf(REPORTHEADERFORMAT, fullname[k], pRate[k], reghr[k], gross[k],
> ft[k], ssit[k], netPay[k], ovthr[k], st[k], defr[k]);     }
>   printf(REPORTHEADERTOT, totPayRate, totRegHrs, totGross, totFed,
> totSSIT, totNet, totOvtHrs, totSt, totDefr);  printf(REPORTHEADERAVG,
> avgPayRate, avgRegHrs, avgGross, avgFed, avgSSIT, avgNet, avgOvtHrs,
> avgSt, avgDefr); }

This is my make file:

dataReport.exe: main.o InitializeAccumulators.o InputEmployeeData.o CalculateGross.o calculateTaxes.o CalculateNetPay.o CalculateTotAvg.o PrintReportSummary.o
    g++ main.o InitializeAccumulators.o InputEmployeeData.o CalculateGross.o calculateTaxes.o CalculateNetPay.o CalculateTotAvg.o PrintReportSummary.o -o dataReport.exe

main.o: main.cpp maxEmployee.h
    g++ -c main.cpp -o main.o

InitializeAccumulators.o: InitializeAccumulators.cpp
    g++ -c InitializeAccumulators.cpp -o InitializeAccumulators.o

InputEmployeeData.o: InputEmployeeData.cpp
    g++ -c InputEmployeeData.cpp -o InputEmployeeData.o

CalculateGross.o: CalculateGross.cpp
    g++ -c CalculateGross.cpp -o CalculateGross.o

calculateTaxes.o: calculateTaxes.cpp taxrates.h
    g++ -c calculateTaxes.cpp -o calculateTaxes.o

CalculateNetPay.o: CalculateNetPay.cpp
    g++ -c CalculateNetPay.cpp -o CalculateNetPay.o

CalculateTotAvg.o: CalculateTotAvg.cpp
    g++ -c CalculateTotAvg.cpp -o CalculateTotAvg.o

PrintReportSummary.o: PrintReportSummary.cpp maxEmployee.h
    g++ -c PrintReportSummary.cpp -o PrintReportSummary.o

clean:
    rm *.o dataReport.exe

So then my question is how do I fix this? I've been stuck on this for a couple days now...

Body:
In main you loop 1 time, so the variable "i" has a value of 1 at the end of the for loop.

In PrintReportSummary you use the following loop:

for (int k = 0; k <= i; k++)

Substitute 1 for i gives:

for (int k = 0; k <= 1; k++)

So the loop body is executed 2 times. The behaviour should be the same in windows so you might re-test that :)
Furthermore, if you input 40 records, or you set MAXEMP to 1 and input 1 record, the program will crash or show undefined behaviour at the second for loop, cause it would access elements out of bounds from your arrays.

Solution: change <= to <.

To clean up the code a little you could use structs instead of that many function arguments :)


问:
The columns in table do not match an existing primary key or UNIQUE constraint
How does one work around the issue of not matching an existig primary key or unique constraint when creating a FK in SSMS?

I have two tables namely : user and firstdb where both fields have the same datatype. In user table I have two primary keys, and in the foreign key table I have one field which I want to make it the target of a foreign key.

I tried to have one field as a primary key in the user table, the relationship worked fine at that time but once I set the second field to primary it forces me to delete the existing relationship for some reason.
I tried to create a relationship like this in MySQL, it worked fine with me, but it doesn't work.

答:
You seem to have a profound misunderstand of what a primary key is.  A primary key (singular) is one or more columns that uniquely identify each row (and none of the columns are NULL).  When you click "primary key" by two columns, you are generating a composite primary key.

Foreign key references need to be to the complete primary key.  If you have a composite primary key, you need a composite foreign key.

Having single column foreign key references is one reason why the best type of primary key is an identity column.  I am guessing that userid is such a column.

If you want uEmailId to be unique and non-NULL, then define it as unique and non-NULL.  However, don't add it to the primary key!

ContentLicense: CC BY-SA 4.0


问:
Jenkins 2.x Parameterized Trigger Plugin Computed Parameter
I am using the above plugin in a Jenkins job, but want to pass the invoked job some parameter that is computed and/or fetched from some custom source. Easy enough to do in a shell script, except that none of the Add Parameters options that are built-in allow for a way to do this kind of dynamic computation.

I have found the EnvInject plugin, but the problem here is that the computed parameter is a secret and needs to avoid being stored anywhere on disk. The only way I could figure out in the EnvInject plugin requires first writing the computed secret to disk and then read it in from that disk file as an environment variable in a subsequent step using the EnvInject plugin.

So the question is, is there any known parameter source for the Parameterized Trigger Plugin (docs says the parameter sources themselves are pluggable) that would allow me to compute the parameter dynamically?

答:
So I found that the EnvInject plugin can inject environment variables from evaluating a Groovy script. A little less convenient than a simple shell script, especially as there aren't that many examples to be found online or in the plugin docs, but it works.

An example script, which you can put in the Build Environment section by checking the "Inject environment variables" checkbox:

```<code>try {
  def json = /curl -s -H "X-Vault-Token:${VAULT_TOKEN}" -X GET https://xxx.yyy.zzz/v1/secret/oe/dmp/aws/mykey.key/.execute().text
  def access_key_id = /echo '${json}' | jq -r '.data' | jq -r '.aws_access_key_id'/.execute().text>
  def secret_access_key = /echo '${json}' | jq -r '.data' | jq -r '.aws_secret_access_key'/.execute().text

  return ['AWS_SECRET_ACCESS_KEY' : secret_access_key, 'AWS_ACCESS_KEY_ID' : access_key_id]
} catch (Throwable t) {
  println(t)
  throw t;
}
</code>```

Body:
So I found that the EnvInject plugin can inject environment variables from evaluating a Groovy script. A little less convenient than a simple shell script, especially as there aren't that many examples to be found online or in the plugin docs, but it works.

An example script, which you can put in the Build Environment section by checking the "Inject environment variables" checkbox:

try {
  def json = /curl -s -H "X-Vault-Token:${VAULT_TOKEN}" -X GET https://xxx.yyy.zzz/v1/secret/oe/dmp/aws/mykey.key/.execute().text
  def access_key_id = /echo '${json}' | jq -r '.data' | jq -r '.aws_access_key_id'/.execute().text>
  def secret_access_key = /echo '${json}' | jq -r '.data' | jq -r '.aws_secret_access_key'/.execute().text

  return ['AWS_SECRET_ACCESS_KEY' : secret_access_key, 'AWS_ACCESS_KEY_ID' : access_key_id]
} catch (Throwable t) {
  println(t)
  throw t;
}


问:
Mezzanine/Django 1.10 migrations: Database tables does not much with migrations
I am using Mezzanine (Django 1.10) so I can't see a "db.sqlite3"

I searched similar questions as mine and most of the solutions provided were not effective.

I created a new model and later decided to add a new field. I did "python manage.py makemigrations ", and when I looked at my migrations folder, it's there; the new field exists. Now, when I ran the app and looked into admin, it gave me error where it said "No such column exists". Therefore, I think, my database is not synced with the migrations I have.

This is what I did:
1. deleted everything in the migration folder and recreated the "init.py".

1.1 ran "python manage.py makemigrations <app_name>"

1.2 ran "python manage.py migrate <app_name>"

1.3 ran "python manage.py runserver"

I can actually just rename my model into a different name with the same fields, however, sometimes Django would give error such as "no such table exist". It would also be quiet tedious to do because if I rename my model, I have to rename it in every file where I have imported the model such as in admin.py, forms.py, views.py, etc.

I heard about South, but its not applicable to Django 1.10.

Please Help. Thank you!

答: I just solved this problem. Since I am using Mezzanine then the name of the database is not the same. Look for the file dev.db which would be located at the same folder of your manage.py. Then, delete it. Then, run python manage.py makemigrations and python manage.py migrate again. Then (I hope) it would work.


问:
Extract specific text out of bash variable containing TSV string
I have the following TSV and newlines string assigned to a variable in bash:

```<code>TAGS    Product3    qwerty  text    Desc3
TAGS    Product1    qwerty  text    Desc1
TAGS    Product2    qwerty  text    Desc2
</code>```

I would like to extract the last column to a new string, and it has to be product ordered by my product input, for example:

Product1,Product2,Product3 will have to output: Desc1,Desc2,Desc3

What would be the best approach to accomplish this?

答:
sort + awk + paste pipeline:

```<code>echo "$tsv" | sort -nk2 | awk '{print $5}' | paste -sd',' -
</code>```

The output:

```<code>Desc1,Desc2,Desc3
</code>```

sort -nk2 - sorts the input by the second column numerically

awk '{print $5}' - prints out each fifth column

paste -sd',' - merge lines with ,

Body:
I have the following TSV and newlines string assigned to a variable in bash:

TAGS    Product3    qwerty  text    Desc3
TAGS    Product1    qwerty  text    Desc1
TAGS    Product2    qwerty  text    Desc2

I would like to extract the last column to a new string, and it has to be product ordered by my product input, for example:

Product1,Product2,Product3 will have to output: Desc1,Desc2,Desc3

What would be the best approach to accomplish this?

Body:
sort + awk + paste pipeline:

echo "$tsv" | sort -nk2 | awk '{print $5}' | paste -sd',' -

The output:

Desc1,Desc2,Desc3

sort -nk2 - sorts the input by the second column numerically

awk '{print $5}' - prints out each fifth column

paste -sd',' - merge lines with ,


问:
Java script to close doesn't work
I build a toggle bar in html/css and I want to use JS to close. I think I did all the code right, yet the script does not work.

Code:

```<code>$(document).ready(function(){
$(".fa-times").click(function(){$(".sidebar_menu").addClass("hide_menu");
$(".toggle_menu").addClass("opacity_one");});
</code>```

jsfiddle link

The point is that I created a button "x shaped" that closes the side bar but you won't be able to see it cuz is a custom font and I have no clue how to upload it onto jsfiddle. The button is placed in the top-right corner of the purple bar.

I hope its enough information and the code is easy to understand. I`m just at the start with html/css/js but I have to do this for a microsoft project since noone in my team can't even set a default html page.

P.S. Ignore the white element with that random text.

答: Correct me if i am wrong,as ii saw you fiddle your code working fine.When user click on cross btn that time blue side bar hiding left side.</p>

Title: Java script to close doesn't work

Body:
I build a toggle bar in html/css and I want to use JS to close. I think I did all the code right, yet the script does not work.

Code:

$(document).ready(function(){
$(".fa-times").click(function(){$(".sidebar_menu").addClass("hide_menu");
$(".toggle_menu").addClass("opacity_one");});

jsfiddle link

The point is that I created a button "x shaped" that closes the side bar but you won't be able to see it cuz is a custom font and I have no clue how to upload it onto jsfiddle. The button is placed in the top-right corner of the purple bar.

I hope its enough information and the code is easy to understand. I`m just at the start with html/css/js but I have to do this for a microsoft project since noone in my team can't even set a default html page.

P.S. Ignore the white element with that random text.


问:
Ajax and SQL population of a dropdown
This seems to be the pain of my life I have now spent hours on this and none of the researched solutions seem to fix it. My code is supposed to populate a dropdown from a database called "notes" the field that is populated from is supposed is "name" and then the program is supposed to select all of the records with the name as the same selected. Except it does not seem to populate the list. I don't think that it's a database connection error as when all patients is selected all the records show up.

Here's my code:

<?php

// php select option value from database

$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "CareM_database";

// connect to mysql database

 //load_data_select.php

 mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
 $connect = mysqli_connect($hostname, $username, $password, $databaseName);
 function fill_name($connect)
 {
      $output = '';
      $sql = "SELECT name, id FROM name";
      $result = mysqli_query($connect, $sql);
      while($row = mysqli_fetch_array($result))
      {
           $output .= '<option value="'.$row["id"].'">'.$row["name"].'</option>';
      }
      return $output;
 }
 function fill_patients($connect)
 {
      $output = '';
      $sql = "SELECT * FROM notes";
      $result = mysqli_query($connect, $sql);
      while($row = mysqli_fetch_array($result))
      {
           $output .= '
';
           $output .= '
'.$row["details"].'';
           $output .=     '
';
           $output .=     '
';
      }
      return $output;
 }
 ?>
 <!DOCTYPE html>

           <title>Patient Notes View</title>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

                     <select name="name" id="name">
                          <option value="">Show All Patients</option>
                          <?php echo fill_patients($connect); ?>
                     </select>

                          <?php echo fill_patients($connect);?>

   ```

答: First of all add jquery.min.js before add bootstrap js</p>

Title: Ajax and SQL population of a dropdown


问:
Why is this program not waiting for input from user?
I currently have the following code wrote:

```<code>import java.util.Scanner;

public class TicketPriceWithDiscount {

public static void main(String[] args) {

    TicketPriceWithDiscount obj = new TicketPriceWithDiscount();

}

  public TicketPriceWithDiscount(){

    double regPrice = 9.25;
    double otherPrice = 5.25; // ages under 12 or over 65
    double discount = 2.00;
    String person;
    int pInput;

    Scanner keyboard = new Scanner(System.in);

    System.out.println("What is your age?");

    pInput = keyboard.nextInt();

    System.out.println("Do you have a coupon? Yes or no will do.");

    person = keyboard.nextLine();

    if(person == "yes" && pInput <= 12 || pInput >= 65){
        otherPrice = otherPrice - discount;
        System.out.println("Your ticket price is: " + otherPrice);

    }

    else if(person == "yes" && pInput >= 12 && pInput <= 65){
        regPrice = regPrice - discount;
        System.out.println("Your ticket price is: " + regPrice);
    }

    else if(pInput <= 12 || pInput >= 65){
        System.out.println("Your ticket price is: " + otherPrice);
    }

    else if(pInput >= 12 || pInput <= 65) {
        System.out.println("Your ticket price is: " + regPrice);
    }

}

}
</code>```

The program runs up to the point in which I ask for the person to input wither or not they have a coupon.

```<code>System.out.println("Do you have a coupon? Yes or no will do.");

    person = keyboard.nextLine();
</code>```

At this point, the program does not wait for an input and completes the if statement based on age input which it does wait for a reply from the user.

The output intended is for the user to input age, say yes or no to the coupon question and for the program to continue its run depending on those answers.

What I have tried:

closing the scanner - keyboard.close();

create a new scanner after closing the first instance of scanner.

Guidance is highly appreciated.

答:
change to :</p>

```<code>import java.util.Scanner;

public class TicketPriceWithDiscount {

public static void main(String[] args) {

    TicketPriceWithDiscount obj = new TicketPriceWithDiscount();

}

  public TicketPriceWithDiscount(){

    double regPrice = 9.25;
    double otherPrice = 5.25; // ages under 12 or over 65
    double discount = 2.00;
    String person;
    int pInput;

    Scanner keyboard = new Scanner(System.in);

    System.out.println("What is your age?");
    pInput = keyboard.nextInt();

    System.out.println("Do you have a coupon? Yes or no will do.");
    //change to next() not nextLine()
    //because nextLine is used when you read a file
    person = keyboard.next();

     //use equals  not ==  and don't forget the parentheses
    if(person.equals("yes") && (pInput <= 12 || pInput >= 65)){
        otherPrice = otherPrice - discount;
        System.out.println("rani hna");
        System.out.println("Your ticket price is: " + otherPrice);

    }

    //use equal not ==
    else if(person.equals("yes")  && pInput >= 12 && pInput <= 65){
        regPrice = regPrice - discount;
        System.out.println("Your ticket price is: " + regPrice);
    }

    else if(pInput <= 12 || pInput >= 65){
        System.out.println("Your ticket price is: " + otherPrice);
    }

    else if(pInput >= 12 || pInput <= 65) {
        System.out.println("Your ticket price is: " + regPrice);
    }

}

}
</code>```

Body:
I currently have the following code wrote:

import java.util.Scanner;

public class TicketPriceWithDiscount {

public static void main(String[] args) {

    TicketPriceWithDiscount obj = new TicketPriceWithDiscount();

}

  public TicketPriceWithDiscount(){

    double regPrice = 9.25;
    double otherPrice = 5.25; // ages under 12 or over 65
    double discount = 2.00;
    String person;
    int pInput;

    Scanner keyboard = new Scanner(System.in);

    System.out.println("What is your age?");

    pInput = keyboard.nextInt();

    System.out.println("Do you have a coupon? Yes or no will do.");

    person = keyboard.nextLine();

    if(person == "yes" && pInput <= 12 || pInput >= 65){
        otherPrice = otherPrice - discount;
        System.out.println("Your ticket price is: " + otherPrice);

    }

    else if(person == "yes" && pInput >= 12 && pInput <= 65){
        regPrice = regPrice - discount;
        System.out.println("Your ticket price is: " + regPrice);
    }

    else if(pInput <= 12 || pInput >= 65){
        System.out.println("Your ticket price is: " + otherPrice);
    }

    else if(pInput >= 12 || pInput <= 65) {
        System.out.println("Your ticket price is: " + regPrice);
    }

}

}

The program runs up to the point in which I ask for the person to input wither or not they have a coupon.

System.out.println("Do you have a coupon? Yes or no will do.");

    person = keyboard.nextLine();

At this point, the program does not wait for an input and completes the if statement based on age input which it does wait for a reply from the user.

The output intended is for the user to input age, say yes or no to the coupon question and for the program to continue its run depending on those answers.

What I have tried:

closing the scanner - keyboard.close();

create a new scanner after closing the first instance of scanner.

Guidance is highly appreciated.

Body:
change to :

import java.util.Scanner;

public class TicketPriceWithDiscount {

public static void main(String[] args) {

    TicketPriceWithDiscount obj = new TicketPriceWithDiscount();

}

  public TicketPriceWithDiscount(){

    double regPrice = 9.25;
    double otherPrice = 5.25; // ages under 12 or over 65
    double discount = 2.00;
    String person;
    int pInput;

    Scanner keyboard = new Scanner(System.in);

    System.out.println("What is your age?");
    pInput = keyboard.nextInt();

    System.out.println("Do you have a coupon? Yes or no will do.");
    //change to next() not nextLine()
    //because nextLine is used when you read a file
    person = keyboard.next();

     //use equals  not ==  and don't forget the parentheses
    if(person.equals("yes") && (pInput <= 12 || pInput >= 65)){
        otherPrice = otherPrice - discount;
        System.out.println("rani hna");
        System.out.println("Your ticket price is: " + otherPrice);

    }

    //use equal not ==
    else if(person.equals("yes")  && pInput >= 12 && pInput <= 65){
        regPrice = regPrice - discount;
        System.out.println("Your ticket price is: " + regPrice);
    }

    else if(pInput <= 12 || pInput >= 65){
        System.out.println("Your ticket price is: " + otherPrice);
    }

    else if(pInput >= 12 || pInput <= 65) {
        System.out.println("Your ticket price is: " + regPrice);
    }

}

}


问:
Download file from https url with authentication using wildcards
I need to download an artifact from nexus repository using command line. The artifact file name is unknowm but the extension name is always *.zip. I am using the curl command with wildcard characters. When I execute the command it says HTTP/1.1 404 Not Found

curl --insecure  -O -u username:password -v https://nexus.internal.org.com/content/repositories/snapshots/com/org/artifact/1.4.0/*.zip

```<code>> Accept: */*
>
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
 0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--   0< HTTP/1.1 404 Not Found
< Accept-Ranges: bytes
< Content-Type: text/html
< Date: Wed, 01 Mar 2017 22:28:35 GMT
< Server: Nexus/2.14.2-01
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< transfer-encoding: chunked
< Connection: keep-alive
</code>```

The file is actually present in the URL location. Is the command I'm running alright?

答:
I found a good way to do this with the instructions from this answer
that basically requests the content of an entire prefix, sets some boundaries into the recursion and filters accepted files by a shell-like pattern.

If I am not mistaken, the command to do what you want would be:

```<code>wget --recursive --level=1 --no-parent --no-directories \
  --accept '*.zip' \
  --directory-prefix=. \
   https://nexus.internal.org.com/content/repositories/snapshots/com/org/artifact/1.4.0/
</code>```

Body:
I need to download an artifact from nexus repository using command line. The artifact file name is unknowm but the extension name is always *.zip. I am using the curl command with wildcard characters. When I execute the command it says HTTP/1.1 404 Not Found

curl --insecure  -O -u username:password -v https://nexus.internal.org.com/content/repositories/snapshots/com/org/artifact/1.4.0/*.zip

> Accept: */*
>
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
 0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--   0< HTTP/1.1 404 Not Found
< Accept-Ranges: bytes
< Content-Type: text/html
< Date: Wed, 01 Mar 2017 22:28:35 GMT
< Server: Nexus/2.14.2-01
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< transfer-encoding: chunked
< Connection: keep-alive

The file is actually present in the URL location. Is the command I'm running alright?

Body:
I found a good way to do this with the instructions from this answer
that basically requests the content of an entire prefix, sets some boundaries into the recursion and filters accepted files by a shell-like pattern.

If I am not mistaken, the command to do what you want would be:

wget --recursive --level=1 --no-parent --no-directories \
  --accept '*.zip' \
  --directory-prefix=. \
   https://nexus.internal.org.com/content/repositories/snapshots/com/org/artifact/1.4.0/


问:
How to call ONLY javascript function in html.actionlink
I have java script function

```<code>   function SetTextBoxValue(data) {
        $('#text_box').val($(this).val("myField"))

    };
</code>```

Is it possible, and how, to call only this function, WITHOUT controller and action names from @Html.ActionLink() in razor view?

To  extend a question, i have table and a form with 4 text boxes on same view. I need to fill one textbox with a value of a specific column in table when user click on link in that column.

答:
You need 2 steps :

1 : add onclick="return someJsFct" in your actionLink

```<code>@Html.ActionLink("click here", "", "", null, new { onclick="return SetTextBoxValue('data')" });
</code>```

2 :
your javascript function must return false to prevent the actionLink from calling the server

```<code><script language="javascript">
    function SetTextBoxValue(data) {
        // some code

        return false;
    }
</script>
</code>```

Body:
I have java script function

   function SetTextBoxValue(data) {
        $('#text_box').val($(this).val("myField"))

    };

Is it possible, and how, to call only this function, WITHOUT controller and action names from @Html.ActionLink() in razor view?

To  extend a question, i have table and a form with 4 text boxes on same view. I need to fill one textbox with a value of a specific column in table when user click on link in that column.

Body:
You need 2 steps :

1 : add onclick="return someJsFct" in your actionLink

@Html.ActionLink("click here", "", "", null, new { onclick="return SetTextBoxValue('data')" });

2 :
your javascript function must return false to prevent the actionLink from calling the server

<script language="javascript">
    function SetTextBoxValue(data) {
        // some code

        return false;
    }
</script>


问:
 Anchor remains in URL and in page after refreshing
I have this little issue here with my page, where if I reload it while being anchored, the anchor remains and there is a problem to it. I.E

```<code>http://localhost/public/product/1#mod1
</code>```

The anchor is #mod1, and while the anchor remains active after refresh, my CSS code is saying that this element:

```<code>.overlay:target
</code>```

is active. Which is a very big issue, because then it doesn't allow me to explore the functionallity I have implemented on this anchor, unless I remove the #mod1 from the end of the page manually by hand. Because this CSS element makes this div visible when it should be not unless activated with the a href element.

```<code><a href="#mod{{$key}}" class="button">(?)</a>
<div id="mod{{$key}}" class="overlay">
    content
</div>
</code>```

Any ideas on how could I solve it? I tried catching whether the user has refreshed the page and redirecting him to an action/route/url, but the page stays blank then and URL unchanged.

答:
You cannot use href with angularJS because it will misdirect the target link. AngularJS is a markup language for HTML, it is not HTML. Because angularJS is not HTML, we're provided a special set of directives to write angularJS values inline into HTML markup. The answer to solve your issue would be to replace the href tag in the anchor element with the angularJS directive ngHref. You can find more information about how to use ngHref and other directives at the link below. Good luck.

https://docs.angularjs.org/api/ng/directive/ngHref

Title: <a href> Anchor remains in URL and in page after refreshing

Body:
I have this little issue here with my page, where if I reload it while being anchored, the anchor remains and there is a problem to it. I.E

http://localhost/public/product/1#mod1

The anchor is #mod1, and while the anchor remains active after refresh, my CSS code is saying that this element:

.overlay:target

is active. Which is a very big issue, because then it doesn't allow me to explore the functionallity I have implemented on this anchor, unless I remove the #mod1 from the end of the page manually by hand. Because this CSS element makes this div visible when it should be not unless activated with the a href element.

(?)

    content

Any ideas on how could I solve it? I tried catching whether the user has refreshed the page and redirecting him to an action/route/url, but the page stays blank then and URL unchanged.


问:
Visual Studio messes up project settings
I've created an empty C++ project, added main.cpp, and set up build configurations. Particularly, I changed Output Directory and Intermediate Directory. Pushed everything to GitHub, and cloned it to the other computer. Opened solution, checked properties of the project to find out that it is now set back to default. Tried compiling, wrong directories are used. git status on both computers shows nothing. I also checked .vcxproj to find out that changed strings are present in the file.

What could be the cause of this behavior?

Repository: https://github.com/kirdaybov/experiments

My environment:

1st computer: VS Express 2015 update 1.

2nd computer: VS Community 2015 update 3.

答:
This happens to me all the time!

VS has the nasty habit of not saving project and solution options, even when you configure it to "Save to Compile", or even when you click the "Save" button.

You must click the "Save All" button. Or to be extra safe, close VS before committing.

Or could be caused because one of the computers is compiling the "Debug" configuration while the other is compiling the "Release" one. Or one is compiling the "Any CPU" and the other the "x86". Note that the "current configuration" option is not pushed to the repository.


问:
Android: How to create a notification from the command line (terminal emulator or shell script)?
I would like to create a notification (icon in notification bar plus message in notification drawer) from a shell script that I'm running on my android device. I have CyanogenMod11, which comes with BusyBox v1.22.1 bionic.

I've discovered how to create a toast (http://forum.xda-developers.com/showthread.php?t=773232) but what I need is a notification. For difference between toast and notification, see this excellent thread: https://android.stackexchange.com/questions/52789/popups-dialogs-notifications-toasts-whats-the-difference

Can anyone point me in the right direction? I'm guessing it will involve the Android Activity Manager (am) but I've searched every nook and cranny of the internet and cannot find a way to create a notification from the command line on android.

答:
source:
https://forum.xda-developers.com/showpost.php?p=69859668&postcount=18

date: 30th November 2016, 02:32 PM

Two years ago I was in need of a simple notification tool that could have been run by a command line in a script.
So far the best I found was this thread and the tiny app made by corruptor64.
That wasn't exactly what I was looking for so I finally decided to try to make the tool by myself.
Starting from scratch (I am not an Android developer) in a few days of studying and developing I ended up with a working small app, that I named Notify4Scripts and I made it public only this past June, here on GitHub
https://github.com/halnovemila/Notify4Scripts

Note that since the app is basically a service that has to be launched by the Android's shell "am" (activity manager) command, the Android system needs to be rooted first in order to be able to use such am command and have notify4scripts executed.


问:
Cron does not run shell script properly
im having the problem that a bash script is not running from cron. When i instead run it as root from the cli it works well. As you can see i write to a txt file when the script has finished. This is also done when the script runs from cron, only the Oracle dmp is not saved (and obviously not zipped). The job is done extremely quick, so i guess it does not do the oracle export...

Thank you for you help!

backup.sh

```<code>#!/bin/bash
#makes an Oracle  backup and zips the created file
TIME=`date +%F_%H:%M:%S`
FILENAME=Backup-$TIME

exp userid=user/password file=/home/user/DatabaseBackup/$FILENAME.dmp
zip /home/user/DatabaseBackup/$FILENAME.zip /home/user/DatabaseBackup/$FILENAME$
find /home/user/DatabaseBackup/ -mtime +0 -type f -delete

echo "Backup completed:" `date +%F_%H:%M:%S` >> /home/user/scripts/logBackup.txt
#END
</code>```

crontab -e
26 * * * * /home/user/scripts/backup.sh

答:
Ok, what i did is:

I added

```<code>>> /home/user/cron.txt 2>&1
</code>```

this to my cronjob declaration, wiht this i have now the output of the cornjob.

With this it was easy to find out that some evironmet variables for oracle were missing...

Thanks for any help provided!

Title: Cron does not run shell script properly

Body:
im having the problem that a bash script is not running from cron. When i instead run it as root from the cli it works well. As you can see i write to a txt file when the script has finished. This is also done when the script runs from cron, only the Oracle dmp is not saved (and obviously not zipped). The job is done extremely quick, so i guess it does not do the oracle export...

Thank you for you help!

backup.sh

#!/bin/bash
#makes an Oracle  backup and zips the created file
TIME=`date +%F_%H:%M:%S`
FILENAME=Backup-$TIME

exp userid=user/password file=/home/user/DatabaseBackup/$FILENAME.dmp
zip /home/user/DatabaseBackup/$FILENAME.zip /home/user/DatabaseBackup/$FILENAME$
find /home/user/DatabaseBackup/ -mtime +0 -type f -delete

echo "Backup completed:" `date +%F_%H:%M:%S` >> /home/user/scripts/logBackup.txt
#END

crontab -e
26 * * * * /home/user/scripts/backup.sh

Body:
Ok, what i did is:

I added

>> /home/user/cron.txt 2>&1

this to my cronjob declaration, wiht this i have now the output of the cornjob.

With this it was easy to find out that some evironmet variables for oracle were missing...

Thanks for any help provided!


问:
FillStyle query or something else?
Just practicing using constructors that have arguments and have come across an error that I believe stems from the fillStyle method.

My canvas just appears blank and there are no errors on the console?

Trying to build 5 different circles each with their own specific color.

I've created a fiddle: https://jsfiddle.net/kvuf7dxb/;

The main bulk of code:

```<code>    var circle1;
    var circle2;
    var circle3;
    var circle4;
    var circle5;

    function drawCircles() {

        ctx.clearRect(0,0,w,h);

        circle1 = new Circle(600,600,102,55);
        circle2 = new Circle(600,600,40,10);
        circle3 = new Circle(600,600,37,12);
        circle4 = new Circle(600,600,280,34);
        circle5 = new Circle(600,600,390,55);

    }

        function Circle(x, y, color,r) {
            this.x = x;
            this.y = y;
            this.color = color;
            this.r = r;

            this.show = function() {
                ctx.beginPath();
                ctx.moveTo(this.x,this.y);
                ctx.fillStyle = this.color;
                ctx.arc(this.x,this.y,this.r,0,Math.PI*2,true);
                ctx.fill();
            };
        }
</code>```

I'm aware that all the circles will appear at the same x and y position.

答:
There are several issues that need to be fixed. Here's a working version.

var canvas = document.getElementById('stars');
var ctx = canvas.getContext('2d');
var w = window.innerWidth;
var h = window.innerHeight;
canvas.width = w;
canvas.height = h;

var circle1 = new Circle(20, 20, '66CC00', 55),
    circle2 = new Circle(30, 30, 'FF0000', 10),
    circle3 = new Circle(40, 40, '3333FF', 12),
    circle4 = new Circle(50, 50, 'FFFF00', 34),
    circle5 = new Circle(70, 70, 'FF9933', 55);

drawCircles();

function drawCircles() {
    ctx.clearRect(0, 0, w, h);
    circle1.show();
    circle2.show();
    circle3.show();
    circle4.show();
    circle5.show();
    requestAnimationFrame(drawCircles);
}

function Circle(x, y, color, r) {
    this.x = w * x / 100;
    this.y = h * y / 100;
    this.color = '#' + color;
    this.r = r;
    this.show = function() {
        ctx.beginPath();
        ctx.fillStyle = this.color;
        ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
        ctx.fill();
    };
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    background: black;
    overflow: hidden;
}</code>```

<canvas id="stars"></canvas>```

Title: FillStyle query or something else?

Body:
Just practicing using constructors that have arguments and have come across an error that I believe stems from the fillStyle method.

My canvas just appears blank and there are no errors on the console?

Trying to build 5 different circles each with their own specific color.

I've created a fiddle: https://jsfiddle.net/kvuf7dxb/;

The main bulk of code:

    var circle1;
    var circle2;
    var circle3;
    var circle4;
    var circle5;

    function drawCircles() {

        ctx.clearRect(0,0,w,h);

        circle1 = new Circle(600,600,102,55);
        circle2 = new Circle(600,600,40,10);
        circle3 = new Circle(600,600,37,12);
        circle4 = new Circle(600,600,280,34);
        circle5 = new Circle(600,600,390,55);

    }

        function Circle(x, y, color,r) {
            this.x = x;
            this.y = y;
            this.color = color;
            this.r = r;

            this.show = function() {
                ctx.beginPath();
                ctx.moveTo(this.x,this.y);
                ctx.fillStyle = this.color;
                ctx.arc(this.x,this.y,this.r,0,Math.PI*2,true);
                ctx.fill();
            };
        }

I'm aware that all the circles will appear at the same x and y position.

Body:
There are several issues that need to be fixed. Here's a working version.

var canvas = document.getElementById('stars');
var ctx = canvas.getContext('2d');
var w = window.innerWidth;
var h = window.innerHeight;
canvas.width = w;
canvas.height = h;

var circle1 = new Circle(20, 20, '66CC00', 55),
    circle2 = new Circle(30, 30, 'FF0000', 10),
    circle3 = new Circle(40, 40, '3333FF', 12),
    circle4 = new Circle(50, 50, 'FFFF00', 34),
    circle5 = new Circle(70, 70, 'FF9933', 55);

drawCircles();

function drawCircles() {
    ctx.clearRect(0, 0, w, h);
    circle1.show();
    circle2.show();
    circle3.show();
    circle4.show();
    circle5.show();
    requestAnimationFrame(drawCircles);
}

function Circle(x, y, color, r) {
    this.x = w * x / 100;
    this.y = h * y / 100;
    this.color = '#' + color;
    this.r = r;
    this.show = function() {
        ctx.beginPath();
        ctx.fillStyle = this.color;
        ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
        ctx.fill();
    };
}

body {
    background: black;
    overflow: hidden;
}

<canvas id="stars"></canvas>