问:
How to make extension method for external lib interface using typescript?
Any ideas how to make this extension method? I am using exceljs lib, and I want to have .applyStyles() method that could be used for any cell object. See sample of the code.

```<code>import * as ExcelJS from 'exceljs';
import { Cell } from 'exceljs';

declare module 'exceljs' {
  interface Cell {
    applyStyles(style: string): void;
  }
}

Cell.prototype.applyStyles = function(style: string) {
  if (style === 'center') {
    this.alignment = { horizontal: 'center' };
  }
};
</code>```
```<code>import './exceljs-extensions';
import * as ExcelJS from 'exceljs';
async() => {
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet('Sheet1');

  const cell = worksheet.getCell('A1');
  cell.value = 'Hello, World!';
  cell.applyStyles('center');

  await workbook.xlsx.writeFile('myWorkbook.xlsx');
}

</code>```

see playground: https://playcode.io/1044024

I am expecting to have a valid extension method to exceljs "Cell" interface

Body:
Any ideas how to make this extension method? I am using exceljs lib, and I want to have .applyStyles() method that could be used for any cell object. See sample of the code.

import * as ExcelJS from 'exceljs';
import { Cell } from 'exceljs';

declare module 'exceljs' {
  interface Cell {
    applyStyles(style: string): void;
  }
}

Cell.prototype.applyStyles = function(style: string) {
  if (style === 'center') {
    this.alignment = { horizontal: 'center' };
  }
};

import './exceljs-extensions';
import * as ExcelJS from 'exceljs';
async() => {
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet('Sheet1');

  const cell = worksheet.getCell('A1');
  cell.value = 'Hello, World!';
  cell.applyStyles('center');

  await workbook.xlsx.writeFile('myWorkbook.xlsx');
}

see playground: https://playcode.io/1044024

I am expecting to have a valid extension method to exceljs "Cell" interface


来源: stackexchange

问:
Credentials fail logging into Pandora via Puppeteer using Chrome or Chromium
The credentials are verified to be correct.

When I run my script, I have headless:false and am watching everything seemingly behave correctly, but I get an incorrect username/password error. The same holds true if I manually type in the creds in this SAME browser that pops open when my script starts.

If I switch to my installed browser, however, creds work and I can login no problem.

I am just learning Puppeteer and do not have much front end experience. My guess is either Pandora has some extra layers of protection for logging in via scripts, or something I don't know about headless browsers in general.

Here is my script:

```<code>const puppeteer = require('puppeteer');
var fs = require('fs');
var ini = require('ini');
var config = ini.parse(fs.readFileSync('./creds.ini', 'utf-8'));
pandora_user = config.pandora.name;
pandora_pass = config.pandora.pass;
(async () => {
  const browser = await puppeteer.launch(
    {
        headless: false,
        executablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
    }
);
  const page = await browser.newPage();
  const timeout = 500000; // my internet is down, running off bluetooth phone connection, dont judge me here
  page.setDefaultTimeout(timeout);

  try {
    await page.goto("https://www.pandora.com/account/sign-in");
    await page.waitForSelector(`input[name=email]`, {timeout, visible: true});
    await page.waitForSelector(`input[name=password]`, {timeout, visible: true});
    await page.type(`input[name=email]`, pandora_user);
    await page.type(`input[name=password]`, pandora_pass);

    await Promise.all([
      page.click(`button[name="login"]`),
      page.waitForNavigation()
    ])
  } catch (err) {
    console.log(err);
  } finally {
    await browser.close();
  }
</code>```

Tried adding ignoreDefaultArgs: ['--enable-automation'], to the launch args

ContentLicense: CC BY-SA 4.0

Body:
The credentials are verified to be correct.

When I run my script, I have headless:false and am watching everything seemingly behave correctly, but I get an incorrect username/password error. The same holds true if I manually type in the creds in this SAME browser that pops open when my script starts.

If I switch to my installed browser, however, creds work and I can login no problem.

I am just learning Puppeteer and do not have much front end experience. My guess is either Pandora has some extra layers of protection for logging in via scripts, or something I don't know about headless browsers in general.

Here is my script:

const puppeteer = require('puppeteer');
var fs = require('fs');
var ini = require('ini');
var config = ini.parse(fs.readFileSync('./creds.ini', 'utf-8'));
pandora_user = config.pandora.name;
pandora_pass = config.pandora.pass;
(async () => {
  const browser = await puppeteer.launch(
    {
        headless: false,
        executablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
    }
);
  const page = await browser.newPage();
  const timeout = 500000; // my internet is down, running off bluetooth phone connection, dont judge me here
  page.setDefaultTimeout(timeout);

  try {
    await page.goto("https://www.pandora.com/account/sign-in");
    await page.waitForSelector(`input[name=email]`, {timeout, visible: true});
    await page.waitForSelector(`input[name=password]`, {timeout, visible: true});
    await page.type(`input[name=email]`, pandora_user);
    await page.type(`input[name=password]`, pandora_pass);

    await Promise.all([
      page.click(`button[name="login"]`),
      page.waitForNavigation()
    ])
  } catch (err) {
    console.log(err);
  } finally {
    await browser.close();
  }

Tried adding ignoreDefaultArgs: ['--enable-automation'], to the launch args


问:
Refused to execute script from '....' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled
Hi I am new to React and recently built my app which was working fine locally but when my colleagues deployed it on the azure , we are facing this issue.

I tried looking for answers in stackoverflow itself but it was associated with changing webpack.config.js file which looks nothing like my config file which is in node_modules/react-scripts/config. So no idea how to solve it. Here is my public/index.html file

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <title>Booking System</title>

    You need to enable JavaScript to run this app.

```


问:
nodejs hmac md5 incorrect calculation
Guys how is it possible that crypto produces the following hash

```<code>console.log(crypto.createHmac('md5', 'key').update('value').digest('hex'))
01433efd5f16327ea4b31144572c67f6
</code>```

whereas node-forge produces incorrect one, however works fine for SSL calculation

```<code>let md5 = forge.hmac.create()
md5.start('MD5', 'key')
md5.update('value')
console.log(Buffer.from(md5.digest().data).toString('hex'))

01433ec3bd5f16327ec2a4c2b31144572c67c3b6
</code>```

openssl produces the same output as crypto

```<code>echo -n "value" | openssl dgst -md5 -hmac "key"
01433efd5f16327ea4b31144572c67f6
</code>```

Title: nodejs hmac md5 incorrect calculation

Body:
Guys how is it possible that crypto produces the following hash

console.log(crypto.createHmac('md5', 'key').update('value').digest('hex'))
01433efd5f16327ea4b31144572c67f6

whereas node-forge produces incorrect one, however works fine for SSL calculation

let md5 = forge.hmac.create()
md5.start('MD5', 'key')
md5.update('value')
console.log(Buffer.from(md5.digest().data).toString('hex'))

01433ec3bd5f16327ec2a4c2b31144572c67c3b6

openssl produces the same output as crypto

echo -n "value" | openssl dgst -md5 -hmac "key"
01433efd5f16327ea4b31144572c67f6


问:
Content Security Policy script-src violated for inline event handlers in dhtmlx suite 4.2
I'm working on an app which is using dhtmlxSuite 4.2 and I was working on refactoring our code base in order to support Content Security Policy. For now, we are removing the 'unsafe-inline' and we are using a nonce to secure inline scripts.

Could you please provide some information regarding dhtmlx suite 4.2, does it support CSP and if yes, how can I configure it to support CSP using nonce? I was looking over internet but I'm not able to find any relevant documentation for this version.

Our script-src directive in CSP header is:

script-src 'self' 'strict-dynamic' 'unsafe-eval' 'nonce-r4nd0m'

I'm using the following line to add the dhtmlx .js files to the code:


问:
Android studio location permission listener
I am trying to ask for user location permission but I need to set some kind of listener to the user response otherwise, I cant get the user location and the app crashes due to null pointer exception.

This are the functions I am using to get and set the location

```<code>private void setLocation() {
    if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 44);

    }
    LocationManager locationManager;
    locationManager = (LocationManager) getSystemService(ScoreActivity.this.LOCATION_SERVICE);
    Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
    onLocationChanged(location);
}
</code>```
```<code>@Override
public void onLocationChanged(@NonNull Location location) {
    locationDetails=new LatLng(location.getLatitude(),location.getLongitude());
}
</code>```

Body:
I am trying to ask for user location permission but I need to set some kind of listener to the user response otherwise, I cant get the user location and the app crashes due to null pointer exception.

This are the functions I am using to get and set the location

private void setLocation() {
    if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 44);

    }
    LocationManager locationManager;
    locationManager = (LocationManager) getSystemService(ScoreActivity.this.LOCATION_SERVICE);
    Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
    onLocationChanged(location);
}

@Override
public void onLocationChanged(@NonNull Location location) {
    locationDetails=new LatLng(location.getLatitude(),location.getLongitude());
}


问:
Find Realm PrivateKey in Keycloak SPI module
I have an SPI module that listens for events and sends them to my backend service, but I want to encrypt the connection from Keycloak to the backend with the realm certificates. For this purpose, I need the private key of one of these certificates. I saw that if I have a KeycloakSession I can get it as:

```<code>session.keys().getActiveKey(session.getContext().getRealm(), KeyUse.SIG, Algorithm.RS256).getPrivateKey()
</code>```

However, event listeners have no way to get the session, or at least I haven't found a way. Is there another option to access the certificates without using a session?

Body:
I have an SPI module that listens for events and sends them to my backend service, but I want to encrypt the connection from Keycloak to the backend with the realm certificates. For this purpose, I need the private key of one of these certificates. I saw that if I have a KeycloakSession I can get it as:

session.keys().getActiveKey(session.getContext().getRealm(), KeyUse.SIG, Algorithm.RS256).getPrivateKey()

However, event listeners have no way to get the session, or at least I haven't found a way. Is there another option to access the certificates without using a session?


问:
Volley always executes Error Listener and returns null in error message
I am trying to get the imageUrl from the Json response and set the image on ImageView but Error.ResponseListener is always executing and

e.message.toString() always returns null

```<code>
    private fun getImageFromURL() {

        val requestQueue = Volley.newRequestQueue(context)
        val stringRequest = StringRequest(Request.Method.GET, URL, { response ->
            try {
                val jsonObject = JSONObject(response)
                val jsonArray = jsonObject.getJSONArray("items")
                val imageUrl = jsonArray.getJSONObject(0).getJSONObject("image_versions2")
                    .getJSONArray("candidates").getJSONObject(0).getString("url")

                uri = Uri.parse(imageUrl)
                Glide.with(requireContext()).load(imageUrl).into(binding.ivInstaImage)

                binding.progressBar.visibility = View.GONE
                binding.ivInstaImage.visibility = View.VISIBLE
                binding.btnDownload.visibility = View.VISIBLE

            } catch (e: Exception) {
                binding.progressBar.visibility = View.GONE
                Toast.makeText(context, e.message.toString(), Toast.LENGTH_SHORT).show()
            }
        }, { error ->
            binding.progressBar.visibility = View.GONE
            Toast.makeText(context, error.message.toString(), Toast.LENGTH_SHORT).show()
        })
        requestQueue.add(stringRequest)
    }

}
</code>```

Body:
I am trying to get the imageUrl from the Json response and set the image on ImageView but Error.ResponseListener is always executing and

e.message.toString() always returns null

    private fun getImageFromURL() {

        val requestQueue = Volley.newRequestQueue(context)
        val stringRequest = StringRequest(Request.Method.GET, URL, { response ->
            try {
                val jsonObject = JSONObject(response)
                val jsonArray = jsonObject.getJSONArray("items")
                val imageUrl = jsonArray.getJSONObject(0).getJSONObject("image_versions2")
                    .getJSONArray("candidates").getJSONObject(0).getString("url")

                uri = Uri.parse(imageUrl)
                Glide.with(requireContext()).load(imageUrl).into(binding.ivInstaImage)

                binding.progressBar.visibility = View.GONE
                binding.ivInstaImage.visibility = View.VISIBLE
                binding.btnDownload.visibility = View.VISIBLE

            } catch (e: Exception) {
                binding.progressBar.visibility = View.GONE
                Toast.makeText(context, e.message.toString(), Toast.LENGTH_SHORT).show()
            }
        }, { error ->
            binding.progressBar.visibility = View.GONE
            Toast.makeText(context, error.message.toString(), Toast.LENGTH_SHORT).show()
        })
        requestQueue.add(stringRequest)
    }

}


问:
sideEffect with useState and event Listener onMouseMove
I need to add an offset value in y to my mouse position, but when I add the offset value, the mouse position is sometime corrupted and the witness

 disappear, plus the refresh is stopped until I move again my mouse.
When there is no value added, that's work fine.
I try to find a solution with useRef, useEffect, the value prevof useState but my knowledge in React is very limited, and I don't find any solution.
Here a snipped code to resume my problem.
and a link to see the problem in live :)
https://www.knupel.art/

and the code is here :
https://github.com/knupel/knupel_site/blob/master/src/components/image/image_zoom.js#L34

function Test() {
   // other code

   // here the code probleme
   const [mouse, set_mouse] = useState({x:0,y:0});
   const mouse_move = (event) => {
     // let buf = {x:event.pageX, y: event.pageY} // work fine
     let buf = {x:event.pageX, y:event.pageY + 42} // work, but very bad
     set_mouse(buf);
  }

  const info_style = {
        zIndex: "999px",
        position: 'absolute',
        height: '20px',
        width: '20px',
        background: 'yellow',
        opacity: is_over ? 1 : 0,
        left: mouse.x,
        top:  mouse.y,
    }
  // other code
  return(

                <GatsbyImage image={getImage(img)} alt={img.base}/>

 )
}

```


