问:
Global Guards in themultiple GraphQL modules with NestJS and separate access to queries and mutations in resolvers
I want to build a NestJS project where I will separate queries and mutations into two groups: Internal and Public. In the Internal GraphQL module, I will define path and resolvers without any restrictions, but for the Public, I want to define a GraphQL module with path and JWT Guard, which will look at the same resolvers but just specific mutations and queries.

I tried to do the following:

```<code>GraphQLModule.forRootAsync<ApolloDriverConfig>({
   driver: ApolloDriver,
   useClass: InternalGraphQLConfig,
}),
GraphQLModule.forRootAsync<ApolloDriverConfig>({
   driver: ApolloDriver,
   useClass: PublicGraphQLConfig,
}),
</code>```

For protecting the public endpoint (the path is defined in the PublicGraphQLConfig by GqlOptionsFactory) I added middleware by NestMiddleware where I am checking req.originalUrl - the path from the PublicGraphQLConfig. If the URL is the public one, I am checking for the JWT otherwise is a free - internal URL.

But, I do not know how and where I can define the list of queries and mutations for the Public GraphQL model because I do not want to expose all of them.

As I can see in the documentation, this approach may be unavailable, and it is impossible to do it correctly like this. Maybe I have to use directives or something else, but I firmly believe someone has a similar/same challenge and will share an idea/solution with me.

Edit 1:
Here I will add more details about resolvers and GraphQL Module configuration.

One of my resolvers looks like the following:

```<code>...
@Resolver(DogEntity)
class DogResolver {

   @Mutation(...)
   async firstMutation(...) {
    //
   }

   @Mutation(...)
   async secondMutation(...) {
    //
   }

   @Query(...)
   async firstQuery(...) {
    //
   }

   @Query(...)
   async secondQuery(...) {
    //
   }
...
}
</code>```

GraphQL Module configuration looks like this:

```<code>...
@Injectable()
export class PublicGraphQLConfig implements GqlOptionsFactory {
    createGqlOptions(): Promise<ApolloDriverConfig> | ApolloDriverConfig {
        return {
           ...
           resolvers: { DogResolver, ...}
           path: '/my/public/route/graphql'
        };
    }
}

</code>```

The first: It would be amazing if I could add a "global" guardian on the GrapQL Module level with, for example guards parameter in the PublicGraphQLConfig. Because it is impossible, and adding any JWT validation in the context parameter no make sense, I have to add Middleware where I'm checking the path parameter from the GraphQL Module configuration.

The Middleware looks like this:

```<code>...
@Injectable()
export class RequestResponseLoggerMiddleware implements NestMiddleware {
    use(req: Request, res: Response, next: NextFunction) {
        // For public endpoint, all resolvers required JWT token with Admin flag
        if (req.originalUrl === '/my/public/route/graphql') {
            this.validateJWT(req); // Do "throw exception inside"
        }
...

</code>```

The second: It would be amazing to add specific Mutation and/or Query in the GraphQL Module configuration. With the resolvers parameter, I can add only complete resolvers, but not specific queries or mutations. With this, I will be able to access the specific queries and mutations from different Endpoints with/out authorization requests.

The field in the GrapQL Module configuration like the following will be amazing (but, as I can see, it does not exist)

```<code>...

        return {
           ...
           resolvers: {
              DogResolver:firstMutation(),
              DogResolver:firstQuery(),
              ...
           },
           path: '/my/public/route/graphql'
        };
...
</code>```

Body:
I want to build a NestJS project where I will separate queries and mutations into two groups: Internal and Public. In the Internal GraphQL module, I will define path and resolvers without any restrictions, but for the Public, I want to define a GraphQL module with path and JWT Guard, which will look at the same resolvers but just specific mutations and queries.

I tried to do the following:

GraphQLModule.forRootAsync<ApolloDriverConfig>({
   driver: ApolloDriver,
   useClass: InternalGraphQLConfig,
}),
GraphQLModule.forRootAsync<ApolloDriverConfig>({
   driver: ApolloDriver,
   useClass: PublicGraphQLConfig,
}),

For protecting the public endpoint (the path is defined in the PublicGraphQLConfig by GqlOptionsFactory) I added middleware by NestMiddleware where I am checking req.originalUrl - the path from the PublicGraphQLConfig. If the URL is the public one, I am checking for the JWT otherwise is a free - internal URL.

But, I do not know how and where I can define the list of queries and mutations for the Public GraphQL model because I do not want to expose all of them.

As I can see in the documentation, this approach may be unavailable, and it is impossible to do it correctly like this. Maybe I have to use directives or something else, but I firmly believe someone has a similar/same challenge and will share an idea/solution with me.

Edit 1:
Here I will add more details about resolvers and GraphQL Module configuration.

One of my resolvers looks like the following:

...
@Resolver(DogEntity)
class DogResolver {

   @Mutation(...)
   async firstMutation(...) {
    //
   }

   @Mutation(...)
   async secondMutation(...) {
    //
   }

   @Query(...)
   async firstQuery(...) {
    //
   }

   @Query(...)
   async secondQuery(...) {
    //
   }
...
}

GraphQL Module configuration looks like this:

...
@Injectable()
export class PublicGraphQLConfig implements GqlOptionsFactory {
    createGqlOptions(): Promise<ApolloDriverConfig> | ApolloDriverConfig {
        return {
           ...
           resolvers: { DogResolver, ...}
           path: '/my/public/route/graphql'
        };
    }
}

The first: It would be amazing if I could add a "global" guardian on the GrapQL Module level with, for example guards parameter in the PublicGraphQLConfig. Because it is impossible, and adding any JWT validation in the context parameter no make sense, I have to add Middleware where I'm checking the path parameter from the GraphQL Module configuration.

The Middleware looks like this:

...
@Injectable()
export class RequestResponseLoggerMiddleware implements NestMiddleware {
    use(req: Request, res: Response, next: NextFunction) {
        // For public endpoint, all resolvers required JWT token with Admin flag
        if (req.originalUrl === '/my/public/route/graphql') {
            this.validateJWT(req); // Do "throw exception inside"
        }
...

The second: It would be amazing to add specific Mutation and/or Query in the GraphQL Module configuration. With the resolvers parameter, I can add only complete resolvers, but not specific queries or mutations. With this, I will be able to access the specific queries and mutations from different Endpoints with/out authorization requests.

The field in the GrapQL Module configuration like the following will be amazing (but, as I can see, it does not exist)

...

        return {
           ...
           resolvers: {
              DogResolver:firstMutation(),
              DogResolver:firstQuery(),
              ...
           },
           path: '/my/public/route/graphql'
        };
...


来源: stackexchange

问:
OAuth 2.0 token generation service in Outsystems
I'm working in a demo where I need to consume a REST API that needs an access token. Currently I'm generating this token with Postman and using it parametrically but I need to make automatic. I already have everything I need but the service to generate this token.

If someone can help me, I would be very thankful.

I tried to generate the token with Postman and use it in a variable, it works, but I need to make ir automatic.

ContentLicense: CC BY-SA 4.0


问:
Deeplink with dynamic paths not resolving my activity
Here is an exemple of the link:

https://somelink.someotherlink.ws/path1/path2/path3/path4/dynamic_path1/dynamic_path2

```<code>    <activity
        android:name=".activite.Activity"
        android:exported="true">
        <tools:validation testUrl="https://somelink.someotherlink.ws/path1/path2/path3/path4/..*/..*/"/>
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:scheme="https"
                android:host="somelink.someotherlink.ws"
                android:pathPattern="/path1/path2/path3/path4/..*/..*/" />
        </intent-filter>
    </activity>
</code>```

So here when I run the test from the android studio tool the url is resolving my activity and also launching it.

This also is working when clicking this url link from other apps

But only when it comes to web browser (Entering the link in the search bar and click enter or any other programatic redirection) the redirection not going to my app.

Ex:

https://somelink.someotherlink.ws/path1/path2/path3/path4/dynamic_path1/dynamic_path2

this is not getting resolved in anyway

I've also tried to use the two dot enforcement and single dot enforcement but getting same result.

Thanks for any help.

Body:
Here is an exemple of the link:

https://somelink.someotherlink.ws/path1/path2/path3/path4/dynamic_path1/dynamic_path2

    <activity
        android:name=".activite.Activity"
        android:exported="true">
        <tools:validation testUrl="https://somelink.someotherlink.ws/path1/path2/path3/path4/..*/..*/"/>
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:scheme="https"
                android:host="somelink.someotherlink.ws"
                android:pathPattern="/path1/path2/path3/path4/..*/..*/" />
        </intent-filter>
    </activity>

So here when I run the test from the android studio tool the url is resolving my activity and also launching it.

This also is working when clicking this url link from other apps

But only when it comes to web browser (Entering the link in the search bar and click enter or any other programatic redirection) the redirection not going to my app.

Ex:

https://somelink.someotherlink.ws/path1/path2/path3/path4/dynamic_path1/dynamic_path2

this is not getting resolved in anyway

I've also tried to use the two dot enforcement and single dot enforcement but getting same result.

Thanks for any help.


问:
rb.AddForce() is launching my player in the opposite direction of the vector 2 value I assigned
Im making a game where you click and drag with the mouse then release to launch the player. But sometimes the player gets launched in the opposite direction of where it should go. I made a debug output to show you the different values. Here is the output

In that image for example you can see that the Vector2 of force * power is positive on the y axis, but the player launched downwards, and the same happens Viceversa. I think its also worth to note that this happens inconsistantly for some reason. Here is my code:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    public GameObject player;
    public float power = 10f;
    public Rigidbody2D rb;
    public float maxSpeed;

    public Vector2 minPower;
    public Vector2 maxPower;

    TragectoryLine tl;

    Camera cam;
    public Vector2 force;
    public Vector3 startPoint;
    public Vector3 endPoint;
    public Vector3 currentPoint;
    public Vector3 startPointMouse;

    public bool isPulling = false;
    float distance;

    private void Start()
    {
        cam = Camera.main;
        tl = GetComponent<TragectoryLine>();
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            startPointMouse = cam.ScreenToWorldPoint(Input.mousePosition);
            startPointMouse.z = 15;
        }
        if (Input.GetMouseButton(0))
        {
            startPoint = player.transform.position;
            startPoint.z = 15;
            isPulling = true;
            Vector3 currentPoint = cam.ScreenToWorldPoint(Input.mousePosition);
            currentPoint.z = 15;
            tl.RenderLine(startPoint, currentPoint);

        }

        if (Input.GetMouseButtonUp(0))
        {
            endPoint = cam.ScreenToWorldPoint(Input.mousePosition);
            endPoint.z = 15;
            isPulling = false;

            tl.EndLine();
            distance = startPointMouse.magnitude - endPoint.magnitude;

            if (distance < 0)
            {
                distance = -distance;
            }
            if (distance >= 1)
            {
                rb.AddForce(force * power, ForceMode2D.Impulse);
            }

            force = new Vector2(Mathf.Clamp(startPoint.x - endPoint.x, minPower.x, maxPower.x), Mathf.Clamp(startPoint.y - endPoint.y, minPower.y, maxPower.y));

            Debug.Log("distance" + distance);
            Debug.Log("start" + startPoint);
            Debug.Log("end" + endPoint);
            Debug.Log("force" +force);
            Debug.Log("force * power" + force * power);
        }

    }

