问:
setAuth is not updating the auth state
My previous post got associated with a post that didn't answer my question and closed.

I am attempting to create a ProtectedRoutes component, however, I can't seem to get the auth state to update.

It should check if there is a cookie stored, and if so, set auth as true. Then if auth is true, it redirects to the auth component, otherwise to the landing/login page.

The auth page always redirects back to the landing page. The state is never updating to true. I have searched everywhere, and I cannot figure out why the state won't update.

Is it even possible to create this ProtectedRoutes component this way?

ProtectedRoutes.js

```<code>import React, { Component, useState, useEffect } from "react";
import { Route, Navigate } from "react-router-dom";
import Cookies from "universal-cookie";
const cookies = new Cookies();

export default function ProtectedRoutes({component: Component, ...rest}) {
    const [auth, setAuth] = useState(false);
    //get cookie from browser if logged in
    const token = cookies.get("TOKEN");

    useEffect(() => {
        if (token) {
            setAuth(true);
        }
    },[token]);

    return auth ? <Component /> : <Navigate to="/" />
}
</code>```

App.js

```<code>import { Container, Col, Row } from "react-bootstrap";
import "./App.css";
import Register from "./Register";
import Login from "./Login";
import { Routes, Route } from "react-router-dom";
import Account from "./Account";
import FreeComponent from "./FreeComponent";
import AuthComponent from "./AuthComponent";
import Private from "./ProtectedRoutes";
import ProtectedRoutes from "./ProtectedRoutes";

function App() {
  return (
    <Container>
      <Row>
        <Col className="text-center">
          <h1 className="header">React Authentication Tutorial</h1>

          <section id="navigation">
            <a href="/">Home</a>
            <a href="/free">Free Component</a>
            <a href="/auth">Auth Component</a>
          </section>
        </Col>
      </Row>

      {/* Routes */ }
      <Routes>
        <Route exact path="/" element={ <Account /> } />
        <Route exact path="/free" element={ <FreeComponent /> } />
        <Route path="/auth" element={<ProtectedRoutes component={AuthComponent} />} />
      </Routes>
    </Container>
  );
}

export default App;
</code>```

AuthComponent.js

```<code>import React from 'react';

export default function AuthComponent() {
    return (
        <div>
            <h1 className="text-center">Auth Component</h1>
        </div>
    );
}
</code>```

答:
Is there a reason to even hold auth as an item of React state ?

If everything is driven from the cookie with the token in it, then there's no need to also store it in state and then have a useEffect in turn listening for that.

I think what's probably happening is your page renders the first time (i.e. before your useEffect has run) and immediately commences the Navigate path, because auth is still false (its initial value). Your useEffect does run, but it's too late - your app has already moved on to showing the Navigate component.

Try this:

```<code>export default function ProtectedRoutes({component: Component, ...rest}) {
    //get cookie from browser if logged in
    const token = cookies.get("TOKEN");

    return token ? <Component /> : <Navigate to="/" />
}
</code>```

Title: setAuth is not updating the auth state

Body:
My previous post got associated with a post that didn't answer my question and closed.

I am attempting to create a ProtectedRoutes component, however, I can't seem to get the auth state to update.

It should check if there is a cookie stored, and if so, set auth as true. Then if auth is true, it redirects to the auth component, otherwise to the landing/login page.

The auth page always redirects back to the landing page. The state is never updating to true. I have searched everywhere, and I cannot figure out why the state won't update.

Is it even possible to create this ProtectedRoutes component this way?

ProtectedRoutes.js

import React, { Component, useState, useEffect } from "react";
import { Route, Navigate } from "react-router-dom";
import Cookies from "universal-cookie";
const cookies = new Cookies();

export default function ProtectedRoutes({component: Component, ...rest}) {
    const [auth, setAuth] = useState(false);
    //get cookie from browser if logged in
    const token = cookies.get("TOKEN");

    useEffect(() => {
        if (token) {
            setAuth(true);
        }
    },[token]);

    return auth ? <Component /> : <Navigate to="/" />
}

App.js

import { Container, Col, Row } from "react-bootstrap";
import "./App.css";
import Register from "./Register";
import Login from "./Login";
import { Routes, Route } from "react-router-dom";
import Account from "./Account";
import FreeComponent from "./FreeComponent";
import AuthComponent from "./AuthComponent";
import Private from "./ProtectedRoutes";
import ProtectedRoutes from "./ProtectedRoutes";

function App() {
  return (
    <Container>
      <Row>
        <Col className="text-center">

React Authentication Tutorial

            Home
            Free Component
            Auth Component

        </Col>
      </Row>

      {/* Routes */ }
      <Routes>
        <Route exact path="/" element={ <Account /> } />
        <Route exact path="/free" element={ <FreeComponent /> } />
        <Route path="/auth" element={<ProtectedRoutes component={AuthComponent} />} />
      </Routes>
    </Container>
  );
}

export default App;

AuthComponent.js

import React from 'react';

export default function AuthComponent() {
    return (

Auth Component

    );
}

Body:
Is there a reason to even hold auth as an item of React state ?

If everything is driven from the cookie with the token in it, then there's no need to also store it in state and then have a useEffect in turn listening for that.

I think what's probably happening is your page renders the first time (i.e. before your useEffect has run) and immediately commences the Navigate path, because auth is still false (its initial value). Your useEffect does run, but it's too late - your app has already moved on to showing the Navigate component.

Try this:

export default function ProtectedRoutes({component: Component, ...rest}) {
    //get cookie from browser if logged in
    const token = cookies.get("TOKEN");

    return token ? <Component /> : <Navigate to="/" />
}


来源: stackexchange

问:
datadog.apiKey was 'null' but it is required
I am currently using spring boot 2.7.0-M1 and following is my dependencies in build.gradle:

```<code>    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.cloud:spring-cloud-starter-config'
    implementation 'org.springframework.boot:spring-boot-starter-cache'
    compileOnly 'org.projectlombok:lombok'
    implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    implementation 'io.micrometer:micrometer-registry-datadog:latest.release'
    datadogagent("com.datadoghq:dd-java-agent:$datadoghq_dd_version")
    implementation("com.datadoghq:dd-trace-api:${datadoghq_dd_version}")
</code>```

However, when i try to set micrometer bean:

```<code>@Configuration
public class MeterRegistryConfig {
  @Bean
  MeterRegistry meterRegistry(ApplicationContext context) {
    DatadogConfig config = new DatadogConfig() {
      @Override
      public Duration step() {
        return Duration.ofSeconds(10);
      }

      @Override
      public String get(String k) {
        return null; // accept the rest of the defaults
      }
    };

    return new DatadogMeterRegistry(config, Clock.SYSTEM);
  }
}
</code>```

I am getting a startup error:

```<code>2022-02-05 05:07:56.457 ERROR 7897 --- [  restartedMain] o.s.b.web.embedded.tomcat.TomcatStarter  : Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'webMvcMetricsFilter' defined in class path resource [org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfiguration.class]: Unsatisfied dependency expressed through method 'webMvcMetricsFilter' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'compositeMeterRegistry' defined in class path resource [org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryConfiguration.class]: Unsatisfied dependency expressed through method 'compositeMeterRegistry' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'meterRegistry' defined in class path resource [com/hbomax/ml/mlsvc/config/MeterRegistryConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.micrometer.core.instrument.MeterRegistry]: Factory method 'meterRegistry' threw exception; nested exception is io.micrometer.core.instrument.config.validate.ValidationException: datadog.apiKey was 'null' but it is required
2022-02-05 05:07:56.504  INFO 7897 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2022-02-05 05:07:56.520  WARN 7897 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
2022-02-05 05:07:56.541  INFO 7897 --- [  restartedMain] ConditionEvaluationReportLoggingListener :
</code>```

Here's my application.yaml:

```<code>management:
  info:
    git:
      mode: full
  metrics:
    distribution:
      percentiles:
        http:
          server:
            requests: 0.5, 0.95, 0.99
      percentiles-histogram:
        http:
          server:
            requests: true
      sla:
        http:
          server:
            requests: 200ms, 400ms, 600ms
    export:
      datadog:
        step: 30s
        enabled: true
        api-key: xxxxxxx
    tags:
      application: ${spring.application.name}
      env: ${spring.profiles}
</code>```

Can someone help me understand what is the issue? I tried searching around but din't get any solution. I tried replacing api-key with apiKey(I know it's silly) but no success.

Any help folks?

答:
You are using Spring Boot's configuration properties in application.yml but you are also making your own DatadogMeterRegistry that doesn't use those configuration properties, and therefore it will not have the required API key configuration.

You can delete the MeterRegistryConfig class entirely and instead use the DatadogMeterRegistry that Spring Boot will auto-configure from configuration properties because you have the micrometer-registry-datadog dependency on your classpath. See this section of the Spring Boot documentation.

ContentLicense: CC BY-SA 4.0

Body:
I am currently using spring boot 2.7.0-M1 and following is my dependencies in build.gradle:

    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.cloud:spring-cloud-starter-config'
    implementation 'org.springframework.boot:spring-boot-starter-cache'
    compileOnly 'org.projectlombok:lombok'
    implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    implementation 'io.micrometer:micrometer-registry-datadog:latest.release'
    datadogagent("com.datadoghq:dd-java-agent:$datadoghq_dd_version")
    implementation("com.datadoghq:dd-trace-api:${datadoghq_dd_version}")

However, when i try to set micrometer bean:

@Configuration
public class MeterRegistryConfig {
  @Bean
  MeterRegistry meterRegistry(ApplicationContext context) {
    DatadogConfig config = new DatadogConfig() {
      @Override
      public Duration step() {
        return Duration.ofSeconds(10);
      }

      @Override
      public String get(String k) {
        return null; // accept the rest of the defaults
      }
    };

    return new DatadogMeterRegistry(config, Clock.SYSTEM);
  }
}

I am getting a startup error:

2022-02-05 05:07:56.457 ERROR 7897 --- [  restartedMain] o.s.b.web.embedded.tomcat.TomcatStarter  : Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'webMvcMetricsFilter' defined in class path resource [org/springframework/boot/actuate/autoconfigure/metrics/web/servlet/WebMvcMetricsAutoConfiguration.class]: Unsatisfied dependency expressed through method 'webMvcMetricsFilter' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'compositeMeterRegistry' defined in class path resource [org/springframework/boot/actuate/autoconfigure/metrics/CompositeMeterRegistryConfiguration.class]: Unsatisfied dependency expressed through method 'compositeMeterRegistry' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'meterRegistry' defined in class path resource [com/hbomax/ml/mlsvc/config/MeterRegistryConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.micrometer.core.instrument.MeterRegistry]: Factory method 'meterRegistry' threw exception; nested exception is io.micrometer.core.instrument.config.validate.ValidationException: datadog.apiKey was 'null' but it is required
2022-02-05 05:07:56.504  INFO 7897 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2022-02-05 05:07:56.520  WARN 7897 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
2022-02-05 05:07:56.541  INFO 7897 --- [  restartedMain] ConditionEvaluationReportLoggingListener :

Here's my application.yaml:

management:
  info:
    git:
      mode: full
  metrics:
    distribution:
      percentiles:
        http:
          server:
            requests: 0.5, 0.95, 0.99
      percentiles-histogram:
        http:
          server:
            requests: true
      sla:
        http:
          server:
            requests: 200ms, 400ms, 600ms
    export:
      datadog:
        step: 30s
        enabled: true
        api-key: xxxxxxx
    tags:
      application: ${spring.application.name}
      env: ${spring.profiles}

Can someone help me understand what is the issue? I tried searching around but din't get any solution. I tried replacing api-key with apiKey(I know it's silly) but no success.

Any help folks?


问:
Zeitwerk fails in production loading custom SimpleNavigation renderer
Getting ready for Rails 7 by shifting to Zeitwerk autoloader (Rails 6.1.4.4 on Ruby 2.7.5). Turned off the config.autoloader = :classic line in application.rb. App is loading 6.1 defaults.

Dev mode runs fine, but production fails on boot (also fails locally in production mode):

```<code>pid=4 tid=2l2g WARN: Zeitwerk::NameError: expected file /app/app/navigation_renderers/public_issue_renderer.rb to define constant PublicIssueRenderer, but didn't
pid=4 tid=2l2g WARN: /app/vendor/bundle/ruby/2.7.0/gems/zeitwerk-2.5.3/lib/zeitwerk/loader/callbacks.rb:25:in `on_file_autoloaded'
</code>```

(This is on Heroku-20 in a staging environment).

That file does define that as a class, however.:

```<code>module SimpleNavigation
  module Renderer
    class PublicIssueRenderer < SimpleNavigation::Renderer::Base
      [functions removed for brevity]
    end
  end
end
</code>```

I am not sure why the double /app/app exists, as the directory is simply in app along with everything else:

答:
The only way I was able to get past this was to put these two lines at the top of the file:

```<code>class PublicIssueRenderer
end
</code>```

and then continue with the module as shown above. Feels wrong, but it passes Zeitwerk and still works.

Body:
Getting ready for Rails 7 by shifting to Zeitwerk autoloader (Rails 6.1.4.4 on Ruby 2.7.5). Turned off the config.autoloader = :classic line in application.rb. App is loading 6.1 defaults.

Dev mode runs fine, but production fails on boot (also fails locally in production mode):

pid=4 tid=2l2g WARN: Zeitwerk::NameError: expected file /app/app/navigation_renderers/public_issue_renderer.rb to define constant PublicIssueRenderer, but didn't
pid=4 tid=2l2g WARN: /app/vendor/bundle/ruby/2.7.0/gems/zeitwerk-2.5.3/lib/zeitwerk/loader/callbacks.rb:25:in `on_file_autoloaded'

(This is on Heroku-20 in a staging environment).

That file does define that as a class, however.:

module SimpleNavigation
  module Renderer
    class PublicIssueRenderer < SimpleNavigation::Renderer::Base
      [functions removed for brevity]
    end
  end
end

I am not sure why the double /app/app exists, as the directory is simply in app along with everything else:

Body:
The only way I was able to get past this was to put these two lines at the top of the file:

class PublicIssueRenderer
end

and then continue with the module as shown above. Feels wrong, but it passes Zeitwerk and still works.


问:
Difference between Functions Bot, Web App Bot & Bot Channels Registration in Microsoft Azure?
What's the difference?
I couldn't find specific information about all three services here or on Microsoft Azure or on Azure Bot Service...</p>

答:
Registration of Web App Bot and Bot Channels is deprecated as of 9/1/2021. Azure Bot takes the place of both the Web App Bot resource and Bot Channels resource types.

https://learn.microsoft.com/en-us/learn/modules/intro-to-bot-service-bot-framework-composer/2-what-is-azure-bot-service


问:
Cannot read properties of null (reading 'id') [Discord Slash Commands]
I'm trying to get a little familiar with the slash command handler, but I get an error when trying to grab the member id, this happens with just about everything I try to grab.

Here at the top is directly my command, where I try to send a message with the content "user.id".

this is my command:

```<code>const { SlashCommandBuilder } = require("@discordjs/builders");

module.exports = {
    data: new SlashCommandBuilder()
    .setName("avatar")
    .setDescription("SERVUSSS")
    .addUserOption(option => option.setName("member").setDescription("memberdings").setRequired(true)),
    async execute(interaction) {
        const user = interaction.options.getUser('target');
        await interaction.reply(`${user.id}`);
    }
}
</code>```

this is my deploy file:

```<code>require("dotenv").config();
const fs = require("fs");
const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const commands = [];

const commandFiles = fs.readdirSync("./src/commands").filter(file => file.endsWith(".js"));

commandFiles.forEach(commandFile => {
    const command = require(`./commands/${commandFile}`);
    commands.push(command.data.toJSON());
});

const restClient = new REST({version: "9"}).setToken(process.env.TOKEN);

restClient.put(Routes.applicationGuildCommands(process.env.APPLICATION_ID, process.env.GUILD_ID),
{body: commands }).then(() => console.log("success")).catch(console.error);
</code>```

my index file:

```<code>require("dotenv").config();
const { Client, Collection } = require("discord.js");
const fs = require("fs");

const client = new Client({intents: []});
client.commands = new Collection();

const commandFiles = fs.readdirSync("./src/commands").filter(file => file.endsWith(".js"));

commandFiles.forEach(commandFile => {
    const command = require(`./commands/${commandFile}`);
    client.commands.set(command.data.name, command);
});

client.once("ready", () => {
    console.log("ready!!");
});

client.on("interactionCreate", async (interaction) => {
    if(!interaction.isCommand()) return;

    const command = client.commands.get(interaction.commandName)

    if(command) {
        try {
            await command.execute(interaction)
        } catch(error) {
            console.log(error)

            if(interaction.deferred || interaction.replied) {
                interaction.editReply("error")
            } else {
                interaction.reply("error")
            }
        }
    }
})

client.login(process.env.TOKEN)
</code>```

I actually stick to it pretty much all the time
https://discordjs.guide/ just do not understand what I'm doing wrong

答: In your command file, the name for the option is given as member, but when you are using interaction.options.getUser(), you are passing the name as 'target'. So all you have to do is change the line where you are declaring the user to: const user = interaction.options.getUser('member')

Body:
I'm trying to get a little familiar with the slash command handler, but I get an error when trying to grab the member id, this happens with just about everything I try to grab.

Here at the top is directly my command, where I try to send a message with the content "user.id".

this is my command:

const { SlashCommandBuilder } = require("@discordjs/builders");

module.exports = {
    data: new SlashCommandBuilder()
    .setName("avatar")
    .setDescription("SERVUSSS")
    .addUserOption(option => option.setName("member").setDescription("memberdings").setRequired(true)),
    async execute(interaction) {
        const user = interaction.options.getUser('target');
        await interaction.reply(`${user.id}`);
    }
}

this is my deploy file:

require("dotenv").config();
const fs = require("fs");
const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const commands = [];

const commandFiles = fs.readdirSync("./src/commands").filter(file => file.endsWith(".js"));

commandFiles.forEach(commandFile => {
    const command = require(`./commands/${commandFile}`);
    commands.push(command.data.toJSON());
});

const restClient = new REST({version: "9"}).setToken(process.env.TOKEN);

restClient.put(Routes.applicationGuildCommands(process.env.APPLICATION_ID, process.env.GUILD_ID),
{body: commands }).then(() => console.log("success")).catch(console.error);

my index file:

require("dotenv").config();
const { Client, Collection } = require("discord.js");
const fs = require("fs");

const client = new Client({intents: []});
client.commands = new Collection();

const commandFiles = fs.readdirSync("./src/commands").filter(file => file.endsWith(".js"));

commandFiles.forEach(commandFile => {
    const command = require(`./commands/${commandFile}`);
    client.commands.set(command.data.name, command);
});

client.once("ready", () => {
    console.log("ready!!");
});

client.on("interactionCreate", async (interaction) => {
    if(!interaction.isCommand()) return;

    const command = client.commands.get(interaction.commandName)

    if(command) {
        try {
            await command.execute(interaction)
        } catch(error) {
            console.log(error)

            if(interaction.deferred || interaction.replied) {
                interaction.editReply("error")
            } else {
                interaction.reply("error")
            }
        }
    }
})

client.login(process.env.TOKEN)

I actually stick to it pretty much all the time
https://discordjs.guide/ just do not understand what I'm doing wrong


问:
Most Pythonic and efficient to join list of strings until the length gets too high
Assume I am creating a checkout system for a store. This is a list of the products:

products = ["Apple", "Banana", "Cherry", "Durian"]
```
<p>And I want to join them with commas. So, I can use this:</p>
<pre class="lang-py prettyprint-override"><code>", ".join(products) # Returns "Apple, Banana, Cherry, Durian"
</code>```

What if I want to limit the length of the output string? Say, I want to output "Apple, Banana…" if the final string is longer than 20 characters?
The problem is, I want to prevent the names from being cut, so I don't want "Apple, Banana, Cher…". In some cases, the strings in products may contain commas, so I don't want to split the string with commas.

答:
```<code>products = ["Apple", "Banana", "Cherry", "Durian"]

string = products[0]

for v in products[1:]:
    if len(string) + len(', ') + len(v) <= 20:
        string = string + ', ' + v
    else:
        string = string + '...'
        break

print(string)
</code>```

Output:

```<code>Apple, Banana...
</code>```

Body:
Assume I am creating a checkout system for a store. This is a list of the products:

products = ["Apple", "Banana", "Cherry", "Durian"]

And I want to join them with commas. So, I can use this:

", ".join(products) # Returns "Apple, Banana, Cherry, Durian"

What if I want to limit the length of the output string? Say, I want to output "Apple, Banana…" if the final string is longer than 20 characters?
The problem is, I want to prevent the names from being cut, so I don't want "Apple, Banana, Cher…". In some cases, the strings in products may contain commas, so I don't want to split the string with commas.

Body:
products = ["Apple", "Banana", "Cherry", "Durian"]

string = products[0]

for v in products[1:]:
    if len(string) + len(', ') + len(v) <= 20:
        string = string + ', ' + v
    else:
        string = string + '...'
        break

print(string)

Output:

Apple, Banana...


问:
How to add a script into Bolt?

I have a C# script imported from asset store. I want to import it in Bolt for easier to use. I've researched for a long time, asked many people. Some of them said that I need to click into Tools - Bolt - Unit Option Wizard and add the type of the script, some of them said I just have to add it as an unit. I did all that ways but still can't achieve what I want.

答: If you just want to run the script from a flow machine(bolt visual scripting component on a object) a simple way is to assign the script to an empty object and set this object active from the flow machine. To have a reference to this object inside bolt, you need to add this object to the scene variables as a game object, then just drag and drop it inside the graph of your flow machine. Bolt flow machines and C# scripts can interact in many different ways, you can read and write variables from the graph/app/object inside the script too. If you want to know more about this, drop me a line. I hope I have answered your question. If so , remember to vote it up. If you set the object inactive, the script will stop running. I really wanna know too if there is another way, something like a node called "run script x"...</p>

Title: How to add a script into Bolt?


问:
How do I give input to a merged model?
I have created a model by merging five small models where each four of them take an array with four-element and the last one takes one.
My input array contains 626 lists of

```<code>[np.ones(4),np.ones(4), np.ones(4),np.ones(4),np.ones(1)]
</code>```