问:
Views Filtering nodes through taxonomy terms from paragraphs bundle doesn't work
My node type has a paragraph bundle field which including a taxonomy terms field, but in my views, the nodes just not showing up by filtering this taxonomy terms, if the terms field not in the paragraph bundle, the node will show, but if its in the paragraph bundle, the node won't show, any one knows if I am missing something, I am in Drupal7 , Thanks

I have added relationship in my views with paragraphs bundle, but no help


问:
ffmpeg mp4 to hls but video parts size are not balanced, some are big and small
here's the problem:

my command:

```<code>ffmpeg -i output.mp4 -start_number 0 -hls_time 10 -hls_list_size 0 -f hls 1.m3u8
</code>```

Body:
here's the problem:

my command:

ffmpeg -i output.mp4 -start_number 0 -hls_time 10 -hls_list_size 0 -f hls 1.m3u8


问:
How to “listen” to a Firestore document using a Cloudflare Worker?
I need to get the value of a document stored in a Google Firestore database the next time someone changes it. From what I understand, this is called “listening to a document.”

However, I can’t use the firebase client library since my code will run on a Cloudflare worker (in JavaScript).

I found a “listen” endpoint in the Firestore REST API documentation here, but it does not seem to work. Some people on the Internet say that this endpoint does not exist in the REST API.

But below the documentation for the rest API, there is documentation for an “RPC API” with also a “listen” function here.

However, even after looking everywhere for hours, I don’t understand how to call it. I could not find anywhere the URL to send the request to, the headers to use, the body, the method, or anything about that “RPC API”.

I’ve already tried calling the normal REST API with simple endpoints, which worked (so it’s not an authentication problem or anything like that).

I’ve also tried calling the REST listen endpoint the documentation mentions but without success (it always results in the same 400 “INVALID_ARGUMENT” error)

I would appreciate any help (an example, information about the request, …).


问:
Reactive forms apply formControlName for a tag instead of a input
I have a reactive form myForm

```<code><form [formGroup]="myForm">
</code>```

it has a sub FormArray called emails within the myForm

```<code><div formArrayName="emails">
  <div *ngFor="let item of myForm.get('emails')['controls']; let i= index" [formGroupName]="i">
    <input type="text" formControlName="from"/>
</code>```

My question is as formControlName="from" is perfectly works, why there is no facility to render like this?

```<code><div formArrayName="emails">
  <div *ngFor="let item of myForm.get('emails')['controls']; let i= index" [formGroupName]="i">
    <div> {{from}} </div>
</code>```

why should we write additional code as part of the rendering?

Body:
I have a reactive form myForm

<form [formGroup]="myForm">

it has a sub FormArray called emails within the myForm

    <input type="text" formControlName="from"/>

My question is as formControlName="from" is perfectly works, why there is no facility to render like this?

 {{from}}

why should we write additional code as part of the rendering?


问:
JavaScript Basic Maths Calculator
My question might sounds stupid but I'm a newbie. My goal is to create a calculator based on JavaScript on my website. First multiplication works, however the other ones, I tried many things and nothing seems to work.

Here's the code below, that works at the beginning.

Feel free to ask any question if necessary, thanks for your time!

```<code><script data-info='hacks-body'>
// on lost hours input
$('#input-lost-hours').on('input', function(){
  // update fee per hour text
  $('#text-lost-hours').text(formatNumber($(this).val()));
  // update total fee text
  $('#text-monthly-fee').text(formatNumber(calculateTotalFee()));
});

// on cost hour inout
$('#input-hour-cost').on('input', function(){
  // update total hours text
  $('#text-cost-hour').text(formatNumber($(this).val()));
  // update total fee text
  $('#text-monthly-fee').text(formatNumber(calculateTotalFee()));
});

// on budget
$('#input-monthly-budget').on('input', function(){
  // update total hours text
  $('#text-freelance-budget').text(formatNumber($(this).val()));
  // update total fee text
  $('#text-total-budget').text(formatNumber(calculateTotalFee()));
});

// calculate total fee
function calculateTotalFee(){
  // get fee per hour value
  const monthCost = Number($('#input-lost-hours').val());
  // get total hours value
  const costHr = Number($('#input-hour-cost').val());
  // get monthly budget + service fee
  const monthBudget = Number($('#input-monthly-cost').val());
  // service fee
  const servFee = Number($('#text-service-fee').val());
  // multiply per hour value by total hours to get total fee
  return monthCost * costHr;
}

// format number function
// e.g. 3500 becomes 3,500
function formatNumber(num){
  return new Intl.NumberFormat().format(num);
}
</script>
</code>```

I tried to add different functions, and separate them, but once I modify something, it goes all broken, and nothing is working.

Title: JavaScript Basic Maths Calculator

Body:
My question might sounds stupid but I'm a newbie. My goal is to create a calculator based on JavaScript on my website. First multiplication works, however the other ones, I tried many things and nothing seems to work.

Here's the code below, that works at the beginning.

Feel free to ask any question if necessary, thanks for your time!

I tried to add different functions, and separate them, but once I modify something, it goes all broken, and nothing is working.


问:
My geopy.geocoders is throwing error: SSL: CERTIFICATE_VERIFY_FAILED. How can I resolve this?
When I try to run this code.

```<code>from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="ryan_data")
location = geolocator.geocode("175 5th Avenue NYC")
print(location.address)
</code>```

I get this error.

GeocoderUnavailable: HTTPSConnectionPool(host='nominatim.openstreetmap.org', port=443): Max retries exceeded with url: /search?q=175+5th+Avenue+NYC&format=json&limit=1 (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)')))

This should be a pretty simple thing, but I can't get the code to run. I'm trying to run the code on my corporate laptop. The exact same code works perfectly find on my personal laptop. Any idea what's wrong here?

