问:
How can I access a sub-collection firebase?
```<code>getLikeInfo() {
  this.firestore.getDocument({
    path: ['Posts', this.postData.postId],
    onComplete: (result) => {
      let userDocument = result.data();
      this.userLikeId = userDocument!['creatorId'];
    },
  });
</code>```

I want access to the sub collection "PostLinks". I tried more and more thing, but none work. Can someone explain me how I can access on a sub collection?

答:
I don't exactly know what framework/library your this.firestore comes from, but I think you're looking for something like:

```<code>this.firestore.getDocuments({
  path: ['Posts', this.postData.postId, 'PostLikes'],
  ...
</code>```

Body:
getLikeInfo() {
  this.firestore.getDocument({
    path: ['Posts', this.postData.postId],
    onComplete: (result) => {
      let userDocument = result.data();
      this.userLikeId = userDocument!['creatorId'];
    },
  });

I want access to the sub collection "PostLinks". I tried more and more thing, but none work. Can someone explain me how I can access on a sub collection?

Body:
I don't exactly know what framework/library your this.firestore comes from, but I think you're looking for something like:

this.firestore.getDocuments({
  path: ['Posts', this.postData.postId, 'PostLikes'],
  ...


来源: stackexchange

问:
How to create custom field validation decorators in NestJS with GraphQL
I'm working on a NestJS API with apollo-server-express and I have the next InputType for appointments:

```<code>@InputType()
export class AppointmentInput {
    @Field(of => String)
    @IsNotEmpty()
    name: string;

    @Field(of => String)
    @IsNotEmpty()
    @IsDateString()
    dateStart: string;

    @Field(of => String)
    @IsNotEmpty()
    @IsDateString()
    dateEnd: string;

    @Field(of => Boolean)
    @IsBoolean()
    paid: boolean;

    @Field(of => Int)
    idDoctor: number;

    @Field(of => Int)
    idPatient: number;
    @Field(of => Int)
    idService: number;
}
</code>```

Let's say I want to validate if the name has some "a" letter with a Pipe:

```<code>import { PipeTransform, Injectable, ArgumentMetadata, HttpException, HttpStatus } from '@nestjs/common';

@Injectable()
export class NamePipe implements PipeTransform<string, string>{
  transform(name: string, metadata: ArgumentMetadata) {
    if (name.includes('a')) {
      throw new HttpException('The name has an a', HttpStatus.BAD_REQUEST);
    }
    return name;
  }
}
</code>```

But if use it like this:

```<code>@Field(of => String)
@IsNotEmpty()
@UsePipes(NamePipe)
name: string;
</code>```

It throws me the next error:

The return type of a property decorator function must be either 'void' or 'any'.
Unable to resolve signature of property decorator when called as an expression.
Type 'TypedPropertyDescriptor' is not assignable to type 'void'.

How can I solve this and use custom decorators to validate my fields? Also is important that my decorators can call services, because maybe in the future I want to validate for example the role id, and check if in the database exists a role with that id and if not throw an error.

答: I think you should rather create a custom class-validator decorator and use it like any class-validator decorator, assuming you've already applied a global NestJS validation pipe</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a NestJS API with apollo-server-express and I have the next InputType for appointments:

@InputType()
export class AppointmentInput {
    @Field(of => String)
    @IsNotEmpty()
    name: string;

    @Field(of => String)
    @IsNotEmpty()
    @IsDateString()
    dateStart: string;

    @Field(of => String)
    @IsNotEmpty()
    @IsDateString()
    dateEnd: string;

    @Field(of => Boolean)
    @IsBoolean()
    paid: boolean;

    @Field(of => Int)
    idDoctor: number;

    @Field(of => Int)
    idPatient: number;
    @Field(of => Int)
    idService: number;
}

Let's say I want to validate if the name has some "a" letter with a Pipe:

import { PipeTransform, Injectable, ArgumentMetadata, HttpException, HttpStatus } from '@nestjs/common';

@Injectable()
export class NamePipe implements PipeTransform<string, string>{
  transform(name: string, metadata: ArgumentMetadata) {
    if (name.includes('a')) {
      throw new HttpException('The name has an a', HttpStatus.BAD_REQUEST);
    }
    return name;
  }
}

But if use it like this:

@Field(of => String)
@IsNotEmpty()
@UsePipes(NamePipe)
name: string;

It throws me the next error:

The return type of a property decorator function must be either 'void' or 'any'.
Unable to resolve signature of property decorator when called as an expression.
Type 'TypedPropertyDescriptor' is not assignable to type 'void'.

How can I solve this and use custom decorators to validate my fields? Also is important that my decorators can call services, because maybe in the future I want to validate for example the role id, and check if in the database exists a role with that id and if not throw an error.


问:
Why does this for loop in C program print Hi 11 times?
```<code>#include <stdio.h>
int main()
{
int i = 1024;
for (; i; i >>= 1)
printf("Hi");
return 0;
}
</code>```

Why does the for loop print Hi 11 times? I don't understand.

Body:
#include <stdio.h>
int main()
{
int i = 1024;
for (; i; i >>= 1)
printf("Hi");
return 0;
}

Why does the for loop print Hi 11 times? I don't understand.

Body:
#include <stdio.h>

int main()
{
    for (int i = 1024; i>0; i >>= 1) {
        printf("%d ", i);
    }

    // proccess above as follows:

    // 1024 (decimal) equal with 00000100 00000000 (binary)
    //
    //  1024 >>= 1 mean rotate 00000100 00000000 to right one bit (put 0 bit in left positin, values will be shift to right one bit each loop)
    //  00000100 00000000  = 1024 (STEP 1) > START
    //  00000010 00000000  = 512  (STEP 2)
    //  00000001 00000000  = 256  (STEP 3)
    //  00000000 10000000  = 128  (STEP 4)
    //  00000000 01000000  = 64   (STEP 5)
    //  00000000 00100000  = 32   (STEP 6)
    //  00000000 00010000  = 16   (STEP 7)
    //  00000000 00001000  = 8    (STEP 8)
    //  00000000 00000100  = 4    (STEP 9)
    //  00000000 00000010  = 2    (STEP 10)
    //  00000000 00000001  = 1    (STEP 11) > FINISH
}


问:
How can reshape 2d tensor to 1d
```<code>tensor([[0, 5],
        [1, 4],
        [2, 2],
        [4, 2],
        [7, 9],
        [2, 0])
</code>```

I want to reshape this tensor to

```<code>tensor([[5],
        [14],
        [22],
        [42],
        [79],
        [20])
</code>```

how can i solve this problem? please help me

答:
I don't know about tensor data type, but for normal list you can iterate over each inner list and convert them to digit

def toDigit(l):
    z = 1
    s = 0
    for v in l[::-1]:
        s += v * z
        z *= 10
    return s

a = [[0, 5],[1, 4],[2, 2],[4, 2],[7, 9],[2, 0], [0,0]]
print([toDigit(t) for t in a])
```
<p>The output will be:</p>
<pre class="lang-python prettyprint-override"><code>[5, 14, 22, 42, 79, 20, 0]
</code>```

Title: How can reshape 2d tensor to 1d

Body:
tensor([[0, 5],
        [1, 4],
        [2, 2],
        [4, 2],
        [7, 9],
        [2, 0])

I want to reshape this tensor to

tensor([[5],
        [14],
        [22],
        [42],
        [79],
        [20])

how can i solve this problem? please help me

Body:
I don't know about tensor data type, but for normal list you can iterate over each inner list and convert them to digit

def toDigit(l):
    z = 1
    s = 0
    for v in l[::-1]:
        s += v * z
        z *= 10
    return s

a = [[0, 5],[1, 4],[2, 2],[4, 2],[7, 9],[2, 0], [0,0]]
print([toDigit(t) for t in a])

The output will be:

[5, 14, 22, 42, 79, 20, 0]


问:
Why is 'undefined' returned when comparing an function argument to a string from a function?
I created cpuPlay to call either rock, paper, or scissors, whenever a random number between 0-2 is called. This function works properly, but rps() is the function that I can't seem to build properly after 3 days of doing this. No matter how I build this, it seems I keep on getting one of four answers when I call rps(). The answers I get are either 'rock','paper','scissors','undefined'.

Before I thought it was because I used .toLowerCase() on playerChoice, but either way, this function has been giving the same results. If you keep on running rps('paper'), it eventually shows. I'm not sure how I should go any further with this problem, or maybe I'm not supposed to be able to compare.  I don't even know anymore.

```<code>function cpuPlay(){
    let numberGen = Math.floor(Math.random() * 3)

  if (numberGen === 0){
    return 'rock'
  }
  if (numberGen === 1){
    return 'paper'
  }
  if (numberGen === 2){
    return 'scissors'
  }
}
// cpuPlay()

function rps(playersChoice){
  if(playersChoice == 'paper' && cpuPlay() == 'rock'){
    console.log('rock')
  } else if (playersChoice == 'paper' && cpuPlay() == 'paper'){
    console.log('paper')
  } else if (playersChoice == 'paper' &&  cpuPlay() == 'scissors'){
    console.log('scissors');
  }
}
rps('paper')
</code>```

答:
cpuPlay() generates a random value every time you call it.

You are generating a random value and comparing it to rock. Then you generate a new random value and compare it to paper. Then you generate a third random value and compare it to scissors.

You should generate the CPU player's response once, at the top of the comparison function and then compare that value each time.

```<code>function rps(playersChoice){
    const cpuChoice = cpuPlay();
    if(playersChoice == 'paper' && cpuChoice == 'rock'){
</code>```

Body:
I created cpuPlay to call either rock, paper, or scissors, whenever a random number between 0-2 is called. This function works properly, but rps() is the function that I can't seem to build properly after 3 days of doing this. No matter how I build this, it seems I keep on getting one of four answers when I call rps(). The answers I get are either 'rock','paper','scissors','undefined'.

Before I thought it was because I used .toLowerCase() on playerChoice, but either way, this function has been giving the same results. If you keep on running rps('paper'), it eventually shows. I'm not sure how I should go any further with this problem, or maybe I'm not supposed to be able to compare.  I don't even know anymore.

function cpuPlay(){
    let numberGen = Math.floor(Math.random() * 3)

  if (numberGen === 0){
    return 'rock'
  }
  if (numberGen === 1){
    return 'paper'
  }
  if (numberGen === 2){
    return 'scissors'
  }
}
// cpuPlay()

function rps(playersChoice){
  if(playersChoice == 'paper' && cpuPlay() == 'rock'){
    console.log('rock')
  } else if (playersChoice == 'paper' && cpuPlay() == 'paper'){
    console.log('paper')
  } else if (playersChoice == 'paper' &&  cpuPlay() == 'scissors'){
    console.log('scissors');
  }
}
rps('paper')

Body:
cpuPlay() generates a random value every time you call it.

You are generating a random value and comparing it to rock. Then you generate a new random value and compare it to paper. Then you generate a third random value and compare it to scissors.

You should generate the CPU player's response once, at the top of the comparison function and then compare that value each time.

function rps(playersChoice){
    const cpuChoice = cpuPlay();
    if(playersChoice == 'paper' && cpuChoice == 'rock'){


问:
How to get intellisense for express.js in vscode
I have tried installing type definitions with:

My code is in server.js javascript file.

npm install @types/express

But still it doesn't seem to give intellisense for app after instantiating express .

But when I use express like this :

```<code>app = express() ;

app.listen(8000) ;
</code>```

I am not getting the codecompletion or intellisense for app instance of express.

How to fix this ?

答:
Quick Fix

Add this JsDoc comment to your controllers:

/** @type {import("express").RequestHandler} */
exports.myController = (req, res) => {
  // biz logic. ( here you would get intelliscence on req, res objects )
  const { id } = req.query;
  const { data } = req.body;
  res.status(200).json({data});
}

```
<h4>Optional</h4>
<p>If you are using typescript you can create a utility function to wrap your actual handler to avoid writing RequestHandler types on every controller.</p>
```// endpoint.ts
import { RequestHandler } from 'express';

export const endpoint = (cb: RequestHandler) => {
  const handler: RequestHandler  = (req, res, next) => {
    cb(req,res,next)
  }
  return handler
}
```
```// myController.ts
import { endpoint } from 'utils/endpoint';

export const myEndpoint = endpoint((req,res) => {
  res.send("Hey!");
});

```

Body:
I have tried installing type definitions with:

My code is in server.js javascript file.

npm install @types/express

But still it doesn't seem to give intellisense for app after instantiating express .

But when I use express like this :

app = express() ;

app.listen(8000) ;

I am not getting the codecompletion or intellisense for app instance of express.

How to fix this ?

Body:
Quick Fix

Add this JsDoc comment to your controllers:

/** @type {import("express").RequestHandler} */
exports.myController = (req, res) => {
  // biz logic. ( here you would get intelliscence on req, res objects )
  const { id } = req.query;
  const { data } = req.body;
  res.status(200).json({data});
}

Optional

If you are using typescript you can create a utility function to wrap your actual handler to avoid writing RequestHandler types on every controller.

// endpoint.ts
import { RequestHandler } from 'express';

export const endpoint = (cb: RequestHandler) => {
  const handler: RequestHandler  = (req, res, next) => {
    cb(req,res,next)
  }
  return handler
}

// myController.ts
import { endpoint } from 'utils/endpoint';

export const myEndpoint = endpoint((req,res) => {
  res.send("Hey!");
});


问:
How can delete User in Django and DRF using serializers and generic views
I am trying to make user CRUD functions, I have made other functions but can't figure out the way to delete the user using the API, It will be also great if you can provide a review on the code, am I doing it correctly, and in safe way.

Here are the serializers I am using:

serializers.py

```<code>
from .models import User

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(
        max_length=128,
        min_length=8,
        write_only=True
    )

    class Meta:
        model = User
        fields = ('email', 'password', 'first_name', 'last_name')
        extra_kwargs = {
            'password': {'write_only': True},
            'first_name': {'required': True},
            'last_name': {'required': True},
        }

    def create(self, validated_data):
        user = User(
            email = validated_data['email'],
            first_name = validated_data['first_name'],
            last_name = validated_data['last_name']
        )
        user.set_password(validated_data['password'])
        user.save()
        return user

class UpdateUserSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(required=True)

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')
        extra_kwargs = {
            'first_name': {'required': True},
            'last_name': {'required': True},
        }

    def validate_email(self, value):
        user = self.context['request'].user
        if User.objects.exclude(pk=user.pk).filter(email=value).exists():
            raise serializers.ValidationError({"email": "This email is already in use."})
        return value

    def update(self, instance, validated_data):
        user = self.context['request'].user
        if user.pk != instance.pk:
            raise serializers.ValidationError({"authorize": "You dont have permission for this user."})
        instance.first_name = validated_data['first_name']
        instance.last_name = validated_data['last_name']
        instance.email = validated_data['email']
        instance.save()
        return instance
</code>```

views.py

```<code>from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth import get_user_model

from .serializers import UserSerializer, UpdateUserSerializer, ChangePasswordSerializer
# Create your views here.

class UserCreate(generics.CreateAPIView):
    authentication_classes = ()
    permission_classes = ()
    serializer_class = UserSerializer

class ChangePasswordView(generics.UpdateAPIView):
    User = get_user_model()
    queryset = User.objects.all()
    permission_classes = (IsAuthenticated,)
    serializer_class = ChangePasswordSerializer

class UpdateUserView(generics.UpdateAPIView):
    User = get_user_model()
    queryset = User.objects.all()
    permission_classes = (IsAuthenticated,)
    serializer_class = UpdateUserSerializer

class HelloView(APIView):
    permission_classes = (IsAuthenticated, )

    def get(self, request):
        content = {'message':'Hello World!'}
        return Response(content)
</code>```

urls.py

```<code>from django.urls import path
from rest_framework_simplejwt import views

from .views import (
    UserCreate,
    UpdateUserView,
    ChangePasswordView,
    HelloView
    )

urlpatterns = [
    path('create/', UserCreate.as_view(), name='user_create'),
    path('token/', views.TokenObtainPairView.as_view(), name='token_optain_pair'),
    path('token/refresh/', views.TokenRefreshView.as_view(), name='token_refresh'),
    path('hello/', HelloView.as_view(), name='hello'),
    path('update/<int:pk>/', UpdateUserView.as_view(), name='update_user'),
    path('change_password/<int:pk>/', ChangePasswordView.as_view(), name='auth_change_password'),
]
</code>```

I am learning Django and DRF so please let me know if I am doing any thing wrong here, thanks

答:
```<code>class UserSerializer(serializers.ModelSerializer):
    class Meta:
          model = User
          fields = '__all__'

class UserDeleteApi(generics.DestroyAPIView):
   queryset = User.objects.all()
   serializer_class = UserSerializer

path('api/<int:pk>/delete',UserDeleteApi.as_view())
</code>```

You Can try this way

Body:
I am trying to make user CRUD functions, I have made other functions but can't figure out the way to delete the user using the API, It will be also great if you can provide a review on the code, am I doing it correctly, and in safe way.

Here are the serializers I am using:

serializers.py

from .models import User

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(
        max_length=128,
        min_length=8,
        write_only=True
    )

    class Meta:
        model = User
        fields = ('email', 'password', 'first_name', 'last_name')
        extra_kwargs = {
            'password': {'write_only': True},
            'first_name': {'required': True},
            'last_name': {'required': True},
        }

    def create(self, validated_data):
        user = User(
            email = validated_data['email'],
            first_name = validated_data['first_name'],
            last_name = validated_data['last_name']
        )
        user.set_password(validated_data['password'])
        user.save()
        return user

class UpdateUserSerializer(serializers.ModelSerializer):
    email = serializers.EmailField(required=True)

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')
        extra_kwargs = {
            'first_name': {'required': True},
            'last_name': {'required': True},
        }

    def validate_email(self, value):
        user = self.context['request'].user
        if User.objects.exclude(pk=user.pk).filter(email=value).exists():
            raise serializers.ValidationError({"email": "This email is already in use."})
        return value

    def update(self, instance, validated_data):
        user = self.context['request'].user
        if user.pk != instance.pk:
            raise serializers.ValidationError({"authorize": "You dont have permission for this user."})
        instance.first_name = validated_data['first_name']
        instance.last_name = validated_data['last_name']
        instance.email = validated_data['email']
        instance.save()
        return instance

views.py

from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth import get_user_model

from .serializers import UserSerializer, UpdateUserSerializer, ChangePasswordSerializer
# Create your views here.

class UserCreate(generics.CreateAPIView):
    authentication_classes = ()
    permission_classes = ()
    serializer_class = UserSerializer

class ChangePasswordView(generics.UpdateAPIView):
    User = get_user_model()
    queryset = User.objects.all()
    permission_classes = (IsAuthenticated,)
    serializer_class = ChangePasswordSerializer

class UpdateUserView(generics.UpdateAPIView):
    User = get_user_model()
    queryset = User.objects.all()
    permission_classes = (IsAuthenticated,)
    serializer_class = UpdateUserSerializer

class HelloView(APIView):
    permission_classes = (IsAuthenticated, )

    def get(self, request):
        content = {'message':'Hello World!'}
        return Response(content)

urls.py

from django.urls import path
from rest_framework_simplejwt import views

from .views import (
    UserCreate,
    UpdateUserView,
    ChangePasswordView,
    HelloView
    )

urlpatterns = [
    path('create/', UserCreate.as_view(), name='user_create'),
    path('token/', views.TokenObtainPairView.as_view(), name='token_optain_pair'),
    path('token/refresh/', views.TokenRefreshView.as_view(), name='token_refresh'),
    path('hello/', HelloView.as_view(), name='hello'),
    path('update/<int:pk>/', UpdateUserView.as_view(), name='update_user'),
    path('change_password/<int:pk>/', ChangePasswordView.as_view(), name='auth_change_password'),
]

I am learning Django and DRF so please let me know if I am doing any thing wrong here, thanks

Body:
class UserSerializer(serializers.ModelSerializer):
    class Meta:
          model = User
          fields = '__all__'

class UserDeleteApi(generics.DestroyAPIView):
   queryset = User.objects.all()
   serializer_class = UserSerializer

path('api/<int:pk>/delete',UserDeleteApi.as_view())

You Can try this way


问:
Is there a function in python to number the time an item appears in the dataframe?
I am trying to check when a client appears in my dataframe to do some logic with other results. However, I am unable to number when the customer appears. I've gotten the first and last time it appears, I just can't get it in the intervals between the first and last time. Could you please help me? Here is an example table, I want column C as the result.

```<code>Date    Customer    Appear
01/01/2021  A   1
01/01/2021  B   1
01/01/2021  C   1
01/02/2021  A   2
01/02/2021  B   2
01/02/2021  C   2
01/03/2021  A   3
01/03/2021  B   3
01/03/2021  C   3
01/04/2021  A   4
01/04/2021  B   4
01/05/2021  A   5
01/05/2021  B   5
01/06/2021  A   6
</code>```

答:
You can try with groupby with cumcount

```<code>df['new'] = df.groupby('Customer').cumcount()+1
Out[202]:
0     1
1     1
2     1
3     2
4     2
5     2
6     3
7     3
8     3
9     4
10    4
11    5
12    5
13    6
dtype: int64
</code>```

Body:
I am trying to check when a client appears in my dataframe to do some logic with other results. However, I am unable to number when the customer appears. I've gotten the first and last time it appears, I just can't get it in the intervals between the first and last time. Could you please help me? Here is an example table, I want column C as the result.

Date    Customer    Appear
01/01/2021  A   1
01/01/2021  B   1
01/01/2021  C   1
01/02/2021  A   2
01/02/2021  B   2
01/02/2021  C   2
01/03/2021  A   3
01/03/2021  B   3
01/03/2021  C   3
01/04/2021  A   4
01/04/2021  B   4
01/05/2021  A   5
01/05/2021  B   5
01/06/2021  A   6

Body:
You can try with groupby with cumcount

df['new'] = df.groupby('Customer').cumcount()+1
Out[202]:
0     1
1     1
2     1
3     2
4     2
5     2
6     3
7     3
8     3
9     4
10    4
11    5
12    5
13    6
dtype: int64


问:
Not accurately read numeric number with a DataReader from SQLite
I got a problem where I can't read the data from my database correctly.

To give you an example, I got the important value that is in the database 6.69879289850025E-06, but I read 6.0 (which is not accurate since it's suppose to be way smaller) in the C# program.

Something similar happen to ImportantValue2 where the value that is in the database is -0,000158976621370616 and in my C# program I get 0,0.

```<code> public double ImportantValue1 { get; set; }
 public double ImportantValue2 { get; set; }
 public string Note { get; set; }

public MyObject(SQLiteDataReader reader)
        {
            ImportantValue1 = Convert.ToDouble(reader["important_value_1"]); //Value in the database is REAL
            ImportantValue2 = Convert.ToDouble(reader["important_value_2"]);//Value in the database is REAL
            Note = reader["note"].ToString(); //Value in the database is TEXT
        }
</code>```

Update

And this is how I call it.

```<code>using (SQLiteConnection c = new SQLiteConnection(connection))
{
    c.Open();
    using (SQLiteCommand cmd = new SQLiteCommand(sqlCommand, c))
    {
        using (SQLiteDataReader reader = cmd.ExecuteReader())
        {
            if (reader.Read())
            {
                objectFromBD = new MyObject(reader);
            }
        }
    }
}

</code>```

And the SQLite code

```<code>CREATE TABLE "table"(
    "id" INTEGER,
    "important_value_1" REAL NOT NULL,
    "important_value_2" REAL NOT NULL,
    "note" TEXT NOT NULL,

    PRIMARY KEY ("id" AUTOINCREMENT)
);
</code>```

Thank you for your help!

答:
reader["important_value_1"] will return index which column exists in your SQL script instead of your expectation value.

reader["important_value_1"] will get the value of the specified column.

You can try to use reader["important_value_1"] in reader.GetDouble function to read your data from columns.

```<code>ImportantValue1  = reader.GetDouble(reader["important_value_1"])
ImportantValue2  = reader.GetDouble(reader["important_value_2"])
</code>```

SqliteDataReader.Item[] Property

Note

You might need to use reader.Read() let the reader point to read the next row if you want.

```<code>while (reader.Read()){
   //... read all rows from your db
}
</code>```

Body:
I got a problem where I can't read the data from my database correctly.

To give you an example, I got the important value that is in the database 6.69879289850025E-06, but I read 6.0 (which is not accurate since it's suppose to be way smaller) in the C# program.

Something similar happen to ImportantValue2 where the value that is in the database is -0,000158976621370616 and in my C# program I get 0,0.

 public double ImportantValue1 { get; set; }
 public double ImportantValue2 { get; set; }
 public string Note { get; set; }

public MyObject(SQLiteDataReader reader)
        {
            ImportantValue1 = Convert.ToDouble(reader["important_value_1"]); //Value in the database is REAL
            ImportantValue2 = Convert.ToDouble(reader["important_value_2"]);//Value in the database is REAL
            Note = reader["note"].ToString(); //Value in the database is TEXT
        }

Update

And this is how I call it.

using (SQLiteConnection c = new SQLiteConnection(connection))
{
    c.Open();
    using (SQLiteCommand cmd = new SQLiteCommand(sqlCommand, c))
    {
        using (SQLiteDataReader reader = cmd.ExecuteReader())
        {
            if (reader.Read())
            {
                objectFromBD = new MyObject(reader);
            }
        }
    }
}

And the SQLite code

CREATE TABLE "table"(
    "id" INTEGER,
    "important_value_1" REAL NOT NULL,
    "important_value_2" REAL NOT NULL,
    "note" TEXT NOT NULL,

    PRIMARY KEY ("id" AUTOINCREMENT)
);

Thank you for your help!

Body:
reader["important_value_1"] will return index which column exists in your SQL script instead of your expectation value.

reader["important_value_1"] will get the value of the specified column.

You can try to use reader["important_value_1"] in reader.GetDouble function to read your data from columns.

ImportantValue1  = reader.GetDouble(reader["important_value_1"])
ImportantValue2  = reader.GetDouble(reader["important_value_2"])

SqliteDataReader.Item[] Property

Note

You might need to use reader.Read() let the reader point to read the next row if you want.

while (reader.Read()){
   //... read all rows from your db
}


问:
Is there a way to create an array of an element that contains a specific CSS style?
I'm trying to capture the elements that do not contain a display type of none.

```<code>let pfCard = document.getElementsByClassName("PortfolioCard").style.display = 'block';
</code>```

This doesn't seem to be working as I believe it is attempting to modify the style type instead of retrieve it.

答:
Maybe this one?

console.log([...document.getElementsByClassName("PortfolioCard")].filter(item=> window.getComputedStyle(item).getPropertyValue('display') != "block"))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='PortfolioCard' style='display:block'></div>
<div class="PortfolioCard" style="display:block"></div>
<div class="PortfolioCard" style='display:none'></div></code>```

Or usearray.forEach:

let arr= [];
[...document.getElementsByClassName("PortfolioCard")].forEach(item=>{
if(window.getComputedStyle(item).getPropertyValue('display') != "block")
arr.push(item)
})
console.log(arr)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='PortfolioCard' style='display:block'></div>
<div class="PortfolioCard" style="display:block"></div>
<div class="PortfolioCard" style='display:none'></div></code>```

Body:
I'm trying to capture the elements that do not contain a display type of none.

let pfCard = document.getElementsByClassName("PortfolioCard").style.display = 'block';

This doesn't seem to be working as I believe it is attempting to modify the style type instead of retrieve it.

Body:
Maybe this one?

console.log([...document.getElementsByClassName("PortfolioCard")].filter(item=> window.getComputedStyle(item).getPropertyValue('display') != "block"))

<div class='PortfolioCard' style='display:block'></div>
<div class="PortfolioCard" style="display:block"></div>
<div class="PortfolioCard" style='display:none'></div>

Or usearray.forEach:

let arr= [];
[...document.getElementsByClassName("PortfolioCard")].forEach(item=>{
if(window.getComputedStyle(item).getPropertyValue('display') != "block")
arr.push(item)
})
console.log(arr)

<div class='PortfolioCard' style='display:block'></div>
<div class="PortfolioCard" style="display:block"></div>
<div class="PortfolioCard" style='display:none'></div>


问:
Docker and playwright
I need to install playwright inside of docker. This is my dockerfile.

```<code>FROM python:3.9

EXPOSE 8000

WORKDIR /fastanalytics

COPY /requirements.txt /fastanalytics/requirements.txt

RUN pip install --no-cache-dir --upgrade -r /fastanalytics/requirements.txt

RUN playwright install
RUN playwright install-deps
RUN apt-get update && apt-get upgrade -y

</code>```

But when I am installing I got the below error. I tried installing everything in the error message but it didn't help.

```<code>E: Package 'ttf-ubuntu-font-family' has no installation candidate
E: Unable to locate package libenchant1c2a
E: Unable to locate package libicu66
E: Package 'libjpeg-turbo8' has no installation candidate
</code>```

答:
Based on their docs (https://playwright.dev/python/docs/cli#install-system-dependencies), it looks like they only officially support Ubuntu systems whereas the python:3.9 is based off of Debian. Try using Ubuntu as your base image and install python on it:

```<code>FROM ubuntu:20.04

RUN apt update
RUN apt install python3.9

...
</code>```

Title: Docker and playwright

Body:
I need to install playwright inside of docker. This is my dockerfile.

FROM python:3.9

EXPOSE 8000

WORKDIR /fastanalytics

COPY /requirements.txt /fastanalytics/requirements.txt

RUN pip install --no-cache-dir --upgrade -r /fastanalytics/requirements.txt

RUN playwright install
RUN playwright install-deps
RUN apt-get update && apt-get upgrade -y

But when I am installing I got the below error. I tried installing everything in the error message but it didn't help.

E: Package 'ttf-ubuntu-font-family' has no installation candidate
E: Unable to locate package libenchant1c2a
E: Unable to locate package libicu66
E: Package 'libjpeg-turbo8' has no installation candidate

Body:
Based on their docs (https://playwright.dev/python/docs/cli#install-system-dependencies), it looks like they only officially support Ubuntu systems whereas the python:3.9 is based off of Debian. Try using Ubuntu as your base image and install python on it:

FROM ubuntu:20.04

RUN apt update
RUN apt install python3.9

...


问:
Converting "Stream<String>" to "String" in java8 to combine group of strings in a stream
I want to convert Stream<String> to String and print all the string.

```<code>Stream<String> result= Stream.of("do","re","ma","po","fa","si")
                             .filter(str -> str.length()>5)
                             .peek(System.out:: println);
                           //.allMatch(str -> str.length() >5);

System.out.println(result);
</code>```

Here down output i get

java.util.Spliterators$1Adapter@63961c42

The result is printing an object but not a String and while converting to toString() also printing the same but how to print as a String

答:
You misunderstand the mechanisms behind the Stream API.

A stream pipeline consists of a source (which might be an array, a
collection, a generator function, an I/O channel, etc), zero or more
intermediate operations (which transform a stream into another stream,
such as filter(Predicate)), and a terminal operation (which produces a
result or side-effect, such as count() or forEach(Consumer)). Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only
as needed.

The main conclusion:

Operations on the data in the pipeline will be performed only if the terminal operation is initiated.

Stream without a terminal operation is perfectly valid from the compiler's perspective of view. It will compile, but it'll not be executed.

And what you have tried to print (java.util.Spliterators$1Adapter@63961c42) isn't a result, but the stream object itself.

To produce a result or side-effect Stream-pipeline must end with a terminal operation (collect(), reduce(), count(), forEach(), findFirst(), findAny, anyMatch() - which commented out in your code). Note, that peek() is an intermediate operation and confuse it with forEach(). You can use peek() as many time as need, which can be useful for debugging purposes.

```<code>    public static void main(String[] args) {

        String result = getStream()
                .filter(str -> str.length() > 5 && str.length() < 8)
                .findFirst() // that will produce a single result that may or may not be present
                .orElseThrow(); // action for the case if result is not present

        System.out.println("Single result: " + result + "\n");

        getStream()
                .filter(str -> str.contains("a"))
                .peek(System.out::println) // intermediate operation that will print every element that matches the first filter
                .filter(str -> str.length() > 8)
                .forEach(System.out::println); // terminal operation that prints every element remained after processing the pipeline
    }

    private static Stream<String> getStream() {
        return Stream.of("Ignoranti", "quem", "portum", "petat", "nullus", "suus", "ventus", "est");
    }
</code>```

output

```<code>Single result: portum

Ignoranti
Ignoranti
petat
</code>```

Body:
I want to convert Stream<String> to String and print all the string.

Stream<String> result= Stream.of("do","re","ma","po","fa","si")
                             .filter(str -> str.length()>5)
                             .peek(System.out:: println);
                           //.allMatch(str -> str.length() >5);

System.out.println(result);

Here down output i get

java.util.Spliterators$1Adapter@63961c42

The result is printing an object but not a String and while converting to toString() also printing the same but how to print as a String

Body:
You misunderstand the mechanisms behind the Stream API.

A stream pipeline consists of a source (which might be an array, a
collection, a generator function, an I/O channel, etc), zero or more
intermediate operations (which transform a stream into another stream,
such as filter(Predicate)), and a terminal operation (which produces a
result or side-effect, such as count() or forEach(Consumer)). Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only
as needed.

The main conclusion:

Operations on the data in the pipeline will be performed only if the terminal operation is initiated.

Stream without a terminal operation is perfectly valid from the compiler's perspective of view. It will compile, but it'll not be executed.

And what you have tried to print (java.util.Spliterators$1Adapter@63961c42) isn't a result, but the stream object itself.

To produce a result or side-effect Stream-pipeline must end with a terminal operation (collect(), reduce(), count(), forEach(), findFirst(), findAny, anyMatch() - which commented out in your code). Note, that peek() is an intermediate operation and confuse it with forEach(). You can use peek() as many time as need, which can be useful for debugging purposes.

    public static void main(String[] args) {

        String result = getStream()
                .filter(str -> str.length() > 5 && str.length() < 8)
                .findFirst() // that will produce a single result that may or may not be present
                .orElseThrow(); // action for the case if result is not present

        System.out.println("Single result: " + result + "\n");

        getStream()
                .filter(str -> str.contains("a"))
                .peek(System.out::println) // intermediate operation that will print every element that matches the first filter
                .filter(str -> str.length() > 8)
                .forEach(System.out::println); // terminal operation that prints every element remained after processing the pipeline
    }

    private static Stream<String> getStream() {
        return Stream.of("Ignoranti", "quem", "portum", "petat", "nullus", "suus", "ventus", "est");
    }

output

Single result: portum

Ignoranti
Ignoranti
petat


问:
"Console.log" with Photoshop Scripting - ExtendedScript Toolkit
I'm doing a bit of Photoshop scripting for the first time and it sure would be great to have a console.log-like function to output array and object values in the Javascript console of the ExtendScript Toolkit App.

Is there an equivalent function?

答:
Log to a file instead

I know this is old, but I was recently in need of logging for some values of an InDesign script and I'd like to share my "solution".

My first problem was that I didn't even figure out where the output produced by $.writeln() goes. So I resorted to a crude function that logs to a file in the document directory. Maybe it'll be of use to somebody. I'm guessing this may work for Photoshop or other ExtendScript environments as well.

I learned that ExtendScript does not support JSON methods, so I used a polyfill. Simply put the file (in my case json2.js) in the same directory as your .jsx.

#include "json2.js"; // include polyfill file

function log (input) {
    if(!debug) return;
    if(!JSON || !JSON.stringify) return;

    var now = new Date();
    var output = JSON.stringify(input);

    $.writeln(now.toTimeString() + ": " + output);

    var logFile = File(app.activeDocument.filePath + "/log.txt");
    logFile.open("a");
    logFile.writeln(now.toTimeString() + ": " + output);
    logFile.close();
}
```
<h2>Usage</h2>
<pre class="lang-js prettyprint-override"><code>var debug = true;

log("abc 123");
log([1, 3, 4343, "ddddd", null, false]);
</code>```

Use the debug variable to quickly enable or disable output.

ContentLicense: CC BY-SA 3.0

Body:
Log to a file instead

I know this is old, but I was recently in need of logging for some values of an InDesign script and I'd like to share my "solution".

My first problem was that I didn't even figure out where the output produced by $.writeln() goes. So I resorted to a crude function that logs to a file in the document directory. Maybe it'll be of use to somebody. I'm guessing this may work for Photoshop or other ExtendScript environments as well.

I learned that ExtendScript does not support JSON methods, so I used a polyfill. Simply put the file (in my case json2.js) in the same directory as your .jsx.

#include "json2.js"; // include polyfill file

function log (input) {
    if(!debug) return;
    if(!JSON || !JSON.stringify) return;

    var now = new Date();
    var output = JSON.stringify(input);

    $.writeln(now.toTimeString() + ": " + output);

    var logFile = File(app.activeDocument.filePath + "/log.txt");
    logFile.open("a");
    logFile.writeln(now.toTimeString() + ": " + output);
    logFile.close();
}

Usage

var debug = true;

log("abc 123");
log([1, 3, 4343, "ddddd", null, false]);

Use the debug variable to quickly enable or disable output.


问:
Visual Studio Code C# Extension not working
Windows 10 Pro x64

I have been trying for days to fix this issue, downloaded multiple different versions of the .NET SDK, but I still get this error from the C# extension:
"The .NET Core SDK cannot be located. .NET Core debugging will not be enabled. Make sure the .NET Core SDK is installed and is on the path."

I have gone to that help page, and it says to type where.exe into a cmd prompt window, which I did, and received a result, then referred back to the help page, and it said, "There are no known reasons why PATH wouldn't be propagated to the VS Code process."

Here are my OmniSharp output logs:

```<code>Starting OmniSharp server at 11/8/2021, 4:43:45 PM
    Target: c:\Users\eleph\Unity Projects\bEan\bEan.sln

OmniSharp server started.
    Path: c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\OmniSharp.exe
    PID: 15972

[info]: OmniSharp.Stdio.Host
        Starting OmniSharp on Windows 6.2.9200.0 (x64)
[info]: OmniSharp.Services.DotNetCliService
        Checking the 'DOTNET_ROOT' environment variable to find a .NET SDK
[info]: OmniSharp.Services.DotNetCliService
        Using the 'dotnet' on the PATH.
[info]: OmniSharp.Services.DotNetCliService
        DotNetPath set to dotnet
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        Located 1 MSBuild instance(s)
            1: StandAlone 17.0.0 - "c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin"
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        MSBUILD_EXE_PATH environment variable set to 'c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\MSBuild.exe'
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        Registered MSBuild instance: StandAlone 17.0.0 - "c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin"
            CscToolExe = csc.exe
            CscToolPath = c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Roslyn
            MSBuildExtensionsPath = c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild
            MSBuildToolsPath = c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.CSharpFormattingWorkspaceOptionsProvider, Order: 0
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.Completion.CompletionOptionsProvider, Order: 0
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.RenameWorkspaceOptionsProvider, Order: 100
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.ImplementTypeWorkspaceOptionsProvider, Order: 110
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.BlockStructureWorkspaceOptionsProvider, Order: 140
[info]: OmniSharp.Cake.CakeProjectSystem
        Detecting Cake files in 'c:\Users\eleph\Unity Projects\bEan'.
[info]: OmniSharp.Cake.CakeProjectSystem
        Could not find any Cake files
[info]: OmniSharp.MSBuild.ProjectSystem
        Detecting projects in 'c:\Users\eleph\Unity Projects\bEan\bEan.sln'.
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\UnityEngine.TestRunner.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.Timeline.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\UnityEngine.UI.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.TextMeshPro.csproj
[info]: OmniSharp.MSBuild.ProjectManager
        Queue project update for 'c:\Users\eleph\Unity Projects\bEan\Assembly-CSharp.csproj'
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\UnityEditor.TestRunner.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.PlasticSCM.Editor.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\UnityEditor.UI.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.Services.Core.Editor.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.Timeline.Editor.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.TextMeshPro.Editor.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.CollabProxy.Editor.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.Rider.Editor.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.VSCode.Editor.csproj
[info]: OmniSharp.Script.ScriptProjectSystem
        Detecting CSX files in 'c:\Users\eleph\Unity Projects\bEan'.
[info]: OmniSharp.Script.ScriptProjectSystem
        Could not find any CSX files
[info]: OmniSharp.WorkspaceInitializer
        Configuration finished.
[info]: OmniSharp.Stdio.Host
        Omnisharp server running using Stdio at location 'c:\Users\eleph\Unity Projects\bEan' on host 11172.
[info]: OmniSharp.MSBuild.ProjectManager
        Loading project: c:\Users\eleph\Unity Projects\bEan\Assembly-CSharp.csproj
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'Unity.VSCode.Editor.csproj' does not exist.
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'Unity.TextMeshPro.Editor.csproj' does not exist.
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'Unity.Timeline.Editor.csproj' does not exist.
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'Unity.Timeline.csproj' does not exist.
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'Unity.TextMeshPro.csproj' does not exist.
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'UnityEditor.UI.csproj' does not exist.
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'Unity.PlasticSCM.Editor.csproj' does not exist.
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'Unity.Rider.Editor.csproj' does not exist.
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'UnityEngine.UI.csproj' does not exist.
[fail]: OmniSharp.MSBuild.ProjectLoader
        The reference assemblies for ".NETFramework,Version=v5.0.402" were not found. You might be using an older .NET SDK to target .NET 5.0 or higher. Update Visual Studio and/or your .NET SDK.
[warn]: OmniSharp.MSBuild.ProjectManager
        Failed to load project file 'c:\Users\eleph\Unity Projects\bEan\Assembly-CSharp.csproj'.
c:\Users\eleph\Unity Projects\bEan\Assembly-CSharp.csproj
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'Unity.VSCode.Editor.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'Unity.TextMeshPro.Editor.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'Unity.Timeline.Editor.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'Unity.Timeline.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'Unity.TextMeshPro.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'UnityEditor.UI.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'Unity.PlasticSCM.Editor.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'Unity.Rider.Editor.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'UnityEngine.UI.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(1217,5): Error: The reference assemblies for ".NETFramework,Version=v5.0.402" were not found. You might be using an older .NET SDK to target .NET 5.0 or higher. Update Visual Studio and/or your .NET SDK.

[fail]: OmniSharp.MSBuild.ProjectManager
        Attempted to update project that is not loaded: c:\Users\eleph\Unity Projects\bEan\Assembly-CSharp.csproj

</code>```

For reference, this is a C# file from a Unity project, but regular C# files don't work either. Please help, I currently am programming without IntelliSense and without correct syntax highlighting, and it's driving me nuts.

答: Switched to VS, VSCode doesn't really have much Unity support compared to VS.</p>

Body:
Windows 10 Pro x64

I have been trying for days to fix this issue, downloaded multiple different versions of the .NET SDK, but I still get this error from the C# extension:
"The .NET Core SDK cannot be located. .NET Core debugging will not be enabled. Make sure the .NET Core SDK is installed and is on the path."

I have gone to that help page, and it says to type where.exe into a cmd prompt window, which I did, and received a result, then referred back to the help page, and it said, "There are no known reasons why PATH wouldn't be propagated to the VS Code process."

Here are my OmniSharp output logs:

Starting OmniSharp server at 11/8/2021, 4:43:45 PM
    Target: c:\Users\eleph\Unity Projects\bEan\bEan.sln

OmniSharp server started.
    Path: c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\OmniSharp.exe
    PID: 15972

[info]: OmniSharp.Stdio.Host
        Starting OmniSharp on Windows 6.2.9200.0 (x64)
[info]: OmniSharp.Services.DotNetCliService
        Checking the 'DOTNET_ROOT' environment variable to find a .NET SDK
[info]: OmniSharp.Services.DotNetCliService
        Using the 'dotnet' on the PATH.
[info]: OmniSharp.Services.DotNetCliService
        DotNetPath set to dotnet
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        Located 1 MSBuild instance(s)
            1: StandAlone 17.0.0 - "c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin"
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        MSBUILD_EXE_PATH environment variable set to 'c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\MSBuild.exe'
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        Registered MSBuild instance: StandAlone 17.0.0 - "c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin"
            CscToolExe = csc.exe
            CscToolPath = c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Roslyn
            MSBuildExtensionsPath = c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild
            MSBuildToolsPath = c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.CSharpFormattingWorkspaceOptionsProvider, Order: 0
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.Completion.CompletionOptionsProvider, Order: 0
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.RenameWorkspaceOptionsProvider, Order: 100
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.ImplementTypeWorkspaceOptionsProvider, Order: 110
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.BlockStructureWorkspaceOptionsProvider, Order: 140
[info]: OmniSharp.Cake.CakeProjectSystem
        Detecting Cake files in 'c:\Users\eleph\Unity Projects\bEan'.
[info]: OmniSharp.Cake.CakeProjectSystem
        Could not find any Cake files
[info]: OmniSharp.MSBuild.ProjectSystem
        Detecting projects in 'c:\Users\eleph\Unity Projects\bEan\bEan.sln'.
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\UnityEngine.TestRunner.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.Timeline.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\UnityEngine.UI.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.TextMeshPro.csproj
[info]: OmniSharp.MSBuild.ProjectManager
        Queue project update for 'c:\Users\eleph\Unity Projects\bEan\Assembly-CSharp.csproj'
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\UnityEditor.TestRunner.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.PlasticSCM.Editor.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\UnityEditor.UI.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.Services.Core.Editor.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.Timeline.Editor.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.TextMeshPro.Editor.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.CollabProxy.Editor.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.Rider.Editor.csproj
[warn]: OmniSharp.MSBuild.ProjectSystem
        Found project that doesn't exist on disk: c:\Users\eleph\Unity Projects\bEan\Unity.VSCode.Editor.csproj
[info]: OmniSharp.Script.ScriptProjectSystem
        Detecting CSX files in 'c:\Users\eleph\Unity Projects\bEan'.
[info]: OmniSharp.Script.ScriptProjectSystem
        Could not find any CSX files
[info]: OmniSharp.WorkspaceInitializer
        Configuration finished.
[info]: OmniSharp.Stdio.Host
        Omnisharp server running using Stdio at location 'c:\Users\eleph\Unity Projects\bEan' on host 11172.
[info]: OmniSharp.MSBuild.ProjectManager
        Loading project: c:\Users\eleph\Unity Projects\bEan\Assembly-CSharp.csproj
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'Unity.VSCode.Editor.csproj' does not exist.
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'Unity.TextMeshPro.Editor.csproj' does not exist.
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'Unity.Timeline.Editor.csproj' does not exist.
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'Unity.Timeline.csproj' does not exist.
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'Unity.TextMeshPro.csproj' does not exist.
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'UnityEditor.UI.csproj' does not exist.
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'Unity.PlasticSCM.Editor.csproj' does not exist.
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'Unity.Rider.Editor.csproj' does not exist.
[warn]: OmniSharp.MSBuild.ProjectLoader
        The referenced project 'UnityEngine.UI.csproj' does not exist.
[fail]: OmniSharp.MSBuild.ProjectLoader
        The reference assemblies for ".NETFramework,Version=v5.0.402" were not found. You might be using an older .NET SDK to target .NET 5.0 or higher. Update Visual Studio and/or your .NET SDK.
[warn]: OmniSharp.MSBuild.ProjectManager
        Failed to load project file 'c:\Users\eleph\Unity Projects\bEan\Assembly-CSharp.csproj'.
c:\Users\eleph\Unity Projects\bEan\Assembly-CSharp.csproj
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'Unity.VSCode.Editor.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'Unity.TextMeshPro.Editor.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'Unity.Timeline.Editor.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'Unity.Timeline.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'Unity.TextMeshPro.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'UnityEditor.UI.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'Unity.PlasticSCM.Editor.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'Unity.Rider.Editor.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2068,5): Error: The referenced project 'UnityEngine.UI.csproj' does not exist.
c:\Users\eleph\.vscode\extensions\ms-dotnettools.csharp-1.23.16\.omnisharp\1.37.16\.msbuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(1217,5): Error: The reference assemblies for ".NETFramework,Version=v5.0.402" were not found. You might be using an older .NET SDK to target .NET 5.0 or higher. Update Visual Studio and/or your .NET SDK.

[fail]: OmniSharp.MSBuild.ProjectManager
        Attempted to update project that is not loaded: c:\Users\eleph\Unity Projects\bEan\Assembly-CSharp.csproj

For reference, this is a C# file from a Unity project, but regular C# files don't work either. Please help, I currently am programming without IntelliSense and without correct syntax highlighting, and it's driving me nuts.


问:
awk remove before match but after empty line
I didn't find the exact similar question, so i need to ask:

I have a file gist :

```<code>...
must_be_intact

bad_line
bad_line
bad_line
match_line
...
</code>```

I use awk to remove everything before the match but after a space:

'NR==FNR{if (/match_line/) {
    i=0;
    while(1) {
        if (NR-i==/^\s*$/) break;
        del[NR-i];
        i=i-1;
        next
        }
    }
} !(FNR in del)'
```

But this does not work correctly. Help improve this code, or you can advise another way.

答:
You have overcomplicated it.

You can just use tac + awk + tac operations:

tac file | awk '/^match_line$/,!NF{next} 1' | tac
must_be_intact

must_be_intact
must_be_intact
must_be_intact

must_be_intact
must_be_intact
must_be_intact

must_be_intact

must_be_intact

must_be_intact
must_be_intact

must_be_intact
must_be_intact
must_be_intact

```

This awk uses a range from NF==0 (indicating empty line) to a line that just has match_line and uses next in action block to skip that part.

Body:
I didn't find the exact similar question, so i need to ask:

I have a file gist :

...
must_be_intact

bad_line
bad_line
bad_line
match_line
...

I use awk to remove everything before the match but after a space:

'NR==FNR{if (/match_line/) {
    i=0;
    while(1) {
        if (NR-i==/^\s*$/) break;
        del[NR-i];
        i=i-1;
        next
        }
    }
} !(FNR in del)'

But this does not work correctly. Help improve this code, or you can advise another way.

Body:
You have overcomplicated it.

You can just use tac + awk + tac operations:

tac file | awk '/^match_line$/,!NF{next} 1' | tac
must_be_intact

must_be_intact
must_be_intact
must_be_intact

must_be_intact
must_be_intact
must_be_intact

must_be_intact

must_be_intact

must_be_intact
must_be_intact

must_be_intact
must_be_intact
must_be_intact

This awk uses a range from NF==0 (indicating empty line) to a line that just has match_line and uses next in action block to skip that part.


答:
the cpuPlay() is returning random results at every if statement

so when in the first if and the result is not rock, it will jump to next statement again, then but at the second if, the cpuPlay() is returning different results, so end up your function has a chance to have no results.

function rps(playersChoice){
  let cpuRoll = cpuPlay(); // only random once per game
  if(playersChoice == 'paper' && cpuRoll == 'rock'){
    console.log('rock')
  } else if (playersChoice == 'paper' && cpuRoll == 'paper'){
    console.log('paper')
  } else if (playersChoice == 'paper' &&  cpuRoll == 'scissors'){
    console.log('scissors');
  }
}
```

Title: Why is 'undefined' returned when comparing an function argument to a string from a function?

Body:
I created cpuPlay to call either rock, paper, or scissors, whenever a random number between 0-2 is called. This function works properly, but rps() is the function that I can't seem to build properly after 3 days of doing this. No matter how I build this, it seems I keep on getting one of four answers when I call rps(). The answers I get are either 'rock','paper','scissors','undefined'.

Before I thought it was because I used .toLowerCase() on playerChoice, but either way, this function has been giving the same results. If you keep on running rps('paper'), it eventually shows. I'm not sure how I should go any further with this problem, or maybe I'm not supposed to be able to compare.  I don't even know anymore.

function cpuPlay(){
    let numberGen = Math.floor(Math.random() * 3)

  if (numberGen === 0){
    return 'rock'
  }
  if (numberGen === 1){
    return 'paper'
  }
  if (numberGen === 2){
    return 'scissors'
  }
}
// cpuPlay()

function rps(playersChoice){
  if(playersChoice == 'paper' && cpuPlay() == 'rock'){
    console.log('rock')
  } else if (playersChoice == 'paper' && cpuPlay() == 'paper'){
    console.log('paper')
  } else if (playersChoice == 'paper' &&  cpuPlay() == 'scissors'){
    console.log('scissors');
  }
}
rps('paper')


问:
What causes this syntax error when creating a table?
I am trying to create a table in MySQL, but I am getting an error. The code is looking OK to me, but I don't know why I am getting the error.

This is the code :

```<code>CREATE TABLE usage (
    user_id    VARCHAR(20) ,
    usage_date  DATE ,
    usage_location     VARCHAR(20) ,
    time_spent      INT
);
</code>```

The error that I am getting:

```<code>Query 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage (
    user_id    VARCHAR(20) ,
    usage_date  DATE ,
    usage_locatio' at line 1
</code>```

答:
try using some other names like usage1 for datausage because that is reserved</p>
```<code>CREATE TABLE stuffusage (
    user_id    VARCHAR(20) ,
    usage_date  DATE ,
    usage_location     VARCHAR(20) ,
    time_spent      INT
);
</code>```

Body:
I am trying to create a table in MySQL, but I am getting an error. The code is looking OK to me, but I don't know why I am getting the error.

This is the code :

CREATE TABLE usage (
    user_id    VARCHAR(20) ,
    usage_date  DATE ,
    usage_location     VARCHAR(20) ,
    time_spent      INT
);

The error that I am getting:

Query 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage (
    user_id    VARCHAR(20) ,
    usage_date  DATE ,
    usage_locatio' at line 1

Body:
try using some other names like usage1 for datausage because that is reserved

CREATE TABLE stuffusage (
    user_id    VARCHAR(20) ,
    usage_date  DATE ,
    usage_location     VARCHAR(20) ,
    time_spent      INT
);


问:
How can I compile a maven project from GitHub
I'm trying to download and compiler an open-source project from GitHub but with no success.

I was trying to compile Apache's Pulsar, as recently they pushed a vulnerability fix I need, but the new version is not out yet.

So in the meantime I wanted to compile it myself and when it is finally out I'll go back to their official release.

Is that possible?

It's a Maven project so from what I read I need to use 'maven package' but it failed during tests' stage because of noClassDefFound if I'm not mistaken.

I tried two different versions from their GitHub but it also fails there.

Any idea how can I do that?

答:
It's always mvn.

Make sure you have Java 8 or 11 and mvn the latest version.


问:
iPhone: IB, switching between iPhone and iPad
I have a project. When I choose some xib file, iPhone simulator shows in IB. Is there any whey to change it to iPad simulator ? Thanks in advance...</p>

答:
I have no idea about simulator but for device i think there is a good option called universal app.

and i think my question Convert iPad application to iPhone? should help you more ..

this log can help you to convert iphone app to ipad

http://www.raywenderlich.com/1111/how-to-port-an-iphone-application-to-the-ipad


问:
Set public-read ACL for AWS S3 data upload via iOS Amplify
I've been attempting to upload images to an existing resource in S3, the images need to be publicly viewable and our website expects that the app sets the ACL to public-read on the file.

I have been unable to find a solution using the Amplify SDK that gets this done.

Currently even using the "guest" access level my images are not viewable at their S3 URLS.

Does anyone know how to set the "public-read" ACL during upload using the iOS Amplify SDK?

https://docs.amplify.aws/lib/storage/configureaccess/q/platform/ios/

答:
I was able to hack together something that works for now using the escape hatch of the Amplify SDK.

https://docs.amplify.aws/lib/storage/escapehatch/q/platform/ios/

```<code>   func uploadToS3(path: URL, data: Data, bucketName: String, uploadKeyName: String, contentType: String) {

        do {
            let plugin = try Amplify.Storage.getPlugin(for: "awsS3StoragePlugin") as? AWSS3StoragePlugin
            if let escapedPlugin =  plugin {
                let awsS3 = escapedPlugin.getEscapeHatch()

                let request = AWSS3PutObjectRequest()

                if let req = request {
                    req.body = data
                    req.contentType = contentType
                    req.contentLength = NSNumber(integerLiteral: NSData(data: data).length)
                    req.bucket = bucketName
                    req.key = uploadKeyName
                    req.acl = .publicRead

                    awsS3.putObject(req).continueWith { (task) -> AnyObject? in
                        if let error = task.error {
                            print("there was an error with uploading image \(error)")

                        }

                        if task.result != nil {
                            let s3URL = NSURL(string: "http://s3.amazonaws.com/\(bucketName)/\(uploadKeyName)")
                            print("Uploaded to:\n\(s3URL)")
                        }

                        return nil
                    }
                }
            }

        } catch {
            print("Get escape hatch failed with error - \(error)")
        }
}
</code>```

Body:
I was able to hack together something that works for now using the escape hatch of the Amplify SDK.

https://docs.amplify.aws/lib/storage/escapehatch/q/platform/ios/

   func uploadToS3(path: URL, data: Data, bucketName: String, uploadKeyName: String, contentType: String) {

        do {
            let plugin = try Amplify.Storage.getPlugin(for: "awsS3StoragePlugin") as? AWSS3StoragePlugin
            if let escapedPlugin =  plugin {
                let awsS3 = escapedPlugin.getEscapeHatch()

                let request = AWSS3PutObjectRequest()

                if let req = request {
                    req.body = data
                    req.contentType = contentType
                    req.contentLength = NSNumber(integerLiteral: NSData(data: data).length)
                    req.bucket = bucketName
                    req.key = uploadKeyName
                    req.acl = .publicRead

                    awsS3.putObject(req).continueWith { (task) -> AnyObject? in
                        if let error = task.error {
                            print("there was an error with uploading image \(error)")

                        }

                        if task.result != nil {
                            let s3URL = NSURL(string: "http://s3.amazonaws.com/\(bucketName)/\(uploadKeyName)")
                            print("Uploaded to:\n\(s3URL)")
                        }

                        return nil
                    }
                }
            }

        } catch {
            print("Get escape hatch failed with error - \(error)")
        }
}


问:
Specifying custom serializer for a relationship has_one json-api-rb
I have serializers:

```<code>class SerializableContact < JSONAPI::Serializable::Resource
  type :contacts

  has_one :email_event, class: 'SerializableEmailEvent' # class is not working
  has_many :geofence_notifications

  attributes :email,
             :order_id,
             :frequent_order_id
end

class SerializableEmailEvent < JSONAPI::Serializable::Resource
  ...
end
</code>```

Models:

```<code>class Contact < ApplicationRecord
  has_one :email_event, -> { email }, class_name: 'Event'
end

class Event < ApplicationRecord
end
</code>```

I am trying to make SerializableContact to use SerializableEmailEvent as the serializer for email_event relationship. But I cant figure out how to do that.  It always error out with:

```<code>JsonapiCompliable::Errors::MissingSerializer - Could not find serializer for class 'Event'!

Looked for 'SerializableEvent' but doesn't appear to exist.

Use a custom Inferrer if you'd like different lookup logic.
</code>```

I am not sure how to use a custom inferrer for the different lookup logic

答:
Maybe I am a bit late responding to your issue, but here you have how to do it:

has_one :email_event do
  linkage(always: true) do
    { type: "email_event", id: @object.email_event_id } if @object.email_event_id
  end
end
```
<p>They <em>type</em> has to match with the type on your serilizable resource class. So I was expecting it to be:</p>
<pre class="lang-rb prettyprint-override"><code>class SerializableEmailEvent < JSONAPI::Serializable::Resource
  type "email_event"
  ...
end
</code>```

Body:
I have serializers:

class SerializableContact < JSONAPI::Serializable::Resource
  type :contacts

  has_one :email_event, class: 'SerializableEmailEvent' # class is not working
  has_many :geofence_notifications

  attributes :email,
             :order_id,
             :frequent_order_id
end

class SerializableEmailEvent < JSONAPI::Serializable::Resource
  ...
end

Models:

class Contact < ApplicationRecord
  has_one :email_event, -> { email }, class_name: 'Event'
end

class Event < ApplicationRecord
end

I am trying to make SerializableContact to use SerializableEmailEvent as the serializer for email_event relationship. But I cant figure out how to do that.  It always error out with:

JsonapiCompliable::Errors::MissingSerializer - Could not find serializer for class 'Event'!

Looked for 'SerializableEvent' but doesn't appear to exist.

Use a custom Inferrer if you'd like different lookup logic.

I am not sure how to use a custom inferrer for the different lookup logic

Body:
Maybe I am a bit late responding to your issue, but here you have how to do it:

has_one :email_event do
  linkage(always: true) do
    { type: "email_event", id: @object.email_event_id } if @object.email_event_id
  end
end

They type has to match with the type on your serilizable resource class. So I was expecting it to be:

class SerializableEmailEvent < JSONAPI::Serializable::Resource
  type "email_event"
  ...
end


问:
How dynamically edit field in kendo grid
I want to change editable property of the field, but this way it doesn't work. How can I fix this?</p>
```<code>function changeDescription(rawGrid, isEditableDescription) {
        var grid = rawGrid.data("kendoGrid");
        if (!grid) return;

        if (isEditableDescription) {
            grid.dataSource.options.schema.model.fields["Description"].editable = true;
        }
        else {
            grid.dataSource.options.schema.model.fields["Description"].editable = false;
        }
    }
</code>```

答:
You need to call the setOptions method of the grid: https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/methods/setoptions

var grid = $('#grid').data('kendoGrid');
var options = grid.getOptions();
var editable = !options.columns[0].editable || options.columns[0].editable();
options.columns[0].editable = function() { return !editable; };
grid.setOptions(options);
```

Dojo: https://dojo.telerik.com/APEBuhaN

Body:
I want to change editable property of the field, but this way it doesn't work. How can I fix this?

function changeDescription(rawGrid, isEditableDescription) {
        var grid = rawGrid.data("kendoGrid");
        if (!grid) return;

        if (isEditableDescription) {
            grid.dataSource.options.schema.model.fields["Description"].editable = true;
        }
        else {
            grid.dataSource.options.schema.model.fields["Description"].editable = false;
        }
    }

Body:
You need to call the setOptions method of the grid: https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/methods/setoptions

var grid = $('#grid').data('kendoGrid');
var options = grid.getOptions();
var editable = !options.columns[0].editable || options.columns[0].editable();
options.columns[0].editable = function() { return !editable; };
grid.setOptions(options);

Dojo: https://dojo.telerik.com/APEBuhaN


问:
In structured streaming checkpointing why offsets are not committed after foreachbatch
```<code>df
.writeStream
.trigger(Trigger.Once)
.option(checkpointKey, checkpointVal)
.foreachBatch { (batchDF: DataFrame, batchId: Long) => }

</code>```

This is the sample code I am running.
Observing that Structured streaming creates the offsets file at the beginning itself: checkpoints/offsets/3

Why does it not wait for the foreachBatch to complete and then write the offsets to checkpoint directory?

答:
Each micro batch is similar as one transaction.

When kafka source have new messages. The begin and end offsets for
this microbatch will be writen to offsets folder.

Start processing.

If succeed, commit file will be writen into commits folder with same
microbath id. If failed, will reexecute micro batch using the same
offsets range.

Body:
df
.writeStream
.trigger(Trigger.Once)
.option(checkpointKey, checkpointVal)
.foreachBatch { (batchDF: DataFrame, batchId: Long) => }

This is the sample code I am running.
Observing that Structured streaming creates the offsets file at the beginning itself: checkpoints/offsets/3

Why does it not wait for the foreachBatch to complete and then write the offsets to checkpoint directory?


问:
StringBuilder.Append Vs StringBuilder.AppendFormat
I was wondering about StringBuilder and I've got a question that I was hoping the community would be able to explain.

Let's just forget about code readability, which of these is faster and why?

StringBuilder.Append:

```<code>StringBuilder sb = new StringBuilder();
sb.Append(string1);
sb.Append("----");
sb.Append(string2);
</code>```

StringBuilder.AppendFormat:

```<code>StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}----{1}",string1,string2);
</code>```

答:
Append will be faster in most cases because there are many overloads to that method that allow the compiler to call the correct method.  Since you are using Strings the StringBuilder can use the String overload for Append.

AppendFormat takes a String and then an Object[] which means that the format will have to be parsed and each Object in the array will have to be ToString'd before it can be added to the StringBuilder's internal array.

Note: To casperOne's point - it is difficult to give an exact answer without more data.

OwnerDisplayName: Sergio

ContentLicense: CC BY-SA 2.5

Body:
I was wondering about StringBuilder and I've got a question that I was hoping the community would be able to explain.

Let's just forget about code readability, which of these is faster and why?

StringBuilder.Append:

StringBuilder sb = new StringBuilder();
sb.Append(string1);
sb.Append("----");
sb.Append(string2);

StringBuilder.AppendFormat:

StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}----{1}",string1,string2);

LastEditorDisplayName: Samuel

OwnerDisplayName: Andrew Hare

LastEditorDisplayName: Andrew Hare


问:
Unable to set alias in PowerShell using a string
I tried to set an alias in PowerShell by running Set-Alias -Name artisan -Value 'php aritsan', though the command ran successfully but when I call the alias the following error occurs :

artisan : The term 'php aritsan' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:1
+ artisan
+ ~~~~~~~
    + CategoryInfo          : ObjectNotFound: (php aritsan:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
```

What's the correct way to go for?

P.S: artisan is a file in the current directory. The file is packaged with laravel framework

答:
This will help you create an alias for "php artisan" in Windows PowerShell Globally.
Just follow these steps and its done.

First of all search powershell using win+S and run it as administrator and then paste this code and hit Enter.

if (!(Test-Path -Path $PROFILE )) {New-Item -Type File -Path $PROFILE -Force }

Then run this command.

notepad $profile

A notepad file will open. Paste this code in notepad file and hit ctrl+S

Function CD32($arg1,$arg2,$arg3,$arg4,$arg5) {php artisan $arg1 $arg2 $arg3 $arg4 $arg5}
Set-Alias -Name pa -Value CD32

And then finally paste this command on your powershell and hit enter.

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

And it's done. Now you can use "pa" as an alias for "php artisan" globally in your windows powershell.

Here I am using "pa" on my VS Code PowerShell.

Body:
I tried to set an alias in PowerShell by running Set-Alias -Name artisan -Value 'php aritsan', though the command ran successfully but when I call the alias the following error occurs :

artisan : The term 'php aritsan' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:1
+ artisan
+ ~~~~~~~
    + CategoryInfo          : ObjectNotFound: (php aritsan:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

What's the correct way to go for?

P.S: artisan is a file in the current directory. The file is packaged with laravel framework


问:
Kotlin + Java 9 modules: Module java.base cannot be found in the module graph
I'm having some issues on building a Kotlin project that uses Java 9 features. I know kotlin just allow Java 8 bytecode generation, but acording to kotlinlang.org it should support this functionality since Kotlin 1.2:

The Kotlin standard library is now fully compatible with the Java 9
  module system, which forbids split packages (multiple jar files
  declaring classes in the same package).

Well, lets to my problem: I'm getting this when I try to execute gradle build task:

04:29:27: Executing task 'build'...

Task :compileKotlin FAILED e: Module java.base cannot be found in the module graph e: Module java.management cannot be found in the
    module graph

FAILURE: Build failed with an exception.

What went wrong: Execution failed for task ':compileKotlin'.

Compilation error. See log for more details

Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 0s 1 actionable task: 1 executed Compilation error.
  See log for more details 04:29:28: Task execution finished 'build'.

I searched for that error on Google and found this topic where a guy had the same problem, he said he fixed it by targeting a JDK greater than 8, but I'm already with JDK 11 as project SDK and sourceCompatibility.

I'll left some important parts of build.gradle and project structure here to you guys inspect it.

build.gradle

```<code>buildscript {
    ext.kotlin_version = '1.3.21'
    ...

    repositories { ... }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.dokka:dokka-gradle-plugin:0.9.17"
    }
}

plugins {
    ...
}
apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'application'
apply plugin: 'maven'

group 'io.github.dogobot.core'
version '4.0.0'

...

sourceCompatibility = 1.11

repositories {
    mavenCentral()
    jcenter()
    maven { ... }
    maven { ... }
    maven {
        url 'http://maven.ej-technologies.com/repository'
    }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    ...
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
</code>```

module-info.java

```<code>module io.github.dogobot.core {
    requires kotlin.stdlib;
    requires kotlin.reflect;
    requires kotlin.logging;

    requires java.management;

    requires BootingBits;
}
</code>```

I can run the project with no problems on Intellij Idea, just get this error when executing on gradle.

答:
File -> Invalidate caches -> select "Clear file system cache and Local history" -> Invalidate and Restart

Solved it for me...

Body:
I'm having some issues on building a Kotlin project that uses Java 9 features. I know kotlin just allow Java 8 bytecode generation, but acording to kotlinlang.org it should support this functionality since Kotlin 1.2:

The Kotlin standard library is now fully compatible with the Java 9
  module system, which forbids split packages (multiple jar files
  declaring classes in the same package).

Well, lets to my problem: I'm getting this when I try to execute gradle build task:

04:29:27: Executing task 'build'...

Task :compileKotlin FAILED e: Module java.base cannot be found in the module graph e: Module java.management cannot be found in the
    module graph

FAILURE: Build failed with an exception.

What went wrong: Execution failed for task ':compileKotlin'.

Compilation error. See log for more details

Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 0s 1 actionable task: 1 executed Compilation error.
  See log for more details 04:29:28: Task execution finished 'build'.

I searched for that error on Google and found this topic where a guy had the same problem, he said he fixed it by targeting a JDK greater than 8, but I'm already with JDK 11 as project SDK and sourceCompatibility.

I'll left some important parts of build.gradle and project structure here to you guys inspect it.

build.gradle

buildscript {
    ext.kotlin_version = '1.3.21'
    ...

    repositories { ... }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.dokka:dokka-gradle-plugin:0.9.17"
    }
}

plugins {
    ...
}
apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'application'
apply plugin: 'maven'

group 'io.github.dogobot.core'
version '4.0.0'

...

sourceCompatibility = 1.11

repositories {
    mavenCentral()
    jcenter()
    maven { ... }
    maven { ... }
    maven {
        url 'http://maven.ej-technologies.com/repository'
    }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    ...
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

module-info.java

module io.github.dogobot.core {
    requires kotlin.stdlib;
    requires kotlin.reflect;
    requires kotlin.logging;

    requires java.management;

    requires BootingBits;
}

I can run the project with no problems on Intellij Idea, just get this error when executing on gradle.


问:
Color from hex string in jetpack compose
How to parse hex string e.g. #9CCC65 in Color class in jetpack compose.

P.S: option seem to be missing in jetpack compose package

Current Workaround:
Exported parseColor() method from standard Color class.

```<code>@ColorInt
fun parseColor(@Size(min = 1) colorString: String): Int {
    if (colorString[0] == '#') { // Use a long to avoid rollovers on #ffXXXXXX
        var color = colorString.substring(1).toLong(16)
        if (colorString.length == 7) { // Set the alpha value
            color = color or -0x1000000
        } else require(colorString.length == 9) { "Unknown color" }
        return color.toInt()
    }
    throw IllegalArgumentException("Unknown color")
}
</code>```

答:
If you want to avoid having to import android.graphics.Color, here's another straightforward alternative:

val hexString = "#f8f8f2"
Color(("ff" + hexString.removePrefix("#").lowercase()).toLong(16))
```

Color in this case would be immediately the one from androidx.compose.ui.graphics.Color.

Body:
How to parse hex string e.g. #9CCC65 in Color class in jetpack compose.

P.S: option seem to be missing in jetpack compose package

Current Workaround:
Exported parseColor() method from standard Color class.

@ColorInt
fun parseColor(@Size(min = 1) colorString: String): Int {
    if (colorString[0] == '#') { // Use a long to avoid rollovers on #ffXXXXXX
        var color = colorString.substring(1).toLong(16)
        if (colorString.length == 7) { // Set the alpha value
            color = color or -0x1000000
        } else require(colorString.length == 9) { "Unknown color" }
        return color.toInt()
    }
    throw IllegalArgumentException("Unknown color")
}

Body:
If you want to avoid having to import android.graphics.Color, here's another straightforward alternative:

val hexString = "#f8f8f2"
Color(("ff" + hexString.removePrefix("#").lowercase()).toLong(16))

Color in this case would be immediately the one from androidx.compose.ui.graphics.Color.


问:
Postman Error [err_http_headers_sent]: cannot set headers after they are sent to the client Using ReactJS & NodeJS
[err_http_headers_sent]: cannot set headers after they are sent to the client
<=(Link is picture of the actual error)

I have been stuck on this issue for two weeks and the other Stack Overflow posts with this issue don't seem to resolve the issue.  Hoping someone can help with what will resolve this issue. I am using ReactJS and NodeJS "express" for the backend.  I get this error when testing in Postman.  Does anyone know what I am doing wrong?

server.js file:

```<code>import express from 'express';
import { routes } from '../routes/index';
import { initializeDbConnection } from './db';
const PORT = process.env.PORT || 8080;
const app = express();
//This allows access the body of POST/PUT requests in our route handlers as req.body
app.use(express.json());
//Add all the routes to Express server exported from routes/index.js
routes.forEach(route => {
     app[route.method](route.path, route.handler);
});
// Connect to the database, then start the server.
// This prevents from having to create a new DB
// connection for every request
initializeDbConnection()
    .then(() => {
        app.listen(PORT, () => {
            console.log(`Server is listening on port ${PORT}`);
        });
    });
</code>```

signuproute.js code

```<code>import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { getDbConnection } from '../src/db';
export const signUpRoute = {
    path: '/api/signup',
    method: 'post',
    handler: async (req, res) => {
        const { email, password } = req.body;
        const db = getDbConnection('react-auth-db');
        const user = await db.collection('users').findOne({ email });
        if (user) {
            res.sendStatus(409);
        }
        const passwordHash = await bcrypt.hash(password, 10);
        //change once you figure out what info you want to store from users
        const startingInfo = {
            hairColor: '',
            favoriteFood: '',
            bio: '',
        };
        const result = await db.collection('users').insertOne({
            email,
            passwordHash,
            info: startingInfo,
            isVerified: false,
        });
        const { insertedId } = result;
        jwt.sign({
            id: insertedId,
            email,
            info: startingInfo,
            isVerified: false,
        },
        process.env.JWT_SECRET,
        {
            expiresIn: '2d',
        },
        (err, token) => {
            if (err) {
                return res.status(500).send(err);
            }
            res.status(200).send({ token });
        });
    }
}
</code>```

答:
You can try to add return on your res

```<code>return res.sendStatus(409);
</code>```

and

```<code>return res.status(200).send({ token });
</code>```

Body:
[err_http_headers_sent]: cannot set headers after they are sent to the client
<=(Link is picture of the actual error)

I have been stuck on this issue for two weeks and the other Stack Overflow posts with this issue don't seem to resolve the issue.  Hoping someone can help with what will resolve this issue. I am using ReactJS and NodeJS "express" for the backend.  I get this error when testing in Postman.  Does anyone know what I am doing wrong?

server.js file:

import express from 'express';
import { routes } from '../routes/index';
import { initializeDbConnection } from './db';
const PORT = process.env.PORT || 8080;
const app = express();
//This allows access the body of POST/PUT requests in our route handlers as req.body
app.use(express.json());
//Add all the routes to Express server exported from routes/index.js
routes.forEach(route => {
     app[route.method](route.path, route.handler);
});
// Connect to the database, then start the server.
// This prevents from having to create a new DB
// connection for every request
initializeDbConnection()
    .then(() => {
        app.listen(PORT, () => {
            console.log(`Server is listening on port ${PORT}`);
        });
    });

signuproute.js code

import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { getDbConnection } from '../src/db';
export const signUpRoute = {
    path: '/api/signup',
    method: 'post',
    handler: async (req, res) => {
        const { email, password } = req.body;
        const db = getDbConnection('react-auth-db');
        const user = await db.collection('users').findOne({ email });
        if (user) {
            res.sendStatus(409);
        }
        const passwordHash = await bcrypt.hash(password, 10);
        //change once you figure out what info you want to store from users
        const startingInfo = {
            hairColor: '',
            favoriteFood: '',
            bio: '',
        };
        const result = await db.collection('users').insertOne({
            email,
            passwordHash,
            info: startingInfo,
            isVerified: false,
        });
        const { insertedId } = result;
        jwt.sign({
            id: insertedId,
            email,
            info: startingInfo,
            isVerified: false,
        },
        process.env.JWT_SECRET,
        {
            expiresIn: '2d',
        },
        (err, token) => {
            if (err) {
                return res.status(500).send(err);
            }
            res.status(200).send({ token });
        });
    }
}

Body:
You can try to add return on your res

return res.sendStatus(409);

and

return res.status(200).send({ token });