问:
Call related data with populated select from php database
i mange to populate the select by calling data on database
how will i call other data related from the value of the select using database.</p>

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>
</head>
<body>
<?php

$conn = new mysqli('localhost', 'root', 'a', 'emp_table')
or die ('Cannot connect to db');

$result = $conn->query("select * from emp");
echo "<select name='id'>";
while ($row = $result->fetch_assoc()) {
              unset($id, $name);
              $id = $row['id'];
              $name = $row['name'];
              echo '<option value="'.$id.'">'.$name.'</option>';

}
echo "</select>";
?>
</body>
</html>
</code>```

答:
Try this

As per @Nikhil suggested the link
https://www.w3schools.com/xml/ajax_intro.asp

You can achieve this using AJAX. Time to learn the AJAX now.

For connection
If you are working on the localhost the no need to require the password. It should be blank.

I just added the onchange function to the select tag. So whatever the user selects from the dropdown it will call the function getRole and pass the Id to the process page. Process page will return the value related to the ID and display in the span tag.

```<code><?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "emp_table";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
    </head>
    <body>

    <select name="emp_name" id="emp_name"  onchange="getRole(this.value);" >
    <option selected disabled>Select</option>
      <?php
        $result = $conn->query("select * from emp");
        if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
                  $id = $row['id'];
                  $name = $row['name'];
            ?>

        <option value="<?php echo $id;?>"><?php echo $name;?></option>
        <?php }}?>
    </select>

    <span id="emp_details"></span><!--it will display the emp record from process page-->

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <script type="text/javascript">
        function getRole(val){
       var id=$('#emp_name').val();
        $.ajax({
            url:'process.php',
           type:'POST',
           data:'id='+id,
           success:function(data)
           {
            //alert(data);
              $("#emp_details").html(data);
           },

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

Process.php

```<code><?php
if (isset($_POST['id'])) {
   echo $country_id=$conn->real_escape_string(trim($_POST['id']));// here you will get the id of the employee
   /*your more code here*/
}
 ?>
</code>```

Body:
i mange to populate the select by calling data on database
how will i call other data related from the value of the select using database.

<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>

<?php

$conn = new mysqli('localhost', 'root', 'a', 'emp_table')
or die ('Cannot connect to db');

$result = $conn->query("select * from emp");
echo "<select name='id'>";
while ($row = $result->fetch_assoc()) {
              unset($id, $name);
              $id = $row['id'];
              $name = $row['name'];
              echo '<option value="'.$id.'">'.$name.'</option>';

}
echo "</select>";
?>

Body:
Try this

As per @Nikhil suggested the link
https://www.w3schools.com/xml/ajax_intro.asp

You can achieve this using AJAX. Time to learn the AJAX now.

For connection
If you are working on the localhost the no need to require the password. It should be blank.

I just added the onchange function to the select tag. So whatever the user selects from the dropdown it will call the function getRole and pass the Id to the process page. Process page will return the value related to the ID and display in the span tag.

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "emp_table";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
    </head>
    <body>

    <select name="emp_name" id="emp_name"  onchange="getRole(this.value);" >
    <option selected disabled>Select</option>
      <?php
        $result = $conn->query("select * from emp");
        if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
                  $id = $row['id'];
                  $name = $row['name'];
            ?>

        <option value="<?php echo $id;?>"><?php echo $name;?></option>
        <?php }}?>
    </select>

    <span id="emp_details"></span><!--it will display the emp record from process page-->

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <script type="text/javascript">
        function getRole(val){
       var id=$('#emp_name').val();
        $.ajax({
            url:'process.php',
           type:'POST',
           data:'id='+id,
           success:function(data)
           {
            //alert(data);
              $("#emp_details").html(data);
           },

           });
    }
    </script>
    </body>
    </html>

Process.php

<?php
if (isset($_POST['id'])) {
   echo $country_id=$conn->real_escape_string(trim($_POST['id']));// here you will get the id of the employee
   /*your more code here*/
}
 ?>


来源: stackexchange

问:
django UNIQUE constraint failed error
I have fallowing structure of database. I create ProductBidPrice class on view. Add all column has not have any problem but one column which is out_going_price and income_price. When I save the new ProductBidPrice django throw this error

"UNIQUE constraint failed: sales_productbidprice.price_income_id"

. I want use more than one to one realtionship.

I can add and save Django Web Interface. But I can't add in the view.

How can I fix this problem ?

Sorry about my English. I hope explain my problem.

models.py

```<code>    class ProductPriceHistory(BaseModel):
        currency = models.ForeignKey(PriceCurrency)
        price = models.FloatField()
        date = models.DateField()

        class Meta:
            abstract = True

    class ProductIncomePriceHistory(ProductPriceHistory):
        product = models.ForeignKey(Product, related_name="prices_income")

        def __str__(self):
            return "%s %s of %s" % (self.price, self.currency.name, self.product.name)

    class ProductOutgoingPriceHistory(ProductPriceHistory):
        product = models.ForeignKey(Product, related_name="prices_outgoing")

        def __str__(self):
            return "%s %s of %s" % (self.price, self.currency.name, self.product.name)

class AbstractBidDirectSales(BaseModel):
    name = models.CharField(max_length=45)
    sales_date = models.DateField()
    customer = models.ForeignKey(Customer)

    class Meta:
        abstract = True

    class Bid(AbstractBidDirectSales):
        products = models.ManyToManyField(Product, related_name="bids", through="ProductBidPrice")

        def __str__(self):
            return "%s of %s" % (self.name, self.customer.name)

    class DirectSale(AbstractBidDirectSales):
        product = models.ManyToManyField(Product, related_name="directSales",  through="ProductDirectSalesPrice")

        class Meta:
            verbose_name_plural = "DirectSales"

        def __str__(self):
            return "%s of %s" % (self.name, self.customer.name)

    class ProductDirectSalesPrice(BaseModel):
        product = models.ForeignKey(Product)
        directSales = models.ForeignKey(DirectSale)
        price_income = models.OneToOneField(ProductIncomePriceHistory)
        price_outgoing = models.OneToOneField(ProductOutgoingPriceHistory)
        item_number = models.IntegerField()
        piece = models.IntegerField()

        def __str__(self):
            return "%s of %s %s" % (self.product, self.bid.name, self.piece)

    class ProductBidPrice(BaseModel):
        product = models.ForeignKey(Product)
        bid = models.ForeignKey(Bid)
        price_income = models.OneToOneField(ProductIncomePriceHistory)
        price_outgoing = models.OneToOneField(ProductOutgoingPriceHistory)
        item_number = models.IntegerField()
        piece = models.IntegerField()

        def __str__(self):
            return "%s of %s %s" % (self.product, self.bid.name, self.piece)
</code>```

views.py

```<code>@login_required(login_url="/login/")
def add_bid(request):
    if request.method == "POST":
        new_bid = Bid();
        new_bid.name = request.POST["name"];
        new_bid.sales_date = request.POST["date"];
        new_bid.customer_id = request.POST["customerSelection"];
        new_bid.save();
        price = request.POST;
        items = [];
        pieces = [];
        ubb_code = [];
        for q in price:
            if q.startswith("item"):
                items.append(q);
            if q.startswith("piece"):
                pieces.append(q);
            if q.startswith("productSelection"):
                ubb_code.append(q);
        items = sorted(items);
        pieces = sorted(pieces);
        ubb_code = sorted(ubb_code);

        for i in range(len(items)):
            new_bid_product = ProductBidPrice();
            new_bid_product.bid = new_bid;
            new_bid_product.product_id = request.POST[ubb_code[i]];
            new_bid_product.item_number = request.POST[items[i]];
            new_bid_product.piece = request.POST[pieces[i]];
            income_price = ProductIncomePriceHistory.objects.filter(product_id= request.POST[ubb_code[i]]);
            outgoing_price = ProductOutgoingPriceHistory.objects.filter(product_id=request.POST[ubb_code[i]]);
            new_bid_product.price_income_id = income_price[0].id;
            new_bid_product.price_outgoing_id = outgoing_price[0].id;
            new_bid_product.save();

    customers = Customer.objects.all();
    products = Product.objects.all();
    return render(request, "addBid.html", {"customers": customers, "products":products})
</code>```

答:
You have defined this field as a one to one relationship.

```<code>   class ProductBidPrice(BaseModel):
    product = models.ForeignKey(Product)
    bid = models.ForeignKey(Bid)
    price_income = models.OneToOneField(ProductIncomePriceHistory)
</code>```

So only one ProductBidPrice can have one ProductIncomePriceHistory the error is probably raised because you already have a ProductBidPrice with the ProductIncomePriceHistory.id you are trying to use.

I believe you want a many to on relationship, if I am interpreting what you are trying to do correctly.

ContentLicense: CC BY-SA 3.0

Title: django UNIQUE constraint failed error

Body:
I have fallowing structure of database. I create ProductBidPrice class on view. Add all column has not have any problem but one column which is out_going_price and income_price. When I save the new ProductBidPrice django throw this error

"UNIQUE constraint failed: sales_productbidprice.price_income_id"

. I want use more than one to one realtionship.

I can add and save Django Web Interface. But I can't add in the view.

How can I fix this problem ?

Sorry about my English. I hope explain my problem.

models.py

    class ProductPriceHistory(BaseModel):
        currency = models.ForeignKey(PriceCurrency)
        price = models.FloatField()
        date = models.DateField()

        class Meta:
            abstract = True

    class ProductIncomePriceHistory(ProductPriceHistory):
        product = models.ForeignKey(Product, related_name="prices_income")

        def __str__(self):
            return "%s %s of %s" % (self.price, self.currency.name, self.product.name)

    class ProductOutgoingPriceHistory(ProductPriceHistory):
        product = models.ForeignKey(Product, related_name="prices_outgoing")

        def __str__(self):
            return "%s %s of %s" % (self.price, self.currency.name, self.product.name)

class AbstractBidDirectSales(BaseModel):
    name = models.CharField(max_length=45)
    sales_date = models.DateField()
    customer = models.ForeignKey(Customer)

    class Meta:
        abstract = True

    class Bid(AbstractBidDirectSales):
        products = models.ManyToManyField(Product, related_name="bids", through="ProductBidPrice")

        def __str__(self):
            return "%s of %s" % (self.name, self.customer.name)

    class DirectSale(AbstractBidDirectSales):
        product = models.ManyToManyField(Product, related_name="directSales",  through="ProductDirectSalesPrice")

        class Meta:
            verbose_name_plural = "DirectSales"

        def __str__(self):
            return "%s of %s" % (self.name, self.customer.name)

    class ProductDirectSalesPrice(BaseModel):
        product = models.ForeignKey(Product)
        directSales = models.ForeignKey(DirectSale)
        price_income = models.OneToOneField(ProductIncomePriceHistory)
        price_outgoing = models.OneToOneField(ProductOutgoingPriceHistory)
        item_number = models.IntegerField()
        piece = models.IntegerField()

        def __str__(self):
            return "%s of %s %s" % (self.product, self.bid.name, self.piece)

    class ProductBidPrice(BaseModel):
        product = models.ForeignKey(Product)
        bid = models.ForeignKey(Bid)
        price_income = models.OneToOneField(ProductIncomePriceHistory)
        price_outgoing = models.OneToOneField(ProductOutgoingPriceHistory)
        item_number = models.IntegerField()
        piece = models.IntegerField()

        def __str__(self):
            return "%s of %s %s" % (self.product, self.bid.name, self.piece)

views.py

@login_required(login_url="/login/")
def add_bid(request):
    if request.method == "POST":
        new_bid = Bid();
        new_bid.name = request.POST["name"];
        new_bid.sales_date = request.POST["date"];
        new_bid.customer_id = request.POST["customerSelection"];
        new_bid.save();
        price = request.POST;
        items = [];
        pieces = [];
        ubb_code = [];
        for q in price:
            if q.startswith("item"):
                items.append(q);
            if q.startswith("piece"):
                pieces.append(q);
            if q.startswith("productSelection"):
                ubb_code.append(q);
        items = sorted(items);
        pieces = sorted(pieces);
        ubb_code = sorted(ubb_code);

        for i in range(len(items)):
            new_bid_product = ProductBidPrice();
            new_bid_product.bid = new_bid;
            new_bid_product.product_id = request.POST[ubb_code[i]];
            new_bid_product.item_number = request.POST[items[i]];
            new_bid_product.piece = request.POST[pieces[i]];
            income_price = ProductIncomePriceHistory.objects.filter(product_id= request.POST[ubb_code[i]]);
            outgoing_price = ProductOutgoingPriceHistory.objects.filter(product_id=request.POST[ubb_code[i]]);
            new_bid_product.price_income_id = income_price[0].id;
            new_bid_product.price_outgoing_id = outgoing_price[0].id;
            new_bid_product.save();

    customers = Customer.objects.all();
    products = Product.objects.all();
    return render(request, "addBid.html", {"customers": customers, "products":products})

Body:
You have defined this field as a one to one relationship.

   class ProductBidPrice(BaseModel):
    product = models.ForeignKey(Product)
    bid = models.ForeignKey(Bid)
    price_income = models.OneToOneField(ProductIncomePriceHistory)

So only one ProductBidPrice can have one ProductIncomePriceHistory the error is probably raised because you already have a ProductBidPrice with the ProductIncomePriceHistory.id you are trying to use.

I believe you want a many to on relationship, if I am interpreting what you are trying to do correctly.


问:
Rails Console won't run (console error)
I'd like to run rails console command but it throw error everytime I run it.
Here is the error I get :

```<code>Loading development environment (Rails 5.1.4)
D:/RailsInstaller/Ruby2.3.3/lib/ruby/site_ruby/2.3.0/rbreadline.rb:6090:in `delete': invalid byte sequence in UTF-8 (ArgumentErr
or)
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/site_ruby/2.3.0/rbreadline.rb:6090:in `alloc_history_entry'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/site_ruby/2.3.0/rbreadline.rb:6123:in `add_history'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/site_ruby/2.3.0/readline.rb:368:in `<<'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:76:in `block (2 levels) in load_history'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:76:in `each'

        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:76:in `block in load_history'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:75:in `open'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:75:in `load_history'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:65:in `extended'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:21:in `extend'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:21:in `init_save_history'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:45:in `save_history='
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/context.rb:91:in `initialize'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb.rb:426:in `new'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb.rb:426:in `initialize'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb.rb:383:in `new'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb.rb:383:in `start'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/commands/console/console_command.rb:6
2:in `start'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/commands/console/console_command.rb:1
7:in `start'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/commands/console/console_command.rb:9
7:in `perform'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/command.rb:27:in `run'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/invocation.rb:126:in `invoke_command'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor.rb:387:in `dispatch'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/command/base.rb:63:in `perform'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/command.rb:44:in `invoke'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/commands.rb:16:in `<top (required)>'
        from bin/rails:4:in `require'
        from bin/rails:4:in `<main>'
</code>```

