问:
Concatenation of Pandas Dataframes takes extremely long
Im building Dataframes in the following way inside a loop and save them into a list:

```<code>frame_list = []

df1 = pd.DataFrame(data={'a':0,'b':1,'c':1},columns=['a', 'b', 'c'], index=['z'])

df2 = pd.DataFrame(data={'a': 0, 'b': 1, 'c': 1, 'd': 2}, columns=['a', 'b', 'c', 'd'], index=['y'])

frame_list.append(df1)

frame_list.append(df2)
</code>```

After filling the list (round about 1000 entries so 1000 single Dataframes) I want to concatenate all of them into one big Dataframe.

```<code>final_frame = pd.concat(dataframe_list, axis=0)
</code>```

Anyone knows how to speed up that process? For axis = 1 it runs fast, but thats not the representation of the data I want.

Best regards

I tried what I described and I was expecting a faster runtime.

Body:
Im building Dataframes in the following way inside a loop and save them into a list:

frame_list = []

df1 = pd.DataFrame(data={'a':0,'b':1,'c':1},columns=['a', 'b', 'c'], index=['z'])

df2 = pd.DataFrame(data={'a': 0, 'b': 1, 'c': 1, 'd': 2}, columns=['a', 'b', 'c', 'd'], index=['y'])

frame_list.append(df1)

frame_list.append(df2)

After filling the list (round about 1000 entries so 1000 single Dataframes) I want to concatenate all of them into one big Dataframe.

final_frame = pd.concat(dataframe_list, axis=0)

Anyone knows how to speed up that process? For axis = 1 it runs fast, but thats not the representation of the data I want.

Best regards

I tried what I described and I was expecting a faster runtime.


来源: stackexchange

问:
Strip everything after the ampersand in a URL
I'm trying to write a bash script for Alfred which will let me put in a custom time ($time) to link to a YouTube video ($url)

If one or more ampersands are present remove everything after the first ampersand (If there is no ampersand present just keep the existing url):

https://www.youtube.com/watch?v=n6AwsVGJDOY&t=121s&ab_channel=BigThink

would become:

https://www.youtube.com/watch?v=n6AwsVGJDOY

then I will input in Alfred a time eg 3m02s and it will append it to the end of the URL
https://www.youtube.com/watch?v=n6AwsVGJDOY&t=3m02s

```<code>preg_match('/[^&]+/', $url, $match);
$url2 = $match[0];

echo "<a href='$url2&t=$time'>$time</a>" | textutil -stdin -format html -convert rtf -stdout | pbcopy
</code>```

Any help would be appreciated!

The linked question did not answer my query (at least in a way I understand)

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write a bash script for Alfred which will let me put in a custom time ($time) to link to a YouTube video ($url)

If one or more ampersands are present remove everything after the first ampersand (If there is no ampersand present just keep the existing url):

https://www.youtube.com/watch?v=n6AwsVGJDOY&t=121s&ab_channel=BigThink

would become:

https://www.youtube.com/watch?v=n6AwsVGJDOY

then I will input in Alfred a time eg 3m02s and it will append it to the end of the URL
https://www.youtube.com/watch?v=n6AwsVGJDOY&t=3m02s

preg_match('/[^&]+/', $url, $match);
$url2 = $match[0];

echo "$time" | textutil -stdin -format html -convert rtf -stdout | pbcopy

Any help would be appreciated!

The linked question did not answer my query (at least in a way I understand)


问:
does doesn't intel (r) xeon (r) platinum 8370c cpu support epid?
I have a server with cpu : intel (r) xeon (r) platinum 8370c but EPID attestation does not work in this server .Does intel (r) xeon (r) platinum 8370c cpu support EPID attestation? if not how can I use EPID in this CPU?</p>


问:
What is this GitHub "Note" header with icon and are there any other documented anywhere?
I accidentally discovered this nice header GitHub generates:

This is the original code:

```<code>> **Note**
> Make sure the Blazor CSS is imported correctly in `index.html` for `PageLoader` to work correctly:
>
> ```html
> <link href="<ProjectName>.styles.css" rel="stylesheet" />
> ```
</code>```

What's that blue header called? Is it documented anywhere? I have another header **IMPORTANT** but it isn't made into cool header like that.

Body:
I accidentally discovered this nice header GitHub generates:

This is the original code:

> **Note**
> Make sure the Blazor CSS is imported correctly in `index.html` for `PageLoader` to work correctly:
>
> ```html
> <link href="<ProjectName>.styles.css" rel="stylesheet" />
> ```

What's that blue header called? Is it documented anywhere? I have another header **IMPORTANT** but it isn't made into cool header like that.


问:
Axios with PATCH request via PROXY giving 400 BAD Request : Nodejs
Its working for GET, POST call with proxy and without proxy headers locally and when deployed to development server,
But PATCH returns 400 bad error with proxy on server

```<code>axios.patch("url",
{
  "archived": true,
},
{
    headers: {
        Accept: "Application/JSON",
        Authorization: string,
    };
    proxy: {
        host: "xyz.com",
        port: 80,
        auth: {
            username: any;
            password: string;
        };
    };
    timeout: number;
}
);
</code>```

Error: Request failed with status code 400
at createError (C:\ api\node_modules\axios\lib\core\createError.js:16:15)
at settle (C:\ api\node_modules\axios\lib\core\settle.js:17:12)
at IncomingMessage.handleStreamEnd (C:\ api\node_modules\axios\lib\adapters\http.js:269:11)
at IncomingMessage.emit (node:events:402:35)
at IncomingMessage.emit (node:domain:475:12)
at endReadableNT (node:internal/streams/readable:1343:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)

Body:
Its working for GET, POST call with proxy and without proxy headers locally and when deployed to development server,
But PATCH returns 400 bad error with proxy on server

axios.patch("url",
{
  "archived": true,
},
{
    headers: {
        Accept: "Application/JSON",
        Authorization: string,
    };
    proxy: {
        host: "xyz.com",
        port: 80,
        auth: {
            username: any;
            password: string;
        };
    };
    timeout: number;
}
);

Error: Request failed with status code 400
at createError (C:\ api\node_modules\axios\lib\core\createError.js:16:15)
at settle (C:\ api\node_modules\axios\lib\core\settle.js:17:12)
at IncomingMessage.handleStreamEnd (C:\ api\node_modules\axios\lib\adapters\http.js:269:11)
at IncomingMessage.emit (node:events:402:35)
at IncomingMessage.emit (node:domain:475:12)
at endReadableNT (node:internal/streams/readable:1343:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)


问:
Flutter-Firebase Reference Path Does Not Work Correctly
I want to get QR/Code Outputs data for title in Listtile and QRCode/Total Number for subtitle.

My code is below. I think everything seem good and have no idea why it doesn't work correctly.

enter image description here

Can anyone help me with this ?

```<code>class ScannedBarcode extends StatelessWidget {
  //const ScannedBarcode({super.key});

  final ref = FirebaseDatabase.instance.ref("QR Code");
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("QR/Barcode Data"),
        backgroundColor: Colors.orangeAccent[100],
        foregroundColor: Colors.black,
      ),
      backgroundColor: Colors.blueGrey,
      body: Column(
        children: [
          Spacer(
            flex: 1,
          ),
          Expanded(
            flex: 4,
            child: FirebaseAnimatedList(
                query: ref,
                defaultChild: Text('Loading'),
                itemBuilder: (context, snapshot, animation, index) {
                  return ListTile(
                    visualDensity: VisualDensity(vertical: 3),
                    contentPadding:
                        EdgeInsets.symmetric(vertical: 0.0, horizontal: 25.0),
                    tileColor: Colors.blueGrey[50],
                    shape: RoundedRectangleBorder(
                      side: BorderSide(color: Colors.blueGrey),
                      borderRadius: BorderRadius.circular(15.0),
                    ),
                    title: Text(
                        snapshot.child("QR Code/Outputs").value.toString()),
                    subtitle: Text(snapshot
                        .child("QR Code/Total Number")
                        .value
                        .toString()),
                  );
                }),
          ),
          Spacer(
            flex: 1,
          ),
        ],
      ),
    );
  }
}
</code>```

Body:
I want to get QR/Code Outputs data for title in Listtile and QRCode/Total Number for subtitle.

My code is below. I think everything seem good and have no idea why it doesn't work correctly.

enter image description here

Can anyone help me with this ?

class ScannedBarcode extends StatelessWidget {
  //const ScannedBarcode({super.key});

  final ref = FirebaseDatabase.instance.ref("QR Code");
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("QR/Barcode Data"),
        backgroundColor: Colors.orangeAccent[100],
        foregroundColor: Colors.black,
      ),
      backgroundColor: Colors.blueGrey,
      body: Column(
        children: [
          Spacer(
            flex: 1,
          ),
          Expanded(
            flex: 4,
            child: FirebaseAnimatedList(
                query: ref,
                defaultChild: Text('Loading'),
                itemBuilder: (context, snapshot, animation, index) {
                  return ListTile(
                    visualDensity: VisualDensity(vertical: 3),
                    contentPadding:
                        EdgeInsets.symmetric(vertical: 0.0, horizontal: 25.0),
                    tileColor: Colors.blueGrey[50],
                    shape: RoundedRectangleBorder(
                      side: BorderSide(color: Colors.blueGrey),
                      borderRadius: BorderRadius.circular(15.0),
                    ),
                    title: Text(
                        snapshot.child("QR Code/Outputs").value.toString()),
                    subtitle: Text(snapshot
                        .child("QR Code/Total Number")
                        .value
                        .toString()),
                  );
                }),
          ),
          Spacer(
            flex: 1,
          ),
        ],
      ),
    );
  }
}


问:
EF Core Ignore existing tables in DB
I have a old DB that I need to create a new module for which will include some new tables.
The DB currently has no Entity Framework so I want to just add my new tables and just work with them and ignore the previous ones.

This post says in previous versions of entity framework you just need to do this:

```<code>add-migration Initial -IgnoreChanges
</code>```

but EF Core does not support "Ignore Changes" as explained here.

I cannot find an alternative in Entity Framework Core.

How do I add my migrations for my specific tables whilst ignoring the rest of the existing database?

Title: EF Core Ignore existing tables in DB

Body:
I have a old DB that I need to create a new module for which will include some new tables.
The DB currently has no Entity Framework so I want to just add my new tables and just work with them and ignore the previous ones.

This post says in previous versions of entity framework you just need to do this:

add-migration Initial -IgnoreChanges

but EF Core does not support "Ignore Changes" as explained here.

I cannot find an alternative in Entity Framework Core.

How do I add my migrations for my specific tables whilst ignoring the rest of the existing database?


问:
change toolkit redux state inside of fetch
I just want to update state outside of component after server give me failed response.
the project is react native .

After a lot of online search on website like this , I learn that i need to import my store and use dispatch method. but when i import storage and dispatch it, it give me this error: Property 'crypto' doesn't exist .

this is my feachService.js code:

```<code>import { URL } from 'react-native-url-polyfill';
 import  { store } from '../store/index'
 import { errorSliceActions } from '../store/slices/global/errorSlice'

export default (url, isGet) => {
    let headers = {
        Referer: new URL(url).origin,
    }
    headers['X-Requested-With'] = 'XMLHttpRequest'

    return fetch(
        url,
        {
            method: (isGet ? 'GET' : 'POST'),
            headers: headers
        })
        .then(function (res) {
            return res.json();
        })
        .then(function (res)
        {
            if(res && res.isSuccess == false && res.message) {
                store.dispatch(errorSliceActions.add(res.message));
            }
            return {json: function() { return res; }};
        })
        .catch(function (error) { console.log(error.message); })

};
</code>```

this is my storage js file:

```<code>import { configureStore } from '@reduxjs/toolkit';

import errorSliceReducer from './slices/global/errorSlice';

export const store = configureStore({
  reducer: {
    errorSlice: errorSliceReducer
  }
});
</code>```

this is my error slice.js file:

```<code>import { createSlice } from "@reduxjs/toolkit"

function uuidv4() {
    return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
      (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
    );
  }

const errorSlice = createSlice({
    name: "errorSlice",
    initialState: {
        errors: [
        ]
    },
    reducers:
    {
        add: (state, action) => {
            const newItem = {
                id: uuidv4(),
                message: action.payload
            };
            return [...state, newItem];
        },
        remove: (state, action) => {
            return { errors: state.errors.filter(function(item) { return item.id != action.payload; }) }
        }
    }
  })

  export const errorSliceActions = errorSlice.actions;

  export default errorSlice.reducer
</code>```

and this is my code for executing fetch request

```<code>async function loadInfo (inputSearch, inputPage) {
      if(config.dataurl) {
        console.log(inputSearch);
        setIsLoading(true);
        const hasQuestionMark = config.dataurl.indexOf('?') > 0;
        let targetUrl = '/test/test' +  config.dataurl + (!hasQuestionMark ? '?' : '&');
        targetUrl += 'page=' + inputPage;
        targetUrl += '&search=' + inputSearch;
        console.log(targetUrl);
        const response = await feachService(appJSon.baseUrl + targetUrl , true);
        const responseData = await response.json();
        setIsLoading(false);
        if(responseData.pagination)
          setPagination(responseData.pagination);
        if(!responseData.results)
          setItems([]);
        else
          setItems(responseData.results);
      }
    }
</code>```
```<code> useEffect(() => {
        loadInfo('', 1).catch(function (error) { console.log(error.message); });
    }, [])
</code>```

what am i doing wrong ?

Body:
I just want to update state outside of component after server give me failed response.
the project is react native .

After a lot of online search on website like this , I learn that i need to import my store and use dispatch method. but when i import storage and dispatch it, it give me this error: Property 'crypto' doesn't exist .

this is my feachService.js code:

import { URL } from 'react-native-url-polyfill';
 import  { store } from '../store/index'
 import { errorSliceActions } from '../store/slices/global/errorSlice'

export default (url, isGet) => {
    let headers = {
        Referer: new URL(url).origin,
    }
    headers['X-Requested-With'] = 'XMLHttpRequest'

    return fetch(
        url,
        {
            method: (isGet ? 'GET' : 'POST'),
            headers: headers
        })
        .then(function (res) {
            return res.json();
        })
        .then(function (res)
        {
            if(res && res.isSuccess == false && res.message) {
                store.dispatch(errorSliceActions.add(res.message));
            }
            return {json: function() { return res; }};
        })
        .catch(function (error) { console.log(error.message); })

};

this is my storage js file:

import { configureStore } from '@reduxjs/toolkit';

import errorSliceReducer from './slices/global/errorSlice';

export const store = configureStore({
  reducer: {
    errorSlice: errorSliceReducer
  }
});

this is my error slice.js file:

import { createSlice } from "@reduxjs/toolkit"

function uuidv4() {
    return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
      (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
    );
  }

const errorSlice = createSlice({
    name: "errorSlice",
    initialState: {
        errors: [
        ]
    },
    reducers:
    {
        add: (state, action) => {
            const newItem = {
                id: uuidv4(),
                message: action.payload
            };
            return [...state, newItem];
        },
        remove: (state, action) => {
            return { errors: state.errors.filter(function(item) { return item.id != action.payload; }) }
        }
    }
  })

  export const errorSliceActions = errorSlice.actions;

  export default errorSlice.reducer

and this is my code for executing fetch request

async function loadInfo (inputSearch, inputPage) {
      if(config.dataurl) {
        console.log(inputSearch);
        setIsLoading(true);
        const hasQuestionMark = config.dataurl.indexOf('?') > 0;
        let targetUrl = '/test/test' +  config.dataurl + (!hasQuestionMark ? '?' : '&');
        targetUrl += 'page=' + inputPage;
        targetUrl += '&search=' + inputSearch;
        console.log(targetUrl);
        const response = await feachService(appJSon.baseUrl + targetUrl , true);
        const responseData = await response.json();
        setIsLoading(false);
        if(responseData.pagination)
          setPagination(responseData.pagination);
        if(!responseData.results)
          setItems([]);
        else
          setItems(responseData.results);
      }
    }

 useEffect(() => {
        loadInfo('', 1).catch(function (error) { console.log(error.message); });
    }, [])

what am i doing wrong ?


问:
Multiindex merge in dask
I am trying to inner merge two dask dataframes based on two ids namely doi and pmid.
The datasets look like this (only the head, feel free to modify the doi and pmid to construct a MWE):

dd_papers_all:

```<code>{'cited_by_count': {0: nan, 1: nan, 2: 9.0, 3: nan, 4: 30.0},
'cited_by_url': {0: 'None',
 1: 'None',
 2: "['W1968224982', 'W1977435724', 'W2003814720', 'W2006453929', 'W2015063028', 'W2139614344']",
 3: 'None',
 4: "['W181218938', 'W1969520123', 'W1970043627', 'W1977525191', 'W2006834484', 'W2057850214', 'W2062554850', 'W2070252209', 'W2098074569', 'W2123616561', 'W2150154625', 'W2408116868']"},
'authors': {0: "['Walczak M', 'Pawlaczyk J']",
 1: "['Ioan Oliver Avram']",
 2: "['T.M. Dmitrieva', 'T.P. Eremeeva', 'G.I. Alatortseva', 'Vadim I. Agol']",
 3: "['Djurdjina Ružić', 'Tatjana Vujović', 'Gabriela Libiaková', 'Radosav Cerović', 'Alena Gajdošová']",
 4: "['M. Harris']"},
'institutions': {0: '[]',
 1: '[]',
 2: "['Lomonosov Moscow State University', 'USSR Academy of Medical Sciences', 'Lomonosov Moscow State University', 'USSR Academy of Medical Sciences']",
 3: "['Fruit Research Institute', 'Fruit Research Institute', 'Institute of Plant Genetics and Biotechnology', 'Fruit Research Institute', 'Institute of Plant Genetics and Biotechnology']",
 4: "['Durban University of Technology']"},
'paper_id': {0: 'W155261221',
 1: 'W145424619',
 2: 'W1482328891',
 3: 'W1581876373',
 4: 'W1978891149'},
'pub_year_col': {0: 1969, 1: 2010, 2: 1980, 3: 2012, 4: 2008},
'level_0': {0: 'None', 1: 'None', 2: 'None', 3: 'None', 4: 'None'},
'level_1': {0: "['Ophthalmology', 'Pediatrics', 'Internal medicine', 'Endocrinology', 'Anatomy', 'Developmental psychology']",
 1: "['Risk analysis (engineering)', 'Manufacturing engineering', 'Industrial engineering', 'Operations research', 'Mechanical engineering', 'Epistemology', 'Climatology', 'Macroeconomics', 'Operating system']",
 2: "['Virology', 'Cell biology', 'Biochemistry', 'Quantum mechanics']",
 3: "['Horticulture', 'Botany', 'Biochemistry']",
 4: "['Pedagogy', 'Mathematics education', 'Paleontology', 'Social science', 'Neuroscience', 'Programming language', 'Quantum mechanics']"},
'level_2': {0: "['Craniopharyngioma', 'Fundus (uterus)', 'Girl', 'Ventricle', 'Fourth ventricle']",
 1: "['Process (computing)', 'Production (economics)', 'Machine tool', 'Quality (philosophy)', 'Productivity', 'Multiple-criteria decision analysis', 'Machining', 'Forcing (mathematics)']",
 2: "['Mechanism (biology)', 'Replication (statistics)', 'Virus', 'Gene']",
 3: "['Vaccinium', 'In vitro']",
 4: "['Negotiation', 'Reflective practice', 'Construct (python library)', 'Action research', 'Context (archaeology)', 'Reflective writing', 'Perception', 'Power (physics)']"},
'doi': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan},
'pmid': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan},
'mag': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan}}
</code>```

and dd_green_papers_frontier:

```<code>{'paperid': {0: 2006817976,
 1: 2006817976,
 2: 1972698438,
 3: 1968223008,
 4: 2149313415},
'uspto': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0},
'doi': {0: '10.1016/J.AB.2003.07.015',
 1: '10.1016/J.AB.2003.07.015',
 2: '10.1007/S002170100404',
 3: '10.1007/S002170100336',
 4: '10.3324/%X'},
'pmid': {0: 14656521.0, 1: 14656521.0, 2: nan, 3: nan, 4: 12414351.0},
'publn_nr_x': {0: 2693, 1: 2693, 2: 2693, 3: 2693, 4: 2715},
'paperyear': {0: 2003.0, 1: 2003.0, 2: 2001.0, 3: 2001.0, 4: 2002.0},
'papertitle': {0: 'development of melting temperature based sybr green i polymerase chain reaction methods for multiplex genetically modified organism detection',
 1: 'development of melting temperature based sybr green i polymerase chain reaction methods for multiplex genetically modified organism detection',
 2: 'event specific detection of roundup ready soya using two different real time pcr detection chemistries',
 3: 'characterisation of the roundup ready soybean insert',
 4: 'hepatitis c virus infection in a hematology ward evidence for nosocomial transmission and impact on hematologic disease outcome'},
'magfieldid': {0: 149629.0,
 1: 149629.0,
 2: 143660080.0,
 3: 40767140.0,
 4: 2780572000.0},
'oecd_field': {0: '2. Engineering and Technology',
 1: '2. Engineering and Technology',
 2: '1. Natural Sciences',
 3: '1. Natural Sciences',
 4: '3. Medical and Health Sciences'},
'oecd_subfield': {0: '2.11 Other engineering and technologies',
 1: '2.11 Other engineering and technologies',
 2: '1.06 Biological sciences',
 3: '1.06 Biological sciences',
 4: '3.02 Clinical medicine'},
'wosfield': {0: 'Food Science & Technology',
 1: 'Food Science & Technology',
 2: 'Biochemical Research Methods',
 3: 'Biochemistry & Molecular Biology',
 4: 'Hematology'},
'author': {0: 2083283000.0, 1: 2808753700.0, 2: nan, 3: 2315123700.0, 4: nan},
'country_alpha3': {0: 'ESP', 1: 'ESP', 2: nan, 3: 'BEL', 4: nan},
'country_2': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan},
'docdb_family_id': {0: 37137417,
 1: 37137417,
 2: 37137417,
 3: 37137417,
 4: 35462722},
'publn_nr_y': {0: 2693.0, 1: 2693.0, 2: 2693.0, 3: 2693.0, 4: 2715.0},
'cpc_class_interest': {0: 'Y02', 1: 'Y02', 2: 'Y02', 3: 'Y02', 4: 'Y02'}}
</code>```

Specifically, doi is a string variable and pmid is a float.
Now, what I am trying to do (please feel free to suggest me a smarter way to merge the db since they are very large) is the following:

```<code>dd_papall_green = dd_papers_all.merge(
    dd_green_papers_frontier,
    how="inner",
    on=["pmid", "doi"]
).persist()
</code>```

but it fails with the error:

```<code>ValueError: You are trying to merge on object and float64 columns. If you wish to proceed you should use pd.concat
</code>```

Hence, what I did is to convert both doi and pmid to float as:

```<code>dd_papers_all['pmid']=dd_papers_all['pmid'].astype(float)
dd_papers_all['doi']=dd_papers_all['doi'].astype(float)
dd_green_papers_frontier['pmid']=dd_green_papers_frontier['pmid'].astype(float)
dd_green_papers_frontier['doi']=dd_green_papers_frontier['doi'].astype(float)
</code>```

but again the merge fails.

How can I perform the described merge?

Title: Multiindex merge in dask

Body:
I am trying to inner merge two dask dataframes based on two ids namely doi and pmid.
The datasets look like this (only the head, feel free to modify the doi and pmid to construct a MWE):

dd_papers_all:

{'cited_by_count': {0: nan, 1: nan, 2: 9.0, 3: nan, 4: 30.0},
'cited_by_url': {0: 'None',
 1: 'None',
 2: "['W1968224982', 'W1977435724', 'W2003814720', 'W2006453929', 'W2015063028', 'W2139614344']",
 3: 'None',
 4: "['W181218938', 'W1969520123', 'W1970043627', 'W1977525191', 'W2006834484', 'W2057850214', 'W2062554850', 'W2070252209', 'W2098074569', 'W2123616561', 'W2150154625', 'W2408116868']"},
'authors': {0: "['Walczak M', 'Pawlaczyk J']",
 1: "['Ioan Oliver Avram']",
 2: "['T.M. Dmitrieva', 'T.P. Eremeeva', 'G.I. Alatortseva', 'Vadim I. Agol']",
 3: "['Djurdjina Ružić', 'Tatjana Vujović', 'Gabriela Libiaková', 'Radosav Cerović', 'Alena Gajdošová']",
 4: "['M. Harris']"},
'institutions': {0: '[]',
 1: '[]',
 2: "['Lomonosov Moscow State University', 'USSR Academy of Medical Sciences', 'Lomonosov Moscow State University', 'USSR Academy of Medical Sciences']",
 3: "['Fruit Research Institute', 'Fruit Research Institute', 'Institute of Plant Genetics and Biotechnology', 'Fruit Research Institute', 'Institute of Plant Genetics and Biotechnology']",
 4: "['Durban University of Technology']"},
'paper_id': {0: 'W155261221',
 1: 'W145424619',
 2: 'W1482328891',
 3: 'W1581876373',
 4: 'W1978891149'},
'pub_year_col': {0: 1969, 1: 2010, 2: 1980, 3: 2012, 4: 2008},
'level_0': {0: 'None', 1: 'None', 2: 'None', 3: 'None', 4: 'None'},
'level_1': {0: "['Ophthalmology', 'Pediatrics', 'Internal medicine', 'Endocrinology', 'Anatomy', 'Developmental psychology']",
 1: "['Risk analysis (engineering)', 'Manufacturing engineering', 'Industrial engineering', 'Operations research', 'Mechanical engineering', 'Epistemology', 'Climatology', 'Macroeconomics', 'Operating system']",
 2: "['Virology', 'Cell biology', 'Biochemistry', 'Quantum mechanics']",
 3: "['Horticulture', 'Botany', 'Biochemistry']",
 4: "['Pedagogy', 'Mathematics education', 'Paleontology', 'Social science', 'Neuroscience', 'Programming language', 'Quantum mechanics']"},
'level_2': {0: "['Craniopharyngioma', 'Fundus (uterus)', 'Girl', 'Ventricle', 'Fourth ventricle']",
 1: "['Process (computing)', 'Production (economics)', 'Machine tool', 'Quality (philosophy)', 'Productivity', 'Multiple-criteria decision analysis', 'Machining', 'Forcing (mathematics)']",
 2: "['Mechanism (biology)', 'Replication (statistics)', 'Virus', 'Gene']",
 3: "['Vaccinium', 'In vitro']",
 4: "['Negotiation', 'Reflective practice', 'Construct (python library)', 'Action research', 'Context (archaeology)', 'Reflective writing', 'Perception', 'Power (physics)']"},
'doi': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan},
'pmid': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan},
'mag': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan}}

and dd_green_papers_frontier:

{'paperid': {0: 2006817976,
 1: 2006817976,
 2: 1972698438,
 3: 1968223008,
 4: 2149313415},
'uspto': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0},
'doi': {0: '10.1016/J.AB.2003.07.015',
 1: '10.1016/J.AB.2003.07.015',
 2: '10.1007/S002170100404',
 3: '10.1007/S002170100336',
 4: '10.3324/%X'},
'pmid': {0: 14656521.0, 1: 14656521.0, 2: nan, 3: nan, 4: 12414351.0},
'publn_nr_x': {0: 2693, 1: 2693, 2: 2693, 3: 2693, 4: 2715},
'paperyear': {0: 2003.0, 1: 2003.0, 2: 2001.0, 3: 2001.0, 4: 2002.0},
'papertitle': {0: 'development of melting temperature based sybr green i polymerase chain reaction methods for multiplex genetically modified organism detection',
 1: 'development of melting temperature based sybr green i polymerase chain reaction methods for multiplex genetically modified organism detection',
 2: 'event specific detection of roundup ready soya using two different real time pcr detection chemistries',
 3: 'characterisation of the roundup ready soybean insert',
 4: 'hepatitis c virus infection in a hematology ward evidence for nosocomial transmission and impact on hematologic disease outcome'},
'magfieldid': {0: 149629.0,
 1: 149629.0,
 2: 143660080.0,
 3: 40767140.0,
 4: 2780572000.0},
'oecd_field': {0: '2. Engineering and Technology',
 1: '2. Engineering and Technology',
 2: '1. Natural Sciences',
 3: '1. Natural Sciences',
 4: '3. Medical and Health Sciences'},
'oecd_subfield': {0: '2.11 Other engineering and technologies',
 1: '2.11 Other engineering and technologies',
 2: '1.06 Biological sciences',
 3: '1.06 Biological sciences',
 4: '3.02 Clinical medicine'},
'wosfield': {0: 'Food Science & Technology',
 1: 'Food Science & Technology',
 2: 'Biochemical Research Methods',
 3: 'Biochemistry & Molecular Biology',
 4: 'Hematology'},
'author': {0: 2083283000.0, 1: 2808753700.0, 2: nan, 3: 2315123700.0, 4: nan},
'country_alpha3': {0: 'ESP', 1: 'ESP', 2: nan, 3: 'BEL', 4: nan},
'country_2': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan},
'docdb_family_id': {0: 37137417,
 1: 37137417,
 2: 37137417,
 3: 37137417,
 4: 35462722},
'publn_nr_y': {0: 2693.0, 1: 2693.0, 2: 2693.0, 3: 2693.0, 4: 2715.0},
'cpc_class_interest': {0: 'Y02', 1: 'Y02', 2: 'Y02', 3: 'Y02', 4: 'Y02'}}

Specifically, doi is a string variable and pmid is a float.
Now, what I am trying to do (please feel free to suggest me a smarter way to merge the db since they are very large) is the following:

dd_papall_green = dd_papers_all.merge(
    dd_green_papers_frontier,
    how="inner",
    on=["pmid", "doi"]
).persist()

but it fails with the error:

ValueError: You are trying to merge on object and float64 columns. If you wish to proceed you should use pd.concat

Hence, what I did is to convert both doi and pmid to float as:

dd_papers_all['pmid']=dd_papers_all['pmid'].astype(float)
dd_papers_all['doi']=dd_papers_all['doi'].astype(float)
dd_green_papers_frontier['pmid']=dd_green_papers_frontier['pmid'].astype(float)
dd_green_papers_frontier['doi']=dd_green_papers_frontier['doi'].astype(float)

but again the merge fails.

How can I perform the described merge?


问:
Cannot connect to mqtt by using esp32
```<code>WiFi connected
IP address:
192.168.1.xxx
Attempting MQTT connection...connected
Guru Meditation Error: Core  1 panic'ed (IllegalInstruction). Exception was unhandled.
Memory dump at 0x400d25bc: ee650213 00f01d0a 41004136
Core  1 register dump:
PC      : 0x400d25c1  PS      : 0x00060930  A0      : 0x00000000  A1      : 0x3ffb4010
A2      : 0x75e82caf  A3      : 0x75e82caf  A4      : 0x3ffc2f84  A5      : 0x00000000
A6      : 0x00000000  A7      : 0x00000000  A8      : 0x800d24dc  A9      : 0x3ffb3ff0
A10     : 0x00000001  A11     : 0x00000001  A12     : 0x00000010  A13     : 0x3ffc2f84
A14     : 0x3ffb927c  A15     : 0x80000001  SAR     : 0x0000000a  EXCCAUSE: 0x00000000
EXCVADDR: 0x00000000  LBEG    : 0x40084415  LEND    : 0x4008441d  LCOUNT  : 0x00000026

Backtrace:0x400d25be:0x3ffb4010

ELF file SHA256: 0000000000000000

Rebooting...
ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:1344
load:0x40078000,len:13864
load:0x40080400,len:3608
entry 0x400805f0

Connecting to xxx
</code>```

Guys, i got bugged when connecting to mqtt server. I'm using ESP32.

Here is my code for connecting.

```<code>void connectMQTT(void *pvParameters) {
  vTaskDelay(6000 / portTICK_PERIOD_MS);
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String clientId = "FreeRTOS";
    clientId += String(random(0xffff), HEX);
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      client.subscribe("denled");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 2 seconds");
      delay(2000 / portTICK_PERIOD_MS);
    }
  }
}
</code>```

Here is my task. The default running core on my arduino ide is 1

```<code>xTaskCreatePinnedToCore(
    connectMQTT
  ,    "MQTTConnection" // Task name
  ,    2048          // Stack size (bytes)
  ,    NULL
  ,    3                 // Priority
  ,    NULL
  ,    ARDUINO_RUNNING_CORE);
</code>```

Thanks for reading. This is the first time i post, so if there any feedback is always good for me

Title: Cannot connect to mqtt by using esp32

Body:
WiFi connected
IP address:
192.168.1.xxx
Attempting MQTT connection...connected
Guru Meditation Error: Core  1 panic'ed (IllegalInstruction). Exception was unhandled.
Memory dump at 0x400d25bc: ee650213 00f01d0a 41004136
Core  1 register dump:
PC      : 0x400d25c1  PS      : 0x00060930  A0      : 0x00000000  A1      : 0x3ffb4010
A2      : 0x75e82caf  A3      : 0x75e82caf  A4      : 0x3ffc2f84  A5      : 0x00000000
A6      : 0x00000000  A7      : 0x00000000  A8      : 0x800d24dc  A9      : 0x3ffb3ff0
A10     : 0x00000001  A11     : 0x00000001  A12     : 0x00000010  A13     : 0x3ffc2f84
A14     : 0x3ffb927c  A15     : 0x80000001  SAR     : 0x0000000a  EXCCAUSE: 0x00000000
EXCVADDR: 0x00000000  LBEG    : 0x40084415  LEND    : 0x4008441d  LCOUNT  : 0x00000026

Backtrace:0x400d25be:0x3ffb4010

ELF file SHA256: 0000000000000000

Rebooting...
ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:1344
load:0x40078000,len:13864
load:0x40080400,len:3608
entry 0x400805f0

Connecting to xxx

Guys, i got bugged when connecting to mqtt server. I'm using ESP32.

Here is my code for connecting.

void connectMQTT(void *pvParameters) {
  vTaskDelay(6000 / portTICK_PERIOD_MS);
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String clientId = "FreeRTOS";
    clientId += String(random(0xffff), HEX);
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      client.subscribe("denled");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 2 seconds");
      delay(2000 / portTICK_PERIOD_MS);
    }
  }
}

Here is my task. The default running core on my arduino ide is 1

xTaskCreatePinnedToCore(
    connectMQTT
  ,    "MQTTConnection" // Task name
  ,    2048          // Stack size (bytes)
  ,    NULL
  ,    3                 // Priority
  ,    NULL
  ,    ARDUINO_RUNNING_CORE);

Thanks for reading. This is the first time i post, so if there any feedback is always good for me


问:
Getting URL after InvokeWebRequest, when Status Code is 200 and store in CSV
I am attempting to pull the URL once an InvokeWebRequest has been called in my script. I wish for it do this when the HTTP Status Code is 200. So far, I have got it to tell the Status Code, and give the re-directed URL is 301/302 is the Status Code. Also an Error Message when the Status Code is 4xx//5xx.

I deal with a lot of URLs on clients' ecommerce sites, so need know what the final URL is after a end-user clicks on one of the URLs - essentially something like the query strings being dropped or something like that, on Status Code 200. As mentioned before, I already have 3xx/4xx/5xx reporting.

Attempted -

Reading the page and pulling the URL from the Header

Searching for the 'href' and pulling it

I wish for the CSV out to have the following output -

Expected CSV Output

Actual CSV Output (Row 3)