How do I give this as input while fitting the model?
How does batching work here?

答:
How about this</p>
```<code>tf.keras.Model(inputs=[input1, input2, input3], outputs=outputs)
</code>```

Title: How do I give input to a merged model?

Body:
I have created a model by merging five small models where each four of them take an array with four-element and the last one takes one.
My input array contains 626 lists of

[np.ones(4),np.ones(4), np.ones(4),np.ones(4),np.ones(1)]

How do I give this as input while fitting the model?
How does batching work here?

Body:
How about this

tf.keras.Model(inputs=[input1, input2, input3], outputs=outputs)


问:
ColdFusion Application datasource Property not accessible in CFM Template
The following is running on a ColdFusion 2018 server (in the event this is a version-specific issue).

I'm setting the Application datasource property in the onApplicationStart() LifeCycle Handler, but the datasource property isn't accessible in a CFM Template.

I'm thinking it may have something to do with how the this Scope is handled inside the onApplicationStart() method, but I'm not certain. I tried setting the datasource property using this.datasource as well as Application.datasource, but it's not accessible in the CFM Template either way.

Application.cfc

```<code>// The usual App config stuff here... (omitted for brevity)

// Instantiate Instance of Java System Object used to set System Env Vars
this.System = createObject("java", "java.lang.System");

// Include Config files
include "resources/config/AppSettings.cfm";
include "resources/config/onApplicationStart.cfm";
</code>```

AppSettings.cfm

```<code>if (! isDefined(this.System.getProperty("DB_DSN_CREATED")))
{
    // Code to read values from .env file here ... (omitted for brevity)

    // Set System Env Vars
    this.System.setProperty("DB_USER_NAME",     "DB USERNAME FROM .ENV FILE HERE");
    this.System.setProperty("DB_USER_PASSWORD", "DB PASSWORD FROM .ENV FILE HERE");
}
</code>```

onApplicationStart.cfm

```<code>if (! isDefined(this.System.getProperty("DB_DSN_CREATED")))
{
    this.datasources = {MY_DSN = { PROPS FOR DB CONNECTION HERE }};

    // *** NOTE: This is the Property that isn't accessible in the CFM Template
    //           I also tried Application.datasource, but that didn't work either
    this.datasource = "MY_DSN";

    this.System.setProperty("DB_DSN_CREATED", true);
}
</code>```

db-test.cfm

```<code><cfscript>
    variables.appInstance = createObject('component', 'Application');

    variables.sql = "SQL STATEMENT HERE";
    variables.sqlParams = {};

    // *** NOTE: variables.appInstance.datasource below isn't accessible
    //           I also tried Application.datasource but that didn't work either
    variables.sqlResult = queryExecute(variables.sql, variables.sqlParams, {datasource = variables.appInstance.datasource});

    writeDump(variables.sqlResult);
</cfscript>
</code>```

Does anyone see what I'm missing? Thanks in advance for any guidance!

答:
Thinking on this some more, I suspect you may be misunderstanding how an Application.cfc's this scope operates. Short answer:  this isn't persistent, like the application scope, because the component gets instantiated on every request

From Defining the application and its event handlers in
Application.cfc

When ColdFusion receives a request, it instantiates the
Application CFC and runs the Application.cfc code ...

Your code actually does work. At least in the sense that the include successfully changes the value of this.datasource when invoked. However, since the Application.cfc gets instantiated anew on every request, the component's this scope also gets recreated. Essentially wiping out any previous changes made inside OnApplicationStart(). That's why it seems like the code never assigns a datasource value, when it actually does.

Bottom line, an Application.cfc's this scope isn't intended to be used that way.

Test Case

FWIW, you can see the behavior in action using the test files below. Just load test.cfm in a browser (at least twice) then check the logs. The output shows a value IS assigned to this.datasource the very first time test.cfm is requested from the application. However, that value disappears on the next http request because CF creates a new Application.cfc instance.

Application.cfc

```<code>component
{
    this.name = "myApp_0001";

    function onApplicationStart(){
        writeLog("onApplicationStart()");
        writeLog(serializeJSON({"name": this.name, "datasource": this?.datasource?: "" }));
        include "onApplicationStart.cfm";
    }
    function onRequestStart( string targetPage ) {
        writeLog("onRequestStart()");
        writeLog(serializeJSON({"name": this.name, "datasource": this?.datasource?: "" }));
    }

}
</code>```

OnApplicationStart.cfm

```<code><cfscript>
    writeLog("onApplicationStart.cfm");
    writeLog(serializeJSON({"name": this.name, "datasource": this?.datasource?: "" }));

    writeLog("Assigning this.datasource");
    this.datasource = "MY_DSN";

    writeLog("Post Assign this.datasource");
    writeLog(serializeJSON({"name": this.name, "datasource": this?.datasource?: "" }));
</cfscript>
</code>```

test.cfm

```<code><h3>Test.cfm <cfoutput>#now()#</cfoutput></h3>
</code>```

Results:

```<code>Request #1 - this.Datasource gets assigned
[INFO ] ... - onApplicationStart()
[INFO ] ... - {""datasource"":"""",""name"":""myApp_0001""}
[INFO ] ... - onApplicationStart.cfm
[INFO ] ... - {""datasource"":"""",""name"":""myApp_0001""}
[INFO ] ... - Assigning this.datasource
[INFO ] ... - Post Assign this.datasource
[INFO ] ... - {""datasource"":""MY_DSN"",""name"":""myApp_0001""}
[INFO ] ... - onRequestStart()
[INFO ] ... - {""datasource"":""MY_DSN"",""name"":""myApp_0001""}

Request #2 - this.datasource is no longer assigned
[INFO ] ... - onRequestStart()
[INFO ] ... - {""datasource"":"""",""name"":""myApp_0001""}

Request #3 - this.datasource is no longer assigned
[INFO ] ... - onRequestStart()
[INFO ] ... - {""datasource"":"""",""name"":""myApp_0001""}
</code>```

Body:
The following is running on a ColdFusion 2018 server (in the event this is a version-specific issue).

I'm setting the Application datasource property in the onApplicationStart() LifeCycle Handler, but the datasource property isn't accessible in a CFM Template.

I'm thinking it may have something to do with how the this Scope is handled inside the onApplicationStart() method, but I'm not certain. I tried setting the datasource property using this.datasource as well as Application.datasource, but it's not accessible in the CFM Template either way.

Application.cfc

// The usual App config stuff here... (omitted for brevity)

// Instantiate Instance of Java System Object used to set System Env Vars
this.System = createObject("java", "java.lang.System");

// Include Config files
include "resources/config/AppSettings.cfm";
include "resources/config/onApplicationStart.cfm";

AppSettings.cfm

if (! isDefined(this.System.getProperty("DB_DSN_CREATED")))
{
    // Code to read values from .env file here ... (omitted for brevity)

    // Set System Env Vars
    this.System.setProperty("DB_USER_NAME",     "DB USERNAME FROM .ENV FILE HERE");
    this.System.setProperty("DB_USER_PASSWORD", "DB PASSWORD FROM .ENV FILE HERE");
}

onApplicationStart.cfm

if (! isDefined(this.System.getProperty("DB_DSN_CREATED")))
{
    this.datasources = {MY_DSN = { PROPS FOR DB CONNECTION HERE }};

    // *** NOTE: This is the Property that isn't accessible in the CFM Template
    //           I also tried Application.datasource, but that didn't work either
    this.datasource = "MY_DSN";

    this.System.setProperty("DB_DSN_CREATED", true);
}

db-test.cfm

<cfscript>
    variables.appInstance = createObject('component', 'Application');

    variables.sql = "SQL STATEMENT HERE";
    variables.sqlParams = {};

    // *** NOTE: variables.appInstance.datasource below isn't accessible
    //           I also tried Application.datasource but that didn't work either
    variables.sqlResult = queryExecute(variables.sql, variables.sqlParams, {datasource = variables.appInstance.datasource});

    writeDump(variables.sqlResult);
</cfscript>

Does anyone see what I'm missing? Thanks in advance for any guidance!

Body:
Thinking on this some more, I suspect you may be misunderstanding how an Application.cfc's this scope operates. Short answer:  this isn't persistent, like the application scope, because the component gets instantiated on every request

From Defining the application and its event handlers in
Application.cfc

When ColdFusion receives a request, it instantiates the
Application CFC and runs the Application.cfc code ...

Your code actually does work. At least in the sense that the include successfully changes the value of this.datasource when invoked. However, since the Application.cfc gets instantiated anew on every request, the component's this scope also gets recreated. Essentially wiping out any previous changes made inside OnApplicationStart(). That's why it seems like the code never assigns a datasource value, when it actually does.

Bottom line, an Application.cfc's this scope isn't intended to be used that way.

Test Case

FWIW, you can see the behavior in action using the test files below. Just load test.cfm in a browser (at least twice) then check the logs. The output shows a value IS assigned to this.datasource the very first time test.cfm is requested from the application. However, that value disappears on the next http request because CF creates a new Application.cfc instance.

Application.cfc

component
{
    this.name = "myApp_0001";

    function onApplicationStart(){
        writeLog("onApplicationStart()");
        writeLog(serializeJSON({"name": this.name, "datasource": this?.datasource?: "" }));
        include "onApplicationStart.cfm";
    }
    function onRequestStart( string targetPage ) {
        writeLog("onRequestStart()");
        writeLog(serializeJSON({"name": this.name, "datasource": this?.datasource?: "" }));
    }

}

OnApplicationStart.cfm

<cfscript>
    writeLog("onApplicationStart.cfm");
    writeLog(serializeJSON({"name": this.name, "datasource": this?.datasource?: "" }));

    writeLog("Assigning this.datasource");
    this.datasource = "MY_DSN";

    writeLog("Post Assign this.datasource");
    writeLog(serializeJSON({"name": this.name, "datasource": this?.datasource?: "" }));
</cfscript>

test.cfm

<h3>Test.cfm <cfoutput>#now()#</cfoutput></h3>

Results:

Request #1 - this.Datasource gets assigned
[INFO ] ... - onApplicationStart()
[INFO ] ... - {""datasource"":"""",""name"":""myApp_0001""}
[INFO ] ... - onApplicationStart.cfm
[INFO ] ... - {""datasource"":"""",""name"":""myApp_0001""}
[INFO ] ... - Assigning this.datasource
[INFO ] ... - Post Assign this.datasource
[INFO ] ... - {""datasource"":""MY_DSN"",""name"":""myApp_0001""}
[INFO ] ... - onRequestStart()
[INFO ] ... - {""datasource"":""MY_DSN"",""name"":""myApp_0001""}

Request #2 - this.datasource is no longer assigned
[INFO ] ... - onRequestStart()
[INFO ] ... - {""datasource"":"""",""name"":""myApp_0001""}

Request #3 - this.datasource is no longer assigned
[INFO ] ... - onRequestStart()
[INFO ] ... - {""datasource"":"""",""name"":""myApp_0001""}


问:
How do you implement quick sort to sort in descending order (java)?
This current quicksort implementation will sort an array to be in ascending order. How do I change this code so that it will sort an array to be in descending order? I need some help reversing the logic. Advice would be much appreciated.</p>
```<code>    public void quickSort(int[] array) {

    // An array of size 1 is already sorted
    if (array.length < 2)
        return;

    // Find the largest element and put it at the end of the array
    int max = 0;
    for (int i = 1; i < array.length; i++) {
        if (array[i] > array[max]) {
            max = i;
        }
    }
    swap(array, array.length-1, max);

    // Call the main quicksort method
    quicksort(array, 0, array.length-1);
}

public void quicksort(int[] array, int first, int last) {

    int lower = first + 1, upper = last;

    // Use the middle array element as the bound (pivot) and
    // move it out of the way into the first array element
    swap(array, first, (first + last)/2);
    int bound = array[first];

    // Partition the array
    while (lower <= upper) {
        while (array[lower] < bound) {
            lower++;
        }
        while (array[upper] > bound) {
            upper--;
        }
        if (lower < upper) {
            swap(array, lower++, upper--);
        }
        else {
            lower++;
        }
    }

    // Move the pivot into its proper position in the array
    swap(array, upper, first);

    // Recursively sort the lower and upper subarrays
    if (first < upper-1) {
        quicksort(array, first, upper-1);
    }

    if ((upper+1) < last) {
        quicksort(array, upper+1, last);
    }
}
</code>```

答:
So the basic concept would be to modify...

```<code>while (array[lower] < bound) {
    lower++;
}
while (array[upper] > bound) {
    upper--;
}
</code>```

to match your requirements, but it's not particularly reusable.  Instead, we want to delegate the comparison so that we can use the same code, but which can allow for different algorithms to be used, for example...

```<code>public class QuickSort {

    public static interface Matcher {

        public int compare(int lhs, int rhs);
    }

    public static void sort(int[] array, Matcher matcher) {

        // An array of size 1 is already sorted
        if (array.length < 2) {
            return;
        }

        // Find the largest element and put it at the end of the array
        int max = 0;
        for (int i = 1; i < array.length; i++) {
            if (matcher.compare(array[i], array[max]) > 0) {
                max = 1;
            }
        }
        swap(array, array.length - 1, max);

        // Call the main quicksort method
        sort(array, 0, array.length - 1, matcher);
    }

    protected static void sort(int[] array, int first, int last, Matcher matcher) {

        int lower = first + 1, upper = last;

        // Use the middle array element as the bound (pivot) and
        // move it out of the way into the first array element
        swap(array, first, (first + last) / 2);
        int bound = array[first];

        // Partition the array
        while (lower <= upper) {
            while (matcher.compare(array[lower], bound) < 0) {
                lower++;
            }
            while (matcher.compare(array[upper], bound) > 0) {
                upper--;
            }
            if (lower < upper) {
                swap(array, lower++, upper--);
            } else {
                lower++;
            }
        }

        // Move the pivot into its proper position in the array
        swap(array, upper, first);

        // Recursively sort the lower and upper subarrays
        if (first < upper - 1) {
            sort(array, first, upper - 1, matcher);
        }

        if ((upper + 1) < last) {
            sort(array, upper + 1, last, matcher);
        }
    }

    protected static void swap(int[] values, int first, int second) {
        int temp = values[first];
        values[first] = values[second];
        values[second] = temp;
    }
}
</code>```

Which can then be used something like...

```<code>int[] values = new int[]{1, 0, 2, 9, 3, 8, 4, 7, 5, 6};

QuickSort.sort(values, new QuickSort.Matcher() {
    @Override
    public int compare(int lhs, int rhs) {
        return Integer.compare(lhs, rhs);
    }
});
System.out.println(Arrays.toString(values));

QuickSort.sort(values, new QuickSort.Matcher() {
    @Override
    public int compare(int lhs, int rhs) {
        return Integer.compare(rhs, lhs);
    }
});
System.out.println(Arrays.toString(values));
</code>```

which will output...

```<code>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
</code>```

Body:
This current quicksort implementation will sort an array to be in ascending order. How do I change this code so that it will sort an array to be in descending order? I need some help reversing the logic. Advice would be much appreciated.

    public void quickSort(int[] array) {

    // An array of size 1 is already sorted
    if (array.length < 2)
        return;

    // Find the largest element and put it at the end of the array
    int max = 0;
    for (int i = 1; i < array.length; i++) {
        if (array[i] > array[max]) {
            max = i;
        }
    }
    swap(array, array.length-1, max);

    // Call the main quicksort method
    quicksort(array, 0, array.length-1);
}

public void quicksort(int[] array, int first, int last) {

    int lower = first + 1, upper = last;

    // Use the middle array element as the bound (pivot) and
    // move it out of the way into the first array element
    swap(array, first, (first + last)/2);
    int bound = array[first];

    // Partition the array
    while (lower <= upper) {
        while (array[lower] < bound) {
            lower++;
        }
        while (array[upper] > bound) {
            upper--;
        }
        if (lower < upper) {
            swap(array, lower++, upper--);
        }
        else {
            lower++;
        }
    }

    // Move the pivot into its proper position in the array
    swap(array, upper, first);

    // Recursively sort the lower and upper subarrays
    if (first < upper-1) {
        quicksort(array, first, upper-1);
    }

    if ((upper+1) < last) {
        quicksort(array, upper+1, last);
    }
}

Body:
So the basic concept would be to modify...

while (array[lower] < bound) {
    lower++;
}
while (array[upper] > bound) {
    upper--;
}

to match your requirements, but it's not particularly reusable.  Instead, we want to delegate the comparison so that we can use the same code, but which can allow for different algorithms to be used, for example...

public class QuickSort {

    public static interface Matcher {

        public int compare(int lhs, int rhs);
    }

    public static void sort(int[] array, Matcher matcher) {

        // An array of size 1 is already sorted
        if (array.length < 2) {
            return;
        }

        // Find the largest element and put it at the end of the array
        int max = 0;
        for (int i = 1; i < array.length; i++) {
            if (matcher.compare(array[i], array[max]) > 0) {
                max = 1;
            }
        }
        swap(array, array.length - 1, max);

        // Call the main quicksort method
        sort(array, 0, array.length - 1, matcher);
    }

    protected static void sort(int[] array, int first, int last, Matcher matcher) {

        int lower = first + 1, upper = last;

        // Use the middle array element as the bound (pivot) and
        // move it out of the way into the first array element
        swap(array, first, (first + last) / 2);
        int bound = array[first];

        // Partition the array
        while (lower <= upper) {
            while (matcher.compare(array[lower], bound) < 0) {
                lower++;
            }
            while (matcher.compare(array[upper], bound) > 0) {
                upper--;
            }
            if (lower < upper) {
                swap(array, lower++, upper--);
            } else {
                lower++;
            }
        }

        // Move the pivot into its proper position in the array
        swap(array, upper, first);

        // Recursively sort the lower and upper subarrays
        if (first < upper - 1) {
            sort(array, first, upper - 1, matcher);
        }

        if ((upper + 1) < last) {
            sort(array, upper + 1, last, matcher);
        }
    }

    protected static void swap(int[] values, int first, int second) {
        int temp = values[first];
        values[first] = values[second];
        values[second] = temp;
    }
}

Which can then be used something like...

int[] values = new int[]{1, 0, 2, 9, 3, 8, 4, 7, 5, 6};

QuickSort.sort(values, new QuickSort.Matcher() {
    @Override
    public int compare(int lhs, int rhs) {
        return Integer.compare(lhs, rhs);
    }
});
System.out.println(Arrays.toString(values));

QuickSort.sort(values, new QuickSort.Matcher() {
    @Override
    public int compare(int lhs, int rhs) {
        return Integer.compare(rhs, lhs);
    }
});
System.out.println(Arrays.toString(values));

which will output...

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]


问:
Unhandled Runtime Error while executing a JS code
On my Localhost:3000, when I am running the code, I am getting an error saying:

```<code>Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'id')
</code>```

For the Source part, it is showing a certain section of my code, which is:-

```<code>    ;(async () => {
  20 |     setSelectedMarketNft(
> 21 |       listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
     |                                                                       ^
  22 |     )
  23 |   })()
  24 | }, [selectedNft, listings, isListed])
</code>```

There are certain questions of the similar type on stackOverflow, but I am unable to find any answers from any of them. I am making a web3 project, where I am using next.js, sanity and thirweb.

The source code that contains this is:-

```<code> const MakeOffer = ({ isListed, selectedNft, listings, marketPlaceModule }) => {
  const [selectedMarketNft, setSelectedMarketNft] = useState()
  const [enableButton, setEnableButton] = useState(false)

  useEffect(() => {
    if (!listings || isListed === 'false') return
    ;(async () => {
      setSelectedMarketNft(
        listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
      )
    })()
  }, [selectedNft, listings, isListed])

  useEffect(() => {
    if (!selectedMarketNft || !selectedNft) return

    setEnableButton(true)
  }, [selectedMarketNft, selectedNft])
</code>```

Link to the full source code of the file where this error is occuring is:-
https://github.com/hemang-h/Standard-Demo-Marketplace-and-Minting/blob/main/components/nft/Purchase.js

Can anyone guide me what I am doing wrong here?

EXTRAS
Just for a better understanding, this is the full source code of the file where I am facing this error:

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

import { HiTag } from 'react-icons/hi'
import { IoMdWallet } from 'react-icons/io'
import toast, { Toaster } from 'react-hot-toast'

const style = {
  button: `mr-8 flex items-center py-2 px-12 rounded-lg cursor-pointer`,
  buttonIcon: `text-xl`,
  buttonText: `ml-2 text-lg font-semibold`,
}

const MakeOffer = ({ isListed, selectedNft, listings, marketPlaceModule }) => {
  const [selectedMarketNft, setSelectedMarketNft] = useState()
  const [enableButton, setEnableButton] = useState(false)

  useEffect(() => {
    if (!listings || isListed === 'false') return
    ;(async () => {
      setSelectedMarketNft(
        listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
      )
    })()
  }, [selectedNft, listings, isListed])

  useEffect(() => {
    if (!selectedMarketNft || !selectedNft) return

    setEnableButton(true)
  }, [selectedMarketNft, selectedNft])

  const confirmPurchase = (toastHandler = toast) =>
    toastHandler.success(`Purchase successful!`, {
      style: {
        background: '#04111d',
        color: '#fff',
      },
    })

  const buyItem = async (
    listingId = selectedMarketNft.id,
    quantityDesired = 1,
    module = marketPlaceModule
  ) => {
    console.log(listingId, quantityDesired, module, 'david')
    // yo RAZA lets goooo!!!
    //yo Qazi, ok
    // sure okay about to run it...
    // just clicked buy now...
    // still error
    // where can i see the contract address of the marketplace module
    // in [nftId.js]
    await module
      .buyoutDirectListing({
        listingId: listingId,
        quantityDesired: quantityDesired,
      })
      .catch((error) => console.error(error))

    confirmPurchase()
  }

  return (
    <div className="flex h-20 w-full items-center rounded-lg border border-[#151c22] bg-[#303339] px-12">
      <Toaster position="bottom-left" reverseOrder={false} />
      {isListed === 'true' ? (
        <>
          <div
            onClick={() => {
              enableButton ? buyItem(selectedMarketNft.id, 1) : null
            }}
            className={`${style.button} bg-[#2081e2] hover:bg-[#42a0ff]`}
          >
            <IoMdWallet className={style.buttonIcon} />
            <div className={style.buttonText}>Buy Now</div>
          </div>
          <div
            className={`${style.button} border border-[#151c22]  bg-[#363840] hover:bg-[#4c505c]`}
          >
            <HiTag className={style.buttonIcon} />
            <div className={style.buttonText}>Make Offer</div>
          </div>
        </>
      ) : (
        <div className={`${style.button} bg-[#2081e2] hover:bg-[#42a0ff]`}>
          <IoMdWallet className={style.buttonIcon} />
          <div className={style.buttonText}>List Item</div>
        </div>
      )}
    </div>
  )
}

export default MakeOffer
</code>```

答: You can check by console seletedNft inside makeoffer component to make sure you are getting props correctly and also check if its return object which has key  with name "id" . Its cannot read id property in your selectedNft make sure its exist . I hope its help.</p>

Body:
On my Localhost:3000, when I am running the code, I am getting an error saying:

Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'id')

For the Source part, it is showing a certain section of my code, which is:-

    ;(async () => {
  20 |     setSelectedMarketNft(
> 21 |       listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
     |                                                                       ^
  22 |     )
  23 |   })()
  24 | }, [selectedNft, listings, isListed])

There are certain questions of the similar type on stackOverflow, but I am unable to find any answers from any of them. I am making a web3 project, where I am using next.js, sanity and thirweb.

The source code that contains this is:-

 const MakeOffer = ({ isListed, selectedNft, listings, marketPlaceModule }) => {
  const [selectedMarketNft, setSelectedMarketNft] = useState()
  const [enableButton, setEnableButton] = useState(false)

  useEffect(() => {
    if (!listings || isListed === 'false') return
    ;(async () => {
      setSelectedMarketNft(
        listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
      )
    })()
  }, [selectedNft, listings, isListed])

  useEffect(() => {
    if (!selectedMarketNft || !selectedNft) return

    setEnableButton(true)
  }, [selectedMarketNft, selectedNft])

Link to the full source code of the file where this error is occuring is:-
https://github.com/hemang-h/Standard-Demo-Marketplace-and-Minting/blob/main/components/nft/Purchase.js

Can anyone guide me what I am doing wrong here?

EXTRAS
Just for a better understanding, this is the full source code of the file where I am facing this error:

import { useEffect, useState } from 'react'

import { HiTag } from 'react-icons/hi'
import { IoMdWallet } from 'react-icons/io'
import toast, { Toaster } from 'react-hot-toast'

const style = {
  button: `mr-8 flex items-center py-2 px-12 rounded-lg cursor-pointer`,
  buttonIcon: `text-xl`,
  buttonText: `ml-2 text-lg font-semibold`,
}

const MakeOffer = ({ isListed, selectedNft, listings, marketPlaceModule }) => {
  const [selectedMarketNft, setSelectedMarketNft] = useState()
  const [enableButton, setEnableButton] = useState(false)

  useEffect(() => {
    if (!listings || isListed === 'false') return
    ;(async () => {
      setSelectedMarketNft(
        listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
      )
    })()
  }, [selectedNft, listings, isListed])

  useEffect(() => {
    if (!selectedMarketNft || !selectedNft) return

    setEnableButton(true)
  }, [selectedMarketNft, selectedNft])

  const confirmPurchase = (toastHandler = toast) =>
    toastHandler.success(`Purchase successful!`, {
      style: {
        background: '#04111d',
        color: '#fff',
      },
    })

  const buyItem = async (
    listingId = selectedMarketNft.id,
    quantityDesired = 1,
    module = marketPlaceModule
  ) => {
    console.log(listingId, quantityDesired, module, 'david')
    // yo RAZA lets goooo!!!
    //yo Qazi, ok
    // sure okay about to run it...
    // just clicked buy now...
    // still error
    // where can i see the contract address of the marketplace module
    // in [nftId.js]
    await module
      .buyoutDirectListing({
        listingId: listingId,
        quantityDesired: quantityDesired,
      })
      .catch((error) => console.error(error))

    confirmPurchase()
  }

  return (

      <Toaster position="bottom-left" reverseOrder={false} />
      {isListed === 'true' ? (
        <>

 {
              enableButton ? buyItem(selectedMarketNft.id, 1) : null
            }}
            className={`${style.button} bg-[#2081e2] hover:bg-[#42a0ff]`}
          >
            <IoMdWallet className={style.buttonIcon} />

Buy Now

          <div
            className={`${style.button} border border-[#151c22]  bg-[#363840] hover:bg-[#4c505c]`}
          >
            <HiTag className={style.buttonIcon} />

Make Offer

        </>
      ) : (
        <div className={`${style.button} bg-[#2081e2] hover:bg-[#42a0ff]`}>
          <IoMdWallet className={style.buttonIcon} />

List Item

      )}

  )
}