    private void FixedUpdate()
    {
        rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed);
    }
}
</code>```

Here I added the force using rb.AddForce(force * power, ForceMode2D.Impulse); when the force * power value was positive on the y axis. So why did it go to the opposite direction???

This was working perfectly fine before i tried implementing a feature where the player has to move the mouse a certain distance or else it wont launch. I have tried removing it but it doesnt seem to make a difference. I think I changed something in the code that ruined it but I cant figure out what! Please help!

Body:
Im making a game where you click and drag with the mouse then release to launch the player. But sometimes the player gets launched in the opposite direction of where it should go. I made a debug output to show you the different values. Here is the output

In that image for example you can see that the Vector2 of force * power is positive on the y axis, but the player launched downwards, and the same happens Viceversa. I think its also worth to note that this happens inconsistantly for some reason. Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    public GameObject player;
    public float power = 10f;
    public Rigidbody2D rb;
    public float maxSpeed;

    public Vector2 minPower;
    public Vector2 maxPower;

    TragectoryLine tl;

    Camera cam;
    public Vector2 force;
    public Vector3 startPoint;
    public Vector3 endPoint;
    public Vector3 currentPoint;
    public Vector3 startPointMouse;

    public bool isPulling = false;
    float distance;

    private void Start()
    {
        cam = Camera.main;
        tl = GetComponent<TragectoryLine>();
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            startPointMouse = cam.ScreenToWorldPoint(Input.mousePosition);
            startPointMouse.z = 15;
        }
        if (Input.GetMouseButton(0))
        {
            startPoint = player.transform.position;
            startPoint.z = 15;
            isPulling = true;
            Vector3 currentPoint = cam.ScreenToWorldPoint(Input.mousePosition);
            currentPoint.z = 15;
            tl.RenderLine(startPoint, currentPoint);

        }

        if (Input.GetMouseButtonUp(0))
        {
            endPoint = cam.ScreenToWorldPoint(Input.mousePosition);
            endPoint.z = 15;
            isPulling = false;

            tl.EndLine();
            distance = startPointMouse.magnitude - endPoint.magnitude;

            if (distance < 0)
            {
                distance = -distance;
            }
            if (distance >= 1)
            {
                rb.AddForce(force * power, ForceMode2D.Impulse);
            }

            force = new Vector2(Mathf.Clamp(startPoint.x - endPoint.x, minPower.x, maxPower.x), Mathf.Clamp(startPoint.y - endPoint.y, minPower.y, maxPower.y));

            Debug.Log("distance" + distance);
            Debug.Log("start" + startPoint);
            Debug.Log("end" + endPoint);
            Debug.Log("force" +force);
            Debug.Log("force * power" + force * power);
        }

    }

    private void FixedUpdate()
    {
        rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed);
    }
}

Here I added the force using rb.AddForce(force * power, ForceMode2D.Impulse); when the force * power value was positive on the y axis. So why did it go to the opposite direction???

This was working perfectly fine before i tried implementing a feature where the player has to move the mouse a certain distance or else it wont launch. I have tried removing it but it doesnt seem to make a difference. I think I changed something in the code that ruined it but I cant figure out what! Please help!


问:
Pythonnet in C# - debugger stopped when PythonEngine.Initialize() is called
I tried to run Python code from c# using pythonnet. I followed this intstuction: https://somegenericdev.medium.com/calling-python-from-c-an-introduction-to-pythonnet-c3d45f7d5232 but debugger stopped when I run the line  PythonEngine.Initialize(). What is the reason and how to fix it?


问:
How to show two values in a Vuetify table in one row?
In a Vuetify Table is a column in which a start date and an end date should be displayed. The date comes from the backend. How can I display the data in my desired format in the table, that in one column is both. First the start date then the end date?

Typescript:

```<code>export function useSport() {
  const tableRows = ref<TableColumn[]>();

  onMounted(async () => {
    const yesterday: string = format(sub(new Date(), { days: 2 }),'yyyy-MM-dd');
    const endDate: string = format(sub(new Date(), { days: 7 }), 'yyyy-MM-dd');
    const searchParams: TableSearchParams = {
      startDate: yesterday,
      endDate: endDat,
    }
    const { data } = await fetchTableRow(searchParams);
    if(data) {
      tableRows.value = data.entries;
    }
  });

  const headers: DataTableHeader[] = [
    { text: 'Sport', value: 'sportsName' },
    { text: 'Sports Id', value: 'sportsId' },
    { text: 'Data of members', value: 'yesterday' },
    { text: 'Last delivery', value: 'lastDelivery' },
  ]

  return {
    tabelRows,
    headers,
  };
}
</code>```

Vue.js:

```<code><template>
  <div class="monitoringSports ma-7">
    {{ 'Delivered Sports Data' }}
    <VDataTable
      :headers="headers"
      :items="tableRows"
      :items-per-page="20"
      hide-default-footer
      class="elevation-1"
      no-data-text="No data found"
      >
      <template #item.sportsName="{ item }">
        <AvatarChip
          :variant="AvatarChipVariant.SPORT"
          :objectId="item.sportsId"
          :label="item.sportsName"
        />
      </template>
      <template #item.startData="{ item }">
        <SportsDate :text="item.startData"/>
      </template>
    </VDataTable>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import AvatarChip from '@/AvatarChip.vue';
import { AvatarChipHit } from '@AvatarChip';
import { useMonitoringSports } from './MonitoringSports';

export default defineComponent({
  components: { AvatarChip },
  setup() { const { tableRows, headers }
 = useMonitoringSports();

 return {
  tableRows,
  headers,
  AvatarChip,
  AvatarChipHit,
    };
  },
});
</script>
</code>```

My typing, I created interfaces which will be used in the ts and the vue part:

```<code>export interface TableSearchParams {
  //Mandatory
  startData: string;
  //Optional
  endData?: string;
}

