问:
Is there a way to use IsMouseOver in a resource dictionary
When I use the below block of code in a Window or control it works (I can see the button animation and the size of the button changes when I hover over it), but it does not work when I use it in the resource dictionary. I am creating a Prism app with mah apps window.

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:iconPacks="http://metro.mahapps.com/winfx/xaml/iconpacks"
                    xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
                    xmlns:b="http://schemas.microsoft.com/expression/2010/interactivity"

                   >
    <!--// Merge Dic here //-->
    <ContentControl x:Key="OperatorUIPreview"
                    Content="{StaticResource splashStyle}"/>

    <ContentControl x:Key="OperatorUI.Home"
                  Background="Purple">

        <Grid >
            <Border
                        Background="#323345"
                        CornerRadius="10,10,0,0"
                        Margin="0,85,0,0">

                <Grid >
                    <Button
                                x:Name="home1"
                                Background="Blue"

                            Style="{StaticResource DockBtnStyle}">

                        <Popup Width="70"
                                   HorizontalOffset="-12"
                                   PlacementTarget="{Binding ElementName=home1}"
                                   IsOpen="{Binding ElementName=home1, Path=IsMouseOver, Mode=OneWay}"
                                   Style="{StaticResource PopupStyle}">

                            <Grid>
                                <Border Style="{StaticResource border}">
                                    <TextBlock Text="Home"
                                                   Style="{StaticResource PopupText}" />
                                </Border>

                                <Path Style="{StaticResource ArrowPath}"/>
                            </Grid>
                        </Popup>
                    </Button>
                </Grid>
            </Border>
        </Grid>
    </ContentControl>
</ResourceDictionary>
</code>```

Style:

```<code>  <Style x:Key="DockBtnStyle"
        TargetType="Button">

        <Setter Property="Height"
            Value="50" />

        <Setter Property="Width"
            Value="50" />

        <Setter Property="Template">

            <Setter.Value>

                <ControlTemplate TargetType="{x:Type Button}">

                    <Border x:Name="border"
                        BorderThickness="0"
                        Background="{TemplateBinding Background}" />

                </ControlTemplate>

            </Setter.Value>

        </Setter>

        <!--// Button Animation //-->

        <Style.Triggers>
            <EventTrigger RoutedEvent="MouseEnter">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetProperty="(Button.Width)"
                                        To="65"
                                        Duration="0:0:0.3" />

                        <DoubleAnimation Storyboard.TargetProperty="(Button.Height)"
                                        To="65"
                                        Duration="0:0:0.3" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>

            <EventTrigger RoutedEvent="MouseLeave">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetProperty="(Button.Width)"
                                        To="50"
                                        Duration="0:0:0.3" />

                        <DoubleAnimation Storyboard.TargetProperty="(Button.Height)"
                                        To="50"
                                        Duration="0:0:0.3" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Style.Triggers>
    </Style>
</code>```

Body:
When I use the below block of code in a Window or control it works (I can see the button animation and the size of the button changes when I hover over it), but it does not work when I use it in the resource dictionary. I am creating a Prism app with mah apps window.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:iconPacks="http://metro.mahapps.com/winfx/xaml/iconpacks"
                    xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
                    xmlns:b="http://schemas.microsoft.com/expression/2010/interactivity"

                   >

    <ContentControl x:Key="OperatorUIPreview"
                    Content="{StaticResource splashStyle}"/>

    <ContentControl x:Key="OperatorUI.Home"
                  Background="Purple">

        <Grid >
            <Border
                        Background="#323345"
                        CornerRadius="10,10,0,0"
                        Margin="0,85,0,0">

                <Grid >
                    <Button
                                x:Name="home1"
                                Background="Blue"

                            Style="{StaticResource DockBtnStyle}">

                        <Popup Width="70"
                                   HorizontalOffset="-12"
                                   PlacementTarget="{Binding ElementName=home1}"
                                   IsOpen="{Binding ElementName=home1, Path=IsMouseOver, Mode=OneWay}"
                                   Style="{StaticResource PopupStyle}">

                            <Grid>
                                <Border Style="{StaticResource border}">
                                    <TextBlock Text="Home"
                                                   Style="{StaticResource PopupText}" />
                                </Border>

                                <Path Style="{StaticResource ArrowPath}"/>
                            </Grid>
                        </Popup>
                    </Button>
                </Grid>
            </Border>
        </Grid>
    </ContentControl>
</ResourceDictionary>

Style:

    </Style>


来源: stackexchange

问:
How to change gravity om custom ActionBar in android studio
I am knew at kotlin and android staff, so need your help. I have created custom ActionBar on a specified activity and wanted to add text to it and a button to open drawerLayout. However, it is not working as I want - text and clickable image are centred and I can't change the gravity.

```<code>class MainActivity : AppCompatActivity() {
    lateinit var binding: ActivityMainBinding
    private var mDrawerToggle: ActionBarDrawerToggle? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.toolbar)
        supportActionBar?.title = "App name"
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setIcon(R.drawable.ic_menu)

        mDrawerToggle = ActionBarDrawerToggle(this, binding.drawerMain, binding.toolbar, R.string.days, R.string.abs)
        mDrawerToggle!!.syncState()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (mDrawerToggle?.onOptionsItemSelected(item) == true)
            return true

        return super.onOptionsItemSelected(item)
    }
}
</code>```

(https://i.stack.imgur.com/9bXd9.png)

Setting gravity in xml is not working

ContentLicense: CC BY-SA 4.0

Body:
I am knew at kotlin and android staff, so need your help. I have created custom ActionBar on a specified activity and wanted to add text to it and a button to open drawerLayout. However, it is not working as I want - text and clickable image are centred and I can't change the gravity.

class MainActivity : AppCompatActivity() {
    lateinit var binding: ActivityMainBinding
    private var mDrawerToggle: ActionBarDrawerToggle? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.toolbar)
        supportActionBar?.title = "App name"
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setIcon(R.drawable.ic_menu)

        mDrawerToggle = ActionBarDrawerToggle(this, binding.drawerMain, binding.toolbar, R.string.days, R.string.abs)
        mDrawerToggle!!.syncState()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (mDrawerToggle?.onOptionsItemSelected(item) == true)
            return true

        return super.onOptionsItemSelected(item)
    }
}

(https://i.stack.imgur.com/9bXd9.png)

Setting gravity in xml is not working


问:
Is there a way to set new route on NextJS using useRouter
I am building a NextJS app and I trying to set a new route using next/router.
When I am on the route

```<code>/auth/complete_profile
</code>```

I would like to move to the route

```<code>/account
</code>```

I try doing it like so:

```<code>      if(userData?.id != undefined){
         router.push('/account')
      }
</code>```

But this quickly pushes to account route and goes back to the previous route.

please help.

Body:
I am building a NextJS app and I trying to set a new route using next/router.
When I am on the route

/auth/complete_profile

I would like to move to the route

/account

I try doing it like so:

      if(userData?.id != undefined){
         router.push('/account')
      }

But this quickly pushes to account route and goes back to the previous route.

please help.


问:
Is it posible for a React function to keep calling itself until state value changes?
I'm trying to replicate on React a metronome built with Vue. Basically the play function keeps calling itself while playing is true. Here is the Vue code:

```<code>data() {
    return {
      playing: false,
      audioContext: null,
      audioBuffer: null,
      currentTime: null
    }
},
mounted() {
    this.initContext();
},
methods: {
    toggle()
      if (!this.playing) {
        this.currentTime = this.audioContext.currentTime;
        this.playing = true;
        this.play();
      } else {
        this.playing = false;
      }
    },
    play() {
      this.currentTime += 60 / this.$store.state.tempo;
      const source = this.audioContext.createBufferSource();
      source.buffer = this.audioBuffer;
      source.connect(this.audioContext.destination);
      source.onended = this.playing ? this.play : "";
      source.start(this.currentTime);
    },
    async initContext() {
      this.audioContext = new AudioContext();
      this.audioBuffer = await fetch("click.wav")
        .then(res => res.arrayBuffer())
        .then(arrayBuffer =>
          this.audioContext.decodeAudioData(arrayBuffer)
        )
    }
}
</code>```

This is what I tried. The problem I have is that the state being async on React won't update while the function is running and the value of playing will never change.

```<code>const firstRender = useRef(true);
const [bpm, setBpm] = useState<number>(60);
const [playing, setPlaying] = useState<boolean>(false);
const [context, setContext] = useState<AudioContext>(undefined);
const [buffer, setBuffer] = useState<AudioBuffer>(undefined);
const [currentTime, setCurrentTime] = useState<number>(0);

useEffect(() => {
    if (firstRender.current) {
        firstRender.current = false;
        initContext();
        return;
    }
});

const toggle = () => {
    if (!playing) {
        setCurrentTime(context.currentTime);
        setPlaying(true);
        play();
    } else {
        setPlaying(false)
    }
}

const play = () => {
    setCurrentTime(currentTime + 60 / bpm);
    let source = context.createBufferSource();
    source.buffer = buffer;
    source.connect(context.destination);
    source.onended = playing ? play : undefined;
    source.start(currentTime);
}

