问:
tried to build an image but I am keep getting this error. I clone many projects from public GitHub and have the same issue
[+] Building 14.6s (1/1) FINISHED

=> ERROR [internal] booting buildkit                                                                             14.6s

=> => pulling image moby/buildkit:buildx-stable-1                                                                12.7s

=> => creating container buildx_buildkit_default                                                                  1.9s

------

\> [internal] booting buildkit:

------

Error response from daemon: crun: creating cgroup directory `/sys/fs/cgroup/systemd/docker/buildx/libpod-86ba89f2fa100371f55620a538087d7e63a80541ae3b69b4919483f52ff616fa`: No such file or directory: OCI runtime attempted to invoke a command that was not found

`docker-compose` process finished with exit code 17

```<code># Docker Compose file Reference (https://docs.docker.com/compose/compose-file/)

version: '3'

# Define services
services:

  # App Service
  app:
    # Configuration for building the docker image for the service
    build:
      context: . # Use an image built from the specified dockerfile in the current directory.
      dockerfile: Dockerfile
    ports:
      - "8080:8080" # Forward the exposed port 8080 on the container to port 8080 on the host machine
    restart: unless-stopped
    depends_on:
      - redis # This service depends on redis. Start that first.
    environment: # Pass environment variables to the service
      REDIS_URL: redis:6379
    networks: # Networks to join (Services on the same network can communicate with each other using their name)
      - backend

  # Redis Service
  redis:
    image: "redis:alpine" # Use a public Redis image to build the redis service
    restart: unless-stopped
    networks:
      - backend

networks:
  backend:
</code>```

Body:
[+] Building 14.6s (1/1) FINISHED

=> ERROR [internal] booting buildkit                                                                             14.6s

=> => pulling image moby/buildkit:buildx-stable-1                                                                12.7s

=> => creating container buildx_buildkit_default                                                                  1.9s

------

\> [internal] booting buildkit:

------

Error response from daemon: crun: creating cgroup directory `/sys/fs/cgroup/systemd/docker/buildx/libpod-86ba89f2fa100371f55620a538087d7e63a80541ae3b69b4919483f52ff616fa`: No such file or directory: OCI runtime attempted to invoke a command that was not found

`docker-compose` process finished with exit code 17

# Docker Compose file Reference (https://docs.docker.com/compose/compose-file/)

version: '3'

# Define services
services:

  # App Service
  app:
    # Configuration for building the docker image for the service
    build:
      context: . # Use an image built from the specified dockerfile in the current directory.
      dockerfile: Dockerfile
    ports:
      - "8080:8080" # Forward the exposed port 8080 on the container to port 8080 on the host machine
    restart: unless-stopped
    depends_on:
      - redis # This service depends on redis. Start that first.
    environment: # Pass environment variables to the service
      REDIS_URL: redis:6379
    networks: # Networks to join (Services on the same network can communicate with each other using their name)
      - backend

  # Redis Service
  redis:
    image: "redis:alpine" # Use a public Redis image to build the redis service
    restart: unless-stopped
    networks:
      - backend

networks:
  backend:


来源: stackexchange

问:
Using Terraform 1.1.x, nested block inputs are not being iterated, but just once instead
I am working on automating some PagerDuty resources and first started on service dependencies. What I thought was a fairly straight forward solve has proven not to be true. When we create service dependencies, we want to be able to attach many dependencies either that the service USES or that the service is USED BY. With this in mind, I created the following resource block in Terraform.

```<code>resource "pagerduty_service_dependency" "this" {
  count = var.create_dependencies ? 1 : 0

  dynamic "dependency" {
    for_each = var.dependency
    content {
      type = dependency.value.type
      dynamic "dependent_service" {
        for_each = dependency.value.dependent_service
        content {
          id = dependent_service.value.id
          type = dependent_service.value.type
        }
      }
      dynamic "supporting_service" {
        for_each = dependency.value.supporting_service
        content {
          id = supporting_service.value.id
          type = supporting_service.value.type
        }
      }
    }
  }
}
</code>```

With this block as the variable

```<code>variable "dependency" {
  description = "value"
  type        = any
  default     = []
}

</code>```

And using this block for inputs (Using Terragrunt 0.36.x)

```<code>// Service Dependencies
create_dependencies = true
  dependency = [{
    type = "service"
    dependent_service = [
      {
        id = "DD4V04U"    // The service we are applying the dependency to.
        type = "service"
      }
    ]
    supporting_service = [
      {
        id = "BBF2LHB"    // The service that is being used by "DD4V04U"
        type = "service"
      },
      {
        id = "AAILTY1"    // Another service being used by "DD4V04U"
        type = "service"
      }
    ]
 }]

</code>```

The Terraform will apply the change but will only create the last dependency in the list(object). Subsequent additions to this list of objects result in all other dependencies before it being destroyed except for the last object in the list. This applies for both dependent and supporting service lists of objects.

The original path I went down in terms of providing inputs looked like this:

```<code>// Service Dependencies
  create_dependencies = true
  dependency = [
    {
      type = "service"
      dependent_service = [{
        id = "DD4V04U"
        type = "service"
      }],
      supporting_service = [{
        id = "BBF2LHB"
        type = "service"
      }]
    },
    {
      type = "service"
      dependent_service = [{
        id = "DD4V04U"
        type = "service"
      }],
      supporting_service = [{
        id = "BBF2LHB"
        type = "service"
      }]
    }
  ]
</code>```

...and the API reponds

```<code>╷
│ Error: Too many dependency blocks
│
│   on main.tf line 160, in resource "pagerduty_service_dependency" "this":
│  160:     content {
│
│ No more than 1 "dependency" blocks are allowed
╵

Which seems to go against what the API documentation states can be done.

Any insight here as to what I am missing would be highly appreciated. Thanks for looking.

Cheers
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working on automating some PagerDuty resources and first started on service dependencies. What I thought was a fairly straight forward solve has proven not to be true. When we create service dependencies, we want to be able to attach many dependencies either that the service USES or that the service is USED BY. With this in mind, I created the following resource block in Terraform.

resource "pagerduty_service_dependency" "this" {
  count = var.create_dependencies ? 1 : 0

  dynamic "dependency" {
    for_each = var.dependency
    content {
      type = dependency.value.type
      dynamic "dependent_service" {
        for_each = dependency.value.dependent_service
        content {
          id = dependent_service.value.id
          type = dependent_service.value.type
        }
      }
      dynamic "supporting_service" {
        for_each = dependency.value.supporting_service
        content {
          id = supporting_service.value.id
          type = supporting_service.value.type
        }
      }
    }
  }
}

With this block as the variable

variable "dependency" {
  description = "value"
  type        = any
  default     = []
}

And using this block for inputs (Using Terragrunt 0.36.x)

// Service Dependencies
create_dependencies = true
  dependency = [{
    type = "service"
    dependent_service = [
      {
        id = "DD4V04U"    // The service we are applying the dependency to.
        type = "service"
      }
    ]
    supporting_service = [
      {
        id = "BBF2LHB"    // The service that is being used by "DD4V04U"
        type = "service"
      },
      {
        id = "AAILTY1"    // Another service being used by "DD4V04U"
        type = "service"
      }
    ]
 }]

The Terraform will apply the change but will only create the last dependency in the list(object). Subsequent additions to this list of objects result in all other dependencies before it being destroyed except for the last object in the list. This applies for both dependent and supporting service lists of objects.

The original path I went down in terms of providing inputs looked like this:

// Service Dependencies
  create_dependencies = true
  dependency = [
    {
      type = "service"
      dependent_service = [{
        id = "DD4V04U"
        type = "service"
      }],
      supporting_service = [{
        id = "BBF2LHB"
        type = "service"
      }]
    },
    {
      type = "service"
      dependent_service = [{
        id = "DD4V04U"
        type = "service"
      }],
      supporting_service = [{
        id = "BBF2LHB"
        type = "service"
      }]
    }
  ]

...and the API reponds

╷
│ Error: Too many dependency blocks
│
│   on main.tf line 160, in resource "pagerduty_service_dependency" "this":
│  160:     content {
│
│ No more than 1 "dependency" blocks are allowed
╵

Which seems to go against what the API documentation states can be done.

Any insight here as to what I am missing would be highly appreciated. Thanks for looking.

Cheers


问:
Time format incorrect error when posting buy order Bitget API
Hello and thanks in advance for any help

I used this post (How to fix <Response [400]> error when making a request to the Bitget Futures Rest API in Python?) to get me well on my way to creating a post buy limit order for the Bitget API.

I keep getting this error though: {'code': '40409', 'msg': 'wrong format', 'requestTime': 1673551362880, 'data': None}

Looking up that error code suggests it's the time - I presume that used for the nonce - which is incorrect somehow?

For my post order I've tried using exactly the same format as the very useful answer provided by Tariq - https://stackoverflow.com/users/12907359/tarique in the above post - (Thanks Tariq!) ...therefore, effectively the only things that change from his code (which works for me), is the fact that mine a POST rather than a GET, and the 'query' content is different.

I'm posting below Tariq's code which works and my own as well where I'm getting the error. Any ideas very welcome, thanks!

I have commented where appropriate to highlight Tariq's original code and where I have created similar functions of my own.

```<code>import hashlib
import hmac
import base64
import requests
import time
import json