export interface TableRow {
  sportsId?: string;
  sportsName?: string;
  values?: [
    {
      data?: string;
      amount?: number;
    }
  ];
}

export interface SportsTable {
  entries?: SportsTableRow[];
}

export interface DataTableHeader {
  text: string;
  value: string;
  align?: 'start' | 'center' | 'end';
  sortable?: boolean;
  filterable?: boolean;
  groupable?: boolean;
  divider?: boolean;
  class?: string | string[];
  cellClass?: string | string[];
  width?: string | number;
  filter?: (value: any, search: string, item: any) => boolean;
  sort?: (a: any, b: any) => number;
}

</code>```

sportsName and sportsId are displayed in the vuetify table. The two data are not displayed in the table. Which leads me to my question. Where do I have a thinking error?

Body:
In a Vuetify Table is a column in which a start date and an end date should be displayed. The date comes from the backend. How can I display the data in my desired format in the table, that in one column is both. First the start date then the end date?

Typescript:

export function useSport() {
  const tableRows = ref<TableColumn[]>();

  onMounted(async () => {
    const yesterday: string = format(sub(new Date(), { days: 2 }),'yyyy-MM-dd');
    const endDate: string = format(sub(new Date(), { days: 7 }), 'yyyy-MM-dd');
    const searchParams: TableSearchParams = {
      startDate: yesterday,
      endDate: endDat,
    }
    const { data } = await fetchTableRow(searchParams);
    if(data) {
      tableRows.value = data.entries;
    }
  });

  const headers: DataTableHeader[] = [
    { text: 'Sport', value: 'sportsName' },
    { text: 'Sports Id', value: 'sportsId' },
    { text: 'Data of members', value: 'yesterday' },
    { text: 'Last delivery', value: 'lastDelivery' },
  ]

  return {
    tabelRows,
    headers,
  };
}

Vue.js:

<template>

    {{ 'Delivered Sports Data' }}
    <VDataTable
      :headers="headers"
      :items="tableRows"
      :items-per-page="20"
      hide-default-footer
      class="elevation-1"
      no-data-text="No data found"
      >
      <template #item.sportsName="{ item }">
        <AvatarChip
          :variant="AvatarChipVariant.SPORT"
          :objectId="item.sportsId"
          :label="item.sportsName"
        />
      </template>
      <template #item.startData="{ item }">
        <SportsDate :text="item.startData"/>
      </template>
    </VDataTable>

</template>

My typing, I created interfaces which will be used in the ts and the vue part:

export interface TableSearchParams {
  //Mandatory
  startData: string;
  //Optional
  endData?: string;
}

export interface TableRow {
  sportsId?: string;
  sportsName?: string;
  values?: [
    {
      data?: string;
      amount?: number;
    }
  ];
}

export interface SportsTable {
  entries?: SportsTableRow[];
}

export interface DataTableHeader {
  text: string;
  value: string;
  align?: 'start' | 'center' | 'end';
  sortable?: boolean;
  filterable?: boolean;
  groupable?: boolean;
  divider?: boolean;
  class?: string | string[];
  cellClass?: string | string[];
  width?: string | number;
  filter?: (value: any, search: string, item: any) => boolean;
  sort?: (a: any, b: any) => number;
}

sportsName and sportsId are displayed in the vuetify table. The two data are not displayed in the table. Which leads me to my question. Where do I have a thinking error?


问:
Creating a normalized x axis in Power BI?
I am trying to create a plot which normalizes the x axis based on the date of an event listed in a different query. I have the production data sitting in one query, which contains the value per day. I have a list of events in a second query, which have specific dates at which they occured. My goal is to create some measure or function that will plot each event on the axis in a normalized fashion where the production -1y to 1y from the event is shown on the x axis. This will allow a comparison of the last year of production before the event versus the next year, which can gauge success of the event. I don't know how to successfully do this though, and would appreciate any insight.

Current plot with event dates in table on the right

A person who did something similar merged the two queries and created a column which finds the date of the event, and determines how far in time it has been since (30d since the event is given 30). However, because I have about 70 data points which each have 4-5 of their own events, this merged query duplicated the production for each event, so there is 4-5 logs of production data per data point, which has become hard to manage as I try to do something similar and understand what they're doing. I believe there's a better way to do this but I can't figure out how to connect the two queries in a more efficient way.

Normalized production from day 0 of each event that I'm trying to create

My code below is my attempt at making a measure that will create this normalized axis for me, but I am getting a circular dependency error.

```<code>Normalized Producing Days From Workover =
//These will reference the date values in the measures made of the workover start and end dates
Var startofworkover = DATEVALUE([Measure: WKO Start Date])
var endofworkover = DATEVALUE([Measure: WKO End Date])

//this will filter to dates after the workover
var afterworkover = FILTER('Production Data',
    'Production Data'[Date]>=endofworkover && 'Production Data'[Well Pair] = EARLIER('Production Data'[Well Pair]) && [Allocated Oil Production (m3/d)] >0)

//this will filter to dates before the workover
var beforeworkover = FILTER('Production Data',
    'Production Data'[Date]<startofworkover && 'Production Data'[Well Pair] = EARLIER('Production Data'[Well Pair]) && [Allocated Oil Production (m3/d)] >0)

var result1 = SWITCH(TRUE(),'Production Data'[Date] = startofworkover,0,'Production Data'[Date]>=endofworkover,RANKX(afterworkover,'Production Data'[Date],,ASC,Dense),'Production Data'[Date]<startofworkover,RANKX(beforeworkover,'Production Data'[Date],,DESC,Dense)*-1)