Documentation is here.

https://geopy.readthedocs.io/en/stable/#module-geopy.geocoders

Body:
When I try to run this code.

from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="ryan_data")
location = geolocator.geocode("175 5th Avenue NYC")
print(location.address)

I get this error.

GeocoderUnavailable: HTTPSConnectionPool(host='nominatim.openstreetmap.org', port=443): Max retries exceeded with url: /search?q=175+5th+Avenue+NYC&format=json&limit=1 (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1129)')))

This should be a pretty simple thing, but I can't get the code to run. I'm trying to run the code on my corporate laptop. The exact same code works perfectly find on my personal laptop. Any idea what's wrong here?

Documentation is here.

https://geopy.readthedocs.io/en/stable/#module-geopy.geocoders


问:
Error "Amplify.AuthError error 2" thrown during the sign in flow on iOS with amplify-swift 1.15.1
During the sign in flow in iOS, for few users the Authentication module of the amplify-swift library throws the error The operation couldn't be completed. (Amplify.AuthError error 2). I have searched in the amplify-swift repository for possible solutions but couldn't find any. The version of Amplify pod used in code is 1.15.1.

```<code>func nativeLogin(
  email: String?, password: String?, completion: @escaping (Result<Authstate, Error>) -> Void
) {
  let isAlreadySignedIn = AWSMobileClient.default().isSignedIn
  if isAlreadySignedIn {
    // Do signout and then sign in
    let options = AuthSignOutRequest.Options(globalSignOut: true)
    Amplify.Auth.signOut(options: options) {
      result in
      DispatchQueue.main.async {
        if case .success = result {
          // completion(.success(.logout))
          guard let email = email,
            let password = password
          else {
            self.response(
              completion, .failure(AuthError.passwordValidationError("Missing Email/Password")))
            return
          }
          // log event
          self.signIn(email: email, password: password, completion: completion)
        } else if case .failure(let error) = result {
          // log event
          completion(.failure(error))
        }
      }
    }
  } else {
    self.signIn(email: email, password: password, completion: completion)
  }
}
</code>```

The reason that the signOut method is invoked before actually signing in is to ensure that last logged in user is signed out first.

Can anyone explain where am I going wrong? Or has this error been already fixed in the latest version (2.2.1) of the amplify-swift library?

Body:
During the sign in flow in iOS, for few users the Authentication module of the amplify-swift library throws the error The operation couldn't be completed. (Amplify.AuthError error 2). I have searched in the amplify-swift repository for possible solutions but couldn't find any. The version of Amplify pod used in code is 1.15.1.

func nativeLogin(
  email: String?, password: String?, completion: @escaping (Result<Authstate, Error>) -> Void
) {
  let isAlreadySignedIn = AWSMobileClient.default().isSignedIn
  if isAlreadySignedIn {
    // Do signout and then sign in
    let options = AuthSignOutRequest.Options(globalSignOut: true)
    Amplify.Auth.signOut(options: options) {
      result in
      DispatchQueue.main.async {
        if case .success = result {
          // completion(.success(.logout))
          guard let email = email,
            let password = password
          else {
            self.response(
              completion, .failure(AuthError.passwordValidationError("Missing Email/Password")))
            return
          }
          // log event
          self.signIn(email: email, password: password, completion: completion)
        } else if case .failure(let error) = result {
          // log event
          completion(.failure(error))
        }
      }
    }
  } else {
    self.signIn(email: email, password: password, completion: completion)
  }
}

The reason that the signOut method is invoked before actually signing in is to ensure that last logged in user is signed out first.

Can anyone explain where am I going wrong? Or has this error been already fixed in the latest version (2.2.1) of the amplify-swift library?


问:
Switch background colors between active/inactive tabs
I'm migrating my site from Bootstrap to Tailwind 3 and, in the process, built-in solutions (Dropdown, Tabs, Accordion...) needed to be replaced with alternatives. The section I'm working on right now is a custom Comments Editor I created.

I'll leave a link to what Tailwind's Playground generated for me in a CodePen because the code is longer than the maximum number of allowed characters here. The decision to create a Pen is only because in the Playground it doesn't work as the anchors open in new windows/tabs.

Anyway, the code that really matters, what makes the tabs work, is this one:

```<code>[data-target] {
  scroll-margin-top: 10rem;
}

[data-target]:last-of-type + [role="tabpanel"], :target + [role="tabpanel"]{
  display: flex;
}

[role="tabpanel"], :target ~ [data-target]:last-of-type + [role="tabpanel"]{
  display: none;
}
</code>```

As the title says, I'm looking for a way to change the background-color of the tabs, hinting to the User which one is currently active.

To accomplish that, I would need to switch Tailwind's bg-color-0 with bg-color-100 and take border-b-color-0 out of the once active tab and give it to the new one. But I don't know if I can do that only with CSS.

Not add/remove the classes per se, only their corresponding styles

I've seen a lot of implementations of Pure CSS Tabs, and all of them used hidden <input> fields. Though this implementation doesn't use them, I've added and named them accordingly, but I could only target them with CSS if the User clicked exactly where they're positioned (top-left of the tabs) instead of any part of them.

I'm aware I'll eventually have to add JS to switch the ARIA attributes, but is the basic functionality possible to be accomplished with CSS only? If not, is there an alternative implementation with which I could?

Thank you for your time :)

Body:
I'm migrating my site from Bootstrap to Tailwind 3 and, in the process, built-in solutions (Dropdown, Tabs, Accordion...) needed to be replaced with alternatives. The section I'm working on right now is a custom Comments Editor I created.

I'll leave a link to what Tailwind's Playground generated for me in a CodePen because the code is longer than the maximum number of allowed characters here. The decision to create a Pen is only because in the Playground it doesn't work as the anchors open in new windows/tabs.

Anyway, the code that really matters, what makes the tabs work, is this one:

[data-target] {
  scroll-margin-top: 10rem;
}

[data-target]:last-of-type + [role="tabpanel"], :target + [role="tabpanel"]{
  display: flex;
}

[role="tabpanel"], :target ~ [data-target]:last-of-type + [role="tabpanel"]{
  display: none;
}

As the title says, I'm looking for a way to change the background-color of the tabs, hinting to the User which one is currently active.

To accomplish that, I would need to switch Tailwind's bg-color-0 with bg-color-100 and take border-b-color-0 out of the once active tab and give it to the new one. But I don't know if I can do that only with CSS.

Not add/remove the classes per se, only their corresponding styles

I've seen a lot of implementations of Pure CSS Tabs, and all of them used hidden <input> fields. Though this implementation doesn't use them, I've added and named them accordingly, but I could only target them with CSS if the User clicked exactly where they're positioned (top-left of the tabs) instead of any part of them.

I'm aware I'll eventually have to add JS to switch the ARIA attributes, but is the basic functionality possible to be accomplished with CSS only? If not, is there an alternative implementation with which I could?

Thank you for your time :)


问:
Unable to cast transparent proxy error with uno libreoffice
I am trying to programmatically refresh a calc document (libreoffice) in C# and I get error

"unable to cast transparent proxy to type
unoidl.com.sun.star.util.XRefreshable"

Please see below the code I use

```<code>XRefreshable refreshable = (XRefreshable) document;
</code>```

where document is of type XComponent

Body:
I am trying to programmatically refresh a calc document (libreoffice) in C# and I get error

"unable to cast transparent proxy to type
unoidl.com.sun.star.util.XRefreshable"

Please see below the code I use

XRefreshable refreshable = (XRefreshable) document;

where document is of type XComponent


问:
Saving QBarChart as SVG, Y-axis is not proper drawn
I create multiple QChart() with QLineSeries() and QBarSeries. I like to save the files as pngand svg. The funtion to make the graphs works, but saving the files as svg is different than png.

Result

Code to show fault
`

```<code>from PyQt5.QtWidgets import QApplication, QMainWindow
import sys
from PyQt5.QtChart import QChart, QChartView, QBarSet, QPercentBarSeries, QBarCategoryAxis, QValueAxis, QBarSeries
from PyQt5.QtGui import QPainter, QFont
from PyQt5.QtCore import Qt, QRectF, QPointF, QSizeF, QSize
from PyQt5.QtSvg import QSvgGenerator

class Window(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("PyQt BarChart")
        self.setGeometry(100,100, 680,500)
        self.show ()

        barDict = {'TotalRMSV[mm/s]': [2.85], 'barnames': ['2022']}

        chartview = QChartView()
        output_size = QSize (800, 600)  # pixels
        chart = barChart(barDict, "Test")
        chartview.setChart(chart)
        self.setCentralWidget (chartview)
        save_chart_as_svg(chartview,  output_size, "c://temp/test.svg")

def barChart(barDict, graphtitle='barChart'):
    print ("-> qt_graph_tools.barChart")
    series = chart_create_bar_series(barDict)
    axisY = QValueAxis ()

    axisY.setMin(1)                     # If I set Min to 0, all graphics are ok.
    axisY.setMax(4)

    chart = QChart ()
    chart.addSeries (series)
    chart.setAxisY (axisY, series)

    chart.setTitle (graphtitle)
    chart.setAnimationOptions (QChart.NoAnimation)
    chart.legend ().setAlignment (Qt.AlignBottom)

    return chart

def save_chart_as_svg(chartView, output_size, save_as):
    # the desired size of the rendering
    # in pixels for PNG, in pt for SVG
    output_size.setWidth (int (output_size.width () * 0.75))
    output_size.setHeight (int (output_size.height () * 0.75))   # tranlate pixels to pt
    output_rect = QRectF (QPointF (0, 0), QSizeF (output_size))  # cast to float
    chart = chartView.chart ()
    svg = QSvgGenerator()
    svg.setFileName (save_as)
    svg.setSize (output_size)
    svg.setViewBox (output_rect)
    chart.resize (output_rect.size ())
    painter = QPainter ()
    painter.begin (svg)
    painter.setRenderHint (QPainter.Antialiasing)
    chart.scene ().render (painter, source=output_rect, target=output_rect, mode=Qt.IgnoreAspectRatio)
    painter.end ()
    return svg

def chart_create_bar_series( bardict):
    print("-> qt_graph_tools.chart_create_bar_series")
    series = QBarSeries ()
    for key, data_set in bardict.items():
        if key != 'gear' and key != 'barnames' and key != 'colors':
            barset = QBarSet(key)
            barset.append(data_set)
            series.append(barset)
    return series

App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec_())
</code>```

`

