问:
C# - Several Threads Stuck Waiting for LowLevelLifoSemaphore.WaitNative
I have a old DotNet 6 application running on linux that does a ton of synchronous DB calls and I am trying to debug a threading issue and I noticed that a lot of threads have the following callstack:

```<code>System.Private.CoreLib!System.Threading.LowLevelLifoSemaphore.WaitNative(class Microsoft.Win32.SafeHandles.SafeWaitHandle,int32)
  System.Private.CoreLib!System.Threading.LowLevelLifoSemaphore.WaitForSignal(int32)
  System.Private.CoreLib!System.Threading.LowLevelLifoSemaphore.Wait(int32,bool)
  System.Private.CoreLib!System.Threading.PortableThreadPool+WorkerThread.WorkerThreadStart()
</code>```

That's the whole callstack, and there are many threads with this exact same stack.  What is this LowLevelLifoSemaphore.WaitNative about?  Is there some kind of low level deadlock going on?

Body:
I have a old DotNet 6 application running on linux that does a ton of synchronous DB calls and I am trying to debug a threading issue and I noticed that a lot of threads have the following callstack:

System.Private.CoreLib!System.Threading.LowLevelLifoSemaphore.WaitNative(class Microsoft.Win32.SafeHandles.SafeWaitHandle,int32)
  System.Private.CoreLib!System.Threading.LowLevelLifoSemaphore.WaitForSignal(int32)
  System.Private.CoreLib!System.Threading.LowLevelLifoSemaphore.Wait(int32,bool)
  System.Private.CoreLib!System.Threading.PortableThreadPool+WorkerThread.WorkerThreadStart()

That's the whole callstack, and there are many threads with this exact same stack.  What is this LowLevelLifoSemaphore.WaitNative about?  Is there some kind of low level deadlock going on?


来源: stackexchange

问:
How indent cells in exporting excel , using maatwebsite
In my program with  laravel 8 ,  i use maatwebsite for exporting  an excel file . all things work well and  i can export excel  file but i want text in cells of exported file be indented .

I found no subject about indenting cells with maatwebsite . it is appriciated if have any idea .

ContentLicense: CC BY-SA 4.0


问:
Bitcoin Price Prediction using LSTM
So I wanted to predict the future price of bitcoin using LSTM but as I am new to this domain I'm stuck at what to do in order to print just the price of future lets say I want to predict the price for 3 months ahead from now what should i do in order to just get the closing price for BTC after 3 months from now?
It will be really appreciated if you guys can help me with this problem.</p>
```<code>    train_data, test_data = train_test_split(df, test_size=test_size)
    X_train = extract_window_data(train_data, window_len, zero_base)
    X_test = extract_window_data(test_data, window_len, zero_base)
    y_train = train_data[target_col][window_len:].values
    y_test = test_data[target_col][window_len:].values
    if zero_base:
        y_train = y_train / train_data[target_col][:-window_len].values - 1
        y_test = y_test / test_data[target_col][:-window_len].values - 1

    return train_data, test_data, X_train, X_test, y_train, y_test

def build_lstm_model(input_data, output_size, neurons=100, activ_func='linear',
                     dropout=0.2, loss='mse', optimizer='adam'):
    model = Sequential()
    model.add(LSTM(neurons, input_shape=(input_data.shape[1], input_data.shape[2])))
    model.add(Dropout(dropout))
    model.add(Dense(units=output_size))
    model.add(Activation(activ_func))

    model.compile(loss=loss, optimizer=optimizer)
    return model

np.random.seed(42)
window_len = 5
test_size = 0.2
zero_base = True
lstm_neurons = 100
epochs = 200
batch_size = 32
loss = 'mse'
dropout = 0.2
optimizer = 'adam'

train, test, X_train, X_test, y_train, y_test = prepare_data(
    hist, target_col, window_len=window_len, zero_base=zero_base, test_size=test_size)
print(X_test)

model = build_lstm_model(
    X_train, output_size=1, neurons=lstm_neurons, dropout=dropout, loss=loss,
    optimizer=optimizer)
history = model.fit(
    X_train, y_train, validation_data=(X_test, y_test), epochs=epochs, batch_size=batch_size, verbose=1, shuffle=True)
preds = test[target_col].values[:-window_len] * (preds + 1)
preds = pd.Series(index=targets.index, data=preds)
print(test)
line_plot(targets, preds, 'actual', 'prediction', lw=3)
</code>```

Title: Bitcoin Price Prediction using LSTM

Body:
So I wanted to predict the future price of bitcoin using LSTM but as I am new to this domain I'm stuck at what to do in order to print just the price of future lets say I want to predict the price for 3 months ahead from now what should i do in order to just get the closing price for BTC after 3 months from now?
It will be really appreciated if you guys can help me with this problem.

    train_data, test_data = train_test_split(df, test_size=test_size)
    X_train = extract_window_data(train_data, window_len, zero_base)
    X_test = extract_window_data(test_data, window_len, zero_base)
    y_train = train_data[target_col][window_len:].values
    y_test = test_data[target_col][window_len:].values
    if zero_base:
        y_train = y_train / train_data[target_col][:-window_len].values - 1
        y_test = y_test / test_data[target_col][:-window_len].values - 1

    return train_data, test_data, X_train, X_test, y_train, y_test

def build_lstm_model(input_data, output_size, neurons=100, activ_func='linear',
                     dropout=0.2, loss='mse', optimizer='adam'):
    model = Sequential()
    model.add(LSTM(neurons, input_shape=(input_data.shape[1], input_data.shape[2])))
    model.add(Dropout(dropout))
    model.add(Dense(units=output_size))
    model.add(Activation(activ_func))

    model.compile(loss=loss, optimizer=optimizer)
    return model

np.random.seed(42)
window_len = 5
test_size = 0.2
zero_base = True
lstm_neurons = 100
epochs = 200
batch_size = 32
loss = 'mse'
dropout = 0.2
optimizer = 'adam'

train, test, X_train, X_test, y_train, y_test = prepare_data(
    hist, target_col, window_len=window_len, zero_base=zero_base, test_size=test_size)
print(X_test)

model = build_lstm_model(
    X_train, output_size=1, neurons=lstm_neurons, dropout=dropout, loss=loss,
    optimizer=optimizer)
history = model.fit(
    X_train, y_train, validation_data=(X_test, y_test), epochs=epochs, batch_size=batch_size, verbose=1, shuffle=True)
preds = test[target_col].values[:-window_len] * (preds + 1)
preds = pd.Series(index=targets.index, data=preds)
print(test)
line_plot(targets, preds, 'actual', 'prediction', lw=3)


问:
Mount existing Solr index/collections with data to Bitnami Solr on Kubernetes
For testing purposes, I'm using Docker Desktop on Windows 10 . “Use the WSL2 based engine” setting is on.
I was able to mount a persistent volume claim with a host path c:_solrData to Bitnami Solr
After installation bitnami solr

```<code>helm install solr -f values.yaml azure-marketplace/solr
</code>```

I’m able to see a new collection my-collection_shard1_replica_n1 in the c:_solrData\server\solr\ folder
I have some indexes with data, and I would like to mount them to solr.
I tried to copy my indexes with data to c:_solrData\server\solr\ folder but after

```<code>kubectl delete pod solr-0
</code>```

I’m able to see only one collection my-collection_shard1_replica_n1 in the c:_solrData\server\solr\ folder

Could you please let me know the correct way to add collections to bitnami solr? I would like that after pod/node "restart" we will have all data in our collections.

Body:
For testing purposes, I'm using Docker Desktop on Windows 10 . “Use the WSL2 based engine” setting is on.
I was able to mount a persistent volume claim with a host path c:_solrData to Bitnami Solr
After installation bitnami solr

helm install solr -f values.yaml azure-marketplace/solr

I’m able to see a new collection my-collection_shard1_replica_n1 in the c:_solrData\server\solr\ folder
I have some indexes with data, and I would like to mount them to solr.
I tried to copy my indexes with data to c:_solrData\server\solr\ folder but after

kubectl delete pod solr-0

I’m able to see only one collection my-collection_shard1_replica_n1 in the c:_solrData\server\solr\ folder

Could you please let me know the correct way to add collections to bitnami solr? I would like that after pod/node "restart" we will have all data in our collections.


问:
ReactJS Mapping
I'm in the Project component section of my portfolio and trying to connect the weblinks to the 4 different projects.

```<code>            <div id="portfolio-wrapper" className="bgrid-quarters s-bgrid-thirds cf">
              {
              resumeData.portfolio && resumeData.portfolio.map((item) => {
                return(
                  <div className="columns portfolio-item">
                  <div className="item-wrap">
                      <img src={`${item.imgurl}`} alt="" className="item-imgurl"/>
                      <div className="overlay">
                        <div className="portfolio-item-meta">
                          <h5>{item.name}</h5>
                          <p>{item.description}</p>
                          <h6>{item.url}</h6>
                        </div>
                      </div>
                  </div>
                </div>
              )
            })
          }

</code>```
```<code>      {
        "name":"Zesty Investy",
        "description":"Investment calculator that helps plan finances for retirement",
        "url":"https://grocha78.github.io/Zesty-Investy-Calculonesty/",
        "imgurl":"/assets/zestyinvesty.png"
      },
      {
        "name":"Art Garage",
        "description":"The place that brings artists and potential buyers together.",
        "url":"https://art-garage-app.herokuapp.com/",
        "imgurl":"src/assets/artgarage.png"
      },
      {
        "name":"Tech Blog",
        "description":"A CMS-style blog site similar to a Wordpress site, where developers can publish their blog posts and comment on other developers’ posts as well.",
        "url":"https://not-another-tech-blog-78.herokuapp.com/",
        "imgurl":"src/assets/techblog.png"
      },
      {
        "name":"Weather App",
        "description":"Weather app that provides current and future weather forecasts in cities.",
        "url":"https://grocha78.github.io/How-Is-It-Over-There/",
        "imgurl":"src/assets/weatherapp.png"
      }
    ],
</code>```