I've tried to reinstall/reinstall and clean every version of ruby with no success. I use Ruby 2.3.3 and rails 5.1.4.
Thanks

答:
Since you are on Windows(I'm assuming since you have D:/):

Try installing rb-readline gem in your development group. That's the easiest way for solving readline issues.

There are other solutions as well if that doesn't work.

Title: Rails Console won't run (console error)

Body:
I'd like to run rails console command but it throw error everytime I run it.
Here is the error I get :

Loading development environment (Rails 5.1.4)
D:/RailsInstaller/Ruby2.3.3/lib/ruby/site_ruby/2.3.0/rbreadline.rb:6090:in `delete': invalid byte sequence in UTF-8 (ArgumentErr
or)
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/site_ruby/2.3.0/rbreadline.rb:6090:in `alloc_history_entry'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/site_ruby/2.3.0/rbreadline.rb:6123:in `add_history'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/site_ruby/2.3.0/readline.rb:368:in `<<'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:76:in `block (2 levels) in load_history'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:76:in `each'

        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:76:in `block in load_history'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:75:in `open'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:75:in `load_history'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:65:in `extended'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:21:in `extend'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:21:in `init_save_history'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/ext/save-history.rb:45:in `save_history='
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb/context.rb:91:in `initialize'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb.rb:426:in `new'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb.rb:426:in `initialize'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb.rb:383:in `new'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/2.3.0/irb.rb:383:in `start'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/commands/console/console_command.rb:6
2:in `start'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/commands/console/console_command.rb:1
7:in `start'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/commands/console/console_command.rb:9
7:in `perform'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/command.rb:27:in `run'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/invocation.rb:126:in `invoke_command'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor.rb:387:in `dispatch'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/command/base.rb:63:in `perform'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/command.rb:44:in `invoke'
        from D:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/commands.rb:16:in `<top (required)>'
        from bin/rails:4:in `require'
        from bin/rails:4:in `'

I've tried to reinstall/reinstall and clean every version of ruby with no success. I use Ruby 2.3.3 and rails 5.1.4.
Thanks


问:
Running multiple commands in parallel and exiting cleanly
In this example I have three commands running in parallel.

```<code>sleep 1 && echo 'one' &
sleep 2 && echo 'two'&
sleep 1 && echo 'three'&
sleep 2 && echo 'four' &
wait

echo "done"
</code>```

When I exit / quit the command with a keyboard shortcut the command still seems to be outputting.

```<code>➜  example: ✗ sh ./scripts.sh
three
one
two
four
done
➜  example: ✗ sh ./scripts.sh
^C%➜  example: ✗ one
three
two
four
</code>```

How can I cleanly exit?

答:
By default signals handled by Kernal, but i have seen reference saying all signals except kill can be handled by program also,we can capture CNTRL + C signal using trap like below for instance,

```<code>finish(){
    < code to kill child process goes here >
}
trap finish EXIT

sleep 1 && echo 'one' &
sleep 2 && echo 'two' &
sleep 1 && echo 'three'&
sleep 2 && echo 'four' &

wait
</code>```

for more , stackoverflow or redsymbol.net

Body:
In this example I have three commands running in parallel.

sleep 1 && echo 'one' &
sleep 2 && echo 'two'&
sleep 1 && echo 'three'&
sleep 2 && echo 'four' &
wait

echo "done"

When I exit / quit the command with a keyboard shortcut the command still seems to be outputting.

➜  example: ✗ sh ./scripts.sh
three
one
two
four
done
➜  example: ✗ sh ./scripts.sh
^C%➜  example: ✗ one
three
two
four

How can I cleanly exit?

Body:
By default signals handled by Kernal, but i have seen reference saying all signals except kill can be handled by program also,we can capture CNTRL + C signal using trap like below for instance,

finish(){
    < code to kill child process goes here >
}
trap finish EXIT

sleep 1 && echo 'one' &
sleep 2 && echo 'two' &
sleep 1 && echo 'three'&
sleep 2 && echo 'four' &

wait

for more , stackoverflow or redsymbol.net


问:
ASP.NET webforms listbox - cross-page posting
I'm new to ASP.NET, and I'm having a problem getting a listbox to return the proper data when posting to another page. I have gotten dropdownlists and radio buttons to work. For instance, for dropdownlists, I simply did this:

```<code>Public ReadOnly Property SiteID() As String
    Get
        Return ddlSites.SelectedValue
    End Get
</code>```

Then, on the next page, I successfully returned the value using PreviousPage.SiteID. However, when I try this for a listbox:

```<code>Public ReadOnly Property CustID() As String
    Get
        Return lstLoggedInCustomers.SelectedValue.ToString
    End Get
End Property
</code>```

then call it using PreviousPage, I get an empty string, as SelectedIndex is always returning -1, even though I select an item in the listbox.

答: The SelectedValue is read from the ViewState on postback. But the ViewState is no longer available on the next page. Why don't you save the SelectedValue in Session so you can refer to it on the next page?</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm new to ASP.NET, and I'm having a problem getting a listbox to return the proper data when posting to another page. I have gotten dropdownlists and radio buttons to work. For instance, for dropdownlists, I simply did this:

Public ReadOnly Property SiteID() As String
    Get
        Return ddlSites.SelectedValue
    End Get

Then, on the next page, I successfully returned the value using PreviousPage.SiteID. However, when I try this for a listbox:

Public ReadOnly Property CustID() As String
    Get
        Return lstLoggedInCustomers.SelectedValue.ToString
    End Get
End Property

then call it using PreviousPage, I get an empty string, as SelectedIndex is always returning -1, even though I select an item in the listbox.


问:
Using "Python" in Selenium WebDriver getting this message: object has no attribute
I am using Selenium WebDriver in Python in Pycharm, where I am using a class having 2 test functions.

```<code>class goodsweb(unittest.TestCase):

    def setUp(self):
        driverlocation ="/Users/new/Documents/Learning/Drivers/selenium-2.53.1/py/selenium/webdriver/chromedriver"
        os.environ["webdriver.chrome.driver"] = driverlocation
        self.driver = webdriver.Chrome(driverlocation)

    def test_Test1(self):
        self.EmailEntry = input("Please Enter Email Address: ")
        self.EmailAddress.send_keys(self.EmailEntry)
        self.Password.clear()
        self.password='12345678'
        self.Password.send_keys(self.password)

    def test_Test2(self):
        self.LoginEmail = driver.find_element_by_xpath("//*[@id='sign_form-default']//div[1]/input[@type='email']")
        self.LoginEmail.clear()
        self.LoginEmail.click()
        self.LoginEmail.send_keys(self.EmailEntry)

        self.LoginPassword = driver.find_element_by_xpath("//*[@id='sign_form-default']//div[1]/input[@type='password']")
        self.LoginPassword.clear()
        self.LoginPassword.click()
        self.LoginPassword.send_keys(self.password)
</code>```

Now What I want is get access of EmailEntry and Password of test_Test1 in test_Test2

Whenever I am running the code, I am having this error:

AttributeError: 'goodsweb' object has no attribute 'EmailEntry'

答:
where is your EmailEntry field ?

It can't accessible in goodsweb class. Declare in this class or define as static so you can use in any other classes.

If you want to use one field in other classes or function then you have to define field as static.

For functions the concept is same. You can defined function as static like

```<code>public static void main(){
     // your logic
}
</code>```

For python ::

```<code>class MyClass(object):
    def the_static_method(x):
        print x
    the_static_method = staticmethod(the_static_method)

MyClass.the_static_method(2) # outputs 2
</code>```

Body:
I am using Selenium WebDriver in Python in Pycharm, where I am using a class having 2 test functions.

class goodsweb(unittest.TestCase):

    def setUp(self):
        driverlocation ="/Users/new/Documents/Learning/Drivers/selenium-2.53.1/py/selenium/webdriver/chromedriver"
        os.environ["webdriver.chrome.driver"] = driverlocation
        self.driver = webdriver.Chrome(driverlocation)

    def test_Test1(self):
        self.EmailEntry = input("Please Enter Email Address: ")
        self.EmailAddress.send_keys(self.EmailEntry)
        self.Password.clear()
        self.password='12345678'
        self.Password.send_keys(self.password)

    def test_Test2(self):
        self.LoginEmail = driver.find_element_by_xpath("//*[@id='sign_form-default']//div[1]/input[@type='email']")
        self.LoginEmail.clear()
        self.LoginEmail.click()
        self.LoginEmail.send_keys(self.EmailEntry)

        self.LoginPassword = driver.find_element_by_xpath("//*[@id='sign_form-default']//div[1]/input[@type='password']")
        self.LoginPassword.clear()
        self.LoginPassword.click()
        self.LoginPassword.send_keys(self.password)

Now What I want is get access of EmailEntry and Password of test_Test1 in test_Test2

Whenever I am running the code, I am having this error:

AttributeError: 'goodsweb' object has no attribute 'EmailEntry'

Body:
where is your EmailEntry field ?

It can't accessible in goodsweb class. Declare in this class or define as static so you can use in any other classes.

If you want to use one field in other classes or function then you have to define field as static.

For functions the concept is same. You can defined function as static like

public static void main(){
     // your logic
}

For python ::

class MyClass(object):
    def the_static_method(x):
        print x
    the_static_method = staticmethod(the_static_method)

MyClass.the_static_method(2) # outputs 2


问:
User agent info is not proper when calling from axios call in node js
I have two servers. One is my api server and other one is my rendering server. Both are in node js. When I call any api from my rendering server to my api server using axios and get the req.headers['user-agent'] in my api server then it gives me only axios/0.15.2. But I want the complete user agent info like browser, os, device etc. How do I get those info?

答:
Set a custom header like:

```<code>var config = {
  headers: {'X-My-Custom-Header': 'Header-Value'}
};

axios.get('https://api.github.com/users/codeheaven-io', config);
axios.post('/save', { firstName: 'Marlon' }, config);
</code>```

https://github.com/axios/axios/issues/69

Body:
Set a custom header like:

var config = {
  headers: {'X-My-Custom-Header': 'Header-Value'}
};

axios.get('https://api.github.com/users/codeheaven-io', config);
axios.post('/save', { firstName: 'Marlon' }, config);

https://github.com/axios/axios/issues/69


问:
C# Merge two Lists of the same values
this is my Clients class:

```<code>public class Clients
{
    public string Email { get; set; }
    public string Name { get; set; }

    public Clients(string e, string n)
    {
        Email = e;
        Name = n;
    }
</code>```

I want to make a new list which contains the same clients from List A and List B .
For example:
List A - John, Jonathan, James ....
List B - Martha, Jane, Jonathan ....
Unsubscribers - Jonathan

```<code>    public static List<Clients> SameClients(List<Clients> A, List<Clients> B)
    {
        List<Clients> Unsubscribers = new List<Clients>();
        Unsubscribers = A.Intersect(B).ToList();
        return Unsubscribers;
    }
</code>```

However for some reasons I get empty list and I have no idea what's wrong.

答:
Intersect uses GetHashCode and Equals by default, but you haven't overriden it, so Object.Equals is used which just compares references. Since all your client-instances are initialized with new they are separate instances even if they have equal values. That's why Intersect "thinks" that there are no common clients.

So you have several options.

implement a custom IEqualityComparer<Clients> and pass that to Intersect(or many other LINQ methods). This has the advantage that you could implement different comparer for different requirements and you don't need to modify the original class

let Clients override Equals and GetHashCode and /or

let Clients implement IEquatable<Clients>

For example(showing the last two because other answer showed already IEqualityComparer<T>):

```<code>public class Clients : IEquatable<Clients>
{
    public string Email { get; set; }
    public string Name { get; set; }

    public Clients(string e, string n)
    {
        Email = e;
        Name = n;
    }

    public override bool Equals(object obj)
    {
        return obj is Clients && this.Equals((Clients)obj);
    }

    public bool Equals(Clients other)
    {
        return Email == other?.Email == true
            && Name == other?.Name == true;
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 17;
            hash = hash * 23 + (Email?.GetHashCode() ?? 0);
            hash = hash * 23 + (Name?.GetHashCode() ?? 0);
            return hash;
        }
    }
}
</code>```

Worth reading:

Differences between IEquatable<T>, IEqualityComparer<T>, and overriding .Equals() when using LINQ on a custom object collection?

Title: C# Merge two Lists of the same values

Body:
this is my Clients class:

public class Clients
{
    public string Email { get; set; }
    public string Name { get; set; }

    public Clients(string e, string n)
    {
        Email = e;
        Name = n;
    }

I want to make a new list which contains the same clients from List A and List B .
For example:
List A - John, Jonathan, James ....
List B - Martha, Jane, Jonathan ....
Unsubscribers - Jonathan

    public static List<Clients> SameClients(List<Clients> A, List<Clients> B)
    {
        List<Clients> Unsubscribers = new List<Clients>();
        Unsubscribers = A.Intersect(B).ToList();
        return Unsubscribers;
    }

However for some reasons I get empty list and I have no idea what's wrong.

Body:
Intersect uses GetHashCode and Equals by default, but you haven't overriden it, so Object.Equals is used which just compares references. Since all your client-instances are initialized with new they are separate instances even if they have equal values. That's why Intersect "thinks" that there are no common clients.

So you have several options.

implement a custom IEqualityComparer<Clients> and pass that to Intersect(or many other LINQ methods). This has the advantage that you could implement different comparer for different requirements and you don't need to modify the original class

let Clients override Equals and GetHashCode and /or

let Clients implement IEquatable<Clients>

For example(showing the last two because other answer showed already IEqualityComparer<T>):

public class Clients : IEquatable<Clients>
{
    public string Email { get; set; }
    public string Name { get; set; }

    public Clients(string e, string n)
    {
        Email = e;
        Name = n;
    }

    public override bool Equals(object obj)
    {
        return obj is Clients && this.Equals((Clients)obj);
    }

    public bool Equals(Clients other)
    {
        return Email == other?.Email == true
            && Name == other?.Name == true;
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 17;
            hash = hash * 23 + (Email?.GetHashCode() ?? 0);
            hash = hash * 23 + (Name?.GetHashCode() ?? 0);
            return hash;
        }
    }
}

Worth reading:

Differences between IEquatable<T>, IEqualityComparer<T>, and overriding .Equals() when using LINQ on a custom object collection?


问:
Sum of specific elements of a list based on indexes from another list in python

I am trying to find the durations of all the notes with the same name in a music piece (from .xml), in python. I have 3 lists:

```<code>scales = ['A', 'B', 'C'] #scales names
notesAll = ['B', 'A', 'C', 'A', 'C', 'C']  #note names of the piece
durationsAll = [1, 1.5, 1.5, 1, 1, 2]  #duration of each note from notesAll list
</code>```

I want to sum all the durations from durationsAll list for all the notes with the same name. For example for all the 'A's from notesAll list, which equals to scales[0], I want something like: durationsAll[1] + durationsAll[3]= 1.5 + 1 = 2.5. I need a better solution than my attempt:

```<code>for sc in scales:
  for ntPosition, nt in enumerate(notesAll):
    dtOfEach = 0
    for dtPosition, dt in enumerate(durationsAll):
      if sc == nt:
        dtPosotion = ntPosition  #I guess here is the problem
        dtOfEach = dtOfEach + dt
</code>```

The result I want would be: dtOfEach: 2.5  1  4.5

答:
You could do an indirect sort and then group using groupby

```<code>from itertools import groupby

scales = ['A', 'B', 'C'] #scales names
notesAll = ['B', 'A', 'C', 'A', 'C', 'C']  #note names of the piece
durationsAll = [1, 1.5, 1.5, 1, 1, 2]  #duration of each note from notesAll list

# do indirect sort
idx = sorted(range(len(notesAll)), key=notesAll.__getitem__)
# group and sum
result = {k: sum(map(durationsAll.__getitem__, grp))
          for k, grp in groupby(idx, notesAll.__getitem__)}

# {'A': 2.5, 'B': 1, 'C': 4.5}
</code>```

Body:
I am trying to find the durations of all the notes with the same name in a music piece (from .xml), in python. I have 3 lists:

scales = ['A', 'B', 'C'] #scales names
notesAll = ['B', 'A', 'C', 'A', 'C', 'C']  #note names of the piece
durationsAll = [1, 1.5, 1.5, 1, 1, 2]  #duration of each note from notesAll list

I want to sum all the durations from durationsAll list for all the notes with the same name. For example for all the 'A's from notesAll list, which equals to scales[0], I want something like: durationsAll[1] + durationsAll[3]= 1.5 + 1 = 2.5. I need a better solution than my attempt:

for sc in scales:
  for ntPosition, nt in enumerate(notesAll):
    dtOfEach = 0
    for dtPosition, dt in enumerate(durationsAll):
      if sc == nt:
        dtPosotion = ntPosition  #I guess here is the problem
        dtOfEach = dtOfEach + dt

The result I want would be: dtOfEach: 2.5  1  4.5

Body:
You could do an indirect sort and then group using groupby

from itertools import groupby

scales = ['A', 'B', 'C'] #scales names
notesAll = ['B', 'A', 'C', 'A', 'C', 'C']  #note names of the piece
durationsAll = [1, 1.5, 1.5, 1, 1, 2]  #duration of each note from notesAll list

# do indirect sort
idx = sorted(range(len(notesAll)), key=notesAll.__getitem__)
# group and sum
result = {k: sum(map(durationsAll.__getitem__, grp))
          for k, grp in groupby(idx, notesAll.__getitem__)}

# {'A': 2.5, 'B': 1, 'C': 4.5}


问:
How to render partial view using url
I'm using ASP.NET MVC 4 and have a prepared url in a view like this:

```<code>var sectoionUrl = Url.Action("DisplayArticleSection", new { id = sectionId });
</code>```

Is there any helper to render a partial view using prepared sectionUrl instead of creating it again via helper:

```<code>@Html.Action("DisplayArticleSection", new { id = sectionId })
</code>```

?

Something like this pseudocode:

```<code>@Html.RenderUrl(sectionUrl)
</code>```

答:
Custom HtmlHelper:

```<code>public static class RenderUrlHelper
{
    public static void RenderUrl(this HtmlHelper helper, string originUrl)
    {
        var originRequest = helper.ViewContext.RequestContext.HttpContext.Request;

        if (!Uri.IsWellFormedUriString(originUrl, UriKind.Absolute))
        {
            originUrl = new Uri(originRequest.Url, originUrl).AbsoluteUri;
        }

        int queryIdx = originUrl.IndexOf('?');
        string queryString = null;
        string url = originUrl;

        if (queryIdx != -1)
        {
            url = originUrl.Substring(0, queryIdx);
            queryString = originUrl.Substring(queryIdx + 1);
        }

        // Extract the data and render the action.
        var request = new HttpRequest(null, url, queryString);
        var response = new HttpResponse(new StringWriter());
        var httpContext = new HttpContext(request, response);
        var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
        var values = routeData.Values;
        string controllerName = values["controller"] as string;
        string actionName = values["action"] as string;
        var valuesCollection = HttpUtility.ParseQueryString(queryString);
        RouteValueDictionary routeValues = new RouteValueDictionary(valuesCollection.AllKeys.ToDictionary(k => k, k => (object)valuesCollection[k]));
        helper.RenderAction(actionName, controllerName, routeValues);
    }
}
</code>```

Some code to test custom HtmlHelper:

TestController:

```<code>public class TestController : Controller
{
    public ActionResult Index(string title, int number)
    {
        TestModel model = new TestModel { Title = title, Number = number };
        return PartialView(model);
    }
}
</code>```

TestController Index view:

```<code>@model TestModel

<h1>Title: @Model.Title</h1>
<h2>Number: @Model.Number</h2>
</code>```

TestModel:

```<code>public class TestModel
{
    public string Title { get; set; }
    public int Number { get; set; }
}
</code>```

Usage in any view:

```<code>@{
    var actionUrl = Url.Action("Index", "Test", new { number = 123, title = "Hello Url Renderer" });
    Html.RenderUrl(actionUrl);
}
</code>```

Title: How to render partial view using url

Body:
I'm using ASP.NET MVC 4 and have a prepared url in a view like this:

var sectoionUrl = Url.Action("DisplayArticleSection", new { id = sectionId });

Is there any helper to render a partial view using prepared sectionUrl instead of creating it again via helper:

@Html.Action("DisplayArticleSection", new { id = sectionId })

?

Something like this pseudocode:

@Html.RenderUrl(sectionUrl)

Body:
Custom HtmlHelper:

public static class RenderUrlHelper
{
    public static void RenderUrl(this HtmlHelper helper, string originUrl)
    {
        var originRequest = helper.ViewContext.RequestContext.HttpContext.Request;

        if (!Uri.IsWellFormedUriString(originUrl, UriKind.Absolute))
        {
            originUrl = new Uri(originRequest.Url, originUrl).AbsoluteUri;
        }

        int queryIdx = originUrl.IndexOf('?');
        string queryString = null;
        string url = originUrl;

        if (queryIdx != -1)
        {
            url = originUrl.Substring(0, queryIdx);
            queryString = originUrl.Substring(queryIdx + 1);
        }

        // Extract the data and render the action.
        var request = new HttpRequest(null, url, queryString);
        var response = new HttpResponse(new StringWriter());
        var httpContext = new HttpContext(request, response);
        var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
        var values = routeData.Values;
        string controllerName = values["controller"] as string;
        string actionName = values["action"] as string;
        var valuesCollection = HttpUtility.ParseQueryString(queryString);
        RouteValueDictionary routeValues = new RouteValueDictionary(valuesCollection.AllKeys.ToDictionary(k => k, k => (object)valuesCollection[k]));
        helper.RenderAction(actionName, controllerName, routeValues);
    }
}

Some code to test custom HtmlHelper:

TestController:

public class TestController : Controller
{
    public ActionResult Index(string title, int number)
    {
        TestModel model = new TestModel { Title = title, Number = number };
        return PartialView(model);
    }
}

TestController Index view:

@model TestModel

<h1>Title: @Model.Title</h1>
<h2>Number: @Model.Number</h2>

TestModel:

public class TestModel
{
    public string Title { get; set; }
    public int Number { get; set; }
}

Usage in any view:

@{
    var actionUrl = Url.Action("Index", "Test", new { number = 123, title = "Hello Url Renderer" });
    Html.RenderUrl(actionUrl);
}


问:
Expo: Change default IOS simulator
I am new in expo and react-native
Whenever i run the app from IOS simulator (inside expo) it always boots up the IphoneX. If i need to change the simulator,I have to open it through Xcode, is there any way we can change the default simulator ?

答:
Currently there is no way of changing the simulator from Expo. Expo just uses the last opened simulator in Xcode.

If that doesn't work, try this (updated here from my comment) :

When the simulator is open click on Hardware>Device> Select the other iphone.

Now both will be open. Next exit the simulator from the dock.

Now try and open your project in the ios simulator from expo. It should open in the Simulator you selected from the hardware menu.

Title: Expo: Change default IOS simulator


答:
Should the first sum be 2.5? If so something, like the code at the end of this message should work. I think you basically had it with using a for loop and then enumerate but I wasn't sure what the second enumerate was for.

Also you have a line that reads:

```<code>dtPosotion = ntPosition  #I guess here is the problem
</code>```

Is dtPosotion a typo? Or are you trying to set dtPosition = ntPosition. If so I don't think that's possible because dtPosition and ntPosition are set by your enumerate loops.

```<code>scales = ['A', 'B', 'C'] #scales names
notesAll = ['B', 'A', 'C', 'A', 'C', 'C']  #notes names of the piece
durationsAll = [1, 1.5, 1.5, 1, 1, 2]  #duration of each note from notesAll list
sums = [0,0,0]

for s in scales:
    print "Scale letter:" + str(s)
    for i,j in enumerate(notesAll):
        if j == s:
            sums[scales.index(s)] +=durationsAll[i]

print sums
</code>```

Title: Sum of specific elements of a list based on indexes from another list in python

Body:
Should the first sum be 2.5? If so something, like the code at the end of this message should work. I think you basically had it with using a for loop and then enumerate but I wasn't sure what the second enumerate was for.

Also you have a line that reads:

dtPosotion = ntPosition  #I guess here is the problem

Is dtPosotion a typo? Or are you trying to set dtPosition = ntPosition. If so I don't think that's possible because dtPosition and ntPosition are set by your enumerate loops.

scales = ['A', 'B', 'C'] #scales names
notesAll = ['B', 'A', 'C', 'A', 'C', 'C']  #notes names of the piece
durationsAll = [1, 1.5, 1.5, 1, 1, 2]  #duration of each note from notesAll list
sums = [0,0,0]

for s in scales:
    print "Scale letter:" + str(s)
    for i,j in enumerate(notesAll):
        if j == s:
            sums[scales.index(s)] +=durationsAll[i]

print sums


问:
Multiple Jobs Deployment in Visual Studio Team Services
I have a VS solution with multiple projects, each project is an independent WebJob which I am hosting in a Single AppServices. I am trying to automate this to Continuous deployment.What would be the best strategy to deploy only job in the solution which is changed? Is there a way to find out the project which is changed as part of the merge to CI? We are using git and this solution is in a single repository. We are using azure-webjobsdk for the projects.</p>

答:
You can follow below steps to deploy the only changed webjob:

Assume your file structure as below:

```<code>Git root
   |___WebJob1
          |___WebJob1.sln
          |___webJob1
                 |___WebJob1.csproj
          |___WebJob2
                 |___WebJob2.csproj
          |___ …
          |___WebJobn
                 |___WebJobn.csproj
</code>```

1. Add a variable (such as buildporj with default value none) to record the changed webJob project package.

2. Add NuGet restore task for the WebJob1/WebJob1.sln.

3. Add Visual studio Build task with the MSBuild arguments:

```<code>/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:SkipInvalidConfigurations=true /p:PackageLocation="$(Build.BinariesDirectory)\\"
</code>```

4. Add PowerShell Task to detect which WebJob project changed and copy the package from $(Build.BinariesDirectory) to $(Build.ArtifactStagingDirectory) by the script as below:

```<code>$files=$(git diff HEAD HEAD~ --name-only)
echo "changed files: $files"
for ($i=0;$i -lt $files.Length; $i++)
{
  $file=$files[$i] -split '/'
  $files[$i]=$file[1]
}
$uni=$files | Get-Unique

$uni=@($uni | Where-Object {$_ -notmatch ".sln"})
echo "You changed the project (if more than one projects were changed, only deploy the first one): $uni"
$proj=$uni[0]+".zip"
Write-Host "##vso[task.setvariable variable=buildproj;]$proj"
Copy-Item $(Build.BinariesDirectory)\$proj $(Build.ArtifactStagingDirectory)
</code>```

Add Azure App Service Deploy task by specifing the Package or folder option as $(Build.ArtifactStagingDirectory)\**\$(buildproj).

Body:
You can follow below steps to deploy the only changed webjob:

Assume your file structure as below:

Git root
   |___WebJob1
          |___WebJob1.sln
          |___webJob1
                 |___WebJob1.csproj
          |___WebJob2
                 |___WebJob2.csproj
          |___ …
          |___WebJobn
                 |___WebJobn.csproj

1. Add a variable (such as buildporj with default value none) to record the changed webJob project package.

2. Add NuGet restore task for the WebJob1/WebJob1.sln.

3. Add Visual studio Build task with the MSBuild arguments:

/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:SkipInvalidConfigurations=true /p:PackageLocation="$(Build.BinariesDirectory)\\"

4. Add PowerShell Task to detect which WebJob project changed and copy the package from $(Build.BinariesDirectory) to $(Build.ArtifactStagingDirectory) by the script as below:

$files=$(git diff HEAD HEAD~ --name-only)
echo "changed files: $files"
for ($i=0;$i -lt $files.Length; $i++)
{
  $file=$files[$i] -split '/'
  $files[$i]=$file[1]
}
$uni=$files | Get-Unique

$uni=@($uni | Where-Object {$_ -notmatch ".sln"})
echo "You changed the project (if more than one projects were changed, only deploy the first one): $uni"
$proj=$uni[0]+".zip"
Write-Host "##vso[task.setvariable variable=buildproj;]$proj"
Copy-Item $(Build.BinariesDirectory)\$proj $(Build.ArtifactStagingDirectory)

Add Azure App Service Deploy task by specifing the Package or folder option as $(Build.ArtifactStagingDirectory)\**\$(buildproj).


问:
compiler failure to resolve Implicit types with bounds (sometimes)
Edit:

Last revision was deemed unhelpful as it did not contain necessary information that help narrow down my issue. hence the need to also include the AST.

Below is a library in its entirety that allows parsing and writing of play-json's json based on user defined schema; Similar to what Scala's slick offers for database columns to some extent:

import scala.language.higherKinds
import play.api.libs.functional.syntax._
import play.api.libs.json._

import scala.language.{higherKinds, implicitConversions}

type PathNodes = List[PathNode]

sealed trait Field[A] {

  def pathNodes: PathNodes

  def jsPath: JsPath = JsPath(pathNodes)

  def relativePath: JsPath = JsPath(List(pathNodes.last))

  def format: Format[A]

  def nestedFormatter(path: JsPath): OFormat[A]

  def nestedFormat: OFormat[A] = nestedFormatter(relativePath)
}

case class PlainField[A: Format](prefix: PathNodes) extends Field[A] {

  override def pathNodes: PathNodes = prefix

  def format: Format[A] = implicitly[Format[A]]

  override def nestedFormatter(path: JsPath): OFormat[A] = path.format(format)
}

abstract class JsonSchema[T](val _prefix: PathNodes) extends Field[T] with SchemaExtensionMethods {

  override def pathNodes: PathNodes = _prefix

  def format: OFormat[T]

  protected def plain[A: Format](name: String): PlainField[A] = PlainField[A](_prefix :+ KeyPathNode(name))

  protected def nested[N](name: String, factory: PathNodes => N): N = factory(_prefix :+ KeyPathNode(name))

  protected def nested[B, G <: JsonSchema[B]](name: String)(implicit sm: HasJsonSchema[B, G]): G = sm.apply(_prefix :+ KeyPathNode(name))

  override def nestedFormatter(path: JsPath): OFormat[T] = path.format(format)
}

case class Optional[F, A](field: F)(implicit ev: F <:< Field[A]) extends Field[Option[A]] {

  override def pathNodes: PathNodes = field.pathNodes

  override def format: Format[Option[A]] = {
    implicit val writes: Writes[Option[A]] = JsPath.writeNullable(field.format)
    implicit val reads: Reads[Option[A]] = JsPath.readNullable(field.format)
    implicitly[Format[Option[A]]]
  }

  def map[G, B](f: F => G)(implicit ev: G <:< Field[B]): Optional[G, B] = new Optional[G, B](f(field))

  def flatMap[G <: Field[B], B](f: F => Optional[G, B]): Optional[G, B] = f(field)

  override def nestedFormatter(path: JsPath): OFormat[Option[A]] = path.formatNullable(field.format)
}

case class Collection[F, A](field: F)(implicit ev: F <:< Field[A], repath: Repath[F]) extends Field[Seq[A]] {
  override def pathNodes: PathNodes = field.pathNodes

  override def format: Format[Seq[A]] = {
    implicit val writes: Writes[Seq[A]] = Writes.seq(field.format)
    implicit val reads: Reads[Seq[A]] = Reads.seq(field.format)
    implicitly[Format[Seq[A]]]
  }

  def apply(idx: Int): F = implicitly[Repath[F]].apply(field, IdxPathNode(idx))

  override def nestedFormatter(path: JsPath): OFormat[Seq[A]] = path.format(format)
}

class FormatExtensionMethods[T](val arg: T) {
  def <>[A, B, Fun](apply: Fun, unapply: B => Option[A])(implicit jss: JsonShape[A, B, T, Fun]): OFormat[B] = jss.format(arg, apply, unapply andThen (_.get))
}

class FieldExtensionMethods[F](val field: F) {
  def optional[A](implicit ev: F <:< Field[A]): Optional[F, A] = new Optional[F, A](field)

  def sequence[A](implicit ev: F <:< Field[A], repath: Repath[F]): Collection[F, A] = new Collection[F, A](field)
}

trait SchemaExtensionMethods {
  implicit def formatExtensionMethods[M](t: M): FormatExtensionMethods[M] = new FormatExtensionMethods[M](t)

  implicit def fieldExtensionMethods[M, A](t: M): FieldExtensionMethods[M] = new FieldExtensionMethods[M](t)
}

trait Repath[F] {
  def apply(f: F, node: PathNode): F
}

object Repath {
  implicit def plain[T]: Repath[PlainField[T]] = new Repath[PlainField[T]] {
    override def apply(t: PlainField[T], node: PathNode): PlainField[T] =
      PlainField[T](t.pathNodes :+ node)(t.format)
  }

  implicit def schema[S <: JsonSchema[_]](implicit sm: HasJsonSchema[_, S]): Repath[S] = new Repath[S] {
    override def apply(t: S, node: PathNode): S =
      sm.apply(t.pathNodes :+ node)
  }

  implicit def option[F <: Field[T] : Repath, T]: Repath[Optional[F, T]] = new Repath[Optional[F, T]] {
    override def apply(t: Optional[F, T], node: PathNode): Optional[F, T] =
      new Optional[F, T](implicitly[Repath[F]].apply(t.field, node))
  }

  implicit def sequence[F <: Field[T] : Repath, T]: Repath[Collection[F, T]] = new Repath[Collection[F, T]] {
    override def apply(t: Collection[F, T], node: PathNode): Collection[F, T] =
      new Collection[F, T](implicitly[Repath[F]].apply(t.field, node))
  }
}

trait JsonShape[A, B, -T, Func] {
  def format(t: T, apply: Func, unapply: B => A): OFormat[B]
}

object JsonShape {
  type F[T] = Field[T]

  implicit def cc1[A, B]: JsonShape[A, B, F[A], (A) => B] = (t: F[A], apply: (A) => B, unapply: B => A) => {
    val name = t.pathNodes.last.asInstanceOf[KeyPathNode].key
    OFormat[B](
      Reads[B](jsv => (jsv \ name).validate[A](t.format).map(apply)),
      OWrites[B](b => JsObject(Map(name -> Json.toJson(unapply(b))(t.format))))
    )
  }

  implicit def cc2[T1, T2, B]: JsonShape[(T1, T2), B, (F[T1], F[T2]), (T1, T2) => B] = (t: (F[T1], F[T2]), apply: (T1, T2) => B, unapply: B => (T1, T2)) => {
    (
      t._1.nestedFormat and
        t._2.nestedFormat
      ) (apply, unapply)
  }

  implicit def cc3[T1, T2, T3, B]: JsonShape[(T1, T2, T3), B, (F[T1], F[T2], F[T3]), (T1, T2, T3) => B] = (t: (F[T1], F[T2], F[T3]), apply: (T1, T2, T3) => B, unapply: B => (T1, T2, T3)) => {
    (
      t._1.nestedFormat and
        t._2.nestedFormat and
        t._3.nestedFormat
      ) (apply, unapply)
  }

  //this goes up to 22

}

abstract class HasJsonSchema[T, +S <: JsonSchema[T]](val apply: PathNodes => S) extends OFormat[T] {
  val root: S = apply(Nil)

  def format: OFormat[T] = root.format

  def writes(o: T): JsObject = root.format.writes(o)

  def reads(json: JsValue): JsResult[T] = root.format.reads(json)
}
```

<p>Now let's write a small piece of client code that reproduce the issue: </p>

<pre class="lang-scala prettyprint-override"><code>case class MessageSchema(prefix: PathNodes) extends JsonSchema[Message](prefix) {

  def underlying = plain[String]("underlying")
  //def underlying = plain[String]("underlying").optional if I wanted the field to be Option[String]
  //def underlying = plain[String]("underlying").sequence if I wanted the field to be Seq[String]
  override def format = underlying <> (Message.apply _, Message.unapply)

}

case class Message(underlying: String)

object Message {

  implicit object sm extends HasJsonSchema[Message, MessageSchema](MessageSchema.apply)

}

case class LanguageTaggedSchema[T, S <: JsonSchema[T]](prefix: PathNodes)(implicit evT: HasJsonSchema[T, S]) extends JsonSchema[LanguageTagged[T]](prefix) {
  def lang = plain[String]("lang")

  def data: S = nested("data")(evT)

  def format = (lang, data) <> (LanguageTagged.apply[T] _, LanguageTagged.unapply[T])
}

case class LanguageTagged[T](lang: String, data: T)

object LanguageTagged {

  implicit def schemaMapper[T, S <: JsonSchema[T]](implicit ev: HasJsonSchema[T, S]): HasJsonSchema[LanguageTagged[T], LanguageTaggedSchema[T, S]] =
    new HasJsonSchema[LanguageTagged[T], LanguageTaggedSchema[T, S]](LanguageTaggedSchema.apply[T, S]) {}
}

def toJson[T, S <: JsonSchema[T]](a: T)(implicit ev: HasJsonSchema[T, S]): JsValue = Json.toJson(a)(ev.format)

toJson(Message("hi")) //Ok!
toJson(LanguageTagged("en", Message("hi"))) //Ok!
//or simply write
Json.toJson(LanguageTagged("en", Message("hi")))

//and if i wanted to traverse a json path i would do:
val schema = implicitly[HasJsonSchema[LanguageTagged[Message],LanguageTaggedSchema[Message,MessageSchema]]].root
schema.data.underlying.jsPath
//prints: res2: play.api.libs.json.JsPath = /data/underlying

//Now to where the problem starts:

def getSchema[T, S <: JsonSchema[T]](a: T)(implicit ev: HasJsonSchema[T, S]): S = ev.root

getSchema(Message("hi")) //Ok!
getSchema(LanguageTagged("en", Message("hi"))) //Not Ok but why?
//Error:(211, 11) could not find implicit value for
//parameter ev: A$A6.this.HasJsonSchema[A$A6.this.LanguageTagged[A$A6.this.Message],S]
//getSchema(LanguageTagged("en", Message("hi")));//
//^
</code>```

I have a huge suspicion that the compiler runs into issues because of the bounded type of S inHasJsonSchema[T, S <: JsonSchema[T]] when infering the implicit type S. and so far only in that specific situation as shown on the last line of all the code. as a dubugging attempt I created a similar situation and realized that if the type S was not bounded I wouldn't have this issue. Any sort of solution that refactors the code such that it doesn't depend on bounded types or one that simply solves the implicit resolution is appreciated

答:
What You're trying to achieve cannot be done with subtyping. You should use type-classes instead, a more in-depth explanation:

http://danielwestheide.com/blog/2013/02/06/the-neophytes-guide-to-scala-part-12-type-classes.html

Body:
Edit:

Last revision was deemed unhelpful as it did not contain necessary information that help narrow down my issue. hence the need to also include the AST.

Below is a library in its entirety that allows parsing and writing of play-json's json based on user defined schema; Similar to what Scala's slick offers for database columns to some extent:

import scala.language.higherKinds
import play.api.libs.functional.syntax._
import play.api.libs.json._

import scala.language.{higherKinds, implicitConversions}

type PathNodes = List[PathNode]

sealed trait Field[A] {

  def pathNodes: PathNodes

  def jsPath: JsPath = JsPath(pathNodes)

  def relativePath: JsPath = JsPath(List(pathNodes.last))

  def format: Format[A]

  def nestedFormatter(path: JsPath): OFormat[A]

  def nestedFormat: OFormat[A] = nestedFormatter(relativePath)
}

case class PlainField[A: Format](prefix: PathNodes) extends Field[A] {

  override def pathNodes: PathNodes = prefix

  def format: Format[A] = implicitly[Format[A]]

  override def nestedFormatter(path: JsPath): OFormat[A] = path.format(format)
}

abstract class JsonSchema[T](val _prefix: PathNodes) extends Field[T] with SchemaExtensionMethods {

  override def pathNodes: PathNodes = _prefix

  def format: OFormat[T]

  protected def plain[A: Format](name: String): PlainField[A] = PlainField[A](_prefix :+ KeyPathNode(name))

  protected def nested[N](name: String, factory: PathNodes => N): N = factory(_prefix :+ KeyPathNode(name))

  protected def nested[B, G <: JsonSchema[B]](name: String)(implicit sm: HasJsonSchema[B, G]): G = sm.apply(_prefix :+ KeyPathNode(name))

  override def nestedFormatter(path: JsPath): OFormat[T] = path.format(format)
}

case class Optional[F, A](field: F)(implicit ev: F <:< Field[A]) extends Field[Option[A]] {

  override def pathNodes: PathNodes = field.pathNodes

  override def format: Format[Option[A]] = {
    implicit val writes: Writes[Option[A]] = JsPath.writeNullable(field.format)
    implicit val reads: Reads[Option[A]] = JsPath.readNullable(field.format)
    implicitly[Format[Option[A]]]
  }

  def map[G, B](f: F => G)(implicit ev: G <:< Field[B]): Optional[G, B] = new Optional[G, B](f(field))

  def flatMap[G <: Field[B], B](f: F => Optional[G, B]): Optional[G, B] = f(field)

  override def nestedFormatter(path: JsPath): OFormat[Option[A]] = path.formatNullable(field.format)
}

case class Collection[F, A](field: F)(implicit ev: F <:< Field[A], repath: Repath[F]) extends Field[Seq[A]] {
  override def pathNodes: PathNodes = field.pathNodes

  override def format: Format[Seq[A]] = {
    implicit val writes: Writes[Seq[A]] = Writes.seq(field.format)
    implicit val reads: Reads[Seq[A]] = Reads.seq(field.format)
    implicitly[Format[Seq[A]]]
  }

  def apply(idx: Int): F = implicitly[Repath[F]].apply(field, IdxPathNode(idx))

  override def nestedFormatter(path: JsPath): OFormat[Seq[A]] = path.format(format)
}

class FormatExtensionMethods[T](val arg: T) {
  def <>[A, B, Fun](apply: Fun, unapply: B => Option[A])(implicit jss: JsonShape[A, B, T, Fun]): OFormat[B] = jss.format(arg, apply, unapply andThen (_.get))
}

class FieldExtensionMethods[F](val field: F) {
  def optional[A](implicit ev: F <:< Field[A]): Optional[F, A] = new Optional[F, A](field)

  def sequence[A](implicit ev: F <:< Field[A], repath: Repath[F]): Collection[F, A] = new Collection[F, A](field)
}

trait SchemaExtensionMethods {
  implicit def formatExtensionMethods[M](t: M): FormatExtensionMethods[M] = new FormatExtensionMethods[M](t)

  implicit def fieldExtensionMethods[M, A](t: M): FieldExtensionMethods[M] = new FieldExtensionMethods[M](t)
}

trait Repath[F] {
  def apply(f: F, node: PathNode): F
}

object Repath {
  implicit def plain[T]: Repath[PlainField[T]] = new Repath[PlainField[T]] {
    override def apply(t: PlainField[T], node: PathNode): PlainField[T] =
      PlainField[T](t.pathNodes :+ node)(t.format)
  }

  implicit def schema[S <: JsonSchema[_]](implicit sm: HasJsonSchema[_, S]): Repath[S] = new Repath[S] {
    override def apply(t: S, node: PathNode): S =
      sm.apply(t.pathNodes :+ node)
  }

  implicit def option[F <: Field[T] : Repath, T]: Repath[Optional[F, T]] = new Repath[Optional[F, T]] {
    override def apply(t: Optional[F, T], node: PathNode): Optional[F, T] =
      new Optional[F, T](implicitly[Repath[F]].apply(t.field, node))
  }

  implicit def sequence[F <: Field[T] : Repath, T]: Repath[Collection[F, T]] = new Repath[Collection[F, T]] {
    override def apply(t: Collection[F, T], node: PathNode): Collection[F, T] =
      new Collection[F, T](implicitly[Repath[F]].apply(t.field, node))
  }
}

trait JsonShape[A, B, -T, Func] {
  def format(t: T, apply: Func, unapply: B => A): OFormat[B]
}

object JsonShape {
  type F[T] = Field[T]

  implicit def cc1[A, B]: JsonShape[A, B, F[A], (A) => B] = (t: F[A], apply: (A) => B, unapply: B => A) => {
    val name = t.pathNodes.last.asInstanceOf[KeyPathNode].key
    OFormat[B](
      Reads[B](jsv => (jsv \ name).validate[A](t.format).map(apply)),
      OWrites[B](b => JsObject(Map(name -> Json.toJson(unapply(b))(t.format))))
    )
  }

  implicit def cc2[T1, T2, B]: JsonShape[(T1, T2), B, (F[T1], F[T2]), (T1, T2) => B] = (t: (F[T1], F[T2]), apply: (T1, T2) => B, unapply: B => (T1, T2)) => {
    (
      t._1.nestedFormat and
        t._2.nestedFormat
      ) (apply, unapply)
  }

  implicit def cc3[T1, T2, T3, B]: JsonShape[(T1, T2, T3), B, (F[T1], F[T2], F[T3]), (T1, T2, T3) => B] = (t: (F[T1], F[T2], F[T3]), apply: (T1, T2, T3) => B, unapply: B => (T1, T2, T3)) => {
    (
      t._1.nestedFormat and
        t._2.nestedFormat and
        t._3.nestedFormat
      ) (apply, unapply)
  }

  //this goes up to 22

}

abstract class HasJsonSchema[T, +S <: JsonSchema[T]](val apply: PathNodes => S) extends OFormat[T] {
  val root: S = apply(Nil)

  def format: OFormat[T] = root.format

  def writes(o: T): JsObject = root.format.writes(o)

  def reads(json: JsValue): JsResult[T] = root.format.reads(json)
}

Now let's write a small piece of client code that reproduce the issue:

case class MessageSchema(prefix: PathNodes) extends JsonSchema[Message](prefix) {

  def underlying = plain[String]("underlying")
  //def underlying = plain[String]("underlying").optional if I wanted the field to be Option[String]
  //def underlying = plain[String]("underlying").sequence if I wanted the field to be Seq[String]
  override def format = underlying <> (Message.apply _, Message.unapply)

}

case class Message(underlying: String)

object Message {

  implicit object sm extends HasJsonSchema[Message, MessageSchema](MessageSchema.apply)

}

case class LanguageTaggedSchema[T, S <: JsonSchema[T]](prefix: PathNodes)(implicit evT: HasJsonSchema[T, S]) extends JsonSchema[LanguageTagged[T]](prefix) {
  def lang = plain[String]("lang")

  def data: S = nested("data")(evT)

  def format = (lang, data) <> (LanguageTagged.apply[T] _, LanguageTagged.unapply[T])
}

case class LanguageTagged[T](lang: String, data: T)

object LanguageTagged {

  implicit def schemaMapper[T, S <: JsonSchema[T]](implicit ev: HasJsonSchema[T, S]): HasJsonSchema[LanguageTagged[T], LanguageTaggedSchema[T, S]] =
    new HasJsonSchema[LanguageTagged[T], LanguageTaggedSchema[T, S]](LanguageTaggedSchema.apply[T, S]) {}
}

def toJson[T, S <: JsonSchema[T]](a: T)(implicit ev: HasJsonSchema[T, S]): JsValue = Json.toJson(a)(ev.format)

toJson(Message("hi")) //Ok!
toJson(LanguageTagged("en", Message("hi"))) //Ok!
//or simply write
Json.toJson(LanguageTagged("en", Message("hi")))

//and if i wanted to traverse a json path i would do:
val schema = implicitly[HasJsonSchema[LanguageTagged[Message],LanguageTaggedSchema[Message,MessageSchema]]].root
schema.data.underlying.jsPath
//prints: res2: play.api.libs.json.JsPath = /data/underlying

//Now to where the problem starts:

def getSchema[T, S <: JsonSchema[T]](a: T)(implicit ev: HasJsonSchema[T, S]): S = ev.root

getSchema(Message("hi")) //Ok!
getSchema(LanguageTagged("en", Message("hi"))) //Not Ok but why?
//Error:(211, 11) could not find implicit value for
//parameter ev: A$A6.this.HasJsonSchema[A$A6.this.LanguageTagged[A$A6.this.Message],S]
//getSchema(LanguageTagged("en", Message("hi")));//
//^

I have a huge suspicion that the compiler runs into issues because of the bounded type of S inHasJsonSchema[T, S <: JsonSchema[T]] when infering the implicit type S. and so far only in that specific situation as shown on the last line of all the code. as a dubugging attempt I created a similar situation and realized that if the type S was not bounded I wouldn't have this issue. Any sort of solution that refactors the code such that it doesn't depend on bounded types or one that simply solves the implicit resolution is appreciated


问:
angular 2+ fetch specific value from local json file
I want to fetch only a certain object from the file. But I somehow only can fetch the entire data from the file.

So far my method to fetch the data looks like this:

```<code>getGeoCityFromLocalFile(lon, lat) {
    return this.http.get('/assets/city-list.json')
    .map(res => res.json()).subscribe(res => {
         If(res.coord.lon === lon && res.coord.lat === lat) {
             this.cityStatsStorage = res;
             console.log(this.cityStatsStorage);
             return this.cityStatsStorage;
         }
    });
}
</code>```

I want to fetch only this Object where the lon an lan Input are the same.

答:
Your problem lies in here:

```<code>If(res.coord.lon === lon && res.coord.lat === lat)
</code>```

Res is an array and not a single object, so you would need a loop. Example:

```<code>for (var i=0; i<res.length; i++){
   if (res[i].coord.lon === lon && res[i].coord.lat === lat){
      this.cityStatsStorage = res[i];
      console.log(this.cityStatsStorage);
      return this.cityStatsStorage;
   }
}
</code>```

Body:
I want to fetch only a certain object from the file. But I somehow only can fetch the entire data from the file.

So far my method to fetch the data looks like this:

getGeoCityFromLocalFile(lon, lat) {
    return this.http.get('/assets/city-list.json')
    .map(res => res.json()).subscribe(res => {
         If(res.coord.lon === lon && res.coord.lat === lat) {
             this.cityStatsStorage = res;
             console.log(this.cityStatsStorage);
             return this.cityStatsStorage;
         }
    });
}

I want to fetch only this Object where the lon an lan Input are the same.

Body:
Your problem lies in here:

If(res.coord.lon === lon && res.coord.lat === lat)

Res is an array and not a single object, so you would need a loop. Example:

for (var i=0; i<res.length; i++){
   if (res[i].coord.lon === lon && res[i].coord.lat === lat){
      this.cityStatsStorage = res[i];
      console.log(this.cityStatsStorage);
      return this.cityStatsStorage;
   }
}


问:
Can you help me decipher this cryptography?
i've been trying to work out the result for a while but I have'nt worked it out yet.

It says:
Sometimes hackers appear in the most unlikely of places. Our team recently uncovered a hacker who was running a coffee shop as a cover for his secret identity. He hacked the cash register to show secret messages to particular customers. We knew it used some kind of cipher to hide them. Take a look at the example receipt below - can you find the hidden message?
                                 ***

```<code>                            Crypto Coffee
                       Brew Street, Copenhagen
   Qu.      Reference            Name       Amount
   2        rcuuyqtfk          Americano    EUR 4.00
   3        dphulfdqr          Croissant    EUR 2.25
                                                    Total: EUR 6.25
</code>```

I know it has something to do with the reference but I just can't decipher it. Any help would be grateful. Thanks.

答:
Is this some kind of homework?
If yes I'm kind of reluctant to give the solution, but since it likely is supposed to be decryptable, take a look into some easy ciphers.
Try Cesar's cipher first. If you take the numbers on the receipt into account, it's even easier...</p>

Body:
i've been trying to work out the result for a while but I have'nt worked it out yet.

It says:
Sometimes hackers appear in the most unlikely of places. Our team recently uncovered a hacker who was running a coffee shop as a cover for his secret identity. He hacked the cash register to show secret messages to particular customers. We knew it used some kind of cipher to hide them. Take a look at the example receipt below - can you find the hidden message?
                                 ***

                            Crypto Coffee
                       Brew Street, Copenhagen
   Qu.      Reference            Name       Amount
   2        rcuuyqtfk          Americano    EUR 4.00
   3        dphulfdqr          Croissant    EUR 2.25
                                                    Total: EUR 6.25

I know it has something to do with the reference but I just can't decipher it. Any help would be grateful. Thanks.


问:
ASIHTTP: Upload UIImage?
Can someone please tell me how I can use an ASIHTTPRequest object in Objective-c to upload an UIImage object? Do I need to convert it to an NSData object?

(This is for an avatar upload url)

```<code>E.g.

UIImage *toUpload = [UIImage imageNamed:@"test.jpg"]

URL: "http://www.example.com/api/users/avatar/upload?access_token=12345"
RequestType: PUT
</code>```

答:
Heres an example using ASIFormRequest that will also attempt to compress the image to given maximum size</p>

```<code>    //Compress the image
CGFloat compression = 0.9f;
CGFloat maxCompression = 0.1f;
int maxFileSize = 250*1024;

NSData *imageData = UIImageJPEGRepresentation(yourImage, compression);

while ([imageData length] > maxFileSize && compression > maxCompression)
{
    compression -= 0.1;
    imageData = UIImageJPEGRepresentation(yourImage, compression);
}

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:whereYourServerEndPointIs.com]];