const initContext = async () => {
    const audioContext = new AudioContext();
    const audioBuffer = await fetch("click.wav")
        .then(res => res.arrayBuffer())
        .then(arrayBuffer =>
            audioContext.decodeAudioData(arrayBuffer)
        )

    setContext(audioContext);
    setBuffer(audioBuffer);
}
</code>```

I guess the solution should be on useEffect but I could not manage to recreate it. Any suggestion is appreciated!

Body:
I'm trying to replicate on React a metronome built with Vue. Basically the play function keeps calling itself while playing is true. Here is the Vue code:

data() {
    return {
      playing: false,
      audioContext: null,
      audioBuffer: null,
      currentTime: null
    }
},
mounted() {
    this.initContext();
},
methods: {
    toggle()
      if (!this.playing) {
        this.currentTime = this.audioContext.currentTime;
        this.playing = true;
        this.play();
      } else {
        this.playing = false;
      }
    },
    play() {
      this.currentTime += 60 / this.$store.state.tempo;
      const source = this.audioContext.createBufferSource();
      source.buffer = this.audioBuffer;
      source.connect(this.audioContext.destination);
      source.onended = this.playing ? this.play : "";
      source.start(this.currentTime);
    },
    async initContext() {
      this.audioContext = new AudioContext();
      this.audioBuffer = await fetch("click.wav")
        .then(res => res.arrayBuffer())
        .then(arrayBuffer =>
          this.audioContext.decodeAudioData(arrayBuffer)
        )
    }
}

This is what I tried. The problem I have is that the state being async on React won't update while the function is running and the value of playing will never change.

const firstRender = useRef(true);
const [bpm, setBpm] = useState<number>(60);
const [playing, setPlaying] = useState<boolean>(false);
const [context, setContext] = useState<AudioContext>(undefined);
const [buffer, setBuffer] = useState<AudioBuffer>(undefined);
const [currentTime, setCurrentTime] = useState<number>(0);

useEffect(() => {
    if (firstRender.current) {
        firstRender.current = false;
        initContext();
        return;
    }
});

const toggle = () => {
    if (!playing) {
        setCurrentTime(context.currentTime);
        setPlaying(true);
        play();
    } else {
        setPlaying(false)
    }
}

const play = () => {
    setCurrentTime(currentTime + 60 / bpm);
    let source = context.createBufferSource();
    source.buffer = buffer;
    source.connect(context.destination);
    source.onended = playing ? play : undefined;
    source.start(currentTime);
}

const initContext = async () => {
    const audioContext = new AudioContext();
    const audioBuffer = await fetch("click.wav")
        .then(res => res.arrayBuffer())
        .then(arrayBuffer =>
            audioContext.decodeAudioData(arrayBuffer)
        )

    setContext(audioContext);
    setBuffer(audioBuffer);
}

I guess the solution should be on useEffect but I could not manage to recreate it. Any suggestion is appreciated!


问:
Update config.json file for a static frontend React site, using AWS CodePipeline and CDK
I'm building a CDK Pipeline that with update another CDK template.
This CDK template is a static frontend react app.
The backend uses an AWS Lambda, API Gateway, and CloudFront Distribution to host the site.
I want to put the api's in the config.json file as I normally would if I were building it manually one service at a time.

The problem seems to be in the cdk pipeline-stack, which builds the static-frontend-stack.
When you initialize a new pipeline, it wants you to add shell steps first, (npm i, cd into correct folder, npm run build, etc) which creates the distribution folder I need.
As well as turning the whole thing into a CF template.

Then you can drop that into different stages you want, e.g., test and prod.

However, I won't receive CfnOutputs until the stages are built. And the CfnOutputs hold the api's and other info I need to put into the config.json file (which was already built first, and created empty values).

There is even a envFromCfnOutputs param to add to the initial codebuild pipeline, but since they are initialized/created later, typescript yells at me for putting it in there before. I understand why that errors, but I can't figure a clever way to fix this issue.

import * as cdk from "aws-cdk-lib";
import { Construct } from "constructs";
import * as pipelines from "aws-cdk-lib/pipelines";
import * as codecommit from "aws-cdk-lib/aws-codecommit";
import { Stages } from "./stages";
import { Stack, Stage } from "aws-cdk-lib";

interface PipelineStackProps extends cdk.StackProps {
  env: {
    account: string;
    region: string;
    stage: string;
  };
}

export class PipelineStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props: PipelineStackProps) {
    super(scope, id, props);

    /************ Grab Repo ************/
    const source = codecommit.Repository.fromRepositoryName(
      this,
      "PreCallbackSMSSolution",
      "PreCallbackSMSSolution"
    );

    /************ Define Pipeline & Build ShellStep (for Frontend) ************/
    const Pipeline = new pipelines.CodePipeline(this, "Pipeline", {
      pipelineName: `CodePipeline`,
      selfMutation: true,
      crossAccountKeys: true,
      synthCodeBuildDefaults: {
        rolePolicy: [
          // @desc Policy to allow CodeBuild to use CodeArtifact
          // @external https://docs.aws.amazon.com/codeartifact/latest/ug/using-npm-packages-in-codebuild.html
          new cdk.aws_iam.PolicyStatement({
            actions: [
              "codeartifact:GetAuthorizationToken",
              "codeartifact:GetRepositoryEndpoint",
              "codeartifact:ReadFromRepository",
            ],
            resources: ["*"],
          }),
          new cdk.aws_iam.PolicyStatement({
            actions: ["sts:GetServiceBearerToken"],
            resources: ["*"],
            conditions: {
              StringEquals: {
                "sts:AWSServiceName": "codeartifact.amazonaws.com",
              },
            },
          }),
        ],
      },
      synth: new pipelines.ShellStep("Synth", {
        input: pipelines.CodePipelineSource.codeCommit(source, "master"),
        installCommands: [
          "cd $CODEBUILD_SRC_DIR/deployment",
          "npm install -g typescript",
          "npm run co:login",
          "npm i",
        ],
        env: {
          stage: props.env.stage,
        },
        envFromCfnOutputs: {
          // TODO: cfn outputs need to go here!
          // CcpUrlOutput: TestStage.CcpUrlOutput,
          // loginUrlOutput: TestStage.LoginUrlOutput,
          // regionOutput: TestStage.RegionOutput,
          // apiOutput: TestStage.ApiOutput
        },
        commands: [
          "cd $CODEBUILD_SRC_DIR/frontend",
          "pwd",
          "apt-get install jq -y",
          "chmod +x ./generate-config.sh",
          "npm i",
          "npm run build-prod",
          "pwd",
          "cat ./src/config-prod.json",
          "cd ../deployment",
          "npx cdk synth",
        ],
        primaryOutputDirectory: "$CODEBUILD_SRC_DIR/deployment/cdk.out", // $CODEBUILD_SRC_DIR = starts root path
      }),
    });

    /************ Initialize Test Stack & Add Stage************/
    const TestStage = new Stages(this, "TestStage", {
      env: { account: "***********", region: "us-east-1", stage: "test" },
    }); // Aspen Sandbox
    Pipeline.addStage(TestStage);

    /************ Initialize Prod Stack & Add Stage ************/
    const ProdStage = new Stages(this, "ProdStage", {
      env: { account: "***********", region: "us-east-1", stage: "prod" },
    }); // Aspen Sandbox
    Pipeline.addStage(ProdStage);

    /************ Build Pipeline ************/

    Pipeline.buildPipeline();

    /************ Manual Approve Stage ************/

    const ApproveStage = Pipeline.pipeline.addStage({
      stageName: "PromoteToProd",
      placement: {
        justAfter: Pipeline.pipeline.stage("TestStage"),
      },
    });

    ApproveStage.addAction(
      new cdk.aws_codepipeline_actions.ManualApprovalAction({
        actionName: "Approve",
        additionalInformation: "Approve this deployment for production.",
      })
    );
  }
  /****/
}
```


问:
Parametrizing Rust trait on list of types?
I'm toying with an idea for a computation-graph based game engine. The gist is that each abstract concept (Player, Map, Enemy, Spaceship, etc) is a node in a DAG. The nodes themselves are simply Rust types which implement a "Component" interface which specifies how

a. How members of the Component are created/deleted/retrieved

b. What other Components the Component relies on (ie, what are the dependencies?)

c. How to update a member of the Component

Expressing (a) is easy enough: here's a trait which (I think :) specifies this behavior

```<code>pub trait Component {
    type KeyType: Copy; // Each member of a Component is associated with a key

    fn Add(_: Self::KeyType) -> bool;
    fn Delete(_: Self::KeyType) -> bool;
    fn Get<'a>(_: Self::KeyType) -> Option<&'a Self>;
    fn GetAll<'a>() -> dyn Iterator<Item = (Self::KeyType, &'a Self)>;

    // TODO This block will be described next
}
</code>```

An implementation is easy to imagine: an impl corresponding to the Player Component could just use player IDs (u32, for instance) for keys, and then basically implement all the other functions using some static(global) hash map. So far so good.

(b) and (c) are harder. I'd like to express through the trait

A Component can "rely" on (members of) other Components

A member of a Component can specify which members of its dependencies that it requires to update itself.

Each member of a Component implements a function using the results of (2) to update itself.

In other words, I want the TODO block from above to express to something like this

```<code>// (a) Each Component specifies its dependencies as a list (set) of Components. This list is fixed at compile time.
type Dependencies: [Component;]

// For each Dependency, a member of the Component can specify a list of members that it needs. The keys of the returned map are fixed at compile time, but the requested members can always change
fn GetDependencyMembers(&mut self) -> Map<DepType d, List<d::KeyType>>

// Each Component must implement an "update" function which looks like the following.
// "N" varies from component to component.
fn Update<'a>(
    List&'a Dep1Type>,
    ...
    List<&'a DepNType>,
)
</code>```

Unfortunately, my meager rust isn't adequate to translate this into working code. Could someone with more knowledge show me how I should write this?

Body:
I'm toying with an idea for a computation-graph based game engine. The gist is that each abstract concept (Player, Map, Enemy, Spaceship, etc) is a node in a DAG. The nodes themselves are simply Rust types which implement a "Component" interface which specifies how

a. How members of the Component are created/deleted/retrieved

b. What other Components the Component relies on (ie, what are the dependencies?)

c. How to update a member of the Component

Expressing (a) is easy enough: here's a trait which (I think :) specifies this behavior

pub trait Component {
    type KeyType: Copy; // Each member of a Component is associated with a key

    fn Add(_: Self::KeyType) -> bool;
    fn Delete(_: Self::KeyType) -> bool;
    fn Get<'a>(_: Self::KeyType) -> Option<&'a Self>;
    fn GetAll<'a>() -> dyn Iterator<Item = (Self::KeyType, &'a Self)>;

    // TODO This block will be described next
}

An implementation is easy to imagine: an impl corresponding to the Player Component could just use player IDs (u32, for instance) for keys, and then basically implement all the other functions using some static(global) hash map. So far so good.

(b) and (c) are harder. I'd like to express through the trait

A Component can "rely" on (members of) other Components

A member of a Component can specify which members of its dependencies that it requires to update itself.

Each member of a Component implements a function using the results of (2) to update itself.

In other words, I want the TODO block from above to express to something like this

// (a) Each Component specifies its dependencies as a list (set) of Components. This list is fixed at compile time.
type Dependencies: [Component;]

// For each Dependency, a member of the Component can specify a list of members that it needs. The keys of the returned map are fixed at compile time, but the requested members can always change
fn GetDependencyMembers(&mut self) -> Map<DepType d, List<d::KeyType>>

