问:
Updating SVG Document CSS styles not always reflected in resulting image
I have inherited code from a Batik application, which loads an SVG Document from file and puts it in a buffered image property in the class, which is then converted to a PNG by the client. Initially loading it works fine. Updating it does not work. The code below is for initial loading of the document, parsing it, and writing it into a buffered image.

```<code>public void decode(BOrd ord, byte[] bytes, BTransform.Scale scale) {
      try {
         InputStream inputStream = new ByteArrayInputStream(bytes);
         String uri = "ord://" + ord;
         String parser = XMLResourceDescriptor.getXMLParserClassName();
         SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
         svgDocument = (SVGOMDocument)f.createDocument(uri, inputStream);
         originalStyles=null; //Set to null to force update
         updateDocument(svgDocument, owner);
         UserAgent userAgent = new UserAgentAdapter();
         BridgeContext bridgeContext = AccessController.doPrivileged((PrivilegedAction<BridgeContext>)() -> {
            return new BridgeContext(userAgent, new DocumentLoader(userAgent)) {
               public SVGAnimationEngine getAnimationEngine() {
                  if (this.animationEngine == null) {
                     this.animationEngine = new SVGAnimationEngine(this.document, this) {
                        protected float tick(float time, boolean hyperlinking) {
                           return BMtSvgDecoder.ENABLE_SVG_HYPERLINKING ? super.tick(time, hyperlinking) : super.tick(time, false);
                        }
                     };
                     this.setAnimationLimitingMode();
                  }

                  return this.animationEngine;
               }
            };
         });
         //Dynamic state means that the rendering should update if the document has changed.
         bridgeContext.setDynamicState(BridgeContext.DYNAMIC);
         //Remember the bridge context.
         this.bridgeContext=bridgeContext;
         //GVT is the data structure used internally to render the document
         GVTBuilder builder = new GVTBuilder();
         GraphicsNode gvtRoot = builder.build(bridgeContext, svgDocument);
         this.image = initImage(bridgeContext, scale);
         if (scale != null) {
            AffineTransform trans = new AffineTransform();
            trans.scale(scale.getX(), scale.getY());
            gvtRoot.setTransform(trans);
         }
         this.image = initImage(bridgeContext, scale);
         renderImage(this.image, gvtRoot);//Creates the buffered image which is stored as field.
         if (hasAnimationElement(svgDocument)) {
            this.animator = new BMtSvgDecoder.SvgAnimator(svgDocument, bridgeContext, gvtRoot, scale);
         } else {
            this.animator = null;
         }
//         printXML("Initially loaded SVG", svgDocument);
      } catch (Exception e) {
         throw new BajaRuntimeException(e);
      }
   }
</code>```

The "updateDocument(svgDocument, owner)" method, does 2 things:

It retrieves the
    <defs id="Patterns_And_Gradients">
        <radialGradient id="radialGradient1" cx="0.5" cy="0.5" r="0.73">
            <stop class="gradient1-start" offset="0%"/>
            <stop class="gradient1-mid" offset="10%"/>
            <stop class="gradient1-stop" offset="100%"/>
        </radialGradient>
    </defs>
    <g id="widgetContainer">
        <g id="shape" class="shapePositionTransform">
            <circle class="format1 gradient1" cx="100" cy="100" r="20"/>
            <text id="symbolText" class="symbolTextFormat symbolTextXYAdjust" x="100" y="100">T</text>

        <g id="probe">

            <line id="probeLine" class="format1 shapeOrientationTransform" x1="100" y1="80" x2="100" y2="60"/>
        </g>
    </g>
    <g id="valueStatusTextGroup">
        <text id="valueText" class="valueTextFormat valueTextTransform" x="0" y="0">20 °C
        <tspan id="statusTextPrefix">{</tspan>
        <tspan id="statusTextOverridden" class="statusTextFormat statusTextXYAdjust" dx="-5">✋</tspan>
        <tspan id="statusTextAlarm" class="statusTextFormat statusTextXYAdjust" dx="-4">⚠</tspan>
        <tspan id="statusTextSuffix" class= "statusTextXYAdjust" dx="-2">}</tspan></text>
    </g>
</g>
</svg>