export default MakeOffer


问:
How do I access the filesystem outside of the sandbox on a jailbroken iOS device?
I'm going to develop a simple app for jailbroken iOS devices.  I would like to access the filesystem of the device outside of the app's sandbox and move some files (from a directory to another, for example).

How can I do this using Xcode 3.1 or 4, compatible with OS version 3.1.3?

答: Just use NSFileManager. On a jailbroken device, it gives you full access to the filesystem—just give it the paths you want to mess with. You can get the contents of a directory with its -contentsOfDirectoryAtPath:error: method and move files around with -moveItemAtPath:toPath:error:.

ContentLicense: CC BY-SA 3.0


问:
Get Download URL from Firebase Storage in Flutter
I'm currently exploring Flutter, I found there is an official Firebase Storage plugin in Flutter firebase_storage
I have storage reference like this one:

```<code>final StorageReference ref = FirebaseStorage.instance.ref().child("default.png");
</code>```

But there is no method to get download URL from that StorageReference.

答:
Try This</p>
```<code>Future<String> uploadFile(XFile _file) async {
File file = File(_file.path);
try {
  var ref = FirebaseStorage.instance.ref('uploads/' + _file.name);
  var uploadTask = await ref.putFile(file);
  if (uploadTask.state == TaskState.success) {
    final url = await ref.getDownloadURL();
    return url;
  }
  return "0";
} catch (e) {
  print(e);
  return e.toString();
  }
}
</code>```

Body:
I'm currently exploring Flutter, I found there is an official Firebase Storage plugin in Flutter firebase_storage
I have storage reference like this one:

final StorageReference ref = FirebaseStorage.instance.ref().child("default.png");

But there is no method to get download URL from that StorageReference.

Body:
Try This

Future<String> uploadFile(XFile _file) async {
File file = File(_file.path);
try {
  var ref = FirebaseStorage.instance.ref('uploads/' + _file.name);
  var uploadTask = await ref.putFile(file);
  if (uploadTask.state == TaskState.success) {
    final url = await ref.getDownloadURL();
    return url;
  }
  return "0";
} catch (e) {
  print(e);
  return e.toString();
  }
}


问:
How to make a line graph in ggplot with discrete x-axis?
So I have a table as follows:

```<code>data <- structure(list(Variable = c("Content", "Content", "Content",
"Content", "Content", "Content"), content_type = c("LIVE",
"LIVE", "LIVE", "VOD", "VOD", "VOD"), CURRENT_STATUS = c("ACTIVE",
"CANCELLED", "EXPIRED", "ACTIVE", "CANCELLED", "EXPIRED"), `1 Day` = c(0.768763, 0.734808, 0.714794, 1.200606, 0.766533,
0.765004), `7 Day` = c(1.181393, 0.989723, 1.035509,
3.793286, 1.734361, 2.112217), `14 Day` = c(1.431612,
1.123995, 1.206466, 5.428656, 2.226542, 2.868766),
    `21 Day` = c(1.609405, 1.189455, 1.313989, 6.671368, 2.485925,
    3.381902), `28 Day` = c(1.785089, 1.237489, 1.415171,
    7.717914, 2.678954, 3.795692), `35 Day` = c(1.945274,
    1.274576, 1.488107, 8.644254, 2.815237, 4.101302), `42 Day` = c(2.095211, 1.306524, 1.540499, 9.465924, 2.932306,
    4.320128), `49 Day` = c(2.286882, 1.344057, 1.616501,
    10.245316, 3.04714, 4.532644), `56 Day` = c(2.426061,
    1.369303, 1.666257, 10.937274, 3.169794, 4.709551), `90 Day` = c(2.974361, 1.435433, 1.812601, 13.656243,
    3.419348, 5.263874)), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))
</code>```

So each of the columns which numeric data are as follows:

```<code>1 Day
7 Day
14 Day
21 Day
...
90 Day
</code>```

So I want each of the days to be a tick on the x-axis, and the y value to be the value, 3 lines total for each current_status and two tables, for each content_type.

I am expecting it to look something like this:

```<code>ggplot(df, aes(x = day, y = count)) +
  geom_line(aes(color = CURRENT_STATUS, linetype = CURRENT_STATUS))+
facet_wrap(~content_type)
</code>```

But I am unsure how to represent the days (which are strings as the variable names) as their actual numeric day values on the x axis (consequently, y being count would be all the values in the table....

So basically, I need to wrangle this table to make sense for a line graph with the specifications above.

答:
I think you just need to pivot your data, order the days, and assign a grouping in the aesthetic:

```<code>library(tidyverse)

data_long <- data %>%
  pivot_longer(cols = ends_with("Day"),
           names_to = "day",
           values_to = "count") %>%
  mutate(day = as_factor(day))

  ggplot(data = data_long, aes(x = day, y = count, group = CURRENT_STATUS)) +
  geom_line(aes(color = CURRENT_STATUS, linetype = CURRENT_STATUS)) +
  facet_wrap(~content_type)
</code>```

Body:
So I have a table as follows:

data <- structure(list(Variable = c("Content", "Content", "Content",
"Content", "Content", "Content"), content_type = c("LIVE",
"LIVE", "LIVE", "VOD", "VOD", "VOD"), CURRENT_STATUS = c("ACTIVE",
"CANCELLED", "EXPIRED", "ACTIVE", "CANCELLED", "EXPIRED"), `1 Day` = c(0.768763, 0.734808, 0.714794, 1.200606, 0.766533,
0.765004), `7 Day` = c(1.181393, 0.989723, 1.035509,
3.793286, 1.734361, 2.112217), `14 Day` = c(1.431612,
1.123995, 1.206466, 5.428656, 2.226542, 2.868766),
    `21 Day` = c(1.609405, 1.189455, 1.313989, 6.671368, 2.485925,
    3.381902), `28 Day` = c(1.785089, 1.237489, 1.415171,
    7.717914, 2.678954, 3.795692), `35 Day` = c(1.945274,
    1.274576, 1.488107, 8.644254, 2.815237, 4.101302), `42 Day` = c(2.095211, 1.306524, 1.540499, 9.465924, 2.932306,
    4.320128), `49 Day` = c(2.286882, 1.344057, 1.616501,
    10.245316, 3.04714, 4.532644), `56 Day` = c(2.426061,
    1.369303, 1.666257, 10.937274, 3.169794, 4.709551), `90 Day` = c(2.974361, 1.435433, 1.812601, 13.656243,
    3.419348, 5.263874)), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))

