问:
Coupon code not working for items in cart
I am trying to implement a coupon code feature in my Django e-commerce website. I have added the apply_coupon method to the Order model and a coupon field to the Order model, and I have also added a coupon_code parameter to the cart view function. However, when I test the coupon code by entering it in the cart page, nothing happens and the discount is not applied.

I've included the relevant code snippets below. Can someone please help me understand why the coupon code is not working and how to fix it?

views.py

from django.shortcuts import render
from django.http import JsonResponse
from django.contrib import messages
import json
import datetime

from .models import *
from .utils import cookieCart, cartData, guestOrder

def store(request):
    data = cartData(request)

    cartItems = data['cartItems']
    order = data['order']
    items = data['items']

    products = Product.objects.all()
    context = {'products': products, 'cartItems': cartItems}
    return render(request, 'store/store.html', context)

def cart(request):
    data = cartData(request)
    cartItems = data['cartItems']
    order = data['order']
    items = data['items']

    coupon = Coupon(code='PERMANENT', discount=0.2, active=True, valid_until=None)
    coupon.save()

    # Kupon kodu işlevini ekleyin
    coupon_code = request.GET.get('coupon_code', None)
    if coupon_code:
        # Eğer bir sipariş nesnesi oluşturulmuşsa kupon uygulayın
        if hasattr(order, 'apply_coupon'):
            coupon_applied = order.apply_coupon(coupon_code)
            if not coupon_applied:
                messages.warning(request, 'Geçersiz veya etkin olmayan bir kupon kodu girdiniz.')
            else:
                messages.success(request, 'Kupon kodu başarıyla uygulandı.')
        else:
            messages.warning(request, 'Kupon kodu sadece giriş yapmış müşteriler için geçerlidir.')

    products = Product.objects.all()
    context = {'items': items, 'order': order, 'cartItems': cartItems}
    return render(request, 'store/cart.html', context)

def checkout(request):
    data = cartData(request)

    cartItems = data['cartItems']
    order = data['order']
    items = data['items']

    context = {'items': items, 'order': order, 'cartItems': cartItems}
    return render(request, 'store/checkout.html', context)

def updateItem(request):
    data = json.loads(request.body)
    productId = data['productId']
    action = data['action']
    print('Action:', action)
    print('Product:', productId)

    customer = request.user.customer
    product = Product.objects.get(id=productId)
    order, created = Order.objects.get_or_create(customer=customer, complete=False)

    orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)

    if action == 'add':
        orderItem.quantity = (orderItem.quantity + 1)
    elif action == 'remove':
        orderItem.quantity = (orderItem.quantity - 1)

    orderItem.save()

    if orderItem.quantity <= 0:
        orderItem.delete()

    return JsonResponse('Item was added', safe=False)

def processOrder(request):
    transaction_id = datetime.datetime.now().timestamp()
    data = json.loads(request.body)

    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
    else:
        customer, order = guestOrder(request, data)

    total = float(data['form']['total'])
    order.transaction_id = transaction_id

    if total == order.get_cart_total:
        order.complete = True
    order.save()

    if order.shipping == True:
        ShippingAddress.objects.create(
            customer=customer,
            order=order,
            address=data['shipping']['address'],
            city=data['shipping']['city'],
            state=data['shipping']['state'],
            zipcode=data['shipping']['zipcode'],
        )

    return JsonResponse('Payment submitted..', safe=False)
```
<p>models.py</p>
<pre class="lang-py prettyprint-override"><code>from django.db import models
from django.contrib.auth.models import User

class Customer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
    name = models.CharField(max_length=200, null=True)
    email = models.CharField(max_length=200, null=True)

    def __str__(self):
        return self.name

class Product(models.Model):
    name = models.CharField(max_length=200, null=True)
    price = models.FloatField(max_length=200, null=True)
    digital = models.BooleanField(default=False, null=True, blank=True)
    image = models.ImageField(null=True, blank=True)

    def __str__(self):
        return self.name

    @property
    def imageURL(self):
        try:
            url = self.image.url
        except:
            url = ''
        return url

class Coupon(models.Model):
    code = models.CharField(max_length=20)
    discount = models.FloatField()
    active = models.BooleanField(default=True)
    valid_until = models.DateField(null=True, blank=True)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.code

    @property
    def apply_coupon(self):
        coupon = Coupon.objects.get(code=self.code)
        if coupon and coupon.valid_until is None or coupon.valid_until >= timezone.now():
            self.coupon = coupon
            self.save()
            return True
        return False

class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
    date_order = models.DateTimeField(auto_now_add=True)
    complete = models.BooleanField(default=False, null=True, blank=True)
    transaction_id = models.CharField(max_length=200, null=True)
    coupon = models.ForeignKey(Coupon, on_delete=models.SET_NULL, null=True, blank=True)

    def __str__(self):
        return str(self.id)

    @property
    def shipping(self):
        shipping = False
        orderitems = self.orderitem_set.all()
        for i in orderitems:
            if i.product.digital == False:
                shipping = True
        return shipping

    @property
    def get_cart_total(self):
        orderitems = self.orderitem_set.all()
        total = sum([item.get_total for item in orderitems])
        return total

    @property
    def get_cart_items(self):
        orderitems = self.orderitem_set.all()
        total = sum([item.quantity for item in orderitems])
        return total

class OrderItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
    quantity = models.IntegerField(default=0, null=True, blank=True)
    date_added = models.DateTimeField(auto_now_add=True)

    @property
    def get_total(self):
        total = self.product.price * self.quantity
        return total

class ShippingAddress(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
    address = models.CharField(max_length=200, null=True)
    city = models.CharField(max_length=200, null=True)
    state = models.CharField(max_length=200, null=True)
    zipcode = models.CharField(max_length=200, null=True)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.address
</code>```

utils.py

import json
from .models import *

def cookieCart(request):
    # Create empty cart for now for non-logged in user
    try:
        cart = json.loads(request.COOKIES['cart'])
    except:
        cart = {}
        print('CART:', cart)

    items = []
    order = {'get_cart_total': 0, 'get_cart_items': 0, 'shipping': False}
    cartItems = order['get_cart_items']

    for i in cart:
        # We use try block to prevent items in cart that may have been removed from causing error
        try:
            if (cart[i]['quantity'] > 0):  # items with negative quantity = lot of freebies
                cartItems += cart[i]['quantity']

                product = Product.objects.get(id=i)
                total = (product.price * cart[i]['quantity'])

                order['get_cart_total'] += total
                order['get_cart_items'] += cart[i]['quantity']

                item = {
                    'id': product.id,
                    'product': {'id': product.id, 'name': product.name, 'price': product.price,
                                'imageURL': product.imageURL}, 'quantity': cart[i]['quantity'],
                    'digital': product.digital, 'get_total': total,
                }
                items.append(item)

                if product.digital == False:
                    order['shipping'] = True
            else:
                cart[i]['quantity'] = -1 * cart[i]['quantity']
                product = Product.objects.get(id=i)
                product.price = -1 * product.price
                total = (product.price * cart[i]['quantity'])

                order['get_cart_total'] += total
                order['get_cart_items'] += cart[i]['quantity']

                item = {
                    'id': product.id,
                    'product': {'id': product.id, 'name': product.name, 'price': product.price,
                                'imageURL': product.imageURL}, 'quantity': cart[i]['quantity'],
                    'digital': product.digital, 'get_total': total,
                }
                items.append(item)

                if product.digital == False:
                    order['shipping'] = True
        except:
            pass

    return {'cartItems': cartItems, 'order': order, 'items': items}

def cartData(request):
    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
        items = order.orderitem_set.all()
        cartItems = order.get_cart_items
    else:
        cookieData = cookieCart(request)
        cartItems = cookieData['cartItems']
        order = cookieData['order']
        items = cookieData['items']

    return {'cartItems': cartItems, 'order': order, 'items': items}

def apply_coupon(order, coupon_code):
    coupon = Coupon.objects.get(code=coupon_code)
    if coupon and coupon.valid_until is None or coupon.valid_until >= timezone.now():
        order.coupon = coupon
        order.save()
        return True
    return False

def guestOrder(request, data):
    name = data['form']['name']
    email = data['form']['email']

    cookieData = cookieCart(request)
    items = cookieData['items']

    customer, created = Customer.objects.get_or_create(
        email=email,
    )
    customer.name = name
    customer.save()

    order = Order.objects.create(
        customer=customer,
        complete=False,
    )

    for item in items:
        product = Product.objects.get(id=item['id'])
        orderItem = OrderItem.objects.create(
            product=product,
            order=order,
            quantity=(item['quantity'] if item['quantity'] > 0 else -1 * item['quantity']),
            # negative quantity = freebies
        )
    return customer, order