api_passphrase = "your secret"
api_key = "api key"
api_sec = "api secret"
api_url = "https://api.bitget.com"

#symbol = "BTCUSDT_UMCBL" # this is futures
symbol = 'BTC/USDT' # this is spot - I've added this here

def parse_params_to_str(params):
    url = '?'
    for key, value in params.items():
        url = url + str(key) + '=' + str(value) + '&'

    return url[0:-1]

def get_signature(message):
    mac = hmac.new(bytes(api_sec, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256')
    d = mac.digest()
    return base64.b64encode(d)

def bitget_request_info(request_path, body, query, method): # this is Tariq's
    std_time = time.time() * 1000
    new_time = int(std_time)
    if str(body) == '{}' or str(body) == 'None':
        converted_body = ''
    else:
        converted_body = json.dumps(body)

    message = str(new_time) + method + request_path + parse_params_to_str(query) + converted_body

    headers = {"ACCESS-KEY": api_key,
               "ACCESS-SIGN": get_signature(message),
               "ACCESS-TIMESTAMP": str(new_time),
               "ACCESS-PASSPHRASE": api_passphrase,
               "Content-Type": "application/json",
               "Locale": "en-US"
               }
    if method == "GET":
        request_resp = requests.get((api_url + request_path), headers=headers, params=query)
    return request_resp

def bitget_post_buy_order(request_path, body, query, method): # This is my version for the post buy order
    std_time = time.time() * 1000
    new_time = int(std_time)
    if str(body) == '{}' or str(body) == 'None':
        converted_body = ''
    else:
        converted_body = json.dumps(body)

    message = str(new_time) + method + request_path + parse_params_to_str(query) + converted_body

    headers = {"ACCESS-KEY": api_key,
               "ACCESS-SIGN": get_signature(message),
               "ACCESS-TIMESTAMP": str(new_time),
               "ACCESS-PASSPHRASE": api_passphrase
               "Content-Type": "application/json",
               "Locale": "en-US"
              }
    if method == "POST":
        request_resp = requests.post((api_url + request_path), headers=headers, params=query)
    return request_resp

def get_info(): # this was Tariq's (I put it in a def)
    order_resp = bitget_request_info("/api/mix/v1/account/account", None, query, "GET")
    print(order_resp.json())

def place_buy_order(): # this is my version
    place_order = bitget_post_buy_order("/api/spot/v1/trade/orders", None, query, "POST")
    print(place_order.json())

def get_query_deets(): # this was Tariq's original
    global query
    query = {
        "symbol": symbol,
        "marginCoin": "USDT"
    }
    return(query)

def buy_order_deets(): # this is mine for the post buy order query
    global query
    query = {
        'symbol': symbol,
        'side': 'buy',
        'orderType': 'limit',
        'price': 9999,
        'quantity': 0.01
    }
    return(query)

def main():
    buy_order_deets()
    place_buy_order()
    #get_query_deets()
    #get_info()

main()
</code>```

Body:
Hello and thanks in advance for any help

I used this post (How to fix <Response [400]> error when making a request to the Bitget Futures Rest API in Python?) to get me well on my way to creating a post buy limit order for the Bitget API.

I keep getting this error though: {'code': '40409', 'msg': 'wrong format', 'requestTime': 1673551362880, 'data': None}

Looking up that error code suggests it's the time - I presume that used for the nonce - which is incorrect somehow?

For my post order I've tried using exactly the same format as the very useful answer provided by Tariq - https://stackoverflow.com/users/12907359/tarique in the above post - (Thanks Tariq!) ...therefore, effectively the only things that change from his code (which works for me), is the fact that mine a POST rather than a GET, and the 'query' content is different.

I'm posting below Tariq's code which works and my own as well where I'm getting the error. Any ideas very welcome, thanks!

I have commented where appropriate to highlight Tariq's original code and where I have created similar functions of my own.

import hashlib
import hmac
import base64
import requests
import time
import json

api_passphrase = "your secret"
api_key = "api key"
api_sec = "api secret"
api_url = "https://api.bitget.com"

#symbol = "BTCUSDT_UMCBL" # this is futures
symbol = 'BTC/USDT' # this is spot - I've added this here

def parse_params_to_str(params):
    url = '?'
    for key, value in params.items():
        url = url + str(key) + '=' + str(value) + '&'

    return url[0:-1]

def get_signature(message):
    mac = hmac.new(bytes(api_sec, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256')
    d = mac.digest()
    return base64.b64encode(d)

def bitget_request_info(request_path, body, query, method): # this is Tariq's
    std_time = time.time() * 1000
    new_time = int(std_time)
    if str(body) == '{}' or str(body) == 'None':
        converted_body = ''
    else:
        converted_body = json.dumps(body)

    message = str(new_time) + method + request_path + parse_params_to_str(query) + converted_body

    headers = {"ACCESS-KEY": api_key,
               "ACCESS-SIGN": get_signature(message),
               "ACCESS-TIMESTAMP": str(new_time),
               "ACCESS-PASSPHRASE": api_passphrase,
               "Content-Type": "application/json",
               "Locale": "en-US"
               }
    if method == "GET":
        request_resp = requests.get((api_url + request_path), headers=headers, params=query)
    return request_resp

def bitget_post_buy_order(request_path, body, query, method): # This is my version for the post buy order
    std_time = time.time() * 1000
    new_time = int(std_time)
    if str(body) == '{}' or str(body) == 'None':
        converted_body = ''
    else:
        converted_body = json.dumps(body)

    message = str(new_time) + method + request_path + parse_params_to_str(query) + converted_body

    headers = {"ACCESS-KEY": api_key,
               "ACCESS-SIGN": get_signature(message),
               "ACCESS-TIMESTAMP": str(new_time),
               "ACCESS-PASSPHRASE": api_passphrase
               "Content-Type": "application/json",
               "Locale": "en-US"
              }
    if method == "POST":
        request_resp = requests.post((api_url + request_path), headers=headers, params=query)
    return request_resp

def get_info(): # this was Tariq's (I put it in a def)
    order_resp = bitget_request_info("/api/mix/v1/account/account", None, query, "GET")
    print(order_resp.json())

def place_buy_order(): # this is my version
    place_order = bitget_post_buy_order("/api/spot/v1/trade/orders", None, query, "POST")
    print(place_order.json())

def get_query_deets(): # this was Tariq's original
    global query
    query = {
        "symbol": symbol,
        "marginCoin": "USDT"
    }
    return(query)

def buy_order_deets(): # this is mine for the post buy order query
    global query
    query = {
        'symbol': symbol,
        'side': 'buy',
        'orderType': 'limit',
        'price': 9999,
        'quantity': 0.01
    }
    return(query)

def main():
    buy_order_deets()
    place_buy_order()
    #get_query_deets()
    #get_info()

main()


问:
"No display specified error" generated by tinkter when starting Python program at bootup with Raspberry Pi
I have a Python program that displays weather information in graphical form on a Respberry Pi. The program uses Turtle and tkinter to generate the graphics. Running the program from the command line .i.e. "$ python3 DisplayProgram.py works properly.

I added a startup service (DisplayProgram.service) to systemd so that the program would start up at reboot.  However, when I test the program with "$ sudo systemctl start DisplayProgram.service" command, the error _tkinter.TclError: no display and no $DISPLAY environment variable is generated.

From reading other posts, I am aware that this error occurs because, prior to the calls to tkinter, no parent program has set the $DISPLAY environment variable to specify the screen where the graphics are to be displayed.  (I assume that when, running the program from the command line, the Python interpreter sets the appropriate environment variables.)

And so, the simple question is how to define the $DISPLAY environment variables in the absence of a parent program/server?


问:
Why in the Journal Transaction screen is the Post Period value being ignored by the REST API?
I'm trying  to use the REST API to create a record in the Journal Transactions screen.  The problem I'm running into is that if the Transaction Date I'm using is before the Post Period, I don't want the Post Period to default to the period of the Transaction Date.   In the UI, I can force the Post Period to be after the period of the Transaction Date, but it seems in the REST API, it ignores me setting the Post Period and defaults to the Period of the Transaction Date - and if that period is closed, it gives me an error.

Is this a bug that is known, or am I doing something wrong?

Here's a snippet of my JSON string - not sure that this matters, just wanted to show I was actually setting the Post Period field AFTER setting the transaction date....

```<code>{
"Module": {
    "value": "GL"
},
"TransactionDate": {
    "value": "10/31/2022 11:00:00 PM"
},
"PostPeriod": {
    "value": "012023"
},
"Ledger": {
    "value": "ACTUAL"
},
"Description": {
    "value": "ID: 7731"
},
"ControlTotal": {
    "value": "5842.32"
}
}
</code>```

Thanks...

Body:
I'm trying  to use the REST API to create a record in the Journal Transactions screen.  The problem I'm running into is that if the Transaction Date I'm using is before the Post Period, I don't want the Post Period to default to the period of the Transaction Date.   In the UI, I can force the Post Period to be after the period of the Transaction Date, but it seems in the REST API, it ignores me setting the Post Period and defaults to the Period of the Transaction Date - and if that period is closed, it gives me an error.

Is this a bug that is known, or am I doing something wrong?

Here's a snippet of my JSON string - not sure that this matters, just wanted to show I was actually setting the Post Period field AFTER setting the transaction date....

{
"Module": {
    "value": "GL"
},
"TransactionDate": {
    "value": "10/31/2022 11:00:00 PM"
},
"PostPeriod": {
    "value": "012023"
},
"Ledger": {
    "value": "ACTUAL"
},
"Description": {
    "value": "ID: 7731"
},
"ControlTotal": {
    "value": "5842.32"
}
}

Thanks...


问:
Translate javascript to angular typescript
I have a ZenDesk form and they have recommended me a javascript code to solve a problem that I have to edit the fields of the form and make them read-only, the problem is that I can't use normal javascript in angular9, the code from the documentation is this:

```<code><script type="text/javascript">
  zE('webWidget', 'prefill', {
    name: {
      value: 'isamu',
      readOnly: true // optional
    },
    email: {
      value: 'isamu@voltron.com',
      readOnly: true // optional
    },
    phone: {
      value: '61431909749',
      readOnly: true // optional
    }
  });
</script>
</code>```

I tried states solutions and they did not work for me

```<code>this.s.type = "text/javascript";
this.s.id = "ze-snippet";
this.s.src = "XXX";
this.s.text = "";

this.renderer2.appendChild(this.document.body, this.s);

this.zE('webWidget', 'prefill', {
  name: {
    value: 'isamu',
    readOnly: true // optional
  },
  email: {
    value: 'isamu@voltron.com',
    readOnly: true // optional
  }
});

window["zE"] = {
  webWidget: {
    prefill: {
      name: {
        value: 'isamu',
        readOnly: true // optional
      },
      email: {
        value: 'isamu@voltron.com',
        readOnly: true // optional
      }
    }
  }
};
</code>```

What could I do with this problem?

Body:
I have a ZenDesk form and they have recommended me a javascript code to solve a problem that I have to edit the fields of the form and make them read-only, the problem is that I can't use normal javascript in angular9, the code from the documentation is this:

I tried states solutions and they did not work for me

this.s.type = "text/javascript";
this.s.id = "ze-snippet";
this.s.src = "XXX";
this.s.text = "";

this.renderer2.appendChild(this.document.body, this.s);

this.zE('webWidget', 'prefill', {
  name: {
    value: 'isamu',
    readOnly: true // optional
  },
  email: {
    value: 'isamu@voltron.com',
    readOnly: true // optional
  }
});

window["zE"] = {
  webWidget: {
    prefill: {
      name: {
        value: 'isamu',
        readOnly: true // optional
      },
      email: {
        value: 'isamu@voltron.com',
        readOnly: true // optional
      }
    }
  }
};

What could I do with this problem?


问:
if response.get("X-Frame-Options") is not None: Exception Type: AttributeError at /index/ Exception Value: 'tuple' object has no attribute 'get'
```<code>from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.shortcuts import render,redirect
from .models import User,Post
from django.urls import reverse
from django.http import HttpResponse, HttpResponseRedirect,JsonResponse
from django.core.paginator import Paginator
import json

# Create your views here.

def register(request):
    if request.method == "POST":
        username = request.POST["username"]
        email = request.POST["email"]
        password = request.POST["password"]
        confirmation = request.POST["confirmation"]

        if password != confirmation:
            return render(request,"blog/register.html",{
                "message":"Password must match"
            })

        try:
            user = User.objects.create_user(username,email,password)
            user.save()

        except IntegrityError:
            return render(request,"blog/register.html",{
                "message": "Username already taken."
            })

    return render(request,"blog/register.html")

def login_view(request):
    if request.method == "POST":
        username = request.POST["username"]
        psw = request.POST["password"]

        user = authenticate(request,username=username,password=psw)

        if user is not None:
            login(request,user)
            return HttpResponseRedirect(reverse("index"))
        else:
            return render( request,"blog/login.html",{
                "message":"Invalid username and/or password."
            })

    return render(request, "blog/login.html")

def logout_view(request):
    logout(request)
    return HttpResponseRedirect(reverse("index"))

def addPost(request):

    if request.method == "POST":
        body = request.POST["body"]
        post = Post(user= request.user, post = body)
        post.save()
    return render(request,"blog/addpost.html")

def index(request):
    posts = Post.objects.all()
    # paginator = Paginator(posts, 10)
    # page_number = request.GET.get('page')
    # page_obj = paginator.get_page(page_number)

    return render(request,"blog/index.html", {'page_obj': posts}),

# def edit_post(request,post_id):
#     posts = Post.objects.get(id=post_id)
#     if request.method == 'POST':

#         textarea = request.POST["body"]
#         posts.post = textarea
#         posts.save()from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.shortcuts import render,redirect
from .models import User,Post
from django.urls import reverse
from django.http import HttpResponse, HttpResponseRedirect,JsonResponse
from django.core.paginator import Paginator
import json

# Create your views here.

def register(request):
    if request.method == "POST":
        username = request.POST["username"]
        email = request.POST["email"]
        password = request.POST["password"]
        confirmation = request.POST["confirmation"]

        if password != confirmation:
            return render(request,"blog/register.html",{
                "message":"Password must match"
            })

        try:
            user = User.objects.create_user(username,email,password)
            user.save()

        except IntegrityError:
            return render(request,"blog/register.html",{
                "message": "Username already taken."
            })

    return render(request,"blog/register.html")

def login_view(request):
    if request.method == "POST":
        username = request.POST["username"]
        psw = request.POST["password"]

        user = authenticate(request,username=username,password=psw)

        if user is not None:
            login(request,user)
            return HttpResponseRedirect(reverse("index"))
        else:
            return render( request,"blog/login.html",{
                "message":"Invalid username and/or password."
            })

    return render(request, "blog/login.html")

def logout_view(request):
    logout(request)
    return HttpResponseRedirect(reverse("index"))

def addPost(request):

    if request.method == "POST":
        body = request.POST["body"]
        post = Post(user= request.user, post = body)
        post.save()
    return render(request,"blog/addpost.html")

def index(request):
    posts = Post.objects.all()
    # paginator = Paginator(posts, 10)
    # page_number = request.GET.get('page')
    # page_obj = paginator.get_page(page_number)

    return render(request,"blog/index.html", {'page_obj': posts}),

# def edit_post(request,post_id):
#     posts = Post.objects.get(id=post_id)
#     if request.method == 'POST':

#         textarea = request.POST["body"]
#         posts.post = textarea
#         posts.save()
#     return render(request,"blog/index.html")

Index.html
{%extends "blog/layout.html"%}

{%block body%}

{% endblock %}
#     return render(request,"blog/index.html")

Index.html
{%extends "blog/layout.html"%}

{%block body%}

{% endblock %}
</code>```

Firstly, I tried to editing my posts. But after the login, editing part did not work. I commented all of the code related to edit post. After that, My index page return this error:

Traceback (most recent call last):
File "C:\Users\OSMAN MERT\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\OSMAN MERT\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\deprecation.py", line 136, in call
response = self.process_response(request, response)
File "C:\Users\OSMAN MERT\AppData\Local\Programs\Python\Python310\lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response
if response.get("X-Frame-Options") is not None:

Exception Type: AttributeError at /index/
Exception Value: 'tuple' object has no attribute 'get'

Body:
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.shortcuts import render,redirect
from .models import User,Post
from django.urls import reverse
from django.http import HttpResponse, HttpResponseRedirect,JsonResponse
from django.core.paginator import Paginator
import json

# Create your views here.

def register(request):
    if request.method == "POST":
        username = request.POST["username"]
        email = request.POST["email"]
        password = request.POST["password"]
        confirmation = request.POST["confirmation"]

        if password != confirmation:
            return render(request,"blog/register.html",{
                "message":"Password must match"
            })

        try:
            user = User.objects.create_user(username,email,password)
            user.save()

        except IntegrityError:
            return render(request,"blog/register.html",{
                "message": "Username already taken."
            })

    return render(request,"blog/register.html")

def login_view(request):
    if request.method == "POST":
        username = request.POST["username"]
        psw = request.POST["password"]

        user = authenticate(request,username=username,password=psw)

        if user is not None:
            login(request,user)
            return HttpResponseRedirect(reverse("index"))
        else:
            return render( request,"blog/login.html",{
                "message":"Invalid username and/or password."
            })

    return render(request, "blog/login.html")

def logout_view(request):
    logout(request)
    return HttpResponseRedirect(reverse("index"))

def addPost(request):

    if request.method == "POST":
        body = request.POST["body"]
        post = Post(user= request.user, post = body)
        post.save()
    return render(request,"blog/addpost.html")

def index(request):
    posts = Post.objects.all()
    # paginator = Paginator(posts, 10)
    # page_number = request.GET.get('page')
    # page_obj = paginator.get_page(page_number)

    return render(request,"blog/index.html", {'page_obj': posts}),

# def edit_post(request,post_id):
#     posts = Post.objects.get(id=post_id)
#     if request.method == 'POST':

#         textarea = request.POST["body"]
#         posts.post = textarea
#         posts.save()from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.shortcuts import render,redirect
from .models import User,Post
from django.urls import reverse
from django.http import HttpResponse, HttpResponseRedirect,JsonResponse
from django.core.paginator import Paginator
import json

# Create your views here.

def register(request):
    if request.method == "POST":
        username = request.POST["username"]
        email = request.POST["email"]
        password = request.POST["password"]
        confirmation = request.POST["confirmation"]

        if password != confirmation:
            return render(request,"blog/register.html",{
                "message":"Password must match"
            })

        try:
            user = User.objects.create_user(username,email,password)
            user.save()

        except IntegrityError:
            return render(request,"blog/register.html",{
                "message": "Username already taken."
            })

    return render(request,"blog/register.html")

def login_view(request):
    if request.method == "POST":
        username = request.POST["username"]
        psw = request.POST["password"]

        user = authenticate(request,username=username,password=psw)

        if user is not None:
            login(request,user)
            return HttpResponseRedirect(reverse("index"))
        else:
            return render( request,"blog/login.html",{
                "message":"Invalid username and/or password."
            })

    return render(request, "blog/login.html")

def logout_view(request):
    logout(request)
    return HttpResponseRedirect(reverse("index"))

def addPost(request):

    if request.method == "POST":
        body = request.POST["body"]
        post = Post(user= request.user, post = body)
        post.save()
    return render(request,"blog/addpost.html")

def index(request):
    posts = Post.objects.all()
    # paginator = Paginator(posts, 10)
    # page_number = request.GET.get('page')
    # page_obj = paginator.get_page(page_number)

    return render(request,"blog/index.html", {'page_obj': posts}),

# def edit_post(request,post_id):
#     posts = Post.objects.get(id=post_id)
#     if request.method == 'POST':

#         textarea = request.POST["body"]
#         posts.post = textarea
#         posts.save()
#     return render(request,"blog/index.html")

Index.html
{%extends "blog/layout.html"%}

{%block body%}

{% endblock %}
#     return render(request,"blog/index.html")

Index.html
{%extends "blog/layout.html"%}

{%block body%}

{% endblock %}

Firstly, I tried to editing my posts. But after the login, editing part did not work. I commented all of the code related to edit post. After that, My index page return this error:

Traceback (most recent call last):
File "C:\Users\OSMAN MERT\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\OSMAN MERT\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\deprecation.py", line 136, in call
response = self.process_response(request, response)
File "C:\Users\OSMAN MERT\AppData\Local\Programs\Python\Python310\lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response
if response.get("X-Frame-Options") is not None:

Exception Type: AttributeError at /index/
Exception Value: 'tuple' object has no attribute 'get'


问:
CODECHEF problem : same output , but one showing wrong submission
BOTH code output will be same for any testcase , still CODE 1 submitted successfully and CODE 2 not , why??

CODE 1:

```<code>int t = in.nextInt();
while((t--)>0){
    int n = in.nextInt();
    for(int j=0;j<n;j++){
        if(j==0 || j==n-1)
            System.out.print("1");
        else
           System.out.print("0");
    }
    System.out.print("\n");
</code>```

CODE 2:

```<code>int t = in.nextInt();
while((t--)>0){
    int n = in.nextInt();
    System.out.println((int)Math.pow(10,n-1)+1);
}
</code>```

Sample test case :

```<code>2
4
3
</code>```

Output:

```<code>1001
101
</code>```

problem link : https://www.codechef.com/problems/ZOOZ

PLEASE OPT ME OUT , if you got the logic where i'm wrong.

Body:
BOTH code output will be same for any testcase , still CODE 1 submitted successfully and CODE 2 not , why??

CODE 1:

int t = in.nextInt();
while((t--)>0){
    int n = in.nextInt();
    for(int j=0;j<n;j++){
        if(j==0 || j==n-1)
            System.out.print("1");
        else
           System.out.print("0");
    }
    System.out.print("\n");

CODE 2:

int t = in.nextInt();
while((t--)>0){
    int n = in.nextInt();
    System.out.println((int)Math.pow(10,n-1)+1);
}

Sample test case :

2
4
3

Output:

1001
101

problem link : https://www.codechef.com/problems/ZOOZ

PLEASE OPT ME OUT , if you got the logic where i'm wrong.


问:
Cox model selection: Test all variable combination
I need to test, which cox model fits the best based on partial AIC. Below you see the code, that I am using to test the combination of 5 parameters. How can I adjust my code, to test all possible variables combinations?</p>
```<code>parameters = ['v1', 'v3', 'v4','v5','CRD','followup']

p = []
for parameter in parameters:
    p.append(parameter)
print(p)

cph = CoxPHFitter()

cph.fit(df[p], duration_col="followup", event_col="CRD", show_progress=True, step_size = .5)

cph.print_summary(decimals = 5)
</code>```

Body:
I need to test, which cox model fits the best based on partial AIC. Below you see the code, that I am using to test the combination of 5 parameters. How can I adjust my code, to test all possible variables combinations?

parameters = ['v1', 'v3', 'v4','v5','CRD','followup']

p = []
for parameter in parameters:
    p.append(parameter)
print(p)

cph = CoxPHFitter()

cph.fit(df[p], duration_col="followup", event_col="CRD", show_progress=True, step_size = .5)

cph.print_summary(decimals = 5)


问:
How do I perform this type of authentication in the postman
Good afternoon, everyone! Guys I'm going through a problem with basic authentication in Postman, I'll leave below details of what's going on. I need to send a Post so I can perform authentication and the server will return me a token bearer, but I'm taking a 400 error. I'll leave attached images of the Curl request and how I'm setting up in Postman.

Auth:
enter image description here

Body:
enter image description here

Reading the documentation I'm using I realized that I needed to perform a basic authentication using client_id and client_secret for me to be returned a token bearer, the same error is returned to me when I perform a request in curl. Could you help me with this mistake? Could you tell me where I'm going wrong?

Segue requisição curl:

```<code>curl -X 'POST' \
  'https://portoapicloud-hml.portoseguro.com.br/oauth/v2/access-token' \
  -H 'accept: application/json' \
  -H 'Authorization: Basic NjZiNWJmMWI4MDE0NDExMWE1MGYwMWMyYmUxZjFiZDY6YzIwMGEwNzZlNmFkNDBkYThkYTkwODQ2YWI4OTI3MjU=' \
  -H 'Content-Type: application/json' \
  -d '{
  "grant_type": "client_credentials"
}'
</code>```

Body:
Good afternoon, everyone! Guys I'm going through a problem with basic authentication in Postman, I'll leave below details of what's going on. I need to send a Post so I can perform authentication and the server will return me a token bearer, but I'm taking a 400 error. I'll leave attached images of the Curl request and how I'm setting up in Postman.

Auth:
enter image description here

Body:
enter image description here

Reading the documentation I'm using I realized that I needed to perform a basic authentication using client_id and client_secret for me to be returned a token bearer, the same error is returned to me when I perform a request in curl. Could you help me with this mistake? Could you tell me where I'm going wrong?

Segue requisição curl:

curl -X 'POST' \
  'https://portoapicloud-hml.portoseguro.com.br/oauth/v2/access-token' \
  -H 'accept: application/json' \
  -H 'Authorization: Basic NjZiNWJmMWI4MDE0NDExMWE1MGYwMWMyYmUxZjFiZDY6YzIwMGEwNzZlNmFkNDBkYThkYTkwODQ2YWI4OTI3MjU=' \
  -H 'Content-Type: application/json' \
  -d '{
  "grant_type": "client_credentials"
}'


问:
Android JUnit5 ViewModel test observer invoke times not working
Here is my view model -

```<code>@HiltViewModel
class LoginViewModel @Inject constructor(private val accountService: AccountService) :
    ViewModel() {

    private val viewState = LoginViewState()

    fun loginUser(email: String, password: String) =
        accountService.performAccountAction(AccountAction.LoginUser(email, password)).map {
            when (it) {
                is AccountResult.Loading -> viewState.copy(loading = true)
                is AccountResult.UserLoggedIn -> viewState.copy(
                        loading = false,
                        destinationUri = TargetViewType.TO_PET_MATCHES_TAB_VIEW,
                        userLoggedIn = true
                    )
                is AccountResult.AccountError -> viewState.copy(
                        loading = false,
                        userLoggedIn = false,
                        loginError = it.error
                    )
                else -> viewState.copy(loading = false)
            }
        }.asLiveData(Dispatchers.Default + viewModelScope.coroutineContext)
}
</code>```

Here is my Login View State code -

```<code>data class LoginViewState(
    val loading: Boolean = false,
    val userLoggedIn: Boolean = false,
    val destinationUri: TargetViewType? = null,
    val loginError: AccountErrorType? = null
)
</code>```

Here is my test code for the view model -

```<code>@OptIn(ExperimentalCoroutinesApi::class)
@ExtendWith(InstantTaskExecutorExtension::class, CoroutinesTestExtension::class)
internal class LoginViewModelTest {

    @get:Rule
    val testCoroutineRule = TestCoroutineRule()

    @get:Rule
    val coroutineScope = MainCoroutineScopeRule()

    @get:Rule
    val rule = InstantTaskExecutorRule()

    @Mock
    private lateinit var accountService: AccountService

    @Mock
    private lateinit var mockObserver: Observer<LoginViewState>

    @Captor
    private lateinit var captor: ArgumentCaptor<LoginViewState>

    private lateinit var loginViewModel: LoginViewModel

    private lateinit var loginViewState: LoginViewState

    @BeforeEach
    fun setUp() {
        MockitoAnnotations.openMocks(this)
        loginViewState = LoginViewState()
        loginViewModel = LoginViewModel(accountService)
    }

    @AfterEach
    fun tearDown() {
    }

    @Test
    fun `Given - login user, When - account service returns user logged in, Then - view model logs in user`() {
        runBlocking {
            val flow = flow {
                emit(AccountResult.Loading)
                delay(10)
                emit(AccountResult.UserLoggedIn)
            }

            `when`(
                accountService.performAccountAction(
                    AccountAction.LoginUser(
                        "email",
                        "pwd"
                    )
                )
            ).thenReturn(flow)
            val liveData = loginViewModel.loginUser("email", "pwd")
            liveData.observeForever(mockObserver)

            verify(mockObserver).onChanged(captor.capture())
            assertEquals(true, captor.value.loading)
            coroutineScope.testScheduler.apply { advanceTimeBy(10); runCurrent() }
            verify(mockObserver, times(2)).onChanged(captor.capture())
            assertEquals(false, captor.value.loading)
        }
    }
}
</code>```

The problem is the test fails because the line verify(mockObserver, times(2)).onChanged(captor.capture()) says it was invoked once although I see it should be twice. Also the last line in the test assertEquals(false, captor.value.loading) fails since the expected value is true. Seems like the second emit of the flow is not being executed.

Body:
Here is my view model -

@HiltViewModel
class LoginViewModel @Inject constructor(private val accountService: AccountService) :
    ViewModel() {

    private val viewState = LoginViewState()

    fun loginUser(email: String, password: String) =
        accountService.performAccountAction(AccountAction.LoginUser(email, password)).map {
            when (it) {
                is AccountResult.Loading -> viewState.copy(loading = true)
                is AccountResult.UserLoggedIn -> viewState.copy(
                        loading = false,
                        destinationUri = TargetViewType.TO_PET_MATCHES_TAB_VIEW,
                        userLoggedIn = true
                    )
                is AccountResult.AccountError -> viewState.copy(
                        loading = false,
                        userLoggedIn = false,
                        loginError = it.error
                    )
                else -> viewState.copy(loading = false)
            }
        }.asLiveData(Dispatchers.Default + viewModelScope.coroutineContext)
}

Here is my Login View State code -

data class LoginViewState(
    val loading: Boolean = false,
    val userLoggedIn: Boolean = false,
    val destinationUri: TargetViewType? = null,
    val loginError: AccountErrorType? = null
)

Here is my test code for the view model -

@OptIn(ExperimentalCoroutinesApi::class)
@ExtendWith(InstantTaskExecutorExtension::class, CoroutinesTestExtension::class)
internal class LoginViewModelTest {

    @get:Rule
    val testCoroutineRule = TestCoroutineRule()

    @get:Rule
    val coroutineScope = MainCoroutineScopeRule()

    @get:Rule
    val rule = InstantTaskExecutorRule()

    @Mock
    private lateinit var accountService: AccountService

    @Mock
    private lateinit var mockObserver: Observer<LoginViewState>

    @Captor
    private lateinit var captor: ArgumentCaptor<LoginViewState>

    private lateinit var loginViewModel: LoginViewModel

    private lateinit var loginViewState: LoginViewState

    @BeforeEach
    fun setUp() {
        MockitoAnnotations.openMocks(this)
        loginViewState = LoginViewState()
        loginViewModel = LoginViewModel(accountService)
    }

    @AfterEach
    fun tearDown() {
    }

    @Test
    fun `Given - login user, When - account service returns user logged in, Then - view model logs in user`() {
        runBlocking {
            val flow = flow {
                emit(AccountResult.Loading)
                delay(10)
                emit(AccountResult.UserLoggedIn)
            }

            `when`(
                accountService.performAccountAction(
                    AccountAction.LoginUser(
                        "email",
                        "pwd"
                    )
                )
            ).thenReturn(flow)
            val liveData = loginViewModel.loginUser("email", "pwd")
            liveData.observeForever(mockObserver)

            verify(mockObserver).onChanged(captor.capture())
            assertEquals(true, captor.value.loading)
            coroutineScope.testScheduler.apply { advanceTimeBy(10); runCurrent() }
            verify(mockObserver, times(2)).onChanged(captor.capture())
            assertEquals(false, captor.value.loading)
        }
    }
}

The problem is the test fails because the line verify(mockObserver, times(2)).onChanged(captor.capture()) says it was invoked once although I see it should be twice. Also the last line in the test assertEquals(false, captor.value.loading) fails since the expected value is true. Seems like the second emit of the flow is not being executed.


问:
Why Firebase sends a 'Permission Denied' response when I try to authenticate from NextAuth.js?
I have a NextJS project setup and I use NextAuth.js to add Firebase Auth.

I used the docs from NextAuth.js for adding Firebase Auth on the app but it's not working unless I set security rules on Firestore as allow read, write: if true;.

What could be the problem from not working with allow read, write: if request.auth != null;?

I have a firebase.config.ts:

import { initializeApp, FirebaseOptions } from "firebase/app";
import {getAuth} from "firebase/auth";

const firebaseConfig: FirebaseOptions = {
  apiKey: process.env.API_KEY,
  authDomain: process.env.AUTH_DOMAIN,
  projectId: process.env.PROJECT_ID,
  storageBucket: process.env.STORAGE_BUCKET,
  messagingSenderId: process.env.MESSAGING_SENDER_ID,
  appId: process.env.APP_ID,
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

export {auth, app, firebaseConfig}
```
<p>This is used in the <code>/pages/api/auth/[...nextauth].ts</code> to conform to the NextAuth.js docs</p>
<pre class="lang-js prettyprint-override"><code>import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
import { FirestoreAdapter } from "@next-auth/firebase-adapter"

import {firebaseConfig} from "../../../firebase.config"

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
    })],
    adapter: FirestoreAdapter(firebaseConfig)
})
</code>```

And then I just trigger the Authentication by using this:

import { signIn } from "next-auth/react";

export default function Header() {
  return (

Tixer

      <button
        onClick={() => signIn()}
        className="hover:text-gray-300 text-white font-bold py-2 px-4 rounded"
      >
        Sign In
      </button>

  );
}

```
<p>In the terminal I see this:</p>
```[next-auth][error][adapter_error_getUserByAccount]

https://next-auth.js.org/errors#adapter_error_getuserbyaccount

Missing or insufficient permissions. {
  message: 'Missing or insufficient permissions.',
  stack: 'FirebaseError: Missing or insufficient permissions.',
  name: 'FirebaseError'
}
```

