问:
haw to store image binary into mongodb and then retrive it
iam trying to recieve a file from the user with formidable.js then save it in mongo db as binary then serve it from a server but when i try to write the binary into a file to see if i can get the hole file vs code cant open the file

```<code>const express =require("express");
const {connection} =require("./config/connect.js");
const { IncomingForm } = require('formidable');

const {User} = require("./user");
const {Team} = require("./teams.js");
const {Storage}=require("./data.js");
const{Post}=require("./posts.js");
const fs=require("fs");

const bodyParser=require("body-parser");
const { file } = require("googleapis/build/src/apis/file/index.js");
const BASE_URL="http://localhost:8000";
const app=express();

const procees=async(req,res,next)=>{
  const form = new IncomingForm({ multiples: true });

  const chunks=[]
  form.onPart =async(part) => {
    part.on('data',async(buffer) => {
      // do whatever you want here

      await chunks.push(Buffer.from(buffer, 'base64'));

    });
   form._handlePart(part)
  };
  form.parse(req, async(err, fields, files) => {
    if (err) {
      res.writeHead(err.httpCode || 400, { 'Content-Type': 'text/plain' });
      res.end(String(err));
      return;
    }
    const {id,reqtype,tagged_user,description,links}=req.body;
    const filedata = Buffer.from(await Buffer.concat(chunks),'base64');
    console.log(filedata.length)
    await fs.writeFileSync("new-path1.jpg",Buffer.from(Buffer.concat(chunks), "base64"));
    const user=await User.findOne({id});

      const file=files.file
      const match = [
      "image/bmp",
      "image/apng",
      "image/avif" ,
      "image/gif",
      "image/jpeg",
      "image/png",
      "image/svg+xml",
      "image/webp",
      "image/x-png",
      "image/jpg"];
       if(match.indexOf(file.mimetype) === -1){
         return res.send({message:"this is not an image"});
       }
        const thefilename=`${user.id+user.fullName.replace( / +/g, '_')}-${Date.now()}`

        if(user.team==="team-cover" ||user.team==="team-user" ||user.team==="team-post" && !user.team  ){
          res.send({message:"wrong request"});
        }else if(user.team==="team-cover" ||user.team==="team-user" ||user.team==="team-post" && user.team) {
          const team=await Team.findOne({id:user.team});
        }

      if(Buffer.byteLength(filedata)>16777216){
        console.log("sdasd")
        const motherdata=await Storage.create({type:file.mimetype,file:thefilename,size:filedata.length});
         for(let chunk in chunks ){
            const data=await Storge.create({type:file.mimetype,time:file.mtime,file:thefilename,size:chunk.length,data:chunk});
            await motherdata.updateOne({$push:{data:data.id}});
                  }
                  }else{
          console.log("sdasd2")
        const data=await Storage.create({type:file.mimetype,file:thefilename,size:filedata.length,data:filedata})
        const post=await Post.create({file:thefilename,time:file.mtime,description,$push:{links},photo:`${BASE_URL}/get/photo/:${thefilename}`,data:data.id,$push:{outerUser:tagged_user}});
        await post.save()
      }
        await user.updateOne({profile_photo:`${BASE_URL}/get/photo/:${thefilename}`});

    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ fields, files }, null, 2));
  });

}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

app.use("/upload",procees)
app.use("/get/photo/:name",async(req,res,next)=>{
  try{
    console.log("sdfsdf",77)
    const {name}=req.params;
    const name1=name.replace(':', '')
    console.log("gf")
    const photo=await Storage.findOne({file:name1});
    console.log("jhfjj")
    switch(photo.type){
      case "image/bmp":
         res.set("Content-Type", "image/bmp");
      case "image/apng":
         res.set("Content-Type", "image/apng");
      case"image/avif":
         res.set("Content-Type", "image/avif");
      case "image/gif":
         res.set("Content-Type", "image/gif");
      case "image/png":
         res.set("Content-Type", "image/png");
      case"image/svg+xml":
         res.set("Content-Type", "image/svg+xml");
      case "image/webp":
         res.set("Content-Type","image/webp");
      case "image/x-png":
         res.set("Content-Type","image/x-png");
      default:
         res.set("Content-Type", "image/jpeg");
    }
    console.log(photo.data.length)
    res.writeHead(200, {
      'Content-Type': `${photo.type}`,
      'Content-Length': img.length
    });
    await fs.writeFileSync("new-path.jpg",Buffer.from(photo.data, "base64"));
    res.send("pk")
  }catch(error){
    return res.send({message:error.message});
  }
})
app.use("/flash",(req,res,next)=>{
  const {url}=req.body;
  res.send(`
  <!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
  </head>
  <body>
      <div style="width:100%;height:100%">
          <img style="width:40%;height:80%" ;base64, src="data:image/jpeg;base64,#{${url}}}" alt="alternate" />

      </div>
  </body>
  </html>
  `)
})
app.listen(8000,async()=>{
  await connection();
  console.log("server is workingh");
});
</code>```

I tried to write directly without collecting the chunks first still can't get the file. Since I couldn't retrive the file from mongo i tried to write into a local file to test but I can't either

Body:
iam trying to recieve a file from the user with formidable.js then save it in mongo db as binary then serve it from a server but when i try to write the binary into a file to see if i can get the hole file vs code cant open the file

const express =require("express");
const {connection} =require("./config/connect.js");
const { IncomingForm } = require('formidable');

const {User} = require("./user");
const {Team} = require("./teams.js");
const {Storage}=require("./data.js");
const{Post}=require("./posts.js");
const fs=require("fs");

const bodyParser=require("body-parser");
const { file } = require("googleapis/build/src/apis/file/index.js");
const BASE_URL="http://localhost:8000";
const app=express();

const procees=async(req,res,next)=>{
  const form = new IncomingForm({ multiples: true });

  const chunks=[]
  form.onPart =async(part) => {
    part.on('data',async(buffer) => {
      // do whatever you want here

      await chunks.push(Buffer.from(buffer, 'base64'));

    });
   form._handlePart(part)
  };
  form.parse(req, async(err, fields, files) => {
    if (err) {
      res.writeHead(err.httpCode || 400, { 'Content-Type': 'text/plain' });
      res.end(String(err));
      return;
    }
    const {id,reqtype,tagged_user,description,links}=req.body;
    const filedata = Buffer.from(await Buffer.concat(chunks),'base64');
    console.log(filedata.length)
    await fs.writeFileSync("new-path1.jpg",Buffer.from(Buffer.concat(chunks), "base64"));
    const user=await User.findOne({id});

      const file=files.file
      const match = [
      "image/bmp",
      "image/apng",
      "image/avif" ,
      "image/gif",
      "image/jpeg",
      "image/png",
      "image/svg+xml",
      "image/webp",
      "image/x-png",
      "image/jpg"];
       if(match.indexOf(file.mimetype) === -1){
         return res.send({message:"this is not an image"});
       }
        const thefilename=`${user.id+user.fullName.replace( / +/g, '_')}-${Date.now()}`

        if(user.team==="team-cover" ||user.team==="team-user" ||user.team==="team-post" && !user.team  ){
          res.send({message:"wrong request"});
        }else if(user.team==="team-cover" ||user.team==="team-user" ||user.team==="team-post" && user.team) {
          const team=await Team.findOne({id:user.team});
        }

      if(Buffer.byteLength(filedata)>16777216){
        console.log("sdasd")
        const motherdata=await Storage.create({type:file.mimetype,file:thefilename,size:filedata.length});
         for(let chunk in chunks ){
            const data=await Storge.create({type:file.mimetype,time:file.mtime,file:thefilename,size:chunk.length,data:chunk});
            await motherdata.updateOne({$push:{data:data.id}});
                  }
                  }else{
          console.log("sdasd2")
        const data=await Storage.create({type:file.mimetype,file:thefilename,size:filedata.length,data:filedata})
        const post=await Post.create({file:thefilename,time:file.mtime,description,$push:{links},photo:`${BASE_URL}/get/photo/:${thefilename}`,data:data.id,$push:{outerUser:tagged_user}});
        await post.save()
      }
        await user.updateOne({profile_photo:`${BASE_URL}/get/photo/:${thefilename}`});

    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ fields, files }, null, 2));
  });

}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

app.use("/upload",procees)
app.use("/get/photo/:name",async(req,res,next)=>{
  try{
    console.log("sdfsdf",77)
    const {name}=req.params;
    const name1=name.replace(':', '')
    console.log("gf")
    const photo=await Storage.findOne({file:name1});
    console.log("jhfjj")
    switch(photo.type){
      case "image/bmp":
         res.set("Content-Type", "image/bmp");
      case "image/apng":
         res.set("Content-Type", "image/apng");
      case"image/avif":
         res.set("Content-Type", "image/avif");
      case "image/gif":
         res.set("Content-Type", "image/gif");
      case "image/png":
         res.set("Content-Type", "image/png");
      case"image/svg+xml":
         res.set("Content-Type", "image/svg+xml");
      case "image/webp":
         res.set("Content-Type","image/webp");
      case "image/x-png":
         res.set("Content-Type","image/x-png");
      default:
         res.set("Content-Type", "image/jpeg");
    }
    console.log(photo.data.length)
    res.writeHead(200, {
      'Content-Type': `${photo.type}`,
      'Content-Length': img.length
    });
    await fs.writeFileSync("new-path.jpg",Buffer.from(photo.data, "base64"));
    res.send("pk")
  }catch(error){
    return res.send({message:error.message});
  }
})
app.use("/flash",(req,res,next)=>{
  const {url}=req.body;
  res.send(`
  <!DOCTYPE html>

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

  `)
})
app.listen(8000,async()=>{
  await connection();
  console.log("server is workingh");
});

I tried to write directly without collecting the chunks first still can't get the file. Since I couldn't retrive the file from mongo i tried to write into a local file to test but I can't either


来源: stackexchange

问:
Issue with SimpMessagingTemplate not sending socket message to client
I have a web application that uses Kafka and Spring WebSocket for emitting different events to a mobile app. Events are triggered based on the logic where mobile app is online or offline.

The logic works perfectly fine if an event is triggered when mobile app is already online. But if it's offline, the triggered event is stored in a postgres table and marked with status PENDING. So when the mobile app comes back online, these table searches for the message and then triggers the event.

In order to update the mobile status, I am using Socket Sessions, and ChannelInterceptor which updates the mobile app status on SUBSCRIBE and DISCONNECT event.

I have logs at every possible place, and all the logs are executed when the mobile app comes back online. There's no error anywhere. The last log is right before :

```<code>messagingTemplate.convertAndSendToUser();
</code>```

Logs :