[request addData:imageData withFileName:@"someFileName.jpeg" andContentType:@"image/jpeg" forKey:@"uploadedImage"];
</code>```

Title: ASIHTTP: Upload UIImage?

Body:
Can someone please tell me how I can use an ASIHTTPRequest object in Objective-c to upload an UIImage object? Do I need to convert it to an NSData object?

(This is for an avatar upload url)

E.g.

UIImage *toUpload = [UIImage imageNamed:@"test.jpg"]

URL: "http://www.example.com/api/users/avatar/upload?access_token=12345"
RequestType: PUT

Body:
Heres an example using ASIFormRequest that will also attempt to compress the image to given maximum size

    //Compress the image
CGFloat compression = 0.9f;
CGFloat maxCompression = 0.1f;
int maxFileSize = 250*1024;

NSData *imageData = UIImageJPEGRepresentation(yourImage, compression);

while ([imageData length] > maxFileSize && compression > maxCompression)
{
    compression -= 0.1;
    imageData = UIImageJPEGRepresentation(yourImage, compression);
}

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:whereYourServerEndPointIs.com]];

[request addData:imageData withFileName:@"someFileName.jpeg" andContentType:@"image/jpeg" forKey:@"uploadedImage"];


问:
the number of items at a given depth in all sub-lists of a list
I feel like i'm going at it all wrong. I am recursing at the depth of a list as if it was a Tree. This causes problems because It's an arbitrary list that can have strings, ints ...
Here's what I have</p>

```<code>def visit_depth(list_, depth):
    if depth == 0:
        return 1
    elif depth >0:
        return sum([visit_depth(l, depth - 1) for l in list_])
    else:
        return 0