So each of the columns which numeric data are as follows:

1 Day
7 Day
14 Day
21 Day
...
90 Day

So I want each of the days to be a tick on the x-axis, and the y value to be the value, 3 lines total for each current_status and two tables, for each content_type.

I am expecting it to look something like this:

ggplot(df, aes(x = day, y = count)) +
  geom_line(aes(color = CURRENT_STATUS, linetype = CURRENT_STATUS))+
facet_wrap(~content_type)

But I am unsure how to represent the days (which are strings as the variable names) as their actual numeric day values on the x axis (consequently, y being count would be all the values in the table....

So basically, I need to wrangle this table to make sense for a line graph with the specifications above.

Body:
I think you just need to pivot your data, order the days, and assign a grouping in the aesthetic:

library(tidyverse)

data_long <- data %>%
  pivot_longer(cols = ends_with("Day"),
           names_to = "day",
           values_to = "count") %>%
  mutate(day = as_factor(day))

  ggplot(data = data_long, aes(x = day, y = count, group = CURRENT_STATUS)) +
  geom_line(aes(color = CURRENT_STATUS, linetype = CURRENT_STATUS)) +
  facet_wrap(~content_type)


问:
How do iterate a sequence with varying starting positions
Say I have an array:

```<code>[10,12,20,50]
</code>```

I can iterate though this array like normal which would look at the position at 0, then 1, 2, and 3.

What if I wanted to start an any arbritrary position in the array, and then go through all the numbers in order.

So the other permutations would be:

```<code>10,12,20,50
12,20,50,10
20,50,10,12
50,10,12,20
</code>```

Is there a general function that would allow me to do this type of sliding iteration?

so looking at the index positions from the above it would be:

```<code>0,1,2,3
1,2,3,0
2,3,0,1
3,0,1,2
</code>```

It would be great if some languages have this built in, but I want to know the algorithm to do this also so I understand.

答:
Let's iterate over an array.

```<code>val arr = Array(10, 12, 20, 50)

for (i <- 0 to arr.length - 1) {
    println(arr(i))
}
</code>```

With output:

```<code>10
12
20
50
</code>```

Pretty basic.

What about:

```<code>val arr = Array(10, 12, 20, 50)

for (i <- 2 to (2 + arr.length - 1)) {
    println(arr(i))
}
</code>```

Oops. Out of bounds. But what if we modulo that index by the length of the array?

```<code>val arr = Array(10, 12, 20, 50)

for (i <- 2 to (2 + arr.length - 1)) {
    println(arr(i % arr.length))
}
</code>```
```<code>20
50
10
12
</code>```

Now you just need to wrap it up in a function that replaces 2 in that example with an argument.

Body:
Say I have an array:

[10,12,20,50]

I can iterate though this array like normal which would look at the position at 0, then 1, 2, and 3.

What if I wanted to start an any arbritrary position in the array, and then go through all the numbers in order.

So the other permutations would be:

10,12,20,50
12,20,50,10
20,50,10,12
50,10,12,20

Is there a general function that would allow me to do this type of sliding iteration?

so looking at the index positions from the above it would be:

0,1,2,3
1,2,3,0
2,3,0,1
3,0,1,2

It would be great if some languages have this built in, but I want to know the algorithm to do this also so I understand.

Body:
Let's iterate over an array.

val arr = Array(10, 12, 20, 50)

for (i <- 0 to arr.length - 1) {
    println(arr(i))
}

With output:

10
12
20
50

Pretty basic.

What about:

val arr = Array(10, 12, 20, 50)

for (i <- 2 to (2 + arr.length - 1)) {
    println(arr(i))
}

Oops. Out of bounds. But what if we modulo that index by the length of the array?

val arr = Array(10, 12, 20, 50)

for (i <- 2 to (2 + arr.length - 1)) {
    println(arr(i % arr.length))
}

20
50
10
12

Now you just need to wrap it up in a function that replaces 2 in that example with an argument.


问:
OSError: someObject.o: cannot open shared object file: No such file or directory
I'm failing to load a shared object library with python. I've tried setting the LD_LIBRARY_PATH to where the someObject.o is located and that works when I am using non-sudo command to run the python script but when I use sudo I run into a linking error.

```<code>OSError: bbumintflib.o: cannot open shared object file: No such file or directory
</code>```

Does anyone know how to link a .o file to the .so file?

using ldd, I know the .so cannot find the .o file.

```<code>>>>ldd someSharedObject.so
linux-vdso.so.1 (0x00007ffca69af000)
someObject.o => not found
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f53c96b8000)
/lib64/ld-linux-x86-64.so.2 (0x00007f53c9a57000)
</code>```

Edit:

This is how I am building the object and sharedObject files

```<code>gcc -I ../include -I../../module1/include -I ../../module2/include --shared -fPIC someCFile.c -o someObject.o plat_linux.c

gcc someObject.o -shared -o someSharedObject.so
</code>```

答:
This is your problem:

```<code>gcc -I ../include -I../../module1/include -I ../../module2/include --shared -fPIC someCFile.c -o someObject.o plat_linux.c
gcc someObject.o -shared -o someSharedObject.so
</code>```

The first command produces a shared library with odd name someObject.o.

The second command links a new shared library named someSharedObject.so, which depends on someObject.o.

To fix this, do this:

```<code>gcc -I ... --shared -fPIC someCFile.c plat_linux.c -o someSharedObject.so
</code>```

Body:
I'm failing to load a shared object library with python. I've tried setting the LD_LIBRARY_PATH to where the someObject.o is located and that works when I am using non-sudo command to run the python script but when I use sudo I run into a linking error.

OSError: bbumintflib.o: cannot open shared object file: No such file or directory

Does anyone know how to link a .o file to the .so file?

using ldd, I know the .so cannot find the .o file.

>>>ldd someSharedObject.so
linux-vdso.so.1 (0x00007ffca69af000)
someObject.o => not found
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f53c96b8000)
/lib64/ld-linux-x86-64.so.2 (0x00007f53c9a57000)

Edit:

This is how I am building the object and sharedObject files

gcc -I ../include -I../../module1/include -I ../../module2/include --shared -fPIC someCFile.c -o someObject.o plat_linux.c

gcc someObject.o -shared -o someSharedObject.so

Body:
This is your problem:

gcc -I ../include -I../../module1/include -I ../../module2/include --shared -fPIC someCFile.c -o someObject.o plat_linux.c
gcc someObject.o -shared -o someSharedObject.so

The first command produces a shared library with odd name someObject.o.

The second command links a new shared library named someSharedObject.so, which depends on someObject.o.

To fix this, do this:

gcc -I ... --shared -fPIC someCFile.c plat_linux.c -o someSharedObject.so


问:
Swapping variables in python with a function
I need to write a program whose input is two integers and whose output is the two integers swapped.

If input is: 3 8, output is 8 3.

The program must define and call the following function. swap_values() returns the two values in swapped order.
def swap_values(user_val1, user_val2)

so far I have:

```<code>def swap_values(user_val1, user_val2):
    return user_val2, user_val1

user_val1 = int(input())
user_val2 = int(input())
swap_values(user_val1, user_val2)

print (swap_values(user_val1, user_val2))
</code>```

but that produces (8, 3) and also doesn't work with a function call like swap_values(-1, 10).

So I'm wondering what I would need to do to get 8 3 for the input and then 10 -1 for the function call.

答:
Actually, for the "function", all you really need is:

```<code>def swap_values(user_val1, user_val2):
    return user_val2, user_val1
</code>```

This effectively swaps the values on the return.

Body:
I need to write a program whose input is two integers and whose output is the two integers swapped.

If input is: 3 8, output is 8 3.

The program must define and call the following function. swap_values() returns the two values in swapped order.
def swap_values(user_val1, user_val2)

so far I have:

def swap_values(user_val1, user_val2):
    return user_val2, user_val1

user_val1 = int(input())
user_val2 = int(input())
swap_values(user_val1, user_val2)

print (swap_values(user_val1, user_val2))

but that produces (8, 3) and also doesn't work with a function call like swap_values(-1, 10).

So I'm wondering what I would need to do to get 8 3 for the input and then 10 -1 for the function call.

Body:
Actually, for the "function", all you really need is:

def swap_values(user_val1, user_val2):
    return user_val2, user_val1

This effectively swaps the values on the return.


问:
Can I mix Python dataframe positional index and column name?
Can I get an entry in dataframe using negative/positional index and column name? For example,</p>
```<code>import pandas as pd
df = pd.DataFrame({'a':[0,1,2], 'b':[3,4,5]})
# df is:
#    a  b
# 0  0  3
# 1  1  4
# 2  2  5
df.iloc[-1]['a']  # got 2
df['a'].iloc[-1]  # got 2
df.loc[1,'a']     # got 1
df.loc[-1,'a']    # got KeyError: -1
</code>```

答:
No you can't mix both within the same iloc/loc (this used to be the case with the now deprecated ix indexer)

The correct approach would be one of the double slice:

```<code>df.iloc[-1]['a']
</code>```

Note that the "issue" is not specific to negative positional indices. When you do df.loc[1,'a'] you are not slicing per position, but per name. This would also fail with a KeyError if you had no 1 in the index.

Body:
Can I get an entry in dataframe using negative/positional index and column name? For example,

import pandas as pd
df = pd.DataFrame({'a':[0,1,2], 'b':[3,4,5]})
# df is:
#    a  b
# 0  0  3
# 1  1  4
# 2  2  5
df.iloc[-1]['a']  # got 2
df['a'].iloc[-1]  # got 2
df.loc[1,'a']     # got 1
df.loc[-1,'a']    # got KeyError: -1

Body:
No you can't mix both within the same iloc/loc (this used to be the case with the now deprecated ix indexer)

The correct approach would be one of the double slice:

df.iloc[-1]['a']

Note that the "issue" is not specific to negative positional indices. When you do df.loc[1,'a'] you are not slicing per position, but per name. This would also fail with a KeyError if you had no 1 in the index.


问:
HTML files have disappeared from VS Code Project Folders
Upon opening my VS Code project and selecting the single HTML file inside it, a prompt appeared stating that the HTML file doesn’t exist: “(Error: Unable to resolve nonexistent file [file path])”. I opened the only other VS Code project I have containing an HTML file and the single HTML file within that project had disappeared as well.

I then opened Finder and, navigating to the two projects, found that there were no longer HTML files inside either project folders; only the CSS and JavaScript files I had created were there. Having not opened or touched the projects for about a week or so, I’m confused as to how these two HTML files in two different projects are both now “nonexistent.”

So far I’ve tried to show hidden files in Finder, look up the file names in Spotlight Search, check my Trash bin, and search for the file in my iCloud Drive. However, I still haven’t been able to find or recover the files.

答: from the get started window open the folder or file there the drop down menu didn't work for me</p>


问:
Use inline SVG as favicon
I have a single HTML page and I want to create a favicon from inline svg and use it inside the HTML. How to proceed?

This is my current attempt:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" type="image/svg+xml" sizes="21x21" href="favicon16.svg">
    <title>Document</title>
</head>
<body>
    <svg width="100" height="100">
    <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
   </svg>