return result1
</code>```

Body:
I am trying to create a plot which normalizes the x axis based on the date of an event listed in a different query. I have the production data sitting in one query, which contains the value per day. I have a list of events in a second query, which have specific dates at which they occured. My goal is to create some measure or function that will plot each event on the axis in a normalized fashion where the production -1y to 1y from the event is shown on the x axis. This will allow a comparison of the last year of production before the event versus the next year, which can gauge success of the event. I don't know how to successfully do this though, and would appreciate any insight.

Current plot with event dates in table on the right

A person who did something similar merged the two queries and created a column which finds the date of the event, and determines how far in time it has been since (30d since the event is given 30). However, because I have about 70 data points which each have 4-5 of their own events, this merged query duplicated the production for each event, so there is 4-5 logs of production data per data point, which has become hard to manage as I try to do something similar and understand what they're doing. I believe there's a better way to do this but I can't figure out how to connect the two queries in a more efficient way.

Normalized production from day 0 of each event that I'm trying to create

My code below is my attempt at making a measure that will create this normalized axis for me, but I am getting a circular dependency error.

Normalized Producing Days From Workover =
//These will reference the date values in the measures made of the workover start and end dates
Var startofworkover = DATEVALUE([Measure: WKO Start Date])
var endofworkover = DATEVALUE([Measure: WKO End Date])

//this will filter to dates after the workover
var afterworkover = FILTER('Production Data',
    'Production Data'[Date]>=endofworkover && 'Production Data'[Well Pair] = EARLIER('Production Data'[Well Pair]) && [Allocated Oil Production (m3/d)] >0)

//this will filter to dates before the workover
var beforeworkover = FILTER('Production Data',
    'Production Data'[Date]<startofworkover && 'Production Data'[Well Pair] = EARLIER('Production Data'[Well Pair]) && [Allocated Oil Production (m3/d)] >0)

var result1 = SWITCH(TRUE(),'Production Data'[Date] = startofworkover,0,'Production Data'[Date]>=endofworkover,RANKX(afterworkover,'Production Data'[Date],,ASC,Dense),'Production Data'[Date]<startofworkover,RANKX(beforeworkover,'Production Data'[Date],,DESC,Dense)*-1)

return result1


问:
Geoviews map 403 load error in python flask Application
I am trying to generate a map with data to be displayed in a flask application. All that is displayed when I run the app is Figure(id='1021', ...). I also get this error in console: [Error] Failed to load resource: the server responded with a status of 403 () (bokeh.min.js.map, line 0). Any Ideas?

app.py

```<code>from flask import Flask, render_template
import geoviews as gv
import project_4 as map
import holoviews as hv
import geoviews.tile_sources as gvts
import pandas as pd
from bokeh.models import HoverTool
from geoviews import dim, opts
import numpy as np

app = Flask(__name__)

@app.route("/")
def index():
     # Load the data and create the GeoViews points
    college_data = pd.read_csv('updated_locations.csv')
    college_gv_points = gv.Points(college_data, ['longitude', 'latitude'], ['university', 'num_students_attended'])

    # Create the hover tool
    tooltips = [('Unviversity', '@university'),
                ('Attendees', '@num_students_attended'),]
    hover = HoverTool(tooltips=tooltips)

    # Create the light and dark plots
    light_plot = (gvts.CartoLight * college_gv_points).opts(
        opts.Points(alpha=0.3,
                    hover_line_color='black',
                    color = 'blue', line_color='black', xaxis=None, yaxis=None,
                    tools=[hover],size=np.sqrt(dim('num_students_attended'))*2,
                    hover_fill_color='blue', hover_fill_alpha=0.2))

    dark_plot = (gvts.CartoDark.options(alpha=0.8) * college_gv_points).opts(
        opts.Points(alpha=0.6,
                    hover_line_color='black',
                    color = 'orange', line_color=None, xaxis=None, yaxis=None,
                    tools=[hover],size=np.sqrt(dim('num_students_attended'))*2,
                    hover_fill_color='orange', hover_fill_alpha=0.4))

    # Render the map using Holoviews
    hv_points = hv.render(dark_plot)
    return render_template('index.html', plot=hv_points)

if __name__ == '__main__':
    app.run(port=8000, debug=True)

</code>```

index.html

```<code><!DOCTYPE html>
<html>
  <head>
    <link
      href="http://cdn.pydata.org/bokeh/release/bokeh-1.3.4.min.css"
      rel="stylesheet"
      type="text/css"
    />
    <script src="http://cdn.pydata.org/bokeh/release/bokeh-1.3.4.min.js"></script>
  </head>
  <body>
    {{ plot | safe }}
  </body>
