问:
Not able to take to an Intent properly
I've to check whether the user entered code is valid with the database code. If yes, it should populate all the details from firebase database to all the fields in the layout. Otherwise, It should take back to Home Page giving a user a toast that he isn't authorized.

The problem is, even if the user entered code matches the database code it is taking me to HomePage. How can I solve this ? Can anyone guide me.

Code in my onCreate method:

```<code>inputCodesReference.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot ds: dataSnapshot.getChildren()) {
      enteredUserCode = (String) ds.child("code").getValue();
    }
  }
  @Override
  public void onCancelled(DatabaseError databaseError) {}
});

familyListReference.addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot ds: dataSnapshot.getChildren()) {
      String key = (String) ds.getKey();
      DatabaseReference keyReference = FirebaseDatabase.getInstance().getReference().child("familylist").child(key);
      keyReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
          final String code = dataSnapshot.child("code").getValue(String.class);
          String family = dataSnapshot.child("family").getValue(String.class);
          String father = dataSnapshot.child("fatherName").getValue(String.class);
          String mother = dataSnapshot.child("motherName").getValue(String.class);

          for (DataSnapshot childSnapshot: dataSnapshot.child("children").getChildren()) {
            String child = childSnapshot.getValue(String.class);
            if (code.equals(enteredUserCode))
              children.add(child);
          }

          if (code.equals(enteredUserCode)) {
            Log.d(TAG, "[FINAL CHECK IN ACTIVITY] Database Code: " + code);
            Log.d(TAG, "[FINAL CHECK IN ACTIVITY] User Input code: " + enteredUserCode);
            familyName = family;
            fatherName = father;
            motherName = mother;
            relativeLayout.setVisibility(View.VISIBLE);
            welcomeMessage.setText("Welcome " + familyName + " family!");
            fatherRadioButton.setText(fatherName);
            motherRadioButton.setText(motherName);
          } else {
            Intent intent = new Intent(getApplicationContext(), HomePage.class);
            startActivity(intent);
            finish();
          }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
          Log.d(TAG, "Read failed");
        }
      }); // [Key Reference]

    } // END of for Loop
  }

  @Override
  public void onCancelled(DatabaseError databaseError) {
    Log.d(TAG, "Read failed");
  }
}); // [familyList Database Reference]

//[CHECK IN]
checkinButton.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
      if (fatherRadioButton.isChecked()) {
        checkIn = new CheckIn(familyName, fatherName, null, checkInTime, childrenToDatabase);
      } else {
        checkIn = new CheckIn(familyName, null, motherName, checkInTime, childrenToDatabase);
      }
      checkInCheckOutDatabaseReference.push().setValue(checkIn);
      Intent intent = new Intent(CheckInFinalActivity.this, HomePage.class);
      startActivity(intent);
      Toast.makeText(CheckInFinalActivity.this, "Check in Successful!", Toast.LENGTH_LONG).show();
    }
  }
});
</code>```

答:
The lines where you get enteredUserCode inside the onDataChange method are executed whenever the DataSnapshot is retrieved from firebase as this call is asynchronous in nature.

Hence, the enteredUserCode might not be available for the familyListReference at that moment. To make sure that the enteredUserCode is available, you need to move the familyListReference's listener inside the inputCodeReference onDataChange method.

Here's the modified code.

```<code>inputCodesReference.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot ds: dataSnapshot.getChildren()) {
      enteredUserCode = (String) ds.child("code").getValue();
    }
    familyListReference.addListenerForSingleValueEvent(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot ds: dataSnapshot.getChildren()) {
          String key = (String) ds.getKey();
          DatabaseReference keyReference = FirebaseDatabase.getInstance().getReference().child("familylist").child(key);
          keyReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
              final String code = dataSnapshot.child("code").getValue(String.class);
              String family = dataSnapshot.child("family").getValue(String.class);
              String father = dataSnapshot.child("fatherName").getValue(String.class);
              String mother = dataSnapshot.child("motherName").getValue(String.class);

              for (DataSnapshot childSnapshot: dataSnapshot.child("children").getChildren()) {
                String child = childSnapshot.getValue(String.class);
                if (code.equals(enteredUserCode))
                  children.add(child);
              }

              if (code.equals(enteredUserCode)) {
                Log.d(TAG, "[FINAL CHECK IN ACTIVITY] Database Code: " + code);
                Log.d(TAG, "[FINAL CHECK IN ACTIVITY] User Input code: " + enteredUserCode);
                familyName = family;
                fatherName = father;
                motherName = mother;
                relativeLayout.setVisibility(View.VISIBLE);
                welcomeMessage.setText("Welcome " + familyName + " family!");
                fatherRadioButton.setText(fatherName);
                motherRadioButton.setText(motherName);
              } else {
                Intent intent = new Intent(getApplicationContext(), HomePage.class);
                startActivity(intent);
                finish();
              }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
              Log.d(TAG, "Read failed");
            }
          }); // [Key Reference]

        } // END of for Loop
      }

      @Override
      public void onCancelled(DatabaseError databaseError) {
        Log.d(TAG, "Read failed");
      }
    }); // [familyList Database Reference]
  }
  @Override
  public void onCancelled(DatabaseError databaseError) {}
});

//[CHECK IN]
checkinButton.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
      if (fatherRadioButton.isChecked()) {
        checkIn = new CheckIn(familyName, fatherName, null, checkInTime, childrenToDatabase);
      } else {
        checkIn = new CheckIn(familyName, null, motherName, checkInTime, childrenToDatabase);
      }
      checkInCheckOutDatabaseReference.push().setValue(checkIn);
      Intent intent = new Intent(CheckInFinalActivity.this, HomePage.class);
      startActivity(intent);
      Toast.makeText(CheckInFinalActivity.this, "Check in Successful!", Toast.LENGTH_LONG).show();
    }
  }
});
</code>```

This ensures the enteredUserCode is ready and available for the next actions.

Now that you have a single method, the code can be further simplified by getting a rootFirebaseInstance instead of adding two listeners. It depends on how you have organized your json schema.

Title: Not able to take to an Intent properly

Body:
I've to check whether the user entered code is valid with the database code. If yes, it should populate all the details from firebase database to all the fields in the layout. Otherwise, It should take back to Home Page giving a user a toast that he isn't authorized.

The problem is, even if the user entered code matches the database code it is taking me to HomePage. How can I solve this ? Can anyone guide me.

Code in my onCreate method:

inputCodesReference.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot ds: dataSnapshot.getChildren()) {
      enteredUserCode = (String) ds.child("code").getValue();
    }
  }
  @Override
  public void onCancelled(DatabaseError databaseError) {}
});

familyListReference.addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot ds: dataSnapshot.getChildren()) {
      String key = (String) ds.getKey();
      DatabaseReference keyReference = FirebaseDatabase.getInstance().getReference().child("familylist").child(key);
      keyReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
          final String code = dataSnapshot.child("code").getValue(String.class);
          String family = dataSnapshot.child("family").getValue(String.class);
          String father = dataSnapshot.child("fatherName").getValue(String.class);
          String mother = dataSnapshot.child("motherName").getValue(String.class);

          for (DataSnapshot childSnapshot: dataSnapshot.child("children").getChildren()) {
            String child = childSnapshot.getValue(String.class);
            if (code.equals(enteredUserCode))
              children.add(child);
          }

          if (code.equals(enteredUserCode)) {
            Log.d(TAG, "[FINAL CHECK IN ACTIVITY] Database Code: " + code);
            Log.d(TAG, "[FINAL CHECK IN ACTIVITY] User Input code: " + enteredUserCode);
            familyName = family;
            fatherName = father;
            motherName = mother;
            relativeLayout.setVisibility(View.VISIBLE);
            welcomeMessage.setText("Welcome " + familyName + " family!");
            fatherRadioButton.setText(fatherName);
            motherRadioButton.setText(motherName);
          } else {
            Intent intent = new Intent(getApplicationContext(), HomePage.class);
            startActivity(intent);
            finish();
          }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
          Log.d(TAG, "Read failed");
        }
      }); // [Key Reference]

    } // END of for Loop
  }

  @Override
  public void onCancelled(DatabaseError databaseError) {
    Log.d(TAG, "Read failed");
  }
}); // [familyList Database Reference]

//[CHECK IN]
checkinButton.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
      if (fatherRadioButton.isChecked()) {
        checkIn = new CheckIn(familyName, fatherName, null, checkInTime, childrenToDatabase);
      } else {
        checkIn = new CheckIn(familyName, null, motherName, checkInTime, childrenToDatabase);
      }
      checkInCheckOutDatabaseReference.push().setValue(checkIn);
      Intent intent = new Intent(CheckInFinalActivity.this, HomePage.class);
      startActivity(intent);
      Toast.makeText(CheckInFinalActivity.this, "Check in Successful!", Toast.LENGTH_LONG).show();
    }
  }
});

Body:
The lines where you get enteredUserCode inside the onDataChange method are executed whenever the DataSnapshot is retrieved from firebase as this call is asynchronous in nature.

Hence, the enteredUserCode might not be available for the familyListReference at that moment. To make sure that the enteredUserCode is available, you need to move the familyListReference's listener inside the inputCodeReference onDataChange method.

Here's the modified code.

inputCodesReference.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot ds: dataSnapshot.getChildren()) {
      enteredUserCode = (String) ds.child("code").getValue();
    }
    familyListReference.addListenerForSingleValueEvent(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot ds: dataSnapshot.getChildren()) {
          String key = (String) ds.getKey();
          DatabaseReference keyReference = FirebaseDatabase.getInstance().getReference().child("familylist").child(key);
          keyReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
              final String code = dataSnapshot.child("code").getValue(String.class);
              String family = dataSnapshot.child("family").getValue(String.class);
              String father = dataSnapshot.child("fatherName").getValue(String.class);
              String mother = dataSnapshot.child("motherName").getValue(String.class);

              for (DataSnapshot childSnapshot: dataSnapshot.child("children").getChildren()) {
                String child = childSnapshot.getValue(String.class);
                if (code.equals(enteredUserCode))
                  children.add(child);
              }

              if (code.equals(enteredUserCode)) {
                Log.d(TAG, "[FINAL CHECK IN ACTIVITY] Database Code: " + code);
                Log.d(TAG, "[FINAL CHECK IN ACTIVITY] User Input code: " + enteredUserCode);
                familyName = family;
                fatherName = father;
                motherName = mother;
                relativeLayout.setVisibility(View.VISIBLE);
                welcomeMessage.setText("Welcome " + familyName + " family!");
                fatherRadioButton.setText(fatherName);
                motherRadioButton.setText(motherName);
              } else {
                Intent intent = new Intent(getApplicationContext(), HomePage.class);
                startActivity(intent);
                finish();
              }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
              Log.d(TAG, "Read failed");
            }
          }); // [Key Reference]

        } // END of for Loop
      }

      @Override
      public void onCancelled(DatabaseError databaseError) {
        Log.d(TAG, "Read failed");
      }
    }); // [familyList Database Reference]
  }
  @Override
  public void onCancelled(DatabaseError databaseError) {}
});

