问:
Cancel Animation on Click instead of hover - JQuery
I'm just wondering if there is a way to cancel an animation on click instead of hover. The fiddle below uses hover to stop the effect. I tried something similar like this approach but seems a bit different required here.

What I would like if you click the li again it will reset like if you're not hovering over the div anymore. And when you click li it will start the animation.

http://jsfiddle.net/htmlboy/qQyhE/

JQuery Code

```<code>//animate with no stop()

$(".nostop li").hover(
  function () {
      $(this).animate({width:"100px"},500);
  },
   function () {
    $(this).animate({width:"80px"},500);
  }
);

//animate with stop()
$(".stop li").hover(
  function () {
      $(this).stop().animate({width:"100px"},500);
  },
   function () {
    $(this).stop().animate({width:"80px"},500);
  }
);
</code>```

答:
Please find the below solution:

```<code>//animate with no stop()
$(".nostop li").on("click",function(){
 if( $(this).width() == "100")
    $(this).animate({width:"80px"},500);
    else
     $(this).animate({width:"100px"},500);
  }
);

//animate with stop()
$(".stop li").on("click",function(){
 if( $(this).width() == "100")
    $(this).stop().animate({width:"80px"},500);
    else
    $(this).stop().animate({width:"100px"},500);
  }
);
</code>```

http://jsfiddle.net/qQyhE/45/

Body:
I'm just wondering if there is a way to cancel an animation on click instead of hover. The fiddle below uses hover to stop the effect. I tried something similar like this approach but seems a bit different required here.

What I would like if you click the li again it will reset like if you're not hovering over the div anymore. And when you click li it will start the animation.

http://jsfiddle.net/htmlboy/qQyhE/

JQuery Code

//animate with no stop()

$(".nostop li").hover(
  function () {
      $(this).animate({width:"100px"},500);
  },
   function () {
    $(this).animate({width:"80px"},500);
  }
);

//animate with stop()
$(".stop li").hover(
  function () {
      $(this).stop().animate({width:"100px"},500);
  },
   function () {
    $(this).stop().animate({width:"80px"},500);
  }
);

Body:
Please find the below solution:

//animate with no stop()
$(".nostop li").on("click",function(){
 if( $(this).width() == "100")
    $(this).animate({width:"80px"},500);
    else
     $(this).animate({width:"100px"},500);
  }
);

//animate with stop()
$(".stop li").on("click",function(){
 if( $(this).width() == "100")
    $(this).stop().animate({width:"80px"},500);
    else
    $(this).stop().animate({width:"100px"},500);
  }
);

http://jsfiddle.net/qQyhE/45/


来源: stackexchange

问:
Default and maximum length of VARCHAR
I am very new to Apache Phoenix. I have created table using query in SQuirrel SQL client. Here I shared the sample query below.

CREATE TABLE IF NOT EXISTS Sample(Action VARCHAR NOT NULL, Title VARCHAR, Email VARCHAR, Type VARCHAR CONSTRAINT PKforum PRIMARY KEY (Action));

Title column has the value which maximum size is 200 characters.

Then I tried to fetch data from Apache Phoenix using Simba Pheonix ODBC driver. For this, used the below C# code..

```<code>OdbcConnection connection = new OdbcConnection("Driver={Simba Phoenix ODBC Driver};host=<host name>;port=8765");
        connection.Open();
        OdbcCommand command = new OdbcCommand(query,connection);
        OdbcDataReader dataReader = command.ExecuteReader();
        DataTable dataTable = new DataTable();
        dataTable.Load(dataReader);
        connection.Close();
</code>```

When loading data table I got the below exception.

failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.

If I change my query like below its working fine.

CREATE TABLE IF NOT EXISTS Sample(Action VARCHAR NOT NULL, Title VARCHAR(300), Email VARCHAR, Type VARCHAR CONSTRAINT PKforum PRIMARY KEY (Action));

Here my doubt is,
 What is the default size and maximum size of VARCHAR in Phoenix server?

答:
Range will be the type of int as mentioned below ..

https://phoenix.apache.org/language/index.html#int

ContentLicense: CC BY-SA 3.0

Title: Default and maximum length of VARCHAR

Body:
I am very new to Apache Phoenix. I have created table using query in SQuirrel SQL client. Here I shared the sample query below.

CREATE TABLE IF NOT EXISTS Sample(Action VARCHAR NOT NULL, Title VARCHAR, Email VARCHAR, Type VARCHAR CONSTRAINT PKforum PRIMARY KEY (Action));

Title column has the value which maximum size is 200 characters.

Then I tried to fetch data from Apache Phoenix using Simba Pheonix ODBC driver. For this, used the below C# code..

OdbcConnection connection = new OdbcConnection("Driver={Simba Phoenix ODBC Driver};host=<host name>;port=8765");
        connection.Open();
        OdbcCommand command = new OdbcCommand(query,connection);
        OdbcDataReader dataReader = command.ExecuteReader();
        DataTable dataTable = new DataTable();
        dataTable.Load(dataReader);
        connection.Close();

When loading data table I got the below exception.

failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.

If I change my query like below its working fine.

CREATE TABLE IF NOT EXISTS Sample(Action VARCHAR NOT NULL, Title VARCHAR(300), Email VARCHAR, Type VARCHAR CONSTRAINT PKforum PRIMARY KEY (Action));

Here my doubt is,
 What is the default size and maximum size of VARCHAR in Phoenix server?


问:
Default initial value for weights
When setting up a neural network, or any numeric optimization system using gradient descent, it's necessary to provide initial values for the weights (or whatever the system parameters are to be called).

One strategy is to initialize them to random values (set the random number seed to a known value, change for a different starting point). But this isn't always desirable (e.g. right now I'm comparing accuracy in single versus double precision, the TensorFlow random number generator outputs different values in each case). So I'm talking about a scenario where the initial values will be nonrandom.

Some initial value must be provided. In the absence of any information to specify a value, what should it be? The most obvious values are 0.0 and 1.0. Is there a reason to prefer one of those over the other?  Or is there some other value  that tends to be preferable for some reason?

答:
As sascha observes, constant initial weights aren't a solution in general anyway because you have to break symmetry. Better solution for the particular context in which I came across the problem: a random number generator that gives the same sequence regardless of type.</p>

```<code>dtype = np.float64

# Random number generator that returns the correct type
# and returns the same sequence regardless of type
def rnd(shape=(), **kwargs):
    if type(shape) == int or type(shape) == float:
        shape = shape,
    x = tf.random_normal(shape, **kwargs, dtype=np.float64)
    if dtype == np.float32:
        x = tf.to_float(x)
    return x.eval()
</code>```

Title: Default initial value for weights

Body:
As sascha observes, constant initial weights aren't a solution in general anyway because you have to break symmetry. Better solution for the particular context in which I came across the problem: a random number generator that gives the same sequence regardless of type.

dtype = np.float64

# Random number generator that returns the correct type
# and returns the same sequence regardless of type
def rnd(shape=(), **kwargs):
    if type(shape) == int or type(shape) == float:
        shape = shape,
    x = tf.random_normal(shape, **kwargs, dtype=np.float64)
    if dtype == np.float32:
        x = tf.to_float(x)
    return x.eval()


问:
Selenium/testNG: How to run your test based on class priority and not on your method priorily from the XML file
If have the following:

Class A
{
  Method M(priority = 2)
}

Class B
{
  Method M(priority = 1)
}
```

<p>Then <code>Class B</code> is going to be executed before <code>Class A</code>. How can I execute <code>Class A</code> first?</p>

<p>The XML file that I am using is:</p>

<pre class="lang-xml prettyprint-override"><code><classes>
  <class name="com.Users.Admin_ManageUsers_AR"/>
  <class name="com.Users.Admin_ManageUsers_AR"/>
</classes>
</code>```

答:
An implicit way to prioritise test class execution is to add an alphabetically ordered prefix in class names.  Like, you have test classes named : login , checkout, logout.
Then rename them as TC01_login , TC02_checkout , TC03_logout. This will automatically prioritise the test execution as per the TC_{serial_number}</p>

Body:
If have the following:

Class A
{
  Method M(priority = 2)
}

Class B
{
  Method M(priority = 1)
}

Then Class B is going to be executed before Class A. How can I execute Class A first?

The XML file that I am using is:

<classes>
  <class name="com.Users.Admin_ManageUsers_AR"/>
  <class name="com.Users.Admin_ManageUsers_AR"/>
</classes>


问:
How to "Decompile" a Bookmarklet?
We all know that bookmarklets are nothing but some
executable javascript code that do some things for us
when we click on them depending on the function that they
are intended to do... My Question is:

For example, I have a Bookmarklet, don't know, something like this one:

```<code>javascript:void(window.open('http://www.pdfdownload.org/web2pdf/Default.aspx?left=0&right=0&top=0&bottom=0&page=0&cURL='+document.location.href));
</code>```

As far as I understand, the bookmarklet code (with the "&cURL=" thing) takes the URL that is in the adress bar of the browser and then do something with it in order to get a result. Something similar can be done with a selection, by changing some parameters in the bookmarklet (Like with the "Search selection in Google Maps" one) and some others.

How can I "decompile" a bookmarklet in order to make it take the desired data (in this case an URL) from a form?

For example, let's say I want to use the above bookmarklet in a webpage to provide a form that let's the user input a URL and then click a button to get the result.

I've seen other bookmarklets that get the URL from a "?input=" and others from a "?url="

How can I pass bookmarklet's functions to a form?

答:
In a bookmarklet it's actually easiest to use prompt('Please enter a URL', 'default value') instead of the variable. Displaying a form in the current webpage is rather cumbersome.

If you just need one user-entered value, prompt() is an easy to use alternative to ask a user for more info. (Of course you can use multiple prompt() calls, too, but this will probably lead to a confused user)

ContentLicense: CC BY-SA 2.5

Title: How to "Decompile" a Bookmarklet?

Body:
We all know that bookmarklets are nothing but some
executable javascript code that do some things for us
when we click on them depending on the function that they
are intended to do... My Question is:

For example, I have a Bookmarklet, don't know, something like this one:

javascript:void(window.open('http://www.pdfdownload.org/web2pdf/Default.aspx?left=0&right=0&top=0&bottom=0&page=0&cURL='+document.location.href));

As far as I understand, the bookmarklet code (with the "&cURL=" thing) takes the URL that is in the adress bar of the browser and then do something with it in order to get a result. Something similar can be done with a selection, by changing some parameters in the bookmarklet (Like with the "Search selection in Google Maps" one) and some others.

How can I "decompile" a bookmarklet in order to make it take the desired data (in this case an URL) from a form?