The image is the resulting SVG shown in Firefox and the Window is its data as QChartView. System: Windows 11, PyQt5.15, python 3.10. If you set the axisY.setMin(0), the output is correct, with higher value it should be cutted at the borderline, but is not. It's not a good idea to set Min fix to 0, because sometimes I'm interested in a range e.g. 5..7

Body:
I create multiple QChart() with QLineSeries() and QBarSeries. I like to save the files as pngand svg. The funtion to make the graphs works, but saving the files as svg is different than png.

Result

Code to show fault
`

from PyQt5.QtWidgets import QApplication, QMainWindow
import sys
from PyQt5.QtChart import QChart, QChartView, QBarSet, QPercentBarSeries, QBarCategoryAxis, QValueAxis, QBarSeries
from PyQt5.QtGui import QPainter, QFont
from PyQt5.QtCore import Qt, QRectF, QPointF, QSizeF, QSize
from PyQt5.QtSvg import QSvgGenerator

class Window(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("PyQt BarChart")
        self.setGeometry(100,100, 680,500)
        self.show ()

        barDict = {'TotalRMSV[mm/s]': [2.85], 'barnames': ['2022']}

        chartview = QChartView()
        output_size = QSize (800, 600)  # pixels
        chart = barChart(barDict, "Test")
        chartview.setChart(chart)
        self.setCentralWidget (chartview)
        save_chart_as_svg(chartview,  output_size, "c://temp/test.svg")

def barChart(barDict, graphtitle='barChart'):
    print ("-> qt_graph_tools.barChart")
    series = chart_create_bar_series(barDict)
    axisY = QValueAxis ()

    axisY.setMin(1)                     # If I set Min to 0, all graphics are ok.
    axisY.setMax(4)

    chart = QChart ()
    chart.addSeries (series)
    chart.setAxisY (axisY, series)

    chart.setTitle (graphtitle)
    chart.setAnimationOptions (QChart.NoAnimation)
    chart.legend ().setAlignment (Qt.AlignBottom)

    return chart

def save_chart_as_svg(chartView, output_size, save_as):
    # the desired size of the rendering
    # in pixels for PNG, in pt for SVG
    output_size.setWidth (int (output_size.width () * 0.75))
    output_size.setHeight (int (output_size.height () * 0.75))   # tranlate pixels to pt
    output_rect = QRectF (QPointF (0, 0), QSizeF (output_size))  # cast to float
    chart = chartView.chart ()
    svg = QSvgGenerator()
    svg.setFileName (save_as)
    svg.setSize (output_size)
    svg.setViewBox (output_rect)
    chart.resize (output_rect.size ())
    painter = QPainter ()
    painter.begin (svg)
    painter.setRenderHint (QPainter.Antialiasing)
    chart.scene ().render (painter, source=output_rect, target=output_rect, mode=Qt.IgnoreAspectRatio)
    painter.end ()
    return svg

def chart_create_bar_series( bardict):
    print("-> qt_graph_tools.chart_create_bar_series")
    series = QBarSeries ()
    for key, data_set in bardict.items():
        if key != 'gear' and key != 'barnames' and key != 'colors':
            barset = QBarSet(key)
            barset.append(data_set)
            series.append(barset)
    return series

App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec_())

`

The image is the resulting SVG shown in Firefox and the Window is its data as QChartView. System: Windows 11, PyQt5.15, python 3.10. If you set the axisY.setMin(0), the output is correct, with higher value it should be cutted at the borderline, but is not. It's not a good idea to set Min fix to 0, because sometimes I'm interested in a range e.g. 5..7


问:
c padding and alignment
Having brushed up on memory alignment I found this example

```<code>#include <stdio.h>
#include <stdlib.h>
typedef struct {
    int x;
    char y;
    long long z;
} Example;

typedef struct{
    int a;  // 8 bytes
    Example e;  // 16 bytes
} Example2;

int main(){
    printf("%ld\n", sizeof(Example));
    printf("%ld\n", sizeof(Example2));
}
</code>```

which prints 16, 24 to the screen although I would have expected 16, 32 in this case. Example2's second member Example has a sizeof 16 bytes and is thus the largest member of Example2 which defines the alignment of this struct, does it not? So with 16 bytes alignment I exptected to be a padding of 8 bytes inserted after the a member of Example2 but there seems to be none inserted. Why is that please?

Title: c padding and alignment

Body:
Having brushed up on memory alignment I found this example

#include <stdio.h>
#include <stdlib.h>
typedef struct {
    int x;
    char y;
    long long z;
} Example;

typedef struct{
    int a;  // 8 bytes
    Example e;  // 16 bytes
} Example2;

int main(){
    printf("%ld\n", sizeof(Example));
    printf("%ld\n", sizeof(Example2));
}

which prints 16, 24 to the screen although I would have expected 16, 32 in this case. Example2's second member Example has a sizeof 16 bytes and is thus the largest member of Example2 which defines the alignment of this struct, does it not? So with 16 bytes alignment I exptected to be a padding of 8 bytes inserted after the a member of Example2 but there seems to be none inserted. Why is that please?


问:
Why these HTML elements added to DOM using react/nextjs are not visible?
I have a component that renders some html, I want to add some other html element onClick. This is what I tried so far:

```<code>const [elementsToAdd, setElementsToAdd] = useState([]);

const handleAddAnother = () => {
  let nextVal = elementsToAdd.length;
  const newChild = getChild(nextVal);
  elementsToAdd.push(newChild);
  setElementsToAdd(elementsToAdd);
}

const getChild = id => {
  return (
    <p>some text</p>
  )
}

const renderChildren = () => elementsToAdd.map(child => {
  return child;
});

return (
  {renderChildren()}
  {questionType === 1 || questionType === 2 ? (
    <p onClick={handleAddAnother}>Add some element</p>
  ) : null}
)
</code>```

additional DOM elements are added to elementsToAdd array as expected. However, they are not visible in the page. They become visible only when questionType changes (for example from 1 to 2).

what am I doing wrong?

Body:
I have a component that renders some html, I want to add some other html element onClick. This is what I tried so far:

const [elementsToAdd, setElementsToAdd] = useState([]);

const handleAddAnother = () => {
  let nextVal = elementsToAdd.length;
  const newChild = getChild(nextVal);
  elementsToAdd.push(newChild);
  setElementsToAdd(elementsToAdd);
}

const getChild = id => {
  return (

some text

  )
}

const renderChildren = () => elementsToAdd.map(child => {
  return child;
});

return (
  {renderChildren()}
  {questionType === 1 || questionType === 2 ? (

Add some element

  ) : null}
)

additional DOM elements are added to elementsToAdd array as expected. However, they are not visible in the page. They become visible only when questionType changes (for example from 1 to 2).

what am I doing wrong?


问:
How can I publish IG story with ig-user-id without login issues?
In the Graph API documentation, it says that there is no access for the creating story for Instagram. Is there anyone have a solution for creating instagram story with having just ig-user-id, without login issues? Thanks in advance.

I know we can create a story with giving login details but I don't wanna use the password.


问:
A question about the Java File class and its Serialization maybe？
I don't know why the isFile() of the element f in the files list traversed by the for loop in the FileInit class in the code below is always false.false. But if delete the content related to FileItem, it will return to normal.It's kind of weird to me, and I didn't find a targeted answer. It might be some peculiarity of Java.A cloud disk project is used to learn Java, using Google's Gson library.