```
<p>Here is the resulting document after update:</p>
```<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ev="http://www.w3.org/2001/xml-events" contentScriptType="text/ecmascript" zoomAndPan="magnify" contentStyleType="text/css" version="1.0" width="200px" xml:space="preserve" preserveAspectRatio="xMidYMid meet" viewBox="0 0 200 200" height="200px" class="base" color-interpolation-filters="sRGB">
        <style id="styles" xml:space="preserve">
  :root{
        --angle1: 90deg;
        --origin-x1: 100px;
        --origin-y1: 100px;
        --translate-x1: 0px;
        --translate-y1: 0px;
        --angle2: 0deg;
        --origin-x2: 0px;
        --origin-y2: 0px;
        --translate-x2: 100px;
        --translate-y2: 140px;
        --color1: #ff0000;
        --color2: #ffffff;
        --color3: #000000;
        --color4: #0000ff;
        --colorSymbolText: #000000;
        --colorValueText: #000000;
        --colorStatusText: #ff0000;
        --stroke1-width: 3.0px;
        --font1-family: Calibri;
        --font1-size: 24.0;
        --font1-style: normal;
        --font1-weight: normal;
        --font1-text-decoration: none;
        --font2-family: Calibri;
        --font2-size: 18.0;
        --font2-style: normal;
        --font2-weight: normal;
        --font2-text-decoration: none;
        --font3-family: Segoe UI Symbol;
        --font3-size: 18.0;
        --font3-style: normal;
        --font3-weight: normal;
        --font3-text-decoration: none;
        }
    .format1 {
            fill: #ff0000;
                stroke: #000000;
                stroke-width: 3.0px;
        }
        .symbolTextFormat{
                text-anchor:middle;
                dominant-baseline: central;
                font-family: Calibri;
                font-size: 24.0;
                font-style: normal;
        font-weight: normal;
                text-decoration: none;
                fill: #000000;
        }
        .valueTextFormat{
                text-anchor:middle;
                dominant-baseline: central;
                font-family: Calibri;
                font-size: 18.0;
                font-style: normal;
        font-weight: normal;
                text-decoration: none;
                fill: #000000;
        }
        .statusTextFormat{
                font-family: Segoe UI Symbol;
                font-size: 18.0;
                font-style: normal;
        font-weight: normal;
                text-decoration: none;
                fill: #ff0000;
        }
        .gradient1 {
            fill: url(#radialGradient1);
        }

        .gradient1-start {
                stop-color:#ffffff;
                stop-opacity: 1;
        }
    .gradient1-mid {
                stop-color:#ffffff;
                stop-opacity: 1;
        }
    .gradient1-stop {
                stop-color:#ff0000;
                stop-opacity: 1;
        }
  </style>
        <defs id="Patterns_And_Gradients">
                <radialGradient xlink:type="simple" r="0.73" xlink:actuate="onLoad" cx="0.5" cy="0.5" id="radialGradient1" xlink:show="other">
                        <stop offset="0%" class="gradient1-start"/>
                        <stop offset="10%" class="gradient1-mid"/>
                        <stop offset="100%" class="gradient1-stop"/>
                </radialGradient>
        </defs>
        <g id="widgetContainer">
                <g class="shapePositionTransform" id="shape" transform="rotate(0.0, 0.0, 0.0) translate(0.0, 0.0)">
                        <circle r="20" class="format1 gradient1" cx="100" cy="100"/>
                        <text dy="8.5" x="100" y="100" id="symbolText" class="symbolTextFormat symbolTextXYAdjust">T</text>

                <g id="probe">

                        <line transform="rotate(90.0, 100.0, 100.0) translate(0.0, 0.0)" x1="100" x2="100" y1="80" y2="60" class="format1 shapeOrientationTransform" id="probeLine"/>
                </g>
        </g>
        <g id="valueStatusTextGroup">
                <text x="0" y="0" id="valueText" class="valueTextFormat valueTextTransform" transform="rotate(0.0, 100.0, 100.0) translate(100.0, 140.0)">-26.5 ┬░C<tspan id="statusTextPrefix">[</tspan>
                <tspan class="statusTextFormat statusTextXYAdjust" dx="-11.0" id="statusTextOverridden"/>
                <tspan class="statusTextFormat statusTextXYAdjust" dx="-11.0" id="statusTextAlarm">ÔÜá</tspan>
                <tspan class="statusTextXYAdjust" dx="-11.0" id="statusTextSuffix">]</tspan></text>
        </g>
</g>
</svg>
```

What I noted is that somewhere in the process, the strange xlink... attributes have been introduced into the svg.

Anyone has an idea why the code above won't consider the changed style?

Body:
I have inherited code from a Batik application, which loads an SVG Document from file and puts it in a buffered image property in the class, which is then converted to a PNG by the client. Initially loading it works fine. Updating it does not work. The code below is for initial loading of the document, parsing it, and writing it into a buffered image.

public void decode(BOrd ord, byte[] bytes, BTransform.Scale scale) {
      try {
         InputStream inputStream = new ByteArrayInputStream(bytes);
         String uri = "ord://" + ord;
         String parser = XMLResourceDescriptor.getXMLParserClassName();
         SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
         svgDocument = (SVGOMDocument)f.createDocument(uri, inputStream);
         originalStyles=null; //Set to null to force update
         updateDocument(svgDocument, owner);
         UserAgent userAgent = new UserAgentAdapter();
         BridgeContext bridgeContext = AccessController.doPrivileged((PrivilegedAction<BridgeContext>)() -> {
            return new BridgeContext(userAgent, new DocumentLoader(userAgent)) {
               public SVGAnimationEngine getAnimationEngine() {
                  if (this.animationEngine == null) {
                     this.animationEngine = new SVGAnimationEngine(this.document, this) {
                        protected float tick(float time, boolean hyperlinking) {
                           return BMtSvgDecoder.ENABLE_SVG_HYPERLINKING ? super.tick(time, hyperlinking) : super.tick(time, false);
                        }
                     };
                     this.setAnimationLimitingMode();
                  }

                  return this.animationEngine;
               }
            };
         });
         //Dynamic state means that the rendering should update if the document has changed.
         bridgeContext.setDynamicState(BridgeContext.DYNAMIC);
         //Remember the bridge context.
         this.bridgeContext=bridgeContext;
         //GVT is the data structure used internally to render the document
         GVTBuilder builder = new GVTBuilder();
         GraphicsNode gvtRoot = builder.build(bridgeContext, svgDocument);
         this.image = initImage(bridgeContext, scale);
         if (scale != null) {
            AffineTransform trans = new AffineTransform();
            trans.scale(scale.getX(), scale.getY());
            gvtRoot.setTransform(trans);
         }
         this.image = initImage(bridgeContext, scale);
         renderImage(this.image, gvtRoot);//Creates the buffered image which is stored as field.
         if (hasAnimationElement(svgDocument)) {
            this.animator = new BMtSvgDecoder.SvgAnimator(svgDocument, bridgeContext, gvtRoot, scale);
         } else {
            this.animator = null;
         }
//         printXML("Initially loaded SVG", svgDocument);
      } catch (Exception e) {
         throw new BajaRuntimeException(e);
      }
   }

The "updateDocument(svgDocument, owner)" method, does 2 things:

It retrieves the
    <defs id="Patterns_And_Gradients">
        <radialGradient id="radialGradient1" cx="0.5" cy="0.5" r="0.73">
            <stop class="gradient1-start" offset="0%"/>
            <stop class="gradient1-mid" offset="10%"/>
            <stop class="gradient1-stop" offset="100%"/>
        </radialGradient>
    </defs>
    <g id="widgetContainer">
        <g id="shape" class="shapePositionTransform">
            <circle class="format1 gradient1" cx="100" cy="100" r="20"/>
            <text id="symbolText" class="symbolTextFormat symbolTextXYAdjust" x="100" y="100">T</text>

        <g id="probe">

            <line id="probeLine" class="format1 shapeOrientationTransform" x1="100" y1="80" x2="100" y2="60"/>
        </g>
    </g>
    <g id="valueStatusTextGroup">
        <text id="valueText" class="valueTextFormat valueTextTransform" x="0" y="0">20 °C
        <tspan id="statusTextPrefix">{</tspan>
        <tspan id="statusTextOverridden" class="statusTextFormat statusTextXYAdjust" dx="-5">✋</tspan>
        <tspan id="statusTextAlarm" class="statusTextFormat statusTextXYAdjust" dx="-4">⚠</tspan>
        <tspan id="statusTextSuffix" class= "statusTextXYAdjust" dx="-2">}</tspan></text>
    </g>
</g>
</svg>

Here is the resulting document after update:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ev="http://www.w3.org/2001/xml-events" contentScriptType="text/ecmascript" zoomAndPan="magnify" contentStyleType="text/css" version="1.0" width="200px" xml:space="preserve" preserveAspectRatio="xMidYMid meet" viewBox="0 0 200 200" height="200px" class="base" color-interpolation-filters="sRGB">

        <defs id="Patterns_And_Gradients">
                <radialGradient xlink:type="simple" r="0.73" xlink:actuate="onLoad" cx="0.5" cy="0.5" id="radialGradient1" xlink:show="other">
                        <stop offset="0%" class="gradient1-start"/>
                        <stop offset="10%" class="gradient1-mid"/>
                        <stop offset="100%" class="gradient1-stop"/>
                </radialGradient>
        </defs>
        <g id="widgetContainer">
                <g class="shapePositionTransform" id="shape" transform="rotate(0.0, 0.0, 0.0) translate(0.0, 0.0)">
                        <circle r="20" class="format1 gradient1" cx="100" cy="100"/>
                        <text dy="8.5" x="100" y="100" id="symbolText" class="symbolTextFormat symbolTextXYAdjust">T</text>

                <g id="probe">

                        <line transform="rotate(90.0, 100.0, 100.0) translate(0.0, 0.0)" x1="100" x2="100" y1="80" y2="60" class="format1 shapeOrientationTransform" id="probeLine"/>
                </g>
        </g>
        <g id="valueStatusTextGroup">
                <text x="0" y="0" id="valueText" class="valueTextFormat valueTextTransform" transform="rotate(0.0, 100.0, 100.0) translate(100.0, 140.0)">-26.5 ┬░C<tspan id="statusTextPrefix">[</tspan>
                <tspan class="statusTextFormat statusTextXYAdjust" dx="-11.0" id="statusTextOverridden"/>
                <tspan class="statusTextFormat statusTextXYAdjust" dx="-11.0" id="statusTextAlarm">ÔÜá</tspan>
                <tspan class="statusTextXYAdjust" dx="-11.0" id="statusTextSuffix">]</tspan></text>
        </g>
</g>
</svg>

What I noted is that somewhere in the process, the strange xlink... attributes have been introduced into the svg.

Anyone has an idea why the code above won't consider the changed style?


来源: stackexchange

问:
switch case in do-while loop using character(char) data type
```<code>#include<stdio.h>

int main() {
    char operation='f';//Its working fine with int data type
    float n1, n2;
    printf("Enter two operands: \n");
    scanf("%f %f",&n1, &n2);

    do{
    printf("Enter an operator (+, -, *, /, f: for exit): \n");
    scanf("%c", &operation);

    switch(operation)
    {
        case '+':  //Replace '+' by 1 when operation is int data type
            printf("%.1f + %.1f = %.1f\n",n1, n2, n1+n2);
            break;

        case '-':  //Replace '-' by 2 when operation is int data type
            printf("%.1f - %.1f = %.1f\n",n1, n2, n1-n2);
            break;

        case '*':  //Replace '*' by 3 when operation is int data type
            printf("%.1f * %.1f = %.1f\n",n1, n2, n1*n2);
            break;

        case '/':  //Replace '/' by 4 when operation is int data type
            printf("%.1f / %.1f = %.1f\n",n1, n2, n1/n2);
            break;
    case 'f':  //Replace 'f' by 0 when operation is int data type
    break;
        // operator doesn't match any case constant +, -, *, /
        default:
            printf("Error! operator is not correct\n");
    }
    }while(operation!='f');

    return 0;
}

***CONSOLE USING char type**
*
──(kali㉿kali)-[~/Desktop/program]
└─$ gcc test01.c

┌──(kali㉿kali)-[~/Desktop/program]
└─$ ./a.out
Enter two operands:
12
5
Enter an operator (+, -, *, /, f for exit):
Error! operator is not correct
Enter an operator (+, -, *, /, f for exit):
+
12.0 + 5.0 = 17.0
Enter an operator (+, -, *, /, f for exit):
Error! operator is not correct
Enter an operator (+, -, *, /, f for exit):
h
Error! operator is not correct
Enter an operator (+, -, *, /, f for exit):
Error! operator is not correct
Enter an operator (+, -, *, /, f for exit):
f

┌──(kali㉿kali)-[~/Desktop/program]
└─$

***CONSOLE USING int data type for variable operation***

┌──(kali㉿kali)-[~/Desktop/program]
└─$ gcc test01.c

┌──(kali㉿kali)-[~/Desktop/program]
└─$ ./a.out
Enter two operands:
12
4
Enter an operator (1, 2, 3, 4, 0 for exit):
1
12.0 + 4.0 = 16.0
Enter an operator (1, 2, 3, 4, 0 for exit):
0

┌──(kali㉿kali)-[~/Desktop/program]
└─$

</code>```

After "Enter an operator (+, -, *, /, f for exit):" it should take the input value using "scanf()", instead it is going to the "default case" and once again it is showing this "Enter an operator (+, -, *, /, f for exit):"  and asking for input. But this is not the case when I am using any "char data type" rather it is working when I am using "int data type". Please explain.

I am using it in LINUX base OS, Kali.

ContentLicense: CC BY-SA 4.0

Body:
#include<stdio.h>

int main() {
    char operation='f';//Its working fine with int data type
    float n1, n2;
    printf("Enter two operands: \n");
    scanf("%f %f",&n1, &n2);

    do{
    printf("Enter an operator (+, -, *, /, f: for exit): \n");
    scanf("%c", &operation);

    switch(operation)
    {
        case '+':  //Replace '+' by 1 when operation is int data type
            printf("%.1f + %.1f = %.1f\n",n1, n2, n1+n2);
            break;

        case '-':  //Replace '-' by 2 when operation is int data type
            printf("%.1f - %.1f = %.1f\n",n1, n2, n1-n2);
            break;

        case '*':  //Replace '*' by 3 when operation is int data type
            printf("%.1f * %.1f = %.1f\n",n1, n2, n1*n2);
            break;

        case '/':  //Replace '/' by 4 when operation is int data type
            printf("%.1f / %.1f = %.1f\n",n1, n2, n1/n2);
            break;
    case 'f':  //Replace 'f' by 0 when operation is int data type
    break;
        // operator doesn't match any case constant +, -, *, /
        default:
            printf("Error! operator is not correct\n");
    }
    }while(operation!='f');

    return 0;
}

***CONSOLE USING char type**
*
──(kali㉿kali)-[~/Desktop/program]
└─$ gcc test01.c

┌──(kali㉿kali)-[~/Desktop/program]
└─$ ./a.out
Enter two operands:
12
5
Enter an operator (+, -, *, /, f for exit):
Error! operator is not correct
Enter an operator (+, -, *, /, f for exit):
+
12.0 + 5.0 = 17.0
Enter an operator (+, -, *, /, f for exit):
Error! operator is not correct
Enter an operator (+, -, *, /, f for exit):
h
Error! operator is not correct
Enter an operator (+, -, *, /, f for exit):
Error! operator is not correct
Enter an operator (+, -, *, /, f for exit):
f

┌──(kali㉿kali)-[~/Desktop/program]
└─$

***CONSOLE USING int data type for variable operation***

┌──(kali㉿kali)-[~/Desktop/program]
└─$ gcc test01.c

┌──(kali㉿kali)-[~/Desktop/program]
└─$ ./a.out
Enter two operands:
12
4
Enter an operator (1, 2, 3, 4, 0 for exit):
1
12.0 + 4.0 = 16.0
Enter an operator (1, 2, 3, 4, 0 for exit):
0

┌──(kali㉿kali)-[~/Desktop/program]
└─$

After "Enter an operator (+, -, *, /, f for exit):" it should take the input value using "scanf()", instead it is going to the "default case" and once again it is showing this "Enter an operator (+, -, *, /, f for exit):"  and asking for input. But this is not the case when I am using any "char data type" rather it is working when I am using "int data type". Please explain.

I am using it in LINUX base OS, Kali.


问:
React application gets data from secureLocalStorage only when devTools is opened. How to make it to always get it?
I am storing some information about a user in secureLocalStorage and I use useEffect in order to get that information when rendering the page. However, it gets the data only when the devTools is opened. When it is not opened, it just gets a null, even though there is data in the localStorage.

useEffect(() => {
  const fetchUsers = async () => {
    setLoading(true);
    let aux = await JSON.parse(secureLocalStorage.getItem("om"));
    console.log(aux);
    if (aux == undefined) {
      setUser(null);
    } else {
      setUser(aux);
    }
    setLoading(false);
  };

  fetchUsers();
}, []);
```

I really can't understand why it reads data only when devTools is opened. What should I do in order to make it get the data when rendering the page without devTools being opened?

Everything that I have tried has been mentioned in the code above.

Body:
I am storing some information about a user in secureLocalStorage and I use useEffect in order to get that information when rendering the page. However, it gets the data only when the devTools is opened. When it is not opened, it just gets a null, even though there is data in the localStorage.

useEffect(() => {
  const fetchUsers = async () => {
    setLoading(true);
    let aux = await JSON.parse(secureLocalStorage.getItem("om"));
    console.log(aux);
    if (aux == undefined) {
      setUser(null);
    } else {
      setUser(aux);
    }
    setLoading(false);
  };

  fetchUsers();
}, []);

I really can't understand why it reads data only when devTools is opened. What should I do in order to make it get the data when rendering the page without devTools being opened?

Everything that I have tried has been mentioned in the code above.


问:
AWS SQS - Configure the number of times the message to move from DLQ to source queue using Redrive policy
Is there a way to configure the redrive policy so that the number of times the messages to move from DLQ to source queue, or it keeps on redriving the messages to the source queue from DLQ if we set the redrive policy?

I went through the AWS documentation on Redrive policy, but couldn't find any. Please share the resources if any to look into.


问:
Problem with playing the next song automatically with SDL_Mixer
I have this c program which used to search for the mp3 files of given directory and add the files data to linked list.i use SDL2 for audio handling. so much far i would be able to get the playing of mp3 file and what i'm facing here is that i don't know how to play the next song when the first song is played in the linked list.

Here is my code for the program.

```<code>#include <dirent.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "file_handle.h"

#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>

struct tags
{
  const char *artist;
} tags;

Mix_Music *music = NULL;

bool loadmedia(char *filepath);
void play();
void init();
void load_file_directory(char *dir_path);

int main(int argc, char *argv[])
{

  char *file_path;

  if (argc <= 1)
  {
    fprintf(stderr, "no arguments provided!\n");
  }
  else
  {
    file_path = argv[2];
  }

  if (file_path)
  {
    load_file_directory(file_path);
  }

  init();

  int count = 0;
  for (struct song *node = head; node; node = node->next)
  {
    printf("%s\n", node->file_path);
  }
  for (struct song *node = head; node; node = node->next)
  {
    printf("%s\n", node->file_path);
    printf("count is %d\n", count);
    count++;
    Mix_Music *song = Mix_LoadMUS(node->file_path);
    if (Mix_PlayMusic(song, 1) != 0)
    {
      printf("something\n");
    }
    while (!SDL_QuitRequested())
      SDL_Delay(250);
    Mix_FreeMusic(song);
  }

  // char *file = argv[1];

  // bool status = loadmedia(file);
  // if(status){
  //   printf("%s - %s\n",Mix_GetMusicArtistTag(music),Mix_GetMusicTitleTag(music));
  //   if(Mix_PlayMusic(music,1)){
  //     printf("something wrong");
  //     Mix_FreeMusic(music);

  //   }

  // }

  // while(!SDL_QuitRequested())
  // SDL_Delay(250);
}

bool loadmedia(char *file_path)
{

  bool success = false;
  if (file_path)
  {
    music = Mix_LoadMUS(file_path);
    success = true;
  }
  else
  {
    printf("File Loaded Failed\n");
  }

  return success;
}

void init()
{

  bool success;
  if (SDL_Init(SDL_INIT_AUDIO) < 0)
  {
    printf("Couldn't initialize SDL: %s\n", SDL_GetError());
    success = false;
  }

  if (Mix_Init(MIX_INIT_MP3) != MIX_INIT_MP3)
  {
    fprintf(stderr, "could not initialized mixer\n", Mix_GetError());
  }

  if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0)
  {
    printf("SDL_mixer could not be initialized %s\n", Mix_GetError());
    success = false;
  }
}
</code>```

Body:
I have this c program which used to search for the mp3 files of given directory and add the files data to linked list.i use SDL2 for audio handling. so much far i would be able to get the playing of mp3 file and what i'm facing here is that i don't know how to play the next song when the first song is played in the linked list.

Here is my code for the program.

#include <dirent.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "file_handle.h"

#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>

struct tags
{
  const char *artist;
} tags;

Mix_Music *music = NULL;

bool loadmedia(char *filepath);
void play();
void init();
void load_file_directory(char *dir_path);

int main(int argc, char *argv[])
{

  char *file_path;

  if (argc <= 1)
  {
    fprintf(stderr, "no arguments provided!\n");
  }
  else
  {
    file_path = argv[2];
  }

  if (file_path)
  {
    load_file_directory(file_path);
  }

  init();

  int count = 0;
  for (struct song *node = head; node; node = node->next)
  {
    printf("%s\n", node->file_path);
  }
  for (struct song *node = head; node; node = node->next)
  {
    printf("%s\n", node->file_path);
    printf("count is %d\n", count);
    count++;
    Mix_Music *song = Mix_LoadMUS(node->file_path);
    if (Mix_PlayMusic(song, 1) != 0)
    {
      printf("something\n");
    }
    while (!SDL_QuitRequested())
      SDL_Delay(250);
    Mix_FreeMusic(song);
  }

  // char *file = argv[1];

  // bool status = loadmedia(file);
  // if(status){
  //   printf("%s - %s\n",Mix_GetMusicArtistTag(music),Mix_GetMusicTitleTag(music));
  //   if(Mix_PlayMusic(music,1)){
  //     printf("something wrong");
  //     Mix_FreeMusic(music);

  //   }

  // }

  // while(!SDL_QuitRequested())
  // SDL_Delay(250);
}

bool loadmedia(char *file_path)
{

  bool success = false;
  if (file_path)
  {
    music = Mix_LoadMUS(file_path);
    success = true;
  }
  else
  {
    printf("File Loaded Failed\n");
  }

  return success;
}

void init()
{

  bool success;
  if (SDL_Init(SDL_INIT_AUDIO) < 0)
  {
    printf("Couldn't initialize SDL: %s\n", SDL_GetError());
    success = false;
  }

  if (Mix_Init(MIX_INIT_MP3) != MIX_INIT_MP3)
  {
    fprintf(stderr, "could not initialized mixer\n", Mix_GetError());
  }

  if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0)
  {
    printf("SDL_mixer could not be initialized %s\n", Mix_GetError());
    success = false;
  }
}