Body:
I have a NextJS project setup and I use NextAuth.js to add Firebase Auth.

I used the docs from NextAuth.js for adding Firebase Auth on the app but it's not working unless I set security rules on Firestore as allow read, write: if true;.

What could be the problem from not working with allow read, write: if request.auth != null;?

I have a firebase.config.ts:

import { initializeApp, FirebaseOptions } from "firebase/app";
import {getAuth} from "firebase/auth";

const firebaseConfig: FirebaseOptions = {
  apiKey: process.env.API_KEY,
  authDomain: process.env.AUTH_DOMAIN,
  projectId: process.env.PROJECT_ID,
  storageBucket: process.env.STORAGE_BUCKET,
  messagingSenderId: process.env.MESSAGING_SENDER_ID,
  appId: process.env.APP_ID,
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

export {auth, app, firebaseConfig}

This is used in the /pages/api/auth/[...nextauth].ts to conform to the NextAuth.js docs

import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
import { FirestoreAdapter } from "@next-auth/firebase-adapter"

import {firebaseConfig} from "../../../firebase.config"

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
    })],
    adapter: FirestoreAdapter(firebaseConfig)
})

And then I just trigger the Authentication by using this:

import { signIn } from "next-auth/react";

export default function Header() {
  return (

Tixer

      <button
        onClick={() => signIn()}
        className="hover:text-gray-300 text-white font-bold py-2 px-4 rounded"
      >
        Sign In
      </button>

  );
}

