问:
Vue3 Element Plus not rendaring the props inside the imported element when testing with the vitest
I have a very basic component called

ConfirmModal.vue

<template>
  <el-dialog v-model="dialogVisible" :title="title" width="30%">
    {{ content }}
    <template #footer>

        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="emit('onConfirm')">
          Confirm
        </el-button>

    </template>
  </el-dialog>
</template>

```
<p>and a test called</p>
<p><code>ConfirmModal.spec.ts</code></p>
<pre class="lang-js prettyprint-override"><code>import { mount } from "@vue/test-utils";
import { describe, expect, it } from "vitest";
import ConfirmModal from "../ConfirmModal.vue";

describe("ConfirmModal.vue", () => {
  it("render the modal", () => {
    const wrapper = mount(ConfirmModal, {
      props: {
        show: true,
        content: "something",
      },
    });

    expect(wrapper.find("span").text()).toContain("something");
  });
});

</code>```

The test is failing like this

```<b> FAIL </b> components/__tests__/ConfirmModal.spec.ts > ConfirmModal.vue > render the modal
<b>Error</b>: Cannot call text on an empty DOMWrapper.
 ❯ Object.get ../node_modules/@vue/test-utils/dist/vue-test-utils.esm-bundler.mjs:1513:27
 ❯ components/__tests__/ConfirmModal.spec.ts:14:31
     12|     });
     13|
     14|     expect(wrapper.find("span").text()).toContain("something");
       |                               ^
     15|   });
     16| });
```

I'm not sure what is missing here.

Body:
I have a very basic component called

ConfirmModal.vue

<template>
  <el-dialog v-model="dialogVisible" :title="title" width="30%">
    {{ content }}
    <template #footer>

        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="emit('onConfirm')">
          Confirm
        </el-button>

    </template>
  </el-dialog>
</template>

and a test called

ConfirmModal.spec.ts

import { mount } from "@vue/test-utils";
import { describe, expect, it } from "vitest";
import ConfirmModal from "../ConfirmModal.vue";

describe("ConfirmModal.vue", () => {
  it("render the modal", () => {
    const wrapper = mount(ConfirmModal, {
      props: {
        show: true,
        content: "something",
      },
    });

    expect(wrapper.find("span").text()).toContain("something");
  });
});

The test is failing like this

 FAIL  components/__tests__/ConfirmModal.spec.ts > ConfirmModal.vue > render the modal
Error: Cannot call text on an empty DOMWrapper.
 ❯ Object.get ../node_modules/@vue/test-utils/dist/vue-test-utils.esm-bundler.mjs:1513:27
 ❯ components/__tests__/ConfirmModal.spec.ts:14:31
     12|     });
     13|
     14|     expect(wrapper.find("span").text()).toContain("something");
       |                               ^
     15|   });
     16| });

I'm not sure what is missing here.


来源: stackexchange

问:
Dynamically duplicate columns in an R dataframe using column names
I have 5 columns, Units1, Units2, Units3, Units4, Units5. I am trying to create a new column say

```<code>master$Sales <- master$Units1
</code>```

However, I want this Units1 to be dynamic such that Sales has the datatype of UnitsX.

My current solution created Sales as a list instead of double.

```<code>Sales_Variable <- "Units"
UnitsType <- x #which is 1 in this case
master$Sales <- master[names(master) == paste0(Sales_Variable,UnitsType)]
</code>```

Please guide me on how I can solve this.

Thanks,

Ashutosh Deshpande

ContentLicense: CC BY-SA 4.0

Body:
I have 5 columns, Units1, Units2, Units3, Units4, Units5. I am trying to create a new column say

master$Sales <- master$Units1

However, I want this Units1 to be dynamic such that Sales has the datatype of UnitsX.

My current solution created Sales as a list instead of double.

Sales_Variable <- "Units"
UnitsType <- x #which is 1 in this case
master$Sales <- master[names(master) == paste0(Sales_Variable,UnitsType)]

Please guide me on how I can solve this.

Thanks,

Ashutosh Deshpande


问:
How to show server.port in intellj idea Services tool bar
i want to see server.port like this

what should i add to configuration?


问:
Reactjs JwtToken is not being stored
We have a web application project that has jwtToken for login. my problem is that my device removes token when refreshed.

I already used different browsers but it still the same. The same project works on my other team's device and I'm the only one that does this kind of problem.

This is my jwtToken.js

const jwtToken = (user, statusCode, res) => {
    // Create Jwt token
    const token = user.getJwtToken();

    // Options for cookie
    const options = {
        expires: new Date(
            Date.now() + process.env.COOKIE_EXPIRES_TIME * 24 * 60 * 60 * 1000
        ),
httpOnly: true
    }
    res.status(statusCode).cookie('token', token, options).json({
        success: true,
        token,
        user
    })

}

module.exports = jwtToken;
```

<p>This is my login Function at the controller</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>exports.loginUser = async (req, res, next) => {
    const { email, password } = req.body;

    // Checks if email and password is entered by user
    if (!email || !password) {
        return next(new ErrorHandler('Please enter email & password', 400))
    }
    const user = await User.findOne({email }).select('+password')

    if (!user) {
        return next(new ErrorHandler('Invalid Credentials', 401));
    }

    else if (user.status == "deactive" ) {
        return next(new ErrorHandler('Account is on Hold!', 401));
    }

    // Checks if password is correct or not
    const isPasswordMatched = await user.comparePassword(password);

    if (!isPasswordMatched) {
        return next(new ErrorHandler('Invalid Email or Password', 401));
    }
    sendToken(user, 200, res)
}</code>```

Title: Reactjs JwtToken is not being stored

Body:
We have a web application project that has jwtToken for login. my problem is that my device removes token when refreshed.

I already used different browsers but it still the same. The same project works on my other team's device and I'm the only one that does this kind of problem.

This is my jwtToken.js

const jwtToken = (user, statusCode, res) => {
    // Create Jwt token
    const token = user.getJwtToken();

    // Options for cookie
    const options = {
        expires: new Date(
            Date.now() + process.env.COOKIE_EXPIRES_TIME * 24 * 60 * 60 * 1000
        ),
httpOnly: true
    }
    res.status(statusCode).cookie('token', token, options).json({
        success: true,
        token,
        user
    })

}

module.exports = jwtToken;

This is my login Function at the controller

exports.loginUser = async (req, res, next) => {
    const { email, password } = req.body;

    // Checks if email and password is entered by user
    if (!email || !password) {
        return next(new ErrorHandler('Please enter email & password', 400))
    }
    const user = await User.findOne({email }).select('+password')

    if (!user) {
        return next(new ErrorHandler('Invalid Credentials', 401));
    }

    else if (user.status == "deactive" ) {
        return next(new ErrorHandler('Account is on Hold!', 401));
    }

    // Checks if password is correct or not
    const isPasswordMatched = await user.comparePassword(password);

    if (!isPasswordMatched) {
        return next(new ErrorHandler('Invalid Email or Password', 401));
    }
    sendToken(user, 200, res)
}


问:
how can i delete inserted html input
I am trying to rewrite the input value on a website but there already exists a value. I first want to clarify that value them insert my value.

This is what I tried:

```<code>driver.find_element_by_xpath("/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div/div[3]/div[1]/div/div[2]/input").clear()
time.sleep(2)
driver.find_element_by_xpath("/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div/div[3]/div[1]/div/div[2]/input").send_keys("1,000")
</code>```

however, this only adds my value to the already existing value.

outcome: 267,0001,000

Title: how can i delete inserted html input

Body:
I am trying to rewrite the input value on a website but there already exists a value. I first want to clarify that value them insert my value.

This is what I tried:

driver.find_element_by_xpath("/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div/div[3]/div[1]/div/div[2]/input").clear()
time.sleep(2)
driver.find_element_by_xpath("/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div/div[3]/div[1]/div/div[2]/input").send_keys("1,000")

however, this only adds my value to the already existing value.

outcome: 267,0001,000


问:
Confused why getting a User from Repository fixed "failed to lazily initialize a collection of role" compared to using SecurityContextHolder
My goal was to pass a List of Businesses to the model from the controller to display it in a view and I have succeeded, but have a bit of confusion.

When I initially tried using:

```<code>public User getCurrentAuthenticatedUser() {
    UserDetailsImpl user = (UserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    return user.getUser();
}

@GetMapping("")
public String list(Model model) {
    model.addAttribute("businesses", userService.getCurrentAuthenticatedUser().getBusinesses());
    return "business/list";
}
</code>```

I got this error: "failed to lazily initialize a collection of role: com.xyz.User.businesses could not initialize proxy - no Session"

Then I tried:

```<code>@GetMapping("")
public String list(Model model) {
    int userId = userService.getCurrentAuthenticatedUser().getId();
    User user = userService.getById(userId); // gets User using Spring Data JPA UserRepository
    List<Business> businesses = user.getBusinesses();
    model.addAttribute("businesses", businesses);
    return "business/list";
}
</code>```

And this worked perfectly fine.

What was the issue using the first method. It seemed more simple rather than calling a User from the UserRepository. I've seen some posts that say you should use EAGER fetching, but that's just seems like a bandaid solution.
From the beginner's understanding: Since fetch type is LAZY the businesses don't exist yet in the User but are fetched on demand later on so there shouldn't be an issue.
Edit: After more thought I remembered that with basic Hibernate you would have to create Transactions and commit transactions. I'm assuming that User is not within a Transaction that's why I can't get businesses using the 1st method.
What would be a better solution to fetch the current Authenticated user? And that user's attributes such as a list of businesses.

Model Classes:
Business:

```<code>@Entity
@Table(name = "businesses")
public class Business {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
private LocalDate date;

@ManyToOne(cascade={CascadeType.MERGE})
@JoinColumn(name="user_id")
private User user;

public Business() {
}

public Business(String name, String description, LocalDate date, User user) {
    ...
}

public Business(Long id, String name, String description, LocalDate date, User user) {
    ...
}
... getters/setters

}
</code>```

USER:

```<code>@Entity
@Table(name = "users")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String password;
private boolean enabled;

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable( name = "users_roles",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();

@OneToMany(fetch = FetchType.LAZY, mappedBy="user", cascade={CascadeType.MERGE})
private List<Business> businesses;

... getters/setters
</code>```

}

Body:
My goal was to pass a List of Businesses to the model from the controller to display it in a view and I have succeeded, but have a bit of confusion.

When I initially tried using:

public User getCurrentAuthenticatedUser() {
    UserDetailsImpl user = (UserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    return user.getUser();
}

@GetMapping("")
public String list(Model model) {
    model.addAttribute("businesses", userService.getCurrentAuthenticatedUser().getBusinesses());
    return "business/list";
}

I got this error: "failed to lazily initialize a collection of role: com.xyz.User.businesses could not initialize proxy - no Session"

Then I tried:

@GetMapping("")
public String list(Model model) {
    int userId = userService.getCurrentAuthenticatedUser().getId();
    User user = userService.getById(userId); // gets User using Spring Data JPA UserRepository
    List<Business> businesses = user.getBusinesses();
    model.addAttribute("businesses", businesses);
    return "business/list";
}

And this worked perfectly fine.

What was the issue using the first method. It seemed more simple rather than calling a User from the UserRepository. I've seen some posts that say you should use EAGER fetching, but that's just seems like a bandaid solution.
From the beginner's understanding: Since fetch type is LAZY the businesses don't exist yet in the User but are fetched on demand later on so there shouldn't be an issue.
Edit: After more thought I remembered that with basic Hibernate you would have to create Transactions and commit transactions. I'm assuming that User is not within a Transaction that's why I can't get businesses using the 1st method.
What would be a better solution to fetch the current Authenticated user? And that user's attributes such as a list of businesses.

Model Classes:
Business:

@Entity
@Table(name = "businesses")
public class Business {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
private LocalDate date;

@ManyToOne(cascade={CascadeType.MERGE})
@JoinColumn(name="user_id")
private User user;

public Business() {
}

public Business(String name, String description, LocalDate date, User user) {
    ...
}

public Business(Long id, String name, String description, LocalDate date, User user) {
    ...
}
... getters/setters

}

USER:

@Entity
@Table(name = "users")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String password;
private boolean enabled;

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable( name = "users_roles",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();

@OneToMany(fetch = FetchType.LAZY, mappedBy="user", cascade={CascadeType.MERGE})
private List<Business> businesses;

... getters/setters

}


问:
Split chronological data in k groups to optimize k linear regressions
I have X and Y data arranged in chronological order. I want to find the k-1 bounds that divide my data into k clusters so that each cluster optimizes a linear regression Yk = ak.Xk + bk

I tried an iterative search for the bounds but without much success. I am writing this question thinking that a probabilistic approach might be better but I don't know how to implement it.

How would you do to solve this problem ?


Title: Display ID in an Heatmap representation of Distance (Dissimilarity) [R]

Body:
I have computed the distance (Bray-Curtis dissimilarity) of a dataset, and I am trying to visualize the result in a heatmap with package pheatmap. I succeed to have the heatmap. Nevertheless, the ID of the rows and columns, despite being present in the distance data, does not appear in the heat map which complexify the interpretation. I have tried to use annotation = & annotation_row = on a vector file of the extracted species, but that does not work. Giving that message:

Error in annotation_row[rownames(mat), , drop = F] :
  incorrect number of dimensions

Here is my code :

pheatmap(SpeBioDiss, annotation_row = Species, display_numbers = TRUE, cutree_rows = 5)

Here is my distance result:

SpeBioDiss <- structure(c(0.827283062404109, 0.999999999787744, 0.9976722025141,
0.993374122995813, 0.998684926724875, 0.996197694728471, 0.989724955190119,
0.43469497244591, 0.998418051673928, 0.990491388512666, 0.988338518981963,
0.989979469784687, 0.879991761967327, 0.737830539150324, 0.999999999543069,
0.96686014238935, 0.999999999537163, 0.977779088460779, 0.971844000006402,
0.999999999910839, 0.998794230920093, 0.999999999860431, 0.954480706731319,
0.986383026735704, 0.999999999929866, 0.912568317170688, 0.989047686370974,
0.989834812440211, 0.995315319366, 0.989609248520695, 0.928510389713861,
0.998057874156962, 0.987854549530747, 0.992809949172826, 0.997407926107517,
0.909702450081414, 0.899798177145296, 0.99999999991479, 0.95554497428788,
0.999999999914587, 0.981235337313036, 0.967860370501579, 0.999999999951837,
0.971870341370678, 0.999999999940163, 0.980228806939195, 0.928365081882989,
0.999999999936412, 0.989205204788684, 0.984802956273953, 0.990965089341073,
0.990997808073696, 0.998899563434765, 0.868730864585977, 0.97270276778642,
0.796523461858723, 0.893406508131487, 0.859623131053019, 0.97751172307757,
0.992352942466323, 0.99270915413726, 0.999999999607947, 0.9508032302371,
0.960255464055028, 0.647809134982572, 0.965799875755295, 0.906196625100659,
0.881340898467892, 0.986324697364517, 0.984173284697104, 0.961678344499017,
0.97986620519704, 0.98690337782425, 0.999999999932508, 0.989623321891195,
0.944514676798707, 0.958806930494846, 0.98866095752338, 0.95156505020099,
0.996130071685143, 0.999247798044378, 0.965322769139301, 0.999999999924102,
0.978266121630812, 0.92761939748347, 0.999999999955018, 0.944624365903456,
0.999999999944994, 0.999041093040236, 0.927062571232258, 0.486062169541527,
0.593141761296058, 0.516292483313821, 0.99118348278939, 0.996783394765032,
0.619795864489088, 0.982232130897591, 0.992734309081685, 0.924598423484611,
0.974445210104049, 0.99982611778834, 0.69835963101293, 0.999999999996886,
0.709436124371844, 0.78995367441768, 0.971643515325166, 0.837308356943407,
0.980872135495413, 0.924572400917035, 0.653481146200731, 0.591810902482557,
0.672035195833418, 0.996330790132122, 0.997137152915808, 0.635984964998261,
0.981345155269224, 0.994376102065022, 0.930677171351289, 0.983201791967876,
0.999832370468777, 0.764184967748081, 0.999999999996999, 0.7045992031759,
0.812823313491083, 0.949771727368739, 0.834752963315194, 0.970400438275127,
0.925270479615979, 0.558014389501429, 0.672194628479746, 0.995449343202001,
0.998108902874361, 0.622403790473656, 0.987148325574506, 0.995901444878825,
0.954611105456894, 0.980411108141993, 0.999900646342368, 0.82052818896192,
0.999999999998221, 0.781202000345684, 0.847354085250656, 0.96829041721517,
0.853866125723307, 0.982350607718347, 0.938086774654263, 0.719471914702451,
0.992095819587618, 0.997430216274891, 0.809335312202303, 0.978762423998145,
0.994742394681612, 0.938296212728146, 0.97033221807679, 0.999864946331165,
0.639941090476378, 0.999999999997582, 0.719176255540318, 0.894340516954927,
0.975714604352471, 0.915544830974035, 0.988696122154319, 0.94535527415508,
0.649943501040855, 0.949697309110096, 0.990413748324289, 0.997139520382115,
0.984287631185666, 0.979522989853084, 0.590405670464466, 0.996419977905822,
0.972889572022567, 0.999999999390479, 0.968075724489297, 0.967233155902039,
0.999690652287721, 0.999835684664338, 0.998603120221952, 0.940022477459311,
0.989643067553156, 0.995045900529729, 0.882175397694128, 0.892273666456609,
0.937617479767168, 0.931552968844194, 0.918863522176468, 0.991128211890621,
0.999999998120205, 0.989542335192327, 0.993984904250088, 0.972031567351805,
0.991313450355957, 0.994205794688569, 0.977396556368122, 0.996629984503012,
0.967580146059101, 0.989476190216704, 0.890942743652863, 0.983152745974521,
0.999697074109512, 0.847897990098422, 0.999999999994575, 0.705634125835866,
0.605802301755415, 0.906351449109105, 0.695673878775299, 0.959063591120359,
0.921666363807104, 0.820618619072126, 0.865695201384915, 0.693116070958152,
0.971577127295237, 0.988542799582319, 0.93825601292248, 0.99999999978303,
0.912834299792486, 0.935523776828192, 0.892721796075054, 0.930289058045599,
0.897969222994677, 0.913359438526875, 0.973302516149733, 0.857882783195953,
0.990098891491555, 0.993017292621689, 0.982833891711216, 0.999999999145984,
0.977110625992913, 0.970718120565762, 0.965561655724669, 0.972927823056258,
0.973267020957655, 0.975663721930446, 0.99374623773649, 0.909536833391596,
0.99612122887274, 0.824680942705843, 0.999999999930411, 0.77252723021654,
0.811959026265691, 0.874889109841753, 0.81246377408837, 0.935785119858506,
0.786391028551874, 0.926360731578736, 0.997149871048469, 0.900874359222991,
0.999999999839384, 0.885658873115255, 0.965819298805294, 0.997589524147627,
0.99782220913215, 0.996929289000309, 0.822818168192554, 0.961257329845712,
0.999532349794741, 0.999999964187906, 0.999447988081021, 0.999240832367375,
0.997829075841445, 0.999171094979177, 0.997808550561867, 0.998284898285629,
0.999822823307865, 0.999999999991625, 0.462533091236181, 0.827340176688411,
0.990451540594486, 0.875073699833685, 0.981300451114506, 0.876691869899626,
0.635503894157547, 0.999999999990113, 0.999999999983617, 0.999999999889566,
0.999999999985152, 0.999999999800174, 0.99999999995788, 0.999999999996827,
0.743669325337782, 0.879399730516722, 0.717970246714169, 0.918754919809119,
0.79311340763433, 0.632769318134201, 0.935167760442773, 0.643795000909155,
0.974723602282508, 0.936924401954657, 0.874128264084042, 0.885248041356563,
0.879319154156419, 0.871935806863086, 0.963919209341847, 0.91254396820454,
0.882664703372587, 0.869095793241582, 0.938704426640601, 0.978376838321269,
0.87876180016034), maxdist = 1, Size = 25L, Labels = c("Acartia longiremis",
"Acartia spp.", "Bradyidius similis", "Calanoida indet.", "Calanus finmarchicus",
"Calanus glacialis", "Calanus hyperboreus", "Calanus spp.", "Centropages spp.",
"Copepoda", "Metridia longa", "Microcalanus pusillus", "Microcalanus pygmaeus",
"Microcalanus spp.", "Microsetella norvegica", "Oithona atlantica",
"Oithona similis", "Oithona spp.", "Oncaea borealis", "Pareuchaeta glacialis",
"Pareuchaeta norvegica", "Pareuchaeta spp.", "Pseudocalanus acuspes",
"Pseudocalanus minutus", "Pseudocalanus spp."), Diag = FALSE, Upper = FALSE, method = "bray", call = vegdist(x = Zoodata_Biom_DisSpecies,
    method = "bray"), class = "dist")

The vector file, containing the extraction of the species from the dataset :

Species <- c("Acartia longiremis", "Acartia spp.", "Bradyidius similis",
"Calanoida indet.", "Calanus finmarchicus", "Calanus glacialis",
"Calanus hyperboreus", "Calanus spp.", "Centropages spp.", "Copepoda",
"Metridia longa", "Microcalanus pusillus", "Microcalanus pygmaeus",
"Microcalanus spp.", "Microsetella norvegica", "Oithona atlantica",
"Oithona similis", "Oithona spp.", "Oncaea borealis", "Pareuchaeta glacialis",
"Pareuchaeta norvegica", "Pareuchaeta spp.", "Pseudocalanus acuspes",
"Pseudocalanus minutus", "Pseudocalanus spp.")


问:
Jest return mocked value when S3.getObject function is called
I'm totally new to Jest and typescript. my 2nd test case to be honest.
I want in my jest test - when s3.getObject is called in the actual class, it should return the mocked value.

my handler code:

```<code>var aws = require("aws-sdk");
var s3 = new aws.S3({apiVersion: '2006-03-01'});

exports.handler = async function (event, context, callback) {
    const bucket = 'event.s3.bucket.name';
    const filename = 'fileName';
    const inputBucketParams = {
        Bucket: bucket,
        Key: filename,
    };
    let result;

        try {
            **//I want the result to be the mocked value in my test case.**
            result = await s3.getObject(inputBucketParams).promise();
            const fileContent = getFileContents(result.Body.toString("utf-8"));
</code>```

my test case:

```<code>import {getFileContent} from "../../utils/FileContent";
import anything = jasmine.anything;

const lambdaHandler = require('../lambda/myLambda');
const AWSMock = require('aws-sdk-mock');
const AWS = require("aws-sdk");

describe('Test getS3Object', () => {
    beforeEach(() => AWSMock.setSDKInstance(AWS));
})

let s3Object = {
    "bucket": {
    },
    "object": {

    }
};

let event = {Records: [
        {
            s3: s3Object --> from above.
        }
    ]
}

var aws = require("aws-sdk");
var s3 = new aws.S3({apiVersion: '2006-03-01'});

describe('my handler test', async function () {
    const s3GetObject = AWSMock.mock('S3', 'getObject', getFileContent('fileName.csv'));
    const s3mock = jest.fn();
    const getObjectMock = jest.fn(() => getFileContent('fileName.csv'));
    const params = {
        Bucket: 'bucketName',
        Key: 'filename'
    }
    var returnValue = s3mock.mockReturnValue({
        Body: getFileContent('fileName.csv')
    });

    test('s3 getObject response mock', async () => {
        //jest.spyOn(s3, "getObject")
        const getObjectMockValue = s3.spyOn('S3', 'getObject').mockReturnValue({
                Body: getFileContent('fileName.csv')
        })

    // my handler is called from this, and when it get to s3.getObject, it fails.
        const handlerResponse = await lambdaHandler.handler(event, anything(), anything());
    });
});

</code>```

I want in my jest test - when s3.getObject is called in the actual class, it should return the mocked value.

Body:
I'm totally new to Jest and typescript. my 2nd test case to be honest.
I want in my jest test - when s3.getObject is called in the actual class, it should return the mocked value.

my handler code:

var aws = require("aws-sdk");
var s3 = new aws.S3({apiVersion: '2006-03-01'});

exports.handler = async function (event, context, callback) {
    const bucket = 'event.s3.bucket.name';
    const filename = 'fileName';
    const inputBucketParams = {
        Bucket: bucket,
        Key: filename,
    };
    let result;

        try {
            **//I want the result to be the mocked value in my test case.**
            result = await s3.getObject(inputBucketParams).promise();
            const fileContent = getFileContents(result.Body.toString("utf-8"));

my test case:

import {getFileContent} from "../../utils/FileContent";
import anything = jasmine.anything;

const lambdaHandler = require('../lambda/myLambda');
const AWSMock = require('aws-sdk-mock');
const AWS = require("aws-sdk");

describe('Test getS3Object', () => {
    beforeEach(() => AWSMock.setSDKInstance(AWS));
})

let s3Object = {
    "bucket": {
    },
    "object": {

    }
};

let event = {Records: [
        {
            s3: s3Object --> from above.
        }
    ]
}

var aws = require("aws-sdk");
var s3 = new aws.S3({apiVersion: '2006-03-01'});

describe('my handler test', async function () {
    const s3GetObject = AWSMock.mock('S3', 'getObject', getFileContent('fileName.csv'));
    const s3mock = jest.fn();
    const getObjectMock = jest.fn(() => getFileContent('fileName.csv'));
    const params = {
        Bucket: 'bucketName',
        Key: 'filename'
    }
    var returnValue = s3mock.mockReturnValue({
        Body: getFileContent('fileName.csv')
    });

    test('s3 getObject response mock', async () => {
        //jest.spyOn(s3, "getObject")
        const getObjectMockValue = s3.spyOn('S3', 'getObject').mockReturnValue({
                Body: getFileContent('fileName.csv')
        })

    // my handler is called from this, and when it get to s3.getObject, it fails.
        const handlerResponse = await lambdaHandler.handler(event, anything(), anything());
    });
});

I want in my jest test - when s3.getObject is called in the actual class, it should return the mocked value.


问:
Caclulate Area Under Threshold in python (Matplotlib) (I am not looking for Area under Curve, trapz didn't work)
I have the following problem, I am trying to plot and calculate area und Threshold for a set of Data. The Data comprises Timestamps on the X Axis and Measurements of arterial blood pressure on the y axis. Our research is interested in measuring the Area under the curve total, and the area under curve under a certain Threshold (namely 65), and Area under Threshold. Area under the curve could be measured easily in other software (Matlab or Prism or Trapz from Numpy). The problem is calculating the later 2 : Area under Threshold (the shaded area in the picture below), and area under curve under certain threshold.

Raw Data

This is the area under Threshold that we need to calculate

I used Fill between method to shade the area wanted, but have no idea how would i go about calculating the area. Could you please help me.

here is the simple code we used to plot:

```<code>data = pd.read_excel("Min 02-01.xlsx")
map = data["ART (MEAN) (0.9765625 Hz)"]
timestamp = data["Timestamp"]

plt.plot_date(timestamp, map, marker='', linestyle='solid')
plt.gcf().autofmt_xdate()

plt.fill_between(timestamp, map, 65, where=(map <= 65), interpolate=True, color='red')

plt.legend()
plt.title('MAP VS Time')
plt.xlabel('Time')
plt.ylabel('MAP (mmHg)')
plt.tight_layout()
plt.show()

</code>```

I am open to solutions using other software or other programming languages

Body:
I have the following problem, I am trying to plot and calculate area und Threshold for a set of Data. The Data comprises Timestamps on the X Axis and Measurements of arterial blood pressure on the y axis. Our research is interested in measuring the Area under the curve total, and the area under curve under a certain Threshold (namely 65), and Area under Threshold. Area under the curve could be measured easily in other software (Matlab or Prism or Trapz from Numpy). The problem is calculating the later 2 : Area under Threshold (the shaded area in the picture below), and area under curve under certain threshold.

Raw Data

This is the area under Threshold that we need to calculate

I used Fill between method to shade the area wanted, but have no idea how would i go about calculating the area. Could you please help me.

here is the simple code we used to plot:

data = pd.read_excel("Min 02-01.xlsx")
map = data["ART (MEAN) (0.9765625 Hz)"]
timestamp = data["Timestamp"]

plt.plot_date(timestamp, map, marker='', linestyle='solid')
plt.gcf().autofmt_xdate()

plt.fill_between(timestamp, map, 65, where=(map <= 65), interpolate=True, color='red')

plt.legend()
plt.title('MAP VS Time')
plt.xlabel('Time')
plt.ylabel('MAP (mmHg)')
plt.tight_layout()
plt.show()

I am open to solutions using other software or other programming languages


问:
How to create a newrelic_alert_muting_rule that covers all day on weekends?
I want to create a newrelic_alert_muting_rule resource to cover all day on weekends, so I've written the following schedule:

```<code>schedule {
  time_zone          = "Europe/London"
  repeat             = "WEEKLY"
  weekly_repeat_days = ["SATURDAY", "SUNDAY"]
}
</code>```

Could someone confirm whether that's the correct way to create a muting rule that covers all day?

Body:
I want to create a newrelic_alert_muting_rule resource to cover all day on weekends, so I've written the following schedule:

schedule {
  time_zone          = "Europe/London"
  repeat             = "WEEKLY"
  weekly_repeat_days = ["SATURDAY", "SUNDAY"]
}

Could someone confirm whether that's the correct way to create a muting rule that covers all day?


问:
How does one search for 32-bit application in winget?
Installing a 32-bit can be done by the following command:
winget install <application> -a x86

But how do you search to check if that application already exists in the system before installing it again. I have 64 & 32 bit installed of same application but their naming and Id are very much the same.

winget list --id <application> -a x86 ???


问:
Remote-connect to Elastic Node via Python
Trying to connect to a single Elastic node via Python, but I keep getting errors, mostly related to certificate issues. I have Elastic installed on an Ubuntu server and then try to connect to it from a Windows 10 machine.

Connecting to it via the browser from the Windows machine is no problem. I get the expected output:

The problem is when I have to connect using Python. I've tried every example in the tutorial page, but none worked. Here's my latest attempt:

```<code>from elasticsearch import Elasticsearch
from ssl import create_default_context

es_username = 'elastic'
es_password = 'xuVmOMJqLGbLskP3PTpT'
es_host = '10.20.20.131'
es_port = 9200
cafile = r'C:\Users\user\Desktop\PYTHON\certificate.crt'

context = create_default_context(cafile=cafile)
es = Elasticsearch(
    ['https://10.20.20.131'],
    basic_auth=(es_username, es_password),
    scheme="https",
    verify_certs=False,
    port=9200,
    ssl_context=context,
)

print(es.info())
</code>```

I've copied the certificate from the ubuntu server to the Windows machine, but still it refuses to validate it.

I dont know what I'm doing wrong. Any help is appreciated.

Body:
Trying to connect to a single Elastic node via Python, but I keep getting errors, mostly related to certificate issues. I have Elastic installed on an Ubuntu server and then try to connect to it from a Windows 10 machine.

Connecting to it via the browser from the Windows machine is no problem. I get the expected output:

The problem is when I have to connect using Python. I've tried every example in the tutorial page, but none worked. Here's my latest attempt:

from elasticsearch import Elasticsearch
from ssl import create_default_context

es_username = 'elastic'
es_password = 'xuVmOMJqLGbLskP3PTpT'
es_host = '10.20.20.131'
es_port = 9200
cafile = r'C:\Users\user\Desktop\PYTHON\certificate.crt'

context = create_default_context(cafile=cafile)
es = Elasticsearch(
    ['https://10.20.20.131'],
    basic_auth=(es_username, es_password),
    scheme="https",
    verify_certs=False,
    port=9200,
    ssl_context=context,
)

print(es.info())

I've copied the certificate from the ubuntu server to the Windows machine, but still it refuses to validate it.

I dont know what I'm doing wrong. Any help is appreciated.


问:
Problem: Adding a column to MS Access DB that is used by a VB.NET program via OLE no longer updates the automatically generaate code
I have a VB.NET program that I wrote 20 years ago and last updated 7 years ago. I have gotten a new computer and new version of Visual Studio recently.

The program uses a DB created with MS Access via the OLEDB mechanism. I originally created the DB connection by dragging and dropping tables from the DB into a VB window. This generates a lot of code automagically that I have never had to look at in the past. This code takes care of the DB queries and updates. Code I have explicitly written adds, modifies or deletes rows from the tables.

In the past I have been able to manually add a column to the Access DB and get the automatically generated code to update and make that column available to my code.

I am trying to do that now and I've either forgotten a crucial step or the newest version of Visual Studio is not compatible with my ancient code. The symptom is the new column does not get updated when I update all the other columns. If I look at the automagically generated code (in routine InitilizeComponent) it has lines like:

```<code>Me.OleDbUpdateCommand5.CommandText = resources.GetString("OleDbUpdateCommand5.CommandText")
        Me.OleDbUpdateCommand5.Connection = Me.dcWageLossDB
        Me.OleDbUpdateCommand5.Parameters.AddRange(New System.Data.OleDb.OleDbParameter() {New System.Data.OleDb.OleDbParameter("CaseId", System...
</code>```

where in the arguments of the last call it lists all the columns EXCEPT for my my new one.

Note that while the new column does not get properly added to the DB queries, it does get added to internal structures so that in my code I can refer to the new column by name and set its value.

I know this question is rather fuzzy. It is not practical to provide the (quite long and complex) code. Since the problem probably depends on the long history, it also is not practical to try to create a small simple version of it.

I'm just hoping someone has run into this problem and knows the solution.

Thanks

I have already tried graphically deleting and adding back all the tables in the .xsd file used in the query via the solution explorer - data connections. It didn't help.

In desperation, I also tried modifying my hand the automagically generated code, adding it the new column in a fashion similar to what it had for all the old columns. I couldn't make that work.

Body:
I have a VB.NET program that I wrote 20 years ago and last updated 7 years ago. I have gotten a new computer and new version of Visual Studio recently.

The program uses a DB created with MS Access via the OLEDB mechanism. I originally created the DB connection by dragging and dropping tables from the DB into a VB window. This generates a lot of code automagically that I have never had to look at in the past. This code takes care of the DB queries and updates. Code I have explicitly written adds, modifies or deletes rows from the tables.

In the past I have been able to manually add a column to the Access DB and get the automatically generated code to update and make that column available to my code.

I am trying to do that now and I've either forgotten a crucial step or the newest version of Visual Studio is not compatible with my ancient code. The symptom is the new column does not get updated when I update all the other columns. If I look at the automagically generated code (in routine InitilizeComponent) it has lines like:

Me.OleDbUpdateCommand5.CommandText = resources.GetString("OleDbUpdateCommand5.CommandText")
        Me.OleDbUpdateCommand5.Connection = Me.dcWageLossDB
        Me.OleDbUpdateCommand5.Parameters.AddRange(New System.Data.OleDb.OleDbParameter() {New System.Data.OleDb.OleDbParameter("CaseId", System...

where in the arguments of the last call it lists all the columns EXCEPT for my my new one.

Note that while the new column does not get properly added to the DB queries, it does get added to internal structures so that in my code I can refer to the new column by name and set its value.

I know this question is rather fuzzy. It is not practical to provide the (quite long and complex) code. Since the problem probably depends on the long history, it also is not practical to try to create a small simple version of it.

I'm just hoping someone has run into this problem and knows the solution.

Thanks

I have already tried graphically deleting and adding back all the tables in the .xsd file used in the query via the solution explorer - data connections. It didn't help.

In desperation, I also tried modifying my hand the automagically generated code, adding it the new column in a fashion similar to what it had for all the old columns. I couldn't make that work.


问:
HTML Video not playing in majority of FF Responsive Mode Phone User Agents
I have a video which plays fine on native FF and Galaxy S10/S10+ UA in FF Responsive Design mode. It played properly once on iPhone SE but hasn't worked again since.
In all other UAs available the thumbnail loads, but when pressing play, the video pauses immediately, and progresses by a few frames. the progress bar fills white implying the whole video is loaded.
Sometimes rapid clicking can make the video play as intended.
Here is the code:

```<code><figure class="grid-item-1/3">
    <video controls playsinline>
        <source src="resources/video1.mp4" type="video/mp4">
        <source src="resources/video2.webm" type="video/webm">
    </video>
</figure>
</code>```

The MP4 is encoded with H264.HP video and MPEG-4 AAC audio and the webm VP9 and Vorbis, the former being encoded by my phone when I took it and the latter, handbrake.

When the initial MP4 had issues, I researched codec compatibility, and encoded it as a .webm. When this didn't work I Googled the issue and was only able to find one relevant issue - where I added the playsinline tag.

I have tried viewing the page locally and on my webserver, neither behaves differently.

I have also tested the page on an actual phone - Google Pixel 4, Android 13, with Chrome & Firefox and the video works as intended.

I also tried adding height & width tags that matched the resolution of the source file, that just broke my CSS and the video still wouldn't play.

Body:
I have a video which plays fine on native FF and Galaxy S10/S10+ UA in FF Responsive Design mode. It played properly once on iPhone SE but hasn't worked again since.
In all other UAs available the thumbnail loads, but when pressing play, the video pauses immediately, and progresses by a few frames. the progress bar fills white implying the whole video is loaded.
Sometimes rapid clicking can make the video play as intended.
Here is the code:

    <video controls playsinline>
        <source src="resources/video1.mp4" type="video/mp4">
        <source src="resources/video2.webm" type="video/webm">
    </video>

The MP4 is encoded with H264.HP video and MPEG-4 AAC audio and the webm VP9 and Vorbis, the former being encoded by my phone when I took it and the latter, handbrake.

When the initial MP4 had issues, I researched codec compatibility, and encoded it as a .webm. When this didn't work I Googled the issue and was only able to find one relevant issue - where I added the playsinline tag.

I have tried viewing the page locally and on my webserver, neither behaves differently.

I have also tested the page on an actual phone - Google Pixel 4, Android 13, with Chrome & Firefox and the video works as intended.

I also tried adding height & width tags that matched the resolution of the source file, that just broke my CSS and the video still wouldn't play.


问:
Tabulator: add class to class list, on cells when hidden by pagination
I need to add and/or remove a class to all cells even when they are hidden by pagination. I am able to add a class, but only the cells on the active page are getting the class. I understand that is because it is only updating what is available in the DOM and the hidden rows are not active in the DOM at the time, I'm adding the class.

Is there a way that Tabulator handles this?

As you can see from below i'm getting the rows (not shown) and then looping over the rows and attempting to update the cell classList.

```<code>for (var i = 0; i < rows.length; i++) {
    if (rows[i] != this){
        var row = rows[i],
            cell = row.getCell(col),
            cellElement = cell.getElement();

        cellElement.classList.add('disable-cell');

        console.log(cell);

    }
}
</code>```

Body:
I need to add and/or remove a class to all cells even when they are hidden by pagination. I am able to add a class, but only the cells on the active page are getting the class. I understand that is because it is only updating what is available in the DOM and the hidden rows are not active in the DOM at the time, I'm adding the class.

Is there a way that Tabulator handles this?

As you can see from below i'm getting the rows (not shown) and then looping over the rows and attempting to update the cell classList.

for (var i = 0; i < rows.length; i++) {
    if (rows[i] != this){
        var row = rows[i],
            cell = row.getCell(col),
            cellElement = cell.getElement();

        cellElement.classList.add('disable-cell');

        console.log(cell);

    }
}


问:
How do you configure 3rd party C# Roslyn analysers in an .editorconfig file (SonarLint, xUnit etc)?
I'm trying to configure the SonarLint and xUnit analyzers in the .editorconfig file but I have no idea how.

I scoured both SonarLint and xUnit's docs and there's no indication on how to achieve this.

What am I missing?


问:
What does intval() actually do?
As shown in the code sample below the conversion of a float value of 43648 to integer with intval() yields int(43647) and not int(43648).

Code:

```<code>$f = (float)"43.650" - 0.002;
var_dump($f);
var_dump($f*1000);
var_dump(intval($f*1000));
</code>```

Output:

```<code>float(43.648)
float(43648)
int(43647)
</code>```

Why?

Title: What does intval() actually do?

Body:
As shown in the code sample below the conversion of a float value of 43648 to integer with intval() yields int(43647) and not int(43648).

Code:

$f = (float)"43.650" - 0.002;
var_dump($f);
var_dump($f*1000);
var_dump(intval($f*1000));

Output:

float(43.648)
float(43648)
int(43647)

Why?


问:
Selenide driver implemention: TS2345 Argument of type 'WebDriver' is not assignable to parameter of type 'WebDriver | (() => WebDriver)'
Im using selenidejs with typescript.
I first init a WebDriver with selenium, and then I implement it to the selenide Browser,
as seen in this link - docs to selenidejs:
https://github.com/KnowledgeExpert/selenidejs

When I try to do it like in the link, it shows the error in the title.
I need to implement the Browser like this, since i want to add arguments (chromeoptions) to the driver.

world.ts:

```<code>import { Builder, Capabilities } from 'selenium-webdriver';
import { Browser } from 'selenidejs';

async init() {

    const webdriver = new Builder().withCapabilities(Capabilities.chrome()).build();
    const browser = Browser.configuredWith()
        .driver(await webdriver) // the error happens here
        .baseUrl('https://google.com')
        .timeout(4000)
        .build();
}

</code>```

many thanks for helping

Body:
Im using selenidejs with typescript.
I first init a WebDriver with selenium, and then I implement it to the selenide Browser,
as seen in this link - docs to selenidejs:
https://github.com/KnowledgeExpert/selenidejs

When I try to do it like in the link, it shows the error in the title.
I need to implement the Browser like this, since i want to add arguments (chromeoptions) to the driver.

world.ts:

import { Builder, Capabilities } from 'selenium-webdriver';
import { Browser } from 'selenidejs';

async init() {

    const webdriver = new Builder().withCapabilities(Capabilities.chrome()).build();
    const browser = Browser.configuredWith()
        .driver(await webdriver) // the error happens here
        .baseUrl('https://google.com')
        .timeout(4000)
        .build();
}

many thanks for helping


问:
Modify onHeadersReceived (webrequest API) with a value from chrome storage
In my scenario, I am using manifest V3 + webrequest with blocking (self hosted extension).
Is there a good way to deal with modifying a response header that includes a value that is stored in chrome's storage area? I'm noticing that if I try to retrieve the value inside the callback, that by the time the script resumes (post fetching the value), then the page has already loaded and its too late to modify the header.

I tried using the get function to retrieve a value from the StorageArea.
Another approach I tried was using an async funtion with await when fetching the data.
Both end up with the same results.

What I did get to work was caching the storage area in a global variable (same as seen in the "Asynchronous preload from storage" section in the storage api documentation (https://developer.chrome.com/docs/extensions/reference/storage/#asynchronous-preload-from-storage). Then I directly used the variable inside the webRequest.onHeadersReceived callback.

Would this be the best approach? Is it reliable? When the service worker eventually is terminated, I'm assuming that the global variable will no longer contain the data that was previously saved and I would have to ensure that it gets re-initialized using other events.


问:
I Want to Get the Match Data on Specific Post ID Inside of Repeater and Select Field
```<code>           <?php if( have_rows('repeater_movies') ): // Repeater Field
                            while ( have_rows('repeater_movies') ) : the_row(); ?>

                            <?php $posts = get_sub_field('movies_relationship'); // Relationship Field

                                if($posts ): ?>
                                <?php foreach( $posts as $p):
                                // this is the line i want to fix.
                                if ($p->$id = get_the_ID());
                                ?>

                                <a href="<?php echo get_permalink($p->ID); ?>"><?php echo get_the_title($p->ID);?> </a>
                                <?php the_sub_field('select_role' ,$post->ID,false);?>

                                <?php endforeach; ?>
                                <?php endif;?>
                                <?php endwhile;

                            else :
                            //No thing Found
                            endif;?>
</code>```

Im Trying to get the role of each data on relationship field without getting the whole data on single line. i want to get only the related data on current post. if actor 1 is current. then give me the tag data on main role (Actor 1)... please see attached file here thanks

Body:
           <?php if( have_rows('repeater_movies') ): // Repeater Field
                            while ( have_rows('repeater_movies') ) : the_row(); ?>

                            <?php $posts = get_sub_field('movies_relationship'); // Relationship Field

                                if($posts ): ?>
                                <?php foreach( $posts as $p):
                                // this is the line i want to fix.
                                if ($p->$id = get_the_ID());
                                ?>

                                <a href="<?php echo get_permalink($p->ID); ?>"><?php echo get_the_title($p->ID);?>
                                <?php the_sub_field('select_role' ,$post->ID,false);?>

                                <?php endforeach; ?>
                                <?php endif;?>
                                <?php endwhile;

                            else :
                            //No thing Found
                            endif;?>

Im Trying to get the role of each data on relationship field without getting the whole data on single line. i want to get only the related data on current post. if actor 1 is current. then give me the tag data on main role (Actor 1)... please see attached file here thanks


问:
Devise logging in stops working after adding a new devise model
I have a rails application and I use devise for authentication. So I had one user that authenticated well and after adding another type of user that needed to be authenticated I discovered the original user could no longer sign in.

This is the original user sessions and registrations controllers:

```<code>class Users::SessionsController < Devise::SessionsController
  respond_to :json
  skip_before_action :require_no_authentication

  private

  def respond_with(resource, _opts = {})
    user = User.find_by(email: params[:user][:email].downcase)

    if user&.phone_number == params[:user][:phone_number]
      sign_in(resource_name, user)

      render json: user, status: :ok
    else
      render json: { message: "Invalid Email or Phone Number", success: "0" }, status: :unauthorized
    end
  end

  def respond_to_on_destroy
    head :no_content
  end
end
</code>```
```<code>class Users::RegistrationsController < Devise::RegistrationsController
  respond_to :json
  skip_before_action :require_no_authentication

  def create
    build_resource(sign_up_params)
    resource.save
    sign_up(resource_name, resource) if resource.persisted?

    if resource.persisted?
      render json: resource, status: :ok
    else
      render json: resource.errors, status: :unprocessable_entity
    end
  end
end
</code>```

This is the new sessions and registrations controllers for the new user:

```<code>class BrokerageUsers::SessionsController < Devise::SessionsController
  respond_to :json
  skip_before_action :require_no_authentication

  private

  def respond_with(resource, _opts = {})
    user = BrokerageUser.find_by(email: params[:brokerage_user]&.dig(:email)&.downcase)

    if user && user.valid_password?(params[:brokerage_user][:password])
      sign_in(resource_name, user)

      render json: user, status: :ok
    else
      render json: { message: "Invalid Email or Password", success: "0" }, status: :unauthorized
    end
  end
end
</code>```
```<code>class BrokerageUsers::RegistrationsController < Devise::RegistrationsController
  respond_to :json
  skip_before_action :require_no_authentication

  def create
    build_resource(sign_up_params)
    resource.save
    sign_up(resource_name, resource) if resource.persisted?

    if resource.persisted?
      render json: resource, status: :ok
    else
      render json: resource.errors, status: :unprocessable_entity
    end
  end

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:email, :password) }
  end
end
</code>```

This is the folder structure that I have:

structure

This is my routes.rb:

```<code>Rails.application.routes.draw do
  devise_for :users,
              controllers: {
                sessions: 'users/sessions',
                registrations: 'users/registrations'
             }
  devise_for :brokerage_users,
              controllers: {
                sessions: 'brokerage_users/sessions',
                registrations: 'brokerage_users/registrations'
              }
end
</code>```

I have no idea what is wrong here, what I know is logging in and signing up worked well for User before I added BrokerageUser but afterwards only signing up in user seem to work but signing returns 401 (tested it many times with correct credentials that I used right after signing up).

BrokerageUser's logging in and signing up are working perfectly fine however.

I tried putting log statements inside the User's sessions controller at the top of respond_with function but it seems execution never comes to this part of the code.

Body:
I have a rails application and I use devise for authentication. So I had one user that authenticated well and after adding another type of user that needed to be authenticated I discovered the original user could no longer sign in.

This is the original user sessions and registrations controllers:

class Users::SessionsController < Devise::SessionsController
  respond_to :json
  skip_before_action :require_no_authentication

  private

  def respond_with(resource, _opts = {})
    user = User.find_by(email: params[:user][:email].downcase)

    if user&.phone_number == params[:user][:phone_number]
      sign_in(resource_name, user)

      render json: user, status: :ok
    else
      render json: { message: "Invalid Email or Phone Number", success: "0" }, status: :unauthorized
    end
  end

  def respond_to_on_destroy
    head :no_content
  end
end

class Users::RegistrationsController < Devise::RegistrationsController
  respond_to :json
  skip_before_action :require_no_authentication

  def create
    build_resource(sign_up_params)
    resource.save
    sign_up(resource_name, resource) if resource.persisted?

    if resource.persisted?
      render json: resource, status: :ok
    else
      render json: resource.errors, status: :unprocessable_entity
    end
  end
end

This is the new sessions and registrations controllers for the new user:

class BrokerageUsers::SessionsController < Devise::SessionsController
  respond_to :json
  skip_before_action :require_no_authentication

  private

  def respond_with(resource, _opts = {})
    user = BrokerageUser.find_by(email: params[:brokerage_user]&.dig(:email)&.downcase)

    if user && user.valid_password?(params[:brokerage_user][:password])
      sign_in(resource_name, user)

      render json: user, status: :ok
    else
      render json: { message: "Invalid Email or Password", success: "0" }, status: :unauthorized
    end
  end
end

class BrokerageUsers::RegistrationsController < Devise::RegistrationsController
  respond_to :json
  skip_before_action :require_no_authentication

  def create
    build_resource(sign_up_params)
    resource.save
    sign_up(resource_name, resource) if resource.persisted?

    if resource.persisted?
      render json: resource, status: :ok
    else
      render json: resource.errors, status: :unprocessable_entity
    end
  end

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:email, :password) }
  end
end

This is the folder structure that I have:

structure

This is my routes.rb:

Rails.application.routes.draw do
  devise_for :users,
              controllers: {
                sessions: 'users/sessions',
                registrations: 'users/registrations'
             }
  devise_for :brokerage_users,
              controllers: {
                sessions: 'brokerage_users/sessions',
                registrations: 'brokerage_users/registrations'
              }
end

I have no idea what is wrong here, what I know is logging in and signing up worked well for User before I added BrokerageUser but afterwards only signing up in user seem to work but signing returns 401 (tested it many times with correct credentials that I used right after signing up).

BrokerageUser's logging in and signing up are working perfectly fine however.

I tried putting log statements inside the User's sessions controller at the top of respond_with function but it seems execution never comes to this part of the code.


问:
Cast Boolean to varchar or is there a way to compare boolean with null if true or false not provided
I am using a Saas based application. And i need one report. For that i had to write a data query(sql) it has multiple where conditions connected with OR ..Now i want to put filter on boolean value..if i put value in boolean it works ..but when i need to out filter on other conditions and the boolean field remains null ..it throws an error. Can anyone help me resolve this.

Query :

```<code>Select .... Where boolean='true/false' or string=''
</code>```

But if i place null or no value in boolean as i have to search with string it throws error.

Body:
I am using a Saas based application. And i need one report. For that i had to write a data query(sql) it has multiple where conditions connected with OR ..Now i want to put filter on boolean value..if i put value in boolean it works ..but when i need to out filter on other conditions and the boolean field remains null ..it throws an error. Can anyone help me resolve this.

Query :

Select .... Where boolean='true/false' or string=''

But if i place null or no value in boolean as i have to search with string it throws error.


问:
Chronometer is flickering while running
I have developed a Stopwatch app which is having chronometer for time count but the problem is that the chronometer is flickering while counting time. I have search the Internet for the solution of this but I can't find anything. Can anyone help whith this issue??

Plese Provide solution of this error

I have attached the java code.

My Java code is:

```<code>public class MainActivity extends AppCompatActivity {

    //Name Declare
    private AdView mAdView;
    private ImageButton imageButton2, imageButton;
    private Chronometer chronometer2;
    private TextView textView2;
    private ConstraintLayout clayout;
    boolean iscolor = true;

    //Millis
    private boolean isResume;
    Handler handler;
    long tMilliSec, tStart, tBuff, tUpdate = 0L;
    int sec, min, milliSec;

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

        //Ads
        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });

        mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        //ID Declare
        imageButton2 = findViewById(R.id.imageButton2);
        imageButton = findViewById(R.id.imageButton);
        chronometer2 = findViewById(R.id.chronometer2);
        textView2 = findViewById(R.id.textView2);
        clayout = findViewById(R.id.clayout);

        //Dark Theme
        imageButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (iscolor) {
                    clayout.setBackgroundColor(Color.parseColor("#0A253A"));
                    textView2.setTextColor(Color.parseColor("#0074f4"));
                    chronometer2.setTextColor(Color.parseColor("#0074f4"));
                    iscolor = false;
                } else {
                    clayout.setBackgroundColor(Color.parseColor("#4286f5"));
                    textView2.setTextColor(Color.parseColor("#BCB9B9"));
                    chronometer2.setTextColor(Color.parseColor("#ffffff"));
                    iscolor = true;
                }

            }

        });

        handler = new Handler();

        clayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isResume){
                    tStart = SystemClock.uptimeMillis();
                    handler.postDelayed(runnable, 0);
                    chronometer2.start();
                    isResume = true;
                    textView2.setText("Tap to pause");
                }
                else{
                    tBuff += tMilliSec;
                    handler.removeCallbacks(runnable);
                    chronometer2.stop();
                    isResume = false;
                    textView2.setText("Tap to resume");

                }

            }
        });

        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tMilliSec = 0L;
                tStart = 0L;
                tBuff = 0L;
                tUpdate = 0L;
                sec = 0;
                min = 0;
                milliSec = 0;
                handler.removeCallbacks(runnable);
                chronometer2.stop();
                isResume = false;
                chronometer2.setText("00:00:00");
                textView2.setText("Tap to start");

            }
        });

    }

    public Runnable runnable = new Runnable() {
        @Override
        public void run() {
            tMilliSec = SystemClock.uptimeMillis() - tStart;
            tUpdate = tBuff + tMilliSec;
            sec = (int) (tUpdate/1000);
            min = sec/60;
            sec = sec%60;
            milliSec = (int) (tUpdate%100);
            chronometer2.setText(String.format("%02d", min) + ":"
                    + String.format("%02d", sec) + ":" + String.format("%02d", milliSec));
            handler.postDelayed(this, 60);
        }
    };
}

</code>```

Title: Chronometer is flickering while running

Body:
I have developed a Stopwatch app which is having chronometer for time count but the problem is that the chronometer is flickering while counting time. I have search the Internet for the solution of this but I can't find anything. Can anyone help whith this issue??

Plese Provide solution of this error

I have attached the java code.

My Java code is:

public class MainActivity extends AppCompatActivity {

    //Name Declare
    private AdView mAdView;
    private ImageButton imageButton2, imageButton;
    private Chronometer chronometer2;
    private TextView textView2;
    private ConstraintLayout clayout;
    boolean iscolor = true;

    //Millis
    private boolean isResume;
    Handler handler;
    long tMilliSec, tStart, tBuff, tUpdate = 0L;
    int sec, min, milliSec;

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

        //Ads
        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });

        mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        //ID Declare
        imageButton2 = findViewById(R.id.imageButton2);
        imageButton = findViewById(R.id.imageButton);
        chronometer2 = findViewById(R.id.chronometer2);
        textView2 = findViewById(R.id.textView2);
        clayout = findViewById(R.id.clayout);

        //Dark Theme
        imageButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (iscolor) {
                    clayout.setBackgroundColor(Color.parseColor("#0A253A"));
                    textView2.setTextColor(Color.parseColor("#0074f4"));
                    chronometer2.setTextColor(Color.parseColor("#0074f4"));
                    iscolor = false;
                } else {
                    clayout.setBackgroundColor(Color.parseColor("#4286f5"));
                    textView2.setTextColor(Color.parseColor("#BCB9B9"));
                    chronometer2.setTextColor(Color.parseColor("#ffffff"));
                    iscolor = true;
                }

            }

        });

        handler = new Handler();

        clayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isResume){
                    tStart = SystemClock.uptimeMillis();
                    handler.postDelayed(runnable, 0);
                    chronometer2.start();
                    isResume = true;
                    textView2.setText("Tap to pause");
                }
                else{
                    tBuff += tMilliSec;
                    handler.removeCallbacks(runnable);
                    chronometer2.stop();
                    isResume = false;
                    textView2.setText("Tap to resume");

                }

            }
        });

        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tMilliSec = 0L;
                tStart = 0L;
                tBuff = 0L;
                tUpdate = 0L;
                sec = 0;
                min = 0;
                milliSec = 0;
                handler.removeCallbacks(runnable);
                chronometer2.stop();
                isResume = false;
                chronometer2.setText("00:00:00");
                textView2.setText("Tap to start");

            }
        });

    }

    public Runnable runnable = new Runnable() {
        @Override
        public void run() {
            tMilliSec = SystemClock.uptimeMillis() - tStart;
            tUpdate = tBuff + tMilliSec;
            sec = (int) (tUpdate/1000);
            min = sec/60;
            sec = sec%60;
            milliSec = (int) (tUpdate%100);
            chronometer2.setText(String.format("%02d", min) + ":"
                    + String.format("%02d", sec) + ":" + String.format("%02d", milliSec));
            handler.postDelayed(this, 60);
        }
    };
}


