问:
AlarmManager does not start for more than a day for a 10-minute setWindow(...)
Periodically I get some messages from FCM. On receiving FCM message, I should schedule AlarmManager.setWindow(10min) for doing some work.
If setWindow(...) is scheduled already, then nothing does:

```<code>...

val cx = applicationContext
val alarmMng = cx.getSystemService(Context.ALARM_SERVICE) as AlarmManager

val intent = Intent(cx, AlmaReceiver::class.java).putExtra("pcreated", System.currentTimeMillis())
val pintentcheck = PendingIntent.getBroadcast(cx, 5556, intent, Utils.getFlagsForPendingIntent("almaIsExist"))

if ( pintentcheck == null ) {
    val timedelta = (Random(Utils.getSeedRandom(cx)).nextInt(170)*1000).toLong()
    val pintent = PendingIntent.getBroadcast(cx, 5556, intent, Utils.getFlagsForPendingIntent("alma"))
    alarmMng.setWindow( AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + timedelta, 10*60*1000, pintent )
}
</code>```

So, I schedule AlarmManager with delay 0-170 sec if PendingIntent doest exist.

```<code>class Utils {
    companion object {
        fun getFlagsForPendingIntent( type:String ?= "alma" ): Int {
            return when (type) {
                "alma" -> {
                    if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ) {
                        PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
                    } else {
                        PendingIntent.FLAG_ONE_SHOT
                    }
                }
                "almaIsExist" -> {
                    if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ) {
                        PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_NO_CREATE
                    } else {
                        PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_NO_CREATE
                    }
                }
                else -> {0}
            }
        }
    }
}
</code>```

I know Alarm is created. I know PendingIntent is created:

dumpsys alarm | grep "AlmaReceiver":

```<code>RTC_WAKEUP #63: Alarm{982e964 type 0 origWhen 1672847964164 whenElapsed 274200000 com.myproj.proj}
      tag=*walarm*:com.myproj.proj/.AlmaReceiver
      type=RTC_WAKEUP origWhen=2023-01-04 17:59:24.164 window=+10m0s0ms repeatInterval=0 count=0 flags=0x0
      policyWhenElapsed: requester=-2h39m4s771ms app_standby=-20m4s546ms device_idle=-- battery_saver=-1m36s470ms power_pending=+2d21h20m55s229ms
      whenElapsed=+2d21h20m55s229ms maxWhenElapsed=+2d21h20m55s229ms
      operation=PendingIntent{73207cd: PendingIntentRecord{43bf882 com.myproj.proj broadcastIntent}}
</code>```

dumpsys activity intents | grep "43bf882":

```<code>* com.myproj.proj: 1 items
    #0: PendingIntentRecord{43bf882 com.myproj.proj broadcastIntent}
      uid=10019 packageName=com.myproj.proj featureId=null type=broadcastIntent flags=0x44000000
      requestCode=5556 requestResolvedType=null
      requestIntent=cmp=com.myproj.proj/.AlmaReceiver (has extras)
</code>```

After a day of waiting, the Alarm does not start but continues to exist.

Why, and how can I fix it?

Body:
Periodically I get some messages from FCM. On receiving FCM message, I should schedule AlarmManager.setWindow(10min) for doing some work.
If setWindow(...) is scheduled already, then nothing does:

...

val cx = applicationContext
val alarmMng = cx.getSystemService(Context.ALARM_SERVICE) as AlarmManager

val intent = Intent(cx, AlmaReceiver::class.java).putExtra("pcreated", System.currentTimeMillis())
val pintentcheck = PendingIntent.getBroadcast(cx, 5556, intent, Utils.getFlagsForPendingIntent("almaIsExist"))

if ( pintentcheck == null ) {
    val timedelta = (Random(Utils.getSeedRandom(cx)).nextInt(170)*1000).toLong()
    val pintent = PendingIntent.getBroadcast(cx, 5556, intent, Utils.getFlagsForPendingIntent("alma"))
    alarmMng.setWindow( AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + timedelta, 10*60*1000, pintent )
}

So, I schedule AlarmManager with delay 0-170 sec if PendingIntent doest exist.

class Utils {
    companion object {
        fun getFlagsForPendingIntent( type:String ?= "alma" ): Int {
            return when (type) {
                "alma" -> {
                    if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ) {
                        PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
                    } else {
                        PendingIntent.FLAG_ONE_SHOT
                    }
                }
                "almaIsExist" -> {
                    if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ) {
                        PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_NO_CREATE
                    } else {
                        PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_NO_CREATE
                    }
                }
                else -> {0}
            }
        }
    }
}

I know Alarm is created. I know PendingIntent is created:

dumpsys alarm | grep "AlmaReceiver":

RTC_WAKEUP #63: Alarm{982e964 type 0 origWhen 1672847964164 whenElapsed 274200000 com.myproj.proj}
      tag=*walarm*:com.myproj.proj/.AlmaReceiver
      type=RTC_WAKEUP origWhen=2023-01-04 17:59:24.164 window=+10m0s0ms repeatInterval=0 count=0 flags=0x0
      policyWhenElapsed: requester=-2h39m4s771ms app_standby=-20m4s546ms device_idle=-- battery_saver=-1m36s470ms power_pending=+2d21h20m55s229ms
      whenElapsed=+2d21h20m55s229ms maxWhenElapsed=+2d21h20m55s229ms
      operation=PendingIntent{73207cd: PendingIntentRecord{43bf882 com.myproj.proj broadcastIntent}}

dumpsys activity intents | grep "43bf882":

* com.myproj.proj: 1 items
    #0: PendingIntentRecord{43bf882 com.myproj.proj broadcastIntent}
      uid=10019 packageName=com.myproj.proj featureId=null type=broadcastIntent flags=0x44000000
      requestCode=5556 requestResolvedType=null
      requestIntent=cmp=com.myproj.proj/.AlmaReceiver (has extras)

After a day of waiting, the Alarm does not start but continues to exist.

Why, and how can I fix it?


来源: stackexchange

问:
Need to Update Group fields in a Nested Group Before Post Creation ACF
The code below works but fails When trying to update additional fields that are
located inside another group that is within this group. To give this problem more context, the below fields are pulled in from a CSV and every field is getting saved besides the fields within the secondary subgroup.</p>
```<code>    // THIS CODE PULLS FROM UPLOADED CSV
    $field_key = 'field_615c993de0975';
    $values = array(
        'event_street_address'           => $post["event_street_address"],
        'event_city'                     => $post["event_city"],
        'event_stateprovince'            => $post["event_stateprovince"],
        'event_zip_codepostal_code'      => $post["event_zip_codepostal_code"],
        'event_country'                  => $post["event_country"]

);

    update_field( $field_key, $values, $post["id"] );
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The code below works but fails When trying to update additional fields that are
located inside another group that is within this group. To give this problem more context, the below fields are pulled in from a CSV and every field is getting saved besides the fields within the secondary subgroup.

    // THIS CODE PULLS FROM UPLOADED CSV
    $field_key = 'field_615c993de0975';
    $values = array(
        'event_street_address'           => $post["event_street_address"],
        'event_city'                     => $post["event_city"],
        'event_stateprovince'            => $post["event_stateprovince"],
        'event_zip_codepostal_code'      => $post["event_zip_codepostal_code"],
        'event_country'                  => $post["event_country"]

);

    update_field( $field_key, $values, $post["id"] );


问:
Suspend function inside flow kotlin
So I have the below kotlin code with flows and suspend function.

```<code>suspend fun doWork(): Int {
    // do some time intensive task
    return if (task.isSuccessful){1}else{-1}
}

suspend fun sendTaskStatus(status:Int): Boolean {
    // send this status data to the server via internet
    return task.isSuccessful()
}