In the terminal I see this:

[next-auth][error][adapter_error_getUserByAccount]

https://next-auth.js.org/errors#adapter_error_getuserbyaccount

Missing or insufficient permissions. {
  message: 'Missing or insufficient permissions.',
  stack: 'FirebaseError: Missing or insufficient permissions.',
  name: 'FirebaseError'
}


问:
.htaccess works for .html but not .php
I want to restrict the access to my directory (and redirect to my index.php)
but it is not working well. When i change the extension from PHP to HTML it works fine, but I cannot make it work for php

This is what I have in my .htaccess:

```<code>Options All -Indexes

<files .htaccess>
order allow,deny
deny from all
</files>

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]

</code>```

I'm new to all of this, so I really don't know how to solve this.

Thanks!

Title: .htaccess works for .html but not .php

Body:
I want to restrict the access to my directory (and redirect to my index.php)
but it is not working well. When i change the extension from PHP to HTML it works fine, but I cannot make it work for php

This is what I have in my .htaccess:

Options All -Indexes

<files .htaccess>
order allow,deny
deny from all
</files>

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]

I'm new to all of this, so I really don't know how to solve this.

Thanks!


问:
how to find the irfunction's enclosing class in kotlin
In kotlin, i have an Irfunction, how should i find which class it belongs to ?