The "Landing Page" field is what I am trying to fill - the rest are working.

Script below -

```<code>[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$urlInput = "C:\Users\User\Desktop\testurls.txt"
$csvOutput = "C:\Users\User\Desktop\testurl_result.csv"

#$totalUrls = Get-Content $urlInput | Measure-Object –Line
#Write-Host "Total URLs = $totalUrls"

$results = Test-Path "C:\Users\User\Desktop\testurl_result.csv"

If ($results -eq $false) {
    Remove-Item "testurl_result.csv" -Force
}

Get-Content $urlInput | ForEach-Object { $uri = $_;
    try
    {
        Start-Sleep 5
        Invoke-WebRequest -Uri $uri -Method HEAD -MaximumRedirection 0 -ErrorAction SilentlyContinue
        $link = Invoke-WebRequest -Uri $uri -Method HEAD -MaximumRedirection 0 -ErrorAction SilentlyContinue

    }
    catch
    {
        New-Object -TypeName psobject -Property @{Error = $_}
    }
} | Select-Object @{Name='Click URL'; Expression={$uri}}, StatusCode, @{Name='Path'; Expression={([uri]$uri).AbsolutePath}}, @{Name='UTMs'; Expression={([uri]$uri).Query}}, @{Name='RedirectTo';Expression={$_.Headers["Location"]}}, @{Name='Landing Page';Expression={$link.Links | select -ExpandProperty href}}, Error | Export-Csv $csvOutput -NoTypeInformation
</code>```

Thanks.

Body:
I am attempting to pull the URL once an InvokeWebRequest has been called in my script. I wish for it do this when the HTTP Status Code is 200. So far, I have got it to tell the Status Code, and give the re-directed URL is 301/302 is the Status Code. Also an Error Message when the Status Code is 4xx//5xx.

I deal with a lot of URLs on clients' ecommerce sites, so need know what the final URL is after a end-user clicks on one of the URLs - essentially something like the query strings being dropped or something like that, on Status Code 200. As mentioned before, I already have 3xx/4xx/5xx reporting.

Attempted -

Reading the page and pulling the URL from the Header

Searching for the 'href' and pulling it

I wish for the CSV out to have the following output -

Expected CSV Output

Actual CSV Output (Row 3)

The "Landing Page" field is what I am trying to fill - the rest are working.

Script below -

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$urlInput = "C:\Users\User\Desktop\testurls.txt"
$csvOutput = "C:\Users\User\Desktop\testurl_result.csv"

#$totalUrls = Get-Content $urlInput | Measure-Object –Line
#Write-Host "Total URLs = $totalUrls"

$results = Test-Path "C:\Users\User\Desktop\testurl_result.csv"

If ($results -eq $false) {
    Remove-Item "testurl_result.csv" -Force
}

Get-Content $urlInput | ForEach-Object { $uri = $_;
    try
    {
        Start-Sleep 5
        Invoke-WebRequest -Uri $uri -Method HEAD -MaximumRedirection 0 -ErrorAction SilentlyContinue
        $link = Invoke-WebRequest -Uri $uri -Method HEAD -MaximumRedirection 0 -ErrorAction SilentlyContinue

    }
    catch
    {
        New-Object -TypeName psobject -Property @{Error = $_}
    }
} | Select-Object @{Name='Click URL'; Expression={$uri}}, StatusCode, @{Name='Path'; Expression={([uri]$uri).AbsolutePath}}, @{Name='UTMs'; Expression={([uri]$uri).Query}}, @{Name='RedirectTo';Expression={$_.Headers["Location"]}}, @{Name='Landing Page';Expression={$link.Links | select -ExpandProperty href}}, Error | Export-Csv $csvOutput -NoTypeInformation

Thanks.


问:
C# configuration reads yaml incorrect
I use .net core 3.1, linux, docker.

When i have a json config, i can write something like that:

json:

```<code>{ "SomeSection": {...} }
</code>```

c# :

```<code>// Microsoft.Extensions.Configuration.IConfiguration Configuration from DI

var section = Configuration.GetSection("SomeSection");
Console.WriteLine(section.Value); // returns "null"

var children = section.GetChildren().ToArray();
foreach (var child in children) Console.Writeline(child.Value); // returns values from json
</code>```

But when i switched to yaml, i started to have this situation:

yaml:

```<code>SomeSection:
  SomeKey: SomeValue
</code>```

c# :

```<code>// Microsoft.Extensions.Configuration.IConfiguration Configuration from DI

var section = Configuration.GetSection("SomeSection");
Console.WriteLine(section.Value); // returns "map[SomeKey:SomeValue]"

var children = section.GetChildren().ToArray(); // empty array
</code>```

And ok - new format equals new rules to read that format. But even YamlDotNET can't parse string map[SomeKey:SomeValue]. What do i do wrong?

Tried to write yaml like

```<code>SomeSection:{SomeKey: SomeValue}
</code>```

but also get map[...]

Tried to make something like

```<code>SomeSection:
  Level1:
    Level2:
      SomeKey: SomeValue
</code>```

And it also seems like map[Level1:map[Level2:map[SomeKey:SomeValue]]]

Title: C# configuration reads yaml incorrect

Body:
I use .net core 3.1, linux, docker.

When i have a json config, i can write something like that:

json:

{ "SomeSection": {...} }

c# :

// Microsoft.Extensions.Configuration.IConfiguration Configuration from DI

var section = Configuration.GetSection("SomeSection");
Console.WriteLine(section.Value); // returns "null"

var children = section.GetChildren().ToArray();
foreach (var child in children) Console.Writeline(child.Value); // returns values from json

But when i switched to yaml, i started to have this situation:

yaml:

SomeSection:
  SomeKey: SomeValue

c# :

// Microsoft.Extensions.Configuration.IConfiguration Configuration from DI

var section = Configuration.GetSection("SomeSection");
Console.WriteLine(section.Value); // returns "map[SomeKey:SomeValue]"

var children = section.GetChildren().ToArray(); // empty array

And ok - new format equals new rules to read that format. But even YamlDotNET can't parse string map[SomeKey:SomeValue]. What do i do wrong?

Tried to write yaml like

SomeSection:{SomeKey: SomeValue}

but also get map[...]

Tried to make something like

SomeSection:
  Level1:
    Level2:
      SomeKey: SomeValue

And it also seems like map[Level1:map[Level2:map[SomeKey:SomeValue]]]


问:
NestJS: TypeORM One to Many relation cascade update not working
Below is my DB design diagram -

Entities -

```<code>// Sports table entity
@Entity({name: 'Sports'})
export class Sports {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column()
  name!: string;

  @OneToMany(() => Tennis, (tennis) => tennis.sport, {cascade: true})
  tennis!: Tennis[];
}
</code>```
```<code>// Tennis table entity
@Entity({name: 'Tennis'})
export class Tennis {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column()
  sportsId!: number

  @Column()
  racketBrand!: string;

  @ManyToOne(() => Sports, (sport) => sport.tennis, {
    onDelete: 'CASCADE',
    onUpdate: 'CASCADE',
  })
  sport!: Sports;
}
</code>```

sports.service.ts

```<code>public async update(id: number, updateSportsDto: UpdateSportsDto) {
    return this.sportsRepository.save({id, ...updateSportsDto}).then(() => {
      return this.sportsRepository.findOneOrFail({
        where: {id},
        relations: ['sports', 'sports.tennis'],
      });
    });
  }
</code>```

When I try to do a PATCH /sports/:id request to update records, I get following error message:

"message": "null value in column \"sports_id\" of relation \"tennis\" violates not-null constraint",

I am successfully able to perform cascade insert operation, but having trouble with cascade update.

There are couple of answers I referred, but those didn't help -

https://stackoverflow.com/a/55101273/10011503

https://stackoverflow.com/a/65012542/10011503

How do I make sure sports_id gets passed from Sports table to Tennis table?

Body:
Below is my DB design diagram -

Entities -

// Sports table entity
@Entity({name: 'Sports'})
export class Sports {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column()
  name!: string;

  @OneToMany(() => Tennis, (tennis) => tennis.sport, {cascade: true})
  tennis!: Tennis[];
}

// Tennis table entity
@Entity({name: 'Tennis'})
export class Tennis {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column()
  sportsId!: number

  @Column()
  racketBrand!: string;

  @ManyToOne(() => Sports, (sport) => sport.tennis, {
    onDelete: 'CASCADE',
    onUpdate: 'CASCADE',
  })
  sport!: Sports;
}

sports.service.ts

public async update(id: number, updateSportsDto: UpdateSportsDto) {
    return this.sportsRepository.save({id, ...updateSportsDto}).then(() => {
      return this.sportsRepository.findOneOrFail({
        where: {id},
        relations: ['sports', 'sports.tennis'],
      });
    });
  }

When I try to do a PATCH /sports/:id request to update records, I get following error message:

"message": "null value in column \"sports_id\" of relation \"tennis\" violates not-null constraint",

I am successfully able to perform cascade insert operation, but having trouble with cascade update.

There are couple of answers I referred, but those didn't help -

https://stackoverflow.com/a/55101273/10011503

https://stackoverflow.com/a/65012542/10011503

How do I make sure sports_id gets passed from Sports table to Tennis table?


问:
I want to avoid adding duplicated in mysql table
I want to avoid any duplicate data in the database so that everything in there in unique. See my code below:</p>
```<code>$add_to_continue_query = $wpdb->prepare("INSERT INTO wp_learning_history (`user_id`, `blog_id`, `activity_id`, `mark_as_complete`) VALUES($user_id, $site_id, $activity_id, 0)");
        $add_to_continue = $wpdb->get_results($add_to_continue_query);
</code>```

Body:
I want to avoid any duplicate data in the database so that everything in there in unique. See my code below:

$add_to_continue_query = $wpdb->prepare("INSERT INTO wp_learning_history (`user_id`, `blog_id`, `activity_id`, `mark_as_complete`) VALUES($user_id, $site_id, $activity_id, 0)");
        $add_to_continue = $wpdb->get_results($add_to_continue_query);


问:
Deduction in xslt and converting to new value
My initial xml file has 2 different dates. I want to received as output just mathematical value of deduction and converting to "Years"

```<code><option>
      <Exercise>
        <Date>
          <currentDate>2019-09-19</currentDate>
        </Date>
      </Exercise>
      <Exercise>
        <Date>
          <currentDate>2029-09-19</currentDate>
        </Date>
      </Exercise>
</option>
</code>```

And want to recieve the next output. With a created new tag.

```<code><newDataTag> _10Y </newDataTag>

</code>```

this approach that I use, but in my case I received 3653

```<code><newDataTag>
        fn:days-from-duration(xs:date(/option/Exercise[2]/Date/currentDate)-(xs:date(/option/Exercise[1]/Date/currentDate)))
</newDataTag>
</code>```

Body:
My initial xml file has 2 different dates. I want to received as output just mathematical value of deduction and converting to "Years"

<option>
      <Exercise>
        <Date>
          <currentDate>2019-09-19</currentDate>
        </Date>
      </Exercise>
      <Exercise>
        <Date>
          <currentDate>2029-09-19</currentDate>
        </Date>
      </Exercise>
</option>

And want to recieve the next output. With a created new tag.

<newDataTag> _10Y </newDataTag>

this approach that I use, but in my case I received 3653

<newDataTag>
        fn:days-from-duration(xs:date(/option/Exercise[2]/Date/currentDate)-(xs:date(/option/Exercise[1]/Date/currentDate)))
</newDataTag>


问:
Symfony Attribute class to check if user is logged in
Hi I have problem with Attribute class.

I created attribute class that takes RequestStack object as an argument. I need to check in this class if user was binded to request attributes, but there is no way to autowire it or pass an instance. If I pass it like, new RequestStack(), then I don't have access to any request, but there is no exception.

How can I fix it. I wanna use it like the symfony security bundle do it, Fe.
#[IsGranted('ROLE_USER')]

I tried:

configuring services.yaml