How can the clickable web links for each project show individually? Right now it just shows them but they are unclickable.

I've tried adding 4 different sections but this just shows 4 rows of the image shown in the pictures of my Portfolio section.
I've added the weblink to the href section for each project and it does show only the 1 row that is currently seen but the links are all bunched together and it doesn't work.
I'm not too sure on what to do next and I'd appreciate any help.

Title: ReactJS Mapping

Body:
I'm in the Project component section of my portfolio and trying to connect the weblinks to the 4 different projects.

              {
              resumeData.portfolio && resumeData.portfolio.map((item) => {
                return(

                      <img src={`${item.imgurl}`} alt="" className="item-imgurl"/>

{item.name}

{item.description}

{item.url}

              )
            })
          }

      {
        "name":"Zesty Investy",
        "description":"Investment calculator that helps plan finances for retirement",
        "url":"https://grocha78.github.io/Zesty-Investy-Calculonesty/",
        "imgurl":"/assets/zestyinvesty.png"
      },
      {
        "name":"Art Garage",
        "description":"The place that brings artists and potential buyers together.",
        "url":"https://art-garage-app.herokuapp.com/",
        "imgurl":"src/assets/artgarage.png"
      },
      {
        "name":"Tech Blog",
        "description":"A CMS-style blog site similar to a Wordpress site, where developers can publish their blog posts and comment on other developers’ posts as well.",
        "url":"https://not-another-tech-blog-78.herokuapp.com/",
        "imgurl":"src/assets/techblog.png"
      },
      {
        "name":"Weather App",
        "description":"Weather app that provides current and future weather forecasts in cities.",
        "url":"https://grocha78.github.io/How-Is-It-Over-There/",
        "imgurl":"src/assets/weatherapp.png"
      }
    ],

How can the clickable web links for each project show individually? Right now it just shows them but they are unclickable.

I've tried adding 4 different <a sections but this just shows 4 rows of the image shown in the pictures of my Portfolio section.
I've added the weblink to the href section for each project and it does show only the 1 row that is currently seen but the links are all bunched together and it doesn't work.
I'm not too sure on what to do next and I'd appreciate any help.


问:
What is causing the error: Bundler & Minifier error 0: Expected '}'
During a Jenkins build, I am getting the following errors:

Bundler: Begin processing bundleconfig.json

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(29,21,29,21): Bundler & Minifier error 0: Expected '}': ... [/src/Vizualization/Vizualization.csproj]

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(32,33,32,33): Bundler & Minifier error 0: Expected ';' [/src/Vizualization/Vizualization.csproj]

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(32,33,32,33): Bundler & Minifier error 0: Expected expression: : [/src/Vizualization/Vizualization.csproj]

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(46,14,46,14): Bundler & Minifier error 0: Expected '}': ; [/src/Vizualization/Vizualization.csproj]

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(61,5,61,5): Bundler & Minifier error 0: Expected ')': } [/src/Vizualization/Vizualization.csproj]

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(61,6,61,6): Bundler & Minifier error 0: Expected ')': ; [/src/Vizualization/Vizualization.csproj]

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(62,1,62,1): Bundler & Minifier error 0: Syntax error: } [/src/Vizualization/Vizualization.csproj]

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(62,2,62,2): Bundler & Minifier error 0: Expected expression: ) [/src/Vizualization/Vizualization.csproj]

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(62,3,62,3): Bundler & Minifier error 0: Expected expression: ) [/src/Vizualization/Vizualization.csproj]

Bundler: Done processing bundleconfig.json

I do not get this when I build locally.  Each are triggered by dotnet build "Vizualization.csproj" -c Release -o /app/build

I've looked over the code and do not see any mismatched curly braces.  Because of this and the fact that I cannot reproduce it locally, the MRE is the file, but it is small (see source of datatables-knockout-binding.min.js below)

```<code>(function (factory) {
    if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
        factory(require("jquery"), require("knockout"));
    }
    else if (typeof define === "function" && define["amd"]) {
        define(["jquery", "knockout"], factory);
    }
    else {
        factory($, ko);
    }
}(function ($, ko) {
    function getOptions(allBindings) {
        return allBindings.get("tableOptions") || {};
    }

    ko.bindingHandlers.datatable = {
        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            const data = valueAccessor();
            const update = () => {
                const oldTable = $(element).closest("table").DataTable();
                const pageInfo = oldTable.page.info();
                const page = pageInfo.page;
                const pageLength = pageInfo.length;
                const order = oldTable.order();
                const search = oldTable.search();
                oldTable.destroy();
                ko.bindingHandlers.foreach.update(element, valueAccessor, allBindings, viewModel, bindingContext);
                const tableOptions = {
                    ...getOptions(allBindings),
                    order,
                    pageLength,
                    deferLoading: true
                };

                if (tableOptions.search) {
                    tableOptions.search.search = search;
                }
                else {
                    tableOptions.search = { search };
                }

                $(element).closest("table")
                    .DataTable(tableOptions)
                    .page(page)
                    .draw();
            };

            data.subscribe(update, null, "arrayChange");
            ko.utils.arrayForEach(element.childNodes, function (node) {
                if (node && node.nodeType !== 1 /*element*/) {
                    node.parentNode.removeChild(node);
                }
            });

            ko.bindingHandlers.foreach.init(element, valueAccessor, allBindings, viewModel, bindingContext);
            ko.bindingHandlers.foreach.update(element, valueAccessor, allBindings, viewModel, bindingContext);
            const tableOptions = getOptions(allBindings);
            $(element).closest("table").DataTable(tableOptions);
            return { controlsDescendantBindings: true };
        }
    };
}));
</code>```

Body:
During a Jenkins build, I am getting the following errors:

Bundler: Begin processing bundleconfig.json

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(29,21,29,21): Bundler & Minifier error 0: Expected '}': ... [/src/Vizualization/Vizualization.csproj]

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(32,33,32,33): Bundler & Minifier error 0: Expected ';' [/src/Vizualization/Vizualization.csproj]

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(32,33,32,33): Bundler & Minifier error 0: Expected expression: : [/src/Vizualization/Vizualization.csproj]

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(46,14,46,14): Bundler & Minifier error 0: Expected '}': ; [/src/Vizualization/Vizualization.csproj]

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(61,5,61,5): Bundler & Minifier error 0: Expected ')': } [/src/Vizualization/Vizualization.csproj]

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(61,6,61,6): Bundler & Minifier error 0: Expected ')': ; [/src/Vizualization/Vizualization.csproj]

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(62,1,62,1): Bundler & Minifier error 0: Syntax error: } [/src/Vizualization/Vizualization.csproj]

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(62,2,62,2): Bundler & Minifier error 0: Expected expression: ) [/src/Vizualization/Vizualization.csproj]

/src/Vizualization/wwwroot/js/datatables-knockout-binding.min.js(62,3,62,3): Bundler & Minifier error 0: Expected expression: ) [/src/Vizualization/Vizualization.csproj]

Bundler: Done processing bundleconfig.json

I do not get this when I build locally.  Each are triggered by dotnet build "Vizualization.csproj" -c Release -o /app/build

I've looked over the code and do not see any mismatched curly braces.  Because of this and the fact that I cannot reproduce it locally, the MRE is the file, but it is small (see source of datatables-knockout-binding.min.js below)

(function (factory) {
    if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
        factory(require("jquery"), require("knockout"));
    }
    else if (typeof define === "function" && define["amd"]) {
        define(["jquery", "knockout"], factory);
    }
    else {
        factory($, ko);
    }
}(function ($, ko) {
    function getOptions(allBindings) {
        return allBindings.get("tableOptions") || {};
    }

    ko.bindingHandlers.datatable = {
        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            const data = valueAccessor();
            const update = () => {
                const oldTable = $(element).closest("table").DataTable();
                const pageInfo = oldTable.page.info();
                const page = pageInfo.page;
                const pageLength = pageInfo.length;
                const order = oldTable.order();
                const search = oldTable.search();
                oldTable.destroy();
                ko.bindingHandlers.foreach.update(element, valueAccessor, allBindings, viewModel, bindingContext);
                const tableOptions = {
                    ...getOptions(allBindings),
                    order,
                    pageLength,
                    deferLoading: true
                };

                if (tableOptions.search) {
                    tableOptions.search.search = search;
                }
                else {
                    tableOptions.search = { search };
                }

                $(element).closest("table")
                    .DataTable(tableOptions)
                    .page(page)
                    .draw();
            };

            data.subscribe(update, null, "arrayChange");
            ko.utils.arrayForEach(element.childNodes, function (node) {
                if (node && node.nodeType !== 1 /*element*/) {
                    node.parentNode.removeChild(node);
                }
            });

            ko.bindingHandlers.foreach.init(element, valueAccessor, allBindings, viewModel, bindingContext);
            ko.bindingHandlers.foreach.update(element, valueAccessor, allBindings, viewModel, bindingContext);
            const tableOptions = getOptions(allBindings);
            $(element).closest("table").DataTable(tableOptions);
            return { controlsDescendantBindings: true };
        }
    };
}));


问:
Testing authenticated route with sinon never goes through to controller
I'm trying to unit test a expressjs route that should just check if the response has status with value 200 and has property 'success' set to true.
This response should be returned from the last method in middleware chain: UserController.findOne.

```<code>router.get('/:email', ifAuthenticated, UserController.findOne);
</code>```

The request has to go through passportjs middleware ifAuthenticated for authentication check.

The middleware in question:

```<code>export const ifAuthenticated = (req, res, next) => {
  if (req.isAuthenticated()) return next();
  return ReE(res, { 'message': 'Not authorized' }, 401);
}
</code>```

The test case with relevant code:

```<code>beforeEach(() => {
  authenticate = sinon.stub(passport, 'authenticate').returns(() => { });
});

afterEach(() => {
  authenticate.restore();
});

describe.only('Find user api tests', () => {
  const result = {
    "success": true,
    "user": {
      "id": "58557283-610d-4879-b65b-0125db36d763",
      "firstName": "Mac",
      "lastName": "Ole",
      "email": "test@a.pl",
      "phone": 123456789,
    }
  }

  beforeEach(() => {
    query = sinon.stub(userController, 'findOne').resolves(result);
    authenticate.yields(null, { email: 'test@a.pl' });
    sinon.stub(authMiddleware, 'ifAuthenticated').callsFake((req, res, next) => next());
  });

  afterEach(() => {
    query.restore();
    authenticate.restore();
  });

  it('Should return one user', (done) => {
    chai.request(server)
      .get('/v1/users/test@a.pl')
      .end(function (err, res) {
        if (err) return done(err);
        res.should.have.status(200);
        res.body.should.have.property('success').eq(true);
        done();
      });
  })
})
</code>```

The issue is that no matter what I try, the test always fails and returns from the ifAuthenticated middleware with status 401 even though it is stubbed:

```<code>sinon.stub(authMiddleware, 'ifAuthenticated').callsFake((req, res, next) => next());
</code>```

Test result:

```<code>Uncaught AssertionError: expected Response{ domain: null, …(35), …(1) } to have status code 200 but got 401
</code>```

What I'd like to achieve is for the stubbed middleware to return next() and go through to controller.

It is possible I'm missing something trivial but don't really know anymore where to look, so any advice is much appreciated.

Do you have any idea what am I missing?

Body:
I'm trying to unit test a expressjs route that should just check if the response has status with value 200 and has property 'success' set to true.
This response should be returned from the last method in middleware chain: UserController.findOne.

router.get('/:email', ifAuthenticated, UserController.findOne);

The request has to go through passportjs middleware ifAuthenticated for authentication check.

The middleware in question:

export const ifAuthenticated = (req, res, next) => {
  if (req.isAuthenticated()) return next();
  return ReE(res, { 'message': 'Not authorized' }, 401);
}

The test case with relevant code:

beforeEach(() => {
  authenticate = sinon.stub(passport, 'authenticate').returns(() => { });
});

afterEach(() => {
  authenticate.restore();
});

describe.only('Find user api tests', () => {
  const result = {
    "success": true,
    "user": {
      "id": "58557283-610d-4879-b65b-0125db36d763",
      "firstName": "Mac",
      "lastName": "Ole",
      "email": "test@a.pl",
      "phone": 123456789,
    }
  }

  beforeEach(() => {
    query = sinon.stub(userController, 'findOne').resolves(result);
    authenticate.yields(null, { email: 'test@a.pl' });
    sinon.stub(authMiddleware, 'ifAuthenticated').callsFake((req, res, next) => next());
  });

  afterEach(() => {
    query.restore();
    authenticate.restore();
  });

  it('Should return one user', (done) => {
    chai.request(server)
      .get('/v1/users/test@a.pl')
      .end(function (err, res) {
        if (err) return done(err);
        res.should.have.status(200);
        res.body.should.have.property('success').eq(true);
        done();
      });
  })
})

The issue is that no matter what I try, the test always fails and returns from the ifAuthenticated middleware with status 401 even though it is stubbed:

sinon.stub(authMiddleware, 'ifAuthenticated').callsFake((req, res, next) => next());

Test result:

Uncaught AssertionError: expected Response{ domain: null, …(35), …(1) } to have status code 200 but got 401

What I'd like to achieve is for the stubbed middleware to return next() and go through to controller.

It is possible I'm missing something trivial but don't really know anymore where to look, so any advice is much appreciated.

Do you have any idea what am I missing?


问:
Upload files to orders backend in woocomerce
I have been searching for a solution to allow me to upload files via the order page backend
we do artwork for most of our orders and would like to be able to manually add the file into the already processing orders backend, this is mainly for our purposes when printing jobsheets etc, but if the customer has an account be handy for them to access it to (but not to important)
i have searched for plugins but all seem to be for frontend rather than backend.
only way i think could be done is via custom field which i have tried but failed

im new to this site so i hope this question is allowed sorry if it is not

Tried implementing via custom field backend but did not work


问:
Cannot connect Npgsql to Postgres running on Docker
I have Postgres running on Docker, I'm trying to update the DB with EntityFramework and I get an error in the Package Manager Console: Failed to connect to 172.17.0.2:5432. The postgres was created directly in Docker Desktop app.

```<code>PM> Update-Database
Build started...
Build succeeded.
Npgsql.NpgsqlException (0x80004005): Failed to connect to 172.17.0.2:5432
 ---> System.TimeoutException: Timeout during connection attempt
   at Npgsql.Internal.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.Internal.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.Internal.NpgsqlConnector.RawOpen(SslMode sslMode, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken, Boolean isFirstAttempt)
   at Npgsql.Internal.NpgsqlConnector.<Open>g__OpenCore|208_1(NpgsqlConnector conn, SslMode sslMode, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken, Boolean isFirstAttempt)
   at Npgsql.Internal.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.UnpooledDataSource.Get(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.<Open>g__OpenAsync|45_0(Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.Open()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists(Boolean async, CancellationToken cancellationToken)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists(Boolean async, CancellationToken cancellationToken)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Failed to connect to 172.17.0.2:5432
</code>```

Program.cs

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseNpgsql(builder.Configuration.GetConnectionString("AppDbConnection")));
```
<p>Connection string in appsettings.json</p>
<pre class="lang-json prettyprint-override"><code>"ConnectionStrings": {
    "AppDbConnection": "Host=172.17.0.2; Port=5432; Database=MyNewDb; Username=postgres; Password=postgrespw;"
  }
</code>```

I checked on what ip and port the container is running:

❯ docker ps
CONTAINER ID   IMAGE             COMMAND                  CREATED             STATUS             PORTS                           NAMES
f9b7485b6473   dpage/pgadmin4    "/entrypoint.sh"         59 minutes ago      Up 58 minutes      443/tcp, 0.0.0.0:5050->80/tcp   pgadmin4
f1422d67616e   postgres:latest   "docker-entrypoint.s…"   About an hour ago   Up About an hour   0.0.0.0:49153->5432/tcp         postgres-O7pV

❯ docker inspect f1422 | grep IPAddress
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.2",
                    "IPAddress": "172.17.0.2",

❯ docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
5a77b8e238bc   bridge    bridge    local
aae4971464e6   host      host      local
59c3a23f98d4   none      null      local
```

Body:
I have Postgres running on Docker, I'm trying to update the DB with EntityFramework and I get an error in the Package Manager Console: Failed to connect to 172.17.0.2:5432. The postgres was created directly in Docker Desktop app.

PM> Update-Database
Build started...
Build succeeded.
Npgsql.NpgsqlException (0x80004005): Failed to connect to 172.17.0.2:5432
 ---> System.TimeoutException: Timeout during connection attempt
   at Npgsql.Internal.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.Internal.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.Internal.NpgsqlConnector.RawOpen(SslMode sslMode, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken, Boolean isFirstAttempt)
   at Npgsql.Internal.NpgsqlConnector.<Open>g__OpenCore|208_1(NpgsqlConnector conn, SslMode sslMode, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken, Boolean isFirstAttempt)
   at Npgsql.Internal.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.UnpooledDataSource.Get(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.<Open>g__OpenAsync|45_0(Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.Open()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists(Boolean async, CancellationToken cancellationToken)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists(Boolean async, CancellationToken cancellationToken)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Failed to connect to 172.17.0.2:5432

Program.cs

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseNpgsql(builder.Configuration.GetConnectionString("AppDbConnection")));

Connection string in appsettings.json

"ConnectionStrings": {
    "AppDbConnection": "Host=172.17.0.2; Port=5432; Database=MyNewDb; Username=postgres; Password=postgrespw;"
  }

I checked on what ip and port the container is running:

❯ docker ps
CONTAINER ID   IMAGE             COMMAND                  CREATED             STATUS             PORTS                           NAMES
f9b7485b6473   dpage/pgadmin4    "/entrypoint.sh"         59 minutes ago      Up 58 minutes      443/tcp, 0.0.0.0:5050->80/tcp   pgadmin4
f1422d67616e   postgres:latest   "docker-entrypoint.s…"   About an hour ago   Up About an hour   0.0.0.0:49153->5432/tcp         postgres-O7pV

❯ docker inspect f1422 | grep IPAddress
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.2",
                    "IPAddress": "172.17.0.2",

❯ docker network ls
NETWORK ID     NAME      DRIVER    SCOPE
5a77b8e238bc   bridge    bridge    local
aae4971464e6   host      host      local
59c3a23f98d4   none      null      local


问:
How do I filter a nested array to display in a navigation list?
I have a Json File called customerData filled with a nested array. When I am displaying this I want to filter the array that is nested inside the first Array. I have already filtered the first array.

The flow of data goes from customerData.json to Customer.swift to ModelData.swift to Dashboard.swift.

I included a photo of my display.

Here is my Json data called customerData:

```<code>[
    {
        "name":"Michael",
        "id": 101,
        "category": "Admin",
        "isFeatured": true,

        "staff":[
            {
                "firstName": "Zeus",
                "lastName": "Lightening",
                "id": 106,
                "day": "Tuesday",
                "phoneNumber": "123-456-7890"
            },
            {
                "firstName": "Poseidon",
                "lastName": "Sea",
                "id": 107,
                "day": "Sunday",
                "phoneNumber": "123-456-7890"
            }

        ]
    },
    {
        "name":"Caleb",
        "id": 102,
        "category": "Tech",
        "isFeatured": true,

        "staff":[
            {
                "firstName": "Hera",
                "lastName": "marriage",
                "id": 108,
                "day": "Monday",
                "phoneNumber": "123-456-7890"
            }, {
                "firstName": "Athena",
                "lastName": "Wisdoem",
                "id": 109,
                "day": "Sunday",
                "phoneNumber": "123-456-7890"
            }
        ]
    }
]
</code>```

I then have a swift file called Customer:

```<code>import Foundation
import SwiftUI
import CoreLocation