```<code>public class FileInit {
    String path;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    //Query file method, will return a list containing file information
    public String queryFiles() throws NoSuchAlgorithmException, IOException {
        //Query the path and build a File collection
        File file = new File(path);
        File[] files = file.listFiles();
        //Build a List to store the converted FileItem
        List<FileItem> fileItems = new ArrayList<>();
        //Traversing files to make judgments
        for (File f:files){
            FileItem fileItem = new FileItem(f);
            fileItem.printFile();
            fileItems.add(fileItem);
        }
        Gson gson = new Gson();
        return gson.toJson(fileItems);
    }
    //formatted output
    public void printFiles(String files){
        Gson gson = new Gson();
        Type type = new TypeToken<List<FileItem>>(){}.getType();
        List<FileItem> fileItems = gson.fromJson(files, type);
        // Format output file list
        int count = 0;
        for (FileItem f :fileItems ) {
            String name;
            if (f.getFileType()==null){
                name = f.getFileName() + "/";
            }else {
                name = f.getFileName();
            }
            System.out.printf("%-40s", name);
            count++;
            if (count % 3 == 0) {
                System.out.println();
            }
        }
        System.out.println();
    }
    //Change directory command
    public void changeDic(String addPath){
        File fileDic1 = new File(path+addPath);
        File fileDic2 = new File(addPath);
        if (addPath.equals("..")) {
            File parent = new File(path).getParentFile();
            if (parent != null) {
                this.path = parent.getPath();
            }else{
                System.out.println("Parent directory does not exist");
            }
        }
        else {
            if (fileDic1.exists()){
                this.path = path+addPath;
            } else if (fileDic2.exists()) {
                this.path = addPath;
            }else{
                System.out.println("Illegal input path");
            }
        }
    }
}
</code>```
```<code>public class FileItem {
    private String fileName;
    private String fileHash;
    private String filePath;
    private long fileLength;
    private String fileType;

    //Construction method of FileItem
    /*
Build a construction method that only needs fileName and filePath, and judge whether to calculate the hash value, file size, and file type according to the folder or file
*/
    public FileItem(String fileName,String filePath) {
        this.fileName = fileName;
        this.filePath = filePath;
        File file =new File(this.filePath+"/"+this.fileName);
        if (file.isFile()){
            try {
                //Get the file size through the file built-in method
                this.fileLength = file.length();
                // Define a regular expression for extracting the suffix of the file name
                String regex = "\\.(\\w+)$";
                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher(fileName);
                // If the match is successful
                if (matcher.find()) {
                    // Get the suffix of the file name
                    this.fileType = matcher.group(1);
                }else{
                    this.fileType = null;
                }
                //Calculate the Hash value of the file by calling the FileHash method
                this.fileHash=FileHash(file.getPath());
                System.out.printf(fileHash);
                System.out.print("\n");
            } catch (NoSuchAlgorithmException | IOException e) {
                throw new RuntimeException(e);
            }
        }else{
            this.fileName=fileName;
            this.fileLength=0;
            this.fileType = null;
            this.fileHash=null;
        }
    }

    //Build a constructor that only needs a json file
    public FileItem(String json){
        Gson gson = new Gson();
        FileItem fileItem = gson.fromJson(json,FileItem.class);
        this.fileName=fileItem.getFileName();
        this.filePath=fileItem.getFilePath();
        this.fileHash=fileItem.getFileHash();
        this.fileLength=fileItem.getFileLength();
        this.fileType=fileItem.getFileType();
    }

    //Realize mutual conversion between FileItem and File class
    public File toFile(){
        return new File(this.filePath+"/"+this.fileName);
    }

    public FileItem(File file) throws NoSuchAlgorithmException, IOException {
        FileItem fileItem = new FileItem(file.getName(),file.getPath());
        this.fileName=fileItem.getFileName();
        this.filePath=fileItem.getFilePath();
        this.fileHash=fileItem.getFileHash();
        this.fileLength=fileItem.getFileLength();
        this.fileType=fileItem.getFileType();
    }

    //Display FileItem related information
    public void printFile(){
        if (fileType==null){
            System.out.println(fileName+"是文件夹");
        }else {
            System.out.println(fileName+"是"+fileType+"文件");
        }
        double fileLenOp=(double)fileLength;
        //Different file sizes use different output methods
        if(fileLength<=1024*1024){
            System.out.printf("file size is:%.3fKB\n",fileLenOp/1024);
        } else if ((fileLength<1024*1024*1024)) {
            System.out.printf("file size is:%.3fMB\n",fileLenOp/1024/1024);
        }else {
            System.out.printf("file size is:%.3fGB\n",fileLenOp/1024/1024/1024);
        }
        System.out.println("file hash is:"+fileHash);
    }

    //Getter and Setter methods for FileItem

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFileHash() {
        return fileHash;
    }

    public void setFileHash(String fileHash) {
        this.fileHash = fileHash;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public long getFileLength() {
        return fileLength;
    }

    public void setFileLength(long fileLength) {
        this.fileLength = fileLength;
    }

    public String getFileType() {
        return fileType;
    }

    public void setFileType(String fileType) {
        this.fileType = fileType;
    }
}

</code>```

I try to query the file information in a folder by using the methods related to the File class. And return them as a collection. Then realize the conversion of the File class and the FileItem class by traversing this collection to form a new FileItem class collection , so that it can be converted into Json format data for network transmission. However, all fileitems in the generated FileItem collection are judged as folders. And if you comment out the FileItem related content, the judgment of File will be normal, but if you don’t do this , the judgment of File will always remain false.

Body:
I don't know why the isFile() of the element f in the files list traversed by the for loop in the FileInit class in the code below is always false.false. But if delete the content related to FileItem, it will return to normal.It's kind of weird to me, and I didn't find a targeted answer. It might be some peculiarity of Java.A cloud disk project is used to learn Java, using Google's Gson library.

public class FileInit {
    String path;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    //Query file method, will return a list containing file information
    public String queryFiles() throws NoSuchAlgorithmException, IOException {
        //Query the path and build a File collection
        File file = new File(path);
        File[] files = file.listFiles();
        //Build a List to store the converted FileItem
        List<FileItem> fileItems = new ArrayList<>();
        //Traversing files to make judgments
        for (File f:files){
            FileItem fileItem = new FileItem(f);
            fileItem.printFile();
            fileItems.add(fileItem);
        }
        Gson gson = new Gson();
        return gson.toJson(fileItems);
    }
    //formatted output
    public void printFiles(String files){
        Gson gson = new Gson();
        Type type = new TypeToken<List<FileItem>>(){}.getType();
        List<FileItem> fileItems = gson.fromJson(files, type);
        // Format output file list
        int count = 0;
        for (FileItem f :fileItems ) {
            String name;
            if (f.getFileType()==null){
                name = f.getFileName() + "/";
            }else {
                name = f.getFileName();
            }
            System.out.printf("%-40s", name);
            count++;
            if (count % 3 == 0) {
                System.out.println();
            }
        }
        System.out.println();
    }
    //Change directory command
    public void changeDic(String addPath){
        File fileDic1 = new File(path+addPath);
        File fileDic2 = new File(addPath);
        if (addPath.equals("..")) {
            File parent = new File(path).getParentFile();
            if (parent != null) {
                this.path = parent.getPath();
            }else{
                System.out.println("Parent directory does not exist");
            }
        }
        else {
            if (fileDic1.exists()){
                this.path = path+addPath;
            } else if (fileDic2.exists()) {
                this.path = addPath;
            }else{
                System.out.println("Illegal input path");
            }
        }
    }
}

public class FileItem {
    private String fileName;
    private String fileHash;
    private String filePath;
    private long fileLength;
    private String fileType;

    //Construction method of FileItem
    /*
Build a construction method that only needs fileName and filePath, and judge whether to calculate the hash value, file size, and file type according to the folder or file
*/
    public FileItem(String fileName,String filePath) {
        this.fileName = fileName;
        this.filePath = filePath;
        File file =new File(this.filePath+"/"+this.fileName);
        if (file.isFile()){
            try {
                //Get the file size through the file built-in method
                this.fileLength = file.length();
                // Define a regular expression for extracting the suffix of the file name
                String regex = "\\.(\\w+)$";
                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher(fileName);
                // If the match is successful
                if (matcher.find()) {
                    // Get the suffix of the file name
                    this.fileType = matcher.group(1);
                }else{
                    this.fileType = null;
                }
                //Calculate the Hash value of the file by calling the FileHash method
                this.fileHash=FileHash(file.getPath());
                System.out.printf(fileHash);
                System.out.print("\n");
            } catch (NoSuchAlgorithmException | IOException e) {
                throw new RuntimeException(e);
            }
        }else{
            this.fileName=fileName;
            this.fileLength=0;
            this.fileType = null;
            this.fileHash=null;
        }
    }

    //Build a constructor that only needs a json file
    public FileItem(String json){
        Gson gson = new Gson();
        FileItem fileItem = gson.fromJson(json,FileItem.class);
        this.fileName=fileItem.getFileName();
        this.filePath=fileItem.getFilePath();
        this.fileHash=fileItem.getFileHash();
        this.fileLength=fileItem.getFileLength();
        this.fileType=fileItem.getFileType();
    }

    //Realize mutual conversion between FileItem and File class
    public File toFile(){
        return new File(this.filePath+"/"+this.fileName);
    }

    public FileItem(File file) throws NoSuchAlgorithmException, IOException {
        FileItem fileItem = new FileItem(file.getName(),file.getPath());
        this.fileName=fileItem.getFileName();
        this.filePath=fileItem.getFilePath();
        this.fileHash=fileItem.getFileHash();
        this.fileLength=fileItem.getFileLength();
        this.fileType=fileItem.getFileType();
    }

    //Display FileItem related information
    public void printFile(){
        if (fileType==null){
            System.out.println(fileName+"是文件夹");
        }else {
            System.out.println(fileName+"是"+fileType+"文件");
        }
        double fileLenOp=(double)fileLength;
        //Different file sizes use different output methods
        if(fileLength<=1024*1024){
            System.out.printf("file size is:%.3fKB\n",fileLenOp/1024);
        } else if ((fileLength<1024*1024*1024)) {
            System.out.printf("file size is:%.3fMB\n",fileLenOp/1024/1024);
        }else {
            System.out.printf("file size is:%.3fGB\n",fileLenOp/1024/1024/1024);
        }
        System.out.println("file hash is:"+fileHash);
    }

    //Getter and Setter methods for FileItem

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFileHash() {
        return fileHash;
    }