```<code>abstract class IrFunction : IrDeclarationBase(), IrPossiblyExternalDeclaration,
        IrDeclarationWithVisibility, IrTypeParametersContainer, IrSymbolOwner, IrDeclarationParent,
        IrReturnTarget, IrMemberWithContainerSource, IrMetadataSourceOwner {
</code>```

Sadly the documentation for Ir related concept is missing and I have to guess the meaning and my guess is not always correct.

Body:
In kotlin, i have an Irfunction, how should i find which class it belongs to ?

abstract class IrFunction : IrDeclarationBase(), IrPossiblyExternalDeclaration,
        IrDeclarationWithVisibility, IrTypeParametersContainer, IrSymbolOwner, IrDeclarationParent,
        IrReturnTarget, IrMemberWithContainerSource, IrMetadataSourceOwner {

Sadly the documentation for Ir related concept is missing and I have to guess the meaning and my guess is not always correct.


问:
Helm uninstall does not delete all resources in microkubernetes
I wonder why helm uninstall does not remove my pods.

Example and minimum viable code, as in https://helm.sh/docs/intro/using_helm/ :

```<code>$ kubectl create namespace mydemo
namespace/mydemo created

$ helm install happy-panda bitnami/wordpress -n mydemo
NAME: happy-panda
LAST DEPLOYED: Fri Jan 13 08:50:58 2023
NAMESPACE: mydemo
STATUS: deployed
REVISION: 1
TEST SUITE: None
NOTES:
CHART NAME: wordpress
CHART VERSION: 15.2.22
APP VERSION: 6.1.1

** Please be patient while the chart is being deployed **

Your WordPress site can be accessed through the following DNS name from within your cluster:

    happy-panda-wordpress.mydemo.svc.cluster.local (port 80)

To access your WordPress site from outside the cluster follow the steps below:

1. Get the WordPress URL by running these commands:

  NOTE: It may take a few minutes for the LoadBalancer IP to be available.
        Watch the status with: 'kubectl get svc --namespace mydemo -w happy-panda-wordpress'

   export SERVICE_IP=$(kubectl get svc --namespace mydemo happy-panda-wordpress --include "{{ range (index .status.loadBalancer.ingress 0) }}{{ . }}{{ end }}")
   echo "WordPress URL: http://$SERVICE_IP/"
   echo "WordPress Admin URL: http://$SERVICE_IP/admin"

2. Open a browser and access WordPress using the obtained URL.

3. Login with the following credentials below to see your blog:

  echo Username: user
  echo Password: $(kubectl get secret --namespace mydemo happy-panda-wordpress -o jsonpath="{.data.wordpress-password}" | base64 -d)

</code>```

Installation goes well; the helm release shows up and resources are available (get ready soon afterwards):

```<code>$ kubectl get all -n mydemo
NAME                                         READY   STATUS    RESTARTS   AGE
pod/happy-panda-wordpress-6756b48578-xqzwr   0/1     Running   0          23s
pod/happy-panda-mariadb-0                    0/1     Running   0          23s

NAME                            TYPE           CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE
service/happy-panda-mariadb     ClusterIP      10.152.183.104   <none>        3306/TCP                     23s
service/happy-panda-wordpress   LoadBalancer   10.152.183.221   <pending>     80:31402/TCP,443:32116/TCP   23s

NAME                                    READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/happy-panda-wordpress   0/1     1            0           23s

NAME                                               DESIRED   CURRENT   READY   AGE
replicaset.apps/happy-panda-wordpress-6756b48578   1         1         0       23s

NAME                                   READY   AGE
statefulset.apps/happy-panda-mariadb   0/1     23s

$ helm list -n mydemo
NAME        NAMESPACE   REVISION    UPDATED                                     STATUS      CHART               APP VERSION
happy-panda mydemo      1           2023-01-13 08:50:58.636327755 +1300 NZDT    deployed    wordpress-15.2.22   6.1.1

</code>```

Now, we try to uninstall the helm release:

```<code>
$ helm uninstall happy-panda -n mydemo
release "happy-panda" uninstalled

</code>```

The helm release is gone as expected:

```<code>$ helm list -n mydemo
NAME    NAMESPACE   REVISION    UPDATED STATUS  CHART   APP VERSION
</code>```

... unfortunately, some resources are still there:

```<code>$ kubectl get all -n mydemo
NAME                                         READY   STATUS    RESTARTS   AGE
pod/happy-panda-mariadb-0                    1/1     Running   0          2m17s
pod/happy-panda-wordpress-6756b48578-xqzwr   0/1     Running   0          2m17s

NAME                                               DESIRED   CURRENT   READY   AGE
replicaset.apps/happy-panda-wordpress-6756b48578   1         1         0       2m17s
</code>```

I was on microk8s version 1.25 previously, but have upgraded to 1.26 already.

```<code>$ microk8s version
MicroK8s v1.26.0 revision 4390

$ helm version
version.BuildInfo{Version:"v3.10.3", GitCommit:"835b7334cfe2e5e27870ab3ed4135f136eecc704", GitTreeState:"clean", GoVersion:"go1.18.9"}

</code>```

Now, I can obviously force-delete the namespace, but it would be so much nicer to use the helm uninstall functionality as intended. - This is on a local dev machine, running on Ubuntu 22.04.

Any ideas?

Body:
I wonder why helm uninstall does not remove my pods.

Example and minimum viable code, as in https://helm.sh/docs/intro/using_helm/ :

$ kubectl create namespace mydemo
namespace/mydemo created

$ helm install happy-panda bitnami/wordpress -n mydemo
NAME: happy-panda
LAST DEPLOYED: Fri Jan 13 08:50:58 2023
NAMESPACE: mydemo
STATUS: deployed
REVISION: 1
TEST SUITE: None
NOTES:
CHART NAME: wordpress
CHART VERSION: 15.2.22
APP VERSION: 6.1.1

** Please be patient while the chart is being deployed **

Your WordPress site can be accessed through the following DNS name from within your cluster:

    happy-panda-wordpress.mydemo.svc.cluster.local (port 80)

To access your WordPress site from outside the cluster follow the steps below:

1. Get the WordPress URL by running these commands:

  NOTE: It may take a few minutes for the LoadBalancer IP to be available.
        Watch the status with: 'kubectl get svc --namespace mydemo -w happy-panda-wordpress'

   export SERVICE_IP=$(kubectl get svc --namespace mydemo happy-panda-wordpress --include "{{ range (index .status.loadBalancer.ingress 0) }}{{ . }}{{ end }}")
   echo "WordPress URL: http://$SERVICE_IP/"
   echo "WordPress Admin URL: http://$SERVICE_IP/admin"

2. Open a browser and access WordPress using the obtained URL.

3. Login with the following credentials below to see your blog:

  echo Username: user
  echo Password: $(kubectl get secret --namespace mydemo happy-panda-wordpress -o jsonpath="{.data.wordpress-password}" | base64 -d)

Installation goes well; the helm release shows up and resources are available (get ready soon afterwards):

$ kubectl get all -n mydemo
NAME                                         READY   STATUS    RESTARTS   AGE
pod/happy-panda-wordpress-6756b48578-xqzwr   0/1     Running   0          23s
pod/happy-panda-mariadb-0                    0/1     Running   0          23s

NAME                            TYPE           CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE
service/happy-panda-mariadb     ClusterIP      10.152.183.104   <none>        3306/TCP                     23s
service/happy-panda-wordpress   LoadBalancer   10.152.183.221   <pending>     80:31402/TCP,443:32116/TCP   23s

NAME                                    READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/happy-panda-wordpress   0/1     1            0           23s

NAME                                               DESIRED   CURRENT   READY   AGE
replicaset.apps/happy-panda-wordpress-6756b48578   1         1         0       23s

NAME                                   READY   AGE
statefulset.apps/happy-panda-mariadb   0/1     23s

$ helm list -n mydemo
NAME        NAMESPACE   REVISION    UPDATED                                     STATUS      CHART               APP VERSION
happy-panda mydemo      1           2023-01-13 08:50:58.636327755 +1300 NZDT    deployed    wordpress-15.2.22   6.1.1

Now, we try to uninstall the helm release:

$ helm uninstall happy-panda -n mydemo
release "happy-panda" uninstalled

The helm release is gone as expected:

$ helm list -n mydemo
NAME    NAMESPACE   REVISION    UPDATED STATUS  CHART   APP VERSION

... unfortunately, some resources are still there:

$ kubectl get all -n mydemo
NAME                                         READY   STATUS    RESTARTS   AGE
pod/happy-panda-mariadb-0                    1/1     Running   0          2m17s
pod/happy-panda-wordpress-6756b48578-xqzwr   0/1     Running   0          2m17s

NAME                                               DESIRED   CURRENT   READY   AGE
replicaset.apps/happy-panda-wordpress-6756b48578   1         1         0       2m17s

I was on microk8s version 1.25 previously, but have upgraded to 1.26 already.

$ microk8s version
MicroK8s v1.26.0 revision 4390

$ helm version
version.BuildInfo{Version:"v3.10.3", GitCommit:"835b7334cfe2e5e27870ab3ed4135f136eecc704", GitTreeState:"clean", GoVersion:"go1.18.9"}

Now, I can obviously force-delete the namespace, but it would be so much nicer to use the helm uninstall functionality as intended. - This is on a local dev machine, running on Ubuntu 22.04.

Any ideas?


问:
Material dropdown adding a background color when I hovers over dropdown
I am using material UI dropdown and modified few styling of default dropdown. But for some reason when I hover mouse over the dropdown list, it adds reddish color as to the background.

const dropDownStyle = makeStyles({
  formControl: {
    "& .MuiInputBase-root": {
      color: "#4553da",
      borderColor: "#4454f4",
      borderWidth: "2px",
      borderStyle: "solid",
      borderRadius: "100px",
      minWidth: "120px",
      justifyContent: "center",
      backgroundColor: "#4454f4",
    },
    "& .MuiSelect-select.MuiSelect-select": {
      paddingRight: "0px",
    },
  },
  select: {
    fontSize: "12px",
    fontfamily: "sans-serif",
    textAlign: "center",
  },
  selectIcon: {
    position: "relative",
    color: "#6EC177",
    fontSize: "17px",
    fontWeight: "bold",
  },
  paper: {
    borderRadius: 12,
    marginTop: 8,
  },
  list: {
    paddingTop: 0,
    paddingBottom: 0,
    "& li": {
      fontWeight: 200,
      paddingTop: 8,
      paddingBottom: 8,
      fontSize: "12px",
    },
    "& li.Mui-selected": {
      color: "white",
      background: "blue",
    },
    "& li.Mui-selected:hover": {
      background: "blue",
    },
  },
});

const DropDown = ({ label, value, handleChange, items }) => {
  console.log("label ", label);
  console.log("Dropdown ", value);
  console.log("Dropdown handleChange", handleChange);
  console.log("Dropdown items", items);

  const classes = dropDownStyle();

  console.log("classes :", classes);
  const menuProps = {
    classes: {
      list: classes.list,
      paper: classes.paper,
    },
    anchorOrigin: {
      vertical: "bottom",
      horizontal: "center",
    },
    transformOrigin: {
      vertical: "top",
      horizontal: "center",
    },
    getContentAnchorEl: null,
  };

  return (
    <FormControl variant="outlined" style={{ marginTop: 5, minWidth: 260 }}>
      <InputLabel shrink>{label}</InputLabel>
      <Select
        label={label}
        value={value}
        onChange={handleChange}
        disableUnderline
        MenuProps={menuProps}
        classes={{
          select: classes.select,
        }}
      >
        {items.map((item) => (
          <MenuItem key={item.key} value={item.value}>
            {item.key}
          </MenuItem>
        ))}
      </Select>
    </FormControl>
  );
};```

AS shown below, whenever I hover mouse over dropdown, color changes by itself.

I noticed some weird behavior. I see jss4 class under style and I am not sure where it is coming from

Body:
I am using material UI dropdown and modified few styling of default dropdown. But for some reason when I hover mouse over the dropdown list, it adds reddish color as to the background.

const dropDownStyle = makeStyles({
  formControl: {
    "& .MuiInputBase-root": {
      color: "#4553da",
      borderColor: "#4454f4",
      borderWidth: "2px",
      borderStyle: "solid",
      borderRadius: "100px",
      minWidth: "120px",
      justifyContent: "center",
      backgroundColor: "#4454f4",
    },
    "& .MuiSelect-select.MuiSelect-select": {
      paddingRight: "0px",
    },
  },
  select: {
    fontSize: "12px",
    fontfamily: "sans-serif",
    textAlign: "center",
  },
  selectIcon: {
    position: "relative",
    color: "#6EC177",
    fontSize: "17px",
    fontWeight: "bold",
  },
  paper: {
    borderRadius: 12,
    marginTop: 8,
  },
  list: {
    paddingTop: 0,
    paddingBottom: 0,
    "& li": {
      fontWeight: 200,
      paddingTop: 8,
      paddingBottom: 8,
      fontSize: "12px",
    },
    "& li.Mui-selected": {
      color: "white",
      background: "blue",
    },
    "& li.Mui-selected:hover": {
      background: "blue",
    },
  },
});

const DropDown = ({ label, value, handleChange, items }) => {
  console.log("label ", label);
  console.log("Dropdown ", value);
  console.log("Dropdown handleChange", handleChange);
  console.log("Dropdown items", items);

  const classes = dropDownStyle();

  console.log("classes :", classes);
  const menuProps = {
    classes: {
      list: classes.list,
      paper: classes.paper,
    },
    anchorOrigin: {
      vertical: "bottom",
      horizontal: "center",
    },
    transformOrigin: {
      vertical: "top",
      horizontal: "center",
    },
    getContentAnchorEl: null,
  };

  return (
    <FormControl variant="outlined" style={{ marginTop: 5, minWidth: 260 }}>
      <InputLabel shrink>{label}</InputLabel>
      <Select
        label={label}
        value={value}
        onChange={handleChange}
        disableUnderline
        MenuProps={menuProps}
        classes={{
          select: classes.select,
        }}
      >
        {items.map((item) => (
          <MenuItem key={item.key} value={item.value}>
            {item.key}
          </MenuItem>
        ))}
      </Select>
    </FormControl>
  );
};

AS shown below, whenever I hover mouse over dropdown, color changes by itself.

I noticed some weird behavior. I see jss4 class under style and I am not sure where it is coming from


问:
Using C# to light up an LED button on a Novation Launchpad Mini MK3
I wanted to make a simple program that will play an animation I can make to make my setup look nicer :) The thing I'm really struggling with is finding a solution for lighting up an LED on my Launchpad Mini MK3 by the X and Y coordinate or index.

I've tried DryWetMidi, but from reading the documentation I assume there are no lighting effects for it.

I thought about just sending some data straight to my launchpad, but I've never really worked with an external device, so I have no idea on how to make it.

If anyone has an idea, or a working AND TRUSTED library, it would be great if you mention it! Code examples are welcome!


问:
How do I alter a pandas dataframe's shape so that it has more columns and a single row per record?
I have item sales by store; each row shows the store number, item number, and the quantity. A store can have as many as 4 rows (all 4 items), or just one, like below:

StoreNo
ItemNo
Qty

1
1111
30

1
1112
25

1
1113
0

2
1111
20

2
1112
20

2
1114
30

3
1112
25

3
1111
0

3
1113
15

4
1114
0

5
1114
25

5
1112
25

I would like to make it into a dataframe that has just one row per store, and each item number and its quantity as a column for that row, excluding all zero quantity records, like this:

StoreNo
ItemNo1
Qty1
ItemNo2
Qty2
ItemNo3
Qty3
ItemNo4
Qty4

1
1111
30
1112
25

2
1111
20
1112
20
1114
30

3
1112
25
1113
15

5
1114
25
1112
25

If a store has only two items that have nonzero quantities, it should have four columns to the right of the store number that have data, and four that have NaN. Also, note the only item in store 4 had a zero quantity, so it doesn't show up at all in the resulting dataframe.

I'm unsure of the code I should use to accomplish this.


问:
Angular Sorting in HTML without the use of a Pipe
Angular.io states that filtering and sorting should not be done in a Pipe due to the amount of calls per-second it will make, however, in the community, there is no shortage of examples and tutorials on doing it with a Pipe.

What is the ideal way to implement a pre/post-sort in a template, without mutating the original data and still have a reference to the original data?

I am coming from Vue.js, my first thought is a computed property, which may be close to a 'get' in angular??, but not sure.


问:
this is problem when i want to add ui authentication for my laravel project
This what it present when i run npm run dev

how can i solve these problem?

```<code>npm ERR! code ELIFECYCLE
npm ERR! errno 1 npm ERR! @ dev: `vite`
npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm.
There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\\Users\\master dvd\\AppData\\Roaming\\npm-cache_logs\\2023-01-12T19_06_21_061Z-debug.log
</code>```

Body:
This what it present when i run npm run dev

how can i solve these problem?

npm ERR! code ELIFECYCLE
npm ERR! errno 1 npm ERR! @ dev: `vite`
npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm.
There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\\Users\\master dvd\\AppData\\Roaming\\npm-cache_logs\\2023-01-12T19_06_21_061Z-debug.log


问:
`dotnet publish` without `--no-build` cause app crash on load with FileNotFoundException
I created an MSIX using the VS packaging project, but when I run it, I see two error messages:

Application: ZZZ.exe CoreCLR Version: 6.0.1022.47605 .NET Version:
6.0.10 Description: The process was terminated due to an unhandled exception. Exception Info: System.IO.FileNotFoundException: Could not
load file or assembly 'DevExpress.XtraEditors.v22.1, Version=22.1.3.0,
Culture=neutral, PublicKeyToken=b88d1754d700e49a'. The system cannot
find the file specified. File name: 'DevExpress.XtraEditors.v22.1,
Version=22.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a'

at ZZZ.Startup`1.Start(String instanceName, String appName)    at
ZZZ.Program.Main()

Faulting application name: ZZZ.exe, version: 1.0.0.0, time stamp:
0x6331e747 Faulting module name: KERNELBASE.dll, version:
10.0.19041.2364, time stamp: 0x1e5c8604 Exception code: 0xe0434352 Fault offset: 0x0012e292 Faulting process id: 0x1d64 Faulting
application start time: 0x01d926beb2ed20bf Faulting application path:
C:\Program
Files\WindowsApps\com.XXXX.ZZZ_1.0.0.0_x86__j6zw3m0tavcqa\ZZZ\ZZZ.exe
Faulting module path: C:\WINDOWS\System32\KERNELBASE.dll Report Id:
159bdbc1-e425-49d2-8ef3-d42850e29bd9 Faulting package full name:
com.XXXX.ZZZ_1.0.0.0_x86__j6zw3m0tavcqa Faulting package-relative
application ID: App

App is .NET 6 WinForms

Packaged as a bundle that only has x86

I unzipped the msixbundle file and then the msix file and I do see that the DLL is included in the package (ZZZ\DevExpress.XtraEditors.v22.1.dll).

Does anyone have any ideas what could be failing or how I can get more info?

UPDATE: This issue is not MSIX specific. If I build a self-contained app targeting win-x86, I get the same issue.

UPDATE: I've tracked down the issue further, and it may be a bug in the .NET SDK. dotnet publish causes a FileNotFoundException, but dotnet publish --no-build works perfectly fine.

System info:

❯ dotnet --info .NET SDK (reflecting any global.json):  Version:

6.0.402  Commit:    6862418796

Runtime Environment:  OS Name:     Windows  OS Version:  10.0.19042
OS Platform: Windows  RID:         win10-x64  Base Path:   C:\Program
Files\dotnet\sdk\6.0.402\

Host:   Version:      7.0.1   Architecture: x64   Commit:

97203d38ba

.NET SDKs installed:
3.1.409 [C:\Program Files\dotnet\sdk]
5.0.402 [C:\Program Files\dotnet\sdk]
5.0.408 [C:\Program Files\dotnet\sdk]
6.0.402 [C:\Program Files\dotnet\sdk]
7.0.100-rc.2.22477.23 [C:\Program Files\dotnet\sdk]
7.0.101 [C:\Program Files\dotnet\sdk]


问:
.NET Garbage Collector and JOB_OBJECT memory limits
I'm trying to understand whether .NET garbage collector and memory allocator respect limits defined in Windows JOB_OBJECT.
I'm especially interested in how this works in .NET Framework 4.8 but could not find any information in public documentation.</p>


问:
WPF FixedPage not printing data in listview
I have user control with a fixed page element, everything works fine from the UI but when I print it the data in the listview is not printed on the receipt I tried several things but no matter what it just doesn't show up.

Here is the XAML

```<code>            <FixedPage x:Name="ReceiptData">
                <StackPanel Orientation="Vertical">
                    <Image Source="../Images/LOGO.png" Width="340" Margin="5,1,1,1"></Image>
                    <StackPanel Orientation="Horizontal" >
                        <Label Margin="5,1,0,1" Content="{Binding KioskName, FallbackValue=000000}"></Label>
                    </StackPanel>
                    <StackPanel Orientation="Horizontal">

                        <Label Content="Date:" Margin="5,1,8,1"></Label>
                        <Label Content="{Binding CurrentDateTime, StringFormat=g}"></Label>
                    </StackPanel>
                    <StackPanel Orientation="Horizontal">
                        <Border BorderThickness="0,1,0,0"
                               BorderBrush="Black"
                                Height="5" Width="345"/>
                    </StackPanel>
                    <StackPanel Orientation="Horizontal">
                        <Label Content="Qauntity"></Label>
                        <Label Content="Description" Margin="8,0,0,0"></Label>
                        <Label Content="Price" Margin="130,0,0,0"></Label>
                    </StackPanel>
                    <ListView ItemsSource="{Binding SaleItemsObservable}" MinHeight="300"
                              BorderBrush="{x:Null}"
                              Background="{x:Null}"
                              Foreground="Black">
                        <ListView.View>
                            <GridView ColumnHeaderContainerStyle="{StaticResource gridViewNoHeader}">
                                <GridViewColumn DisplayMemberBinding="{Binding Quantity}" Width="45"/>
                                <GridViewColumn DisplayMemberBinding="{Binding ProductName}" Width="210" />
                                <GridViewColumn DisplayMemberBinding="{Binding Path=Price, StringFormat='{}{0:c}'}" Width="55"/>
                            </GridView>
                        </ListView.View>
                    </ListView>
                    <Image Source="../Images/LOGO.png" Width="340" Margin="5,1,1,1"></Image>
                </StackPanel>
            </FixedPage>
</code>```

This is the code that prints it.

```<code> private void Button_Click(object sender, RoutedEventArgs e)
    {
        InnerGrid.Children.Remove(ReceiptData);
        PrintQueue sourcePrintQueue = new LocalPrintServer().DefaultPrintQueue;
        if (sourcePrintQueue != null)
        {
            var pageContent = new PageContent();
            var fixedDocument = new FixedDocument();

            fixedDocument.PrintTicket = new PrintTicket();
            var printTicket = (PrintTicket)fixedDocument.PrintTicket;
            printTicket.PageOrientation = PageOrientation.Portrait;
            ((IAddChild)pageContent).AddChild(ReceiptData);
            fixedDocument.Pages.Add(pageContent);
            PrintDialog pd = new PrintDialog();
            pd.PrintQueue = sourcePrintQueue;
            pd.PrintTicket = printTicket;
            pd.PrintDocument(fixedDocument.DocumentPaginator, "Kiosk 2.0 Receipt");
        }

    }
</code>```

It prints perfectly fine but the data in the listview is missing no matter what, I have tried setting a template, I have tried manually setting the items in the code behind but nothing works so I assume there is something I am missing to tell it to render that data to the printer? Any ideas?

Body:
I have user control with a fixed page element, everything works fine from the UI but when I print it the data in the listview is not printed on the receipt I tried several things but no matter what it just doesn't show up.

Here is the XAML

            <FixedPage x:Name="ReceiptData">
                <StackPanel Orientation="Vertical">
                    <Image Source="../Images/LOGO.png" Width="340" Margin="5,1,1,1"></Image>
                    <StackPanel Orientation="Horizontal" >

                    </StackPanel>
                    <StackPanel Orientation="Horizontal">

                    </StackPanel>
                    <StackPanel Orientation="Horizontal">
                        <Border BorderThickness="0,1,0,0"
                               BorderBrush="Black"
                                Height="5" Width="345"/>
                    </StackPanel>
                    <StackPanel Orientation="Horizontal">

                    </StackPanel>
                    <ListView ItemsSource="{Binding SaleItemsObservable}" MinHeight="300"
                              BorderBrush="{x:Null}"
                              Background="{x:Null}"
                              Foreground="Black">
                        <ListView.View>
                            <GridView ColumnHeaderContainerStyle="{StaticResource gridViewNoHeader}">
                                <GridViewColumn DisplayMemberBinding="{Binding Quantity}" Width="45"/>
                                <GridViewColumn DisplayMemberBinding="{Binding ProductName}" Width="210" />
                                <GridViewColumn DisplayMemberBinding="{Binding Path=Price, StringFormat='{}{0:c}'}" Width="55"/>
                            </GridView>
                        </ListView.View>
                    </ListView>
                    <Image Source="../Images/LOGO.png" Width="340" Margin="5,1,1,1"></Image>
                </StackPanel>
            </FixedPage>

This is the code that prints it.

 private void Button_Click(object sender, RoutedEventArgs e)
    {
        InnerGrid.Children.Remove(ReceiptData);
        PrintQueue sourcePrintQueue = new LocalPrintServer().DefaultPrintQueue;
        if (sourcePrintQueue != null)
        {
            var pageContent = new PageContent();
            var fixedDocument = new FixedDocument();

            fixedDocument.PrintTicket = new PrintTicket();
            var printTicket = (PrintTicket)fixedDocument.PrintTicket;
            printTicket.PageOrientation = PageOrientation.Portrait;
            ((IAddChild)pageContent).AddChild(ReceiptData);
            fixedDocument.Pages.Add(pageContent);
            PrintDialog pd = new PrintDialog();
            pd.PrintQueue = sourcePrintQueue;
            pd.PrintTicket = printTicket;
            pd.PrintDocument(fixedDocument.DocumentPaginator, "Kiosk 2.0 Receipt");
        }

    }

It prints perfectly fine but the data in the listview is missing no matter what, I have tried setting a template, I have tried manually setting the items in the code behind but nothing works so I assume there is something I am missing to tell it to render that data to the printer? Any ideas?