问:
Geolocation after the device is ready
I have a iphone app built with jquery mobile which is wrapped in phonegap. I am trying to get geolocation after the device is ready to get rid of the nasty alert  /var/mobile/Applications/157EB70D-4AA7-826E-690F0CBE0F/appname.app/www/index.html.

I have set some alerts to see if the device is ready and it keeps saying isDeviceReady is:false which is meaning the device is not ready

he is the code

```<code>$(function() {

var isWatching = false;
var isAndroid = ( navigator.userAgent.indexOf('Android') != -1 ) ? true : false;
    var isDeviceReady = false;

   document.addEventListener("deviceready", onDeviceReady, false);

   function onDeviceReady() {
  isDeviceReady = true;
   }
   function getClientPosition(id, successCallback, errorCallback) {
    if ( isDeviceReady ) {
      var hasFoundMarker = false;
    if ( hasClientPosition() ) {
$(id).gmap('findMarker', 'tag', 'client', function(found, marker) {
                if (found) {
                    hasFoundMarker = true;
                    marker.setPosition(getClientLatLng());
                         $(id).gmap('getMap').setCenter(marker.getPosition());
        if ( $.isFunction(successCallback) ) {
        successCallback.call(this, getClientLatLng());
                    }
                }
            });
            if ( !hasFoundMarker ) {
                addClientMarker(id, getClientLatLng());
                if ( $.isFunction(successCallback) ) {
                    successCallback.call(this,    getClientLatLng());
                }
            }
        }

                            if ( !isWatching[id] ) {
            if ( navigator.geolocation ) {
                isWatching[id] = true;
                if ( isAndroid ) {
                    watch[id] = setInterval(function() {
                         navigator.geolocation.getCurrentPosition (
                            function( position ) {
                                var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                                $(id).gmap('findMarker', 'tag', 'client', function(found, marker) {
                                    if (found) {
                                        hasFoundMarker = true;
                                        marker.setPosition(latlng);
                                        $(id).gmap('getMap').setCenter(latlng);
                                    }
                                });
                                if ( !hasFoundMarker ) {
                                    addClientMarker(id, latlng);
                                }
                                setData(CLIENT_HAS_POSITION, true);
                                setData(CLIENT_LATITUDE, latlng.lat());
                                setData(CLIENT_LONGITUDE, latlng.lng());
                                if ( $.isFunction(successCallback) ) {
                                    successCallback.call(this, latlng);
                                }
                            },
                            function( error ) {
                                if ( $.isFunction(errorCallback) ) {
                                    errorCallback.call(this, error);
                                }
                            },
                            opts.geolocationOptions
                        );
                    }, 5000);
                } else {
                    watch[id] = navigator.geolocation.watchPosition (
                        function( position ) {
                            var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                            $(id).gmap('findMarker', 'tag', 'client', function(found, marker) {
                                if (found) {
                                    hasFoundMarker = true;
                                    marker.setPosition(latlng);
                                    $(id).gmap('getMap').setCenter(latlng);
                                }
                            });
                            if ( !hasFoundMarker ) {
                                addClientMarker(id, latlng);
                            }
                            setData(CLIENT_HAS_POSITION, true);
                            setData(CLIENT_LATITUDE, latlng.lat());
                            setData(CLIENT_LONGITUDE, latlng.lng());
                            if ( $.isFunction(successCallback) ) {
                                successCallback.call(this, latlng);
                            }
                        },
                        function( error ) {
                            if ( $.isFunction(errorCallback) ) {
                                errorCallback.call(this, error);
                            }
                        },
                        opts.geolocationOptions
                    );
                }
            }
        }

    } else {
        var timer = setTimeout(function() {
            getClientPosition(id, successCallback, errorCallback);
            alert('Trying to get client position. This message will pop up again in 15 sec, unless device is ready. IsDeviceReady is: '+isDeviceReady);
        }, 15000);
    }
}
</code>```