```<code>Device Status in request : true
Send Mode : IMMEDIATE
inside immediate never expire >>>>>
Enter: SocketService.send() with argument[s] = [{Status=200, Response={PayloadId=1415, PayloadExpiryDateTime=0, PayloadPriority=1, EventType=NEW_MESSAGE, TemporaryMessage={Messages={Data=[{Title=Message1, DataToSend={Message=Message1, Data=bZijp8pcSKwnbRhnm2khEUkaonv3XpZ6PnS0IRP+ab4p1ub2Cmuuylga6z8RASwPWbTbxbZH5ickk4HcWKeEM1Qq8PHnmAEj/VmnLmhP9UbITDrFbzWaeUcAhdWuFzD1QKfp4lmjsFl6LeswN6x+tgFi+mimURK9EaKuKiQKnP3sZHfw6Bk2o/jH4ik8hoKetO2GRxNOKs/8H9NYUS4hLP/RP3vJttUtHo3fiJd3WwWcxT+w+YZneDFmc28ECjpoJ0ZzgV7NRJlhKBcOMl7V6eV2Rax7yNC2k7zyHH/ylkhkq74heWAtde/S43S6WLTMbtc2+t1MgHNOevsxEyI/ghBE1wJzgBIdvlhFX4M1jam+AYHyXhF7CNC/Hr/i+dpw3/SogNQwIidW8FZ5EWwBJP2nYv0eZ0owK/8zwEs3FZWF9fRUeUGn7VwFNFDsf4P1FUbeWcwHA847iHBuUF2qDVtLNgQtyejGKxhn3+a8yoKyU96cpteOmGmbZPuyU3xRk401gkk4a0noS3SOjWO8B0OKyq782K3gRUoVssPV8Hg=, ReqNr=9.0000001E7}}]}, Playlists={Data=[{Title=TemporaryPlaylist, DataToSend={Message=Temporary Playlist, Data=G7Prf2ZRUh+MSBNTjLH2BT7nNB1o8zXgz/mn9leZ7Q4UoZH1MzMrJj3ISvdkQZNAbVCnYQjh5XhOnUr1kGrZpWJ/lHUyJi1coc7fdMxe0fkgBJk9SySvaFN/TvFQaUlv2wRWIoPVXmLVhukFgzLsDeVWmuzNaWZXTQCemIzrK6SaCJ+FfFAzgxG2Z7QxWkVx, ReqNr=9.0000002E7}}]}, ShowCommands={Data=[{DataToSend={Type=ShowPlaylistRequest, ShowAll=[{CallWord=t2212161322}]}}]}}}, Message=Success}, message, 108]
Sending to Producer : {"Status":200,"Response":{"PayloadId":1415,"PayloadExpiryDateTime":0,"PayloadPriority":1,"EventType":"NEW_MESSAGE","TemporaryMessage":{"Messages":{"Data":[{"Title":"Message1","DataToSend":{"Message":"Message1","Data":"bZijp8pcSKwnbRhnm2khEUkaonv3XpZ6PnS0IRP+ab4p1ub2Cmuuylga6z8RASwPWbTbxbZH5ickk4HcWKeEM1Qq8PHnmAEj/VmnLmhP9UbITDrFbzWaeUcAhdWuFzD1QKfp4lmjsFl6LeswN6x+tgFi+mimURK9EaKuKiQKnP3sZHfw6Bk2o/jH4ik8hoKetO2GRxNOKs/8H9NYUS4hLP/RP3vJttUtHo3fiJd3WwWcxT+w+YZneDFmc28ECjpoJ0ZzgV7NRJlhKBcOMl7V6eV2Rax7yNC2k7zyHH/ylkhkq74heWAtde/S43S6WLTMbtc2+t1MgHNOevsxEyI/ghBE1wJzgBIdvlhFX4M1jam+AYHyXhF7CNC/Hr/i+dpw3/SogNQwIidW8FZ5EWwBJP2nYv0eZ0owK/8zwEs3FZWF9fRUeUGn7VwFNFDsf4P1FUbeWcwHA847iHBuUF2qDVtLNgQtyejGKxhn3+a8yoKyU96cpteOmGmbZPuyU3xRk401gkk4a0noS3SOjWO8B0OKyq782K3gRUoVssPV8Hg=","ReqNr":9.0000001E7}}]},"Playlists":{"Data":[{"Title":"TemporaryPlaylist","DataToSend":{"Message":"Temporary Playlist","Data":"G7Prf2ZRUh+MSBNTjLH2BT7nNB1o8zXgz/mn9leZ7Q4UoZH1MzMrJj3ISvdkQZNAbVCnYQjh5XhOnUr1kGrZpWJ/lHUyJi1coc7fdMxe0fkgBJk9SySvaFN/TvFQaUlv2wRWIoPVXmLVhukFgzLsDeVWmuzNaWZXTQCemIzrK6SaCJ+FfFAzgxG2Z7QxWkVx","ReqNr":9.0000002E7}}]},"ShowCommands":{"Data":[{"DataToSend":{"Type":"ShowPlaylistRequest","ShowAll":[{"CallWord":"t2212161322"}]}}]}}},"Message":"Success"}
Exit: SocketService.send() with result = null
Received from Kafka : {"Status":200,"Response":{"PayloadId":1415,"PayloadExpiryDateTime":0,"PayloadPriority":1,"EventType":"NEW_MESSAGE","TemporaryMessage":{"Messages":{"Data":[{"Title":"Message1","DataToSend":{"Message":"Message1","Data":"bZijp8pcSKwnbRhnm2khEUkaonv3XpZ6PnS0IRP+ab4p1ub2Cmuuylga6z8RASwPWbTbxbZH5ickk4HcWKeEM1Qq8PHnmAEj/VmnLmhP9UbITDrFbzWaeUcAhdWuFzD1QKfp4lmjsFl6LeswN6x+tgFi+mimURK9EaKuKiQKnP3sZHfw6Bk2o/jH4ik8hoKetO2GRxNOKs/8H9NYUS4hLP/RP3vJttUtHo3fiJd3WwWcxT+w+YZneDFmc28ECjpoJ0ZzgV7NRJlhKBcOMl7V6eV2Rax7yNC2k7zyHH/ylkhkq74heWAtde/S43S6WLTMbtc2+t1MgHNOevsxEyI/ghBE1wJzgBIdvlhFX4M1jam+AYHyXhF7CNC/Hr/i+dpw3/SogNQwIidW8FZ5EWwBJP2nYv0eZ0owK/8zwEs3FZWF9fRUeUGn7VwFNFDsf4P1FUbeWcwHA847iHBuUF2qDVtLNgQtyejGKxhn3+a8yoKyU96cpteOmGmbZPuyU3xRk401gkk4a0noS3SOjWO8B0OKyq782K3gRUoVssPV8Hg=","ReqNr":9.0000001E7}}]},"Playlists":{"Data":[{"Title":"TemporaryPlaylist","DataToSend":{"Message":"Temporary Playlist","Data":"G7Prf2ZRUh+MSBNTjLH2BT7nNB1o8zXgz/mn9leZ7Q4UoZH1MzMrJj3ISvdkQZNAbVCnYQjh5XhOnUr1kGrZpWJ/lHUyJi1coc7fdMxe0fkgBJk9SySvaFN/TvFQaUlv2wRWIoPVXmLVhukFgzLsDeVWmuzNaWZXTQCemIzrK6SaCJ+FfFAzgxG2Z7QxWkVx","ReqNr":9.0000002E7}}]},"ShowCommands":{"Data":[{"DataToSend":{"Type":"ShowPlaylistRequest","ShowAll":[{"CallWord":"t2212161322"}]}}]}}},"Message":"Success"}
Sending to Socket Client.......

</code>```

But the front-end never gets the message.

Below are some code snippets:

Channel Interceptor:

```<code>public class SocketInterceptor implements ChannelInterceptor {

    @Autowired
    SocketSessionService socketSessionService;

    private final Logger log = LoggerFactory.getLogger(SocketInterceptor.class);

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {

        MessageHeaders headers = message.getHeaders();
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);

        MultiValueMap<String, String> multiValueMap = headers.get(StompHeaderAccessor.NATIVE_HEADERS,MultiValueMap.class);

        if (multiValueMap !=null) {
            if (multiValueMap.containsKey("destination")) {
                String destination = multiValueMap.get("destination").get(0);
                log.info("Destination in interceptor : " + destination);
            }
        }

        if (accessor.getCommand()!=null) {
            log.info("Client Method : " + accessor.getCommand().name());
            if (accessor.getCommand().equals(StompCommand.CONNECT) || accessor.getCommand().equals(StompCommand.SUBSCRIBE) || accessor.getCommand().equals(StompCommand.SEND)) {
                if (!multiValueMap.containsKey("access-token")) {
                    log.error("Token Error " + "No Token was provided in + " + accessor.getCommand().name());
                    throw new MessagingException("Forbidden: No Token was provided in header for Socket Command: " + accessor.getCommand().name());
                }
                String token = multiValueMap.get("access-token").get(0);
                if (JwtTokenUtil.verifyToken(JwtTokenUtil.decrypt(token))) {
                    log.info("Token Verified Successfully >>>>>>>>>>>>>>>>>>>> ");

                    Claims claims = JwtTokenUtil.verifyJwtToken(JwtTokenUtil.decrypt(token));
                    accessor.setHeader("access-token", token);
                    Principal principal = new UsernamePasswordAuthenticationToken(claims.getId(), null, null);

                    accessor.setUser(principal);
                    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                            claims.getId(), null, null);

                    SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                    if (accessor.getCommand().equals(StompCommand.SUBSCRIBE)){
                        log.info("Storing Socket Session on Socket Command SUBSCRIBE ");
                        SocketSessionModel model=new SocketSessionModel();
                        model.setSessionId(accessor.getSessionId());
                        model.setDeviceId(multiValueMap.get("destination").get(0));
                        model.setAccessToken(token);
                        model.setCurrentStatus(SocketSessionStatus.ONLINE);
                        model.setReportedOnlineAt(ZonedDateTime.now().with(ZoneOffset.UTC));
                        model.setReportedOfflineAt(null);
                        socketSessionService.onSubscribe(model);
                    }
                    ObjectMapper objectMapper= new ObjectMapper();
                    try {
                        log.info("Returning back the frame : " + objectMapper.writeValueAsString(message.getPayload()));
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                    return new GenericMessage<>(message.getPayload(), accessor.getMessageHeaders());
                }
                throw new MessagingException("Token either Expired or Invalid");
            }
        }
        return message;
    }
}
</code>```

WebSocket Config :

```<code>@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    Logger log= LoggerFactory.getLogger(WebSocketConfig.class);

    @Autowired
    SocketSessionService socketSessionService;

    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {

        stompEndpointRegistry.addEndpoint("/ws")
                .setAllowedOrigins("*")
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/user")
                .setTaskScheduler(customTaskScheduler())
                .setHeartbeatValue(new long[]{25000,10000});
        config.setApplicationDestinationPrefixes("/app");
        config.setUserDestinationPrefix("/user");
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(socketInterceptor());
    }
    @Bean
    public SocketInterceptor socketInterceptor() {
        return new SocketInterceptor();
    }

    @Bean
    public TaskScheduler customTaskScheduler(){
        return new ThreadPoolTaskScheduler();
    }

    @EventListener(SessionDisconnectEvent.class)
    public void handleWsDisconnectListener(SessionDisconnectEvent event) {
        Optional<String> sessionId= getSessionIdFromEvent(event);
        sessionId.ifPresent(s -> socketSessionService.onDisconnect(s));
    }
    private Optional<String> getSessionIdFromEvent(AbstractSubProtocolEvent event) {
        String sessionId = null;
        System.out.println("Session Id in event : " + (event.getMessage().getHeaders()).get("simpSessionId"));
        Object sessionIdAsObject = (event.getMessage().getHeaders()).get("simpSessionId");
        if (nonNull(sessionIdAsObject) && sessionIdAsObject.getClass().equals(String.class)) {
            sessionId = (String) sessionIdAsObject;
        }
        return Optional.ofNullable(StringUtils.isEmpty(sessionId) ? null : sessionId);
    }
}
</code>```