```

Body:
I am trying to implement a coupon code feature in my Django e-commerce website. I have added the apply_coupon method to the Order model and a coupon field to the Order model, and I have also added a coupon_code parameter to the cart view function. However, when I test the coupon code by entering it in the cart page, nothing happens and the discount is not applied.

I've included the relevant code snippets below. Can someone please help me understand why the coupon code is not working and how to fix it?

views.py

from django.shortcuts import render
from django.http import JsonResponse
from django.contrib import messages
import json
import datetime

from .models import *
from .utils import cookieCart, cartData, guestOrder

def store(request):
    data = cartData(request)

    cartItems = data['cartItems']
    order = data['order']
    items = data['items']

    products = Product.objects.all()
    context = {'products': products, 'cartItems': cartItems}
    return render(request, 'store/store.html', context)

def cart(request):
    data = cartData(request)
    cartItems = data['cartItems']
    order = data['order']
    items = data['items']

    coupon = Coupon(code='PERMANENT', discount=0.2, active=True, valid_until=None)
    coupon.save()

    # Kupon kodu işlevini ekleyin
    coupon_code = request.GET.get('coupon_code', None)
    if coupon_code:
        # Eğer bir sipariş nesnesi oluşturulmuşsa kupon uygulayın
        if hasattr(order, 'apply_coupon'):
            coupon_applied = order.apply_coupon(coupon_code)
            if not coupon_applied:
                messages.warning(request, 'Geçersiz veya etkin olmayan bir kupon kodu girdiniz.')
            else:
                messages.success(request, 'Kupon kodu başarıyla uygulandı.')
        else:
            messages.warning(request, 'Kupon kodu sadece giriş yapmış müşteriler için geçerlidir.')

    products = Product.objects.all()
    context = {'items': items, 'order': order, 'cartItems': cartItems}
    return render(request, 'store/cart.html', context)

def checkout(request):
    data = cartData(request)

    cartItems = data['cartItems']
    order = data['order']
    items = data['items']

    context = {'items': items, 'order': order, 'cartItems': cartItems}
    return render(request, 'store/checkout.html', context)

def updateItem(request):
    data = json.loads(request.body)
    productId = data['productId']
    action = data['action']
    print('Action:', action)
    print('Product:', productId)

    customer = request.user.customer
    product = Product.objects.get(id=productId)
    order, created = Order.objects.get_or_create(customer=customer, complete=False)

    orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)

    if action == 'add':
        orderItem.quantity = (orderItem.quantity + 1)
    elif action == 'remove':
        orderItem.quantity = (orderItem.quantity - 1)

    orderItem.save()

    if orderItem.quantity <= 0:
        orderItem.delete()

    return JsonResponse('Item was added', safe=False)

def processOrder(request):
    transaction_id = datetime.datetime.now().timestamp()
    data = json.loads(request.body)

    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
    else:
        customer, order = guestOrder(request, data)

    total = float(data['form']['total'])
    order.transaction_id = transaction_id

    if total == order.get_cart_total:
        order.complete = True
    order.save()

    if order.shipping == True:
        ShippingAddress.objects.create(
            customer=customer,
            order=order,
            address=data['shipping']['address'],
            city=data['shipping']['city'],
            state=data['shipping']['state'],
            zipcode=data['shipping']['zipcode'],
        )

    return JsonResponse('Payment submitted..', safe=False)

models.py

from django.db import models
from django.contrib.auth.models import User

class Customer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
    name = models.CharField(max_length=200, null=True)
    email = models.CharField(max_length=200, null=True)

    def __str__(self):
        return self.name

class Product(models.Model):
    name = models.CharField(max_length=200, null=True)
    price = models.FloatField(max_length=200, null=True)
    digital = models.BooleanField(default=False, null=True, blank=True)
    image = models.ImageField(null=True, blank=True)

    def __str__(self):
        return self.name

    @property
    def imageURL(self):
        try:
            url = self.image.url
        except:
            url = ''
        return url

class Coupon(models.Model):
    code = models.CharField(max_length=20)
    discount = models.FloatField()
    active = models.BooleanField(default=True)
    valid_until = models.DateField(null=True, blank=True)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.code

    @property
    def apply_coupon(self):
        coupon = Coupon.objects.get(code=self.code)
        if coupon and coupon.valid_until is None or coupon.valid_until >= timezone.now():
            self.coupon = coupon
            self.save()
            return True
        return False

class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
    date_order = models.DateTimeField(auto_now_add=True)
    complete = models.BooleanField(default=False, null=True, blank=True)
    transaction_id = models.CharField(max_length=200, null=True)
    coupon = models.ForeignKey(Coupon, on_delete=models.SET_NULL, null=True, blank=True)

    def __str__(self):
        return str(self.id)

    @property
    def shipping(self):
        shipping = False
        orderitems = self.orderitem_set.all()
        for i in orderitems:
            if i.product.digital == False:
                shipping = True
        return shipping

    @property
    def get_cart_total(self):
        orderitems = self.orderitem_set.all()
        total = sum([item.get_total for item in orderitems])
        return total

    @property
    def get_cart_items(self):
        orderitems = self.orderitem_set.all()
        total = sum([item.quantity for item in orderitems])
        return total

class OrderItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
    quantity = models.IntegerField(default=0, null=True, blank=True)
    date_added = models.DateTimeField(auto_now_add=True)

    @property
    def get_total(self):
        total = self.product.price * self.quantity
        return total

class ShippingAddress(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
    address = models.CharField(max_length=200, null=True)
    city = models.CharField(max_length=200, null=True)
    state = models.CharField(max_length=200, null=True)
    zipcode = models.CharField(max_length=200, null=True)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.address

utils.py

import json
from .models import *

def cookieCart(request):
    # Create empty cart for now for non-logged in user
    try:
        cart = json.loads(request.COOKIES['cart'])
    except:
        cart = {}
        print('CART:', cart)

    items = []
    order = {'get_cart_total': 0, 'get_cart_items': 0, 'shipping': False}
    cartItems = order['get_cart_items']

    for i in cart:
        # We use try block to prevent items in cart that may have been removed from causing error
        try:
            if (cart[i]['quantity'] > 0):  # items with negative quantity = lot of freebies
                cartItems += cart[i]['quantity']

                product = Product.objects.get(id=i)
                total = (product.price * cart[i]['quantity'])

                order['get_cart_total'] += total
                order['get_cart_items'] += cart[i]['quantity']

                item = {
                    'id': product.id,
                    'product': {'id': product.id, 'name': product.name, 'price': product.price,
                                'imageURL': product.imageURL}, 'quantity': cart[i]['quantity'],
                    'digital': product.digital, 'get_total': total,
                }
                items.append(item)

                if product.digital == False:
                    order['shipping'] = True
            else:
                cart[i]['quantity'] = -1 * cart[i]['quantity']
                product = Product.objects.get(id=i)
                product.price = -1 * product.price
                total = (product.price * cart[i]['quantity'])

                order['get_cart_total'] += total
                order['get_cart_items'] += cart[i]['quantity']

                item = {
                    'id': product.id,
                    'product': {'id': product.id, 'name': product.name, 'price': product.price,
                                'imageURL': product.imageURL}, 'quantity': cart[i]['quantity'],
                    'digital': product.digital, 'get_total': total,
                }
                items.append(item)

                if product.digital == False:
                    order['shipping'] = True
        except:
            pass

    return {'cartItems': cartItems, 'order': order, 'items': items}

def cartData(request):
    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
        items = order.orderitem_set.all()
        cartItems = order.get_cart_items
    else:
        cookieData = cookieCart(request)
        cartItems = cookieData['cartItems']
        order = cookieData['order']
        items = cookieData['items']

    return {'cartItems': cartItems, 'order': order, 'items': items}

def apply_coupon(order, coupon_code):
    coupon = Coupon.objects.get(code=coupon_code)
    if coupon and coupon.valid_until is None or coupon.valid_until >= timezone.now():
        order.coupon = coupon
        order.save()
        return True
    return False

def guestOrder(request, data):
    name = data['form']['name']
    email = data['form']['email']

    cookieData = cookieCart(request)
    items = cookieData['items']

    customer, created = Customer.objects.get_or_create(
        email=email,
    )
    customer.name = name
    customer.save()

    order = Order.objects.create(
        customer=customer,
        complete=False,
    )

    for item in items:
        product = Product.objects.get(id=item['id'])
        orderItem = OrderItem.objects.create(
            product=product,
            order=order,
            quantity=(item['quantity'] if item['quantity'] > 0 else -1 * item['quantity']),
            # negative quantity = freebies
        )
    return customer, order


来源: stackexchange

问:
How can I open jupyter notebook from Anaconda Prompt? I'm having issues with it
I'm trying to open jupyter notebook, but it shows me this issue:
Unable to create process using 'C:\Users\AREA 51.conda\envs\python_course\python.exe "C:\Users\AREA 51.conda\envs\python_course\Scripts\jupyter-script.py" notebook'

I activated a new environment named "python_course" and then I installed jupyter notebook using this command: "conda install jupyter notebook", after  that I tried opening it using "jupyter notebook".
I tried running the prompt as administrator, but it didn't work.

ContentLicense: CC BY-SA 4.0


问:
ERROR Error: NG0900: Error trying to diff 'DataSource is not valid. Please check you Datasource to proceed.'. Only arrays and iterables are allowed
I'm trying to pull my data from database. but I'm getting this error in console. What should I do in this situation?

service.ts

```<code>  getToken(){
    return "82561747775276843117"
    // return localStorage.getItem('token')
  }

  getCurrentUserId() {
    // return localStorage.getItem('userId')
    return "50085825682871846345"
  }

  getDatas() {
    const body = {
      Token: this.getToken(),
      DataStoreId: '54545651247771316477 ',
      Operation: 'read',
      Encrypted: 1951,
      Data: 'select * from "postgres".public.quest',
    };
    return this.http.post(baseUrl + 'Application/DataOps', body).pipe(
      map((response: any) => {
        return response.message;
      })
    );
  }
</code>```

and main.ts:

```<code>questArray:Quest[]=[]
.
.
.

