问:
Indexing and search functionality using Redis in a Spring Boot Application
I'm having trouble implementing search functionality using Redis for my app.
I simply using a Model and a Controller.

Model:

```<code>@RedisHash(value = "person")
public record Person(
    @Id String id,
    @Indexed String name)
    implements Serializable {}
</code>```

Controller

```<code>@RestController
public class MyController {

@Autowired
  private StatefulRediSearchConnection<String, String> searchConnection;

public MyController() {}

@GetMapping("/search")
  public SearchResults<String,String> search(@RequestParam(name="q")String query) {
    RediSearchCommands<String, String> commands = searchConnection.sync();
    SearchResults<String, String> results = commands.search("name", query);
    return results;
  }
</code>```

However, this unfortunately do not work. When calling the error I get the following error:

```<code>io.lettuce.core.RedisCommandExecutionException: Name: no such index
</code>```

When looking in the redis-stack browser I have two different types of data structures.

Hash, the data-object itself as fields (name in redis: person:"id")

Set, with one member, pointing at person:name:"name" (name in redis: person:"id":idx)

Set, with one member, pointing at "id" (name in redis: person:name:"name)

So, I can't use the search command searching for the name field since it seems like this one is not representing an actual index. Any ideas?

Body:
I'm having trouble implementing search functionality using Redis for my app.
I simply using a Model and a Controller.

Model:

@RedisHash(value = "person")
public record Person(
    @Id String id,
    @Indexed String name)
    implements Serializable {}

Controller

@RestController
public class MyController {

@Autowired
  private StatefulRediSearchConnection<String, String> searchConnection;

public MyController() {}

@GetMapping("/search")
  public SearchResults<String,String> search(@RequestParam(name="q")String query) {
    RediSearchCommands<String, String> commands = searchConnection.sync();
    SearchResults<String, String> results = commands.search("name", query);
    return results;
  }

However, this unfortunately do not work. When calling the error I get the following error:

io.lettuce.core.RedisCommandExecutionException: Name: no such index

When looking in the redis-stack browser I have two different types of data structures.

Hash, the data-object itself as fields (name in redis: person:"id")

Set, with one member, pointing at person:name:"name" (name in redis: person:"id":idx)

Set, with one member, pointing at "id" (name in redis: person:name:"name)

So, I can't use the search command searching for the name field since it seems like this one is not representing an actual index. Any ideas?


来源: stackexchange

问:
undefined method for nil:NilClass)
Getting this error, I am not sure why, any assistance on this would be appreciated.

```<code>[52af604a-131e-46a8-9d93-eefa7cf13a5a] ActionView::Template::Error (undefined method `description' for nil:NilClass):
[52af604a-131e-46a8-9d93-eefa7cf13a5a]     33:         </th>
[52af604a-131e-46a8-9d93-eefa7cf13a5a]     34:         <% @table_info.keys.each do |column_name|%>
[52af604a-131e-46a8-9d93-eefa7cf13a5a]     35:           <% column = table[column_name] %>
[52af604a-131e-46a8-9d93-eefa7cf13a5a]     36:           <th<%= raw ManageDevicesHelper.get_column_title(column)%><%= !column.rules.nil? && column.rules.required ? raw(' class="required"') : '' %>><%=column_name%></th>
[52af604a-131e-46a8-9d93-eefa7cf13a5a]     37:         <% end %>
[52af604a-131e-46a8-9d93-eefa7cf13a5a]     38:       </tr></thead>
[52af604a-131e-46a8-9d93-eefa7cf13a5a]     39:       <tbody>
[52af604a-131e-46a8-9d93-eefa7cf13a5a]
[52af604a-131e-46a8-9d93-eefa7cf13a5a] app/helpers/manage_devices_helper.rb:45:in `get_column_title'
[52af604a-131e-46a8-9d93-eefa7cf13a5a] app/views/manage_devices/index.html.erb:36
[52af604a-131e-46a8-9d93-eefa7cf13a5a] app/views/manage_devices/index.html.erb:34:in `each'
[52af604a-131e-46a8-9d93-eefa7cf13a5a] app/views/manage_devices/index.html.erb:34
[52af604a-131e-46a8-9d93-eefa7cf13a5a] app/views/manage_devices/index.html.erb:24
[52af604a-131e-46a8-9d93-eefa7cf13a5a] app/controllers/manage_devices_controller.rb:130:in `show'
</code>```

in manage_devices_helper.rb

```<code>def self.get_column_title(column)
    print "column >>>>>>>>> ...  #{column}"
    title = if !column.description.nil?
              column.description
            elsif !column.comment.nil?
              column.comment
            else
              nil
            end
    title.nil? ? '' : " title=\"#{title}\""
  end
</code>```

table[column_name] output is not nil too,

```<code> primary: N not_null: N unique: N auto_inc: N  > port
    primary: N not_null: Y unique: N auto_inc: N  > description
    primary: N not_null: N unique: N auto_inc: N  > sub_type
</code>```

ContentLicense: CC BY-SA 4.0

Title: undefined method for nil:NilClass)

Body:
Getting this error, I am not sure why, any assistance on this would be appreciated.

[52af604a-131e-46a8-9d93-eefa7cf13a5a] ActionView::Template::Error (undefined method `description' for nil:NilClass):
[52af604a-131e-46a8-9d93-eefa7cf13a5a]     33:
[52af604a-131e-46a8-9d93-eefa7cf13a5a]     34:         <% @table_info.keys.each do |column_name|%>
[52af604a-131e-46a8-9d93-eefa7cf13a5a]     35:           <% column = table[column_name] %>
[52af604a-131e-46a8-9d93-eefa7cf13a5a]     36:           <th<%= raw ManageDevicesHelper.get_column_title(column)%><%= !column.rules.nil? && column.rules.required ? raw(' class="required"') : '' %>><%=column_name%>
[52af604a-131e-46a8-9d93-eefa7cf13a5a]     37:         <% end %>
[52af604a-131e-46a8-9d93-eefa7cf13a5a]     38:

[52af604a-131e-46a8-9d93-eefa7cf13a5a]     39:

[52af604a-131e-46a8-9d93-eefa7cf13a5a]
[52af604a-131e-46a8-9d93-eefa7cf13a5a] app/helpers/manage_devices_helper.rb:45:in `get_column_title'
[52af604a-131e-46a8-9d93-eefa7cf13a5a] app/views/manage_devices/index.html.erb:36
[52af604a-131e-46a8-9d93-eefa7cf13a5a] app/views/manage_devices/index.html.erb:34:in `each'
[52af604a-131e-46a8-9d93-eefa7cf13a5a] app/views/manage_devices/index.html.erb:34
[52af604a-131e-46a8-9d93-eefa7cf13a5a] app/views/manage_devices/index.html.erb:24
[52af604a-131e-46a8-9d93-eefa7cf13a5a] app/controllers/manage_devices_controller.rb:130:in `show'

in manage_devices_helper.rb

def self.get_column_title(column)
    print "column >>>>>>>>> ...  #{column}"
    title = if !column.description.nil?
              column.description
            elsif !column.comment.nil?
              column.comment
            else
              nil
            end
    title.nil? ? '' : " title=\"#{title}\""
  end

table[column_name] output is not nil too,

 primary: N not_null: N unique: N auto_inc: N  > port
    primary: N not_null: Y unique: N auto_inc: N  > description
    primary: N not_null: N unique: N auto_inc: N  > sub_type


问:
My SearchView is unable to filter users in my chat application built with android studio when I make queries. It displays all app users regardless
My chat application has a fragment where all signed up users are displayed. I'm trying to add a search button that filters users that match a name or email that is typed in the text box in part or whole. However this isn't happening and all signed in users are displayed regardless. There are no run time errors though.

I'm not too sure what is wrong, so here is the code.

```<code>    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){

        inflater.inflate(R.menu.menu_main, menu);

        MenuItem item = menu.findItem(R.id.action_search);

        SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                if (!TextUtils.isEmpty(query.trim())){
                    searchUsers(query);
                }
                else {
                    getAllUsers();
                }
                return false;
            }

            @Override
            public boolean onQueryTextChange(String query) {

                if (!TextUtils.isEmpty(query.trim())){
                    searchUsers(query);
                }
                else {
                    getAllUsers();
                }
                return false;
            }
        });

        super.onCreateOptionsMenu(menu, inflater);
    }
</code>```
```<code>private void searchUsers(String query) {

    final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");

    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            usersList.clear();
            for (DataSnapshot dataSnapshot: snapshot.getChildren()){
                ModelUsers modelUsers = dataSnapshot.getValue(ModelUsers.class);

                if (!modelUsers.getUid().equals(firebaseUser.getUid())){

                    if ((modelUsers.getName().toLowerCase()).contains(query.toLowerCase()) ||
                            (modelUsers.getEmail().toLowerCase()).contains(query.toLowerCase()))
                    {
                        usersList.add(modelUsers);

                    } else {

                    }

                }

                adapterUsers = new AdapterUsers(getActivity(), usersList);

                adapterUsers.notifyDataSetChanged();

                recyclerView.setAdapter(adapterUsers);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });

}
</code>```
```<code></code>```

Body:
My chat application has a fragment where all signed up users are displayed. I'm trying to add a search button that filters users that match a name or email that is typed in the text box in part or whole. However this isn't happening and all signed in users are displayed regardless. There are no run time errors though.

I'm not too sure what is wrong, so here is the code.

    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){

        inflater.inflate(R.menu.menu_main, menu);

        MenuItem item = menu.findItem(R.id.action_search);

        SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                if (!TextUtils.isEmpty(query.trim())){
                    searchUsers(query);
                }
                else {
                    getAllUsers();
                }
                return false;
            }

            @Override
            public boolean onQueryTextChange(String query) {

                if (!TextUtils.isEmpty(query.trim())){
                    searchUsers(query);
                }
                else {
                    getAllUsers();
                }
                return false;
            }
        });

        super.onCreateOptionsMenu(menu, inflater);
    }

private void searchUsers(String query) {

    final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");

    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            usersList.clear();
            for (DataSnapshot dataSnapshot: snapshot.getChildren()){
                ModelUsers modelUsers = dataSnapshot.getValue(ModelUsers.class);

                if (!modelUsers.getUid().equals(firebaseUser.getUid())){

                    if ((modelUsers.getName().toLowerCase()).contains(query.toLowerCase()) ||
                            (modelUsers.getEmail().toLowerCase()).contains(query.toLowerCase()))
                    {
                        usersList.add(modelUsers);

                    } else {

                    }

                }

                adapterUsers = new AdapterUsers(getActivity(), usersList);

                adapterUsers.notifyDataSetChanged();

                recyclerView.setAdapter(adapterUsers);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });

}