    public void setFileHash(String fileHash) {
        this.fileHash = fileHash;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public long getFileLength() {
        return fileLength;
    }

    public void setFileLength(long fileLength) {
        this.fileLength = fileLength;
    }

    public String getFileType() {
        return fileType;
    }

    public void setFileType(String fileType) {
        this.fileType = fileType;
    }
}

I try to query the file information in a folder by using the methods related to the File class. And return them as a collection. Then realize the conversion of the File class and the FileItem class by traversing this collection to form a new FileItem class collection , so that it can be converted into Json format data for network transmission. However, all fileitems in the generated FileItem collection are judged as folders. And if you comment out the FileItem related content, the judgment of File will be normal, but if you don’t do this , the judgment of File will always remain false.


问:
Recharts jest snapshot test: ResizeObserver with MUI Tabs
In our Project, we are running jest snapshot tests with React testing library. We are using both Recharts with ResponsiveContainer and MUI with Tabs in the project, and they are both rendered in a specific test.

When no polyfill for ResizeObserver is set, the test fails with

```<code>window.ResizeObserver is not a constructor
</code>```

When setting the polyfill in the test setup:

```<code>
global.ResizeObserver = require('resize-observer-polyfill');
</code>```

the test is failing on the MUI Tabs with this:

```<code>
    TypeError: Cannot read properties of null (reading 'children')
</code>```

Is there a way to solve both problems with a elegant solution?

Body:
In our Project, we are running jest snapshot tests with React testing library. We are using both Recharts with ResponsiveContainer and MUI with Tabs in the project, and they are both rendered in a specific test.

When no polyfill for ResizeObserver is set, the test fails with

window.ResizeObserver is not a constructor

When setting the polyfill in the test setup:

global.ResizeObserver = require('resize-observer-polyfill');

the test is failing on the MUI Tabs with this:

    TypeError: Cannot read properties of null (reading 'children')

Is there a way to solve both problems with a elegant solution?


问:
How do I use SQLAlchemy to reflect Snowflake tables in one database and insert data into a different Snowflake database?
Here's the goal raw SQL:

INSERT INTO "db2"."schema2"."table" ("col1", "col2")
SELECT "db1"."schema1"."tablea"."column1",
       "db1"."schema1"."tableb"."column1"
FROM "db1"."schema1"."tablea" JOIN "db1"."schema1"."tableb"
ON
"db1"."schema1"."tablea"."join_col" = "db1"."schema1"."tableb"."join_col";
```
<p>I'm using SQLAlchemy Core to reflect the tables. This is simple enough but the issue is I'm unable to reflect them in a fully qualified way.</p>
<pre class="lang-py prettyprint-override"><code>from sqlalchemy import create_engine, MetaData, Table, text
from snowflake.sqlalchemy import URL
from sqlalchemy.sql import select, insert

engine = create_engine(URL(
    account="my_account",
    user="my_username",
    password="my_password",
    warehouse="my_warehouse",
    role="my_role",
)
)
metadata = MetaData()

with engine.begin() as cnxn:
    cnxn.execute(text("USE DATABASE db1;"))

tablea = Table("tablea", metadata, autoload_with=engine, schema="schema1")
tableb = Table("tableb", metadata, autoload_with=engine, schema="schema1")

with engine.begin() as cnxn:
    cnxn.execute(text("USE DATABASE db2;"))

table = Table("table", metadata, autoload_with=engine, schema="schema2")

sql = select(tablea.c.column1, tableb.c.column1)
sql = sql.select_from(tablea.join(tableb, tablea.c.join_col == tableb.c.join_col))

insert_stmnt = insert(table).from_select([c.name for c in table.c]), sql)

with engine.begin() as cnxn:
    cnxn.execute(insert_stmnt)
</code>```

The problem is the insert statement fails because I have three tables and two different databases. I think the easy answer is when reflecting the tables they need to be fully qualified. Is that possible? If so, how? I've been trying all different combinations of table_name and schema in the reflection trying to include the database but have been completely striking out.

The only thing I've been able to do is print the insert statement and then manually add the databases to each table in the resulting string. Then, run the string. This completely defeats the purpose of SQLAlchemy IMO.

python_full_version = "3.9.6"
sqlalchemy = "1.4.45"
snowflake-sqlalchemy = "1.4.4"

Body:
Here's the goal raw SQL:

INSERT INTO "db2"."schema2"."table" ("col1", "col2")
SELECT "db1"."schema1"."tablea"."column1",
       "db1"."schema1"."tableb"."column1"
FROM "db1"."schema1"."tablea" JOIN "db1"."schema1"."tableb"
ON
"db1"."schema1"."tablea"."join_col" = "db1"."schema1"."tableb"."join_col";

I'm using SQLAlchemy Core to reflect the tables. This is simple enough but the issue is I'm unable to reflect them in a fully qualified way.

from sqlalchemy import create_engine, MetaData, Table, text
from snowflake.sqlalchemy import URL
from sqlalchemy.sql import select, insert

engine = create_engine(URL(
    account="my_account",
    user="my_username",
    password="my_password",
    warehouse="my_warehouse",
    role="my_role",
)
)
metadata = MetaData()

with engine.begin() as cnxn:
    cnxn.execute(text("USE DATABASE db1;"))

tablea = Table("tablea", metadata, autoload_with=engine, schema="schema1")
tableb = Table("tableb", metadata, autoload_with=engine, schema="schema1")

with engine.begin() as cnxn:
    cnxn.execute(text("USE DATABASE db2;"))

table = Table("table", metadata, autoload_with=engine, schema="schema2")

sql = select(tablea.c.column1, tableb.c.column1)
sql = sql.select_from(tablea.join(tableb, tablea.c.join_col == tableb.c.join_col))

insert_stmnt = insert(table).from_select([c.name for c in table.c]), sql)

with engine.begin() as cnxn:
    cnxn.execute(insert_stmnt)

The problem is the insert statement fails because I have three tables and two different databases. I think the easy answer is when reflecting the tables they need to be fully qualified. Is that possible? If so, how? I've been trying all different combinations of table_name and schema in the reflection trying to include the database but have been completely striking out.

The only thing I've been able to do is print the insert statement and then manually add the databases to each table in the resulting string. Then, run the string. This completely defeats the purpose of SQLAlchemy IMO.

python_full_version = "3.9.6"
sqlalchemy = "1.4.45"
snowflake-sqlalchemy = "1.4.4"


问:
:not(:hover) transition plays on load
I have text that should fade in on hover and fade out when the mouse leaves the bounding box. For that I used the following CSS:

.project h3 {
    /* Other styles */
    opacity: 0; /* Set the default opacity to 0 */
}

.project:hover h3 {
    opacity: 1; /* Set the opacity to 1 when hovered over */
    transition: opacity 0.3s ease; /* Add a smooth transition for the opacity change */
}

.project:not(:hover) h3 {
    transition: opacity 0.6s ease; /* Add a slower transition for the opacity change when not hovered over */
}
```

When I load the page, I want it to be invisible from the start, but right now it starts opaque and fades out immediately. ChatGPT keeps suggesting to just remove the ".project:not(:hover) h3" style and is driving me insane. How can I keep the fade-out when I move my mouse away and still have it be invisible from the start?

The html context is literally just a div with the class "project" and that h3 in it, i created a separate test project to strip it down, the problem persisted.

Title: :not(:hover) transition plays on load

Body:
I have text that should fade in on hover and fade out when the mouse leaves the bounding box. For that I used the following CSS:

.project h3 {
    /* Other styles */
    opacity: 0; /* Set the default opacity to 0 */
}

.project:hover h3 {
    opacity: 1; /* Set the opacity to 1 when hovered over */
    transition: opacity 0.3s ease; /* Add a smooth transition for the opacity change */
}

.project:not(:hover) h3 {
    transition: opacity 0.6s ease; /* Add a slower transition for the opacity change when not hovered over */
}

When I load the page, I want it to be invisible from the start, but right now it starts opaque and fades out immediately. ChatGPT keeps suggesting to just remove the ".project:not(:hover) h3" style and is driving me insane. How can I keep the fade-out when I move my mouse away and still have it be invisible from the start?

The html context is literally just a div with the class "project" and that h3 in it, i created a separate test project to strip it down, the problem persisted.


问:
vulnerability security - Firebase Auth shouldn't return if an account exists or not when signin
I'm checking the security vulnerabilities of my application built on top of Firebase.

Using the firebase auth method signInWithEmailAndPassword or sendPasswordResetEmail these return in the response the error message

There is no user record corresponding to this identifier. The user may
have been deleted.

This is the first step for a hacker to discover user account on a website targeted with brute force attacks.

The SDK limit the number of requests with a rate limit but does it exists a way to avoid to return these detailed errors ?

A secured error message would be This user doesn't exists or the password doesn't match

Thank you


问:
How can reduce package size of the Google API PHP Client by using composer.json extra configuration?
I am using the google-api-php-client in the WP plugin and the PHP composer downloading the complete git repo with almost 200 libraries so the size of the plugin is increasing due to that.

is there a way to get only the desired single package like sheet, drive, etc from this repo by using the PHP composer?

I have tested the following configuration but it is not working.

```<code>{
    "require": {
        "google/apiclient": "^2.12.1"
    },
    "scripts": {
        "pre-autoload-dump": "Google\\Task\\Composer::cleanup"
    },
    "extra": {
        "google/apiclient-services": [
            "Drive",
            "YouTube"
        ]
    }
}
</code>```

Body:
I am using the google-api-php-client in the WP plugin and the PHP composer downloading the complete git repo with almost 200 libraries so the size of the plugin is increasing due to that.

is there a way to get only the desired single package like sheet, drive, etc from this repo by using the PHP composer?

I have tested the following configuration but it is not working.

{
    "require": {
        "google/apiclient": "^2.12.1"
    },
    "scripts": {
        "pre-autoload-dump": "Google\\Task\\Composer::cleanup"
    },
    "extra": {
        "google/apiclient-services": [
            "Drive",
            "YouTube"
        ]
    }
}


问:
Hide/Remove Permission-Policy header warnings in chrome
We have added new permission policies in our application's web.xml file. Since then, we've been watching these warnings in google chrome's (MS Edge as well) console. Also, this is not visible in Firefox.

Is there a way we can elegantly hide or remove these warnings? We haven't been able to find anything after our due R&D. We would really not like our clients to see these warnings.

P.S. it's obvious that we cannot remove these permission policies.


问:
Tensorflow Probability is stuck with negative binomial distribution on fit, no error
I have this simple bayesian neural network that gets stuck on .fit(x, y)

```<code>def get_model(input_shape, loss, optimizer, metrics, kl_weight, output_shape):

    inputs = Input(shape=(input_shape))
    x = BatchNormalization()(inputs)
    x = tfpl.DenseVariational(units=128, activation='tanh', make_posterior_fn=get_posterior, make_prior_fn=get_prior, kl_weight=kl_weight)(x)
    count = Dense(1)(x)
    logits = Dense(output_shape, activation = 'sigmoid')(x)
    neg_binom = tfp.layers.DistributionLambda(
            lambda t: tfd.NegativeBinomial(total_count=t[..., 0:1], logits = t[..., 1:]))
    cat = Concatenate(axis=-1)([count, logits])
    outputs = neg_binom(cat)
    model = Model(inputs, outputs)
    model.compile(optimizer=optimizer, loss=loss, metrics=metrics)
    return model