Kafka Producer Config :

```<code>@Service
public class KafkaProducerConfig {

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Async
    public void send(String data, String kafkaTopic, String key) {

        kafkaTemplate.send(kafkaTopic, key, data);
    }

    @Async
    public void send(String topic, String data ){
        kafkaTemplate.send(topic, data);
    }
}
</code>```

KafkaConsumer Config :

```<code>@EnableKafka
@Configuration
public class KafkaConsumerConfig {

    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServers;

    public ConsumerFactory<String, String> consumerFactory(String groupId) {
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        return new DefaultKafkaConsumerFactory<>(props);
    }

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, String> rawKafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory("something"));
        return factory;
    }
}
</code>```

Kafka Listener :
This is the last step where socket emits the messages to clients. The last line of log mentioned here is executed.

```<code>@Component
public class KafkaListenerForSocket {

    private final Logger log= LoggerFactory.getLogger(KafkaListenerForSocket.class);

    @Autowired
    SimpMessagingTemplate messagingTemplate;

    @KafkaListener(topics = KafkaTopicConstants.MESSAGE, containerFactory = "rawKafkaListenerContainerFactory")
    public void listenToMessages(ConsumerRecord<String, String> consumerRecord) throws IOException {
        ObjectMapper objectMapper=new ObjectMapper();
        String destination="/queue/message";
        BaseSocketResponse response=objectMapper.readValue(consumerRecord.value(), BaseSocketResponse.class);
        messagingTemplate.convertAndSendToUser(consumerRecord.key(),destination,response);

    }

    public void send(Object data, String key){
        log.info("Bypassing Kafka and sending directly");
        String destination="/queue/message";
        log.info("sending to destination : " + "/user/"+key+destination);
        messagingTemplate.convertAndSendToUser(key, destination, data);
    }
}
</code>```

BaseSocketResponse.Java class :

```<code>public class BaseSocketResponse<T> {

    @JsonProperty(value = "Status", required = true)
    private Integer status;

    @JsonProperty(value = "Message", required = true)
    private String statusMessage = "";

    @JsonProperty(value = "Response", required = true)
    private T response;

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getStatusMessage() {
        return statusMessage;
    }

    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }

    public T getResponse() {
        return response;
    }

    public void setResponse(T response) {
        this.response = response;
    }

}
</code>```

front-end code :