//[CHECK IN]
checkinButton.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
      if (fatherRadioButton.isChecked()) {
        checkIn = new CheckIn(familyName, fatherName, null, checkInTime, childrenToDatabase);
      } else {
        checkIn = new CheckIn(familyName, null, motherName, checkInTime, childrenToDatabase);
      }
      checkInCheckOutDatabaseReference.push().setValue(checkIn);
      Intent intent = new Intent(CheckInFinalActivity.this, HomePage.class);
      startActivity(intent);
      Toast.makeText(CheckInFinalActivity.this, "Check in Successful!", Toast.LENGTH_LONG).show();
    }
  }
});

This ensures the enteredUserCode is ready and available for the next actions.

Now that you have a single method, the code can be further simplified by getting a rootFirebaseInstance instead of adding two listeners. It depends on how you have organized your json schema.


来源: stackexchange

问:
Show the value of a geom_point using geom_text
Using this nice code from here:

```<code>countries <- structure(list(country = structure(c(5L, 6L, 3L, 4L, 10L, 8L,
11L, 7L, 1L, 13L, 9L, 12L, 2L), .Label = c("Australia", "China",
"France", "Georgia", "India", "Ireland", "Malaysia", "Poland",
"Qatar", "Singapore", "South Africa", "Spain", "USA"), class = "factor"),
    Latitude = c(20.593684, 53.142367, 46.227638, 32.165622,
    1.352083, 51.919438, -30.559482, 4.210484, -25.274398, 37.09024,
    25.354826, 40.463667, 35.86166), Longitude = c(78.96288,
    -7.692054, 2.213749, -82.900075, 103.819836, 19.145136, 22.937506,
    101.975766, 133.775136, -95.712891, 51.183884, -3.74922,
    104.195397), Value = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    2L, 1L, 2L, 2L)), .Names = c("country", "Latitude", "Longitude",
"Value"), class = "data.frame", row.names = c(NA, -13L))
link1 <- countries[countries$country %in% c("USA", "Spain","China"), ]
link2 <- countries[countries$country %in% c("Australia", "Poland"), ]

library(ggplot2)
library(maps)
base_world <- map_data("world")
p <- ggplot() +
      geom_polygon(data=base_world, aes(x=long, y=lat, group=group)) +
      geom_line(data=link1, aes(x=Longitude, y=Latitude), color="red", size=1) +
      geom_line(data=link2, aes(x=Longitude, y=Latitude), color="green", size=1) +
      geom_point(data=countries, aes(x=Longitude, y=Latitude), colour = "cyan", size=5, alpha=I(0.7)) + #set the color outside of `aes`
      theme(text = element_text(size=20), legend.position="none")  #remove the legend
</code>```

I would like to show next to the geom_point the value. So I tried the geom_text using the following:

```<code>p+geom_text(aes(label=countries$Value,x=Longitude, y=Latitude),hjust=0, vjust=0)
</code>```

but I receive this error:

```<code>Error in eval(expr, envir, enclos) : object 'Longitude' not found
</code>```

答:
Try this:

```<code>p <- ggplot() +
  geom_polygon(data=base_world, aes(x=long, y=lat, group=group)) +
  geom_line(data=link1, aes(x=Longitude, y=Latitude), color="blue", size=1) +
  geom_line(data=link2, aes(x=Longitude, y=Latitude), color="green", size=1) +
  geom_point(data=countries, aes(x=Longitude, y=Latitude), colour = "cyan", size=5, alpha=I(0.7)) + #set the color outside of `aes`
  theme(text = element_text(size=20), legend.position="none") +   #remove the legend
  annotate("text", x = countries$Longitude, y=countries$Latitude, label = countries$Value, hjust = 2, colour = "purple") +
  annotate("text", x = countries$Longitude, y=countries$Latitude, label = countries$country, hjust = -0.1, colour = "red") #if you also want name of countries
</code>```

And this would be the plot:

> p

P.S. I'd prefer annotate over geom_text as a personal preference but if you want to use that then following works (should reference to the data-frame when defining the coordinates):

```<code>p+geom_text(aes(label=countries$Value,x=countries$Longitude, y=countries$Latitude),hjust=0, vjust=0)
</code>```

You may want to consider using different values since texts may not be legible.

ContentLicense: CC BY-SA 3.0

Body:
Using this nice code from here:

countries <- structure(list(country = structure(c(5L, 6L, 3L, 4L, 10L, 8L,
11L, 7L, 1L, 13L, 9L, 12L, 2L), .Label = c("Australia", "China",
"France", "Georgia", "India", "Ireland", "Malaysia", "Poland",
"Qatar", "Singapore", "South Africa", "Spain", "USA"), class = "factor"),
    Latitude = c(20.593684, 53.142367, 46.227638, 32.165622,
    1.352083, 51.919438, -30.559482, 4.210484, -25.274398, 37.09024,
    25.354826, 40.463667, 35.86166), Longitude = c(78.96288,
    -7.692054, 2.213749, -82.900075, 103.819836, 19.145136, 22.937506,
    101.975766, 133.775136, -95.712891, 51.183884, -3.74922,
    104.195397), Value = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    2L, 1L, 2L, 2L)), .Names = c("country", "Latitude", "Longitude",
"Value"), class = "data.frame", row.names = c(NA, -13L))
link1 <- countries[countries$country %in% c("USA", "Spain","China"), ]
link2 <- countries[countries$country %in% c("Australia", "Poland"), ]

library(ggplot2)
library(maps)
base_world <- map_data("world")
p <- ggplot() +
      geom_polygon(data=base_world, aes(x=long, y=lat, group=group)) +
      geom_line(data=link1, aes(x=Longitude, y=Latitude), color="red", size=1) +
      geom_line(data=link2, aes(x=Longitude, y=Latitude), color="green", size=1) +
      geom_point(data=countries, aes(x=Longitude, y=Latitude), colour = "cyan", size=5, alpha=I(0.7)) + #set the color outside of `aes`
      theme(text = element_text(size=20), legend.position="none")  #remove the legend

I would like to show next to the geom_point the value. So I tried the geom_text using the following:

p+geom_text(aes(label=countries$Value,x=Longitude, y=Latitude),hjust=0, vjust=0)

but I receive this error:

Error in eval(expr, envir, enclos) : object 'Longitude' not found

Body:
Try this:

p <- ggplot() +
  geom_polygon(data=base_world, aes(x=long, y=lat, group=group)) +
  geom_line(data=link1, aes(x=Longitude, y=Latitude), color="blue", size=1) +
  geom_line(data=link2, aes(x=Longitude, y=Latitude), color="green", size=1) +
  geom_point(data=countries, aes(x=Longitude, y=Latitude), colour = "cyan", size=5, alpha=I(0.7)) + #set the color outside of `aes`
  theme(text = element_text(size=20), legend.position="none") +   #remove the legend
  annotate("text", x = countries$Longitude, y=countries$Latitude, label = countries$Value, hjust = 2, colour = "purple") +
  annotate("text", x = countries$Longitude, y=countries$Latitude, label = countries$country, hjust = -0.1, colour = "red") #if you also want name of countries

And this would be the plot:

> p

P.S. I'd prefer annotate over geom_text as a personal preference but if you want to use that then following works (should reference to the data-frame when defining the coordinates):

p+geom_text(aes(label=countries$Value,x=countries$Longitude, y=countries$Latitude),hjust=0, vjust=0)

You may want to consider using different values since texts may not be legible.

ContentLicense: CC BY-SA 4.0


问:
php query in database doesn't work
Hello guys i tried to add into database some values and it's not working.I tried everything but no.
What should i do? the name of the table is "credit".
Can you help me to rezolv this problem?</p>

```<code><tr>
    <td><input class="form-control" placeholder="nr" name="nr" type="text" autofocus></td>
    <td><input class="form-control" placeholder="suma" name="suma" type="text" autofocus></td>
    <td><input class="form-control" placeholder="rate" name="rate" type="text" autofocus></td>
    <td><input class="form-control" placeholder="dobanda" name="dobanda" type="text" autofocus></td>
    <td><button class="btn btn-success" value="adaugare">Adaugare credit</button></a></td>
</tr>
</table>
</div>
</div>

<?php if(isset($_POST['adaugare']))
    {
        $nr=$_POST['nr'];
        $suma=$_POST['suma'];
        $rate=$_POST['rate'];
        $dobanda=$_POST['dobanda'];

        if($nr=='')
        {

            echo"<script>alert('Introdu numar')</script>";
            exit();
        }

        if($suma=='')
        {

            echo"<script>alert('Introdu suma')</script>";
            exit();
        }
        if($rate=='')
        {
            echo"<script>alert('Introdu rate')</script>";
            exit();
        }
        if($dobanda=='')
        {
            echo"<script>alert('Introdu dobanda')</script>";
            exit();
        }
        $id=$_SESSION['id'];
        $insert_credit="insert into credit VALUE ('$nr','$id','$suma','$rate','$dobanda')";
        mysqli_query($dbcon,$insert_credit);

    }
</code>```

答:
There are a few things I can see:

1) You don't seem to have a form anywhere so not sure how you are posting anything - you need to wrap your HTML in a form tag

2) You should set the button to be a submit button so you can then send the form data

Also your code is vulnerable to all sorts of nasties as you are not checking the input in any way - lookup SQL injection

Title: php query in database doesn't work