</code>```

I do not get an error, it compiles and when I call model.fit(x,y) I just get:

```<code>Epoch 1/500
</code>```

and it's stuck here forever (about 20 minutes I waited for the longest).

When I use a Poisson Layer, which I did before it starts fitting instantly, an epoch runs about 1s.

What could be the cause of this?

Many thanks for your insights and tips of things to try and debug this behaviour.

Body:
I have this simple bayesian neural network that gets stuck on .fit(x, y)

def get_model(input_shape, loss, optimizer, metrics, kl_weight, output_shape):

    inputs = Input(shape=(input_shape))
    x = BatchNormalization()(inputs)
    x = tfpl.DenseVariational(units=128, activation='tanh', make_posterior_fn=get_posterior, make_prior_fn=get_prior, kl_weight=kl_weight)(x)
    count = Dense(1)(x)
    logits = Dense(output_shape, activation = 'sigmoid')(x)
    neg_binom = tfp.layers.DistributionLambda(
            lambda t: tfd.NegativeBinomial(total_count=t[..., 0:1], logits = t[..., 1:]))
    cat = Concatenate(axis=-1)([count, logits])
    outputs = neg_binom(cat)
    model = Model(inputs, outputs)
    model.compile(optimizer=optimizer, loss=loss, metrics=metrics)
    return model

I do not get an error, it compiles and when I call model.fit(x,y) I just get:

Epoch 1/500

and it's stuck here forever (about 20 minutes I waited for the longest).

When I use a Poisson Layer, which I did before it starts fitting instantly, an epoch runs about 1s.

What could be the cause of this?

Many thanks for your insights and tips of things to try and debug this behaviour.


问:
The directory - files that could conflict
I am new ro reactjs and so i am trying to learn my way through it. I have ran into a problem trying to create a new react project.. i have updated node and npm to the latest version but i keep getting the same error or rather message. Can anyone please help?
the following is the message i keep getting.

```<code>stelg@----MacBook ~ % npx create-react-app monsters-rolodex
The directory monsters-rolodex contains files that could conflict:

  node_modules/
  package-lock.json
  package.json
  public/
  src/

Either try using a new directory name, or remove the files listed above.
</code>```

new to reactjs at the moment

Body:
I am new ro reactjs and so i am trying to learn my way through it. I have ran into a problem trying to create a new react project.. i have updated node and npm to the latest version but i keep getting the same error or rather message. Can anyone please help?
the following is the message i keep getting.

stelg@----MacBook ~ % npx create-react-app monsters-rolodex
The directory monsters-rolodex contains files that could conflict:

  node_modules/
  package-lock.json
  package.json
  public/
  src/

Either try using a new directory name, or remove the files listed above.

new to reactjs at the moment


问:
Module attribute mysteriously appears
```<code>$ python
Python 3.8.10 (default, Nov 14 2022, 12:59:47)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib
>>> urllib.request
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'urllib' has no attribute 'request'
>>> urllib.request
<module 'urllib.request' from '/usr/lib/python3.8/urllib/request.py'>
</code>```

Why is urllib.request recognized as an attribute the second time I try to access it?

Title: Module attribute mysteriously appears

Body:
$ python
Python 3.8.10 (default, Nov 14 2022, 12:59:47)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib
>>> urllib.request
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'urllib' has no attribute 'request'
>>> urllib.request
<module 'urllib.request' from '/usr/lib/python3.8/urllib/request.py'>

Why is urllib.request recognized as an attribute the second time I try to access it?


问:
How to navigate to a page after switching tabs in CupertinoTabBar?
I have a CupertinoTabScaffold which has a tab bar, I use a global key to navigate through the tabs, but I need Navigate to the tab and Navigate the page inside this tab.
I tried to do it via global key and then method but in doesn't work.
After I go to 3 tab i want to go to the page inside the 3 tab, how can I make it?

```<code>GlobalKey<MainScreenState> scakey = GlobalKey<MainScreenState>();
CupertinoTabScaffold(
          controller: _controller,
          key: myKey,
          backgroundColor: Colors.black87,
          tabBar: CupertinoTabBar(
            inactiveColor: Color.fromRGBO(43, 46, 74, 1),
            activeColor: Color.fromRGBO(232, 69, 69, 1),
            iconSize: 27,
            currentIndex: currentIndex,
            onTap: onItemTapped,
            items: const [
              BottomNavigationBarItem(icon: Icon(CupertinoIcons.house), activeIcon: Icon(CupertinoIcons.house_fill)),
              BottomNavigationBarItem(icon: Icon(CupertinoIcons.square_list), activeIcon: Icon(CupertinoIcons.square_list_fill)),
              BottomNavigationBarItem(icon: Icon(CupertinoIcons.cart), activeIcon: Icon(CupertinoIcons.cart_fill)),
              BottomNavigationBarItem(icon: Icon(CupertinoIcons.person), activeIcon: Icon(CupertinoIcons.person_fill)),
            ],
          ),
          tabBuilder: (BuildContext context, int index) {
            print(currentIndex);
            switch (index) {
              case 0:
                return CupertinoTabView(
                  navigatorKey: tabNavKeys[index],
                  builder: (BuildContext context) => HomePage(),
                );
              case 1:
                return CupertinoTabView(
                  navigatorKey: tabNavKeys[1],
                  builder: (BuildContext context) {
                    return const CupertinoPageScaffold(
                      resizeToAvoidBottomInset: false,
                      child: CatalogPage(),
                    );
                  },
                );
              case 2:
                return currentIndex == 2 ? CupertinoTabView(
                  navigatorKey: tabNavKeys[2],
                  builder: (BuildContext context) {
                    return const CupertinoPageScaffold(
                      resizeToAvoidBottomInset: false,
                      child: ShoppingBag(),
                    );
                  },
                ) : Container();
              case 3:
                return CupertinoTabView(
                  navigatorKey: tabNavKeys[3],
                  builder: (BuildContext context) {
                    return const CupertinoPageScaffold(
                      resizeToAvoidBottomInset: false,
                      child: UserProfileScaffold(),
                    );
                  },
                );
              default:
                return Container();
            }
          }),

WebView(
        javascriptMode: JavascriptMode.unrestricted,
        initialUrl: '${link}?token=${Constants.USER_TOKEN}',
        javascriptChannels: {
          JavascriptChannel(
            name: 'WebViewMessage',
            onMessageReceived: (JavascriptMessage message) {
              if (message.message != '') {
                scakey.currentState!.onItemTapped(3); // my navigation method
                // after I go to 3 tab i want to go to the page inside the 3 tab
              }
            },
          ),
        },
      ),
</code>```

Body:
I have a CupertinoTabScaffold which has a tab bar, I use a global key to navigate through the tabs, but I need Navigate to the tab and Navigate the page inside this tab.
I tried to do it via global key and then method but in doesn't work.
After I go to 3 tab i want to go to the page inside the 3 tab, how can I make it?

GlobalKey<MainScreenState> scakey = GlobalKey<MainScreenState>();
CupertinoTabScaffold(
          controller: _controller,
          key: myKey,
          backgroundColor: Colors.black87,
          tabBar: CupertinoTabBar(
            inactiveColor: Color.fromRGBO(43, 46, 74, 1),
            activeColor: Color.fromRGBO(232, 69, 69, 1),
            iconSize: 27,
            currentIndex: currentIndex,
            onTap: onItemTapped,
            items: const [
              BottomNavigationBarItem(icon: Icon(CupertinoIcons.house), activeIcon: Icon(CupertinoIcons.house_fill)),
              BottomNavigationBarItem(icon: Icon(CupertinoIcons.square_list), activeIcon: Icon(CupertinoIcons.square_list_fill)),
              BottomNavigationBarItem(icon: Icon(CupertinoIcons.cart), activeIcon: Icon(CupertinoIcons.cart_fill)),
              BottomNavigationBarItem(icon: Icon(CupertinoIcons.person), activeIcon: Icon(CupertinoIcons.person_fill)),
            ],
          ),
          tabBuilder: (BuildContext context, int index) {
            print(currentIndex);
            switch (index) {
              case 0:
                return CupertinoTabView(
                  navigatorKey: tabNavKeys[index],
                  builder: (BuildContext context) => HomePage(),
                );
              case 1:
                return CupertinoTabView(
                  navigatorKey: tabNavKeys[1],
                  builder: (BuildContext context) {
                    return const CupertinoPageScaffold(
                      resizeToAvoidBottomInset: false,
                      child: CatalogPage(),
                    );
                  },
                );
              case 2:
                return currentIndex == 2 ? CupertinoTabView(
                  navigatorKey: tabNavKeys[2],
                  builder: (BuildContext context) {
                    return const CupertinoPageScaffold(
                      resizeToAvoidBottomInset: false,
                      child: ShoppingBag(),
                    );
                  },
                ) : Container();
              case 3:
                return CupertinoTabView(
                  navigatorKey: tabNavKeys[3],
                  builder: (BuildContext context) {
                    return const CupertinoPageScaffold(
                      resizeToAvoidBottomInset: false,
                      child: UserProfileScaffold(),
                    );
                  },
                );
              default:
                return Container();
            }
          }),

WebView(
        javascriptMode: JavascriptMode.unrestricted,
        initialUrl: '${link}?token=${Constants.USER_TOKEN}',
        javascriptChannels: {
          JavascriptChannel(
            name: 'WebViewMessage',
            onMessageReceived: (JavascriptMessage message) {
              if (message.message != '') {
                scakey.currentState!.onItemTapped(3); // my navigation method
                // after I go to 3 tab i want to go to the page inside the 3 tab
              }
            },
          ),
        },
      ),


问:
Openshift haproxy logformat for ssl logging
Need help with logformat string to be set for haproxy 2.2.48 version used by Openshift 4.10 for logging ssl related attributes for trouble shooting ssl connection failures like sal cert, chiper, ssl error etc. right now it just prints

fe/sni: SSL client certificate not trusted.

Tried enabling the httpslogformat in the ingresscontroller resource, it safely ignores, if i use the httplogformat and apply ssl related  aatributes haproxy fails to start


问:
How can I bind a view-model property to a dynamic resource in WPF app?
I use dynamic resources for localization in my application. It works as expected if I name a resource directly.

```<code><Button Content="{DynamicResource Home}"
              Command="{Binding NavigateHomeCommand}"
              Margin="30 0"/>