问:
Where i can set defaultRecordSettings in Expo Camera?
I have a problem with recording flickers (it works on IPhone < 12) so I tried to find solutions but unsuccessfully(. All i could understand that there are some default recording settings and somehow u can change it. Please if u know smth or u had similar issue, describe it.

It shouldn't flick when i start and stop record video.

Code:

```<code>import React, { useState, useRef, useEffect } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  SafeAreaView,
  StyleSheet,
  Platform,
} from "react-native";
import { Camera, CameraType, FlashMode, VideoCodec, VideoQuality, VideoStabilization, WhiteBalance } from "expo-camera";
import FlipIcon from "../../assets/Svg-Icons/flip-camera.svg";
import CancelIcon from "../../assets/Svg-Icons/cancel-sign.svg";
import {
  useIsFocused,
  useNavigation,
} from "@react-navigation/native";
import RecordButton from "../common/RecordButton";
import { INavigation } from "../../types";
import ArrowRightIcon from "../../assets/Svg-Icons/arrow-right.svg";

interface TimerProps {
    showTimer: boolean;
    closeTimer: () => void;
    setActiveNav: (active: boolean) => void;
  }
  interface Timer{
    maxTime:number,
    value:number,
    timeout:boolean
  }
  export default function AddVideo({
    setActiveNav,
    showTimer,
    closeTimer,
  }: TimerProps) {
  const [hasCameraPermission, setHasCameraPermission] = useState<
    boolean | null
  >(null);
  const [hasMicrophonePermission, setHasMicrophonePermission] = useState<
    boolean | null
  >(null);
  const [cameraType, setCameraType] = useState(CameraType.back);
  const [isCameraReady, setIsCameraReady] = useState<boolean>(false);
  const [isVideoRecording, setIsVideoRecording] = useState<boolean>(false);
  const [videoSource, setVideoSource] = useState<string | null>(null);
  const [timer, setTimer] = useState<Timer>({
    maxTime:60,
    value:0,
    timeout:false,
  })
  let cameraRef = useRef<any>(null);
  const isFocused = useIsFocused();

  useEffect(() => {
    (async () => {
      const cameraPermision = await Camera.requestCameraPermissionsAsync();
      const microphonePermission =
        await Camera.requestMicrophonePermissionsAsync();
      setHasCameraPermission(cameraPermision.status === "granted");
      setHasMicrophonePermission(microphonePermission.status === "granted");
    })();
  }, []);

  const onCameraReady = () => {
    setIsCameraReady(true);
  };

//  NAVIGATION
  const navigation = useNavigation<INavigation>();
  const goBack = () => {
    stopVideoRecording();
    setVideoSource(null);
    navigation.goBack();
  };
  const uploadVideo = () => {

    navigation.navigate(
      //@ts-ignore
      "NewVideoReview",{ currentVideoUri: videoSource }
    );
    setVideoSource(null);
  };
  const recordVideo = async () => {
    if (cameraRef.current) {
      try {
        const videoRecordPromise = cameraRef.current.recordAsync({
          quality:VideoQuality["480p"],
        });
        if (videoRecordPromise) {
          setIsVideoRecording(true);
          setTimer({...timer,value:timer.maxTime, timeout:false});
          setActiveNav(false);
          const data = await videoRecordPromise;
          const source = data.uri;
          if (source) {
            setVideoSource(source);
          }
        }
      } catch (error) {
        console.warn(error);
      }
    }
  };
  const stopVideoRecording = () => {
    if (cameraRef.current) {
      setIsVideoRecording(false);
      setTimer({...timer, value:0})
      setActiveNav(true);
      cameraRef.current.stopRecording();
    }
  };
  useEffect(()=>{
    if (timer.timeout) {
      stopVideoRecording();
    }
  },[timer.timeout])

  const changeTimer = (time: number) => {
        if (isVideoRecording) {
          stopVideoRecording();
        }
        setTimer({...timer, maxTime:time})
        closeTimer();
      };

  if (hasCameraPermission === null && hasMicrophonePermission === null) {
    return <View />;
  }
  if (hasCameraPermission === null && hasMicrophonePermission === null) {
    return <Text style={styles.text}>No access to camera and mic</Text>;
  }
  return (
    <>
     {isFocused && (
        <Camera
        onMountError={(error) => {
                console.log("camera error", error);
              }}
          // ratio={'4:3'}
          style={styles.container}
          type={cameraType}
          ref={cameraRef}
          // whiteBalance={WhiteBalance.incandescent}
          onCameraReady={onCameraReady}
          zoom={0}
        >
          <SafeAreaView>
            <View>
              <TouchableOpacity
               style={{position:'absolute', left:23,top:10, display:isVideoRecording?'none':'flex' }}
                 onPress={() => {
                  setCameraType(
                    cameraType === CameraType.back
                      ? CameraType.front
                      : CameraType.back
                  );
                }}
              >
                <FlipIcon width={22} height={25} fill={"white"} />
              </TouchableOpacity>
              <TouchableOpacity style={{position:'absolute', right:23,top:10 }} onPress={goBack}>
                <CancelIcon width={22} height={22} fill={"white"} />
              </TouchableOpacity>
              </View>
          </SafeAreaView>
          <View
            style={{
              position: "absolute",
              left: 0,
              right: 0,
              bottom: 8,
              alignItems: "center",
            }}
          >
            {showTimer && (
              <View style={styles.timer}>
                <TouchableOpacity
                  onPress={() => changeTimer(180)}
                  style={
                    timer.maxTime === 180
                      ? styles.timeBoxPrimmary
                      : styles.timeBox
                  }
                >
                  <Text style={styles.timeText}>3m</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  onPress={() => changeTimer(60)}
                  style={
                    timer.maxTime === 60
                      ? styles.timeBoxPrimmary
                      : styles.timeBox
                  }
                >
                  <Text style={styles.timeText}>60</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  onPress={() => changeTimer(15)}
                  style={
                    timer.maxTime === 15
                      ? styles.timeBoxPrimmary
                      : styles.timeBox
                  }
                >
                  <Text style={styles.timeText}>15s</Text>
                </TouchableOpacity>
              </View>
            )}

            <View>
              <TouchableOpacity
                onPress={isVideoRecording ? stopVideoRecording : recordVideo}
              >
                <RecordButton
                  setTimerTimeout={(isEnded:boolean)=>setTimer({...timer, timeout:isEnded})}
                  timerValue={timer.value}
                  maxTime={timer.maxTime}
                  isRecording={isVideoRecording}
                  isVideoFocused={isFocused}
                />
              </TouchableOpacity>

              {videoSource && !isVideoRecording && (
                <TouchableOpacity
                  onPress={uploadVideo}
                  style={styles.nextBtn}
                >
                  <Text style={{ color: "#2589FF", fontWeight: "700" }}>
                    Next
                  </Text>
                  <ArrowRightIcon style={{ marginLeft: 4 }} fill={"#2589FF"} />
                </TouchableOpacity>
              )}
            </View>
          </View>
        </Camera>
      )}
    </>
  );
}
</code>```

Body:
I have a problem with recording flickers (it works on IPhone < 12) so I tried to find solutions but unsuccessfully(. All i could understand that there are some default recording settings and somehow u can change it. Please if u know smth or u had similar issue, describe it.

It shouldn't flick when i start and stop record video.

Code:

import React, { useState, useRef, useEffect } from "react";
import {
  View,
  Text,
  TouchableOpacity,
  SafeAreaView,
  StyleSheet,
  Platform,
} from "react-native";
import { Camera, CameraType, FlashMode, VideoCodec, VideoQuality, VideoStabilization, WhiteBalance } from "expo-camera";
import FlipIcon from "../../assets/Svg-Icons/flip-camera.svg";
import CancelIcon from "../../assets/Svg-Icons/cancel-sign.svg";
import {
  useIsFocused,
  useNavigation,
} from "@react-navigation/native";
import RecordButton from "../common/RecordButton";
import { INavigation } from "../../types";
import ArrowRightIcon from "../../assets/Svg-Icons/arrow-right.svg";

interface TimerProps {
    showTimer: boolean;
    closeTimer: () => void;
    setActiveNav: (active: boolean) => void;
  }
  interface Timer{
    maxTime:number,
    value:number,
    timeout:boolean
  }
  export default function AddVideo({
    setActiveNav,
    showTimer,
    closeTimer,
  }: TimerProps) {
  const [hasCameraPermission, setHasCameraPermission] = useState<
    boolean | null
  >(null);
  const [hasMicrophonePermission, setHasMicrophonePermission] = useState<
    boolean | null
  >(null);
  const [cameraType, setCameraType] = useState(CameraType.back);
  const [isCameraReady, setIsCameraReady] = useState<boolean>(false);
  const [isVideoRecording, setIsVideoRecording] = useState<boolean>(false);
  const [videoSource, setVideoSource] = useState<string | null>(null);
  const [timer, setTimer] = useState<Timer>({
    maxTime:60,
    value:0,
    timeout:false,
  })
  let cameraRef = useRef<any>(null);
  const isFocused = useIsFocused();

  useEffect(() => {
    (async () => {
      const cameraPermision = await Camera.requestCameraPermissionsAsync();
      const microphonePermission =
        await Camera.requestMicrophonePermissionsAsync();
      setHasCameraPermission(cameraPermision.status === "granted");
      setHasMicrophonePermission(microphonePermission.status === "granted");
    })();
  }, []);

  const onCameraReady = () => {
    setIsCameraReady(true);
  };

//  NAVIGATION
  const navigation = useNavigation<INavigation>();
  const goBack = () => {
    stopVideoRecording();
    setVideoSource(null);
    navigation.goBack();
  };
  const uploadVideo = () => {

    navigation.navigate(
      //@ts-ignore
      "NewVideoReview",{ currentVideoUri: videoSource }
    );
    setVideoSource(null);
  };
  const recordVideo = async () => {
    if (cameraRef.current) {
      try {
        const videoRecordPromise = cameraRef.current.recordAsync({
          quality:VideoQuality["480p"],
        });
        if (videoRecordPromise) {
          setIsVideoRecording(true);
          setTimer({...timer,value:timer.maxTime, timeout:false});
          setActiveNav(false);
          const data = await videoRecordPromise;
          const source = data.uri;
          if (source) {
            setVideoSource(source);
          }
        }
      } catch (error) {
        console.warn(error);
      }
    }
  };
  const stopVideoRecording = () => {
    if (cameraRef.current) {
      setIsVideoRecording(false);
      setTimer({...timer, value:0})
      setActiveNav(true);
      cameraRef.current.stopRecording();
    }
  };
  useEffect(()=>{
    if (timer.timeout) {
      stopVideoRecording();
    }
  },[timer.timeout])

  const changeTimer = (time: number) => {
        if (isVideoRecording) {
          stopVideoRecording();
        }
        setTimer({...timer, maxTime:time})
        closeTimer();
      };

  if (hasCameraPermission === null && hasMicrophonePermission === null) {
    return <View />;
  }
  if (hasCameraPermission === null && hasMicrophonePermission === null) {
    return <Text style={styles.text}>No access to camera and mic</Text>;
  }
  return (
    <>
     {isFocused && (
        <Camera
        onMountError={(error) => {
                console.log("camera error", error);
              }}
          // ratio={'4:3'}
          style={styles.container}
          type={cameraType}
          ref={cameraRef}
          // whiteBalance={WhiteBalance.incandescent}
          onCameraReady={onCameraReady}
          zoom={0}
        >
          <SafeAreaView>
            <View>
              <TouchableOpacity
               style={{position:'absolute', left:23,top:10, display:isVideoRecording?'none':'flex' }}
                 onPress={() => {
                  setCameraType(
                    cameraType === CameraType.back
                      ? CameraType.front
                      : CameraType.back
                  );
                }}
              >
                <FlipIcon width={22} height={25} fill={"white"} />
              </TouchableOpacity>
              <TouchableOpacity style={{position:'absolute', right:23,top:10 }} onPress={goBack}>
                <CancelIcon width={22} height={22} fill={"white"} />
              </TouchableOpacity>
              </View>
          </SafeAreaView>
          <View
            style={{
              position: "absolute",
              left: 0,
              right: 0,
              bottom: 8,
              alignItems: "center",
            }}
          >
            {showTimer && (
              <View style={styles.timer}>
                <TouchableOpacity
                  onPress={() => changeTimer(180)}
                  style={
                    timer.maxTime === 180
                      ? styles.timeBoxPrimmary
                      : styles.timeBox
                  }
                >
                  <Text style={styles.timeText}>3m</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  onPress={() => changeTimer(60)}
                  style={
                    timer.maxTime === 60
                      ? styles.timeBoxPrimmary
                      : styles.timeBox
                  }
                >
                  <Text style={styles.timeText}>60</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  onPress={() => changeTimer(15)}
                  style={
                    timer.maxTime === 15
                      ? styles.timeBoxPrimmary
                      : styles.timeBox
                  }
                >
                  <Text style={styles.timeText}>15s</Text>
                </TouchableOpacity>
              </View>
            )}

            <View>
              <TouchableOpacity
                onPress={isVideoRecording ? stopVideoRecording : recordVideo}
              >
                <RecordButton
                  setTimerTimeout={(isEnded:boolean)=>setTimer({...timer, timeout:isEnded})}
                  timerValue={timer.value}
                  maxTime={timer.maxTime}
                  isRecording={isVideoRecording}
                  isVideoFocused={isFocused}
                />
              </TouchableOpacity>

              {videoSource && !isVideoRecording && (
                <TouchableOpacity
                  onPress={uploadVideo}
                  style={styles.nextBtn}
                >
                  <Text style={{ color: "#2589FF", fontWeight: "700" }}>
                    Next
                  </Text>
                  <ArrowRightIcon style={{ marginLeft: 4 }} fill={"#2589FF"} />
                </TouchableOpacity>
              )}
            </View>
          </View>
        </Camera>
      )}
    </>
  );
}


问:
Reading from cosmos and loading in DWH Synapse taking 15-20 mins even it is 0 rows
I have been loading the data from cosmos DB to DWH Synapse using Synapse pipelines.
I am able to load the data but it takes more time.
For e.g. we are loading the data incrementally , so if there are no updates then it would be 0 rows read from cosmos. But then too it takes around 20 mins to load.
When I go to monitor and go in execution in detail. I see 5s or 2 s in sink or in transformations. even if I calculate all the times it took , it is only 1 min max. Can anybody guide me how can I check where exactly I can check the timing and where it is the issue when it come to timing of execution.
If it is issue reading from cosmos , then can I improve that ?

Because even though I increase DWUs or cores to max, even for 0 records it takes 20 mins only.


问:
ReadTimeout value used in the FailoverOptions for redis.NewFailoverClient to connect to a redis sentinel doesn't seem to have an effect. Why?
Expected Behavior

If the read operation is taking more time than the ReadTimeout value, it should return an error.

Current Behavior

ReadTimeout exceeds, but no error is returned.

Steps to Reproduce

Connect to a redis sentinel with a ReadTimeout value defined. When the value is smaller, it's easier to reproduce. In the example, I've used 30 microseconds

Do a read operation which takes more than the ReadTimeout and observe the result

Code to reproduce:

```<code>    package main

    import (
    "fmt"
    "github.com/go-redis/redis"
    "time"
    )

    func main() {
    master := "mymaster"
    SentinelServers := []string{"localhost:26379"}
    Password := ""
    PoolSize := 9
    DB := 11
    client := redis.NewFailoverClient(&redis.FailoverOptions{
    MasterName: master,
    SentinelAddrs: SentinelServers,
    Password: Password,
    PoolSize: PoolSize,
    DB: DB,
    ReadTimeout: time.Duration(30) * time.Microsecond,
    })

    res, err := client.Ping().Result()
    if err != nil {
        fmt.Printf("Ping error %s\n", err)
    }
    fmt.Println(res)

    key := "key2"
    value := "val2"
    err = client.Set(key, value, time.Duration(30)*time.Second).Err()
    if err != nil {
        fmt.Printf("Writing error %s\n", err)
    }

    start := time.Now()
    val, err := client.Get(key).Result()
    if err != nil {
        fmt.Printf("Reading error %s\n", err)
        return
    }
    elapsed := time.Since(start)
    fmt.Printf("Cache read in %s\n", elapsed)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(val)
    }

</code>```

I have raised an issue on Github as well.

Body:
Expected Behavior

If the read operation is taking more time than the ReadTimeout value, it should return an error.

Current Behavior

ReadTimeout exceeds, but no error is returned.

Steps to Reproduce

Connect to a redis sentinel with a ReadTimeout value defined. When the value is smaller, it's easier to reproduce. In the example, I've used 30 microseconds

Do a read operation which takes more than the ReadTimeout and observe the result

Code to reproduce:

    package main

    import (
    "fmt"
    "github.com/go-redis/redis"
    "time"
    )

    func main() {
    master := "mymaster"
    SentinelServers := []string{"localhost:26379"}
    Password := ""
    PoolSize := 9
    DB := 11
    client := redis.NewFailoverClient(&redis.FailoverOptions{
    MasterName: master,
    SentinelAddrs: SentinelServers,
    Password: Password,
    PoolSize: PoolSize,
    DB: DB,
    ReadTimeout: time.Duration(30) * time.Microsecond,
    })

    res, err := client.Ping().Result()
    if err != nil {
        fmt.Printf("Ping error %s\n", err)
    }
    fmt.Println(res)

    key := "key2"
    value := "val2"
    err = client.Set(key, value, time.Duration(30)*time.Second).Err()
    if err != nil {
        fmt.Printf("Writing error %s\n", err)
    }

    start := time.Now()
    val, err := client.Get(key).Result()
    if err != nil {
        fmt.Printf("Reading error %s\n", err)
        return
    }
    elapsed := time.Since(start)
    fmt.Printf("Cache read in %s\n", elapsed)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(val)
    }

I have raised an issue on Github as well.


问:
How would I determine if a device is running an older version of firmware?
I'm attempting to use reflection in order to run different APIs on my app, but if the device firmware is too old, those APIs will not exist. Therefore, my goal is to try and check against the firmware on the device, in a way such that I can determine if it's past a certain firmware update. I believe Build.FINGERPRINT provides the firmware value I'm looking for, but I'm unsure how to compare it to another and determine if it's newer or not. Any suggestions are welcome, thank you!</p>


问:
i can't wrap in flutter It was wrap before, I don't know what it looked like
I can't wrap in flutter It was wrap before, I don't know what it looked like

It's manual without rap is difficult and time consuming


问:
Extracting site/location name from a site description column
I have 300,000+ rows of waterquality samples, that I am trying to extract waterbody names from for a waterbody column.

```<code>wbod_data<- data.frame(smpl_ID = c(1, 2, 3, 4, 5),
                         site_loc = c("Nile River at bridge", "MC-M1", "Red ROBIN CREEK 30 M D_S OF STP", "PT068 SCUTTLE LK #2", "FORDING R BELOW HARE CREEK"),
                         waterbody = c(NA, NA, NA, NA, NA))
</code>```

Many of the samples identify the related waterbody as part of a site description field as seen in site_loc. There is a high degree of variability in formatting of the waterbody names, with different naming conventions (River or R), different orders (Station_ID before waterbody name), different object lengths (Red Robin Creek versus Nile River) and multiple waterbodies referenced (FORDING R BELOW HARE CREEK). Some samples have no relevant information such as MC-M1.

For the needs of the project, not every row will have waterbody data, and it is fine if some available data is missed but I am trying to figure out a way to extract as much usable watershed data as possible. My approach so far has used Str_extract to extract the keywords as well as preceding word.

Given a keyword list as follows,

```<code>site_list <- wbod_data$site_loc
wtrbdy <- c("River", "CREEK", "LK", " R ")
keypone <- paste0("([^\\s]+\\s+){1}", keywords)
keypone_list <- paste(keypone, collapse = " | ")
print(wbod_data$waterbody <- str_extract(site_list, keypone_list))`site_list <- wbod_data$site_loc
wtrbdy <- c("River", "CREEK", "LK", " R ")
keypone <- paste0("([^\\s]+\\s+){1}", keywords)
keypone_list <- paste(keypone, collapse = " | ")
print(wbod_data$waterbody <- str_extract(site_list, keypone_list))
</code>```

This results in:
"Nile River "   NA              " ROBIN CREEK " " SCUTTLE LK "  NA

There are a few issues with this. One is that obviously I miss instances of 3 word names, such as RED ROBIN CREEK. Another is whatever is happening with row 5. I'm not sure if it is how I called for R as a vector, or if it has to do with there being more than 1 vector instance in the string.

Any guidance on how to properly call for 1 letter strings such as R, as well as potentially extract instances of 3 word strings would be much appreciated.

Body:
I have 300,000+ rows of waterquality samples, that I am trying to extract waterbody names from for a waterbody column.

wbod_data<- data.frame(smpl_ID = c(1, 2, 3, 4, 5),
                         site_loc = c("Nile River at bridge", "MC-M1", "Red ROBIN CREEK 30 M D_S OF STP", "PT068 SCUTTLE LK #2", "FORDING R BELOW HARE CREEK"),
                         waterbody = c(NA, NA, NA, NA, NA))

Many of the samples identify the related waterbody as part of a site description field as seen in site_loc. There is a high degree of variability in formatting of the waterbody names, with different naming conventions (River or R), different orders (Station_ID before waterbody name), different object lengths (Red Robin Creek versus Nile River) and multiple waterbodies referenced (FORDING R BELOW HARE CREEK). Some samples have no relevant information such as MC-M1.

For the needs of the project, not every row will have waterbody data, and it is fine if some available data is missed but I am trying to figure out a way to extract as much usable watershed data as possible. My approach so far has used Str_extract to extract the keywords as well as preceding word.

Given a keyword list as follows,

site_list <- wbod_data$site_loc
wtrbdy <- c("River", "CREEK", "LK", " R ")
keypone <- paste0("([^\\s]+\\s+){1}", keywords)
keypone_list <- paste(keypone, collapse = " | ")
print(wbod_data$waterbody <- str_extract(site_list, keypone_list))`site_list <- wbod_data$site_loc
wtrbdy <- c("River", "CREEK", "LK", " R ")
keypone <- paste0("([^\\s]+\\s+){1}", keywords)
keypone_list <- paste(keypone, collapse = " | ")
print(wbod_data$waterbody <- str_extract(site_list, keypone_list))

This results in:
"Nile River "   NA              " ROBIN CREEK " " SCUTTLE LK "  NA

There are a few issues with this. One is that obviously I miss instances of 3 word names, such as RED ROBIN CREEK. Another is whatever is happening with row 5. I'm not sure if it is how I called for R as a vector, or if it has to do with there being more than 1 vector instance in the string.

Any guidance on how to properly call for 1 letter strings such as R, as well as potentially extract instances of 3 word strings would be much appreciated.


问:
How to run jenkins pipeline of jenkins multibranch pipeline
I have multibranch pipeline, and I need to run a regular pipeline.

I try:

build job: 'secondPipeline', parameters: [[$class: 'StringParameterValue', name: 'BRANCH', value: "${BRANCH}"]], wait: false

But it doesn't work


问:
How to stop PowerShell from treating ImageMagick program output as errors
I have a small powershell script that does some setup and then call ImageMagick to make a montage and the resize the result. Now, all of this works perfectly fine, but since it is working with somewhat large images, I like to monitor the output by specifying the -monitor flag for the ImageMagick command line.
Now, this also works as far as generating the correct result is concerned, but PowerShell treats the output as an error, thus showing the text in read, and adding the error information header.

Is there a way of getting PowerShell to just display this program output as regular text?

I've omitted the rest of my script here, since this happen even if I run this single line in a PowerShell window:

```<code>mogrify -resize "7680x4320!" -monitor montage*.png
</code>```

which outputs the following in red text

```<code>mogrify : load image[montage.png]: 0 of 4560, 00% complete
At line:1 char:1
+ mogrify -resize "7680x4320!" -monitor montage*.png
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (load image[mont...0, 00% complete:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

load image[montage.png]: 50 of 4560, 01% complete
load image[montage.png]: 100 of 4560, 02% complete
load image[montage.png]: 150 of 4560, 03% complete
load image[montage.png]: 200 of 4560, 04% complete
load image[montage.png]: 250 of 4560, 05% complete
load image[montage.png]: 300 of 4560, 06% complete
.... (more lines like this)
</code>```

Is there a way to tell PowerShell that "Hey, these lines are just expected program output, not errors"?

Body:
I have a small powershell script that does some setup and then call ImageMagick to make a montage and the resize the result. Now, all of this works perfectly fine, but since it is working with somewhat large images, I like to monitor the output by specifying the -monitor flag for the ImageMagick command line.
Now, this also works as far as generating the correct result is concerned, but PowerShell treats the output as an error, thus showing the text in read, and adding the error information header.

Is there a way of getting PowerShell to just display this program output as regular text?

I've omitted the rest of my script here, since this happen even if I run this single line in a PowerShell window:

mogrify -resize "7680x4320!" -monitor montage*.png

which outputs the following in red text

mogrify : load image[montage.png]: 0 of 4560, 00% complete
At line:1 char:1
+ mogrify -resize "7680x4320!" -monitor montage*.png
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (load image[mont...0, 00% complete:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

load image[montage.png]: 50 of 4560, 01% complete
load image[montage.png]: 100 of 4560, 02% complete
load image[montage.png]: 150 of 4560, 03% complete
load image[montage.png]: 200 of 4560, 04% complete
load image[montage.png]: 250 of 4560, 05% complete
load image[montage.png]: 300 of 4560, 06% complete
.... (more lines like this)

Is there a way to tell PowerShell that "Hey, these lines are just expected program output, not errors"?


问:
Invalid text representation: 7 ERROR: invalid input syntax for type uuid
I am running a php symfony project on Windows.

When I run tests with php bin/phpunit --filter{test_name}
I received the following error,

Doctrine\DBAL\Exception\DriverException: An exception occurred while executing 'INSERT INTO personal_hub (unrad_count, updated_at, id) VALUES (?, ?, ?)' with params [0, "2020-01-01 00:00:01", "919d7417-3bc6-4fcf-9b4b-5886db3396a3\r"]:

SQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for type UUID: "919d7417-"bc6-4fcf-9b4b-5886db3396a3
CONTEXT:  unnamed portal parameter $3 = '...'

I run the same test on a Linux computer it is fine, but on Windows I receive this error.

I tried cleaning cache


问:
How to solve "Can't import the named export 'CommonModule' from non EcmaScript module (only default export is available)"
I'm trying to use ng2-pdf-viewer package.

I have added this module to app.module.ts as like that:

```<code>import { PdfViewerModule } from 'ng2-pdf-viewer';

imports: [
    PdfViewerModule,
]
</code>```

But I got these types of errors:

```<code>Error: ./node_modules/ng2-pdf-viewer/fesm2015/ng2-pdf-viewer.mjs 194:29-49
Can't import the named export 'VerbosityLevel' from non EcmaScript module (only default export is available)

Error: ./node_modules/ng2-pdf-viewer/fesm2015/ng2-pdf-viewer.mjs 791:12-21
Can't import the named export 'ViewChild' from non EcmaScript module (only default export is available)

Error: ./node_modules/ng2-pdf-viewer/fesm2015/ng2-pdf-viewer.mjs 690:39-51
Can't import the named export 'debounceTime' from non EcmaScript module (only default export is available)
</code>```

NodeJs: v16.18.1

Npm: v8.19.2

Angular Cli: 11.2.13

OS: linux x64(Ubuntu)

I have tried these:

Removed node_modules and npm install

Removed package-lock.json and npm install

Cleared npm cache by using npm cache clean

Tried to import the module to app.module.ts as import * PdfViewerModule from 'ng2-pdf-viewer';

Tried this solution: https://stackoverflow.com/a/69343125/284199

I've also tried [ngx-extended-pdf-viewer] package as alternative.
But nothing changes.

What is wrong with this?

Thanks

Body:
I'm trying to use ng2-pdf-viewer package.

I have added this module to app.module.ts as like that:

import { PdfViewerModule } from 'ng2-pdf-viewer';

imports: [
    PdfViewerModule,
]

But I got these types of errors:

Error: ./node_modules/ng2-pdf-viewer/fesm2015/ng2-pdf-viewer.mjs 194:29-49
Can't import the named export 'VerbosityLevel' from non EcmaScript module (only default export is available)

Error: ./node_modules/ng2-pdf-viewer/fesm2015/ng2-pdf-viewer.mjs 791:12-21
Can't import the named export 'ViewChild' from non EcmaScript module (only default export is available)

Error: ./node_modules/ng2-pdf-viewer/fesm2015/ng2-pdf-viewer.mjs 690:39-51
Can't import the named export 'debounceTime' from non EcmaScript module (only default export is available)

NodeJs: v16.18.1

Npm: v8.19.2

Angular Cli: 11.2.13

OS: linux x64(Ubuntu)

I have tried these:

Removed node_modules and npm install

Removed package-lock.json and npm install

Cleared npm cache by using npm cache clean

Tried to import the module to app.module.ts as import * PdfViewerModule from 'ng2-pdf-viewer';

Tried this solution: https://stackoverflow.com/a/69343125/284199

I've also tried [ngx-extended-pdf-viewer] package as alternative.
But nothing changes.

What is wrong with this?

Thanks


问:
Command handler 'Call Hierarchy' has exceeded allotted timeout and was auto canceled
I'm working with Visual Studio 2022 on a Docker application in C# and when I try to get the call hierarchy first I get in an endless loop, and after having pressed the "Cancel" button I get the error message, mentioned in the title.

I already re-built my entire solution, I restarted Visual Studio, I even restarted my entire computer, but the problem remains.

I am a regular user of the "Call Hierarchy" feature and it worked this morning, but apparently something is blocking this.

I already know that rebuilding the application, restarting Visual Studio and starting my entire computer does not solve the problem.

Does anybody have another idea what I can do in order to solve this issue?

For your information, I'm working with Microsoft Visual Studio Enterprise 2002 (64-bit) - Current Version 17.4.1.

Edit: I tried another debugging feature, like "Find all references", this is working fine.


问:
How to get symfony messenger Messages before handler consumes them?
I wonder how to get messages which are waiting in my Failed queue from a controller, before the handler consume them.
I don't persist them with doctrine, I put them in a rabbitmq that I can see them from the rabbit admin interface.</p>


问:
Do DataGridViewColumnCollections have an analogue for the ValueMember/DisplayMember distinction that comboboxes have?
I have a DataGridView. In one column, I show my users FooRealName and that is what I want them to see. In my code, I almost always want to manipulate FooID instead of FooRealName. If this were a combobox, I'd exploit the ValueMember/DisplayMember distinction that they have. Do DataGridViewColumnCollections have anything analogous? Or am I forced to go down the messy path of defining an extra FooID column and keeping it invisible?


问:
Docker: ERROR [internal] load metadata for docker.io/majksa/php:8.0-debug
When I run "Docker compose up -d" everything go fine, but then it write "ERROR [internal] load metadata for docker.io/majksa/php:8.0-debug".
Error here

I tried google it, but I couldn't finde anything that halped. Reinstalling didn't work.


问:
subclassing pythons dictionary using __setitem__
I'm subclassing dict this way:

```<code>class StreamIdMap(dict):
    def __init__(self, publisher: str = None, source: str = None, stream: str = None, target: str = None, value=None):
        super(StreamIdMap, self).__init__(
            [((publisher, source, stream, target), value)] if value else [])

    def add(self, publisher, source, stream, target, value=None):
        print(value)
        #self.__setitem__((publisher, source, stream, target), value)
        super(StreamIdMap, self).__setitem__((publisher, source, stream, target), value)

    ### BELOW IS IRRELEVANT TO THE QUESTION,           ###
    ### (but helps to understand the testing examples) ###

    @staticmethod
    def _condition(publisher: str = None, source: str = None, stream: str = None, target: str = None, default: bool = False):
        def condition(_): return default
        if publisher is not None:
            condition = condition and (lambda x: x[0] == publisher)
        if source is not None:
            condition = condition and (lambda x: x[1] == source)
        if stream is not None:
            condition = condition and (lambda x: x[2] == stream)
        if target is not None:
            condition = condition and (lambda x: x[3] == target)
        return condition

    def erase(self, publisher: str = None, source: str = None, stream: str = None, target: str = None):
        condition = StreamIdMap._condition(
            publisher=publisher, source=source, stream=stream, target=target)
        erased = False
        for k in self:
            if condition(k):
                self[k] = None
                erased = True
        return erased

    def getAll(self, publisher: str = None, source: str = None, stream: str = None, target: str = None):
        condition = StreamIdMap._condition(
            publisher=publisher, source=source, stream=stream, target=target)
        return {k: self[k] for k in self if condition(k)}

    def isFilled(self, publisher: str = None, source: str = None, stream: str = None, target: str = None):
        condition = StreamIdMap._condition(
            publisher=publisher, source=source, stream=stream, target=target)
        matches = [self[k] is not None for k in self if condition(k)]
        return len(matches) > 0 and all(matches)

    def getAllAsList(self, publisher: str = None, source: str = None, stream: str = None, target: str = None):
        matches = self.getAll(publisher=publisher, source=source, stream=stream, target=target)
        return [(k, v) for k, v in matches.items()]
</code>```

so (publisher, source, stream, target) is supposed to be the key.

Problem is when I test it out, I get None's for values I tried to set using the .add method:

```<code>>>> x = StreamIdMap('a', 'b', 'c', 'd', 1)
>>> x.add('a', 'b', 'c', 'e', 2)
2
>>> x.add('a', 'z', 'c', 'e', 3)
3
>>> x.isFilled('a', 'z', 'c', 'e')
True
>>> x.isFilled('a', 'b', 'c', 'd')
True
>>> x.isFilled('a', 'b', 'c', 'z')
False
>>> x.erase('a', 'b', 'c', 'z')
False
>>> x.isFilled('a', 'z', 'c', 'e')
True
>>> x.erase('a', 'z', 'c', 'e')
True
>>> x.isFilled('a', 'z', 'c', 'e')
False
>>> x.getAll('a', 'b', 'c', 'd')
{('a', 'b', 'c', 'd'): 1}
>>> x.getAll('a', 'b', 'c')
{('a', 'b', 'c', 'd'): 1, ('a', 'b', 'c', 'e'): None, ('a', 'z', 'c', 'e'): None}
>>> x.getAll('a')
{('a', 'b', 'c', 'd'): 1, ('a', 'b', 'c', 'e'): None, ('a', 'z', 'c', 'e'): None}
>>> x.getAllAsList('a')
[(('a', 'b', 'c', 'd'), 1), (('a', 'b', 'c', 'e'), None), (('a', 'z', 'c', 'e'), None)]
>>> x[('a', 'b', 'c', 'd')]
1
>>> x[('a', 'b', 'c', 'e')]
>>>
</code>```

(there's also some kinda glitch in the getAll method, but don't worry about it). I'm concerned that this line isn't right:

```<code>#self.__setitem__((publisher, source, stream, target), value)
super(StreamIdMap, self).__setitem__((publisher, source, stream, target), value)
</code>```

I thought I could just do self. but I saw other answers with the super self, but both resulted in values being None so I must be missing something else that I can't find.

Body:
I'm subclassing dict this way:

class StreamIdMap(dict):
    def __init__(self, publisher: str = None, source: str = None, stream: str = None, target: str = None, value=None):
        super(StreamIdMap, self).__init__(
            [((publisher, source, stream, target), value)] if value else [])

    def add(self, publisher, source, stream, target, value=None):
        print(value)
        #self.__setitem__((publisher, source, stream, target), value)
        super(StreamIdMap, self).__setitem__((publisher, source, stream, target), value)

    ### BELOW IS IRRELEVANT TO THE QUESTION,           ###
    ### (but helps to understand the testing examples) ###

    @staticmethod
    def _condition(publisher: str = None, source: str = None, stream: str = None, target: str = None, default: bool = False):
        def condition(_): return default
        if publisher is not None:
            condition = condition and (lambda x: x[0] == publisher)
        if source is not None:
            condition = condition and (lambda x: x[1] == source)
        if stream is not None:
            condition = condition and (lambda x: x[2] == stream)
        if target is not None:
            condition = condition and (lambda x: x[3] == target)
        return condition

    def erase(self, publisher: str = None, source: str = None, stream: str = None, target: str = None):
        condition = StreamIdMap._condition(
            publisher=publisher, source=source, stream=stream, target=target)
        erased = False
        for k in self:
            if condition(k):
                self[k] = None
                erased = True
        return erased

    def getAll(self, publisher: str = None, source: str = None, stream: str = None, target: str = None):
        condition = StreamIdMap._condition(
            publisher=publisher, source=source, stream=stream, target=target)
        return {k: self[k] for k in self if condition(k)}

    def isFilled(self, publisher: str = None, source: str = None, stream: str = None, target: str = None):
        condition = StreamIdMap._condition(
            publisher=publisher, source=source, stream=stream, target=target)
        matches = [self[k] is not None for k in self if condition(k)]
        return len(matches) > 0 and all(matches)

    def getAllAsList(self, publisher: str = None, source: str = None, stream: str = None, target: str = None):
        matches = self.getAll(publisher=publisher, source=source, stream=stream, target=target)
        return [(k, v) for k, v in matches.items()]

so (publisher, source, stream, target) is supposed to be the key.

Problem is when I test it out, I get None's for values I tried to set using the .add method:

>>> x = StreamIdMap('a', 'b', 'c', 'd', 1)
>>> x.add('a', 'b', 'c', 'e', 2)
2
>>> x.add('a', 'z', 'c', 'e', 3)
3
>>> x.isFilled('a', 'z', 'c', 'e')
True
>>> x.isFilled('a', 'b', 'c', 'd')
True
>>> x.isFilled('a', 'b', 'c', 'z')
False
>>> x.erase('a', 'b', 'c', 'z')
False
>>> x.isFilled('a', 'z', 'c', 'e')
True
>>> x.erase('a', 'z', 'c', 'e')
True
>>> x.isFilled('a', 'z', 'c', 'e')
False
>>> x.getAll('a', 'b', 'c', 'd')
{('a', 'b', 'c', 'd'): 1}
>>> x.getAll('a', 'b', 'c')
{('a', 'b', 'c', 'd'): 1, ('a', 'b', 'c', 'e'): None, ('a', 'z', 'c', 'e'): None}
>>> x.getAll('a')
{('a', 'b', 'c', 'd'): 1, ('a', 'b', 'c', 'e'): None, ('a', 'z', 'c', 'e'): None}
>>> x.getAllAsList('a')
[(('a', 'b', 'c', 'd'), 1), (('a', 'b', 'c', 'e'), None), (('a', 'z', 'c', 'e'), None)]
>>> x[('a', 'b', 'c', 'd')]
1
>>> x[('a', 'b', 'c', 'e')]
>>>

(there's also some kinda glitch in the getAll method, but don't worry about it). I'm concerned that this line isn't right:

#self.__setitem__((publisher, source, stream, target), value)
super(StreamIdMap, self).__setitem__((publisher, source, stream, target), value)

I thought I could just do self. but I saw other answers with the super self, but both resulted in values being None so I must be missing something else that I can't find.


问:
Blazor: access the user token from iOS
I'm creating application with Blazor in NET6. To call the API via an Azure API Management, I have to pass a token in the request adding

```<code>request.Headers.Authorization =
    new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
</code>```

In this request, I have to pass the token that comes from an Identity Server. So, first, the user has to authenticate to the identity server and then receives the JWT token.

The configuration is

```<code>builder.Services.AddOidcAuthentication(options =>
{
    builder.Configuration.Bind("oidc", options.ProviderOptions);
    options.UserOptions.RoleClaim = "role";
})
.AddAccountClaimsPrincipalFactory<MultipleRoleClaimsPrincipalFactory<RemoteUserAccount>>();

builder.Services.AddAuthorizationCore();
</code>```

Also, to apply the security, I add in the Program.cs this lines

```<code>app.Use((context, next) =>
{
    context.Response.GetTypedHeaders().CacheControl =
        new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
        {
            MustRevalidate = true,
            NoCache = true,
            NoStore = true,
        };

    string oidcAuthority = builder.Configuration.GetValue(typeof(string), "oidc:Authority").ToString();
    string mainUrl = "https://test.mywebsite.com/";
#if DEBUG
    mainUrl = "https://localhost:7040";
#endif

    context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
    context.Response.Headers.Add("Content-Security-Policy",
        $"default-src 'self' {mainUrl} {oidcAuthority} " +
            "https://code.cdn.mozilla.net " +
#if DEBUG
            "https://dc.services.visualstudio.com " +
#endif
            "https://api.myapi.com " +
            "'unsafe-inline' 'unsafe-eval'; " +
        $"script-src 'self' {mainUrl} 'unsafe-inline' 'unsafe-eval'; " +
        $"connect-src 'self' {oidcAuthority} https://code.cdn.mozilla.net https://api.myapi.com;" +
        $"img-src 'self' {mainUrl} data:; " +
        $"style-src 'unsafe-inline' {mainUrl} " +
            "https://code.cdn.mozilla.net " +
            ";" +
        "base-uri 'self'; " +
        "form-action 'self'; " +
        "frame-ancestors 'self';");
    context.Response.Headers.Add("Referrer-Policy", "same-origin");
    context.Response.Headers.Add("Permissions-Policy", "geolocation=(), microphone=()");
    context.Response.Headers.Add("X-XSS-Protection", "1; mode=block");
    context.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
    context.Response.Headers.Add("SameSite", "Strict");

    return next.Invoke();
});
</code>```

So, after that I can read the JWT token with this code:

```<code>IAccessTokenProvider _accessToken;
private async Task<AccessToken> RequestUserToken()
{
    try
    {
        var tokenResult = await _accessToken.RequestAccessToken();
        tokenResult.TryGetToken(out var token);

        Console.WriteLine(token);

        return token;
    }
    catch (AccessTokenNotAvailableException aex)
    {
        throw new ApplicationException($"Exception {aex}");
    }
    catch (Exception ex)
    {
        throw new ApplicationException(
            $"AccessTokenNotAvailable Exception Exception {ex}");
    }
}
</code>```

The application is working on Windows for any browser. On iOS and macOS I can read the token if I use Safari. It is working if I use Microsoft Edge and Chrome.

Do you have any idea how can I fix it?

Title: Blazor: access the user token from iOS

Body:
I'm creating application with Blazor in NET6. To call the API via an Azure API Management, I have to pass a token in the request adding

request.Headers.Authorization =
    new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

In this request, I have to pass the token that comes from an Identity Server. So, first, the user has to authenticate to the identity server and then receives the JWT token.

The configuration is

builder.Services.AddOidcAuthentication(options =>
{
    builder.Configuration.Bind("oidc", options.ProviderOptions);
    options.UserOptions.RoleClaim = "role";
})
.AddAccountClaimsPrincipalFactory<MultipleRoleClaimsPrincipalFactory<RemoteUserAccount>>();

builder.Services.AddAuthorizationCore();

Also, to apply the security, I add in the Program.cs this lines

app.Use((context, next) =>
{
    context.Response.GetTypedHeaders().CacheControl =
        new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
        {
            MustRevalidate = true,
            NoCache = true,
            NoStore = true,
        };

    string oidcAuthority = builder.Configuration.GetValue(typeof(string), "oidc:Authority").ToString();
    string mainUrl = "https://test.mywebsite.com/";
#if DEBUG
    mainUrl = "https://localhost:7040";
#endif

    context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
    context.Response.Headers.Add("Content-Security-Policy",
        $"default-src 'self' {mainUrl} {oidcAuthority} " +
            "https://code.cdn.mozilla.net " +
#if DEBUG
            "https://dc.services.visualstudio.com " +
#endif
            "https://api.myapi.com " +
            "'unsafe-inline' 'unsafe-eval'; " +
        $"script-src 'self' {mainUrl} 'unsafe-inline' 'unsafe-eval'; " +
        $"connect-src 'self' {oidcAuthority} https://code.cdn.mozilla.net https://api.myapi.com;" +
        $"img-src 'self' {mainUrl} data:; " +
        $"style-src 'unsafe-inline' {mainUrl} " +
            "https://code.cdn.mozilla.net " +
            ";" +
        "base-uri 'self'; " +
        "form-action 'self'; " +
        "frame-ancestors 'self';");
    context.Response.Headers.Add("Referrer-Policy", "same-origin");
    context.Response.Headers.Add("Permissions-Policy", "geolocation=(), microphone=()");
    context.Response.Headers.Add("X-XSS-Protection", "1; mode=block");
    context.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
    context.Response.Headers.Add("SameSite", "Strict");

    return next.Invoke();
});

So, after that I can read the JWT token with this code:

IAccessTokenProvider _accessToken;
private async Task<AccessToken> RequestUserToken()
{
    try
    {
        var tokenResult = await _accessToken.RequestAccessToken();
        tokenResult.TryGetToken(out var token);

        Console.WriteLine(token);

        return token;
    }
    catch (AccessTokenNotAvailableException aex)
    {
        throw new ApplicationException($"Exception {aex}");
    }
    catch (Exception ex)
    {
        throw new ApplicationException(
            $"AccessTokenNotAvailable Exception Exception {ex}");
    }
}

The application is working on Windows for any browser. On iOS and macOS I can read the token if I use Safari. It is working if I use Microsoft Edge and Chrome.

Do you have any idea how can I fix it?


问:
Identifying bad rows(utf-8) in oracle table
I get the below error message when trying to export and Oracle table using ora2pg. I would like to know if there is a query i can run to find out which columns have this utf-8 characters in it?

Unicode surrogate U+DBC0 is illegal in UTF-8 at /usr/lib64/perl5/IO/Handle.pm line 420.721 (1800 recs/sec)
Unicode surrogate U+DF72 is illegal in UTF-8 at /usr/lib64/perl5/IO/Handle.pm line 420.
Unicode surrogate U+DBC0 is illegal in UTF-8 at /usr/lib64/perl5/IO/Handle.pm line 420.
Unicode surrogate U+DF72 is illegal in UTF-8 at /usr/lib64/perl5/IO/Handle.pm line 420.
Unicode surrogate U+DBC0 is illegal in UTF-8 at /usr/lib64/perl5/IO/Handle.pm line 420.721 (1802 recs/sec)

Thanks.


问:
extract starting and ending with a special character
extract starting and ending with a special character

Content from the file:

```<code>/genomes/date/pa341/abc.txt

/genomes/date/ha76870/xyz/a1.pdf
</code>```

Result should be

```<code>/genomes/date/pa341/

/genomes/date/ha76870/xyz/
</code>```

Body:
extract starting and ending with a special character

Content from the file:

/genomes/date/pa341/abc.txt

/genomes/date/ha76870/xyz/a1.pdf

Result should be

/genomes/date/pa341/

/genomes/date/ha76870/xyz/


问:
Prevent QFileInfo from prepending C: to path
How can I prevent QFileInfo class from prepending C:/ on Windows?

Example:

I would like to store this path on QFileInfo -> /media/my_folder/my_file

On Windows, the absoluteFilePath() function returns C:/media/my_folder/my_file

How can I solve this issue?


问:
Dividing ranges to each other and multi conditionals
I want to create a multi criteria Worksheet Function in VBA according to this excel formula

```<code>=AGGREGATE(14,6,A:A/(B:B="YES")*(C:C="NO"),1)
</code>```

I don't want using direct excel  formula method like =AGGREGATE(14,6..... The purpose is creating the logic with WorksheetFucnction method.

The main issue is dividing ranges by each other: for example RANGE("A:A")/(RANGE("B:B")="YES") and multi criteria are also problem.

I have tried:

```<code>WorksheetFunction.Aggregate(14,6,Range("A:A")/(Range("B:B")="YES")*(Range("C:C")="NO"),1)
</code>```

But problem arises when it comes down to dividing ranges to each other.

Please share any other method to do this task.

Body:
I want to create a multi criteria Worksheet Function in VBA according to this excel formula

=AGGREGATE(14,6,A:A/(B:B="YES")*(C:C="NO"),1)

I don't want using direct excel  formula method like =AGGREGATE(14,6..... The purpose is creating the logic with WorksheetFucnction method.

The main issue is dividing ranges by each other: for example RANGE("A:A")/(RANGE("B:B")="YES") and multi criteria are also problem.

I have tried:

WorksheetFunction.Aggregate(14,6,Range("A:A")/(Range("B:B")="YES")*(Range("C:C")="NO"),1)

But problem arises when it comes down to dividing ranges to each other.

Please share any other method to do this task.


问:
getPendingNotificationRequests count is not decreasing on notification firing if UNCalendarNotificationTrigger repeat set to true
I am working on a app in that i need to schedule more than 64 notification at a time so i am schedule 64 notifications first and storing rest in database.
All notification is scheduling with UNCalendarNotificationTrigger repeat "true", because that will repeat every day/week.

So problem is that count of pendingNotificationRequest doesn't decrease of notification fires.
if i schedule 60 notifications and 10 notification fires at scheduled time, still i get 60 pending notification request from below code.

if i set to trigger repeat false it works fine, Please assist how can it work in repeat true.

```<code>  let center1 = UNUserNotificationCenter.current()
        center1.getPendingNotificationRequests(completionHandler: { requests in
            print("Total Count : \(requests.count)")
        })
</code>```

Body:
I am working on a app in that i need to schedule more than 64 notification at a time so i am schedule 64 notifications first and storing rest in database.
All notification is scheduling with UNCalendarNotificationTrigger repeat "true", because that will repeat every day/week.

So problem is that count of pendingNotificationRequest doesn't decrease of notification fires.
if i schedule 60 notifications and 10 notification fires at scheduled time, still i get 60 pending notification request from below code.

if i set to trigger repeat false it works fine, Please assist how can it work in repeat true.

  let center1 = UNUserNotificationCenter.current()
        center1.getPendingNotificationRequests(completionHandler: { requests in
            print("Total Count : \(requests.count)")
        })


问:
Is it possible to give each property in Mapbox a different color based on data that we have on the property?
Is it possible in the Mapbox GL JS to set a property color for each property? For each address we know if the property is an existing customer or not, so we would like to give properties of our customers a different color then the properties that are not our customers. Is something possible?

I already know how to set a color for all properties (followed this example: https://docs.mapbox.com/mapbox-gl-js/example/change-building-color-based-on-zoom-level/), but we like to have different colors based on the data that we have on the address/property.

Also wonder how we can map our data (address X is a customer) to a property in Mapbox GL JS.

Regards,

Nick


问:
Angular2 how to disable webpack on development
I upgraded Angular version from 12 to 15. After I run ng serve that is taking long time and development process taking long time. Is there a way to disable on development mode?


问:
Is there a way to allow/deny caslib acces from specific applications in Viya
My company wants to make some visual analytics dashboards available company wide, but not all users should be able to acces the data from outside of VA (from sas-studio or data explorer for example). Ideally the data should be only accessible from within VA.

I have thought about column-level acces, to only allow acces to the columns that are already visible within the dashboard, but some columns are needed for calculations/aggregations even though they are not visible in the dashboard, so this will break the dashboard.

Another solution would also be welcome. As long as the dashboard is accessible (which requires some form of data acces) without enabling the users to explore this data from elsewhere.


问:
SAS script works in windowing environment but fails in Linux
The code works very good, and creates the data, but in Linux it says the the data has 0 observations.
It has to search in library the files with specific name (and date in name).

```<code>%let path=library.name;
%let fname=name.starts.with;

data fnames;
  length
  fref $8
  fname $200
  datestr $17
;
format fdate yymmdd10.;
rc = filename(fref,"&path.");
did = dopen(fref);
 if did ne 0
 then do;
  do i = 1 to dnum(did);
    fname = dread(did,i);
   if index(fname,"&fname.")
     then do;
      datestr = scan(scan(fname,-2,"."),-1,"_");
      date = input(substr(datestr,1,8),yymmdd8.);
      fdate = substr(datestr,1,8);
      output;
    end;
  end;
  rc = dclose(did);
end;
rc = filename(fref);
keep fname fdate;
run;

proc sort data=fnames;
by descending fdate;
run;

data _null_;
set fnames (obs=1);
call symputx("fdate",fdate,"g");
run;
</code>```

How can I run the code in Linux? Why is it not read the data correctly?
Thank you.

Body:
The code works very good, and creates the data, but in Linux it says the the data has 0 observations.
It has to search in library the files with specific name (and date in name).

%let path=library.name;
%let fname=name.starts.with;

data fnames;
  length
  fref $8
  fname $200
  datestr $17
;
format fdate yymmdd10.;
rc = filename(fref,"&path.");
did = dopen(fref);
 if did ne 0
 then do;
  do i = 1 to dnum(did);
    fname = dread(did,i);
   if index(fname,"&fname.")
     then do;
      datestr = scan(scan(fname,-2,"."),-1,"_");
      date = input(substr(datestr,1,8),yymmdd8.);
      fdate = substr(datestr,1,8);
      output;
    end;
  end;
  rc = dclose(did);
end;
rc = filename(fref);
keep fname fdate;
run;

proc sort data=fnames;
by descending fdate;
run;

data _null_;
set fnames (obs=1);
call symputx("fdate",fdate,"g");
run;

How can I run the code in Linux? Why is it not read the data correctly?
Thank you.


问:
SharePoint - Timeout Error - Copying Folder To Another Folder
When I call this method enough times, I think I'm getting throttled because I'm seeing a connection timeout (instead of a 429).

I have a large set of files in a folder that I'm looking to copy to another folder, and looking for suggestions.

Thanks!

```<code>public void AddNewFileAndCheckIn(string sharepointFolderRelativeURL, string localFilePath, string indexName)
        {
            try
            {
                // Get the Folder
                //Folder fileFolder = Web.GetFolderByServerRelativeUrl(this.GetFolderRelativeUrl(sharepointFolderPath));
                var initTimeout = ClientContext.RequestTimeout;

                var timespans = new List<TimeSpan>();
                timespans.Add(TimeSpan.FromSeconds(300));
                timespans.Add(TimeSpan.FromSeconds(300));
                Polly.Retry.RetryPolicy policy = Polly.Policy.Handle<Exception>().WaitAndRetry(timespans);
                policy.Execute(() => {

                    using (var reader = new System.IO.StreamReader(localFilePath))
                    {
                        Folder fileFolder = Web.GetFolderByServerRelativeUrl(sharepointFolderRelativeURL);

                        // Add the File
                        FileCreationInformation fci = new FileCreationInformation();
                        fci.ContentStream = reader.BaseStream; // System.IO.File.ReadAllBytes(localFilePath);
                        fci.Url = System.IO.Path.GetFileName(localFilePath);

                        fileFolder.Files.Add(fci);
                        ClientContext.Load(fileFolder);
                        ClientContext.RequestTimeout = initTimeout * 10;
                        ClientContext.ExecuteQuery();

                        // Get the newly checked in (added) SP File
                        File fileToCheck = Web.GetFileByServerRelativeUrl(System.IO.Path.Combine(fileFolder.ServerRelativeUrl, fci.Url));
                        ClientContext.Load(fileToCheck, item => item, item => item.ListItemAllFields["Created"], item => item.ListItemAllFields["Modified"]);
                        ClientContext.ExecuteQuery();

                        // Update Metadata
                        fileToCheck.ListItemAllFields["Created"] = new System.IO.FileInfo(localFilePath).CreationTime;
                        fileToCheck.ListItemAllFields["Modified"] = new System.IO.FileInfo(localFilePath).LastWriteTime;
                        fileToCheck.ListItemAllFields["Index"] = indexName;
                        fileToCheck.ListItemAllFields.Update();
                        ClientContext.ExecuteQuery();
                    }
                });

            }

            catch (WebException wex)
            {
                throw new SharepointOnlineException(string.Format("Exception In AddNewFileAndCheckIn('{0}','{1}', '{2}')", sharepointFolderRelativeURL, localFilePath, indexName), wex);
            }
            catch (Exception ex)
            {
                // Catch and Rethrow with Details
                //throw new SharepointOnlineException(string.Format("Exception In AddNewFileAndCheckIn('{0}','{1}', '{2}')", sharepointFolderPath, localFilePath, indexName), ex);
                throw new SharepointOnlineException(string.Format("Exception In AddNewFileAndCheckIn('{0}','{1}', '{2}')", sharepointFolderRelativeURL, localFilePath, indexName), ex);
            }
        }
</code>```

Body:
When I call this method enough times, I think I'm getting throttled because I'm seeing a connection timeout (instead of a 429).

I have a large set of files in a folder that I'm looking to copy to another folder, and looking for suggestions.

Thanks!

public void AddNewFileAndCheckIn(string sharepointFolderRelativeURL, string localFilePath, string indexName)
        {
            try
            {
                // Get the Folder
                //Folder fileFolder = Web.GetFolderByServerRelativeUrl(this.GetFolderRelativeUrl(sharepointFolderPath));
                var initTimeout = ClientContext.RequestTimeout;

                var timespans = new List<TimeSpan>();
                timespans.Add(TimeSpan.FromSeconds(300));
                timespans.Add(TimeSpan.FromSeconds(300));
                Polly.Retry.RetryPolicy policy = Polly.Policy.Handle<Exception>().WaitAndRetry(timespans);
                policy.Execute(() => {

                    using (var reader = new System.IO.StreamReader(localFilePath))
                    {
                        Folder fileFolder = Web.GetFolderByServerRelativeUrl(sharepointFolderRelativeURL);

                        // Add the File
                        FileCreationInformation fci = new FileCreationInformation();
                        fci.ContentStream = reader.BaseStream; // System.IO.File.ReadAllBytes(localFilePath);
                        fci.Url = System.IO.Path.GetFileName(localFilePath);

                        fileFolder.Files.Add(fci);
                        ClientContext.Load(fileFolder);
                        ClientContext.RequestTimeout = initTimeout * 10;
                        ClientContext.ExecuteQuery();

                        // Get the newly checked in (added) SP File
                        File fileToCheck = Web.GetFileByServerRelativeUrl(System.IO.Path.Combine(fileFolder.ServerRelativeUrl, fci.Url));
                        ClientContext.Load(fileToCheck, item => item, item => item.ListItemAllFields["Created"], item => item.ListItemAllFields["Modified"]);
                        ClientContext.ExecuteQuery();

                        // Update Metadata
                        fileToCheck.ListItemAllFields["Created"] = new System.IO.FileInfo(localFilePath).CreationTime;
                        fileToCheck.ListItemAllFields["Modified"] = new System.IO.FileInfo(localFilePath).LastWriteTime;
                        fileToCheck.ListItemAllFields["Index"] = indexName;
                        fileToCheck.ListItemAllFields.Update();
                        ClientContext.ExecuteQuery();
                    }
                });

            }

            catch (WebException wex)
            {
                throw new SharepointOnlineException(string.Format("Exception In AddNewFileAndCheckIn('{0}','{1}', '{2}')", sharepointFolderRelativeURL, localFilePath, indexName), wex);
            }
            catch (Exception ex)
            {
                // Catch and Rethrow with Details
                //throw new SharepointOnlineException(string.Format("Exception In AddNewFileAndCheckIn('{0}','{1}', '{2}')", sharepointFolderPath, localFilePath, indexName), ex);
                throw new SharepointOnlineException(string.Format("Exception In AddNewFileAndCheckIn('{0}','{1}', '{2}')", sharepointFolderRelativeURL, localFilePath, indexName), ex);
            }
        }


问:
Is it possible to use together @Id (from JPA) and @Generated (from Hibernate) annotations for a field which is part of a composite primary key?
We have an entity which is using a composite primary key (we are using @IdClass approach because we want to use our custom ID generator). This composite key is defined like this:

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class BasePK implements Serializable {

    private String id;
    private Instant createdAt;

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof BasePK)) {
            return false;
        }
        BasePK that = (BasePK) o;
        return Objects.equals(id, that.id) && Objects.equals(createdAt, that.createdAt);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, createdAt);
    }

}
```
<p>And the entity class looks like this:</p>
<pre class="lang-java prettyprint-override"><code>@NoArgsConstructor
@Getter
@Setter
@IdClass(BasePK.class)
@Table(name = "MY_TABLE")
@Entity
public class MyEntity implements Identifiable <String> {

    @Id
    @NotNull
    @GenericGenerator(name = "ulid-generator", strategy = "com.example.common.jpa.ULIDIdentifier")
    @GeneratedValue(generator = "ulid-generator")
    @Column(name = "ID", updatable = false, nullable = false, length = 26)
    private String id;

    @Id
    @Generated(GenerationTime.INSERT)
    @Column(name = "CREATED_AT", insertable = false, updatable = false, nullable = false)
    private Instant createdAt;

    // ETC.

}
</code>```

The SQL definition is like these (notice that we want to generate the CREATED_AT in the database side just by using a default current UCT time):

MY_TABLE {
    key ID           String(26) not null;
    key CREATED_AT   Timestamp not null default CURRENT_UTCTIMESTAMP;
    // ETC.
}
```

We are aware that using timestamp is not good idea in primary keys and that it could also very easily be generated in application side by using Hibernate @CreatedDate annotation, but the requirements we have received is that this timestamp has to be generated in database side.

So we tried the approach of using the Hibernate annotation @Generated in order to tell Hibernate to exclude the createdAt from the generated SQL, but we noticed that that field is still there in the Hibernate generated SQL: Hibernate: insert into MY_TABLE (ID, OTHER_FIELDS, CREATED_AT) values (?, ?, ?) and that is, of course, making the inserting to fail, because the statement has an extra value that shifts everything resulting in inserting the wrong type and value in the wrong fields.

Is there any way to achieve what we are trying (even though it might be a bad design from the beginning, but for now is not in our hands to change those requirements).

Body:
We have an entity which is using a composite primary key (we are using @IdClass approach because we want to use our custom ID generator). This composite key is defined like this:

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class BasePK implements Serializable {

    private String id;
    private Instant createdAt;

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof BasePK)) {
            return false;
        }
        BasePK that = (BasePK) o;
        return Objects.equals(id, that.id) && Objects.equals(createdAt, that.createdAt);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, createdAt);
    }

}

And the entity class looks like this:

@NoArgsConstructor
@Getter
@Setter
@IdClass(BasePK.class)
@Table(name = "MY_TABLE")
@Entity
public class MyEntity implements Identifiable <String> {

    @Id
    @NotNull
    @GenericGenerator(name = "ulid-generator", strategy = "com.example.common.jpa.ULIDIdentifier")
    @GeneratedValue(generator = "ulid-generator")
    @Column(name = "ID", updatable = false, nullable = false, length = 26)
    private String id;

    @Id
    @Generated(GenerationTime.INSERT)
    @Column(name = "CREATED_AT", insertable = false, updatable = false, nullable = false)
    private Instant createdAt;

    // ETC.

}

The SQL definition is like these (notice that we want to generate the CREATED_AT in the database side just by using a default current UCT time):

MY_TABLE {
    key ID           String(26) not null;
    key CREATED_AT   Timestamp not null default CURRENT_UTCTIMESTAMP;
    // ETC.
}

We are aware that using timestamp is not good idea in primary keys and that it could also very easily be generated in application side by using Hibernate @CreatedDate annotation, but the requirements we have received is that this timestamp has to be generated in database side.

So we tried the approach of using the Hibernate annotation @Generated in order to tell Hibernate to exclude the createdAt from the generated SQL, but we noticed that that field is still there in the Hibernate generated SQL: Hibernate: insert into MY_TABLE (ID, OTHER_FIELDS, CREATED_AT) values (?, ?, ?) and that is, of course, making the inserting to fail, because the statement has an extra value that shifts everything resulting in inserting the wrong type and value in the wrong fields.

Is there any way to achieve what we are trying (even though it might be a bad design from the beginning, but for now is not in our hands to change those requirements).


问:
Why me trackball always disappears when I move a mouse on a SfCartesianChart?
I have SfCartesianChart and trackball inside, when I try to click or move a mouse on the SfCartesianChart then nothing happens, my trackball doesn't appear.

It appears only one second then immediately disappears, I fond out it by clicking and moving a mouse on SfCartesianChart almost a minute...

How to fix that?

This is my SfCartesianChart, there is no trackball when I click or move on blue dots:

And this is my code:

```<code>class HomeWidget extends StatefulWidget {
  const HomeWidget({super.key});

  @override
  State<HomeWidget> createState() => _HomeWidgetState();
}

class _HomeWidgetState extends State<HomeWidget> {
  late TabController _tabController;
  void initState() {
      _tabController = TabController(vsync: this, length: 3);
      super.initState();
  }
  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 220.h,
      child: TabBarView(
        controller: _tabController,
        children: [
          DaysChart(
            monitoringData: state.chartData,
            precision: 1
          ),
          DaysChart(
            monitoringData: state.chartData,
            precision: 2
          ),
           DaysChart(
            monitoringData: state.chartData,
            precision: 3
          ),
        ],
      )
    );
  }
}
</code>```

Chartdata looks like this:

```<code>state.chartData = List<TimeSeriesValues> dayMonitoringData = [
    TimeSeriesValues(DateTime(2007, 2, 1, 8, 40), 30),
    TimeSeriesValues(DateTime(2007, 2, 1, 12, 40), 80),
    TimeSeriesValues(DateTime(2007, 2, 1, 18, 40), 50),
  ];