Body:
Hello guys i tried to add into database some values and it's not working.I tried everything but no.
What should i do? the name of the table is "credit".
Can you help me to rezolv this problem?

    <input class="form-control" placeholder="nr" name="nr" type="text" autofocus>
    <input class="form-control" placeholder="suma" name="suma" type="text" autofocus>
    <input class="form-control" placeholder="rate" name="rate" type="text" autofocus>
    <input class="form-control" placeholder="dobanda" name="dobanda" type="text" autofocus>
    <button class="btn btn-success" value="adaugare">Adaugare credit</button>

<?php if(isset($_POST['adaugare']))
    {
        $nr=$_POST['nr'];
        $suma=$_POST['suma'];
        $rate=$_POST['rate'];
        $dobanda=$_POST['dobanda'];

        if($nr=='')
        {

            echo"";
            exit();
        }

        if($suma=='')
        {

            echo"";
            exit();
        }
        if($rate=='')
        {
            echo"";
            exit();
        }
        if($dobanda=='')
        {
            echo"";
            exit();
        }
        $id=$_SESSION['id'];
        $insert_credit="insert into credit VALUE ('$nr','$id','$suma','$rate','$dobanda')";
        mysqli_query($dbcon,$insert_credit);

    }


问:
Architetural Considerations for VueJS project: Implementing Vuex
Our front-end team is presently working on a Reporting application with the following features:

Dashboards

Portfolio Analysis Tool (search form that returns grid-based results)

Automated Reports page

We've decided to architect the above using VueJS with the Webpack boilerplate (via Vue-Cli) and are trying to design to have common components:

A report component

Has title, description, type (grid, visualization, etc.) and some setting parameters

A report list component

Has a title and an array of report components as its properties

A dashboard that has an array of report list components arranged in a grid

Some requirements

A dashboard component can have 4 or more report list components, each with multiple reports that can be selected for view by the user from a report list select menu. Each report component can have one or more setting parameters that the user can manipulate and submit to re-render the report. A report can be a grid (ag-grid in our case) or a visualization-based report. Lastly, there is also authentication via Auth0.

Questions

Does it make sense to use Vuex to manage state for all our components and related interactions?

Does it sound like the application is a good use-case for Vuex?

If so, why? Is it better than using component to component communication via the built in Vue mechanisms (for parent-child, sibling-sibling components)?

Thank you in advance for helping us make a decision.

答:
I voted to close this question, because the answer is highly opinionated.

I've built multiple projects with Vue, some with dozens of components and many multiple thousands of lines of code. I've never once felt the level of complexity rose to the level that I needed Vuex.

You've described an application with half a dozen components.

I've definitely abstracted my logic out into custom objects, but that's just javascript.

YMMV.


问:
django tables how to detect if table is empty
I am new to django and web development and based on examples and help on SO, I have pieced together something which takes a model and renders it in a django-table. My template code is basically as follows:

```<code>{% block content %}
{% load static %}
{% load render_table from django_tables2 %}
 <div class="function-page">
     <div class="table-form">
        <div class="function-container">
                {% render_table reviews %}
        </div>
     </div>
 </div>
{% endblock %}
</code>```

The view is as follows:

```<code>@login_required(login_url="login/")
def review(request):
    table = DummyTable(DummyModel.objects.all())
    form = DummyForm()
    RequestConfig(request, paginate={"per_page": 10}).configure(table)
    return render(request, 'review.html', {'reviews': table, 'DummyForm': form})
</code>```

This works fine. However, what I would like to do is show a message to the user saying that there are no records when the database table is empty. In the current setting, it shows an empty table with the columns which is probably not the best from a usability point of view.

答:
There are two options. Either you set empty_text inside class Meta

```<code>class Reviews(tables.Table):

    class Meta:
        empty_text = _("There are no reviews yet")
</code>```

Or you can check it inside the template and avoid rendering table this way

```<code>{% if reviews_table.data.list %}
    {% render_table reviews_table %}
{% else %}
    <h1>There are no reviews yet</h1>
{% endif %}
</code>```

Body:
I am new to django and web development and based on examples and help on SO, I have pieced together something which takes a model and renders it in a django-table. My template code is basically as follows:

{% block content %}
{% load static %}
{% load render_table from django_tables2 %}

                {% render_table reviews %}

{% endblock %}

The view is as follows:

@login_required(login_url="login/")
def review(request):
    table = DummyTable(DummyModel.objects.all())
    form = DummyForm()
    RequestConfig(request, paginate={"per_page": 10}).configure(table)
    return render(request, 'review.html', {'reviews': table, 'DummyForm': form})

This works fine. However, what I would like to do is show a message to the user saying that there are no records when the database table is empty. In the current setting, it shows an empty table with the columns which is probably not the best from a usability point of view.

Body:
There are two options. Either you set empty_text inside class Meta

class Reviews(tables.Table):

    class Meta:
        empty_text = _("There are no reviews yet")

Or you can check it inside the template and avoid rendering table this way

{% if reviews_table.data.list %}
    {% render_table reviews_table %}
{% else %}
    <h1>There are no reviews yet</h1>
{% endif %}


问:
Linux system call getifaddr c++
in my c++ application I've wrriten this code:

```<code>struct ifaddrs *ifap;

if (0 != getifaddrs(&ifap)) {
    error = errno;
    return -1;
}

addresses.clear();
for (struct ifaddrs *ifa = ifap; ifa; ifa = ifa->ifa_next) {
    sockaddr *s=ifa->ifa_addr;
    PRINT(" LocalIP sockaddr %u.%u.%u.%u \n",s->sa_data[2],s->sa_data[3],s->sa_data[4],s->sa_data[5]);}
</code>```

when I debug the print I see that when I have static ip like 10.0.0.12 it prints it correct. but ip from DHCP like 192.168.14.12 it prints it "-64.-88.14.12"

how can I solve this issue?

10x

答:
Change %d's to %hhu's.

%d is signed integer.
%u is unsigned integer.
%hhu is unsigned char.

This code shows why:

```<code>#include <cstdio>

int main()
{
        char i = 192;
        printf("%u, %hhu, %d", i,i,i);
}
</code>```

Output: 4294967232, 192, -64

ContentLicense: CC BY-SA 2.5

Title: Linux system call getifaddr c++

Body:
in my c++ application I've wrriten this code:

struct ifaddrs *ifap;

if (0 != getifaddrs(&ifap)) {
    error = errno;
    return -1;
}

addresses.clear();
for (struct ifaddrs *ifa = ifap; ifa; ifa = ifa->ifa_next) {
    sockaddr *s=ifa->ifa_addr;
    PRINT(" LocalIP sockaddr %u.%u.%u.%u \n",s->sa_data[2],s->sa_data[3],s->sa_data[4],s->sa_data[5]);}

when I debug the print I see that when I have static ip like 10.0.0.12 it prints it correct. but ip from DHCP like 192.168.14.12 it prints it "-64.-88.14.12"

how can I solve this issue?

10x

Body:
Change %d's to %hhu's.

%d is signed integer.
%u is unsigned integer.
%hhu is unsigned char.

This code shows why:

#include <cstdio>

int main()
{
        char i = 192;
        printf("%u, %hhu, %d", i,i,i);
}

Output: 4294967232, 192, -64


问:
Determining, if a variable is a valid closure in PHP
Using the following function:

function is_closure($t) { return ( !is_string($t)  && is_callable($t)); }

Can this return true for anything else, than an anonymous closure function? If so, what would be the correct way to determine, if a variable is a closure?

Many thanks

答:
If you get an error about that does not exist ReflectionFunction, use backslash before class:

```<code>// Closure
$closure = function () {};
$reflection = new \ReflectionFunction($closure);
// checkout if it is a closure
$test->isTrue($reflection->isClosure());
</code>```

Body:
If you get an error about that does not exist ReflectionFunction, use backslash before class:

// Closure
$closure = function () {};
$reflection = new \ReflectionFunction($closure);
// checkout if it is a closure
$test->isTrue($reflection->isClosure());


问:
How do I count the number of rows and columns in a file using bash?
Say I have a large file with many rows and many columns. I'd like to find out how many rows and columns I have using bash.</p>

答:
Little twist to kirill_igum's answer, and you can easily count the number of columns of any certain row you want, which was why I've come to this question, even though the question is asking for the whole file. (Though if your file has same columns in each line this also still works of course):

```<code>head -2 file |tail -1 |tr '\t' '\n' |wc -l
</code>```

Gives the number of columns of row 2.
Replace 2 with 55 for example to get it for row 55.

```<code>-bash-4.2$ cat file
1       2       3
1       2       3       4
1       2
1       2       3       4       5

-bash-4.2$ head -1 file |tail -1 |tr '\t' '\n' |wc -l
3
-bash-4.2$ head -4 file |tail -1 |tr '\t' '\n' |wc -l
5
</code>```

Code above works if your file is separated by tabs, as we define it to "tr". If your file has another separator, say commas, you can still count your "columns" using the same trick by simply changing the separator character "t" to ",":

```<code>-bash-4.2$ cat csvfile
1,2,3,4
1,2
1,2,3,4,5
-bash-4.2$ head -2 csvfile |tail -1 |tr '\,' '\n' |wc -l
2
</code>```

Body:
Little twist to kirill_igum's answer, and you can easily count the number of columns of any certain row you want, which was why I've come to this question, even though the question is asking for the whole file. (Though if your file has same columns in each line this also still works of course):

head -2 file |tail -1 |tr '\t' '\n' |wc -l

Gives the number of columns of row 2.
Replace 2 with 55 for example to get it for row 55.

-bash-4.2$ cat file
1       2       3
1       2       3       4
1       2
1       2       3       4       5

-bash-4.2$ head -1 file |tail -1 |tr '\t' '\n' |wc -l
3
-bash-4.2$ head -4 file |tail -1 |tr '\t' '\n' |wc -l
5

Code above works if your file is separated by tabs, as we define it to "tr". If your file has another separator, say commas, you can still count your "columns" using the same trick by simply changing the separator character "t" to ",":

-bash-4.2$ cat csvfile
1,2,3,4
1,2
1,2,3,4,5
-bash-4.2$ head -2 csvfile |tail -1 |tr '\,' '\n' |wc -l
2


问:
How to select tuples that begin with a certain substring in R
I have a data frame that looks as follows