For example, let's say I want to use the above bookmarklet in a webpage to provide a form that let's the user input a URL and then click a button to get the result.

I've seen other bookmarklets that get the URL from a "?input=" and others from a "?url="

How can I pass bookmarklet's functions to a form?


问:
How do i modify my css code to output like this picture
I have this in my style.php file

.msg{
    text-transform: none;
    text-align: center;
    font-weight: bold;
    color: red;
    border: solid 1px #fc0;
    background-color: #EFEF00;       -webkit-border-radius: 0.3em;
    border-radius: 0.3em;             margin: 6px;
    padding: 6px;
    tex
}
#header{
    height: 50px;
    background: #decf9c;
    color: black;
    border-bottom: 2px solid       #663333;
    width: 98%;
}
.b_head{
    padding: 6px;
    background: #663333;
    color: #ffffff;
    font-weight: bold;
    text-align: center;
}

.cart {
    background-image: url('http://www.pvhc.net/img180/xewlwqfroahrisfwokkc.png');
    background-size: contain;
    background-repeat: no-repeat;
    background-color: #663333;
    width: 35px;
    height: 35px;
    border: 1px solid #fff;
    outline: 3px solid #8174f7;
    position: absolute ;
    right: 6px;
    center: 6px;
}

.badge {
    position: absolute;
    left: -15px;
    bottom: -15px;
    font-weight: 700;
    font-family: sans-serif;
    font-size: 20px;
    color: #fff;
    background-color: #663333;
    border: 2px solid #fff;
    padding: 3px;
    width: 12px;
    height: 12px;
    text-align: center;
}

.badge:empty{
    display: none;
}

.content{
    background-color: #fff;
    color: #000;
    padding:8px;
    text-align:center;
    margin-top:62px;
}

.red{
    color: red;
}

.info_post{
    background-color: #ffffcc;
    color: #000;
    font-weight:;
    border:1px solid #663333;
    padding: 4px;
    margin-top: 3px;
}```
</div>
</div>
</p>

<p><strong>I have this in my php file</strong></p>

```<?php
    require("init.php");
    include"style.php";
    if(isset($_SESSION["cart_array"]) && is_array($_SESSION["cart_array"])) {
        $cart = 0;
        $cartTotal = 0;
        foreach ($_SESSION["cart_array"] as $each_item) {
            $id = $each_item["item_id"];
            $qty = $each_item["quantity"];
            $cart += $qty;
            $sql = mysqli_query($conn, "SELECT * FROM promo WHERE code='$id' LIMIT 1");
            while($row=mysqli_fetch_array($sql)){
                $cartTotal += ( $row["price"] * $qty);
                if($cartTotal > 999) {
                    $cartTotal = number_format($cartTotal);
                }
            }
        }
    }
    echo "

 bulk SMS, and E-xchange market

";
    echo "
$cart
";
    echo "

#$cartTotal

login

";
    echo "
<form action='#' method='POST'>
Check code:
<input type='text' name='book' placeholder='Enter  Username' size='17'> <input type='submit' name='submit' maxlength ='2' size='2' value='PRINT'></form>
";
?>
```

currently the output look like this:

In my achievement I want it to look like DEMO:

Thanks in advance

答:
Try adding ::</p>

```<code>.cart {position: relative;}
.badge {bottom: -30px;}
</code>```

Body:
I have this in my style.php file

.msg{
    text-transform: none;
    text-align: center;
    font-weight: bold;
    color: red;
    border: solid 1px #fc0;
    background-color: #EFEF00;       -webkit-border-radius: 0.3em;
    border-radius: 0.3em;             margin: 6px;
    padding: 6px;
    tex
}
#header{
    height: 50px;
    background: #decf9c;
    color: black;
    border-bottom: 2px solid       #663333;
    width: 98%;
}
.b_head{
    padding: 6px;
    background: #663333;
    color: #ffffff;
    font-weight: bold;
    text-align: center;
}

.cart {
    background-image: url('http://www.pvhc.net/img180/xewlwqfroahrisfwokkc.png');
    background-size: contain;
    background-repeat: no-repeat;
    background-color: #663333;
    width: 35px;
    height: 35px;
    border: 1px solid #fff;
    outline: 3px solid #8174f7;
    position: absolute ;
    right: 6px;
    center: 6px;
}

.badge {
    position: absolute;
    left: -15px;
    bottom: -15px;
    font-weight: 700;
    font-family: sans-serif;
    font-size: 20px;
    color: #fff;
    background-color: #663333;
    border: 2px solid #fff;
    padding: 3px;
    width: 12px;
    height: 12px;
    text-align: center;
}

.badge:empty{
    display: none;
}

.content{
    background-color: #fff;
    color: #000;
    padding:8px;
    text-align:center;
    margin-top:62px;
}

.red{
    color: red;
}

.info_post{
    background-color: #ffffcc;
    color: #000;
    font-weight:;
    border:1px solid #663333;
    padding: 4px;
    margin-top: 3px;
}

I have this in my php file

<?php
    require("init.php");
    include"style.php";
    if(isset($_SESSION["cart_array"]) && is_array($_SESSION["cart_array"])) {
        $cart = 0;
        $cartTotal = 0;
        foreach ($_SESSION["cart_array"] as $each_item) {
            $id = $each_item["item_id"];
            $qty = $each_item["quantity"];
            $cart += $qty;
            $sql = mysqli_query($conn, "SELECT * FROM promo WHERE code='$id' LIMIT 1");
            while($row=mysqli_fetch_array($sql)){
                $cartTotal += ( $row["price"] * $qty);
                if($cartTotal > 999) {
                    $cartTotal = number_format($cartTotal);
                }
            }
        }
    }
    echo "

 bulk SMS, and E-xchange market

";
    echo "
$cart
";
    echo "

#$cartTotal

login

";
    echo "
<form action='#' method='POST'>
Check code:
<input type='text' name='book' placeholder='Enter  Username' size='17'> <input type='submit' name='submit' maxlength ='2' size='2' value='PRINT'></form>
";
?>

currently the output look like this:

In my achievement I want it to look like DEMO:

Thanks in advance

Body:
Try adding ::

.cart {position: relative;}
.badge {bottom: -30px;}


问:
React-Native Piker color
I would like change the default color Picker (not item, the Picker view). I've try to add style={{ color: "white" }}, but no result.

```<code><Picker
  selectedValue={this.state.language}
  onValueChange={(itemValue, itemIndex) => this.setState({ language: itemValue })}
  style={{ color: "white" }}
>
  <Picker.Item label="EN" value="en-EN" />
  <Picker.Item label="FR" value="fr-FR" />
</Picker>
</code>```

I've no warning and no error.
Any one have idea ?

Thank you community !

答:
Have you tried it:

```<code><View style={{ backgroundColor: "#f456" }}>
     <Picker selectedValue="a">
          <Picker.Item value="a" label="a" />
     </Picker>