configuring in services.yaml arguments and binding service to it

rewriting it to annotaion, but result is the same

instancing RequestStack inside attribute class

I'm currently thinking to use reflection class, but I'm not sure if the RequestStack is going to contain all the requests (also the original/main one). It's important to me to keep track the request instance.


问:
Jenkins for C++ Project with Docker
I want to integrate my C++ project with Jenkins using Docker.
First I created a setup for Jenkins using:

Dockerfile:

```<code>FROM jenkins/jenkins:latest
USER root
RUN apt-get update && apt-get install git && apt-get install make g++ -y
ENV JAVA_OPTS -Djenkins.install.runSetupWizard=false
ENV CASC_JENKINS_CONFIG /var/jenkins_home/casc.yaml
ENV JENKINS_ADMIN_ID=admin
ENV JENKINS_ADMIN_PASSWORD=password
COPY plugins.txt /usr/share/jenkins/ref/plugins.txt
RUN jenkins-plugin-cli -f /usr/share/jenkins/ref/plugins.txt
COPY casc.yaml /var/jenkins_home/casc.yaml
</code>```

plugins.txt

```<code>ant:latest
antisamy-markup-formatter:latest
authorize-project:latest
build-timeout:latest
cloudbees-folder:latest
configuration-as-code:latest
credentials-binding:latest
email-ext:latest
git:latest
github-branch-source:latest
gradle:latest
ldap:latest
mailer:latest
matrix-auth:latest
pam-auth:latest
pipeline-github-lib:latest
pipeline-stage-view:latest
ssh-slaves:latest
timestamper:latest
workflow-aggregator:latest
ws-cleanup:latest
</code>```

casc.yaml

```<code>jenkins:
  securityRealm:
    local:
      allowsSignup: false
      users:
       - id: ${JENKINS_ADMIN_ID}
         password: ${JENKINS_ADMIN_PASSWORD}
  authorizationStrategy:
    globalMatrix:
      permissions:
        - "USER:Overall/Administer:admin"
        - "GROUP:Overall/Read:authenticated"
  remotingSecurity:
      enabled: true
security:
  queueItemAuthenticator:
    authenticators:
    - global:
        strategy: triggeringUsersAuthorizationStrategy
unclassified:
  location:
    url: http://127.0.0.1:8080/
</code>```

So far, so good. I used docker build -t jenkins:jcasc . and docker run --name jenkins --rm -p 8080:8080 jenkins:jcasc and Jenkins starts normally. I entered the user name (admin) and the password and it worked.

There are although 2 issues that Jenkins displays:

-> It appears that your reverse proxy set up is broken.

-> Building on the built-in node can be a security issue. You should set up distributed builds. See the documentation.

I ignored them so far, and continued with my project and installed Blue Ocean.
After installing Blue Ocean I connected it to my GitHub repository and for this I created a token and the pipeline was created, but it is not giving any result.

The log says:

```<code>Branch indexing

Connecting to https://api.github.com with no credentials, anonymous access

Jenkins-Imposed API Limiter: Current quota for Github API usage has 37 remaining (1 over budget). Next quota of 60 in 36 min. Sleeping for 4 min 43 sec.

Jenkins is attempting to evenly distribute GitHub API requests. To configure a different rate limiting strategy, such as having Jenkins restrict GitHub API requests only when near or above the GitHub rate limit, go to "GitHub API usage" under "Configure System" in the Jenkins settings.
</code>```

My C++ project looks like this:

```<code>-->HelloWorld
  |
  -->HelloWorld.cpp
-->scripts
  |
  -->Linux-Build.sh
  |
  -->Linux-Run.sh
-->Jenkinsfile
</code>```

HelloWorld.cpp:

```<code>#include <iostream>

int main(){

    std::cout << "Hello World!" << std::endl;

    return 0;
}
</code>```

Linux-Build.sh

```<code>#!/bin/bash

vendor/bin/premake/premake5 gmake2
make
</code>```

Linux-Run.sh

```<code>#!/bin/bash

bin/Debug/HelloWorld
</code>```

Jenkinsfile

```<code>pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                sh 'echo "Building..."'
                sh 'chmod +x scripts/Linux-Build.sh'
                sh 'scripts/Linux-Build.sh'
                archiveArtifacts artifacts: 'bin/Debug/*', fingerprint: true
            }
        }
        stage('Test') {
            steps {
                sh 'echo "Running..."'
                sh 'chmod +x scripts/Linux-Run.sh'
                sh 'scripts/Linux-Run.sh'
            }
        }
    }
}
</code>```

So, where might be the problem? I don't know if the problem is in my C++ code, or in the Docker configuration.
I am also a big fan of cmake, instead of make and I would prefer to use cmake for this, but I am not sure how to integrate this and make it work.

EDIT:
In the tutorial that I followed there was a "vendor" directory but the instructor didn't show what was in that directory.

EDIT:
The program took 4 minutes but it eventually did something and the error is:

```<code>+ scripts/Linux-Build.sh

scripts/Linux-Build.sh: line 3: vendor/bin/premake/premake5: No such file or directory

make: *** No targets specified and no makefile found.  Stop.

script returned exit code 2
</code>```

So, the problem is in the C++ project, not Docker.

Title: Jenkins for C++ Project with Docker

Body:
I want to integrate my C++ project with Jenkins using Docker.
First I created a setup for Jenkins using:

Dockerfile:

FROM jenkins/jenkins:latest
USER root
RUN apt-get update && apt-get install git && apt-get install make g++ -y
ENV JAVA_OPTS -Djenkins.install.runSetupWizard=false
ENV CASC_JENKINS_CONFIG /var/jenkins_home/casc.yaml
ENV JENKINS_ADMIN_ID=admin
ENV JENKINS_ADMIN_PASSWORD=password
COPY plugins.txt /usr/share/jenkins/ref/plugins.txt
RUN jenkins-plugin-cli -f /usr/share/jenkins/ref/plugins.txt
COPY casc.yaml /var/jenkins_home/casc.yaml

plugins.txt

ant:latest
antisamy-markup-formatter:latest
authorize-project:latest
build-timeout:latest
cloudbees-folder:latest
configuration-as-code:latest
credentials-binding:latest
email-ext:latest
git:latest
github-branch-source:latest
gradle:latest
ldap:latest
mailer:latest
matrix-auth:latest
pam-auth:latest
pipeline-github-lib:latest
pipeline-stage-view:latest
ssh-slaves:latest
timestamper:latest
workflow-aggregator:latest
ws-cleanup:latest

casc.yaml

jenkins:
  securityRealm:
    local:
      allowsSignup: false
      users:
       - id: ${JENKINS_ADMIN_ID}
         password: ${JENKINS_ADMIN_PASSWORD}
  authorizationStrategy:
    globalMatrix:
      permissions:
        - "USER:Overall/Administer:admin"
        - "GROUP:Overall/Read:authenticated"
  remotingSecurity:
      enabled: true
security:
  queueItemAuthenticator:
    authenticators:
    - global:
        strategy: triggeringUsersAuthorizationStrategy
unclassified:
  location:
    url: http://127.0.0.1:8080/

So far, so good. I used docker build -t jenkins:jcasc . and docker run --name jenkins --rm -p 8080:8080 jenkins:jcasc and Jenkins starts normally. I entered the user name (admin) and the password and it worked.

There are although 2 issues that Jenkins displays:

-> It appears that your reverse proxy set up is broken.

-> Building on the built-in node can be a security issue. You should set up distributed builds. See the documentation.

I ignored them so far, and continued with my project and installed Blue Ocean.
After installing Blue Ocean I connected it to my GitHub repository and for this I created a token and the pipeline was created, but it is not giving any result.

The log says:

Branch indexing

Connecting to https://api.github.com with no credentials, anonymous access

Jenkins-Imposed API Limiter: Current quota for Github API usage has 37 remaining (1 over budget). Next quota of 60 in 36 min. Sleeping for 4 min 43 sec.

Jenkins is attempting to evenly distribute GitHub API requests. To configure a different rate limiting strategy, such as having Jenkins restrict GitHub API requests only when near or above the GitHub rate limit, go to "GitHub API usage" under "Configure System" in the Jenkins settings.

My C++ project looks like this:

-->HelloWorld
  |
  -->HelloWorld.cpp
-->scripts
  |
  -->Linux-Build.sh
  |
  -->Linux-Run.sh
-->Jenkinsfile

HelloWorld.cpp:

#include <iostream>

int main(){

    std::cout << "Hello World!" << std::endl;

    return 0;
}

Linux-Build.sh

#!/bin/bash

vendor/bin/premake/premake5 gmake2
make

Linux-Run.sh

#!/bin/bash

bin/Debug/HelloWorld

Jenkinsfile

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                sh 'echo "Building..."'
                sh 'chmod +x scripts/Linux-Build.sh'
                sh 'scripts/Linux-Build.sh'
                archiveArtifacts artifacts: 'bin/Debug/*', fingerprint: true
            }
        }
        stage('Test') {
            steps {
                sh 'echo "Running..."'
                sh 'chmod +x scripts/Linux-Run.sh'
                sh 'scripts/Linux-Run.sh'
            }
        }
    }
}

So, where might be the problem? I don't know if the problem is in my C++ code, or in the Docker configuration.
I am also a big fan of cmake, instead of make and I would prefer to use cmake for this, but I am not sure how to integrate this and make it work.

EDIT:
In the tutorial that I followed there was a "vendor" directory but the instructor didn't show what was in that directory.

EDIT:
The program took 4 minutes but it eventually did something and the error is:

+ scripts/Linux-Build.sh

scripts/Linux-Build.sh: line 3: vendor/bin/premake/premake5: No such file or directory

make: *** No targets specified and no makefile found.  Stop.

script returned exit code 2

So, the problem is in the C++ project, not Docker.


问:
How to list issues assigned to me on github repo along with their links
I need to list the issues assigned to me on the github repo org/examplerepo on my terminal along with links to them. Is there some way i can do it.

I am using the blow command. its displaying the issues and issue numbers, tags etc..  in a beautiful table format ,  But there are no links to the issues

```<code> ❯ gh -R org/examplerepo issue list --assignee "@me"
</code>```

On checking with chatGPT, it suggested me to try gh issues --assignee=<your-username> --all --state=closed --format="%n%t%l%n%U" and it seems like an incorrect answer, because gh complaints there is no such flag as --format

Body:
I need to list the issues assigned to me on the github repo org/examplerepo on my terminal along with links to them. Is there some way i can do it.

I am using the blow command. its displaying the issues and issue numbers, tags etc..  in a beautiful table format ,  But there are no links to the issues

 ❯ gh -R org/examplerepo issue list --assignee "@me"

On checking with chatGPT, it suggested me to try gh issues --assignee=<your-username> --all --state=closed --format="%n%t%l%n%U" and it seems like an incorrect answer, because gh complaints there is no such flag as --format


问:
Nextjs router is rerendering all components and calling useEffect on common and unchanged components
When I open /app/wa/638934e53d4211b0167378b1?c=6392418d966eaa4e1dbe9e7d route and put a button there that on click calls router.push("/app/wa/638934e53d4211b0167378b1?c=6392418d966eaa4e1dbe9e7d") (SAME ROUTE), nextjs rerenders everythings and make api calls for all the components e.g sidebar, layout, navbar.

My app is using Client side fetching.

Based on the slug in [...slug].tsx, useEffect is called.

I use router.query.slug to a access slug value

useEffect array contains [slug] but I even tried with empty array. It's like whole page is rerendering


问:
How to export the e-mail addresses's active directory group members by powershell
Does anyone know how to export the e-mail addresses's active directory group members, of a particular distribution group, by powershell, be they users or contacts?
Thanks.</p>


问:
Is there a package for AGMAlgorithm in nltk?
I cannot find a package for AGM ("Algebraic-Geometric-Mean") in nltk. Does a package exist for AGM?