getQuest(){
  this.connect.getDatas().subscribe(res=>{
    this.questArray=res

  })
</code>```

and this is my error:
enter image description here

Line 37 is the code in the ts file I wrote above.
Line 27 is the part where I call this function in ngOnInit.

Body:
I'm trying to pull my data from database. but I'm getting this error in console. What should I do in this situation?

service.ts

  getToken(){
    return "82561747775276843117"
    // return localStorage.getItem('token')
  }

  getCurrentUserId() {
    // return localStorage.getItem('userId')
    return "50085825682871846345"
  }

  getDatas() {
    const body = {
      Token: this.getToken(),
      DataStoreId: '54545651247771316477 ',
      Operation: 'read',
      Encrypted: 1951,
      Data: 'select * from "postgres".public.quest',
    };
    return this.http.post(baseUrl + 'Application/DataOps', body).pipe(
      map((response: any) => {
        return response.message;
      })
    );
  }

and main.ts:

questArray:Quest[]=[]
.
.
.

getQuest(){
  this.connect.getDatas().subscribe(res=>{
    this.questArray=res

  })

and this is my error:
enter image description here

Line 37 is the code in the ts file I wrote above.
Line 27 is the part where I call this function in ngOnInit.


问:
Is there anyway to make the following code more efficient and easier to read?
I have two lists, rawmetadata and TPMMetadata , each list contains multiple data frames. Now I'm making new vectors,Response and RECIST, based on the values of each data frame in each list. Consider this code:

```<code>Response = c(rawmetadata[[1]]$Benefit,
              TPMMetadata[[1]]$Benefit,
              rawmetadata[[2]]$Benefit,
              rawmetadata[[3]]$Benefit,
              TPMMetadata[[2]]$Benefit,
              rawmetadata[[4]]$Benefit,
              rawmetadata[[5]]$Benefit,
              TPMMetadata[[3]]$Benefit,
              TPMMetadata[[4]]$Benefit,
              TPMMetadata[[5]]$Benefit,
              rawmetadata[[6]]$Benefit,
              rawmetadata[[7]]$Benefit,
              rawmetadata[[8]]$Benefit,
              TPMMetadata[[6]]$Benefit,
              TPMMetadata[[7]]$Benefit,
              TPMMetadata[[8]]$Benefit,
              rawmetadata[[9]]$Benefit)

RECIST <- c(rawmetadata[[1]]$recist,
            TPMMetadata[[1]]$recist,
            rawmetadata[[2]]$recist,
            rawmetadata[[3]]$recist,
            TPMMetadata[[2]]$recist,
            rawmetadata[[4]]$recist,
            rawmetadata[[5]]$recist,
            TPMMetadata[[3]]$recist,
            TPMMetadata[[4]]$recist,
            TPMMetadata[[5]]$recist,
            rawmetadata[[6]]$recist,
            rawmetadata[[7]]$recist,
            rawmetadata[[8]]$recist,
            TPMMetadata[[6]]$recist,
            TPMMetadata[[7]]$recist,
            TPMMetadata[[8]]$recist,
            rawmetadata[[9]]$recist)
</code>```

The order that you see here, is important. As you see the order of the lists used in making both vectors is exactly the same. I have also this vector, samples, that was made also with two different lists, scoresraw and scorestpm, like this:

```<code>samples <- c(colnames(scoresraw[[1]]),
             colnames(scorestpm[[1]]),
             colnames(scoresraw[[2]]),
             colnames(scoresraw[[3]]),
             colnames(scorestpm[[2]]),
             colnames(scoresraw[[4]]),
             colnames(scoresraw[[5]]),
             colnames(scorestpm[[3]]),
             colnames(scorestpm[[4]]),
             colnames(scorestpm[[5]]),
             colnames(scoresraw[[6]]),
             colnames(scoresraw[[7]]),
             colnames(scoresraw[[8]]),
             colnames(scorestpm[[6]]),
             colnames(scorestpm[[7]]),
             colnames(scorestpm[[8]]),
             colnames(scoresraw[[9]]))
</code>```

The order for samples is also just like the order making Response and RECIST. The order of the "raw" lists and the "TPM" lists is exactly the same and they should stay that way.

Is there any way to make this process easier and shorter? I have more code blocks like this and it's taking a lot of space. Thanks!

Body:
I have two lists, rawmetadata and TPMMetadata , each list contains multiple data frames. Now I'm making new vectors,Response and RECIST, based on the values of each data frame in each list. Consider this code:

Response = c(rawmetadata[[1]]$Benefit,
              TPMMetadata[[1]]$Benefit,
              rawmetadata[[2]]$Benefit,
              rawmetadata[[3]]$Benefit,
              TPMMetadata[[2]]$Benefit,
              rawmetadata[[4]]$Benefit,
              rawmetadata[[5]]$Benefit,
              TPMMetadata[[3]]$Benefit,
              TPMMetadata[[4]]$Benefit,
              TPMMetadata[[5]]$Benefit,
              rawmetadata[[6]]$Benefit,
              rawmetadata[[7]]$Benefit,
              rawmetadata[[8]]$Benefit,
              TPMMetadata[[6]]$Benefit,
              TPMMetadata[[7]]$Benefit,
              TPMMetadata[[8]]$Benefit,
              rawmetadata[[9]]$Benefit)

RECIST <- c(rawmetadata[[1]]$recist,
            TPMMetadata[[1]]$recist,
            rawmetadata[[2]]$recist,
            rawmetadata[[3]]$recist,
            TPMMetadata[[2]]$recist,
            rawmetadata[[4]]$recist,
            rawmetadata[[5]]$recist,
            TPMMetadata[[3]]$recist,
            TPMMetadata[[4]]$recist,
            TPMMetadata[[5]]$recist,
            rawmetadata[[6]]$recist,
            rawmetadata[[7]]$recist,
            rawmetadata[[8]]$recist,
            TPMMetadata[[6]]$recist,
            TPMMetadata[[7]]$recist,
            TPMMetadata[[8]]$recist,
            rawmetadata[[9]]$recist)

The order that you see here, is important. As you see the order of the lists used in making both vectors is exactly the same. I have also this vector, samples, that was made also with two different lists, scoresraw and scorestpm, like this:

samples <- c(colnames(scoresraw[[1]]),
             colnames(scorestpm[[1]]),
             colnames(scoresraw[[2]]),
             colnames(scoresraw[[3]]),
             colnames(scorestpm[[2]]),
             colnames(scoresraw[[4]]),
             colnames(scoresraw[[5]]),
             colnames(scorestpm[[3]]),
             colnames(scorestpm[[4]]),
             colnames(scorestpm[[5]]),
             colnames(scoresraw[[6]]),
             colnames(scoresraw[[7]]),
             colnames(scoresraw[[8]]),
             colnames(scorestpm[[6]]),
             colnames(scorestpm[[7]]),
             colnames(scorestpm[[8]]),
             colnames(scoresraw[[9]]))

The order for samples is also just like the order making Response and RECIST. The order of the "raw" lists and the "TPM" lists is exactly the same and they should stay that way.

Is there any way to make this process easier and shorter? I have more code blocks like this and it's taking a lot of space. Thanks!


问:
Why doesn't my text not scale down in android studio when using code to scale text?
I am trying to create a calculator and I want to scale the input and output for my calculator, I have added the following text to my xml code to solve this problem.

```<code>android:scaleX="1.0"
        android:scaleY="1.0"
        android:scaleType="fitXY"
</code>```

For some reason the input and output of the numbers and symbols won't scale down to the screen size, I have run my app on different screen sizes but it won't scale. I don't understand why this doesn't work as I have tried this on a different app and it works (I scaled an image on the other app).
How do I fix this problem?

The following code is the full code for my input and output section in my activity_main.xml for my calculator app, if it is of any help.

```<code>?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="10"
    tools:context=".MainActivity"
    android:scaleX="1.0"
    android:scaleY="1.0"
    android:scaleType="fitXY">

    <TextView
        android:id="@+id/tvsec"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#000"
        android:text=""
        android:textColor="#f6f6f6"
        android:textSize="23sp"
        android:textAlignment="viewEnd"
        android:padding="10dp"
        android:gravity="bottom"
        android:maxLines="1"
        android:layout_weight="1"
        android:scaleX="1.0"
        android:scaleY="1.0"
        android:scaleType="fitXY">

    </TextView>
    <TextView
        android:id="@+id/tvmain"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#000"
        android:text=""
        android:textColor="#fff"
        android:textSize="35sp"
        android:textAlignment="viewEnd"
        android:padding="10dp"
        android:gravity="bottom"
        android:maxLines="1"
        android:layout_weight="2"
        android:scaleX="1.0"
        android:scaleY="1.0"
        android:scaleType="fitXY">
    </TextView>
</LinearLayout>
</code>```

Please let me know if there is anything I can add regarding information in order to solve this problem.

Body:
I am trying to create a calculator and I want to scale the input and output for my calculator, I have added the following text to my xml code to solve this problem.

android:scaleX="1.0"
        android:scaleY="1.0"
        android:scaleType="fitXY"

For some reason the input and output of the numbers and symbols won't scale down to the screen size, I have run my app on different screen sizes but it won't scale. I don't understand why this doesn't work as I have tried this on a different app and it works (I scaled an image on the other app).
How do I fix this problem?

The following code is the full code for my input and output section in my activity_main.xml for my calculator app, if it is of any help.

?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="10"
    tools:context=".MainActivity"
    android:scaleX="1.0"
    android:scaleY="1.0"
    android:scaleType="fitXY">

    <TextView
        android:id="@+id/tvsec"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#000"
        android:text=""
        android:textColor="#f6f6f6"
        android:textSize="23sp"
        android:textAlignment="viewEnd"
        android:padding="10dp"
        android:gravity="bottom"
        android:maxLines="1"
        android:layout_weight="1"
        android:scaleX="1.0"
        android:scaleY="1.0"
        android:scaleType="fitXY">

    </TextView>
    <TextView
        android:id="@+id/tvmain"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#000"
        android:text=""
        android:textColor="#fff"
        android:textSize="35sp"
        android:textAlignment="viewEnd"
        android:padding="10dp"
        android:gravity="bottom"
        android:maxLines="1"
        android:layout_weight="2"
        android:scaleX="1.0"
        android:scaleY="1.0"
        android:scaleType="fitXY">
    </TextView>
</LinearLayout>

Please let me know if there is anything I can add regarding information in order to solve this problem.


问:
Crash in performBatchUpdates while updating collectionView
I have the following stack trace:

```
Last Exception Backtrace:
0   CoreFoundation                  0x1d2bbde88 __exceptionPreprocess + 164 (NSException.m:202)
1   libobjc.A.dylib                 0x1cbef78d8 objc_exception_throw + 60 (objc-exception.mm:356)
2   Foundation                      0x1cd4e5b4c -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 188 (NSException.m:242)
3   UIKitCore                       0x1d5082998 -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:animator:collectionViewAnimator:] + 3964 (UICollectionView.m:9492)
4   UIKitCore                       0x1d4fe17bc -[UICollectionView _performBatchUpdates:completion:invalidationContext:tentativelyForReordering:animator:animationHandler:] + 520 (UICollectionView.m:11824)
5   FieldService                    0x1006f2f0c specialized EditLatestNewsListViewController.controllerDidChangeContent(_:) + 276 (EditLatestNewsListViewController.swift:170)
6   FieldService                    0x1006f1920 EditLatestNewsListViewController.controllerDidChangeContent(_:) + 4 (:0)
7   FieldService                    0x1006f1920 @objc EditLatestNewsListViewController.controllerDidChangeContent(_:) + 48
8   CoreData                        0x1da3f0c04 __82-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]_block_invoke + 5576 (NSFetchedResultsController.m:2329)
9   CoreData                        0x1da4147e8 developerSubmittedBlockToNSManagedObjectContextPerform + 156 (NSManagedObjectContext.m:3964)
10  CoreData                        0x1da414338 -[NSManagedObjectContext performBlockAndWait:] + 208 (NSManagedObjectContext.m:4075)
11  CoreData                        0x1da3f2c98 -[NSFetchedResultsController _core_managedObjectContextDidChange:] + 124 (NSFetchedResultsController.m:2363)
12  CoreFoundation                  0x1d2beb404 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 (CFNotificationCenter.c:661)
13  CoreFoundation                  0x1d2c92474 ___CFXRegistrationPost_block_invoke + 88 (CFNotificationCenter.c:175)
14  CoreFoundation                  0x1d2c75724 _CFXRegistrationPost + 440 (CFNotificationCenter.c:201)
15  CoreFoundation                  0x1d2bffa08 _CFXNotificationPost + 704 (CFNotificationCenter.c:1193)
16  Foundation                      0x1ccffcffc -[NSNotificationCenter postNotificationName:object:userInfo:] + 92 (NSNotification.m:518)
17  CoreData                        0x1da40cd70 -[NSManagedObjectContext _createAndPostChangeNotification:deletions:updates:refreshes:deferrals:wasMerge:] + 1796 (NSManagedObjectContext.m:8631)
18  CoreData                        0x1da4214bc -[NSManagedObjectContext _processRecentChanges:] + 2508 (NSManagedObjectContext.m:7722)
19  CoreData                        0x1da40c518 -[NSManagedObjectContext _mergeChangesFromDidSaveDictionary:usingObjectIDs:] + 3576 (NSManagedObjectContext.m:3701)
20  CoreData                        0x1da4154d8 -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:] + 376 (NSManagedObjectContext.m:3730)
21  MagicalRecord                   0x10237f228 +[NSManagedObjectContext(MagicalRecord) rootContextDidSave:] + 448 (NSManagedObjectContext+MagicalRecord.m:236)
22  libdispatch.dylib               0x1da18c4b4 _dispatch_call_block_and_release + 32 (init.c:1518)
23  libdispatch.dylib               0x1da18dfdc _dispatch_client_callout + 20 (object.m:560)
24  libdispatch.dylib               0x1da19c7f4 _dispatch_main_queue_drain + 928 (inline_internal.h:2632)
25  libdispatch.dylib               0x1da19c444 _dispatch_main_queue_callback_4CF + 44 (queue.c:7887)
26  CoreFoundation                  0x1d2c4e6f8 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 (CFRunLoop.c:1780)
27  CoreFoundation                  0x1d2c30058 __CFRunLoopRun + 2036 (CFRunLoop.c:3147)
28  CoreFoundation                  0x1d2c34ed4 CFRunLoopRunSpecific + 612 (CFRunLoop.c:3418)
29  GraphicsServices                0x20bf36368 GSEventRunModal + 164 (GSEvent.c:2196)
30  UIKitCore                       0x1d51133d0 -[UIApplication _run] + 888 (UIApplication.m:3745)
31  UIKitCore                       0x1d5113034 UIApplicationMain + 340 (UIApplication.m:5335)
32  FieldService                    0x1005c3214 main + 68 (AppDelegate.swift:20)
33  dyld                            0x1f12a0960 start + 2528 (dyldMain.cpp:1170)