fun listenForCompletion() = flow <String> {
    val isTaskCompleted = false
    val taskStatus = doWork()
    if (taskStaus == 1){
        val isDataSent = sendTaskStatus()
        if(isDataSent)
            isTaskCompleted = true
    }
    emit(isTaskCompleted)
}
</code>```

Now my question is if I collect listenForCompletion() function from a coroutine, what will be the sequence of execution of this code? If this isn't correct what would be the correct way of doing this assuming that flow and suspend functions are preserved?

Title: Suspend function inside flow kotlin

Body:
So I have the below kotlin code with flows and suspend function.

suspend fun doWork(): Int {
    // do some time intensive task
    return if (task.isSuccessful){1}else{-1}
}

suspend fun sendTaskStatus(status:Int): Boolean {
    // send this status data to the server via internet
    return task.isSuccessful()
}

fun listenForCompletion() = flow <String> {
    val isTaskCompleted = false
    val taskStatus = doWork()
    if (taskStaus == 1){
        val isDataSent = sendTaskStatus()
        if(isDataSent)
            isTaskCompleted = true
    }
    emit(isTaskCompleted)
}

Now my question is if I collect listenForCompletion() function from a coroutine, what will be the sequence of execution of this code? If this isn't correct what would be the correct way of doing this assuming that flow and suspend functions are preserved?


问:
How to use sequelize with typescript? Model type is always any and User.init is throwing error
I want to create a model for a user table. I tried to follow the tutorial here in the docs

Here is my file:

```<code>/* eslint-disable @typescript-eslint/naming-convention */
import { RandomUUIDOptions } from "crypto";

import {
  DataTypeAbstract,
  DataTypes,
  Model,
  Optional,
  Sequelize,
  InferAttributes,
} from "sequelize";

// possible attributes of our model
interface User {
  id: RandomUUIDOptions;
  username: string;
  password: string;
  trainer_id: RandomUUIDOptions;
  researcher_id: RandomUUIDOptions;
}

// type of the object passed to Sequelize’s model.create
type UserCreationAttributes = Optional<User, "trainer_id" | "researcher_id">;

export default function createUser(
  sequelize: Sequelize,
  DataTypes: DataTypeAbstract,
  Model: Model
) {
  class User extends Model<InferAttributes<User>, UserCreationAttributes> {
    declare id: RandomUUIDOptions;
    declare username: string;
    declare password: string;
    declare trainer_id: RandomUUIDOptions;
    declare researcher_id: RandomUUIDOptions;
  }

  User.init(
    {
      id: {
        type: DataTypes.UUID,
        primaryKey: true,
        allowNull: false,
        defaultValue: DataTypes.UUIDV4,
      },
      username: {
        type: DataTypes.STRING,
        unique: true,
        allowNull: false,
      },
      password: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      trainer_id: {
        type: DataTypes.UUID,
        allowNull: true,
        references: {
          model: "trainer",
          key: "id",
        },
      },
      researcher_id: {
        type: DataTypes.UUID,
        allowNull: true,
        references: {
          model: "researcher",
          key: "id",
        },
      },
    },
    {
      sequelize,
      modelName: "User",
    }
  );
  return User;
}