</code>```

答:
This causes problems because It's an arbitrary list that can have strings, ints

Guard against them.

```<code>def deep_len(obj, depth=0):
    if isinstance(obj, list):
        if depth == 0:
            return len(obj)
        else:
            return sum(deep_len(elem, depth - 1) for elem in obj)
    else:
        return 0

deep_len([1,2,[2,5],[3]], 0)
# => 4      (this list itself has 4 elements)
deep_len([1,2,[2,5],[3]], 1)
# => 3      (going 1 level down there's just 3 elements)
deep_len([1,2,[2,5],[3]], 2)
# => 0      (there is no 2 levels down)
</code>```

Body:
I feel like i'm going at it all wrong. I am recursing at the depth of a list as if it was a Tree. This causes problems because It's an arbitrary list that can have strings, ints ...
Here's what I have

def visit_depth(list_, depth):
    if depth == 0:
        return 1
    elif depth >0:
        return sum([visit_depth(l, depth - 1) for l in list_])
    else:
        return 0

Body:
This causes problems because It's an arbitrary list that can have strings, ints

Guard against them.

def deep_len(obj, depth=0):
    if isinstance(obj, list):
        if depth == 0:
            return len(obj)
        else:
            return sum(deep_len(elem, depth - 1) for elem in obj)
    else:
        return 0

deep_len([1,2,[2,5],[3]], 0)
# => 4      (this list itself has 4 elements)
deep_len([1,2,[2,5],[3]], 1)
# => 3      (going 1 level down there's just 3 elements)
deep_len([1,2,[2,5],[3]], 2)
# => 0      (there is no 2 levels down)


问:
How to Position Anchors in HTML Tables in the Viewport

I am using anchor elemnts in an html table and want to add some padding to the top of the viewport. I figured out, that I can place the anchor in a dummy DIV element inside of the TD element to achieve this. However I also want to highlight the targets table row.

How can I achieve this without javascript?

I have tried several solutions from
HTML position:fixed page header and in-page anchors,
but they all do not work well in html tables.

Here is some minimal working example.

The "D" anchor has correct highlighting, but positioning does not
work.

The "E" anchor has correct positioning, but no highlighting.

tr:target {
  color: #ee4444;
  position: relative;
  top: -40px;
}

div:target {
  color: #ee4444;
  position: relative;
  top: -40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>go to D go to E
<table>
  <tr>
    <th>Symbol</th>
    <th>1932 ITU/ICAN Phonetic</th>
  </tr>
  <tr>
    <td>A</td>
    <td>Amsterdam</td>
  </tr>
  <tr>
    <td>B</td>
    <td>Baltimore</td>
  </tr>
  <tr>
    <td>C</td>
    <td>Casablanca</td>
  </tr>
  <tr id="D">
    <td>D</td>
    <td>Denmark</td>
  </tr>
  <tr>
    <td>
      <div id="E"></div>E</td>
    <td>Edison</td>
  </tr>
  <tr>
    <td>F</td>
    <td>Florida</td>
  </tr>
  <tr>
    <td>G</td>
    <td>Gallipoli</td>
  </tr>
  <tr>
    <td>H</td>
    <td>Havana</td>
  </tr>
  <tr>
    <td>I</td>
    <td>Italia</td>
  </tr>
  <tr>
    <td>J</td>
    <td>Jerusalem</td>
  </tr>
  <tr>
    <td>K</td>
    <td>Kilogramme</td>
  </tr>
  <tr>
    <td>L</td>
    <td>Liverpool</td>
  </tr>
  <tr>
    <td>M</td>
    <td>Madagascar</td>
  </tr>
  <tr>
    <td>N</td>
    <td>New York</td>
  </tr>
  <tr>
    <td>O</td>
    <td>Oslo</td>
  </tr>
  <tr>
    <td>P</td>
    <td>Paris</td>
  </tr>
  <tr>
    <td>Q</td>
    <td>Quebec</td>
  </tr>
  <tr>
    <td>R</td>
    <td>Roma</td>
  </tr>
  <tr>
    <td>S</td>
    <td>Santiago</td>
  </tr>
  <tr>
    <td>T</td>
    <td>Tripoli</td>
  </tr>
  <tr>
    <td>U</td>
    <td>Upsala</td>
  </tr>
  <tr>
    <td>V</td>
    <td>Valencia</td>
  </tr>
  <tr>
    <td>W</td>
    <td>Washington</td>
  </tr>
  <tr>
    <td>X</td>
    <td>Xanthippe</td>
  </tr>
  <tr>
    <td>Y</td>
    <td>Yokohama</td>
  </tr>
  <tr>
    <td>Z</td>
    <td>Zurich</td>
  </tr>
</table></code>```