```

This is how it looks like controllerDidChangeContent:

```<code>private var collectionViewChanges = [[NSFetchedResultsChangeType: [IndexPath]]]()
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {

    collectionView?.performBatchUpdates({ [weak self] in

        if let collectionViewChanges = self?.collectionViewChanges {
            for collectionViewChange in collectionViewChanges {

                for (type, indexPaths) in collectionViewChange {

                    switch type {
                    case .insert:

                        self?.collectionView?.insertItems(at: indexPaths)

                    case .delete:

                        self?.collectionView?.deleteItems(at: indexPaths)

                    case .update:

                        self?.collectionView?.reloadItems(at: indexPaths)

                    case .move:

                        if let indexPath = indexPaths.first, let newIndexPath = indexPaths.last {
                            self?.collectionView?.moveItem(at: indexPath, to: newIndexPath)
                        }
                    }
                }
            }
        }
        delegate?.contentDidChange()
        updateView()
    })
}
</code>```

Body:
I have the following stack trace:

Last Exception Backtrace:
0   CoreFoundation                  0x1d2bbde88 __exceptionPreprocess + 164 (NSException.m:202)
1   libobjc.A.dylib                 0x1cbef78d8 objc_exception_throw + 60 (objc-exception.mm:356)
2   Foundation                      0x1cd4e5b4c -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 188 (NSException.m:242)
3   UIKitCore                       0x1d5082998 -[UICollectionView _endItemAnimationsWithInvalidationContext:tentativelyForReordering:animator:collectionViewAnimator:] + 3964 (UICollectionView.m:9492)
4   UIKitCore                       0x1d4fe17bc -[UICollectionView _performBatchUpdates:completion:invalidationContext:tentativelyForReordering:animator:animationHandler:] + 520 (UICollectionView.m:11824)
5   FieldService                    0x1006f2f0c specialized EditLatestNewsListViewController.controllerDidChangeContent(_:) + 276 (EditLatestNewsListViewController.swift:170)
6   FieldService                    0x1006f1920 EditLatestNewsListViewController.controllerDidChangeContent(_:) + 4 (:0)
7   FieldService                    0x1006f1920 @objc EditLatestNewsListViewController.controllerDidChangeContent(_:) + 48
8   CoreData                        0x1da3f0c04 __82-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]_block_invoke + 5576 (NSFetchedResultsController.m:2329)
9   CoreData                        0x1da4147e8 developerSubmittedBlockToNSManagedObjectContextPerform + 156 (NSManagedObjectContext.m:3964)
10  CoreData                        0x1da414338 -[NSManagedObjectContext performBlockAndWait:] + 208 (NSManagedObjectContext.m:4075)
11  CoreData                        0x1da3f2c98 -[NSFetchedResultsController _core_managedObjectContextDidChange:] + 124 (NSFetchedResultsController.m:2363)
12  CoreFoundation                  0x1d2beb404 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 (CFNotificationCenter.c:661)
13  CoreFoundation                  0x1d2c92474 ___CFXRegistrationPost_block_invoke + 88 (CFNotificationCenter.c:175)
14  CoreFoundation                  0x1d2c75724 _CFXRegistrationPost + 440 (CFNotificationCenter.c:201)
15  CoreFoundation                  0x1d2bffa08 _CFXNotificationPost + 704 (CFNotificationCenter.c:1193)
16  Foundation                      0x1ccffcffc -[NSNotificationCenter postNotificationName:object:userInfo:] + 92 (NSNotification.m:518)
17  CoreData                        0x1da40cd70 -[NSManagedObjectContext _createAndPostChangeNotification:deletions:updates:refreshes:deferrals:wasMerge:] + 1796 (NSManagedObjectContext.m:8631)
18  CoreData                        0x1da4214bc -[NSManagedObjectContext _processRecentChanges:] + 2508 (NSManagedObjectContext.m:7722)
19  CoreData                        0x1da40c518 -[NSManagedObjectContext _mergeChangesFromDidSaveDictionary:usingObjectIDs:] + 3576 (NSManagedObjectContext.m:3701)
20  CoreData                        0x1da4154d8 -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:] + 376 (NSManagedObjectContext.m:3730)
21  MagicalRecord                   0x10237f228 +[NSManagedObjectContext(MagicalRecord) rootContextDidSave:] + 448 (NSManagedObjectContext+MagicalRecord.m:236)
22  libdispatch.dylib               0x1da18c4b4 _dispatch_call_block_and_release + 32 (init.c:1518)
23  libdispatch.dylib               0x1da18dfdc _dispatch_client_callout + 20 (object.m:560)
24  libdispatch.dylib               0x1da19c7f4 _dispatch_main_queue_drain + 928 (inline_internal.h:2632)
25  libdispatch.dylib               0x1da19c444 _dispatch_main_queue_callback_4CF + 44 (queue.c:7887)
26  CoreFoundation                  0x1d2c4e6f8 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 (CFRunLoop.c:1780)
27  CoreFoundation                  0x1d2c30058 __CFRunLoopRun + 2036 (CFRunLoop.c:3147)
28  CoreFoundation                  0x1d2c34ed4 CFRunLoopRunSpecific + 612 (CFRunLoop.c:3418)
29  GraphicsServices                0x20bf36368 GSEventRunModal + 164 (GSEvent.c:2196)
30  UIKitCore                       0x1d51133d0 -[UIApplication _run] + 888 (UIApplication.m:3745)
31  UIKitCore                       0x1d5113034 UIApplicationMain + 340 (UIApplication.m:5335)
32  FieldService                    0x1005c3214 main + 68 (AppDelegate.swift:20)
33  dyld                            0x1f12a0960 start + 2528 (dyldMain.cpp:1170)

This is how it looks like controllerDidChangeContent:

private var collectionViewChanges = [[NSFetchedResultsChangeType: [IndexPath]]]()
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {

    collectionView?.performBatchUpdates({ [weak self] in

        if let collectionViewChanges = self?.collectionViewChanges {
            for collectionViewChange in collectionViewChanges {

                for (type, indexPaths) in collectionViewChange {

                    switch type {
                    case .insert:

                        self?.collectionView?.insertItems(at: indexPaths)

                    case .delete:

                        self?.collectionView?.deleteItems(at: indexPaths)

                    case .update:

                        self?.collectionView?.reloadItems(at: indexPaths)

                    case .move:

                        if let indexPath = indexPaths.first, let newIndexPath = indexPaths.last {
                            self?.collectionView?.moveItem(at: indexPath, to: newIndexPath)
                        }
                    }
                }
            }
        }
        delegate?.contentDidChange()
        updateView()
    })
}


问:
KeyError: 'No input element with the name None', Scrapy, WikiHow
Below is my source code, I am getting -  KeyError: 'No input element with the name None' error.

```<code>import re
import json
from loginform import fill_login_form

class wikihowSpider(scrapy.Spider):

    name = "wikihow"
    start_urls = ['http://www.wikihow.com/Category:Arts-and-Entertainment']
    login_url = 'https://www.wikihow.com/Main-Page#wh-dialog-login'

    def start_requests(self):
        yield scrapy.Request(self.login_url, self.parse_login)

    def parse_login(self, response):
        print('Here')
        data, url, method = fill_login_form(response.url, response.body,
                                        'username', 'password')
        return scrapy.FormRequest(url, formdata=dict(data),
                              method=method, callback=self.parse_main)
   def parse_main(self, response):
       # crawl

</code>```

My use-case is to log-in and then crawl given a list of starting urls.

I also tried using versions of examples mentioned here but kept getting an error like  Ignoring response <404 https://www.wikihow.com/wikiHowTo?search=&wpName=username&wpPassword=password&wpRemember=1&wploginattempt=Log+in>: HTTP status code is not handled or not allowed errors.  Any help would be appreciated!

Body:
Below is my source code, I am getting -  KeyError: 'No input element with the name None' error.

import re
import json
from loginform import fill_login_form

class wikihowSpider(scrapy.Spider):

    name = "wikihow"
    start_urls = ['http://www.wikihow.com/Category:Arts-and-Entertainment']
    login_url = 'https://www.wikihow.com/Main-Page#wh-dialog-login'

    def start_requests(self):
        yield scrapy.Request(self.login_url, self.parse_login)

    def parse_login(self, response):
        print('Here')
        data, url, method = fill_login_form(response.url, response.body,
                                        'username', 'password')
        return scrapy.FormRequest(url, formdata=dict(data),
                              method=method, callback=self.parse_main)
   def parse_main(self, response):
       # crawl

My use-case is to log-in and then crawl given a list of starting urls.

I also tried using versions of examples mentioned here but kept getting an error like  Ignoring response <404 https://www.wikihow.com/wikiHowTo?search=&wpName=username&wpPassword=password&wpRemember=1&wploginattempt=Log+in>: HTTP status code is not handled or not allowed errors.  Any help would be appreciated!


问:
Calendar Table in Tableau
I am trying to replicate in Tableau the following data model that I have in PowerBi:

Stores Table: It has the name of each store, its characteristics and a key that connects to the Sales Table and the budget table.

Sales: It has the date, sales and key that coonects to Stores Table.

Budget: It has the date, budget per day and key that coonects to Stores Table.

Calendar: It has the date in a period of time.

The logic in this model is the next one, compare Budget v/s Sales for every day and for each kind of Stores. Calendar table filter days or date for both tables.

In Tableau I make the following connection, where only the information from the sales table is filtered by Calendar table

The idea is to connect both tables as in power bi, is this possible?

Title: Calendar Table in Tableau


问:
MYSQL client issue - Having an access denied issue connecting via Bash Script (WSL2-Ubantu to a localhost windows MySQL DB 8.0 instance
I seem to be having an issue when running a bash script in windows WSL2 / Ubantu, but have no issue if I run the mysql command line with the same params.

This is a fairly straight forward script, albeit , I am new to bash scripting.

```<code>
#!/bin/bash
    PROPERTY_FILE="MySQLDB_glenn.properties"
    SCRIPTS_DIR="/home/glenn/scripts/"
    echo $SCRIPTS_DIR$PROPERTY_FILE
    WSL_HOST_IP=$(ipconfig.exe | awk '/WSL/ {getline; getline; getline; getline; print substr($14,   1, length($14)-1)}')
    ALT_WSL_HOST=$WSL_HOST_IP

    function atestfunction()
    {

       myTest=$(echo "This is a test")
       echo $myTest
    }
     function getProperty()
    {
     PROP_KEY=$1
     PROP_VALUE=$(cat $SCRIPTS_DIR$PROPERTY_FILE | grep $PROP_KEY | cut -d'=' -f2)
     echo $PROP_VALUE
    }

    echo "# Reading properties from $PROPERTY_FILE = " $SCRIPTS_DIR$PROPERTY_FILE
    DB_USER=$(getProperty "db.username")
    DB_PASS=$(getProperty "db.password")
    DB_HOST=$(getProperty "db.hostname")
    DB_DEFAULT=$(getProperty "db.defaultdb")

    echo $DB_USER
    echo $DB_PASS
    echo $DB_HOST
    echo $DB_DEFAULT
    echo $ALT_WSL_HOST

    echo "Selecting from DB " $DB_DEFAULT

    mysql -u$DB_USER -p$DB_PASS -h$ALT_WSL_HOST $DB_DEFAULT -e "use test1; select * from products;"