</code>```

However, I got some problems:

the Model type throws this error : Type 'Model<any, any>' is not a constructor function type.

the User.init throws this error: Property 'init' does not exist on type 'typeof User'.

the dataTypes properties are throwing this type of error: Property 'some_type_like_string_or_UUID' does not exist on type 'AbstractDataTypeConstructor'.

Why am I getting these errors? How can I solve this?

Body:
I want to create a model for a user table. I tried to follow the tutorial here in the docs

Here is my file:

/* eslint-disable @typescript-eslint/naming-convention */
import { RandomUUIDOptions } from "crypto";

import {
  DataTypeAbstract,
  DataTypes,
  Model,
  Optional,
  Sequelize,
  InferAttributes,
} from "sequelize";

// possible attributes of our model
interface User {
  id: RandomUUIDOptions;
  username: string;
  password: string;
  trainer_id: RandomUUIDOptions;
  researcher_id: RandomUUIDOptions;
}

// type of the object passed to Sequelize’s model.create
type UserCreationAttributes = Optional<User, "trainer_id" | "researcher_id">;

export default function createUser(
  sequelize: Sequelize,
  DataTypes: DataTypeAbstract,
  Model: Model
) {
  class User extends Model<InferAttributes<User>, UserCreationAttributes> {
    declare id: RandomUUIDOptions;
    declare username: string;
    declare password: string;
    declare trainer_id: RandomUUIDOptions;
    declare researcher_id: RandomUUIDOptions;
  }

  User.init(
    {
      id: {
        type: DataTypes.UUID,
        primaryKey: true,
        allowNull: false,
        defaultValue: DataTypes.UUIDV4,
      },
      username: {
        type: DataTypes.STRING,
        unique: true,
        allowNull: false,
      },
      password: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      trainer_id: {
        type: DataTypes.UUID,
        allowNull: true,
        references: {
          model: "trainer",
          key: "id",
        },
      },
      researcher_id: {
        type: DataTypes.UUID,
        allowNull: true,
        references: {
          model: "researcher",
          key: "id",
        },
      },
    },
    {
      sequelize,
      modelName: "User",
    }
  );
  return User;
}

However, I got some problems:

the Model type throws this error : Type 'Model<any, any>' is not a constructor function type.

the User.init throws this error: Property 'init' does not exist on type 'typeof User'.

the dataTypes properties are throwing this type of error: Property 'some_type_like_string_or_UUID' does not exist on type 'AbstractDataTypeConstructor'.

Why am I getting these errors? How can I solve this?


问:
How to upload image along with json data to an API in springboot?
I need to upload an image along with "empId" field as json data to a table. Below is my  Entity class

@Entity
@Table(name = "FILES")

public class FileEntity {

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String id;
    private String empId;

    public String getEmpId() {
        return empId;
    }

    public void setEmpId(String ggid) {
        this.empId = ggid;
    }

    private String name;

    private String contentType;

    private Long size;

    @Lob
    private byte[] data;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public Long getSize() {
        return size;
    }

    public void setSize(Long size) {
        this.size = size;
    }

    public byte[] getData() {
        return data;
    }

    public void setData(byte[] data) {
        this.data = data;
   }
}
```
<p>below is my FileResponse class</p>
<pre class="lang-java prettyprint-override"><code>public class FileResponse {

    private String id;
    private String name;
    private Long size;
    private String url;
    private String contentType;
    private String empId;
    public String getEmpId() {
        return empId;
    }

    public void setEmpId(String ggid) {
        this.empId = ggid;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getSize() {
        return size;
    }

    public void setSize(Long size) {
        this.size = size;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }
}
</code>```

Below is the controller class

@RestController
@RequestMapping("files")
public class FilesController {

     @Autowired
    private FileService fileService;

    @PostMapping
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file ) {
        try {

            fileService.save(file);

            return ResponseEntity.status(HttpStatus.OK)
                                 .body(String.format("File uploaded successfully: %s", file.getOriginalFilename()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                                 .body(String.format("Could not upload the file: %s!", file.getOriginalFilename()));
        }
    }

    @GetMapping
    public List<FileResponse> list() {
        return fileService.getAllFiles()
                          .stream()
                          .map(this::mapToFileResponse)
                          .collect(Collectors.toList());
    }

    private FileResponse mapToFileResponse(FileEntity fileEntity) {
        String downloadURL = ServletUriComponentsBuilder.fromCurrentContextPath()
                                                        .path("/files/")
                                                        .path(fileEntity.getId())
                                                        .toUriString();
        FileResponse fileResponse = new FileResponse();
        fileResponse.setId(fileEntity.getId());
        fileResponse.setName(fileEntity.getName());
        fileResponse.setContentType(fileEntity.getContentType());
        fileResponse.setSize(fileEntity.getSize());
        fileResponse.setUrl(downloadURL);

        return fileResponse;
    }

    @GetMapping("{id}")
    public ResponseEntity<byte[]> getFile(@PathVariable String id) {
        Optional<FileEntity> fileEntityOptional = fileService.getFile(id);

        if (!fileEntityOptional.isPresent()) {
            return ResponseEntity.notFound()
                                 .build();
        }

        FileEntity fileEntity = fileEntityOptional.get();
        return ResponseEntity.ok()
                             .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileEntity.getName() + "\"")
                             .contentType(MediaType.valueOf(fileEntity.getContentType()))
                             .body(fileEntity.getData());
    }
}
```
<p>Below is the service class</p>
<pre class="lang-java prettyprint-override"><code>@Service
public class FileService {

    @Autowired
    private  FileRepository fileRepository;

    public void save(MultipartFile file) throws IOException {
        FileEntity fileEntity = new FileEntity();
        fileEntity.setName(StringUtils.cleanPath(file.getOriginalFilename()));
        fileEntity.setContentType(file.getContentType());
        fileEntity.setData(file.getBytes());
        fileEntity.setSize(file.getSize());

        fileRepository.save(fileEntity);
    }

    public Optional<FileEntity> getFile(String id) {
        return fileRepository.findById(id);
    }

    public List<FileEntity> getAllFiles() {
        return fileRepository.findAll();
    }
}

</code>```

@Repository
public interface FileRepository extends JpaRepository<FileEntity, String> {
}
```
<p>I tried sending json data in postman along with image by modifying the arguments in post method in controller as below</p>
<pre class="lang-java prettyprint-override"><code>@PostMapping
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file , @Valid @RequestBody FileEntity data) {
        try {

            fileService.save(file);

            return ResponseEntity.status(HttpStatus.OK)
                                 .body(String.format("File uploaded successfully: %s", file.getOriginalFilename()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                                 .body(String.format("Could not upload the file: %s!", file.getOriginalFilename()));
        }
</code>```

but it is not working as expected and I sent request via postman using form data option in body .So please help me with this.

Body:
I need to upload an image along with "empId" field as json data to a table. Below is my  Entity class

@Entity
@Table(name = "FILES")

public class FileEntity {

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String id;
    private String empId;

    public String getEmpId() {
        return empId;
    }

    public void setEmpId(String ggid) {
        this.empId = ggid;
    }

    private String name;

    private String contentType;

    private Long size;

    @Lob
    private byte[] data;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public Long getSize() {
        return size;
    }

    public void setSize(Long size) {
        this.size = size;
    }

    public byte[] getData() {
        return data;
    }

    public void setData(byte[] data) {
        this.data = data;
   }
}

below is my FileResponse class

public class FileResponse {

    private String id;
    private String name;
    private Long size;
    private String url;
    private String contentType;
    private String empId;
    public String getEmpId() {
        return empId;
    }

    public void setEmpId(String ggid) {
        this.empId = ggid;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getSize() {
        return size;
    }

    public void setSize(Long size) {
        this.size = size;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }
}

Below is the controller class

@RestController
@RequestMapping("files")
public class FilesController {

     @Autowired
    private FileService fileService;

    @PostMapping
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file ) {
        try {

            fileService.save(file);

            return ResponseEntity.status(HttpStatus.OK)
                                 .body(String.format("File uploaded successfully: %s", file.getOriginalFilename()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                                 .body(String.format("Could not upload the file: %s!", file.getOriginalFilename()));
        }
    }

    @GetMapping
    public List<FileResponse> list() {
        return fileService.getAllFiles()
                          .stream()
                          .map(this::mapToFileResponse)
                          .collect(Collectors.toList());
    }

    private FileResponse mapToFileResponse(FileEntity fileEntity) {
        String downloadURL = ServletUriComponentsBuilder.fromCurrentContextPath()
                                                        .path("/files/")
                                                        .path(fileEntity.getId())
                                                        .toUriString();
        FileResponse fileResponse = new FileResponse();
        fileResponse.setId(fileEntity.getId());
        fileResponse.setName(fileEntity.getName());
        fileResponse.setContentType(fileEntity.getContentType());
        fileResponse.setSize(fileEntity.getSize());
        fileResponse.setUrl(downloadURL);

        return fileResponse;
    }

    @GetMapping("{id}")
    public ResponseEntity<byte[]> getFile(@PathVariable String id) {
        Optional<FileEntity> fileEntityOptional = fileService.getFile(id);

        if (!fileEntityOptional.isPresent()) {
            return ResponseEntity.notFound()
                                 .build();
        }

        FileEntity fileEntity = fileEntityOptional.get();
        return ResponseEntity.ok()
                             .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileEntity.getName() + "\"")
                             .contentType(MediaType.valueOf(fileEntity.getContentType()))
                             .body(fileEntity.getData());
    }
}

Below is the service class

@Service
public class FileService {

    @Autowired
    private  FileRepository fileRepository;

    public void save(MultipartFile file) throws IOException {
        FileEntity fileEntity = new FileEntity();
        fileEntity.setName(StringUtils.cleanPath(file.getOriginalFilename()));
        fileEntity.setContentType(file.getContentType());
        fileEntity.setData(file.getBytes());
        fileEntity.setSize(file.getSize());

        fileRepository.save(fileEntity);
    }

    public Optional<FileEntity> getFile(String id) {
        return fileRepository.findById(id);
    }

    public List<FileEntity> getAllFiles() {
        return fileRepository.findAll();
    }
}

@Repository
public interface FileRepository extends JpaRepository<FileEntity, String> {
}

I tried sending json data in postman along with image by modifying the arguments in post method in controller as below

@PostMapping
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file , @Valid @RequestBody FileEntity data) {
        try {

            fileService.save(file);

            return ResponseEntity.status(HttpStatus.OK)
                                 .body(String.format("File uploaded successfully: %s", file.getOriginalFilename()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                                 .body(String.format("Could not upload the file: %s!", file.getOriginalFilename()));
        }

but it is not working as expected and I sent request via postman using form data option in body .So please help me with this.


问:
Enable authorization in MongoDB
I created some mongodb users and when I tried to enable Authorization I added this directive

```<code>security:
  authorization: "enabled"
</code>```

to /etc/mongod.config file, and when I restarted mongod it won't start and it exited with error.

My mongodb is version 5.x as a replicaset of three nodes.

Any thoughts?

Title: Enable authorization in MongoDB

Body:
I created some mongodb users and when I tried to enable Authorization I added this directive

security:
  authorization: "enabled"

to /etc/mongod.config file, and when I restarted mongod it won't start and it exited with error.

My mongodb is version 5.x as a replicaset of three nodes.

Any thoughts?


问:
R: Read specific columns of .dta file and converting variable names to lower case without reading whole file
I have a folder with multiple .dta files and I'm using the read_dta() function of the haven library to bind them. The problem is that some of the files have thier column names in lower case and others have them in upper case.

I was wondering if there is a way to only read the specific columns by changing their name to lower case in every case without reading the whole file and then selecting the columns, since the files are really large and this would take forever.

I was hoping that by using the .name_repair =  element in the read_dta() function I could do this, but I really don't know how.

Im trying something like this

```<code>#Set working directory:
setwd("T:/")

#List of .dta file names to bind:
list_names<-list_names[grepl("_sdem.dta", list_names)]

#Variable names to select form those files:
vars_select<-c("r_def", "c_res", "ur", "con", "n_hog", "v_sel", "n_pro_viv","fac", "n_ren", "upm","eda", "clase1", "clase2", "clase3", "ent", "sex", "e_con", "niv_ins", "eda7c", "tpg_p8a","emp_ppal", "tue_ppal", "sub_o" )

#Read and bind ONLY the selected variables form the list of files
dataset <- data.frame()

for (i in 1:length(list_names)){
  temp_data <- read_dta(list_names[i], col_select = vars_select)
  dataset <- rbind(dataset, temp_data)
}
</code>```

The problem is that when some of the files have their variable names in upper case format, their variables are not in the vars_select list and therefore, the next error appears:

```<code>Error: Can't subset columns that don't exist.
x Columns `r_def`, `c_res`, `n_hog`, `v_sel`, `n_pro_viv`, etc. don't exist.
</code>```

I was trying to use the .name_repair = element in the read_dta() function to try to correct this, by using the tolower() function.

I was trying something like this with a specific file that has an upper case variable name format:

```<code>example_data <- read_dta("T:/2017_2_sdem.dta", col_select = vars_select, .name_repair = tolower(names()))

</code>```

But the same error appears:

```<code>Error: Can't subset columns that don't exist.
x Columns `r_def`, `c_res`, `n_hog`, `v_sel`, `n_pro_viv`, etc. don't exist.
</code>```

Thanks so much for your help!

Body:
I have a folder with multiple .dta files and I'm using the read_dta() function of the haven library to bind them. The problem is that some of the files have thier column names in lower case and others have them in upper case.

I was wondering if there is a way to only read the specific columns by changing their name to lower case in every case without reading the whole file and then selecting the columns, since the files are really large and this would take forever.

I was hoping that by using the .name_repair =  element in the read_dta() function I could do this, but I really don't know how.

Im trying something like this

#Set working directory:
setwd("T:/")

#List of .dta file names to bind:
list_names<-list_names[grepl("_sdem.dta", list_names)]

#Variable names to select form those files:
vars_select<-c("r_def", "c_res", "ur", "con", "n_hog", "v_sel", "n_pro_viv","fac", "n_ren", "upm","eda", "clase1", "clase2", "clase3", "ent", "sex", "e_con", "niv_ins", "eda7c", "tpg_p8a","emp_ppal", "tue_ppal", "sub_o" )

#Read and bind ONLY the selected variables form the list of files
dataset <- data.frame()

for (i in 1:length(list_names)){
  temp_data <- read_dta(list_names[i], col_select = vars_select)
  dataset <- rbind(dataset, temp_data)
}

The problem is that when some of the files have their variable names in upper case format, their variables are not in the vars_select list and therefore, the next error appears:

Error: Can't subset columns that don't exist.
x Columns `r_def`, `c_res`, `n_hog`, `v_sel`, `n_pro_viv`, etc. don't exist.

I was trying to use the .name_repair = element in the read_dta() function to try to correct this, by using the tolower() function.

I was trying something like this with a specific file that has an upper case variable name format:

example_data <- read_dta("T:/2017_2_sdem.dta", col_select = vars_select, .name_repair = tolower(names()))

But the same error appears:

Error: Can't subset columns that don't exist.
x Columns `r_def`, `c_res`, `n_hog`, `v_sel`, `n_pro_viv`, etc. don't exist.

Thanks so much for your help!


问:
Import a function that requires a function loaded on global
I want to call a function from existing file that requires functions already called in global environmet.

Here's an example of a function that was created in a .py file:

```<code>def test_func(param):
    sqrt = math.sqrt(param)
    return sqrt
</code>```

When I try to run:

```<code>import math

from test_func import *

test_func(param=4)
</code>```

I got the error:

```<code>NameError: name 'math' is not defined
</code>```

How can I call this function correctly?

Body:
I want to call a function from existing file that requires functions already called in global environmet.

Here's an example of a function that was created in a .py file:

def test_func(param):
    sqrt = math.sqrt(param)
    return sqrt

When I try to run:

import math

from test_func import *

test_func(param=4)

I got the error:

NameError: name 'math' is not defined

How can I call this function correctly?


问:
costum code execute on jupyter cell run ends
I want to add custom code that will be executed on every cell run on my jupyter notebook on my vscode editor

my main goal is that in case the cell run was more than 1 min say Done

something like:

```<code>if cell_run > 60:
    os.system("say Done")
</code>```

when I run cell it prints automatically the time it takes to run it so I guess
I can use something like that
any idea how to do that?

Body:
I want to add custom code that will be executed on every cell run on my jupyter notebook on my vscode editor

my main goal is that in case the cell run was more than 1 min say Done

something like:

if cell_run > 60:
    os.system("say Done")

when I run cell it prints automatically the time it takes to run it so I guess
I can use something like that
any idea how to do that?


问:
How install TCOD::Key with Straberry perl (windows 10)
I have got Strawberry perl with windows 10. Using cpan I try to install TCOD::Key. The problem is the libtcod.h file is absent. I do not understand how install the libraria.

```<code>D:\Documents>cpanm --force TCOD::Key
--> Working on TCOD::Key
Fetching http://www.cpan.org/authors/id/J/JJ/JJATRIA/TCOD-0.009.tar.gz ... OK
Configuring TCOD-0.009 ... OK
Building and testing TCOD-0.009 ... FAIL
! Installing TCOD::Key failed. See C:\Users\User\.cpanm\work\1672857094.2144\build.log for details. Retry with --force to force install it.
</code>```

screenshot

I expect that by installing the library, the TSOD::Key module will install successfully.

Body:
I have got Strawberry perl with windows 10. Using cpan I try to install TCOD::Key. The problem is the libtcod.h file is absent. I do not understand how install the libraria.

D:\Documents>cpanm --force TCOD::Key
--> Working on TCOD::Key
Fetching http://www.cpan.org/authors/id/J/JJ/JJATRIA/TCOD-0.009.tar.gz ... OK
Configuring TCOD-0.009 ... OK
Building and testing TCOD-0.009 ... FAIL
! Installing TCOD::Key failed. See C:\Users\User\.cpanm\work\1672857094.2144\build.log for details. Retry with --force to force install it.

screenshot

I expect that by installing the library, the TSOD::Key module will install successfully.


问:
AWS XRay tracing in Lightsail?
I have 2 environments (test and prod) running in a single AWS Lightsail instance. Both are Node servers running with pm2. I want to be able to get tracing data from both environments using AWS XRay.

I have configured the code according to the Getting Started guide. This includes having a daemon running in the background in order to send traces in batches. Even though the daemon is running and it seems like there are no issues, I don't get tracing data sent to AWS Cloudwatch. I get both success logs saying that the traces have been sent and error logs saying that the context cannot be determined at the same time.

Success logs:
Segment sent: {"trace_id:"foobar", "id":"baz"}

Failure logs:
Error: Failed to get the current sub/segment from the context.

And in the xray.log file:
2023-01-04T11:24:24-07:00 [Warn] Delaying sending of additional batches by 30 seconds
2023-01-04T11:47:57-07:00 [Error] Sending segment batch failed with: AccessDeniedException

I am fairly certain that my permissions are correct as the Lightsail user has AWSXrayFullAccess, CloudWatchFullAccess and AWSXRayDaemonWriteAccess. I can't imagine there are many other permissions that I could give but I could be wrong.

Any advice/ideas would be very appreciated.

Title: AWS XRay tracing in Lightsail?


问:
An ActionDispatch::Http::Parameters::ParseError occurred in sessions#create
I have a production Rails 6 application.  I get notified when an error occurs on the site.  We currently have someone that I suspect is trying to be nefarious which has caused multiple ParseErrors to different end points, typically endpoints set up using devise. I can see that they are taking parameters from different areas of the site in addition to adding their own and trying to send a request:

```<code>An ActionDispatch::Http::Parameters::ParseError occurred in passwords#create:

822: unexpected token at 'utf8=%E2%9C%93&authenticity_token=yay0c3PqNyV5PE6u613nCzdl%2BEPZClNiZF1hcTiPrXbwsqUJyJ9XWdo3K9v2YzjQeV63r8IkpMwRysvKGlkZ0w%3D%3D&user%5Bemail%5D=BrennaCollelo66%40aol.com&commit=Send+me+reset+password+instructions'

* URL        : https://myurl.com/users/password
* HTTP Method: POST
* IP address : 113.163.57.58
* Parameters : {}
</code>```

I've used Postman to try to replicate the error:

But when I try I always get a 200 response.  Any ideas on what I can do to replicate the error or prevent them from making the request?

Body:
I have a production Rails 6 application.  I get notified when an error occurs on the site.  We currently have someone that I suspect is trying to be nefarious which has caused multiple ParseErrors to different end points, typically endpoints set up using devise. I can see that they are taking parameters from different areas of the site in addition to adding their own and trying to send a request:

An ActionDispatch::Http::Parameters::ParseError occurred in passwords#create:

822: unexpected token at 'utf8=%E2%9C%93&authenticity_token=yay0c3PqNyV5PE6u613nCzdl%2BEPZClNiZF1hcTiPrXbwsqUJyJ9XWdo3K9v2YzjQeV63r8IkpMwRysvKGlkZ0w%3D%3D&user%5Bemail%5D=BrennaCollelo66%40aol.com&commit=Send+me+reset+password+instructions'

* URL        : https://myurl.com/users/password
* HTTP Method: POST
* IP address : 113.163.57.58
* Parameters : {}

I've used Postman to try to replicate the error:

But when I try I always get a 200 response.  Any ideas on what I can do to replicate the error or prevent them from making the request?


问:
How to show number of audio channels in a running html5 video
I am using video.js to play a HLS mpeg Transport Stream in the browser.
This is working fine without issues.

I want to show the user the information of audio while the video segments are being played. (like number of audio channels,  channel layout info etc)

Is this possible? If yes how? Can somebody guide me or point me in proper direction.
Thanks


问:
What is the correct way to query a column with IS NOT NULL with Prisma?
Is there a difference between these two queries?

```<code>this._client.myTable.findMany({
  where: {
    NOT: {
      myColumn: null
    }
  }
})
</code>```

and

```<code>this._client.myTable.findMany({
  where: {
    myColumn: {
      not: null
    }
  }
})
</code>```

or is there a more "correct" way to do this?

Body:
Is there a difference between these two queries?

this._client.myTable.findMany({
  where: {
    NOT: {
      myColumn: null
    }
  }
})

and

this._client.myTable.findMany({
  where: {
    myColumn: {
      not: null
    }
  }
})

or is there a more "correct" way to do this?


问:
How to add one positional srgument in aiogram middleware?
I have several files.
The task is to configure the middleware so that it adds the user to the local database after pressing the start button in telegram bot.
As a result I get an error.
Here it is:
TypeError: on_start() missing 1 required positional argument: 'request'

I have several files.
The task is to configure the middleware so that it adds the user to the local database after pressing the start button in telegram bot.
As a result I get an error.
Here it is:
TypeError: on_start() missing 1 required positional argument: 'request'

File middleware.py:

```<code>    `from typing import Dict, Any, Callable, Awaitable

    from aiogram import BaseMiddleware
    from aiogram.types import Message
    from apscheduler.schedulers.asyncio import AsyncIOScheduler

    class SchedulerMiddleware(BaseMiddleware):
    def __init__(self, scheduler: AsyncIOScheduler):
    self.scheduler = scheduler

    async def __call__(self,
    handler: Callable[[Message, Dict[str, Any]], Awaitable[Any]],
    event: Message,
    data: Dict[str, Any],
    ) -> Any:
    data['scheduler'] = self.scheduler
    return await handler(event, data)`
</code>```

File db_middleware.py

```<code>    `from typing import Callable, Awaitable, Dict, Any

    from aiogram import BaseMiddleware
    from aiogram.types import Message

    class DbSession(BaseMiddleware):
    def __init__(self, connector):
    self.connector = connector

    async def __call__(self,
    handler: Callable[[Message, Dict[str, Any]], Awaitable[Any]],
    event: Message,
    data: Dict[str, Any],
    ) -> Any:
    async with self.connector.connection() as connect:
    data['request'] = Request(connect)
    return await handler(event, data)`
</code>```

File fsm.py:

```<code>    `import asyncio
    import logging

    from aiogram import Bot, types, Dispatcher
    from aiogram.filters import Command, Text
    from aiogram.fsm.context import FSMContext
    from aiogram.fsm.state import StatesGroup, State
    from aiogram.types import BotCommand, BotCommandScopeDefault
    from apscheduler.schedulers.asyncio import AsyncIOScheduler

    from LearnBot.middleware.middleware import SchedulerMiddleware
    from LearnBot.others.db_connect import Request
    from main import States

    token = "5100032963:***"

    class States(StatesGroup):
    first_name = State()
    last_name = State()
    telephone = State()
    complete = State()
    cancel = State()

    async def comm(bot: Bot):
    command = [
    BotCommand(
    command='start',
    description='Начало работы',
    ),
    BotCommand(
    command='help',
    description='Помощь',
    ),
    ]

    await bot.set_my_commands(command, BotCommandScopeDefault())

    async def on_start(message: types.Message, state: FSMContext, request: Request):
    await message.reply("Введите необходимые даные\nВведите имя " + message.text)
    await request.add_user(message)
    await state.set_state(States.first_name)

    def register_fsm(dp: Dispatcher):
    dp.message.register(cancel, States.complete, Text(text='cancel', ignore_case=True))

    dp.message.register(on_start, Command(commands='start'))

    async def start():
    try:
    logging.basicConfig(
    level=logging.INFO
    )

    bots = Bot(token)
    dp = Dispatcher()

    scheduler = AsyncIOScheduler(timezone='Europe/Moscow')

    # scheduler.add_job(run_interval_args, 'interval', seconds=10, args=(55,))
    dp.update.middleware.register(SchedulerMiddleware(scheduler))
    dp.message.register(on_start, Command(commands='start'))
    scheduler.start()

    await dp.start_polling(bots)
    except Exception as ex:
    print(ex)

    if __name__ == "__main__":
    asyncio.run(start())`
</code>```

Body:
I have several files.
The task is to configure the middleware so that it adds the user to the local database after pressing the start button in telegram bot.
As a result I get an error.
Here it is:
TypeError: on_start() missing 1 required positional argument: 'request'

I have several files.
The task is to configure the middleware so that it adds the user to the local database after pressing the start button in telegram bot.
As a result I get an error.
Here it is:
TypeError: on_start() missing 1 required positional argument: 'request'

File middleware.py:

    `from typing import Dict, Any, Callable, Awaitable

    from aiogram import BaseMiddleware
    from aiogram.types import Message
    from apscheduler.schedulers.asyncio import AsyncIOScheduler

    class SchedulerMiddleware(BaseMiddleware):
    def __init__(self, scheduler: AsyncIOScheduler):
    self.scheduler = scheduler

    async def __call__(self,
    handler: Callable[[Message, Dict[str, Any]], Awaitable[Any]],
    event: Message,
    data: Dict[str, Any],
    ) -> Any:
    data['scheduler'] = self.scheduler
    return await handler(event, data)`

File db_middleware.py

    `from typing import Callable, Awaitable, Dict, Any

    from aiogram import BaseMiddleware
    from aiogram.types import Message

    class DbSession(BaseMiddleware):
    def __init__(self, connector):
    self.connector = connector

    async def __call__(self,
    handler: Callable[[Message, Dict[str, Any]], Awaitable[Any]],
    event: Message,
    data: Dict[str, Any],
    ) -> Any:
    async with self.connector.connection() as connect:
    data['request'] = Request(connect)
    return await handler(event, data)`

File fsm.py:

    `import asyncio
    import logging

    from aiogram import Bot, types, Dispatcher
    from aiogram.filters import Command, Text
    from aiogram.fsm.context import FSMContext
    from aiogram.fsm.state import StatesGroup, State
    from aiogram.types import BotCommand, BotCommandScopeDefault
    from apscheduler.schedulers.asyncio import AsyncIOScheduler

    from LearnBot.middleware.middleware import SchedulerMiddleware
    from LearnBot.others.db_connect import Request
    from main import States

    token = "5100032963:***"

    class States(StatesGroup):
    first_name = State()
    last_name = State()
    telephone = State()
    complete = State()
    cancel = State()

    async def comm(bot: Bot):
    command = [
    BotCommand(
    command='start',
    description='Начало работы',
    ),
    BotCommand(
    command='help',
    description='Помощь',
    ),
    ]

    await bot.set_my_commands(command, BotCommandScopeDefault())

    async def on_start(message: types.Message, state: FSMContext, request: Request):
    await message.reply("Введите необходимые даные\nВведите имя " + message.text)
    await request.add_user(message)
    await state.set_state(States.first_name)

    def register_fsm(dp: Dispatcher):
    dp.message.register(cancel, States.complete, Text(text='cancel', ignore_case=True))

    dp.message.register(on_start, Command(commands='start'))

    async def start():
    try:
    logging.basicConfig(
    level=logging.INFO
    )

    bots = Bot(token)
    dp = Dispatcher()

    scheduler = AsyncIOScheduler(timezone='Europe/Moscow')

    # scheduler.add_job(run_interval_args, 'interval', seconds=10, args=(55,))
    dp.update.middleware.register(SchedulerMiddleware(scheduler))
    dp.message.register(on_start, Command(commands='start'))
    scheduler.start()

    await dp.start_polling(bots)
    except Exception as ex:
    print(ex)

    if __name__ == "__main__":
    asyncio.run(start())`


问:
Android - Getting Historical Step Counter Data
I want to get every past day's step count. I will not be publishing this app, i want to create a better tracker for myself. I know my phone stores that information. I tried SensorManager but it does not both fire sensorChange event and get historical data. I dont want to use GoogleFitApi.

Which library or class should i use?


问:
Quick method to view formatted html in a variable or property during debugging
I am debugging a Django app. During debugging, I've set a breakpoint so I can see a rendered html string stored in a variable. The variable has a property called content and within is a html string which is enclose din b''. I know I can copy the value from the debugger and open a text window and paste it in. Then I can formatted so I can read it. This is time-consuming though and I wonder if there is a simple trick or alternative that will allow me to quickly view the formatted html?</p>


问:
Variable not incrementing as expected
I need help to understand the below;

```<code>def increment(n):
    n += 1
    return n

a = 1
increment(a)
print(a)
</code>```

The output is 1 and not 2 as per my little understanding of Python.

I have added the line return n in an attempt to pass on the value from n to a. It still does not.

As per a comment from @TimRoberts below, editing the above code with a = increment(a) gives an output of 2.

I am writing this here to highlight this one of many good comments below.

Title: Variable not incrementing as expected

Body:
I need help to understand the below;

def increment(n):
    n += 1
    return n

a = 1
increment(a)
print(a)

The output is 1 and not 2 as per my little understanding of Python.

I have added the line return n in an attempt to pass on the value from n to a. It still does not.

As per a comment from @TimRoberts below, editing the above code with a = increment(a) gives an output of 2.

I am writing this here to highlight this one of many good comments below.


问:
Can you make a pointer to a function pointer inside of a class?
I was trying something silly just to avoid using a single if statement in c++ in Atmel Studio (I'm programming an Atmega328pb for a battery charger but that has relatively little to do with the question except for the GCC version which I guess is supposed to be c++11 but quite a couple of functionalities are missing from what I understand). Is it possible to make an (array of pointers but I guess it's the same thing) pointer to a pointer to a method of a class? and have all of that be a part of the class itself?

Something kinda like this (not the whole thing):

```<code>#include <iostream>
typedef void func_ptr_t (void);

class battery{
public:
    bool enable;
    uint8_t port;
    func_ptr_t (battery::*func_ptr[2]);
    void*(battery::*enable_ptr[2])(void); // what I think would be the pointer to a pointer

    battery(uint8_t _battery, bool _enable): enable(_enable), port(_battery) {
        func_ptr[0] = {&battery::set_ports_low};
        func_ptr[1] = {&battery::set_ports_high}; //these two, at least when I tried them, worked successfully to call the methods of a particular object
    }

    void set_ports_low(){}
    void set_ports_high(){}
};

int main() {
    return 0;
}
</code>```

That's kind of the idea of the program so far, but then I attempted to initialize the pointer to a pointer like this in the constructor
enable_ptr[1] = {&battery::func_ptr[0]};
And I get the error (in vs code):

a value of type "void (battery::**)()" cannot be used to initialize an entity of type "void *(battery::*)()"C/C++(144)
```

Which I guess could be a syntax problem but I don't know if the whole thing is fundamentally wrong with the way I'm establishing it.

Any help or insights would help, I'm more interested in knowing if it could be done rather than its uses here, but still do tell if what I'm trying here is just pointless or if it does have a place in some application.

Body:
I was trying something silly just to avoid using a single if statement in c++ in Atmel Studio (I'm programming an Atmega328pb for a battery charger but that has relatively little to do with the question except for the GCC version which I guess is supposed to be c++11 but quite a couple of functionalities are missing from what I understand). Is it possible to make an (array of pointers but I guess it's the same thing) pointer to a pointer to a method of a class? and have all of that be a part of the class itself?

Something kinda like this (not the whole thing):

#include <iostream>
typedef void func_ptr_t (void);

class battery{
public:
    bool enable;
    uint8_t port;
    func_ptr_t (battery::*func_ptr[2]);
    void*(battery::*enable_ptr[2])(void); // what I think would be the pointer to a pointer

    battery(uint8_t _battery, bool _enable): enable(_enable), port(_battery) {
        func_ptr[0] = {&battery::set_ports_low};
        func_ptr[1] = {&battery::set_ports_high}; //these two, at least when I tried them, worked successfully to call the methods of a particular object
    }

    void set_ports_low(){}
    void set_ports_high(){}
};

int main() {
    return 0;
}

That's kind of the idea of the program so far, but then I attempted to initialize the pointer to a pointer like this in the constructor
enable_ptr[1] = {&battery::func_ptr[0]};
And I get the error (in vs code):

a value of type "void (battery::**)()" cannot be used to initialize an entity of type "void *(battery::*)()"C/C++(144)

Which I guess could be a syntax problem but I don't know if the whole thing is fundamentally wrong with the way I'm establishing it.

Any help or insights would help, I'm more interested in knowing if it could be done rather than its uses here, but still do tell if what I'm trying here is just pointless or if it does have a place in some application.


问:
SlicerCaches.SlicerItems(integer number) throwing runtime error 5
I am working on a model which includes a macro to update pivottables and select sliceritems. Included in this is a loop through the sliceritems which sets all of them to 'select = false', except for current year.

The code stops on the line below, and I cannot figure out why. I have spent way to much time trying to figure it out, so I need to ask your help..
if ActiveWorkbook.SlicerCaches("Slicer_Years").SlicerItems(i).Selected then

in this case, i has got the value of 2

i is an integer value

when I replace the i with a 2, it works and I get a true or false

when I replace the 2 with i, I get runtime error 5

This is my code (there is more code below it, but this is what is relevant). It stops on the line 'If sCYears.SlicerItems(i).Selected Then' with Runtime error 5.

```<code>
Sub RefreshPivots()

'Declare variables
    Dim tblPivot As PivotTable
    Dim strCYear, strMonth As String
    Dim sCYears, sCDate As SlicerCache
    Dim i As Integer

'Populate variables
    strCYear = "" & Sheets("Start").Range("Cyear").Value
    strMonth = Sheets("Lookup").Range("NorskPer").Value
    Set sCYears = ThisWorkbook.SlicerCaches("Slicer_Years")
    Set sCDate = ThisWorkbook.SlicerCaches("Slicer_Date")

'Loop to refresh all pivottables
    For Each tblPivot In ActiveWorkbook.PivotTables
        tblPivot.RefreshTable
    Next tblPivot

'Set slicer for year
    For Each tblPivot In sCYears.PivotTables
        tblPivot.ManualUpdate = True 'Stops PivotTable from refreshing after each PivotItem is changed
    Next tblPivot`

    sCYears.SlicerItems(1).Selected = True 'at least one item must be selected
    For i = 2 To sCYears.SlicerItems.Count
        If sCYears.SlicerItems(i).Selected Then sCYears.SlicerItems(i).Selected = False 'de-select all other items
    Next i
    sCYears.SlicerItems(strCYear).Selected = True 'select current year
    If sCYears.SlicerItems(1).Name <> strCYear Then 'de-select item 1 if not current year
        sCYears.SlicerItems(1).Selected = False
    End If

end sub`
`
</code>```

Body:
I am working on a model which includes a macro to update pivottables and select sliceritems. Included in this is a loop through the sliceritems which sets all of them to 'select = false', except for current year.

The code stops on the line below, and I cannot figure out why. I have spent way to much time trying to figure it out, so I need to ask your help..
if ActiveWorkbook.SlicerCaches("Slicer_Years").SlicerItems(i).Selected then

in this case, i has got the value of 2

i is an integer value

when I replace the i with a 2, it works and I get a true or false

when I replace the 2 with i, I get runtime error 5

This is my code (there is more code below it, but this is what is relevant). It stops on the line 'If sCYears.SlicerItems(i).Selected Then' with Runtime error 5.

Sub RefreshPivots()

'Declare variables
    Dim tblPivot As PivotTable
    Dim strCYear, strMonth As String
    Dim sCYears, sCDate As SlicerCache
    Dim i As Integer

'Populate variables
    strCYear = "" & Sheets("Start").Range("Cyear").Value
    strMonth = Sheets("Lookup").Range("NorskPer").Value
    Set sCYears = ThisWorkbook.SlicerCaches("Slicer_Years")
    Set sCDate = ThisWorkbook.SlicerCaches("Slicer_Date")

'Loop to refresh all pivottables
    For Each tblPivot In ActiveWorkbook.PivotTables
        tblPivot.RefreshTable
    Next tblPivot

'Set slicer for year
    For Each tblPivot In sCYears.PivotTables
        tblPivot.ManualUpdate = True 'Stops PivotTable from refreshing after each PivotItem is changed
    Next tblPivot`

    sCYears.SlicerItems(1).Selected = True 'at least one item must be selected
    For i = 2 To sCYears.SlicerItems.Count
        If sCYears.SlicerItems(i).Selected Then sCYears.SlicerItems(i).Selected = False 'de-select all other items
    Next i
    sCYears.SlicerItems(strCYear).Selected = True 'select current year
    If sCYears.SlicerItems(1).Name <> strCYear Then 'de-select item 1 if not current year
        sCYears.SlicerItems(1).Selected = False
    End If

end sub`
`


问:
Heroku: Support Wildcards with SSL
I'm building an app where when a user creates an account the user's name becomes a subdomain: if a user creates an account with name Jack Winston the domain will be jack-winston.domain.com. I'm using Heroku as hosting and when I'm trying to add *.domain.com to domains it says that apps that use ACM are not allowed to create wildcard domains.

How do I create a wildcard domain with SSL on Heroku?

If I have to switch to manual SSL then how can I update SSL automatically?

Title: Heroku: Support Wildcards with SSL


问:
Prisma/MySQL - Question about nested upsert (Update or Create)
I'm trying to implement a nested upsert as in the prisma docs:

https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries#update-or-create-a-related-record

I have a product which I want to add to basket. If the basket already contains the product, I want to update the amount to 5.

```<code>  if (req.method == "PUT") {
    const productId = req.body.id;

    const newBasket = await prisma.basket.update({
      where: { id: 6 },
      data: {
        basketProduct: {
          upsert: {
            create: { productId: productId, amount: 1 },
            update: { productId: productId, amount: 5 },
          },
        },
      },
    });
    return res.status(201).send(newBasket);
  }
</code>```

If I understand correctly this is how it should work, however I'm getting the following error

```<code>error - PrismaClientValidationError:
Invalid `prisma.basket.update()` invocation:

{
  where: {
    id: 6
  },
  data: {
    basketProduct: {
      upsert: {
        create: {
          productId: 61,
          amount: 1
        },
        update: {
          productId: 61,
          amount: 5
        },
+       where: {
+         id?: Int,
+         productId?: Int
+       }
      }
    }
  }
}

Argument where for data.basketProduct.upsert.where is missing.
</code>```

Apparently I need a where in my upsert, but it doesn't mention it in the docs.

These are my models

```<code>model Basket {
  id              Int       @id @default(autoincrement())
  basketProduct   BasketProduct[]
  @@map(name: "basket")
}

model BasketProduct {
  id              Int       @id @default(autoincrement())
  amount          Int
  basket          Basket    @relation(fields: [basketId], references: [id], onDelete: Cascade)
  basketId        Int       @map("basket_id")
  product         Product   @relation(fields: [productId], references: [id], onDelete: Cascade)
  productId       Int       @unique @map("product_id")
  @@map(name: "basket_product")
}
</code>```

Body:
I'm trying to implement a nested upsert as in the prisma docs:

https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries#update-or-create-a-related-record

I have a product which I want to add to basket. If the basket already contains the product, I want to update the amount to 5.

  if (req.method == "PUT") {
    const productId = req.body.id;

    const newBasket = await prisma.basket.update({
      where: { id: 6 },
      data: {
        basketProduct: {
          upsert: {
            create: { productId: productId, amount: 1 },
            update: { productId: productId, amount: 5 },
          },
        },
      },
    });
    return res.status(201).send(newBasket);
  }

If I understand correctly this is how it should work, however I'm getting the following error

error - PrismaClientValidationError:
Invalid `prisma.basket.update()` invocation:

{
  where: {
    id: 6
  },
  data: {
    basketProduct: {
      upsert: {
        create: {
          productId: 61,
          amount: 1
        },
        update: {
          productId: 61,
          amount: 5
        },
+       where: {
+         id?: Int,
+         productId?: Int
+       }
      }
    }
  }
}

Argument where for data.basketProduct.upsert.where is missing.

Apparently I need a where in my upsert, but it doesn't mention it in the docs.

These are my models

model Basket {
  id              Int       @id @default(autoincrement())
  basketProduct   BasketProduct[]
  @@map(name: "basket")
}

model BasketProduct {
  id              Int       @id @default(autoincrement())
  amount          Int
  basket          Basket    @relation(fields: [basketId], references: [id], onDelete: Cascade)
  basketId        Int       @map("basket_id")
  product         Product   @relation(fields: [productId], references: [id], onDelete: Cascade)
  productId       Int       @unique @map("product_id")
  @@map(name: "basket_product")
}


问:
Can you retrieve GeoJSON building footprints from a mapbox API?
I want to query a mapbox API and receive GeoJSON polygon or multi-polygon features containing building footprints within a certain radius of certain coordinates.

I have been experimenting with https://docs.mapbox.com/playground/tilequery/.

This is a sample request that I was hoping would return the polygons as arrays of coordinates:

https://api.mapbox.com/v4/mapbox.mapbox-streets-v8/tilequery/-93.1182,44.9502.json?radius=215&limit=5&dedupe&geometry=polygon&layers=building&access_token=myaccesstoken

However, the response contains only the point coordinates in the geometry property:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "id": 126168971,
      "geometry": {"type": "Point", "coordinates": [-93.1183, 44.9502]},
      "properties": {
        "underground": "false",
        "extrude": "true",
        "height": 3,
        "iso_3166_2": "US-MN",
        "min_height": 0,
        "iso_3166_1": "US",
        "type": "building",
        "tilequery": {"distance": 0, "geometry": "polygon", "layer": "building"}
      }
    }
  ]
}
```


问:
Problem with uploading custom font with Custom Fields in Wordpress
I made 1 field with 2 subfields in Advanced Custom Fields plugin.

1st subfield should be for font file upload.
2nd subfield should be for entering my custom text that will be displayed in font file from 1st subfield.

```<code><?php
function so_extend_frequent_bought_shortcode2() {
    global $product;
    $id = $product->get_id();
     $img = get_post_meta($id, 'wp_custom_attachment', true);
     $text = get_post_meta($id, 'text_input', true);
     $texz='';
     if(!empty($text)){
        $texz=$text;
     }else{
        $texz='Text coming from Static resource';
     }
     if(!empty($img)){
     $url= $img['url'];
 }
    $font_title = get_field("font_title");
    $upload_file = the_sub_field("upload_file");
    $title_name = the_sub_field("title_name");

?>

<style type="text/css">
 @font-face {
font-family: "<?php echo $title_name; ?>";
src: url('<?php echo $upload_file; ?>') format("opentype");
}
</style>

     <input type="text" class="font-input" id="font-input-<?php echo $title_name;?>" value="<?php echo $product->get_title();?>" style="font-family:<?php echo $title_name;?>;font-size: 120px;">

    <?php
}
add_shortcode( 'my_new_shortcode2', 'so_extend_frequent_bought_shortcode2' );
</code>```

I want to upload custom font with it and assign some name for it and publish it on my page, but I'm having some issue apparently. I made (edited some existing) shortcode for functions.php that doesn't displays font in uploaded file (it displays it now in system font instead).

What I'm doing wrong?

Body:
I made 1 field with 2 subfields in Advanced Custom Fields plugin.

1st subfield should be for font file upload.
2nd subfield should be for entering my custom text that will be displayed in font file from 1st subfield.

<?php
function so_extend_frequent_bought_shortcode2() {
    global $product;
    $id = $product->get_id();
     $img = get_post_meta($id, 'wp_custom_attachment', true);
     $text = get_post_meta($id, 'text_input', true);
     $texz='';
     if(!empty($text)){
        $texz=$text;
     }else{
        $texz='Text coming from Static resource';
     }
     if(!empty($img)){
     $url= $img['url'];
 }
    $font_title = get_field("font_title");
    $upload_file = the_sub_field("upload_file");
    $title_name = the_sub_field("title_name");

?>

     <input type="text" class="font-input" id="font-input-<?php echo $title_name;?>" value="<?php echo $product->get_title();?>" style="font-family:<?php echo $title_name;?>;font-size: 120px;">

    <?php
}
add_shortcode( 'my_new_shortcode2', 'so_extend_frequent_bought_shortcode2' );

I want to upload custom font with it and assign some name for it and publish it on my page, but I'm having some issue apparently. I made (edited some existing) shortcode for functions.php that doesn't displays font in uploaded file (it displays it now in system font instead).

What I'm doing wrong?


问:
Fluentbit AWS S3 output not flushing logs on instance termination
I've installed fluent-bit as a Windows service in a Windows Server 2019 EC2 instance. I am using tail as Input from a text file and S3 for Output with upload_timeout as 10 min. If I gracefully shut down the EC2 instance(eg. from AWS console) before the completion of 10 mins, I don't see any logs in S3. As per https://docs.fluentbit.io/manual/pipeline/outputs/s3#reliability, I assumed fluent-bit will send the logs before it shuts down. I've tried both multipart upload and put object. Also tried changing the "Service" config grace period to 20 seconds but no luck. I don't want to keep the upload_timeout very less as it will end up creating lots of files in S3 which will be difficult to analyze later. Do we have any other option which we can use to achieve this?

Config I am using ->

```<code>[SERVICE]
    flush        5
    grace       20
    .....