</code>```

Still templates localization needs bindings for view-model properties which seem to be incompatible with dynamic resources.
Here's the code example.

```<code><DataTemplate DataType="{x:Type presentation:SideBarItem}"
                  x:Key="OptionsButtonTemplate">
      <Button Command="{Binding NavigateRelatedViewCommand}">
        <Button.Template>
          <ControlTemplate>
            <TextBlock Text="{DynamicResource {Binding Title}}"
                       FontSize="18"/>
          </ControlTemplate>
        </Button.Template>
      </Button>
    </DataTemplate>
</code>```

Is there a workaround for this case?

Body:
I use dynamic resources for localization in my application. It works as expected if I name a resource directly.

<Button Content="{DynamicResource Home}"
              Command="{Binding NavigateHomeCommand}"
              Margin="30 0"/>

Still templates localization needs bindings for view-model properties which seem to be incompatible with dynamic resources.
Here's the code example.

<DataTemplate DataType="{x:Type presentation:SideBarItem}"
                  x:Key="OptionsButtonTemplate">
      <Button Command="{Binding NavigateRelatedViewCommand}">
        <Button.Template>
          <ControlTemplate>
            <TextBlock Text="{DynamicResource {Binding Title}}"
                       FontSize="18"/>
          </ControlTemplate>
        </Button.Template>
      </Button>
    </DataTemplate>

Is there a workaround for this case?


问:
Total rows different after migrating dataset using BigQuery Data Transfer Service
I have a dataset with 40+ tables which I want to migrate from one region to another. I am using BQ transfer service to do the migration. Once I run the job, it is shown as successful but some of the tables have differences like total partitions are different or total number of rows are different. I have tried to redo the transfer and still the same behavior. I did not find anything online and I am very confused on why this is happening and how to solve it.

For example, in the image below, you can see that the total rows and other storage info is different in the destination table. You can see the last modified date on the source which indicates that no new record was inserted. Apart from starting the transfer service, I have no involvement in the process. I tried to look through the logs and no relevant error was found. Transfer service job was also successful.

In the image below, total rows are fine but partition and other info is different.

Any help would be much appreciated.


问:
SwiftSoup with srcset
This code makes a list of image urls from a site, but the thing is, when these images are part of srcsets, all images are not downloaded, just one version. I want to get the best quality image, but I need to get all the images of the srcset first. With this only I get a default version.</p>
```<code>func scrapeImgUrls(site: String) -> [String]{

        let content = try! String(contentsOf: URL(string: site)!)

 var elements = try! (SwiftSoup.parse(content).select("img[src$=.jpg]")).array()

    }
</code>```

Title: SwiftSoup with srcset

Body:
This code makes a list of image urls from a site, but the thing is, when these images are part of srcsets, all images are not downloaded, just one version. I want to get the best quality image, but I need to get all the images of the srcset first. With this only I get a default version.

func scrapeImgUrls(site: String) -> [String]{

        let content = try! String(contentsOf: URL(string: site)!)

 var elements = try! (SwiftSoup.parse(content).select("img[src$=.jpg]")).array()

    }


问:
Compile Cython with zig cc on Windows - linking problem
I have tried to compile a piece of complex code with zig on Windows with no success (referencing this question as a starting point):

```<code>cython base.py
zig build-lib --verbose-link -DMS_WIN64 -dynamic -target x86_64-windows \
    -I c:\python38\include\ -lc c:\python38\python38.dll base.c
</code>```

The output is not very optimistic:

```<code>LLD Link... lld-link: error: undefined symbol: __declspec(dllimport) _Py_RefTotal
>>> referenced by C:\Users\xxx\AppData\Local\zig\o\xxx\base.obj:(_Py_INCREF)
>>> referenced by C:\Users\xxx\AppData\Local\zig\o\xxx\base.obj:(_Py_INCREF)
>>> referenced by C:\Users\xxx\AppData\Local\zig\o\xxx\base.obj:(_Py_DECREF)
>>> referenced 3 more times

lld-link: error: undefined symbol: __declspec(dllimport) _Py_NegativeRefcount
>>> referenced by C:\Users\xxx\AppData\Local\zig\o\xxx\base.obj:(_Py_DECREF)
</code>```

Same Python/C code is compiled and linked perfectly fine with mingw64.
Internet is silent on this topic. Can anyone suggest a path to dig?

UPD 1: The problem seems to be related to enabled _DEBUG macro. _Py_RefTotal and _Py_NegativeRefcount are included when Py_REF_DEBUG is defined (object.h).
This controlled like Py_REF_DEBUG <- Py_DEBUG <- _DEBUG

Source file, generated by Cython, includes Python.h:

```<code>ifdef MS_COREDLL ->
    if defined(_MSC_VER) ->
        if defined(_DEBUG) ->
            pragma comment(lib,"python27_d.lib") ->
                this debug library is missing on default Python setup
</code>```

So the question is changed to: How to disable debug macro while compiling with zig (without Python imports modification)? This is something happened when compiling with mingw.

WORKAROUND

Unfortunately, -U option (undef macro) is not implemented in zig compiler.
The only automated workaround I was able to figure out so far, is to update the code generated by Cython with a simple batch file:

```<code>@echo off

cython base.py

echo #ifdef _DEBUG>header.c
echo   #undef _DEBUG>>header.c
echo #endif>>header.c

type header.c >> base_new.c
type base.c >> base_new.c
del /Q base.c 1>nul 2>&1
del /Q header.c 1>nul 2>&1
move base_new.c base.c 1>nul 2>&1

zig build-lib --verbose-link -DMS_WIN64 -dynamic -target x86_64-windows \
    -I c:\python38\include\ -lc c:\python38\python38.dll base.c
</code>```

Body:
I have tried to compile a piece of complex code with zig on Windows with no success (referencing this question as a starting point):

cython base.py
zig build-lib --verbose-link -DMS_WIN64 -dynamic -target x86_64-windows \
    -I c:\python38\include\ -lc c:\python38\python38.dll base.c

The output is not very optimistic:

LLD Link... lld-link: error: undefined symbol: __declspec(dllimport) _Py_RefTotal
>>> referenced by C:\Users\xxx\AppData\Local\zig\o\xxx\base.obj:(_Py_INCREF)
>>> referenced by C:\Users\xxx\AppData\Local\zig\o\xxx\base.obj:(_Py_INCREF)
>>> referenced by C:\Users\xxx\AppData\Local\zig\o\xxx\base.obj:(_Py_DECREF)
>>> referenced 3 more times

lld-link: error: undefined symbol: __declspec(dllimport) _Py_NegativeRefcount
>>> referenced by C:\Users\xxx\AppData\Local\zig\o\xxx\base.obj:(_Py_DECREF)

Same Python/C code is compiled and linked perfectly fine with mingw64.
Internet is silent on this topic. Can anyone suggest a path to dig?

UPD 1: The problem seems to be related to enabled _DEBUG macro. _Py_RefTotal and _Py_NegativeRefcount are included when Py_REF_DEBUG is defined (object.h).
This controlled like Py_REF_DEBUG <- Py_DEBUG <- _DEBUG

Source file, generated by Cython, includes Python.h:

ifdef MS_COREDLL ->
    if defined(_MSC_VER) ->
        if defined(_DEBUG) ->
            pragma comment(lib,"python27_d.lib") ->
                this debug library is missing on default Python setup

So the question is changed to: How to disable debug macro while compiling with zig (without Python imports modification)? This is something happened when compiling with mingw.

WORKAROUND

Unfortunately, -U option (undef macro) is not implemented in zig compiler.
The only automated workaround I was able to figure out so far, is to update the code generated by Cython with a simple batch file:

@echo off

cython base.py

echo #ifdef _DEBUG>header.c
echo   #undef _DEBUG>>header.c
echo #endif>>header.c

type header.c >> base_new.c
type base.c >> base_new.c
del /Q base.c 1>nul 2>&1
del /Q header.c 1>nul 2>&1
move base_new.c base.c 1>nul 2>&1

zig build-lib --verbose-link -DMS_WIN64 -dynamic -target x86_64-windows \
    -I c:\python38\include\ -lc c:\python38\python38.dll base.c