from nltk.inference import AGMAlgorithm
```
<p>Gave me following error:</p>
```ImportError: cannot import name 'AGMAlgorithm' from 'nltk.inference'
```

Body:
I cannot find a package for AGM ("Algebraic-Geometric-Mean") in nltk. Does a package exist for AGM?

from nltk.inference import AGMAlgorithm

Gave me following error:

ImportError: cannot import name 'AGMAlgorithm' from 'nltk.inference'


问:
Electron | TypeError: "x" is not a constructor
I have a simple electron app that opens a browser window to a url of a webpage.

I import my stuff using
const { BrowserWindow, app, MessageChannelMain } = require('electron');

I create my window on app.on("ready") using window = new BrowserWindow({ ... }); and everything works fine.

When I try to create a MessageChannelMain using const {port1, port2} = new MessageChannelMain();, I get the error:
TypeError: MessageChannelMain is not a constructor.

Full code:

```<code>function init_window(){
    if ( mainWindow == null ) {
        mainWindow = create_window();
        load_window(); // calls mainWindow.loadURL(myURL);

        const {port1, port2} = new MessageChannelMain();
        port2.postMessage({ test: 21 })
        port2.on('message', (event) => {
            console.log('from renderer main world:', event.data)
        });
        port2.start();

        mainWindow.webContents.postMessage('main-world-port', null, [port1])

        mainWindow.on('closed', function(event) {
          mainWindow = null;
        });

        mainWindow.webContents.on("did-fail-load", function(event) {

        })
    }
}

function create_window() {
    return new BrowserWindow({
        width: 1200,
        height: 800,
        darkTheme: true,
        webPreferences: {
            contextIsolation: true,
            preload: path.join(__dirname, 'preload.js'),
        },
    });
}
</code>```

When I console.log(MessageChannelMain); I get undefined.

At the same time, I get other errors when I try to use some electron stuff on the preload script:

const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld(
  'electron',
  {
    doThing: () => ipcRenderer.send('do-a-thing')
  }
)
```

Here I am getting TypeError: Cannot read property 'exposeInMainWorld' of undefined

Body:
I have a simple electron app that opens a browser window to a url of a webpage.

I import my stuff using
const { BrowserWindow, app, MessageChannelMain } = require('electron');

I create my window on app.on("ready") using window = new BrowserWindow({ ... }); and everything works fine.

When I try to create a MessageChannelMain using const {port1, port2} = new MessageChannelMain();, I get the error:
TypeError: MessageChannelMain is not a constructor.

Full code:

function init_window(){
    if ( mainWindow == null ) {
        mainWindow = create_window();
        load_window(); // calls mainWindow.loadURL(myURL);

        const {port1, port2} = new MessageChannelMain();
        port2.postMessage({ test: 21 })
        port2.on('message', (event) => {
            console.log('from renderer main world:', event.data)
        });
        port2.start();

        mainWindow.webContents.postMessage('main-world-port', null, [port1])

        mainWindow.on('closed', function(event) {
          mainWindow = null;
        });

        mainWindow.webContents.on("did-fail-load", function(event) {

        })
    }
}

function create_window() {
    return new BrowserWindow({
        width: 1200,
        height: 800,
        darkTheme: true,
        webPreferences: {
            contextIsolation: true,
            preload: path.join(__dirname, 'preload.js'),
        },
    });
}

When I console.log(MessageChannelMain); I get undefined.

At the same time, I get other errors when I try to use some electron stuff on the preload script:

const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld(
  'electron',
  {
    doThing: () => ipcRenderer.send('do-a-thing')
  }
)

Here I am getting TypeError: Cannot read property 'exposeInMainWorld' of undefined


问:
Local and global features extraction
I have a 10-layered CNN architecture where 2 skip connections are there.
One is from 1st layer to the 3rd layer. And another skip is from the 1st to 10th layer as shown in the figure. Can we say skip-1  extracts global features and skip-2 extracts local features from the given input image?

Sequential CNN layered network with skip connections

As the network goes deeper it will extract global features. So I'm thinking that at the 9th layer we have global features of the image and skip-2 gives local features from the 1st layer. Is this correct?

Title: Local and global features extraction


问:
How to keep only first value from distinct values in one column based on repeated values in other column in R?
So I have a large dataset that looks something like this:

```<code>df <- data.frame(ID =c("A","A","A","B","B","B","C","C","C"),
plot = c(1,1,1,2,2,3,4,5,5))

df

  ID plot
1  A    1
2  A    1
3  A    1
4  B    2
5  B    2
6  B    3
7  C    4
8  C    5
9  C    5
</code>```

I want to keep just the first values from plot so the data looks like this in the end:

```<code>df1 <- data.frame(ID =c("A","A","A","B","B","B","C","C","C"),
plot = c(1,1,1,2,2,2,4,4,4))

df1

ID plot
1  A    1
2  A    1
3  A    1
4  B    2
5  B    2
6  B    2
7  C    4
8  C    4
9  C    4
</code>```

Body:
So I have a large dataset that looks something like this:

df <- data.frame(ID =c("A","A","A","B","B","B","C","C","C"),
plot = c(1,1,1,2,2,3,4,5,5))

df

  ID plot
1  A    1
2  A    1
3  A    1
4  B    2
5  B    2
6  B    3
7  C    4
8  C    5
9  C    5

I want to keep just the first values from plot so the data looks like this in the end:

df1 <- data.frame(ID =c("A","A","A","B","B","B","C","C","C"),
plot = c(1,1,1,2,2,2,4,4,4))

df1

ID plot
1  A    1
2  A    1
3  A    1
4  B    2
5  B    2
6  B    2
7  C    4
8  C    4
9  C    4


问:
understanding trans_new on ggplot
Coming from this example (pasted here)

```<code>trans_cube <- trans_new(name = "cube root",
                        transform = cube_root,
                        inverse = cube)

# dummy data
plot_data <- data.frame(x = 1:10,
                        y = cube(1:10))

# without applying a transform
ggplot(plot_data, aes(x = x, y = y)) +
  geom_point()
# applying a transform
ggplot(plot_data, aes(x = x, y = y)) +
  geom_point() +
  coord_trans(y = trans_cube)
</code>```

Why the simple transformation of just adding a constant (using scales::trans_new) won't work?

```<code>trans_add <- trans_new(name = "add",
                         transform = function(x) x + 200,
                         inverse = function(x) x -200)

ggplot(plot_data, aes(x = x, y = y)) +   geom_point() +
coord_trans(y = trans_add )
</code>```

The reason I'm asking is because I would like to back transform my y-axis and I need to do it using coord_trans or scale_y_continuous or similar.

UPDATE

I managed to show the back transformation with custom breaks by using the following, however I would like to know why the trans_new doesn't work.

```<code>fun_sc_back <- function(x){x*187+266} # transform
fun_sc <- function(x){(x-266)/187}    # inverse

p_tr +
  scale_y_continuous(breaks =fun_sc(c(250, 500, 750)), labels=fun_sc_back)
</code>```

Title: understanding trans_new on ggplot

Body:
Coming from this example (pasted here)

trans_cube <- trans_new(name = "cube root",
                        transform = cube_root,
                        inverse = cube)

# dummy data
plot_data <- data.frame(x = 1:10,
                        y = cube(1:10))

# without applying a transform
ggplot(plot_data, aes(x = x, y = y)) +
  geom_point()
# applying a transform
ggplot(plot_data, aes(x = x, y = y)) +
  geom_point() +
  coord_trans(y = trans_cube)

Why the simple transformation of just adding a constant (using scales::trans_new) won't work?

trans_add <- trans_new(name = "add",
                         transform = function(x) x + 200,
                         inverse = function(x) x -200)

ggplot(plot_data, aes(x = x, y = y)) +   geom_point() +
coord_trans(y = trans_add )

The reason I'm asking is because I would like to back transform my y-axis and I need to do it using coord_trans or scale_y_continuous or similar.

UPDATE

I managed to show the back transformation with custom breaks by using the following, however I would like to know why the trans_new doesn't work.

fun_sc_back <- function(x){x*187+266} # transform
fun_sc <- function(x){(x-266)/187}    # inverse

p_tr +
  scale_y_continuous(breaks =fun_sc(c(250, 500, 750)), labels=fun_sc_back)


问:
How to set signalfx.accessToken in spring application
I have have tried pushing custom metrics to splunk apm using below dependency and setting the properties using springboot application

```<code><dependency>
        <groupId>io.micrometer</groupId>
        <artifactId>micrometer-registry-signalfx</artifactId>
    </dependency>
</code>```

Properties

```<code>management.metrics.export.signalfx.access-token= <token>
management.metrics.export.signalfx.enabled=true
management.metrics.export.signalfx.uri=<uri>
management.metrics.export.signalfx.source=testservice
</code>```

Now there is a requirement to try pushing from spring mvc application and I have added same dependency in the pom and created custom metric code as below but I am getting error while spring application is deployed

```<code>        MeterRegistry resgRegistry = new SignalFxMeterRegistry(new SignalFxConfig() {

        @Override
        public String get(String key) {
            // TODO Auto-generated method stub
            return null;
        }
    }, Clock.SYSTEM);

    Timer myTimer = Timer.builder("surya_timer").register(Metrics.globalRegistry);
    Timer timer = Timer.builder("test").register(resgRegistry);

    timer.record(Duration.ofMillis(123));
    myTimer.record(Duration.ofMillis(567));
</code>```

Error

```<code>io.micrometer.core.instrument.config.validate.ValidationException: signalfx.accessToken was 'null' but it is required
io.micrometer.core.instrument.config.validate.Validated$Either.orThrow(Validated.java:375)
io.micrometer.core.instrument.config.MeterRegistryConfig.requireValid(MeterRegistryConfig.java:49)
io.micrometer.core.instrument.push.PushMeterRegistry.<init>(PushMeterRegistry.java:42)
io.micrometer.core.instrument.step.StepMeterRegistry.<init>(StepMeterRegistry.java:43)
io.micrometer.signalfx.SignalFxMeterRegistry.<init>(SignalFxMeterRegistry.java:78)
io.micrometer.signalfx.SignalFxMeterRegistry.<init>(SignalFxMeterRegistry.java:74)
</code>```

Please help me How to set this access token in the spring application

Body:
I have have tried pushing custom metrics to splunk apm using below dependency and setting the properties using springboot application

<dependency>
        <groupId>io.micrometer</groupId>
        <artifactId>micrometer-registry-signalfx</artifactId>
    </dependency>

Properties

management.metrics.export.signalfx.access-token= <token>
management.metrics.export.signalfx.enabled=true
management.metrics.export.signalfx.uri=<uri>
management.metrics.export.signalfx.source=testservice

Now there is a requirement to try pushing from spring mvc application and I have added same dependency in the pom and created custom metric code as below but I am getting error while spring application is deployed

        MeterRegistry resgRegistry = new SignalFxMeterRegistry(new SignalFxConfig() {

        @Override
        public String get(String key) {
            // TODO Auto-generated method stub
            return null;
        }
    }, Clock.SYSTEM);

    Timer myTimer = Timer.builder("surya_timer").register(Metrics.globalRegistry);
    Timer timer = Timer.builder("test").register(resgRegistry);

    timer.record(Duration.ofMillis(123));
    myTimer.record(Duration.ofMillis(567));

Error

io.micrometer.core.instrument.config.validate.ValidationException: signalfx.accessToken was 'null' but it is required
io.micrometer.core.instrument.config.validate.Validated$Either.orThrow(Validated.java:375)
io.micrometer.core.instrument.config.MeterRegistryConfig.requireValid(MeterRegistryConfig.java:49)
io.micrometer.core.instrument.push.PushMeterRegistry.<init>(PushMeterRegistry.java:42)
io.micrometer.core.instrument.step.StepMeterRegistry.<init>(StepMeterRegistry.java:43)
io.micrometer.signalfx.SignalFxMeterRegistry.<init>(SignalFxMeterRegistry.java:78)
io.micrometer.signalfx.SignalFxMeterRegistry.<init>(SignalFxMeterRegistry.java:74)

Please help me How to set this access token in the spring application