答:
You can try below this.</p>

```<code>tr:target {
    color: #ee4444;
    position:relative;
    top:0px;
}
span:target {
   color: #ee4444;
   position:relative;
   top:0px;
}

<tr id="D"><td>D</td><td>Denmark</td></tr>
<tr><td><span id="E">hello</span>E</td><td>Edison</td></tr>
</code>```

Body:
I am using anchor elemnts in an html table and want to add some padding to the top of the viewport. I figured out, that I can place the anchor in a dummy DIV element inside of the TD element to achieve this. However I also want to highlight the targets table row.

How can I achieve this without javascript?

I have tried several solutions from
HTML position:fixed page header and in-page anchors,
but they all do not work well in html tables.

Here is some minimal working example.

The "D" anchor has correct highlighting, but positioning does not
work.

The "E" anchor has correct positioning, but no highlighting.

tr:target {
  color: #ee4444;
  position: relative;
  top: -40px;
}

div:target {
  color: #ee4444;
  position: relative;
  top: -40px;
}

go to D go to E

    Symbol
    1932 ITU/ICAN Phonetic

    A
    Amsterdam

    B
    Baltimore

    C
    Casablanca

    D
    Denmark

E
    Edison

    F
    Florida

    G
    Gallipoli

    H
    Havana

    I
    Italia

    J
    Jerusalem

    K
    Kilogramme

    L
    Liverpool

    M
    Madagascar

    N
    New York

    O
    Oslo

    P
    Paris

    Q
    Quebec

    R
    Roma

    S
    Santiago

    T
    Tripoli

    U
    Upsala

    V
    Valencia

    W
    Washington

    X
    Xanthippe

    Y
    Yokohama

    Z
    Zurich