</code>```

And TimeSeriesValues class:

```<code>class TimeSeriesValues {
  final DateTime time;
  final int values;

  TimeSeriesValues(this.time, this.values);
}
</code>```

And this is DaysChart:

```<code>class DaysChart extends StatefulWidget {
  const DaysChart({
    Key? key,
    required this.monitoringData,
    required this.precision,
  }) : super(key: key);
  final List<TimeSeriesValues> monitoringData;
  final int precision;

  @override
  State<DaysChart> createState() => _DaysChartState();
}

class _DaysChartState extends State<DaysChart> {

  late TrackballBehavior _trackballBehavior;
  @override
  void initState() {
    _trackballBehavior = TrackballBehavior(
      enable: true,
      shouldAlwaysShow: true,
      lineColor: const Color(0xFF454545),
      activationMode: ActivationMode.singleTap,
      tooltipDisplayMode: TrackballDisplayMode.nearestPoint,
      tooltipSettings: const InteractiveTooltip(
        arrowLength: 0,
        arrowWidth: 0,
        canShowMarker: false,
        color: Colors.transparent,
      ),
      builder: (context, TrackballDetails trackballDetails) {
        var tag = Localizations.maybeLocaleOf(context)?.toLanguageTag();
        return SizedBox(
          height: 50,
          child: Column(
            children: [
              Text(
                "${trackballDetails.point!.yValue.round().toString()}%",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16.sp,
                )
              ),
              Text(
                DateFormat.MMMMd(tag).format(trackballDetails.point!.x),
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 10.sp,
                ),
              )
            ],
          )
        );
      }
    );

    super.initState();
  }