问:
Percentage Graph in IG with multiple values
I have an IG with different columns. Out of those columns, I have 3 columns for percentage (lets say percent1, percent2 and percent3) containing some percentage values (all sum up to 100%).

I want to display a percent bar that will show all the percentages in a single bar for each row.

Please help me out as I am new to Oracle Apex. I am using Apex version 20.1

Expecting a percent bar like this

enter image description here


问:
Wordpress HLS Player with Auto Quality Settings Detection
I want to embed some HLS Links into my PSYPLAY Theme these links are without m3u8 extention, I am able to play it with Super Video Player wordpress plugin but it doesnt support multiple quality switch option but hls links does support multi quality switch, yesterday I found a player code at code, FYI.

[Codepen][1]

this player supports hls and multi quality switch but i dont know how i can import this code as a plugin in wordpress and use this to embed videos.

i tried to compile all this into html format with script code and style code with some online tutorial it is working in that format but when putting that code into my theme player embed option it is destroying my whole page css and not not working there.

Please someone guide me to implement this player into my wordpress website.
[Codepen][1]


问:
Form refresh issue- after every refresh selected record replaced by the last record of the grid
Created extension of "SMAServiceOrderTable" form and added 2 customized view's view1 and view2 as a data source both link type "outer join" .

after changing to link type "Delayed" form issue is got solved .
but its causing slow filtration of record in list page. kindly suggest any other solution .


问:
How to grant access to a private load-balancer from an EBS environment using CDK?
I have an existing elasticbeanstalk environment, say hello-env. And I have created an ApplicationLoadBalancedFargateService. I have made this service private. But I want to allow hello-env to access the load-balancer URL. How do I achieve that using CDK?

```<code>const cdk = require("aws-cdk-lib");
const { Construct } = require("constructs");
const ecs = require("aws-cdk-lib/aws-ecs");
const ecsp = require("aws-cdk-lib/aws-ecs-patterns");
const ecr = require("aws-cdk-lib/aws-ecr");
const kms = require("aws-cdk-lib/aws-kms");
const ebs = require("aws-cdk-lib/aws-elasticbeanstalk");

class MyEcsStack extends cdk.Stack {
  constructor(scope, id, props) {
    super(scope, id, props);

    const myPvtService = new ecsp.ApplicationLoadBalancedFargateService(
      this,
      "MyPvtService",
      {
        cpu: 256,
        memoryLimitMiB: 512,
        desiredCount: 1,
        taskImageOptions: {
          image: ecs.ContainerImage.fromEcrRepository(
            ecr.Repository.fromRepositoryAttributes(this, "MyPvtApp", {
              repositoryArn:
                "arn:aws:ecr:us-east-1:<my-account>:repository/my-pvt-app",
              repositoryName: "my-pvt-app",
            }),
            "dev"
          ),
          containerPort: 9000,
        },
        publicLoadBalancer: false,
      }
    );

    const myKey = kms.Key.fromKeyArn(
      this,
      "myKey",
      "arn:aws:kms:us-east-1:<my-account>:key/mrk-28490388455e548c1998f64c89f853f61"
    );

    myKey.grant(
      myPvtService.taskDefinition.taskRole,
      "kms:GetPublicKey"
    );
    myKey.grant(myPvtService.taskDefinition.taskRole, "kms:Sign");

  }
}

module.exports = { MyEcsStack };
</code>```

In the above code, I am allowing myPvtService to access the KMS keys. Similarly I want to allow an EBS Environment to access the load balancer service. How do I achieve that? There is no way to create and EBS env object using something like fromArn.

Body:
I have an existing elasticbeanstalk environment, say hello-env. And I have created an ApplicationLoadBalancedFargateService. I have made this service private. But I want to allow hello-env to access the load-balancer URL. How do I achieve that using CDK?

const cdk = require("aws-cdk-lib");
const { Construct } = require("constructs");
const ecs = require("aws-cdk-lib/aws-ecs");
const ecsp = require("aws-cdk-lib/aws-ecs-patterns");
const ecr = require("aws-cdk-lib/aws-ecr");
const kms = require("aws-cdk-lib/aws-kms");
const ebs = require("aws-cdk-lib/aws-elasticbeanstalk");

class MyEcsStack extends cdk.Stack {
  constructor(scope, id, props) {
    super(scope, id, props);

    const myPvtService = new ecsp.ApplicationLoadBalancedFargateService(
      this,
      "MyPvtService",
      {
        cpu: 256,
        memoryLimitMiB: 512,
        desiredCount: 1,
        taskImageOptions: {
          image: ecs.ContainerImage.fromEcrRepository(
            ecr.Repository.fromRepositoryAttributes(this, "MyPvtApp", {
              repositoryArn:
                "arn:aws:ecr:us-east-1:<my-account>:repository/my-pvt-app",
              repositoryName: "my-pvt-app",
            }),
            "dev"
          ),
          containerPort: 9000,
        },
        publicLoadBalancer: false,
      }
    );

    const myKey = kms.Key.fromKeyArn(
      this,
      "myKey",
      "arn:aws:kms:us-east-1:<my-account>:key/mrk-28490388455e548c1998f64c89f853f61"
    );

    myKey.grant(
      myPvtService.taskDefinition.taskRole,
      "kms:GetPublicKey"
    );
    myKey.grant(myPvtService.taskDefinition.taskRole, "kms:Sign");

  }
}

module.exports = { MyEcsStack };

In the above code, I am allowing myPvtService to access the KMS keys. Similarly I want to allow an EBS Environment to access the load balancer service. How do I achieve that? There is no way to create and EBS env object using something like fromArn.


问:
How can I track a change in Power BI report?
I would like to track changes made in a PowerBI report, for example which visual is added, deleted or changed.

I can track the Dataset with ALM toolkit but it does not allow tracking of report. Is there any app for that?


问:
Capistrano deploy error: Directory does not exist '/home/ubuntu/inventory/current'
I am trying to setup deployment with capistrano and using rbenv for managing ruby version. When i do cap production deploy, everything runs fine but right after running migrations successfully, cap is aborted and i get this error thrown up:

Command: if test ! -d /home/ubuntu/inventory/current; then echo "Directory does not exist '/home/ubuntu/inventory/current'" 1>&2; false; fi

I am using postgresql on my ec2 instance.


问:
Delete json object based on the date inside the value: Python
I have a JSON file that holds various dates as values, I need to delete all objects in the json on the condition that they include these dates.

Below is my JSON file, it has been cut for example's sake (as it goes up to the 60's & there can be multiple objects inside each of the lists). So when targeting the file it needs to be collectively, rather than stating "0" or "1" / [0] or [1] etc:

```<code>  {
    "transactions": {
        "0": [
            {
                "transaction_date": "11/29/2022",
                "asset_description": "Western Asset Inflation-Linked Opportunities & Inc",
                "asset_type": "Stock",
                "type": "Sale (Full)",
                "amount": "$1,001 - $15,000",
                "party": "Democrat"
            },
            {
                "transaction_date": "11/29/2021",
                "asset_description": "Goldman Sachs Access Treasury 0-1 Year ETF",
                "asset_type": "Other Securities",
                "type": "Purchase",
                "amount": "$1,001 - $15,000",
                "party": "Democrat"
            }
          ],
        "1":[
            {
                "transaction_date": "11/29/2019",
                "asset_description": "Western Asset Inflation-Linked Opportunities & Inc",
                "asset_type": "Stock",
                "type": "Sale (Full)",
                "amount": "$1,001 - $15,000",
                "party": "Democrat"
            }
          ]
    }
  }

</code>```

My code attempts to collect all objects on the condition that their values include the year of the date and then delete them from the JSON file:

```<code>import json

data = json.load(open("xxxtester.json"))

delete_keys = []

for value in data['transactions']:
    if data['transactions'][value] == '2013':
        delete_keys.append(value)
for value in data['transactions']:
    if data['transactions'][value] == '2014':
        delete_keys.append(value)
for value in data['transactions']:
    if data['transactions'][value] == '2015':
        delete_keys.append(value)
for value in data['transactions']:
    if data['transactions'][value] == '2016':
        delete_keys.append(value)
for value in data['transactions']:
    if data['transactions'][value] == '2017':
        delete_keys.append(value)
for value in data['transactions']:
    if data['transactions'][value] == '2018':
        delete_keys.append(value)
for value in data['transactions']:
    if data['transactions'][value] == '2019':
        delete_keys.append(value)
for value in data['transactions']:
    if data['transactions'][value] == '2020':
        delete_keys.append(value)
for value in data['transactions']:
    if data['transactions'][value] == '2021':
        delete_keys.append(value)

for key in delete_keys:
    del data['transactions'][key]

open("xxxtester.json", "w").write(
    json.dumps(data, indent=4))
</code>```

Is there a way for me to include code that can select a value if it INCLUDES x inside the value? As opposed to if the ENTIRE value is x. eg. calling the value by "2021" if the date is "11/29/2021", as there are multiple different dates so the easiest thing for me to do is call them by their year and delete them. I only need 2022 dates and newer.

Below is my desired output:

```<code>  {
    "transactions": {
        "0": [
            {
                "transaction_date": "11/29/2022",
                "asset_description": "Western Asset Inflation-Linked Opportunities & Inc",
                "asset_type": "Stock",
                "type": "Sale (Full)",
                "amount": "$1,001 - $15,000",
                "party": "Democrat"
            }
          ],
    }
  }

</code>```

Body:
I have a JSON file that holds various dates as values, I need to delete all objects in the json on the condition that they include these dates.

Below is my JSON file, it has been cut for example's sake (as it goes up to the 60's & there can be multiple objects inside each of the lists). So when targeting the file it needs to be collectively, rather than stating "0" or "1" / [0] or [1] etc:

  {
    "transactions": {
        "0": [
            {
                "transaction_date": "11/29/2022",
                "asset_description": "Western Asset Inflation-Linked Opportunities & Inc",
                "asset_type": "Stock",
                "type": "Sale (Full)",
                "amount": "$1,001 - $15,000",
                "party": "Democrat"
            },
            {
                "transaction_date": "11/29/2021",
                "asset_description": "Goldman Sachs Access Treasury 0-1 Year ETF",
                "asset_type": "Other Securities",
                "type": "Purchase",
                "amount": "$1,001 - $15,000",
                "party": "Democrat"
            }
          ],
        "1":[
            {
                "transaction_date": "11/29/2019",
                "asset_description": "Western Asset Inflation-Linked Opportunities & Inc",
                "asset_type": "Stock",
                "type": "Sale (Full)",
                "amount": "$1,001 - $15,000",
                "party": "Democrat"
            }
          ]
    }
  }

My code attempts to collect all objects on the condition that their values include the year of the date and then delete them from the JSON file:

import json

data = json.load(open("xxxtester.json"))

delete_keys = []

for value in data['transactions']:
    if data['transactions'][value] == '2013':
        delete_keys.append(value)
for value in data['transactions']:
    if data['transactions'][value] == '2014':
        delete_keys.append(value)
for value in data['transactions']:
    if data['transactions'][value] == '2015':
        delete_keys.append(value)
for value in data['transactions']:
    if data['transactions'][value] == '2016':
        delete_keys.append(value)
for value in data['transactions']:
    if data['transactions'][value] == '2017':
        delete_keys.append(value)
for value in data['transactions']:
    if data['transactions'][value] == '2018':
        delete_keys.append(value)
for value in data['transactions']:
    if data['transactions'][value] == '2019':
        delete_keys.append(value)
for value in data['transactions']:
    if data['transactions'][value] == '2020':
        delete_keys.append(value)
for value in data['transactions']:
    if data['transactions'][value] == '2021':
        delete_keys.append(value)

for key in delete_keys:
    del data['transactions'][key]

open("xxxtester.json", "w").write(
    json.dumps(data, indent=4))

Is there a way for me to include code that can select a value if it INCLUDES x inside the value? As opposed to if the ENTIRE value is x. eg. calling the value by "2021" if the date is "11/29/2021", as there are multiple different dates so the easiest thing for me to do is call them by their year and delete them. I only need 2022 dates and newer.