[INPUT]
    Name              tail
    Path              {TextFilePath}
    Read_from_Head    On

[OUTPUT]
    Name s3
    Match *
    bucket {SomeS3Bucket}
    region us-east-2
    store_dir {SomeLocalDirectory}
    upload_timeout 10m
    #use_put_object true -> Tried with and without this setting
</code>```

Body:
I've installed fluent-bit as a Windows service in a Windows Server 2019 EC2 instance. I am using tail as Input from a text file and S3 for Output with upload_timeout as 10 min. If I gracefully shut down the EC2 instance(eg. from AWS console) before the completion of 10 mins, I don't see any logs in S3. As per https://docs.fluentbit.io/manual/pipeline/outputs/s3#reliability, I assumed fluent-bit will send the logs before it shuts down. I've tried both multipart upload and put object. Also tried changing the "Service" config grace period to 20 seconds but no luck. I don't want to keep the upload_timeout very less as it will end up creating lots of files in S3 which will be difficult to analyze later. Do we have any other option which we can use to achieve this?

Config I am using ->

[SERVICE]
    flush        5
    grace       20
    .....

[INPUT]
    Name              tail
    Path              {TextFilePath}
    Read_from_Head    On

[OUTPUT]
    Name s3
    Match *
    bucket {SomeS3Bucket}
    region us-east-2
    store_dir {SomeLocalDirectory}
    upload_timeout 10m
    #use_put_object true -> Tried with and without this setting


问:
Why isn't Gradle adding the SQLite JAR files to my Java project?
First of all, I'm pretty new to Gradle. My problem is that Gradle isn't adding the SQLite JAR files to my project even though I included them in my build.gradle file and the project was built correctly.

I followed the following tutorial in order to build my Java project with Gradle:
Building Java Applications Sample
Then I added the following code to my build.gradle file:

```<code>plugins {
    // Apply the application plugin to add support for building a CLI application in Java.
    id 'application'
}