```<code>> df[1:10,c("Uri","Latency")]
                                                                                Uri
1                          /filters/test_group_1/test_datasource%20with%20space/test_application_alias_100
2                                                          /applications?includeDashboards&includeMappings
3                                                                   /applications/test_application_alias_1
4                                                          /applications?includeDashboards&includeMappings
5                                                                 /applications/test_application_alias_200
6                                                                 /applications/test_application_alias_100
7    /filters/00000000-0000-0000-0000-000000000001/test_datasource%20with%20space/test_application_alias_0
8                                             /dashboards?dashboard=test_dashboard_alias_9&includeMappings
9               /filters/00000000-0000-0000-0000-000000000001/test_dataSource_1/test_application_alias_100
10 /filters/00000000-0000-0000-0000-000000000001/test_datasource%20with%20space/test_application_alias_100
   Latency
1      296
2     1388
3       58
4      833
5      239
6       60
7      217
8       36
9       86
10     112
</code>```

I want to select only those rows that start with /applications. Note that the rest of the Uri could be anything, and is not important.

I could've got the exact matches by doing the following,

```<code>df[which(df$Uri == "/applications"),c("Uri","Latency")]
</code>```

However, since, I am looking for a substring, I understand, I may have to do some wildcard processing, which in SQL would look like.

```<code>select * from <table_name> where Uri like '%/applications%'
</code>```

How can I do the same in R

答:
Assuming that df$Uri is a character vector, I'd go with with:

```<code>df[startsWith(df$Uri, "/applications"), ]
</code>```

Body:
I have a data frame that looks as follows

> df[1:10,c("Uri","Latency")]
                                                                                Uri
1                          /filters/test_group_1/test_datasource%20with%20space/test_application_alias_100
2                                                          /applications?includeDashboards&includeMappings
3                                                                   /applications/test_application_alias_1
4                                                          /applications?includeDashboards&includeMappings
5                                                                 /applications/test_application_alias_200
6                                                                 /applications/test_application_alias_100
7    /filters/00000000-0000-0000-0000-000000000001/test_datasource%20with%20space/test_application_alias_0
8                                             /dashboards?dashboard=test_dashboard_alias_9&includeMappings
9               /filters/00000000-0000-0000-0000-000000000001/test_dataSource_1/test_application_alias_100
10 /filters/00000000-0000-0000-0000-000000000001/test_datasource%20with%20space/test_application_alias_100
   Latency
1      296
2     1388
3       58
4      833
5      239
6       60
7      217
8       36
9       86
10     112

I want to select only those rows that start with /applications. Note that the rest of the Uri could be anything, and is not important.

I could've got the exact matches by doing the following,

df[which(df$Uri == "/applications"),c("Uri","Latency")]

However, since, I am looking for a substring, I understand, I may have to do some wildcard processing, which in SQL would look like.

select * from <table_name> where Uri like '%/applications%'

How can I do the same in R

Body:
Assuming that df$Uri is a character vector, I'd go with with:

df[startsWith(df$Uri, "/applications"), ]


问:
Change _FillValue in netCDF file
Is there a python netCDF4 command/example to change the global metadata _FillValue in a netCDF file? I have tried replacing all -ve values in a netCDF file, but till the time the _FillValue attribute is set, that does not work</p>

答:
You can also use cdo to set the missing entries to another value, for example 999.0

```<code>cdo setmisstoc,999.0 in.nc out.nc
</code>```

However, from the description of your problem, it seems that you don't actually need to change the value for _Fillvalue but instead you want to set negative values to missing. You can achieve this by using the cdo function "set range to miss"

```<code>cdo setrtomiss,-1e8,0 in.nc out.nc
</code>```

the first argument is a big negative number that is smaller than the smallest value in your dataset.   I'm assuming in the above answer that the field in question does already have a value set, otherwise you would need to add it with e.g.

```<code>cdo setattribute,field@_FillValue=-1.e32 infile outfile
</code>```