Body:
You can try below this.

tr:target {
    color: #ee4444;
    position:relative;
    top:0px;
}
span:target {
   color: #ee4444;
   position:relative;
   top:0px;
}

<tr id="D"><td>D</td><td>Denmark</td></tr>
<tr><td><span id="E">hello</span>E</td><td>Edison</td></tr>


问:
Child categories not appearing in wordpress admin menu
I am creating a plugin and adding some categories

some categories are child categories for instance:

Clothes

Hats

Shirts

I add my category like this:

```<code>function addCategory($name, $description, $slug){
  $term = wp_insert_term( $name, 'product_cat', [
  'description'=> $description,
  'slug' => $slug ]
  );
  if ( is_wp_error( $term ) ) {
     $term_id = $term->error_data['term_exists'] || null;
     return false;
  } else {
     $term_id = $term['term_id'];
     add_term_meta ($term_id, "display_style", "products", true);
     return $term_id;
  }
}
</code>```

if in my category object the parent_id is different from 0 then I call this function:

```<code>function updateParentID($localID, $parentLocalID){
  global $wpdb;
  $table_name = $wpdb->prefix.'term_taxonomy';
  $sql ="UPDATE $table_name SET parent = $parentLocalID WHERE  term_id = $localID";
  $rez = $wpdb->query($sql);
  return $rez;
}
</code>```