@override
  Widget build(BuildContext context) {
    final List<double> stops = <double>[];
    stops.add(0.1);
    stops.add(1.0);

  return SizedBox(
    height: 190.h,
    width: 320.w,
    child: SfCartesianChart(
      plotAreaBorderWidth: 0,
      plotAreaBorderColor: Colors.white24,
      trackballBehavior: _trackballBehavior,
      primaryXAxis: DateTimeCategoryAxis(
        majorTickLines: const MajorTickLines(width: 0),
        axisLine: const AxisLine(
          color: Colors.white24,
          dashArray: <double>[5,5]
        ),
        minimum: widget.monitoringData.first.time,
        maximum: widget.monitoringData.last.time,
        intervalType: widget.precision == 1
          ? DateTimeIntervalType.minutes
          : widget.precision == 2
            ? DateTimeIntervalType.days
            : DateTimeIntervalType.months,
           dateFormat: widget.precision == 1
            ? DateFormat.Hm()
              : widget.precision == 2
              ? DateFormat.E()
              : DateFormat.MMMd(),
             borderColor: Colors.transparent,
             majorGridLines: const MajorGridLines(
             width: 0.5,
              color: Colors.transparent,
          ),
      ),
      primaryYAxis: NumericAxis(
        majorGridLines: const MajorGridLines(width: 0.5, color: Colors.white24, dashArray: <double>[5, 5]),
        majorTickLines: const MajorTickLines(width: 0),
        axisLine: const AxisLine(
          width: 0
        ),
        labelStyle: const TextStyle(
          fontSize: 0
        ),
        minimum: 0,
        maximum: 100
      ),
      series: <ChartSeries<TimeSeriesValues, DateTime>>[
      AreaSeries<TimeSeriesValues, DateTime>(
        borderWidth: 2,
        animationDuration: 0,
        borderColor: const Color(0xFF409CFF),
        dataSource: widget.monitoringData,
        markerSettings: const MarkerSettings(
          isVisible: true,
          color: Color(0xFF409CFF),
          height: 11,
          width: 11,
          borderWidth: 3,
          borderColor: Colors.transparent,
        ),
        xValueMapper: (TimeSeriesValues sales, _) => sales.time,
        yValueMapper: (TimeSeriesValues sales, _) => sales.values,
        gradient: LinearGradient(
          colors: const [Color(0xFF121212), Color(0xFF10273F)],
          stops: stops,
          begin: Alignment.bottomCenter,
          end: Alignment.topCenter),
        )
      ]
  );
}
</code>```

Body:
I have SfCartesianChart and trackball inside, when I try to click or move a mouse on the SfCartesianChart then nothing happens, my trackball doesn't appear.

It appears only one second then immediately disappears, I fond out it by clicking and moving a mouse on SfCartesianChart almost a minute...

How to fix that?

This is my SfCartesianChart, there is no trackball when I click or move on blue dots:

And this is my code:

class HomeWidget extends StatefulWidget {
  const HomeWidget({super.key});

  @override
  State<HomeWidget> createState() => _HomeWidgetState();
}

class _HomeWidgetState extends State<HomeWidget> {
  late TabController _tabController;
  void initState() {
      _tabController = TabController(vsync: this, length: 3);
      super.initState();
  }
  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 220.h,
      child: TabBarView(
        controller: _tabController,
        children: [
          DaysChart(
            monitoringData: state.chartData,
            precision: 1
          ),
          DaysChart(
            monitoringData: state.chartData,
            precision: 2
          ),
           DaysChart(
            monitoringData: state.chartData,
            precision: 3
          ),
        ],
      )
    );
  }
}

Chartdata looks like this:

state.chartData = List<TimeSeriesValues> dayMonitoringData = [
    TimeSeriesValues(DateTime(2007, 2, 1, 8, 40), 30),
    TimeSeriesValues(DateTime(2007, 2, 1, 12, 40), 80),
    TimeSeriesValues(DateTime(2007, 2, 1, 18, 40), 50),
  ];

And TimeSeriesValues class:

class TimeSeriesValues {
  final DateTime time;
  final int values;

  TimeSeriesValues(this.time, this.values);
}

And this is DaysChart:

class DaysChart extends StatefulWidget {
  const DaysChart({
    Key? key,
    required this.monitoringData,
    required this.precision,
  }) : super(key: key);
  final List<TimeSeriesValues> monitoringData;
  final int precision;

  @override
  State<DaysChart> createState() => _DaysChartState();
}

class _DaysChartState extends State<DaysChart> {

  late TrackballBehavior _trackballBehavior;
  @override
  void initState() {
    _trackballBehavior = TrackballBehavior(
      enable: true,
      shouldAlwaysShow: true,
      lineColor: const Color(0xFF454545),
      activationMode: ActivationMode.singleTap,
      tooltipDisplayMode: TrackballDisplayMode.nearestPoint,
      tooltipSettings: const InteractiveTooltip(
        arrowLength: 0,
        arrowWidth: 0,
        canShowMarker: false,
        color: Colors.transparent,
      ),
      builder: (context, TrackballDetails trackballDetails) {
        var tag = Localizations.maybeLocaleOf(context)?.toLanguageTag();
        return SizedBox(
          height: 50,
          child: Column(
            children: [
              Text(
                "${trackballDetails.point!.yValue.round().toString()}%",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16.sp,
                )
              ),
              Text(
                DateFormat.MMMMd(tag).format(trackballDetails.point!.x),
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 10.sp,
                ),
              )
            ],
          )
        );
      }
    );

    super.initState();
  }
@override
  Widget build(BuildContext context) {
    final List<double> stops = <double>[];
    stops.add(0.1);
    stops.add(1.0);

  return SizedBox(
    height: 190.h,
    width: 320.w,
    child: SfCartesianChart(
      plotAreaBorderWidth: 0,
      plotAreaBorderColor: Colors.white24,
      trackballBehavior: _trackballBehavior,
      primaryXAxis: DateTimeCategoryAxis(
        majorTickLines: const MajorTickLines(width: 0),
        axisLine: const AxisLine(
          color: Colors.white24,
          dashArray: <double>[5,5]
        ),
        minimum: widget.monitoringData.first.time,
        maximum: widget.monitoringData.last.time,
        intervalType: widget.precision == 1
          ? DateTimeIntervalType.minutes
          : widget.precision == 2
            ? DateTimeIntervalType.days
            : DateTimeIntervalType.months,
           dateFormat: widget.precision == 1
            ? DateFormat.Hm()
              : widget.precision == 2
              ? DateFormat.E()
              : DateFormat.MMMd(),
             borderColor: Colors.transparent,
             majorGridLines: const MajorGridLines(
             width: 0.5,
              color: Colors.transparent,
          ),
      ),
      primaryYAxis: NumericAxis(
        majorGridLines: const MajorGridLines(width: 0.5, color: Colors.white24, dashArray: <double>[5, 5]),
        majorTickLines: const MajorTickLines(width: 0),
        axisLine: const AxisLine(
          width: 0
        ),
        labelStyle: const TextStyle(
          fontSize: 0
        ),
        minimum: 0,
        maximum: 100
      ),
      series: <ChartSeries<TimeSeriesValues, DateTime>>[
      AreaSeries<TimeSeriesValues, DateTime>(
        borderWidth: 2,
        animationDuration: 0,
        borderColor: const Color(0xFF409CFF),
        dataSource: widget.monitoringData,
        markerSettings: const MarkerSettings(
          isVisible: true,
          color: Color(0xFF409CFF),
          height: 11,
          width: 11,
          borderWidth: 3,
          borderColor: Colors.transparent,
        ),
        xValueMapper: (TimeSeriesValues sales, _) => sales.time,
        yValueMapper: (TimeSeriesValues sales, _) => sales.values,
        gradient: LinearGradient(
          colors: const [Color(0xFF121212), Color(0xFF10273F)],
          stops: stops,
          begin: Alignment.bottomCenter,
          end: Alignment.topCenter),
        )
      ]
  );
}


问:
How to get filesource from Intervention Image?
I'm using Intervention image package to resize and crop upload images.

```<code>$img = Image::make($source)
        ->resize($resize['width'], $resize['height'], function ($constraint) {
            $constraint->aspectRatio();
            $constraint->upsize();
        })
        ->encode()->stream();
</code>```

But I need to store into S3 like this:

```<code>$s3Client->putObject([
        'Bucket' => $s3_bucket,
        'Key'    => $Key,
        'Body'   => fopen($img, 'r+')
    ]);
</code>```

fopen(): Argument #1 ($filename) must not contain any null bytes

Body:
I'm using Intervention image package to resize and crop upload images.

$img = Image::make($source)
        ->resize($resize['width'], $resize['height'], function ($constraint) {
            $constraint->aspectRatio();
            $constraint->upsize();
        })
        ->encode()->stream();

But I need to store into S3 like this:

$s3Client->putObject([
        'Bucket' => $s3_bucket,
        'Key'    => $Key,
        'Body'   => fopen($img, 'r+')
    ]);

fopen(): Argument #1 ($filename) must not contain any null bytes


问:
CRM Plugin: how to update associated contacts' email address when you update account email address
I'm using Visual Studio 2022 version.

I have an "account" entity which has associated "contacts". When the current "account" entity's "email_address" is updated, I want all the associated contacts email_addresses to be updated with that address.

I want to do this in a plug-in which runs on the "account" entity when you update the email_address. When you do so, ALL the associated contacts have their email_address updated to that email_address.

I'm new to CRM can anyone let me know how to build this logic.


问:
How to Securely Use SecretStrage in VScode Extension
I am trying to create an extension to VSCode and am thinking of using SecretStrage to hold secret values.

In the vscode-extension-samples repository, SecretStrage is used as follows

```<code>export class AzureDevOpsAuthenticationProvider implements AuthenticationProvider, Disposable {
  private static secretKey = 'AzureDevOpsPAT';
  ...

  private cacheTokenFromStorage() {
    this.currentToken = this.secretStorage.get(AzureDevOpsAuthenticationProvider.secretKey) as Promise<string | undefined>;
    return this.currentToken;
  }
}
</code>```

However, I fear that this would allow access to the secret value when the implementation is seen and the secretkey is known.

As long as I don't publish my implementation on github, etc., will it ever be known if I use a fixed value for secretkey?

Or should I implement it more securely? Is there a good solution for that?

Body:
I am trying to create an extension to VSCode and am thinking of using SecretStrage to hold secret values.

In the vscode-extension-samples repository, SecretStrage is used as follows

export class AzureDevOpsAuthenticationProvider implements AuthenticationProvider, Disposable {
  private static secretKey = 'AzureDevOpsPAT';
  ...

  private cacheTokenFromStorage() {
    this.currentToken = this.secretStorage.get(AzureDevOpsAuthenticationProvider.secretKey) as Promise<string | undefined>;
    return this.currentToken;
  }
}

However, I fear that this would allow access to the secret value when the implementation is seen and the secretkey is known.

As long as I don't publish my implementation on github, etc., will it ever be known if I use a fixed value for secretkey?

Or should I implement it more securely? Is there a good solution for that?


问:
How to collect all validations errors when using custom class validator
I'm using a custom class validator to validate serializer fields, and I would like to raise ValidationError for all fields so API error response has fields with all errors instead of a single error, instead, now I'm getting the validation error only for single fields. Before I've used method validations inside my serializer and it worked as I need, but this is not the case with class validators.

Here is how validators look like

class TitleValidator:

    MIN_TITLE_LENGTH = 20

    def __call__(self, attrs: dict):
        title = attrs.get("title", "")
        if len(title) < self.MIN_TITLE_LENGTH:
            raise ValidationError(f"Min title length is {self.MIN_TITLE_LENGTH}")
        return title

class SlugsValidator:

    def __call__(self, attrs):
        slug = attrs.get("slug", "")
        if len(slug) < 10:
            raise ValidationError("Slug must be at least 10 characters long")
        return slug
```


问:
Data Abstract and encapsulation
What is the difference between data abstract and data encapsulation.
I have knowledge about abstract but I do not know data encapsulation.</p>

Title: Data Abstract and encapsulation