In general it seems that defining a "global" _FillValue can cause issues (e.g. see https://github.com/Unidata/netcdf-c/issues/458) and anyway if you have a combination of integer and float fields then defining a default float fill can not be applied to all fields. I'm personally of the opinion that it is best practise to define a fill value for each field separately and if possible use the defaults for each data type.

cdo commands can be called directly from python using the cdo package.

Title: Change _FillValue in netCDF file

Body:
You can also use cdo to set the missing entries to another value, for example 999.0

cdo setmisstoc,999.0 in.nc out.nc

However, from the description of your problem, it seems that you don't actually need to change the value for _Fillvalue but instead you want to set negative values to missing. You can achieve this by using the cdo function "set range to miss"

cdo setrtomiss,-1e8,0 in.nc out.nc

the first argument is a big negative number that is smaller than the smallest value in your dataset.   I'm assuming in the above answer that the field in question does already have a value set, otherwise you would need to add it with e.g.

cdo setattribute,field@_FillValue=-1.e32 infile outfile

In general it seems that defining a "global" _FillValue can cause issues (e.g. see https://github.com/Unidata/netcdf-c/issues/458) and anyway if you have a combination of integer and float fields then defining a default float fill can not be applied to all fields. I'm personally of the opinion that it is best practise to define a fill value for each field separately and if possible use the defaults for each data type.

cdo commands can be called directly from python using the cdo package.


问:
Sleep in JQuery?
greetings all
i want to make JQuery sleep/wait for a second between two functions

```<code>$('#div1').hide();
//sleep or wait or for a sec
$("#div2").show();
</code>```

how to do so ?

答:
You can't just pause the execution of the code between the calls. That would mean that the browser would not display the change caused by the hide call, as no updates are done while the code is running. The code would just appear to do nothing.

Use the setTimeout method to schedule code to be executed at a later time:

```<code>$('#div1').hide();
window.setTimeout(function(){
  $("#div2").show();
}, 1000);
</code>```

This will set the element as hidden and schedule the code to show it to start later. The code will continue after the setTimeout call so that the function can exit and the browser gets back the control so that it can actually hide the element.

Title: Sleep in JQuery?

Body:
greetings all
i want to make JQuery sleep/wait for a second between two functions

$('#div1').hide();
//sleep or wait or for a sec
$("#div2").show();

how to do so ?

Body:
You can't just pause the execution of the code between the calls. That would mean that the browser would not display the change caused by the hide call, as no updates are done while the code is running. The code would just appear to do nothing.

Use the setTimeout method to schedule code to be executed at a later time:

$('#div1').hide();
window.setTimeout(function(){
  $("#div2").show();
}, 1000);

This will set the element as hidden and schedule the code to show it to start later. The code will continue after the setTimeout call so that the function can exit and the browser gets back the control so that it can actually hide the element.


问:
How to do databind two way in v-html?
I have an element div with atribute contenteditable="true". This div behaves like an element textarea.

```<code><div v-on:keyup.enter="SendMensage" v-html="msg" contenteditable="true"></div>
</code>```

my code:

```<code>data() {
     return {
        msg: '',
     }
},

methods: {
     enviaMensagem() {

        console.log(this.msg);

     }
}
</code>```

My problem is that the databind does not work. What is typed in the div does not reflect on the variable. Does anyone know what can it be?

答:
You need to listen to changes of the element, because v-model only works on <textarea> or <input>. You can do this by using an @input listener.

The markup you get like this will be escaped. If you want to unescape it, you can use e.g. this approach. Then, you actually have the markup right next to the pseudo-textarea field. So, why not using a <textarea> from begin with?

new Vue({
  el: '#editor',
  data: {
    msg: ''
  },
  methods: {
    typing: function(el) {
      this.msg = el.target.innerHTML;
    },
    submit: function() {
      console.log("Submitting: ", this.msg);
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.input {
  display: inline-block;
  vertical-align: middle;
  border: 1px solid black;
  width: 200px;
  height: 100px;
}
.output {
  display: inline-block;
  vertical-align: middle;
  width: 200px;
  height: 100px;
  background: #eee;
}</code>```

```

Title: How to do databind two way in v-html?

Body:
I have an element div with atribute contenteditable="true". This div behaves like an element textarea.

my code:

data() {
     return {
        msg: '',
     }
},

methods: {
     enviaMensagem() {

        console.log(this.msg);

     }
}

My problem is that the databind does not work. What is typed in the div does not reflect on the variable. Does anyone know what can it be?

Body:
You need to listen to changes of the element, because v-model only works on <textarea> or <input>. You can do this by using an @input listener.

The markup you get like this will be escaped. If you want to unescape it, you can use e.g. this approach. Then, you actually have the markup right next to the pseudo-textarea field. So, why not using a <textarea> from begin with?

new Vue({
  el: '#editor',
  data: {
    msg: ''
  },
  methods: {
    typing: function(el) {
      this.msg = el.target.innerHTML;
    },
    submit: function() {
      console.log("Submitting: ", this.msg);
    }
  }
});

.input {
  display: inline-block;
  vertical-align: middle;
  border: 1px solid black;
  width: 200px;
  height: 100px;
}
.output {
  display: inline-block;
  vertical-align: middle;
  width: 200px;
  height: 100px;
  background: #eee;
}

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script>

<div id="editor">
  <div class="input" @input="typing" @keyup.enter="submit" contenteditable="true"></div>
  <div class="output" v-html="msg"></div>
</div>


问:
Mathematica: what is symbolic programming?
I am a big fan of Stephen Wolfram, but he is definitely one not shy of tooting his own horn.  In many references, he extols Mathematica as a different symbolic programming paradigm.  I am not a Mathematica user.

My questions are: what is this symbolic programming? And how does it compare to functional languages (such as Haskell)?

答:
As others here already mentioned, Mathematica does a lot of term rewriting. Maybe Haskell isn't the best comparison though, but Pure is a nice functional term-rewriting language (that should feel familiar to people with a Haskell background). Maybe reading their Wiki page on term rewriting will clear up a few things for you:

http://code.google.com/p/pure-lang/wiki/Rewriting


问:
How can I loop through and pare down an object?
If i have the following:

```<code>{
    prop: "X",
    something: "Apple"
},
{
    prop: "X",
    something: "Apple"
},
{
    prop: "Y",
    something: "Banana"
},
{
    prop: "Y",
    something: "Banana"
}
</code>```

How can I morph that into a new object that would look something like this?

```<code>{
    prop: "X",
    apple: 2
},
{
    prop: "Y",
    banana: 2
}
</code>```

答:
Array.prototype.reduce can be helpful here:

let data = [{
    prop: "X",
    something: "Apple"
},
{
    prop: "X",
    something: "Apple"
},
{
    prop: "Y",
    something: "Banana"
},
{
    prop: "Y",
    something: "Banana"
}];

let newData = data.reduce((prev, curr) => {
  prev[curr.prop] = prev[curr.prop] || {};

  let lowercaseKey = curr.something.toLowerCase();

  prev[curr.prop][lowercaseKey] = prev[curr.prop][lowercaseKey] ? prev[curr.prop][lowercaseKey] + 1 : 1;
  prev[curr.prop].prop = curr.prop;

  return prev;
}, {});

newData = Object.keys(newData).map(key => newData[key]);

console.log(newData);```

Basically, it uses an object as an accumulator (the last argument of the reduce function) to keep track of the total values for each item in the array (this is beneficial instead of just immediately pushing to a new array, because you'd first have to iterate through the new array for every iteration of the reduce function to find if the object already exists or not). Then, lastly, we iterate once more over all the keys of the new object, and get the values.

Pro-tip: Easier to understand if you play around with the code snippet above and log the values during each iteration.

Body:
If i have the following:

{
    prop: "X",
    something: "Apple"
},
{
    prop: "X",
    something: "Apple"
},
{
    prop: "Y",
    something: "Banana"
},
{
    prop: "Y",
    something: "Banana"
}

How can I morph that into a new object that would look something like this?

{
    prop: "X",
    apple: 2
},
{
    prop: "Y",
    banana: 2
}

Body:
Array.prototype.reduce can be helpful here:

let data = [{
    prop: "X",
    something: "Apple"
},
{
    prop: "X",
    something: "Apple"
},
{
    prop: "Y",
    something: "Banana"
},
{
    prop: "Y",
    something: "Banana"
}];

let newData = data.reduce((prev, curr) => {
  prev[curr.prop] = prev[curr.prop] || {};

  let lowercaseKey = curr.something.toLowerCase();

  prev[curr.prop][lowercaseKey] = prev[curr.prop][lowercaseKey] ? prev[curr.prop][lowercaseKey] + 1 : 1;
  prev[curr.prop].prop = curr.prop;

  return prev;
}, {});

newData = Object.keys(newData).map(key => newData[key]);

console.log(newData);

Basically, it uses an object as an accumulator (the last argument of the reduce function) to keep track of the total values for each item in the array (this is beneficial instead of just immediately pushing to a new array, because you'd first have to iterate through the new array for every iteration of the reduce function to find if the object already exists or not). Then, lastly, we iterate once more over all the keys of the new object, and get the values.

Pro-tip: Easier to understand if you play around with the code snippet above and log the values during each iteration.


问:
Fabricjs - How to move the selected object by keyboard
i want to move the selected object by keyboard，because it can be moved more accurately,I don't know how to do it. </p>

答:
Here is my simple implementation of moving selected object/group using left/up/right/down keys:

https://jsfiddle.net/milanhlinak/4fofjzvm/

```<code><!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src="lib/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="lib/fabric.min.js"></script>
</head>

<body>

    <canvas id="canvas" style="border: 1px solid #cccccc"></canvas>

    <script>
        const STEP = 10;

        var Direction = {
            LEFT: 0,
            UP: 1,
            RIGHT: 2,
            DOWN: 3
        };

        var canvas = new fabric.Canvas('canvas', {
            width: 500,
            height: 500,
        });

        canvas.add(new fabric.Rect({
            left: 100,
            top: 100,
            width: 50,
            height: 50,
            fill: '#faa'

        }));
        canvas.add(new fabric.Rect({
            left: 300,
            top: 300,
            width: 50,
            height: 50,
            fill: '#afa'
        }));

        fabric.util.addListener(document.body, 'keydown', function (options) {
            if (options.repeat) {
                return;
            }
            var key = options.which || options.keyCode; // key detection
            if (key === 37) { // handle Left key
                moveSelected(Direction.LEFT);
            } else if (key === 38) { // handle Up key
                moveSelected(Direction.UP);
            } else if (key === 39) { // handle Right key
                moveSelected(Direction.RIGHT);
            } else if (key === 40) { // handle Down key
                moveSelected(Direction.DOWN);
            }
        });

        function moveSelected(direction) {

            var activeObject = canvas.getActiveObject();
            var activeGroup = canvas.getActiveGroup();

            if (activeObject) {
                switch (direction) {
                case Direction.LEFT:
                    activeObject.setLeft(activeObject.getLeft() - STEP);
                    break;
                case Direction.UP:
                    activeObject.setTop(activeObject.getTop() - STEP);
                    break;
                case Direction.RIGHT:
                    activeObject.setLeft(activeObject.getLeft() + STEP);
                    break;
                case Direction.DOWN:
                    activeObject.setTop(activeObject.getTop() + STEP);
                    break;
                }
                activeObject.setCoords();
                canvas.renderAll();
                console.log('selected objects was moved');
            } else if (activeGroup) {
                switch (direction) {
                case Direction.LEFT:
                    activeGroup.setLeft(activeGroup.getLeft() - STEP);
                    break;
                case Direction.UP:
                    activeGroup.setTop(activeGroup.getTop() - STEP);
                    break;
                case Direction.RIGHT:
                    activeGroup.setLeft(activeGroup.getLeft() + STEP);
                    break;
                case Direction.DOWN:
                    activeGroup.setTop(activeGroup.getTop() + STEP);
                    break;
                }
                activeGroup.setCoords();
                canvas.renderAll();
                console.log('selected group was moved');
            } else {
                console.log('no object selected');
            }

        }
    </script>

</body>

</html>
</code>```

Body:
Here is my simple implementation of moving selected object/group using left/up/right/down keys:

https://jsfiddle.net/milanhlinak/4fofjzvm/

<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src="lib/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="lib/fabric.min.js"></script>
</head>

<body>

    <canvas id="canvas" style="border: 1px solid #cccccc"></canvas>

    <script>
        const STEP = 10;

        var Direction = {
            LEFT: 0,
            UP: 1,
            RIGHT: 2,
            DOWN: 3
        };

        var canvas = new fabric.Canvas('canvas', {
            width: 500,
            height: 500,
        });

        canvas.add(new fabric.Rect({
            left: 100,
            top: 100,
            width: 50,
            height: 50,
            fill: '#faa'

        }));
        canvas.add(new fabric.Rect({
            left: 300,
            top: 300,
            width: 50,
            height: 50,
            fill: '#afa'
        }));

        fabric.util.addListener(document.body, 'keydown', function (options) {
            if (options.repeat) {
                return;
            }
            var key = options.which || options.keyCode; // key detection
            if (key === 37) { // handle Left key
                moveSelected(Direction.LEFT);
            } else if (key === 38) { // handle Up key
                moveSelected(Direction.UP);
            } else if (key === 39) { // handle Right key
                moveSelected(Direction.RIGHT);
            } else if (key === 40) { // handle Down key
                moveSelected(Direction.DOWN);
            }
        });

        function moveSelected(direction) {

            var activeObject = canvas.getActiveObject();
            var activeGroup = canvas.getActiveGroup();

            if (activeObject) {
                switch (direction) {
                case Direction.LEFT:
                    activeObject.setLeft(activeObject.getLeft() - STEP);
                    break;
                case Direction.UP:
                    activeObject.setTop(activeObject.getTop() - STEP);
                    break;
                case Direction.RIGHT:
                    activeObject.setLeft(activeObject.getLeft() + STEP);
                    break;
                case Direction.DOWN:
                    activeObject.setTop(activeObject.getTop() + STEP);
                    break;
                }
                activeObject.setCoords();
                canvas.renderAll();
                console.log('selected objects was moved');
            } else if (activeGroup) {
                switch (direction) {
                case Direction.LEFT:
                    activeGroup.setLeft(activeGroup.getLeft() - STEP);
                    break;
                case Direction.UP:
                    activeGroup.setTop(activeGroup.getTop() - STEP);
                    break;
                case Direction.RIGHT:
                    activeGroup.setLeft(activeGroup.getLeft() + STEP);
                    break;
                case Direction.DOWN:
                    activeGroup.setTop(activeGroup.getTop() + STEP);
                    break;
                }
                activeGroup.setCoords();
                canvas.renderAll();
                console.log('selected group was moved');
            } else {
                console.log('no object selected');
            }

        }
    </script>

</body>

</html>


问:
@Id annotation not working in Hibernate with Oracle
I am learning hibernate from this book and I am trying to save an entity Book.

```<code>import javax.persistence.Entity;

import javax.persistence.Id;

@Entity
public class Book {

@Id

private int id;

private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

    Book book1 = new Book();

    book1.setName("Sample");
    session.save(book1);
</code>```

But this code works only one time and that too when there is no data in Books table, because each time it generates '0' as the primary key id.Below is the exception trace.

```<code>ERROR: HHH000346: Error during managed flush

[org.hibernate.exception.ConstraintViolationException: could not execute statement]
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1403)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:473)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3133)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2370)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)

Caused by: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (SPRING.SYS_C0015610) violated

    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:450)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399)
    at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1059)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:522)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:257)
    at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:587)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:225)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:53)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:943)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1150)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:4798)
    at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:4875)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1361)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
    ... 19 more
</code>```

Book says:

By default, the @Id annotation will automatically determine the most appropriate primary
  key generation strategy to use—you can override this by also applying the @GeneratedValue
  annotation

However, if I use @GeneratedValue annotation with @ID the code works fine and each time a new primary key id is generated. This scenario doesn't make sense to me. Am I missing anything or is there any db specific issue?

```<code>CREATE TABLE BOOK(
ID INTEGER,
NAME VARCHAR2(50)
);