Anyone have any ideas where i am going wrong?

ContentLicense: CC BY-SA 3.0

Title: Geolocation after the device is ready

Body:
I have a iphone app built with jquery mobile which is wrapped in phonegap. I am trying to get geolocation after the device is ready to get rid of the nasty alert  /var/mobile/Applications/157EB70D-4AA7-826E-690F0CBE0F/appname.app/www/index.html.

I have set some alerts to see if the device is ready and it keeps saying isDeviceReady is:false which is meaning the device is not ready

he is the code

$(function() {

var isWatching = false;
var isAndroid = ( navigator.userAgent.indexOf('Android') != -1 ) ? true : false;
    var isDeviceReady = false;

   document.addEventListener("deviceready", onDeviceReady, false);

   function onDeviceReady() {
  isDeviceReady = true;
   }
   function getClientPosition(id, successCallback, errorCallback) {
    if ( isDeviceReady ) {
      var hasFoundMarker = false;
    if ( hasClientPosition() ) {
$(id).gmap('findMarker', 'tag', 'client', function(found, marker) {
                if (found) {
                    hasFoundMarker = true;
                    marker.setPosition(getClientLatLng());
                         $(id).gmap('getMap').setCenter(marker.getPosition());
        if ( $.isFunction(successCallback) ) {
        successCallback.call(this, getClientLatLng());
                    }
                }
            });
            if ( !hasFoundMarker ) {
                addClientMarker(id, getClientLatLng());
                if ( $.isFunction(successCallback) ) {
                    successCallback.call(this,    getClientLatLng());
                }
            }
        }

                            if ( !isWatching[id] ) {
            if ( navigator.geolocation ) {
                isWatching[id] = true;
                if ( isAndroid ) {
                    watch[id] = setInterval(function() {
                         navigator.geolocation.getCurrentPosition (
                            function( position ) {
                                var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                                $(id).gmap('findMarker', 'tag', 'client', function(found, marker) {
                                    if (found) {
                                        hasFoundMarker = true;
                                        marker.setPosition(latlng);
                                        $(id).gmap('getMap').setCenter(latlng);
                                    }
                                });
                                if ( !hasFoundMarker ) {
                                    addClientMarker(id, latlng);
                                }
                                setData(CLIENT_HAS_POSITION, true);
                                setData(CLIENT_LATITUDE, latlng.lat());
                                setData(CLIENT_LONGITUDE, latlng.lng());
                                if ( $.isFunction(successCallback) ) {
                                    successCallback.call(this, latlng);
                                }
                            },
                            function( error ) {
                                if ( $.isFunction(errorCallback) ) {
                                    errorCallback.call(this, error);
                                }
                            },
                            opts.geolocationOptions
                        );
                    }, 5000);
                } else {
                    watch[id] = navigator.geolocation.watchPosition (
                        function( position ) {
                            var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                            $(id).gmap('findMarker', 'tag', 'client', function(found, marker) {
                                if (found) {
                                    hasFoundMarker = true;
                                    marker.setPosition(latlng);
                                    $(id).gmap('getMap').setCenter(latlng);
                                }
                            });
                            if ( !hasFoundMarker ) {
                                addClientMarker(id, latlng);
                            }
                            setData(CLIENT_HAS_POSITION, true);
                            setData(CLIENT_LATITUDE, latlng.lat());
                            setData(CLIENT_LONGITUDE, latlng.lng());
                            if ( $.isFunction(successCallback) ) {
                                successCallback.call(this, latlng);
                            }
                        },
                        function( error ) {
                            if ( $.isFunction(errorCallback) ) {
                                errorCallback.call(this, error);
                            }
                        },
                        opts.geolocationOptions
                    );
                }
            }
        }

    } else {
        var timer = setTimeout(function() {
            getClientPosition(id, successCallback, errorCallback);
            alert('Trying to get client position. This message will pop up again in 15 sec, unless device is ready. IsDeviceReady is: '+isDeviceReady);
        }, 15000);
    }
}

Anyone have any ideas where i am going wrong?


问:
Pytorch training with brevitas gives Nan after first step
So, I'm trying to implement the VGG16 architecture with pytorch and brevitas for FPGA. While training the model, my loss comes out to be nan. My input images are correct (I debugged this with a couple of outputs), but there is no prediction happening after the first step. Can someone tell me what I'm doing wrong?

I will attach my model structure and training below

Model Structure
This is the model structure

Training
enter image description here

Dataloader
enter image description here

I've tried changing hyperparamers, Optimizers and so on, but I still get the same nan after my first stem in my first epoch. Can someone help out?

Thanks


问:
How to generate graph in pdf in rails
I want to generate bar graph in pdf, How to generate graph in pdf in rails.
I want to generate direct graph in pdf without storing any image.

```<code>  <div class="chartCard">
    <div class="chartBox">
      <canvas id="myChart"></canvas>
      <div>
      </div>
      <script  type="text/javascript"  width="400" height="400" data_fail="<%data_fail_reason%>" data_count="<%data_fail_count%>" >

        const data = {
            data: {
                labels: data_fail_reason,
                datasets: [{
                    label: '# of Votes',
                    data: data_fail_count,
                    borderWidth: 1
                }]
            },
        }

        const bgColor = {
          id: 'bgColor',
          beforeDraw:(chart.options) => {
            const {ctx,width,height} = chart;
            ctx.fillStyly='white'
            ctx.fillRect(0,0,width,height)
            ctx.restore()
          }
        }

        const config = {
          type: 'bar',
          data,
          options:{
            scales:{
              y:{
                beginAtZero:true
              }
            }
          },
          plugins:[bgColor]
        }

        var ctx = document.getElementById('myChart');
        var myChart = new Chart(ctx,config);

      </script>
    </div>
  </div>
</code>```

I'm writing this code in report.html.erb file.
I'm using ruby on rails 5 and wicked-pdf,wkhtmltopdf-binary gems

In apllication.js

```<code>const Chart = require('chart.js')
</code>```

Title: How to generate graph in pdf in rails

Body:
I want to generate bar graph in pdf, How to generate graph in pdf in rails.
I want to generate direct graph in pdf without storing any image.

      <canvas id="myChart"></canvas>

I'm writing this code in report.html.erb file.
I'm using ruby on rails 5 and wicked-pdf,wkhtmltopdf-binary gems

In apllication.js

const Chart = require('chart.js')


问:
how can build multi layer query with doctrine for Postgresql in symfony5.4?
```<code>SELECT *
FROM game
WHERE game."id" IN (SELECT DISTINCT(game_id)
                    FROM game_gamecategory
                    ***WHERE  gamecategory_id IN (1,4)***
                    GROUP BY game_id
                    HAVING COUNT(*) > 1)
ORDER BY id;
</code>```

I want to make query builder above query;
Following code is my query builder.
But I can't get correct records with it.

```<code>            $qb = $this->createQueryBuilder('g')
                ->leftJoin('g.provider', 'p')
                ->leftJoin('g.categories', 'c')
                ->andWhere("(" . $this->whereSearch([4], 'c.id') . ")")
                ***->andWhere("(" . $this->whereSearch([1], 'c.id') . ")")***
                ->addOrderBy('g.popularity', 'DESC')
                ->addOrderBy('g.id', 'DESC')
                ->setMaxResults($limit);
</code>```

Body:
SELECT *
FROM game
WHERE game."id" IN (SELECT DISTINCT(game_id)
                    FROM game_gamecategory
                    ***WHERE  gamecategory_id IN (1,4)***
                    GROUP BY game_id
                    HAVING COUNT(*) > 1)
ORDER BY id;

I want to make query builder above query;
Following code is my query builder.
But I can't get correct records with it.

            $qb = $this->createQueryBuilder('g')
                ->leftJoin('g.provider', 'p')
                ->leftJoin('g.categories', 'c')
                ->andWhere("(" . $this->whereSearch([4], 'c.id') . ")")
                ***->andWhere("(" . $this->whereSearch([1], 'c.id') . ")")***
                ->addOrderBy('g.popularity', 'DESC')
                ->addOrderBy('g.id', 'DESC')
                ->setMaxResults($limit);


问:
Merge nativescript app with native ios swift app
We are trying to embed the nativescript app into existing ios swift app using this https://github.com/NativeScript/sample-ios-embedded/blob/master/HOWTO.md , we have NS 8 and the class changed alot compared to older version.

Can someone guide us to proceed with this or any links that can help

Tried the embed app but its for older version of NS and doesnt work with latest NS


问:
My netmiko script isn't working when I try to connect to my router
I'm trying to run my python script with my router but I get this errror when I run it: Failed to enter enable mode. Please ensure you pass the 'secret' argument to ConnectHandler.

I have already included the enable argument in my script but I still get the error.
I would appreciate help, I am new to using netmiko.

```<code>import difflib
import netmiko

routerconnectinfo = { #create variable of information to store
    'device_type': 'cisco_ios', #connect via ssh
    #'device_type': 'cisco_ios_telnet', #connect via telnet
    'host':'192.168.56.101', #ip address of the route
    'username':'ubaid', #username of the route
    'password':'rahman', #password for router
    'secret':'chicken'
}

session = netmiko.ConnectHandler(**routerconnectinfo)
session.enable()

config = session.send_command("show running-config")
file = open("running_config_copied.txt", "w")
file.write(config)
file.close()

config = session.send_command("show startup-config")
file = open("startup_config_copied.txt", "w")
file.write(config)
file.close()

with open('running_config_copied.txt', 'r') as file1, open('startup_config_copied.txt', 'r') as file2:
    diffs = difflib.ndiff(file1.readlines(), file2.readlines())
    for diff in diffs:
        print(diff)
</code>```

I have added session.enable() to go into enable mode on my router but it still doesn't work.

Body:
I'm trying to run my python script with my router but I get this errror when I run it: Failed to enter enable mode. Please ensure you pass the 'secret' argument to ConnectHandler.

I have already included the enable argument in my script but I still get the error.
I would appreciate help, I am new to using netmiko.

import difflib
import netmiko

routerconnectinfo = { #create variable of information to store
    'device_type': 'cisco_ios', #connect via ssh
    #'device_type': 'cisco_ios_telnet', #connect via telnet
    'host':'192.168.56.101', #ip address of the route
    'username':'ubaid', #username of the route
    'password':'rahman', #password for router
    'secret':'chicken'
}

session = netmiko.ConnectHandler(**routerconnectinfo)
session.enable()

config = session.send_command("show running-config")
file = open("running_config_copied.txt", "w")
file.write(config)
file.close()

config = session.send_command("show startup-config")
file = open("startup_config_copied.txt", "w")
file.write(config)
file.close()

with open('running_config_copied.txt', 'r') as file1, open('startup_config_copied.txt', 'r') as file2:
    diffs = difflib.ndiff(file1.readlines(), file2.readlines())
    for diff in diffs:
        print(diff)

I have added session.enable() to go into enable mode on my router but it still doesn't work.


问:
Jboss server logs not printing in eclipse console
I have configured JBoss 7.0 in eclipse and when I deploy my project, server logs are getting written in server.log file but are not getting displayed in eclipse console.

Can anyone suggest possible reasons for this?


问:
Mongo group by time interval and offset interval
I want to query the data based on time, so i tried group by time(15mins) with match followed by group query.
Group by time: 15 mins

```<code>{$group: {_id: {
        "date": {
            "$subtract": [
                {
                    "$toLong": {
                        "$toDate": "$timeStamp"
                    }
                },
                {
                    "$mod": [
                        {
                            "$toLong": {
                                "$toDate": "$timeStamp"
                            }
                        },
                        900000
                    ]
                }
            ]
        }
    },value: {$avg: {
            "$divide": [
                "$rvalue",
                1000
            ]
        }
    }
}
</code>```

}

This gives me timeStamp with millisec and avg value.
But now i want a query where group by time and offset..query simily to influx group by time(time_intervel,offset_interval)
example influx query:

```<code>SELECT MEAN("water_level")
FROM "h2o_feet"
WHERE "location"='coyote_creek'
  AND time >= '2015-08-18T00:06:00Z' AND time <= '2015-08-18T00:54:00Z'
GROUP BY time(18m,6m)
</code>```

I'm expecting a query similar to influx group by time_interval and offset_interval

Body:
I want to query the data based on time, so i tried group by time(15mins) with match followed by group query.
Group by time: 15 mins

{$group: {_id: {
        "date": {
            "$subtract": [
                {
                    "$toLong": {
                        "$toDate": "$timeStamp"
                    }
                },
                {
                    "$mod": [
                        {
                            "$toLong": {
                                "$toDate": "$timeStamp"
                            }
                        },
                        900000
                    ]
                }
            ]
        }
    },value: {$avg: {
            "$divide": [
                "$rvalue",
                1000
            ]
        }
    }
}

}

This gives me timeStamp with millisec and avg value.
But now i want a query where group by time and offset..query simily to influx group by time(time_intervel,offset_interval)
example influx query:

SELECT MEAN("water_level")
FROM "h2o_feet"
WHERE "location"='coyote_creek'
  AND time >= '2015-08-18T00:06:00Z' AND time <= '2015-08-18T00:54:00Z'
GROUP BY time(18m,6m)

I'm expecting a query similar to influx group by time_interval and offset_interval


问:
How to make several props display text in a reusable component in Vue.js
While I was trying to create a new reusable component,  I've stuck with a problem. I want to make a reusable component that has several texts when should be changed out of this component because this is a reusable component, and I'm gonna use it in the several pages of my app, so I have to make the text changeable.

I've just used the guide and passed props in the script tag and directly accessed then using iteir keywords and prop name. But my code turned out a bit long, so I I somehow need to figure out the another do to it.

```<code><template>
    <div class="tabs">
      <div class="tab_header">{{ title }}</div>
      <ul class="tabs_header">
        <li
          v-for="title in tabTitles"
          :key="title"
          @click="selectedTitle = title"
          :class="{ selected: title == selectedTitle }"
        >
          {{ title }}
        </li>
      </ul>
      <slot />
      <section>
        <h2>Information</h2>
        <div class="Information">
            <h3>Genre</h3>
            <p>{{genre}}</p>

        </div>
        <div class="information">
            <h3>Original Release</h3>
            <p>{{originalRelease}}</p>
        </div>
        <div class="information">
            <h3>Platform(s)</h3>
            <p>{{platforms}}</p>
        </div>
      </section>
      <section>
        <h2>Staff</h2>
        <div class="Information">
            <h3>Delelopers</h3>
            <p>{{developers}}</p>
        </div>
        <div class="information">
            <h3>Publisher(s)</h3>
            <p>{{publishers}}</p>
        </div>
        <div class="informaiton">
            <h3>Directors(s)</h3>
            <p>{{directors}}</p>
        </div>
        <div class="information">
            <h3>Writer(s)</h3>
            <p>{{writers}}</p>
        </div>
        <div class="informaiton">
            <h3>Artist(s)</h3>
            <p>{{artists}}</p>
        </div>
      </section>
      <section>
        <div class="information">
            <h3>Prequel</h3>
            <p>{{prequel}}</p>
        </div>
        <div class="information">
            <h3>Sequel</h3>
            <p>{{sequel}}</p>
        </div>
        <div class="information">
            <h3>Spin-Off</h3>
            <p>{{spin-off}}</p>
        </div>
      </section>

    </div>
  </template>
  <script>
  import { ref } from "vue";
  import { provide } from "vue";
  export default {
    setup(props, { slots }) {
      const tabTitles = ref(slots.default().map((tab) => tab.props.title));
      const selectedTitle = ref(tabTitles.value[0]);

      provide("selectedTitle", selectedTitle);

      return {
        selectedTitle,
        tabTitles,
      };
    },
    props: ["title"],
    created() {
      console.log(this.title);
    },
    props: ["genre"],
    created(){
        connsole.log(this.genre);
    },
    props:["originalRelease"],
    created(){
        console.log(this.originalRelease);
    },
    props:["platforms"],
    created(){
        console.log(this.platforms);
    },
    props:["developers"],
    created(){
        console.log(this.delevopers);
    },
    props:["publishers"],
    created(){
        console.log(this.publishers);
    },
    props:["directors"],
    created(){
        console.log(this.directors);
    },
    props:["writers"],
    created(){
        console.log(this.writers);
    },
    props:["artists"],
    created(){
        console.log(this.artists);
    },
    props:["prequel"],
    created(){
        console.log(this.prequel);
    },
    props:["sequel"],
    created(){
        console.log(this.sequel);
    },
    props:["spin-off"],
    created(){
        console.log(this.spin-off);
    },
  };
  </script>
</code>```

The second problem is the fact it doesn't work at all, even though I've used the same technique that was suggested by that guy.

This is the code that I used on my page.

```<code> <TabsWrapperNarrowVue title="sfgsdfgs"
                genre="fgdfgsdfgsdf" originalRelease="gsfdgsdf"
                platforms="sfgsdfg" developers="sgfsdgs"
                publishers="gfdgsdfgsd." directors="sfgsdfgsd"
                writers="sfgsdgsd"
                artists="sfgsdfgsdfg"
                spin-off="Msfgdgfsd">
                <TabNarrowVue>1</TabNarrowVue>
                <TabNarrowVue>1</TabNarrowVue>
                <TabNarrowVue>1</TabNarrowVue>
                <TabNarrowVue>1</TabNarrowVue>
              </TabsWrapperNarrowVue>
</code>```

Body:
While I was trying to create a new reusable component,  I've stuck with a problem. I want to make a reusable component that has several texts when should be changed out of this component because this is a reusable component, and I'm gonna use it in the several pages of my app, so I have to make the text changeable.

I've just used the guide and passed props in the script tag and directly accessed then using iteir keywords and prop name. But my code turned out a bit long, so I I somehow need to figure out the another do to it.

<template>

{{ title }}

          {{ title }}

      <slot />

Information

Genre

{{genre}}

Original Release

{{originalRelease}}

Platform(s)

{{platforms}}

Staff

Delelopers

{{developers}}

Publisher(s)

{{publishers}}

Directors(s)

{{directors}}

Writer(s)

{{writers}}

Artist(s)

{{artists}}

Prequel

{{prequel}}

Sequel

{{sequel}}

Spin-Off

{{spin-off}}

  </template>

The second problem is the fact it doesn't work at all, even though I've used the same technique that was suggested by that guy.

This is the code that I used on my page.

 <TabsWrapperNarrowVue title="sfgsdfgs"
                genre="fgdfgsdfgsdf" originalRelease="gsfdgsdf"
                platforms="sfgsdfg" developers="sgfsdgs"
                publishers="gfdgsdfgsd." directors="sfgsdfgsd"
                writers="sfgsdgsd"
                artists="sfgsdfgsdfg"
                spin-off="Msfgdgfsd">
                <TabNarrowVue>1</TabNarrowVue>
                <TabNarrowVue>1</TabNarrowVue>
                <TabNarrowVue>1</TabNarrowVue>
                <TabNarrowVue>1</TabNarrowVue>
              </TabsWrapperNarrowVue>


问:
Interpreting raw memory as a c++ object — without explicitly creating it
In the following code a chunk of raw memory (assume it is a network buffer allocated with malloc) is being interpreted as an object. Note that the HwAddr object is never created explicitly and thus its lifetime does not begin. Accessing non-static members of such object would result in UB as it happens in parsePacket().

There appears to be a loophole, however, in that if HwAddr class could be an implicit-lifetime object the code below would be valid. Unfortunately, this isn't the case because this class isn't an aggregate.

The question: is my argument correct? Would it be sufficient to make the HwAddr class an aggregate (e.g. by removing non-default constructor) for the code to not contain an UB? What else am I missing?

```<code>#include <cstdint>
#include <type_traits>
#include <array>
#include <arpa/inet.h>

struct HwAddr {
    std::array<uint8_t, 6> bytes;

    HwAddr() = default;
    HwAddr(const uint8_t *data)
        : bytes{data[0], data[1], data[2], data[3], data[4], data[5]} {}

    bool is_multicast() const noexcept {
        return htons(bytes[0]) & (1<<0);
    }

    bool is_local() const noexcept {
        return htons(bytes[0]) & (1<<1);
    }
};

static_assert(std::is_standard_layout_v<HwAddr>);
static_assert(std::is_trivially_constructible_v<HwAddr>);
//static_assert(std::is_aggregate_v<HwAddr>); // oopsie!!!
static_assert(!std::is_trivially_constructible_v<HwAddr,const uint8_t*>);
static_assert(std::is_trivially_destructible_v<HwAddr>);

struct Packet {
    HwAddr *mac;
    uint16_t priority;
};

void parsePacket(Packet &pkt, uint8_t *buf, std::size_t len) {
    std::size_t const kHwAddrOffset = 42;
    pkt.mac = reinterpret_cast<HwAddr*>(buf + kHwAddrOffset);
    pkt.priority = *reinterpret_cast<uint16_t*>(buf);
    if (pkt.mac->is_local() ) { // UB !!!
        // ...
    }
}

</code>```

Also, what would be the best way to "safeguard" such constructs against an UB? Are static checks for is_trivially_constructible/is_aggregate enough?

PS. This appears to be the case of P0593...

Body:
In the following code a chunk of raw memory (assume it is a network buffer allocated with malloc) is being interpreted as an object. Note that the HwAddr object is never created explicitly and thus its lifetime does not begin. Accessing non-static members of such object would result in UB as it happens in parsePacket().

There appears to be a loophole, however, in that if HwAddr class could be an implicit-lifetime object the code below would be valid. Unfortunately, this isn't the case because this class isn't an aggregate.

The question: is my argument correct? Would it be sufficient to make the HwAddr class an aggregate (e.g. by removing non-default constructor) for the code to not contain an UB? What else am I missing?

#include <cstdint>
#include <type_traits>
#include <array>
#include <arpa/inet.h>

struct HwAddr {
    std::array<uint8_t, 6> bytes;

    HwAddr() = default;
    HwAddr(const uint8_t *data)
        : bytes{data[0], data[1], data[2], data[3], data[4], data[5]} {}

    bool is_multicast() const noexcept {
        return htons(bytes[0]) & (1<<0);
    }

    bool is_local() const noexcept {
        return htons(bytes[0]) & (1<<1);
    }
};

static_assert(std::is_standard_layout_v<HwAddr>);
static_assert(std::is_trivially_constructible_v<HwAddr>);
//static_assert(std::is_aggregate_v<HwAddr>); // oopsie!!!
static_assert(!std::is_trivially_constructible_v<HwAddr,const uint8_t*>);
static_assert(std::is_trivially_destructible_v<HwAddr>);

struct Packet {
    HwAddr *mac;
    uint16_t priority;
};

void parsePacket(Packet &pkt, uint8_t *buf, std::size_t len) {
    std::size_t const kHwAddrOffset = 42;
    pkt.mac = reinterpret_cast<HwAddr*>(buf + kHwAddrOffset);
    pkt.priority = *reinterpret_cast<uint16_t*>(buf);
    if (pkt.mac->is_local() ) { // UB !!!
        // ...
    }
}

Also, what would be the best way to "safeguard" such constructs against an UB? Are static checks for is_trivially_constructible/is_aggregate enough?

PS. This appears to be the case of P0593...


问:
What is the "focal_mean()" morphological operator?
What is mean the "focal_mean" in the morphological operators? What is the algorithm behind this operator? which kernel algorithm is used in this process?</p>