// Each Component must implement an "update" function which looks like the following.
// "N" varies from component to component.
fn Update<'a>(
    List&'a Dep1Type>,
    ...
    List<&'a DepNType>,
)

Unfortunately, my meager rust isn't adequate to translate this into working code. Could someone with more knowledge show me how I should write this?


问:
JDBI how to bind table valued parameter for stored procedure
I have a stored Procedure which takes table valued parameter as input. I am using JDBI in my SpringBoot Application. How do I bind TVP to stored procedure.
This is my Stored Procedure.

```<code>    CREATE PROCEDURE exampleSP
    @country char(2),
    @store int,
    @tags as dbo.udtTags READONLY,
    AS
    BEGIN
    select * from sales where country = @country AND store = @store AND id in (select ids from     @tags)
    END
</code>```

This is my User Defined Table.

```<code>    CREATE TYPE udtTags AS TABLE
        (
             ids INT
        )
    GO
</code>```

This is what I have tried:

```<code>List<Integer> idList = new ArrayList<>();
idList.add(1);
idList.add(2);
return jdbi.withHandle(handle -> {
OutParameters result = handle.createCall("{call exampleSP(:country, :store, :ids)}")
       .bind("country", "US")
       .bind("store", 1)
       .bindList("ids", idList)
       .invoke();
return null;
});
</code>```

This is giving error:
org.jdbi.v3.core.statement.UnableToCreateStatementException: Missing named parameter 'ids' in binding:{positional:{}, named:{__ids_1:1,store:1,country:US,__ids_0:2, finder:[]}

Body:
I have a stored Procedure which takes table valued parameter as input. I am using JDBI in my SpringBoot Application. How do I bind TVP to stored procedure.
This is my Stored Procedure.

    CREATE PROCEDURE exampleSP
    @country char(2),
    @store int,
    @tags as dbo.udtTags READONLY,
    AS
    BEGIN
    select * from sales where country = @country AND store = @store AND id in (select ids from     @tags)
    END

This is my User Defined Table.

    CREATE TYPE udtTags AS TABLE
        (
             ids INT
        )
    GO

This is what I have tried:

List<Integer> idList = new ArrayList<>();
idList.add(1);
idList.add(2);
return jdbi.withHandle(handle -> {
OutParameters result = handle.createCall("{call exampleSP(:country, :store, :ids)}")
       .bind("country", "US")
       .bind("store", 1)
       .bindList("ids", idList)
       .invoke();
return null;
});

This is giving error:
org.jdbi.v3.core.statement.UnableToCreateStatementException: Missing named parameter 'ids' in binding:{positional:{}, named:{__ids_1:1,store:1,country:US,__ids_0:2, finder:[]}


问:
Is there a chrome extension to setup proxies and switch between them using a programming language?
I'm developing a selenium application that uses undetected chromedriver as a web driver, I want to use the application with a proxy, undetected chromedriver doesn't really have a functional way to add a proxy, I am wondering if there's a chrome extension that allows you to add a proxy using a programming language, I'm developing my selenium application in Python. Otherwise, I'll appreciate any way to implement a proxy to my application efficiently. Thanks for your time.

I tried selenium-wire, but the web drivers are missing quite so many classes and do behave poorly. I also tried a lot of chrome extensions, they require you to use their UI. I also tried a project I found at github but it doesn't support undetected chromedriver. There's a chrome extension that does what I need according to its description but it's not functional.


问:
Django logging does not work inside views and viewsets
Can someone please help me understand why django does not print logging messages that I put inside views methods?
When I call logger.debug() from outside views it works correctly

my views.py

import logging

logger = logging.getLogger(__name__)
logger.debug('THIS LOGGING MESSSAGE SHOWS UP IN LOGS')

class RequestGetResultViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin):
    permission_classes = (IsAuthenticated,)
    serializer_class = serializers.RequestGetResultSerializer
    queryset = Request.objects.all()

    def get_queryset(self):]
        logger.debug('THIS LOGGING MESSSAGE DOES NOT SHOW UP')
        return self.queryset.filter(user=self.request.user.id)

    @action(methods=['get'], detail=True, renderer_classes=(PassthroughRenderer,))
    def download(self, *args, **kwargs):
        logger.debug('THIS LOGGING MESSSAGE DOES NOT SHOW UP')
        # working code here
        return response
```
<p>my settings.py:</p>
<pre class="lang-py prettyprint-override"><code>LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'DEBUG' ,
    },

}

</code>```

Body:
Can someone please help me understand why django does not print logging messages that I put inside views methods?
When I call logger.debug() from outside views it works correctly

my views.py

import logging

logger = logging.getLogger(__name__)
logger.debug('THIS LOGGING MESSSAGE SHOWS UP IN LOGS')

class RequestGetResultViewSet(viewsets.GenericViewSet, mixins.RetrieveModelMixin):
    permission_classes = (IsAuthenticated,)
    serializer_class = serializers.RequestGetResultSerializer
    queryset = Request.objects.all()

    def get_queryset(self):]
        logger.debug('THIS LOGGING MESSSAGE DOES NOT SHOW UP')
        return self.queryset.filter(user=self.request.user.id)

    @action(methods=['get'], detail=True, renderer_classes=(PassthroughRenderer,))
    def download(self, *args, **kwargs):
        logger.debug('THIS LOGGING MESSSAGE DOES NOT SHOW UP')
        # working code here
        return response

my settings.py:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'DEBUG' ,
    },

}


问:
points inverting at focal point (3d projection in python)
I'm working on making a 3d engine but have an issue with the projection.

When I'm projecting the x,y points it gets inverted when behind the camera.

I have found this issue on other formulas, and couldn't find a solution.

Here's my code for the projection. It may be short but I figure this is the issue.

See figure for points inversion:

```<code>world_coordinate=np.array([[*coordinate,1]])
        camera_coordinate = np.dot(camera.extrinsic, world_coordinate.T)
        camera_coordinate[0] *= 1
        tmp = camera_coordinate[1].copy()
        camera_coordinate[1] = camera_coordinate[2]
        camera_coordinate[2] = tmp
        image_coordinate = np.dot(camera.intrinsic, camera_coordinate)
        image_coordinate /= image_coordinate[2]
        x,y = image_coordinate.tolist()[0][0].__round__(),image_coordinate.tolist()[1][0].__round__()
</code>```

My GitHub repository:
https://github.com/roberto-e-torres/3d-engine/releases/tag/non-production

Body:
I'm working on making a 3d engine but have an issue with the projection.

When I'm projecting the x,y points it gets inverted when behind the camera.

I have found this issue on other formulas, and couldn't find a solution.

Here's my code for the projection. It may be short but I figure this is the issue.

See figure for points inversion:

world_coordinate=np.array([[*coordinate,1]])
        camera_coordinate = np.dot(camera.extrinsic, world_coordinate.T)
        camera_coordinate[0] *= 1
        tmp = camera_coordinate[1].copy()
        camera_coordinate[1] = camera_coordinate[2]
        camera_coordinate[2] = tmp
        image_coordinate = np.dot(camera.intrinsic, camera_coordinate)
        image_coordinate /= image_coordinate[2]
        x,y = image_coordinate.tolist()[0][0].__round__(),image_coordinate.tolist()[1][0].__round__()

My GitHub repository:
https://github.com/roberto-e-torres/3d-engine/releases/tag/non-production


问:
how to change hwnd attributes
```<code>const HWND window = CreateWindowExW(
    WS_EX_TOPMOST |WS_EX_TRANSPARENT |WS_EX_LAYERED,
    wc.lpszClassName,
    L"Sexy window frfr",
    WS_POPUP,
    0, 0,
    GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
    nullptr,
    nullptr,
    wc.hInstance,
    nullptr);
</code>```

I'm trying to set the WS_EX_TRANSPARENT to off when I click VK_INSERT but I can't find any function that does that.

Title: how to change hwnd attributes

Body:
const HWND window = CreateWindowExW(
    WS_EX_TOPMOST |WS_EX_TRANSPARENT |WS_EX_LAYERED,
    wc.lpszClassName,
    L"Sexy window frfr",
    WS_POPUP,
    0, 0,
    GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
    nullptr,
    nullptr,
    wc.hInstance,
    nullptr);

I'm trying to set the WS_EX_TRANSPARENT to off when I click VK_INSERT but I can't find any function that does that.


问:
Why do we need closures when we have built-in objects in Javascript?
My current understanding is that closures are a way for functional programming languages / languages with first class functions to create an object like entity (Some data and a way to act on that data)

Now, in Javascript, we already have built-in objects, and can simply use Object.create(somePrototype) to create an object. Functions are themselves objects in Javascript.

So why do we use closures? Why can't (React)Hooks etc be built using built-in objects?


问:
Header with centered text and button aligned to the right
I want to have a header on my website with some text which is centred in the page. There should be a button on the same height/line which is aligned to the right.

This is what I've got currently:

And this is defined like this:

Please Center Me

    search

```
<pre class="lang-css prettyprint-override"><code>header {
    width: 100%;
    height: auto;
    background-color: #1DA87F;
    color: #EBEF8E;
    font-size: 1.5em;
    display: flex;
}

header h1 {
    margin: auto;
    align-self: center;
}

.material-icons {
    font-size: 1.5em;
    margin: auto;
    align-self: flex-end;
}
</code>```

As you can see, the "Please Center Me" text is not really centered, it's being off-set by the search text (icon).

Body:
I want to have a header on my website with some text which is centred in the page. There should be a button on the same height/line which is aligned to the right.

This is what I've got currently:

And this is defined like this:

Please Center Me

    search

header {
    width: 100%;
    height: auto;
    background-color: #1DA87F;
    color: #EBEF8E;
    font-size: 1.5em;
    display: flex;
}

header h1 {
    margin: auto;
    align-self: center;
}

.material-icons {
    font-size: 1.5em;
    margin: auto;
    align-self: flex-end;
}

As you can see, the "Please Center Me" text is not really centered, it's being off-set by the search text (icon).


问:
springboot socket communications
I've been trying to make my own gps tracker server using springboot. There is a standalone project called Traccar and they use  their own methods to create connections but I can't integrate the netty framework in springboot; specially for the different handlers methods.

For example if any user send by post method the command to use, my server would be capable to take that command and send to the gps connected by socket but here is my problem because any time a channel is open, the message to send convert in null from the POST method to the writeFlush().

Any one knows how to intercept the method to take the command and send to the socket?