</code>```
```<code>I setup two versions of the account user , granting it all and with the ability to access via localhost and the second account via 172.0.0.0/255.0.0.0 to handle the fact that WSL comes up with different addresses on reboot.
</code>```

the variable $ALT_WSL_HOST value is 172.25.208.1 (as I debug it as I type this)
In the Bash script debugger (VS Code) or while running the script ./simpleDBselect.sh, i get
ERROR 1045 (28000): Access denied for user 'wsl_root
'@'172.25.220.8' (using password: YES)

The same mysql command in the same session (i just invoked it in the Terminal Tab of VS Code) or quitting VS code , I get:
mysql -uwsl_root -pxxx-xxxxx -h172.25.208.1 test1 -e "use test1; select * from products;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+-----------+----------+-------------+---------------+---------+-------------+-----------+-------------+
| productID | widgetid | productName | productNumber | color   | inhouseCost | listPrice | productSize |
+-----------+----------+-------------+---------------+---------+-------------+-----------+-------------+
|         1 |      101 | Widget1     | s1001         | Yellow  |       25.00 |     40.00 | medium      |
|         2 |      102 | Widget2     | s1002         | Black   |       27.00 |     45.00 | small       |
|         3 |      103 | Widget3     | s1003         | Black   |       28.00 |     40.00 | medium      |
|         4 |      104 | Widget4     | s1004         | Red     |       21.00 |     34.00 | small       |
|         5 |      105 | Widget5     | s1005         | Green   |       15.00 |     26.00 | large       |
|         6 |      106 | Widget6     | s1006         | Magenta |       40.00 |     75.00 | large       |
|         7 |      107 | Widget7     | s1007         | Orange  |       50.00 |     85.00 | medium      |
|         8 |      108 | Widget8     | s1008         | Blue    |       39.00 |     55.00 | small       |
|         9 |      109 | Widget9     | s1009         | Gold    |      189.00 |    300.00 | large       |
+-----------+----------+-------------+---------------+---------+-------------+-----------+-------------+

Does anyone know what I might be missing. I have read loads of documentation and think I have the DB accounts setup correctly for the variable hosts. Note,I have also tried '%' as is the default wildcard . Should I just install MySQL in the ubantu running in WSL as opposed to the windows install. Also note that I am cognizant that WSL running its own virtual ip address , hence why i'm using WSL_HOST_IP=$(ipconfig.exe | awk '/WSL/ {getline; getline; getline; getline; print substr($14,   1, length($14)-1)}').

Any help would be appreciated as I'm at my feeble wits end :)

Best Regards,
Glenn Firester

see above description for my attempts, but wsl_root has DBA and all grants to the tables in db test1

Body:
I seem to be having an issue when running a bash script in windows WSL2 / Ubantu, but have no issue if I run the mysql command line with the same params.

This is a fairly straight forward script, albeit , I am new to bash scripting.

#!/bin/bash
    PROPERTY_FILE="MySQLDB_glenn.properties"
    SCRIPTS_DIR="/home/glenn/scripts/"
    echo $SCRIPTS_DIR$PROPERTY_FILE
    WSL_HOST_IP=$(ipconfig.exe | awk '/WSL/ {getline; getline; getline; getline; print substr($14,   1, length($14)-1)}')
    ALT_WSL_HOST=$WSL_HOST_IP

    function atestfunction()
    {

       myTest=$(echo "This is a test")
       echo $myTest
    }
     function getProperty()
    {
     PROP_KEY=$1
     PROP_VALUE=$(cat $SCRIPTS_DIR$PROPERTY_FILE | grep $PROP_KEY | cut -d'=' -f2)
     echo $PROP_VALUE
    }

    echo "# Reading properties from $PROPERTY_FILE = " $SCRIPTS_DIR$PROPERTY_FILE
    DB_USER=$(getProperty "db.username")
    DB_PASS=$(getProperty "db.password")
    DB_HOST=$(getProperty "db.hostname")
    DB_DEFAULT=$(getProperty "db.defaultdb")

    echo $DB_USER
    echo $DB_PASS
    echo $DB_HOST
    echo $DB_DEFAULT
    echo $ALT_WSL_HOST

    echo "Selecting from DB " $DB_DEFAULT

    mysql -u$DB_USER -p$DB_PASS -h$ALT_WSL_HOST $DB_DEFAULT -e "use test1; select * from products;"

I setup two versions of the account user , granting it all and with the ability to access via localhost and the second account via 172.0.0.0/255.0.0.0 to handle the fact that WSL comes up with different addresses on reboot.

the variable $ALT_WSL_HOST value is 172.25.208.1 (as I debug it as I type this)
In the Bash script debugger (VS Code) or while running the script ./simpleDBselect.sh, i get
ERROR 1045 (28000): Access denied for user 'wsl_root
'@'172.25.220.8' (using password: YES)

The same mysql command in the same session (i just invoked it in the Terminal Tab of VS Code) or quitting VS code , I get:
mysql -uwsl_root -pxxx-xxxxx -h172.25.208.1 test1 -e "use test1; select * from products;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+-----------+----------+-------------+---------------+---------+-------------+-----------+-------------+
| productID | widgetid | productName | productNumber | color   | inhouseCost | listPrice | productSize |
+-----------+----------+-------------+---------------+---------+-------------+-----------+-------------+
|         1 |      101 | Widget1     | s1001         | Yellow  |       25.00 |     40.00 | medium      |
|         2 |      102 | Widget2     | s1002         | Black   |       27.00 |     45.00 | small       |
|         3 |      103 | Widget3     | s1003         | Black   |       28.00 |     40.00 | medium      |
|         4 |      104 | Widget4     | s1004         | Red     |       21.00 |     34.00 | small       |
|         5 |      105 | Widget5     | s1005         | Green   |       15.00 |     26.00 | large       |
|         6 |      106 | Widget6     | s1006         | Magenta |       40.00 |     75.00 | large       |
|         7 |      107 | Widget7     | s1007         | Orange  |       50.00 |     85.00 | medium      |
|         8 |      108 | Widget8     | s1008         | Blue    |       39.00 |     55.00 | small       |
|         9 |      109 | Widget9     | s1009         | Gold    |      189.00 |    300.00 | large       |
+-----------+----------+-------------+---------------+---------+-------------+-----------+-------------+

Does anyone know what I might be missing. I have read loads of documentation and think I have the DB accounts setup correctly for the variable hosts. Note,I have also tried '%' as is the default wildcard . Should I just install MySQL in the ubantu running in WSL as opposed to the windows install. Also note that I am cognizant that WSL running its own virtual ip address , hence why i'm using WSL_HOST_IP=$(ipconfig.exe | awk '/WSL/ {getline; getline; getline; getline; print substr($14,   1, length($14)-1)}').

Any help would be appreciated as I'm at my feeble wits end :)

Best Regards,
Glenn Firester

see above description for my attempts, but wsl_root has DBA and all grants to the tables in db test1


问:
Replace an image file by another one using React/JavaScript?
Every user have a ownership of one item.
Ex: I'm the user that have the ownership of item number 3, my home page will have the 3.gif that is stored at /item folder, showing my item.

I want to make a button where people can click to upgrade their item, changing the image. But I don't want to change the source path of the file, I want to replace the image file by an file that is stored in another folder called itemUpgrades.

I have an folder with images files like that
item/1.gif
item/2.gif
item/3.gif
...

I want to replace the image file by an file that is stored in another folder called itemUpgrades.
itemUpgrades/1.gif
itemUpgrades/2.gif
itemUpgrades/3.gif

That way, after hit the "upgrade" button, the 3.gif from /item folder should be replaced by the 3.gif from /itemUpgrades folder. How can I do this?


问:
Is it possible to build CLSAG ring signatures on Secp256k1?
Is it possible to implement CLSAG ring signatures with SECP256k1? And would the implementation be very different from this (https://github.com/crate-crypto/CLSAG) Ristretto255 variant of the CLSAG ring signatures?

As I understand it, it doesn't matter what curve parameters I take? So theoretically I could also use a NIST curve? I would just have to swap the values (curve parameters)? Or the library, right? I would want to implement the whole thing in JavaScript using the Noble Libs.

Did I understand this right so far?

PS: I'm not an expert, I've only used crypto so far, but I want to take a deeper look now. Why do I want to take Secp256k1? This has no deeper reasons, is simply the most familiar to me and so far one of the best tested.


问:
I'm trying to get started in Kotlin Android and making an app that required write-read system based on JSON
So i found two methods that were suitable for simple reading, but as code became more complex "Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference" or "java.io.FileNotFoundException: 20210922: open failed: EROFS (Read-only file system)" appeared.

Here are two methods that i was trying to use.

```<code>private fun getJSONFromAssets(): String? {
        var json: String? = null
        val charset: Charset = Charsets.UTF_8
        try {
            val workerJSONFile = assets.open("users.json")
            val size = workerJSONFile.available()
            val buffer = ByteArray(size)
            workerJSONFile.read(buffer)
            workerJSONFile.close()
            json = String(buffer, charset)
        } catch (e: IOException) {
            e.printStackTrace()
            return null
        }
        return json
    }
</code>```

And

```<code>private fun getAdapter(): WorkerAdapter {
        val nullWorker = WorkerModel(0, "0", "0", false)
        val temp: MutableList<WorkerModel> = MutableList(1) { nullWorker }
        val nullWorkerList = Workers(temp)
        return try {
            val bReader: BufferedReader = File("workers.json").bufferedReader()
            val workers = Gson().fromJson(bReader.readText(), Workers::class.java)
            WorkerAdapter(this, workers.workers, this) { show -> showDeleteItemMenu(show) }
        } catch (e: IOException) {
            e.printStackTrace()
            WorkerAdapter(this, nullWorkerList.workers, this) { show -> showDeleteItemMenu(show) }
        }
    }