问:
Flyway unable to find location and load sql scripts
After launching an application written in spring boot, the sql scripts do not load into the database.

Only an empty table named flyway_schema_history is created in the database.

The path given to the scripts is as follows: resources/db.migration

An example script named V1__create_invoice.sql looks like this:

```<code>create table invoice
(
    id          bigint        not null auto_increment PRIMARY KEY,
    name        varchar(255)  not null,
    price       decimal(9, 2) not null,
);
</code>```

In the IntelliJ console, I get such information about the database or flyway:

This is how flyway configuration files are defined:

```<code>spring.flyway.baselineOnMigrate=true
spring.flyway.locations=classpath:resources/db/migration
spring.flyway.enabled=true
</code>```

This is how the files to connect to the database are defined:

```<code>spring.datasource.url=jdbc:mysql://${DATABASE_URL:localhost}:${DATABASE_PORT:3306}/${DATABASE_NAME:public}?useUnicode=true&serverTimezone=UTC
spring.datasource.username=${DATABASE_USERNAME:root}
spring.datasource.password=${DATABASE_PASSWORD:password}
</code>```

I've tried changing the path to the scripts folder several times, for example like this
classpath:db/migration or classpath:db.migration but it didn't change anything.

Body:
After launching an application written in spring boot, the sql scripts do not load into the database.

Only an empty table named flyway_schema_history is created in the database.

The path given to the scripts is as follows: resources/db.migration

An example script named V1__create_invoice.sql looks like this:

create table invoice
(
    id          bigint        not null auto_increment PRIMARY KEY,
    name        varchar(255)  not null,
    price       decimal(9, 2) not null,
);

In the IntelliJ console, I get such information about the database or flyway:

This is how flyway configuration files are defined:

spring.flyway.baselineOnMigrate=true
spring.flyway.locations=classpath:resources/db/migration
spring.flyway.enabled=true

This is how the files to connect to the database are defined:

spring.datasource.url=jdbc:mysql://${DATABASE_URL:localhost}:${DATABASE_PORT:3306}/${DATABASE_NAME:public}?useUnicode=true&serverTimezone=UTC
spring.datasource.username=${DATABASE_USERNAME:root}
spring.datasource.password=${DATABASE_PASSWORD:password}

I've tried changing the path to the scripts folder several times, for example like this
classpath:db/migration or classpath:db.migration but it didn't change anything.


问:
Could not find driver using MySQL database in PhpStorm
In PhpStorm, when trying to access the database from the web, Fatal error: Uncaught PDOException: could not find driver pops out. When testing connection in Data Sources and Drivers, driver is shown and connection is OK.

I removed the uncommented the extension=pdo_mysql in php.ini file. When running it from the console, works fine.


问:
passport.authenticate('local', function (err, user, info) is not working
I'm having some issues with setting up passport. The information gets to the console.log(req.body). and the user is being saved in the mongodb database with all the salting and hashing
passport.authenticate is not woking while signing up new users. but
and Express sessions are not being created.

```<code>
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const cors = require('cors');

const session = require('express-session');
const passport = require("passport");
const LocalStrategy = require("passport-local");
const passportLocalMongoose = require("passport-local-mongoose");
const findOrCreate = require("mongoose-findorcreate");

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(
  cors({
    origin: true,
    credentials: true,
    optionsSuccessStatus: 200
  }));
mongoose.set("strictQuery", false);

app.use(session({
  secret: "our little secret.",
  resave: false,
  saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

mongoose.connect("mongodb://localhost:27017/blogDB");
const userSchema = new mongoose.Schema(
  {
    name: String,
    username: String,
    password: String,
    posts: [{
      title: String,
      content: String,
      timestamp: Date
    }]
  }
);
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
const User = new mongoose.model("user", userSchema);

passport.use(new LocalStrategy(User.authenticate()));
// passport.use(User.createStrategy());
passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
      done(err, user);
  });
});

app.post("/signup", function (req, res) {
  User.register(
    { name:req.body.name,
      username:req.body.email },
    req.body.password,
    function (err, user) {
      if (err) {
        console.log(err);
      } else {
        res.send(user);
        passport.authenticate('local', function (err, user, info) {
          if (!err) {
          console.log("authenticated");
          }
        })(req, res)
      }
    })
})

</code>```

i have been searching the whole web tring to find a solution, tried a so many solutions but nothing worked

Body:
I'm having some issues with setting up passport. The information gets to the console.log(req.body). and the user is being saved in the mongodb database with all the salting and hashing
passport.authenticate is not woking while signing up new users. but
and Express sessions are not being created.

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const cors = require('cors');

const session = require('express-session');
const passport = require("passport");
const LocalStrategy = require("passport-local");
const passportLocalMongoose = require("passport-local-mongoose");
const findOrCreate = require("mongoose-findorcreate");

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(
  cors({
    origin: true,
    credentials: true,
    optionsSuccessStatus: 200
  }));
mongoose.set("strictQuery", false);

app.use(session({
  secret: "our little secret.",
  resave: false,
  saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

mongoose.connect("mongodb://localhost:27017/blogDB");
const userSchema = new mongoose.Schema(
  {
    name: String,
    username: String,
    password: String,
    posts: [{
      title: String,
      content: String,
      timestamp: Date
    }]
  }
);
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
const User = new mongoose.model("user", userSchema);

passport.use(new LocalStrategy(User.authenticate()));
// passport.use(User.createStrategy());
passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
      done(err, user);
  });
});