Title: springboot socket communications


问:
Cannot get value of session from redis
I'm trying to get a value from redis to see what value is stored against a session (using express-session).

If I do:

```<code>❯ redis-cli
127.0.0.1:6379> KEYS *
1) "sess:NhtX2aESQFU3YAqfaKawNWC7FS6GY9SM"
2) "sess:DkVqgapP6dwrAElp0AENKY1j1iTDHbxz"
127.0.0.1:6379> GET "sess:DkVqgapP6dwrAElp0AENKY1j1iTDHbxz"
(nil)
127.0.0.1:6379> GET 'sess:DkVqgapP6dwrAElp0AENKY1j1iTDHbxz'
(nil)
127.0.0.1:6379> GET `sess:DkVqgapP6dwrAElp0AENKY1j1iTDHbxz`
(nil)
127.0.0.1:6379>
</code>```

I'm sure it's something basic I'm doing wrong. I've used different delimiters (single/double quotes, etc.) but can't get anything. Is it the datatype of what's stored there??

Title: Cannot get value of session from redis

Body:
I'm trying to get a value from redis to see what value is stored against a session (using express-session).

If I do:

❯ redis-cli
127.0.0.1:6379> KEYS *
1) "sess:NhtX2aESQFU3YAqfaKawNWC7FS6GY9SM"
2) "sess:DkVqgapP6dwrAElp0AENKY1j1iTDHbxz"
127.0.0.1:6379> GET "sess:DkVqgapP6dwrAElp0AENKY1j1iTDHbxz"
(nil)
127.0.0.1:6379> GET 'sess:DkVqgapP6dwrAElp0AENKY1j1iTDHbxz'
(nil)
127.0.0.1:6379> GET `sess:DkVqgapP6dwrAElp0AENKY1j1iTDHbxz`
(nil)
127.0.0.1:6379>

I'm sure it's something basic I'm doing wrong. I've used different delimiters (single/double quotes, etc.) but can't get anything. Is it the datatype of what's stored there??


问:
Apply a PCA to dataframe in a rolling manner
I'd like to apply PCA to a dataframe on 30 days windows.
In other words, everyday a the lasted 30 days of data are used to compute the PCA.

Idea

```<code>df.rolling(30).apply(make_pca)
</code>```

Will not work because it rolls over columns one after the other not really using the whole dataframe

Unsatisfying solution

```<code>df.iloc[:, 0].rolling(30).apply(lambda x: make_pca(df.loc[x.index]))
</code>```

Works but kinda looks ugly.
Looping over the df would work as well but it's quite slow / ugly

Any better idea?

Thanks

Body:
I'd like to apply PCA to a dataframe on 30 days windows.
In other words, everyday a the lasted 30 days of data are used to compute the PCA.

Idea

df.rolling(30).apply(make_pca)

Will not work because it rolls over columns one after the other not really using the whole dataframe

Unsatisfying solution

df.iloc[:, 0].rolling(30).apply(lambda x: make_pca(df.loc[x.index]))

Works but kinda looks ugly.
Looping over the df would work as well but it's quite slow / ugly

Any better idea?

Thanks


问:
Python routing traffic through tor
i am trying to make a script that routes my traffic through TOR.But an error occurred i can't solve.

script's code:

```<code>import socket
import socks
import stem.process
import requests
import time

def start_tor(tor_path='C:\\PATH-TO-TOR\\TorBrowser\\Tor\\tor.exe'):
  tor_process = stem.process.launch_tor_with_config(
    tor_cmd=tor_path,
    config = {
      'SocksPort': str(9050)
    },
  )
  return tor_process

def create_connection(address, timeout=None, source_address=None):
  sock = socks.socksocket()
  sock.connect(address)
  return sock

# start TOR
tor_process = start_tor('C:\\PATH-TO-TOR\\TorBrowser\\Tor\\tor.exe')

# patch the socket module
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
socket.create_connection = create_connection

print('Rooting all your device traffic through TOR Relays')
while True:
    print('TOR is running')
    response = requests.get("http://ipinfo.io/ip")
    print("Connected to:", response.text)
    time.sleep(10)
    tor_process.signal(stem.Signal.NEWNYM)
</code>```

the error that it prints is:

```<code>File "c:\Users\User\Documents\test3.py", line 36, in <module>
tor_process.signal(stem.Signal.NEWNYM)
AttributeError: 'Popen' object has no attribute 'signal'
</code>```

Basically in the line 36 i want to change ip (every 3 minutes as i have in my code)

Title: Python routing traffic through tor

Body:
i am trying to make a script that routes my traffic through TOR.But an error occurred i can't solve.

script's code:

import socket
import socks
import stem.process
import requests
import time

def start_tor(tor_path='C:\\PATH-TO-TOR\\TorBrowser\\Tor\\tor.exe'):
  tor_process = stem.process.launch_tor_with_config(
    tor_cmd=tor_path,
    config = {
      'SocksPort': str(9050)
    },
  )
  return tor_process

def create_connection(address, timeout=None, source_address=None):
  sock = socks.socksocket()
  sock.connect(address)
  return sock

# start TOR
tor_process = start_tor('C:\\PATH-TO-TOR\\TorBrowser\\Tor\\tor.exe')

# patch the socket module
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
socket.create_connection = create_connection

print('Rooting all your device traffic through TOR Relays')
while True:
    print('TOR is running')
    response = requests.get("http://ipinfo.io/ip")
    print("Connected to:", response.text)
    time.sleep(10)
    tor_process.signal(stem.Signal.NEWNYM)

the error that it prints is:

File "c:\Users\User\Documents\test3.py", line 36, in <module>
tor_process.signal(stem.Signal.NEWNYM)
AttributeError: 'Popen' object has no attribute 'signal'

Basically in the line 36 i want to change ip (every 3 minutes as i have in my code)


问:
How can I use Tippy JS in Interactive mode while selecting text with mousemove?
I'm trying to show an interactive menu while user is selecting text.

The problem is that in certain instances, the tippy div ends up interfering with the users selection.

Here is a video showing the problem:
https://www.screencast.com/t/MC5eUd61u4Uu

HTML

```<code><div id="selection-ref"></div>
<p><br></p>
<p>Lorem ipsum dolor</p>
<p>d</p>
<p>d</p>
<p>s</p>
<p>fdsaf</p>
<p>dsaf</p>
</code>```

CSS

```<code>#selection-ref {
  position: absolute;

  /* debug only styles */
  background: rgba(200,0,0,0.2);
  pointer-events: none;
}
</code>```

JS

```<code>const selectionRef = document.querySelector('#selection-ref')

const [instance] = tippy('#selection-ref', {
  content: 'tooltip',
  sticky: true,
  interactive: true,
  appendTo: () => document.body
})

// inspired by https://jsfiddle.net/joktrpkz/7/
const selection = window.getSelection()

window.addEventListener('mousemove', (event) => {
  if (!selection.isCollapsed) {
    const { left, top, width, height } = selection.getRangeAt(0).getBoundingClientRect()

    selectionRef.style.left = `${left}px`
    selectionRef.style.top = `${top}px`
    selectionRef.style.width = `${width}px`
    selectionRef.style.height = `${height}px`

    instance.show()
  }
})

window.addEventListener('mousedown', (event) => {
  instance.hide()
})
</code>```

Here is a codepen:
https://codepen.io/temilson/pen/MWBJVpG

There is absolutely no problem when tippy is NOT in interactive mode.

I've tried adding this to my tippy props without any change:

appendTo: () => document.body

Body:
I'm trying to show an interactive menu while user is selecting text.

The problem is that in certain instances, the tippy div ends up interfering with the users selection.

Here is a video showing the problem:
https://www.screencast.com/t/MC5eUd61u4Uu

HTML

Lorem ipsum dolor

d

d

s

fdsaf

dsaf

CSS

#selection-ref {
  position: absolute;

  /* debug only styles */
  background: rgba(200,0,0,0.2);
  pointer-events: none;
}

JS

const selectionRef = document.querySelector('#selection-ref')

const [instance] = tippy('#selection-ref', {
  content: 'tooltip',
  sticky: true,
  interactive: true,
  appendTo: () => document.body
})

// inspired by https://jsfiddle.net/joktrpkz/7/
const selection = window.getSelection()

window.addEventListener('mousemove', (event) => {
  if (!selection.isCollapsed) {
    const { left, top, width, height } = selection.getRangeAt(0).getBoundingClientRect()

    selectionRef.style.left = `${left}px`
    selectionRef.style.top = `${top}px`
    selectionRef.style.width = `${width}px`
    selectionRef.style.height = `${height}px`

    instance.show()
  }
})

window.addEventListener('mousedown', (event) => {
  instance.hide()
})

Here is a codepen:
https://codepen.io/temilson/pen/MWBJVpG

There is absolutely no problem when tippy is NOT in interactive mode.

I've tried adding this to my tippy props without any change:

appendTo: () => document.body


问:
Malformed UTF-8 characters, possibly incorrectly encoded (works with other columns)
I have saved foreign text in database under name column in users table and it throws Malformed UTF-8 errors but strange thing that is happening when I swap the values with another column only then its working.

name
username

村田篤郎
happiness

John Doe
jdoe

the above User table structure causes error while if I swap as shown below it works.

name
username

happiness
村田篤郎

John Doe
jdoe

Database collation is `utf8mb4_0900_ai_ci` and User table has (name =utf8_unicode_ci , username = utf8_unicode_ci) collation.

Laravel eloquent query

```<code>User::withTrashed()->notAdmin()->select('id', 'email', 'name', 'profile_picture', 'created_at', 'deleted_at', 'is_active', 'email_verified_at', 'provider')
            ->withCount(['campaigns', 'inactivecampaigns', 'activecampaigns'])
            ->orderBy('created_at')
            ->get();
</code>```

User.php

```<code>class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    protected  $keyType = 'string';
    public $incrementing = false;
...
</code>```

config/database.php

```<code><?php
return [
    'connections' => [
        'mysql' => [
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ]

    ]
];
</code>```

When swapped it worked and my guess is name column is serializing from somewhere else but I couldn't find anything within code.

Body:
I have saved foreign text in database under name column in users table and it throws Malformed UTF-8 errors but strange thing that is happening when I swap the values with another column only then its working.

name
username

村田篤郎
happiness

John Doe
jdoe

the above User table structure causes error while if I swap as shown below it works.