```<code>var stompClient = null;

function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
        $("#conversation").show();
    }
    else {
        $("#conversation").hide();
    }
    $("#userinfo").html("");
}

function connect() {
    let header={"access-token" : $("#token").val()};
    var socket = new SockJS('/services/toplight/ws');
    stompClient = Stomp.over(socket);
    stompClient.connect(header, function (frame) {
        if(frame.command == "CONNECTED") {
            console.log("Inside frame command : >>>>> " + frame);
            setConnected(true);
            subscribe(stompClient)
        }
    }, (error) => {
        console.log("Inside Connect error : " + error );
        onConnectError(error);
    });
}

function subscribe(stompClient){

    var token=$("#token").val();
    var header={"access-token": token};

console.log("Subscribing to Destination : " + '/user/'+$("#name").val()+'/queue/message');
    stompClient.subscribe('/user/'+$("#name").val()+'/queue/message' , greeting, header);

    var greeting=function(message){
        var body=JSON.parse(message.body);
        if(body.Response.EventType=="NEW_MESSAGE"){
            showNewMessage(response);
        }

        if(body.Response.EventType=="DEVICE_UPDATE_RESPONSE"){
            showDeviceUpdate(response);
        }

        if(body.Response.EventType=="MESSAGE_UPDATE_RESPONSE"){
            showMessageUpdate(response);
        }
    };

}

function onConnectError(error){
    console.log("Error : >>>>> " + error);
    $("#greetings").append("<h3><tr><td>" + error + "</h3>");
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a web application that uses Kafka and Spring WebSocket for emitting different events to a mobile app. Events are triggered based on the logic where mobile app is online or offline.

The logic works perfectly fine if an event is triggered when mobile app is already online. But if it's offline, the triggered event is stored in a postgres table and marked with status PENDING. So when the mobile app comes back online, these table searches for the message and then triggers the event.

In order to update the mobile status, I am using Socket Sessions, and ChannelInterceptor which updates the mobile app status on SUBSCRIBE and DISCONNECT event.

I have logs at every possible place, and all the logs are executed when the mobile app comes back online. There's no error anywhere. The last log is right before :

messagingTemplate.convertAndSendToUser();

Logs :

Device Status in request : true
Send Mode : IMMEDIATE
inside immediate never expire >>>>>
Enter: SocketService.send() with argument[s] = [{Status=200, Response={PayloadId=1415, PayloadExpiryDateTime=0, PayloadPriority=1, EventType=NEW_MESSAGE, TemporaryMessage={Messages={Data=[{Title=Message1, DataToSend={Message=Message1, Data=bZijp8pcSKwnbRhnm2khEUkaonv3XpZ6PnS0IRP+ab4p1ub2Cmuuylga6z8RASwPWbTbxbZH5ickk4HcWKeEM1Qq8PHnmAEj/VmnLmhP9UbITDrFbzWaeUcAhdWuFzD1QKfp4lmjsFl6LeswN6x+tgFi+mimURK9EaKuKiQKnP3sZHfw6Bk2o/jH4ik8hoKetO2GRxNOKs/8H9NYUS4hLP/RP3vJttUtHo3fiJd3WwWcxT+w+YZneDFmc28ECjpoJ0ZzgV7NRJlhKBcOMl7V6eV2Rax7yNC2k7zyHH/ylkhkq74heWAtde/S43S6WLTMbtc2+t1MgHNOevsxEyI/ghBE1wJzgBIdvlhFX4M1jam+AYHyXhF7CNC/Hr/i+dpw3/SogNQwIidW8FZ5EWwBJP2nYv0eZ0owK/8zwEs3FZWF9fRUeUGn7VwFNFDsf4P1FUbeWcwHA847iHBuUF2qDVtLNgQtyejGKxhn3+a8yoKyU96cpteOmGmbZPuyU3xRk401gkk4a0noS3SOjWO8B0OKyq782K3gRUoVssPV8Hg=, ReqNr=9.0000001E7}}]}, Playlists={Data=[{Title=TemporaryPlaylist, DataToSend={Message=Temporary Playlist, Data=G7Prf2ZRUh+MSBNTjLH2BT7nNB1o8zXgz/mn9leZ7Q4UoZH1MzMrJj3ISvdkQZNAbVCnYQjh5XhOnUr1kGrZpWJ/lHUyJi1coc7fdMxe0fkgBJk9SySvaFN/TvFQaUlv2wRWIoPVXmLVhukFgzLsDeVWmuzNaWZXTQCemIzrK6SaCJ+FfFAzgxG2Z7QxWkVx, ReqNr=9.0000002E7}}]}, ShowCommands={Data=[{DataToSend={Type=ShowPlaylistRequest, ShowAll=[{CallWord=t2212161322}]}}]}}}, Message=Success}, message, 108]
Sending to Producer : {"Status":200,"Response":{"PayloadId":1415,"PayloadExpiryDateTime":0,"PayloadPriority":1,"EventType":"NEW_MESSAGE","TemporaryMessage":{"Messages":{"Data":[{"Title":"Message1","DataToSend":{"Message":"Message1","Data":"bZijp8pcSKwnbRhnm2khEUkaonv3XpZ6PnS0IRP+ab4p1ub2Cmuuylga6z8RASwPWbTbxbZH5ickk4HcWKeEM1Qq8PHnmAEj/VmnLmhP9UbITDrFbzWaeUcAhdWuFzD1QKfp4lmjsFl6LeswN6x+tgFi+mimURK9EaKuKiQKnP3sZHfw6Bk2o/jH4ik8hoKetO2GRxNOKs/8H9NYUS4hLP/RP3vJttUtHo3fiJd3WwWcxT+w+YZneDFmc28ECjpoJ0ZzgV7NRJlhKBcOMl7V6eV2Rax7yNC2k7zyHH/ylkhkq74heWAtde/S43S6WLTMbtc2+t1MgHNOevsxEyI/ghBE1wJzgBIdvlhFX4M1jam+AYHyXhF7CNC/Hr/i+dpw3/SogNQwIidW8FZ5EWwBJP2nYv0eZ0owK/8zwEs3FZWF9fRUeUGn7VwFNFDsf4P1FUbeWcwHA847iHBuUF2qDVtLNgQtyejGKxhn3+a8yoKyU96cpteOmGmbZPuyU3xRk401gkk4a0noS3SOjWO8B0OKyq782K3gRUoVssPV8Hg=","ReqNr":9.0000001E7}}]},"Playlists":{"Data":[{"Title":"TemporaryPlaylist","DataToSend":{"Message":"Temporary Playlist","Data":"G7Prf2ZRUh+MSBNTjLH2BT7nNB1o8zXgz/mn9leZ7Q4UoZH1MzMrJj3ISvdkQZNAbVCnYQjh5XhOnUr1kGrZpWJ/lHUyJi1coc7fdMxe0fkgBJk9SySvaFN/TvFQaUlv2wRWIoPVXmLVhukFgzLsDeVWmuzNaWZXTQCemIzrK6SaCJ+FfFAzgxG2Z7QxWkVx","ReqNr":9.0000002E7}}]},"ShowCommands":{"Data":[{"DataToSend":{"Type":"ShowPlaylistRequest","ShowAll":[{"CallWord":"t2212161322"}]}}]}}},"Message":"Success"}
Exit: SocketService.send() with result = null
Received from Kafka : {"Status":200,"Response":{"PayloadId":1415,"PayloadExpiryDateTime":0,"PayloadPriority":1,"EventType":"NEW_MESSAGE","TemporaryMessage":{"Messages":{"Data":[{"Title":"Message1","DataToSend":{"Message":"Message1","Data":"bZijp8pcSKwnbRhnm2khEUkaonv3XpZ6PnS0IRP+ab4p1ub2Cmuuylga6z8RASwPWbTbxbZH5ickk4HcWKeEM1Qq8PHnmAEj/VmnLmhP9UbITDrFbzWaeUcAhdWuFzD1QKfp4lmjsFl6LeswN6x+tgFi+mimURK9EaKuKiQKnP3sZHfw6Bk2o/jH4ik8hoKetO2GRxNOKs/8H9NYUS4hLP/RP3vJttUtHo3fiJd3WwWcxT+w+YZneDFmc28ECjpoJ0ZzgV7NRJlhKBcOMl7V6eV2Rax7yNC2k7zyHH/ylkhkq74heWAtde/S43S6WLTMbtc2+t1MgHNOevsxEyI/ghBE1wJzgBIdvlhFX4M1jam+AYHyXhF7CNC/Hr/i+dpw3/SogNQwIidW8FZ5EWwBJP2nYv0eZ0owK/8zwEs3FZWF9fRUeUGn7VwFNFDsf4P1FUbeWcwHA847iHBuUF2qDVtLNgQtyejGKxhn3+a8yoKyU96cpteOmGmbZPuyU3xRk401gkk4a0noS3SOjWO8B0OKyq782K3gRUoVssPV8Hg=","ReqNr":9.0000001E7}}]},"Playlists":{"Data":[{"Title":"TemporaryPlaylist","DataToSend":{"Message":"Temporary Playlist","Data":"G7Prf2ZRUh+MSBNTjLH2BT7nNB1o8zXgz/mn9leZ7Q4UoZH1MzMrJj3ISvdkQZNAbVCnYQjh5XhOnUr1kGrZpWJ/lHUyJi1coc7fdMxe0fkgBJk9SySvaFN/TvFQaUlv2wRWIoPVXmLVhukFgzLsDeVWmuzNaWZXTQCemIzrK6SaCJ+FfFAzgxG2Z7QxWkVx","ReqNr":9.0000002E7}}]},"ShowCommands":{"Data":[{"DataToSend":{"Type":"ShowPlaylistRequest","ShowAll":[{"CallWord":"t2212161322"}]}}]}}},"Message":"Success"}
Sending to Socket Client.......

But the front-end never gets the message.

Below are some code snippets:

Channel Interceptor:

public class SocketInterceptor implements ChannelInterceptor {

    @Autowired
    SocketSessionService socketSessionService;

    private final Logger log = LoggerFactory.getLogger(SocketInterceptor.class);

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {

        MessageHeaders headers = message.getHeaders();
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);

        MultiValueMap<String, String> multiValueMap = headers.get(StompHeaderAccessor.NATIVE_HEADERS,MultiValueMap.class);

        if (multiValueMap !=null) {
            if (multiValueMap.containsKey("destination")) {
                String destination = multiValueMap.get("destination").get(0);
                log.info("Destination in interceptor : " + destination);
            }
        }

        if (accessor.getCommand()!=null) {
            log.info("Client Method : " + accessor.getCommand().name());
            if (accessor.getCommand().equals(StompCommand.CONNECT) || accessor.getCommand().equals(StompCommand.SUBSCRIBE) || accessor.getCommand().equals(StompCommand.SEND)) {
                if (!multiValueMap.containsKey("access-token")) {
                    log.error("Token Error " + "No Token was provided in + " + accessor.getCommand().name());
                    throw new MessagingException("Forbidden: No Token was provided in header for Socket Command: " + accessor.getCommand().name());
                }
                String token = multiValueMap.get("access-token").get(0);
                if (JwtTokenUtil.verifyToken(JwtTokenUtil.decrypt(token))) {
                    log.info("Token Verified Successfully >>>>>>>>>>>>>>>>>>>> ");

                    Claims claims = JwtTokenUtil.verifyJwtToken(JwtTokenUtil.decrypt(token));
                    accessor.setHeader("access-token", token);
                    Principal principal = new UsernamePasswordAuthenticationToken(claims.getId(), null, null);

                    accessor.setUser(principal);
                    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                            claims.getId(), null, null);

                    SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                    if (accessor.getCommand().equals(StompCommand.SUBSCRIBE)){
                        log.info("Storing Socket Session on Socket Command SUBSCRIBE ");
                        SocketSessionModel model=new SocketSessionModel();
                        model.setSessionId(accessor.getSessionId());
                        model.setDeviceId(multiValueMap.get("destination").get(0));
                        model.setAccessToken(token);
                        model.setCurrentStatus(SocketSessionStatus.ONLINE);
                        model.setReportedOnlineAt(ZonedDateTime.now().with(ZoneOffset.UTC));
                        model.setReportedOfflineAt(null);
                        socketSessionService.onSubscribe(model);
                    }
                    ObjectMapper objectMapper= new ObjectMapper();
                    try {
                        log.info("Returning back the frame : " + objectMapper.writeValueAsString(message.getPayload()));
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                    return new GenericMessage<>(message.getPayload(), accessor.getMessageHeaders());
                }
                throw new MessagingException("Token either Expired or Invalid");
            }
        }
        return message;
    }
}

WebSocket Config :

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    Logger log= LoggerFactory.getLogger(WebSocketConfig.class);

    @Autowired
    SocketSessionService socketSessionService;

    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {

        stompEndpointRegistry.addEndpoint("/ws")
                .setAllowedOrigins("*")
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/user")
                .setTaskScheduler(customTaskScheduler())
                .setHeartbeatValue(new long[]{25000,10000});
        config.setApplicationDestinationPrefixes("/app");
        config.setUserDestinationPrefix("/user");
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(socketInterceptor());
    }
    @Bean
    public SocketInterceptor socketInterceptor() {
        return new SocketInterceptor();
    }

    @Bean
    public TaskScheduler customTaskScheduler(){
        return new ThreadPoolTaskScheduler();
    }

    @EventListener(SessionDisconnectEvent.class)
    public void handleWsDisconnectListener(SessionDisconnectEvent event) {
        Optional<String> sessionId= getSessionIdFromEvent(event);
        sessionId.ifPresent(s -> socketSessionService.onDisconnect(s));
    }
    private Optional<String> getSessionIdFromEvent(AbstractSubProtocolEvent event) {
        String sessionId = null;
        System.out.println("Session Id in event : " + (event.getMessage().getHeaders()).get("simpSessionId"));
        Object sessionIdAsObject = (event.getMessage().getHeaders()).get("simpSessionId");
        if (nonNull(sessionIdAsObject) && sessionIdAsObject.getClass().equals(String.class)) {
            sessionId = (String) sessionIdAsObject;
        }
        return Optional.ofNullable(StringUtils.isEmpty(sessionId) ? null : sessionId);
    }
}

Kafka Producer Config :

@Service
public class KafkaProducerConfig {

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Async
    public void send(String data, String kafkaTopic, String key) {

        kafkaTemplate.send(kafkaTopic, key, data);
    }

    @Async
    public void send(String topic, String data ){
        kafkaTemplate.send(topic, data);
    }
}

KafkaConsumer Config :

@EnableKafka
@Configuration
public class KafkaConsumerConfig {

    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServers;

    public ConsumerFactory<String, String> consumerFactory(String groupId) {
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        return new DefaultKafkaConsumerFactory<>(props);
    }

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, String> rawKafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory("something"));
        return factory;
    }
}

Kafka Listener :
This is the last step where socket emits the messages to clients. The last line of log mentioned here is executed.

@Component
public class KafkaListenerForSocket {

    private final Logger log= LoggerFactory.getLogger(KafkaListenerForSocket.class);

    @Autowired
    SimpMessagingTemplate messagingTemplate;

    @KafkaListener(topics = KafkaTopicConstants.MESSAGE, containerFactory = "rawKafkaListenerContainerFactory")
    public void listenToMessages(ConsumerRecord<String, String> consumerRecord) throws IOException {
        ObjectMapper objectMapper=new ObjectMapper();
        String destination="/queue/message";
        BaseSocketResponse response=objectMapper.readValue(consumerRecord.value(), BaseSocketResponse.class);
        messagingTemplate.convertAndSendToUser(consumerRecord.key(),destination,response);

    }

    public void send(Object data, String key){
        log.info("Bypassing Kafka and sending directly");
        String destination="/queue/message";
        log.info("sending to destination : " + "/user/"+key+destination);
        messagingTemplate.convertAndSendToUser(key, destination, data);
    }
}

BaseSocketResponse.Java class :

public class BaseSocketResponse<T> {

    @JsonProperty(value = "Status", required = true)
    private Integer status;

    @JsonProperty(value = "Message", required = true)
    private String statusMessage = "";

    @JsonProperty(value = "Response", required = true)
    private T response;

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getStatusMessage() {
        return statusMessage;
    }

    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }

    public T getResponse() {
        return response;
    }

    public void setResponse(T response) {
        this.response = response;
    }

}

front-end code :

var stompClient = null;

function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
        $("#conversation").show();
    }
    else {
        $("#conversation").hide();
    }
    $("#userinfo").html("");
}

function connect() {
    let header={"access-token" : $("#token").val()};
    var socket = new SockJS('/services/toplight/ws');
    stompClient = Stomp.over(socket);
    stompClient.connect(header, function (frame) {
        if(frame.command == "CONNECTED") {
            console.log("Inside frame command : >>>>> " + frame);
            setConnected(true);
            subscribe(stompClient)
        }
    }, (error) => {
        console.log("Inside Connect error : " + error );
        onConnectError(error);
    });
}

function subscribe(stompClient){

    var token=$("#token").val();
    var header={"access-token": token};

console.log("Subscribing to Destination : " + '/user/'+$("#name").val()+'/queue/message');
    stompClient.subscribe('/user/'+$("#name").val()+'/queue/message' , greeting, header);

    var greeting=function(message){
        var body=JSON.parse(message.body);
        if(body.Response.EventType=="NEW_MESSAGE"){
            showNewMessage(response);
        }

        if(body.Response.EventType=="DEVICE_UPDATE_RESPONSE"){
            showDeviceUpdate(response);
        }

        if(body.Response.EventType=="MESSAGE_UPDATE_RESPONSE"){
            showMessageUpdate(response);
        }
    };

}

function onConnectError(error){
    console.log("Error : >>>>> " + error);
    $("#greetings").append("

" + error + "
");
}


问:
bin/dev restarting after ctrl+c
I am using a project based on Bullet Train. Bullet train is based on Ruby on Rails

It's Procfile.dev file looks like this

web: bin/rails server -p 3000
worker: bundle exec sidekiq -t 25
js: yarn build --watch
light-js: yarn light:build --watch
light-css: yarn light:build:css --watch
light-mailer-css: yarn light:build:mailer:css --watch
```

So when I run bin/dev starts ok. Whenever I need to make a change, I hit Ctrl+C, but instead of just shutting down, it shuts down and starts again, only after the second Ctrl+C the script stops.

Any ideas on what could be causing the restart?

Title: bin/dev restarting after ctrl+c

Body:
I am using a project based on Bullet Train. Bullet train is based on Ruby on Rails

It's Procfile.dev file looks like this

web: bin/rails server -p 3000
worker: bundle exec sidekiq -t 25
js: yarn build --watch
light-js: yarn light:build --watch
light-css: yarn light:build:css --watch
light-mailer-css: yarn light:build:mailer:css --watch

So when I run bin/dev starts ok. Whenever I need to make a change, I hit Ctrl+C, but instead of just shutting down, it shuts down and starts again, only after the second Ctrl+C the script stops.

Any ideas on what could be causing the restart?


问:
Spring cloud Consul for non spring boot web app
I have microservice written in spring boot that is not web app (no spring-boot-starter-web dependency).
It consumes event from message bus and do some other calculation not related to web request at all.

Still I want it to be registered with Hashicorp Consul using spring cloud service registration (for external configuration and health checks) but it only registered automatically when I add the spring-boot-starter-web dependency.

Any ideas how to use spring-cloud-starter-consul without web dependency?


问:
How to get history of all previous pushed navigation for flutter web/native application?
There is an issue with my navigation and it's parsed value from previous screen for web application.
Actually, I go via Get.toNamed(Routes.VISAS); to next screen and next screen's back button is not working when I reload the web application so I have implemented own back button then try to called Get.back(); or Navigator.of(context).pop(); manually but still not working. so I thought during reload the web app it removes all previous navigation and it's parsed value from previous screen as well and this is a big issue for my web app.