If I check my term_taxonomy table I do have the right ID for the parent field.

However if on the admin panel I check the categories I can't see the categories but the item count is at 4:

If I click the Name column to filter by alphabetical order then they appear:

From what I can see they are correctly linked in the database:

I noticed in the admin panel if I edit a child category and just save without changing any details then they will appear correctly:

How could get them to show all the time. Am I missing something when adding the parent.

Note:

I noticed in the docs there's a wp_update_term but I couldn't find any wp_update_term_taxonomy

答:
To set parent/child of the term, why you are using separate custom query($wpdb->query())? Well, but i think you can use the parent parameter which is in wp_insert_term parameter it self.

Example,

```<code>wp_insert_term(
'Banana', // the term
'product_cat', // the taxonomy
array(
  'description'=> 'Sweet banana',
  'slug' => 'banana',
  'parent'=> $parent_term_id
 )
);
</code>```

Body:
I am creating a plugin and adding some categories

some categories are child categories for instance:

Clothes

Hats

Shirts

I add my category like this:

function addCategory($name, $description, $slug){
  $term = wp_insert_term( $name, 'product_cat', [
  'description'=> $description,
  'slug' => $slug ]
  );
  if ( is_wp_error( $term ) ) {
     $term_id = $term->error_data['term_exists'] || null;
     return false;
  } else {
     $term_id = $term['term_id'];
     add_term_meta ($term_id, "display_style", "products", true);
     return $term_id;
  }
}

if in my category object the parent_id is different from 0 then I call this function:

function updateParentID($localID, $parentLocalID){
  global $wpdb;
  $table_name = $wpdb->prefix.'term_taxonomy';
  $sql ="UPDATE $table_name SET parent = $parentLocalID WHERE  term_id = $localID";
  $rez = $wpdb->query($sql);
  return $rez;
}

If I check my term_taxonomy table I do have the right ID for the parent field.

However if on the admin panel I check the categories I can't see the categories but the item count is at 4:

If I click the Name column to filter by alphabetical order then they appear:

From what I can see they are correctly linked in the database:

I noticed in the admin panel if I edit a child category and just save without changing any details then they will appear correctly:

How could get them to show all the time. Am I missing something when adding the parent.

Note:

I noticed in the docs there's a wp_update_term but I couldn't find any wp_update_term_taxonomy

Body:
To set parent/child of the term, why you are using separate custom query($wpdb->query())? Well, but i think you can use the parent parameter which is in wp_insert_term parameter it self.

Example,

wp_insert_term(
'Banana', // the term
'product_cat', // the taxonomy
array(
  'description'=> 'Sweet banana',
  'slug' => 'banana',
  'parent'=> $parent_term_id
 )
);


问:
Enzyme not returning the correct children for a newly defined component
I'm expecting the following test to pass:

```<code>const Foo = ({ children }) => (
  <div>
    {children}
  </div>
);

describe('<Foo />', function () {
  it('always renders a <div />', function () {
    const foo = mount(
      <Foo>
        <div className="foo" />
      </Foo>
    );

    expect(foo.children().html()).to.equal('<div class="foo"></div>');
  });
});
</code>```

However, the above would give me:

```<code>AssertionError: expected '<div><div class="foo"></div></div>' to equal '<div class="foo"></div>'
</code>```

Temporary fix

I found that I can simply chain two children() calls to make this work:

```<code>describe('<Foo />', function () {
  it('always renders a <div />', function () {
    const foo = mount(
      <Foo>
        <div className="foo" />
      </Foo>
    );

    expect(foo.children().children().html()).to.equal('<div class="foo"></div>');
  });
});
</code>```

Inconsistency

If I just use a normal div instead of the Foo component to wrap the inner div, I'll get the right result. That is,

```<code>describe('<Foo />', function () {
  it('always renders a <div />', function () {
    const foo = mount(
      <div>
        <div className="foo" />
      </div>
    );

    expect(foo.children().html()).to.equal('<div class="foo"></div>');
  });
});
</code>```

Furthermore, I found that foo.children().html() returns exactly the same string as foo.html(). Hence the following expect would pass:

```<code>expect(foo.html()).to.equal(foo.children().html());
</code>```

Question

If that's the expected behaviour, why?
Is there a neater way to get the children than just to chain it twice?

答:
As I haven't received an answer or gathered enough views on this question, I've logged an issue on the repository and "ljharb" has given me the answer:

This is intentional. When you mount a component, you get that component - you need .children() to get at the thing it renders.

Body:
I'm expecting the following test to pass:

const Foo = ({ children }) => (

    {children}

);

describe('<Foo />', function () {
  it('always renders a
', function () {
    const foo = mount(
      <Foo>

      </Foo>
    );

    expect(foo.children().html()).to.equal('

');
  });
});

However, the above would give me:

AssertionError: expected '

' to equal '

'

Temporary fix

I found that I can simply chain two children() calls to make this work:

describe('<Foo />', function () {
  it('always renders a
', function () {
    const foo = mount(
      <Foo>

      </Foo>
    );

    expect(foo.children().children().html()).to.equal('

');
  });
});

Inconsistency

If I just use a normal div instead of the Foo component to wrap the inner div, I'll get the right result. That is,

describe('<Foo />', function () {
  it('always renders a
', function () {
    const foo = mount(

    );

    expect(foo.children().html()).to.equal('

');
  });
});

Furthermore, I found that foo.children().html() returns exactly the same string as foo.html(). Hence the following expect would pass:

expect(foo.html()).to.equal(foo.children().html());

Question

If that's the expected behaviour, why?
Is there a neater way to get the children than just to chain it twice?


问:
How to update a record in csv file using Apache commons csv api in java?
I have a csv file written using Apache commons API and I also can read the file, however I'm unable to know how to edit a record value in the csv file using Apache commons API, need help on this.</p>

答:
The Apache CSV interface only support reading and writing exclusively, you cannot update records with the provided API.

So your best option is probably to read the file into memory, do the changes and write it out again.

If the size of the file is bigger than available memory you might need some streaming approach which reads records and writes them out before reading the next one. You need to write to a separate file in this case naturally.


问:
How to write a Spring JPA query for a one to one relationship?
I am new to Spring JPA (or rather looking into it after a long time) and I need some help with writing JPA repository.
I have an entity class Itinerary and User. There is a one to one relationship between the two.

```<code>@Entity
@Table(name = "ITINERARY")
public class Itinerary implements Serializable {

    @Id
    @Column(name = "ID")
    @GeneratedValue(generator = "Itinerary_IDGenerator", strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = "Itinerary_IDGenerator", sequenceName = "Itinerary_IDGenerator", allocationSize = 1)
    private long id;

    @Basic(optional = false)
    @Column(nullable = false)
    @Temporal(TemporalType.DATE)
    private Date itineraryDate;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID")
    User user;
}

@Entity
@Table(name = "USER")
public class User implements Serializable {

    @Id
    @Column(name = "ID")
    @GeneratedValue(generator = "User_IDGenerator", strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = "User_IDGenerator", sequenceName = "User_IDGenerator", allocationSize = 1)
    private long id;

    @Basic(optional = false)
    @Column(unique = true, nullable = false)
    private String signInName;
}
</code>```

I want to write a Spring JPA repository for the Itinerary entity to have a method that will return an itinerary for a user (with the specifid singInName) and the itinerary date.
I have write the following interface, but I don't know how to specify the spring query. I have provided a JPA query that works.

```<code>public interface ItineraryRepository extends Repository<Itinerary, Long> {

    //String queryStr = "select i from Itinerary i where i.user.signInName = '" + signedInUser + "' and i.itineraryDate = :today";

    @Query(select i from Itinerary i where i.user.signInName = :signInName and i.itineraryDate = :today)
    Itinerary findBySignInNameAndDate(@Param("signInName") String signInName, @Param("itineraryDate") Date itineraryDate);

}
</code>```

I get an error on the query.

```<code>Invalid derived query! No property signInName found for type Itinerary!
</code>```

and

```<code>Syntax error on tokens, delete these tokens
</code>```

How do I convert this query to a spring query? I could not find an example in the documentation. I am not sure if this is possible at all and whether I am using the repository incorrectly.

答:
Use this method in your repository Interface. And no need of @Query

```<code> findByItineraryDateAndUser_SignInName(Date itineraryDate, String signInName);
</code>```

Spring data is intelligent enough to understand what query it needs to use to fetch results based on your method name(atleast in simple query cases).

User_SignInName specifies to look for a property signInName inside property user.

Body:
I am new to Spring JPA (or rather looking into it after a long time) and I need some help with writing JPA repository.
I have an entity class Itinerary and User. There is a one to one relationship between the two.

@Entity
@Table(name = "ITINERARY")
public class Itinerary implements Serializable {

    @Id
    @Column(name = "ID")
    @GeneratedValue(generator = "Itinerary_IDGenerator", strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = "Itinerary_IDGenerator", sequenceName = "Itinerary_IDGenerator", allocationSize = 1)
    private long id;

    @Basic(optional = false)
    @Column(nullable = false)
    @Temporal(TemporalType.DATE)
    private Date itineraryDate;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID")
    User user;
}

@Entity
@Table(name = "USER")
public class User implements Serializable {

    @Id
    @Column(name = "ID")
    @GeneratedValue(generator = "User_IDGenerator", strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = "User_IDGenerator", sequenceName = "User_IDGenerator", allocationSize = 1)
    private long id;

    @Basic(optional = false)
    @Column(unique = true, nullable = false)
    private String signInName;
}

I want to write a Spring JPA repository for the Itinerary entity to have a method that will return an itinerary for a user (with the specifid singInName) and the itinerary date.
I have write the following interface, but I don't know how to specify the spring query. I have provided a JPA query that works.

public interface ItineraryRepository extends Repository<Itinerary, Long> {

    //String queryStr = "select i from Itinerary i where i.user.signInName = '" + signedInUser + "' and i.itineraryDate = :today";

    @Query(select i from Itinerary i where i.user.signInName = :signInName and i.itineraryDate = :today)
    Itinerary findBySignInNameAndDate(@Param("signInName") String signInName, @Param("itineraryDate") Date itineraryDate);

}

I get an error on the query.

Invalid derived query! No property signInName found for type Itinerary!

and

Syntax error on tokens, delete these tokens

How do I convert this query to a spring query? I could not find an example in the documentation. I am not sure if this is possible at all and whether I am using the repository incorrectly.

Body:
Use this method in your repository Interface. And no need of @Query

 findByItineraryDateAndUser_SignInName(Date itineraryDate, String signInName);

Spring data is intelligent enough to understand what query it needs to use to fetch results based on your method name(atleast in simple query cases).

User_SignInName specifies to look for a property signInName inside property user.


问:
Working with Multiple Nuget Projects in one Solution
I have 2 projects: A & B that I want to publish as NuGet Packages but I don't know how to develop efficiently in Visual Studio.

```<code>Solution 1
   Project A
   Project B - references Project A as NuGet reference
</code>```

When I make a change to Project A that is needed in Project B do I have to publish Project A?  Is there a way to get the project reference functionality during development?  Maybe Project B shouldn't reference Project A via NuGet?

There must be a good way to handle this situation, no?  I've reviewed the NuGet docs but I couldn't find anything.  There must be docs/blogs/SO posts to read more about this... I'm struggling to come up w/ the right keywords.

答:
You could add following Post-build event command to pack your project after building.

```<code>"the nuget.exe path\nuget.exe" pack "project path\NuGetPackageLibrary.csproj" -OutputDirectory "Your target path"
</code>```

When your build successful, the package in target path will be replaced by the latest version.

ContentLicense: CC BY-SA 4.0

Body:
I have 2 projects: A & B that I want to publish as NuGet Packages but I don't know how to develop efficiently in Visual Studio.

Solution 1
   Project A
   Project B - references Project A as NuGet reference

When I make a change to Project A that is needed in Project B do I have to publish Project A?  Is there a way to get the project reference functionality during development?  Maybe Project B shouldn't reference Project A via NuGet?

There must be a good way to handle this situation, no?  I've reviewed the NuGet docs but I couldn't find anything.  There must be docs/blogs/SO posts to read more about this... I'm struggling to come up w/ the right keywords.

Body:
You could add following Post-build event command to pack your project after building.

"the nuget.exe path\nuget.exe" pack "project path\NuGetPackageLibrary.csproj" -OutputDirectory "Your target path"

When your build successful, the package in target path will be replaced by the latest version.


问:
Allow anonymous users to create unpublished nodes in Drupal?
I'm creating a site for a client based on drupal, and the client wants an anonymous user (not logged in) to be able to create a new node, but only an unpublished one. Then an admin can review the node and alter it before publishing himself.

I have looked at using triggers and actions, but writing a custom trigger module seems a bit daunting, as I'm not very fluent with the Drupal API currently. Any ideas are appreciated.

答: You can accomplish that without custom coding or triggers/actions. Just set the content type's default to unpublished and set the permissions for the content type to allow anonymous users to create that type of content.</p>