</code>```

Body:
So i found two methods that were suitable for simple reading, but as code became more complex "Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference" or "java.io.FileNotFoundException: 20210922: open failed: EROFS (Read-only file system)" appeared.

Here are two methods that i was trying to use.

private fun getJSONFromAssets(): String? {
        var json: String? = null
        val charset: Charset = Charsets.UTF_8
        try {
            val workerJSONFile = assets.open("users.json")
            val size = workerJSONFile.available()
            val buffer = ByteArray(size)
            workerJSONFile.read(buffer)
            workerJSONFile.close()
            json = String(buffer, charset)
        } catch (e: IOException) {
            e.printStackTrace()
            return null
        }
        return json
    }

And

private fun getAdapter(): WorkerAdapter {
        val nullWorker = WorkerModel(0, "0", "0", false)
        val temp: MutableList<WorkerModel> = MutableList(1) { nullWorker }
        val nullWorkerList = Workers(temp)
        return try {
            val bReader: BufferedReader = File("workers.json").bufferedReader()
            val workers = Gson().fromJson(bReader.readText(), Workers::class.java)
            WorkerAdapter(this, workers.workers, this) { show -> showDeleteItemMenu(show) }
        } catch (e: IOException) {
            e.printStackTrace()
            WorkerAdapter(this, nullWorkerList.workers, this) { show -> showDeleteItemMenu(show) }
        }
    }


问:
pywinauto save (permant) control identifiers to variable
I am trying to save control identifiers to a variable.
The reason is that: i use main_dlg.print_control_identifiers(filename="control_ids.text") but i am getting this error:

```<code>Traceback (most recent call last):
  File "run_tests.py", line 7, in <module>
    main_dlg.print_control_identifiers(filename="control_ids.text")
  File "C:\python\lib\site-packages\pywinauto\application.py", line 696, in prin
t_control_identifiers
    print_identifiers([this_ctrl, ], log_func=log_func)
  File "C:\python\lib\site-packages\pywinauto\application.py", line 685, in prin
t_identifiers
    print_identifiers(ctrl.children(), current_depth + 1, log_func)
  File "C:\python\lib\site-packages\pywinauto\application.py", line 681, in prin
t_identifiers
    log_func(output)
  File "C:\python\lib\site-packages\pywinauto\application.py", line 694, in log_
func
    log_file.write(str(msg) + os.linesep)
  File "C:\python\lib\codecs.py", line 721, in write
    return self.writer.write(data)
  File "C:\python\lib\codecs.py", line 377, in write
    data, consumed = self.encode(object, self.errors)
  File "C:\python\lib\encodings\cp1252.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_table)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 71-76: c
haracter maps to <undefined>
</code>```

because the program i am trying to control has greek characters inside.

So, i decided to save the control identifiers to a variable and then save it with the right encoding to a txt file.

A simple solution i thought is:

```<code>from pywinauto.application import Application
import os

app = Application(backend="uia").start("C:/python/Lib/site-packages/QtDesigner/designer.exe")
main_dlg = app.QtDesigner
main_dlg.wait('visible')
main_dlg.print_control_identifiers()
</code>```

and then:

```<code>python script_name.py > output.txt
</code>```

after that in output.txt file there are the control identifiers of the program (in this example QtDesigner).

Body:
I am trying to save control identifiers to a variable.
The reason is that: i use main_dlg.print_control_identifiers(filename="control_ids.text") but i am getting this error:

Traceback (most recent call last):
  File "run_tests.py", line 7, in <module>
    main_dlg.print_control_identifiers(filename="control_ids.text")
  File "C:\python\lib\site-packages\pywinauto\application.py", line 696, in prin
t_control_identifiers
    print_identifiers([this_ctrl, ], log_func=log_func)
  File "C:\python\lib\site-packages\pywinauto\application.py", line 685, in prin
t_identifiers
    print_identifiers(ctrl.children(), current_depth + 1, log_func)
  File "C:\python\lib\site-packages\pywinauto\application.py", line 681, in prin
t_identifiers
    log_func(output)
  File "C:\python\lib\site-packages\pywinauto\application.py", line 694, in log_
func
    log_file.write(str(msg) + os.linesep)
  File "C:\python\lib\codecs.py", line 721, in write
    return self.writer.write(data)
  File "C:\python\lib\codecs.py", line 377, in write
    data, consumed = self.encode(object, self.errors)
  File "C:\python\lib\encodings\cp1252.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_table)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 71-76: c
haracter maps to <undefined>

because the program i am trying to control has greek characters inside.

So, i decided to save the control identifiers to a variable and then save it with the right encoding to a txt file.

A simple solution i thought is:

from pywinauto.application import Application
import os

app = Application(backend="uia").start("C:/python/Lib/site-packages/QtDesigner/designer.exe")
main_dlg = app.QtDesigner
main_dlg.wait('visible')
main_dlg.print_control_identifiers()

and then:

python script_name.py > output.txt

after that in output.txt file there are the control identifiers of the program (in this example QtDesigner).


问:
log4php not logging multiple classes
How can I implement log4php in order to log multiple classes separately?
I have the following example for classes A and B:

```<code>    class A{
      private $log;
      private static $instance;
      public static function getInstance(): Db3
      {
        if (!self::$instance) {
            self::$instance = new self;
        }
        return self::$instance;
      }

      function __construct()
      {
         Logger::configure('path/to/log4php.xml');
         $this->log = Logger::getLogger(__CLASS__);
      }
    }
</code>```

and also class B:

```<code>    class B{
      private $log;
      private static $instance;
      public static function getInstance(): Db3
      {
        if (!self::$instance) {
            self::$instance = new self;
        }
        return self::$instance;
      }

      function __construct()
      {
         Logger::configure('path/to/log4php.xml');
         $this->log = Logger::getLogger(__CLASS__);
      }
    }
</code>```

This is the log4php.xml config:

```<code><configuration xmlns="http://logging.apache.org/log4php/">
    <appender name="A" class="LoggerAppenderDailyFile">
        <param name="file" value="/path/to/logs/%s.A.log" />
        <param name="datePattern" value="Y-m-d" />
        <layout class="LoggerLayoutPattern">
            <param name="conversionPattern" value="%date{Y-m-d H:i:s,u} %-15logger %-5level %msg%n" />
        </layout>
    </appender>
    <appender name="B" class="LoggerAppenderDailyFile">
        <param name="file" value="/path/to/logs/%s.B.log" />
        <param name="datePattern" value="Y-m-d" />
        <layout class="LoggerLayoutPattern">
            <param name="conversionPattern" value="%date{Y-m-d H:i:s,u} %-15logger %-5level %msg%n" />
        </layout>
    </appender>

    <logger name="A"><level value="DEBUG" /><appender_ref ref="A" /></logger>
    <logger name="B"><level value="DEBUG" /><appender_ref ref="B" /></logger>
</configuration>
</code>```

I need log4php to log class A and class B separately but for some reason it is not working if I do this:

```<code>$a=A::getInstance();
$a->test();
$b=B::getInstance();
$b->test();
</code>```

Everything gets logged in the same file, not in yyyy-mm-dd.A.log and B.log
test() only has this line: $this->log->info('this is a test') in both classes.

Title: log4php not logging multiple classes

Body:
How can I implement log4php in order to log multiple classes separately?
I have the following example for classes A and B:

    class A{
      private $log;
      private static $instance;
      public static function getInstance(): Db3
      {
        if (!self::$instance) {
            self::$instance = new self;
        }
        return self::$instance;
      }

      function __construct()
      {
         Logger::configure('path/to/log4php.xml');
         $this->log = Logger::getLogger(__CLASS__);
      }
    }

and also class B:

    class B{
      private $log;
      private static $instance;
      public static function getInstance(): Db3
      {
        if (!self::$instance) {
            self::$instance = new self;
        }
        return self::$instance;
      }

      function __construct()
      {
         Logger::configure('path/to/log4php.xml');
         $this->log = Logger::getLogger(__CLASS__);
      }
    }

This is the log4php.xml config:

<configuration xmlns="http://logging.apache.org/log4php/">
    <appender name="A" class="LoggerAppenderDailyFile">
        <param name="file" value="/path/to/logs/%s.A.log" />
        <param name="datePattern" value="Y-m-d" />
        <layout class="LoggerLayoutPattern">
            <param name="conversionPattern" value="%date{Y-m-d H:i:s,u} %-15logger %-5level %msg%n" />
        </layout>
    </appender>
    <appender name="B" class="LoggerAppenderDailyFile">
        <param name="file" value="/path/to/logs/%s.B.log" />
        <param name="datePattern" value="Y-m-d" />
        <layout class="LoggerLayoutPattern">
            <param name="conversionPattern" value="%date{Y-m-d H:i:s,u} %-15logger %-5level %msg%n" />
        </layout>
    </appender>

    <logger name="A"><level value="DEBUG" /><appender_ref ref="A" /></logger>
    <logger name="B"><level value="DEBUG" /><appender_ref ref="B" /></logger>
</configuration>

I need log4php to log class A and class B separately but for some reason it is not working if I do this:

$a=A::getInstance();
$a->test();
$b=B::getInstance();
$b->test();

Everything gets logged in the same file, not in yyyy-mm-dd.A.log and B.log
test() only has this line: $this->log->info('this is a test') in both classes.


问:
How to call a third party composer app in a Codeigniter Controller
I try to work with "https://github.com/FragLand/minestat", and tried to get the server status.

But I get the error: Class "MineStat" not found, so **how do I work exactly with third party components and add them to codeigniter so that I can use them in a controller
**

I tried to add the line

use MineStat;

and then I tried to work with it, so I created a function.

```<code>public function getServerStatus($ip) {
        $ms = new MineStat($ip);
        return $ms->is_online();
    }