struct Customer: Hashable, Codable, Identifiable {

    var id: Int
    var name: String

    var staff: [Person]

    struct Person: Hashable, Codable, Identifiable  {
        var day: String
        var firstName: String
        var lastName: String
        var id: Int
        var phoneNumber: String
    }
}
</code>```

Then I have another swift file called ModelData:

```<code>import Foundation
import Combine

var customers: [Customer] = load("customerData.json")
var person: [Customer.Person] = load("customerData.json")
</code>```

Then I have a swift UIView called Dashboard. This is where I want to display the lists. There is a filtered list already in Dashboard.swift. There is some commented out Code of the filter that does not work.

```<code>import SwiftUI
import Foundation

struct Dashboard: View {
    @State var person = [Customer.Person]()

    var filterdRoutes:[Customer.Person]{
        person.filter() { filteredCustomer in
          (filteredCustomer.day == "Tuesday")
        }
    }

    var filterdTech:[Customer]{
        customers.filter { filteredCustomer in
            (filteredCustomer.name == "Michael")        }
    }

    var body: some View {
        NavigationView {
            List{
                ForEach(filterdTech) { department in
                    Section(header: Text(department.name)){
                                ForEach(filterdRoutes) { filter1 in

                        NavigationLink(destination: RouteDetail(person: filter1)) {
                            RouteRow(person: filter1)
                        }
                        }
                    }
                }
            }

        }
    }
}
</code>```

Screenshot

Body:
I have a Json File called customerData filled with a nested array. When I am displaying this I want to filter the array that is nested inside the first Array. I have already filtered the first array.

The flow of data goes from customerData.json to Customer.swift to ModelData.swift to Dashboard.swift.

I included a photo of my display.

Here is my Json data called customerData:

[
    {
        "name":"Michael",
        "id": 101,
        "category": "Admin",
        "isFeatured": true,

        "staff":[
            {
                "firstName": "Zeus",
                "lastName": "Lightening",
                "id": 106,
                "day": "Tuesday",
                "phoneNumber": "123-456-7890"
            },
            {
                "firstName": "Poseidon",
                "lastName": "Sea",
                "id": 107,
                "day": "Sunday",
                "phoneNumber": "123-456-7890"
            }

        ]
    },
    {
        "name":"Caleb",
        "id": 102,
        "category": "Tech",
        "isFeatured": true,

        "staff":[
            {
                "firstName": "Hera",
                "lastName": "marriage",
                "id": 108,
                "day": "Monday",
                "phoneNumber": "123-456-7890"
            }, {
                "firstName": "Athena",
                "lastName": "Wisdoem",
                "id": 109,
                "day": "Sunday",
                "phoneNumber": "123-456-7890"
            }
        ]
    }
]

I then have a swift file called Customer:

import Foundation
import SwiftUI
import CoreLocation

struct Customer: Hashable, Codable, Identifiable {

    var id: Int
    var name: String

    var staff: [Person]

    struct Person: Hashable, Codable, Identifiable  {
        var day: String
        var firstName: String
        var lastName: String
        var id: Int
        var phoneNumber: String
    }
}

Then I have another swift file called ModelData:

import Foundation
import Combine

var customers: [Customer] = load("customerData.json")
var person: [Customer.Person] = load("customerData.json")

Then I have a swift UIView called Dashboard. This is where I want to display the lists. There is a filtered list already in Dashboard.swift. There is some commented out Code of the filter that does not work.

import SwiftUI
import Foundation

struct Dashboard: View {
    @State var person = [Customer.Person]()

    var filterdRoutes:[Customer.Person]{
        person.filter() { filteredCustomer in
          (filteredCustomer.day == "Tuesday")
        }
    }

    var filterdTech:[Customer]{
        customers.filter { filteredCustomer in
            (filteredCustomer.name == "Michael")        }
    }

    var body: some View {
        NavigationView {
            List{
                ForEach(filterdTech) { department in
                    Section(header: Text(department.name)){
                                ForEach(filterdRoutes) { filter1 in

                        NavigationLink(destination: RouteDetail(person: filter1)) {
                            RouteRow(person: filter1)
                        }
                        }
                    }
                }
            }

        }
    }
}

Screenshot


问:
"GET" name search does not return desired customer result using the HighRise API
See these 2 videos which explain the real problem:

https://watch.screencastify.com/v/PBrkqxnIHLJ3E3TiOvRQ

https://watch.screencastify.com/v/p2Ul86Pm6Gq4M9UwD9zN

I have a NEW customer with the name "Greg Nel". When I want to create OR if I want to search for this customer in HighRise using their API, it returns the result "Gregory Snell" which is a different person BUT in his name it contains all the same letters of the NEW customer.

How can I write this GET request to get the correct result?

I have tried these with no good results:

```<code>/people/search.xml?term=Greg Nel
/people/search.xml?term="Greg Nel" (using quotes)
/people/search.xml?criteria[first-name]=Greg&criteria[last-name]=Nel
</code>```

I expect the API to return me the result of either:

-Null (if the exact search term is NOT found), or
-the correct result which would be the profile ID data of the customer that I am looking for

Body:
See these 2 videos which explain the real problem:

https://watch.screencastify.com/v/PBrkqxnIHLJ3E3TiOvRQ

https://watch.screencastify.com/v/p2Ul86Pm6Gq4M9UwD9zN

I have a NEW customer with the name "Greg Nel". When I want to create OR if I want to search for this customer in HighRise using their API, it returns the result "Gregory Snell" which is a different person BUT in his name it contains all the same letters of the NEW customer.

How can I write this GET request to get the correct result?

I have tried these with no good results:

/people/search.xml?term=Greg Nel
/people/search.xml?term="Greg Nel" (using quotes)
/people/search.xml?criteria[first-name]=Greg&criteria[last-name]=Nel

I expect the API to return me the result of either:

-Null (if the exact search term is NOT found), or
-the correct result which would be the profile ID data of the customer that I am looking for


问:
Vercel localhost:3000/api/graphql All Mutations and Queries Returning null
I am starting practicing creating my own servers using Vercel and Apollo/GraphQL, and while I have the Apollo Playground setup, I find that every single mutation or query returns null. I have console.log statements at the top of each mutation / query function, and the fact that the Playground's Docs and Schemas find these mutations/queries tells me that the server side of the code should be okay, but it seems like none of these are even getting hit according to the lack of logs.

my pages/api/graphql.js file I believe is correct, as it was essentially a copy-and-paste from another properly functioning project.

Similarly, if there were issues in my schema / typeDefs, the playground would not even properly run.

Does anyone have any suggestions of where to look?


问:
Running IRT with correlated items and many missing values
I'm hoping to run an IRT analysis where I have a couple families of items, and each person has answered one question from each family. Are there R packages for doing something like this? I've looked at options like hIRT but this seems to only account for individual level covariates, not item level covariates. I'm expecting the data to look something like this:

1a
1b
1c
2a
2b
2c

1

0

0

1

1

1

where each person answers one of 1a, 1b, and 1c, and one of 2a, 2b, and 2c.


问:
How to Mock window.System.NonGridPageBrowserScroll in Angular spec ts
I have a method

```<code>this.window.System.NonGridPageBrowserScroll();
</code>```

I need to Mock this one in the spec.ts file.
I am not finding any good resources online

I did tried Stubwindow etc

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

Body:
I have a method

this.window.System.NonGridPageBrowserScroll();

I need to Mock this one in the spec.ts file.
I am not finding any good resources online

I did tried Stubwindow etc

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


问:
Is it possible to show organisation repos in GitHub desktop without manually cloning through the app?
I wrote a script to clone many repositories from my organisation (The organisation is set as a business), but these repositories do not automatically show up in GitHub Desktop. It seems as though to make repositories show up in GitHub desktop I need to clone through GitHub desktop or add each repository manually through the local option.

Is there a way to make organisation repositories that I have cloned automatically show up on GitHub desktop?


问:
Best datatype for a postgreSQL database in this situation
I am kinda new to database design. Current design was working perfect until I found an issue.

Is a financial APP that recieve a lot of data.

There are mainly 2 data types:

Auto calculated where precision will be between 0% and 100% with 2 decimals, in few cases can be little more than 100%, so I set Numeric(6,2)

The other situation is raw data to calculate all those metrics. With big stocks I was ok with smallint/integer, because numbers are big and can be always integers (numbers like 257637, 188143) taking into account I save them in Millions. Problem is that, since I use millions unit, I realised that when I storage some small stocks those values can go as low as 0.10, so what should I do in this situation, go to Numeric(10,2) or so in all columns? Or there is another better way.

Thanks in advance.


问:
why doesn't std::vector free its memory after a user interrupt?
In case a user sent the SIGINT interrupt ( or any other interrupt that would interrupt program execution ) to a program, why does the std::vector deallocator fail to run automatically in such a case?

i used this test code to try it out:

#include <cstdio>
#include <vector>

using std::vector;

int main(void) {
  vector<int> buf(40, 0);

  int i{};
  for (;;) {
    printf("!my great program: %d\n", buf[i]);
    ++i;
  }

  return 0; // a pipe dream
}
```
<p>i compiled it with debug symbols using <code>gcc</code> and ran it through <code>valgrind</code> using this command:
<code>valgrind --leak-check=full --show-leak-kinds=all -v --log-file=val.log ./prog </code></p>
<p>after running the program through <code>valgrind</code> i got this as the heap summary:</p>
```...
==602714== HEAP SUMMARY:
==602714==     in use at exit: 73,888 bytes in 3 blocks
==602714==   total heap usage: 3 allocs, 0 frees, 73,888 bytes allocated
...
```

Body:
In case a user sent the SIGINT interrupt ( or any other interrupt that would interrupt program execution ) to a program, why does the std::vector deallocator fail to run automatically in such a case?