ALTER TABLE BOOK ADD PRIMARY KEY(ID);
</code>```

答:
Hibernate use  assigned as  default generator strategy if there is no  element . In this case, your application assigns the id of entity.
If you want hibernate will take care of auto generation id then you should use GeneratedValue or any another id Generated strategy

```<code>@Id
@GeneratedValue(strategy = GenerationType.AUTO)
</code>```

here are some examples

You id type is int

```<code>private int id;
</code>```

When you first time insert value then jvm will assign id default value 0 so hibernate easily insert id with 0 value,
Now when your again try to insert value because there is no id generator strategy  then again jvm set id default value 0 and when hibernate try to insert it with id 0 value then its throw ConstraintViolationException  exception because id with 0 value already exist in database.
So if you want hibernate with auto assign the Id for your entity you can use jpa specific @GeneratedValue strategy (AUTO/IDENTITY/SEQUENCE/TABLE)
or another hibernate strategy which will take care of assign id for Entity

```<code>      increment
      sequence
      hilo
      native
      identity
      seqhilo
      uuid
      guid
      select
      foreign
      sequence-identity
</code>```

Body:
I am learning hibernate from this book and I am trying to save an entity Book.

import javax.persistence.Entity;

import javax.persistence.Id;

@Entity
public class Book {

@Id

private int id;

private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

    Book book1 = new Book();

    book1.setName("Sample");
    session.save(book1);

But this code works only one time and that too when there is no data in Books table, because each time it generates '0' as the primary key id.Below is the exception trace.

ERROR: HHH000346: Error during managed flush

[org.hibernate.exception.ConstraintViolationException: could not execute statement]
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1403)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:473)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3133)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2370)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)

Caused by: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (SPRING.SYS_C0015610) violated

    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:450)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399)
    at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1059)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:522)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:257)
    at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:587)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:225)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:53)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:943)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1150)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:4798)
    at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:4875)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1361)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
    ... 19 more

Book says:

By default, the @Id annotation will automatically determine the most appropriate primary
  key generation strategy to use—you can override this by also applying the @GeneratedValue
  annotation

However, if I use @GeneratedValue annotation with @ID the code works fine and each time a new primary key id is generated. This scenario doesn't make sense to me. Am I missing anything or is there any db specific issue?

CREATE TABLE BOOK(
ID INTEGER,
NAME VARCHAR2(50)
);

ALTER TABLE BOOK ADD PRIMARY KEY(ID);

Body:
Hibernate use  assigned as  default generator strategy if there is no  element . In this case, your application assigns the id of entity.
If you want hibernate will take care of auto generation id then you should use GeneratedValue or any another id Generated strategy

@Id
@GeneratedValue(strategy = GenerationType.AUTO)

here are some examples

You id type is int

private int id;

When you first time insert value then jvm will assign id default value 0 so hibernate easily insert id with 0 value,
Now when your again try to insert value because there is no id generator strategy  then again jvm set id default value 0 and when hibernate try to insert it with id 0 value then its throw ConstraintViolationException  exception because id with 0 value already exist in database.
So if you want hibernate with auto assign the Id for your entity you can use jpa specific @GeneratedValue strategy (AUTO/IDENTITY/SEQUENCE/TABLE)
or another hibernate strategy which will take care of assign id for Entity

      increment
      sequence
      hilo
      native
      identity
      seqhilo
      uuid
      guid
      select
      foreign
      sequence-identity


问:
How to apply CSS class without affecting global behvior
I am using a third party library which has its own CSS class. This is how the DOM looks:

```<code><div id="toast-container" class="toast-custom" aria-live="polite" role="alert">
      <div class="toast toast-info" style="display: block;"> ....
</code>```

This is the class I am overriding to fix the width

```<code>.toast-custom {
  top: 0;
  left: 30%;
  width: 50%;
}
</code>```

This is the class already provided by framework

```<code>#toast-container > div {
  position: relative;
  pointer-events: auto;
  overflow: hidden;
  margin: 0 0 6px;
  padding: 15px 15px 15px 50px;
  width: 46%;
  -moz-border-radius: 3px 3px 3px 3px;
  -webkit-border-radius: 3px 3px 3px 3px;
  border-radius: 3px 3px 3px 3px;
  background-position: 15px center;
  background-repeat: no-repeat;
  -moz-box-shadow: 0 0 12px #999999;
  -webkit-box-shadow: 0 0 12px #999999;
  box-shadow: 0 0 12px #999999;
  color: #ffffff;
  opacity: 0.8;
  -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=80);
  filter: alpha(opacity=80);
}
</code>```

I am not able to modify the width of the dix without touching #toast-container > div but if I make change to #toast-container > div it will have a global impact. How can I make use of .toast-custom to make the required change?

答:
The issue that you're having is that an # "ID selector" (eg. #my-rule) is more specific than a . "class selector" (eg. .my-rule), and the [last] most specific CSS selector (rule) wins.

This should work on any #toast-containers that implements .toast-custom:

```<code>/* Note "no space" between */
#toast-container.toast-custom > div {
  ...
}
</code>```

This is basically saying "select the direct descendant  div of #toast-containers elements that also have a .toast-custom class applied." Since that is more specific than the framework's rule, your rule will override, but only in that case. -- (#toast-containers that do not implement .toast-custom should not be affected.)

From MDN

Specificity is the means by which browsers decide which CSS property
  values are the most relevant to an element and, therefore, will be
  applied.

See CSS Specificity on MDN for more information.

Body:
I am using a third party library which has its own CSS class. This is how the DOM looks:

 ....

This is the class I am overriding to fix the width

.toast-custom {
  top: 0;
  left: 30%;
  width: 50%;
}

This is the class already provided by framework

#toast-container > div {
  position: relative;
  pointer-events: auto;
  overflow: hidden;
  margin: 0 0 6px;
  padding: 15px 15px 15px 50px;
  width: 46%;
  -moz-border-radius: 3px 3px 3px 3px;
  -webkit-border-radius: 3px 3px 3px 3px;
  border-radius: 3px 3px 3px 3px;
  background-position: 15px center;
  background-repeat: no-repeat;
  -moz-box-shadow: 0 0 12px #999999;
  -webkit-box-shadow: 0 0 12px #999999;
  box-shadow: 0 0 12px #999999;
  color: #ffffff;
  opacity: 0.8;
  -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=80);
  filter: alpha(opacity=80);
}

I am not able to modify the width of the dix without touching #toast-container > div but if I make change to #toast-container > div it will have a global impact. How can I make use of .toast-custom to make the required change?

Body:
The issue that you're having is that an # "ID selector" (eg. #my-rule) is more specific than a . "class selector" (eg. .my-rule), and the [last] most specific CSS selector (rule) wins.

This should work on any #toast-containers that implements .toast-custom:

/* Note "no space" between */
#toast-container.toast-custom > div {
  ...
}

This is basically saying "select the direct descendant  div of #toast-containers elements that also have a .toast-custom class applied." Since that is more specific than the framework's rule, your rule will override, but only in that case. -- (#toast-containers that do not implement .toast-custom should not be affected.)

From MDN

Specificity is the means by which browsers decide which CSS property
  values are the most relevant to an element and, therefore, will be
  applied.

See CSS Specificity on MDN for more information.


问:
Token replacement
I currently implement a replace function in the page render method which replaces commonly used strings - such as replace [cfe] with the root to the customer front end. This is because the value may be different based on the version of the site - for example the root to the image folder ([imagepath]) is /Images on development and live, but /Test/Images on test.

I have a catalogue of products for which I would like to change [productName] to a link to the catalogue page for that product. I would like to go through the entire page and replace all instances of [someValue] with the relevant link. Currently I do this by looping through all the products in the product database and replacing [productName] with the link to the catalog page for that product. However this is limited to products which exist in the database. "Links" to products which have been removed currently wont be replaced, so [someValue] will be displayed to the user. This does not look good.

So you should be able to see my problem from this. Does anyone know of a way to achieve what I would like to easily? I could use regexes, but I don't have much experience of those. If this is the easiest way, using "For Each Match As String In Regex.Matches(blah, blah)" then I am willing to look further into this.

However at some point I would like to take this further - for example setting page layouts such as 3 columns with an image top right using [layout type="3colImageTopRight" imageURL="imageURL"]Content here[/layout]. I think I could kind of do this now, but I cant figure out how to deal with this if the imageURL were, say, [Image:Product01.gif] (using regex.match("[[a-zA-Z]{0,}]") I think would match just [layout type="3colImageTopRight" imageURL="[Image:Product01.gif] (it would not get to the end of the layout tag). Obviously the above wouldn't quite work, as I haven't included double quotes in the match string or anything, but you get the general idea. You should be able to get the general idea of what I am getting at and what I am trying to do though.

Does anyone have any ideas or pointers which could help me with this? Also if this is not strictly token replacement then please point me to what it is, so I can further develop this.

Aristos - hope reexplaining this resolves the confusion.

Thanks in advance,

Regards,

Richard Clarke

答:
@RichardClarke - I would go with Regular Expressions, they're not as terrible to learn as you might think and with a bit of careful usage will solve your problems.

I've always found this a very useful tool.

```<code> http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx
</code>```

goes nicely with a cheat sheet ;-)

```<code> http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/
</code>```

Good luck.

Title: Token replacement

Body:
@RichardClarke - I would go with Regular Expressions, they're not as terrible to learn as you might think and with a bit of careful usage will solve your problems.

I've always found this a very useful tool.

 http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx

goes nicely with a cheat sheet ;-)

 http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/

Good luck.


问:
subprocess Popen.stdin.write causes AttributeError
I'm working on a short, native (do NOT recommend an outside [non-native] module such as pexpect), cross-platform, insecure remote control application for python (Windows will use py2exe and an exe file). I am using start_new_thread for the blocking calls such as readline(). For some reason, however, I get this string of ugliness as my output:

```<code>Unhandled exception in thread started by <function read_stream at 0xb6918730>Unhandled exception in thread started by <function send_stream at 0xb69186f0>
Traceback (most recent call last):

Traceback (most recent call last):
  File "main.py", line 17, in read_stream
    s.send(pipe.stdout.readline())
AttributeError  File "main.py", line 14, in send_stream
    pipe.stdin.write(s.recv(4096))