</code>```

Body:
I try to work with "https://github.com/FragLand/minestat", and tried to get the server status.

But I get the error: Class "MineStat" not found, so **how do I work exactly with third party components and add them to codeigniter so that I can use them in a controller
**

I tried to add the line

use MineStat;

and then I tried to work with it, so I created a function.

public function getServerStatus($ip) {
        $ms = new MineStat($ip);
        return $ms->is_online();
    }


问:
What data type is this annotation specifying?
I'm in the process of writing and running functional tests for code written in TypeScript. My functional tests are in python, which is what I'm familiar with as far as syntax.

The service I am testing is written in typescript. I noticed this global property in the class.

```<code>readonly subnetMappings: Array<CfnFirewall.SubnetMappingProperty | cdk.IResolvable> | cdk.IResolvable;
</code>```

I am reading the cdk documentation here https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-networkfirewall.CfnFirewall.SubnetMappingProperty.html

After reading this I was thinking in my functional test I would write something like this -

```<code>subnet_mappings = [CfnFirewall.SubnetMappingProperty = {
  subnetId: 'subnetId',
}];
</code>```

Is this correct?

Body:
I'm in the process of writing and running functional tests for code written in TypeScript. My functional tests are in python, which is what I'm familiar with as far as syntax.

The service I am testing is written in typescript. I noticed this global property in the class.

readonly subnetMappings: Array<CfnFirewall.SubnetMappingProperty | cdk.IResolvable> | cdk.IResolvable;

I am reading the cdk documentation here https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-networkfirewall.CfnFirewall.SubnetMappingProperty.html

After reading this I was thinking in my functional test I would write something like this -

subnet_mappings = [CfnFirewall.SubnetMappingProperty = {
  subnetId: 'subnetId',
}];

Is this correct?


问:
Flink 1.15 toRetractStream conversion error: Don't support Legacy conversion for retract stream
I'm upgrading Flink 1.9 to 1.15.2 and am getting an error (see below) for my apps using Table API to Datastream API conversions (flink-table-api-scala-bridge).

Environment:
Flink: 1.15.2
Scala 2.12.2
EMR 6.9

Questions:
Can anyone provide context on what this error means?

I see toRetractStream is deprecated and toChangelogStream() is recommended. How can I convert a case class into a Schema (https://nightlies.apache.org/flink/flink-docs-release-1.15/api/java//org/apache/flink/table/api/bridge/java/StreamTableEnvironment.html#toChangelogStream-org.apache.flink.table.api.Table-org.apache.flink.table.api.Schema-)?

Code:

```<code>    val paymentSubscriptionsStream: DataStream[(Boolean, PaymentSubscriptions)] =
      sTableEnv
        .toRetractStream[PaymentSubscriptions](joinedStreams)
        .filter(x => x._1)
</code>```

Case Class:

```<code>case class PaymentSubscriptions(
  company_id: java.lang.Long,
  company_code: String,
  user_access_id: String,
  benevity_account_alias: String,
  subscription_id: java.lang.Long,
  subscription_amount: java.math.BigDecimal,
  subscription_name: String,
  transaction_reference_number: String,
  transaction_source: String,
  subscription_created_timestamp: String,
  date_key: java.lang.Long,
  exchange_rate_date: java.lang.Long,
  recipient: String,
  portfolio_id: java.lang.Long,
  pledge_site_pledge_id: String,
  match_cap: java.math.BigDecimal,
  match_opt_out: String,
  pledge_source: String,
  pledge_type: String,
  pledge_status: String,
  transaction_currency: String,
  exchange_rate_code: String,
  deactivated_flag: Int,
  ts: java.lang.Long
)
</code>```

Error:
The program finished with the following exception:

```<code>org.apache.flink.client.program.ProgramInvocationException: The main method caused an error: Don't support LEGACY('STRUCTURED_TYPE', 'ANY<scala.Tuple2, [encoded data, 6875 characters]>') conversion for the retract sink
    at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:372)
    at org.apache.flink.client.program.PackagedProgram.invokeInteractiveModeForExecution(PackagedProgram.java:222)
    at org.apache.flink.client.ClientUtils.executeProgram(ClientUtils.java:114)
    at org.apache.flink.client.cli.CliFrontend.executeProgram(CliFrontend.java:836)
    at org.apache.flink.client.cli.CliFrontend.run(CliFrontend.java:247)
    at org.apache.flink.client.cli.CliFrontend.parseAndRun(CliFrontend.java:1078)
    at org.apache.flink.client.cli.CliFrontend.lambda$main$10(CliFrontend.java:1156)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1878)
    at org.apache.flink.runtime.security.contexts.HadoopSecurityContext.runSecured(HadoopSecurityContext.java:41)
    at org.apache.flink.client.cli.CliFrontend.main(CliFrontend.java:1156)
Caused by: org.apache.flink.table.api.TableException: Don't support LEGACY('STRUCTURED_TYPE', 'ANY<scala.Tuple2, [encoded data, 6875 characters]>') conversion for the retract sink
    at org.apache.flink.table.planner.sinks.TableSinkUtils$.inferSinkPhysicalDataType(TableSinkUtils.scala:219)
    at org.apache.flink.table.planner.sinks.TableSinkUtils$.inferSinkPhysicalSchema(TableSinkUtils.scala:136)
    at org.apache.flink.table.planner.delegation.PlannerBase.translateToRel(PlannerBase.scala:280)
    at org.apache.flink.table.planner.delegation.PlannerBase.$anonfun$translate$1(PlannerBase.scala:185)
    at scala.collection.TraversableLike.$anonfun$map$1(TraversableLike.scala:233)
    at scala.collection.Iterator.foreach(Iterator.scala:937)
    at scala.collection.Iterator.foreach$(Iterator.scala:937)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1425)
    at scala.collection.IterableLike.foreach(IterableLike.scala:70)
    at scala.collection.IterableLike.foreach$(IterableLike.scala:69)
    at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
    at scala.collection.TraversableLike.map(TraversableLike.scala:233)
    at scala.collection.TraversableLike.map$(TraversableLike.scala:226)
    at scala.collection.AbstractTraversable.map(Traversable.scala:104)
    at org.apache.flink.table.planner.delegation.PlannerBase.translate(PlannerBase.scala:185)
    at org.apache.flink.table.api.bridge.internal.AbstractStreamTableEnvironmentImpl.toStreamInternal(AbstractStreamTableEnvironmentImpl.java:223)
    at org.apache.flink.table.api.bridge.scala.internal.StreamTableEnvironmentImpl.toRetractStream(StreamTableEnvironmentImpl.scala:222)
    at io.benevity.data.PaymentsDataService$.main(PaymentsDataService.scala:555)
    at io.benevity.data.PaymentsDataService.main(PaymentsDataService.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:355)
</code>```

Tried this and expected it to work as it did in Flink 1.9

```<code>val paymentSubscriptionsStream: DataStream[(Boolean, PaymentSubscriptions)] =
  sTableEnv
    .toRetractStream[PaymentSubscriptions](joinedStreams)
    .filter(x => x._1)
</code>```

However got the 'don't support... conversion in retract stream' error.

Body:
I'm upgrading Flink 1.9 to 1.15.2 and am getting an error (see below) for my apps using Table API to Datastream API conversions (flink-table-api-scala-bridge).

Environment:
Flink: 1.15.2
Scala 2.12.2
EMR 6.9

Questions:
Can anyone provide context on what this error means?

I see toRetractStream is deprecated and toChangelogStream() is recommended. How can I convert a case class into a Schema (https://nightlies.apache.org/flink/flink-docs-release-1.15/api/java//org/apache/flink/table/api/bridge/java/StreamTableEnvironment.html#toChangelogStream-org.apache.flink.table.api.Table-org.apache.flink.table.api.Schema-)?

Code:

    val paymentSubscriptionsStream: DataStream[(Boolean, PaymentSubscriptions)] =
      sTableEnv
        .toRetractStream[PaymentSubscriptions](joinedStreams)
        .filter(x => x._1)

Case Class:

case class PaymentSubscriptions(
  company_id: java.lang.Long,
  company_code: String,
  user_access_id: String,
  benevity_account_alias: String,
  subscription_id: java.lang.Long,
  subscription_amount: java.math.BigDecimal,
  subscription_name: String,
  transaction_reference_number: String,
  transaction_source: String,
  subscription_created_timestamp: String,
  date_key: java.lang.Long,
  exchange_rate_date: java.lang.Long,
  recipient: String,
  portfolio_id: java.lang.Long,
  pledge_site_pledge_id: String,
  match_cap: java.math.BigDecimal,
  match_opt_out: String,
  pledge_source: String,
  pledge_type: String,
  pledge_status: String,
  transaction_currency: String,
  exchange_rate_code: String,
  deactivated_flag: Int,
  ts: java.lang.Long
)

Error:
The program finished with the following exception:

org.apache.flink.client.program.ProgramInvocationException: The main method caused an error: Don't support LEGACY('STRUCTURED_TYPE', 'ANY<scala.Tuple2, [encoded data, 6875 characters]>') conversion for the retract sink
    at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:372)
    at org.apache.flink.client.program.PackagedProgram.invokeInteractiveModeForExecution(PackagedProgram.java:222)
    at org.apache.flink.client.ClientUtils.executeProgram(ClientUtils.java:114)
    at org.apache.flink.client.cli.CliFrontend.executeProgram(CliFrontend.java:836)
    at org.apache.flink.client.cli.CliFrontend.run(CliFrontend.java:247)
    at org.apache.flink.client.cli.CliFrontend.parseAndRun(CliFrontend.java:1078)
    at org.apache.flink.client.cli.CliFrontend.lambda$main$10(CliFrontend.java:1156)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1878)
    at org.apache.flink.runtime.security.contexts.HadoopSecurityContext.runSecured(HadoopSecurityContext.java:41)
    at org.apache.flink.client.cli.CliFrontend.main(CliFrontend.java:1156)
Caused by: org.apache.flink.table.api.TableException: Don't support LEGACY('STRUCTURED_TYPE', 'ANY<scala.Tuple2, [encoded data, 6875 characters]>') conversion for the retract sink
    at org.apache.flink.table.planner.sinks.TableSinkUtils$.inferSinkPhysicalDataType(TableSinkUtils.scala:219)
    at org.apache.flink.table.planner.sinks.TableSinkUtils$.inferSinkPhysicalSchema(TableSinkUtils.scala:136)
    at org.apache.flink.table.planner.delegation.PlannerBase.translateToRel(PlannerBase.scala:280)
    at org.apache.flink.table.planner.delegation.PlannerBase.$anonfun$translate$1(PlannerBase.scala:185)
    at scala.collection.TraversableLike.$anonfun$map$1(TraversableLike.scala:233)
    at scala.collection.Iterator.foreach(Iterator.scala:937)
    at scala.collection.Iterator.foreach$(Iterator.scala:937)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1425)
    at scala.collection.IterableLike.foreach(IterableLike.scala:70)
    at scala.collection.IterableLike.foreach$(IterableLike.scala:69)
    at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
    at scala.collection.TraversableLike.map(TraversableLike.scala:233)
    at scala.collection.TraversableLike.map$(TraversableLike.scala:226)
    at scala.collection.AbstractTraversable.map(Traversable.scala:104)
    at org.apache.flink.table.planner.delegation.PlannerBase.translate(PlannerBase.scala:185)
    at org.apache.flink.table.api.bridge.internal.AbstractStreamTableEnvironmentImpl.toStreamInternal(AbstractStreamTableEnvironmentImpl.java:223)
    at org.apache.flink.table.api.bridge.scala.internal.StreamTableEnvironmentImpl.toRetractStream(StreamTableEnvironmentImpl.scala:222)
    at io.benevity.data.PaymentsDataService$.main(PaymentsDataService.scala:555)
    at io.benevity.data.PaymentsDataService.main(PaymentsDataService.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:355)

Tried this and expected it to work as it did in Flink 1.9

val paymentSubscriptionsStream: DataStream[(Boolean, PaymentSubscriptions)] =
  sTableEnv
    .toRetractStream[PaymentSubscriptions](joinedStreams)
    .filter(x => x._1)

However got the 'don't support... conversion in retract stream' error.


问:
How do I make my bullets continuously move instead of stopping where I clicked?
My bullets do move in the direction of where I clicked which is great until it stops there and doesn't move any further.</p>
```<code>if ev.type == pygame.MOUSEBUTTONDOWN:
    mousePos=pygame.mouse.get_pos()
    bulletDestination.append(mousePos) #where I clicked
    bullet=[knightPos[0]+63,knightPos[1]+27,20,20] #Position of the center of my player
    bullets.append(bullet)