i used this test code to try it out:

#include <cstdio>
#include <vector>

using std::vector;

int main(void) {
  vector<int> buf(40, 0);

  int i{};
  for (;;) {
    printf("!my great program: %d\n", buf[i]);
    ++i;
  }

  return 0; // a pipe dream
}

i compiled it with debug symbols using gcc and ran it through valgrind using this command:
valgrind --leak-check=full --show-leak-kinds=all -v --log-file=val.log ./prog

after running the program through valgrind i got this as the heap summary:

...
==602714== HEAP SUMMARY:
==602714==     in use at exit: 73,888 bytes in 3 blocks
==602714==   total heap usage: 3 allocs, 0 frees, 73,888 bytes allocated
...


问:
extract list of data from a specific attribute of a list of object instances in Phython
here a small Python (3.X) question:

consider having a list of objects from a class with several attributes.

Which would be a pythonic way to derrive the values for a specific attribute from all object instances as a list.

The following code is working, but I guess there might be more elegant ways?

```<code>class Point:
def __init__(self, x: float, y: float):
    self.x = x
    self.y = y

# create some test data
points = []
points.append(Point(10.0, 20.0))
points.append(Point(30.0, 10.0))
points.append(Point(10.0, 60.0))

#probably unpythonic way of derriving list of specific instance attribute data
x = []
for point in points:
    x.append(point.x)

#output
print("x=" + str(x))
# x=[10.0, 30.0, 10,0]
</code>```

What would be your suggestion? Thanks!

Body:
here a small Python (3.X) question:

consider having a list of objects from a class with several attributes.

Which would be a pythonic way to derrive the values for a specific attribute from all object instances as a list.

The following code is working, but I guess there might be more elegant ways?

class Point:
def __init__(self, x: float, y: float):
    self.x = x
    self.y = y

# create some test data
points = []
points.append(Point(10.0, 20.0))
points.append(Point(30.0, 10.0))
points.append(Point(10.0, 60.0))

#probably unpythonic way of derriving list of specific instance attribute data
x = []
for point in points:
    x.append(point.x)

#output
print("x=" + str(x))
# x=[10.0, 30.0, 10,0]

What would be your suggestion? Thanks!


问:
Why does my text's position get messed up when going into windowed mode?
Hey so I have this html code and it works perfectly fine when I'm viewing it in full screen. However, when I go into windowed mode the "InfotextÜ" and "Infotext" get completely messed up. Kind of the same happens with the button-24. What do I have to do so that the "layout" stays the same?

```<code>    <!DOCTYPE html>
    <html>
    <head>
    <title>ParadisoPiccolo</title>
    <link rel="icon" type="image/png" sizes="192x192" href="https://i.imgur.com/XVO5fKh.png">
    <style>
    body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    overflow: scroll;
    }

    h1 {
    font-size: 3.5em;
    }

    h2 {
    text-align: center;
    font-size: 2em;
    padding-top: 2%;
    }

    p {
    margin: 20px 0;
    line-height: 1.5;
    }

    ul {
    list-style: none;
    margin: 20px 0;
    padding: 0;
    }

    header {
    overflow: hidden;
    position: relative;
    }

    li {
    margin: 10px 0;
    }

    .content {
    position: relative;
    padding: 20px 1px;
    padding-left: 2.5%;
    }

    img {
    width: 90vw;
    margin-left: auto;
    margin-right: auto;
    display: block;
    vertical-align: top;
    }

    #slideshow {
    position: absolute;
    top: 55%;
    left: 12%;
    width: 15%;
    height: 16%;
    }

    #slideshow img {
    width: 170%;
    height: 170%;
    object-fit: cover;
    }

    #menu {
    position: fixed;
    width: 100%;
    background-color: #333;
    color: #fff;
    z-index: 2;
    padding: 0;
    }

    .Infotext {
    position: absolute;
    top: 57%;
    left: 40%;
    font-size: 160%;

    }

    .InfotextÜ {
    position: absolute;
    top: 53.5%;
    left: 40%;
    font-family: Arno Pro Caption;
    font-size: 225%;
    }

    .button-24 {
    position: fixed;
    top: 90%;
    left: 50%;
    width: 9%;
    transform: translateX(-50%);
    background: #FF4742;
    border: 1px solid #FF4742;
    border-radius: 6px;
    box-shadow: rgba(0, 0, 0, 0.1) 1px 2px 4px;
    box-sizing: border-box;
    color: #FFFFFF;
    cursor: pointer;
    display: inline-block;
    font-family: nunito,roboto,proxima-nova,"proxima nova",sans-serif;
    font-size: 100%;
    font-weight: 800;
    line-height: 16px;
    min-height: 40px;
    outline: 0;
    padding: 12px 43px;
    text-align: center;
    text-rendering: geometricprecision;
    text-transform: none;
    user-select: none;
    -webkit-user-select: none;
    touch-action: manipulation;
    vertical-align: middle;
    }

    .button-24:hover,
    .button-24:active {
    background-color: initial;
    background-position: 0 0;
    color: #FF4742;
    }

    .button-24:active {
    opacity: .5;
    }

    footer {
    background-color: #333;
    color: #fff;
    padding: 20px;
    text-align: center;
    }
    </style>

    </head>
    <body>
    <header>
    <div id="slideshow">
    (...)
    </div>
    <p class="InfotextÜ">Paradiso Piccolo</p>
    <p class="Infotext">Das Paradiso Piccolo ist eine Ferienwohnung am See. <br>
    Sehr schön gelegen direkt    am Seeufer.<br> Von der eigenen Liegewiese am Strand geht's raus auf <br>
    den See zum Schwimmen, Surfen, Segeln oder Kiten. <br> Vom Balkon genießt man am Abend den Blick auf
    das Seepanorama. <br> Eine Perle am See.</p>
    <img id="image" src="https://i.imgur.com/O0jKPtk.jpg" alt="Foto">
    </header>
    (...)
    </html>
</code>```

I tried setting the position to relative but that just puts the text above the image and I get confused even more. Thanks in advance.

Body:
Hey so I have this html code and it works perfectly fine when I'm viewing it in full screen. However, when I go into windowed mode the "InfotextÜ" and "Infotext" get completely messed up. Kind of the same happens with the button-24. What do I have to do so that the "layout" stays the same?

    <!DOCTYPE html>

    <title>ParadisoPiccolo</title>
    <link rel="icon" type="image/png" sizes="192x192" href="https://i.imgur.com/XVO5fKh.png">

    (...)

Paradiso Piccolo

Das Paradiso Piccolo ist eine Ferienwohnung am See.

    Sehr schön gelegen direkt    am Seeufer.
 Von der eigenen Liegewiese am Strand geht's raus auf

    den See zum Schwimmen, Surfen, Segeln oder Kiten.
 Vom Balkon genießt man am Abend den Blick auf
    das Seepanorama.
 Eine Perle am See.

    (...)

I tried setting the position to relative but that just puts the text above the image and I get confused even more. Thanks in advance.


问:
Problem with Server Class Socket in JAVA [Eclipse]
I've tried to develop this Server in Java with Eclipse, but when I run it says me this error:

```<code>Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error, insert "}" to complete ClassBody
</code>```

I don't understand where I should insert this "}" because I've just tried to close the class with "};" but it persists... thanks in advance!

This is the code:

import java.io.*;
import java.net.*;
import java.util.*;

public class ServerStr {
    ServerSocket server = null;
    Socket client = null;
    String stringaRicevuta = null;
    String stringaModificata = null;
    BufferedReader inDalClient;
    DataOutputStream outVersoClient;

    public Socket attendi() {
        try {
            System.out.println("1 SERVER partito in esecuzione..partito.");
            server = new ServerSocket(6789);
            client = server.accept();
            server.close();
            inDalClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
            outVersoClient = new DataOutputStream(client.getOutputStream());
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println("Errore durante l'istanza del server");
            System.exit(1);
        }
        return client;
    }

    public void comunica() {
        try {
            System.out.println("3 benvenuto client, scrivi una frase e la trasformo in maiuscolo. Attendo...");
            stringaRicevuta = inDalClient.readLine();
            System.out.println(" e ricevuta la stringa dal cliente" + stringaRicevuta);
            stringaModificata = stringaRicevuta.toUpperCase();
            System.out.println(" invio la stringa modificata al client...");
            outVersoClient.writeBytes(stringaModificata + '\n');
            System.out.println("9 SERVER: fine elaborazione... buonanotte!");
            client.close();
        }
        finally {
        }
    };