</body>
</html>
</code>```

Title: Use inline SVG as favicon

Body:
I have a single HTML page and I want to create a favicon from inline svg and use it inside the HTML. How to proceed?

This is my current attempt:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" type="image/svg+xml" sizes="21x21" href="favicon16.svg">
    <title>Document</title>

    <svg width="100" height="100">
    <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
   </svg>

Body:
It can be dataURL, and doesn't need to use base64. You only need to exchange "#" with "%23", place all in one line, and be carefull with quotes, of course. My search-engines page favicon:

<link rel="shortcut icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='.8 .8 14.4 14.4'><path d='M10 8.99a1 1 0 00-.695 1.717l4.004 4a1 1 0 101.414-1.414l-4.004-4A1 1 0 0010 8.99z' fill='%2380b0ff' stroke='%235D7FDDaa' stroke-width='.3'/><path d='M6.508 1C3.48 1 1.002 3.474 1.002 6.5S3.48 12 6.508 12s5.504-2.474 5.504-5.5S9.536 1 6.508 1zm0 2a3.486 3.486 0 013.504 3.5c0 1.944-1.556 3.5-3.504 3.5a3.488 3.488 0 01-3.506-3.5C3.002 4.556 4.56 3 6.508 3z' fill='%2380b0ff' stroke='%235D7FDDaa' stroke-width='.3'/></svg>">

But the proper way it should be:

<link rel="shortcut icon" href="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='.8%20.8%2014.4%2014.4'%3e%3cpath%20d='M10%208.99a1%201%200%2000-.695%201.717l4.004%204a1%201%200%20101.414-1.414l-4.004-4A1%201%200%200010%208.99z'%20fill='%2380b0ff'%20stroke='%235D7FDDaa'%20stroke-width='.3'/%3e%3cpath%20d='M6.508%201C3.48%201%201.002%203.474%201.002%206.5S3.48%2012%206.508%2012s5.504-2.474%205.504-5.5S9.536%201%206.508%201zm0%202a3.486%203.486%200%20013.504%203.5c0%201.944-1.556%203.5-3.504%203.5a3.488%203.488%200%2001-3.506-3.5C3.002%204.556%204.56%203%206.508%203z'%20fill='%2380b0ff'%20stroke='%235D7FDDaa'%20stroke-width='.3'/%3e%3c/svg%3e">

...so the link from Jeremie can be useful.


问:
How can I create a wrapper for the RecyclerView Adapter that will accept any Adapter that implements RecyclerView.Adapter<RecyclerView.ViewHolder>
I know the title is a bit weird, sorry. This is a weird one that I'm not even sure I can explain it correctly, here is my attempt:

Basically I want to implement a wrapper for any adapters that extend RecyclerView.Adapter<RecyclerView.ViewHolder> , the wrapper eventually will be able to insert rows if needed and it will modify things like getItemCount() as necessary, but I'm nowhere near that part yet.

This is my class definition:

```<code>class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
</code>```

I pass to it the original adapter which I want to wrap.

If I have the class definition like that, and then I try to create an instance of MyRecyclerAdapterWrapper like this:

```<code>val wrapper = MyRecyclerAdapterWrapper(activity, myOriginalAdapter)
</code>```

Where myOriginalAdapter is an instance of:

```<code>class MyOriginalAdapter() : RecyclerView.Adapter<MyOriginalAdapter.MyViewHolder>() {
</code>```

I then get an error saying that it is expecting RecyclerView.Adapter<RecyclerView.ViewHolder>  but instead got MyOriginalAdapter.

So then I tried the out keyword on the class definition like this:

```<code>class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<out RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
</code>```

And that allows my constructor call MyRecyclerAdapterWrapper(activity, myOriginalAdapter) to stop complaining, however then my MyRecyclerAdapterWrapper class fails at implementing some of the RecyclerView.Adapter<RecyclerView.ViewHolder> overrides because originalAdapter expects Nothing instead of RecyclerView.ViewHolder.

For example inside MyRecyclerAdapterWrapper I have this piece of code:

```<code>override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        originalAdapter.onBindViewHolder(holder,position)
}
</code>```

The error here is Type mismatch Required: Nothing Found: RecyclerView.ViewHolder.

So what is the correct way to handle this?

Edit: just wanted to be clear that other adapters will also use this wrapper, so the wrapper must be generic.

Edit: I should have mentioned this, there is a similar wrapper that works fine that I was using but it is in Java, the class definition on that one was:

```<code>public final class MyRecyclerAdapterWrapper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
     public MyRecyclerAdapterWrapper(@NonNull Activity activity,
        @NonNull RecyclerView.Adapter originalAdapter){
</code>```

Edit: Based on the answer from @muetzenflo I was able to get most of it to work but still have a problem with some methods.

I now have this:

```<code>class MyRecyclerAdapterWrapper<T : RecyclerView.ViewHolder>(activity: Activity, val originalAdapter: RecyclerView.Adapter<T>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
</code>```

And

```<code> class MyCustomAdapter(): RecyclerView.Adapter<MyCustomAdapter.MyViewHolder>(){
        class MyViewHolder(v: View): RecyclerView.ViewHolder(v) {

        }
</code>```

This works:

```<code>val myRecyclerAdapterWrapper = MyRecyclerAdapterWrapper(this, MyCustomAdapter())
</code>```

But this doesn't:

```<code>genericMethod(myRecyclerAdapterWrapper)

private fun genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<RecyclerView.ViewHolder>) {

    }
</code>```

The error is:

```<code>Type mismatch: inferred type is MainActivity.MyRecyclerAdapterWrapper<MainActivity.MyCustomAdapter.MyViewHolder> but MainActivity.MyRecyclerAdapterWrapper<RecyclerView.ViewHolder> was expected
</code>```

Edit: Think I figured out how to make the generic methods:

```<code>private fun <T> genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<T> ) where T : RecyclerView.ViewHolder {

    }
</code>```

So in the end this is how my class ended up and it all compiles and runs:

```<code>class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val myRecyclerAdapterWrapper = MyRecyclerAdapterWrapper(this, MyCustomAdapter())
        genericMethod(myRecyclerAdapterWrapper)
    }
    private fun <T> genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<T> ) where T : RecyclerView.ViewHolder {
    }
    class MyRecyclerAdapterWrapper<T : RecyclerView.ViewHolder>(activity: Activity, val originalAdapter: RecyclerView.Adapter<T>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return originalAdapter.onCreateViewHolder(parent,viewType)
        }
        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            originalAdapter.onBindViewHolder(holder as T,position)
        }
        override fun getItemCount(): Int {
            return originalAdapter.itemCount
        }
    }
    class MyCustomAdapter(): RecyclerView.Adapter<MyCustomAdapter.MyViewHolder>(){
        class MyViewHolder(v: View): RecyclerView.ViewHolder(v) {
        }
        override fun getItemCount(): Int {
            TODO("Not yet implemented")
        }
        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            TODO("Not yet implemented")
        }
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            TODO("Not yet implemented")
        }
    }
}
</code>```

答:
parameter require Nothing because you declared out for generic parameter

try to change RecyclerView.ViewHolder to MyOriginalAdapter.MyViewHolder

```<code>
class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<MyOriginalAdapter.MyViewHolder>) : RecyclerView.Adapter<MyOriginalAdapter.MyViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyOriginalAdapter.MyViewHolder {
        TODO("Not yet implemented")
    }

    override fun onBindViewHolder(holder: MyOriginalAdapter.MyViewHolder, position: Int) {
        originalAdapter.onBindViewHolder(holder, position)
    }

    override fun getItemCount(): Int {
        TODO("Not yet implemented")
    }
}
</code>```

Body:
I know the title is a bit weird, sorry. This is a weird one that I'm not even sure I can explain it correctly, here is my attempt:

Basically I want to implement a wrapper for any adapters that extend RecyclerView.Adapter<RecyclerView.ViewHolder> , the wrapper eventually will be able to insert rows if needed and it will modify things like getItemCount() as necessary, but I'm nowhere near that part yet.

This is my class definition:

class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

I pass to it the original adapter which I want to wrap.

If I have the class definition like that, and then I try to create an instance of MyRecyclerAdapterWrapper like this:

val wrapper = MyRecyclerAdapterWrapper(activity, myOriginalAdapter)

Where myOriginalAdapter is an instance of:

class MyOriginalAdapter() : RecyclerView.Adapter<MyOriginalAdapter.MyViewHolder>() {

I then get an error saying that it is expecting RecyclerView.Adapter<RecyclerView.ViewHolder>  but instead got MyOriginalAdapter.

So then I tried the out keyword on the class definition like this:

class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<out RecyclerView.ViewHolder>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

And that allows my constructor call MyRecyclerAdapterWrapper(activity, myOriginalAdapter) to stop complaining, however then my MyRecyclerAdapterWrapper class fails at implementing some of the RecyclerView.Adapter<RecyclerView.ViewHolder> overrides because originalAdapter expects Nothing instead of RecyclerView.ViewHolder.

For example inside MyRecyclerAdapterWrapper I have this piece of code:

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        originalAdapter.onBindViewHolder(holder,position)
}

The error here is Type mismatch Required: Nothing Found: RecyclerView.ViewHolder.

So what is the correct way to handle this?

Edit: just wanted to be clear that other adapters will also use this wrapper, so the wrapper must be generic.

Edit: I should have mentioned this, there is a similar wrapper that works fine that I was using but it is in Java, the class definition on that one was:

public final class MyRecyclerAdapterWrapper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
     public MyRecyclerAdapterWrapper(@NonNull Activity activity,
        @NonNull RecyclerView.Adapter originalAdapter){

Edit: Based on the answer from @muetzenflo I was able to get most of it to work but still have a problem with some methods.

I now have this:

class MyRecyclerAdapterWrapper<T : RecyclerView.ViewHolder>(activity: Activity, val originalAdapter: RecyclerView.Adapter<T>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

And

 class MyCustomAdapter(): RecyclerView.Adapter<MyCustomAdapter.MyViewHolder>(){
        class MyViewHolder(v: View): RecyclerView.ViewHolder(v) {

        }

This works:

val myRecyclerAdapterWrapper = MyRecyclerAdapterWrapper(this, MyCustomAdapter())

But this doesn't:

genericMethod(myRecyclerAdapterWrapper)

private fun genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<RecyclerView.ViewHolder>) {

    }

The error is:

Type mismatch: inferred type is MainActivity.MyRecyclerAdapterWrapper<MainActivity.MyCustomAdapter.MyViewHolder> but MainActivity.MyRecyclerAdapterWrapper<RecyclerView.ViewHolder> was expected

Edit: Think I figured out how to make the generic methods:

private fun <T> genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<T> ) where T : RecyclerView.ViewHolder {

    }

So in the end this is how my class ended up and it all compiles and runs:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val myRecyclerAdapterWrapper = MyRecyclerAdapterWrapper(this, MyCustomAdapter())
        genericMethod(myRecyclerAdapterWrapper)
    }
    private fun <T> genericMethod(myRecyclerAdapterWrapper: MyRecyclerAdapterWrapper<T> ) where T : RecyclerView.ViewHolder {
    }
    class MyRecyclerAdapterWrapper<T : RecyclerView.ViewHolder>(activity: Activity, val originalAdapter: RecyclerView.Adapter<T>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return originalAdapter.onCreateViewHolder(parent,viewType)
        }
        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            originalAdapter.onBindViewHolder(holder as T,position)
        }
        override fun getItemCount(): Int {
            return originalAdapter.itemCount
        }
    }
    class MyCustomAdapter(): RecyclerView.Adapter<MyCustomAdapter.MyViewHolder>(){
        class MyViewHolder(v: View): RecyclerView.ViewHolder(v) {
        }
        override fun getItemCount(): Int {
            TODO("Not yet implemented")
        }
        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            TODO("Not yet implemented")
        }
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            TODO("Not yet implemented")
        }
    }
}

Body:
parameter require Nothing because you declared out for generic parameter

try to change RecyclerView.ViewHolder to MyOriginalAdapter.MyViewHolder

class MyRecyclerAdapterWrapper(activity: Activity,val originalAdapter: RecyclerView.Adapter<MyOriginalAdapter.MyViewHolder>) : RecyclerView.Adapter<MyOriginalAdapter.MyViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyOriginalAdapter.MyViewHolder {
        TODO("Not yet implemented")
    }

    override fun onBindViewHolder(holder: MyOriginalAdapter.MyViewHolder, position: Int) {
        originalAdapter.onBindViewHolder(holder, position)
    }

    override fun getItemCount(): Int {
        TODO("Not yet implemented")
    }
}


问:
Cannot edit in read-only editor VS Code
I am using Visual Studio Code V 1.31.1. I used an input function but I can't write an input in output panel it shows this error

Cannot edit in read-only editor.

Please help me solve this problem.

答: I installed the https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner and it started working for me.</p>

Title: Cannot edit in read-only editor VS Code


问:
SQL join query using rows which only have date of today to sort
I'm sure this is really simple... just tired now.

I have a query

```<code>SELECT post.*, votes.datetime, COUNT(votes.post_id) AS votes
FROM posts LEFT JOIN votes
ON posts.id = votes.post_id
GROUP BY posts.id
ORDER BY votes DESC
</code>```

I need to fetch all posts on the left table whilst when counting votes on the votes table using the votes which happened today or between 1 hour and another hour of the same day. Does this make enough sense?

I have tried adding

```<code>WHERE DATE(votes.datetime) = DATE(NOW())
</code>```

But no luck, it just shows the rows which have votes which happened today and no other posts rows which have either no votes at all or votes that happened today.

I am using data type datetime for the datetime column

Any ideas how I can do this easily?

Thanks in advance!

-Stefan

答:
I'm not exactly sure if I understand your problem correctly, but the way I understand it I would suggest usinf LEFT OUTER JOIN instead of LEFT JOIN.

This way you get all the posts, even those without votes.

```<code>SELECT post.*, votes.datetime, COUNT(votes.post_id) AS votes
FROM posts LEFT OUTER JOIN votes
ON posts.id = votes.post_id
WHERE DATE(votes.datetime) = DATE(NOW())
GROUP BY posts.id
ORDER BY votes DESC
</code>```

Body:
I'm sure this is really simple... just tired now.

I have a query

SELECT post.*, votes.datetime, COUNT(votes.post_id) AS votes
FROM posts LEFT JOIN votes
ON posts.id = votes.post_id
GROUP BY posts.id
ORDER BY votes DESC

I need to fetch all posts on the left table whilst when counting votes on the votes table using the votes which happened today or between 1 hour and another hour of the same day. Does this make enough sense?

I have tried adding

WHERE DATE(votes.datetime) = DATE(NOW())

But no luck, it just shows the rows which have votes which happened today and no other posts rows which have either no votes at all or votes that happened today.

I am using data type datetime for the datetime column

Any ideas how I can do this easily?

Thanks in advance!

-Stefan

Body:
I'm not exactly sure if I understand your problem correctly, but the way I understand it I would suggest usinf LEFT OUTER JOIN instead of LEFT JOIN.

This way you get all the posts, even those without votes.

SELECT post.*, votes.datetime, COUNT(votes.post_id) AS votes
FROM posts LEFT OUTER JOIN votes
ON posts.id = votes.post_id
WHERE DATE(votes.datetime) = DATE(NOW())
GROUP BY posts.id
ORDER BY votes DESC


问:
Excel VBA GetObject() "Filename or class name not found during Automation operation"
I have "Main" folder which contains Main.xlsm and "readings" folder. Folder "readings" contains a file named Book1.xlsx. It only opens and closes the workbook for experiment with GetObject() function.
Folder "Main" screenshot
and
Folder "readings" screenshot.
I am trying to open an existing workbook with vba GetObject() function by pressing a UserForm CommandButton, but receive an error (432)screenshot.

Here is code that I use:

```<code>Private Sub CommandButton1_Click()
    Dim MyWB As Workbook
    Set MyWB = GetObject(ThisWorkbook.Path & "\readings\Book1.xlsx")
    MyWB.Close
    Set MyWB = Nothing