app.post("/signup", function (req, res) {
  User.register(
    { name:req.body.name,
      username:req.body.email },
    req.body.password,
    function (err, user) {
      if (err) {
        console.log(err);
      } else {
        res.send(user);
        passport.authenticate('local', function (err, user, info) {
          if (!err) {
          console.log("authenticated");
          }
        })(req, res)
      }
    })
})

i have been searching the whole web tring to find a solution, tried a so many solutions but nothing worked


问:
I got sinusoidal noise in evoked object in mne python
I have a eeg recording with sfreq of 2500 Hz, I tried to preprocess it with mne, as following:
(resampling, filtering, interpolating bad channels, ICA, setting eeg reference) but looking at evokes, there is a sinusoidal noise in it, which I don't see it when preprocessing with fieldtrip and even when I preprocessd it before by mne...
Can anyone help me with this?the final evoke for a stimulus seen in Cz
this is the true answer

```<code>raw_erp = mne.io.read_raw_brainvision(vhdr_fname=vhdr_fname_erp, preload=True)
sfreq = 250
raw_erp_ready = raw_erp.filter(l_freq=None, h_freq=sfreq/2)
raw_erp_resampled = raw_erp.resample(sfreq=sfreq)

l_freq = .1 # Hz
h_freq = 40 # Hz
raw_erp_filtered = raw_erp_resampled.filter(l_freq=l_freq, h_freq=h_freq)

bad_channels = ['AF8', 'Fz','PO7','PO8'] # bad channels by exploring signal traces
raw_erp_filtered.info['bads'].extend(bad_channels) # adding some bad channels after exploring signals
raw_rm_bd_ch = raw_erp_filtered.interpolate_bads(reset_bads=True, mode='accurate', verbose=None)

ica = mne.preprocessing.ICA(n_components=20, random_state=97, max_iter=800)
ica.fit(raw_rm_bd_ch)
ica.exclude = [0, 1] # which components should be removed after looking at the components
ica.apply(raw_rm_bd_ch)

raw_avg_ref = raw_rm_bd_ch.set_eeg_reference(ref_channels='average', projection=False)

events = mne.events_from_annotations(raw_avg_ref)
#events idx need to be resampled (in this case 2500 / 250 = 10)
for idx in range(len(events[0])):
    events[0][idx][0] = int(events[0][idx][0] / 10)

epochs = mne.Epochs(raw_avg_ref, events[0], event_id=events[1], tmin=-0.2, tmax=0.5,
                    preload=True)
epochs.apply_baseline(baseline=(None, 0))

</code>```

I tried before with mne, almost the same approach, but seems that I changed sth that I cant figure it out..any idea?
thanks in advance

Body:
I have a eeg recording with sfreq of 2500 Hz, I tried to preprocess it with mne, as following:
(resampling, filtering, interpolating bad channels, ICA, setting eeg reference) but looking at evokes, there is a sinusoidal noise in it, which I don't see it when preprocessing with fieldtrip and even when I preprocessd it before by mne...
Can anyone help me with this?the final evoke for a stimulus seen in Cz
this is the true answer

raw_erp = mne.io.read_raw_brainvision(vhdr_fname=vhdr_fname_erp, preload=True)
sfreq = 250
raw_erp_ready = raw_erp.filter(l_freq=None, h_freq=sfreq/2)
raw_erp_resampled = raw_erp.resample(sfreq=sfreq)

l_freq = .1 # Hz
h_freq = 40 # Hz
raw_erp_filtered = raw_erp_resampled.filter(l_freq=l_freq, h_freq=h_freq)

bad_channels = ['AF8', 'Fz','PO7','PO8'] # bad channels by exploring signal traces
raw_erp_filtered.info['bads'].extend(bad_channels) # adding some bad channels after exploring signals
raw_rm_bd_ch = raw_erp_filtered.interpolate_bads(reset_bads=True, mode='accurate', verbose=None)

ica = mne.preprocessing.ICA(n_components=20, random_state=97, max_iter=800)
ica.fit(raw_rm_bd_ch)
ica.exclude = [0, 1] # which components should be removed after looking at the components
ica.apply(raw_rm_bd_ch)

raw_avg_ref = raw_rm_bd_ch.set_eeg_reference(ref_channels='average', projection=False)

events = mne.events_from_annotations(raw_avg_ref)
#events idx need to be resampled (in this case 2500 / 250 = 10)
for idx in range(len(events[0])):
    events[0][idx][0] = int(events[0][idx][0] / 10)

epochs = mne.Epochs(raw_avg_ref, events[0], event_id=events[1], tmin=-0.2, tmax=0.5,
                    preload=True)
epochs.apply_baseline(baseline=(None, 0))

I tried before with mne, almost the same approach, but seems that I changed sth that I cant figure it out..any idea?
thanks in advance


问:
is this animation in flutter like boiler code or ok?
below is my sample code. the animation is exactly how I want it to be.

The question is whether it is too much with the controller or the rotation transition / boiler code.

are there other simpler solutions?

```<code>class LoadingScreen extends StatefulWidget {
  final String assetName = "assets/images/origin.png";

  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> with TickerProviderStateMixin {
  late AnimationController _controller;
  late AnimationController _controller2;
  late AnimationController _controller3;
  late AnimationController _controller4;
  late Animation<double> _animation;
  late Animation<double> _animation2;
  late Animation<double> _animation3;
  late Animation<double> _animation4;

  final Tween<double> turnsTween = Tween<double>(begin: 0, end: 1 / 4);

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this, duration: const Duration(seconds: 1));
    _animation = CurvedAnimation(parent: _controller, curve: Curves.bounceOut);

    _controller2 = AnimationController(vsync: this, duration: const Duration(seconds: 1));
    _animation2 = CurvedAnimation(parent: _controller2, curve: Curves.bounceOut);

    _controller3 = AnimationController(vsync: this, duration: const Duration(seconds: 1));
    _animation3 = CurvedAnimation(parent: _controller3, curve: Curves.bounceOut);

    _controller4 = AnimationController(vsync: this, duration: const Duration(seconds: 1));
    _animation4 = CurvedAnimation(parent: _controller4, curve: Curves.bounceOut);

    _controller.forward();
    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _controller2.forward();
      }
    });
    _controller2.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _controller3.forward();
      }
    });
    _controller3.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _controller4.forward();
      }
    });
    _controller4.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _controller.reset();
        _controller2.reset();
        _controller3.reset();
        _controller4.reset();
        _controller.forward();
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    _controller2.dispose();
    _controller3.dispose();
    _controller4.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: RotationTransition(
        turns: turnsTween.animate(_animation4),
        child: RotationTransition(
          turns: turnsTween.animate(_animation3),
          child: RotationTransition(
            turns: turnsTween.animate(_animation2),
            child: RotationTransition(
              turns: turnsTween.animate(_animation),
              child: Center(
                child: Image.asset(
                  widget.assetName,
                  width: 200,
                  height: 200,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
</code>```

It works for me, but I would like to avoid performance problems.
Simply asked because StackOverFlow would like to have boiler text: is it possible to simplify my code?

Body:
below is my sample code. the animation is exactly how I want it to be.

The question is whether it is too much with the controller or the rotation transition / boiler code.

are there other simpler solutions?

class LoadingScreen extends StatefulWidget {
  final String assetName = "assets/images/origin.png";

  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> with TickerProviderStateMixin {
  late AnimationController _controller;
  late AnimationController _controller2;
  late AnimationController _controller3;
  late AnimationController _controller4;
  late Animation<double> _animation;
  late Animation<double> _animation2;
  late Animation<double> _animation3;
  late Animation<double> _animation4;

  final Tween<double> turnsTween = Tween<double>(begin: 0, end: 1 / 4);

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this, duration: const Duration(seconds: 1));
    _animation = CurvedAnimation(parent: _controller, curve: Curves.bounceOut);

    _controller2 = AnimationController(vsync: this, duration: const Duration(seconds: 1));
    _animation2 = CurvedAnimation(parent: _controller2, curve: Curves.bounceOut);

    _controller3 = AnimationController(vsync: this, duration: const Duration(seconds: 1));
    _animation3 = CurvedAnimation(parent: _controller3, curve: Curves.bounceOut);

    _controller4 = AnimationController(vsync: this, duration: const Duration(seconds: 1));
    _animation4 = CurvedAnimation(parent: _controller4, curve: Curves.bounceOut);