    public static void main(String args[]) {
        ServerStr servente = new ServerStr();
        servente.attendi();
        servente.comunica();
    }
```

Body:
I've tried to develop this Server in Java with Eclipse, but when I run it says me this error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error, insert "}" to complete ClassBody

I don't understand where I should insert this "}" because I've just tried to close the class with "};" but it persists... thanks in advance!

This is the code:

import java.io.*;
import java.net.*;
import java.util.*;

public class ServerStr {
    ServerSocket server = null;
    Socket client = null;
    String stringaRicevuta = null;
    String stringaModificata = null;
    BufferedReader inDalClient;
    DataOutputStream outVersoClient;

    public Socket attendi() {
        try {
            System.out.println("1 SERVER partito in esecuzione..partito.");
            server = new ServerSocket(6789);
            client = server.accept();
            server.close();
            inDalClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
            outVersoClient = new DataOutputStream(client.getOutputStream());
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println("Errore durante l'istanza del server");
            System.exit(1);
        }
        return client;
    }

    public void comunica() {
        try {
            System.out.println("3 benvenuto client, scrivi una frase e la trasformo in maiuscolo. Attendo...");
            stringaRicevuta = inDalClient.readLine();
            System.out.println(" e ricevuta la stringa dal cliente" + stringaRicevuta);
            stringaModificata = stringaRicevuta.toUpperCase();
            System.out.println(" invio la stringa modificata al client...");
            outVersoClient.writeBytes(stringaModificata + '\n');
            System.out.println("9 SERVER: fine elaborazione... buonanotte!");
            client.close();
        }
        finally {
        }
    };

    public static void main(String args[]) {
        ServerStr servente = new ServerStr();
        servente.attendi();
        servente.comunica();
    }


问:
Cannot plot a 2d surface with surface countours using matplotlib
I would like to plot a multivariate function f_ab using the axes3d method with a and b as "variables". For some reason, the method throws an error saying that z is not a 2d array. If I check the shape of f_ab, I get (50,50)

```<code>import numpy as np

a = np.linspace(5,10,50)
b = np.linspace(3,8,50)

f_ab = np.zeros((len(a),len(b)))

for i in range(len(a)):
    for j in range(len(b)):
        f_ab[i,j] = (a[i]**0.5)*(b[j])

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt

ax = plt.figure().add_subplot(projection='3d')
X, Y, Z = a, b, f_ab

# Plot the 3D surface
ax.plot_surface(X, Y, Z, edgecolor='royalblue', lw=0.5, rstride=8, cstride=8,
                alpha=0.3)

# Plot projections of the contours for each dimension.  By choosing offsets
# that match the appropriate axes limits, the projected contours will sit on
# the 'walls' of the graph.
ax.contour(X, Y, Z, zdir='z', offset=np.min(f_ab), cmap='coolwarm')
ax.contour(X, Y, Z, zdir='x', offset=50, cmap='coolwarm')
ax.contour(X, Y, Z, zdir='y', offset=50, cmap='coolwarm')

ax.set(xlim=(0,50), ylim=(0,50), zlim=(np.min(f_ab),np.max(f_ab)),
       xlabel='a', ylabel='b', zlabel='z')
</code>```

The error looks like this:

```<code>File ~\AppData\Roaming\Python\Python310\site-packages\matplotlib\contour.py:1501, in QuadContourSet._check_xyz(self, args, kwargs)
   1498 z = ma.asarray(args[2], dtype=np.float64)
   1500 if z.ndim != 2:
-> 1501     raise TypeError(f"Input z must be 2D, not {z.ndim}D")
   1502 if z.shape[0] < 2 or z.shape[1] < 2:
   1503     raise TypeError(f"Input z must be at least a (2, 2) shaped array, "
   1504                     f"but has shape {z.shape}")

TypeError: Input z must be 2D, not 1D
</code>```

I tried changing the zdir parameter in the ax.contour, but could not get the desired result.

How can I resolve the error?

Body:
I would like to plot a multivariate function f_ab using the axes3d method with a and b as "variables". For some reason, the method throws an error saying that z is not a 2d array. If I check the shape of f_ab, I get (50,50)

import numpy as np

a = np.linspace(5,10,50)
b = np.linspace(3,8,50)

f_ab = np.zeros((len(a),len(b)))

for i in range(len(a)):
    for j in range(len(b)):
        f_ab[i,j] = (a[i]**0.5)*(b[j])

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt

ax = plt.figure().add_subplot(projection='3d')
X, Y, Z = a, b, f_ab

# Plot the 3D surface
ax.plot_surface(X, Y, Z, edgecolor='royalblue', lw=0.5, rstride=8, cstride=8,
                alpha=0.3)

# Plot projections of the contours for each dimension.  By choosing offsets
# that match the appropriate axes limits, the projected contours will sit on
# the 'walls' of the graph.
ax.contour(X, Y, Z, zdir='z', offset=np.min(f_ab), cmap='coolwarm')
ax.contour(X, Y, Z, zdir='x', offset=50, cmap='coolwarm')
ax.contour(X, Y, Z, zdir='y', offset=50, cmap='coolwarm')

ax.set(xlim=(0,50), ylim=(0,50), zlim=(np.min(f_ab),np.max(f_ab)),
       xlabel='a', ylabel='b', zlabel='z')

The error looks like this:

File ~\AppData\Roaming\Python\Python310\site-packages\matplotlib\contour.py:1501, in QuadContourSet._check_xyz(self, args, kwargs)
   1498 z = ma.asarray(args[2], dtype=np.float64)
   1500 if z.ndim != 2:
-> 1501     raise TypeError(f"Input z must be 2D, not {z.ndim}D")
   1502 if z.shape[0] < 2 or z.shape[1] < 2:
   1503     raise TypeError(f"Input z must be at least a (2, 2) shaped array, "
   1504                     f"but has shape {z.shape}")

TypeError: Input z must be 2D, not 1D

I tried changing the zdir parameter in the ax.contour, but could not get the desired result.

How can I resolve the error?


问:
Choose multiple or single images from the phone storage without having a null exception pointer and with or without using startActivityForResult()
I want to pick multiple or single images from phone gallery. But my code returning null pointer also one major problem I have notice the createChooser runs twice.

After tries two pick image two time it sends me to the parent activity

OnCreate Method

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item_business);

```<code>    ItemName = findViewById(R.id.item_name);
    ItemDes = findViewById(R.id.item_des);
    pickImage = findViewById(R.id.pickImage);

    ChooseImageList = new ArrayList<>();
    UrlsList = new ArrayList<>();

    pickImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CheckPermission();
            PickImageFromGallery();
        }
    });

}
</code>```

Checking Permission

```<code>private void CheckPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(addItemBusiness.this,
                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(addItemBusiness.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
            } else {
                PickImageFromGallery();
            }
        }
    }
</code>```

Move to gallery

```<code>private void PickImageFromGallery() {
   Intent intent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
    startActivityForResult(Intent.createChooser(intent, "Select images"), 100);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
   Log.i("result", "inside activity result");
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 100 && resultCode == RESULT_OK) {
        Log.i("result", "result is ok");
        if (data.getClipData() != null) {
            Log.i("result", "fine");
            int count = data.getClipData().getItemCount();
            for (int i = 0; i < count; i++) {
                ImageUri = data.getClipData().getItemAt(i).getUri();
                ChooseImageList.add(ImageUri);
                SetAdapter();
            }
        } else if (data.getData() != null) {
            Log.i("result", "clip data is null");
            ImageUri = data.getData();
            ChooseImageList.add(ImageUri);
            SetAdapter();
        }
    }

}
</code>```

Adapter

```<code> private void SetAdapter(){
        ViewPagerAdapter adapter = new ViewPagerAdapter(this, ChooseImageList);
        viewPager.setAdapter(adapter);
    }
</code>```

Adapter Class

```<code>private Context context;
    ArrayList<Uri> ImageUrls;
    LayoutInflater layoutInflater;

    public ViewPagerAdapter(Context context, ArrayList<Uri> imageUrls) {
        this.context = context;
        ImageUrls = imageUrls;
        layoutInflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return ImageUrls.size();
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View view=layoutInflater.inflate(R.layout.show_imgaes_layout,container,false);
        ImageView imageView=view.findViewById(R.id.UploadImage);
        imageView.setImageURI(ImageUrls.get(position));
        container.addView(view);

        return view ;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view== object;
    }

    @Override
    public void destroyItem(@NonNull View container, int position, @NonNull Object object) {
        ((RelativeLayout)object).removeView(container);
    }
</code>```

Hope that you can find the issue. Thank you

Body:
I want to pick multiple or single images from phone gallery. But my code returning null pointer also one major problem I have notice the createChooser runs twice.

After tries two pick image two time it sends me to the parent activity

OnCreate Method

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item_business);

    ItemName = findViewById(R.id.item_name);
    ItemDes = findViewById(R.id.item_des);
    pickImage = findViewById(R.id.pickImage);

    ChooseImageList = new ArrayList<>();
    UrlsList = new ArrayList<>();

    pickImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CheckPermission();
            PickImageFromGallery();
        }
    });

}

Checking Permission

private void CheckPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(addItemBusiness.this,
                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(addItemBusiness.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
            } else {
                PickImageFromGallery();
            }
        }
    }

Move to gallery

private void PickImageFromGallery() {
   Intent intent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
    startActivityForResult(Intent.createChooser(intent, "Select images"), 100);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
   Log.i("result", "inside activity result");
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 100 && resultCode == RESULT_OK) {
        Log.i("result", "result is ok");
        if (data.getClipData() != null) {
            Log.i("result", "fine");
            int count = data.getClipData().getItemCount();
            for (int i = 0; i < count; i++) {
                ImageUri = data.getClipData().getItemAt(i).getUri();
                ChooseImageList.add(ImageUri);
                SetAdapter();
            }
        } else if (data.getData() != null) {
            Log.i("result", "clip data is null");
            ImageUri = data.getData();
            ChooseImageList.add(ImageUri);
            SetAdapter();
        }
    }

}

Adapter

 private void SetAdapter(){
        ViewPagerAdapter adapter = new ViewPagerAdapter(this, ChooseImageList);
        viewPager.setAdapter(adapter);
    }

Adapter Class

private Context context;
    ArrayList<Uri> ImageUrls;
    LayoutInflater layoutInflater;

    public ViewPagerAdapter(Context context, ArrayList<Uri> imageUrls) {
        this.context = context;
        ImageUrls = imageUrls;
        layoutInflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return ImageUrls.size();
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View view=layoutInflater.inflate(R.layout.show_imgaes_layout,container,false);
        ImageView imageView=view.findViewById(R.id.UploadImage);
        imageView.setImageURI(ImageUrls.get(position));
        container.addView(view);

        return view ;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view== object;
    }

    @Override
    public void destroyItem(@NonNull View container, int position, @NonNull Object object) {
        ((RelativeLayout)object).removeView(container);
    }

Hope that you can find the issue. Thank you


问:
Hover on sibling in CSS
When I try to add hover on the first child to add effect on the second child it works but when I try in reverse it doesn't do anything

```<code>  <body>
    <style>
      .first__child {
        height: 100px;
        aspect-ratio: 1;
        background-color: red;
      }
      .second__child {
        height: 100px;
        aspect-ratio: 1;
        background-color: red;
      }
      .first__child:hover ~ .second__child {
        background-color: blue;
      }
      .second__child:hover ~ .first__child {
        background-color: blue;
      }

    </style>
    <main>
      <div class="first__child">
        <p>dummy text</p>
      </div>
      <div class="second__child">
        <p>dummy text</p>
      </div>
    </main>
  </body>
