答:
Does this constraint hold true all the time (D == -C) ?

If so, you do not need to keep redundant data in your table, store only one "amount" value (for example the debit):

786 | 1194-838HELLUJP-05 |  -5800

and then, on the application level, append a D- to the name and get the raw amount or append a C- and get the - amount.

Title: Table has pairs of matching records, need to select and update only one record

Body:
I have a table with pairs of matching records that I query like this:

select id,name,amount,type from accounting_entries
  where name like "%05" and amount != 0 order by name limit 10;

Results:

+------+----------------------+--------+-------+
| id   | name                 | amount | type  |
+------+----------------------+--------+-------+
|  786 | D-1194-838HELLUJP-05 |  -5800 | DEBIT |
|  785 | D-1194-838HELLUJP-05 |  -5800 | DEBIT |
| 5060 | D-1195-UOK4HS5POF-05 |  -5000 | DEBIT |
| 5059 | D-1195-UOK4HS5POF-05 |  -5000 | DEBIT |
|  246 | D-1196-0FUCJI66BX-05 |  -7000 | DEBIT |
|  245 | D-1196-0FUCJI66BX-05 |  -7000 | DEBIT |
| 9720 | D-1197-W2J0EC1BOB-05 |  -6500 | DEBIT |
| 9719 | D-1197-W2J0EC1BOB-05 |  -6500 | DEBIT |
| 2694 | D-1198-MFKIKHGW0S-05 |  -5500 | DEBIT |
| 2693 | D-1198-MFKIKHGW0S-05 |  -5500 | DEBIT |
+------+----------------------+--------+-------+
10 rows in set (0.01 sec)

I need to perform an update so that the resulting data will look like this:

+------+----------------------+--------+--------+
| id   | name                 | amount | type   |
+------+----------------------+--------+--------+
|  786 | D-1194-838HELLUJP-05 |  -5800 | DEBIT  |
|  785 | C-1194-838HELLUJP-05 |   5800 | CREDIT |
| 5060 | D-1195-UOK4HS5POF-05 |  -5000 | DEBIT  |
| 5059 | C-1195-UOK4HS5POF-05 |   5000 | CREDIT |
|  246 | D-1196-0FUCJI66BX-05 |  -7000 | DEBIT  |
|  245 | C-1196-0FUCJI66BX-05 |   7000 | CREDIT |
| 9720 | D-1197-W2J0EC1BOB-05 |  -6500 | DEBIT  |
| 9719 | C-1197-W2J0EC1BOB-05 |   6500 | CREDIT |
| 2694 | D-1198-MFKIKHGW0S-05 |  -5500 | DEBIT  |
| 2693 | C-1198-MFKIKHGW0S-05 |   5500 | CREDIT |
+------+----------------------+--------+--------+
10 rows in set (0.01 sec)

One entry should negate the other entry. It doesn't matter if I update the first or second matching record, what matters is that one has a positive amount and the other has a negative amount. And the type and name need to be updated.

Any clues on how to do this? What would the update command look like? Maybe using a group by clause? I have some ideas on how to do it with a stored procedure, but can I do it with a simple update?


来源: stackexchange

问:
PHP / AJAX: Delete unsuccessful at AJAX
Currently, I created a system that has AJAX function. To be more clear, below is my current process flow:

1) dashboard.php will display 3 select option which is team, time from and time to

2) user need to complete all 3 select option and click button 'search'. At this point where AJAX (range.php).

3) All data row will be listed and each data have a delete button. User can delete data based on data row.

My problem is, the data is not deleted.

Below is my current code.

dashboard.php

```<code>      <select class="form-control"  name="team" id="team">
        <option value="">Please select...</option>
        <?php foreach ($data as $row2): ?>
        <option value= <?php echo $row2["team_id"]; ?> <?php echo (($_GET["team"] ?? '') == $row2["team_id"]) ? 'selected' : ''; ?> ><?php echo $row2["fullname"]; ?></option>
        <?php endforeach ?>
      </select>
    <td width="1%"></td>
    </td>
    <td width="20%"><input type="text" name="from" id="from" class="form-control" placeholder="From" value = '<?php echo $_GET["from"] ?? ''; ?>'></td>
    <td width="1%"></td>
    <td width="20%"><input type="text" name="to" id="to" class="form-control" placeholder="To" value = '<?php echo $_GET["to"] ?? ''; ?>'></td>
    <td width="1%"></td>
    <td width="10%"><input type="button" name="range" id="range" value="Search" class="btn btn-primary"><td>
  </tr>
</table><br>
<div id = "dashboard">

<script>
$(document).ready(function(){
  $.datepicker.setDefaults({
    dateFormat: 'yy-mm-dd'
  });
  $(function(){
    $("#from").datepicker().attr("autocomplete", "off");;
    $("#to").datepicker().attr("autocomplete", "off");;
  });
  $('#range').click(function(){
    var from = $('#from').val();
    var to = $('#to').val();
    var team = $('#team').val();
    if(from != '' && to != '' && team != '')
    {
      $.ajax({
        url:"range.php",
        method:"POST",
        data:{from:from, to:to, team:team},
        success:function(data)
        {
          $('#dashboard').html(data);
        }
      });
    }
    else
    {
      alert("Please select both team and date range");
    }
  });

  if($('#from').val() && $('#to').val() && $('#team').val()){

    $('#range').click();

  }

});
</script>
</code>```

range.php (AJAX)

```<code><?php

require_once "../../../config/configPDO.php";
require_once "../../../config/check.php";

$email = $_SESSION['login_user'];

if(isset($_POST["from"], $_POST["to"], $_POST["team"]))
{

$result = '';
$query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$_POST['team']."' AND report_date BETWEEN '".$_POST["from"]."' AND '".$_POST["to"]."' ORDER BY ot_report.report_date DESC";
$sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql -> execute();

if($sql->rowCount() > 0)
{
    echo'

    <form method="post" action="">
    <div class="row" style="height: 300px; overflow-y: scroll;">
    <div class="col-lg-12 grid-margin stretch-card">
    <table class = "table-bordered" width = "100%">
    <thead>
    <tr>
    <th>id</th>
    <th>Date</th>
    <th>Status</th>
    <th colspan = "2" width = "7%">Action</th>
    </tr>
    </thead>
    <tbody>';

    while($row = $sql->fetch(PDO::FETCH_ASSOC))
    {
        $datereport = $row['report_date'];
        $datereport2 = strtotime($datereport);
        $report_date = date('d M Y', $datereport2);

        $report_id = $row["report_id"];

        echo'<tr>';

            echo '<td>'.$report_id.'</td>';
            echo '<td>'.$report_date.'</td>';
            echo '<td align="center">';
            echo '<a class="btn-view btn-primary btn-sm" href="view_task/view_task.php?report_id='. $report_id .'" data-toggle="tooltip">View</a></td>';

            echo '<td align="center">';
            echo '<form action = "delete_ajax.php" method = "post" onSubmit=\"return confirm("Do you want to delete this report?")\">';
                echo '<input type = "hidden" name = "from" value = "'.$_POST["from"].'">';
                echo '<input type = "hidden" name = "to" value = "'.$_POST["to"].'">';
                echo '<input type = "hidden" name = "team" value = "'.$_POST["team"].'">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-danger">Delete</button>';
            echo '</form>';

            echo '</td>';

        echo '</tr>';

    }

}
</code>```

delete_ajax.php

```<code>  <?php

  require_once '../../../config/configPDO.php';

  $report_id = $_POST['report_id'];

  $sql = "DELETE FROM ot_report WHERE report_id=:report_id";
  $query = $conn->prepare($sql);
  $query->execute(array(':report_id' => $report_id));

  header("Location: dashboard_engineer.php?from='".$_POST["from"]."'&to='".$_POST["to"]."' &team='".$_POST["team"]."'");

  ?>
</code>```

Can anyone knows what is the problem? The data cannot deleted!. Help anyone

答:
maybe this is because in the range.php file you have 2 form tags

first is outside while function

```<code><form method="post" action="">
</code>```

and second one is in while function

```<code><form action = "delete_ajax.php" method = "post" onSubmit=\"return confirm("Do you want to delete this report?")\">
</code>```

try removing the first one

ContentLicense: CC BY-SA 4.0

Title: PHP / AJAX: Delete unsuccessful at AJAX

Body:
Currently, I created a system that has AJAX function. To be more clear, below is my current process flow:

1) dashboard.php will display 3 select option which is team, time from and time to

2) user need to complete all 3 select option and click button 'search'. At this point where AJAX (range.php).

3) All data row will be listed and each data have a delete button. User can delete data based on data row.

My problem is, the data is not deleted.

Below is my current code.

dashboard.php

      <select class="form-control"  name="team" id="team">
        <option value="">Please select...</option>
        <?php foreach ($data as $row2): ?>
        <option value= <?php echo $row2["team_id"]; ?> <?php echo (($_GET["team"] ?? '') == $row2["team_id"]) ? 'selected' : ''; ?> ><?php echo $row2["fullname"]; ?></option>
        <?php endforeach ?>
      </select>

    <input type="text" name="from" id="from" class="form-control" placeholder="From" value = '<?php echo $_GET["from"] ?? ''; ?>'>

    <input type="text" name="to" id="to" class="form-control" placeholder="To" value = '<?php echo $_GET["to"] ?? ''; ?>'>

    <input type="button" name="range" id="range" value="Search" class="btn btn-primary">

range.php (AJAX)

<?php

require_once "../../../config/configPDO.php";
require_once "../../../config/check.php";

$email = $_SESSION['login_user'];