name
username

happiness
村田篤郎

John Doe
jdoe

Database collation is `utf8mb4_0900_ai_ci` and User table has (name =utf8_unicode_ci , username = utf8_unicode_ci) collation.

Laravel eloquent query

User::withTrashed()->notAdmin()->select('id', 'email', 'name', 'profile_picture', 'created_at', 'deleted_at', 'is_active', 'email_verified_at', 'provider')
            ->withCount(['campaigns', 'inactivecampaigns', 'activecampaigns'])
            ->orderBy('created_at')
            ->get();

User.php

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    protected  $keyType = 'string';
    public $incrementing = false;
...

config/database.php

<?php
return [
    'connections' => [
        'mysql' => [
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ]

    ]
];

When swapped it worked and my guess is name column is serializing from somewhere else but I couldn't find anything within code.


问:
Extracting/Decompiling Multiple Python Files Using PyDecipher
I have an exe written in Python and Compiled using PyInstaller.
However, I would like to reverse it into the original Python File(s).

I successfully managed to decompile the file on Linux using PyDecipher, but the problem is, I only see one file from the project, plus a bunch of other unrelated files, and the other project files are amiss.
The structure was like:

```<code>Project
  includes
    database.py
    convertor.py
  records
    names.csv
  app.py
  libraries.py
  config.py
</code>```

As can be seen above, app.py imports config.py and libraries.py which also in turn imports files from includes directory.
Eventually, I created .exe using PyInstaller, but when I extract the exe using PyDecipher, only app.py was found. The rest are nowhere to be seen.

I've been scurrying the web, but I don't seem to find any satisfactory answer.

Any help will be handsomely appreciated.
Thanks in advance.

Body:
I have an exe written in Python and Compiled using PyInstaller.
However, I would like to reverse it into the original Python File(s).

I successfully managed to decompile the file on Linux using PyDecipher, but the problem is, I only see one file from the project, plus a bunch of other unrelated files, and the other project files are amiss.
The structure was like:

Project
  includes
    database.py
    convertor.py
  records
    names.csv
  app.py
  libraries.py
  config.py

As can be seen above, app.py imports config.py and libraries.py which also in turn imports files from includes directory.
Eventually, I created .exe using PyInstaller, but when I extract the exe using PyDecipher, only app.py was found. The rest are nowhere to be seen.

I've been scurrying the web, but I don't seem to find any satisfactory answer.

Any help will be handsomely appreciated.
Thanks in advance.


问:
Elasticsearch Pagination on composite aggregation gives wrong results
I'm having such kind of problem on defining composite aggregation for paginating the results.

```<code>    CompositeAggregationBuilder aggregationBuilder = AggregationBuilders
                    .composite(aggrField, List.of(new TermsValuesSourceBuilder(aggrField).field(aggrField)))
                    .aggregateAfter(Map.of("keyword", aggrField))
                    .size(bucketListInfo.getTopResultsCount());
            searchSourceBuilder
                    .from(2)
                    .size(4)
                    .aggregation(aggregationBuilder);

final SearchRequest searchRequest = new SearchRequest(bucketListInfo.getIndexName())
                .source(searchSourceBuilder);
        try {
            final SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            return processBucketsFromResponse(bucketListInfo, response);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
</code>```

the problem comes this way:

when I getting the response, it contains all hits, not only paginated ones, say if I specify the from param as 2, and size param as 4 and expect that it will give me the results starting from second page with the size of 4, but it gives me all records, no matter what pagination params I have specified.

when I add this

.aggregateAfter(Map.of("keyword", aggrField))
I get this kind of error :

[type=illegal_argument_exception, reason=Missing value for [after.[my-aggr-field].keyword]]];

So any workaround of this, any suggestions please.

Body:
I'm having such kind of problem on defining composite aggregation for paginating the results.

    CompositeAggregationBuilder aggregationBuilder = AggregationBuilders
                    .composite(aggrField, List.of(new TermsValuesSourceBuilder(aggrField).field(aggrField)))
                    .aggregateAfter(Map.of("keyword", aggrField))
                    .size(bucketListInfo.getTopResultsCount());
            searchSourceBuilder
                    .from(2)
                    .size(4)
                    .aggregation(aggregationBuilder);

final SearchRequest searchRequest = new SearchRequest(bucketListInfo.getIndexName())
                .source(searchSourceBuilder);
        try {
            final SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            return processBucketsFromResponse(bucketListInfo, response);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }

the problem comes this way:

when I getting the response, it contains all hits, not only paginated ones, say if I specify the from param as 2, and size param as 4 and expect that it will give me the results starting from second page with the size of 4, but it gives me all records, no matter what pagination params I have specified.

when I add this

.aggregateAfter(Map.of("keyword", aggrField))
I get this kind of error :

[type=illegal_argument_exception, reason=Missing value for [after.[my-aggr-field].keyword]]];

So any workaround of this, any suggestions please.


问:
External Table between Docker SQL Server and Docker MongoDB
I have a container with SQL (following this example https://github.com/croblesm/mssql-polybase)

I have a container with MongoDB running as normal.

I need to create a external table to consume mongoDB data and create a report.

I did follow this instructions https://learn.microsoft.com/en-us/sql/relational-databases/polybase/polybase-configure-mongodb?view=sql-server-ver16

but I'm getting an error on SQL

```<code>Msg 7320, Level 16, State 110, Line 2
Cannot execute the query "Remote Query" against OLE DB provider "MSOLEDBSQL" for linked server "(null)". External access operation failed because the location URI is invalid. Revise the URI and try again.
</code>```

Here are the networkSettings of my Mongo Container:

```<code> "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "fd848692fbdb9ba61c5bbbe774d05955bef0cca850e2bb137e54323fede0b5c1",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "27017/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "27017"
                    }
                ]
            },
            "SandboxKey": "/var/run/docker/netns/fd848692fbdb",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "",
            "Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
            "MacAddress": "",
            "Networks": {
                "oms_dev_setup_default": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": [
                        "mongodb",
                        "1eb3634590ea"
                    ],
                    "NetworkID": "0f740644bac8ee38bf6e237c31e718d524d1cb74932c4426744f1820aa51abb1",
                    "EndpointID": "349f1b5717f0fd8a401b518d62846c53166e4d729843e2fd162c05baec32b82a",
                    "Gateway": "172.18.0.1",
                    "IPAddress": "172.18.0.4",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:12:00:04",
                    "DriverOpts": null
                }
            }
        }
</code>```

I think the problem is related with the configuration of the SQL EXTERNAL DATA SOURCE.

```<code>ALTER EXTERNAL DATA SOURCE MongoDBSource
SET LOCATION = 'mongodb://172.18.0.1:27017'', --- Host CREDENTIAL = MongoDBConnection,CONNECTION_OPTIONS = "ssl=false;"';
</code>```

I did try several combinations but nothing is working

Body:
I have a container with SQL (following this example https://github.com/croblesm/mssql-polybase)

I have a container with MongoDB running as normal.

I need to create a external table to consume mongoDB data and create a report.

I did follow this instructions https://learn.microsoft.com/en-us/sql/relational-databases/polybase/polybase-configure-mongodb?view=sql-server-ver16

but I'm getting an error on SQL

Msg 7320, Level 16, State 110, Line 2
Cannot execute the query "Remote Query" against OLE DB provider "MSOLEDBSQL" for linked server "(null)". External access operation failed because the location URI is invalid. Revise the URI and try again.

Here are the networkSettings of my Mongo Container:

 "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "fd848692fbdb9ba61c5bbbe774d05955bef0cca850e2bb137e54323fede0b5c1",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "27017/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "27017"
                    }
                ]
            },
            "SandboxKey": "/var/run/docker/netns/fd848692fbdb",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "",
            "Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
            "MacAddress": "",
            "Networks": {
                "oms_dev_setup_default": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": [
                        "mongodb",
                        "1eb3634590ea"
                    ],
                    "NetworkID": "0f740644bac8ee38bf6e237c31e718d524d1cb74932c4426744f1820aa51abb1",
                    "EndpointID": "349f1b5717f0fd8a401b518d62846c53166e4d729843e2fd162c05baec32b82a",
                    "Gateway": "172.18.0.1",
                    "IPAddress": "172.18.0.4",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:12:00:04",
                    "DriverOpts": null
                }
            }
        }

I think the problem is related with the configuration of the SQL EXTERNAL DATA SOURCE.

ALTER EXTERNAL DATA SOURCE MongoDBSource
SET LOCATION = 'mongodb://172.18.0.1:27017'', --- Host CREDENTIAL = MongoDBConnection,CONNECTION_OPTIONS = "ssl=false;"';

I did try several combinations but nothing is working


问:
Display data retrieved from mysql in piechart
I need some help in creating a pie chart in react for the data retrieved from mysql database.

App.js code :

```<code>import React , { PureComponent } from 'react';
import {useState , useEffect } from 'react';
import './App.css';
import { PieChart , Pie , Tooltip } from "recharts";

function App() {

  const [category, setCategory] = useState([]);
  useEffect(()=>{
    const getDbData = async ()=>{
      const getA = await fetch('http://localhost:3001/posts/');
      const getData = await getA.json();
      setCategory(getData);
      console.log(getData);
      // console.log(data);
    }
    getDbData();
  },[])

  return (
    <div className="App">
      <h1>Hello World!!</h1>
      <h2>My PieChart</h2>
        <PieChart width={400} height={400}>
          <Pie dataKey="value" isAnimationActive={false}
          data={category}
            cx="50%" cy="50%" outerRadius={80} fill="#8884d8"
            label
          />
          <Tooltip />
        </PieChart>
    </div>
  );
}

export default App;
</code>```

Also I have installed all the dependencies required but still pie chart is not created for the data which I have fetched from database.

Server.js :

```<code>const express = require("express");
const app = express();
const mysql = require('mysql');
const cors = require('cors');

app.use(cors());
app.use(express.json());

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

db.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
  });

app.get('/posts', (req, res) => {
  db.query("SELECT empname , empage FROM employee;", (err, results, fields) => {
    if(err) throw err;
    res.send(results);
  });
});

app.listen(3001 ,(error)=>{
    if (error) throw error ;
    console.log("Server is running on port 3001");
})
</code>```

When I hardcode data and try to display in pie chart then it works But it is not working when I am trying to display the data which I have fetched from database.