repositories {
    // Use Maven Central for resolving dependencies.
    mavenCentral()
}

dependencies {
    // This dependency is used by the application.
    implementation 'com.google.guava:guava:31.1-jre'
    implementation 'com.toedter:jcalendar:1.4'
    implementation group: 'org.xerial', name: 'sqlite-jdbc', version: '3.40.0.0'
}

testing {
    suites {
        // Configure the built-in test suite
        test {
            // Use JUnit Jupiter test framework
            useJUnitJupiter('5.9.1')
        }
    }
}

application {
    // Define the main class for the application.
    mainClass = 'myApp.App'
}
</code>```

Notice that I've also used the JCalendar library, which works just fine.
Despite being able to build the project succesfully and using the JCalendar library, when I check if the SQLite library is available I can't find nor use it. Also, when I execute the following code:

```<code>public static void main( String args[] ) {
        Connection c = null;
        try {
            Class.forName("org.sqlite.JDBC");
            c = DriverManager.getConnection("jdbc:sqlite:database.db");
        } catch ( Exception e ) {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            System.exit(0);
        }
        System.out.println("Opened database successfully");
    }
</code>```

I get the following error:
java.lang.ClassNotFoundException: org.sqlite.JDBC
Any suggestions?

Body:
First of all, I'm pretty new to Gradle. My problem is that Gradle isn't adding the SQLite JAR files to my project even though I included them in my build.gradle file and the project was built correctly.

I followed the following tutorial in order to build my Java project with Gradle:
Building Java Applications Sample
Then I added the following code to my build.gradle file:

plugins {
    // Apply the application plugin to add support for building a CLI application in Java.
    id 'application'
}

repositories {
    // Use Maven Central for resolving dependencies.
    mavenCentral()
}

dependencies {
    // This dependency is used by the application.
    implementation 'com.google.guava:guava:31.1-jre'
    implementation 'com.toedter:jcalendar:1.4'
    implementation group: 'org.xerial', name: 'sqlite-jdbc', version: '3.40.0.0'
}

testing {
    suites {
        // Configure the built-in test suite
        test {
            // Use JUnit Jupiter test framework
            useJUnitJupiter('5.9.1')
        }
    }
}

application {
    // Define the main class for the application.
    mainClass = 'myApp.App'
}

Notice that I've also used the JCalendar library, which works just fine.
Despite being able to build the project succesfully and using the JCalendar library, when I check if the SQLite library is available I can't find nor use it. Also, when I execute the following code:

public static void main( String args[] ) {
        Connection c = null;
        try {
            Class.forName("org.sqlite.JDBC");
            c = DriverManager.getConnection("jdbc:sqlite:database.db");
        } catch ( Exception e ) {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            System.exit(0);
        }
        System.out.println("Opened database successfully");
    }

I get the following error:
java.lang.ClassNotFoundException: org.sqlite.JDBC
Any suggestions?


问:
combine multiple FFT operation on GPU within python
I am using pytorch for calculating the 3d convolution using the FFT.
The current code does an FFT first, then a pointwise multiplication in Fourier space and finally an inverse FFT. The code works but seems to be very slow compared to an optimized C++ CUDA code (approximately a factor 5 slower).

I think the main problem is that each pytorch operation is handled by a seperate CUDA kernel. Is it somehow possible to merge these operations?
I heard about cuFFTDx. Can this somehow be used from python?
Or does cupy help?

thanks for any hint.
best wishes
Florian