Below is my desired output:

  {
    "transactions": {
        "0": [
            {
                "transaction_date": "11/29/2022",
                "asset_description": "Western Asset Inflation-Linked Opportunities & Inc",
                "asset_type": "Stock",
                "type": "Sale (Full)",
                "amount": "$1,001 - $15,000",
                "party": "Democrat"
            }
          ],
    }
  }


问:
Can one explicitly stop Maven plugins after a module's build?
Our project comprises multiple modules. One of the plugins we use (soapui-maven-plugin used to provide mock services) needs a different configuration for each module.

That particular plugin, however, apparently does not end and get restarted for each module but "survives" between the modules. I.e. the first instance continues to run while subsequent modules are being built. The problem is, that this instance is then wrongly configured for those subsequent modules and hence out unit-test fail.

The plugin does not provide any explicit "stop" goal or such to explicitly terminate it.

My question thus: is there a generic way that would allow to enforce that all (or a specific) plugin(s) started for the build of a module is terminated at the end of the build of that module? Such that the subsequent build of a successor module then needs to restart that module again (using the proper config for that next module).

I would have expected that this is the default behavior of Maven and its plugins to terminate after each module but obviously not so. Is that maybe some artifact of enabling parallel builds?
Or can one force that plugin termination somehow?


问:
GLCM features for filter image
Suppose the GLCM has Homoginity, Energy, etc. features, but the problem is that all the values I got from the images have the same homogeneity and the same for all. Can anyone help me if this is correct, or did I do something wrong in the code? I tried but needed help understanding the output; why is it so? Is it after taking the filtered image? How will it become like that?</p>

Title: GLCM features for filter image


问:
Can not extract resource from com.android.aaptcompiler.ParsedResource@7091b558
I am having this problem.

I am having this problem.


问:
Pandas: How do I plot a bar graph similar to the one found in the Pandas documentation with a different type of DataFrame?
I have a DataFrame that looks like this:

There are 4 different sectors: Private Sector, Government Sector, Institutes of Higher Learning and Public Research Institutes,
and 3 types of expenditures: Capital Expenditure, Manpower Expenditure and Other Operating Expenditure

How do I make it look like this:

where I have the sectors on the x-axis and the different types of expenditures bunched up together per axis? The year does not matter for this chart.

The following code is my attempt at doing so (.csv used for the dataframe can be found here):

```<code>import pandas as pd

filePath = "./research-and-development-expenditure-by-type-of-cost/research-and-development-expenditure-by-type-of-cost.csv"
data = pd.read_csv(filePath)
df = pd.DataFrame(data)
dfByYear = df.set_index('year')
dfByYear = dfByYear.sort_values(['year', 'sector','type_of_expenditure'], ascending=[True,False,True])
totalExpenditureBySector = dfByYear.groupby(['sector', 'type_of_expenditure']).sum()
totalExpenditureBySector.plot.bar(rot=0,figsize=(15,10))
</code>```

This was the closest I've gotten so far:

From what I understand, the reason why the one in the Pandas documentation works and mine doesn't is the fact that the DataFrames are very different. How do I make this work?

Body:
I have a DataFrame that looks like this:

There are 4 different sectors: Private Sector, Government Sector, Institutes of Higher Learning and Public Research Institutes,
and 3 types of expenditures: Capital Expenditure, Manpower Expenditure and Other Operating Expenditure

How do I make it look like this:

where I have the sectors on the x-axis and the different types of expenditures bunched up together per axis? The year does not matter for this chart.

The following code is my attempt at doing so (.csv used for the dataframe can be found here):

import pandas as pd

filePath = "./research-and-development-expenditure-by-type-of-cost/research-and-development-expenditure-by-type-of-cost.csv"
data = pd.read_csv(filePath)
df = pd.DataFrame(data)
dfByYear = df.set_index('year')
dfByYear = dfByYear.sort_values(['year', 'sector','type_of_expenditure'], ascending=[True,False,True])
totalExpenditureBySector = dfByYear.groupby(['sector', 'type_of_expenditure']).sum()
totalExpenditureBySector.plot.bar(rot=0,figsize=(15,10))

This was the closest I've gotten so far:

From what I understand, the reason why the one in the Pandas documentation works and mine doesn't is the fact that the DataFrames are very different. How do I make this work?


问:
There is problem when trying to close and open the Nav "hamburger" menu on the mobile screen
enter image description here this befor you close
enter image description here after you close

```<code>const Navbar = () => {
  const [nav, setNav] = useState(false);
  const handleNav = () => setNav(!nav);
  return (
    <div name="top" className="navbar">
</code>```

//Then is my UnorderList

//Then this part where icons are inported

```<code><div className="hamburger" onClick={handleNav}>
          {!nav ? (
            <HiMenuAlt3 className="icon" />
          ) : (
            <RiCloseFill className="icon" />
          )}
        </div>
</code>```

So everything I have tried has been working so far i just need help in fixing the code

Body:
enter image description here this befor you close
enter image description here after you close

const Navbar = () => {
  const [nav, setNav] = useState(false);
  const handleNav = () => setNav(!nav);
  return (

//Then is my UnorderList

//Then this part where icons are inported

          {!nav ? (
            <HiMenuAlt3 className="icon" />
          ) : (
            <RiCloseFill className="icon" />
          )}

So everything I have tried has been working so far i just need help in fixing the code


问:
Cloud function that makes an API request works (204) when run as a script on local not via testing or functions-framework (401)
I'm working on a Google cloud gen1 non http triggered cloud function and I would like to test it locally before deploying.

The function makes an api request to github actions. It works locally with a 204 response when I just run the script on it's own. However, when I try to either run from the GCP functions UI using the testing tab, or via functions-framework, I get a 401 error.

Billing is enabled for the project.

Variable PAT is in .env file on local, on GCP it's a secret manifested as an env var.

The trigger for the function occurs once every 24 hours and I did notice that the function ran via the pub/sub trigger. I just cannot invoke the function locally or via the UI during the course of development and testing (the 401 response).

Here's main.py:

```<code>import requests
import os
from dotenv import load_dotenv

# globals, reads .env if present, else reads host env vars
load_dotenv()
OWNER = os.environ['OWNER']
REPO = os.environ['REPO']
EVENT_TYPE = os.environ['EVENT_TYPE']
PAT = os.environ['PAT']

# the function
def requestGHA(PAT=PAT, OWNER=OWNER, REPO=REPO, EVENT_TYPE=EVENT_TYPE):

    # Set up the headers for the API request
    headers = {
        "Accept": "application/vnd.github+json",
        "Authorization": f"Bearer {PAT}",
    }

    # Set up the URL for the API request
    url = f"https://api.github.com/repos/{OWNER}/{REPO}/dispatches"

    # Set up the payload for the API request
    payload = {
        "event_type": EVENT_TYPE,
        "client_payload": {
            "db_schema": "dev"
        }
    }

    # Make the API request
    response = requests.post(url, json=payload, headers=headers)

    return str(response.status_code)
</code>```

If I run this in a python console and then type requestGHA(), everything works with a 204 response. But when I try e.g. via functions framework:

```<code>$ functions-framework --target requestGHA --debug
 * Serving Flask app "requestGHA" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://192.168.0.33:8080/ (Press CTRL+C to quit)
 * Restarting with watchdog (inotify)
 * Debugger is active!
 * Debugger PIN: 103-819-696
</code>```

After running this if I visit http://localhost:8080/ I see 401.

Why can't I run my cloud function locally?

Body:
I'm working on a Google cloud gen1 non http triggered cloud function and I would like to test it locally before deploying.

The function makes an api request to github actions. It works locally with a 204 response when I just run the script on it's own. However, when I try to either run from the GCP functions UI using the testing tab, or via functions-framework, I get a 401 error.

Billing is enabled for the project.

Variable PAT is in .env file on local, on GCP it's a secret manifested as an env var.

The trigger for the function occurs once every 24 hours and I did notice that the function ran via the pub/sub trigger. I just cannot invoke the function locally or via the UI during the course of development and testing (the 401 response).

Here's main.py:

import requests
import os
from dotenv import load_dotenv

# globals, reads .env if present, else reads host env vars
load_dotenv()
OWNER = os.environ['OWNER']
REPO = os.environ['REPO']
EVENT_TYPE = os.environ['EVENT_TYPE']
PAT = os.environ['PAT']

# the function
def requestGHA(PAT=PAT, OWNER=OWNER, REPO=REPO, EVENT_TYPE=EVENT_TYPE):

    # Set up the headers for the API request
    headers = {
        "Accept": "application/vnd.github+json",
        "Authorization": f"Bearer {PAT}",
    }

    # Set up the URL for the API request
    url = f"https://api.github.com/repos/{OWNER}/{REPO}/dispatches"

    # Set up the payload for the API request
    payload = {
        "event_type": EVENT_TYPE,
        "client_payload": {
            "db_schema": "dev"
        }
    }

    # Make the API request
    response = requests.post(url, json=payload, headers=headers)

    return str(response.status_code)

If I run this in a python console and then type requestGHA(), everything works with a 204 response. But when I try e.g. via functions framework:

$ functions-framework --target requestGHA --debug
 * Serving Flask app "requestGHA" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://192.168.0.33:8080/ (Press CTRL+C to quit)
 * Restarting with watchdog (inotify)
 * Debugger is active!
 * Debugger PIN: 103-819-696

After running this if I visit http://localhost:8080/ I see 401.

Why can't I run my cloud function locally?


问:
How Form component renders JSON schema objects in React?
I am using react-jsonschema library to render the UI in react using JSON schema. I want to know exactly how  is rendering the UI. I know there should be some logic to iterate the objects from JSON Schema but what exactly it is? There are few other libraries like Jsonforms which also uses   component. I tried replicating the github repository from react-jsonschema and tried searching for the Form component in Node Modules under "rjsf" folder but couldn't find it. Can someone please help me?

I tried checking the Node Modules files for rjsf but got typescript declaration file.


问:
message.guilds.fetchAuditLogs is not a function
I recently updated my bot from discordjs v13 to v14, everything works so far except for reading/fetching auditlogs

My Test-Code

```<code>module.exports = async (client, message) => {
    if (!message.guilds) return;
    console.log(message.guilds)

        console.log("1")
        await new Promise(resolve => setTimeout(resolve, 5000));
        console.log("2")
         const fetchedLogs = await message.guilds.fetchAuditLogs( {
            limit: 6,
            type: 'MESSAGE_DELETE'
        } )
        console.log("3")
        console.log(fetchedLogs)
    }
</code>```

With discordv13 my "logger" for the deleted messages worked without problems, but since discordv14 i get this error:

When I use message.guilds:

message.guilds.fetchAuditLogs is not a function

When I use message.guild:

TypeError: Cannot read properties of undefined (reading 'fetchAuditLogs')

According to documentation message.guild.fetchAuditLogs()
would be the correct way to do it but message.guild returned "undefined" while message.guilds returned the GuildManager()

Body:
I recently updated my bot from discordjs v13 to v14, everything works so far except for reading/fetching auditlogs

My Test-Code

module.exports = async (client, message) => {
    if (!message.guilds) return;
    console.log(message.guilds)

        console.log("1")
        await new Promise(resolve => setTimeout(resolve, 5000));
        console.log("2")
         const fetchedLogs = await message.guilds.fetchAuditLogs( {
            limit: 6,
            type: 'MESSAGE_DELETE'
        } )
        console.log("3")
        console.log(fetchedLogs)
    }

With discordv13 my "logger" for the deleted messages worked without problems, but since discordv14 i get this error:

When I use message.guilds:

message.guilds.fetchAuditLogs is not a function

When I use message.guild:

TypeError: Cannot read properties of undefined (reading 'fetchAuditLogs')

According to documentation message.guild.fetchAuditLogs()
would be the correct way to do it but message.guild returned "undefined" while message.guilds returned the GuildManager()