AttributeError: 'NoneType' object has no attribute 'stdin'
: 'NoneType' object has no attribute 'stdout'
</code>```

Here is my program (main.py):

```<code>#!/usr/bin/env python
import socket
import subprocess as sp
from thread import start_new_thread
from platform import system

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.0.0.201', 49200))
shell = 'powershell.exe' if system() == 'Windows' else '/bin/bash' # is this right?
pipe = sp.Popen(shell, shell=True, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
entered_command=False
def send_stream(): # send what you get from command center
        while True:
                pipe.stdin.write(s.recv(4096))
def read_stream(): # send back what is returned from shell command
        while True:
                s.send(pipe.stdout.readline())
start_new_thread(send_stream, ())
start_new_thread(read_stream, ())
</code>```

Thanks for your help.

答:
It turns out that the problem is that the program was trying to exit after the two start_new_thread calls because it had reached the end, and caused errors while trying to do so. So I replaced:

```<code>start_new_thread(send_stream, ())
start_new_thread(read_stream, ())
</code>```

With:

```<code>start_new_thread(send_stream, ())
read_stream()
</code>```

Body:
I'm working on a short, native (do NOT recommend an outside [non-native] module such as pexpect), cross-platform, insecure remote control application for python (Windows will use py2exe and an exe file). I am using start_new_thread for the blocking calls such as readline(). For some reason, however, I get this string of ugliness as my output:

Unhandled exception in thread started by <function read_stream at 0xb6918730>Unhandled exception in thread started by <function send_stream at 0xb69186f0>
Traceback (most recent call last):

Traceback (most recent call last):
  File "main.py", line 17, in read_stream
    s.send(pipe.stdout.readline())
AttributeError  File "main.py", line 14, in send_stream
    pipe.stdin.write(s.recv(4096))
AttributeError: 'NoneType' object has no attribute 'stdin'
: 'NoneType' object has no attribute 'stdout'

Here is my program (main.py):

#!/usr/bin/env python
import socket
import subprocess as sp
from thread import start_new_thread
from platform import system

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.0.0.201', 49200))
shell = 'powershell.exe' if system() == 'Windows' else '/bin/bash' # is this right?
pipe = sp.Popen(shell, shell=True, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
entered_command=False
def send_stream(): # send what you get from command center
        while True:
                pipe.stdin.write(s.recv(4096))
def read_stream(): # send back what is returned from shell command
        while True:
                s.send(pipe.stdout.readline())
start_new_thread(send_stream, ())
start_new_thread(read_stream, ())

Thanks for your help.

Body:
It turns out that the problem is that the program was trying to exit after the two start_new_thread calls because it had reached the end, and caused errors while trying to do so. So I replaced:

start_new_thread(send_stream, ())
start_new_thread(read_stream, ())

With:

start_new_thread(send_stream, ())
read_stream()


问:
How to make smaller a background circle in a font awesome icon?
I need to produce the following warning sign using Font Awesome:

However, I am not able to make it exactly as it is because I have like an extra border:

This is my HTML:

```<code><div role="alert" class="alert alert-dismissible">
  <i id="exclamation-mark" class="fa fa-exclamation-circle extraClass" aria-hidden="true"></i>
  <p style="display: inline;vertical-align: middle">
    <span>Oops! Something went horribly wrong. </span> We’re really sorry. Please try that again.
  </p>
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    ×
  </button>
</div>
</code>```

This is my CSS (SCSS):

```<code>$color-secondary-1: #db2b4b;

p > span {
  font-weight: bold;
}

div {
  color: white;
  text-align: center;
  background-color: $color-secondary-1;

  i {
    font-size: 100px;
    color: #ff91a5;
    background: white;
    border-radius: 50%;
    height: 1em;
    width: 1em;
  }
}

.extraClass{
     font-size:3em;
}
</code>```

This is my CodePen link.

答:
you could use a radial-gradient to draw your background:

```<code>background: radial-gradient(circle at center,white 20px,transparent 20px) no-repeat center;
</code>```

p > span {
  font-weight: bold;
}

div {
  color: white;
  text-align: center;
  background-color: #db2b4b;
}
div i {
  font-size: 50px!important;/* for demo purpose in the snippet on SO */
  color: #ff91a5;
  background: radial-gradient(circle at center, #ffffff 20px, rgba(0, 0, 0, 0) 20px) no-repeat center;
  border-radius: 50%;
  height: 1em;
  width: 1em;
}

.extraClass {
  font-size: 3em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/>
<div role="alert" class="alert alert-dismissible">
  <i id="exclamation-mark" class="fa fa-exclamation-circle extraClass" aria-hidden="true"></i>
  <p style="display: inline;vertical-align: middle">
    <span>Oops! Something went horribly wrong. </span> We’re really sorry. Please try that again.
  </p>
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">    ×
  </button>
</div></code>```

Body:
I need to produce the following warning sign using Font Awesome:

However, I am not able to make it exactly as it is because I have like an extra border:

This is my HTML:

    Oops! Something went horribly wrong.  We’re really sorry. Please try that again.

  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    ×
  </button>

This is my CSS (SCSS):

$color-secondary-1: #db2b4b;

p > span {
  font-weight: bold;
}

div {
  color: white;
  text-align: center;
  background-color: $color-secondary-1;

  i {
    font-size: 100px;
    color: #ff91a5;
    background: white;
    border-radius: 50%;
    height: 1em;
    width: 1em;
  }
}

.extraClass{
     font-size:3em;
}

This is my CodePen link.

Body:
you could use a radial-gradient to draw your background:

background: radial-gradient(circle at center,white 20px,transparent 20px) no-repeat center;

p > span {
  font-weight: bold;
}

div {
  color: white;
  text-align: center;
  background-color: #db2b4b;
}
div i {
  font-size: 50px!important;/* for demo purpose in the snippet on SO */
  color: #ff91a5;
  background: radial-gradient(circle at center, #ffffff 20px, rgba(0, 0, 0, 0) 20px) no-repeat center;
  border-radius: 50%;
  height: 1em;
  width: 1em;
}

.extraClass {
  font-size: 3em;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/>
<div role="alert" class="alert alert-dismissible">
  <i id="exclamation-mark" class="fa fa-exclamation-circle extraClass" aria-hidden="true"></i>
  <p style="display: inline;vertical-align: middle">
    <span>Oops! Something went horribly wrong. </span> We’re really sorry. Please try that again.
  </p>
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">    ×
  </button>
</div>


问:
splitting large file into small files
I have a text file which has thousands of number values like
1
2
3
4
5
.
.
.
.
n

I know we can use awk to separate these values. But is there a way in which one can fetch first 10,20,40,80,160....,n values in different text files.

I was using python to do so but it takes a lot of time to separate these files.Here is the sample code for python

```<code>import numpy as np
from itertools import islice
data = np.loadtxt('ABC.txt',
                 unpack=True,
                 delimiter=',',
                 skiprows=1)
n = 10
iterator = list(islice(data[0], n))
for item in range(n):
np.savetxt('output1.txt',iterator,delimiter=',',fmt='%10.5f')

iterator = list(islice(data[0], n*2))
for item in iterator:
np.savetxt('output2.txt', iterator, delimiter=',',fmt='%10.5f')

iterator = list(islice(data[0], n*4))
for item in iterator:
np.savetxt('output3.txt', iterator, delimiter=',',fmt='%10.5f')

iterator = list(islice(data[0], n*8))
for item in iterator:
np.savetxt('output4.txt', iterator, delimiter=',',fmt='%10.5f')
</code>```

and so on.

Is there a better way to do this in bash or in python. Thank you in advance!

答:
SED is your friend:</p>

```<code>$ numlines=$( wc -l big_text_file.txt | cut -d' ' -f1 )

$ step=100

$ echo $numlines
861

$ for (( ii=1; ii<=$numlines; ii+=$step )); do echo $ii,$(( ii+step-1 ))w big_text_file.${ii}.txt; done > break.sed

$ cat break.sed
1,100w big_text_file.1.txt
101,200w big_text_file.101.txt
201,300w big_text_file.201.txt
301,400w big_text_file.301.txt
401,500w big_text_file.401.txt
501,600w big_text_file.501.txt
601,700w big_text_file.601.txt
701,800w big_text_file.701.txt
801,900w big_text_file.801.txt

$ sed -n -f break.sed big_text_file.txt

$ wc -l big_text_file*.txt
   100 big_text_file.101.txt
   100 big_text_file.1.txt
   100 big_text_file.201.txt
   100 big_text_file.301.txt
   100 big_text_file.401.txt
   100 big_text_file.501.txt
   100 big_text_file.601.txt
   100 big_text_file.701.txt
    61 big_text_file.801.txt
   861 big_text_file.txt
  1722 total
</code>```

Title: splitting large file into small files

Body:
I have a text file which has thousands of number values like
1
2
3
4
5
.
.
.
.
n

I know we can use awk to separate these values. But is there a way in which one can fetch first 10,20,40,80,160....,n values in different text files.

I was using python to do so but it takes a lot of time to separate these files.Here is the sample code for python

import numpy as np
from itertools import islice
data = np.loadtxt('ABC.txt',
                 unpack=True,
                 delimiter=',',
                 skiprows=1)
n = 10
iterator = list(islice(data[0], n))
for item in range(n):
np.savetxt('output1.txt',iterator,delimiter=',',fmt='%10.5f')

iterator = list(islice(data[0], n*2))
for item in iterator:
np.savetxt('output2.txt', iterator, delimiter=',',fmt='%10.5f')

iterator = list(islice(data[0], n*4))
for item in iterator:
np.savetxt('output3.txt', iterator, delimiter=',',fmt='%10.5f')

iterator = list(islice(data[0], n*8))
for item in iterator:
np.savetxt('output4.txt', iterator, delimiter=',',fmt='%10.5f')

and so on.

Is there a better way to do this in bash or in python. Thank you in advance!

Body:
SED is your friend:

$ numlines=$( wc -l big_text_file.txt | cut -d' ' -f1 )

$ step=100

$ echo $numlines
861

$ for (( ii=1; ii<=$numlines; ii+=$step )); do echo $ii,$(( ii+step-1 ))w big_text_file.${ii}.txt; done > break.sed

$ cat break.sed
1,100w big_text_file.1.txt
101,200w big_text_file.101.txt
201,300w big_text_file.201.txt
301,400w big_text_file.301.txt
401,500w big_text_file.401.txt
501,600w big_text_file.501.txt
601,700w big_text_file.601.txt
701,800w big_text_file.701.txt
801,900w big_text_file.801.txt

$ sed -n -f break.sed big_text_file.txt

$ wc -l big_text_file*.txt
   100 big_text_file.101.txt
   100 big_text_file.1.txt
   100 big_text_file.201.txt
   100 big_text_file.301.txt
   100 big_text_file.401.txt
   100 big_text_file.501.txt
   100 big_text_file.601.txt
   100 big_text_file.701.txt
    61 big_text_file.801.txt
   861 big_text_file.txt
  1722 total


问:
Reading NFC Tags with iPhone 6 / iOS 8
Now that Apple just announced the iPhone 6 will have an NFC chip, does anyone know if iOS 8 will enable reading/detecting RFID tags for the iPhone 6 device? Anyone have any details to share on this?</p>

答:
The ability to read an NFC tag has been added to iOS 11 which only support iPhone 7 and 7 plus

As a test drive I made this repo

First: We need to initiate NFCNDEFReaderSession class

```<code>var session: NFCNDEFReaderSession?
session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false)
</code>```

Then we need to start the session by:

```<code>session?.begin()
</code>```

and when done:

```<code>session?.invalidate()
</code>```

The delegate (which self should implement) has basically two functions:

```<code>func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage])
func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error)
</code>```

here is my reference Apple docs

Title: Reading NFC Tags with iPhone 6 / iOS 8

Body:
The ability to read an NFC tag has been added to iOS 11 which only support iPhone 7 and 7 plus

As a test drive I made this repo

First: We need to initiate NFCNDEFReaderSession class

var session: NFCNDEFReaderSession?
session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false)

Then we need to start the session by:

session?.begin()

and when done:

session?.invalidate()

The delegate (which self should implement) has basically two functions:

func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage])
func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error)