so I was thinking to get rid of this issue , first of all I fetch the navigation history if there is no push screen in stack so I will navigate to my home screen else go back to previous screen().
and 2nd issue : when I parsed value via constructor it remove as well when reload the web application so I Will use SharedPreferences() to resolve this. I know this is not a good approach. Help me out to get navigation history in flutter application.

GOTO NEXT SCREEN :

```<code>Get.toNamed(Routes.VISAS);
</code>```

FOR BACK :

```<code>Get.back(); // Not working when I reload the web application
//Navigator.of(context).pop();
</code>```

From :

TO:

Body:
There is an issue with my navigation and it's parsed value from previous screen for web application.
Actually, I go via Get.toNamed(Routes.VISAS); to next screen and next screen's back button is not working when I reload the web application so I have implemented own back button then try to called Get.back(); or Navigator.of(context).pop(); manually but still not working. so I thought during reload the web app it removes all previous navigation and it's parsed value from previous screen as well and this is a big issue for my web app.

so I was thinking to get rid of this issue , first of all I fetch the navigation history if there is no push screen in stack so I will navigate to my home screen else go back to previous screen().
and 2nd issue : when I parsed value via constructor it remove as well when reload the web application so I Will use SharedPreferences() to resolve this. I know this is not a good approach. Help me out to get navigation history in flutter application.

GOTO NEXT SCREEN :

Get.toNamed(Routes.VISAS);

FOR BACK :

Get.back(); // Not working when I reload the web application
//Navigator.of(context).pop();

From :

TO:


问:
There are two functions for uploading pictures in ViewController
I upload the image when button 1 is clicked, but the second image also shows the image uploaded by button 1!

What should I do so that the image uploaded on button 1 is displayed on image 1, and the image on the boat on button 2 is displayed on image 2?

Here is my code, thanks for your help

```<code>    @IBAction func imageSelect(sender: Any){
        let actionSheetController = UIAlertController()

               let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel) { (alertAction) -> Void in
                   print("Tap 取消 Button")
               }

               let takingPicturesAction = UIAlertAction(title: "拍照", style: UIAlertAction.Style.destructive) { (alertAction) -> Void in
                   self.getImageGo(type: 1)
               }

               let photoAlbumAction = UIAlertAction(title: "相册", style: UIAlertAction.Style.default) { (alertAction) -> Void in
                   self.getImageGo(type: 2)
               }

               actionSheetController.addAction(cancelAction)
               actionSheetController.addAction(takingPicturesAction)
               actionSheetController.addAction(photoAlbumAction)

               actionSheetController.popoverPresentationController?.sourceView = sender as? UIView
               //显示
               self.present(actionSheetController, animated: true, completion: nil)

    }

    @IBAction func imageSelect2(sender: Any){
        let actionSheetController = UIAlertController()

               let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel) { (alertAction) -> Void in
                   print("Tap 取消 Button")
               }

               let takingPicturesAction = UIAlertAction(title: "拍照", style: UIAlertAction.Style.destructive) { (alertAction) -> Void in
                   self.getImageGo(type: 1)
               }

               let photoAlbumAction = UIAlertAction(title: "相册", style: UIAlertAction.Style.default) { (alertAction) -> Void in
                   self.getImageGo(type: 2)
               }

               actionSheetController.addAction(cancelAction)
               actionSheetController.addAction(takingPicturesAction)
               actionSheetController.addAction(photoAlbumAction)

               //iPad设备浮动层设置锚点
               actionSheetController.popoverPresentationController?.sourceView = sender as? UIView
               //显示
               self.present(actionSheetController, animated: true, completion: nil)
    }

    func getImageGo(type:Int){
           takingPicture =  UIImagePickerController.init()
           if(type==1){
               takingPicture.sourceType = .camera

               //takingPicture.showsCameraControls = true
           }else if(type==2){
               takingPicture.sourceType = .photoLibrary
           }

           takingPicture.allowsEditing = true
           takingPicture.delegate = self
           present(takingPicture, animated: true, completion: nil)
       }
</code>```

I think the problem is here in the code, but I don't know how to modify it, thanks for your help

```<code>func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
           takingPicture.dismiss(animated: true, completion: nil)
           if(takingPicture.allowsEditing == false){
               //原图
               ID1.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
               ID2.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
           }else{
               //截图
               ID1.image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
               ID2.image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
           }

       }
</code>```

Body:
I upload the image when button 1 is clicked, but the second image also shows the image uploaded by button 1!

What should I do so that the image uploaded on button 1 is displayed on image 1, and the image on the boat on button 2 is displayed on image 2?

Here is my code, thanks for your help

    @IBAction func imageSelect(sender: Any){
        let actionSheetController = UIAlertController()

               let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel) { (alertAction) -> Void in
                   print("Tap 取消 Button")
               }

               let takingPicturesAction = UIAlertAction(title: "拍照", style: UIAlertAction.Style.destructive) { (alertAction) -> Void in
                   self.getImageGo(type: 1)
               }

               let photoAlbumAction = UIAlertAction(title: "相册", style: UIAlertAction.Style.default) { (alertAction) -> Void in
                   self.getImageGo(type: 2)
               }

               actionSheetController.addAction(cancelAction)
               actionSheetController.addAction(takingPicturesAction)
               actionSheetController.addAction(photoAlbumAction)

               actionSheetController.popoverPresentationController?.sourceView = sender as? UIView
               //显示
               self.present(actionSheetController, animated: true, completion: nil)

    }

    @IBAction func imageSelect2(sender: Any){
        let actionSheetController = UIAlertController()

               let cancelAction = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel) { (alertAction) -> Void in
                   print("Tap 取消 Button")
               }

               let takingPicturesAction = UIAlertAction(title: "拍照", style: UIAlertAction.Style.destructive) { (alertAction) -> Void in
                   self.getImageGo(type: 1)
               }

               let photoAlbumAction = UIAlertAction(title: "相册", style: UIAlertAction.Style.default) { (alertAction) -> Void in
                   self.getImageGo(type: 2)
               }

               actionSheetController.addAction(cancelAction)
               actionSheetController.addAction(takingPicturesAction)
               actionSheetController.addAction(photoAlbumAction)

               //iPad设备浮动层设置锚点
               actionSheetController.popoverPresentationController?.sourceView = sender as? UIView
               //显示
               self.present(actionSheetController, animated: true, completion: nil)
    }

    func getImageGo(type:Int){
           takingPicture =  UIImagePickerController.init()
           if(type==1){
               takingPicture.sourceType = .camera

               //takingPicture.showsCameraControls = true
           }else if(type==2){
               takingPicture.sourceType = .photoLibrary
           }

           takingPicture.allowsEditing = true
           takingPicture.delegate = self
           present(takingPicture, animated: true, completion: nil)
       }

I think the problem is here in the code, but I don't know how to modify it, thanks for your help

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
           takingPicture.dismiss(animated: true, completion: nil)
           if(takingPicture.allowsEditing == false){
               //原图
               ID1.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
               ID2.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
           }else{
               //截图
               ID1.image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
               ID2.image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
           }

       }


问:
Is there an Application Version Issue with the Elastic Beanstalk restart-app-server action on Lambda?
I am attempting to deploy a Flask (python3.8) application via AWS Elastic Beanstalk (EB). I have a backend data pipeline that generates a serve.json file, which contains metadata about the S3 prefix to use for serving up data on the frontend. serve.json is updated and overwritten everyday, and I have an S3 trigger on the prefix containing serve.json that is to call a Lambda function which will restart the WSGI web-app server managing the Flask app, which is running on the EC2 instances created by EB. After each restart, my Flask app should read in data from .parquet files on the S3 prefix specified in the updated serve.json and offer a RESTful API.

Problem: When I restart-app-server via boto3/Lambda, although the application restarts, my EB environment (my-eb-environment) gets degraded (Health: Red) with cause = Incorrect application version found on all instances. Expected version n/a..

CLI Route: The CLI action works as expected. The effect of the action can be seen in the eb health console below:

$    aws elasticbeanstalk restart-app-server --environment-name "my-eb-environment"

Lambda Route: An S3 trigger calls the Lambda function below when serve.json is uploaded to the trigger prefix:

```<code>from datetime import datetime
import boto3

def lambda_handler(event, context):
    """
    restart the WSGI App Server running on EC2 instance(s) associated with
    an Elastic Beanstalk Environment
    """
    print(str(datetime.now()))
    EB_ENV_NAME = 'my-eb-environment'
    try:
        eb_client = boto3.client('elasticbeanstalk')
        eb_response = eb_client.restart_app_server(EnvironmentName=EB_ENV_NAME)
        print('SUCCESS! RESTARTED WEB SERVER FOR EnvironmentName {}'.format(EB_ENV_NAME))
        response = 200
        return (eb_response, response)
    except Exception as e:
        print('BAD REQUEST: COULD NOT RESTART WEB SERVER\nMESSAGE: {}'.format(e))
        response = 400
        return (None, response)
</code>```

I can describe-log-streams and get-log-events to view logs of the Lambda function. It is clear that the app has refreshed:

But, eb health reveals that the EB environment has degraded:

Running the CLI command on my terminal again refreshes the application server and makes the environment healthy:

$    aws elasticbeanstalk restart-app-server --environment-name "my-eb-environment"

Questions:

How do I resolve the application version issue on the Lambda route to perform restart-app-server with this pipeline to automate app refreshing with S3 triggers?

Are there any alternative solutions for automated EB application refreshing based on S3 triggers? I do not wish to reboot the EC2 instances, because I would like to avoid the downtime if I can.

Body:
I am attempting to deploy a Flask (python3.8) application via AWS Elastic Beanstalk (EB). I have a backend data pipeline that generates a serve.json file, which contains metadata about the S3 prefix to use for serving up data on the frontend. serve.json is updated and overwritten everyday, and I have an S3 trigger on the prefix containing serve.json that is to call a Lambda function which will restart the WSGI web-app server managing the Flask app, which is running on the EC2 instances created by EB. After each restart, my Flask app should read in data from .parquet files on the S3 prefix specified in the updated serve.json and offer a RESTful API.

Problem: When I restart-app-server via boto3/Lambda, although the application restarts, my EB environment (my-eb-environment) gets degraded (Health: Red) with cause = Incorrect application version found on all instances. Expected version n/a..

CLI Route: The CLI action works as expected. The effect of the action can be seen in the eb health console below:

$    aws elasticbeanstalk restart-app-server --environment-name "my-eb-environment"

Lambda Route: An S3 trigger calls the Lambda function below when serve.json is uploaded to the trigger prefix:

from datetime import datetime
import boto3

def lambda_handler(event, context):
    """
    restart the WSGI App Server running on EC2 instance(s) associated with
    an Elastic Beanstalk Environment
    """
    print(str(datetime.now()))
    EB_ENV_NAME = 'my-eb-environment'
    try:
        eb_client = boto3.client('elasticbeanstalk')
        eb_response = eb_client.restart_app_server(EnvironmentName=EB_ENV_NAME)
        print('SUCCESS! RESTARTED WEB SERVER FOR EnvironmentName {}'.format(EB_ENV_NAME))
        response = 200
        return (eb_response, response)
    except Exception as e:
        print('BAD REQUEST: COULD NOT RESTART WEB SERVER\nMESSAGE: {}'.format(e))
        response = 400
        return (None, response)