</View>
</code>```

Works fine in my case.

Title: React-Native Piker color

Body:
I would like change the default color Picker (not item, the Picker view). I've try to add style={{ color: "white" }}, but no result.

<Picker
  selectedValue={this.state.language}
  onValueChange={(itemValue, itemIndex) => this.setState({ language: itemValue })}
  style={{ color: "white" }}
>
  <Picker.Item label="EN" value="en-EN" />
  <Picker.Item label="FR" value="fr-FR" />
</Picker>

I've no warning and no error.
Any one have idea ?

Thank you community !

Body:
Have you tried it:

<View style={{ backgroundColor: "#f456" }}>
     <Picker selectedValue="a">
          <Picker.Item value="a" label="a" />
     </Picker>
</View>

Works fine in my case.


问:
Make Gradle use Maven local repository for downloading artifacts
I know I can configure Gradle to use local Maven repository

```<code>repositories {
    mavenLocal()
    mavenCentral()
}
</code>```

Can I configure Gradle to download into Local (maven) repository? (So that Maven would also be able to use those jars)

ref Gradle configuration to use maven local repository

答:
It should be as simple as

```<code>apply plugin: 'maven'
apply plugin: 'java'
dependencies {
    mavenLocal()
}
</code>```

And

```<code>gradle install
</code>```

More info here

ContentLicense: CC BY-SA 4.0

Body:
I know I can configure Gradle to use local Maven repository

repositories {
    mavenLocal()
    mavenCentral()
}

Can I configure Gradle to download into Local (maven) repository? (So that Maven would also be able to use those jars)

ref Gradle configuration to use maven local repository

Body:
It should be as simple as

apply plugin: 'maven'
apply plugin: 'java'
dependencies {
    mavenLocal()
}

And

gradle install

More info here


问:
How can I center an element's side to middle of an other element?
I'm using ConstraintLayout and would like to center an element's left side to the middle of an element which is above it.

```<code>[I'm Element 1]

        | // middle of element 1

        [Element 2 should start at middle of element 1]
</code>```

Is this possible without writing code, and if yes, how?

答:
The solution was the following: Instead of a guideline, use a 1px * 1px View as a guideline, position it to the center of element1 with layout_constraintLeft_toLeftOf & layout_constraintRight_toRightOf attributes and then align element2 to this View guideline:

```<code><android.support.constraint.ConstraintLayout>
    ...

    <TextView
            android:id="@+id/element1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    <View
            android:id="@+id/guideline"
            android:layout_width="1px"
            android:layout_height="1px"
            android:background="#00000000"
            app:layout_constraintLeft_toLeftOf="@id/element1"
            app:layout_constraintRight_toRightOf="@id/element1" />

    <TextView
            android:id="@+id/element2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintLeft_toRightOf="@id/guideline"
            app:layout_constraintTop_toBottomOf="@id/element1" />

    ...
</android.support.constraint.ConstraintLayout>
</code>```

Body:
I'm using ConstraintLayout and would like to center an element's left side to the middle of an element which is above it.

[I'm Element 1]

        | // middle of element 1

        [Element 2 should start at middle of element 1]

Is this possible without writing code, and if yes, how?

Body:
The solution was the following: Instead of a guideline, use a 1px * 1px View as a guideline, position it to the center of element1 with layout_constraintLeft_toLeftOf & layout_constraintRight_toRightOf attributes and then align element2 to this View guideline:

<android.support.constraint.ConstraintLayout>
    ...

    <TextView
            android:id="@+id/element1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    <View
            android:id="@+id/guideline"
            android:layout_width="1px"
            android:layout_height="1px"
            android:background="#00000000"
            app:layout_constraintLeft_toLeftOf="@id/element1"
            app:layout_constraintRight_toRightOf="@id/element1" />

    <TextView
            android:id="@+id/element2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintLeft_toRightOf="@id/guideline"
            app:layout_constraintTop_toBottomOf="@id/element1" />

    ...
</android.support.constraint.ConstraintLayout>


问:
How to set up Identity in an ASP.Net core project using EF 6.0 in a separate class library
A while ago I asked this question about using EF with ASP.Net core, and this is working great.  Now that I want to add ASP.Net Identity, I'm wondering if the best approach is to add identity logic to the separate project with regular / non-core EF, or into the main core project with EF core, or something else.  I see a lot of pages that discuss EF core, but I would prefer to use the same context everywhere, and I would prefer to use regular EF as I am currently doing.  I'm looking for what would be a clean / best practices approach here, I have been using regular EF since to my knowledge EF core 1.0 doesn't support stored procs, and I prefer to continue to use a database first approach anyway.  Appreciate any help that gets me out of the quicksand.

NOTE: My 'User' table (called something else) has some existing profile data in it; I intend to use this as my Identity User table.

答:
Have you considered having an explicit Identity service that can issue tokens based on your existing identity database?

IdentityServer4 is an OpenId Connect provider. It supports EF so that you can use your existing user data to perform authentication.

The push now is towards .NET Core and it would be a good step in that direction to have a separate project dedicated to handling identity that uses IdentityServer4 and EF Core.


问:
SwaggerUI/YAML - should NOT have additional properties additionalProperty: requestBody
Designing an API using editor.swagger.io I find myself unable to add a requestBody attribute, getting an error I cannot address:

```<code>Schema error at paths['/projects/{projectId}/user'].post
should NOT have additional properties
additionalProperty: requestBody
Jump to line 91
</code>```

I don't understand what I'm doing wrong, especially after looking at the requestBody documentation. Research has brought me nothing other than the tendency for errors to be misleading.

EDIT: From what the answers here have shown, it looks like the editor is supposed to use OpenAPI 2.0, but actually expects 3.0 while returning errors for both. I'd use some help on what to use, given that I've included a

```<code>swagger: "2.0"
</code>```

line at the beginning of the document.
While testing with openapi: 3.0.0 as shown by @Mike in his answer, I just get more errors about allowed additional properties.

Here's what's generating the error, line 91 being post: .

```<code>/projects/{projectId}/user:
      post:
        tags:
        - projects
        summary: Modify project user.
        operationId: modifyProjectUser
        parameters:
        - name: projectId
          in: path
          description: ID of the project
          required: true
          type: integer
          format: int32
        requestBody:
          content:
            application/json:
              schema:
              $ref: '#/definitions/User'
        responses:
          "200":
            description: Successful operation
            schema:
              type: array
              items:
                $ref: "#/definitions/User"
        security:
        - api_key: []
</code>```

答:
I got clarifications from an external source, so here's what I've learned:

Specifying swagger: 2.0 also means that the OpenAPI Specification 2.0.0 is expected by the editor, whereas I thought it used OAS 3.
I'm still unsure about why in: body did not work in the first place but I've added quotes around "body", which made the error disappear. Then I tried removing the quotes and it worked fine.

The editor doesn't seem very reliable when it comes to error reporting.

Body:
Designing an API using editor.swagger.io I find myself unable to add a requestBody attribute, getting an error I cannot address:

Schema error at paths['/projects/{projectId}/user'].post
should NOT have additional properties
additionalProperty: requestBody
Jump to line 91

I don't understand what I'm doing wrong, especially after looking at the requestBody documentation. Research has brought me nothing other than the tendency for errors to be misleading.

EDIT: From what the answers here have shown, it looks like the editor is supposed to use OpenAPI 2.0, but actually expects 3.0 while returning errors for both. I'd use some help on what to use, given that I've included a

swagger: "2.0"

line at the beginning of the document.
While testing with openapi: 3.0.0 as shown by @Mike in his answer, I just get more errors about allowed additional properties.

Here's what's generating the error, line 91 being post: .

/projects/{projectId}/user:
      post:
        tags:
        - projects
        summary: Modify project user.
        operationId: modifyProjectUser
        parameters:
        - name: projectId
          in: path
          description: ID of the project
          required: true
          type: integer
          format: int32
        requestBody:
          content:
            application/json:
              schema:
              $ref: '#/definitions/User'
        responses:
          "200":
            description: Successful operation
            schema:
              type: array
              items:
                $ref: "#/definitions/User"
        security:
        - api_key: []


问:
Regex: Match all combinations of 2 digits except for specified
I need two regexes:

Match all two-digit combinations except for "00" (so 01, 02, ... 99 is fine)

Match all two-digit combinations except for "00" and "01" (so 02, 03, ... 99 is fine)

I tried with something like ^(00)([0-9][0-9]) for the first one, but it doesn't work. Any help is appreciated.

答:
Match all two-digit combinations except for "00" (so 01, 02, ... 99 is fine)

```<code>^(?!00)[0-9]{2}$
</code>```

Match all two-digit combinations except for "00" and "01" (so 02, 03, ... 99 is fine)

```<code>^(?!0[10])[0-9]{2}$
</code>```

Body:
Match all two-digit combinations except for "00" (so 01, 02, ... 99 is fine)

^(?!00)[0-9]{2}$

Match all two-digit combinations except for "00" and "01" (so 02, 03, ... 99 is fine)

^(?!0[10])[0-9]{2}$


答:
I'd check if the element is being animated and trigger .stop() or .animate() again:

```<code>$(".stop li").click(function() {
  if ($(this).is(':animated')) {
    $(this).stop();
  } else {
    $(this).animate({
      width: "100px"
    }, 1000);
    $(this).animate({
      width: "80px"
    }, 1000);
  }
});
</code>```

JsFiddle demo

Title: Cancel Animation on Click instead of hover - JQuery

Body:
I'd check if the element is being animated and trigger .stop() or .animate() again:

$(".stop li").click(function() {
  if ($(this).is(':animated')) {
    $(this).stop();
  } else {
    $(this).animate({
      width: "100px"
    }, 1000);
    $(this).animate({
      width: "80px"
    }, 1000);
  }
});

JsFiddle demo


问:
Pandas DataFrame: test if index name is set
I have a DataFrame with multiple columns of which one is of type datetime. Sometimes this column is used as index via df.set_index(...).

On other occasions I need to reset that index in order to keep the datetime column. Now I'm looking for a way how to check if the dataframe has a default index or not. I tried this, but this is not working for all cases:

```<code>if df.index.name is not None:
    df.reset_index(inplace=True)
</code>```

I could test if the index is of type datetime, but I really wonder if there is a general method like df.is_index_set(). Any recommendations?

答:
You should not test the index.name attribute as it is not set in all scenarios. You can do the following tests :

```<code>In[13]:

df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
type(df.index) == pd.RangeIndex

Out[13]: True

In[14]:
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'), index=pd.date_range(dt.datetime(2017,1,1), periods=5))
df.index.is_all_dates

Out[14]: True
</code>```

So the default index is a pd.RangeIndex, if your index is a DatetimeIndex you can just call is_all_dates or compare against pd.DatetimeIndex

The first method will handle even if you set the index to an int column which is monotonic:

```<code>In[27]:
df = pd.DataFrame({'a':[0,1,2,3,4], 'b':35,'c':np.random.randn(5)})
df = df.set_index('a')
type(df.index) == pd.RangeIndex

Out[27]: False
</code>```

the index dtype here is an Int64Index:

```<code>In[28]:
df.index

Out[28]: Int64Index([0, 1, 2, 3, 4], dtype='int64', name='a')
</code>```

Body:
I have a DataFrame with multiple columns of which one is of type datetime. Sometimes this column is used as index via df.set_index(...).

On other occasions I need to reset that index in order to keep the datetime column. Now I'm looking for a way how to check if the dataframe has a default index or not. I tried this, but this is not working for all cases:

if df.index.name is not None:
    df.reset_index(inplace=True)

I could test if the index is of type datetime, but I really wonder if there is a general method like df.is_index_set(). Any recommendations?

Body:
You should not test the index.name attribute as it is not set in all scenarios. You can do the following tests :

In[13]:

df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
type(df.index) == pd.RangeIndex

Out[13]: True

In[14]:
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'), index=pd.date_range(dt.datetime(2017,1,1), periods=5))
df.index.is_all_dates

Out[14]: True

So the default index is a pd.RangeIndex, if your index is a DatetimeIndex you can just call is_all_dates or compare against pd.DatetimeIndex

The first method will handle even if you set the index to an int column which is monotonic:

In[27]:
df = pd.DataFrame({'a':[0,1,2,3,4], 'b':35,'c':np.random.randn(5)})
df = df.set_index('a')
type(df.index) == pd.RangeIndex

Out[27]: False

the index dtype here is an Int64Index:

In[28]:
df.index

Out[28]: Int64Index([0, 1, 2, 3, 4], dtype='int64', name='a')


问:
APP Crash : Fatal Exception: io.reactivex.exceptions.CompositeException
Using retrofit I call API for getting list, but when no data found then I am calling onErrorGetOccasion method and in that I got HttpException and for that I handle it as shown in code.

Now my issue is sometimes in onErrorGetOccasion method I got Fatal

```<code>Exception: io.reactivex.exceptions.CompositeException this error and app crash.
</code>```

Any suggestion for this?

```<code>//Get Occasion API
private void callGetOccasionAPI(String pageIndex, boolean isDialogShown) {

    if (NetworkUtils.isConnected()) {
        if (mPageCount == 1 && isDialogShown)
            showProgressDialog(mContext);
        RetrofitAdapter.createRetroServiceWithSessionToken(mContext)
                .getOccasion(pageIndex)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::onSuccessGetOccasion, this::onErrorGetOccasion);
    } else {
        SnackBarUtils.defaultSnackBar(getString(R.string.error_no_internet), mRootView);
    }
}