here is my reference Apple docs


问:
How to access service in vagrant from native ip 127.0.0.1?
Use Vagrant installed devstack. Set the HOST_IP to 127.0.0.1 before the installation config. After finish the installation, it told use these information to access web ui:

```<code>=========================
DevStack Component Timing
=========================
Total runtime    3523

run_process      113
test_with_retry    7
pip_install      647
wait_for_service  51
yum_install      338
git_timed        853
=========================

This is your host IP address: 127.0.0.1
This is your host IPv6 address: ::1
Horizon is now available at http://127.0.0.1/dashboard
Keystone is serving at http://127.0.0.1/identity/
The default users are: admin and demo
The password: secret
Services are running under systemd unit files.
For more information see:
https://docs.openstack.org/developer/devstack/systemd.html
</code>```

I set private_ip in Vagrantfile with 192.168.33.11, I tried this way to access the web ui:

http://192.168.33.11/dashboard

But not works. Therefore, I test used curl in Vagrant can confirm something:

```<code>[stack@localhost devstack]$ curl -I http://127.0.0.1/dashboard
HTTP/1.1 302 Found
Date: Mon, 05 Jun 2017 10:38:37 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.1e-fips mod_wsgi/3.4 Python/2.7.5
Vary: Accept-Language,Cookie
X-Frame-Options: SAMEORIGIN
Content-Language: en
Location: http://127.0.0.1/dashboard/auth/login/?next=/dashboard/
Content-Type: text/html; charset=utf-8
</code>```

How to access the dashboard now?

答:
This does not work because devstack is running on 127.0.0.1 on your VM.

You can change the HOST_IP variable from the config file (under the localrc section - see https://docs.openstack.org/developer/devstack/configuration.html) and use the static IP you set from Vagrantfile

```<code>HOST_IP=192.168.33.11
SERVICE_HOST=$HOST_IP
</code>```

Body:
Use Vagrant installed devstack. Set the HOST_IP to 127.0.0.1 before the installation config. After finish the installation, it told use these information to access web ui:

=========================
DevStack Component Timing
=========================
Total runtime    3523

run_process      113
test_with_retry    7
pip_install      647
wait_for_service  51
yum_install      338
git_timed        853
=========================

This is your host IP address: 127.0.0.1
This is your host IPv6 address: ::1
Horizon is now available at http://127.0.0.1/dashboard
Keystone is serving at http://127.0.0.1/identity/
The default users are: admin and demo
The password: secret
Services are running under systemd unit files.
For more information see:
https://docs.openstack.org/developer/devstack/systemd.html

I set private_ip in Vagrantfile with 192.168.33.11, I tried this way to access the web ui:

http://192.168.33.11/dashboard

But not works. Therefore, I test used curl in Vagrant can confirm something:

[stack@localhost devstack]$ curl -I http://127.0.0.1/dashboard
HTTP/1.1 302 Found
Date: Mon, 05 Jun 2017 10:38:37 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.1e-fips mod_wsgi/3.4 Python/2.7.5
Vary: Accept-Language,Cookie
X-Frame-Options: SAMEORIGIN
Content-Language: en
Location: http://127.0.0.1/dashboard/auth/login/?next=/dashboard/
Content-Type: text/html; charset=utf-8

How to access the dashboard now?

Body:
This does not work because devstack is running on 127.0.0.1 on your VM.

You can change the HOST_IP variable from the config file (under the localrc section - see https://docs.openstack.org/developer/devstack/configuration.html) and use the static IP you set from Vagrantfile

HOST_IP=192.168.33.11
SERVICE_HOST=$HOST_IP


问:
replace a variable's value if it contains a certain string
I have a variable called diagnosis and I want to replace everything that contains the word "pneumonia" with just "pneumonia"

I tried this:

```<code>replace diagnosis = "Pneumonia" if regexm (diagnosis, "pneumonia")
</code>```

But I got an error: unrecognized command: regexm

I have Stata/IC version 12.1 for Windows.

答:
Answer:

take out the space between regexm and (diagnosis, "pneumonia")

Additional suggestions:

regexm takes a long time, so I would do something more like

```<code>replace diagnosis = "Pneumonia" if diagnosis == "pneumonia"
</code>```

which achieves the same result, or if you want to do this more generally you can write

```<code>replace diagnosis = strproper(diagnosis)
</code>```

which has the same results in your example.

Body:
I have a variable called diagnosis and I want to replace everything that contains the word "pneumonia" with just "pneumonia"

I tried this:

replace diagnosis = "Pneumonia" if regexm (diagnosis, "pneumonia")

But I got an error: unrecognized command: regexm

I have Stata/IC version 12.1 for Windows.

Body:
Answer:

take out the space between regexm and (diagnosis, "pneumonia")

Additional suggestions:

regexm takes a long time, so I would do something more like

replace diagnosis = "Pneumonia" if diagnosis == "pneumonia"

which achieves the same result, or if you want to do this more generally you can write

replace diagnosis = strproper(diagnosis)

which has the same results in your example.


问:
Catching customurlscheme in android app?
Currently using CustomTabs/Native UI with Xamarin.Auth to authenticate an Android application with Google through a custom web api ( I can not edit/change the web api). Is it possible to intercept a url (https) and return to the application once this url is reached? or will this not work with custom tabs due to chrome already being open?

Code for Intent Filter:

```<code>[
    IntentFilter
    (
        actions: new[] { Intent.ActionView },
        Categories = new[]
                {
                    Intent.CategoryDefault,
                    Intent.CategoryBrowsable
                },
        DataSchemes = new[]
                {
                    "https://redirectwebsite.com/"
                },
        DataPath = "https"
    )
]
</code>```

答:
Solution:
I was able to succussfully navigate back to my android app and grab the token information by changing my intent filter:

```<code> [IntentFilter
    (
    actions: new[] { Intent.ActionView },
    Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
    DataSchemes = new[] { "https" },
    DataHost = "redirectwebsite.net",
    DataPath = "/",
    AutoVerify = true
    )
]
</code>```

Body:
Currently using CustomTabs/Native UI with Xamarin.Auth to authenticate an Android application with Google through a custom web api ( I can not edit/change the web api). Is it possible to intercept a url (https) and return to the application once this url is reached? or will this not work with custom tabs due to chrome already being open?

Code for Intent Filter:

[
    IntentFilter
    (
        actions: new[] { Intent.ActionView },
        Categories = new[]
                {
                    Intent.CategoryDefault,
                    Intent.CategoryBrowsable
                },
        DataSchemes = new[]
                {
                    "https://redirectwebsite.com/"
                },
        DataPath = "https"
    )
]

Body:
Solution:
I was able to succussfully navigate back to my android app and grab the token information by changing my intent filter:

 [IntentFilter
    (
    actions: new[] { Intent.ActionView },
    Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
    DataSchemes = new[] { "https" },
    DataHost = "redirectwebsite.net",
    DataPath = "/",
    AutoVerify = true
    )
]


问:
Is there a plan to support MappedDiagnosticsLogicalContext in NLog for Dotnet standard?
Looking at the current code of NLog 5.0.0,  https://github.com/NLog/NLog/blob/5.0.0-beta05-test/src/NLog/MappedDiagnosticsLogicalContext.cs, it won't support MappedDiagnosticsLogicalContext for .Net standard.
So, I have a few related questions:

Why is it not supported?

Would it be in .net standard 2.0 ?

What should I use instead? The MappedDiagnosticContext does not support all the async features as far as I know.

Thanks.

答:
Thanks to Rolf, I got my answers, so just sharing :-)
Looking at the branch coreCLR from NLog https://github.com/NLog/NLog/blob/coreCLR/src/NLog/MappedDiagnosticsLogicalContext.cs, MappedDiagnosticLogicalContext is fully supported starting with .Net Standard 1.3.
I tested it by download the 5.0.0-beta07 beta version:

```<code>PM> install-package NLog -Pre
...
Successfully installed 'NLog 5.0.0-beta07' to ClassLibrary1
...
</code>```

And there is it:

```<code> NLog.MappedDiagnosticsLogicalContext.Set(key, value);
</code>```

Body:
Thanks to Rolf, I got my answers, so just sharing :-)
Looking at the branch coreCLR from NLog https://github.com/NLog/NLog/blob/coreCLR/src/NLog/MappedDiagnosticsLogicalContext.cs, MappedDiagnosticLogicalContext is fully supported starting with .Net Standard 1.3.
I tested it by download the 5.0.0-beta07 beta version:

PM> install-package NLog -Pre
...
Successfully installed 'NLog 5.0.0-beta07' to ClassLibrary1
...

And there is it:

 NLog.MappedDiagnosticsLogicalContext.Set(key, value);