</code>```

I tried "+" or ">" instead of "~" but it doesn't work , Is there a "previous sibling" selector? can't find answer from this question either

Title: Hover on sibling in CSS

Body:
When I try to add hover on the first child to add effect on the second child it works but when I try in reverse it doesn't do anything

dummy text

dummy text

I tried "+" or ">" instead of "~" but it doesn't work , Is there a "previous sibling" selector? can't find answer from this question either


问:
Reactive java test (StepVerifier)
I would like to write a test for the piece of code below. Specially I would like to verify the existence of the "response" object. Can I achieve this using "StepVerifier"?

saharaSnowTickets.raiseIncidentWithCustomDescriptionAndNonRandomEventId(summary, description,
Severity.SEV_2,
cmdId
).retryWhen(Retry.backoff(properties.getRetry(), getDuration(properties.getUnity(), properties.getDuration())))
.doOnNext(response -> {log.info("response {}", response) })
.then();

Title: Reactive java test (StepVerifier)


问:
Streamlink progress bar
I want to download stream when its on and using streamlink in bash script. But when stream starts the progress bar is begin print in stdout. I would like to know how to turn it print off?

```<code>--logfile "FILE"
</code>```

helping with other type of logs but not with the download, progress bar anyway printed in console
I mean this kind of print:

```<code>[download][.._2023-01-10_23-25-53.ts] Written 155.8 MB (8m4s @ 394.4 KB/s)
</code>```
```<code>quality="1080p,best"
dir="/home/artem/writer/"
while true
do
datetime=$(date +%Y-%m-%d)_$(date +%k-%M-%S)
echo "$datetime" >> /home/artem/writer/"${name} log"
file="${name}_$datetime.ts"
streamlink --hls-segment-threads 3 $link $quality -o "$dir$file" --logfile "${name} log"
echo " " >> /home/artem/writer/"${name} log"
sleep 30
done
</code>```

My bash script code ^^ (sry don't want to show link)

I did try --no-progress option i find it somewhere in google but its not working

Title: Streamlink progress bar

Body:
I want to download stream when its on and using streamlink in bash script. But when stream starts the progress bar is begin print in stdout. I would like to know how to turn it print off?

--logfile "FILE"

helping with other type of logs but not with the download, progress bar anyway printed in console
I mean this kind of print:

[download][.._2023-01-10_23-25-53.ts] Written 155.8 MB (8m4s @ 394.4 KB/s)

quality="1080p,best"
dir="/home/artem/writer/"
while true
do
datetime=$(date +%Y-%m-%d)_$(date +%k-%M-%S)
echo "$datetime" >> /home/artem/writer/"${name} log"
file="${name}_$datetime.ts"
streamlink --hls-segment-threads 3 $link $quality -o "$dir$file" --logfile "${name} log"
echo " " >> /home/artem/writer/"${name} log"
sleep 30
done

My bash script code ^^ (sry don't want to show link)

I did try --no-progress option i find it somewhere in google but its not working


问:
.NET Core System.Diagnostics.Activity cannot handle multiple ParentIds from traceparent header?
We are implementing OpenTelemetry tracing in Nginx and .NET Core microservices. We have created a local setup for Nginx according to https://opentelemetry.io/blog/2022/instrument-nginx/. This works great, multiple spans are created (one per module called in Nginx):

Nginx spans

However these spans are all passed to the microservice via the traceparent header:

Activity parent ids

It seems like System.Diagnostics.Activity is not able to handle this, as a new Id is generated that is also the RootId.

We have tried to set the ParentId using the SetParentId() method, however this has no effect whatsoever, in fact it doesn't change the ParentId at all (though the decompiled code shows no reason for doing so).

To test if it could actually work, we have used reflection to "hack" the necessary private fields:

Hacked

This of course isn't the way to go, but the test shows it could and should actually work:

Linked

We have disabled opentelemetry for nginx and used a proxy_pass_header to pass a traceparent. This also seems to work without any issues.

Any thoughts?

Cheers,

Peter


问:
Error running excel vba code from PERSONAL.XLBS: Compile error: User-defined type not defined
I’ve written some VBA code to download some photos from our online database.  Our database can dump to an excel file by running a report which includes web addresses of the photos.  I’d like to have the person be able to run the report and then run the macro with a keystroke and download the photos without having to open an additional workbook.  I cobbled this sub together from some code that I found online and customized it to fit my needs. I wrote it as a module in a workbook and it works great.  When I moved it to the PERSONAL.XLSB project, it does not work.  Moved it back again and it works from the workbook.  In order to get it to work in the first place, I had to go to Tools->References and enable “Microsoft Scripting Runtime” and “Microsoft Office 16.0 Object Library”.  The failure point is the line “Dim xmlhttp As New MSXML2.XMLHTTP60”.  I get the error:  “Compile error: User-defined type not defined".  I’m thinking that this has something to do with  it not being able to use the enabled references when it is in the PERSONAL.XLSB project.  This is really beyond my experience.  Can anyone give me some idea of how to make this work?

code below:

```<code>   Option Explicit

   Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" _
    Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, _
    ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long

   Sub download_all_photos()

    Dim wk As Workbook
    Dim ws1 As Worksheet
    Dim counter As Integer

    Dim xmlhttp As New MSXML2.XMLHTTP60

    Dim myURL As String, typ As String, name0 As String, name2 As String
    Dim catname As String
    Dim name1 As String, xstate As String, dlpath As String
    Dim pos As Integer
    Dim FileName As String
    Dim FileExists As String
    Dim xstatus As Long
    Dim i As Long
    Dim j As Long
    Dim lastRow_photos As Long
    Dim lastrow_Current As Integer
    Dim Sheet As Variant
    Dim CurrentRange As Range
    Dim purl As String

    Application.ScreenUpdating = False

    ' About to create a new "photo_url" sheet, delete any old one
    For Each Sheet In ActiveWorkbook.Worksheets
        If Sheet.Name = "photo_url" Then
            Application.DisplayAlerts = False
            Worksheets("photo_url").Delete
            Application.DisplayAlerts = True
        End If
    Next Sheet

    Sheets.Add.Name = "photo_url"

    lastrow_Current = Worksheets("Current").Cells(Rows.Count, 2).End(xlUp).Row

    j = 1
    For i = 2 To lastrow_Current

        purl = Worksheets("Current").Cells(i, 19).Value
        If purl <> "" Then

            purl = Replace(purl, Chr(34), "")
            purl = Replace(purl, "<a target=_blank href=", "")
            purl = Replace(purl, ">Photo Link</a>", "")
            Worksheets("photo_url").Cells(j, 1).Value = purl
            Worksheets("photo_url").Cells(j, 2).Value = Worksheets("Current").Cells(i, 2).Value
            Worksheets("photo_url").Cells(j, 3).Value = Worksheets("Current").Cells(i, 3).Value
            Worksheets("photo_url").Cells(j, 4).Value = Replace(Worksheets("Current").Cells(i, 7).Value, "/ ", "_")

            j = j + 1
        End If
    Next i

    Worksheets("photo_url").Columns("A:D").AutoFit

    lastRow_photos = Worksheets("photo_url").Cells(Rows.Count, 2).End(xlUp).Row
    dlpath = Worksheets("Instructions").Range("A1").Value
    counter = 0

    For i = 1 To lastRow_photos

        myURL = Worksheets("photo_url").Range("A" & i).Value
        catname = Worksheets("photo_url").Range("C" & i).Value & "_" & Worksheets("photo_url").Range("B" & i).Value     'use if want to add shelterluv ID

        xmlhttp.Open "GET", myURL, False
        xmlhttp.send

        name0 = xmlhttp.getResponseHeader("Content-Disposition")

        If name0 <> "" Then
            pos = InStr(1, name0, "=")
            name2 = Mid(name0, pos + 1, (Len(name0) - (pos)))
        Else
            name2 = FileNameFromPath(myURL)
        End If

        FileName = dlpath & "\" & catname & ".png"
        FileExists = Dir(FileName)
        If FileExists = "" Then
            name2 = catname
        Else
            name2 = catname & Int(2 + Rnd * (100000 - 2 + 1))   ' add a random number to name
        End If

        Debug.Print myURL; FileName

        xstatus = URLDownloadToFile(0, myURL, FileName, 0, 0)

        Debug.Print xstatus

    Next i

    Application.ScreenUpdating = True

    End Sub

    Function FileNameFromPath(strFullPath As String) As String

    FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, "/"))

  End Function