</html>
</code>```

Body:
I am trying to generate a map with data to be displayed in a flask application. All that is displayed when I run the app is Figure(id='1021', ...). I also get this error in console: [Error] Failed to load resource: the server responded with a status of 403 () (bokeh.min.js.map, line 0). Any Ideas?

app.py

from flask import Flask, render_template
import geoviews as gv
import project_4 as map
import holoviews as hv
import geoviews.tile_sources as gvts
import pandas as pd
from bokeh.models import HoverTool
from geoviews import dim, opts
import numpy as np

app = Flask(__name__)

@app.route("/")
def index():
     # Load the data and create the GeoViews points
    college_data = pd.read_csv('updated_locations.csv')
    college_gv_points = gv.Points(college_data, ['longitude', 'latitude'], ['university', 'num_students_attended'])

    # Create the hover tool
    tooltips = [('Unviversity', '@university'),
                ('Attendees', '@num_students_attended'),]
    hover = HoverTool(tooltips=tooltips)

    # Create the light and dark plots
    light_plot = (gvts.CartoLight * college_gv_points).opts(
        opts.Points(alpha=0.3,
                    hover_line_color='black',
                    color = 'blue', line_color='black', xaxis=None, yaxis=None,
                    tools=[hover],size=np.sqrt(dim('num_students_attended'))*2,
                    hover_fill_color='blue', hover_fill_alpha=0.2))

    dark_plot = (gvts.CartoDark.options(alpha=0.8) * college_gv_points).opts(
        opts.Points(alpha=0.6,
                    hover_line_color='black',
                    color = 'orange', line_color=None, xaxis=None, yaxis=None,
                    tools=[hover],size=np.sqrt(dim('num_students_attended'))*2,
                    hover_fill_color='orange', hover_fill_alpha=0.4))

    # Render the map using Holoviews
    hv_points = hv.render(dark_plot)
    return render_template('index.html', plot=hv_points)

if __name__ == '__main__':
    app.run(port=8000, debug=True)

index.html

<!DOCTYPE html>

    <link
      href="http://cdn.pydata.org/bokeh/release/bokeh-1.3.4.min.css"
      rel="stylesheet"
      type="text/css"
    />

    {{ plot | safe }}


问:
Importing and exporting files from flutter app on mobile devices
Developing an application with database backend (sembast) I ran into an interesting question:
What is really (I mean REALLY) proper way to work with files in flutter.

Long must read
Having database I want to: import files, export files without too much fuss from/to local file system.
Now as I get it there is a "user space" on android (minSdkVersion: 21) that is accessible and everything outside it works on some SDK version, not all of them.

Issues by numbers:

There is no reliable way to get "Downloads" dir for all platforms (at least mobile ones).

What's the point exporting to /data/user/0/app_name/bla-bla-bla if we can't read it with file explorer?

Import from /storage/emulated/0/Download just fails with no permissions. (That's considering my Manifest has READ/WRITE_EXTERNAL_STORAGE).

Now I wonder, if there is a way to export json file somewhere on file system from where I could later import data to app with no permission issue? Ideally it would be great to have a class or module that delivers cross platform set of locations.


问:
List = csv.collect(), then df.column.isin(List)) not working?
After looking at the documentation and looking at some stackoverflow posts, I tried two different methods, but I feel I might be doing something wrong before that.

To start off, this is what some_list_without_header.csv looks like:

```<code>12345
23456
34567
</code>```
```<code>schema_for_list = StructType([StructField('_c0', StringType())])

some_list = spark.read.csv("some_list_without_header.csv", header=False, schema = schema_for_list).collect()

###

schema_for_data = StructType([
  StructField('COLUMN_TO_CHECK', StringType()),
  StructField('COLUMN2', StringType())
])

data = spark.read.csv("data.csv", header = True, schema = schema_for_data)

### Tried few ways, here are couple examples, neither working

data.filter(data.COLUMN_TO_CHECK.isin(some_list))

data.where(F.col('COLUMN_TO_CHECK').isin(some_list))
</code>```

Here is the error message

```<code>Py4JJavaError: An error occurred while calling z:org.apache.spark.sql.functions.lit.
: org.apache.spark.SparkRuntimeException: The feature is not supported: literal for '[EXAMPLE_NUMBER_STRING]' of class java.util.ArrayList.
    at org.apache.spark.sql.errors.QueryExecutionErrors$.literalTypeUnsupportedError(QueryExecutionErrors.scala:296)
    at org.apache.spark.sql.catalyst.expressions.Literal$.apply(literals.scala:101)
    at org.apache.spark.sql.functions$.lit(functions.scala:125)
    at org.apache.spark.sql.functions.lit(functions.scala)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.ClientServerConnection.waitForCommands(ClientServerConnection.java:182)
    at py4j.ClientServerConnection.run(ClientServerConnection.java:106)
    at java.base/java.lang.Thread.run(Thread.java:829)
</code>```

Body:
After looking at the documentation and looking at some stackoverflow posts, I tried two different methods, but I feel I might be doing something wrong before that.

To start off, this is what some_list_without_header.csv looks like:

12345
23456
34567

schema_for_list = StructType([StructField('_c0', StringType())])

some_list = spark.read.csv("some_list_without_header.csv", header=False, schema = schema_for_list).collect()

###

schema_for_data = StructType([
  StructField('COLUMN_TO_CHECK', StringType()),
  StructField('COLUMN2', StringType())
])

data = spark.read.csv("data.csv", header = True, schema = schema_for_data)

### Tried few ways, here are couple examples, neither working

data.filter(data.COLUMN_TO_CHECK.isin(some_list))

data.where(F.col('COLUMN_TO_CHECK').isin(some_list))

Here is the error message

Py4JJavaError: An error occurred while calling z:org.apache.spark.sql.functions.lit.
: org.apache.spark.SparkRuntimeException: The feature is not supported: literal for '[EXAMPLE_NUMBER_STRING]' of class java.util.ArrayList.
    at org.apache.spark.sql.errors.QueryExecutionErrors$.literalTypeUnsupportedError(QueryExecutionErrors.scala:296)
    at org.apache.spark.sql.catalyst.expressions.Literal$.apply(literals.scala:101)
    at org.apache.spark.sql.functions$.lit(functions.scala:125)
    at org.apache.spark.sql.functions.lit(functions.scala)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.ClientServerConnection.waitForCommands(ClientServerConnection.java:182)
    at py4j.ClientServerConnection.run(ClientServerConnection.java:106)
    at java.base/java.lang.Thread.run(Thread.java:829)


问:
html email form multi attachment via phpmailer no composer question/issue
I am having trouble getting form to send attachments. It will either hang up or not send them and the error file shows nothing. Site is on a shared hosting server. The form works without attachments.

I am not a coder but i have searched this site and most of the information i have found refers to editing files created by composer which i am not using. Do I need to need to create a temp folder for the files before they are attached and if I do where do I define the path? The php code below is what I found for multiple attachments without composer and have been trying to adapt without success. Below is the code for attaching the file in the html form (I can post the entire html form if needed but since it works i did not see the need) and the php mail file any help would be appreciated.

```<code>    <div class="form-group">
      <label class="control-label col-sm-2" for="lname">Attach File:</label>
      <div class="col-sm-10">
        <input type="file" class="form-control" id="attachFile" name="attachFile[]" multiple="multiple">
      </div>
    </div>
    <div class="form-group">
      <label class="control-label col-sm-2" for="comment">Message:</label>
      <div class="col-sm-10">
        <textarea class="form-control" rows="5" name="message" id="message"></textarea>
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-offset-2 col-sm-10">
        <button type="submit" class="btn btn-default" name="sendEmail">Send Email</button>