for i in range(0,len(bullets),1):
    angle3=math.atan2(bulletDestination[i][1]-bullets[i][1],bulletDestination[i][0]-bullets[i][0])
    bulletDeltax= math.cos(angle3)*bulletSpeed
    bulletDeltay= math.sin(angle3)*bulletSpeed
    bullets[i][0]+=(bulletDeltax)
    bullets[i][1]+=(bulletDeltay)
    pygame.draw.rect(mainSurface, rectColor3,bullets[i])
</code>```

Body:
My bullets do move in the direction of where I clicked which is great until it stops there and doesn't move any further.

if ev.type == pygame.MOUSEBUTTONDOWN:
    mousePos=pygame.mouse.get_pos()
    bulletDestination.append(mousePos) #where I clicked
    bullet=[knightPos[0]+63,knightPos[1]+27,20,20] #Position of the center of my player
    bullets.append(bullet)

for i in range(0,len(bullets),1):
    angle3=math.atan2(bulletDestination[i][1]-bullets[i][1],bulletDestination[i][0]-bullets[i][0])
    bulletDeltax= math.cos(angle3)*bulletSpeed
    bulletDeltay= math.sin(angle3)*bulletSpeed
    bullets[i][0]+=(bulletDeltax)
    bullets[i][1]+=(bulletDeltay)
    pygame.draw.rect(mainSurface, rectColor3,bullets[i])


问:
Head problems with NextJs
Hello how are you?  My problem is the following: I have a blog made with styled components and nextjs, server side rendering.

The problem I have is, that the Head tag (next/head) that I apply in my post pages, loads after the page (so I think)

What happens is that the post title (title, og:description) does not appear when I share the link (I need SEO optimized), my assumption is that it is being applied after page rendering as when I am in browser the page title appears (but it doesn't appear when I give a view-source)

how can i solve the problem?  how can i make sure that Head will be applied correctly?

I've applied a Head to _app.tsx, and I've also applied a few different Heads to other pages.  This Head that is in app.tsx works correctly, but not in other pages (the way I expected)

Title: Head problems with NextJs


问:
Can we stream data from Google Datastore into Pubsub?
I want to process the data inserted in Google Datastore in real time.

Is there any function available to stream datastore records into PubSub or a trigger on DataStore ?


问:
Android S Notification on click intent not working
i am building a flutter plugin in java that creates a media notification, and i am having a problem getting the notification click to bring the app to foreground, it used to work on previous android versions but not when testing it on S (31) as a target.

if found this section in the docs :

As of Android Build.VERSION_CODES.S, apps targeting API level Build.VERSION_CODES.S or higher won't be able to start activities while processing broadcast receivers or services in response to notification clicks. To launch an activity in those cases, provide a PendingIntent for the activity itself.

I would like to know if thi is the case or not, or if i need to check something else, here is the code i am using to create the intent i set in the notification builder :

private PendingIntent createContentIntent() {
        Intent openUI = new Intent(mContext, AudioplayerPlugin.class);
        openUI.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        return PendingIntent.getActivity(mContext, REQUEST_CODE, openUI,
                PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_CANCEL_CURRENT);
    }
```

AudioplayerPlugin is the plugins own name, the app itself is another activity.

Body:
i am building a flutter plugin in java that creates a media notification, and i am having a problem getting the notification click to bring the app to foreground, it used to work on previous android versions but not when testing it on S (31) as a target.

if found this section in the docs :

As of Android Build.VERSION_CODES.S, apps targeting API level Build.VERSION_CODES.S or higher won't be able to start activities while processing broadcast receivers or services in response to notification clicks. To launch an activity in those cases, provide a PendingIntent for the activity itself.

I would like to know if thi is the case or not, or if i need to check something else, here is the code i am using to create the intent i set in the notification builder :

private PendingIntent createContentIntent() {
        Intent openUI = new Intent(mContext, AudioplayerPlugin.class);
        openUI.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        return PendingIntent.getActivity(mContext, REQUEST_CODE, openUI,
                PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_CANCEL_CURRENT);
    }

AudioplayerPlugin is the plugins own name, the app itself is another activity.


问:
Best way to navigate modals collection parameter values
I have a String array like this

```<code>static availableOptions() {
    return [
      "Option 1",
      "Option 2",
      "Option 3",
    ];
  }
</code>```

and this one that relies on the pick from the first

```<code>static availableOthers(String option) {

switch (option) {
      case "Option 1":
      case "Option 2":
        return ["Other 1.1","Other 1.2"]
      case "Option 3":
        return ["Other 3.1","Other 3.2"]
      default:
    }
  }
</code>```

I'm trying to build a showModalBottomSheet widget to display the first list in the bottom, then onTap navigates to a list (still in the modal) and then the tap navigates to the third list (so then I can build an object with the 3 values).

I'm struggling to find the best way to do so without having too much code duplication.
I tried to create a modal like:

```<code>Future<dynamic> chooseOptions(BuildContext context) {
  return showModalBottomSheet(
    context: context,
    builder: (context) {
      return genericListBuilder(getAList());
    },
  );
}
</code>```

and add onTap function to the genericListBuilder (which just build a simple List.viewer) but at the end didnt work out very well as I couldn't get the information from the "tap"

Any suggestions or help would be really appreciated :)

Body:
I have a String array like this

static availableOptions() {
    return [
      "Option 1",
      "Option 2",
      "Option 3",
    ];
  }

and this one that relies on the pick from the first

static availableOthers(String option) {

switch (option) {
      case "Option 1":
      case "Option 2":
        return ["Other 1.1","Other 1.2"]
      case "Option 3":
        return ["Other 3.1","Other 3.2"]
      default:
    }
  }

I'm trying to build a showModalBottomSheet widget to display the first list in the bottom, then onTap navigates to a list (still in the modal) and then the tap navigates to the third list (so then I can build an object with the 3 values).

I'm struggling to find the best way to do so without having too much code duplication.
I tried to create a modal like:

Future<dynamic> chooseOptions(BuildContext context) {
  return showModalBottomSheet(
    context: context,
    builder: (context) {
      return genericListBuilder(getAList());
    },
  );
}

and add onTap function to the genericListBuilder (which just build a simple List.viewer) but at the end didnt work out very well as I couldn't get the information from the "tap"

Any suggestions or help would be really appreciated :)


问:
Using predefined (self designed) validation set for parameter optimization for one class svm
I am trying to execute a oneclass svm study in Python (Jupyter Notebook). But I am not able to use my predefined validation set to optimize the parameters of OneClassSVM in sklearn.GridSearch(). There is a solution for regular svm here: Using explicit (predefined) validation set for grid search with sklearn but the hyperopt mentioned there does not work for OneClassSVM.
As an example, we could redo analysis by introducing a validation set from here: https://www.kaggle.com/code/amarnayak/once-class-svm-to-detect-anomaly/notebook
My code after including the validation set for the example workflow so far:

```<code>import pandas as pd
from sklearn import svm
cc =  pd.read_csv("creditcard.csv")
#I observed a conflict in the name 'class'. Therefore, I have changed the name from class to category

cc= cc.rename(columns={'Class': 'Category'})
cc.Category.value_counts()
# For convinience, divide the dataframe cc based on two labels.

nor_obs = cc.loc[cc.Category==0]    #Data frame with normal observation
ano_obs = cc.loc[cc.Category==1]    #Data frame with anomalous observation

train_feature = nor_obs.loc[0:100000, :]. # train set
train_feature = train_feature.drop('Category', 1)
validation_feature = nor_obs.loc[100000:200000, :] # validation set
validation_feature = validation_feature.drop('Category', 1)

Y_1 = nor_obs.loc[200000:, 'Category']
Y_2 = ano_obs['Category']
X_test_1 = nor_obs.loc[200000:, :].drop('Category',1)
X_test_2 = ano_obs.drop('Category',1)
X_test = X_test_1.append(X_test_2) # test set
Y_1 = nor_obs.loc[200000:, 'Category']
Y_2 = ano_obs['Category']
Y_test= Y_1.append(Y_2) # test labels

# the one class svm model
oneclass = svm.OneClassSVM()
parameters = {'kernel':('linear', 'rbf'), 'gamma':[0.1,0.2, 0.3, 0.4, 0.5]}
clf = GridSearchCV() or just GridSearch() # need help here to use the validation_feature data set
clf.fit(train_feature)
## Need some scores too for the trained set
predictions = oneclass.predict(X_test)
</code>```

Is there a way I could use GridSearch to optimize the parameters using the validation_feature dataset?

Body:
I am trying to execute a oneclass svm study in Python (Jupyter Notebook). But I am not able to use my predefined validation set to optimize the parameters of OneClassSVM in sklearn.GridSearch(). There is a solution for regular svm here: Using explicit (predefined) validation set for grid search with sklearn but the hyperopt mentioned there does not work for OneClassSVM.
As an example, we could redo analysis by introducing a validation set from here: https://www.kaggle.com/code/amarnayak/once-class-svm-to-detect-anomaly/notebook
My code after including the validation set for the example workflow so far:

import pandas as pd
from sklearn import svm
cc =  pd.read_csv("creditcard.csv")
#I observed a conflict in the name 'class'. Therefore, I have changed the name from class to category

cc= cc.rename(columns={'Class': 'Category'})
cc.Category.value_counts()
# For convinience, divide the dataframe cc based on two labels.

nor_obs = cc.loc[cc.Category==0]    #Data frame with normal observation
ano_obs = cc.loc[cc.Category==1]    #Data frame with anomalous observation

train_feature = nor_obs.loc[0:100000, :]. # train set
train_feature = train_feature.drop('Category', 1)
validation_feature = nor_obs.loc[100000:200000, :] # validation set
validation_feature = validation_feature.drop('Category', 1)

Y_1 = nor_obs.loc[200000:, 'Category']
Y_2 = ano_obs['Category']
X_test_1 = nor_obs.loc[200000:, :].drop('Category',1)
X_test_2 = ano_obs.drop('Category',1)
X_test = X_test_1.append(X_test_2) # test set
Y_1 = nor_obs.loc[200000:, 'Category']
Y_2 = ano_obs['Category']
Y_test= Y_1.append(Y_2) # test labels

# the one class svm model
oneclass = svm.OneClassSVM()
parameters = {'kernel':('linear', 'rbf'), 'gamma':[0.1,0.2, 0.3, 0.4, 0.5]}
clf = GridSearchCV() or just GridSearch() # need help here to use the validation_feature data set
clf.fit(train_feature)
## Need some scores too for the trained set
predictions = oneclass.predict(X_test)

Is there a way I could use GridSearch to optimize the parameters using the validation_feature dataset?