I can describe-log-streams and get-log-events to view logs of the Lambda function. It is clear that the app has refreshed:

But, eb health reveals that the EB environment has degraded:

Running the CLI command on my terminal again refreshes the application server and makes the environment healthy:

$    aws elasticbeanstalk restart-app-server --environment-name "my-eb-environment"

Questions:

How do I resolve the application version issue on the Lambda route to perform restart-app-server with this pipeline to automate app refreshing with S3 triggers?

Are there any alternative solutions for automated EB application refreshing based on S3 triggers? I do not wish to reboot the EC2 instances, because I would like to avoid the downtime if I can.


问:
I won't click date picker using python selenium web driver and chrome browser
I am try to click date picker using python selenium automation chrome web driver.
But it won't working. and I feed the date string in text box also not working.
I got the error was NoSuchElementException and TimeOutException.
NoSuchElementException : time.sleep below or equal 30 seconds
TimeOutException : time.sleep above 30 seconds

```<code>st_date = 'Apr 1, 2022'
# I using the script like
driver.find_element(By.ID, By.Css_Selector,
By.Xpath and By.Classname)
webdriver_wait(driver, 30).
until(EC.clickble_to_be_element((By.ID,
By.Css_Selector, By.Xpath and By.Classname))).click()
send_keys(st_date)
</code>```

If I checking the html code iframe not including I inspect the browser.

Body:
I am try to click date picker using python selenium automation chrome web driver.
But it won't working. and I feed the date string in text box also not working.
I got the error was NoSuchElementException and TimeOutException.
NoSuchElementException : time.sleep below or equal 30 seconds
TimeOutException : time.sleep above 30 seconds

st_date = 'Apr 1, 2022'
# I using the script like
driver.find_element(By.ID, By.Css_Selector,
By.Xpath and By.Classname)
webdriver_wait(driver, 30).
until(EC.clickble_to_be_element((By.ID,
By.Css_Selector, By.Xpath and By.Classname))).click()
send_keys(st_date)

If I checking the html code iframe not including I inspect the browser.


问:
i want to merge downloaded adaptive streams using pytube
i want to merge downloaded adaptive streams using pytube. My attempts with ffmpeg were futile. always the same error: "could not find codec parameter..."
the command i used is shown in the image.
Please help me

enter image description here
I tried the command in the image


问:
add a react button in this code with the function of updating data from database
I made a discord bot that sends an embed with data in it taken from mysql , but when I add the react function to update the database it always gives the following error `

```<code>        throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
              ^

DiscordAPIError[10014]: Unknown Emoji
    at SequentialHandler.runRequest (D:\BotDc\node_modules\@discordjs\rest\dist\index.js:667:15)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SequentialHandler.queueRequest (D:\BotDc\node_modules\@discordjs\rest\dist\index.js:464:14)
    at async REST.request (D:\BotDc\node_modules\@discordjs\rest\dist\index.js:910:22)
    at async MessageManager.react (D:\BotDc\node_modules\discord.js\src\managers\MessageManager.js:242:5)
    at async Message.react (D:\BotDc\node_modules\discord.js\src\structures\Message.js:760:5)
    at async Query.onResult (D:\BotDc\index.js:48:11) {
  rawError: { message: 'Unknown Emoji', code: 10014 },
  code: 10014,
  status: 400,
  method: 'PUT',
  url: 'https://discord.com/api/v10/channels/745223942976962590/messages/1056802702929186836/reactions/1%3F%3F/@me'
}
</code>```

`

and also when I only send embed without react on discord it will show error before embed is sent in pict
pict

keep in mind I am sending multiple messages with 1 comands and mysql

her my code  `

```<code>const Discord = require('discord.js');
const fs = require('fs');
const path = require('path');
const mysql = require('mysql2');

const { token } = require('./config.json');

const client = new Discord.Client({ intents: [Discord.GatewayIntentBits.Guilds] });

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'continue_web'
});

connection.connect((err) => {
  if (err) throw err;
  console.log('Connected to MySQL database');
});

client.once(Discord.Events.ClientReady, c => {
  client.commands = new Discord.Collection();
  client.on(Discord.Events.InteractionCreate, async interaction => {
    if (!interaction.isChatInputCommand()) return;
    if (interaction.commandName === 'ping') {
connection.query("SELECT * , CASE sex WHEN 1 THEN 'Laki-Laki' WHEN 2 THEN 'Perempuan' END AS gender_text FROM accounts WHERE gauth_status='pending'", async (error, results) => {
  if (error) throw error;
  for (const result of results) {
    const exampleEmbed = new Discord.EmbedBuilder()
      .setColor(0x0099FF)
      .setTitle(result.nickname)
      .setURL('https://discord.js.org/')
      .setAuthor({ name: result.nickname , iconURL: 'https://continue-rp.my.id/forum/data/avatars/m/0/1.jpg?1671348397', url: 'https://discord.js.org' })
      .setDescription('Request Character Story')
      .addFields({ name: 'Story:', value: result.ucpmail , inline: false })
      .addFields({ name: 'Umur:', value: result.age + ' Tahun' , inline: true })
      .addFields({ name: 'Gender:', value: result.gender_text , inline: true })
      .addFields({
        name: 'Actions:',
        value: ':one: Approve\n:two: Reject',
        inline: true
      })
      .setTimestamp()
      .setFooter({ text: 'Character Dibuat:'+ '\n'+ result.create_date , iconURL: 'https://continue-rp.my.id/forum/data/avatars/m/0/1.jpg?1671348397' });
    await interaction.channel.send({ embeds: [exampleEmbed] });
  }
});

    }
  });
  console.log(`Ready! Logged in as ${c.user.tag}`);
});

client.login(token);

</code>```

`

I've tried various methods such as reply, but can only send 1 message, which I expect can update the database using React

Body:
I made a discord bot that sends an embed with data in it taken from mysql , but when I add the react function to update the database it always gives the following error `

        throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
              ^

DiscordAPIError[10014]: Unknown Emoji
    at SequentialHandler.runRequest (D:\BotDc\node_modules\@discordjs\rest\dist\index.js:667:15)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SequentialHandler.queueRequest (D:\BotDc\node_modules\@discordjs\rest\dist\index.js:464:14)
    at async REST.request (D:\BotDc\node_modules\@discordjs\rest\dist\index.js:910:22)
    at async MessageManager.react (D:\BotDc\node_modules\discord.js\src\managers\MessageManager.js:242:5)
    at async Message.react (D:\BotDc\node_modules\discord.js\src\structures\Message.js:760:5)
    at async Query.onResult (D:\BotDc\index.js:48:11) {
  rawError: { message: 'Unknown Emoji', code: 10014 },
  code: 10014,
  status: 400,
  method: 'PUT',
  url: 'https://discord.com/api/v10/channels/745223942976962590/messages/1056802702929186836/reactions/1%3F%3F/@me'
}

`

and also when I only send embed without react on discord it will show error before embed is sent in pict
pict

keep in mind I am sending multiple messages with 1 comands and mysql

her my code  `

const Discord = require('discord.js');
const fs = require('fs');
const path = require('path');
const mysql = require('mysql2');

const { token } = require('./config.json');

const client = new Discord.Client({ intents: [Discord.GatewayIntentBits.Guilds] });

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'continue_web'
});

connection.connect((err) => {
  if (err) throw err;
  console.log('Connected to MySQL database');
});

client.once(Discord.Events.ClientReady, c => {
  client.commands = new Discord.Collection();
  client.on(Discord.Events.InteractionCreate, async interaction => {
    if (!interaction.isChatInputCommand()) return;
    if (interaction.commandName === 'ping') {
connection.query("SELECT * , CASE sex WHEN 1 THEN 'Laki-Laki' WHEN 2 THEN 'Perempuan' END AS gender_text FROM accounts WHERE gauth_status='pending'", async (error, results) => {
  if (error) throw error;
  for (const result of results) {
    const exampleEmbed = new Discord.EmbedBuilder()
      .setColor(0x0099FF)
      .setTitle(result.nickname)
      .setURL('https://discord.js.org/')
      .setAuthor({ name: result.nickname , iconURL: 'https://continue-rp.my.id/forum/data/avatars/m/0/1.jpg?1671348397', url: 'https://discord.js.org' })
      .setDescription('Request Character Story')
      .addFields({ name: 'Story:', value: result.ucpmail , inline: false })
      .addFields({ name: 'Umur:', value: result.age + ' Tahun' , inline: true })
      .addFields({ name: 'Gender:', value: result.gender_text , inline: true })
      .addFields({
        name: 'Actions:',
        value: ':one: Approve\n:two: Reject',
        inline: true
      })
      .setTimestamp()
      .setFooter({ text: 'Character Dibuat:'+ '\n'+ result.create_date , iconURL: 'https://continue-rp.my.id/forum/data/avatars/m/0/1.jpg?1671348397' });
    await interaction.channel.send({ embeds: [exampleEmbed] });
  }
});

    }
  });
  console.log(`Ready! Logged in as ${c.user.tag}`);
});

client.login(token);

`

I've tried various methods such as reply, but can only send 1 message, which I expect can update the database using React


问:
C# Issue finding controls inside of nested Accordions
I have a user control comprised of two nested accordions with a repeater inside, all of which are pulled from a database. The repeater has CheckBoxes with MutuallyExclusiveCheckBoxExtenders inside. When the page posts back I am attempting to use LINQ along with a recursive FindControl function to gather all of the CheckBoxes. The issue is that the CheckBoxes are not being located.

Basic Structure, cleaned up for brevity:

```<code><ajaxToolkit:Accordion ID="acc1">
    <ContentTemplate>
       <ajaxToolkit:Accordion ID="acc2">
            <ContentTemplate>
                <asp:Repeater ID="r1">
                    <ItemTemplate>
                        <asp:CheckBox ID="cb1" />
                        <asp:CheckBox ID="cb2" />
                        <ajaxToolkit:MutuallyExclusiveCheckBoxExtender ID="mece1" TargetControlID="cb1" />
                        <ajaxToolkit:MutuallyExclusiveCheckBoxExtender ID="meceMine2" TargetControlID="cb2" />
                    </ItemTemplate>
                </asp:Repeater>
            </ContentTemplate>
        </ajaxToolkit:Accordion>
    </ContentTemplate>
</ajaxToolkit:Accordion>
</code>```

Everything displays correctly. On button click, elsewhere on the page, I am attempting to gather all of the controls and only the accordion controls, some literals, and the hidden fields I am using are being displayed.

Here is the recursive FindControls function I am using:

```<code>public static void FindControls(Control start, List<Control> list)
{
    list.Add(start);

    foreach (Control c in start.Controls)
    {
        FindControls(c, list);
    }
}
</code>```

This function is never finding the CheckBoxes in order to return them even though it displays correctly.

ContentLicense: CC BY-SA 3.0

Body:
I have a user control comprised of two nested accordions with a repeater inside, all of which are pulled from a database. The repeater has CheckBoxes with MutuallyExclusiveCheckBoxExtenders inside. When the page posts back I am attempting to use LINQ along with a recursive FindControl function to gather all of the CheckBoxes. The issue is that the CheckBoxes are not being located.

Basic Structure, cleaned up for brevity:

<ajaxToolkit:Accordion ID="acc1">
    <ContentTemplate>
       <ajaxToolkit:Accordion ID="acc2">
            <ContentTemplate>
                <asp:Repeater ID="r1">
                    <ItemTemplate>
                        <asp:CheckBox ID="cb1" />
                        <asp:CheckBox ID="cb2" />
                        <ajaxToolkit:MutuallyExclusiveCheckBoxExtender ID="mece1" TargetControlID="cb1" />
                        <ajaxToolkit:MutuallyExclusiveCheckBoxExtender ID="meceMine2" TargetControlID="cb2" />
                    </ItemTemplate>
                </asp:Repeater>
            </ContentTemplate>
        </ajaxToolkit:Accordion>
    </ContentTemplate>
</ajaxToolkit:Accordion>

Everything displays correctly. On button click, elsewhere on the page, I am attempting to gather all of the controls and only the accordion controls, some literals, and the hidden fields I am using are being displayed.

Here is the recursive FindControls function I am using:

public static void FindControls(Control start, List<Control> list)
{
    list.Add(start);

    foreach (Control c in start.Controls)
    {
        FindControls(c, list);
    }
}

This function is never finding the CheckBoxes in order to return them even though it displays correctly.


问:
Importing a JSON object to a Google Cloud SQL instance authentication error
I have been stuck on this for the last 2 days, first time in a long time I had to use stackoverflow. But I love this community

What I am trying to do?

I am trying to upload a JSON object to update a table in a cloud SQL instance.

Error I am getting

I have tried using a service account and 02Auth credentials but I still get these errors.

Code below

```<code>    from pprint import pprint

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from google.oauth2 import service_account
import google.auth.credentials

    credentials = GoogleCredentials.get_application_default()
quota_project_id = "alert-groove-360914"
scopes = ["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/sqlservice.admin"]
#credentials, _ = google.auth.load_credentials_from_file(
#            "alert-groove-360914-0d5821a7921c.json", scopes=scopes, quota_project_id=quota_project_id
#        )
#credentials = service_account.Credentials.from_service_account_file("alert-groove-360914-0d5821a7921c.json")
service = discovery.build('sqladmin', 'v1beta4', credentials=credentials)

# Project ID of the project that contains the instance.
project = 'XXXXXXXX'  # TODO: Update placeholder value.

# Cloud SQL instance ID. This does not include the project ID.
instance = 'employment-types'  # TODO: Update placeholder value.

database_instance_body = {
    "id": 3,
    "first_name": "XXXXXXXX",
    "last_name": "XXXXXXX",
    "email": "XXXXXX28@gmail.com",
    "mobile_number": "XXXXXXXXX",
    "country_id": 224,
    "new_user": False,
    "status": 1,
    "reason": 'null',
    "duration": 'null',
    "linkedin_id": 'null',
    "sync_contacts": False,
    "linkedin_sync": False,
    "available": True,
    "radar_visibility": 'null',
    "details": {
        "organization": "Foras",
        "isSelfEmployed": False,
        "gender_id": 2,
        "location_id": 457,
        "gender": 'null',
        "about": "The best around and nothing will ever get me down",
        "image": "https:\/\/foras.tedmob.com\/storage\/users\/image-8596.jpg",
        "lat": "25.20082000253009",
        "long": "55.280527271443894",
        "Gender_Rel": "Male",
        "job_title": "Engineer",
        "Experience": "10+ years",
        "Location": "Dubai"
    },
    "interests": [
        {
            "id": 106,
            "title": "Nightlife",
            "icon": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-5908.png",
            "image": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-7960.png",
            "category": {
                "category": "Culture"
            }
        },
        {
            "id": 102,
            "title": "Music",
            "icon": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-5908.png",
            "image": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-7960.png",
            "category": {
                "category": "Culture"
            }
        },
        {
            "id": 98,
            "title": "Personal finance",
            "icon": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-5908.png",
            "image": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-7960.png",
            "category": {
                "category": "Finance"
            }
        },
        {
            "id": 101,
            "title": "Crypto currency ",
            "icon": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-5908.png",
            "image": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-7960.png",
            "category": {
                "category": "Finance"
            }
        },
        {
            "id": 104,
            "title": "Breaking",
            "icon": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-5908.png",
            "image": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-7960.png",
            "category": {
                "category": "Culture"
            }
        }
    ],
    "languages": [],
    "goals": [
        {
            "id": 2,
            "title": "Find a new job",
            "icon": "https:\/\/foras.tedmob.com\/storage\/goals\/find-a-new-job-6804.png",
            "pivot": {
                "user_id": 3,
                "goal_id": 2
            },
            "category": {
                "category": "Career"
            }
        },
        {
            "id": 11,
            "title": "Explore a career change",
            "icon": "https:\/\/foras.tedmob.com\/storage\/goals\/explore-a-career-change-5885.png",
            "pivot": {
                "user_id": 3,
                "goal_id": 11
            },
            "category": {
                "category": "Career"
            }
        },
        {
            "id": 12,
            "title": "Find co-founders",
            "icon": "https:\/\/foras.tedmob.com\/storage\/goals\/find-co-founders-2170.png",
            "pivot": {
                "user_id": 3,
                "goal_id": 12
            },
            "category": {
                "category": "Networking"
            }
        }
    ],
    "country": {
        "id": 224,
        "name": "United Arab Emirates",
        "iso": "AE",
        "phone_code": "+971"
    },
    "academic_levels": [
        {
            "id": 4,
            "title": "Master's degree",
            "pivot": {
                "user_id": 3,
                "academic_level_id": 4
            }
        }
    ],
    "experiences": [
        {
            "id": 1,
            "title": "test1",
            "company_name": "test",
            "isCurrentlyWorking": True,
            "start_date": "2021-06-15 00:00:00",
            "end_date": "2022-09-13 00:00:00",
            "end_position": True,
            "headline": "test",
            "industry": "test",
            "description": "description",
            "employment_type": 1
        }
    ]
}
request = service.instances().update(project=project, instance=instance, body=database_instance_body)

request.execute()
</code>```

Body:
I have been stuck on this for the last 2 days, first time in a long time I had to use stackoverflow. But I love this community

What I am trying to do?

I am trying to upload a JSON object to update a table in a cloud SQL instance.

Error I am getting

I have tried using a service account and 02Auth credentials but I still get these errors.

Code below

    from pprint import pprint

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from google.oauth2 import service_account
import google.auth.credentials

    credentials = GoogleCredentials.get_application_default()
quota_project_id = "alert-groove-360914"
scopes = ["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/sqlservice.admin"]
#credentials, _ = google.auth.load_credentials_from_file(
#            "alert-groove-360914-0d5821a7921c.json", scopes=scopes, quota_project_id=quota_project_id
#        )
#credentials = service_account.Credentials.from_service_account_file("alert-groove-360914-0d5821a7921c.json")
service = discovery.build('sqladmin', 'v1beta4', credentials=credentials)

# Project ID of the project that contains the instance.
project = 'XXXXXXXX'  # TODO: Update placeholder value.

# Cloud SQL instance ID. This does not include the project ID.
instance = 'employment-types'  # TODO: Update placeholder value.

database_instance_body = {
    "id": 3,
    "first_name": "XXXXXXXX",
    "last_name": "XXXXXXX",
    "email": "XXXXXX28@gmail.com",
    "mobile_number": "XXXXXXXXX",
    "country_id": 224,
    "new_user": False,
    "status": 1,
    "reason": 'null',
    "duration": 'null',
    "linkedin_id": 'null',
    "sync_contacts": False,
    "linkedin_sync": False,
    "available": True,
    "radar_visibility": 'null',
    "details": {
        "organization": "Foras",
        "isSelfEmployed": False,
        "gender_id": 2,
        "location_id": 457,
        "gender": 'null',
        "about": "The best around and nothing will ever get me down",
        "image": "https:\/\/foras.tedmob.com\/storage\/users\/image-8596.jpg",
        "lat": "25.20082000253009",
        "long": "55.280527271443894",
        "Gender_Rel": "Male",
        "job_title": "Engineer",
        "Experience": "10+ years",
        "Location": "Dubai"
    },
    "interests": [
        {
            "id": 106,
            "title": "Nightlife",
            "icon": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-5908.png",
            "image": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-7960.png",
            "category": {
                "category": "Culture"
            }
        },
        {
            "id": 102,
            "title": "Music",
            "icon": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-5908.png",
            "image": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-7960.png",
            "category": {
                "category": "Culture"
            }
        },
        {
            "id": 98,
            "title": "Personal finance",
            "icon": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-5908.png",
            "image": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-7960.png",
            "category": {
                "category": "Finance"
            }
        },
        {
            "id": 101,
            "title": "Crypto currency ",
            "icon": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-5908.png",
            "image": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-7960.png",
            "category": {
                "category": "Finance"
            }
        },
        {
            "id": 104,
            "title": "Breaking",
            "icon": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-5908.png",
            "image": "https:\/\/foras.tedmob.com\/storage\/interests\/basket-ball-7960.png",
            "category": {
                "category": "Culture"
            }
        }
    ],
    "languages": [],
    "goals": [
        {
            "id": 2,
            "title": "Find a new job",
            "icon": "https:\/\/foras.tedmob.com\/storage\/goals\/find-a-new-job-6804.png",
            "pivot": {
                "user_id": 3,
                "goal_id": 2
            },
            "category": {
                "category": "Career"
            }
        },
        {
            "id": 11,
            "title": "Explore a career change",
            "icon": "https:\/\/foras.tedmob.com\/storage\/goals\/explore-a-career-change-5885.png",
            "pivot": {
                "user_id": 3,
                "goal_id": 11
            },
            "category": {
                "category": "Career"
            }
        },
        {
            "id": 12,
            "title": "Find co-founders",
            "icon": "https:\/\/foras.tedmob.com\/storage\/goals\/find-co-founders-2170.png",
            "pivot": {
                "user_id": 3,
                "goal_id": 12
            },
            "category": {
                "category": "Networking"
            }
        }
    ],
    "country": {
        "id": 224,
        "name": "United Arab Emirates",
        "iso": "AE",
        "phone_code": "+971"
    },
    "academic_levels": [
        {
            "id": 4,
            "title": "Master's degree",
            "pivot": {
                "user_id": 3,
                "academic_level_id": 4
            }
        }
    ],
    "experiences": [
        {
            "id": 1,
            "title": "test1",
            "company_name": "test",
            "isCurrentlyWorking": True,
            "start_date": "2021-06-15 00:00:00",
            "end_date": "2022-09-13 00:00:00",
            "end_position": True,
            "headline": "test",
            "industry": "test",
            "description": "description",
            "employment_type": 1
        }
    ]
}
request = service.instances().update(project=project, instance=instance, body=database_instance_body)

request.execute()


问:
JOIN self in MikroORM query Builder
I would like to do this:

SELECT * FROM (
    SELECT * FROM `gps_log`                                           -- Same table
    WHERE log_time >= DATE_SUB(NOW(), INTERVAL 232324324 MINUTE)
) as g
JOIN (SELECT MAX(gps_log_id) as gps_id, consignment_consignment_id
      FROM `gps_log`                                                   -- Same table
      GROUP BY consignment_consignment_id
     ) AS max ON max.gps_id = g.gps_log_id