-------------------------------------------------------------------------------------------------------------------
<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once 'PHPMailer/PHPMailer/src/PHPMailer.php';
require_once 'PHPMailer/PHPMailer/src/SMTP.php';

$msg = ''; // start with a blank message
$msg .= 'Email: ' . $_POST['email'] . "\n";
$msg .= 'City: ' . $_POST['city'] . "\n";
$msg .= 'State: ' . $_POST['state'] . "\n";
$msg .= 'Telephone: ' . $_POST['phone'] . "\n";
$msg .= 'Message: ' . $_POST['message'] . "\n";

if (array_key_exists('attachFile', $_FILES)) {

    $mail = new PHPMailer();
    $mail->IsSMTP(); // telling the class to use SMTP
    $mail->Host = 'mail.domain.com'; // SMTP server
    $mail->Username = 'form@domain.com';
    $mail->Password = 'password';
    $mail->setFrom ('form@domain.com');
    $mail->AddAddress ('user@domain.com');
    $mail->Subject = "Info Request";
    $mail->Body = $msg;
    $mail->WordWrap = 50;
    #  $mail->Port = 465;
    for ($ct = 0, $ctMax = count($_FILES['attachFile']['tmp_name']); $ct < $ctMax; $ct++) {
        //Extract an extension from the provided filename
        $ext = PHPMailer::mb_pathinfo($_FILES['attachFile']['name'][$ct], PATHINFO_EXTENSION);
        //Define a safe location to move the uploaded file to, preserving the extension
        $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['attachFile']['name'][$ct])) . '.' . $ext;
        $filename = $_FILES['attachFile']['name'][$ct];
        if (move_uploaded_file($_FILES['attachFile']['tmp_name'][$ct], $uploadfile)) {
            if (!$mail->addAttachment($uploadfile, $filename)) {
                $msg .= 'Failed to attach file ' . $filename;
            }
        } else {
            $msg .= 'Failed to move file to ' . $uploadfile;
        }
    }
    if (!$mail->send()) {
        $msg .= 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        $msg .= 'Message sent!';
    }
}
# $return = $mail->Send();
?>
<html>
<head>
//<meta HTTP-EQUIV="refresh" Content="0;url=thankyou.html">
</head>
<body bgcolor="#366A7F">
</body>
</html>

</code>```

Body:
I am having trouble getting form to send attachments. It will either hang up or not send them and the error file shows nothing. Site is on a shared hosting server. The form works without attachments.

I am not a coder but i have searched this site and most of the information i have found refers to editing files created by composer which i am not using. Do I need to need to create a temp folder for the files before they are attached and if I do where do I define the path? The php code below is what I found for multiple attachments without composer and have been trying to adapt without success. Below is the code for attaching the file in the html form (I can post the entire html form if needed but since it works i did not see the need) and the php mail file any help would be appreciated.

      Attach File:

        <input type="file" class="form-control" id="attachFile" name="attachFile[]" multiple="multiple">

      Message:

        <textarea class="form-control" rows="5" name="message" id="message"></textarea>

        <button type="submit" class="btn btn-default" name="sendEmail">Send Email</button>
-------------------------------------------------------------------------------------------------------------------
<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once 'PHPMailer/PHPMailer/src/PHPMailer.php';
require_once 'PHPMailer/PHPMailer/src/SMTP.php';

$msg = ''; // start with a blank message
$msg .= 'Email: ' . $_POST['email'] . "\n";
$msg .= 'City: ' . $_POST['city'] . "\n";
$msg .= 'State: ' . $_POST['state'] . "\n";
$msg .= 'Telephone: ' . $_POST['phone'] . "\n";
$msg .= 'Message: ' . $_POST['message'] . "\n";

if (array_key_exists('attachFile', $_FILES)) {

    $mail = new PHPMailer();
    $mail->IsSMTP(); // telling the class to use SMTP
    $mail->Host = 'mail.domain.com'; // SMTP server
    $mail->Username = 'form@domain.com';
    $mail->Password = 'password';
    $mail->setFrom ('form@domain.com');
    $mail->AddAddress ('user@domain.com');
    $mail->Subject = "Info Request";
    $mail->Body = $msg;
    $mail->WordWrap = 50;
    #  $mail->Port = 465;
    for ($ct = 0, $ctMax = count($_FILES['attachFile']['tmp_name']); $ct < $ctMax; $ct++) {
        //Extract an extension from the provided filename
        $ext = PHPMailer::mb_pathinfo($_FILES['attachFile']['name'][$ct], PATHINFO_EXTENSION);
        //Define a safe location to move the uploaded file to, preserving the extension
        $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['attachFile']['name'][$ct])) . '.' . $ext;
        $filename = $_FILES['attachFile']['name'][$ct];
        if (move_uploaded_file($_FILES['attachFile']['tmp_name'][$ct], $uploadfile)) {
            if (!$mail->addAttachment($uploadfile, $filename)) {
                $msg .= 'Failed to attach file ' . $filename;
            }
        } else {
            $msg .= 'Failed to move file to ' . $uploadfile;
        }
    }
    if (!$mail->send()) {
        $msg .= 'Mailer Error: ' . $mail->ErrorInfo;
    } else {
        $msg .= 'Message sent!';
    }
}
# $return = $mail->Send();
?>

//<meta HTTP-EQUIV="refresh" Content="0;url=thankyou.html">


问:
Getting err uploading csv files to a MySql Server (version 8.0.31). Error 1290 (HY000): The MySql server is running with the --secure-file-priv option
Complete error:

```<code>ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
</code>```

This is the sql statement I am running which creates the error:

```<code>CREATE DATABASE IF NOT EXISTS db;