</code>```

Body:
I’ve written some VBA code to download some photos from our online database.  Our database can dump to an excel file by running a report which includes web addresses of the photos.  I’d like to have the person be able to run the report and then run the macro with a keystroke and download the photos without having to open an additional workbook.  I cobbled this sub together from some code that I found online and customized it to fit my needs. I wrote it as a module in a workbook and it works great.  When I moved it to the PERSONAL.XLSB project, it does not work.  Moved it back again and it works from the workbook.  In order to get it to work in the first place, I had to go to Tools->References and enable “Microsoft Scripting Runtime” and “Microsoft Office 16.0 Object Library”.  The failure point is the line “Dim xmlhttp As New MSXML2.XMLHTTP60”.  I get the error:  “Compile error: User-defined type not defined".  I’m thinking that this has something to do with  it not being able to use the enabled references when it is in the PERSONAL.XLSB project.  This is really beyond my experience.  Can anyone give me some idea of how to make this work?

code below:

   Option Explicit

   Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" _
    Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, _
    ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long

   Sub download_all_photos()

    Dim wk As Workbook
    Dim ws1 As Worksheet
    Dim counter As Integer

    Dim xmlhttp As New MSXML2.XMLHTTP60

    Dim myURL As String, typ As String, name0 As String, name2 As String
    Dim catname As String
    Dim name1 As String, xstate As String, dlpath As String
    Dim pos As Integer
    Dim FileName As String
    Dim FileExists As String
    Dim xstatus As Long
    Dim i As Long
    Dim j As Long
    Dim lastRow_photos As Long
    Dim lastrow_Current As Integer
    Dim Sheet As Variant
    Dim CurrentRange As Range
    Dim purl As String

    Application.ScreenUpdating = False

    ' About to create a new "photo_url" sheet, delete any old one
    For Each Sheet In ActiveWorkbook.Worksheets
        If Sheet.Name = "photo_url" Then
            Application.DisplayAlerts = False
            Worksheets("photo_url").Delete
            Application.DisplayAlerts = True
        End If
    Next Sheet

    Sheets.Add.Name = "photo_url"

    lastrow_Current = Worksheets("Current").Cells(Rows.Count, 2).End(xlUp).Row

    j = 1
    For i = 2 To lastrow_Current

        purl = Worksheets("Current").Cells(i, 19).Value
        If purl <> "" Then

            purl = Replace(purl, Chr(34), "")
            purl = Replace(purl, "Photo Link", "")
            Worksheets("photo_url").Cells(j, 1).Value = purl
            Worksheets("photo_url").Cells(j, 2).Value = Worksheets("Current").Cells(i, 2).Value
            Worksheets("photo_url").Cells(j, 3).Value = Worksheets("Current").Cells(i, 3).Value
            Worksheets("photo_url").Cells(j, 4).Value = Replace(Worksheets("Current").Cells(i, 7).Value, "/ ", "_")

            j = j + 1
        End If
    Next i

    Worksheets("photo_url").Columns("A:D").AutoFit

    lastRow_photos = Worksheets("photo_url").Cells(Rows.Count, 2).End(xlUp).Row
    dlpath = Worksheets("Instructions").Range("A1").Value
    counter = 0

    For i = 1 To lastRow_photos

        myURL = Worksheets("photo_url").Range("A" & i).Value
        catname = Worksheets("photo_url").Range("C" & i).Value & "_" & Worksheets("photo_url").Range("B" & i).Value     'use if want to add shelterluv ID

        xmlhttp.Open "GET", myURL, False
        xmlhttp.send

        name0 = xmlhttp.getResponseHeader("Content-Disposition")

        If name0 <> "" Then
            pos = InStr(1, name0, "=")
            name2 = Mid(name0, pos + 1, (Len(name0) - (pos)))
        Else
            name2 = FileNameFromPath(myURL)
        End If

        FileName = dlpath & "\" & catname & ".png"
        FileExists = Dir(FileName)
        If FileExists = "" Then
            name2 = catname
        Else
            name2 = catname & Int(2 + Rnd * (100000 - 2 + 1))   ' add a random number to name
        End If

        Debug.Print myURL; FileName

        xstatus = URLDownloadToFile(0, myURL, FileName, 0, 0)

        Debug.Print xstatus

    Next i

    Application.ScreenUpdating = True

    End Sub

    Function FileNameFromPath(strFullPath As String) As String

    FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, "/"))

  End Function


问:
Node.js script returns an empty array
I'm still learning Node.js

I have been able to run some scripts successuly before.

I'm trying to use a new module I found (Github https://github.com/facundoolano/app-store-scraper)

I am running into an issue when trying to run one of the functions.

If I try one of the functions, like here:

var store = require('app-store-scraper');

store.suggest({term: 'candy'}).then(console.log).catch(console.log);
```
<p>Which I save in search.js</p>
<p>If I then execute:</p>
```node search.js
```
<p>the terminal returns:</p>
```[]
```

What am I missing?

Title: Node.js script returns an empty array

Body:
I'm still learning Node.js

I have been able to run some scripts successuly before.

I'm trying to use a new module I found (Github https://github.com/facundoolano/app-store-scraper)

I am running into an issue when trying to run one of the functions.

If I try one of the functions, like here:

var store = require('app-store-scraper');

store.suggest({term: 'candy'}).then(console.log).catch(console.log);

Which I save in search.js

If I then execute:

node search.js

the terminal returns:

[]

What am I missing?


问:
Not able to use azure credit provided by github student developer pack
I logged into azure account with referral link provided by github student developer pack but when i try to access bash/powershell it shows You need an Azure subscription to use Azure cloud Shell. Also, credits are not shown in the overview tab.

I tried to claim credit provided by github student developer pack but it is not shown there.


问:
Laravel Add method to route::resource
I need to add an additional method (POST search) to the routes that are added as a resource, can someone guide me on how I can achieve it?

In the routes.php file I have the following code:

```<code>Route::resources([
    '/user' => App\Http\Controllers\UserTC::class,
    '/role' => App\Http\Controllers\RoleTC::class,
    ...
]);
</code>```

Somehow I want the search method to be used when setting route::resources such as index, show, store, etc.

Thanks

Edit 1: What I'm looking for is to prevent doing this:

```<code>Route::post('/user/search', [App\Http\Controllers\UserTC::class, 'search']);
Route::post('/role/search', [App\Http\Controllers\RoleTC::class, 'search']);
...etc
</code>```

Title: Laravel Add method to route::resource

Body:
I need to add an additional method (POST search) to the routes that are added as a resource, can someone guide me on how I can achieve it?

In the routes.php file I have the following code:

Route::resources([
    '/user' => App\Http\Controllers\UserTC::class,
    '/role' => App\Http\Controllers\RoleTC::class,
    ...
]);

Somehow I want the search method to be used when setting route::resources such as index, show, store, etc.

Thanks

Edit 1: What I'm looking for is to prevent doing this:

Route::post('/user/search', [App\Http\Controllers\UserTC::class, 'search']);
Route::post('/role/search', [App\Http\Controllers\RoleTC::class, 'search']);
...etc


问:
How to set basic auth headers - Woocommerce rest API redux query
As title says, I am having issues setting basic auth headers inside a headers object for redux query.

```<code>const wooApiHeaders = {

}

const baseUrl = 'https://stagemonkey.dk/kumau';

const createRequest = (url:any) => ({ url, headers: wooApiHeaders })

export const wooApi = createApi({
    reducerPath: 'wooApi',
    baseQuery: fetchBaseQuery({ baseUrl }),
    endpoints: (builder) => ({
        getWoo: builder.query({
            query: () => createRequest('/wp-json/wc/v3/products')
        })
    })
})
</code>```

I have been reading through docs but are facing some issues.

Body:
As title says, I am having issues setting basic auth headers inside a headers object for redux query.

const wooApiHeaders = {

}

const baseUrl = 'https://stagemonkey.dk/kumau';

const createRequest = (url:any) => ({ url, headers: wooApiHeaders })

export const wooApi = createApi({
    reducerPath: 'wooApi',
    baseQuery: fetchBaseQuery({ baseUrl }),
    endpoints: (builder) => ({
        getWoo: builder.query({
            query: () => createRequest('/wp-json/wc/v3/products')
        })
    })
})

I have been reading through docs but are facing some issues.


问:
At leetcode, using Python3, how come this function be faster than the two simple others?
The exercise is at this Link.

How can a solution with ".split()" be faster than any solution running only a while counting the last word size? Like:

```<code>class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        for word in s.split(' ')[::-1]:
            if word != '':
                return len(word)
</code>```

Faster than:

```<code>class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        firstLetter = len(s) -1
        for i in range(firstLetter, -1, -1):
            if s[i] != ' ':
                firstLetter = i
                break
        for i in range(firstLetter, -1, -1):
            if s[i] == ' ':
                return firstLetter - i
        return firstLetter+1
</code>```

or

```<code>class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        # trim the trailing spaces
        p = len(s) - 1
        while p >= 0 and s[p] == ' ':
            p -= 1

        # compute the length of last word
        length = 0
        while p >= 0 and s[p] != ' ':
            p -= 1
            length += 1
        return length
</code>```

Body:
The exercise is at this Link.

How can a solution with ".split()" be faster than any solution running only a while counting the last word size? Like:

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        for word in s.split(' ')[::-1]:
            if word != '':
                return len(word)

Faster than:

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        firstLetter = len(s) -1
        for i in range(firstLetter, -1, -1):
            if s[i] != ' ':
                firstLetter = i
                break
        for i in range(firstLetter, -1, -1):
            if s[i] == ' ':
                return firstLetter - i
        return firstLetter+1

or

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        # trim the trailing spaces
        p = len(s) - 1
        while p >= 0 and s[p] == ' ':
            p -= 1

        # compute the length of last word
        length = 0
        while p >= 0 and s[p] != ' ':
            p -= 1
            length += 1
        return length


问:
Undefined behavior for assignment operator
Today I encountered following UB:

```<code>std::vector<double> operator -(const std::vector<double>& this_, const std::vector<double>& other_){
    std::vector<double> result;
    for(int i = 0; i < this_.size(); i++){
        result[i] = this_[i] - other_[i];
    }
    return result;
}
</code>```

Basically what I think is when I declare the result the default constructor is called, but it does not initialize the object to a valid state, so when I try to access the element using result[i], it causes undefined behavior.

So my question is this: Does lhs have operation priority over rhs? If not, how can this be UB if it evaluates the rhs first and sets lhs to rhs?

Body:
Today I encountered following UB:

std::vector<double> operator -(const std::vector<double>& this_, const std::vector<double>& other_){
    std::vector<double> result;
    for(int i = 0; i < this_.size(); i++){
        result[i] = this_[i] - other_[i];
    }
    return result;
}

Basically what I think is when I declare the result the default constructor is called, but it does not initialize the object to a valid state, so when I try to access the element using result[i], it causes undefined behavior.

So my question is this: Does lhs have operation priority over rhs? If not, how can this be UB if it evaluates the rhs first and sets lhs to rhs?