Body:
I need some help in creating a pie chart in react for the data retrieved from mysql database.

App.js code :

import React , { PureComponent } from 'react';
import {useState , useEffect } from 'react';
import './App.css';
import { PieChart , Pie , Tooltip } from "recharts";

function App() {

  const [category, setCategory] = useState([]);
  useEffect(()=>{
    const getDbData = async ()=>{
      const getA = await fetch('http://localhost:3001/posts/');
      const getData = await getA.json();
      setCategory(getData);
      console.log(getData);
      // console.log(data);
    }
    getDbData();
  },[])

  return (

Hello World!!

My PieChart

        <PieChart width={400} height={400}>
          <Pie dataKey="value" isAnimationActive={false}
          data={category}
            cx="50%" cy="50%" outerRadius={80} fill="#8884d8"
            label
          />
          <Tooltip />
        </PieChart>

  );
}

export default App;

Also I have installed all the dependencies required but still pie chart is not created for the data which I have fetched from database.

Server.js :

const express = require("express");
const app = express();
const mysql = require('mysql');
const cors = require('cors');

app.use(cors());
app.use(express.json());

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

db.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
  });

app.get('/posts', (req, res) => {
  db.query("SELECT empname , empage FROM employee;", (err, results, fields) => {
    if(err) throw err;
    res.send(results);
  });
});

app.listen(3001 ,(error)=>{
    if (error) throw error ;
    console.log("Server is running on port 3001");
})

When I hardcode data and try to display in pie chart then it works But it is not working when I am trying to display the data which I have fetched from database.


问:
easy3d/core/export.h: No such file or directory
I am trying to use Easy3D library for visualization.I installed library correctly(at least got no errors). I linked it correctly in CmakeLists.txt(No errors here). I try to test it but got error.

Source code:

```<code>#include <iostream>
#include <easy3d/core/surface_mesh.h>
#include <easy3d/core/surface_mesh_builder.h>
#include <easy3d/util/initializer.h>

int main(){
   std::cout << "hi" << std::endl;
   return 0;
};

</code>```

And the error is :

```<code>
fatal error: easy3d/core/export.h: No such file or directory
[build]    30 | #include <easy3d/core/export.h>
</code>```

I checked the folders and there is no export.h anywhere(I could not find it). It is included in some of the functions aswell. What did I do wrong?

Body:
I am trying to use Easy3D library for visualization.I installed library correctly(at least got no errors). I linked it correctly in CmakeLists.txt(No errors here). I try to test it but got error.

Source code:

#include <iostream>
#include <easy3d/core/surface_mesh.h>
#include <easy3d/core/surface_mesh_builder.h>
#include <easy3d/util/initializer.h>

int main(){
   std::cout << "hi" << std::endl;
   return 0;
};

And the error is :

fatal error: easy3d/core/export.h: No such file or directory
[build]    30 | #include <easy3d/core/export.h>

I checked the folders and there is no export.h anywhere(I could not find it). It is included in some of the functions aswell. What did I do wrong?


问:
How can I deploy Vite app that uses MERN stact to Render.com?
I have been trying to get my MERN app to run on Render, but I cannot get it to work.

```<code>root
        backend
            server.js
            controllers
            middleware
            models
            routes
            package.json
       public
       src
       package.json
</code>```

I dont know if I structured it incorrectly. Here is the package.json in "backend"

```<code>{
  "name": "supportsys",
  "private": true,
  "version": "0.0.0",
  "type": "commonjs",
  "scripts": {
    "dev": "concurrently \"vite\" \"npm run server\"",
    "build": "vite build",
    "preview": "vite preview",
    "start": "node server.js",
    "server": "nodemon server.js"
  },
  "dependencies": {
    "@reduxjs/toolkit": "^1.9.1",
    "axios": "^1.2.2",
    "bcryptjs": "^2.4.3",
    "colors": "^1.4.0",
    "cors": "^2.8.5",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "express-async-handler": "^1.2.0",
    "jsonwebtoken": "^9.0.0",
    "mongoose": "^6.8.2",
  },
  "devDependencies": {
    "@import-meta-env/unplugin": "^0.4.1",
    "@types/react": "^18.0.26",
    "@types/react-dom": "^18.0.9",
    "@vitejs/plugin-react": "^3.0.0",
    "autoprefixer": "^10.4.13",
    "nodemon": "^2.0.20",
    "postcss": "^8.4.20",
    "tailwindcss": "^3.2.4",
    "vite": "^4.0.0"
  },
  "main": "server.js",
  "author": "",
  "license": "ISC",
  "description": ""
}
</code>```

This is the package.json in my root folder

```<code>{
  "name": "supportsys",
  "private": true,
  "version": "0.0.0",
  "type": "commonjs",
  "scripts": {
    "dev": "concurrently \"vite\" \"npm run server\"",
    "build": "vite build",
    "preview": "vite preview",
    "start": "node backend/server.js",
    "server": "nodemon backend/server.js"
  },
  "dependencies": {
    "@reduxjs/toolkit": "^1.9.1",
    "axios": "^1.2.2",
    "bcryptjs": "^2.4.3",
    "colors": "^1.4.0",
    "concurrently": "^7.6.0",
    "cors": "^2.8.5",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "express-async-handler": "^1.2.0",
    "jsonwebtoken": "^9.0.0",
    "mongoose": "^6.8.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-icons": "^4.7.1",
    "react-modal": "^3.16.1",
    "react-redux": "^8.0.5",
    "react-router-dom": "^6.6.1",
    "react-toastify": "^9.1.1",
    "redux": "^4.2.0",
    "redux-devtools-extension": "^2.13.9"
  },
  "devDependencies": {
    "@import-meta-env/unplugin": "^0.4.1",
    "@types/react": "^18.0.26",
    "@types/react-dom": "^18.0.9",
    "@vitejs/plugin-react": "^3.0.0",
    "autoprefixer": "^10.4.13",
    "nodemon": "^2.0.20",
    "postcss": "^8.4.20",
    "tailwindcss": "^3.2.4",
    "vite": "^4.0.0"
  },
  "main": "",
  "author": "",
  "license": "ISC",
  "description": ""
}
</code>```

My server.js file

```<code>const express = require("express");
require("dotenv").config();
const colors = require("colors");
const path = require("path");
const app = express();
var cors = require("cors");
app.use(cors());
const port = process.env.PORT || 9000;
const errorHandler = require("./middleware/errorMiddleware");
const connectDB = require("./config/db");

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

connectDB();

if (process.env.NODE_ENV === "production") {
  // Set build folder as static
  app.use(express.static(path.join(__dirname, "../build")));

  app.get("*", (req, res) => {
    res.sendFile(path.join(__dirname, "../index.html"));
  });
} else {
  app.get("/", (req, res) => {
    res.status(200).json({ message: "Welcome to the API" });
  });
}

app.use("/api/users", require("./routes/userRoutes"));
app.use("/api/tickets", require("./routes/ticketRoutes"));
app.use(errorHandler);

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});
</code>```

I would appreciate if someone could point me towards a direction. I cannot possibly manage to host my backend as webservice, static site runs fine but backend is not there.

I deployed my backend to render and when I deploy my backend i get this error on console "Loading failed for the module with source “https://sys-ctzx.onrender.com/src/main.jsx”."

Body:
I have been trying to get my MERN app to run on Render, but I cannot get it to work.

root
        backend
            server.js
            controllers
            middleware
            models
            routes
            package.json
       public
       src
       package.json

I dont know if I structured it incorrectly. Here is the package.json in "backend"

{
  "name": "supportsys",
  "private": true,
  "version": "0.0.0",
  "type": "commonjs",
  "scripts": {
    "dev": "concurrently \"vite\" \"npm run server\"",
    "build": "vite build",
    "preview": "vite preview",
    "start": "node server.js",
    "server": "nodemon server.js"
  },
  "dependencies": {
    "@reduxjs/toolkit": "^1.9.1",
    "axios": "^1.2.2",
    "bcryptjs": "^2.4.3",
    "colors": "^1.4.0",
    "cors": "^2.8.5",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "express-async-handler": "^1.2.0",
    "jsonwebtoken": "^9.0.0",
    "mongoose": "^6.8.2",
  },
  "devDependencies": {
    "@import-meta-env/unplugin": "^0.4.1",
    "@types/react": "^18.0.26",
    "@types/react-dom": "^18.0.9",
    "@vitejs/plugin-react": "^3.0.0",
    "autoprefixer": "^10.4.13",
    "nodemon": "^2.0.20",
    "postcss": "^8.4.20",
    "tailwindcss": "^3.2.4",
    "vite": "^4.0.0"
  },
  "main": "server.js",
  "author": "",
  "license": "ISC",
  "description": ""
}

This is the package.json in my root folder

{
  "name": "supportsys",
  "private": true,
  "version": "0.0.0",
  "type": "commonjs",
  "scripts": {
    "dev": "concurrently \"vite\" \"npm run server\"",
    "build": "vite build",
    "preview": "vite preview",
    "start": "node backend/server.js",
    "server": "nodemon backend/server.js"
  },
  "dependencies": {
    "@reduxjs/toolkit": "^1.9.1",
    "axios": "^1.2.2",
    "bcryptjs": "^2.4.3",
    "colors": "^1.4.0",
    "concurrently": "^7.6.0",
    "cors": "^2.8.5",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "express-async-handler": "^1.2.0",
    "jsonwebtoken": "^9.0.0",
    "mongoose": "^6.8.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-icons": "^4.7.1",
    "react-modal": "^3.16.1",
    "react-redux": "^8.0.5",
    "react-router-dom": "^6.6.1",
    "react-toastify": "^9.1.1",
    "redux": "^4.2.0",
    "redux-devtools-extension": "^2.13.9"
  },
  "devDependencies": {
    "@import-meta-env/unplugin": "^0.4.1",
    "@types/react": "^18.0.26",
    "@types/react-dom": "^18.0.9",
    "@vitejs/plugin-react": "^3.0.0",
    "autoprefixer": "^10.4.13",
    "nodemon": "^2.0.20",
    "postcss": "^8.4.20",
    "tailwindcss": "^3.2.4",
    "vite": "^4.0.0"
  },
  "main": "",
  "author": "",
  "license": "ISC",
  "description": ""
}

My server.js file