USE db;

CREATE TABLE IF NOT EXISTS A(
    id int NOT NULL,
    description text NOT NULL,
    PRIMARY KEY (id)
);

LOAD DATA INFILE 'C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\a.csv'
INTO TABLE goal
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
</code>```

What I have tried to fix this error: in the my.ini file:

```<code># This variable is used to limit the effect of data import and export operations, such as
# those performed by the LOAD DATA and SELECT ... INTO OUTFILE statements and the
# LOAD_FILE() function. These operations are permitted only to users who have the FILE privilege.
secure-file-priv=NULL
</code>```

I have also tried commenting the line out. Still get the error mentioned above.

I moved a.csv to C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\ because I thought the premise of secure-file-priv was to only allow uploads from specific folder.

I do not know what to do. Neither solution worked. Will respond to any questions right away.

Body:
Complete error:

ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

This is the sql statement I am running which creates the error:

CREATE DATABASE IF NOT EXISTS db;

USE db;

CREATE TABLE IF NOT EXISTS A(
    id int NOT NULL,
    description text NOT NULL,
    PRIMARY KEY (id)
);

LOAD DATA INFILE 'C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\a.csv'
INTO TABLE goal
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;

What I have tried to fix this error: in the my.ini file:

# This variable is used to limit the effect of data import and export operations, such as
# those performed by the LOAD DATA and SELECT ... INTO OUTFILE statements and the
# LOAD_FILE() function. These operations are permitted only to users who have the FILE privilege.
secure-file-priv=NULL

I have also tried commenting the line out. Still get the error mentioned above.

I moved a.csv to C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\ because I thought the premise of secure-file-priv was to only allow uploads from specific folder.

I do not know what to do. Neither solution worked. Will respond to any questions right away.


问:
How can I change the field of an object by specifying its path?
Is it really possible to specify an array of "paths" to the fields in advance in order to change them inside the object later?
Without duplicating the Do() call

class Item
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }
    public int Value3 { get; set; }
    public int Value4 { get; set; }
}
```
<pre class="lang-cs prettyprint-override"><code>var targetItem = new Item();
var common1 = new Item();
var common2 = new Item();

var functions = new List<Func<Item, int>>
            {
                i => i.Value1,
                i => i.Value2,
                i => i.Value3,
                i => i.Value4
            };

foreach(var func in functions)
{
    func(targetItem) = Do(func); //something
}

int Do(Func<Item, int> func)
{
    //super hard logic
    return func(common1) + func(common2);
}
</code>```

this example outputs

func(targetItem) = Do(func); ->
CS0131  The left-hand side of an assignment must be a variable, property or indexer

targetItem.Value1 = Do(i => i.Value1);
targetItem.Value2 = Do(i => i.Value2);
targetItem.Value3 = Do(i => i.Value3);
targetItem.Value4 = Do(i => i.Value4);
```

I can certainly do this, but it's not very nice :)

Thanks

Body:
Is it really possible to specify an array of "paths" to the fields in advance in order to change them inside the object later?
Without duplicating the Do() call

class Item
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }
    public int Value3 { get; set; }
    public int Value4 { get; set; }
}

var targetItem = new Item();
var common1 = new Item();
var common2 = new Item();

var functions = new List<Func<Item, int>>
            {
                i => i.Value1,
                i => i.Value2,
                i => i.Value3,
                i => i.Value4
            };

foreach(var func in functions)
{
    func(targetItem) = Do(func); //something
}

int Do(Func<Item, int> func)
{
    //super hard logic
    return func(common1) + func(common2);
}

this example outputs

func(targetItem) = Do(func); ->
CS0131  The left-hand side of an assignment must be a variable, property or indexer

targetItem.Value1 = Do(i => i.Value1);
targetItem.Value2 = Do(i => i.Value2);
targetItem.Value3 = Do(i => i.Value3);
targetItem.Value4 = Do(i => i.Value4);

I can certainly do this, but it's not very nice :)

Thanks


问:
Quantizing JPEG files using Pillow increases file size
I'm trying to use the Pillow library to quantize JPEGs to decrease file size but I find that quantizing and converting back to RGB results in a larger file size.

I am saving the JPEG with the default quality of 75. I have also tried converting the source file to PNG, using pngquant, and converting back. I know that Tinypng works on JPEG files so I'm wondering if I'm missing anything.

```<code>test = Image.open(filepath)
test = test.quantize()
test = test.convert('RGB')
test.save('test.jpeg', optimize = True, quality = 75)
</code>```

Image File

Body:
I'm trying to use the Pillow library to quantize JPEGs to decrease file size but I find that quantizing and converting back to RGB results in a larger file size.

I am saving the JPEG with the default quality of 75. I have also tried converting the source file to PNG, using pngquant, and converting back. I know that Tinypng works on JPEG files so I'm wondering if I'm missing anything.

test = Image.open(filepath)
test = test.quantize()
test = test.convert('RGB')
test.save('test.jpeg', optimize = True, quality = 75)

Image File


问:
I can't create a Spam Group Telegram Bot
I'm trying to create a bot that, given the message I give it through a special command, is able to send the message I previously gave it to the public Telegram groups every certain time given by me.

I'm looking for every solution but I can't achieve it at all, I know it can be done 100%, I've searched everywhere but I can't. Can you help me please?