    _controller.forward();
    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _controller2.forward();
      }
    });
    _controller2.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _controller3.forward();
      }
    });
    _controller3.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _controller4.forward();
      }
    });
    _controller4.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _controller.reset();
        _controller2.reset();
        _controller3.reset();
        _controller4.reset();
        _controller.forward();
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    _controller2.dispose();
    _controller3.dispose();
    _controller4.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: RotationTransition(
        turns: turnsTween.animate(_animation4),
        child: RotationTransition(
          turns: turnsTween.animate(_animation3),
          child: RotationTransition(
            turns: turnsTween.animate(_animation2),
            child: RotationTransition(
              turns: turnsTween.animate(_animation),
              child: Center(
                child: Image.asset(
                  widget.assetName,
                  width: 200,
                  height: 200,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

It works for me, but I would like to avoid performance problems.
Simply asked because StackOverFlow would like to have boiler text: is it possible to simplify my code?


问:
Do I have to set a type hint in my PHP class that has an interface?
Small question to typehinting. I have a ClassA that implements the interface IClass. IClass has a method action($parameter). In the interface I set the type of $parameter and the type of the return value. Here is an example of how I just implemented it.

Class

class ClassA implements IClassA{
    public function action($parameter)
    {
        return true;
    }
}
```
<p><strong>Interface</strong></p>
<pre class="lang-php prettyprint-override"><code>use Model;

interface IClassA {
    public function action(Model $parameter): bool
}
</code>```

Body:
Small question to typehinting. I have a ClassA that implements the interface IClass. IClass has a method action($parameter). In the interface I set the type of $parameter and the type of the return value. Here is an example of how I just implemented it.

Class

class ClassA implements IClassA{
    public function action($parameter)
    {
        return true;
    }
}

Interface

use Model;

interface IClassA {
    public function action(Model $parameter): bool
}


问:
Is it possible to convert a GraphQL Schema to SQL create table queries?
My Free Heroku DBs that connected with Hausra was deleted, I am trying to recover it.

Before that,  I am curious whether it is possible to generate SQL Create table queries from an existing GraphQL schema file ... That is, is it possible to create the database with tables with relations (datas not needed) from the GraphQL schema file ?


问:
Filter and remove Task Items from shared Outlook Inbox folder
In a shared Outlook account, I receive mails that will be transformed into an Outlook-Task and sent to assignee. An updated copy of the task is kept in shared account task list. (This part is working)
If Assignee rejects, accepts or changes status on this task, I receive notification about that in the Inbox folder. In Outlook I need to open and close this task update, for it to disappear from the folder.

Problem: How do I automate this open close Task Item process. Or even better: Set parameter to to Task Item so it does it?

```<code>Sub FilterTaskItemsFromSharedInbox()

Dim db As DAO.Database
Set db = CurrentDb

Dim rs As DAO.Recordset
Set rs = db.OpenRecordset("Main_tbl")

Dim rsA As DAO.Recordset
Dim fld  As DAO.Field
Set fld = rs("FileData")

Dim ol As Outlook.Application
Set ol = New Outlook.Application

Dim i As Object
Dim MI As Outlook.MailItem

Dim ns As Outlook.NameSpace
Set ns = ol.GetNamespace("MAPI")

Dim st As Outlook.Store
Set st = ns.Stores("Shared Account")

Dim fol As Outlook.Folder
'Set fol = st.GetDefaultFolder(olFolderInbox)
Set fol = ns.Folders("Shared Account Name").Folders("Inbox") 'Shared Outlook account

'Filter Tasks from Mails (I.Class 50 = olTaskRequestUpdate - I.Class 43 = olMail - I.Class 53 = olMeetingRequest
For Each i In fol.Items

Select Case i.Class
Case 43 'olMailItem
'VBA code to extract object information (EmailSender/Subject/Body/Attachments) and add to new record in Access DB (Done and Working)
Case 50 'olTaskRequestUpdate
'Need VBA code to Open/Close Task Item or set parameter, for it to disappear from Inbox Folder

Case 53 'olMeetingRequest
Debug.Print "This is a Meeting Request" '(Unlikely to receive meeting request in account, but should create some VBA to handle it
End Select

Next

End Sub
```
```

Body:
In a shared Outlook account, I receive mails that will be transformed into an Outlook-Task and sent to assignee. An updated copy of the task is kept in shared account task list. (This part is working)
If Assignee rejects, accepts or changes status on this task, I receive notification about that in the Inbox folder. In Outlook I need to open and close this task update, for it to disappear from the folder.

Problem: How do I automate this open close Task Item process. Or even better: Set parameter to to Task Item so it does it?

Sub FilterTaskItemsFromSharedInbox()

Dim db As DAO.Database
Set db = CurrentDb

Dim rs As DAO.Recordset
Set rs = db.OpenRecordset("Main_tbl")

Dim rsA As DAO.Recordset
Dim fld  As DAO.Field
Set fld = rs("FileData")

Dim ol As Outlook.Application
Set ol = New Outlook.Application

Dim i As Object
Dim MI As Outlook.MailItem

Dim ns As Outlook.NameSpace
Set ns = ol.GetNamespace("MAPI")

Dim st As Outlook.Store
Set st = ns.Stores("Shared Account")

Dim fol As Outlook.Folder
'Set fol = st.GetDefaultFolder(olFolderInbox)
Set fol = ns.Folders("Shared Account Name").Folders("Inbox") 'Shared Outlook account

'Filter Tasks from Mails (I.Class 50 = olTaskRequestUpdate - I.Class 43 = olMail - I.Class 53 = olMeetingRequest
For Each i In fol.Items

Select Case i.Class
Case 43 'olMailItem
'VBA code to extract object information (EmailSender/Subject/Body/Attachments) and add to new record in Access DB (Done and Working)
Case 50 'olTaskRequestUpdate
'Need VBA code to Open/Close Task Item or set parameter, for it to disappear from Inbox Folder

Case 53 'olMeetingRequest
Debug.Print "This is a Meeting Request" '(Unlikely to receive meeting request in account, but should create some VBA to handle it
End Select

Next

End Sub
```


问:
React native google translate ap i(@vitalets/google-translate-api)
```<code>const test = async () => {
try {
  const { text } = await translate("dynamic text", {
    to: "mr",
  }
  );
} catch (error) {
  console.error(error);
}
</code>```

}

[TypeError: Error.captureStackTrace is not a function. (In 'Error.captureStackTrace(err, ClientError)', 'Error.captureStackTrace' is undefined)]
I don't know why i getting this error all time after calling the function.

Body:
const test = async () => {
try {
  const { text } = await translate("dynamic text", {
    to: "mr",
  }
  );
} catch (error) {
  console.error(error);
}

}

[TypeError: Error.captureStackTrace is not a function. (In 'Error.captureStackTrace(err, ClientError)', 'Error.captureStackTrace' is undefined)]
I don't know why i getting this error all time after calling the function.


问:
ARKit triggers using Reality Composer
Running iOS 16

Created scene with Reality Composer
Added some usdz
Added some behaviors
Added a custom trigger

All works well in Reality Composer, but poorly on a real device

Tried to create a notify action

And I have managed to figure out the syntax to setup an action against it!

```<code>chessBoard.actions.customNotification.onAction = { entity in
                    print("custom action")
                    let trans = Transform(translation:SIMD3(x: 0, y: 0, z: +0.1))
                    entity?.move(to: trans, relativeTo: entity, duration: 2)
}
</code>```

But for life of me I cannot figure out the syntax to notify this! These don't work, red syntax!! doesn't exist..Apple Docx say it is this...

https://developer.apple.com/documentation/realitykit/creating-a-trigger

```<code>let chess = try! ChessSetWithBoardSquare.loadBoard()
        chess.notifications.allNotifications[0].post. //No
        chess.parent.notifications.allNotifications[0].post //No
        arView.scene.anchors.notifications.customNotification.post() //No
        arView.scene.notifications.customNotification.post() //No

</code>```

Nor can I find a reference to the correct syntax at this point in time...

Title: ARKit triggers using Reality Composer

Body:
Running iOS 16

Created scene with Reality Composer
Added some usdz
Added some behaviors
Added a custom trigger

All works well in Reality Composer, but poorly on a real device

Tried to create a notify action

And I have managed to figure out the syntax to setup an action against it!

chessBoard.actions.customNotification.onAction = { entity in
                    print("custom action")
                    let trans = Transform(translation:SIMD3(x: 0, y: 0, z: +0.1))
                    entity?.move(to: trans, relativeTo: entity, duration: 2)
}

But for life of me I cannot figure out the syntax to notify this! These don't work, red syntax!! doesn't exist..Apple Docx say it is this...

https://developer.apple.com/documentation/realitykit/creating-a-trigger

let chess = try! ChessSetWithBoardSquare.loadBoard()
        chess.notifications.allNotifications[0].post. //No
        chess.parent.notifications.allNotifications[0].post //No
        arView.scene.anchors.notifications.customNotification.post() //No
        arView.scene.notifications.customNotification.post() //No

Nor can I find a reference to the correct syntax at this point in time...


问:
Is there any way to register a table which is created without using Django Model?
How to register the following table in apps.py or how to show this Table in admit panel?</p>
```<code>from django.db import connection
cursor = connection.cursor()
cursor.execute("CREATE TABLE appName_{} LIKE appName_table".format(str(request.user)+"_table"))
</code>```

Body:
How to register the following table in apps.py or how to show this Table in admit panel?

from django.db import connection
cursor = connection.cursor()
cursor.execute("CREATE TABLE appName_{} LIKE appName_table".format(str(request.user)+"_table"))


问:
I don’t get information gain equation in XGBoost
I’m currently studying XGBoost, and I learned that information gain in XGBoost is computed like this:

XGBoost information gain

What I’m curious is that, previously about information gain, I learned that it is computed (entropy of parent node - sum of entropy of child nodes), which is the opposite of XGBoost since XGBoost IG is computed as (score of left node + score of right node - score of parent node). I don’t understand why.


问:
Getting Uncaught (in Promise) syntax error when use the useEffect hook with fetch to get data from backend server
I am trying to make a simple application for getting data from the backend with express and react.

For getting info from the server I am using fetch but I encountered

Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE
"... is not valid JSON

when I wrote this simple code. Here is react code

```<code>import React, {useState, useEffect} from 'react'

export default function App(){

    const [resorceType, setResourceType] = useState("posts")

    console.log("Render")

    useEffect(() =>{
      fetch("http://localhost:5000")
      .then(response => response.json())
      .then(response => setResourceType(response))

    }, [resorceType])

    return(
        <>
            <div>
                <button onClick={() => setResourceType("posts")}>posts</button>
                <button onClick={() => setResourceType("users")}>users</button>
                <button onClick={() => setResourceType("comments")}>comments</button>
            </div>

            <h1>{resorceType}</h1>
        </>
    )

}
</code>```

Here is express code

```<code>app.get("/", (req,res) => {
    res.get({"name" : "john"})
})

app.listen(port, err => {

    if(err){
        return console.log("Error Happened\n", err)
    }

    console.log(`${port} is listening`)
})
</code>```

My server and react code is running correctly. But I cannot fetch an object or string from the server. And the error message indicates that I have a problem with the index.js. Shouldn't we change the index.js when writing react application? If so which change can I do Can someone explain Why I am getting this error?

Body:
I am trying to make a simple application for getting data from the backend with express and react.

For getting info from the server I am using fetch but I encountered

Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE
"... is not valid JSON

when I wrote this simple code. Here is react code

import React, {useState, useEffect} from 'react'

export default function App(){

    const [resorceType, setResourceType] = useState("posts")

    console.log("Render")

    useEffect(() =>{
      fetch("http://localhost:5000")
      .then(response => response.json())
      .then(response => setResourceType(response))

    }, [resorceType])

    return(
        <>

                <button onClick={() => setResourceType("posts")}>posts</button>
                <button onClick={() => setResourceType("users")}>users</button>
                <button onClick={() => setResourceType("comments")}>comments</button>

{resorceType}

        </>
    )

}

Here is express code

app.get("/", (req,res) => {
    res.get({"name" : "john"})
})

app.listen(port, err => {

    if(err){
        return console.log("Error Happened\n", err)
    }

    console.log(`${port} is listening`)
})

My server and react code is running correctly. But I cannot fetch an object or string from the server. And the error message indicates that I have a problem with the index.js. Shouldn't we change the index.js when writing react application? If so which change can I do Can someone explain Why I am getting this error?


问:
After configuring Spring Web security login gives me Invalid username and password error
After configuring Spring's Web Security my register works expected but when I try to login my login page says that my username or password is invalid a I am using in memory mysql database and I checked database values after register if I am typing in correct (username, password). When i used hardcoded values in CustomUserDetailsService login worked like expected

My SecurityConfig :

```<code>package ru.connor.shopping_app.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import ru.connor.shopping_app.service.CustomUserDetailsService;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SpringSecurity extends WebSecurityConfigurerAdapter {
    private final CustomUserDetailsService customUserDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/login", "/register", "/error", "/shop/**", "/image/**").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login")
                .loginProcessingUrl("/process_login")
                .defaultSuccessUrl("/")
                .usernameParameter("email")
                .passwordParameter("password")
                .failureUrl("/login?error")
                .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/login"); // Logout
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**", "/static/**", "/images/**", "/productImages/**", "/css/**", "/js/**");
    }

}

</code>```

CustomUserDetailsService :

```<code>package ru.connor.shopping_app.service;

import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import ru.connor.shopping_app.model.User;
import ru.connor.shopping_app.repository.UserRepository;

import java.util.Optional;

@RequiredArgsConstructor
@Service
public class CustomUserDetailsService implements UserDetailsService {
    private final UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Optional<User> user = userRepository.findAllByEmail(s);
        if (user.isEmpty()) throw new UsernameNotFoundException("User not found");

        return new User(user.get());
    }
}
</code>```

UserService:

```<code>package ru.connor.shopping_app.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import ru.connor.shopping_app.model.Role;
import ru.connor.shopping_app.model.User;
import ru.connor.shopping_app.repository.UserRepository;

import java.security.Principal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserService {
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    public boolean createUser(User user) {
        String email = user.getEmail();
        if (userRepository.findByEmail(email) != null) return false;
        user.setActive(true);
        user.setFirstName(user.getFirstName());
        user.setLastName(user.getLastName());
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.getRoles().add(Role.ROLE_USER);
        log.info("Saving new User with email: {}", email);
        userRepository.save(user);
        return true;
    }

    public List<User> list() {
        return userRepository.findAll();
    }

    public void banUser(Long id) {
        User user = userRepository.findById(Math.toIntExact(id)).orElse(null);
        if (user != null) {
            if (user.isActive()) {
                user.setActive(false);
                log.info("Ban user with id = {}; email: {}", user.getId(), user.getEmail());
            } else {
                user.setActive(true);
                log.info("Unban user with id = {}; email: {}", user.getId(), user.getEmail());
            }
        }
        userRepository.save(user);
    }

    public void changeUserRoles(User user, Map<String, String> form) {
        Set<String> roles = Arrays.stream(Role.values())
                .map(Role::name)
                .collect(Collectors.toSet());
        user.getRoles().clear();
        for (String key : form.keySet()) {
            if (roles.contains(key)) {
                user.getRoles().add(Role.valueOf(key));
            }
        }
        userRepository.save(user);
    }

    public User getUserByPrincipal(Principal principal) {
        if (principal == null) return new User();
        return userRepository.findByEmail(principal.getName());
    }
}
</code>```

I do not understand what the problem is

Body:
After configuring Spring's Web Security my register works expected but when I try to login my login page says that my username or password is invalid a I am using in memory mysql database and I checked database values after register if I am typing in correct (username, password). When i used hardcoded values in CustomUserDetailsService login worked like expected

My SecurityConfig :

package ru.connor.shopping_app.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import ru.connor.shopping_app.service.CustomUserDetailsService;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SpringSecurity extends WebSecurityConfigurerAdapter {
    private final CustomUserDetailsService customUserDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/login", "/register", "/error", "/shop/**", "/image/**").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login")
                .loginProcessingUrl("/process_login")
                .defaultSuccessUrl("/")
                .usernameParameter("email")
                .passwordParameter("password")
                .failureUrl("/login?error")
                .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/login"); // Logout
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**", "/static/**", "/images/**", "/productImages/**", "/css/**", "/js/**");
    }

}

CustomUserDetailsService :

package ru.connor.shopping_app.service;

import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import ru.connor.shopping_app.model.User;
import ru.connor.shopping_app.repository.UserRepository;

import java.util.Optional;

@RequiredArgsConstructor
@Service
public class CustomUserDetailsService implements UserDetailsService {
    private final UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Optional<User> user = userRepository.findAllByEmail(s);
        if (user.isEmpty()) throw new UsernameNotFoundException("User not found");

        return new User(user.get());
    }
}

UserService:

package ru.connor.shopping_app.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import ru.connor.shopping_app.model.Role;
import ru.connor.shopping_app.model.User;
import ru.connor.shopping_app.repository.UserRepository;

import java.security.Principal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserService {
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    public boolean createUser(User user) {
        String email = user.getEmail();
        if (userRepository.findByEmail(email) != null) return false;
        user.setActive(true);
        user.setFirstName(user.getFirstName());
        user.setLastName(user.getLastName());
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.getRoles().add(Role.ROLE_USER);
        log.info("Saving new User with email: {}", email);
        userRepository.save(user);
        return true;
    }

    public List<User> list() {
        return userRepository.findAll();
    }

    public void banUser(Long id) {
        User user = userRepository.findById(Math.toIntExact(id)).orElse(null);
        if (user != null) {
            if (user.isActive()) {
                user.setActive(false);
                log.info("Ban user with id = {}; email: {}", user.getId(), user.getEmail());
            } else {
                user.setActive(true);
                log.info("Unban user with id = {}; email: {}", user.getId(), user.getEmail());
            }
        }
        userRepository.save(user);
    }

    public void changeUserRoles(User user, Map<String, String> form) {
        Set<String> roles = Arrays.stream(Role.values())
                .map(Role::name)
                .collect(Collectors.toSet());
        user.getRoles().clear();
        for (String key : form.keySet()) {
            if (roles.contains(key)) {
                user.getRoles().add(Role.valueOf(key));
            }
        }
        userRepository.save(user);
    }

    public User getUserByPrincipal(Principal principal) {
        if (principal == null) return new User();
        return userRepository.findByEmail(principal.getName());
    }
}

I do not understand what the problem is


问:
CoreData how to fetch all child elements using a SwiftUI property wrapper
I am building a File Manager app.

In this App the user can optionally select a Folder. And I am building now a SwiftUI view to show the files of the selected folder, or ALL files if there are no selection.

I do have the selected folder in a AppState class:

```<code>class AppState: ObservableObject {
    @Published var selectedFolder: Folder?
}
</code>```

And I am trying to build my FileListView using a predicate to filter the Files with that selected Folder:

```<code>struct FileListView: View {

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \File.order, ascending: true)], predicate: NSPredicate(format: "folder = %@", appState.selectedFolder), animation: .default)
    var fileList: FetchedResults<File>

    @EnvironmentObject
    var appState: AppState

    var body: some View {
        List {
            ForEach(fileList) {
                file in
                Text(file.name)
            }
        }
    }
}
</code>```

However that Predicate does not work as expected and I get the following compilation error:

Cannot use instance member 'appState' within property initializer; property initializers run before 'self' is available

Body:
I am building a File Manager app.

In this App the user can optionally select a Folder. And I am building now a SwiftUI view to show the files of the selected folder, or ALL files if there are no selection.

I do have the selected folder in a AppState class:

class AppState: ObservableObject {
    @Published var selectedFolder: Folder?
}

And I am trying to build my FileListView using a predicate to filter the Files with that selected Folder:

struct FileListView: View {

    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \File.order, ascending: true)], predicate: NSPredicate(format: "folder = %@", appState.selectedFolder), animation: .default)
    var fileList: FetchedResults<File>

    @EnvironmentObject
    var appState: AppState

    var body: some View {
        List {
            ForEach(fileList) {
                file in
                Text(file.name)
            }
        }
    }
}

However that Predicate does not work as expected and I get the following compilation error:

Cannot use instance member 'appState' within property initializer; property initializers run before 'self' is available


问:
Spring boot ressource server with azure ad
I am running into an issue and asking for any help.
I got a react app running and there I log in with the oidc azure ad. I am getting all information I wanted as well as a jwt.

Now I want my frontend to call routes on my spring boot backend. That's why I decided that my backend is a resource server. And here I want to validate the provided JWT.
As soon as I do a request I got the following error:

Failed to lazily resolve the supplied JwtDecoder instance

Unable to resolve the Configuration with the provided Issuer of
"https://login.microsoftonline.com/3d1f9219-b455-xxxx-xxxx-xxxxxxxxxxxx/wsfed"

I think that my issuer-uri is wrong. But I cannot find a solution for this.
Here is my filterChain method:

```<code>@Bean
open fun filterChain(http: HttpSecurity) : SecurityFilterChain{
    http
        .authorizeHttpRequests{
            authorize -> authorize.antMatchers("/**").hasAnyAuthority("SCOPE_user.read")
            .anyRequest().authenticated()
        }
        .oauth2ResourceServer{
            oauth2 -> oauth2.jwt(Customizer.withDefaults())
        }
    return http.build()
}
</code>```

and thats my application.yml

```<code>spring:
    security:
        oauth2:
          resourceserver:
            jwt:
              issuer-uri: https://login.microsoftonline.com/3d1f9219-b455-xxxx-xxxx-xxxxxxxxxxxx/wsfed
</code>```

I've already tried other issuer-uris like
https://login.microsoftonline.com/common/discovery/keys
https://login.microsoftonline.com/{tenant_id}/discovery/keys?appid={client_id}

but without success.

I know this is kotlin but I am fine with java too.

EDIT:

I've changed the issuer-uri to:
https://login.microsoftonline.com/{tenant-id}/v2.0

But now I am facing 401 Unauthorized http error

Body:
I am running into an issue and asking for any help.
I got a react app running and there I log in with the oidc azure ad. I am getting all information I wanted as well as a jwt.

Now I want my frontend to call routes on my spring boot backend. That's why I decided that my backend is a resource server. And here I want to validate the provided JWT.
As soon as I do a request I got the following error:

Failed to lazily resolve the supplied JwtDecoder instance

Unable to resolve the Configuration with the provided Issuer of
"https://login.microsoftonline.com/3d1f9219-b455-xxxx-xxxx-xxxxxxxxxxxx/wsfed"

I think that my issuer-uri is wrong. But I cannot find a solution for this.
Here is my filterChain method:

@Bean
open fun filterChain(http: HttpSecurity) : SecurityFilterChain{
    http
        .authorizeHttpRequests{
            authorize -> authorize.antMatchers("/**").hasAnyAuthority("SCOPE_user.read")
            .anyRequest().authenticated()
        }
        .oauth2ResourceServer{
            oauth2 -> oauth2.jwt(Customizer.withDefaults())
        }
    return http.build()
}

and thats my application.yml

spring:
    security:
        oauth2:
          resourceserver:
            jwt:
              issuer-uri: https://login.microsoftonline.com/3d1f9219-b455-xxxx-xxxx-xxxxxxxxxxxx/wsfed

I've already tried other issuer-uris like
https://login.microsoftonline.com/common/discovery/keys
https://login.microsoftonline.com/{tenant_id}/discovery/keys?appid={client_id}

but without success.

I know this is kotlin but I am fine with java too.

EDIT:

I've changed the issuer-uri to:
https://login.microsoftonline.com/{tenant-id}/v2.0

But now I am facing 401 Unauthorized http error


问:
Turn monitor on and off
I am trying to turn a desktop monitor connected to a Windows 10 PC on and off,
Any ideas how this could be done by using Delphi?

The following used to work for older Windows versions but it no longer works for Windows 10
"SendMessage(Application.Handle, WM_SYSCOMMAND, SC_MONITORPOWER, - 1);"

Thanks!

I did not try anything yet because i need some information of how it can be done.

Title: Turn monitor on and off


问:
Webscraping with proxies
```<code>from selenium import webdriver
import time
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup
import pandas as pd
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import csv
import requests
from csv import writer
from selenium.webdriver.common.proxy import Proxy, ProxyType

with open("proxies.csv",encoding='utf-8') as f:
    prox=[line.strip() for line in f]
    for i in prox:
        proxy_ip_port =i
        proxy = Proxy()
        proxy.proxy_type = ProxyType.MANUAL
        proxy.http_proxy = proxy_ip_port
        proxy.ssl_proxy = proxy_ip_port
        capabilities = webdriver.DesiredCapabilities.CHROME
        proxy.add_to_capabilities(capabilities)

    # replace 'your_absolute_path' with your chrome binary absolute path
        driver = webdriver.Chrome('C:\Program Files (x86)\chromedriver.exe', desired_capabilities=capabilities)
        with open("data.csv",encoding='utf-8') as file:
            start_urls=[line.strip() for line in file]

            for u in start_urls:
                driver.get(u)
                try:
                    title=driver.find_element(By.CSS_SELECTOR,'div.mp0t_0a  h1').text
                except:
                    pass

                print(title)

            time.sleep(8)

            driver.quit()
</code>```

I want that they try all the proxies but they will check only first proxy if the first proxy will not work ...they give me error ...I want that if first proxy do not work they automatically move to second proxy is that possible kindly recommend if it possible

Title: Webscraping with proxies

Body:
from selenium import webdriver
import time
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup
import pandas as pd
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import csv
import requests
from csv import writer
from selenium.webdriver.common.proxy import Proxy, ProxyType

with open("proxies.csv",encoding='utf-8') as f:
    prox=[line.strip() for line in f]
    for i in prox:
        proxy_ip_port =i
        proxy = Proxy()
        proxy.proxy_type = ProxyType.MANUAL
        proxy.http_proxy = proxy_ip_port
        proxy.ssl_proxy = proxy_ip_port
        capabilities = webdriver.DesiredCapabilities.CHROME
        proxy.add_to_capabilities(capabilities)

    # replace 'your_absolute_path' with your chrome binary absolute path
        driver = webdriver.Chrome('C:\Program Files (x86)\chromedriver.exe', desired_capabilities=capabilities)
        with open("data.csv",encoding='utf-8') as file:
            start_urls=[line.strip() for line in file]

            for u in start_urls:
                driver.get(u)
                try:
                    title=driver.find_element(By.CSS_SELECTOR,'div.mp0t_0a  h1').text
                except:
                    pass

                print(title)

            time.sleep(8)

            driver.quit()

I want that they try all the proxies but they will check only first proxy if the first proxy will not work ...they give me error ...I want that if first proxy do not work they automatically move to second proxy is that possible kindly recommend if it possible


问:
Validate google signin accesstoken with Django social backend
I want to validate the google access token that i get from signing to google with my django social auth

```<code>   token = await user!.authentication.then((value) {
      return value.accessToken;
    });
    print("lolol" + token);
    try {
      var params = {
        "auth_token": token,
      };

      final response = _dioClient.dio.post(
        "http://192.168.1.12:8000/social_auth/google/",
        options: Options(headers: {
          HttpHeaders.contentTypeHeader: "application/json",
        }),
        data: jsonEncode(params),
      );
      print(response);
    } catch (e) {
      print(e);
    }
</code>```

With django google package

```<code>
class Google:
    """Google class to fetch the user info and return it"""

    @staticmethod
    def validate(auth_token):
        """
        validate method Queries the Google oAUTH2 api to fetch the user info
        """
        try:
            idinfo = id_token.verify_oauth2_token(
                auth_token, requests.Request())

            if 'accounts.google.com' in idinfo['iss']:
                return idinfo

        except:
            return "The token is either invalid or has expired"
</code>```

i want Validate google signin accesstoken with Django social backend

Body:
I want to validate the google access token that i get from signing to google with my django social auth

   token = await user!.authentication.then((value) {
      return value.accessToken;
    });
    print("lolol" + token);
    try {
      var params = {
        "auth_token": token,
      };

      final response = _dioClient.dio.post(
        "http://192.168.1.12:8000/social_auth/google/",
        options: Options(headers: {
          HttpHeaders.contentTypeHeader: "application/json",
        }),
        data: jsonEncode(params),
      );
      print(response);
    } catch (e) {
      print(e);
    }

With django google package

class Google:
    """Google class to fetch the user info and return it"""

    @staticmethod
    def validate(auth_token):
        """
        validate method Queries the Google oAUTH2 api to fetch the user info
        """
        try:
            idinfo = id_token.verify_oauth2_token(
                auth_token, requests.Request())

            if 'accounts.google.com' in idinfo['iss']:
                return idinfo

        except:
            return "The token is either invalid or has expired"

i want Validate google signin accesstoken with Django social backend


问:
Error: 'undefined reference to '_gmpz_set_str' when using gmp library in devC++

```<code>#include <stdio.h>
#include <gmp.h>

int main(void)
{

    mpz_t x;
    mpz_init(x);
    mpz_set_str(x, "12345", 10);
    mpz_mul_ui(x, x, 2);
    gmp_printf("%Zd\n", x);
    mpz_clear(x);
    return 0;
}
</code>```

I have already set up gmp and linked library libgmp.a and libgmpxx.a in Linker project of devC++. But i still get error undefined reference to '_gmpz_set_str'.
Please help me solve this problem.

Body:
#include <stdio.h>
#include <gmp.h>

int main(void)
{

    mpz_t x;
    mpz_init(x);
    mpz_set_str(x, "12345", 10);
    mpz_mul_ui(x, x, 2);
    gmp_printf("%Zd\n", x);
    mpz_clear(x);
    return 0;
}

I have already set up gmp and linked library libgmp.a and libgmpxx.a in Linker project of devC++. But i still get error undefined reference to '_gmpz_set_str'.
Please help me solve this problem.


问:
Decoupling my components from the UI system
So, my goal is to have my React components not coupled to the UI system's elements. I want to be able to "quickly" move from, let's say, Mantine to MUI.

Here's what I could achieve so far.

tsconfig.json:

{
  "compilerOptions": {
    ...
    "baseUrl": "./src",
    "paths": {
      ...
      "@ui/*": ["ui/*"]
    }
  }
}
```
<p>Related files:</p>
```ui
├── autocomplete.ts
├── button.ts
├── index.ts
├── provider.ts
├── icons
│   ├── icon.ts
│   ├── index.ts
│   └── tabler
│       └── copy.tsx
└── system
   ├── index.ts
   └── mantine
       ├── autocomplete.tsx
       ├── button.tsx
       ├── index.ts
       └── provider.tsx
```
<p>The ones in the <code>ui</code> root directory will only describe an interface, like so:
<code>ui/button.ts</code>:</p>
<pre class="lang-js prettyprint-override"><code>export interface ButtonProps {
  text: string;
  onClick: () => void;
  rightIcon?: React.ReactElement;
}
</code>```

The ones in the ui/system/[mantine|mui|...] will be responsible to render the UI component, implementing the respective interface. When necessary I'd tweak the parameters in order to compy to the UI system's component props. Here's an example:

import { Button } from '@mantine/core';
import { ButtonProps } from '@ui/button';

const MantineButton: React.FC<ButtonProps> = (props: ButtonProps) => {
  const { text, onClick, rightIcon } = props;

  return (
    <Button onClick={onClick} rightIcon={rightIcon}>
      {text}
    </Button>
  );
};

export default MantineButton;
```
<p>All the implemented components are exported in the respective UI system folder <code>index.ts</code>, where I rename then to a common simple name:</p>
<pre class="lang-js prettyprint-override"><code>export { default as UiSystemProvider } from './provider';
export { default as Autocomplete } from './autocomplete';
export { default as Button } from './button';
</code>```

I then choose whichever UI system I want to use by re-exporting everything that is being exported in the UI system's directory:

export * from './mantine';
//export * from './mui';
//export * from './bootstrap';
```
<p>Finally, I can have my client components to import an UI component from <code>@ui/system</code> and this would hopefully reach the correct UI component from the UI system that is currently being used by the project, like so:</p>
<pre class="lang-js prettyprint-override"><code>import { Autocomplete, Button } from '@ui/system';
</code>```

So, this kind of works, but my question is: what would be a more Reactish way of achieving this? I am coming back to React after a while away...

I don't plan to have 2+ UI systems in the project when it goes live, I just want to be able to quickly move from one to another if I decided to, so this was the way I've found to reduce the coupling.

I'll appreciate any tips you can give me.

Thank you

Body:
So, my goal is to have my React components not coupled to the UI system's elements. I want to be able to "quickly" move from, let's say, Mantine to MUI.

Here's what I could achieve so far.

tsconfig.json:

{
  "compilerOptions": {
    ...
    "baseUrl": "./src",
    "paths": {
      ...
      "@ui/*": ["ui/*"]
    }
  }
}

Related files:

ui
├── autocomplete.ts
├── button.ts
├── index.ts
├── provider.ts
├── icons
│   ├── icon.ts
│   ├── index.ts
│   └── tabler
│       └── copy.tsx
└── system
   ├── index.ts
   └── mantine
       ├── autocomplete.tsx
       ├── button.tsx
       ├── index.ts
       └── provider.tsx

The ones in the ui root directory will only describe an interface, like so:
ui/button.ts:

export interface ButtonProps {
  text: string;
  onClick: () => void;
  rightIcon?: React.ReactElement;
}

The ones in the ui/system/[mantine|mui|...] will be responsible to render the UI component, implementing the respective interface. When necessary I'd tweak the parameters in order to compy to the UI system's component props. Here's an example:

import { Button } from '@mantine/core';
import { ButtonProps } from '@ui/button';

const MantineButton: React.FC<ButtonProps> = (props: ButtonProps) => {
  const { text, onClick, rightIcon } = props;

  return (
    <Button onClick={onClick} rightIcon={rightIcon}>
      {text}
    </Button>
  );
};

export default MantineButton;

All the implemented components are exported in the respective UI system folder index.ts, where I rename then to a common simple name:

export { default as UiSystemProvider } from './provider';
export { default as Autocomplete } from './autocomplete';
export { default as Button } from './button';

I then choose whichever UI system I want to use by re-exporting everything that is being exported in the UI system's directory:

export * from './mantine';
//export * from './mui';
//export * from './bootstrap';

Finally, I can have my client components to import an UI component from @ui/system and this would hopefully reach the correct UI component from the UI system that is currently being used by the project, like so:

import { Autocomplete, Button } from '@ui/system';

So, this kind of works, but my question is: what would be a more Reactish way of achieving this? I am coming back to React after a while away...

I don't plan to have 2+ UI systems in the project when it goes live, I just want to be able to quickly move from one to another if I decided to, so this was the way I've found to reduce the coupling.

I'll appreciate any tips you can give me.

Thank you


问:
Is it possible to define Yarn 3 flags as defaults?
I've added yarn-plugin-outdated to my project. There are some CLI flags supported such as --url, so I can run yarn outdated --url and all outdated packages will be listed with URLs.

Is there any way to set this flag as default, so I don't need to type full command every time?


问:
Microsoft Identity Platform url throws not found exception
I am trying to get a Blazor Server project running using the Microsoft Identity Platform.  I run through all of the steps, and then run the project, and get this exception:

```<code>OException: IDX20807: Unable to retrieve document from: 'https://stangrentals.b2clogin.com/StangRentals.onmicrosoft.com/b2c_1_susi/v2.0/.well-known/openid-configuration'. HttpResponseMessage: 'StatusCode: 404, ReasonPhrase: 'Not Found'
</code>```

Obviously, something is incorrect about the URL, but it is unclear to me what the issue is.

I have posted the full reproduce issues details here, but I am basically accepting all of the defaults and then trying to run the project to no avail.

Body:
I am trying to get a Blazor Server project running using the Microsoft Identity Platform.  I run through all of the steps, and then run the project, and get this exception:

OException: IDX20807: Unable to retrieve document from: 'https://stangrentals.b2clogin.com/StangRentals.onmicrosoft.com/b2c_1_susi/v2.0/.well-known/openid-configuration'. HttpResponseMessage: 'StatusCode: 404, ReasonPhrase: 'Not Found'

Obviously, something is incorrect about the URL, but it is unclear to me what the issue is.

I have posted the full reproduce issues details here, but I am basically accepting all of the defaults and then trying to run the project to no avail.


问:
How to plot polygons in shapefile with z coordinate in 3D using rayshader
I have a .shp file with polygons having z value on every coordinate.

I want to represent this shp file in 3d format where I could see the height applied to each polygon in 3D. There is a tool Arcscene which does the same thing

but I want to achieve same functionality with R. I was reading about the rayshader library but I don't seem to find the correct solution for this use case.

What I tried is this

```<code>library(sf)
library(ggplot2)
library(rayshader)
nc <- st_read("shp/allpolygons.shp")
#plot(st_zm(nc), max.plot = 1)
gg_usa = ggplot(st_zm(nc)) + geom_sf()
plot_gg(gg_usa,multicore = TRUE,width=5,height=5,
        scale=250,windowsize=c(1400,866),zoom = 0.55, phi = 30)
render_polygons()
</code>```

which gives me output as this

which is not what I am looking for. What is the correct way to do this with rayshader or any other library?

Body:
I have a .shp file with polygons having z value on every coordinate.

I want to represent this shp file in 3d format where I could see the height applied to each polygon in 3D. There is a tool Arcscene which does the same thing

but I want to achieve same functionality with R. I was reading about the rayshader library but I don't seem to find the correct solution for this use case.

What I tried is this

library(sf)
library(ggplot2)
library(rayshader)
nc <- st_read("shp/allpolygons.shp")
#plot(st_zm(nc), max.plot = 1)
gg_usa = ggplot(st_zm(nc)) + geom_sf()
plot_gg(gg_usa,multicore = TRUE,width=5,height=5,
        scale=250,windowsize=c(1400,866),zoom = 0.55, phi = 30)
render_polygons()

which gives me output as this

which is not what I am looking for. What is the correct way to do this with rayshader or any other library?


问:
useMemo Failed to parse source for import analysis because the content contains invalid JS syntax
I was trying to create a custom hook which returns a component its params to set the state. But when the component is exported it throws "[plugin:vite:import-analysis] Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.". what might be the issue? Is it vite that is causing it?
custom hook file consists:

```<code>import {  useMemo} from "react"

import React from "react";

export default () => {

    const Notice = useMemo(() => <div>this is a component from custom hook!</div>, []);
    return {
        Notice
    };
}
</code>```

app.jsx file imports it as :

```<code>import useNotification from './customHooks/useNotification
 const { Notice } = useNotification()
 return (
    <div className="App relative">
      <Notice />
     </div>)}
    </div>
  )
</code>```

what might be the workaround for this issue? Or I might have misunderstood sth?

also package.joson has the devedencies as:

```<code> "dependencies": {
    "@reduxjs/toolkit": "^1.9.1",
    "axios": "^1.2.1",
    "dotenv": "^16.0.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-icons": "^4.7.1",
    "react-redux": "^8.0.5",
    "react-scripts": "^5.0.1",
    "redux": "^4.2.0",
    "redux-saga": "^1.2.2"
  },
  "devDependencies": {
    "@types/react": "^18.0.26",
    "@types/react-dom": "^18.0.9",
    "@vitejs/plugin-react": "^3.0.0",
    "autoprefixer": "^10.4.13",
    "postcss": "^8.4.20",
    "tailwindcss": "^3.2.4",
    "vite": "^4.0.0"
  }```
```

Body:
I was trying to create a custom hook which returns a component its params to set the state. But when the component is exported it throws "[plugin:vite:import-analysis] Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.". what might be the issue? Is it vite that is causing it?
custom hook file consists:

import {  useMemo} from "react"

import React from "react";

export default () => {

    const Notice = useMemo(() =>
this is a component from custom hook!
, []);
    return {
        Notice
    };
}

app.jsx file imports it as :

import useNotification from './customHooks/useNotification
 const { Notice } = useNotification()
 return (

      <Notice />

)}

  )

what might be the workaround for this issue? Or I might have misunderstood sth?

also package.joson has the devedencies as:

 "dependencies": {
    "@reduxjs/toolkit": "^1.9.1",
    "axios": "^1.2.1",
    "dotenv": "^16.0.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-icons": "^4.7.1",
    "react-redux": "^8.0.5",
    "react-scripts": "^5.0.1",
    "redux": "^4.2.0",
    "redux-saga": "^1.2.2"
  },
  "devDependencies": {
    "@types/react": "^18.0.26",
    "@types/react-dom": "^18.0.9",
    "@vitejs/plugin-react": "^3.0.0",
    "autoprefixer": "^10.4.13",
    "postcss": "^8.4.20",
    "tailwindcss": "^3.2.4",
    "vite": "^4.0.0"
  }```


问:
BackdropFilter shows no blurring on WebViewX
Using the webviewx_plus package for rending a webpage.
BackdropFilter ImageFilter.blur() not showing blur on the WebView as desired according to the design, but shows blur to all other widgets (Container/Text/Image/etc)</p>
```<code>Stack(
 children: [
  //Container(
  // width: 200,
  // height: 200,
  // color: Colors.green,
  // child: Text('This container works fine),
  //),
  WebViewX(
   width: double.maxFinite,
   height: double.maxFinite,
   ignoreAllGestures: true,
   initialContent: '<h2> Hello, world! </h2>',
   initialSourceType: SourceType.url,
   onWebViewCreated: (controller) async {
    controller
     .loadContent('https://example.com');
    return webViewXController = controller;
   },
  ),
  BackdropFilter(
   filter: ImageFilter.blur(
    sigmaX: 20,
    sigmaY: 20,
   ),
   child: Container(
    width: 200,
    height: 200,
    color: Colors.pink,
    child: Text('Hello'),
   ),
  ),
 ]
)
</code>```

Body:
Using the webviewx_plus package for rending a webpage.
BackdropFilter ImageFilter.blur() not showing blur on the WebView as desired according to the design, but shows blur to all other widgets (Container/Text/Image/etc)

Stack(
 children: [
  //Container(
  // width: 200,
  // height: 200,
  // color: Colors.green,
  // child: Text('This container works fine),
  //),
  WebViewX(
   width: double.maxFinite,
   height: double.maxFinite,
   ignoreAllGestures: true,
   initialContent: '
 Hello, world!
',
   initialSourceType: SourceType.url,
   onWebViewCreated: (controller) async {
    controller
     .loadContent('https://example.com');
    return webViewXController = controller;
   },
  ),
  BackdropFilter(
   filter: ImageFilter.blur(
    sigmaX: 20,
    sigmaY: 20,
   ),
   child: Container(
    width: 200,
    height: 200,
    color: Colors.pink,
    child: Text('Hello'),
   ),
  ),
 ]
)