const express = require("express");
require("dotenv").config();
const colors = require("colors");
const path = require("path");
const app = express();
var cors = require("cors");
app.use(cors());
const port = process.env.PORT || 9000;
const errorHandler = require("./middleware/errorMiddleware");
const connectDB = require("./config/db");

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

connectDB();

if (process.env.NODE_ENV === "production") {
  // Set build folder as static
  app.use(express.static(path.join(__dirname, "../build")));

  app.get("*", (req, res) => {
    res.sendFile(path.join(__dirname, "../index.html"));
  });
} else {
  app.get("/", (req, res) => {
    res.status(200).json({ message: "Welcome to the API" });
  });
}

app.use("/api/users", require("./routes/userRoutes"));
app.use("/api/tickets", require("./routes/ticketRoutes"));
app.use(errorHandler);

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

I would appreciate if someone could point me towards a direction. I cannot possibly manage to host my backend as webservice, static site runs fine but backend is not there.

I deployed my backend to render and when I deploy my backend i get this error on console "Loading failed for the module with source “https://sys-ctzx.onrender.com/src/main.jsx”."


问:
Navigationcontroller Hero transition animation no change
NavigationController embed in SearchViewController and DetailViewController when we click row DetailViewController I want it to pass with effect while passing, how can I do that?

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
        let back = UIBarButtonItem()
        vc.hero.isEnabled = true
        vc.hero.modalAnimationType = .zoomSlide(direction: .down)
        back.title = self.viewModel.moviesList?[indexPath.row].Title
        back.tintColor = .black
        navigationItem.backBarButtonItem = back
        vc.viewModel.movieId = self.viewModel.moviesList?[indexPath.row].imdbID
        self.navigationController?.pushViewController(vc, animated: true)
    }

</code>```

this way nothing changes

Body:
NavigationController embed in SearchViewController and DetailViewController when we click row DetailViewController I want it to pass with effect while passing, how can I do that?

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
        let back = UIBarButtonItem()
        vc.hero.isEnabled = true
        vc.hero.modalAnimationType = .zoomSlide(direction: .down)
        back.title = self.viewModel.moviesList?[indexPath.row].Title
        back.tintColor = .black
        navigationItem.backBarButtonItem = back
        vc.viewModel.movieId = self.viewModel.moviesList?[indexPath.row].imdbID
        self.navigationController?.pushViewController(vc, animated: true)
    }

this way nothing changes


问:
Using CKEditor for Laravel Project - Getting "Error code: exportpdf-no-token-url."
Allowing user to edit information in a blog.

They are allowed to change to frontcover of the blog, which is an image.

When I attempt to allow them to change the image + text, I get the console error: "Error code: exportpdf-no-token-url."

After reading the documentation for CKEditor, I found the solution:

```<code>Location: plugins/exportpdf/plugin.js
Description: The exportPdf_tokenUrl configuration variable for the CKEditor Export to PDF plugin was not specified.
Additional data: None.
</code>```

But the documentation doesn't specify solving this issue at all.

Any suggestions?

(Saw a few people ask this question, but the solutions weren't working for me.)

Body:
Allowing user to edit information in a blog.

They are allowed to change to frontcover of the blog, which is an image.

When I attempt to allow them to change the image + text, I get the console error: "Error code: exportpdf-no-token-url."

After reading the documentation for CKEditor, I found the solution:

Location: plugins/exportpdf/plugin.js
Description: The exportPdf_tokenUrl configuration variable for the CKEditor Export to PDF plugin was not specified.
Additional data: None.

But the documentation doesn't specify solving this issue at all.

Any suggestions?

(Saw a few people ask this question, but the solutions weren't working for me.)


问:
Requests.get returns different results depending on which machine the program runs on
I have a program that I've been trying to deploy on Streamlit Cloud... When running the program on my local machine, I get 1 set of results from my request.get, but when deployed to their servers, I get an entirely different set of results.

When using this locally, I wind up with a list of airlines, which I then combine with pricing data.

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
browser = requests.get(f'https://www.google.com/search?q=fly{airline}+from+{origins}+to+{destination}+on+{date}+one+way{nonstop}', headers = headers)
soup = BeautifulSoup(browser.content, 'html.parser')
airlinefind = soup.find_all(class_='BNeawe s3v9rd AP7Wnd')

for air in airlinefind:
    if airlinefind[x].string != None and airlinefind[x].string != 'Southwest':
        if len(airlinefind[x].string) > 19:
            st.write(f"Broke at 112; {airlinefind[x].string}, position {x} :thumbsdown:")
            break
        airlines.append(airlinefind[x].string)
        st.write(f"{airlinefind[x].string} :thumbsup:")
    x+=1

for air in airlines:
    if " " in air and air not in airlinelist:
        st.write(f"{air} ")
        pass
    else:
        new.append(air)
        st.write(f"{air} :airplane:")
```

When running this on Streamlit, however, I find that it is unable to retrieve this data, and instead gets an entirely different page.

I noticed that when opening the page in Brave incognito, it fails to load the chart, but it does do so correctly when in Edge incognito, even with JS disabled. (see attached photo for clarity).

Edge incognito

Same search, in Brave Incognito

Any ideas of how to enforce a consistent result?

Body:
I have a program that I've been trying to deploy on Streamlit Cloud... When running the program on my local machine, I get 1 set of results from my request.get, but when deployed to their servers, I get an entirely different set of results.

When using this locally, I wind up with a list of airlines, which I then combine with pricing data.

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
browser = requests.get(f'https://www.google.com/search?q=fly{airline}+from+{origins}+to+{destination}+on+{date}+one+way{nonstop}', headers = headers)
soup = BeautifulSoup(browser.content, 'html.parser')
airlinefind = soup.find_all(class_='BNeawe s3v9rd AP7Wnd')

for air in airlinefind:
    if airlinefind[x].string != None and airlinefind[x].string != 'Southwest':
        if len(airlinefind[x].string) > 19:
            st.write(f"Broke at 112; {airlinefind[x].string}, position {x} :thumbsdown:")
            break
        airlines.append(airlinefind[x].string)
        st.write(f"{airlinefind[x].string} :thumbsup:")
    x+=1

for air in airlines:
    if " " in air and air not in airlinelist:
        st.write(f"{air} ")
        pass
    else:
        new.append(air)
        st.write(f"{air} :airplane:")

When running this on Streamlit, however, I find that it is unable to retrieve this data, and instead gets an entirely different page.

I noticed that when opening the page in Brave incognito, it fails to load the chart, but it does do so correctly when in Edge incognito, even with JS disabled. (see attached photo for clarity).

Edge incognito

Same search, in Brave Incognito

Any ideas of how to enforce a consistent result?


问:
NextJS Monolith to serve directories under /pages as different projects with dynamic basePaths for a possible Nginx reverse proxy
I have a NextJS application which acts like a monolith. Means, I have multiple directories under /pages which acts as different projects.

```<code> /pages/first_project/[...slugs]
 /pages/second_project/[...slugs]
</code>```

For the setup I have Docker which runs nextjs as a container alongside Nginx as a prima-facie to reverse proxy back to the application.
I would like Nginx to map its /location against the pages directory in NextJS.

For e.g

```<code>/first_project --> /pages/first_project/
/second_project --> /pages/second_project/
</code>```

In my company, the hosting of the projects are like this:

```<code><company.com>/first_project/[...slugs]
<company.com>/second_project/[...slugs]
</code>```

The issue I am facing is, since /location in the Nginx looks for all the build files in that particular location. I can't have dynamic hosting possible. I was wondering if this is at all possible?

If I don't provide a basePath in next.config.js, then for <company.com>/first_project/, Nginx expects files to be available in the location --> first_project. However, files are available at the root directory of the project. So I end up getting error.

I obviously can fix this issue by setting basePath in next.config as first_project. However, this will fail for second_project. Is there any way to dynamically load basePath? Please let me know.

Company Nginx Config:

```<code>server {
    listen 80;
    server_name _;
    location /first_project {
      proxy_pass http://local:8000;

    }
    location /second_project {
      proxy_pass http://local:8000;

    }

}
</code>```

(local:8000)NextJS Nginx Monolith Config

```<code>upstream nextjs_upstream {
  server <nextjs_project>:3000;
}

server {
  listen 80 default_server;

  server_name _;

  server_tokens off;

  gzip on;
  gzip_proxied any;
  gzip_comp_level 4;
  gzip_types text/css application/javascript image/svg+xml;

  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection 'upgrade';
  proxy_set_header Host $host;
  proxy_cache_bypass $http_upgrade;

  location /_next/static {

    proxy_pass http://nextjs_upstream;
  }

  location / {
    proxy_pass http://nextjs_upstream;
  }
}
</code>```

Any help will be appreciated. Thanks :)

Body:
I have a NextJS application which acts like a monolith. Means, I have multiple directories under /pages which acts as different projects.

 /pages/first_project/[...slugs]
 /pages/second_project/[...slugs]

For the setup I have Docker which runs nextjs as a container alongside Nginx as a prima-facie to reverse proxy back to the application.
I would like Nginx to map its /location against the pages directory in NextJS.

For e.g

/first_project --> /pages/first_project/
/second_project --> /pages/second_project/

In my company, the hosting of the projects are like this:

<company.com>/first_project/[...slugs]
<company.com>/second_project/[...slugs]

The issue I am facing is, since /location in the Nginx looks for all the build files in that particular location. I can't have dynamic hosting possible. I was wondering if this is at all possible?

If I don't provide a basePath in next.config.js, then for <company.com>/first_project/, Nginx expects files to be available in the location --> first_project. However, files are available at the root directory of the project. So I end up getting error.

I obviously can fix this issue by setting basePath in next.config as first_project. However, this will fail for second_project. Is there any way to dynamically load basePath? Please let me know.

Company Nginx Config:

server {
    listen 80;
    server_name _;
    location /first_project {
      proxy_pass http://local:8000;

    }
    location /second_project {
      proxy_pass http://local:8000;

    }

}

(local:8000)NextJS Nginx Monolith Config

upstream nextjs_upstream {
  server <nextjs_project>:3000;
}

server {
  listen 80 default_server;

  server_name _;

  server_tokens off;

  gzip on;
  gzip_proxied any;
  gzip_comp_level 4;
  gzip_types text/css application/javascript image/svg+xml;

  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection 'upgrade';
  proxy_set_header Host $host;
  proxy_cache_bypass $http_upgrade;

  location /_next/static {

    proxy_pass http://nextjs_upstream;
  }

  location / {
    proxy_pass http://nextjs_upstream;
  }
}