private void onErrorGetOccasion(Throwable throwable) {
    hideProgressDialog();
    if (throwable instanceof HttpException) {
        ResponseBody body = ((HttpException) throwable).response().errorBody();
        Utils.setLog(body != null ? body.toString() : null);
        try {
            if (body != null) {
                if (body.string().contains(mContext.getString(R.string.msg_event_not_found))) {
                    if (mPageCount == 1) {
                        mTxtRecordNotFound.setVisibility(View.VISIBLE);
                        mRecyclerView.setVisibility(View.INVISIBLE);
                    }
                } else {
                    SnackBarUtils.errorSnackBar(getString(R.string.error_api), mRootView, null);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            Crashlytics.log(e.getMessage());
        }
    }
}
</code>```

答:
CompositeException is usually thrown when your error handler itself throws an exception when it's handling an error thrown in the stream.

Make sure your error handling code is not throwing any exceptions.

Usually the stack trace will have the root cause below the CompositeException, prefixed with Caused by.

Body:
Using retrofit I call API for getting list, but when no data found then I am calling onErrorGetOccasion method and in that I got HttpException and for that I handle it as shown in code.

Now my issue is sometimes in onErrorGetOccasion method I got Fatal

Exception: io.reactivex.exceptions.CompositeException this error and app crash.

Any suggestion for this?

//Get Occasion API
private void callGetOccasionAPI(String pageIndex, boolean isDialogShown) {

    if (NetworkUtils.isConnected()) {
        if (mPageCount == 1 && isDialogShown)
            showProgressDialog(mContext);
        RetrofitAdapter.createRetroServiceWithSessionToken(mContext)
                .getOccasion(pageIndex)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::onSuccessGetOccasion, this::onErrorGetOccasion);
    } else {
        SnackBarUtils.defaultSnackBar(getString(R.string.error_no_internet), mRootView);
    }
}

private void onErrorGetOccasion(Throwable throwable) {
    hideProgressDialog();
    if (throwable instanceof HttpException) {
        ResponseBody body = ((HttpException) throwable).response().errorBody();
        Utils.setLog(body != null ? body.toString() : null);
        try {
            if (body != null) {
                if (body.string().contains(mContext.getString(R.string.msg_event_not_found))) {
                    if (mPageCount == 1) {
                        mTxtRecordNotFound.setVisibility(View.VISIBLE);
                        mRecyclerView.setVisibility(View.INVISIBLE);
                    }
                } else {
                    SnackBarUtils.errorSnackBar(getString(R.string.error_api), mRootView, null);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            Crashlytics.log(e.getMessage());
        }
    }
}


问:
Encoding issue in python while using w2v
I'm writing my first app in python to use word2vec model.
Here is my simple code

```<code>import gensim, logging
import sys
import warnings
from gensim.models import Word2Vec

logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

def main():
    ####LOAD MODEL
    model = Word2Vec.load_word2vec_format('models/vec-cbow.txt', binary=False)
    model.similarity('man', 'women')

if __name__ == '__main__':
    with warnings.catch_warnings():
        warnings.simplefilter("error")
        #warnings.simplefilter("ignore")
    main()
</code>```

I getting this the following error:

```<code>UnicodeDecodeError: 'utf8' codec can't decode bytes in position 96-97: invalid continuation byte
</code>```

I tried solving it by adding these two lines, but I'm still getting the error.

```<code>reload(sys)  # Reload does the trick!
sys.setdefaultencoding('UTF8') #UTF8 #latin-1
</code>```

The w2v model was trained on English sentences.

EDIT: Here is the full stack:

```<code>**%run "...\getSimilarity.py"**
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
**...\getSimilarity.py in <module>()**
     64         warnings.simplefilter("error")
     65         #warnings.simplefilter("ignore")
---> 66     main()

**...\getSimilarity.py in main()**
     30     ####LOAD MODEL
---> 31     model = Word2Vec.load_word2vec_format('models/vec-cbow.txt', binary=False)  # C binary format
     32     model.similarity('man', 'women')

**...\AppData\Local\Enthought\Canopy\User\lib\site-packages\gensim-0.12.4-py2.7-win-amd64.egg\gensim\models\word2vec.pyc in load_word2vec_format(cls, fname, fvocab, binary, encoding, unicode_errors)**
   1090             else:
   1091                 for line_no, line in enumerate(fin):
-> 1092                     parts = utils.to_unicode(line.rstrip(), encoding=encoding, errors=unicode_errors).split(" ")
   1093                     if len(parts) != vector_size + 1:
   1094                         raise ValueError("invalid vector on line %s (is this really the text format?)" % (line_no))

**...\AppData\Local\Enthought\Canopy\User\lib\site-packages\gensim-0.12.4-py2.7-win-amd64.egg\gensim\utils.pyc in any2unicode(text, encoding, errors)**
    215     if isinstance(text, unicode):
    216         return text
--> 217     return unicode(text, encoding, errors=errors)
    218 to_unicode = any2unicode
    219

**...\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.6.2.3262.win-x86_64\lib\encodings\utf_8.pyc in decode(input, errors)**
     14
     15 def decode(input, errors='strict'):
---> 16     return codecs.utf_8_decode(input, errors, True)
     17
     18 class IncrementalEncoder(codecs.IncrementalEncoder):

**UnicodeDecodeError: 'utf8' codec can't decode bytes in position 96-97: invalid continuation byte**
</code>```

Any hints how to solve the problem?
Thanks in advance.

答:
From the gensim FAQ you can that option about setting unicode_errors as 'ignore' or 'replace', which seems to work in some occasions but not all.

But if you look at the specific help of the function, there is also this:

```<code>binary is a boolean indicating whether the data is in binary word2vec format
</code>```

This is beause the word2vec model is saved as binary and not as any encoded string. Therefore, just setting binary = True should work in all these cases.

For example, if you are trying to use the google pre-trained model from here, this should work:

```<code>google_model = gensim.models.KeyedVectors.load_word2vec_format('./GoogleNews-vectors-negative300.bin', binary = True)
</code>```

Hope this helps!

Body:
I'm writing my first app in python to use word2vec model.
Here is my simple code

import gensim, logging
import sys
import warnings
from gensim.models import Word2Vec

logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

def main():
    ####LOAD MODEL
    model = Word2Vec.load_word2vec_format('models/vec-cbow.txt', binary=False)
    model.similarity('man', 'women')

if __name__ == '__main__':
    with warnings.catch_warnings():
        warnings.simplefilter("error")
        #warnings.simplefilter("ignore")
    main()

I getting this the following error:

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 96-97: invalid continuation byte

I tried solving it by adding these two lines, but I'm still getting the error.

reload(sys)  # Reload does the trick!
sys.setdefaultencoding('UTF8') #UTF8 #latin-1

The w2v model was trained on English sentences.

EDIT: Here is the full stack:

**%run "...\getSimilarity.py"**
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
**...\getSimilarity.py in <module>()**
     64         warnings.simplefilter("error")
     65         #warnings.simplefilter("ignore")
---> 66     main()

**...\getSimilarity.py in main()**
     30     ####LOAD MODEL
---> 31     model = Word2Vec.load_word2vec_format('models/vec-cbow.txt', binary=False)  # C binary format
     32     model.similarity('man', 'women')

**...\AppData\Local\Enthought\Canopy\User\lib\site-packages\gensim-0.12.4-py2.7-win-amd64.egg\gensim\models\word2vec.pyc in load_word2vec_format(cls, fname, fvocab, binary, encoding, unicode_errors)**
   1090             else:
   1091                 for line_no, line in enumerate(fin):
-> 1092                     parts = utils.to_unicode(line.rstrip(), encoding=encoding, errors=unicode_errors).split(" ")
   1093                     if len(parts) != vector_size + 1:
   1094                         raise ValueError("invalid vector on line %s (is this really the text format?)" % (line_no))

**...\AppData\Local\Enthought\Canopy\User\lib\site-packages\gensim-0.12.4-py2.7-win-amd64.egg\gensim\utils.pyc in any2unicode(text, encoding, errors)**
    215     if isinstance(text, unicode):
    216         return text
--> 217     return unicode(text, encoding, errors=errors)
    218 to_unicode = any2unicode
    219

**...\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.6.2.3262.win-x86_64\lib\encodings\utf_8.pyc in decode(input, errors)**
     14
     15 def decode(input, errors='strict'):
---> 16     return codecs.utf_8_decode(input, errors, True)
     17
     18 class IncrementalEncoder(codecs.IncrementalEncoder):

**UnicodeDecodeError: 'utf8' codec can't decode bytes in position 96-97: invalid continuation byte**

Any hints how to solve the problem?
Thanks in advance.

Body:
From the gensim FAQ you can that option about setting unicode_errors as 'ignore' or 'replace', which seems to work in some occasions but not all.

But if you look at the specific help of the function, there is also this:

binary is a boolean indicating whether the data is in binary word2vec format

This is beause the word2vec model is saved as binary and not as any encoded string. Therefore, just setting binary = True should work in all these cases.

For example, if you are trying to use the google pre-trained model from here, this should work:

google_model = gensim.models.KeyedVectors.load_word2vec_format('./GoogleNews-vectors-negative300.bin', binary = True)

Hope this helps!


问:
What is the proper way to copy InventTable in ax 2012?
In previous versions, there was InventTable and InventTableModule(there were more but they often could be ignored), so copying an an item was easy with buf2buf and replacing itemId.

In ax2012 there are dozens of Eco* tables all over the place so copying them all would is much more error prone (easier to forget something).

What's proper way to copy an item with all its attributes values? Manual copy of tables? Axd classes? Ax classes? Some other mechanism?

答:
As far as I know there aren't any classes available that allow you to copy an item out of the box so you'll have to write your own code to copy all the data.

I agree the new table structure makes it a bit cumbersome but you could start with the code as explained in this blog post

Basically the class allows you to

Copy product attributes and categories

Delete product attributes

Get product attributes

Set product attributes

Needless to say you will have to review the code to see if it meets all your requirements, but it could be a good starting point


问:
Find a value in a string and output it to a text file via a batch file
I'm trying to output a numeral value from a ffmpeg output and add it to a text file.

I'd like to run it as a single line from a batch file where I have all my variables set up already, but I'm not sure if it's even possible.

This is the output string, from where i want to copy the average value:

```<code>[Parsed_psnr_0 @ 0000000003763ec0] PSNR y:18.250891 u:33.358190 v:36.566447 average:19.962586 min:11.944585 max:41.255356
</code>```

In this case 19.962586, i got several 100 files to process and the number is always different.

Here is a weak attempt out of ignorance to do that:

```<code>powershell Get-Content -Path "'D:\work folder\test.txt'" | -match 'average:(.+?) min:' | Out-File -Path "D:\work folder\test_result.txt"
</code>```

not working and neither did the 100 variations I tried, but I've included it as a rough idea of what I am trying.

答:
the following is a working powershell solution:

```<code>powershell -Command "(Get-Content -Path 'C:\file.txt').Split(' ') | foreach { if ($_ -match 'average'){ $_ -replace """[^^.0-9]""" , '' | Out-File -FilePath 'D:\file_output.txt' -Append}}"
</code>```

credit goes to Adrian C.

Body:
I'm trying to output a numeral value from a ffmpeg output and add it to a text file.

I'd like to run it as a single line from a batch file where I have all my variables set up already, but I'm not sure if it's even possible.

This is the output string, from where i want to copy the average value:

[Parsed_psnr_0 @ 0000000003763ec0] PSNR y:18.250891 u:33.358190 v:36.566447 average:19.962586 min:11.944585 max:41.255356

In this case 19.962586, i got several 100 files to process and the number is always different.

Here is a weak attempt out of ignorance to do that:

powershell Get-Content -Path "'D:\work folder\test.txt'" | -match 'average:(.+?) min:' | Out-File -Path "D:\work folder\test_result.txt"

not working and neither did the 100 variations I tried, but I've included it as a rough idea of what I am trying.

Body:
the following is a working powershell solution:

powershell -Command "(Get-Content -Path 'C:\file.txt').Split(' ') | foreach { if ($_ -match 'average'){ $_ -replace """[^^.0-9]""" , '' | Out-File -FilePath 'D:\file_output.txt' -Append}}"

credit goes to Adrian C.


问:
Laravel Generate Migration from existing Model

How can I create migration file from existing model in Laravel or model from existing migration?
</p>

答:
For the model, just create a model, there isn't anything special, just make sure to set the $table if not following convention.

For generating migrations from an existing Database schema there is a package:

Xethron - Laravel Migration Generator


问:
Export a dynamic array from a React component to another component
I built a react component that imports a Json file into an array to map the result. I need that array in another component. I don't know if I must built this component inside the new component or if there's a method to export the needed array (data). The array source is updated every 4 seconds.

Thanks for your help.

My first component is:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

class Ramas extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: []
        };
    }

    componentDidMount() {
        const fetchData = () => {
            axios
            .get('http://localhost:8888/dp_8/fuente/procesos_arbol.json')
            .then(({ data })=> {
                this.setState({
                    data: data
                });
                console.log(data);
            })
            .catch(()=> {console.log('no recibido');});
        };
        fetchData();
        this.update = setInterval(fetchData, 4000);
    } //  final componentDidMount

    render() {
        const initialData = this.state.data.map((el) => {
            return (
        <p>id={ el.id } | name - { el.name } | padre - {el.parent}</p>
      );
        });

        return (<div className="datos_iniciales">
      { initialData }
      </div>);
    }

}

ReactDOM.render(
  <Ramas />,
  document.getElementById('container')
);
</code>```

答:
make one top level component that can contain the two components.

in the Ramas component ->

```<code>const updatedData = setInterval(fetchData, 4000);
this.props.datasource(updatedData);
</code>```

write a new top level component ->

```<code>class TopComponent Extends React.Component{
  state = {data: ''}

  handleDataUpdate = (updatedData) => {
     this.setState({data: updatedData});
  }

  render = () => {
      <Ramas datasource={this.handleDataUpdate}>
          <SecondComponent updatedData={this.state.data}>
      </Ramas>
  }

}
</code>```

now from SecondComponent updatedData prop you can get the fresh data

By the way it is in ES7 syntax I wrote

Body:
I built a react component that imports a Json file into an array to map the result. I need that array in another component. I don't know if I must built this component inside the new component or if there's a method to export the needed array (data). The array source is updated every 4 seconds.

Thanks for your help.

My first component is:

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

class Ramas extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: []
        };
    }

    componentDidMount() {
        const fetchData = () => {
            axios
            .get('http://localhost:8888/dp_8/fuente/procesos_arbol.json')
            .then(({ data })=> {
                this.setState({
                    data: data
                });
                console.log(data);
            })
            .catch(()=> {console.log('no recibido');});
        };
        fetchData();
        this.update = setInterval(fetchData, 4000);
    } //  final componentDidMount

    render() {
        const initialData = this.state.data.map((el) => {
            return (

id={ el.id } | name - { el.name } | padre - {el.parent}

      );
        });

        return (

      { initialData }

);
    }

}

ReactDOM.render(
  <Ramas />,
  document.getElementById('container')
);

Body:
make one top level component that can contain the two components.

in the Ramas component ->

const updatedData = setInterval(fetchData, 4000);
this.props.datasource(updatedData);

write a new top level component ->

class TopComponent Extends React.Component{
  state = {data: ''}

  handleDataUpdate = (updatedData) => {
     this.setState({data: updatedData});
  }

  render = () => {
      <Ramas datasource={this.handleDataUpdate}>
          <SecondComponent updatedData={this.state.data}>
      </Ramas>
  }

}

now from SecondComponent updatedData prop you can get the fresh data

By the way it is in ES7 syntax I wrote


问:
SQL COUNT returns "Null value eliminated" error on left join
I have a bit of code that looks roughly like this:

```<code>DECLARE @Test int, @LookupVal varchar(50) = 'test'
SELECT @Test = COUNT(M.MembershipID)
FROM dbo.Users U WITH (NOLOCK)
LEFT JOIN dbo.UserMemberships M WITH (NOLOCK) ON M.UserID = U.UserID
AND M.MembershipID = @LookupVal
SELECT @Test
</code>```

This works fine when the lookup returns multiple rows; the second SELECT returns the number of rows. If there are no MembershipIDs with value 'test' it correctly shows 0, but the system log also show the error message "Warning: Null value is eliminated by an aggregate or other SET operation."

I know I could disable this with SET ANSI_WARNINGS OFF. However, I am convinced this must be some setting I (or a coworker) have accidentally changed on our instance of SQL Server. I have written lots of statements in this format throughout a large code base, and I have never before seen this error until today. I want to know what setting might have changed, so I can switch that back.

Another change that fixes it is removing the LEFT; as a regular JOIN this correctly returns the value 0 with no other errors. Also if I simply SELECT COUNT(M.MembershipID) without putting it into the @Test variable, then it simply displays 0 and no error. It is only on a LEFT JOIN with the variable that the error occurs.

NOTE: I am not simply asking about this message, or looking for a way to disable it in this specific case. I want to know why it has suddenly started happening in an old bit of code, specifically caused by the combination of a left join and selecting into a variable.

答:
```<code>Assuming your query output the intended results

DECLARE @Test int, @LookupVal varchar(50) = 'test'
SELECT @Test = COUNT(M.MembershipID)
FROM  dbo.UserMemberships M WITH (NOLOCK)
LEFT JOIN dbo.Users U WITH (NOLOCK) ON M.UserID = U.UserID
WHERE M.MembershipID = @LookupVal
SELECT @Test
</code>```

 OR

```<code>If you want to keep the same format of the query

SELECT @Test = COUNT(ISNULL(M.MembershipID,''))
FROM dbo.Users U WITH (NOLOCK)
LEFT JOIN dbo.UserMemberships M WITH (NOLOCK) ON M.UserID = U.UserID
AND M.MembershipID = @LookupVal
</code>```

Body:
I have a bit of code that looks roughly like this:

DECLARE @Test int, @LookupVal varchar(50) = 'test'
SELECT @Test = COUNT(M.MembershipID)
FROM dbo.Users U WITH (NOLOCK)
LEFT JOIN dbo.UserMemberships M WITH (NOLOCK) ON M.UserID = U.UserID
AND M.MembershipID = @LookupVal
SELECT @Test

This works fine when the lookup returns multiple rows; the second SELECT returns the number of rows. If there are no MembershipIDs with value 'test' it correctly shows 0, but the system log also show the error message "Warning: Null value is eliminated by an aggregate or other SET operation."

I know I could disable this with SET ANSI_WARNINGS OFF. However, I am convinced this must be some setting I (or a coworker) have accidentally changed on our instance of SQL Server. I have written lots of statements in this format throughout a large code base, and I have never before seen this error until today. I want to know what setting might have changed, so I can switch that back.

Another change that fixes it is removing the LEFT; as a regular JOIN this correctly returns the value 0 with no other errors. Also if I simply SELECT COUNT(M.MembershipID) without putting it into the @Test variable, then it simply displays 0 and no error. It is only on a LEFT JOIN with the variable that the error occurs.

NOTE: I am not simply asking about this message, or looking for a way to disable it in this specific case. I want to know why it has suddenly started happening in an old bit of code, specifically caused by the combination of a left join and selecting into a variable.

Body:
Assuming your query output the intended results

DECLARE @Test int, @LookupVal varchar(50) = 'test'
SELECT @Test = COUNT(M.MembershipID)
FROM  dbo.UserMemberships M WITH (NOLOCK)
LEFT JOIN dbo.Users U WITH (NOLOCK) ON M.UserID = U.UserID
WHERE M.MembershipID = @LookupVal
SELECT @Test

 OR

If you want to keep the same format of the query

SELECT @Test = COUNT(ISNULL(M.MembershipID,''))
FROM dbo.Users U WITH (NOLOCK)
LEFT JOIN dbo.UserMemberships M WITH (NOLOCK) ON M.UserID = U.UserID
AND M.MembershipID = @LookupVal


问:
Data Structure in Cassandra
Is there a way to read the SSTable in Cassandra? I see from the documentation that sstabledump is an enterprise version, Is it possible to get the trial version of sstabledump?

Or is there a way to read the SSTable using the existing utilities in Cassandra/bin folder?

答:
sstabledump is also available in apache cassandra.

It can be found in tools/bin directory in cassandra 3.x

Note: sstable2json was replaced by sstabledump in 3.0

Title: Data Structure in Cassandra


问:
Xamarin Forms UWP Sqlite connection, Could not load file or assembly SQLite-net
I am stuck in connecting sqlite with xamarin forms/pcl/uwp application. Following is my code to set path for database

Android (Following works perfectly alright)

```<code>App1.globals.path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
//App1.globals.path=> /data/user/0/com.companyname.App1/files
LoadApplication(new App1.App());
</code>```

UWP (Following does not work)

```<code>App1.globals.path = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
//App1.globals.path => C:\Users\sami.akram\AppData\Local\Packages\8e3de984-9360-4549-a5cc-80071995402b_hy7qfqqm9rwga\LocalState
LoadApplication(new App1.App());
</code>```

Following is the code in App1 (Portable) => Main App

```<code>[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace App1
{

    public class globals
    {
        public static string path = "test.db3";
    }

    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
            var dbPath = System.IO.Path.Combine(globals.path, "test.db3");
            var db = new SQLiteConnection(dbPath);
            SetMainPage();
        }
    }
}
</code>```

Error I face is

Could not load file or assembly 'SQLite-net, Version=1.4.118.0, Culture=neutral, PublicKeyToken=null'. The located assembly's manifest definition does not match the assembly reference

But assembly version should not be any issue as I have installed same sqllite for all projects following image shows it. Note I tried the app with .net 4.5 and .net 4.6 but it results same.

I tried clean solution rebuild solution. Nothing is helping yet, same error could not load assembly..

答:
There's an issue with the "sqlite-net-pcl" NuGet package version 1.4.118.0 that only affects UWP projects referencing a Xamarin.Forms PCL project.

The bug has been fixed with the "sqlite-net-pcl" version 1.5.166-beta.

A couple of issues have been added to the official SQLite-net GitHub page:

Could not load SQLite-net on Xamarin.Forms UWP #627

Version numbers in netstandard1.1 and portable-net45+wp8+wpa81+win8+MonoAndroid10+MonoTouch10+Xamarin.iOS10 #601

Body:
I am stuck in connecting sqlite with xamarin forms/pcl/uwp application. Following is my code to set path for database

Android (Following works perfectly alright)

App1.globals.path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
//App1.globals.path=> /data/user/0/com.companyname.App1/files
LoadApplication(new App1.App());

UWP (Following does not work)

App1.globals.path = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
//App1.globals.path => C:\Users\sami.akram\AppData\Local\Packages\8e3de984-9360-4549-a5cc-80071995402b_hy7qfqqm9rwga\LocalState
LoadApplication(new App1.App());

Following is the code in App1 (Portable) => Main App

[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace App1
{

    public class globals
    {
        public static string path = "test.db3";
    }

    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
            var dbPath = System.IO.Path.Combine(globals.path, "test.db3");
            var db = new SQLiteConnection(dbPath);
            SetMainPage();
        }
    }
}

Error I face is

Could not load file or assembly 'SQLite-net, Version=1.4.118.0, Culture=neutral, PublicKeyToken=null'. The located assembly's manifest definition does not match the assembly reference

But assembly version should not be any issue as I have installed same sqllite for all projects following image shows it. Note I tried the app with .net 4.5 and .net 4.6 but it results same.

I tried clean solution rebuild solution. Nothing is helping yet, same error could not load assembly..


问:
WebSocket handshake error when connection to endpoint
We were using Twilio Video for development of our system, I am able to use the system with my own laptop but working laptops have an error while trying to connect with Chrome browser.

I am getting below error:

```<code>WebSocket connection to 'wss://endpoint.twilio.com/' failed: Error during WebSocket handshake: 'Upgrade' header is missing
</code>```

The full error text is below:

```<code>twilio-video.js:20135 WebSocket connection to 'wss://endpoint.twilio.com/' failed: Error during WebSocket handshake: 'Upgrade' header is missing
connect @ twilio-video.js:20135
Transport @ twilio-video.js:20025
(anonymous) @ twilio-video.js:21181
twilio-video.js:14542 Tue Nov 28 2017 11:07:49 GMT+0300 (Turkey Standard Time) | sip.transport | WebSocket connection error: {"isTrusted":true}
LoggerFactory.print @ twilio-video.js:14542
LoggerFactory.(anonymous function) @ twilio-video.js:14559
Logger.(anonymous function) @ twilio-video.js:14553
onError @ twilio-video.js:20315
ws.onerror @ twilio-video.js:20155
twilio-video.js:14542 Tue Nov 28 2017 11:07:49 GMT+0300 (Turkey Standard Time) | sip.transport | WebSocket disconnected (code: 1006)
twilio-video.js:14542 Tue Nov 28 2017 11:07:49 GMT+0300 (Turkey Standard Time) | sip.transport | WebSocket abrupt disconnection
LoggerFactory.print @ twilio-video.js:14542
LoggerFactory.(anonymous function) @ twilio-video.js:14559
Logger.(anonymous function) @ twilio-video.js:14553
onClose @ twilio-video.js:20204
ws.onclose @ twilio-video.js:20147
twilio-video.js:14542 Tue Nov 28 2017 11:07:49 GMT+0300 (Turkey Standard Time) | sip.ua | transport wss://endpoint.twilio.com failed | connection state set to 2
twilio-video.js:14542 Tue Nov 28 2017 11:07:49 GMT+0300 (Turkey Standard Time) | sip.ua | next connection attempt in 28 seconds
twilio-video.js:14542 Tue Nov 28 2017 11:08:17 GMT+0300 (Turkey Standard Time) | sip.transport | connecting to WebSocket wss://endpoint.twilio.com
twilio-video.js:20135 WebSocket connection to 'wss://endpoint.twilio.com/' failed: Error during WebSocket handshake: 'Upgrade' header is missing
connect @ twilio-video.js:20135
Transport @ twilio-video.js:20025
(anonymous) @ twilio-video.js:21181
twilio-video.js:14542 Tue Nov 28 2017 11:08:19 GMT+0300 (Turkey Standard Time) | sip.transport | WebSocket connection error: {"isTrusted":true}
LoggerFactory.print @ twilio-video.js:14542
LoggerFactory.(anonymous function) @ twilio-video.js:14559
Logger.(anonymous function) @ twilio-video.js:14553
onError @ twilio-video.js:20315
ws.onerror @ twilio-video.js:20155
twilio-video.js:14542 Tue Nov 28 2017 11:08:19 GMT+0300 (Turkey Standard Time) | sip.transport | WebSocket disconnected (code: 1006)
twilio-video.js:14542 Tue Nov 28 2017 11:08:19 GMT+0300 (Turkey Standard Time) | sip.transport | WebSocket abrupt disconnection
LoggerFactory.print @ twilio-video.js:14542
LoggerFactory.(anonymous function) @ twilio-video.js:14559
Logger.(anonymous function) @ twilio-video.js:14553
onClose @ twilio-video.js:20204
ws.onclose @ twilio-video.js:20147
twilio-video.js:14542 Tue Nov 28 2017 11:08:19 GMT+0300 (Turkey Standard Time) | sip.ua | transport wss://endpoint.twilio.com failed | connection state set to 2
twilio-video.js:14542 Tue Nov 28 2017 11:08:19 GMT+0300 (Turkey Standard Time) | sip.ua | next connection attempt in 30 seconds
twilio-video.js:14542 Tue Nov 28 2017 11:08:49 GMT+0300 (Turkey Standard Time) | sip.transport | connecting to WebSocket wss://endpoint.twilio.com
</code>```

We do not even understand what is the problem actually.

答:
This error message means that you are trying to connect to a HTTP server and not to a WebSocket server.

Possible reasons:

The URI you are using is not correct (in the past i have seen correct twilio websocket URI in this format: wss://xxx.endpoint.twilio.com. In your example the xxx part is missing)

You are behind some HTTP proxy which doesn't support WebSocket

Body:
We were using Twilio Video for development of our system, I am able to use the system with my own laptop but working laptops have an error while trying to connect with Chrome browser.

I am getting below error:

WebSocket connection to 'wss://endpoint.twilio.com/' failed: Error during WebSocket handshake: 'Upgrade' header is missing

The full error text is below:

twilio-video.js:20135 WebSocket connection to 'wss://endpoint.twilio.com/' failed: Error during WebSocket handshake: 'Upgrade' header is missing
connect @ twilio-video.js:20135
Transport @ twilio-video.js:20025
(anonymous) @ twilio-video.js:21181
twilio-video.js:14542 Tue Nov 28 2017 11:07:49 GMT+0300 (Turkey Standard Time) | sip.transport | WebSocket connection error: {"isTrusted":true}
LoggerFactory.print @ twilio-video.js:14542
LoggerFactory.(anonymous function) @ twilio-video.js:14559
Logger.(anonymous function) @ twilio-video.js:14553
onError @ twilio-video.js:20315
ws.onerror @ twilio-video.js:20155
twilio-video.js:14542 Tue Nov 28 2017 11:07:49 GMT+0300 (Turkey Standard Time) | sip.transport | WebSocket disconnected (code: 1006)
twilio-video.js:14542 Tue Nov 28 2017 11:07:49 GMT+0300 (Turkey Standard Time) | sip.transport | WebSocket abrupt disconnection
LoggerFactory.print @ twilio-video.js:14542
LoggerFactory.(anonymous function) @ twilio-video.js:14559
Logger.(anonymous function) @ twilio-video.js:14553
onClose @ twilio-video.js:20204
ws.onclose @ twilio-video.js:20147
twilio-video.js:14542 Tue Nov 28 2017 11:07:49 GMT+0300 (Turkey Standard Time) | sip.ua | transport wss://endpoint.twilio.com failed | connection state set to 2
twilio-video.js:14542 Tue Nov 28 2017 11:07:49 GMT+0300 (Turkey Standard Time) | sip.ua | next connection attempt in 28 seconds
twilio-video.js:14542 Tue Nov 28 2017 11:08:17 GMT+0300 (Turkey Standard Time) | sip.transport | connecting to WebSocket wss://endpoint.twilio.com
twilio-video.js:20135 WebSocket connection to 'wss://endpoint.twilio.com/' failed: Error during WebSocket handshake: 'Upgrade' header is missing
connect @ twilio-video.js:20135
Transport @ twilio-video.js:20025
(anonymous) @ twilio-video.js:21181
twilio-video.js:14542 Tue Nov 28 2017 11:08:19 GMT+0300 (Turkey Standard Time) | sip.transport | WebSocket connection error: {"isTrusted":true}
LoggerFactory.print @ twilio-video.js:14542
LoggerFactory.(anonymous function) @ twilio-video.js:14559
Logger.(anonymous function) @ twilio-video.js:14553
onError @ twilio-video.js:20315
ws.onerror @ twilio-video.js:20155
twilio-video.js:14542 Tue Nov 28 2017 11:08:19 GMT+0300 (Turkey Standard Time) | sip.transport | WebSocket disconnected (code: 1006)
twilio-video.js:14542 Tue Nov 28 2017 11:08:19 GMT+0300 (Turkey Standard Time) | sip.transport | WebSocket abrupt disconnection
LoggerFactory.print @ twilio-video.js:14542
LoggerFactory.(anonymous function) @ twilio-video.js:14559
Logger.(anonymous function) @ twilio-video.js:14553
onClose @ twilio-video.js:20204
ws.onclose @ twilio-video.js:20147
twilio-video.js:14542 Tue Nov 28 2017 11:08:19 GMT+0300 (Turkey Standard Time) | sip.ua | transport wss://endpoint.twilio.com failed | connection state set to 2
twilio-video.js:14542 Tue Nov 28 2017 11:08:19 GMT+0300 (Turkey Standard Time) | sip.ua | next connection attempt in 30 seconds
twilio-video.js:14542 Tue Nov 28 2017 11:08:49 GMT+0300 (Turkey Standard Time) | sip.transport | connecting to WebSocket wss://endpoint.twilio.com

We do not even understand what is the problem actually.


问:
Creating MongoDB documents inside chained Promisified functions
An app runs a process every 15 minutes that creates many output files with the following format:

```<code><timestamp>-<piece-code>.txt
</code>```

All files created by the process will share the "timestamp" component but the "piece-code" will differ, meaning I have a relationship of One Timestamp to Many Pieces, that I want to save in mongodb as:

```<code>"Registry" { time: (numeric) }
"Piece" { file: (string), piece: (string), registry: (reference) }
</code>```

In the process I want to find if a timestamp exists already before creating it to avoid duplicates, but my code seems to fail to do this.

Thanks in advance for your help!

```<code>const mongoose = require('mongoose');

const Registry = require('../model/Registry');
const Piece = require('../model/Piece');
mongoose.Promise = require('bluebird');

// Set up default mongoose connection
let mongoDB = 'mongodb://127.0.0.1/numbers';
mongoose.connect(mongoDB, {
  useMongoClient: true
});

//Get the default connection
let db = mongoose.connection;

// Bind connection to error event
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

// Error handler
let error = (err) => {
  console.log("** Error: ", err);
  db.close();
};

// Finish routine
let finish = () => {
    console.log("I have finished");
    db.close();
};

// Create a number if it does not exist already
let newRegistry = (timestamp) => {
  return new Promise((resolve, reject) => {
    Registry.count({}).then((c) => { console.log(c) })

    // Does this Registry exist?
    Registry.findOne({ time: timestamp })
      .then((reg, err) => {
        if (err) {
          reject(err);
        }
        // Create when it does not exist
        if (!reg) {
          Registry.create({
            time: timestamp
          }).then((doc, err) => {
            if (err) {
              reject(err);
            }
            resolve(doc._id);
          })
          .catch(error);
        } else {
          // Else, resolve
          resolve(reg._id);
        }

      });
  });
}

let newPiece = (registryId, filename, piece) => {
  return Piece.create({
    registry: mongoose.Types.ObjectId(registryId),
    file: filename,
    piece: piece
  });

};

let createRegs = (files) => {
  return new Promise((resolve, reject) => {
    let promises = [];
    let total = files.length;
    for (let i=0; i<total; i++) {
      let fileAr = files[i].split("-");
      let time = fileAr[0];
      let piece = fileAr[1];

      let promise = newRegistry(time)
        .then((regId) => {
          return newPiece(regId, files[i], piece);
        });

      promises.push(promise);
    }

    Promise.all(promises)
      .then(() => {
        resolve();
      })
      .catch(error);
  });
}

// Register input time and file pieces: one "time" can have many "pieces"
let filenames = ["1512473256-e.txt", "1512471758-a.txt", "1512471892-a.txt", "1512471758-b.txt"];

// Must end up with 3 "Registry" and 4 "Piece" documents
createRegs(filenames)
  .then(finish)
  .catch(error);
</code>```

答:
My approach will be this:

First I'd create a dictionary where keys would be the timestamp, and value would be an array with different pieces.

Once you have this dictionary, I'd treat each timestamp of the list

Look for the timestamp in the DB. Create it if it doesn't exist yet.

Loop through all pieces of the timestamp and add it to the database.

With this approach you avoid your concurrency problem.
Hope it helps.

Body:
An app runs a process every 15 minutes that creates many output files with the following format:

<timestamp>-<piece-code>.txt

All files created by the process will share the "timestamp" component but the "piece-code" will differ, meaning I have a relationship of One Timestamp to Many Pieces, that I want to save in mongodb as:

"Registry" { time: (numeric) }
"Piece" { file: (string), piece: (string), registry: (reference) }

In the process I want to find if a timestamp exists already before creating it to avoid duplicates, but my code seems to fail to do this.

Thanks in advance for your help!

const mongoose = require('mongoose');

const Registry = require('../model/Registry');
const Piece = require('../model/Piece');
mongoose.Promise = require('bluebird');

// Set up default mongoose connection
let mongoDB = 'mongodb://127.0.0.1/numbers';
mongoose.connect(mongoDB, {
  useMongoClient: true
});

//Get the default connection
let db = mongoose.connection;

// Bind connection to error event
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

// Error handler
let error = (err) => {
  console.log("** Error: ", err);
  db.close();
};

// Finish routine
let finish = () => {
    console.log("I have finished");
    db.close();
};

// Create a number if it does not exist already
let newRegistry = (timestamp) => {
  return new Promise((resolve, reject) => {
    Registry.count({}).then((c) => { console.log(c) })

    // Does this Registry exist?
    Registry.findOne({ time: timestamp })
      .then((reg, err) => {
        if (err) {
          reject(err);
        }
        // Create when it does not exist
        if (!reg) {
          Registry.create({
            time: timestamp
          }).then((doc, err) => {
            if (err) {
              reject(err);
            }
            resolve(doc._id);
          })
          .catch(error);
        } else {
          // Else, resolve
          resolve(reg._id);
        }

      });
  });
}

let newPiece = (registryId, filename, piece) => {
  return Piece.create({
    registry: mongoose.Types.ObjectId(registryId),
    file: filename,
    piece: piece
  });

};

let createRegs = (files) => {
  return new Promise((resolve, reject) => {
    let promises = [];
    let total = files.length;
    for (let i=0; i<total; i++) {
      let fileAr = files[i].split("-");
      let time = fileAr[0];
      let piece = fileAr[1];

      let promise = newRegistry(time)
        .then((regId) => {
          return newPiece(regId, files[i], piece);
        });

      promises.push(promise);
    }

    Promise.all(promises)
      .then(() => {
        resolve();
      })
      .catch(error);
  });
}

// Register input time and file pieces: one "time" can have many "pieces"
let filenames = ["1512473256-e.txt", "1512471758-a.txt", "1512471892-a.txt", "1512471758-b.txt"];

// Must end up with 3 "Registry" and 4 "Piece" documents
createRegs(filenames)
  .then(finish)
  .catch(error);


问:
Eigen copy constructor vs. operator= performance

At my job, I use the Eigen math library. I have encountered a behavior where using an Eigen Matrix copy constructor in an initializer list for my own classes is significantly slower than using operator= in the constructor body.

In these examples, "Matrix" is a statically-sized dense matrix.

```<code>class Slow {
    public:
        Slow(const Matrix &m) : my_matrix{m} {}
    private:
        Matrix my_matrix;
}

class Fast {
    public:
        Fast(const Matrix &m) : my_matrix{} {
            my_matrix = m;
        }
    private:
        Matrix my_matrix;
}
</code>```

My program frequently invokes the copy constructor of my class, and the difference in performance between the two options above is quite noticeable. I verified that the generated assembly is in fact different.

I understand that the copy-constructor and operator= are not the same, but I am having trouble wading through the Eigen source code to figure out why one is faster than the other. Can anyone with some Eigen expertise weigh in on what happens under the hood that causes operator= to be so much faster? Insight and/or links to recommended reading are equally welcome.

答:
In the "fast" version, the copy is manually handled by Eigen with inlining,  explicit loop unrolling, and explicit vectorization. In the "slow" case, the copy-ctor boils down to something like:

```<code>template<typename T,int Size>
struct storage {
  T data[Size];
  storage(storage &other)
    : data(other.data)
  {}
};
</code>```

that we assumed to be properly optimized by the compiler. Unfortunately, if Size is a bit too large, both clang and gcc implement this copy as a call to memcpy loosing the compile-time Size information. On the other hand, letting the compiler handling this copy enables higher level optimizations, like temporary removal in some cases.

Body:
At my job, I use the Eigen math library. I have encountered a behavior where using an Eigen Matrix copy constructor in an initializer list for my own classes is significantly slower than using operator= in the constructor body.

In these examples, "Matrix" is a statically-sized dense matrix.

class Slow {
    public:
        Slow(const Matrix &m) : my_matrix{m} {}
    private:
        Matrix my_matrix;
}

class Fast {
    public:
        Fast(const Matrix &m) : my_matrix{} {
            my_matrix = m;
        }
    private:
        Matrix my_matrix;
}

My program frequently invokes the copy constructor of my class, and the difference in performance between the two options above is quite noticeable. I verified that the generated assembly is in fact different.

I understand that the copy-constructor and operator= are not the same, but I am having trouble wading through the Eigen source code to figure out why one is faster than the other. Can anyone with some Eigen expertise weigh in on what happens under the hood that causes operator= to be so much faster? Insight and/or links to recommended reading are equally welcome.

Body:
In the "fast" version, the copy is manually handled by Eigen with inlining,  explicit loop unrolling, and explicit vectorization. In the "slow" case, the copy-ctor boils down to something like:

template<typename T,int Size>
struct storage {
  T data[Size];
  storage(storage &other)
    : data(other.data)
  {}
};

that we assumed to be properly optimized by the compiler. Unfortunately, if Size is a bit too large, both clang and gcc implement this copy as a call to memcpy loosing the compile-time Size information. On the other hand, letting the compiler handling this copy enables higher level optimizations, like temporary removal in some cases.


问:
How can I make a bulma table responsive?
I am using the Bulma CSS framework and specifically I am trying to make the table in it responsive.

I have tried giving it a width: 100%; and applying overflow-x: auto; but it doesn't seem to work. Here is the demo: http://104.236.64.172:8081/#/pricing

Code:

```<code><div class="panel-block">
    <table class="table is-bordered pricing__table">
        <thead>
            <tr>
                <th>Travellers</th>
                <th>Standard</th>
                <th>Delux</th>
                <th>Premium</th>
                <th>Luxury</th>
            </tr>
        </thead>

        <tbody>
            <tr>
                <td>Per Person Cost</td>
                <td>₹ 70,523.90</td>
                <td>₹ 70,523.90</td>
                <td>₹ 70,523.90</td>
                <td>₹ 70,523.90</td>
            </tr>
            <tr>
                <td>
                    Extra Person <br>
                    (> 12 yrs)
                </td>
                <td>₹ 70,523.90</td>
                <td>₹ 70,523.90</td>
                <td>₹ 70,523.90</td>
                <td>₹ 70,523.90</td>
            </tr>
            <tr>
                <td>
                    Extra Child <br>
                    (> 12 yrs)
                </td>
                <td>₹ 70,523.90</td>
                <td>₹ 70,523.90</td>
                <td>₹ 70,523.90</td>
                <td>₹ 70,523.90</td>
            </tr>
            <tr>
                <td>Total Cost</td>
                <td>₹ 70,523.90</td>
                <td>₹ 70,523.90</td>
                <td>₹ 70,523.90</td>
                <td>₹ 70,523.90</td>
            </tr>
        </tbody>
    </table>
</div>
</code>```

Relevant CSS:

```<code>.pricing__table {
    width: 100%;
    overflow-x: auto;
}
</code>```

答:
You could wrap the table in a container, and apply the overflow property there instead.

Also, you can use the is-fullwidth modifier on table, instead of declaring width in the CSS.

fiddle

.table__wrapper {
  overflow-x: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.css" rel="stylesheet" />
<div class="table__wrapper">
  <table class="table is-bordered pricing__table is-fullwidth">
    <tbody>
      <tr>
        <td>Per Person Cost</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
      </tr>
      <tr>
        <td>
          Extra Person <br> (> 12 yrs)
        </td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
      </tr>
      <tr>
        <td>
          Extra Child <br> (> 12 yrs)
        </td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
      </tr>
      <tr>
        <td>Total Cost</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
      </tr>
    </tbody>
  </table>
</div></code>```

Update as per comment

In your case, you also need to add the width property to .pricing

updated fiddle

.table__wrapper {
  overflow-x: auto;
}

.pricing {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.css" rel="stylesheet"/>
<div class="panel">
  <div class="panel-block">
    <div class="pricing">
      <div class="table__wrapper">
        <table class="table is-bordered pricing__table is-fullwidth">
          <tbody>
            <tr>
              <td>Per Person Cost</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
            </tr>
            <tr>
              <td>
                Extra Person
                <br> (> 12 yrs)
              </td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
            </tr>
            <tr>
              <td>
                Extra Child
                <br> (> 12 yrs)
              </td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
            </tr>
            <tr>
              <td>Total Cost</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div></code>```

Body:
I am using the Bulma CSS framework and specifically I am trying to make the table in it responsive.

I have tried giving it a width: 100%; and applying overflow-x: auto; but it doesn't seem to work. Here is the demo: http://104.236.64.172:8081/#/pricing

Code:

                Travellers
                Standard
                Delux
                Premium
                Luxury

                Per Person Cost
                ₹ 70,523.90
                ₹ 70,523.90
                ₹ 70,523.90
                ₹ 70,523.90

                    Extra Person

                    (> 12 yrs)

                ₹ 70,523.90
                ₹ 70,523.90
                ₹ 70,523.90
                ₹ 70,523.90

                    Extra Child

                    (> 12 yrs)

                ₹ 70,523.90
                ₹ 70,523.90
                ₹ 70,523.90
                ₹ 70,523.90

                Total Cost
                ₹ 70,523.90
                ₹ 70,523.90
                ₹ 70,523.90
                ₹ 70,523.90

Relevant CSS:

.pricing__table {
    width: 100%;
    overflow-x: auto;
}

Body:
You could wrap the table in a container, and apply the overflow property there instead.

Also, you can use the is-fullwidth modifier on table, instead of declaring width in the CSS.

fiddle

.table__wrapper {
  overflow-x: auto;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.css" rel="stylesheet" />
<div class="table__wrapper">
  <table class="table is-bordered pricing__table is-fullwidth">
    <tbody>
      <tr>
        <td>Per Person Cost</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
      </tr>
      <tr>
        <td>
          Extra Person <br> (> 12 yrs)
        </td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
      </tr>
      <tr>
        <td>
          Extra Child <br> (> 12 yrs)
        </td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
      </tr>
      <tr>
        <td>Total Cost</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
        <td>₹ 70,523.90</td>
      </tr>
    </tbody>
  </table>
</div>

Update as per comment

In your case, you also need to add the width property to .pricing

updated fiddle

.table__wrapper {
  overflow-x: auto;
}

.pricing {
  width: 100%;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.css" rel="stylesheet"/>
<div class="panel">
  <div class="panel-block">
    <div class="pricing">
      <div class="table__wrapper">
        <table class="table is-bordered pricing__table is-fullwidth">
          <tbody>
            <tr>
              <td>Per Person Cost</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
            </tr>
            <tr>
              <td>
                Extra Person
                <br> (> 12 yrs)
              </td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
            </tr>
            <tr>
              <td>
                Extra Child
                <br> (> 12 yrs)
              </td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
            </tr>
            <tr>
              <td>Total Cost</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
              <td>₹ 70,523.90</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>


问:
Showing only values which are larger than the user entered value in C#

Question

After finishing this product order manager, I was tasked with adding a feature which lets the user enter a double value, which once entered, will only show the products with prices greater than the chosen value.

I am lost on how I should begin to add this extra option to allow for the filtering of data based on what the user enters.

If someone could point me in the correct direction, I would be ever so thankful!

ConsoleView.cs

```<code>class ConsoleView
{
    public int ShowMenu()
    {
        Console.WriteLine("_________Menu________");
        Console.WriteLine("1) Add Orders");
        Console.WriteLine("2) See all orders");
        Console.WriteLine("3) Filter Orders");
        Console.WriteLine("4) exit");
        Console.WriteLine("______________________");
        Console.WriteLine("Please enter a selection (1-4):");

        return Convert.ToInt32(Console.ReadLine());
    }

    public Order AddOrder()
    {
        Console.WriteLine("What is the name of the product?");
        string name = Console.ReadLine();
        Console.WriteLine("What is the amount paid for the product?");
        double value = Convert.ToDouble(Console.ReadLine());

        return new Order(name, value);
    }

    public void DisplayAllOrders(Order[] orders)
    {
        Console.WriteLine("___________ORDERS_____________");
        for (int i = 0; i< orders.Length; i++)
        {

            Console.WriteLine("Product Name: " + orders[i].GetOrders() + " - Amount Paid - " + orders[i].GetAmount());
        }
        Console.WriteLine("______________________________");
    }

    public void FilterOrder(Order filter)
    {
        Console.WriteLine("What numerical value would you like the information to be greater than?");
        double Value = Convert.ToInt32(Console.ReadLine());

    }

}
</code>```

Order.cs

```<code>class Order
{

    private string orderName;
    private double orderAmount;

    public Order(string ProductName, double Price)
    {
        SetName(ProductName);
        SetAmount(Price);
    }

    public void SetName(string name)
    {
        orderName = name;
    }

    public string GetOrders()
    {
        return orderName;
    }

    public void SetAmount(double value)
    {
        orderAmount = value;
    }

    public double GetAmount()
    {
        return orderAmount;
    }

    public static void FilterPrices(double userNum)
    {
        int largeNum = priceArray[0];
    }
}
</code>```

OrderManager.cs

```<code>class OrderManager
{
    private List<Order> orders;

    public OrderManager()
    {
        orders = new List<Order>();
    }

    public void AddOrder(Order order)
    {
        orders.Add(order);

    }

   public void setAmount(Order amount)
    {
        orders.Add(amount);
    }

    public Order[] GetOrder()
    {
        return orders.ToArray();
    }
}
</code>```

Program.cs

```<code>static void Main(string[] args)
{
    ConsoleView view = new ConsoleView();
    OrderManager model = new OrderManager();
    int userSelection;

    do
    {
        userSelection = view.ShowMenu();
        if (userSelection == 1)
        {
            //Add orders

            model.AddOrder(view.AddOrder());
        }

        else if (userSelection == 2)
        {
            //Display Orders

            view.DisplayAllOrders(model.GetOrder());
        }
        else if (userSelection == 3)
        {
            //Filter Orders
            model.FilterOrder
        }
    }
    while (userSelection != 4);
</code>```

答:
The oldscool way would be to have a method which loops through your orders collection and checks each order whether it satisfies the criterion.

You can start with such a method

```<code>class OrderManager
{
    public List<Order> GetFilteredOrders(double minValue)
    {
          // make a second collection to collect the orders that will match the criterion
          // loop here through collection
          // check if(orders[i].GetAmout() > minValue)
          // collect them

          // return the collected items
    }
}
</code>```

Body:
Question

After finishing this product order manager, I was tasked with adding a feature which lets the user enter a double value, which once entered, will only show the products with prices greater than the chosen value.

I am lost on how I should begin to add this extra option to allow for the filtering of data based on what the user enters.

If someone could point me in the correct direction, I would be ever so thankful!

ConsoleView.cs

class ConsoleView
{
    public int ShowMenu()
    {
        Console.WriteLine("_________Menu________");
        Console.WriteLine("1) Add Orders");
        Console.WriteLine("2) See all orders");
        Console.WriteLine("3) Filter Orders");
        Console.WriteLine("4) exit");
        Console.WriteLine("______________________");
        Console.WriteLine("Please enter a selection (1-4):");

        return Convert.ToInt32(Console.ReadLine());
    }

    public Order AddOrder()
    {
        Console.WriteLine("What is the name of the product?");
        string name = Console.ReadLine();
        Console.WriteLine("What is the amount paid for the product?");
        double value = Convert.ToDouble(Console.ReadLine());

        return new Order(name, value);
    }

    public void DisplayAllOrders(Order[] orders)
    {
        Console.WriteLine("___________ORDERS_____________");
        for (int i = 0; i< orders.Length; i++)
        {

            Console.WriteLine("Product Name: " + orders[i].GetOrders() + " - Amount Paid - " + orders[i].GetAmount());
        }
        Console.WriteLine("______________________________");
    }

    public void FilterOrder(Order filter)
    {
        Console.WriteLine("What numerical value would you like the information to be greater than?");
        double Value = Convert.ToInt32(Console.ReadLine());

    }

}

Order.cs

class Order
{

    private string orderName;
    private double orderAmount;

    public Order(string ProductName, double Price)
    {
        SetName(ProductName);
        SetAmount(Price);
    }

    public void SetName(string name)
    {
        orderName = name;
    }

    public string GetOrders()
    {
        return orderName;
    }

    public void SetAmount(double value)
    {
        orderAmount = value;
    }

    public double GetAmount()
    {
        return orderAmount;
    }

    public static void FilterPrices(double userNum)
    {
        int largeNum = priceArray[0];
    }
}

OrderManager.cs

class OrderManager
{
    private List<Order> orders;

    public OrderManager()
    {
        orders = new List<Order>();
    }

    public void AddOrder(Order order)
    {
        orders.Add(order);

    }

   public void setAmount(Order amount)
    {
        orders.Add(amount);
    }

    public Order[] GetOrder()
    {
        return orders.ToArray();
    }
}

Program.cs

static void Main(string[] args)
{
    ConsoleView view = new ConsoleView();
    OrderManager model = new OrderManager();
    int userSelection;

    do
    {
        userSelection = view.ShowMenu();
        if (userSelection == 1)
        {
            //Add orders

            model.AddOrder(view.AddOrder());
        }

        else if (userSelection == 2)
        {
            //Display Orders

            view.DisplayAllOrders(model.GetOrder());
        }
        else if (userSelection == 3)
        {
            //Filter Orders
            model.FilterOrder
        }
    }
    while (userSelection != 4);

Body:
The oldscool way would be to have a method which loops through your orders collection and checks each order whether it satisfies the criterion.

You can start with such a method

class OrderManager
{
    public List<Order> GetFilteredOrders(double minValue)
    {
          // make a second collection to collect the orders that will match the criterion
          // loop here through collection
          // check if(orders[i].GetAmout() > minValue)
          // collect them

          // return the collected items
    }
}