if(isset($_POST["from"], $_POST["to"], $_POST["team"]))
{

$result = '';
$query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$_POST['team']."' AND report_date BETWEEN '".$_POST["from"]."' AND '".$_POST["to"]."' ORDER BY ot_report.report_date DESC";
$sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$sql -> execute();

if($sql->rowCount() > 0)
{
    echo'

    <form method="post" action="">

    id
    Date
    Status
    Action

';

    while($row = $sql->fetch(PDO::FETCH_ASSOC))
    {
        $datereport = $row['report_date'];
        $datereport2 = strtotime($datereport);
        $report_date = date('d M Y', $datereport2);

        $report_id = $row["report_id"];

        echo'
';

            echo ''.$report_id.'	';
            echo ''.$report_date.'	';
            echo '';
            echo 'View	';

            echo '';
            echo '<form action = "delete_ajax.php" method = "post" onSubmit=\"return confirm("Do you want to delete this report?")\">';
                echo '<input type = "hidden" name = "from" value = "'.$_POST["from"].'">';
                echo '<input type = "hidden" name = "to" value = "'.$_POST["to"].'">';
                echo '<input type = "hidden" name = "team" value = "'.$_POST["team"].'">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-danger">Delete</button>';
            echo '</form>';

            echo '	';

        echo '
';

    }

}

delete_ajax.php

  <?php

  require_once '../../../config/configPDO.php';

  $report_id = $_POST['report_id'];

  $sql = "DELETE FROM ot_report WHERE report_id=:report_id";
  $query = $conn->prepare($sql);
  $query->execute(array(':report_id' => $report_id));

  header("Location: dashboard_engineer.php?from='".$_POST["from"]."'&to='".$_POST["to"]."' &team='".$_POST["team"]."'");

  ?>

Can anyone knows what is the problem? The data cannot deleted!. Help anyone

Body:
maybe this is because in the range.php file you have 2 form tags

first is outside while function

<form method="post" action="">

and second one is in while function

<form action = "delete_ajax.php" method = "post" onSubmit=\"return confirm("Do you want to delete this report?")\">

try removing the first one


问:
How to check two month are equal or not from date format YYYY-MM-DD?
I have two dates like 2020-12-31 and 2020-12-01 in string format yyyy-mm-dd while check the month it should return true.

Suppose I compare 2020-11-31 and 2020-12-31 it should return false.

If there is a difference in only month and year, it should return true.

For example today Feb 18, 2020, Suppose I choose Feb 11, 2020, it should return true, If I choose Jan 11, 2020, then it should return false.

Date difference should not be considered

答:
@Maheshwaran
You can use something like this</p>

```<code>var d1 = new Date("2020-12-31")
var d2 = new Date("2020-12-31")
return d1.getMonth() === d2.getMonth() && d1.getYear() === d2.getYear()
</code>```

Body:
@Maheshwaran
You can use something like this

var d1 = new Date("2020-12-31")
var d2 = new Date("2020-12-31")
return d1.getMonth() === d2.getMonth() && d1.getYear() === d2.getYear()


问:
How to convert custom object with map field that includes list of custom object to json?
Let's say, I have an Employee class which looks like this:

```<code>public class Employee{

Map<String, ArrayList<Salary>> salary = new HashMap<String, ArrayList<Salary>>();
String name;
String age;
}

public class Salary{
String amount;
String currency;
}
</code>```

What is the smartest way of convertion to/from Json in Java?

Or;

What if my json should look like that:

```<code>  {
  "name": "Test",
  "age": "12",
  "salary": {
    "first": {
      "41130": {
        "amount": "100",
        "currency": "€"
      },
      "41132": {
        "amount": "100",
        "currency": "€"
      }
    },
    "second": {
      "41129": {
        "amount": "100",
        "currency": "€"
      }
    }
  }
}
</code>```

When i tried to convert this to Employee I am getting error below.

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
  Expected BEGIN_ARRAY but was BEGIN_OBJECT

答:
I think you can use Jackson ObjectMapper
https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html#writeValue(java.io.OutputStream,%20java.lang.Object)</p>

```<code>ObjectMapper objectMapper = new ObjectMapper();
Employee employee = new Employee();
objectMapper.writeValue(new FileOutputStream("data/output.json"), employee);
</code>```

Body:
Let's say, I have an Employee class which looks like this:

public class Employee{

Map<String, ArrayList<Salary>> salary = new HashMap<String, ArrayList<Salary>>();
String name;
String age;
}

public class Salary{
String amount;
String currency;
}

What is the smartest way of convertion to/from Json in Java?

Or;

What if my json should look like that:

  {
  "name": "Test",
  "age": "12",
  "salary": {
    "first": {
      "41130": {
        "amount": "100",
        "currency": "€"
      },
      "41132": {
        "amount": "100",
        "currency": "€"
      }
    },
    "second": {
      "41129": {
        "amount": "100",
        "currency": "€"
      }
    }
  }
}

When i tried to convert this to Employee I am getting error below.

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
  Expected BEGIN_ARRAY but was BEGIN_OBJECT

Body:
I think you can use Jackson ObjectMapper
https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html#writeValue(java.io.OutputStream,%20java.lang.Object)

ObjectMapper objectMapper = new ObjectMapper();
Employee employee = new Employee();
objectMapper.writeValue(new FileOutputStream("data/output.json"), employee);


问:
how to send send the data using python django?
How to send the json data using post request in django python.
I have a code for get the data and I don't use any html file.

```<code>class employeeList(APIView):
    def get(self, request):
        employee1 = employees.objects.all()
        serializer = employeeSerializer(employee1, many=True)
        return Response(serializer.data)
    def post(self,request):
        pass
</code>```

can you please help for post request.Now I want to create post function to send the data

答:
You can use this basically,</p>

```<code>def post(self, request):
    serializer = employeeSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    serializer.save()
    return Response({'message':'Data davet succesfully'})
</code>```

Body:
How to send the json data using post request in django python.
I have a code for get the data and I don't use any html file.

class employeeList(APIView):
    def get(self, request):
        employee1 = employees.objects.all()
        serializer = employeeSerializer(employee1, many=True)
        return Response(serializer.data)
    def post(self,request):
        pass

can you please help for post request.Now I want to create post function to send the data

Body:
You can use this basically,

def post(self, request):
    serializer = employeeSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    serializer.save()
    return Response({'message':'Data davet succesfully'})


问:
Init once with lambda function pointer, self-modifying (C++)
I was wondering if it's possible to create inline lambda initialization function, so after initialization it would replace itself with dummy initialization. Some sort of lazy initialization algorithm with as less pain as possible. Here is some pseudo code what I would like to achieve:

```<code>SomeData* data = nullptr;
auto initF = [&]
{
    data = initData();
    initF = [&] {};
};
</code>```

so in for loop it would look like this:

```<code>for(int i = 0; i < count; i++) {
     initF();
     data[i] = ....;
}
</code>```

Basically if count is 0 - initF would not be ever called, but once called - pointer becomes initialized and can be used after that.

答:
Well, your code almost works. Since initF essentially has to change types, from something that actually does work to just a no-op, you can use a std::function:

```<code>int data;
std::function<void()> calcData = [&]() {
    data = 5; // something expensive
    calcData = []() { }
};
</code>```

I think you can go further and just eliminate data's separate existence, so you just have the function.

```<code>std::function<int&()> data = [&]() -> int& {
    return (data = [res = 5]() mutable -> int& { return res; })();
    //              ^^^ the variable becomes a "hidden" data member of the closure
}
</code>```

This eliminates the chance of accidentally using the variable before you call the initializer.

Body:
I was wondering if it's possible to create inline lambda initialization function, so after initialization it would replace itself with dummy initialization. Some sort of lazy initialization algorithm with as less pain as possible. Here is some pseudo code what I would like to achieve:

SomeData* data = nullptr;
auto initF = [&]
{
    data = initData();
    initF = [&] {};
};

so in for loop it would look like this:

for(int i = 0; i < count; i++) {
     initF();
     data[i] = ....;
}

Basically if count is 0 - initF would not be ever called, but once called - pointer becomes initialized and can be used after that.

Body:
Well, your code almost works. Since initF essentially has to change types, from something that actually does work to just a no-op, you can use a std::function:

int data;
std::function<void()> calcData = [&]() {
    data = 5; // something expensive
    calcData = []() { }
};

I think you can go further and just eliminate data's separate existence, so you just have the function.

std::function<int&()> data = [&]() -> int& {
    return (data = [res = 5]() mutable -> int& { return res; })();
    //              ^^^ the variable becomes a "hidden" data member of the closure
}

This eliminates the chance of accidentally using the variable before you call the initializer.


问:
Bootstrap version 3.4 not working in Angular 9
I have installed bootstrap version 3.4 using Angular cli. Below is the command I used
    npm install --save bootstrap@3
Then I have added

```<code>"styles": [
          "./node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
        ],
        "scripts": [
          "./node_modules/bootstrap/dist/js/bootstrap.min.js"
        ]
</code>```

In angular.json file.
But I am unable to access the bootstrap default style class. No bootstrap file is showing in browser console whenever I run the application.

I am unable to find the issue here. Your help would be greatly appreciated.
Adding screenshot of my node_modules folder

答:
Your paths shouldn't start with a ./.

Instead, try the following:

```<code>"styles": [
  "node_modules/bootstrap/dist/css/bootstrap.min.css",
  "src/styles.css"
],
"scripts": [
  "node_modules/bootstrap/dist/js/bootstrap.min.js"
  ]
</code>```

This now makes them relative to the project root.

Working demo: https://stackblitz.com/edit/angular-etn2fd

Body:
I have installed bootstrap version 3.4 using Angular cli. Below is the command I used
    npm install --save bootstrap@3
Then I have added

"styles": [
          "./node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
        ],
        "scripts": [
          "./node_modules/bootstrap/dist/js/bootstrap.min.js"
        ]

In angular.json file.
But I am unable to access the bootstrap default style class. No bootstrap file is showing in browser console whenever I run the application.

I am unable to find the issue here. Your help would be greatly appreciated.
Adding screenshot of my node_modules folder

Body:
Your paths shouldn't start with a ./.

Instead, try the following:

"styles": [
  "node_modules/bootstrap/dist/css/bootstrap.min.css",
  "src/styles.css"
],
"scripts": [
  "node_modules/bootstrap/dist/js/bootstrap.min.js"
  ]

This now makes them relative to the project root.

Working demo: https://stackblitz.com/edit/angular-etn2fd


问:
How i can process my payload to insert bulk data in multiple tables with atomicity/consistency in cassandra?
I have to design the database for customers having prices for millions of materials they acquire through multiple suppliers for the next 24 months. So the database will store prices on a daily basis for every material supplied by a specific supplier for the next 24 months. Now I have multiple use cases to solve so I created multiple tables to solve each use case in the best possible way.
Now the insertion of data into these tables will happen on a regular basis in a big chunk (let's say for 1k items), which should ensure the data consistency as well i.e. the data should be inserted into all the tables or in none of them. Failure in doing so should be flagged as a "failure" with no inserts for further action. How can I solve this in Cassandra effectively?

On option I can think of is to use small BATCH processes (1K in number for 1k items for example). I might hit multiple partitions during insertion in different tables having a different set of primary keys;

Any Thoughts?
Thanks

答:
If you are talking about with respect of Database(Cassandra) then you should consider many things for data modelling point.
You need to go through the data modeling detail on below link with batch.
https://docs.datastax.com/en/dse/6.0/cql/cql/ddl/dataModelingCQLTOC.html
https://docs.datastax.com/en/dse/6.0/cql/cql/cql_reference/cql_commands/cqlBatch.html

Also, based on application nature you should think about compaction strategy for processing of high writes or reads.


问:
SqlAlchemy: Get instances of certain type in a relationship that can contain objects of several types
I have an application with a "BaseVisibilizer"  class that is base
class for two other classes:

```<code>class BaseVisibilizer(declarativeBase):
       __tablename__ = "base_visibilizers"
       _polymorphicIdentity = Column("polymorphic_identity", String(20), key="polymorphicIdentity")
       __mapper_args__ = {
               'polymorphic_on': _polymorphicIdentity,
               'polymorphic_identity': None
       }

       def __init__(self):
               super(BaseVisibilizer, self).__init__()
</code>```

This is the base class for my User and UserGroup classes: both classes
can be used to control the visibility of certain items.

```<code>class UserGroup(BaseVisibilizer.BaseVisibilizer):
       __tablename__ = "user_groups"
       _id = Column("id", Integer, ForeignKey(BaseVisibilizer.BaseVisibilizer.id), primary_key=True)

       __mapper_args__ = {
               'polymorphic_identity': 'UserGroup',
               'inherit_condition': _id == BaseVisibilizer.BaseVisibilizer._id,
       }

       _name = Column("name", String(50), nullable=False)
</code>```

```<code>class User(BaseVisibilizer.BaseVisibilizer):
       __tablename__ = "users"
       _id = Column("id", Integer, ForeignKey(BaseVisibilizer.BaseVisibilizer.id), primary_key=True)

       __mapper_args__ = {
               'polymorphic_identity': 'User',
               'inherit_condition': _id == BaseVisibilizer.BaseVisibilizer._id,
       }
       _firstName = Column("first_name", String(50), key="fistName")
       _lastName = Column("last_name", String(50), key="lastName")
       _userName = Column("user_name", String(50), unique=True, nullable=False)
</code>```

In many of the other classes of my system I have a relationship that
can contain "BaseVisibilizers" (Users or UserGroups).

```<code>class Whatever(declarativeBase):
       allowedVisibilizers = relationship("BaseVisibilizer",
               secondary="intermediate_whatevers_to_base_visibilizers",
               collection_class=set)
</code>```

So in the instances of Whatever, the allowedVisibilizers set can
contain instances of User of UserGroup (because both are
BaseVisibilizers). If the logged user or the UserGroup the logged user
belongs to is among the "allowedVisibilizers" , that user will be able
to access (or "see") that instance of Whatever.

At a certain point, I would like to create a method in the Whatever
class that would give me only the allowed visibilizers that are
actually a UserGroup (discarding the Users) but I haven't been able to
do it.

I've tried several things, but obviously, not the right one
(subqueries, joins of "allowedvisibilizers"...):

```<code>What I'd like is something like:
class Whatever(declarativeBase):
       [ . . . ]
       def getAllowedUserGroups(self):
               session = Database.Session()
               query = session.query(UserGroup.UserGroup).filter(UserGroup.UserGroup.in_(self.allowedVisibilizers))
               return query.all()
</code>```

(but obviously, UserGroup is a class and doesn't have an in_)

Of course, I could always get all the "allowedVisibilizers" and remove
the Users from the returned value, but I was trying to make it a
little bit optimized than that and avoid unnecessary calls to the
database.

Any hint will be very appreciated. Thank you in advance!

答:
One solution would be to create another relationship on Whatever which would include the filter to the specific table UserGroup, which should do the trick.

See Multiple Relationships against the Same Parent/Child documentation for more information. In your case adding additional join condition on UserGroup table should do the trick.

Also consider using Building Query-Enabled Properties to specify readonly.

ContentLicense: CC BY-SA 3.0

Body:
I have an application with a "BaseVisibilizer"  class that is base
class for two other classes:

class BaseVisibilizer(declarativeBase):
       __tablename__ = "base_visibilizers"
       _polymorphicIdentity = Column("polymorphic_identity", String(20), key="polymorphicIdentity")
       __mapper_args__ = {
               'polymorphic_on': _polymorphicIdentity,
               'polymorphic_identity': None
       }

       def __init__(self):
               super(BaseVisibilizer, self).__init__()

This is the base class for my User and UserGroup classes: both classes
can be used to control the visibility of certain items.

class UserGroup(BaseVisibilizer.BaseVisibilizer):
       __tablename__ = "user_groups"
       _id = Column("id", Integer, ForeignKey(BaseVisibilizer.BaseVisibilizer.id), primary_key=True)

       __mapper_args__ = {
               'polymorphic_identity': 'UserGroup',
               'inherit_condition': _id == BaseVisibilizer.BaseVisibilizer._id,
       }

       _name = Column("name", String(50), nullable=False)

class User(BaseVisibilizer.BaseVisibilizer):
       __tablename__ = "users"
       _id = Column("id", Integer, ForeignKey(BaseVisibilizer.BaseVisibilizer.id), primary_key=True)

       __mapper_args__ = {
               'polymorphic_identity': 'User',
               'inherit_condition': _id == BaseVisibilizer.BaseVisibilizer._id,
       }
       _firstName = Column("first_name", String(50), key="fistName")
       _lastName = Column("last_name", String(50), key="lastName")
       _userName = Column("user_name", String(50), unique=True, nullable=False)

In many of the other classes of my system I have a relationship that
can contain "BaseVisibilizers" (Users or UserGroups).

class Whatever(declarativeBase):
       allowedVisibilizers = relationship("BaseVisibilizer",
               secondary="intermediate_whatevers_to_base_visibilizers",
               collection_class=set)

So in the instances of Whatever, the allowedVisibilizers set can
contain instances of User of UserGroup (because both are
BaseVisibilizers). If the logged user or the UserGroup the logged user
belongs to is among the "allowedVisibilizers" , that user will be able
to access (or "see") that instance of Whatever.

At a certain point, I would like to create a method in the Whatever
class that would give me only the allowed visibilizers that are
actually a UserGroup (discarding the Users) but I haven't been able to
do it.

I've tried several things, but obviously, not the right one
(subqueries, joins of "allowedvisibilizers"...):

What I'd like is something like:
class Whatever(declarativeBase):
       [ . . . ]
       def getAllowedUserGroups(self):
               session = Database.Session()
               query = session.query(UserGroup.UserGroup).filter(UserGroup.UserGroup.in_(self.allowedVisibilizers))
               return query.all()

(but obviously, UserGroup is a class and doesn't have an in_)

Of course, I could always get all the "allowedVisibilizers" and remove
the Users from the returned value, but I was trying to make it a
little bit optimized than that and avoid unnecessary calls to the
database.

Any hint will be very appreciated. Thank you in advance!


问:
Sum netchanges between shapshots in transactional fact
I have a transactional fact with irregular effective from and effectiveTo dates with cumulative total and net changes over ID and time.

Now I want to sum the net changes between two snapshots, for example 2012-01-01 and 2015-07-01 that should include all the rows including and between the snapshot dates.

I would like to select the relevant rows using the snapshot dates so that I can perform a sum on NC_Total grouped on ID.

What is the most efficient way to to this? Can I create a table valued function for this?

This is how the table looks selected for ID IN (1,2):

This is the resultset I should get back using the snapshot dates:

Select rows on snapshot date

And this is how I would like to finally sum it:

Sum of snapshot dates

答:
So I ended up writing a table valued function for this but the gist of the selection had less to do with SQL than with thinking about the datelogic. The solution was not as elegant as I would have wanted:

DECLARE @t1 DATETIME = '2012-01-01'

DECLARE @t2 DATETIME = '2015-07-01'

AND (EffectiveFrom >= @t1 AND EffectiveFrom <= @t2) -- All transactions between the snapshots


问:
Is there a way to programmatically trigger a VueJS element with .native using $refs?
I have searched GitHub Issues and Google but I can't seem to find the solution that fits my needs.

Template:

```<code><v-file-input
    dense
    accept="image/png, image/jpeg, image/gif"
    @change="onImageChangeHandler"
    v-show="false"
    ref="fileInput"
></v-file-input>
<v-btn
    dense
    color="primary"
    @click="onUploadClickHandler"
    small
>
    <v-icon left>mdi-camera</v-icon>
    Upload Photo
</v-btn>

</code>```

JS:

```<code>onImageChangeHandler(e) {
    if (e) {
        const fr = new FileReader();
        fr.readAsDataURL(e);
        fr.addEventListener("load", () => {
            this.localPersonalData.image = fr.result.split(
                "base64,"
            )[1];
        });
    }
},
onUploadClickHandler(e) {
    this.$refs.fileInput.$el.click(); // I need to click the hidden file input
}
</code>```

Upon closer inspection, I found out that Vuetify parses v-file-input component in nested divs and the input element is at the bottom of the html tree.

```<code><div
  data-v-a2f0f47e=""
  class="v-input v-input--dense theme--light v-text-field v-text-field--is-booted v-file-input"
  style="display: none;"
>
  <div class="v-input__prepend-outer">
    <div class="v-input__icon v-input__icon--prepend">
      <i
        role="button"
        class="v-icon notranslate v-icon--link mdi mdi-paperclip theme--light"
      ></i>
    </div>
  </div>
  <div class="v-input__control">
    <div class="v-input__slot">
      <div class="v-text-field__slot">
        <div class="v-file-input__text"></div>
        <!-- I want to click this input -->
        <input
          accept="image/png, image/jpeg, image/gif"
          id="input-333"
          type="file"
        />
      </div>
      <div class="v-input__append-inner">
        <div class="v-input__icon v-input__icon--">
          <i
            role="button"
            class="v-icon notranslate v-icon--link material-icons theme--light"
          ></i>
        </div>
      </div>
    </div>
    <div class="v-text-field__details">
      <div class="v-messages theme--light">
        <div class="v-messages__wrapper"></div>
      </div>
    </div>
  </div>
</div>
</code>```

Therefore, I probably need to use .native but how do I do that programmatically?

EDIT: Should I just use native html input with type file instead?

答:
What I understand is you want to open a file right?
Try this

```<code><input type="file" ref="file" style="display: none">
<v-button @click="$refs.file.click()">Button to open the file</v-button>
</code>```

And with the ref in js use as this.$ref.file and get your file you uploded
To clear the reference this.$ref.value=""

Body:
I have searched GitHub Issues and Google but I can't seem to find the solution that fits my needs.

Template:

<v-file-input
    dense
    accept="image/png, image/jpeg, image/gif"
    @change="onImageChangeHandler"
    v-show="false"
    ref="fileInput"
></v-file-input>
<v-btn
    dense
    color="primary"
    @click="onUploadClickHandler"
    small
>
    <v-icon left>mdi-camera</v-icon>
    Upload Photo
</v-btn>

JS:

onImageChangeHandler(e) {
    if (e) {
        const fr = new FileReader();
        fr.readAsDataURL(e);
        fr.addEventListener("load", () => {
            this.localPersonalData.image = fr.result.split(
                "base64,"
            )[1];
        });
    }
},
onUploadClickHandler(e) {
    this.$refs.fileInput.$el.click(); // I need to click the hidden file input
}

Upon closer inspection, I found out that Vuetify parses v-file-input component in nested divs and the input element is at the bottom of the html tree.

        <input
          accept="image/png, image/jpeg, image/gif"
          id="input-333"
          type="file"
        />

Therefore, I probably need to use .native but how do I do that programmatically?

EDIT: Should I just use native html input with type file instead?

Body:
What I understand is you want to open a file right?
Try this

<input type="file" ref="file" style="display: none">
<v-button @click="$refs.file.click()">Button to open the file</v-button>

And with the ref in js use as this.$ref.file and get your file you uploded
To clear the reference this.$ref.value=""


问:
Javascript - Auto-scroll to an active menu item on page load in horizontal scrolling menu
Try to create a horizontal scrolling menu for mobile devices with CSS and Pure JavaScript.
I had created a bellow structure to achieve this and which is looks good. Now, I need to auto-scroll to active nav item on page load using Javascript, It seems if the last item having active class it was hidden. The active class is dynamically set through back-end codes.
I have tried with some JavaScript but not working perfectly.

window.onload = function () {
        document.getElementsByClassName('nav-menu')[0].scrollLeft = 0;
        var menus = document.getElementsByClassName('nav-menu__item');
        for (var i = 0; i < menus.length; i++) {
            if (menus[i].classList.contains('active')) {
                document.getElementsByClassName('nav-menu')[0].scrollLeft = menus[i].offsetLeft;
            }
        }
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.account-nav{
    padding:0;
    margin: 0 0 30px;
}
.account-nav__container{
    margin:0;
    padding:0;
    border-bottom: 1px solid #757575;
}
.account-nav__container .nav-menu{
    display:flex;
    list-style: none;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    -ms-overflow-style: -ms-autohiding-scrollbar;
    scrollbar-width: none;
}
.account-nav__container .nav-menu::-webkit-scrollbar {
    display: none;
}
.account-nav__container .nav-menu .nav-menu__item{
    display:block;
    margin-right:20px;
    margin-bottom:-1px;
    white-space: nowrap;
}
.account-nav__container .nav-menu .nav-menu__item.active{
    border-bottom: 2px solid black;
}
.account-nav__container .nav-menu .nav-menu__item .nav-menu__item--link{
    display:block;
    padding:15px 0;
    text-decoration:none;
    text-align:left;
}
.account-nav__container .nav-menu .nav-menu__item .nav-menu__item--link:active,
.account-nav__container .nav-menu .nav-menu__item .nav-menu__item--link:hover,
.account-nav__container .nav-menu .nav-menu__item .nav-menu__item--link:focus{
    outline:none;
}
.account-nav__container .nav-menu .nav-menu__item.active .nav-menu__item--link{
    font-weight: 700;
}
.account-nav__container .nav-menu .nav-menu__item.active .nav-menu__item--link::after{
    background:none !important;
}</code>```

                Personal Information

                You Orders

                Returns & Exchanges

                Settings

                Preferences

                Addresses

```

答:
You had it, you just needed a single line of CSS.

From the MDN docs for offsetLeft:

left is an integer representing the offset to the left in pixels from the closest relatively positioned parent element.

You didn't have a relatively positioned parent element. In this case it should be your ul, see the snippet, all I added was the position: relative for the ul.nav-menu, works great.

window.onload = function () {
        document.getElementsByClassName('nav-menu')[0].scrollLeft = 0;
        var menus = document.getElementsByClassName('nav-menu__item');
        for (var i = 0; i < menus.length; i++) {
            if (menus[i].classList.contains('active')) {
                document.getElementsByClassName('nav-menu')[0].scrollLeft = menus[i].offsetLeft;
            }
        }
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.account-nav{
    padding:0;
    margin: 0 0 30px;
}
.account-nav__container{
    margin:0;
    padding:0;
    border-bottom: 1px solid #757575;
}
.account-nav__container .nav-menu{
    display:flex;
    list-style: none;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    -ms-overflow-style: -ms-autohiding-scrollbar;
    scrollbar-width: none;
}
.account-nav__container .nav-menu::-webkit-scrollbar {
    display: none;
}
.account-nav__container .nav-menu .nav-menu__item{
    display:block;
    margin-right:20px;
    margin-bottom:-1px;
    white-space: nowrap;
}
ul.nav-menu {
  position: relative
}
.account-nav__container .nav-menu .nav-menu__item.active{
    border-bottom: 2px solid black;
}
.account-nav__container .nav-menu .nav-menu__item .nav-menu__item--link{
    display:block;
    padding:15px 0;
    text-decoration:none;
    text-align:left;
}
.account-nav__container .nav-menu .nav-menu__item .nav-menu__item--link:active,
.account-nav__container .nav-menu .nav-menu__item .nav-menu__item--link:hover,
.account-nav__container .nav-menu .nav-menu__item .nav-menu__item--link:focus{
    outline:none;
}
.account-nav__container .nav-menu .nav-menu__item.active .nav-menu__item--link{
    font-weight: 700;
}
.account-nav__container .nav-menu .nav-menu__item.active .nav-menu__item--link::after{
    background:none !important;
}</code>```

                Personal Information

                You Orders

                Returns & Exchanges

                Settings

                Preferences

                Addresses

```

Body:
Try to create a horizontal scrolling menu for mobile devices with CSS and Pure JavaScript.
I had created a bellow structure to achieve this and which is looks good. Now, I need to auto-scroll to active nav item on page load using Javascript, It seems if the last item having active class it was hidden. The active class is dynamically set through back-end codes.
I have tried with some JavaScript but not working perfectly.

window.onload = function () {
        document.getElementsByClassName('nav-menu')[0].scrollLeft = 0;
        var menus = document.getElementsByClassName('nav-menu__item');
        for (var i = 0; i < menus.length; i++) {
            if (menus[i].classList.contains('active')) {
                document.getElementsByClassName('nav-menu')[0].scrollLeft = menus[i].offsetLeft;
            }
        }
    }

.account-nav{
    padding:0;
    margin: 0 0 30px;
}
.account-nav__container{
    margin:0;
    padding:0;
    border-bottom: 1px solid #757575;
}
.account-nav__container .nav-menu{
    display:flex;
    list-style: none;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    -ms-overflow-style: -ms-autohiding-scrollbar;
    scrollbar-width: none;
}
.account-nav__container .nav-menu::-webkit-scrollbar {
    display: none;
}
.account-nav__container .nav-menu .nav-menu__item{
    display:block;
    margin-right:20px;
    margin-bottom:-1px;
    white-space: nowrap;
}
.account-nav__container .nav-menu .nav-menu__item.active{
    border-bottom: 2px solid black;
}
.account-nav__container .nav-menu .nav-menu__item .nav-menu__item--link{
    display:block;
    padding:15px 0;
    text-decoration:none;
    text-align:left;
}
.account-nav__container .nav-menu .nav-menu__item .nav-menu__item--link:active,
.account-nav__container .nav-menu .nav-menu__item .nav-menu__item--link:hover,
.account-nav__container .nav-menu .nav-menu__item .nav-menu__item--link:focus{
    outline:none;
}
.account-nav__container .nav-menu .nav-menu__item.active .nav-menu__item--link{
    font-weight: 700;
}
.account-nav__container .nav-menu .nav-menu__item.active .nav-menu__item--link::after{
    background:none !important;
}

                Personal Information

                You Orders

                Returns & Exchanges

                Settings

                Preferences

                Addresses

Body:
You had it, you just needed a single line of CSS.

From the MDN docs for offsetLeft:

left is an integer representing the offset to the left in pixels from the closest relatively positioned parent element.

You didn't have a relatively positioned parent element. In this case it should be your ul, see the snippet, all I added was the position: relative for the ul.nav-menu, works great.

window.onload = function () {
        document.getElementsByClassName('nav-menu')[0].scrollLeft = 0;
        var menus = document.getElementsByClassName('nav-menu__item');
        for (var i = 0; i < menus.length; i++) {
            if (menus[i].classList.contains('active')) {
                document.getElementsByClassName('nav-menu')[0].scrollLeft = menus[i].offsetLeft;
            }
        }
    }

.account-nav{
    padding:0;
    margin: 0 0 30px;
}
.account-nav__container{
    margin:0;
    padding:0;
    border-bottom: 1px solid #757575;
}
.account-nav__container .nav-menu{
    display:flex;
    list-style: none;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    -ms-overflow-style: -ms-autohiding-scrollbar;
    scrollbar-width: none;
}
.account-nav__container .nav-menu::-webkit-scrollbar {
    display: none;
}
.account-nav__container .nav-menu .nav-menu__item{
    display:block;
    margin-right:20px;
    margin-bottom:-1px;
    white-space: nowrap;
}
ul.nav-menu {
  position: relative
}
.account-nav__container .nav-menu .nav-menu__item.active{
    border-bottom: 2px solid black;
}
.account-nav__container .nav-menu .nav-menu__item .nav-menu__item--link{
    display:block;
    padding:15px 0;
    text-decoration:none;
    text-align:left;
}
.account-nav__container .nav-menu .nav-menu__item .nav-menu__item--link:active,
.account-nav__container .nav-menu .nav-menu__item .nav-menu__item--link:hover,
.account-nav__container .nav-menu .nav-menu__item .nav-menu__item--link:focus{
    outline:none;
}
.account-nav__container .nav-menu .nav-menu__item.active .nav-menu__item--link{
    font-weight: 700;
}
.account-nav__container .nav-menu .nav-menu__item.active .nav-menu__item--link::after{
    background:none !important;
}

<div class="account-nav" role="navigation">
    <div class="account-nav__container">
        <ul role="menubar" class="nav-menu">
            <li role="menuitem" class="nav-menu__item">
                <a class="nav-menu__item--link" href="/Customer/Account/EditAccount.html">Personal Information</a>
            </li>
            <li role="menuitem" class="nav-menu__item">
                <a class="nav-menu__item--link" href="/Customer/Account/OrderSummary.html">You Orders</a>
            </li>
            <li role="menuitem" class="nav-menu__item">
                <a class="nav-menu__item--link" href="/Customer/Account/ReturnSummary.html">Returns &amp; Exchanges</a>
            </li>
            <li role="menuitem" class="nav-menu__item active">
                <a class="nav-menu__item--link" href="/Customer/Account/AccountSettings.html">Settings</a>
            </li>
            <li role="menuitem" class="nav-menu__item">
                <a class="nav-menu__item--link" href="/Customer/Account/CommunicationPreferences.html">Preferences</a>
            </li>
            <li role="menuitem" class="nav-menu__item">
                <a class="nav-menu__item--link" href="/Customer/Account/AddressBook.html">Addresses</a>
            </li>
        </ul>
    </div>
</div>


问:
How to reset the bootstrap modal when it gets closed and open it fresh again?
I have a list box in the bootstrap modal and a button.
When the button is clicked a new button gets rendered inside a div in the modal.
When I close the modal and reopen it, the last operation performed on the modal like the button rendered earlier is still present in the modal.

How do reset the modal so that when the modal is opened again, the button is not present and user can again select the option from the list box and click on the button to render a new button and so on.

```<code><!-- Modal -->
<div
  class="modal fade"
  id="myModal"
  tabindex="-1"
  role="dialog"
  aria-labelledby="myModalLabel"
  aria-hidden="true"
>
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">
          <span aria-hidden="true">×</span
          ><span class="sr-only">Close</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">Select Language</h4>
      </div>
      <div class="modal-body">
        <button type="button" class="btn" data-dismiss="modal">Close</button>
        <button type="button" class="btn" id="submit_form">Submit</button>

        <div class="modal-body1">
          <div id="placeholder-div1"></div>
        </div>
      </div>

      <div class="modal-footer">
        <script>
          $("#submit_form").on("click", function () {
            $(".modal-body1").html("<h3>test</h3>");
          });
        </script>

        <script>
          $(function () {
            $(".modal-footer").click(function () {
              $(".modal").modal("hide");
            });
          });
        </script>
      </div>
    </div>
  </div>
</div>
</code>```

-- Update ---

Why doesn't this work?

```<code><script type="text/javascript">
  $(function () {
    $("#myModal").on("hidden.bs.modal", function (e) {
      console.log("Modal hidden");
      $("#placeholder-div1").html("");
    });
  });
</script>
</code>```

答:
Using BS 3.3.7

$("#yourModal").on('hidden.bs.modal', function () {
    $(this).data('bs.modal', null); // will clear all element inside modal
});
```

Body:
I have a list box in the bootstrap modal and a button.
When the button is clicked a new button gets rendered inside a div in the modal.
When I close the modal and reopen it, the last operation performed on the modal like the button rendered earlier is still present in the modal.

How do reset the modal so that when the modal is opened again, the button is not present and user can again select the option from the list box and click on the button to render a new button and so on.

        <button type="button" class="close" data-dismiss="modal">
          ×Close
        </button>

Select Language

        <button type="button" class="btn" data-dismiss="modal">Close</button>
        <button type="button" class="btn" id="submit_form">Submit</button>

-- Update ---

Why doesn't this work?


问:
Remove ASCII or Unicode characters from encrypted data
I'm trying to get an encrypted code stored in a MySQL database using C#. Sometimes the code is fine but sometimes I get some ASCII and Unicode characters at the end of the decrypted code.

I understand, because of the encryption/decryption process, you get some extra characters; the problem is that those characters are not consistent (is not like I always get a bunch of \0 at the end).

```<code>codeA\0\0\0\0\0\0\0\0\0
codeB\u0010\u0010\u0010\u0010\u0010\u0010\u0010\u0010\u0010
codeC\b\b\b\b\b\b\b\b\b
codeD\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0003
</code>```

I get different ending characters and to be honest it would be difficult to add a "Replace" method for every character that happens to appear.

Is there a way to remove those "special" characters at the end? Or maybe am I just storing/reading the code wrong?

I write the process for PHP (web page utf-8, the writer of the code) and C# (console app, the reader of the code)

PHP

```<code>// Get $code from html form in utf-8

$code = $_POST['code'];
$encrypted_code = base64_encode(openssl_encrypt($code, 'aes-256-ecb', 'keykeykeykeykeykeykeykey', OPENSSL_RAW_DATA)));

// Store $encrypted_code into database
</code>```

C#

```<code>// Read encrypted_code from database using MySqlConnection

Aes aes = Aes.Create();
aes.Key = Encoding.UTF8.GetBytes("keykeykeykeykeykeykeykey");
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.None;
aes.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
string code = null;
using (aes)
{
            byte[] encrypted_code = Convert.FromBase64String(encrypted_code);
            using (var encrypted_stream = new MemoryStream(encrypted_code))
            using (var decrypter_stream = new CryptoStream(encrypted_stream, decryptor, CryptoStreamMode.Read))
            using (var decrypted_stream = new StreamReader(decrypter_stream))
            code = decrypted_stream.ReadLine().
                        Replace("\0", string.Empty).
                        Replace("\b", string.Empty).
                        Replace("\v", string.Empty).
                        Replace("\t", string.Empty).
                        Replace("\u0010", string.Empty).
                        Replace("\u0003", string.Empty).
                        Replace("\u0006", string.Empty);
}

//Use code for whatever
</code>```

答:
By default the PHP encryption method you chose adds padding which returns data results like "CodeA\0\0\0\0\0\0\0\0\0". In order to get decrypted data returned without the padding simply change the PaddingMode in the C# code to:

aes.Padding = PaddingMode.PKCS7;

BTW:
This code:
$encrypted_code = openssl_encrypt($code, 'aes-256-ecb', 'keykeykeykeykeykeykeykey');

produces the same as this code:
$encrypted_code = base64_encode(openssl_encrypt($code, 'aes-256-ecb', 'keykeykeykeykeykeykeykey', OPENSSL_RAW_DATA));

Body:
I'm trying to get an encrypted code stored in a MySQL database using C#. Sometimes the code is fine but sometimes I get some ASCII and Unicode characters at the end of the decrypted code.

I understand, because of the encryption/decryption process, you get some extra characters; the problem is that those characters are not consistent (is not like I always get a bunch of \0 at the end).

codeA\0\0\0\0\0\0\0\0\0
codeB\u0010\u0010\u0010\u0010\u0010\u0010\u0010\u0010\u0010
codeC\b\b\b\b\b\b\b\b\b
codeD\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0003\u0003

I get different ending characters and to be honest it would be difficult to add a "Replace" method for every character that happens to appear.

Is there a way to remove those "special" characters at the end? Or maybe am I just storing/reading the code wrong?

I write the process for PHP (web page utf-8, the writer of the code) and C# (console app, the reader of the code)

PHP

// Get $code from html form in utf-8

$code = $_POST['code'];
$encrypted_code = base64_encode(openssl_encrypt($code, 'aes-256-ecb', 'keykeykeykeykeykeykeykey', OPENSSL_RAW_DATA)));

// Store $encrypted_code into database

C#

// Read encrypted_code from database using MySqlConnection

Aes aes = Aes.Create();
aes.Key = Encoding.UTF8.GetBytes("keykeykeykeykeykeykeykey");
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.None;
aes.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
string code = null;
using (aes)
{
            byte[] encrypted_code = Convert.FromBase64String(encrypted_code);
            using (var encrypted_stream = new MemoryStream(encrypted_code))
            using (var decrypter_stream = new CryptoStream(encrypted_stream, decryptor, CryptoStreamMode.Read))
            using (var decrypted_stream = new StreamReader(decrypter_stream))
            code = decrypted_stream.ReadLine().
                        Replace("\0", string.Empty).
                        Replace("\b", string.Empty).
                        Replace("\v", string.Empty).
                        Replace("\t", string.Empty).
                        Replace("\u0010", string.Empty).
                        Replace("\u0003", string.Empty).
                        Replace("\u0006", string.Empty);
}

//Use code for whatever


问:
Print function with class
```<code>x <- structure(1:3, foo = 42, class = "hello")

x
[1] 1 2 3
attr(,"foo")
[1] 42
attr(,"class")
[1] "hello"
</code>```

But if we set

```<code>print.hello <- function(x, ...){
    print(123)
}
</code>```

x will become

```<code>x
[1] 123
</code>```

Why the print.hello function overwrite everything in x?

P.S. I'm reading Hands-On Programming with R, 10.4.1 Method Dispatch

答:
It doesn't, x stays the same, the print of x however changes.</p>

```<code>> x <- structure(1:3, foo = 42, class = "hello")
> print.hello <- function(x, ...){
>   print("asffdas")
> }
> x
[1] "asffdas"
> as.numeric(x)
[1] 1 2 3
</code>```

Title: Print function with class

Body:
x <- structure(1:3, foo = 42, class = "hello")

x
[1] 1 2 3
attr(,"foo")
[1] 42
attr(,"class")
[1] "hello"

But if we set

print.hello <- function(x, ...){
    print(123)
}

x will become

x
[1] 123

Why the print.hello function overwrite everything in x?

P.S. I'm reading Hands-On Programming with R, 10.4.1 Method Dispatch

Body:
It doesn't, x stays the same, the print of x however changes.

> x <- structure(1:3, foo = 42, class = "hello")
> print.hello <- function(x, ...){
>   print("asffdas")
> }
> x
[1] "asffdas"
> as.numeric(x)
[1] 1 2 3


问:
How to add draging slider same as Netflix?
what i want is to add a dragging slider (or sliding of images by click n swiping ) into my page
Here is the example of code
https://codepen.io/amar1203/pen/ExjyKLz

```<code>   <html>
   <body>

  https://codepen.io/amar1203/pen/ExjyKLz

    </html
</code>```

but i want dragging feature inisde it check this and help me out with the code.

答:
Check the implementation with slick slider. For more details and implementation options on slick slider, please refer Here

var $ = jQuery;
$(document).ready(function() {
  $('.wrapper').slick({
    infinite: true,
    slidesToShow: 3,
    slidesToScroll: 3,
    mobileFirst:true,
     responsive: [
     {
      breakpoint: 1300,
      settings: {
        slidesToShow: 5,
        slidesToScroll: 5,
        infinite: true,
      }
    },
    {
      breakpoint: 1024,
      settings: {
        slidesToShow: 3,
        slidesToScroll: 3,
        infinite: true,
      }
    },
    {
      breakpoint: 600,
      settings: {
        slidesToShow: 2,
        slidesToScroll: 2
      }
    }]
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  scroll-behavior: smooth;
}

body {
  margin: 0;
  background-color: #000;
}

h1 {
  font-family: Arial;
  color: red;
  text-align: center;
}

.slick-prev {
  z-index: 1!important;
  left: 0 !important;
}

.slick-prev:before {
  content: '‹' !important;
  font-size: 60px!important;
}

.slick-next {
  right: 0 !important;
}

.slick-next:before {
  content: '›'!important;
  font-size: 60px!important;
}

.item {
  transition: .5s;
}

.item:hover {
  transition: .5s;
  transform: scale(1.2);
}

/* .wrapper {
    display: grid;
    grid-template-columns: repeat(3, 100%);
    overflow: hidden;
    scroll-behavior: smooth;
 }
 .wrapper section {
    width: 100%;
    position: relative;
    display: grid;
    grid-template-columns: repeat(7, auto);
    margin: 20px 0;
 }

 .wrapper section .item {
    padding: 0 2px;
    transition: 250ms all;
 }
 .wrapper section .item:hover {
    margin: 0 40px;
    transform: scale(1.2);
 }
 .wrapper section a {
    position: absolute;
    color: #fff;
    text-decoration: none;
    font-size: 6em;
    background: #000;
    width: 80px;
    padding: 20px;
    text-align: center;
    z-index: 1;
 }
 .wrapper section a:nth-of-type(1) {
    top: 0;
    bottom: 0;
    left: 0;
    background: linear-gradient(-90deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 1) 100%);
 }
 .wrapper section a:nth-of-type(2) {
    top: 0;
    bottom: 0;
    right: 0;
    background: linear-gradient(90deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 1) 100%);
 } */</code>```

<link href="https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css" rel="stylesheet"/>

<link href="https://kenwheeler.github.io/slick/slick/slick-theme.css" rel="stylesheet"/>

NETFLIX

```

Body:
what i want is to add a dragging slider (or sliding of images by click n swiping ) into my page
Here is the example of code
https://codepen.io/amar1203/pen/ExjyKLz

  https://codepen.io/amar1203/pen/ExjyKLz

    </html

but i want dragging feature inisde it check this and help me out with the code.

Body:
Check the implementation with slick slider. For more details and implementation options on slick slider, please refer Here

var $ = jQuery;
$(document).ready(function() {
  $('.wrapper').slick({
    infinite: true,
    slidesToShow: 3,
    slidesToScroll: 3,
    mobileFirst:true,
     responsive: [
     {
      breakpoint: 1300,
      settings: {
        slidesToShow: 5,
        slidesToScroll: 5,
        infinite: true,
      }
    },
    {
      breakpoint: 1024,
      settings: {
        slidesToShow: 3,
        slidesToScroll: 3,
        infinite: true,
      }
    },
    {
      breakpoint: 600,
      settings: {
        slidesToShow: 2,
        slidesToScroll: 2
      }
    }]
  });
});

html {
  scroll-behavior: smooth;
}

body {
  margin: 0;
  background-color: #000;
}

h1 {
  font-family: Arial;
  color: red;
  text-align: center;
}

.slick-prev {
  z-index: 1!important;
  left: 0 !important;
}

.slick-prev:before {
  content: '‹' !important;
  font-size: 60px!important;
}

.slick-next {
  right: 0 !important;
}

.slick-next:before {
  content: '›'!important;
  font-size: 60px!important;
}

.item {
  transition: .5s;
}

.item:hover {
  transition: .5s;
  transform: scale(1.2);
}

/* .wrapper {
    display: grid;
    grid-template-columns: repeat(3, 100%);
    overflow: hidden;
    scroll-behavior: smooth;
 }
 .wrapper section {
    width: 100%;
    position: relative;
    display: grid;
    grid-template-columns: repeat(7, auto);
    margin: 20px 0;
 }

 .wrapper section .item {
    padding: 0 2px;
    transition: 250ms all;
 }
 .wrapper section .item:hover {
    margin: 0 40px;
    transform: scale(1.2);
 }
 .wrapper section a {
    position: absolute;
    color: #fff;
    text-decoration: none;
    font-size: 6em;
    background: #000;
    width: 80px;
    padding: 20px;
    text-align: center;
    z-index: 1;
 }
 .wrapper section a:nth-of-type(1) {
    top: 0;
    bottom: 0;
    left: 0;
    background: linear-gradient(-90deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 1) 100%);
 }
 .wrapper section a:nth-of-type(2) {
    top: 0;
    bottom: 0;
    right: 0;
    background: linear-gradient(90deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 1) 100%);
 } */

<link href="https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js"></script>

<link href="https://kenwheeler.github.io/slick/slick/slick-theme.css" rel="stylesheet"/>
<h1>NETFLIX</h1>
<div class="wrapper">
  <div class="item">
    <img src="https://occ-0-1567-1123.1.nflxso.net/dnm/api/v5/rendition/412e4119fb212e3ca9f1add558e2e7fed42f8fb4/AAAABRvngexxF8H1-OzRWFSj6ddD-aB93tTBP9kMNz3cIVfuIfLEP1E_0saiNAwOtrM6xSOXvoiSCMsihWSkW0dq808-R7_lBnr6WHbjkKBX6I3sD0uCcS8kSPbRjEDdG8CeeVXEAEV6spQ.webp" />
  </div>
  <div class="item">
    <img src="https://occ-0-243-299.1.nflxso.net/dnm/api/v5/rendition/412e4119fb212e3ca9f1add558e2e7fed42f8fb4/AAAABZEK-7pZ1H5FD4cTyUb9qB_KeyJGz5p-kfPhCFv4GU_3mbdm8Xfsy4IBchlG9PFNdGff8cBNPaeMra72VFnot41nt0y3e8RLgaVwwh3UvyM2H2_MkmadWbQUeGuf811K7-cxJJh7gA.jpg" />
  </div>
  <div class="item">
    <img src="https://occ-0-243-299.1.nflxso.net/dnm/api/v5/rendition/412e4119fb212e3ca9f1add558e2e7fed42f8fb4/AAAABQCoK53qihwVPLRxPEDX98nyYpGbxgi5cc0ZOM4iHQu7KQvtgNyaNM5PsgI0vy5g3rLPZdjGCFr1EggrCPXpL77p2H08jV0tNEmIfs_e8KUfvBJ6Ay5nM4UM1dl-58xA6t1swmautOM.webp" />
  </div>
  <div class="item">
    <img src="https://occ-0-243-299.1.nflxso.net/dnm/api/v5/rendition/412e4119fb212e3ca9f1add558e2e7fed42f8fb4/AAAABdYtAqj8CyaJTWq5taD8Ro_UgwH3nne9QpFGVps-2J3IG-leqrfqXFii4jzZn48nPYTkrlwKQEV0R7_cEKlYBPRzdKqNODc-Oz26IL3LlLgFboXibIWXwxzeYxzuqn0I9TpARjeByw.jpg" />
  </div>
  <div class="item">
    <img src="https://occ-0-243-299.1.nflxso.net/dnm/api/v5/rendition/412e4119fb212e3ca9f1add558e2e7fed42f8fb4/AAAABbcCX42tsqGbBvO2y9CQv5-7QvYbCfoHtXsuc6NPCtZaKa4l4fBX3XWvUwG9F2A3CTsNpHVmulxBbdXKwK8Q6xGjejd9FoadGkZ7CnGrSl601TOQjzSHJ23NuIPC8j0QMGORL4uRIA.jpg" />
  </div>

  <div class="item">
    <img src="https://occ-0-243-299.1.nflxso.net/dnm/api/v5/rendition/412e4119fb212e3ca9f1add558e2e7fed42f8fb4/AAAABVopDZ5Fy9_fk_HO5WxHTXKKjKhtWFupbSjuvPwfLK_vytzon4EwRUdGgYJ34JwPxOTK_NkV3aXfkULMB0Dcct-FyfqzH-X44VXuRMp4QeBHlvKwWeZFpZlGdItPzmmg4scmwhG7SQ.jpg" />
  </div>
  <div class="item">
    <img src="https://occ-0-243-299.1.nflxso.net/dnm/api/v5/rendition/412e4119fb212e3ca9f1add558e2e7fed42f8fb4/AAAABTOj1-116yVcgKWMU2dI3GFR4x0fSkiGsqtLLeLUxRR7STaksjAqBTrYlTfrB8nIGnGvXksi0ewXAhVGg6-pLxpFOIfcpjK-pf8D5xehFZo5a6vJbo4L0AGbrzglbyUoq255QBJgRQ.jpg" />
  </div>
  <div class="item">
    <img src="https://occ-0-243-299.1.nflxso.net/dnm/api/v5/rendition/a76057bcfd003711a76fb3985b1f2cf74beee3b8/AAAABd3IBDpxbRcHXvRMFCZeKa2aHLU1P4SJtrACMS9om3yhLjqPlvNlmR_fypPxjtbsbnKaC4JZhPSpDG4r_kdxSHHAltWguMcCB-1Y1OShr2zWfUv7Whf_39fNH5ZJ3_0gxQrs0akmQjQz44_LT7jXH5LMZ7iMBAzac5IEj4m7Fn_5OWEGYnVsDsKG-QTommDooULMDF9bEw.jpg" />
  </div>
  <div class="item">
    <img src="https://occ-0-243-299.1.nflxso.net/dnm/api/v5/rendition/a76057bcfd003711a76fb3985b1f2cf74beee3b8/AAAABXSd7bhDddcwkq9XpksoQFCHVx29Sxl_h4hb2n3F2GIt32a4XWcOnctQfgnT5qdolv8UML6_xNB5CJ89h56wueb13mYmEBr0sx5e9iLPdtVcOQAOmKXKWHHXwFvJuCUwuNnL3s8eAQwqLXPVMHMEsujM684rUGrZNF2btN2GRy5-RyEslsxZO93V2Q_H2bWs8A8oayt1h5M.webp" />
  </div>
  <div class="item">
    <img src="https://occ-0-243-299.1.nflxso.net/dnm/api/v5/rendition/a76057bcfd003711a76fb3985b1f2cf74beee3b8/AAAABbXWODpAWqVXcmmjMA7K-2mPkQpvwCLfSdeyhVXzR8A3MSpdSEnnjf4HEJJTYC-TnktU6njTUGAxmzWEYCaJbk4v_ZeL-7QGzmkvYBjg_N-evr2XmcX-Fanoyvu_nimFP4iigPe4O3Vr_WcgplhwkDrJwPUJa84wRLrNAx3TufN5V7cWRP4indqu5HQahvgFEqfL9zjp4g.jpg" />
  </div>

  <div class="item">
    <img src="https://occ-0-243-299.1.nflxso.net/dnm/api/v5/rendition/412e4119fb212e3ca9f1add558e2e7fed42f8fb4/AAAABRr4YxdaABuAuH_3FmSQZn7BCvLp-UUPsXE9MiYpvFP3CSUHV2zOew5oVqKqqdaOd3tbFVS0Uf67uIs7_eZydlCghg4nK0nMatRpPImABwTOhnNzCLCxdKrua7pPIcPCZqBYTeAO5g.jpg" />
  </div>
  <div class="item">
    <img src="https://occ-0-243-299.1.nflxso.net/dnm/api/v5/rendition/412e4119fb212e3ca9f1add558e2e7fed42f8fb4/AAAABTyWK1MKaw8GcObtz47R2Tj7wkLJ7qQu9tk6TVpcoyxpzD4B-zZ569bQ5vGrREBL-MWFkGilXUwy7tCDaj2XOGkUB4RsbbFAmp9NgSr6lygMpUGNHSlyfrFbUORsRkrxSIoh_ggOvg.jpg" />
  </div>
  <div class="item">
    <img src="https://occ-0-243-299.1.nflxso.net/dnm/api/v5/rendition/a76057bcfd003711a76fb3985b1f2cf74beee3b8/AAAABY7NwkWEJIfXsn6t3Li4bGSCQ1nEErPisI5ZZtXlC-_VRBZOUrhWK5X3vt3t6SR_cpgVhCwxgQqFFDJhk62Kk8hawOnYGZMr0LKeLczMFV2zalCFjkcdLksvT4HB2LEi6LFyruyk3Uu0LmNGsHfC2A8Bly60smr_3sDbz4RruXcklPOG1qYq9wUVu3zfaiwNvqmG4b8aFA.jpg" />
  </div>
  <div class="item">
    <img src="https://occ-0-243-299.1.nflxso.net/dnm/api/v5/rendition/a76057bcfd003711a76fb3985b1f2cf74beee3b8/AAAABemXHOga9feFnOux6I2YyACBD94wvM7N3vcTGIfMpQ_BcaXeoeM9XyzdVdamKtxt0SHXZfvsl6czcp3E48tXMLtHBxuQsh1BjHtPGgJDZ81je_FjItINiqzLtir0A30s_e4KR8G3d7AYAPDjZVOY97bNpzNqtkcHcGp7fGnJByVCps1uLfG9U9tK3Ma1A_3JbRt0NiT2_Q.jpg" />
  </div>
  <div class="item">
    <img src="https://occ-0-243-299.1.nflxso.net/dnm/api/v5/rendition/a76057bcfd003711a76fb3985b1f2cf74beee3b8/AAAABVxuRB932hvre-XP0gh6ar5ztoR3Oe3QjKHkyvcDnRak2MKXOrx5H7mFQSvggefMFOppwEs7ZCCpiqrJ_CYGvtvYB9NpU4SWUtNO6uV2u-DTID267AcHjHcGvGBQJ1ufddDkxcGOZyi5MlOQ5QUmBun4652FbYUnib3zMYQDgcna_Pvz8y_HO5fbokxezrRR1JZAAiqFSQ.jpg" />
  </div>

</div>


答:
Remove relative path use like below. As src is used directly just like that use node_modules not ./node_modules

```<code>"styles": [

              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/styles.css"
            ],
</code>```

A good resource link is

https://medium.com/@oyewusioyekunle/how-to-add-bootstrap-to-your-angular-project-angular-8-6379fd6a0f46

Title: Bootstrap version 3.4 not working in Angular 9

Body:
Remove relative path use like below. As src is used directly just like that use node_modules not ./node_modules

"styles": [

              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/styles.css"
            ],

A good resource link is

https://medium.com/@oyewusioyekunle/how-to-add-bootstrap-to-your-angular-project-angular-8-6379fd6a0f46


问:
How can we transform pairwise mapped strings to multiple groups of strings based on a score?
If pairwise mapping of words has score more than 0.5, then group them together.If any other keyword having score more than 0.5 with a group, add the keyword to the group.

Example:

Input:

```<code>word1              word2       score
hello           hello world    0.75
hello world     hi world       0.555
hello           hi world       0
good morning    hello          0
good morning    morning        0.75
morning         hello          0
morning         hello world    0
morning         hi world       0
good morning    hello world    0
good morning    hi world       0
</code>```

Output:

```<code>word                 group
hello                 1
hello world           1
hi world              1
good morning          2
morning               2
</code>```

答:
First filter rows by boolean indexing and Series.gt:

```<code>df1 = df[df['score'].gt(0.5)]
print (df1)
          word1        word2  score
0         hello  hello world  0.750
1   hello world     hi world  0.555
4  good morning      morning  0.750
</code>```

Use networkx with connected_components for dictionary:

```<code>import networkx as nx

# Create the graph from the dataframe
g = nx.Graph()
g.add_edges_from(df1[['word1','word2']].itertuples(index=False))

connected_components = nx.connected_components(g)

# Find the component id of the nodes
node2id = {}
for cid, component in enumerate(connected_components):
    for node in component:
        node2id[node] = cid + 1
</code>```

Last reshape by DataFrame.stack, remove duplicates by Series.drop_duplicates and last use Series.map for new column:

```<code>df2 = df1[['word1','word2']].stack().drop_duplicates().reset_index(drop=True).to_frame('word')
df2['group'] = df2['word'].map(node2id)
print (df2)
           word  group
0         hello      1
1   hello world      1
2      hi world      1
3  good morning      2
4       morning      2
</code>```

Body:
If pairwise mapping of words has score more than 0.5, then group them together.If any other keyword having score more than 0.5 with a group, add the keyword to the group.

Example:

Input:

word1              word2       score
hello           hello world    0.75
hello world     hi world       0.555
hello           hi world       0
good morning    hello          0
good morning    morning        0.75
morning         hello          0
morning         hello world    0
morning         hi world       0
good morning    hello world    0
good morning    hi world       0

Output:

word                 group
hello                 1
hello world           1
hi world              1
good morning          2
morning               2

Body:
First filter rows by boolean indexing and Series.gt:

df1 = df[df['score'].gt(0.5)]
print (df1)
          word1        word2  score
0         hello  hello world  0.750
1   hello world     hi world  0.555
4  good morning      morning  0.750

Use networkx with connected_components for dictionary:

import networkx as nx

# Create the graph from the dataframe
g = nx.Graph()
g.add_edges_from(df1[['word1','word2']].itertuples(index=False))

connected_components = nx.connected_components(g)

# Find the component id of the nodes
node2id = {}
for cid, component in enumerate(connected_components):
    for node in component:
        node2id[node] = cid + 1

Last reshape by DataFrame.stack, remove duplicates by Series.drop_duplicates and last use Series.map for new column:

df2 = df1[['word1','word2']].stack().drop_duplicates().reset_index(drop=True).to_frame('word')
df2['group'] = df2['word'].map(node2id)
print (df2)
           word  group
0         hello      1
1   hello world      1
2      hi world      1
3  good morning      2
4       morning      2


问:
Your Windows License Will Expire Soon
How can I temporarily remove the showing of "Your Windows License Will Expire Soon" on my laptop?
I am currently doing lots of things right now and I don't want to address this problem for now.</p>

答:
try in cmd slmgr /rearm it will reset the counter to 30 days

This command can only be used several times, so you can’t indefinitely
  extend the trial. The number of time it can be used depends on the
  “rearm count,” which you can view using the slmgr.vbs /dlv command. It
  seems different on different versions of Windows–it was three times on
  Windows 7, and it seems to be five times on Windows Server 2008 R2.

Please note:

This no longer seems to work on Windows 10, which is very lenient if
  you don’t provide it a product key anyway. This option still works on
  older versions of Windows and may continue to work on other editions
  of Windows, such as Windows Server, in the future.

Title: Your Windows License Will Expire Soon


问:
Sharing on social media, the URL does not render any meta data
We have built a project (Web Application) in React .net core using react in client-side rendering.

We've used react-helmet for dynamically assigning meta tags.

The issue being when the app renders in the browser. The browser gets only the static HTML on initial load which does not include the dynamic meta tags we have set. However on inspecting you get those meta tags under "Elements".

Also, if we use these URL for sharing on any social media, like WhatsApp or Facebook, the URL does not render any metadata as it should.

Tried searching for solutions to our problem, the most obvious answer we came across was to try server-side rendering instead. We get that, but it is not a solution to try out at this juncture when we're ready with app to roll it out.

Others we came across were "react-snap", "react-snapshot", but no luck
with react-snap, it requires to upgrade React's version to 16+, which we did but I guess not all dependencies were upgraded, there was an error saying "

hydrate is not a function

(hydrate concerns the react-dom)

With react-snapshot, we could not find the necessary type definition, which is required in react .net core to function properly

Please guide for the next probable step (except the paid ones like prerender, etc)?

Main goal: Social Applications should render the meta data when we paste/share the URL within them.

答:
I had the same issue today. I had two React Web applications that need this. Here is how I solved it:

put your preview image in the public folder

still in public folder, Open index.html, add the line <meta property="og:image" content="preview.png"/>
or <meta property="og:image" content="%PUBLIC_URL%/preview.png"/>.

Go to https://www.linkedin.com/post-inspector/  to check if it works.

I hope this would help!


问:
Changing timezone of a system using Java
I am currently writing an application where I want to provide a feature wherein a user can change the current time and timezone of the system.
Using the input timezone value , I run a shell script  which links the local time to the passed timezone.
On UI, I am showing a list of timezones by calling - TimeZone.getAvailableIDs();
This retrieves TZ info from the "tzdb.dat" which comes along with the JRE.

But some of the timezones like "IST" are not supported by the native system. And these kind of unsupported Timezones are returned by TimeZone.getAvailableIDs().

So is there any way in Java where we can retrieve native system supported timezones ?

答:
Time zones have a poor history

Time zones are, surprisingly, a real mess. I have been surprised to learn that they have not historically been well-defined and standardized.

In more recent times, a format of Continent/Region seems to have been widely adopted. See examples on this Wikipedia page. And learn about tzdata maintained currently by IANA.

You asked:

is there any way in Java where we can retrieve native system supported timezones ?

The TimeZone class in Java is now obsolete, supplanted by the modern java.time class ZoneId. Get a set of time zone names.

```<code>Set< String > zoneIds = ZoneId.getAvailableZoneIds() ;
</code>```

Time zones change surprisingly often, both in their name and their currently used offset-from-UTC. Be sure to keep the tzdata in your Java implementation up-to-date. Ditto for your host OS. And your database system as well, with some such as Postgres having their own internal copy.

True time zones

You said:

But some of the timezones like "IST"

IST is not a real time zone. It is a pseudo-zone, which could mean Irish Standard Time, India Standard Time, or something else.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

If you meant India time, use:

```<code>ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
</code>```

If you meant Ireland time, use:

```<code>ZoneId z = ZoneId.of( "Europe/Dublin" ) ;
</code>```

Do not rely on current default time zone

As commented by Matt Johnson-Pint, you should generally not be altering your host OS’ default time zone. Indeed, servers should usually be set for UTC (an offset of zero hours-minutes-seconds).

In your Java code, always specify your desired/expected time zone. The JVM’s current default time zone can be altered at any moment by any code in any thread of any app within the JVM — so depending on the current default is not reliable.

If you want the current moment as seen in India, specify the appropriate time zone.

```<code>ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;  // Capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone).
</code>```

Body:
Time zones have a poor history

Time zones are, surprisingly, a real mess. I have been surprised to learn that they have not historically been well-defined and standardized.

In more recent times, a format of Continent/Region seems to have been widely adopted. See examples on this Wikipedia page. And learn about tzdata maintained currently by IANA.

You asked:

is there any way in Java where we can retrieve native system supported timezones ?

The TimeZone class in Java is now obsolete, supplanted by the modern java.time class ZoneId. Get a set of time zone names.

Set< String > zoneIds = ZoneId.getAvailableZoneIds() ;

Time zones change surprisingly often, both in their name and their currently used offset-from-UTC. Be sure to keep the tzdata in your Java implementation up-to-date. Ditto for your host OS. And your database system as well, with some such as Postgres having their own internal copy.

True time zones

You said:

But some of the timezones like "IST"

IST is not a real time zone. It is a pseudo-zone, which could mean Irish Standard Time, India Standard Time, or something else.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

If you meant India time, use:

ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;

If you meant Ireland time, use:

ZoneId z = ZoneId.of( "Europe/Dublin" ) ;

Do not rely on current default time zone

As commented by Matt Johnson-Pint, you should generally not be altering your host OS’ default time zone. Indeed, servers should usually be set for UTC (an offset of zero hours-minutes-seconds).

In your Java code, always specify your desired/expected time zone. The JVM’s current default time zone can be altered at any moment by any code in any thread of any app within the JVM — so depending on the current default is not reliable.

If you want the current moment as seen in India, specify the appropriate time zone.

ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;  // Capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone).


问:
How we can make a URL dynamic in [TestInitialize] Method in mstest, c#?
My code is(I replace actual URL with ../../../).

```<code>[TestInitialize]
        public static void Initalize()
        {
            AppiumOptions desiredcap = new AppiumOptions();
            desiredcap.AddAdditionalCapability("app", @".../../../..../");
            driver = new WindowsDriver<WindowsElement>(new Uri("http://127.0.0.1:4723"), desiredcap);

            if (driver == null)
            {
                Console.WriteLine("App not running");
                return;
            }
}
</code>```

I want to make URL dynamic of

```<code>desiredcap.AddAdditionalCapability("app", @".../../../..../");
</code>```

because i want to use this method in different project. Is it possible to write variable url instead of ../../../ and take url value from some other file or from Testcase.

答:
So, you can create base class with Initalize(string capUrl) method and call it in derived classes as here:

```<code>    [TestInitialize]
    public static void Initalize()
    {
        base.Initalize("http://SomeUri.com")
    }
</code>```

If you need to specify it in Testcase. Then you need to remove [TestInitialize] and it's better to rename it  to something like "PrepareTest". And call it by hands in test method. Like this:

```<code>[Testcase("http://SomeUri.com")]
public void TestMethod(string uri)
{
    this.PrepareTest(uri);
}
</code>```

Is this solution helps you? Or you need something other?

Body:
My code is(I replace actual URL with ../../../).

[TestInitialize]
        public static void Initalize()
        {
            AppiumOptions desiredcap = new AppiumOptions();
            desiredcap.AddAdditionalCapability("app", @".../../../..../");
            driver = new WindowsDriver<WindowsElement>(new Uri("http://127.0.0.1:4723"), desiredcap);

            if (driver == null)
            {
                Console.WriteLine("App not running");
                return;
            }
}

I want to make URL dynamic of

desiredcap.AddAdditionalCapability("app", @".../../../..../");

because i want to use this method in different project. Is it possible to write variable url instead of ../../../ and take url value from some other file or from Testcase.

Body:
So, you can create base class with Initalize(string capUrl) method and call it in derived classes as here:

    [TestInitialize]
    public static void Initalize()
    {
        base.Initalize("http://SomeUri.com")
    }

If you need to specify it in Testcase. Then you need to remove [TestInitialize] and it's better to rename it  to something like "PrepareTest". And call it by hands in test method. Like this:

[Testcase("http://SomeUri.com")]
public void TestMethod(string uri)
{
    this.PrepareTest(uri);
}

Is this solution helps you? Or you need something other?


问:
arithmatic operators as a function input (C++)
Let's say I have a function

```<code>#include <iostream>
int do_math (num_1, num_2, "*"){
....
}
</code>```

Where the code takes the inputs and applies the operator in the function to obtain the result of the calculation.

I'm not sure how to incorporate the arithmetic operator in the function to do the calculation. I was thinking of using the operator value from the ASCII table, but I was hoping maybe I can somehow incorporate istringstream method to do that. Any suggestions?

答:
Use char type for the operator and check it in the switch.

For example:

```<code>int do_math( const int a, const int b, const char op )
{
    switch ( op )
    {
    case '+':
        return a + b;

    // ...
    }
}
</code>```

Body:
Let's say I have a function

#include <iostream>
int do_math (num_1, num_2, "*"){
....
}

Where the code takes the inputs and applies the operator in the function to obtain the result of the calculation.

I'm not sure how to incorporate the arithmetic operator in the function to do the calculation. I was thinking of using the operator value from the ASCII table, but I was hoping maybe I can somehow incorporate istringstream method to do that. Any suggestions?

Body:
Use char type for the operator and check it in the switch.

For example:

int do_math( const int a, const int b, const char op )
{
    switch ( op )
    {
    case '+':
        return a + b;

    // ...
    }
}


问:
Converting doc.x to pdf file using python3 in mac
I'm beginner in python3 and I have a project to convert word files (doc.x) to pdf files on mac.

I saw few codes that relevant to windows but didn't succeeding adapt it to mac.

someone can help me?

答:
You can use the docx2pdf python library to convert docx to pdf on macOS (or Windows). It uses Microsoft Word's APIs to directly convert to PDF creating a perfect copy. Internally, it uses JXA (Javscript for Automation, basically AppleScript in JS) in macOS and win32com in Windows.

Install:

```<code>pip install docx2pdf
</code>```

Usage:

```<code>from docx2pdf import convert
convert("input.docx", "output.pdf")
</code>```

Disclaimer: I wrote this tool after struggling to find a cross-platform solution for batch converting docx to pdf with zero formatting issues since it directly uses Microsoft Word. Please give the repo a star if it helps! https://github.com/AlJohri/docx2pdf

Body:
You can use the docx2pdf python library to convert docx to pdf on macOS (or Windows). It uses Microsoft Word's APIs to directly convert to PDF creating a perfect copy. Internally, it uses JXA (Javscript for Automation, basically AppleScript in JS) in macOS and win32com in Windows.

Install:

pip install docx2pdf

Usage:

from docx2pdf import convert
convert("input.docx", "output.pdf")

Disclaimer: I wrote this tool after struggling to find a cross-platform solution for batch converting docx to pdf with zero formatting issues since it directly uses Microsoft Word. Please give the repo a star if it helps! https://github.com/AlJohri/docx2pdf


问:
SurfaceView inside TabHost causes crash
I have a SurfaceView-derived class in an Activity inside a TabHost (like the HelloTabWidget sample). The SurfaceView I'm using comes with the excellent andrtoid-flot-chart library: FlotChartContainer.java

When I switch between the tabs, everything works. However, as soon as the tab containing this view has been initialized (e.g. shown) my application is doomed. It will crash whenever the following occurs:

Pressing Home button
When I re-open my application, it crashes due to an IllegalStateException in surfaceCreated().

Starting new activity
When I start a new activity (startActivity) and press the Back button (this invokes my SurfaceView's surfaceDestroyed...?!), it crashes due to an IllegalStateException in surfaceCreated().

I'm targeting API level 7 (Android 2.1).

The code works when TabHost is not used.

Switching between tabs does not invoke surfaceDestroyed(). Instead, onPause() and onResume() are used.

When an activity is finished, surfaceDestroyed() is called even if it is not in the active tab.

Please help!

答: Check activity life cycle in android , while onPause() , onStop() , onDestroy() , destroy the surface view which has been used in your application , and recreate surface in onResume() , then it is working fine.</p>

Title: SurfaceView inside TabHost causes crash


问:
Why a || a = 'bar' will get a reference error in javascript?
The code snippet is:

```<code>var a = 'foo'
a || a = 'bar'
</code>```

What I expected is that it can work normally which means a will be 'bar' finally.But I got an error

Uncaught SyntaxError: Invalid left-hand side in assignment.

According to the error,I thought maybe it is something wrong with the left hand side expression a || a.It seems that a || a is invalid here.But why?I turn to ecmascript language specification for help.In 12.15.1 Static Semantics: Early Errors, I find:

It is an early Reference Error if LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral and AssignmentTargetType of LeftHandSideExpression is invalid.

So, the AssignmentTargetType of LeftHandSideExpression a||a is invalid.But I am confused why a||a 's AssignmentTargetType is invalid.About this,the specification just said:

12.15.3 Static Semantics: AssignmentTargetType

AssignmentExpression:

YieldExpression

ArrowFunction

AsyncArrowFunction

LeftHandSideExpression = AssignmentExpression

LeftHandSideExpression AssignmentOperator AssignmentExpression

Return invalid.

I can't figure out why a||a 's AssignmentTargetType is invalid based on what is given.

My question is: Why a||a = 'bar' will get a reference error in javascript?If it is something with invalid AssignmentTargetType of LeftHandSideExpression,why a||a is invalid?

答: JavaScript will execute from left to right. a || a will evaluate to foo before you try re-assigning a new value to a. That means you're trying to run 'foo' = 'bar' which leads you to your invalid left hand assignment error.

Body:
The code snippet is:

var a = 'foo'
a || a = 'bar'

What I expected is that it can work normally which means a will be 'bar' finally.But I got an error

Uncaught SyntaxError: Invalid left-hand side in assignment.

According to the error,I thought maybe it is something wrong with the left hand side expression a || a.It seems that a || a is invalid here.But why?I turn to ecmascript language specification for help.In 12.15.1 Static Semantics: Early Errors, I find:

It is an early Reference Error if LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral and AssignmentTargetType of LeftHandSideExpression is invalid.

So, the AssignmentTargetType of LeftHandSideExpression a||a is invalid.But I am confused why a||a 's AssignmentTargetType is invalid.About this,the specification just said:

12.15.3 Static Semantics: AssignmentTargetType

AssignmentExpression:

YieldExpression

ArrowFunction

AsyncArrowFunction

LeftHandSideExpression = AssignmentExpression

LeftHandSideExpression AssignmentOperator AssignmentExpression

Return invalid.

I can't figure out why a||a 's AssignmentTargetType is invalid based on what is given.

My question is: Why a||a = 'bar' will get a reference error in javascript?If it is something with invalid AssignmentTargetType of LeftHandSideExpression,why a||a is invalid?


问:
post and put api call through tornado
I wanted to post and update data in yaml file through tornado api call .. could you please give some code example</p>

```<code>import tornado.web
import tornado.ioloop
import nest_asyncio
import json

class basicRequestHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello , world...." )

if __name__ =="__main__":
    app = tornado.web.Application([(r"/", basicRequestHandler)])

    app.listen(8881)
    print("I'm listening on port 8881")
    tornado.ioloop.IOLoop.current().start()
</code>```

答:
Prepared for you this example:</p>

```<code>from typing import Dict

import tornado.web
import tornado.ioloop

import yaml
from tornado.escape import json_decode

class BaseHandler(tornado.web.RequestHandler):
    yaml_filename = 'data.yaml'
    json_args: Dict

    async def prepare(self):
        self.json_args = json_decode(self.request.body) or {}

    def data_received(self, chunk):
        ...

class MainHandler(BaseHandler):
    def post(self):
        with open(self.yaml_filename, 'w') as file:
            # ...
            yaml.dump(self.json_args, file)

    def put(self):
        with open(self.yaml_filename) as file:
            yaml_data = yaml.full_load(file)
        # ...
        yaml_data.update(self.json_args)
        # ...
        with open(self.yaml_filename, 'w') as file:
            yaml.dump(yaml_data, file)

if __name__ == "__main__":
    app = tornado.web.Application([(r"/", MainHandler)])
    app.listen(8881)
    print("I'm listening on port 8881")
    tornado.ioloop.IOLoop.current().start()
</code>```

Title: post and put api call through tornado

Body:
I wanted to post and update data in yaml file through tornado api call .. could you please give some code example

import tornado.web
import tornado.ioloop
import nest_asyncio
import json

class basicRequestHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello , world...." )

if __name__ =="__main__":
    app = tornado.web.Application([(r"/", basicRequestHandler)])

    app.listen(8881)
    print("I'm listening on port 8881")
    tornado.ioloop.IOLoop.current().start()

Body:
Prepared for you this example:

from typing import Dict

import tornado.web
import tornado.ioloop

import yaml
from tornado.escape import json_decode

class BaseHandler(tornado.web.RequestHandler):
    yaml_filename = 'data.yaml'
    json_args: Dict

    async def prepare(self):
        self.json_args = json_decode(self.request.body) or {}

    def data_received(self, chunk):
        ...

class MainHandler(BaseHandler):
    def post(self):
        with open(self.yaml_filename, 'w') as file:
            # ...
            yaml.dump(self.json_args, file)

    def put(self):
        with open(self.yaml_filename) as file:
            yaml_data = yaml.full_load(file)
        # ...
        yaml_data.update(self.json_args)
        # ...
        with open(self.yaml_filename, 'w') as file:
            yaml.dump(yaml_data, file)

if __name__ == "__main__":
    app = tornado.web.Application([(r"/", MainHandler)])
    app.listen(8881)
    print("I'm listening on port 8881")
    tornado.ioloop.IOLoop.current().start()


问:
How to draw an image on another image?
I have a UWP SoftwareBitmap to which I would like to add padding on two sides (as if it's shown in Fit mode) and get the result as a SoftwareBitmap. I assume I need to copy it onto a new empty SoftwareBitmap, but I can't find any way to do that.

答:
How to draw an image on another image?

You could use Win2D library to draw an image with padding. If you used SoftwareBitmap as the source, please try to convert it to file at first and you could refer to this document.

We need to make Win2D CanvasRenderTarget and set it's width as image width + 2 * padding width. Then use CanvasRenderTarget to create DrawingSession and draw your image. For more please refer to the following code.

```<code>// file parameter is the image file
using (var stream = await file.OpenAsync(FileAccessMode.Read))
{   //padding width
    float padding = 30;
    var device = new CanvasDevice();
    var bitmap = await CanvasBitmap.LoadAsync(device, stream);
    var renderer = new CanvasRenderTarget(device,
                                          bitmap.SizeInPixels.Width+ 2*padding,
                                          bitmap.SizeInPixels.Height, bitmap.Dpi);
    using (var ds = renderer.CreateDrawingSession())
    {   // draw image from point xy = point(padding,0)
        ds.DrawImage(bitmap,padding,0);
    }
    stream.Seek(0);
    InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
    await renderer.SaveAsync(randomAccessStream, CanvasBitmapFileFormat.Png);
    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(randomAccessStream);
    var softwareBitmap = await decoder.GetSoftwareBitmapAsync();

}
</code>```

I need to copy it onto a new empty SoftwareBitmap, but I can't find any way to do that.

You could use CopyTo method to copy the current SoftwareBitmap into the provided SoftwareBitmap object.

Title: How to draw an image on another image?

Body:
How to draw an image on another image?

You could use Win2D library to draw an image with padding. If you used SoftwareBitmap as the source, please try to convert it to file at first and you could refer to this document.

We need to make Win2D CanvasRenderTarget and set it's width as image width + 2 * padding width. Then use CanvasRenderTarget to create DrawingSession and draw your image. For more please refer to the following code.

// file parameter is the image file
using (var stream = await file.OpenAsync(FileAccessMode.Read))
{   //padding width
    float padding = 30;
    var device = new CanvasDevice();
    var bitmap = await CanvasBitmap.LoadAsync(device, stream);
    var renderer = new CanvasRenderTarget(device,
                                          bitmap.SizeInPixels.Width+ 2*padding,
                                          bitmap.SizeInPixels.Height, bitmap.Dpi);
    using (var ds = renderer.CreateDrawingSession())
    {   // draw image from point xy = point(padding,0)
        ds.DrawImage(bitmap,padding,0);
    }
    stream.Seek(0);
    InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
    await renderer.SaveAsync(randomAccessStream, CanvasBitmapFileFormat.Png);
    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(randomAccessStream);
    var softwareBitmap = await decoder.GetSoftwareBitmapAsync();

}

I need to copy it onto a new empty SoftwareBitmap, but I can't find any way to do that.

You could use CopyTo method to copy the current SoftwareBitmap into the provided SoftwareBitmap object.