Any help will be appreciated. Thanks :)


问:
why mysql "LOAD DATA INFILE" buffers data in memory and very CPU intensive?
when we load data from binary tsv file with mysql -e "LOAD DATA INFILE..."
i see memory goes up i think loading the whole file in memory (if it has enough).
and then , we need to wait for the next "memory upload"

is there some sorting going on?
it takes may be a minute to load 4G file into memory.
if i just copy this file to "in memory partition" (tmp fs) it takes few secs
so it must be doing something with data cpu bound

thanks

load binary encoded files to mysql table with "LOAD DATA INFILE"


问:
ValueError: could not convert string to float: in python colab

import  numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from google.colab import files
uploded = files.upload()

df = pd.read_csv("quotation_test_data.csv")

print(df)

import seaborn as sns

df . describe() #describe the data as it shows mean , count

df.isnull().sum()   #for see is there any column dont have a data

df ["Net profit"].value_counts()

sns.countplot(df['Net profit'])

#spli data into  x and y then make it into train and test  data

x=df.iloc[: , :-1]

y=df.iloc[: , :-1]

# [:,:-1] the  (:) mean the coumln  (:-1) this mean  like print the alll column except the last  one

#npw i will split the data into train and  test data  will use sklearn
from sklearn.model_selection import train_test_split

x_train , x_test,y_train,y_test = train_test_split(x,y,random_state=100)

x_train.shape

y_train.shape

from sklearn.tree import DecisionTreeClassifier #intilize desion tree

from pandas.core.common import random_state
clf = DecisionTreeClassifier(criterion="gini",max_depth=7,min_samples_split=10,random_state=10) # criteraition

import pandas as pd
data=pd.read_csv('quotation_test_data.csv')

dataconver = data.replace('[^\d.]','', regex=True).astype(float)
```
<p>i was try to make a desion tree</p>
<p>then this is show for me :</p>
```ValueError                                Traceback (most recent call last)
<ipython-input-75-df55a55b03a4> in <module>
----> 1 dataconver = data.replace('[^\d.]', regex=True).astype(float)
      2

7 frames
/usr/local/lib/python3.8/dist-packages/pandas/core/dtypes/cast.py in astype_nansafe(arr, dtype, copy, skipna)
   1199     if copy or is_object_dtype(arr.dtype) or is_object_dtype(dtype):
   1200         # Explicit copy, or required since NumPy can't view from / to object.
-> 1201         return arr.astype(dtype, copy=True)
   1202
   1203     return arr.astype(dtype, copy=copy)

ValueError: could not convert string to float: 'Kellie Scott'
```

i was try make desion tree

Body:
import  numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from google.colab import files
uploded = files.upload()

df = pd.read_csv("quotation_test_data.csv")

print(df)

import seaborn as sns

df . describe() #describe the data as it shows mean , count

df.isnull().sum()   #for see is there any column dont have a data

df ["Net profit"].value_counts()

sns.countplot(df['Net profit'])

#spli data into  x and y then make it into train and test  data

x=df.iloc[: , :-1]

y=df.iloc[: , :-1]

# [:,:-1] the  (:) mean the coumln  (:-1) this mean  like print the alll column except the last  one

#npw i will split the data into train and  test data  will use sklearn
from sklearn.model_selection import train_test_split

x_train , x_test,y_train,y_test = train_test_split(x,y,random_state=100)

x_train.shape

y_train.shape

from sklearn.tree import DecisionTreeClassifier #intilize desion tree

from pandas.core.common import random_state
clf = DecisionTreeClassifier(criterion="gini",max_depth=7,min_samples_split=10,random_state=10) # criteraition

import pandas as pd
data=pd.read_csv('quotation_test_data.csv')

dataconver = data.replace('[^\d.]','', regex=True).astype(float)

i was try to make a desion tree

then this is show for me :

ValueError                                Traceback (most recent call last)
<ipython-input-75-df55a55b03a4> in <module>
----> 1 dataconver = data.replace('[^\d.]', regex=True).astype(float)
      2

7 frames
/usr/local/lib/python3.8/dist-packages/pandas/core/dtypes/cast.py in astype_nansafe(arr, dtype, copy, skipna)
   1199     if copy or is_object_dtype(arr.dtype) or is_object_dtype(dtype):
   1200         # Explicit copy, or required since NumPy can't view from / to object.
-> 1201         return arr.astype(dtype, copy=True)
   1202
   1203     return arr.astype(dtype, copy=copy)

ValueError: could not convert string to float: 'Kellie Scott'

i was try make desion tree


问:
Custom ConditionalGenericConverter annotation doesn't convert parameters in Spring GraphQL
I have a REST API developed in Spring and now I'm learning how to use GraphQL in my Spring project so I'm "translating" my REST endpoints to GraphQL queries.

Just to give some background on what I'm trying to do, I will show how one of my REST controllers look like (code in Kotlin):

Rest Controller

@RestController
@RequestMapping("countries")
class CountryController(private val countryService: CountryService) {

    @GetMapping("{code}")
    fun findByCode(@PathVariable @Uppercase code: String): Country {
        return countryService.findByCode(code)
    }
}
```
<p>It's basically an endpoint that fetches a country based on a code. For example <code>/countries/bra</code> will fetch information about the country Brazil.</p>
<p>In the code above there's also a custom annotation called <code>@Uppercase</code>. This annotation extends <code>ConditionalGenericConverter</code> and the only thing it does is to take the <code>code</code> parameter and convert it to uppercase. This is the code for this annotation:</p>
<h3>@Uppercase implementation</h3>
<pre class="lang-kotlin prettyprint-override"><code>@Target(AnnotationTarget.VALUE_PARAMETER)
annotation class Uppercase

@Component
class UppercaseConverter : ConditionalGenericConverter {
    override fun matches(sourceType: TypeDescriptor, targetType: TypeDescriptor): Boolean {
        return targetType.getAnnotation(Uppercase::class.java) != null
    }

    override fun getConvertibleTypes(): MutableSet<ConvertiblePair>? {
        return mutableSetOf(ConvertiblePair(String::class.java, String::class.java))
    }

    override fun convert(source: Any?, sourceType: TypeDescriptor, targetType: TypeDescriptor): String {
        return (source as String).uppercase()
    }
}
</code>```

Everything works as expected in the code above and the code parameter is always converted to uppercase if I use the @Uppercase annotation in my REST controller.

Now I created a similar controller for Spring GraphQL that looks like this:

GraphQL Controller

@Controller
class CountryResolver(private val countryService: CountryService) {

    @QueryMapping(name = "country")
    fun findByCode(@Argument @Uppercase code: String): Country {
        return countryService.findByCode(code)
    }
}
```

And my GraphQL is executed properly with the code above, except that the parameter code is not converted to uppercase when I use my custom annotation @Uppercase. It seems that my custom annotation only works with @PathVariable in the REST controller, but it doesn't with @Argument in the GraphQL controller.

Any idea why on how to make it work with GraphQL as well? Thanks in advance!

Body:
I have a REST API developed in Spring and now I'm learning how to use GraphQL in my Spring project so I'm "translating" my REST endpoints to GraphQL queries.

Just to give some background on what I'm trying to do, I will show how one of my REST controllers look like (code in Kotlin):

Rest Controller

@RestController
@RequestMapping("countries")
class CountryController(private val countryService: CountryService) {

    @GetMapping("{code}")
    fun findByCode(@PathVariable @Uppercase code: String): Country {
        return countryService.findByCode(code)
    }
}

It's basically an endpoint that fetches a country based on a code. For example /countries/bra will fetch information about the country Brazil.

In the code above there's also a custom annotation called @Uppercase. This annotation extends ConditionalGenericConverter and the only thing it does is to take the code parameter and convert it to uppercase. This is the code for this annotation:

@Uppercase implementation

@Target(AnnotationTarget.VALUE_PARAMETER)
annotation class Uppercase

@Component
class UppercaseConverter : ConditionalGenericConverter {
    override fun matches(sourceType: TypeDescriptor, targetType: TypeDescriptor): Boolean {
        return targetType.getAnnotation(Uppercase::class.java) != null
    }

    override fun getConvertibleTypes(): MutableSet<ConvertiblePair>? {
        return mutableSetOf(ConvertiblePair(String::class.java, String::class.java))
    }

    override fun convert(source: Any?, sourceType: TypeDescriptor, targetType: TypeDescriptor): String {
        return (source as String).uppercase()
    }
}

Everything works as expected in the code above and the code parameter is always converted to uppercase if I use the @Uppercase annotation in my REST controller.

Now I created a similar controller for Spring GraphQL that looks like this:

GraphQL Controller

@Controller
class CountryResolver(private val countryService: CountryService) {

    @QueryMapping(name = "country")
    fun findByCode(@Argument @Uppercase code: String): Country {
        return countryService.findByCode(code)
    }
}

And my GraphQL is executed properly with the code above, except that the parameter code is not converted to uppercase when I use my custom annotation @Uppercase. It seems that my custom annotation only works with @PathVariable in the REST controller, but it doesn't with @Argument in the GraphQL controller.

Any idea why on how to make it work with GraphQL as well? Thanks in advance!


问:
Numpy, mapping a RGB colour ramp to normalised values
I have a normalised range of values in a numpy array, so 0 to 1, let's call this normal_array.

```<code>normal_array = np.array([0.0, 0.3, 0.356, 0.49, 0.64, 0.784, 1.0])
</code>```

I need to create another numpy array which contains the rgb values of a colour ramp, let's call this colour_array. How do I map the RGB values from a colour ramp to the normal_array?

It would be great if I could use an existing colour ramp like these from matplotlib; https://matplotlib.org/stable/tutorials/colors/colormaps.html

How do you map the 0-1 values to rgb values from a colour ramp?

Body:
I have a normalised range of values in a numpy array, so 0 to 1, let's call this normal_array.

normal_array = np.array([0.0, 0.3, 0.356, 0.49, 0.64, 0.784, 1.0])

I need to create another numpy array which contains the rgb values of a colour ramp, let's call this colour_array. How do I map the RGB values from a colour ramp to the normal_array?

It would be great if I could use an existing colour ramp like these from matplotlib; https://matplotlib.org/stable/tutorials/colors/colormaps.html

How do you map the 0-1 values to rgb values from a colour ramp?