End Sub
</code>```

Later added [1hr]: (P.S. I know about Workbooks.Open() method, but want to solve why GetObject() is not working)

Later Added [2 hr]: I tried on another computer and it worked, now I have to find out what is wrong with my system that prevents it to work.

Later Added [06.02, evening]: Repairing Office did not help, Full Office Uninstall and Reinstall also did not help, I am stuck

Please help to resolve why it is happening.
(Excel 2016, Windows 10 Pro 64bit)

答:
Thank You Harun24HR for replies!

But finally, the reason was in - I had to run Excel as Administrator, I dont know why, because I tried on other computers and did not use Administrator and it worked, strange, but for my system the reason is this

Body:
I have "Main" folder which contains Main.xlsm and "readings" folder. Folder "readings" contains a file named Book1.xlsx. It only opens and closes the workbook for experiment with GetObject() function.
Folder "Main" screenshot
and
Folder "readings" screenshot.
I am trying to open an existing workbook with vba GetObject() function by pressing a UserForm CommandButton, but receive an error (432)screenshot.

Here is code that I use:

Private Sub CommandButton1_Click()
    Dim MyWB As Workbook
    Set MyWB = GetObject(ThisWorkbook.Path & "\readings\Book1.xlsx")
    MyWB.Close
    Set MyWB = Nothing
End Sub

Later added [1hr]: (P.S. I know about Workbooks.Open() method, but want to solve why GetObject() is not working)

Later Added [2 hr]: I tried on another computer and it worked, now I have to find out what is wrong with my system that prevents it to work.

Later Added [06.02, evening]: Repairing Office did not help, Full Office Uninstall and Reinstall also did not help, I am stuck

Please help to resolve why it is happening.
(Excel 2016, Windows 10 Pro 64bit)


问:
Why are my gunicorn Python/Flask workers exiting from signal term?
I have a Python/Flask web application that I am deploying via Gunicorn in a docker image on Amazon ECS. Everything is going fine, and then suddenly, including the last successful request, I see this in the logs:

[2017-03-29 21:49:42 +0000] [14] [DEBUG] GET /heatmap_column/e4c53623-2758-4863-af06-91bd002e0107/ADA
[2017-03-29 21:49:43 +0000] [1] [INFO] Handling signal: term
[2017-03-29 21:49:43 +0000] [14] [INFO] Worker exiting (pid: 14)
[2017-03-29 21:49:43 +0000] [8] [INFO] Worker exiting (pid: 8)
[2017-03-29 21:49:43 +0000] [12] [INFO] Worker exiting (pid: 12)
[2017-03-29 21:49:43 +0000] [10] [INFO] Worker exiting (pid: 10)
...
[2017-03-29 21:49:43 +0000] [1] [INFO] Shutting down: Master

And the processes die off and the program exits. ECS then restarts the service, and the docker image is run again, but in the meanwhile the service is interrupted.

What would be causing my program to get a TERM signal? I can't find any references to this happening on the web. Note that this only happens in Docker on ECS, not locally.

答: For me, it turned out that the worker was quitting due to one of the containers in my Docker Swarm stack was failing repeatedly, resulting in the rollback process. The gunicorn process received the signal 'term' when the rollback process began.</p>


问:
delete rows based on value in a column
I have a df like this;

```<code>NEW_df <- data.frame(CAR = c("YES","NO","MAYBE","YES","NO"),
                     BIKE = c(2,0,4,NA,9),
                     PLANE = c(8,0,6,7,9),
                     BOAT = c(0,0,0,4,0),
                     SCOOTER = c(2,3,6,9,0))
</code>```

I want to delete only rows where column BOAT is '0', when column CAR is "YES" or "MAYBE"
so I have something like this;

```<code>NEW_df2 <- data.frame(CAR = c("NO","YES","NO"),
                     BIKE = c(0,NA,9),
                     PLANE = c(0,7,9),
                     BOAT = c(0,4,0),
                     SCOOTER = c(3,9,0))
</code>```

I have tried this:

```<code>NEW_df[NEW_df$BOAT %in% subset(NEW_df, CAR == "YES")$BOAT, ]

NEW_df[NEW_df$BOAT %in% subset(NEW_df, CAR == "MAYBE")$BOAT, ]
</code>```

I'm sure I am doing something wrong.

答:
Here's a tidyverse dplyr solution using filter(). Same idea as the base R answer. Create a condition that matches BOAT == 0 & CAR %in% c("YES", "MAYBE") and filter to keep the opposite using the not ! operator:

```<code>library(dplyr)

NEW_df2 <- NEW_df %>%
  filter(!(BOAT == 0 & CAR %in% c("YES", "MAYBE" )))

print(NEW_df2)
</code>```
```<code>> print(NEW_df2)
  CAR BIKE PLANE BOAT SCOOTER
1  NO    0     0    0       3
2 YES   NA     7    4       9
3  NO    9     9    0       0
</code>```

Title: delete rows based on value in a column

Body:
I have a df like this;

NEW_df <- data.frame(CAR = c("YES","NO","MAYBE","YES","NO"),
                     BIKE = c(2,0,4,NA,9),
                     PLANE = c(8,0,6,7,9),
                     BOAT = c(0,0,0,4,0),
                     SCOOTER = c(2,3,6,9,0))

I want to delete only rows where column BOAT is '0', when column CAR is "YES" or "MAYBE"
so I have something like this;

NEW_df2 <- data.frame(CAR = c("NO","YES","NO"),
                     BIKE = c(0,NA,9),
                     PLANE = c(0,7,9),
                     BOAT = c(0,4,0),
                     SCOOTER = c(3,9,0))

I have tried this:

NEW_df[NEW_df$BOAT %in% subset(NEW_df, CAR == "YES")$BOAT, ]

NEW_df[NEW_df$BOAT %in% subset(NEW_df, CAR == "MAYBE")$BOAT, ]

I'm sure I am doing something wrong.

Body:
Here's a tidyverse dplyr solution using filter(). Same idea as the base R answer. Create a condition that matches BOAT == 0 & CAR %in% c("YES", "MAYBE") and filter to keep the opposite using the not ! operator:

library(dplyr)

NEW_df2 <- NEW_df %>%
  filter(!(BOAT == 0 & CAR %in% c("YES", "MAYBE" )))

print(NEW_df2)

> print(NEW_df2)
  CAR BIKE PLANE BOAT SCOOTER
1  NO    0     0    0       3
2 YES   NA     7    4       9
3  NO    9     9    0       0