```
<p>but with MikroORM's query builder. I have read the docs and could not get it working with explicit joining.</p>
<p>My current solution is to <code>getKnex</code> instance and calling the raw sql. However I felt that it is unclean and still could not get it working:</p>
```
const qb = this.em.createQueryBuilder(GpsLog);
const knex = qb.getKnexQuery(); // instance of Knex' QueryBuilder

knex.select("*")
    .fromRaw(
        "(SELECT * FROM `gps_log` WHERE log_time >= DATE_SUB(NOW(), INTERVAL 232324324 MINUTE)) as g"
    )
    .joinRaw(
        "(SELECT MAX(gps_log_id) as gps_id, consignment_consignment_id FROM `gps_log` GROUP BY consignment_consignment_id) AS max ON max.gps_id = g.gps_log_id"
    )

const res = await this.em.getConnection().execute(knex);
const result = res.map(a => this.em.map(GpsLog, a));

return result;

```
<p>For reference, here is my entity table:</p>
```
@Entity()
export class GpsLog {

    /* SQL properties */
    @PrimaryKey({ hidden: true })
    gpsLogId!: number;

    @Property({ type: types.double })
    long!: string;

    @Property({ type: types.double })
    lat!: string;

    @Property()
    logTime: Date;

    /* JSON Formatter */
    @Property({ persist: false })
    get self() {
        return `/consgts/${this.consignment}/logs/${this.gpsLogId}`;
    }

    @Property({ persist: false })
    get consgt() {
        return `/consgts/${this.consignment}`;
    }

    /* SQL Relationships */
    @ManyToOne(() => Consignment, { mapToPk: true, hidden: true })
    consignment!: Consignment;
}

```

Title: JOIN self in MikroORM query Builder

Body:
I would like to do this:

SELECT * FROM (
    SELECT * FROM `gps_log`                                           -- Same table
    WHERE log_time >= DATE_SUB(NOW(), INTERVAL 232324324 MINUTE)
) as g
JOIN (SELECT MAX(gps_log_id) as gps_id, consignment_consignment_id
      FROM `gps_log`                                                   -- Same table
      GROUP BY consignment_consignment_id
     ) AS max ON max.gps_id = g.gps_log_id

but with MikroORM's query builder. I have read the docs and could not get it working with explicit joining.

My current solution is to getKnex instance and calling the raw sql. However I felt that it is unclean and still could not get it working:

const qb = this.em.createQueryBuilder(GpsLog);
const knex = qb.getKnexQuery(); // instance of Knex' QueryBuilder

knex.select("*")
    .fromRaw(
        "(SELECT * FROM `gps_log` WHERE log_time >= DATE_SUB(NOW(), INTERVAL 232324324 MINUTE)) as g"
    )
    .joinRaw(
        "(SELECT MAX(gps_log_id) as gps_id, consignment_consignment_id FROM `gps_log` GROUP BY consignment_consignment_id) AS max ON max.gps_id = g.gps_log_id"
    )

const res = await this.em.getConnection().execute(knex);
const result = res.map(a => this.em.map(GpsLog, a));

return result;

For reference, here is my entity table:

@Entity()
export class GpsLog {

    /* SQL properties */
    @PrimaryKey({ hidden: true })
    gpsLogId!: number;

    @Property({ type: types.double })
    long!: string;

    @Property({ type: types.double })
    lat!: string;

    @Property()
    logTime: Date;

    /* JSON Formatter */
    @Property({ persist: false })
    get self() {
        return `/consgts/${this.consignment}/logs/${this.gpsLogId}`;
    }

    @Property({ persist: false })
    get consgt() {
        return `/consgts/${this.consignment}`;
    }

    /* SQL Relationships */
    @ManyToOne(() => Consignment, { mapToPk: true, hidden: true })
    consignment!: Consignment;
}


问:
how i use url scheme intent with Context#
Can I use Context#startActivityIfNeeded() in the intent url scheme

another content about intent url scheme using Context#startActivityIfNeeded() but I still don't understand.


问:
How to link node 18.12.1 with glibc 2.28 at runtime?
I installed glibc 2.28 on my Linux Mint 19.1 system successfully by following How to install GLIBC 2.29 or higher in Ubuntu 18.04.

Now I need to actually run node. The new glibc has been installed in /opt/glibc. How to make sure node links with glibc 2.28.


问:
Obtain version of packages installed from docker image/container
Assume I pull a docker image using docker pull image1. The image is for a python application and its dependencies. I can run a container from this image, and everything works well. I am interested in finding the list of all installed packages and their dependencies from the running container or pulled image. I am wondering if there is a way to get that.

Note: I know if there is a requirements.txt, then I can find all the information but assume there is no such thing.


问:
Flutter, TextField direction line by line
how i can build a textField to change text direction line by line ( based on the first character )

For example, I want it to be displayed as below when typing 2 letters in different languages in the text field

```<code>// this line started with LTR characters, start at left
Hi Good morning

// this line started with RTL characters, start at right
                 سلام، صبح بخیر

Are you ok?
                    حالت خوبه؟

</code>```

I looked at Flutter's code and noticed that Flutter uses text span to create text in the text field (that is, all the text can only be changed), is this possible with Flutter's own text field widget?

Body:
how i can build a textField to change text direction line by line ( based on the first character )

For example, I want it to be displayed as below when typing 2 letters in different languages in the text field

// this line started with LTR characters, start at left
Hi Good morning

// this line started with RTL characters, start at right
                 سلام، صبح بخیر

Are you ok?
                    حالت خوبه؟

I looked at Flutter's code and noticed that Flutter uses text span to create text in the text field (that is, all the text can only be changed), is this possible with Flutter's own text field widget?


问:
Glob glob does not read file and nothing is working after I run code
I am a newbie in Python .

I`ve tried to run this code for image processing for multiple images but nothing seems to work.

No error comes out and the console mentioned that it has run file.

When I exclude glob and try to run for one file the system seems to work just fine.
Can anyone advise me on this.

I have try to reset spyder, reload anaconda and it seems like nothing change

The code are as follow.

```<code>import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
import math
import glob

path = 'C:/users/OneDrive/Bubble visualization/4mm/L7.5G122/*.bmp'

image_bac = cv2.imread('background_C001H001S0002000001.bmp')

x=0
for file in glob.glob(path):
    x=x+1
    print(x)
    print(file)
    image_bub = cv2.imread(file)

    # parameters you need to set
    kernelsize = 5#Needs to be a odd number
    threshold = 7#Threshold of binarization
    max_area = 100000#The maximum area of contour [pixel x pixel]
    min_area = 4#The minimum area of contour [pixel x pixel]

    # convert color image to gray scale
    img_bub = cv2.cvtColor(image_bub, cv2.COLOR_RGB2GRAY)
    img_bac = cv2.cvtColor(image_bac, cv2.COLOR_RGB2GRAY)
    # convert uint8 image to float32
    img_bub=img_bub.astype(np.float32)
    img_bac=img_bac.astype(np.float32)

    # apply background subtraction and replace <0 values by 0
    img_sub=img_bac-img_bub
    img_sub=np.where(img_sub<0,0,img_sub)
    # convert float32 array to uint8 image
    img_sub=img_sub.astype(np.uint8)

    cv2.imwrite('img_aftersub.png', img_sub)

    # apply median filter to denoise and binarize
    img_med = cv2.medianBlur(img_sub,kernelsize)
    ret,img_thresh = cv2.threshold(img_med,threshold,255,cv2.THRESH_BINARY)

    # obtain contour
    contours, hierarchy = cv2.findContours(img_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # save only valid contours and its area (in this case identified by size)
    saved_contour = []
    contour_area = []
    for cnt in contours:
        area = cv2.contourArea(cnt)
        if (area < max_area) & (area>min_area):
            saved_contour.append(cnt)
            contour_area.append(area)

    # write only valid contours
    img_cnt = cv2.drawContours(image_bub, saved_contour, -1, (0,255,0), 3)
    #saveimage
    cv2.imwrite('img_out.png', img_cnt)
    # show image
    cv2.imshow("output", img_cnt)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# convert list of areas into ndarray
    contour_area1 = np.array(contour_area)

    #convert contour area to area in mm
    area1 = contour_area1**0.0096
    #1mm = 0.0096 pixel

    diameter = np.sqrt((4.0*area1)/np.pi)

    # calulate the mean and std of area and print
    mean = np.average(diameter)
    std = np.std(diameter)
    print("the average d is: " + str(mean))
    print("the std of d is: " + str(std))
</code>```

I hope some one could point out my mistake in the coding.

Body:
I am a newbie in Python .

I`ve tried to run this code for image processing for multiple images but nothing seems to work.

No error comes out and the console mentioned that it has run file.

When I exclude glob and try to run for one file the system seems to work just fine.
Can anyone advise me on this.

I have try to reset spyder, reload anaconda and it seems like nothing change

The code are as follow.

import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
import math
import glob

path = 'C:/users/OneDrive/Bubble visualization/4mm/L7.5G122/*.bmp'

image_bac = cv2.imread('background_C001H001S0002000001.bmp')

x=0
for file in glob.glob(path):
    x=x+1
    print(x)
    print(file)
    image_bub = cv2.imread(file)

    # parameters you need to set
    kernelsize = 5#Needs to be a odd number
    threshold = 7#Threshold of binarization
    max_area = 100000#The maximum area of contour [pixel x pixel]
    min_area = 4#The minimum area of contour [pixel x pixel]

    # convert color image to gray scale
    img_bub = cv2.cvtColor(image_bub, cv2.COLOR_RGB2GRAY)
    img_bac = cv2.cvtColor(image_bac, cv2.COLOR_RGB2GRAY)
    # convert uint8 image to float32
    img_bub=img_bub.astype(np.float32)
    img_bac=img_bac.astype(np.float32)

    # apply background subtraction and replace <0 values by 0
    img_sub=img_bac-img_bub
    img_sub=np.where(img_sub<0,0,img_sub)
    # convert float32 array to uint8 image
    img_sub=img_sub.astype(np.uint8)

    cv2.imwrite('img_aftersub.png', img_sub)

    # apply median filter to denoise and binarize
    img_med = cv2.medianBlur(img_sub,kernelsize)
    ret,img_thresh = cv2.threshold(img_med,threshold,255,cv2.THRESH_BINARY)

    # obtain contour
    contours, hierarchy = cv2.findContours(img_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # save only valid contours and its area (in this case identified by size)
    saved_contour = []
    contour_area = []
    for cnt in contours:
        area = cv2.contourArea(cnt)
        if (area < max_area) & (area>min_area):
            saved_contour.append(cnt)
            contour_area.append(area)

    # write only valid contours
    img_cnt = cv2.drawContours(image_bub, saved_contour, -1, (0,255,0), 3)
    #saveimage
    cv2.imwrite('img_out.png', img_cnt)
    # show image
    cv2.imshow("output", img_cnt)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# convert list of areas into ndarray
    contour_area1 = np.array(contour_area)

    #convert contour area to area in mm
    area1 = contour_area1**0.0096
    #1mm = 0.0096 pixel

    diameter = np.sqrt((4.0*area1)/np.pi)

    # calulate the mean and std of area and print
    mean = np.average(diameter)
    std = np.std(diameter)
    print("the average d is: " + str(mean))
    print("the std of d is: " + str(std))

I hope some one could point out my mistake in the coding.