qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
74,520,035
|
<p>I would like to collapse a data frame with < 100 columns fourfold,
whereby the code would iterate over groups of 4 adjacent columns and collapse them into one.
However, the resulting values based on each set of 4, depend on the priority of the value.</p>
<p>For example, the highest priority is '1', so whenever any of the 4 columns has a value '1' for that row it should be the resulting value. The second priority is 0, if the set has one '0' and three NA's, the result should be '0' (as long as there's no '1's). The lowest priority is NA, only sets consisting of NA completely would remain NA. An example below, with reproducible code underneath.</p>
<pre><code> ID c1 c2 c3 c4 c5 c6 c7 c8
row1 1 0 0 0 1 0 0 NA
row2 NA NA NA 0 NA NA NA NA
</code></pre>
<p>becomes</p>
<pre><code> ID c1 c2
row1 1 1
row2 0 NA
</code></pre>
<pre><code>structure(list(ID = c("row1", "row2"), c1 = c(1, NA), c2 = c(0,
NA), c3 = c(0, NA), c4 = c(0, 0), c5 = c(1, NA), c6 = c(0, NA
), c7 = c(0, NA), c8 = c(NA, NA)), class = "data.frame", row.names = c(NA,
-2L))
</code></pre>
|
[
{
"answer_id": 74520264,
"author": "DaveArmstrong",
"author_id": 8206434,
"author_profile": "https://Stackoverflow.com/users/8206434",
"pm_score": 3,
"selected": true,
"text": "dat <- structure(list(ID = c(\"row1\", \"row2\"), c1 = c(1, NA), c2 = c(0, \n NA), c3 = c(0, NA), c4 = c(0, 0), c5 = c(1, NA), c6 = c(0, NA\n ), c7 = c(0, NA), c8 = c(NA, NA)), class = \"data.frame\", row.names = c(NA, \n -2L))\n\nout <- data.frame(ID = dat$ID)\nk <- 2 # first column to start\ni <- 1 # first variable name\nwhile(k < ncol(dat)){\n out[[paste0(\"c\", i)]] <- apply(dat[,k:(k+3)], 1, max, na.rm=TRUE)\n out[[paste0(\"c\", i)]] <- ifelse(is.finite(out[[paste0(\"c\", i)]]), out[[paste0(\"c\", i)]], NA)\n k <- k+4\n i <- i+1\n}\n#> Warning in FUN(newX[, i], ...): no non-missing arguments to max; returning -Inf\nout\n#> ID c1 c2\n#> 1 row1 1 1\n#> 2 row2 0 NA\n"
},
{
"answer_id": 74520595,
"author": "langtang",
"author_id": 4447540,
"author_profile": "https://Stackoverflow.com/users/4447540",
"pm_score": 2,
"selected": false,
"text": "\nf <- function(x) fifelse(all(is.na(x)), NA_real_,1*(sum(x,na.rm = T)>0))\n\ndcast(\n melt(setDT(df),\"ID\",variable.name = \"v\")[\n ,f(value), .(ID,r=paste0(\"c\",rep(1:(uniqueN(v)/4), each=uniqueN(v))))],\n ID~r, value.var = \"V1\",\n)\n ID c1 c2\n1: row1 1 1\n2: row2 0 NA\n"
},
{
"answer_id": 74520773,
"author": "zx8754",
"author_id": 680068,
"author_profile": "https://Stackoverflow.com/users/680068",
"pm_score": 1,
"selected": false,
"text": "x <- df1\nx[ is.na(x) ] <- -1\nres <- cbind(df1[ \"ID\" ],\n lapply(split.default(x[, -1], rep(1:2, each = 4)), \n function(i) do.call(pmax, i)))\n\nres[ res == -1 ] <- NA\nres\n# ID 1 2\n# 1 row1 1 1\n# 2 row2 0 NA\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9623670/"
] |
74,520,048
|
<p>I'm using c# and I'm using CQRS
So let's image this scenario</p>
<pre><code>public async Task<Response<SaleProducts>> Handle(CreateSaleProductCommand request, CancellationToken cancellationToken)
{
var newEntity = MyCustomerMapper.Mapper.Map<SaleProducts>(request);
if (newEntity is null)
throw new ApplicationException("There is a problem in mapper");
var itemToReturn = await _repositoryCommand.AddProductToSaleAsync(newEntity);
if(itemToReturn != null)
{
itemToReturn.Product = await _productQueryRepository.GetByIdAsync(itemToReturn.ProductId);
return new Response<SaleProducts>(itemToReturn);
}
else
throw new ApplicationException("There is a problem when saving the product");
}
</code></pre>
<p>so this function return <code>Response<SaleProducts></code> after saving.</p>
<p>Now I like to make some verification in my <code>_repositoryCommand.AddProductToSaleAsync</code>.</p>
<p>So if verification is ok I return SaleProducts if not I return other value(like bool or string) for exepmle.</p>
<p>So is there any way to have something similar to this</p>
<pre><code> public async Task<Response<SaleProducts | bool>> Handle(CreateSaleProductCommand request, CancellationToken cancellationToken)
</code></pre>
<p>return type <code>SaleProducts | bool | string</code></p>
|
[
{
"answer_id": 74520200,
"author": "Sergey Kudriavtsev",
"author_id": 625594,
"author_profile": "https://Stackoverflow.com/users/625594",
"pm_score": 1,
"selected": false,
"text": "public async Task<Response<(SaleProducts? Products, string? Status)>> Handle(CreateSaleProductCommand request, CancellationToken cancellationToken)\n Handle public async Task<Response<SaleProducts>> Handle(CreateSaleProductCommand request, CancellationToken cancellationToken)\n {\n var newEntity = MyCustomerMapper.Mapper.Map<SaleProducts>(request);\n if (newEntity is null)\n throw new ApplicationException(\"There is a problem in mapper\");\n\n var (itemToReturn, textStatus) = await _repositoryCommand.AddProductToSaleAsync(newEntity);\n if(itemToReturn != null)\n {\n itemToReturn.Product = await _productQueryRepository.GetByIdAsync(itemToReturn.ProductId); \n return new Response<SaleProducts>(itemToReturn);\n }\n else\n {\n // Do whatever processing you want to do with textStatus\n ...\n throw new ApplicationException(\"There is a problem when saving the product\");\n }\n\n\n }\n"
},
{
"answer_id": 74520203,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 2,
"selected": false,
"text": "Either public async Task<Response<Either<string, SaleProducts>>> Handle()\n OneOf OneOf public OneOf<User, InvalidName, NameTaken> CreateUser(string username)\n{\n if (!IsValid(username)) return new InvalidName();\n var user = _repo.FindByUsername(username);\n if(user != null) return new NameTaken();\n var user = new User(username);\n _repo.Save(user);\n return user;\n}\n FluentResults"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287964/"
] |
74,520,077
|
<p>I have a xml file and I have to store the values in the list to use it later.
The xml file contain mostly int<code>s and string</code>s and it looks like this:</p>
<pre><code><AllThings>
<Anythings>
<Anything Step="1" Name="1">
<Somethings>
<Something Id="10">
<Things>
<Thing Id="11">abc</Thing>
<Thing Id="12">123</Thing>
</Things>
</Something>
<Something Id="20">
<Things>
<Thing Id="21">cde</Thing>
<Thing Id="22">345</Thing>
</Things>
</Something>
<Something Id="30">
<Things>
<Thing Id="31">efg</Thing>
<Thing Id="32">567</Thing>
</Things>
</Something>
<Something Id="40">
<Things>
<Thing Id="41">ghi</Thing>
<Thing Id="42">789</Thing>
</Things>
</Something>
</Somethings>
</Anything>
<Anything Step="2" Name="2">
<Somethings>
<Something Id="10">
<Things>
<Thing Id="11">aaa</Thing>
<Thing Id="12">111</Thing>
</Things>
</Something>
<Something Id="20">
<Things>
<Thing Id="21">ccc</Thing>
<Thing Id="22">333</Thing>
</Things>
</Something>
<Something Id="30">
<Things>
<Thing Id="31">eee</Thing>
<Thing Id="32">555</Thing>
</Things>
</Something>
<Something Id="40">
<Things>
<Thing Id="41">ggg</Thing>
<Thing Id="42">777</Thing>
</Things>
</Something>
</Somethings>
</Anything>
</Anythings>
</AllThings>
</code></pre>
<p>What is the best way to get the values from this kind of xml and store it in the list(s)?</p>
<p>I've tried with <code>using System.Xml;</code> to create a reader and make <code>reader.ReadToFollowing("Something")</code> in combination with <code>reader.GetAttribute("Id")</code>, but it hasn`t gone deep enough.
In most tutorials the xml is like:</p>
<pre><code><Animal type="cat">
<Name>Bob</Name>
<Age>8</Age>
</Animal>
</code></pre>
<p>and there it works</p>
|
[
{
"answer_id": 74520200,
"author": "Sergey Kudriavtsev",
"author_id": 625594,
"author_profile": "https://Stackoverflow.com/users/625594",
"pm_score": 1,
"selected": false,
"text": "public async Task<Response<(SaleProducts? Products, string? Status)>> Handle(CreateSaleProductCommand request, CancellationToken cancellationToken)\n Handle public async Task<Response<SaleProducts>> Handle(CreateSaleProductCommand request, CancellationToken cancellationToken)\n {\n var newEntity = MyCustomerMapper.Mapper.Map<SaleProducts>(request);\n if (newEntity is null)\n throw new ApplicationException(\"There is a problem in mapper\");\n\n var (itemToReturn, textStatus) = await _repositoryCommand.AddProductToSaleAsync(newEntity);\n if(itemToReturn != null)\n {\n itemToReturn.Product = await _productQueryRepository.GetByIdAsync(itemToReturn.ProductId); \n return new Response<SaleProducts>(itemToReturn);\n }\n else\n {\n // Do whatever processing you want to do with textStatus\n ...\n throw new ApplicationException(\"There is a problem when saving the product\");\n }\n\n\n }\n"
},
{
"answer_id": 74520203,
"author": "Guru Stron",
"author_id": 2501279,
"author_profile": "https://Stackoverflow.com/users/2501279",
"pm_score": 2,
"selected": false,
"text": "Either public async Task<Response<Either<string, SaleProducts>>> Handle()\n OneOf OneOf public OneOf<User, InvalidName, NameTaken> CreateUser(string username)\n{\n if (!IsValid(username)) return new InvalidName();\n var user = _repo.FindByUsername(username);\n if(user != null) return new NameTaken();\n var user = new User(username);\n _repo.Save(user);\n return user;\n}\n FluentResults"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18241129/"
] |
74,520,084
|
<p>I have the following function that calculates the eucledian distance between all combinations of the vectors in Matrix <code>A</code> and Matrix <code>B</code></p>
<pre><code>def distance_matrix(A,B):
n=A.shape[1]
m=B.shape[1]
C=np.zeros((n,m))
for ai, a in enumerate(A.T):
for bi, b in enumerate(B.T):
C[ai][bi]=np.linalg.norm(a-b)
return C
</code></pre>
<p>This works fine and creates an <code>n*m</code>-Matrix from a <code>d*n</code>-Matrix and a <code>d*m</code>-Matrix containing the eucledian distance between all combinations of the column vectors.</p>
<pre><code>>>> print(A)
[[-1 -1 1 1 2]
[ 1 -1 2 -1 1]]
>>> print(B)
[[-2 -1 1 2]
[-1 2 1 -1]]
>>> print(distance_matrix(A,B))
[[2.23606798 1. 2. 3.60555128]
[1. 3. 2.82842712 3. ]
[4.24264069 2. 1. 3.16227766]
[3. 3.60555128 2. 1. ]
[4.47213595 3.16227766 1. 2. ]]
</code></pre>
<p>I spent some time looking for a <code>numpy</code> or <code>scipy</code> function to achieve this in a more efficient way. Is there such a function or what would be the vecotrized way to do this?</p>
|
[
{
"answer_id": 74520165,
"author": "Sembei Norimaki",
"author_id": 20396240,
"author_profile": "https://Stackoverflow.com/users/20396240",
"pm_score": 2,
"selected": true,
"text": "A = np.array([[-1, -1, 1, 1, 2], [ 1, -1, 2, -1, 1]])\nB = np.array([[-2, -1, 1, 2], [-1, 2, 1, -1]])\n\nC = np.linalg.norm(A.T[:, None, :] - B.T[None, :, :], axis=-1)\nprint(C)\n\narray([[2.23606798, 1. , 2. , 3.60555128],\n [1. , 3. , 2.82842712, 3. ],\n [4.24264069, 2. , 1. , 3.16227766],\n [3. , 3.60555128, 2. , 1. ],\n [4.47213595, 3.16227766, 1. , 2. ]])\n"
},
{
"answer_id": 74520272,
"author": "obchardon",
"author_id": 4363864,
"author_profile": "https://Stackoverflow.com/users/4363864",
"pm_score": 2,
"selected": false,
"text": "np.linalg.norm(A[:,:,None]-B[:,None,:],axis=0)\n ((A[:,:,None]-B[:,None,:])**2).sum(axis=0)**0.5\n A[:,:,None] -> 2,5,1\n ↑ ↓ \nB[:,None,:] -> 2,1,4\n\nA[:,:,None] - B[:,None,:] -> 2,5,4\n sum"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5439470/"
] |
74,520,088
|
<p>I am making a website for a school project, I am a noob!</p>
<p>I am one step away from completing the project, the last piece is to get my Dynamically created HTML products to display in a row of 3.</p>
<p>Here is my HTML:</p>
<pre><code><div id="product-featured-box">
</div>
</code></pre>
<p>Here is the CSS I have:</p>
<pre><code>.product-featured-box {
display: flex;
justify-content: space-between;
table-layout: fixed;
}
.product-box {
display: flex;
}
</code></pre>
<p>In the dev view on Google Chrome, the HTML is generated properly, all product-boxes are inside the featured-product-box, but I have no idea how to get the CSS to get it to do what i want!</p>
<p>Any ideas would help!</p>
<p>I a using MAC OS</p>
<p>I tried playing around with the CSS</p>
|
[
{
"answer_id": 74520234,
"author": "Kailash",
"author_id": 3065049,
"author_profile": "https://Stackoverflow.com/users/3065049",
"pm_score": 0,
"selected": false,
"text": "<div class=\"product-featured-box\">\n<div class=\"product-box\">1</div>\n<div class=\"product-box\">2</div>\n<div class=\"product-box\">3</div>\n</div>\n\n<style type=\"text/css\">\n .product-featured-box {\n display: flex;\n justify-content: space-between;\n\n}\n \n.product-box {\nwidth: 33.3%;\npadding: 15px;\ntext-align: center;\n}\n</style>\n"
},
{
"answer_id": 74520387,
"author": "papillon",
"author_id": 8993709,
"author_profile": "https://Stackoverflow.com/users/8993709",
"pm_score": 1,
"selected": false,
"text": "#product-featured-box {\n display: grid;\n grid-template-columns: repeat(3,1fr);\n} <div id=\"product-featured-box\">\n <div class=\"product-box\">1</div>\n <div class=\"product-box\">2</div>\n <div class=\"product-box\">3</div>\n <div class=\"product-box\">4</div>\n <div class=\"product-box\">5</div>\n <div class=\"product-box\">6</div>\n <div class=\"product-box\">7</div>\n <div class=\"product-box\">8</div>\n <div class=\"product-box\">9</div>\n <div class=\"product-box\">10</div>\n</div> fr 1fr"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20549509/"
] |
74,520,097
|
<p>I have a parent table that is meant to be reusable by just inputting a datasource. Components that want to use this table should have a service injection that provides <code>Observable</code>s for the parent table to consume. as such, I expect any components to need to implement one or more of the HTTP Verbs, Get,Put,Post,Delete. I want these actions to be reflected in the MatTable once they happen and a result is returned. The initial load of the table works fine, but whenever I do a PUT, I don't see the change reflected in the table. Can someone help me point to what I'm missing?`</p>
<p>parent-table (omissions, for clarity):</p>
<pre><code>export class TableComponent {
public tableDataSource = new MatTableDataSource();
public displayedColumns: string[] = [];
@ViewChild(MatPaginator, { static: false }) matPaginator?: MatPaginator;
@ViewChild(MatSort, { static: true }) matSort?: MatSort;
@Input() set tableData(data: MatTableDataSource<any>) {
this.setTableDataSource(data);
constructor() {
console.log("Hello")
}
setTableDataSource(data: MatTableDataSource<any>) {
this.tableDataSource = data;
if (this.matPaginator) {
this.tableDataSource.paginator = this.matPaginator;
}
if (this.matSort) {
this.tableDataSource.sort = this.matSort;
}
}
}
</code></pre>
<p>Table is being used in another component like this:</p>
<pre><code> <app-data-table
[isFilterable]="true"
[isSortable]="true"
[isPageable]="true"
[tableColumns]="customerColumns"
[tableData]="customers"
[rowActionIcon]="'more_vert'"
[menuActions]="this.menuActions"
(rowAction)="onTableAction($event)"
(sort)="sortData($event)"
>
</app-data-table>
</code></pre>
<p>The component looks like this:</p>
<pre><code>export class CustomersComponent {
customers;
selectedCustomer: Customer | null;
menuActions: MenuItemDefinition[];
customerColumns: { name: string; dataKey: string; isSortable: boolean }[];
constructor(private cust_api: CustomerApiService) {
this.customers = new MatTableDataSource<Customer>([]);
ngOnInit(): void {
/** Issue GET call and bind the returning observable to the MatTableDataSource */
this.cust_api.getCustomers().subscribe((customers) => {
this.customers.data = customers;
});
}
updateCustomer(customer: Customer): void {
this.cust_api.updateCustomer(customer as Customer)
.subscribe((updated_customer: Customer) => (customer = updated_customer));
}
</code></pre>
<p>Whenever updateCustomer is called, the api call returns 200 and the content of the changed object in the backend, however the table is not updated. Do I need to change my updateCustomer method somehow, or how can I reflect that the datasource has additions without manually doing that? I thought the idea was to let the MatTableDatasource handle that?</p>
<p>EDIT:</p>
<p>I can get the table to update by directly interacting with the <code>this.customers.data</code> attribute:</p>
<pre><code> updateCustomer(customer: Customer): void {
this.cust_api
.updateCustomer(customer as Customer)
.subscribe((updated_customer: Customer) => {
const to_keep = this.customers.data.filter(
(customer) => customer.id !== updated_customer.id
);
this.customers.data = [updated_customer, ...to_keep];
});
}
</code></pre>
<p>This will refresh the table and put the updated customer at the top - but it still feels hacky. I can't use [tableData]="customers | async" somehow?</p>
|
[
{
"answer_id": 74529647,
"author": "Mohamed.Karkotly",
"author_id": 10242047,
"author_profile": "https://Stackoverflow.com/users/10242047",
"pm_score": -1,
"selected": false,
"text": "MatTable ngOnChanges() ngOnChanges() elements any[] ngOnChanges(changes: SimpleChanges): void {\n this.dataSource = new MatTableDataSource(this.elements);\n}\n"
},
{
"answer_id": 74536133,
"author": "Jimmy",
"author_id": 4960765,
"author_profile": "https://Stackoverflow.com/users/4960765",
"pm_score": 1,
"selected": false,
"text": "async .subscribe"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1230911/"
] |
74,520,102
|
<p>When we build the react app using <code>react-scripts build</code>, the relative paths for the created js/css are like: <strong>/static/js/main.b8ba68fa.js</strong> and so on.</p>
<p>Generated <strong>index.html</strong>:</p>
<pre><code><head>
...
<link rel="icon" href="/favicon.ico" />
<link rel="manifest" href="/manifest.json" />
<link rel="stylesheet" href="/fonts/fonts.css" />
<script defer="defer" src="/static/js/main.b8ba68fa.js"></script>
...
</head>
</code></pre>
<p>The <strong>index.html</strong> I need:</p>
<pre><code><head>
...
<link rel="icon" href="{{DOMAIN}}/favicon.ico" />
<link rel="manifest" href="{{DOMAIN}}/manifest.json" />
<link rel="stylesheet" href="{{DOMAIN}}/fonts/fonts.css" />
<script defer="defer" src="{{DOMAIN}}/static/js/main.b8ba68fa.js"></script>
...
</head>
</code></pre>
<p>What I need is that all the paths of the generated index.html have this string <strong>{{DOMAIN}}</strong> prepended to them.</p>
|
[
{
"answer_id": 74529647,
"author": "Mohamed.Karkotly",
"author_id": 10242047,
"author_profile": "https://Stackoverflow.com/users/10242047",
"pm_score": -1,
"selected": false,
"text": "MatTable ngOnChanges() ngOnChanges() elements any[] ngOnChanges(changes: SimpleChanges): void {\n this.dataSource = new MatTableDataSource(this.elements);\n}\n"
},
{
"answer_id": 74536133,
"author": "Jimmy",
"author_id": 4960765,
"author_profile": "https://Stackoverflow.com/users/4960765",
"pm_score": 1,
"selected": false,
"text": "async .subscribe"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13830075/"
] |
74,520,120
|
<p>I have a program that will create orders for a bunch of orders. However API has limitation that if I wanna do that I got to do it 10 at a time</p>
<pre><code>If orderList.Count > 10 Then
Dim FirstTwenty = From n In orderList Take (10)
Dim theRest = From n In orderList Skip (10)
Dim result1 = Await internalActualcreateNormalLimitOrderMultiple(FirstTwenty.ToArray)
Dim result2 = Await internalActualcreateNormalLimitOrderMultiple(theRest.ToArray)
Return result1 + result2 'no longer json but we don't really use the resulting json unless for debugging
End If
</code></pre>
<p>Basically I want to split {1,2,3,4,5,6,7,8,9,10.11.12,...} into {1,2,3}{4,5,6},{7,8,9},...</p>
<p>And I wonder if I can use linq instead of for each</p>
<p>So I use this recursive function. Get first 10 or twenty and then recursively call the function and so on.</p>
<p>And I look at it and while it's simple, it doesn't seem right. Obviously number of orders won't be big. At most 15. But what about if on day I have 100? I can get like stackoverflow for recursive things.</p>
<p>If only there is a function that can split arrays into array using linq, where, take, and skip that'll be great.</p>
<p>Of course I can do for each but perhaps there is a more elegant way?</p>
<p>Then I wrote another code</p>
<pre><code>Public Shared Function splitArrayIntoSmallerArrays(Of someObject)(arrayOfSomeObject As someObject(), chunkSize As Integer) As List(Of someObject())
Dim output = New List(Of someObject())
Dim newestArray = New List(Of someObject)
For i = 0 To arrayOfSomeObject.Count - 1
newestArray.Add(arrayOfSomeObject(i))
If newestArray.Count = chunkSize Then
output.Add(newestArray.ToArray)
newestArray = New List(Of someObject)
End If
Next
output.Add(newestArray.ToArray)
Return output
End Function
</code></pre>
<p>That'll do it in O(n)</p>
<p>But I think it can be done more simply by using linq, seek, and take but I don't know how. Or may be group by.</p>
<p>Any idea?</p>
|
[
{
"answer_id": 74529647,
"author": "Mohamed.Karkotly",
"author_id": 10242047,
"author_profile": "https://Stackoverflow.com/users/10242047",
"pm_score": -1,
"selected": false,
"text": "MatTable ngOnChanges() ngOnChanges() elements any[] ngOnChanges(changes: SimpleChanges): void {\n this.dataSource = new MatTableDataSource(this.elements);\n}\n"
},
{
"answer_id": 74536133,
"author": "Jimmy",
"author_id": 4960765,
"author_profile": "https://Stackoverflow.com/users/4960765",
"pm_score": 1,
"selected": false,
"text": "async .subscribe"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/700663/"
] |
74,520,133
|
<p>I am trying to work with Coroutines and multithreading together in C++.</p>
<p>In many coroutine examples, they create a new thread in the <code>await_suspend</code> of the <code>co_await</code> operator for the promise type. I want to submit to a thread pool in this function.</p>
<p>Here I define a <code>co_await</code> for <code>future<int></code>.</p>
<pre><code>void await_suspend(std::coroutine_handle<> handle) {
this->wait();
handle.resume();
}
</code></pre>
<p>I want to change this code to submit a lambda/function pointer to a threadpool. Potentially I can use Alexander Krizhanovsky's ringbuffer to communicate with the threadpool to create a threadpool by myself or use boost's threadpool.</p>
<p>My problem is NOT the thread pool. My problem is that I don't know how to get reference to the threadpool in this <code>co_await</code> operator.</p>
<p>How do I pass data from the outside environment where the operator is to this <code>await_suspend</code> function? Here is an example of what I want to do:</p>
<pre><code>void await_suspend(std::coroutine_handle<> handle) {
// how do I get "pool"? from within this function
auto res = pool.enqueue([](int x) {
this->wait();
handle.resume();
});
}
</code></pre>
<p>I am not an expert at C++ so I'm not sure how I would get access to <code>pool</code> in this operator?</p>
<p>Here's the full code inspired by <a href="https://gist.github.com/yizhang82/28842f7dbae34b59fcd7b4d74b4a19d4" rel="nofollow noreferrer">this GitHub gist A simple C++ coroutine example</a>.</p>
<pre><code>#include <future>
#include <iostream>
#include <coroutine>
#include <type_traits>
#include <list>
#include <thread>
using namespace std;
template <>
struct std::coroutine_traits<std::future<int>> {
struct promise_type : std::promise<int> {
future<int> get_return_object() { return this->get_future(); }
std::suspend_never initial_suspend() noexcept { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void return_value(int value) { this->set_value(value); }
void unhandled_exception() {
this->set_exception(std::current_exception());
}
};
};
template <>
struct std::coroutine_traits<std::future<int>, int> {
struct promise_type : std::promise<int> {
future<int> get_return_object() { return this->get_future(); }
std::suspend_never initial_suspend() noexcept { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void return_value(int value) { this->set_value(value); }
void unhandled_exception() {
this->set_exception(std::current_exception());
}
};
};
auto operator co_await(std::future<int> future) {
struct awaiter : std::future<int> {
bool await_ready() { return false; } // suspend always
void await_suspend(std::coroutine_handle<> handle) {
this->wait();
handle.resume();
}
int await_resume() { return this->get(); }
};
return awaiter{std::move(future)};
}
future<int> async_add(int a, int b)
{
auto fut = std::async([=]() {
int c = a + b;
return c;
});
return fut;
}
future<int> async_fib(int n)
{
if (n <= 2)
co_return 1;
int a = 1;
int b = 1;
// iterate computing fib(n)
for (int i = 0; i < n - 2; ++i)
{
int c = co_await async_add(a, b);
a = b;
b = c;
}
co_return b;
}
future<int> test_async_fib()
{
for (int i = 1; i < 10; ++i)
{
int ret = co_await async_fib(i);
cout << "async_fib(" << i << ") returns " << ret << endl;
}
}
int runfib(int arg) {
auto fut = test_async_fib();
fut.wait();
return 0;
}
int run_thread() {
printf("Running thread");
return 0;
}
int main()
{
std::list<shared_ptr<std::thread>> threads = { };
for (int i = 0 ; i < 10; i++) {
printf("Creating thread\n");
std::shared_ptr<std::thread> thread = std::make_shared<std::thread>(runfib, 5);
threads.push_back(thread);
}
std::list<shared_ptr<std::thread>>::iterator it;
for (it = threads.begin(); it != threads.end(); it++) {
(*it).get()->join();
printf("Joining thread");
}
fflush(stdout);
return 0;
}
</code></pre>
|
[
{
"answer_id": 74529647,
"author": "Mohamed.Karkotly",
"author_id": 10242047,
"author_profile": "https://Stackoverflow.com/users/10242047",
"pm_score": -1,
"selected": false,
"text": "MatTable ngOnChanges() ngOnChanges() elements any[] ngOnChanges(changes: SimpleChanges): void {\n this.dataSource = new MatTableDataSource(this.elements);\n}\n"
},
{
"answer_id": 74536133,
"author": "Jimmy",
"author_id": 4960765,
"author_profile": "https://Stackoverflow.com/users/4960765",
"pm_score": 1,
"selected": false,
"text": "async .subscribe"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10662977/"
] |
74,520,139
|
<p>I have a golang application which has API key authorization via the <code>JWT token</code></p>
<p>I am using Kubernetes. So, this golang app is in a pod.</p>
<p>Now, I want to create another application for cronjobs to hit golang endpoint once a week.</p>
<p><strong>What I need:</strong></p>
<p>How to <em><strong>do / skip</strong></em> the authorization?</p>
<p><strong>skip</strong>: Ingress is not required here as I can simply call it internally. Can that help this case?</p>
<p><strong>What I Tried:</strong></p>
<p>I tried keeping the cronjobs and api in the same application so I can simply call the <em>service instead of the endpoint</em>, But that also has a drawback.
I am not able to create replicas as they will also replicate the cronjobs and the same endpoint will be hit <code>1*no of replicas</code> times</p>
<p>I want to call "abc.com" endpoint once a week. It requires a token and I cannot simply pass a token.
I hope there is some way around this.</p>
|
[
{
"answer_id": 74529647,
"author": "Mohamed.Karkotly",
"author_id": 10242047,
"author_profile": "https://Stackoverflow.com/users/10242047",
"pm_score": -1,
"selected": false,
"text": "MatTable ngOnChanges() ngOnChanges() elements any[] ngOnChanges(changes: SimpleChanges): void {\n this.dataSource = new MatTableDataSource(this.elements);\n}\n"
},
{
"answer_id": 74536133,
"author": "Jimmy",
"author_id": 4960765,
"author_profile": "https://Stackoverflow.com/users/4960765",
"pm_score": 1,
"selected": false,
"text": "async .subscribe"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20563540/"
] |
74,520,157
|
<p>I want to trigger a Test pipeline from a stage of Main pipeline, both the pipelines are present in different projects within the same organization. I am able to trigger the pipeline using the resource option but the problem is it triggers the Test pipeline when Main pipeline finishes successfully but I want to trigger the Test pipeline in between run of Main pipeline using an stage. Is it possible to achieve this using any feature of Azure Devops?</p>
<pre><code>
</code></pre>
<p>For now I am adding this resource in Test pipeline yaml to trigger after Main pipeline.</p>
<pre><code>resources:
pipelines:
- pipeline: Test-Repo
source: Test # Test pipeline from different project
project: private
trigger: true # enable the trigger
</code></pre>
|
[
{
"answer_id": 74530980,
"author": "Kim Xu-MSFT",
"author_id": 19287209,
"author_profile": "https://Stackoverflow.com/users/19287209",
"pm_score": 0,
"selected": false,
"text": "trigger:\n- none\n\npool:\n vmImage: ubuntu-latest\n\nstages:\n\n - stage: A\n displayName: A stage\n jobs:\n - job: A\n displayName: A\n steps:\n - task: TriggerBuild@4\n inputs:\n definitionIsInCurrentTeamProject: false\n tfsServer: '{Org URL}'\n teamProject: '{Project B Name}'\n buildDefinition: '213'\n queueBuildForUserThatTriggeredBuild: false\n ignoreSslCertificateErrors: false\n useSameSourceVersion: false\n useCustomSourceVersion: false\n useSameBranch: false\n waitForQueuedBuildsToFinish: false\n storeInEnvironmentVariable: false\n authenticationMethod: 'Personal Access Token'\n password: '{PAT}'\n enableBuildInQueueCondition: false\n dependentOnSuccessfulBuildCondition: false\n dependentOnFailedBuildCondition: false\n checkbuildsoncurrentbranch: false\n failTaskIfConditionsAreNotFulfilled: false\n \n - stage: B\n displayName: B stage\n dependsOn: A\n jobs:\n - job: \n steps:\n - bash: echo \"B\"\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20563639/"
] |
74,520,174
|
<p>I have a text edit controller and I would like to check mutliple characters in the same contains ()</p>
<pre><code>_changeUsernameController.text.contains("a" "b") // what I want
_changeUsernameController.text.contains("a") ||
_changeUsernameController.text.contains("b") // what I have to do
</code></pre>
<p>I don't want to write 50 lines so how can I write all in one line like the 'what I want' line
Thanks</p>
|
[
{
"answer_id": 74520301,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 1,
"selected": false,
"text": "RegExp var reg = RegExp(r'(?:a)|(?:b)');\n_changeUsernameController.text.contains(reg);\n var test1 = 'acc';\nvar test2 = 'cc';\nvar test3 = 'ccb';\nprint(test1.contains(reg)); //true\nprint(test2.contains(reg)); //false\nprint(test3.contains(reg)); //true\n"
},
{
"answer_id": 74520418,
"author": "Raiyan",
"author_id": 14598711,
"author_profile": "https://Stackoverflow.com/users/14598711",
"pm_score": 1,
"selected": false,
"text": "bool containsAny(String text, List<String> substrings) {\n // returns true if any substring of the [substrings] list is contained in the [text]\n for (var substring in substrings) {\n if (text.contains(substring)) return true;\n }\n return false;\n}\n final text = 'Flutter';\nfinal result = containsAny(text, ['c', 'd', 'e']); // true\nfinal result2 = containsAny(text, ['a', 'b', 'c']); // false\n"
},
{
"answer_id": 74520429,
"author": "nvoigt",
"author_id": 2060725,
"author_profile": "https://Stackoverflow.com/users/2060725",
"pm_score": 3,
"selected": true,
"text": "final subStrings = <String>[\"a\", \"b\" /* ... */ ];\nvar result = subStrings.any(_changeUsernameController.text.contains);\n var result = [\"a\", \"b\"].any(_changeUsernameController.text.contains);\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19192614/"
] |
74,520,190
|
<p>I'm submitting base64 image to server side via FormData(). Getting something like</p>
<pre><code>{"------WebKitFormBoundaryjJtrF2zdTOFuHmYM\\r\\nContent-Disposition: form-data; name":"\\"image\\"\\r\\n\\r\\ndata:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASoAAABiCAYAAADnRp6aAAAAAXNSR0IArs4c6QAAIABJREFUeF7tnQd0FFUXx/9vdtNDSC8kJCEJISEJgd7pz4GGfiqoqm5C1aNSPaqq9hYVVFW1VOXnqaCqoQ1VUKmgqmrXUUFVVUupoKq9pczuoIJKBVVVO5UKqqpaSgVV7S1ldof/A9VZZwflQmSiAAAAAElFTkSuQmCC\\r\\n------WebKitFormBoundaryjJtrF2zdTOFuHmYM--\\r\\n"}
</code></pre>
<p>How to parse this to get the image data seperatly.I'm using expressjs as backend.
I'm not submitting a normal image through html form tag. The code :</p>
<pre><code> var src = document.getElementById('hdrimg').src;
var formData = new FormData()
formData.append("image",src);
let response = await fetch('http://localhost:3000/hdrimg', {
method: 'POST',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: formData
});
</code></pre>
<p>Manually submitting source of image with formdata constructor. I tried with multer , express-file-upload as we do for normal files. Is there any other way to retrive the data like this in backend.</p>
<pre><code> {"------WebKitFormBoundaryjJtrF2zdTOFuHmYM\\r\\nContent-Disposition: form-data; name":"\\"image\\"\\r\\n\\r\\ndata:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASoAAABiCAYAAADnRp6aAAAAAXNSR0IArs4c6QAAIABJREFUeF7tnQd0FFUXx/9vdtNDSC8kJCEJISEJgd7pz4GGfiqoqm5C1aNSPaqq9hYVVFW1VOXnqaCqoQ1VUKmgqmrXUUFVVUupoKq9pczuoIJKBVVVO5UKqqpaSgVV7S1ldof/A9VZZwflQmSiAAAAAElFTkSuQmCC\\r\\n------WebKitFormBoundaryjJtrF2zdTOFuHmYM--\\r\\n"}
</code></pre>
|
[
{
"answer_id": 74520301,
"author": "eamirho3ein",
"author_id": 10306997,
"author_profile": "https://Stackoverflow.com/users/10306997",
"pm_score": 1,
"selected": false,
"text": "RegExp var reg = RegExp(r'(?:a)|(?:b)');\n_changeUsernameController.text.contains(reg);\n var test1 = 'acc';\nvar test2 = 'cc';\nvar test3 = 'ccb';\nprint(test1.contains(reg)); //true\nprint(test2.contains(reg)); //false\nprint(test3.contains(reg)); //true\n"
},
{
"answer_id": 74520418,
"author": "Raiyan",
"author_id": 14598711,
"author_profile": "https://Stackoverflow.com/users/14598711",
"pm_score": 1,
"selected": false,
"text": "bool containsAny(String text, List<String> substrings) {\n // returns true if any substring of the [substrings] list is contained in the [text]\n for (var substring in substrings) {\n if (text.contains(substring)) return true;\n }\n return false;\n}\n final text = 'Flutter';\nfinal result = containsAny(text, ['c', 'd', 'e']); // true\nfinal result2 = containsAny(text, ['a', 'b', 'c']); // false\n"
},
{
"answer_id": 74520429,
"author": "nvoigt",
"author_id": 2060725,
"author_profile": "https://Stackoverflow.com/users/2060725",
"pm_score": 3,
"selected": true,
"text": "final subStrings = <String>[\"a\", \"b\" /* ... */ ];\nvar result = subStrings.any(_changeUsernameController.text.contains);\n var result = [\"a\", \"b\"].any(_changeUsernameController.text.contains);\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18290071/"
] |
74,520,196
|
<p>In my first Next.js project, I have an article component which is rendered at server side. I'd like to fetch articls' tags from client side because otherwise I get to many DOM elements. So here is what I came up with:</p>
<pre><code>const ArticlesPage = () => {
const [tags, setTags] = useState([])
const { isLoading, isError, data, error } = useQuery('tags', getTags, {
onSuccess: () => setTags(data)
}
//...
})
console.log('tags are:', tags)
return (
<>
...
{!isLoading && !isError &&
<TagsComponent tags={tags} />
}
{isLoading &&
<div> Loading tags...</div>
}
{isError &&
<div> Error fetching tags</div>
}
</>
</code></pre>
<p>The problem is that tags are rendered on the articles page whimsically, that is when I refresh page they do not show up but when I refocus on page, the tags are displayed.
I don't see any <code>Loading</code> or <code>Error</code> being rendered either. So I'm confused what is going on here?</p>
<p>How can I fix this?</p>
|
[
{
"answer_id": 74520395,
"author": "Taghi Khavari",
"author_id": 11432102,
"author_profile": "https://Stackoverflow.com/users/11432102",
"pm_score": 1,
"selected": false,
"text": "data const ArticlesPage = () => {\n const { isLoading, isError, data: tags, error } = useQuery(\"tags\", getTags);\n console.log(\"tags are:\", tags);\n return (\n <>\n ...\n {!isLoading && !isError && <TagsComponent tags={tags} />}\n {isLoading && <div> Loading tags...</div>}\n {isError && <div> Error fetching tags</div>}\n </>\n );\n};\n"
},
{
"answer_id": 74524848,
"author": "Chad S.",
"author_id": 5274205,
"author_profile": "https://Stackoverflow.com/users/5274205",
"pm_score": 3,
"selected": true,
"text": "getTags {queryKey: [,filter]} filter setFilter const ArticlesPage = () => {\n const [filter, setFilter] = useState({});\n\n const { isLoading, isError, data: tags, error } = useQuery(\n [\"tags\", filter], \n getTags,\n );\n\n console.log(\"tags are:\", tags);\n\n if(isError) return <div>Error fetching tags</div>;\n\n if(isLoading) return <div>Loading tags...</div>;\n\n return <TagsComponent \n tags={tags} \n filter={filter} \n setFilter={setFilter} />;\n};\n filter filterTags(filter, tags) => filteredTags const ArticlesPage = () => {\n const [filter, setFilter] = useState({});\n\n const { isLoading, isError, data: tags, error } = useQuery(\"tags\", getTags);\n\n const filteredTags = useMemo(() => filterTags(filter, tags), [tags, filter]);\n\n if(isError) return <div>Error fetching tags</div>;\n\n if(isLoading) return <div>Loading tags...</div>;\n\n return <TagsComponent \n tags={filteredTags} \n filter={filter} \n setFilter={setFilter} />;\n};\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15363841/"
] |
74,520,197
|
<p>I have a dataframe which contains 3500 items with their values and categorised in 4 different types.</p>
<p>Then I have to distribute the items among 101 people who live in 28 different areas.</p>
<p>df1:</p>
<pre><code>
# A tibble: 3,500 × 4
item area type value
<chr> <chr> <chr> <dbl>
1 Item1 Area2 C 481.
2 Item2 Area26 C 409.
3 Item3 Area17 B 1068
4 Item4 Area8 B 755.
5 Item5 Area14 C 648.
6 Item6 Area17 C 452.
7 Item7 Area26 C 390.
8 Item8 Area11 B 586.
9 Item9 Area25 C 290.
10 Item10 Area6 C 560.
11 Item11 Area8 C 402.
12 Item12 Area8 C 331.
13 Item13 Area1 C 474.
14 Item14 Area19 C 540.
15 Item15 Area5 C 500
16 Item16 Area8 C 672
17 Item17 Area19 C 595
18 Item18 Area5 B 986.
19 Item19 Area19 C 528.
20 Item20 Area5 C 495.
21 Item21 Area10 B 1171
22 Item22 Area26 B 872.
23 Item23 Area7 C 556.
24 Item24 Area19 C 564.
25 Item25 Area26 C 513.
26 Item26 Area2 C 889.
27 Item27 Area24 C 467.
28 Item28 Area19 C 442.
29 Item29 Area24 B 841
30 Item30 Area19 C 435.
31 Item31 Area5 C 527.
32 Item32 Area17 C 300.
33 Item33 Area15 C 407.
34 Item34 Area5 C 659.
35 Item35 Area19 B 350
36 Item36 Area19 C 478.
37 Item37 Area10 C 923.
38 Item38 Area22 C 860.
39 Item39 Area18 C 605.
40 Item40 Area8 C 360.
41 Item41 Area5 C 487.
42 Item42 Area1 B 939
43 Item43 Area5 C 642.
44 Item44 Area5 C 576.
45 Item45 Area12 C 560.
46 Item46 Area8 C 402.
47 Item47 Area11 C 540.
48 Item48 Area5 C 494.
49 Item49 Area5 C 472.
50 Item50 Area22 C 455
...
3496 Item3496 Area5 C 2526.
3497 Item3497 Area17 B 322.
3498 Item3498 Area5 C 201.
3499 Item3499 Area17 B 363.
3500 Item3500 Area19 C 231.
</code></pre>
<p>And another dataframe which contains people who live in each area.</p>
<p>df2:</p>
<pre><code>
# A tibble: 101 × 2
area name
<chr> <chr>
1 Area1 William
2 Area1 Rhiannon
3 Area2 Reana
4 Area2 Milahd
5 Area2 Audrey
6 Area2 Geoffrey
7 Area2 Joan
8 Area2 Shaqeeqa
9 Area2 Maisoon
10 Area3 Kelvin
11 Area3 Ashley
12 Area4 Marco
13 Area4 Thuvan
14 Area5 Nathaniel
15 Area5 Demetrius
16 Area5 Jordan
17 Area5 Sadoon
18 Area5 Saje
19 Area5 Blakeslee
20 Area5 Briana
21 Area5 Aeneva
22 Area5 Pa
23 Area5 Benjamin
24 Area5 Abdul Waahid
25 Area5 Atanasio
26 Area5 Ubaida
27 Area5 Jalen
28 Area5 Jarred
29 Area6 Kelsie
30 Area6 Alexander
31 Area6 Steven
32 Area7 Marco
33 Area7 Kelsey
34 Area8 Lynn
35 Area8 Nasreen
36 Area9 Kelsie
37 Area9 Jalonie
38 Area10 Hailey
39 Area10 Alexander
40 Area10 Steven
41 Area11 Kelvin
42 Area11 Jocelin
43 Area11 Ashley
44 Area11 Briana
45 Area12 Sarah
46 Area12 Cu Chulainn
47 Area12 Firdaus
48 Area13 Alisha
49 Area13 Ethan
50 Area14 Ella
...
96 Area26 Muneeb
97 Area26 Luis
98 Area27 Marco
99 Area27 Kelsey
100 Area28 Kaxee
101 Area28 Mckylaa
</code></pre>
<p>Here there are df1 and df2 complete dataframes: <a href="https://drive.google.com/file/d/1O_Gyp39sT-sIWZjOd4z85tcpBdJIaFDX/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1O_Gyp39sT-sIWZjOd4z85tcpBdJIaFDX/view?usp=sharing</a></p>
<p>My goal is to distribute all items in their corresponding areas, among all people of the area, in the same number of the different types available for each person (or as close as possible).</p>
<p>My first attempt to distribute them in Area1 was this:</p>
<pre><code># get all the items of Area1 of TYPE A and ordered by value
y <- df1 %>% filter(area=="Area1" & type=="A") %>%
arrange(desc(value))
# List of people in Area1
v<-df2 %>% filter(area=="Area1")
v<-unique(v$name)
# Distribute them across all people 1 by 1
y$name<- rep(v, length.out = nrow(y))
# getting all items of Area1 of TYPE B and ordered by value
z <- df1 %>% filter(area=="Area1" & type=="B") %>%
arrange(desc(value))
# Distribute them accross all people 1 by 1
z$name<- rep(v, length.out = nrow(z))
# Combining them
Area1<- rbind(y,z)
</code></pre>
<p>I'm looking to automate this process with a loop or a function in order to do the same with all 28 areas and all items types in each area.</p>
<p>I don't find the way and it's blowing my mind. So, any help would be very appreciated! Thank you!</p>
|
[
{
"answer_id": 74520405,
"author": "DaveArmstrong",
"author_id": 8206434,
"author_profile": "https://Stackoverflow.com/users/8206434",
"pm_score": 1,
"selected": false,
"text": "library(purrr)\nlibrary(dplyr)\nitems <- paste0(\"Item\",1:3000)\ntypes <- c(\"A\", \"B\", \"C\", \"D\")\nvalues <- runif(3000, min=0.1, max=10)\nareas <- paste0(\"Area\",1:27)\n\ndf1 <- data.frame (items)\ndf1$type <- types\ndf1$area <- rep(areas, length.out = nrow(df1))\ndf1$value <- values\n\nnames <- randomNames::randomNames(127, which.names = \"first\")\nareas <- paste0(\"Area\",1:27)\n\ndf2 <- data.frame (names)\ndf2$area <- rep(areas, length.out = nrow(df2))\n\n\nf <- function(area, type){\ny <- df1 %>% filter(area==area & type==type) %>%\n arrange(desc(value))\n\n# List of people in Area1\nv<-df2 %>% filter(area==area)\nv<-unique(v$name)\n\n# Distribute them across all people 1 by 1\ny$name<- rep(v, length.out = nrow(y))\ny\n}\n\narea_type <- df1 %>% select(area, type) %>% distinct()\nout <- map2(area_type$area, area_type$type, f)\nout <- do.call(rbind, out)\nhead(out)\n#> items type area value name\n#> 1 Item1995 C Area24 9.998251 Joshua\n#> 2 Item1991 C Area20 9.985092 Meghan\n#> 3 Item2669 A Area23 9.983082 Valden\n#> 4 Item2131 C Area25 9.979196 Ashley\n#> 5 Item818 B Area8 9.978811 Clay\n#> 6 Item639 C Area18 9.975706 Hector\n map2() purrr area type rbind() load(\"~/Downloads/stackoverflow_dataframes.RData\")\nlibrary(tidyverse)\n\ndf2 <- df2 %>% \n group_by(area) %>% \n mutate(obs= 1:n())\n\ntmp2 <- df2 %>% \n group_by(area) %>% \n tally()\n\ntmp1 <- df1 %>%\n arrange(area, type) %>%\n left_join(tmp2) %>% \n group_split(area, type) %>% \n map(., function(x){x$obs <- rep(1:x$n[1], max(1, ceiling(nrow(x)/x$n[1])), replace=FALSE)[1:nrow(x)]; x}) %>%\n bind_rows() %>% \n left_join(df2)\n#> Joining, by = \"area\"\n#> Joining, by = c(\"area\", \"obs\")\nhead(tmp1)\n#> # A tibble: 6 × 7\n#> item area type value n obs name \n#> <chr> <chr> <chr> <dbl> <int> <int> <chr> \n#> 1 Item1064 Area1 A 5066. 2 1 William \n#> 2 Item3014 Area1 A 3434. 2 2 Rhiannon\n#> 3 Item42 Area1 B 939 2 1 William \n#> 4 Item174 Area1 B 840 2 2 Rhiannon\n#> 5 Item191 Area1 B 1189. 2 1 William \n#> 6 Item787 Area1 B 748. 2 2 Rhiannon\n\n\ntmp1 %>% \n group_by(area, type, obs) %>% \n tally()\n#> # A tibble: 234 × 4\n#> # Groups: area, type [74]\n#> area type obs n\n#> <chr> <chr> <int> <int>\n#> 1 Area1 A 1 1\n#> 2 Area1 A 2 1\n#> 3 Area1 B 1 12\n#> 4 Area1 B 2 11\n#> 5 Area1 C 1 27\n#> 6 Area1 C 2 26\n#> 7 Area10 A 1 3\n#> 8 Area10 A 2 2\n#> 9 Area10 A 3 2\n#> 10 Area10 B 1 7\n#> # … with 224 more rows\n"
},
{
"answer_id": 74521644,
"author": "langtang",
"author_id": 4447540,
"author_profile": "https://Stackoverflow.com/users/4447540",
"pm_score": 2,
"selected": false,
"text": "data.table df2 area type value f() library(data.table)\n\nf <- function(x,l) {\n v = as.vector(sapply(seq_along(x), \\(i) c(x[i:length(x)],x[0:(i-1)])))\n rep(v,length.out=l)\n}\n\nsetDT(df1)[unique(setDT(df2)), on=.(area), allow.cartesian=T] %>% \n .[order(type,-value)] %>% \n .[,nid:=f(1:uniqueN(name),.N), .(area)] %>% \n .[nid==1]\n names name Rdata name type N\n1: William A 1\n2: Rhiannon A 1\n3: William B 12\n4: Rhiannon B 11\n5: Rhiannon C 27\n6: William C 26\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11351821/"
] |
74,520,198
|
<p>In every new message that comes to my account, the application restarts itself. Then it gives this error.I tried to find the solution but failed.I write the error code on the bottom line.</p>
<pre><code>E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.edusoft.teacher.myeducare, PID: 7367
java.lang.RuntimeException: Unable to start receiver com.onesignal.GcmBroadcastReceiver: java.lang.IllegalArgumentException: com.edusoft.teacher.myeducare: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
at android.app.ActivityThread.handleReceiver(ActivityThread.java:4438)
at android.app.ActivityThread.access$1700(ActivityThread.java:265)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2114)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:210)
at android.os.Looper.loop(Looper.java:299)
at android.app.ActivityThread.main(ActivityThread.java:8168)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:556)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1037)
Caused by: java.lang.IllegalArgumentException: com.edusoft.teacher.myeducare: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
at android.app.PendingIntent.checkFlags(PendingIntent.java:378)
at android.app.PendingIntent.getBroadcastAsUser(PendingIntent.java:648)
at android.app.PendingIntent.getBroadcast(PendingIntent.java:635)
at com.onesignal.GenerateNotification.getNewActionPendingIntent(GenerateNotification.java:195)
at com.onesignal.GenerateNotification.createGenericPendingIntentsForNotif(GenerateNotification.java:404)
at com.onesignal.GenerateNotification.showNotification(GenerateNotification.java:388)
at com.onesignal.GenerateNotification.fromJsonPayload(GenerateNotification.java:116)
at com.onesignal.NotificationBundleProcessor.ProcessJobForDisplay(NotificationBundleProcessor.java:115)
at com.onesignal.NotificationBundleProcessor.ProcessFromGCMIntentService(NotificationBundleProcessor.java:98)
at com.onesignal.GcmBroadcastReceiver.startGCMService(GcmBroadcastReceiver.java:138)
at com.onesignal.GcmBroadcastReceiver.processOrderBroadcast(GcmBroadcastReceiver.java:129)
at com.onesignal.GcmBroadcastReceiver.onReceive(GcmBroadcastReceiver.java:70)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:4425)
... 9 more
</code></pre>
<p>i found this code but either i did not use it correctly or it does not work properly</p>
<pre><code>val updatedPendingIntent = PendingIntent.getActivity(
applicationContext,
NOTIFICATION_REQUEST_CODE,
updatedIntent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT // setting the mutability flag
)
</code></pre>
|
[
{
"answer_id": 74520305,
"author": "Rishabh Shukla",
"author_id": 8867099,
"author_profile": "https://Stackoverflow.com/users/8867099",
"pm_score": 0,
"selected": false,
"text": "val updatedPendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)\n } else {\n PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT)\n }\n"
},
{
"answer_id": 74520541,
"author": "Sandesh KhutalSaheb",
"author_id": 18362930,
"author_profile": "https://Stackoverflow.com/users/18362930",
"pm_score": 0,
"selected": false,
"text": "Caused by: java.lang.IllegalArgumentException: com.edusoft.teacher.myeducare: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.\n Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.\n \"androidx.work:work-runtime-ktx:2.5.0\" val updatedPendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n PendingIntent.getActivity(\n applicationContext, NOTIFICATION_REQUEST_CODE, updatedIntent, PendingIntent.FLAG_IMMUTABLE\n )\n } else {\n PendingIntent.getActivity(\n applicationContext, NOTIFICATION_REQUEST_CODE, updatedIntent, PendingIntent.FLAG_ONE_SHOT\n )\n }\n"
},
{
"answer_id": 74521885,
"author": "krupa parekh",
"author_id": 11041834,
"author_profile": "https://Stackoverflow.com/users/11041834",
"pm_score": 3,
"selected": true,
"text": "PendingIntent contentIntent = PendingIntent.getActivity(context,NOTIFICATION_REQUEST_CODE, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20247755/"
] |
74,520,236
|
<pre><code> child: Scaffold(
body: SingleChildScrollView(
child: Column(
children: [
_cardList(context),
Column(
children: [
Expanded(
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: 3,
itemBuilder: (context, index) {
return Card(
child: Image.asset('assets/images/horizontal.jpg'),
);
},
),
)
],
),
</code></pre>
<p>I created a list and added 3 images under each other. But I can't scroll down. I thought because I did Column in Column. But nothing changed when I deleted the Bottom Column.</p>
|
[
{
"answer_id": 74520305,
"author": "Rishabh Shukla",
"author_id": 8867099,
"author_profile": "https://Stackoverflow.com/users/8867099",
"pm_score": 0,
"selected": false,
"text": "val updatedPendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)\n } else {\n PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT)\n }\n"
},
{
"answer_id": 74520541,
"author": "Sandesh KhutalSaheb",
"author_id": 18362930,
"author_profile": "https://Stackoverflow.com/users/18362930",
"pm_score": 0,
"selected": false,
"text": "Caused by: java.lang.IllegalArgumentException: com.edusoft.teacher.myeducare: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.\n Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.\n \"androidx.work:work-runtime-ktx:2.5.0\" val updatedPendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n PendingIntent.getActivity(\n applicationContext, NOTIFICATION_REQUEST_CODE, updatedIntent, PendingIntent.FLAG_IMMUTABLE\n )\n } else {\n PendingIntent.getActivity(\n applicationContext, NOTIFICATION_REQUEST_CODE, updatedIntent, PendingIntent.FLAG_ONE_SHOT\n )\n }\n"
},
{
"answer_id": 74521885,
"author": "krupa parekh",
"author_id": 11041834,
"author_profile": "https://Stackoverflow.com/users/11041834",
"pm_score": 3,
"selected": true,
"text": "PendingIntent contentIntent = PendingIntent.getActivity(context,NOTIFICATION_REQUEST_CODE, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17906689/"
] |
74,520,239
|
<p>In C++ we have <code>std::variant</code> for creating a <a href="https://en.wikipedia.org/wiki/Tagged_union" rel="nofollow noreferrer">sum-types</a> (AKA discriminated-union).<br />
For example, the following will allow <code>v</code> to hold either a <code>std::string</code> or an <code>int</code>:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <variant>
#include <string>
//...
std::variant< std::string, int> v;
v = "aaa"; // now v holds a std::string
v = 5; // now v holds an int
</code></pre>
<p>In addition - the compiler will enforce that you assign <code>v</code> only with values convertible to <code>std::string</code> or <code>int</code>.</p>
<p>I am looking for a similar construct in C#.<br />
Had a look at this post: <a href="https://stackoverflow.com/questions/11046622/variant-type-in-c-sharp">Variant Type in C#</a>,
but it didn't offer the proper equivalent I am looking for.</p>
<p>Is there one in C#?</p>
<hr />
<p>Edit:<br />
The SO post <a href="https://stackoverflow.com/questions/3151702/discriminated-union-in-c-sharp">Discriminated union in C#</a> is related but does not exactly answer my question because I am looking for a general language construct and not for a solution for a specific case.<br />
However one of the answers mentioned the OneOf library, which is also one of the solutions in the accepted answer here.</p>
|
[
{
"answer_id": 74520357,
"author": "pm100",
"author_id": 173397,
"author_profile": "https://Stackoverflow.com/users/173397",
"pm_score": 1,
"selected": false,
"text": "object object v;\n v = \"aaa\";\n v = 42;\n"
},
{
"answer_id": 74520382,
"author": "theemee",
"author_id": 14299113,
"author_profile": "https://Stackoverflow.com/users/14299113",
"pm_score": 3,
"selected": true,
"text": "Either LanguageExt.Core using LanguageExt;\n\n//...\n\nEither<string, int> v;\nv = \"aaa\";\nv = 5;\n OneOf using OneOf;\n\n//...\n\nOneOf<string, int> v;\nv = \"aaa\";\nv = 5;\n Either OneOf"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18519921/"
] |
74,520,243
|
<p>I am creating a simple EXPENSE MANAGER app</p>
<p>I have divided screen in two section</p>
<p>Top Section for showing Two card of TotalIncome and TotalExpense
and other section is showing All Transactions</p>
<p>Here, I have taken Streambuilder for showing all transaction, and with the help of this stream builder <strong>I have created Tow Global Variable totalincome and totalexpense</strong></p>
<p>and showing total income and totalexpense to top section's Card</p>
<p>When I add any transaction, List of transaction refresh properly as it is due to Stream Builder but total income and expense card not refreshing...</p>
<p>here I want the proper way to do it...(
like creating a method that fetch records from firebase and store into a List and to use this list for various needs...</p>
<p>here Is my code</p>
<pre><code>Widget headerSummary(Size size) {
return Container(
height: size.height * 0.15,
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.only(
bottomRight: Radius.circular(30), bottomLeft: Radius.circular(30)),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: SummaryCard(
color: Colors.green,
amount: totalincome.toString(),
icondata: Icons.arrow_upward,
title: 'Income',
),
),
Expanded(
child: SummaryCard(
color: Colors.red,
amount: totalexpense.toString(),
icondata: Icons.arrow_downward,
title: 'Expense',
),
),
],
),
);
}
</code></pre>
<p>transaction</p>
<pre><code>Widget showTransactions(Size size) {
return Container(
height: size.height * .65,
// color: Colors.red,
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('users')
.doc(widget.loggeduser.userid)
.collection('expenses').orderBy("date",descending: true)
.snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
if (snapshot.hasData) {
QuerySnapshot querysnapshot =
snapshot.data as QuerySnapshot;
if (querysnapshot.docs.length > 0) {
List<Map<String, dynamic>> transactionlist = [];
for (int x = 0; x < querysnapshot.docs.length; x++) {
Map<String, dynamic> expensemap = querysnapshot.docs[x]
.data() as Map<String, dynamic>;
transactionlist.add(expensemap);
}
var x=transactionlist.where((element) => element['isexpense']==true).toList();
totalexpense=x.fold(0, (previousValue, element) => previousValue+element['amount']);
var y=transactionlist.where((element) => element['isexpense']==false).toList();
totalincome=y.fold(0, (previousValue, element) => previousValue+element['amount']);
//I have edited this lines...
return ListView.builder(
//reverse: true,
padding: EdgeInsets.symmetric(vertical: 10),
itemCount: transactionlist.length,
itemBuilder: (context, index) {
final trans=TransactionModel.fromjson(transactionlist[index]);
print(trans.toString());
return TransactionCard(
amount: trans.amount.toStringAsFixed(2),
datetime: trans.date.toString(),
paymentby: trans.paymentmode,
category: trans.category.title,
categoryicon: trans.category.iconurl,
isexpense: trans.isexpense,
);
});//listview end
} else {
return Container(
child: Center(
child: Text('No Transaction Found...')));
}
} else {
if (snapshot.hasError) {
return Text('error found');
} else {
return Text('empty..');
}
}
} else {
return Center(child: CircularProgressIndicator());
}
}),
);
}
</code></pre>
<p><a href="https://i.stack.imgur.com/gOJxV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gOJxV.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74520357,
"author": "pm100",
"author_id": 173397,
"author_profile": "https://Stackoverflow.com/users/173397",
"pm_score": 1,
"selected": false,
"text": "object object v;\n v = \"aaa\";\n v = 42;\n"
},
{
"answer_id": 74520382,
"author": "theemee",
"author_id": 14299113,
"author_profile": "https://Stackoverflow.com/users/14299113",
"pm_score": 3,
"selected": true,
"text": "Either LanguageExt.Core using LanguageExt;\n\n//...\n\nEither<string, int> v;\nv = \"aaa\";\nv = 5;\n OneOf using OneOf;\n\n//...\n\nOneOf<string, int> v;\nv = \"aaa\";\nv = 5;\n Either OneOf"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18817235/"
] |
74,520,255
|
<p>I tried to publish my app in production but I'm facing this issue <code>You uploaded an APK or Android App Bundle which has an activity, activity alias, service or broadcast receiver with intent filter, but without 'android:exported' property set. This file can't be installed on Android 12 or higher. See: developer.android.com/about/versions/12/behavior-changes-12#exported</code></p>
<p>I also added android:exported="true" in service and activity, still not resolved.</p>
|
[
{
"answer_id": 74520357,
"author": "pm100",
"author_id": 173397,
"author_profile": "https://Stackoverflow.com/users/173397",
"pm_score": 1,
"selected": false,
"text": "object object v;\n v = \"aaa\";\n v = 42;\n"
},
{
"answer_id": 74520382,
"author": "theemee",
"author_id": 14299113,
"author_profile": "https://Stackoverflow.com/users/14299113",
"pm_score": 3,
"selected": true,
"text": "Either LanguageExt.Core using LanguageExt;\n\n//...\n\nEither<string, int> v;\nv = \"aaa\";\nv = 5;\n OneOf using OneOf;\n\n//...\n\nOneOf<string, int> v;\nv = \"aaa\";\nv = 5;\n Either OneOf"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10106583/"
] |
74,520,280
|
<p>I want to discover the underlying pattern between my features and target so I tried to use groupby but instead of the count I want to calculate the ratio or the percentage compared to the total of the count of each class
the following code is similar to the work I have done.</p>
<pre><code>fet1=["A","B","C"]
fet2=["X","Y","Z"]
target=["0","1"]
df = pd.DataFrame(data={"fet1":np.random.choice(fet1,1000),"fet2":np.random.choice(fet2,1000),"class":np.random.choice(target,1000)})
df.groupby(['fet1','fet2','class'])['class'].agg(['count'])
</code></pre>
|
[
{
"answer_id": 74520281,
"author": "Mohamed Amine",
"author_id": 10327984,
"author_profile": "https://Stackoverflow.com/users/10327984",
"pm_score": -1,
"selected": false,
"text": "fet1=[\"A\",\"B\",\"C\"]\nfet2=[\"X\",\"Y\",\"Z\"]\ntarget=[\"0\",\"1\"]\ndf = pd.DataFrame(data={\"fet1\":np.random.choice(fet1,1000),\"fet2\":np.random.choice(fet2,1000),\"class\":np.random.choice(target,1000)})\ndf.groupby(['fet1','fet2','class'])['class'].agg(['count'])/df.groupby(['class'])['class'].agg(['count'])*100\n\n"
},
{
"answer_id": 74520371,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "out = df.groupby('class').value_counts(normalize=True).mul(100)\n class fet1 fet2\n0 A Y 13.859275\n B Y 12.366738\n X 12.153518\n C X 11.513859\n Y 10.660981\n B Z 10.447761\n A Z 10.021322\n C Z 9.594883\n A X 9.381663\n1 A Y 14.124294\n C Z 13.935970\n B Z 11.676083\n Y 11.111111\n C Y 11.111111\n X 11.111111\n A X 10.169492\n B X 9.416196\n A Z 7.344633\ndtype: float64\n out = (df\n .groupby('class').value_counts(normalize=True).mul(100)\n .reorder_levels(['fet1', 'fet2', 'class']).sort_index()\n)\n fet1 fet2 class\nA X 0 9.381663\n 1 10.169492\n Y 0 13.859275\n 1 14.124294\n Z 0 10.021322\n 1 7.344633\nB X 0 12.153518\n 1 9.416196\n Y 0 12.366738\n 1 11.111111\n Z 0 10.447761\n 1 11.676083\nC X 0 11.513859\n 1 11.111111\n Y 0 10.660981\n 1 11.111111\n Z 0 9.594883\n 1 13.935970\ndtype: float64\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10327984/"
] |
74,520,332
|
<p>I'm trying to follow along with a video course to implement photo gallery with Unsplash.</p>
<p>First I implemented UIViewController with searchbar and navigation bar in it</p>
<pre><code>PhotoCollectionViewController: UIViewController
</code></pre>
<p>and manually adding searchbar and navigation bar</p>
<pre><code>//MARK: - Nav bar inelkaar steken hier
private func setupNavigationBar(){
let titleLabel = UILabel()
titleLabel.text = "Photos"
titleLabel.font = UIFont.systemFont(ofSize: 15)
titleLabel.textColor = .black
navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: titleLabel)
navigationItem.rightBarButtonItems = [addBarButtonItem, actionBarButtonItem]
}
</code></pre>
<p>and the same for searchbar</p>
<p>so I got the result as this:
<a href="https://i.stack.imgur.com/Oh6rK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Oh6rK.png" alt="enter image description here" /></a></p>
<p>after this the <code>PhotoCollectionViewController: UIViewController</code> inheritance seemed be wrong what I did, and I need to change it to UICollectionViewController</p>
<p>I make then another controller inherited from UICollectionViewController with the same logic <code>PhotoCollectionViewController: UICollectionViewController</code></p>
<p>It compiles without any issues, but I don't see navigation an search bar anymore</p>
<p><a href="https://i.stack.imgur.com/oE8GN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oE8GN.png" alt="enter image description here" /></a></p>
<p>How can I fix this?</p>
|
[
{
"answer_id": 74520281,
"author": "Mohamed Amine",
"author_id": 10327984,
"author_profile": "https://Stackoverflow.com/users/10327984",
"pm_score": -1,
"selected": false,
"text": "fet1=[\"A\",\"B\",\"C\"]\nfet2=[\"X\",\"Y\",\"Z\"]\ntarget=[\"0\",\"1\"]\ndf = pd.DataFrame(data={\"fet1\":np.random.choice(fet1,1000),\"fet2\":np.random.choice(fet2,1000),\"class\":np.random.choice(target,1000)})\ndf.groupby(['fet1','fet2','class'])['class'].agg(['count'])/df.groupby(['class'])['class'].agg(['count'])*100\n\n"
},
{
"answer_id": 74520371,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 1,
"selected": false,
"text": "out = df.groupby('class').value_counts(normalize=True).mul(100)\n class fet1 fet2\n0 A Y 13.859275\n B Y 12.366738\n X 12.153518\n C X 11.513859\n Y 10.660981\n B Z 10.447761\n A Z 10.021322\n C Z 9.594883\n A X 9.381663\n1 A Y 14.124294\n C Z 13.935970\n B Z 11.676083\n Y 11.111111\n C Y 11.111111\n X 11.111111\n A X 10.169492\n B X 9.416196\n A Z 7.344633\ndtype: float64\n out = (df\n .groupby('class').value_counts(normalize=True).mul(100)\n .reorder_levels(['fet1', 'fet2', 'class']).sort_index()\n)\n fet1 fet2 class\nA X 0 9.381663\n 1 10.169492\n Y 0 13.859275\n 1 14.124294\n Z 0 10.021322\n 1 7.344633\nB X 0 12.153518\n 1 9.416196\n Y 0 12.366738\n 1 11.111111\n Z 0 10.447761\n 1 11.676083\nC X 0 11.513859\n 1 11.111111\n Y 0 10.660981\n 1 11.111111\n Z 0 9.594883\n 1 13.935970\ndtype: float64\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11719536/"
] |
74,520,385
|
<p>I need to save some items from local storage with c# (via js, because seems like there is no solution with 'pure' c#). I've tried this (sorry for code convention, I've been doing it in a hurry):</p>
<pre><code>
public string token;
string storageToken = "localStorage.getItem('token')";
token = (string)js.ExecuteScript(storageToken);`
</code></pre>
<p>When I run this, it gets an empty string for these elements. My aim is to get local storage elements, save them to variables and use them with in another method:</p>
<pre><code>
string tokenSetItemScript = $"localStorage.setItem('token','{token}')";
js.ExecuteScript(tokenSetItemScript);
</code></pre>
|
[
{
"answer_id": 74521214,
"author": "Alex Karamfilov",
"author_id": 7031148,
"author_profile": "https://Stackoverflow.com/users/7031148",
"pm_score": 1,
"selected": false,
"text": "LocalStorage local = ((WebStorage) driver).getLocalStorage();\n"
},
{
"answer_id": 74538186,
"author": "ggeorge",
"author_id": 5276946,
"author_profile": "https://Stackoverflow.com/users/5276946",
"pm_score": 1,
"selected": true,
"text": "public static class WebDriverExtensions\n{\n public static void SetItemToLocalStorage(this IWebDriver driver, string key, string value)\n {\n var js = (IJavaScriptExecutor)driver;\n js.ExecuteScript(\"localStorage.setItem(arguments[0],arguments[1])\", key, value);\n }\n\n public static string GetItemFromLocalStorage(this IWebDriver driver, string key)\n {\n var js = (IJavaScriptExecutor)driver;\n return (string)js.ExecuteScript($\"return window.localStorage.getItem('{key}')\");\n }\n}\n driver.SetItemToLocalStorage(\"token\", \"your-token\");\nstring token = driver.GetItemFromLocalStorage(\"token\")\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20563836/"
] |
74,520,410
|
<p>i have a problem with RAM usage - I fetch quite a lot of data from DB and pour it into a pandas DataFrame, where I do <code>groub_by</code> to list - something DB is not very good at.</p>
<p>Thing is, as I fetch around 40 columns, pandas is not really good in determining the dtypes for each column. I would love to specify dtype for each column separately, so pandas does not use so much memory using <code>object</code> dtype everywhere. I know, I can transform the dataframe afterwards, but that does not solve the RAM overreach.</p>
<pre><code> import pandas as pd
import numpy as np
# Just a sample sql
sql = "select premise_id, parent_id, addr_ward FROM table;"
# This is list of tuples from database
rows = safe_call_db_read(db.conn, sql)
logger.info("Db fetched dataframe")
dtype = {
'premise_id': np.int64,
'parent_id': np.int64,
'addr_ward': object
}
data_frame = pd.DataFrame(data=rows, dtype=dtype)
</code></pre>
<p>This fails, ofc, because only one dtype is allowed as parameter, throwing this</p>
<pre><code>TypeError: object of type 'type' has no len()
</code></pre>
<p>This SUCKS.</p>
<p>Is there some way of declaring dtypes for each column before actual loading data, that would save each column optimaly and thus saving me some RAM?</p>
<p>Maybe creating empty data frame, declaring dtype for each column and then appending the rows?</p>
|
[
{
"answer_id": 74521214,
"author": "Alex Karamfilov",
"author_id": 7031148,
"author_profile": "https://Stackoverflow.com/users/7031148",
"pm_score": 1,
"selected": false,
"text": "LocalStorage local = ((WebStorage) driver).getLocalStorage();\n"
},
{
"answer_id": 74538186,
"author": "ggeorge",
"author_id": 5276946,
"author_profile": "https://Stackoverflow.com/users/5276946",
"pm_score": 1,
"selected": true,
"text": "public static class WebDriverExtensions\n{\n public static void SetItemToLocalStorage(this IWebDriver driver, string key, string value)\n {\n var js = (IJavaScriptExecutor)driver;\n js.ExecuteScript(\"localStorage.setItem(arguments[0],arguments[1])\", key, value);\n }\n\n public static string GetItemFromLocalStorage(this IWebDriver driver, string key)\n {\n var js = (IJavaScriptExecutor)driver;\n return (string)js.ExecuteScript($\"return window.localStorage.getItem('{key}')\");\n }\n}\n driver.SetItemToLocalStorage(\"token\", \"your-token\");\nstring token = driver.GetItemFromLocalStorage(\"token\")\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10532827/"
] |
74,520,412
|
<p>I want to take <pre>[{'O', 'L'}, {'E', 'L'}, {'O', 'H'}, {'E', 'L'}, {'E', 'H'}]</pre> and change it to <pre>["OL", "EL", "OH", "EL", "EH"]</pre> but I am not seeing how. Help?</p>
|
[
{
"answer_id": 74520575,
"author": "zwippie",
"author_id": 409792,
"author_profile": "https://Stackoverflow.com/users/409792",
"pm_score": 3,
"selected": true,
"text": "Enum.map(my_list, fn {a, b} -> List.to_string([a, b]) end)\n"
},
{
"answer_id": 74520635,
"author": "Dogbert",
"author_id": 320615,
"author_profile": "https://Stackoverflow.com/users/320615",
"pm_score": 1,
"selected": false,
"text": "for iex(1)> list = [{'O', 'L'}, {'E', 'L'}, {'O', 'H'}, {'E', 'L'}, {'E', 'H'}]\n[{'O', 'L'}, {'E', 'L'}, {'O', 'H'}, {'E', 'L'}, {'E', 'H'}]\niex(2)> for {a, b} <- list, do: \"#{a}#{b}\"\n[\"OL\", \"EL\", \"OH\", \"EL\", \"EH\"]\n"
},
{
"answer_id": 74520637,
"author": "Everett",
"author_id": 274030,
"author_profile": "https://Stackoverflow.com/users/274030",
"pm_score": -1,
"selected": false,
"text": "'O' != \"O\" [{\"O\", \"L\"}, ...] ++ 'O' 'L' iex> l = [{'O', 'L'}, {'E', 'L'}, {'O', 'H'}, {'E', 'L'}, {'E', 'H'}]\niex(5)> Enum.map(l, &Tuple.to_list/1) |> Enum.map(fn [x, y] -> x ++ y end)\n['OL', 'EL', 'OH', 'EL', 'EH']\n Enum.join/2 iex> l = [{\"O\", \"L\"}, {\"E\", \"L\"}, {\"O\", \"H\"}, {\"E\", \"L\"}, {\"E\", \"H\"}]\niex> Enum.map(l, &Tuple.to_list/1) |> Enum.map(fn chars -> Enum.join(chars) end)\n[\"OL\", \"EL\", \"OH\", \"EL\", \"EH\"]\n to_string/1 iex> l = [{'O', 'L'}, {'E', 'L'}, {'O', 'H'}, {'E', 'L'}, {'E', 'H'}]\niex> Enum.map(l, &Tuple.to_list/1) |> Enum.map(fn [x, y] -> x ++ y |> to_string() end)\n[\"OL\", \"EL\", \"OH\", \"EL\", \"EH\"]\n"
},
{
"answer_id": 74526868,
"author": "Adam Millerchip",
"author_id": 1225617,
"author_profile": "https://Stackoverflow.com/users/1225617",
"pm_score": 1,
"selected": false,
"text": "<<>> for {[a], [b]} <- list, do: <<a::utf8, b::utf8>>\n 'A' utf8 <<>>"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1096587/"
] |
74,520,422
|
<p>I am trying to extract variable names from file names as follows:</p>
<pre><code>happy = "LOL"
angry = "GRRRR"
surprised= "YUPPIE"
file_names=["happy.wav","angry.wav","surprised.wav"
for i in file_names:
name = i.split('.')
name_=name[0]
print(name_)
</code></pre>
<p>I get the output as:</p>
<pre><code>happy
angry
surprised
</code></pre>
<p>when I wish to get the output as:</p>
<pre><code>"LOL"
"GRRRR"
"YUPPIE"
</code></pre>
<p>What is my code missing?</p>
|
[
{
"answer_id": 74520575,
"author": "zwippie",
"author_id": 409792,
"author_profile": "https://Stackoverflow.com/users/409792",
"pm_score": 3,
"selected": true,
"text": "Enum.map(my_list, fn {a, b} -> List.to_string([a, b]) end)\n"
},
{
"answer_id": 74520635,
"author": "Dogbert",
"author_id": 320615,
"author_profile": "https://Stackoverflow.com/users/320615",
"pm_score": 1,
"selected": false,
"text": "for iex(1)> list = [{'O', 'L'}, {'E', 'L'}, {'O', 'H'}, {'E', 'L'}, {'E', 'H'}]\n[{'O', 'L'}, {'E', 'L'}, {'O', 'H'}, {'E', 'L'}, {'E', 'H'}]\niex(2)> for {a, b} <- list, do: \"#{a}#{b}\"\n[\"OL\", \"EL\", \"OH\", \"EL\", \"EH\"]\n"
},
{
"answer_id": 74520637,
"author": "Everett",
"author_id": 274030,
"author_profile": "https://Stackoverflow.com/users/274030",
"pm_score": -1,
"selected": false,
"text": "'O' != \"O\" [{\"O\", \"L\"}, ...] ++ 'O' 'L' iex> l = [{'O', 'L'}, {'E', 'L'}, {'O', 'H'}, {'E', 'L'}, {'E', 'H'}]\niex(5)> Enum.map(l, &Tuple.to_list/1) |> Enum.map(fn [x, y] -> x ++ y end)\n['OL', 'EL', 'OH', 'EL', 'EH']\n Enum.join/2 iex> l = [{\"O\", \"L\"}, {\"E\", \"L\"}, {\"O\", \"H\"}, {\"E\", \"L\"}, {\"E\", \"H\"}]\niex> Enum.map(l, &Tuple.to_list/1) |> Enum.map(fn chars -> Enum.join(chars) end)\n[\"OL\", \"EL\", \"OH\", \"EL\", \"EH\"]\n to_string/1 iex> l = [{'O', 'L'}, {'E', 'L'}, {'O', 'H'}, {'E', 'L'}, {'E', 'H'}]\niex> Enum.map(l, &Tuple.to_list/1) |> Enum.map(fn [x, y] -> x ++ y |> to_string() end)\n[\"OL\", \"EL\", \"OH\", \"EL\", \"EH\"]\n"
},
{
"answer_id": 74526868,
"author": "Adam Millerchip",
"author_id": 1225617,
"author_profile": "https://Stackoverflow.com/users/1225617",
"pm_score": 1,
"selected": false,
"text": "<<>> for {[a], [b]} <- list, do: <<a::utf8, b::utf8>>\n 'A' utf8 <<>>"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17016466/"
] |
74,520,493
|
<p>I'm using Node Red and Postgresql to record events, one event is that a specific 0x40 light has been switched on, another event is that the same light has been switched off. For simplicity, the on and off times have been stored in different tables.</p>
<p>Using SQL, is it possible to calculate the sum of durations that each light has been on during a given time period, e.g. a 24 hour period? As such the information regarding switch on switch off times is not very useful, but once aggregated the information becomes much more useful.</p>
<p>The table below shows that the light 0x40 was switched on for about 4 seconds, so here the desired output would be as follows.</p>
<pre><code>iddec label TimeOnInSeconds
64 0x40 ruokapöytä 4
</code></pre>
<p><a href="https://i.stack.imgur.com/oYCEZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oYCEZ.png" alt="enter image description here" /></a></p>
|
[
{
"answer_id": 74520575,
"author": "zwippie",
"author_id": 409792,
"author_profile": "https://Stackoverflow.com/users/409792",
"pm_score": 3,
"selected": true,
"text": "Enum.map(my_list, fn {a, b} -> List.to_string([a, b]) end)\n"
},
{
"answer_id": 74520635,
"author": "Dogbert",
"author_id": 320615,
"author_profile": "https://Stackoverflow.com/users/320615",
"pm_score": 1,
"selected": false,
"text": "for iex(1)> list = [{'O', 'L'}, {'E', 'L'}, {'O', 'H'}, {'E', 'L'}, {'E', 'H'}]\n[{'O', 'L'}, {'E', 'L'}, {'O', 'H'}, {'E', 'L'}, {'E', 'H'}]\niex(2)> for {a, b} <- list, do: \"#{a}#{b}\"\n[\"OL\", \"EL\", \"OH\", \"EL\", \"EH\"]\n"
},
{
"answer_id": 74520637,
"author": "Everett",
"author_id": 274030,
"author_profile": "https://Stackoverflow.com/users/274030",
"pm_score": -1,
"selected": false,
"text": "'O' != \"O\" [{\"O\", \"L\"}, ...] ++ 'O' 'L' iex> l = [{'O', 'L'}, {'E', 'L'}, {'O', 'H'}, {'E', 'L'}, {'E', 'H'}]\niex(5)> Enum.map(l, &Tuple.to_list/1) |> Enum.map(fn [x, y] -> x ++ y end)\n['OL', 'EL', 'OH', 'EL', 'EH']\n Enum.join/2 iex> l = [{\"O\", \"L\"}, {\"E\", \"L\"}, {\"O\", \"H\"}, {\"E\", \"L\"}, {\"E\", \"H\"}]\niex> Enum.map(l, &Tuple.to_list/1) |> Enum.map(fn chars -> Enum.join(chars) end)\n[\"OL\", \"EL\", \"OH\", \"EL\", \"EH\"]\n to_string/1 iex> l = [{'O', 'L'}, {'E', 'L'}, {'O', 'H'}, {'E', 'L'}, {'E', 'H'}]\niex> Enum.map(l, &Tuple.to_list/1) |> Enum.map(fn [x, y] -> x ++ y |> to_string() end)\n[\"OL\", \"EL\", \"OH\", \"EL\", \"EH\"]\n"
},
{
"answer_id": 74526868,
"author": "Adam Millerchip",
"author_id": 1225617,
"author_profile": "https://Stackoverflow.com/users/1225617",
"pm_score": 1,
"selected": false,
"text": "<<>> for {[a], [b]} <- list, do: <<a::utf8, b::utf8>>\n 'A' utf8 <<>>"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/896646/"
] |
74,520,574
|
<p>I am trying to hide the main div ('product-block-list__item product-block-list__item--content size__chart') when the class ('ks-chart-container') is not in the page.</p>
<p>(No jQuery if possible)</p>
<hr />
<p>Here is the container with ('ks-chart-container').</p>
<pre><code><div class="product-block-list__item product-block-list__item--content size__chart">
<div class="card">
<button class="card__collapsible-button" data-action="toggle-collapsible" aria-expanded="false" aria-controls="block-template--14697163096134__main-092edfe6-4684-4f51-970d-dfb11469ca43">
<span class="card__title heading h3">Size chart</span>
<span class="plus-button plus-button--large"></span>
</button>
<div id="block-template--14697163096134__main-092edfe6-4684-4f51-970d-dfb11469ca43" class="card__collapsible" style="height: 0px;">
<div class="card__collapsible-content">
<div class="rte text--pull">
<div id="KiwiSizingChart" class=" kiwiSizingLoaded">
<div class="ks-chart-container sizing-chart-container">
<div class="ks-chart-tab-container"></div>
</div>
<div class="ks-calculator-container sizing-calculator-container ks-calculator-inject hide"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<hr />
<p>Here is the container without ('ks-chart-container').</p>
<pre><code><div class="product-block-list__item product-block-list__item--content size__chart">
<div class="card">
<button class="card__collapsible-button" data-action="toggle-collapsible" aria-expanded="false" aria-controls="block-template--14697163096134__main-092edfe6-4684-4f51-970d-dfb11469ca43">
<span class="card__title heading h3">Size chart</span>
<span class="plus-button plus-button--large"></span>
</button>
<div id="block-template--14697163096134__main-092edfe6-4684-4f51-970d-dfb11469ca43" class="card__collapsible" style="height: 0px;">
<div class="card__collapsible-content">
<div class="rte text--pull">
<div id="KiwiSizingChart" class=" kiwiSizingLoaded"></div>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<p>I tried using:</p>
<p><code>.ks-chart-container:empty .product-block-list__item.product-block-list__item--content.size__chart { display: none; }</code></p>
<p>But did not work. (Excuse my coding, I'm a beginner).</p>
|
[
{
"answer_id": 74520575,
"author": "zwippie",
"author_id": 409792,
"author_profile": "https://Stackoverflow.com/users/409792",
"pm_score": 3,
"selected": true,
"text": "Enum.map(my_list, fn {a, b} -> List.to_string([a, b]) end)\n"
},
{
"answer_id": 74520635,
"author": "Dogbert",
"author_id": 320615,
"author_profile": "https://Stackoverflow.com/users/320615",
"pm_score": 1,
"selected": false,
"text": "for iex(1)> list = [{'O', 'L'}, {'E', 'L'}, {'O', 'H'}, {'E', 'L'}, {'E', 'H'}]\n[{'O', 'L'}, {'E', 'L'}, {'O', 'H'}, {'E', 'L'}, {'E', 'H'}]\niex(2)> for {a, b} <- list, do: \"#{a}#{b}\"\n[\"OL\", \"EL\", \"OH\", \"EL\", \"EH\"]\n"
},
{
"answer_id": 74520637,
"author": "Everett",
"author_id": 274030,
"author_profile": "https://Stackoverflow.com/users/274030",
"pm_score": -1,
"selected": false,
"text": "'O' != \"O\" [{\"O\", \"L\"}, ...] ++ 'O' 'L' iex> l = [{'O', 'L'}, {'E', 'L'}, {'O', 'H'}, {'E', 'L'}, {'E', 'H'}]\niex(5)> Enum.map(l, &Tuple.to_list/1) |> Enum.map(fn [x, y] -> x ++ y end)\n['OL', 'EL', 'OH', 'EL', 'EH']\n Enum.join/2 iex> l = [{\"O\", \"L\"}, {\"E\", \"L\"}, {\"O\", \"H\"}, {\"E\", \"L\"}, {\"E\", \"H\"}]\niex> Enum.map(l, &Tuple.to_list/1) |> Enum.map(fn chars -> Enum.join(chars) end)\n[\"OL\", \"EL\", \"OH\", \"EL\", \"EH\"]\n to_string/1 iex> l = [{'O', 'L'}, {'E', 'L'}, {'O', 'H'}, {'E', 'L'}, {'E', 'H'}]\niex> Enum.map(l, &Tuple.to_list/1) |> Enum.map(fn [x, y] -> x ++ y |> to_string() end)\n[\"OL\", \"EL\", \"OH\", \"EL\", \"EH\"]\n"
},
{
"answer_id": 74526868,
"author": "Adam Millerchip",
"author_id": 1225617,
"author_profile": "https://Stackoverflow.com/users/1225617",
"pm_score": 1,
"selected": false,
"text": "<<>> for {[a], [b]} <- list, do: <<a::utf8, b::utf8>>\n 'A' utf8 <<>>"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14463877/"
] |
74,520,583
|
<p>I have observed that the <code>TensorFlow</code> methods like <code>assign_add</code> and <code>assign_sub</code> modify the variables of both object and class (if exist). Here is a simple code to reproduce my observation. Can anyone please clarify about this behavior (<code>assign_sub</code> and <code>assign_add</code> modifying both class and instance attributes)?</p>
<pre class="lang-py prettyprint-override"><code>#a python class
class myc_base():
a=1.
def __init__(self, b=1.):
self.b=b
def add(self, to_add=1.):
self.a+=to_add
self.b+=to_add
def sub(self, to_sub=1.):
self.a-=to_sub
self.b-=to_sub
obj_base=myc_base()
print(f'Init. -- class.a: {myc_base.a} | obj.a: {obj_base.a}, obj.b: {obj_base.b}')
obj_base.add(5.)
print(f'after add -- class.a: {myc_base.a} | obj.a: {obj_base.a}, obj.b: {obj_base.b}')
obj_base.sub(2.)
print(f'after sub -- class.a: {myc_base.a} | obj.a: {obj_base.a}, obj.b: {obj_base.b}')
</code></pre>
<p>Output:</p>
<pre><code>Init. -- class.a: 1.0 | obj.a: 1.0, obj.b: 1.0
after add -- class.a: 1.0 | obj.a: 6.0, obj.b: 6.0
after sub -- class.a: 1.0 | obj.a: 4.0, obj.b: 4.0
</code></pre>
<p>With TensorFlow:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
#a class for tf operations
class myc_tf():
a=tf.Variable(1.)
def __init__(self, b=tf.Variable(1.)):
self.b=b
def add(self, to_add=1.):
self.a.assign_add(to_add)
self.b.assign_add(to_add)
def sub(self, to_sub=1.):
self.a.assign_sub(to_sub)
self.b.assign_sub(to_sub)
obj_tf=myc_tf()
print(f'Init. -- class.a: {myc_tf.a.numpy()} | obj.a: {obj_tf.a.numpy()}, obj.b: {obj_tf.b.numpy()}')
obj_tf.add(5.)
print(f'after add -- class.a: {myc_tf.a.numpy()} | obj.a: {obj_tf.a.numpy()}, obj.b: {obj_tf.b.numpy()}')
obj_tf.sub(2.)
print(f'after sub -- class.a: {myc_tf.a.numpy()} | obj.a: {obj_tf.a.numpy()}, obj.b: {obj_tf.b.numpy()}')
</code></pre>
<p>Output:</p>
<pre><code>Init. -- class.a: 1.0 | obj.a: 1.0, obj.b: 1.0
after add -- class.a: 6.0 | obj.a: 6.0, obj.b: 6.0
after sub -- class.a: 4.0 | obj.a: 4.0, obj.b: 4.0
</code></pre>
|
[
{
"answer_id": 74520710,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 2,
"selected": true,
"text": "a b self.a += to_add\nself.a -= to_sub\n self.a = self.a.__iadd__(to_add)\nself.a = self.a.__isub__(to_sub)\n type(self).a += to_add\n self.a"
},
{
"answer_id": 74522048,
"author": "Jirayu Kaewprateep",
"author_id": 7848579,
"author_profile": "https://Stackoverflow.com/users/7848579",
"pm_score": 0,
"selected": false,
"text": "import os\nfrom os.path import exists\nimport tensorflow as tf\n\nimport matplotlib.pyplot as plt\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Class and Functions\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nclass MyDenseLayer(tf.keras.layers.Layer):\n var1 = tf.Variable([10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0])\n var2 = tf.Variable([10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0])\n \n def __init__(self, num_outputs):\n super(MyDenseLayer, self).__init__()\n self.num_outputs = num_outputs\n self.var2 = self.var1 * 10.0\n \n def build(self, input_shape):\n self.kernel = self.add_weight(\"kernel\",\n shape=[int(input_shape[-1]),\n self.num_outputs])\n\n def call(self, inputs):\n self.var1.assign_add([30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0])\n \n temp = tf.constant( self.var2 ).numpy()\n return temp\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Variables\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nstart = 3\nlimit = 33\ndelta = 3\n\n# Create DATA\nsample = tf.range(start, limit, delta)\nsample = tf.cast( sample, dtype=tf.float32 )\n\n# Initail, ( 10, 1 )\nsample = tf.constant( sample, shape=( 10, 1 ) )\nlayer = MyDenseLayer(10)\ndata = layer(sample)\n\nprint( tf.constant( MyDenseLayer.var1 ).numpy() )\nprint( tf.constant( MyDenseLayer.var2 ).numpy() )\nprint( data )\n [40. 40. 40. 40. 40. 40. 40. 40. 40. 40.]\n[10. 10. 10. 10. 10. 10. 10. 10. 10. 10.]\n[100. 100. 100. 100. 100. 100. 100. 100. 100. 100.]\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17658327/"
] |
74,520,586
|
<p>I am trying to read information from a column in my csv file and use it to create a new column. Please help</p>
<p>I imported the csv file and printed the first 10 rows (+ header) but now I would like to create a column for the years in the title column.</p>
<pre><code>```
import csv
from itertools import islice
from operator import itemgetter
#opening the CSV file
with open('/home/raymondossai/movies.csv', mode ='r')as file:
#reading the CSV file
csvFile = csv.reader(file)
#displaying the contents of the CSV file
for row in islice(csvFile, 11): # first 10 only
print(row)
```
</code></pre>
<p>Result:</p>
<pre><code>['movieId', 'title', 'genres']
['1', 'Toy Story (1995)', 'Adventure|Animation|Children|Comedy|Fantasy']
['2', 'Jumanji (1995)', 'Adventure|Children|Fantasy']
['3', 'Grumpier Old Men (1995)', 'Comedy|Romance']
['4', 'Waiting to Exhale (1995)', 'Comedy|Drama|Romance']
['5', 'Father of the Bride Part II (1995)', 'Comedy']
['6', 'Heat (1995)', 'Action|Crime|Thriller']
['7', 'Sabrina (1995)', 'Comedy|Romance']
['8', 'Tom and Huck (1995)', 'Adventure|Children']
['9', 'Sudden Death (1995)', 'Action']
['10', 'GoldenEye (1995)', 'Action|Adventure|Thriller']
</code></pre>
|
[
{
"answer_id": 74520720,
"author": "maxxel_",
"author_id": 17575465,
"author_profile": "https://Stackoverflow.com/users/17575465",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\ndf = pd.read_csv('/home/raymondossai/movies.csv')\n # get the 4 characters of the year (first 4 characters after the ' (' expression)\ndf['Year'] = df['title'].str.split(pat=' (', expand=True)[1][:4].astype(int)\n"
},
{
"answer_id": 74520826,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "re title rows = [\n [\"movieId\", \"title\", \"genres\"],\n [\"1\", \"Toy Story (1995)\", \"Adventure|Animation|Children|Comedy|Fantasy\"],\n [\"2\", \"Jumanji (1995)\", \"Adventure|Children|Fantasy\"],\n [\"3\", \"Grumpier Old Men (1995)\", \"Comedy|Romance\"],\n [\"4\", \"Waiting to Exhale (1995)\", \"Comedy|Drama|Romance\"],\n [\"5\", \"Father of the Bride Part II (1995)\", \"Comedy\"],\n [\"6\", \"Heat (1995)\", \"Action|Crime|Thriller\"],\n [\"7\", \"Sabrina (1995)\", \"Comedy|Romance\"],\n [\"8\", \"Tom and Huck (1995)\", \"Adventure|Children\"],\n [\"9\", \"Sudden Death (1995)\", \"Action\"],\n [\"10\", \"GoldenEye (1995)\", \"Action|Adventure|Thriller\"],\n]\n\nimport re\n\npat = re.compile(r\"\\((\\d{4})\\)\")\n\nfor movie_id, title, genres in rows[1:]:\n year = pat.search(title)\n print([movie_id, title, genres, year.group(1) if year else \"N/A\"])\n ['1', 'Toy Story (1995)', 'Adventure|Animation|Children|Comedy|Fantasy', '1995']\n['2', 'Jumanji (1995)', 'Adventure|Children|Fantasy', '1995']\n['3', 'Grumpier Old Men (1995)', 'Comedy|Romance', '1995']\n['4', 'Waiting to Exhale (1995)', 'Comedy|Drama|Romance', '1995']\n['5', 'Father of the Bride Part II (1995)', 'Comedy', '1995']\n['6', 'Heat (1995)', 'Action|Crime|Thriller', '1995']\n['7', 'Sabrina (1995)', 'Comedy|Romance', '1995']\n['8', 'Tom and Huck (1995)', 'Adventure|Children', '1995']\n['9', 'Sudden Death (1995)', 'Action', '1995']\n['10', 'GoldenEye (1995)', 'Action|Adventure|Thriller', '1995']\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16610162/"
] |
74,520,590
|
<p>i make program for record audio for android but i find MediaRecorder() Deprecated
<code>kotlin code</code></p>
<pre><code>package noteapp.notesnotesnotescairo.mynoteapp
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.icu.text.SimpleDateFormat
import android.media.MediaRecorder
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Looper
import android.os.Looper.prepare
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.NonCancellable.start
import java.io.IOException
import java.util.*
const val REQUEST_CODE=200
private var permission = arrayOf(Manifest.permission.RECORD_AUDIO)
private var permissionGranted=false
private lateinit var recorder : MediaRecorder
private var dirPath=""
private var filename=""
private var isRecording=false
private var isPaused=false
class MainActivity : AppCompatActivity(){
@RequiresApi(Build.VERSION_CODES.S)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
permissionGranted=ActivityCompat.checkSelfPermission(this, permission[0])==PackageManager.PERMISSION_GRANTED
if(!permissionGranted)
ActivityCompat.requestPermissions(this, permission, REQUEST_CODE)
btnRecord.setOnClickListener{
when{
isPaused->resumeRecorder()
isRecording->pauseRecorder()
else->startRecording()
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode== REQUEST_CODE)
permissionGranted=grantResults[0]==PackageManager.PERMISSION_GRANTED
}
private fun pauseRecorder(){
recorder.pause()
isPaused=true
btnRecord.setImageResource(R.drawable.ic_record)
}
private fun resumeRecorder(){
recorder.resume()
isPaused=false
btnRecord.setImageResource(R.drawable.ic_pause)
}
@RequiresApi(Build.VERSION_CODES.S)
private fun startRecording(){
if(!permissionGranted){
ActivityCompat.requestPermissions(this, permission, REQUEST_CODE)
return
}
recorder = MediaRecorder( this)
dirPath="${externalCacheDir?.absolutePath}/"
var simpleDateFormat= SimpleDateFormat("yyyy.mm.dd.hh.mm.ss")
var date :String=simpleDateFormat.format(Date())
filename="audio_record_$date"
recorder.apply {
setAudioSource(MediaRecorder.AudioSource.MIC)
setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
setOutputFile("$dirPath$filename.mp3")
try{
prepare()
}catch (e:IOException){}
start()
}
btnRecord.setImageResource(R.drawable.ic_pause)
isRecording=true
isPaused=false
}
}
</code></pre>
<p><code>xml code</code></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvTimer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00:00"
android:textSize="56sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:layout_marginBottom="80dp"
app:layout_constraintBottom_toBottomOf="parent"
>
<ImageButton
android:id="@+id/btnDelete"
android:layout_width="@dimen/btn_size"
android:src="@drawable/ic_delete_disable"
android:layout_height="@dimen/btn_size"
android:background="@drawable/ic_ripple"/>
<ImageButton
android:id="@+id/btnRecord"
android:layout_width="66dp"
android:layout_marginStart="30dp"
android:layout_marginEnd="30dp"
android:layout_height="66dp"
android:background="@drawable/ic_record"/>
<ImageButton
android:id="@+id/btnList"
android:layout_width="@dimen/btn_size"
android:src="@drawable/ic_list"
android:layout_height="@dimen/btn_size"
android:background="@drawable/ic_ripple"/>
<ImageButton
android:id="@+id/btnDone"
android:layout_width="@dimen/btn_size"
android:src="@drawable/ic_done"
android:visibility="gone"
android:layout_height="@dimen/btn_size"
android:background="@drawable/ic_ripple"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</code></pre>
<p><code>what is new defind for MediaRecorder() not Deprecated ?</code></p>
<p>give me error</p>
<p>java.lang.NoSuchMethodError: No direct method (Landroid/content/Context;)V in class Landroid/media/MediaRecorder; or its super classes (declaration of 'android.media.MediaRecorder' appears in /system/framework/framework.jar!classes2.dex)</p>
|
[
{
"answer_id": 74520720,
"author": "maxxel_",
"author_id": 17575465,
"author_profile": "https://Stackoverflow.com/users/17575465",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\ndf = pd.read_csv('/home/raymondossai/movies.csv')\n # get the 4 characters of the year (first 4 characters after the ' (' expression)\ndf['Year'] = df['title'].str.split(pat=' (', expand=True)[1][:4].astype(int)\n"
},
{
"answer_id": 74520826,
"author": "Andrej Kesely",
"author_id": 10035985,
"author_profile": "https://Stackoverflow.com/users/10035985",
"pm_score": 1,
"selected": false,
"text": "re title rows = [\n [\"movieId\", \"title\", \"genres\"],\n [\"1\", \"Toy Story (1995)\", \"Adventure|Animation|Children|Comedy|Fantasy\"],\n [\"2\", \"Jumanji (1995)\", \"Adventure|Children|Fantasy\"],\n [\"3\", \"Grumpier Old Men (1995)\", \"Comedy|Romance\"],\n [\"4\", \"Waiting to Exhale (1995)\", \"Comedy|Drama|Romance\"],\n [\"5\", \"Father of the Bride Part II (1995)\", \"Comedy\"],\n [\"6\", \"Heat (1995)\", \"Action|Crime|Thriller\"],\n [\"7\", \"Sabrina (1995)\", \"Comedy|Romance\"],\n [\"8\", \"Tom and Huck (1995)\", \"Adventure|Children\"],\n [\"9\", \"Sudden Death (1995)\", \"Action\"],\n [\"10\", \"GoldenEye (1995)\", \"Action|Adventure|Thriller\"],\n]\n\nimport re\n\npat = re.compile(r\"\\((\\d{4})\\)\")\n\nfor movie_id, title, genres in rows[1:]:\n year = pat.search(title)\n print([movie_id, title, genres, year.group(1) if year else \"N/A\"])\n ['1', 'Toy Story (1995)', 'Adventure|Animation|Children|Comedy|Fantasy', '1995']\n['2', 'Jumanji (1995)', 'Adventure|Children|Fantasy', '1995']\n['3', 'Grumpier Old Men (1995)', 'Comedy|Romance', '1995']\n['4', 'Waiting to Exhale (1995)', 'Comedy|Drama|Romance', '1995']\n['5', 'Father of the Bride Part II (1995)', 'Comedy', '1995']\n['6', 'Heat (1995)', 'Action|Crime|Thriller', '1995']\n['7', 'Sabrina (1995)', 'Comedy|Romance', '1995']\n['8', 'Tom and Huck (1995)', 'Adventure|Children', '1995']\n['9', 'Sudden Death (1995)', 'Action', '1995']\n['10', 'GoldenEye (1995)', 'Action|Adventure|Thriller', '1995']\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20563918/"
] |
74,520,638
|
<p>I am trying to save random numbers in an array</p>
<p>I have tried this bot it gives me an error (A constant value is expected Code CS0150)</p>
<p>`</p>
<pre><code>int x = 0;
Random rnd = new Random();
int[] cards;
while (x != 5)
{
cards =new int[x] { rnd.Next() };
Console.WriteLine(cards[x]);
x++;
}
</code></pre>
<p>`</p>
|
[
{
"answer_id": 74520697,
"author": "MakePeaceGreatAgain",
"author_id": 2528063,
"author_profile": "https://Stackoverflow.com/users/2528063",
"pm_score": 1,
"selected": false,
"text": "cards[x] = rnd.Next() int[] cards = new int[5] int x = 0;\n\nRandom rnd = new Random();\nint[] cards = new int[5];\nwhile (x != 5)\n{\n cards[x] = rnd.Next();\n Console.WriteLine(cards[x]);\n x++;\n}\n"
},
{
"answer_id": 74520907,
"author": "Nikeodeam",
"author_id": 15401598,
"author_profile": "https://Stackoverflow.com/users/15401598",
"pm_score": 0,
"selected": false,
"text": "int x = 0;\n\nRandom rnd = new Random();\nList<int> cards = new List<int>();\nwhile (x != 5)\n{\n cards.Add(rnd.Next()); \n Console.WriteLine(cards[x]);\n x++;\n}\n"
},
{
"answer_id": 74521886,
"author": "Idle_Mind",
"author_id": 2330053,
"author_profile": "https://Stackoverflow.com/users/2330053",
"pm_score": 0,
"selected": false,
"text": "List<> Count Random rnd = new Random();\nList<int> cards = new List<int>();\nwhile (cards.Count < 5)\n{\n cards.Add(rnd.Next());\n Console.WriteLine(cards[cards.Count-1]);\n}\n Array for Length Random rnd = new Random();\nint[] cards = new int[5];\nfor(int x=0; x<cards.Length; x++)\n{\n cards[x] = rnd.Next();\n Console.WriteLine(cards[x]);\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15401598/"
] |
74,520,644
|
<p>I'm facing issue with tensorboard loading in Google Colab. I tried to uninstall and then install it again but no sucess. i'm sharing the code and the error.</p>
<pre><code>!pip install tensorboard
</code></pre>
<pre><code>%load_ext tensorboard
</code></pre>
<pre><code>log_folder = 'log1'
</code></pre>
<pre><code>callbacks = TensorBoard(log_dir= log_folder, histogram_freq= 1)
</code></pre>
<pre><code>model.fit(train_X, train_y, validation_data = (test_X, test_y),callbacks= callbacks,verbose= 0, epochs = 20)
</code></pre>
<pre><code>%tensorboard --logdir = '/content/log1' I tried withour quotes as well i.e /content/log1
</code></pre>
<p><a href="https://i.stack.imgur.com/9ioxa.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I tried to load tensorboard and tried Uninstall and then reinstall</p>
|
[
{
"answer_id": 74520739,
"author": "TQCH",
"author_id": 12568022,
"author_profile": "https://Stackoverflow.com/users/12568022",
"pm_score": 2,
"selected": false,
"text": "--logdir <PATH> --logdir log1"
},
{
"answer_id": 74520947,
"author": "Jirayu Kaewprateep",
"author_id": 7848579,
"author_profile": "https://Stackoverflow.com/users/7848579",
"pm_score": 0,
"selected": false,
"text": "import os\nfrom os.path import exists\n\nimport tensorflow as tf\nimport tensorflow_io as tfio\n\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nVariables\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nPATH = os.path.join('F:\\\\datasets\\\\downloads\\\\Actors\\\\train\\\\Pikaploy', '*.tif')\nPATH_2 = os.path.join('F:\\\\datasets\\\\downloads\\\\Actors\\\\train\\\\Candidt Kibt', '*.tif')\nfiles = tf.data.Dataset.list_files(PATH)\nfiles_2 = tf.data.Dataset.list_files(PATH_2)\n\nlist_file = []\nlist_file_actual = []\nlist_label = []\nlist_label_actual = [ 'Pikaploy', 'Pikaploy', 'Pikaploy', 'Pikaploy', 'Pikaploy', 'Candidt Kibt', 'Candidt Kibt', 'Candidt Kibt', 'Candidt Kibt', 'Candidt Kibt' ]\nlist_image_greyscales = []\nfor file in files.take(5):\n image = tf.io.read_file( file )\n image = tfio.experimental.image.decode_tiff(image, index=0)\n list_file_actual.append(image)\n image = tf.image.resize(image, [32,32], method='nearest')\n list_file.append(image)\n list_image_greyscales.append(tf.image.rgb_to_grayscale(image[:,:,0:3]))\n list_label.append(1)\n \nfor file in files_2.take(5):\n image = tf.io.read_file( file )\n image = tfio.experimental.image.decode_tiff(image, index=0)\n list_file_actual.append(image)\n image = tf.image.resize(image, [32,32], method='nearest')\n list_file.append(image)\n list_image_greyscales.append(tf.image.rgb_to_grayscale(image[:,:,0:3]))\n list_label.append(9)\n \ncheckpoint_path = \"F:\\\\models\\\\checkpoint\\\\\" + os.path.basename(__file__).split('.')[0] + \"\\\\TF_DataSets_01.h5\"\nlog_dir = os.path.dirname(checkpoint_path)\n \n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nDataSet\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\ndataset = tf.data.Dataset.from_tensor_slices((tf.constant(tf.cast(list_file, dtype=tf.int64), shape=(10, 1, 32, 32, 4), dtype=tf.int64),tf.constant(list_label, shape=(10, 1, 1), dtype=tf.int64)))\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Callback\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\ntb_callback = tf.keras.callbacks.TensorBoard(log_dir, update_freq=1, histogram_freq=1)\n\nclass custom_callback(tf.keras.callbacks.Callback):\n def on_epoch_end(self, epoch, logs={}):\n if( logs['accuracy'] >= 0.95 ):\n self.model.stop_training = True\n \ncustom_callback = custom_callback()\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Model Initialize\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.InputLayer(input_shape=( 32, 32, 4 )),\n tf.keras.layers.Normalization(mean=3., variance=2.),\n tf.keras.layers.Normalization(mean=4., variance=6.),\n tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),\n tf.keras.layers.MaxPooling2D((2, 2)),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Reshape((128, 225)),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(96, return_sequences=True, return_state=False)),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(96)),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(192, activation='relu'),\n tf.keras.layers.Dense(10),\n])\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Optimizer\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\noptimizer = tf.keras.optimizers.Nadam(\n learning_rate=0.00001, beta_1=0.9, beta_2=0.999, epsilon=1e-07,\n name='Nadam'\n)\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Loss Fn\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" \nlossfn = tf.keras.losses.SparseCategoricalCrossentropy(\n from_logits=False,\n reduction=tf.keras.losses.Reduction.AUTO,\n name='sparse_categorical_crossentropy'\n)\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Model Summary\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nmodel.compile(optimizer=optimizer, loss=lossfn, metrics=['accuracy'])\n\n# Creates a file writer for the log directory.\nfile_writer = tf.summary.create_file_writer(log_dir + \"\\\\\" + datetime.now().strftime(\"%Y%m%d-%H%M%S\") )\n\n# Using the file writer, log the reshaped image.\nwith file_writer.as_default():\n for i in range(10):\n tf.summary.image(\"Training data\", tf.constant( list_image_greyscales[i], shape=(1,32,32,1) ), step=i)\n tf.summary.scalar(\"Training data label\", data=float(i), step=i)\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Training\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nhistory = model.fit( dataset, batch_size=100, epochs=10, callbacks=[tb_callback, custom_callback] )\nmodel.save_weights(checkpoint_path)\n\nplt.figure(figsize=(5,2))\nplt.title(\"Actors recognitions\")\nfor i in range(len(list_file)):\n img = tf.keras.preprocessing.image.array_to_img(\n list_file[i],\n data_format=None,\n scale=True\n )\n img_array = tf.keras.preprocessing.image.img_to_array(img)\n img_array = tf.expand_dims(img_array, 0)\n predictions = model.predict(img_array)\n score = tf.nn.softmax(predictions[0])\n plt.subplot(5, 2, i + 1)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n plt.imshow(list_file_actual[i])\n plt.xlabel(str(round(score[tf.math.argmax(score).numpy()].numpy(), 2)) + \":\" + str(list_label_actual[tf.math.argmax(score)]))\n \nplt.show()\n\ninput('...')\n\n### tensorboard --logdir=\"F:\\models\\checkpoint\\test_tf_tensorboard_2\\\\\"\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17765799/"
] |
74,520,666
|
<p>Is there a short form for accessing dictionary values in for loop in Python?</p>
<p>I have the following example code:</p>
<pre><code>dict = [{"name": "testdata"}, {"name": "testdata2"}]
for x in dict:
print(x["name"])
</code></pre>
<p>Is there a way to write the dictionary key directly into the line of the for loop, e.g.</p>
<pre><code>dict = [{"name": "testdata"}, {"name": "testdata2"}]
for x in dict["name"]:
print(x)
</code></pre>
<p>which obviously does not work. But the main idea is that x should already be the string "testdata" or "testdata2". I want to avoid this:</p>
<pre><code>dict = [{"name": "testdata"}, {"name": "testdata2"}]
for x in dict:
x = x["name"]
</code></pre>
|
[
{
"answer_id": 74520722,
"author": "deceze",
"author_id": 476,
"author_profile": "https://Stackoverflow.com/users/476",
"pm_score": 2,
"selected": true,
"text": "for x in (i['name'] for i in dict):\n ...\n from operator import itemgetter\n\nfor x in map(itemgetter('name'), dict):\n ...\n"
},
{
"answer_id": 74520825,
"author": "Martin Wettstein",
"author_id": 13969611,
"author_profile": "https://Stackoverflow.com/users/13969611",
"pm_score": 0,
"selected": false,
"text": "'name' dict = [{\"name\": \"testdata\"}, {\"name\": \"testdata2\"}]\n\nfor name in [x[\"name\"] for x in dict]:\n print(name)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19275581/"
] |
74,520,686
|
<p>Epsilon is the smallest value in a number encoding scheme that can be added to <code>1</code> to generate a number that has a distinctly different representation.</p>
<p>Can anyone help me intuit why the loss of precision is greater in the latter example here? </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>console.log(Number.EPSILON > (0.1 + 0.2 - 0.3)) // true</code></pre>
</div>
</div>
</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>console.log(Number.EPSILON > (10000.1 + 10000.2 - 20000.3)) // false</code></pre>
</div>
</div>
</p>
<p>Is it that the significand required to exactly represent many easily-written decimal numbers is larger than the 52 bits available, and that therefore an inaccuracy is introduced by truncation. This inaccuracy is then multiplied by the exponent, and if the exponent is large, the inaccuracy is magnified?</p>
|
[
{
"answer_id": 74520844,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 0,
"selected": false,
"text": "console.log((10000.1 + 10000.2 - 20000.3) / Number.EPSILON)\n// > 16384 \nconsole.log((0.1 + 0.2 - 0.3) / Number.EPSILON)\n// > 0.25\n"
},
{
"answer_id": 74520979,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 2,
"selected": false,
"text": "2.2204460492503130808472633361816E-16 2-52 0.1 + 0.2 - 0.3 10.1 + 10.2 - 10.3 100.1 + 100.2 - 200.3 console.log(Number.EPSILON > (100.1 + 100.2 - 200.3)); // true console.log(Number.EPSILON > (1000.1 + 1000.2 - 2000.3)); // false 100000000.1 -0.1 100000000.1 100000000"
},
{
"answer_id": 74523073,
"author": "Ben Aston",
"author_id": 38522,
"author_profile": "https://Stackoverflow.com/users/38522",
"pm_score": 0,
"selected": false,
"text": "20 10 0.2 0.2 0 . 1 1 1 1 1 1 1 1 1 1\n 1/2 1/4 1/8 1/16 1/32 1/64 1/128 1/256 1/512 1/1024\n Binary Value | Remainder in Base Ten\n | 0.2 \n 0.001 | 0.2 - (1/8) = 0.075 \n 0.0011 | 0.075 - (1/16) = 0.0125 \n 0.0011001 | 0.0125 - (1/128) = 0.0046875\n 0.00110011 | 0.0046875 - (1/256) = 0.00078125\n 0.00110011001 | 0.00078125 - (1/2048) = 0.00048828125\n 0.001100110011 | 0.00048828125 - (1/4096) = 0.000244140625\n ...and so on, in a recurring pattern, forever\n Number"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38522/"
] |
74,520,745
|
<p>I have several images and I want to make a presentation like on Facebook, by unwinding the images on the previous ones :</p>
<p><a href="https://i.stack.imgur.com/THdGM.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>Here are my images, they are with a View Drupal 9 block :</p>
<p><a href="https://i.stack.imgur.com/Cc7K0.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I created the following CSS :</p>
<pre><code>.block-views-blockgroup-subscribers-block-1 .view-content {
display: flex;
flex-direction: row;
position: relative;
}
.block-views-blockgroup-subscribers-block-1 .views-field-user-picture img {
border: 2px solid #f7f9fa;
border-radius: 50%;
transform: translateX(-25%);
}
</code></pre>
<p>But it doesn't work because the images are not displayed on top of the previous image.</p>
<p>How to overflow the images on the previous ones ?</p>
|
[
{
"answer_id": 74520844,
"author": "Dimava",
"author_id": 5734961,
"author_profile": "https://Stackoverflow.com/users/5734961",
"pm_score": 0,
"selected": false,
"text": "console.log((10000.1 + 10000.2 - 20000.3) / Number.EPSILON)\n// > 16384 \nconsole.log((0.1 + 0.2 - 0.3) / Number.EPSILON)\n// > 0.25\n"
},
{
"answer_id": 74520979,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 2,
"selected": false,
"text": "2.2204460492503130808472633361816E-16 2-52 0.1 + 0.2 - 0.3 10.1 + 10.2 - 10.3 100.1 + 100.2 - 200.3 console.log(Number.EPSILON > (100.1 + 100.2 - 200.3)); // true console.log(Number.EPSILON > (1000.1 + 1000.2 - 2000.3)); // false 100000000.1 -0.1 100000000.1 100000000"
},
{
"answer_id": 74523073,
"author": "Ben Aston",
"author_id": 38522,
"author_profile": "https://Stackoverflow.com/users/38522",
"pm_score": 0,
"selected": false,
"text": "20 10 0.2 0.2 0 . 1 1 1 1 1 1 1 1 1 1\n 1/2 1/4 1/8 1/16 1/32 1/64 1/128 1/256 1/512 1/1024\n Binary Value | Remainder in Base Ten\n | 0.2 \n 0.001 | 0.2 - (1/8) = 0.075 \n 0.0011 | 0.075 - (1/16) = 0.0125 \n 0.0011001 | 0.0125 - (1/128) = 0.0046875\n 0.00110011 | 0.0046875 - (1/256) = 0.00078125\n 0.00110011001 | 0.00078125 - (1/2048) = 0.00048828125\n 0.001100110011 | 0.00048828125 - (1/4096) = 0.000244140625\n ...and so on, in a recurring pattern, forever\n Number"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20563401/"
] |
74,520,746
|
<p>Taking a json file as input such as:</p>
<pre class="lang-json prettyprint-override"><code>{"computers":
[{"host":"example",
"platform":"some_platform",
"status":
{"working":"yes",
"display":["no"]},
"description":""
}]
}
</code></pre>
<p>...how can this be flattened to this form:</p>
<pre class="lang-json prettyprint-override"><code>{"computers":
"host":"example",
"platform":"some_platform",
"working":"yes",
"display":"no",
"description":""
}
</code></pre>
<p>ie. the status element has been flattened, the square brackets in <code>"display":["no"]</code> have been removed, and the square brackets around <code>"computers":[...]</code> have been removed.</p>
<p>I have so far tried using flatten in multiple ways, eg.:</p>
<pre><code>cat ./output.json | jq '.computers|.[]|.status|flatten'
</code></pre>
<p>but this only outputs the flattened version of the contents of the status element. I cannot work out how to replace the contents with the flattened version.</p>
|
[
{
"answer_id": 74520851,
"author": "0stone0",
"author_id": 5625547,
"author_profile": "https://Stackoverflow.com/users/5625547",
"pm_score": 0,
"selected": false,
"text": "computers .computers |= (first | . + .status | del(.status) | (.display |= join(.)))\n .computers first .status del() .status join() .display {\n \"computers\": {\n \"host\": \"example\",\n \"platform\": \"some_platform\",\n \"description\": \"\",\n \"working\": \"yes\",\n \"display\": \"no\"\n }\n}\n computer first last .computers |= (last | . + .status | del(.status) | (.display |= join(.)))\n map() add .computers |= (map(. + .status | del(.status) | (.display |= join(.))) | add)\n"
},
{
"answer_id": 74521116,
"author": "knittl",
"author_id": 112968,
"author_profile": "https://Stackoverflow.com/users/112968",
"pm_score": 0,
"selected": false,
"text": ".computers\n| first\n| { host, platform, description }\n+ (.status | .display |= first)\n| { computers: . }\n .computers\n| first\n| del(.status) + (.status | .display |= first)\n| { computers: . }\n {\n computers: (\n .computers[0] | del(.status) + (.status | .display |= first)\n )\n}\n {\n \"computers\": {\n \"host\": \"example\",\n \"platform\": \"some_platform\",\n \"description\": \"\",\n \"working\": \"yes\",\n \"display\": \"no\"\n }\n}\n .computers |= (first | del(.status) + (.status | .display |= first))\n"
},
{
"answer_id": 74524391,
"author": "pmf",
"author_id": 2158479,
"author_profile": "https://Stackoverflow.com/users/2158479",
"pm_score": 1,
"selected": false,
"text": "scalars .computers |= ([paths(scalars) as $p | {($p | map(strings)[-1]): getpath($p)}] | add)\n {\n \"computers\": {\n \"host\": \"example\",\n \"platform\": \"some_platform\",\n \"working\": \"yes\",\n \"display\": \"no\",\n \"description\": \"\"\n }\n}\n .computers .display"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20563943/"
] |
74,520,790
|
<p>I found some nice solutions here:</p>
<p><a href="https://stackoverflow.com/questions/73339847/how-to-create-on-click-popup-which-includes-plots-using-ipyleaflet-folium-or-ge">How to create on click popup which includes plots using ipyleaflet, Folium or Geemap?</a></p>
<p>which potentially would allow me to assign more things to the marker when it's clicked. In my situation I have a lot of circles assigned to the marker, but they appear all which doesn't look well.</p>
<p><a href="https://i.stack.imgur.com/kCe2v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kCe2v.png" alt="enter image description here" /></a></p>
<p>I need the <code>folium.Circle</code> populated at the moment when I click on the marker. It could appear along with the pop-up information.</p>
<p>My code looks as follows:</p>
<pre><code>fm = folium.Marker(
location=[lat,lng],
popup=folium.Popup(max_width=450).add_child(
folium.Circle(
[lat,lng],
radius=10,
fill=True,
weight=0.2)),
icon = folium.Icon(color='darkpurple', icon='glyphicon-briefcase'))
map.add_child(fm)
</code></pre>
<p>Unfortunately, it doesn't work, as my map comes without some features:</p>
<p><a href="https://i.stack.imgur.com/z5oi0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z5oi0.jpg" alt="enter image description here" /></a></p>
<p>Despite no error from Python's console side, I have an error in the map console</p>
<p><strong>Uncaught TypeError: Cannot read properties of undefined (reading 'addLayer')
at i.addTo (leaflet.js:5:64072)</strong></p>
<p>and I have no faintest idea how to solve it</p>
<p>Is there any option of making my circle populated just when clicked on the marker?</p>
|
[
{
"answer_id": 74520851,
"author": "0stone0",
"author_id": 5625547,
"author_profile": "https://Stackoverflow.com/users/5625547",
"pm_score": 0,
"selected": false,
"text": "computers .computers |= (first | . + .status | del(.status) | (.display |= join(.)))\n .computers first .status del() .status join() .display {\n \"computers\": {\n \"host\": \"example\",\n \"platform\": \"some_platform\",\n \"description\": \"\",\n \"working\": \"yes\",\n \"display\": \"no\"\n }\n}\n computer first last .computers |= (last | . + .status | del(.status) | (.display |= join(.)))\n map() add .computers |= (map(. + .status | del(.status) | (.display |= join(.))) | add)\n"
},
{
"answer_id": 74521116,
"author": "knittl",
"author_id": 112968,
"author_profile": "https://Stackoverflow.com/users/112968",
"pm_score": 0,
"selected": false,
"text": ".computers\n| first\n| { host, platform, description }\n+ (.status | .display |= first)\n| { computers: . }\n .computers\n| first\n| del(.status) + (.status | .display |= first)\n| { computers: . }\n {\n computers: (\n .computers[0] | del(.status) + (.status | .display |= first)\n )\n}\n {\n \"computers\": {\n \"host\": \"example\",\n \"platform\": \"some_platform\",\n \"description\": \"\",\n \"working\": \"yes\",\n \"display\": \"no\"\n }\n}\n .computers |= (first | del(.status) + (.status | .display |= first))\n"
},
{
"answer_id": 74524391,
"author": "pmf",
"author_id": 2158479,
"author_profile": "https://Stackoverflow.com/users/2158479",
"pm_score": 1,
"selected": false,
"text": "scalars .computers |= ([paths(scalars) as $p | {($p | map(strings)[-1]): getpath($p)}] | add)\n {\n \"computers\": {\n \"host\": \"example\",\n \"platform\": \"some_platform\",\n \"working\": \"yes\",\n \"display\": \"no\",\n \"description\": \"\"\n }\n}\n .computers .display"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6694814/"
] |
74,520,801
|
<p>Derived from previous question here (<a href="https://stackoverflow.com/questions/74500427/format-authors-name-with-stringr">Format author's name with stringr</a>), I would like to edit a whole variable with different strings.</p>
<p>Previous solution doesn't work as it repeats all strings to each one.</p>
<pre class="lang-r prettyprint-override"><code>library(dplyr)
x <- data.frame(
names = c("Daenerys Targaryen, George R. R. Martin, Luís Inácio Lula da Silva",
"Hadley Alexander Wickham, Joseph J. Allaire",
"Stack Overflow"
)
)
format_names <- function(variable) {
variable %>%
strsplit(", ") %>%
unlist() %>%
gsub("(.*?) (\\w+$)", "\\U\\2\\E, \\1", ., perl = TRUE) %>%
gsub(" ([A-Z])\\w*\\.?", " \\1.", .) %>%
paste(collapse = "; ")
}
x %>%
mutate(new_names = format_names(names))
#> names
#> 1 Daenerys Targaryen, George R. R. Martin, Luís Inácio Lula da Silva
#> 2 Hadley Alexander Wickham, Joseph J. Allaire
#> 3 Stack Overflow
#> new_names
#> 1 TARGARYEN, D.; MARTIN, G. R. R.; SILVA, L. I. L. da; WICKHAM, H. A.; ALLAIRE, J. J.; OVERFLOW, S.
#> 2 TARGARYEN, D.; MARTIN, G. R. R.; SILVA, L. I. L. da; WICKHAM, H. A.; ALLAIRE, J. J.; OVERFLOW, S.
#> 3 TARGARYEN, D.; MARTIN, G. R. R.; SILVA, L. I. L. da; WICKHAM, H. A.; ALLAIRE, J. J.; OVERFLOW, S.
</code></pre>
<p><sup>Created on 2022-11-21 with <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex v2.0.2</a></sup></p>
|
[
{
"answer_id": 74520850,
"author": "MrFlick",
"author_id": 2372064,
"author_profile": "https://Stackoverflow.com/users/2372064",
"pm_score": 3,
"selected": true,
"text": "unlist() sapply format_names <- function(variable) {\n variable %>%\n strsplit(\", \") %>%\n sapply(. %>% \n gsub(\"(.*?) (\\\\w+$)\", \"\\\\U\\\\2\\\\E, \\\\1\", ., perl = TRUE) %>%\n gsub(\" ([A-Z])\\\\w*\\\\.?\", \" \\\\1.\", .) %>%\n paste(collapse = \"; \"))\n}\n"
},
{
"answer_id": 74520869,
"author": "Ruam Pimentel",
"author_id": 13015865,
"author_profile": "https://Stackoverflow.com/users/13015865",
"pm_score": 2,
"selected": false,
"text": "rowwise() dplyr groub_by(names) rowwise() rowwise() dplyr library(dplyr)\n\nx %>% \n rowwise() %>% \n mutate(new_names = format_names(names))\n # A tibble: 3 × 2\n# Rowwise: \n names new_names \n <chr> <chr> \n1 Daenerys Targaryen, George R. R. Martin, Luís Inácio Lula da Silva TARGARYEN, D.; MARTIN, G. …\n2 Hadley Alexander Wickham, Joseph J. Allaire WICKHAM, H. A.; ALLAIRE, J…\n3 Stack Overflow OVERFLOW, S. \n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15611828/"
] |
74,520,805
|
<p>This run gets me every first appearance of an object with certain conditions.</p>
<p>I run this code 900 times in a application run. It takes 10 minutes for 300.000 objects.
I need to run it with a lot more objects (> 10 million objects) So it'll take a really long time.</p>
<p>This is the best code I could do:</p>
<pre><code>string PlayerUrl { get; }
Position Position { get; }
public enum Position
{
GK,
...
}
int ChemistryAmount { get; }
</code></pre>
<pre><code>public static List<IFieldPlayerStatsForPosition> GetFirstFieldPlayerStatsForPositionInList(List<IFieldPlayerStatsForPosition> auxFieldPlayerStatsForPositions)
{
List<IFieldPlayerStatsForPosition> fieldPlayerStatsForPositions = new List<IFieldPlayerStatsForPosition>();
foreach (IFieldPlayerStatsForPosition fieldPlayerStatsForPosition in auxFieldPlayerStatsForPositions)
{
if (!fieldPlayerStatsForPositions.Any(cc => fieldPlayerStatsForPosition.FieldPlayerChemistryApplied.FieldPlayer.PlayerUrl == cc.FieldPlayerChemistryApplied.FieldPlayer.PlayerUrl &&
fieldPlayerStatsForPosition.Position == cc.Position &&
fieldPlayerStatsForPosition.FieldPlayerChemistryApplied.ChemistryAmount == cc.FieldPlayerChemistryApplied.ChemistryAmount))
{
fieldPlayerStatsForPositions.Add(fieldPlayerStatsForPosition);
}
}
return fieldPlayerStatsForPositions;
}
</code></pre>
<p>I need to make it faster... What should I do?
Is there a faster alternative to a foreach and Linq.Any?</p>
|
[
{
"answer_id": 74521055,
"author": "theemee",
"author_id": 14299113,
"author_profile": "https://Stackoverflow.com/users/14299113",
"pm_score": 3,
"selected": true,
"text": "public class FieldPlayerStatsForPositionComparer : IEqualityComparer<IFieldPlayerStatsForPosition> {\n public bool Equals(IFieldPlayerStatsForPosition x, IFieldPlayerStatsForPosition y) {\n if (ReferenceEquals(x, y))\n return true;\n if (ReferenceEquals(x, null))\n return false;\n if (ReferenceEquals(y, null))\n return false;\n if (x.GetType() != y.GetType())\n return false;\n return x.PlayerUrl == y.PlayerUrl && x.Position == y.Position && x.ChemistryAmount == y.ChemistryAmount;\n }\n\n public int GetHashCode(IFieldPlayerStatsForPosition obj) {\n return HashCode.Combine(obj.PlayerUrl, (int)obj.Position, obj.ChemistryAmount);\n }\n}\n\npublic static List<IFieldPlayerStatsForPosition> GetFirstFieldPlayerStatsForPositionInList(List<IFieldPlayerStatsForPosition> auxFieldPlayerStatsForPositions)\n{\n var fieldPlayerStatsForPositions = new HashSet<IFieldPlayerStatsForPosition>(auxFieldPlayerStatsForPositions, new FieldPlayerStatsForPositionComparer());\n return fieldPlayerStatsForPositions.ToList();\n}\n public static IEnumerable<IFieldPlayerStatsForPosition> GetFirstFieldPlayerStatsForPositionInList(IEnumerable<IFieldPlayerStatsForPosition> auxFieldPlayerStatsForPositions) {\n return auxFieldPlayerStatsForPositions.Distinct(new FieldPlayerStatsForPositionComparer());\n}\n public static ICollection<IFieldPlayerStatsForPosition> GetFirstFieldPlayerStatsForPositionInList(IEnumerable<IFieldPlayerStatsForPosition> auxFieldPlayerStatsForPositions) {\n return new HashSet<IFieldPlayerStatsForPosition>(auxFieldPlayerStatsForPositions, new FieldPlayerStatsForPositionComparer());\n}\n BenchmarkDotNet"
},
{
"answer_id": 74521144,
"author": "Kilarn123",
"author_id": 11271840,
"author_profile": "https://Stackoverflow.com/users/11271840",
"pm_score": 1,
"selected": false,
"text": "public static List<IFieldPlayerStatsForPosition> GetFirstFieldPlayerStatsForPositionInList(List<IFieldPlayerStatsForPosition> auxFieldPlayerStatsForPositions)\n{\n return auxFieldPlayerStatsForPositions.DistinctBy(p => new \n { \n p.FieldPlayerChemistryApplied.FieldPlayer.PlayerUrl,\n p.Position,\n p.FieldPlayerChemistryApplied.ChemistryAmount\n }).ToList();\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20561972/"
] |
74,520,838
|
<p>Basically I have a function is my child component, I would like to pass this function as a prop and call it my parent component.</p>
<pre><code> function parent() {
return (
<div>
<button onclick={handleAbort}></button>
</div>
);
}
function child() {
const handleAbort=() =>{
console.log('hello')
}
return (
<div>
</div>
);
}
</code></pre>
|
[
{
"answer_id": 74520941,
"author": "damonholden",
"author_id": 17670742,
"author_profile": "https://Stackoverflow.com/users/17670742",
"pm_score": 0,
"selected": false,
"text": "const handleAbort = () => {\n console.log('hello');\n};\n\nfunction parent() {\n return (\n <div>\n <button onclick={handleAbort}></button>\n </div>\n );\n}\n\nfunction child() {\n return <div></div>;\n}\n"
},
{
"answer_id": 74521007,
"author": "Tomer_Ra",
"author_id": 11971765,
"author_profile": "https://Stackoverflow.com/users/11971765",
"pm_score": 0,
"selected": false,
"text": "function Parent() {\n\n const handleAbort=() =>{\n console.log('hello')\n }\n\n return (\n <div>\n <Child handleClick={handleAbort} />\n </div>\n );\n}\n\n\nfunction Child({handleClick}) {\n\n return (\n <div>\n <button onClick={handleClick}></button>\n </div>\n );\n}\n"
},
{
"answer_id": 74521141,
"author": "andy mccullough",
"author_id": 1849358,
"author_profile": "https://Stackoverflow.com/users/1849358",
"pm_score": 0,
"selected": false,
"text": "function Parent() {\n const handleAbortClick = (msg) => (e) => {\n console.log(msg)\n }\n return (\n <div>\n <Child onAbortClick={handleAbortClick} />\n </div>\n );\n}\n\n\n function Child({ onAbortClick }) { \n return (\n <div>\n <button onClick={onAbortClick('hello')}>Click me</button>\n </div>\n );\n}\n"
},
{
"answer_id": 74521934,
"author": "Tami",
"author_id": 20277199,
"author_profile": "https://Stackoverflow.com/users/20277199",
"pm_score": 1,
"selected": false,
"text": "function Parent() {\n return (\n <div>\n <Child dataToParent={(msg) => console.log(msg)} />\n </div>\n );\n}\n\n\n function Child({dataToParent}) {\n\n const handleAbort=() =>{\n dataToParent('hello')\n }\n return (\n <div>\n <button onclick={handleAbort}></button>\n </div>\n );\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20061856/"
] |
74,520,840
|
<p>I have a maximum of quantity on a value and i want to see all the number on my dropdown</p>
<p>for exemple my quantity is</p>
<p>const quantity= 10</p>
<p>i want to create a function which pushed [1,2,3,4,5,6,7,8,9,10] on an array.</p>
<p>I'm working with react native</p>
|
[
{
"answer_id": 74520879,
"author": "Abbas Shaikh",
"author_id": 12667283,
"author_profile": "https://Stackoverflow.com/users/12667283",
"pm_score": -1,
"selected": false,
"text": "\n function createArray(len){\n let arr = [] \n for(let i = 0 ; i < len;i++){\n arr.push(i + 1);\n }\n return arr\n }\n \n let qty = 10\n console.log(createArray(qty))\n\n"
},
{
"answer_id": 74520884,
"author": "ray",
"author_id": 636077,
"author_profile": "https://Stackoverflow.com/users/636077",
"pm_score": 2,
"selected": false,
"text": "const arr = Array.from({ length: 10 }, (_, i) => i + 1);\nconsole.log(arr);"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15220357/"
] |
74,520,865
|
<p>I have a rectangle defined by 4 points. I want to move it to the left or right by specific distance. By moving I mean that result rectangle should be parallel to the original and if we put straights through corresponding points we will get rectangular cuboid.</p>
<p>On an image I am given coordinates of points A,B,C,D and distance H.
How can I calculate 4 new points using Three.js?
<a href="https://i.stack.imgur.com/1O1F4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1O1F4.png" alt="Dedede" /></a></p>
<p>I guess it has something to do with projection, but I couldn't find an easy way to do it.</p>
|
[
{
"answer_id": 74523952,
"author": "prisoner849",
"author_id": 4045502,
"author_profile": "https://Stackoverflow.com/users/4045502",
"pm_score": 1,
"selected": false,
"text": "body{\n overflow: hidden;\n margin: 0;\n} <script type=\"module\">\nimport * as THREE from \"https://cdn.skypack.dev/three@0.136.0\";\nimport { OrbitControls } from \"https://cdn.skypack.dev/three@0.136.0/examples/jsm/controls/OrbitControls\";\n\nlet scene = new THREE.Scene();\nlet camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000);\ncamera.position.set(0, 5, 5);\nlet renderer = new THREE.WebGLRenderer({ antialias: true });\nrenderer.setSize(innerWidth, innerHeight);\ndocument.body.appendChild(renderer.domElement);\n\nlet controls = new OrbitControls(camera, renderer.domElement);\ncontrols.enableDamping = true;\ncontrols.enablePan = false;\n\nscene.add(new THREE.GridHelper());\n\nlet dir = new THREE.Vector3(0, 0, 1);\nlet colors = [];\nlet ptsBase = [\n [-1, 1], [1, 1], [1, -1], [-1, -1]\n].map(p => {\n colors.push(0, 1, 1);\n return new THREE.Vector3(p[0], p[1], 0);\n});\n\nlet ptsShift = ptsBase.map(p => {\n colors.push(1, 1, 0);\n return p.clone().addScaledVector(dir, 2)\n});\nlet ptsFinal = ptsBase.concat(ptsShift);\n\nlet g = new THREE.BufferGeometry().setFromPoints(ptsFinal);\ng.setIndex([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);\ng.setAttribute(\"color\", new THREE.Float32BufferAttribute(colors, 3));\nlet m = new THREE.LineBasicMaterial({vertexColors: true});\nlet l = new THREE.LineSegments(g, m);\nscene.add(l);\n\nrenderer.setAnimationLoop(() => {\n controls.update();\n renderer.render(scene, camera);\n});\n\n</script>"
},
{
"answer_id": 74529571,
"author": "QwertyKeker",
"author_id": 9740343,
"author_profile": "https://Stackoverflow.com/users/9740343",
"pm_score": 0,
"selected": false,
"text": "let pointA = new THREE.Vector3(0, 0, 0);\nlet pointB = new THREE.Vector3(1, 0, 0);\nlet pointC = new THREE.Vector3(1, 1, 0);\nlet pointD = new THREE.Vector3(0, 1, 0);\nconst distance = 0.5;\n\nlet triangle = new THREE.Triangle(pointA, pointB, pointC);\n\nlet plane = new THREE.Plane();\ntriangle.getPlane(plane);\n\nlet normalVector = plane.normal.multiplyScalar(distance);\n\npointA1 = pointA.clone().add(normalVector);\npointB1 = pointB.clone().add(normalVector);\npointC1 = pointC.clone().add(normalVector);\npointD1 = pointD.clone().add(normalVector);\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9740343/"
] |
74,520,885
|
<p>A sample dataframe:</p>
<pre><code>data = {
"col_A": ["a","a","b","c"],
"col_B": [1, 2, 2, 3],
"col_C": ["demo", "demo", "demo", "demo"]
}
df = pd.DataFrame(data)
</code></pre>
<p>Dataframe</p>
<pre><code>col_A col_B col_C
a 1 demo
a 2 demo
b 2 demo
c 3 demo
</code></pre>
<p>I can easily check if all values in <code>col_A</code> are unique or not by <code>df['col_A'].is_unique</code>.
Is there any way to check for two columns i.e. something like <code>df['col_A', 'col_B'].is_unique</code></p>
<p>If <code>col_A</code> and <code>col_B</code> are the composite key of the data frame or not?</p>
|
[
{
"answer_id": 74520953,
"author": "Rabinzel",
"author_id": 15521392,
"author_profile": "https://Stackoverflow.com/users/15521392",
"pm_score": 3,
"selected": true,
"text": "is_unique df.set_index(['col_A', 'col_B']).index.is_unique\n\n#True\n"
},
{
"answer_id": 74520965,
"author": "ansev",
"author_id": 11884237,
"author_profile": "https://Stackoverflow.com/users/11884237",
"pm_score": 1,
"selected": false,
"text": "DataFrame.duplicated Series.any() not df[['col_A', 'col_B']].duplicated().any()\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8401374/"
] |
74,520,893
|
<p><a href="https://i.stack.imgur.com/Rozzh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rozzh.png" alt="enter image description here" /></a>I am new to PHP and HTML and trying the below. The below html code displays data from the database and add a calendar as row. The calendar displays current date by default. When changed, the changed date should be passed in the url.</p>
<pre><code><?php
include 'connect.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Update Clients</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css">
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<div class="container my-5">
<table class="table">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">Name</th>
<th scope="col">Start Date</th>
<th scope="col">Interest</th>
<th scope="col">Date</th>
<th scope="col">Days</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT id, name, DATE_FORMAT(startDate, '%Y-%m-%d') AS startDate, interest, (SELECT COUNT(1) FROM clientdata c WHERE clientId = id) AS days
FROM `clients` WHERE now() BETWEEN startdate and enddate ORDER BY id";
$result = mysqli_query($con, $sql);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$name = $row['name'];
$startdate = $row['startDate'];
$interest = $row['interest'];
$days = $row['days'];
$todaydate = date("Y-m-d");
echo ' <tr>
<th scope="row">' . $id . '</th>
<td>' . $name . '</td>
<td>' . $startdate . '</td>
<td>' . $interest . '</td>
<td> <input type="date" id = "changeDate" value=' . $todaydate . '></input></td>
<td>' . $days . '</td>
<td>
<button class="btn btn-primary" onchange="myFunction()"><a href="insertClientData.php?id='.$id.'&name='.$name.'&todaydate='. $todaydate .'" class="text-light"> Update </a></button>
</td>
</tr>';
}
}
?>
</tbody>
</table>
</div>
<div class="container my-5">
<table> <tr>
<button class="btn btn-primary my-3"><a href="main.php" class="text-light"> Home Page </a></button>
</tr>
</table>
</div>
</body>
</html>
</code></pre>
<p>Need to display the today's date into the date field and when click on the update URL needs to find the new selected date. The update button should be passed with the selected date</p>
<pre><code><button class="btn btn-primary" onchange="myFunction()"><a href="insertClientData.php?id=.$id.&name=.$name.&todaydate=. $todaydate" class="text-light"> Update </a></button>
</code></pre>
|
[
{
"answer_id": 74521753,
"author": "Peter Bennett",
"author_id": 1947068,
"author_profile": "https://Stackoverflow.com/users/1947068",
"pm_score": 0,
"selected": false,
"text": "<?php\ninclude 'connect.php';\n?>\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Update Clients</title>\n<link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css\">\n<script src=\"/scripts/snippet-javascript-console.min.js?v=1\"></script>\n</head>\n\n<body>\n<div class=\"container my-5\">\n <table class=\"table\">\n <thead>\n <tr>\n <th scope=\"col\">id</th>\n <th scope=\"col\">Name</th>\n <th scope=\"col\">Start Date</th>\n <th scope=\"col\">Interest</th>\n <th scope=\"col\">Date</th>\n <th scope=\"col\">Days</th>\n </tr>\n </thead>\n <tbody>\n <?php\n $sql = \"SELECT id, name, DATE_FORMAT(startDate, '%Y-%m-%d') AS startDate, interest, (SELECT COUNT(1) FROM clientdata c WHERE clientId = id) AS days\n FROM `clients` WHERE now() BETWEEN startdate and enddate ORDER BY id\";\n $result = mysqli_query( $con, $sql );\n if ( $result ) {\n while ( $row = mysqli_fetch_assoc( $result ) ) {\n $id = $row[ 'id' ];\n $name = $row[ 'name' ];\n $startdate = $row[ 'startDate' ];\n $interest = $row[ 'interest' ];\n $days = $row[ 'days' ];\n $todaydate = date( \"Y-m-d\" );\n echo ' \n <form action=\"\" enctype=\"multipart/form-data\" method=\"get\">\n <tr>\n <th scope=\"row\">' . $id . '</th>\n <td>' . $name . '</td>\n <td>' . $startdate . '</td>\n <td>' . $interest . '</td>\n <td> <input type=\"date\" id = \"changeDate\" value=' . $todaydate . '></input></td>\n <td>' . $days . '</td>\n <td> \n <button type=\"submit\" class=\"btn btn-primary\"></button>\n </td>\n </tr>\n </form>\n ';\n }\n }\n ?>\n <br>\n\n </tbody>\n </table>\n</div>\n<div class=\"container my-5\">\n<table>\n<tr>\n <button class=\"btn btn-primary my-3\">\n <a href=\"main.php\" class=\"text-light\"> Home Page </a>\n </button>\n"
},
{
"answer_id": 74522591,
"author": "Ken Lee",
"author_id": 11854986,
"author_profile": "https://Stackoverflow.com/users/11854986",
"pm_score": 2,
"selected": true,
"text": "closest find classes window.location.href <script\n src=\"https://code.jquery.com/jquery-1.12.4.js\"\n integrity=\"sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=\"\n crossorigin=\"anonymous\"></script>\n\n<table border=1> \n<tr>\n<th class=xid scope=\"row\">123</th>\n<td class=xname>Mary Roberson</td>\n<td><input type=\"date\" class = \"changeDate\" value='2022-11-22'></input></td>\n<td>\n<button class=\"btn btn-primary\">Update</button>\n</td>\n\n<tr>\n<th class=xid scope=\"row\">333</th>\n<td class=xname>Peter Pen</td>\n<td><input type=\"date\" class = \"changeDate\" value='2022-11-22'></input></td>\n<td>\n<button class=\"btn btn-primary\">Update</button>\n</td>\n\n</table>\n\n\n<script>\n$('.btn-primary').click(function(){\n\n var xdate=($(this).closest('tr').find('.changeDate').val());\n var xid=($(this).closest('tr').find('.xid').text());\n var xname=($(this).closest('tr').find('.xname').text());\n\n window.location.href=\"insertClientData.php?id=\"+ xid+ \"&name=\"+ xname+ \"&todaydate=\"+ xdate;\n});\n</script>\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1720827/"
] |
74,520,901
|
<p>I know that in php you can make a function or procedure in the code itself like this</p>
<pre><code>
$query = "CREATE FUNCTION Example (x INT)
RETURNS BOOLEAN
BEGIN
END";
mysql_query($query);
$query = "SELECT * FROM table";
mysql_query($query);
</code></pre>
<p>Is it possible to do something similar in Ruby?</p>
<p>At the moment, I need to make some kind of project in ruby, but I don’t know and can’t find whether it’s possible to write exactly this inside the code there. I know that everything there is based on Active Record, but is it possible to write the same code as in PHP? This moment is very important for me.</p>
|
[
{
"answer_id": 74521137,
"author": "Taimoor Hassan",
"author_id": 13000257,
"author_profile": "https://Stackoverflow.com/users/13000257",
"pm_score": 2,
"selected": true,
"text": "query = \"SELECT * FROM table\";\nmysql_query = ActiveRecord::Base.connection.execute(query)\n"
},
{
"answer_id": 74653748,
"author": "Themis Nikellis",
"author_id": 20598698,
"author_profile": "https://Stackoverflow.com/users/20598698",
"pm_score": 0,
"selected": false,
"text": "clients = Client.all\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19024091/"
] |
74,520,916
|
<p>In the following code, the variable <code>x</code> has the type <code>RegExpExecArray | null</code> (according to VSCode).</p>
<pre><code> const storeIdRegExp = /s(?<storeId>\d+)/u;
const x = storeIdRegExp.exec(query);
</code></pre>
<p><strong>How can I find the definition of <code>RegExpExecArray</code>? I couldn't find it documented anywhere.</strong></p>
<hr />
<p>Note: I did find a couple of references in the TypeScript source code, particularly <a href="https://github.com/microsoft/TypeScript/blob/663b19fe4a7c4d4ddaa61aedadd28da06acd27b6/tests/baselines/reference/1.0lib-noErrors.js#L794-L824" rel="nofollow noreferrer">1.0lib-noErrors.js</a> and <a href="https://github.com/microsoft/TypeScript/blob/663b19fe4a7c4d4ddaa61aedadd28da06acd27b6/lib/lib.es2018.regexp.d.ts#L27-L31" rel="nofollow noreferrer">lib.es2018.regexp.d.ts</a> (which I assume applies if the compilation target is ES2018+). But that wasn't easy to find and I'm not 100% sure the union of these interfaces is the correct answer.</p>
|
[
{
"answer_id": 74521137,
"author": "Taimoor Hassan",
"author_id": 13000257,
"author_profile": "https://Stackoverflow.com/users/13000257",
"pm_score": 2,
"selected": true,
"text": "query = \"SELECT * FROM table\";\nmysql_query = ActiveRecord::Base.connection.execute(query)\n"
},
{
"answer_id": 74653748,
"author": "Themis Nikellis",
"author_id": 20598698,
"author_profile": "https://Stackoverflow.com/users/20598698",
"pm_score": 0,
"selected": false,
"text": "clients = Client.all\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/437/"
] |
74,520,937
|
<p>I am using the <code>tmutil status</code> command to give me the current TimeMachine backup status. It gives an output of the sort</p>
<pre><code>% tmutil status
Backup session status:
{
BackupPhase = Copying;
ClientID = "com.apple.backupd";
DateOfStateChange = "2022-11-21 11:23:03 +0000";
DestinationID = "89E08126-7132-4D14-80B4-EFD45E8C5BFC";
FirstBackup = 1;
Progress = {
Percent = "0.1640944884974286";
TimeRemaining = 65013;
"_raw_Percent" = "0.1640944884974286";
"_raw_totalBytes" = 488603537408;
bytes = 80177147549;
files = 159679;
totalBytes = 488603537408;
totalFiles = 3345928;
};
Running = 1;
Stopping = 0;
}
</code></pre>
<p>This is not JSON, though it looks a bit like it.</p>
<p>I want to report on the Percent Complete and the Time Remaining.</p>
<p>I can get the Percent Complete with</p>
<pre><code>tmutil status | grep "raw_Percent" | LC_NUMERIC="C" awk -F '"' '{print "Percent Complete: " ($4 * 100) "%"} '
</code></pre>
<p>and I can get the Time Remaining with</p>
<pre><code>tmutil status | grep "TimeRemaining" | awk '{print "Time Remaining: " ($3/3600) " hours"} '
</code></pre>
<p>How can I run tmutil once (it seems to be a little expensive), and send the output to two <code>grep ... | awk ...</code> commands?</p>
<p>My understanding is that I could do</p>
<pre><code>tmutil status | tee > (grep "raw_Percent" | LC_NUMERIC="C" awk -F '"' '{print "Percent Complete: " ($4 * 100) "%"} ') | (grep "TimeRemaining" | awk '{print "Time Remaining: " ($3/3600) " hours"} ')
</code></pre>
<p>with each command (pipes and all) in brackets.</p>
<p>But, instead, I get</p>
<pre><code>zsh: no matches found: (grep raw_Percent | LC_NUMERIC=C awk -F " {print "Percent Complete: " ($4 * 100) "%"} )
</code></pre>
|
[
{
"answer_id": 74521137,
"author": "Taimoor Hassan",
"author_id": 13000257,
"author_profile": "https://Stackoverflow.com/users/13000257",
"pm_score": 2,
"selected": true,
"text": "query = \"SELECT * FROM table\";\nmysql_query = ActiveRecord::Base.connection.execute(query)\n"
},
{
"answer_id": 74653748,
"author": "Themis Nikellis",
"author_id": 20598698,
"author_profile": "https://Stackoverflow.com/users/20598698",
"pm_score": 0,
"selected": false,
"text": "clients = Client.all\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15452/"
] |
74,520,942
|
<p>I've got the array of string looks like that:</p>
<pre><code>Cola-12-0-15-300-122
Pepsi-123-34-543
7_Up-rrr-12-2342-2
Fanta_Mineral-1212-fgdfg-33
</code></pre>
<p>And I need to retrieve from these values just the first words till the dash.</p>
<p>So I will have</p>
<pre><code>Cola
Pepsi
7_up
Fanta_Mineral
</code></pre>
|
[
{
"answer_id": 74520981,
"author": "Mathias R. Jessen",
"author_id": 712649,
"author_profile": "https://Stackoverflow.com/users/712649",
"pm_score": 2,
"selected": false,
"text": "-replace - -replace '-.*' $strings = -split @'\nPepsi-123-34-543\n7_Up-rrr-12-2342-2\nFanta_Mineral-1212-fgdfg-33\n'@\n\n$strings -replace '-.*'\n Cola\nPepsi\n7_Up\nFanta_Mineral\n"
},
{
"answer_id": 74521385,
"author": "Vish",
"author_id": 9692303,
"author_profile": "https://Stackoverflow.com/users/9692303",
"pm_score": 1,
"selected": false,
"text": "$Strings = @(\n 'Cola-12-0-15-300-122',\n 'Pepsi-123-34-543',\n '7_Up-rrr-12-2342-2',\n 'Fanta_Mineral-1212-fgdfg-33'\n)\n\n$FirstWord = $Strings | ForEach-Object {\n ($_ -split '-')[0]\n}\n\n$FirstWord\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18644650/"
] |
74,520,961
|
<p>I am making a react-native user registration and login app and getting the following error. How can I fix this? My codes store exactly the same data that I use for registration. And in the SIGN IN page, it refuses to log in and shows the (Login FAILED) error. And in the console, it prints the following error. Please help.</p>
<p>WARN: Possible Unhandled Promise Rejection
TypeError: undefined is not an object(evaluating 'UserData.password')</p>
<p><strong>My Code</strong></p>
<pre><code>import React, { useState } from "react";
import {StyleSheet, View} from 'react-native';
import {Input, Button, Card, Tab} from '@rneui/themed';
import { FontAwesome } from '@expo/vector-icons';
import {AuthContext} from "../topuproviders/Authprovider";
import { getDataJSON } from "../functions/topuAsyncStorage";
const SignInScreen = (props) => {
const [Email, setEmail] = useState("");
const [Password, setPassword] = useState("");
return (
<AuthContext.Consumer>
{(auth)=>(<View style ={styles.viewStyle}>
<Card>
<Card.Title>Welcome to Auth App!</Card.Title>
<Card.Divider/>
<Input
placeholder='Email Address'
leftIcon={<FontAwesome name="envelope" size={20} color="#4CAF50" />}
onChangeText={function(currentInput){
setEmail(currentInput)
}}
/>
<Input
placeholder='Password'
secureTextEntry={true}
leftIcon={<FontAwesome name="lock" size={24} color="#4CAF50" />}
onChangeText={function(currentInput){
setPassword(currentInput)
}}
/>
<Button
icon = {<FontAwesome name="arrow-circle-o-right" size={15} color="white" />}
name ="login"
type ="solid"
title="Sign In"
onPress={
async function (){
let UserData = await getDataJSON(Email);
if(UserData.password == Password){
auth.SetIsLoggedIn(true);
auth.setCurrentUser(UserData);
}else{
alert('Login failed');
console.log(UserData); /*** Prints exactly same data what i Input ***/
}
}
}
/>
<Card.Divider/>
<Button
name ="noaccount"
type ="clear"
title="Don't have account?"
onPress={
function (){
props.navigation.navigate("SignUp")
}
}
/>
</Card>
</View>)}
</AuthContext.Consumer>
);
}
export default SignInScreen;
</code></pre>
<p><strong>getdataJson/Asyncstorage</strong></p>
<pre><code>import AsyncStorage from '@react-native-async-storage/async-storage';
const storeData = async (key, value) => {
try {
await AsyncStorage.setItem(key, value);
alert("Data stored succefully");
}catch (error){
alert(error);
}
};
const storeDataJson = async (key, value) => {
try {
const jsonValue = JSON.stringify(value);
await AsyncStorage.setItem(key, jsonValue);
alert("Data stored successfully")
}catch(error){
alert(error);
}
};
const getData = async (key) => {
try {
let data = await AsyncStorage.getItem(key);
if(data != null){
return data;
}else{
alert("No Data with this key!");
}
}catch (error){
alert(error);
}
};
const getDataJSON = async (key) => {
try {
let data = await AsyncStorage.getItem(key);
if(data != null){
const jsonData = JSON.parse(data);
return jsonData;
}else {
alert("No data with this key");
}
}catch(error){
alert(error);
}
};
const removeData = async (key) => {
try {
await AsyncStorage.removeItem(key);
alert("Data removed Successfully");
}catch (error){
alert (error);
}
};
export {storeData, storeDataJson, getData, getDataJSON, removeData}
</code></pre>
|
[
{
"answer_id": 74520981,
"author": "Mathias R. Jessen",
"author_id": 712649,
"author_profile": "https://Stackoverflow.com/users/712649",
"pm_score": 2,
"selected": false,
"text": "-replace - -replace '-.*' $strings = -split @'\nPepsi-123-34-543\n7_Up-rrr-12-2342-2\nFanta_Mineral-1212-fgdfg-33\n'@\n\n$strings -replace '-.*'\n Cola\nPepsi\n7_Up\nFanta_Mineral\n"
},
{
"answer_id": 74521385,
"author": "Vish",
"author_id": 9692303,
"author_profile": "https://Stackoverflow.com/users/9692303",
"pm_score": 1,
"selected": false,
"text": "$Strings = @(\n 'Cola-12-0-15-300-122',\n 'Pepsi-123-34-543',\n '7_Up-rrr-12-2342-2',\n 'Fanta_Mineral-1212-fgdfg-33'\n)\n\n$FirstWord = $Strings | ForEach-Object {\n ($_ -split '-')[0]\n}\n\n$FirstWord\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19788480/"
] |
74,520,971
|
<p>I have a file <strong>in.txt</strong>.</p>
<pre><code>
name="XYZ_PP_0" number="0x12" bytesize="4" info="0x0000001A"
name="GK_LMP_2_0" number="0xA5" bytesize="8" info="0x00000000bbae321f"
name="MP_LKO_1_0" number="0x356" bytesize="4" info="0x00000234"
name="PNP_VXU_1_2_0" number="0x48A" bytesize="8" info="0x00000000a18c3ba3"
name="AVU_W_2_3_1" number="0x867" bytesize="1" info="0x0b"
</code></pre>
<p>From this file i need to search for <code>number="0x867"</code> and check if it's info value matches to the expected given info value which is 0x0a. if it matches print matches else doesn't matches.</p>
<p>then next i need to search for <code>number="0x12"</code> and store it's info value i.e <code>info="0x0000001A"</code> and then search for <code>number="0x356"</code> and store it's info value <code> info="0x00000234"</code> to another variable. this value should be equal to previous info value + 0x00000004 (i.e 0x0000001A + 0x00000004 = 0x0000001E).</p>
<p><strong>if</strong> resulted value matches to <code> info="0x00000234"</code> then print <code>number="0x12" info value 0x00000012 + 0x00000004 matches to info value of number="0x356".</code></p>
<p><strong>else</strong> <code>print resulted value not matching</code></p>
<p>This is current attempt in python:</p>
<pre><code>with open("in.txt", "r") as infile:
XYZ = False
MP = False
AVU = False
xyz = ['number="0x12"', 'info="0x0000001A"']
mp = ['number="0x356"', 'info="0x00000234"']
avu = ['number="0x867"', 'info="0x0b"']
for line in infile:
if all(x in line for x in xyz):
XYZ = True
continue
if all(x in line for x in mp):
MP = True
continue
if all(x in line for x in avu):
AVU = True
continue
</code></pre>
<p>but this code will simply checks if the line is present in file or not. it won't check the conditions mentioned above.</p>
<p>Is there a way i can search for the number in the text file and store it's info value to variable?</p>
|
[
{
"answer_id": 74520981,
"author": "Mathias R. Jessen",
"author_id": 712649,
"author_profile": "https://Stackoverflow.com/users/712649",
"pm_score": 2,
"selected": false,
"text": "-replace - -replace '-.*' $strings = -split @'\nPepsi-123-34-543\n7_Up-rrr-12-2342-2\nFanta_Mineral-1212-fgdfg-33\n'@\n\n$strings -replace '-.*'\n Cola\nPepsi\n7_Up\nFanta_Mineral\n"
},
{
"answer_id": 74521385,
"author": "Vish",
"author_id": 9692303,
"author_profile": "https://Stackoverflow.com/users/9692303",
"pm_score": 1,
"selected": false,
"text": "$Strings = @(\n 'Cola-12-0-15-300-122',\n 'Pepsi-123-34-543',\n '7_Up-rrr-12-2342-2',\n 'Fanta_Mineral-1212-fgdfg-33'\n)\n\n$FirstWord = $Strings | ForEach-Object {\n ($_ -split '-')[0]\n}\n\n$FirstWord\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74520971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20273554/"
] |
74,521,021
|
<p>As the question, how do I animate a series of plots instead of printing each individual plot? Thanks a lot!!!</p>
<pre><code>
import numpy as np
from matplotlib import pyplot as plt
from scipy.integrate import odeint
import matplotlib.animation as animation
%matplotlib inline
# Define vector field
def vField(x,t,a):
u = 2*x[1]
v = -x[0] + a*(x[1] - 1/4 * x[1]**2)
return [u,v]
vec = [-10,-5,0,5,10]
for a in vec:
# Plot vector field
X, Y = np.mgrid[-2:2:20j,-2:2:20j]
U, V = vField([X,Y],0,a)
fig, ax = plt.subplots(figsize=(10, 7))
ax.quiver(X, Y, U, V)
plt.pause(0.01)
plt.show()
</code></pre>
|
[
{
"answer_id": 74520981,
"author": "Mathias R. Jessen",
"author_id": 712649,
"author_profile": "https://Stackoverflow.com/users/712649",
"pm_score": 2,
"selected": false,
"text": "-replace - -replace '-.*' $strings = -split @'\nPepsi-123-34-543\n7_Up-rrr-12-2342-2\nFanta_Mineral-1212-fgdfg-33\n'@\n\n$strings -replace '-.*'\n Cola\nPepsi\n7_Up\nFanta_Mineral\n"
},
{
"answer_id": 74521385,
"author": "Vish",
"author_id": 9692303,
"author_profile": "https://Stackoverflow.com/users/9692303",
"pm_score": 1,
"selected": false,
"text": "$Strings = @(\n 'Cola-12-0-15-300-122',\n 'Pepsi-123-34-543',\n '7_Up-rrr-12-2342-2',\n 'Fanta_Mineral-1212-fgdfg-33'\n)\n\n$FirstWord = $Strings | ForEach-Object {\n ($_ -split '-')[0]\n}\n\n$FirstWord\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15625027/"
] |
74,521,022
|
<p>I'm quite new with xslt and I have a xml-formatted text to transform to a different text format e.g. markdown. xml-formatting nodes can occur several times inside a text content as in the following simplified example:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<content>
<para>
This is a sample
<bold>text</bold>
for testing and
<bold>improvement</bold>
of current software version
</para>
</content>
</code></pre>
<p>My xslt transformation (from JDK 1.8.0) is:</p>
<pre><code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" indent="no" omit-xml-declaration="yes" xml:space="default" />
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="para">
<xsl:for-each select="./*">
<xsl:choose>
<xsl:when test="bold">
<xsl:value-of select="normalize-space(bold/preceding-sibling::text())"/>
<xsl:text> **</xsl:text><xsl:value-of select="normalize-space(bold)"/><xsl:text>** </xsl:text>
<xsl:value-of select="normalize-space(bold/following-sibling::text())"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="normalize-space(.)"/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>which outputs just the string: <code>textimprovement</code>.</p>
<p>How can i get a better transformation ?</p>
<p>Thanks for helping.</p>
|
[
{
"answer_id": 74521681,
"author": "Martin Honnen",
"author_id": 252228,
"author_profile": "https://Stackoverflow.com/users/252228",
"pm_score": 0,
"selected": false,
"text": "<xsl:template match=\"bold\">**<xsl:apply-templates/>**</xsl:template>\n"
},
{
"answer_id": 74522717,
"author": "Michael Kay",
"author_id": 415448,
"author_profile": "https://Stackoverflow.com/users/415448",
"pm_score": 2,
"selected": true,
"text": "<xsl:template match=\"para\">\n <xsl:apply-templates/>\n</xsl:template>\n\n<xsl:template match=\"text()\">\n <xsl:value-of select=\".\"/>\n</xsl:template>\n\n<xsl:template match=\"bold\">\n <xsl:text>**</xsl:text>\n <xsl:apply-templates/>\n <xsl:text>**</xsl:text>\n</xsl:template>\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4545629/"
] |
74,521,036
|
<p>I have a zip file in my download folder with the name "Query Transaction History_20221121040329_01.xls"</p>
<p>This is the code I used to import the file to my machine</p>
<pre><code>unzip(zipfile ="C:/Users/Guest 1/Downloads/Query Transaction
History_20221121040329_42118.zip",
files = "Query Transaction History_20221121040329_01.xls",exdir=".")
</code></pre>
<p>I want to load this zip file without specifying the full name using the startwith function in the baser or any other process that can do the job perfectly.</p>
<p>this is what I want</p>
<pre><code> unzip(zipfile ="C:/Users/Guest 1/Downloads/Query Transaction
History_20221121.zip",
files = "Query Transaction History_20221121.xls",exdir=".")
</code></pre>
|
[
{
"answer_id": 74521681,
"author": "Martin Honnen",
"author_id": 252228,
"author_profile": "https://Stackoverflow.com/users/252228",
"pm_score": 0,
"selected": false,
"text": "<xsl:template match=\"bold\">**<xsl:apply-templates/>**</xsl:template>\n"
},
{
"answer_id": 74522717,
"author": "Michael Kay",
"author_id": 415448,
"author_profile": "https://Stackoverflow.com/users/415448",
"pm_score": 2,
"selected": true,
"text": "<xsl:template match=\"para\">\n <xsl:apply-templates/>\n</xsl:template>\n\n<xsl:template match=\"text()\">\n <xsl:value-of select=\".\"/>\n</xsl:template>\n\n<xsl:template match=\"bold\">\n <xsl:text>**</xsl:text>\n <xsl:apply-templates/>\n <xsl:text>**</xsl:text>\n</xsl:template>\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16087142/"
] |
74,521,040
|
<p>Is there anyway I can reduce this code? I already tried shortening it to the shortest I can possibly think. Is there any possible shortening techniques there is?</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>document.getElementById('switcher').addEventListener('click', (param1) => {
let dmbody = document.body.style;
let dmbutton = document.getElementById('switcher').style;
if(param1.target.value == "Off"){
param1.target.value = "On";
param1.target.textContent = "Dark";
dmbody.backgroundColor = "var(--darkbg-color)";
dmbody.color = "var(--darktxtcolor)";
dmbutton.backgroundColor = "var(--darkbg-color)";
dmbutton.color = "var(--darktxtcolor)";
dmbutton.setProperty("border", "1px solid #FFF");
} else {
param1.target.value = "Off";
param1.target.textContent = "Light";
dmbody.backgroundColor = "var(--lightbg-color)";
dmbody.color = "var(--lighttxtcolor)";
dmbutton.backgroundColor = "var(--lightbg-color)";
dmbutton.color = "var(--lighttxtcolor)";
dmbutton.setProperty("border", "1px solid #000");
}
})</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="switcher" value="Off">Light</button></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74521159,
"author": "Cerbrus",
"author_id": 1835379,
"author_profile": "https://Stackoverflow.com/users/1835379",
"pm_score": 4,
"selected": true,
"text": "document.getElementById('switcher').addEventListener('click', (param1) => {\n let isDark = param1.target.value === \"Off\";\n\n document.body.classList.toggle('dark', isDark);\n param1.target.value = isDark ? \"On\" : \"Off\";\n param1.target.textContent = isDark ? \"Dark\" : \"Light\";\n}) body {\n --lightbg-color: #FFF;\n --lighttxtcolor: #000;\n --darkbg-color: #111;\n --darktxtcolor: #EEE;\n\n background-color: var(--lightbg-color);\n color: var(--lighttxtcolor);\n}\n\n#switcher {\n background-color: var(--lightbg-color);\n color: var(--lighttxtcolor);\n border: 1px solid #000;\n}\n\nbody.dark {\n background-color: var(--darkbg-color);\n color: var(--darktxtcolor);\n}\n\nbody.dark #switcher {\n background-color: var(--darkbg-color);\n color: var(--darktxtcolor);\n border: 1px solid #FFF;\n} <button id=\"switcher\" value=\"Off\">Light</button> document.getElementById('switcher').addEventListener('click', (param1) => {\n let isDark = param1.target.value === \"Off\";\n\n document.body.classList.toggle('dark', isDark);\n param1.target.value = isDark ? \"On\" : \"Off\";\n param1.target.textContent = isDark ? \"Dark\" : \"Light\";\n}) body {\n --bg-color: #FFF;\n --txt-color: #000;\n --border-color: #000;\n}\n\nbody.dark {\n --bg-color: #111;\n --txt-color: #EEE;\n --border-color: #EEE;\n}\n\nbody {\n background-color: var(--bg-color);\n color: var(--txt-color);\n}\n\n#switcher {\n background-color: var(--bg-color);\n color: var(--txt-color);\n border: 1px solid var(--border-color);\n} <button id=\"switcher\" value=\"Off\">Light</button>"
},
{
"answer_id": 74521176,
"author": "Luís Mestre",
"author_id": 7850543,
"author_profile": "https://Stackoverflow.com/users/7850543",
"pm_score": 1,
"selected": false,
"text": "color backgroundColor color document.getElementById('switcher').addEventListener('click', (param1) => {\n let dmbody = document.body.style;\n let dmbutton = document.getElementById('switcher').style;\n let isOff = param1.target.value == \"Off\";\n let color = isOff ? \"dark\" : \"light\";\n\n param1.target.value = isOff ? \"On\" : \"Off\";\n param1.target.textContent = isOff ? \"Dark\" : \"Light\";\n dmbody.backgroundColor = `var(--${color}bg-color)`;\n dmbody.color = `var(--${color}txtcolor)`;\n dmbutton.backgroundColor = `var(--${color}bg-color)`;\n dmbutton.color = `var(--${color}txtcolor)`;\n dmbutton.setProperty(\"border\", `1px solid ${isOff ? \"#FFF\" : \"#000\"}`);\n})\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20305737/"
] |
74,521,041
|
<p>I am new to PowerShell and I am having the following problem.</p>
<p>When typing the following command for asked value of <code>CanonicalNameOfObject</code> I am receiving <code>Microsoft.ActiveDirectory.Management.ADPropertyValueCollection</code>. I know that this problem is because that property isn't in a format that is understood by PowerSell in its raw format.</p>
<p>Can somebody help me to put this right? In general I want to have all computers in the company for a specific branch (which is only a separated folder).</p>
<p><img src="https://i.stack.imgur.com/CAIRG.png" alt="enter image description here" /></p>
<p>Thank you!</p>
<p>Kind regards
Kris</p>
<pre><code>Get-ADComputer -Filter * -Property * |
Select-Object Name,CanonicalNameOfObject,OperatingSystem,OperatingSystemVersion,ipv4Address |
Export-CSV c:\ADcomputerslist.csv -NoTypeInformation -Encoding UTF8
</code></pre>
|
[
{
"answer_id": 74521132,
"author": "Mellik",
"author_id": 20561885,
"author_profile": "https://Stackoverflow.com/users/20561885",
"pm_score": 2,
"selected": false,
"text": "Get-ADComputer -Filter * -Property * | Select-Object CanonicalName\n"
},
{
"answer_id": 74527471,
"author": "Ralph Sch",
"author_id": 20551048,
"author_profile": "https://Stackoverflow.com/users/20551048",
"pm_score": 0,
"selected": false,
"text": "$AdUser.proxyAddresses[0] $UserObject[$propertyName]"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20540384/"
] |
74,521,048
|
<p>I've written a personal budgeting/cash flow model app for my iPad. I'm older and a retired software developer and I created this just cause I like to code. It's taken me over two years to create as a labor of "love" of the craft. Using cloc I get:</p>
<pre><code>-------------------------------------------------------------------------------
Language files blank comment code
-------------------------------------------------------------------------------
Swift 217 5523 3258 24990
CSV 13 0 0 14680
Objective-C 5 685 125 2076
SQL 9 213 29 845
JSON 15 0 0 510
C/C++ Header 7 1107 1413 319
XML 9 0 1 189
-------------------------------------------------------------------------------
SUM: 275 7528 4826 43609
-------------------------------------------------------------------------------
</code></pre>
<p>I don't have the resources to support an app published publicly in the app store so I'll not be submitting it to Apple to distribute. But, I'd like to be able to use it on my iPad and my wife's iPad. I've submitted it for TestFlight and my wife was running it like that for a while. But every 90 days I'd have to resubmit it and version it. So, right now I publish it via XCode off my Mac as a test app and that works fine so I know that is an option.</p>
<p>But, I may not purchase a developer license in perpetuity as I get older and don't regularly practice programming.</p>
<p>Is there a way that I can still run the app on our iPads even after I'm no longer a registered Apple Developer?</p>
|
[
{
"answer_id": 74521132,
"author": "Mellik",
"author_id": 20561885,
"author_profile": "https://Stackoverflow.com/users/20561885",
"pm_score": 2,
"selected": false,
"text": "Get-ADComputer -Filter * -Property * | Select-Object CanonicalName\n"
},
{
"answer_id": 74527471,
"author": "Ralph Sch",
"author_id": 20551048,
"author_profile": "https://Stackoverflow.com/users/20551048",
"pm_score": 0,
"selected": false,
"text": "$AdUser.proxyAddresses[0] $UserObject[$propertyName]"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13622371/"
] |
74,521,051
|
<p>I am doing a test using Cypress
and I have this rows created dynamically, like this one for example:</p>
<p><a href="https://i.stack.imgur.com/3tXNv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3tXNv.png" alt="example table with dropdown icon to the right" /></a></p>
<p>And what I want is to be able to click on the right icon and show or hide the info, each at the time.</p>
<p>I've inserted <code>data-cy= selectorName</code> and the behavior I want to do is:</p>
<ol>
<li>click on first icon (open content)</li>
<li>do some test</li>
<li>click on first icon again (close content)</li>
<li>click on second icon (open content)</li>
</ol>
<p>...and so fort.</p>
<p>I was assuming only two rows of my table and I did it like:</p>
<p><code>cy.get('selector:first').click()</code> or <code>cy.get('selector:last').click();</code> but I need it to work for more rows</p>
|
[
{
"answer_id": 74521132,
"author": "Mellik",
"author_id": 20561885,
"author_profile": "https://Stackoverflow.com/users/20561885",
"pm_score": 2,
"selected": false,
"text": "Get-ADComputer -Filter * -Property * | Select-Object CanonicalName\n"
},
{
"answer_id": 74527471,
"author": "Ralph Sch",
"author_id": 20551048,
"author_profile": "https://Stackoverflow.com/users/20551048",
"pm_score": 0,
"selected": false,
"text": "$AdUser.proxyAddresses[0] $UserObject[$propertyName]"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12416498/"
] |
74,521,094
|
<p>Right now I am working with an STMF429 nucleo-144 board and I am trying get the CAN to work.
Here is my Code:</p>
<pre><code>int intCAN();
int intFilter();
int pins();
int main(void)
{
//int CAN
pins();
intFilter();
intCAN();
CAN1->sTxMailBox[0].TDLR = 0;
CAN1->sTxMailBox[0].TDHR = 0;
CAN1->sTxMailBox[0].TDLR |= 0x8; //DATA0 = 1000
CAN1->sTxMailBox[0].TIR |= CAN_TI0R_TXRQ; //send mailbox
}
int pins()
{
RCC->AHB1ENR |= RCC_AHB1ENR_GPIODEN;
//RX
GPIOD->MODER &= GPIO_MODER_MODER0_1;
GPIOD->OTYPER &= ~(GPIO_OTYPER_OT0);
GPIOD->PUPDR &= ~(GPIO_PUPDR_PUPDR0);
GPIOD->OSPEEDR |= GPIO_OSPEEDR_OSPEED0_0|GPIO_OSPEEDR_OSPEED0_1;
//TX
GPIOD->MODER |= GPIO_MODER_MODER1_1;
GPIOD->OTYPER &= ~(GPIO_OTYPER_OT1);
GPIOD->PUPDR &= ~(GPIO_PUPDR_PUPDR1);
GPIOD->OSPEEDR |= GPIO_OSPEEDR_OSPEED1_0|GPIO_OSPEEDR_OSPEED1_1;
return 0;
}
int intCAN()
{
RCC->APB1ENR |= RCC_APB1ENR_CAN1EN;
CAN1->MCR &= ~(CAN_MCR_SLEEP);
CAN1->MCR |= CAN_MCR_INRQ; //Initilization Request
CAN1->BTR |= CAN_BTR_LBKM; //Loop Back Mode
CAN1->BTR |= 0x7; //BRP = 7
CAN1->BTR |= CAN_BTR_TS2_0|CAN_BTR_TS2_1|CAN_BTR_TS2_2; //Seg 2 = 7
CAN1->BTR |= CAN_BTR_TS1_0|CAN_BTR_TS1_1|CAN_BTR_TS1_2|CAN_BTR_TS1_3; //Seg 1 = 16
CAN1->BTR |= CAN_BTR_SJW_0; //Small Jump Width = 1
CAN1->MCR &= ~(CAN_MCR_INRQ); //exit initilization mode
//Testing
CAN1->sTxMailBox[0].TIR &= ~CAN_TI0R_RTR;
CAN1->sTxMailBox[0].TIR &= ~CAN_TI0R_IDE; //Standard Identifier
CAN1->sTxMailBox[0].TIR &= ~CAN_TI0R_STID;
CAN1->sTxMailBox[0].TIR |= (0x1 << CAN_TI0R_STID_Pos); //Message ID = 1
//Message
CAN1->sTxMailBox[0].TDTR &= ~CAN_TDT0R_DLC;
CAN1->sTxMailBox[0].TDTR |= (0x1 << CAN_TDT0R_DLC_Pos); //Data Length = 1 Byte
return 0;
}
int intFilter()
{
RCC->APB1ENR |= RCC_APB1ENR_CAN1EN;
CAN1->FA1R &= ~(CAN_FA1R_FACT0);
CAN1->FMR |= CAN_FMR_FINIT; //Initilization Mode Filter
CAN1->FM1R |= CAN_FM1R_FBM0; //Filter Bank 0 2 32bit register Identifier List Mode
CAN1->FS1R |= CAN_FS1R_FSC0;
CAN1->FFA1R &= ~(CAN_FFA1R_FFA0);
CAN1->sFilterRegister[0].FR1 |= 0x0;
CAN1->sFilterRegister[0].FR1 |= CAN_F0R1_FB0; //ID Filter = 1
CAN1->FMR &= ~(CAN_FMR_FINIT); //Exit Initilization Mode Filter
CAN1->FA1R |= CAN_FA1R_FACT0;
return 0;
</code></pre>
<p>The TX Pin is the PD0 Pin and the RX Pin is the PD1 Pin
When I run this program all I get is a constant dominant signal which is not what I´m hoping for.
I am testing just the TX Pin with an logic analyser.
I´m pretty confident that it is mostly true but that I am missing something (obvious).
I want to just use the registers (CMSIS) and no HAL.
Does anyone have an idea what I can do?</p>
<p>Thanks in advance
Jeyeffkay</p>
<p>I tried it in Loopback Mode and in different configurations but nothing worked. I´m new to this.</p>
<p>Edit1: At first I just want to have the desired output which should be a whole CAN Message which I can view in the Logic Analyser.</p>
|
[
{
"answer_id": 74521132,
"author": "Mellik",
"author_id": 20561885,
"author_profile": "https://Stackoverflow.com/users/20561885",
"pm_score": 2,
"selected": false,
"text": "Get-ADComputer -Filter * -Property * | Select-Object CanonicalName\n"
},
{
"answer_id": 74527471,
"author": "Ralph Sch",
"author_id": 20551048,
"author_profile": "https://Stackoverflow.com/users/20551048",
"pm_score": 0,
"selected": false,
"text": "$AdUser.proxyAddresses[0] $UserObject[$propertyName]"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16524282/"
] |
74,521,143
|
<p>I have a problem with Freemarker. I want to remove all the special characters from text string in freemarker: "!"#$%&'()*+,-./:;<=>?@[]^_`{|}~". I tried writing regular expression for this but it is not working and facing some errors:</p>
<p><#assign s = 'Foo bAr$%,*^%@()":& baar'></p>
<p>${s?replace('["!"#$%&'()*+,-./\:;<=>?@[]^_`{|}~"]', '', 'r')}</p>
<p>Please help</p>
|
[
{
"answer_id": 74629671,
"author": "bdasliva83",
"author_id": 12969088,
"author_profile": "https://Stackoverflow.com/users/12969088",
"pm_score": 2,
"selected": true,
"text": "${s?replace(\"[^\\\\w]|_\", \"\", \"r\")}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8940980/"
] |
74,521,148
|
<p>I have the following pandas dataframe</p>
<pre><code>is_and_mp market_state reason
'100' None NaN
'400' None NaN
'100' ALGO NaN
'400' OPENING NaN
</code></pre>
<p>I want to write two mappings where if <code>is_and_mp</code> is either <code>'100'</code> or <code>'400'</code>, and <code>market_state == None</code> and <code>reason == NaN</code>, then map <code>market_state =CONTINUOUS_TRADING</code>.</p>
<p>So the output would be:</p>
<pre><code>is_and_mp market_state reason
'100' CONTINUOUS_TRADING NaN
'400' CONTINUOUS_TRADING NaN
'100' ALGO NaN
'400' OPENING NaN
</code></pre>
<p>It is important for the existing mappings not to change! Thanks</p>
|
[
{
"answer_id": 74521205,
"author": "jezrael",
"author_id": 2901002,
"author_profile": "https://Stackoverflow.com/users/2901002",
"pm_score": 3,
"selected": true,
"text": "DataFrame.loc & AND df.loc[df.is_and_mp.isin([ '100', '400']) & df.market_state.isna() & df. reason.isna(), 'market_stat'] = 'CONTINUOUS_TRADING'\n df.loc[df.is_and_mp.isin([ 100, 400]) & df.market_state.isna() & df. reason.isna(), 'market_stat'] = 'CONTINUOUS_TRADING' \n"
},
{
"answer_id": 74521383,
"author": "arsho",
"author_id": 3129414,
"author_profile": "https://Stackoverflow.com/users/3129414",
"pm_score": 0,
"selected": false,
"text": "& df.loc () import pandas as pd\n\ndata = {\n \"is_and_mp\": ['100', '400', '100', '400'],\n \"market_state\": [None, None, 'ALGO', 'OPENING'],\n \"reason\": ['NaN', 'NaN', 'NaN', 'NaN']\n}\n\ndf = pd.DataFrame(data)\n\ndf.loc[(df[\"is_and_mp\"].isin(['100', '400'])) & (df[\"market_state\"].isna()) & (df[\"reason\"] == 'NaN'), \"market_state\"] = \"CONTINUOUS_TRADING\"\nprint(df)\n is_and_mp market_state reason\n0 100 CONTINUOUS_TRADING NaN\n1 400 CONTINUOUS_TRADING NaN\n2 100 ALGO NaN\n3 400 OPENING NaN\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19667022/"
] |
74,521,195
|
<p>I am trying to calibrate two cameras. I want to calibrate each one individually. At this point, my script can calibrate both cameras successfully. But now I want to use those calibrated cameras in real time. the code that I am using is the one available in the <a href="https://docs.opencv.org/4.x/dc/dbb/tutorial_py_calibration.html" rel="nofollow noreferrer">OpenCV documentation</a>.
Below is the code. I'll just share this part because it's the one that it's not working as I want.</p>
<pre><code>def calibrateCamera(self, chessboardRows=9, chessboardCols=6, imshow=False):
self.chessboardRows = chessboardRows
self.chessboardCols = chessboardCols
self.imshow = imshow
chessboardSize = (self.chessboardRows, self.chessboardCols)
criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 30, 0.001)
objp = np.zeros((self.chessboardCols*self.chessboardRows,3), np.float32)
objp[:,:2] = np.mgrid[0:self.chessboardRows,0:self.chessboardCols].T.reshape(-1,2)
objpoints = []
imgpoints = []
for path, index in zip(self.paths, self.indices):
images = glob.glob(path + "*.png")
for img in images:
frame = cv.imread(img)
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
ret, corners = cv.findChessboardCorners(gray, chessboardSize, None)
if ret == True:
objpoints.append(objp)
corners2 = cv.cornerSubPix(gray,corners, (11,11), (-1,-1), criteria)
imgpoints.append(corners2)
cv.drawChessboardCorners(frame, chessboardSize, corners2, ret)
if self.imshow == True:
cv.imshow(f"Calibrated images, Camera{index}", frame)
cv.waitKey(0)
if ret == False:
print("No pattern detected")
break
ret, mtx, dist, rvecs, tvecs = cv.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
print(f"Camera{index} matrix\n", mtx)
print(f"Camera{index} distortion coefficients\n", dist)
h, w = frame.shape[:2]
newcameramtx, roi = cv.getOptimalNewCameraMatrix(mtx, dist, (w,h), 1, (w,h))
mapx, mapy = cv.initUndistortRectifyMap(mtx, dist, None, newcameramtx, (w,h), 5)
dst = cv.remap(frame, mapx, mapy, cv.INTER_LINEAR)
x, y, w, h = roi
dst = dst[y:y+h, x:x+w]
cv.imshow('calibresult.png', dst)
k = cv.waitKey(0)
</code></pre>
<p>Can anyone help me to use this "remap" in real time?
And, lastly, is there any limitation in terms of frame rate to use this kind of method in real time?
Thanks in advance,</p>
|
[
{
"answer_id": 74534045,
"author": "Christoph Rackwitz",
"author_id": 2602877,
"author_profile": "https://Stackoverflow.com/users/2602877",
"pm_score": 1,
"selected": false,
"text": "calibrateCamera() initUndistortRectifyMap() remap() remap() remap() remap()"
},
{
"answer_id": 74536807,
"author": "AlixL",
"author_id": 5183473,
"author_profile": "https://Stackoverflow.com/users/5183473",
"pm_score": 1,
"selected": true,
"text": "cv.initUndistortRectifyMap cv.remap cv.undistortPoints"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20397171/"
] |
74,521,233
|
<p>In my code (a complex GUI application with Tkinter) I have a thread defined in a custom object (a progress bar). It runs a function with a while cicle like this:</p>
<pre><code>def Start(self):
while self.is_active==True:
do it..
time.sleep(1)
do it..
time.sleep(1)
def Stop(self):
self.is_active=False
</code></pre>
<p>It can terminate only when another piece of code, placed in another thread, changes the attribute <strong>self.is_active</strong> using the method <strong>self.Stop()</strong>. I have the same situation in another custom object (a counter) and both of them have to work together when the another thread (the main one) works.</p>
<p>The code works, but I realized that the two threads associated with the progress bar and the counter don't terminate instantly as I wanted, because before to temrinate, they need to wait the end of their functions, and these ones are slow becose of the <strong>time.sleep(1)</strong> instructions. From the user point of view, it means see the end of the main thread with the progress bar and the cunter that terminate LATE and I don't like it.</p>
<p>To be honest I don't know how to solve this issue. Is there a way to force a thread to terminate instantly without waiting the end of the function?</p>
|
[
{
"answer_id": 74521306,
"author": "Ahmed AEK",
"author_id": 15649230,
"author_profile": "https://Stackoverflow.com/users/15649230",
"pm_score": 0,
"selected": false,
"text": "def Start(self):\n while self.is_active==True:\n do it..\n if not self.is_active: return\n time.sleep(1)\n if not self.is_active: return\n do it..\n if not self.is_active: return\n time.sleep(1)\n \ndef Stop(self):\n self.is_active=False\n class MyError(Exception):\n pass\ndef Start(self):\n try:\n while self.is_active==True:\n do it..\n self.check_termination()\n time.sleep(1)\n self.check_termination()\n do it..\n self.check_termination()\n time.sleep(1)\n except MyError:\n return\n\ndef check_termination(self):\n if not self.is_active:\n raise MyError\n self.check_termination() Start"
},
{
"answer_id": 74521446,
"author": "ShadowRanger",
"author_id": 364696,
"author_profile": "https://Stackoverflow.com/users/364696",
"pm_score": 3,
"selected": true,
"text": "daemon=True with bool time.sleep Event .wait Event.wait class Spam:\n def __init__(self):\n self.should_stop = threading.Event() # Create an unset event on init\n \n def Start(self):\n while not self.should_stop.is_set():\n # do it..\n\n if self.should_stop.wait(1):\n break\n\n # do it..\n\n if self.should_stop.wait(1):\n break\n\n def Stop(self):\n self.should_stop.set()\n wait True False wait True break is_active Event @property\n def is_active(self):\n return not self.should_stop.is_set()\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11562537/"
] |
74,521,243
|
<p>How can i see all my deprecated methods functions in react native? i have a old react native project and its not working fine errors are coming one by one so i updated all of my packages which were outdated but after that many errors are coming too while running the project</p>
<p>i tired to fix some but now i get to know that my projects and many deprecated functions and it become very hard to solve one by one i do have many files in one project, So is their any easy way so see all deprecated functions methods variables etc. i do run npm outdated to see deprecated npm packages but it was not a solution..</p>
<p>i dont want my code updated i just want to search or see that what functions and methods are deprecated</p>
|
[
{
"answer_id": 74531058,
"author": "Daniel T",
"author_id": 10477326,
"author_profile": "https://Stackoverflow.com/users/10477326",
"pm_score": 0,
"selected": false,
"text": "npm i -D eslint-plugin-deprecation npm i -D typescript@4.0 @types/jest @types/react @types/react-native @types/react-test-renderer @tsconfig/react-native tsconfig.json {\n \"extends\": \"@tsconfig/react-native/tsconfig.json\"\n}\n .eslintrc.js module.exports = {\n root: true,\n extends: '@react-native-community',\n \"parser\": \"@typescript-eslint/parser\",\n \"parserOptions\": {\n \"ecmaVersion\": 2020,\n \"sourceType\": \"module\",\n \"project\": \"./tsconfig.json\"\n },\n \"plugins\": [\"deprecation\"],\n \"rules\": {\n \"deprecation/deprecation\": \"warn\",\n },\n};\n .eslintignore .eslintrc.js\n // ...\nimport {\n Colors,\n DebugInstructions,\n Header,\n LearnMoreLinks,\n ReloadInstructions,\n} from 'react-native/Libraries/NewAppScreen';\n\n/**\n * @deprecated\n */\nfunction dontUseThis() {}\n\n/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's\n * LTI update could not be added via codemod */\nconst Section = ({children, title}): Node => {\n dontUseThis(); // Newly added line 37 as an example of a deprecated function\n const isDarkMode = useColorScheme() === 'dark';\n return (\n// ...\n npm run lint $ npm run lint\n\n> AwesomeProject@0.0.1 lint\n> eslint .\n\n\n/run/user/1000/AwesomeProject/App.js\n 10:14 warning 'Node' is defined but never used no-unused-vars\n 37:3 warning 'dontUseThis' is deprecated. deprecation/deprecation\n\n✖ 2 problems (0 errors, 2 warnings)\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,521,283
|
<p>How can I slice arrays such as this into n-many subsets, where one subset consists of consecutive values?</p>
<pre><code>arr = np.array((0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 66, 67, 68, 69, 70, 71))
</code></pre>
<pre><code># tells me where they are consecutive
np.where(np.diff(arr) == 1)[0]
</code></pre>
<pre><code># where the break points are
cut_points = np.where(np.diff(arr) != 1)[0] + 1
</code></pre>
<pre><code># wont generalize well with n-many situations
arr[:cut_points[0] ]
arr[cut_points[0] : cut_points[1] ]
arr[cut_points[1] :, ]
</code></pre>
|
[
{
"answer_id": 74521405,
"author": "Haleemur Ali",
"author_id": 2570261,
"author_profile": "https://Stackoverflow.com/users/2570261",
"pm_score": 3,
"selected": true,
"text": "np.split cut_points split_arr = np.split(arr, cut_points)\n\n# split_arr looks like:\n# [array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),\n# array([39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]),\n# array([66, 67, 68, 69, 70, 71])]\n import numpy as np\narr = np.array((0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 66, 67, 68, 69, 70, 71))\ncut_points = np.where(np.diff(arr) != 1)[0] + 1\nsplit_arr = np.split(arr, split_points)\nsplit_arr\n# outputs:\n[array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),\n array([39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]),\n array([66, 67, 68, 69, 70, 71])]\n"
},
{
"answer_id": 74521538,
"author": "ChatterOne",
"author_id": 1485311,
"author_profile": "https://Stackoverflow.com/users/1485311",
"pm_score": 1,
"selected": false,
"text": "l = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 66, 67, 68, 69, 70, 71)\ni = 0\ncurrent_index = -1\nprev_value = None\nresult = []\nfor k in l[::-1]:\n current_value = k + i\n if prev_value != current_value:\n prev_value = current_value\n current_index += 1\n result.append([])\n result[current_index].append(k)\n i += 1\nprint(result)\n [\n [71, 70, 69, 68, 67, 66],\n [55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39],\n [14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n]\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6534818/"
] |
74,521,296
|
<p>Im trying to use the <a href="https://github.com/trivago/prettier-plugin-sort-imports" rel="nofollow noreferrer">https://github.com/trivago/prettier-plugin-sort-imports</a> lib which on the root diercotry but not in my subdirectories.</p>
<p>This is my project structure:</p>
<pre><code>---TheAPP
| subfolder1
package.json
| subfolder2
package.json
package.json
</code></pre>
<p>The library works on the root but not the subfolders.
This is added to my package.json in the root:</p>
<pre><code>scripts: {"prettier": "prettier --write \"**/*.{js,ts,tsx}\""},
</code></pre>
<p>How do i target the subfolder?
Is the problem that each subfolder has its own package.json so i need to install the library to each subfolders package.json?</p>
|
[
{
"answer_id": 74521405,
"author": "Haleemur Ali",
"author_id": 2570261,
"author_profile": "https://Stackoverflow.com/users/2570261",
"pm_score": 3,
"selected": true,
"text": "np.split cut_points split_arr = np.split(arr, cut_points)\n\n# split_arr looks like:\n# [array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),\n# array([39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]),\n# array([66, 67, 68, 69, 70, 71])]\n import numpy as np\narr = np.array((0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 66, 67, 68, 69, 70, 71))\ncut_points = np.where(np.diff(arr) != 1)[0] + 1\nsplit_arr = np.split(arr, split_points)\nsplit_arr\n# outputs:\n[array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),\n array([39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]),\n array([66, 67, 68, 69, 70, 71])]\n"
},
{
"answer_id": 74521538,
"author": "ChatterOne",
"author_id": 1485311,
"author_profile": "https://Stackoverflow.com/users/1485311",
"pm_score": 1,
"selected": false,
"text": "l = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 66, 67, 68, 69, 70, 71)\ni = 0\ncurrent_index = -1\nprev_value = None\nresult = []\nfor k in l[::-1]:\n current_value = k + i\n if prev_value != current_value:\n prev_value = current_value\n current_index += 1\n result.append([])\n result[current_index].append(k)\n i += 1\nprint(result)\n [\n [71, 70, 69, 68, 67, 66],\n [55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39],\n [14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n]\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16382543/"
] |
74,521,303
|
<p>In my application, I am using keycloak with the Authorization server that I have created in Spring Boot application. I have implemented authentication and authorization using OpenID Connect. In Client Authentication parameter in keycloak, I have selected client_secret_post option. The configuration can be seen in the image below: <a href="https://i.stack.imgur.com/n6eGm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n6eGm.png" alt="enter image description here" /></a></p>
<p>In my Authorization server that I have developed in spring boot, I have also done the same thing. <a href="https://i.stack.imgur.com/Apl3Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Apl3Y.png" alt="enter image description here" /></a></p>
<p>Now when I debug the code, I can see that with token request http://auth-server:9000/oauth2/token, the client id and client secret are sent in request paramrters as can be seen in the image below<a href="https://i.stack.imgur.com/maAG6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/maAG6.png" alt="enter image description here" /></a></p>
<p>But with the userinfo request http://auth-server:9000/userinfo, I see that the client id and client secret are not sent in request parameters instead the client id and client secret are decoded and sent in the authorization Header as can be seen in the image below<a href="https://i.stack.imgur.com/yuiJV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yuiJV.png" alt="enter image description here" /></a></p>
<p>Is this the expected behaviour or am I missing something? Why the client_id and client_secret are not being sent as request parameters for the userinfo endpoint URL http://auth-server:9000/userinfo also?</p>
|
[
{
"answer_id": 74521405,
"author": "Haleemur Ali",
"author_id": 2570261,
"author_profile": "https://Stackoverflow.com/users/2570261",
"pm_score": 3,
"selected": true,
"text": "np.split cut_points split_arr = np.split(arr, cut_points)\n\n# split_arr looks like:\n# [array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),\n# array([39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]),\n# array([66, 67, 68, 69, 70, 71])]\n import numpy as np\narr = np.array((0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 66, 67, 68, 69, 70, 71))\ncut_points = np.where(np.diff(arr) != 1)[0] + 1\nsplit_arr = np.split(arr, split_points)\nsplit_arr\n# outputs:\n[array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),\n array([39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]),\n array([66, 67, 68, 69, 70, 71])]\n"
},
{
"answer_id": 74521538,
"author": "ChatterOne",
"author_id": 1485311,
"author_profile": "https://Stackoverflow.com/users/1485311",
"pm_score": 1,
"selected": false,
"text": "l = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 66, 67, 68, 69, 70, 71)\ni = 0\ncurrent_index = -1\nprev_value = None\nresult = []\nfor k in l[::-1]:\n current_value = k + i\n if prev_value != current_value:\n prev_value = current_value\n current_index += 1\n result.append([])\n result[current_index].append(k)\n i += 1\nprint(result)\n [\n [71, 70, 69, 68, 67, 66],\n [55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39],\n [14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n]\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11907420/"
] |
74,521,309
|
<p>jaxb groups all tags in one, I need each tag to have its own namespace.</p>
<p>have:</p>
<pre><code><Request env="DEV" xmlns="http://test1" "xmlns:ns2="urn://test2">
<ApplicationData>
<ns2:Application>
<Square>test</Square>
</ns2:Application>
</ApplicationData>
</Request>
</code></pre>
<p>need:</p>
<pre><code><Request env="DEV" xmlns="http://test1">
<ApplicationData>
<Application xmlns ="urn://test2">
<Square>test</Square>
</Application>
</ApplicationData>
</Request>
</code></pre>
<p>adding namespace into @XmlElement didn't help</p>
<pre><code>@XmlElement(
name = "Application",
required = true,
namespace = "urn://test2")
</code></pre>
<p>package-info:</p>
<pre><code>@javax.xml.bind.annotation.XmlSchema(
namespace = "http://test1",
elementFormDefault = XmlNsForm.QUALIFIED,
xmlns = {
@XmlNs(prefix = "", namespaceURI = "http://test1")
})
</code></pre>
|
[
{
"answer_id": 74521405,
"author": "Haleemur Ali",
"author_id": 2570261,
"author_profile": "https://Stackoverflow.com/users/2570261",
"pm_score": 3,
"selected": true,
"text": "np.split cut_points split_arr = np.split(arr, cut_points)\n\n# split_arr looks like:\n# [array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),\n# array([39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]),\n# array([66, 67, 68, 69, 70, 71])]\n import numpy as np\narr = np.array((0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 66, 67, 68, 69, 70, 71))\ncut_points = np.where(np.diff(arr) != 1)[0] + 1\nsplit_arr = np.split(arr, split_points)\nsplit_arr\n# outputs:\n[array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),\n array([39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]),\n array([66, 67, 68, 69, 70, 71])]\n"
},
{
"answer_id": 74521538,
"author": "ChatterOne",
"author_id": 1485311,
"author_profile": "https://Stackoverflow.com/users/1485311",
"pm_score": 1,
"selected": false,
"text": "l = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 66, 67, 68, 69, 70, 71)\ni = 0\ncurrent_index = -1\nprev_value = None\nresult = []\nfor k in l[::-1]:\n current_value = k + i\n if prev_value != current_value:\n prev_value = current_value\n current_index += 1\n result.append([])\n result[current_index].append(k)\n i += 1\nprint(result)\n [\n [71, 70, 69, 68, 67, 66],\n [55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39],\n [14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n]\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20564272/"
] |
74,521,324
|
<p>I have a text file with the below content:</p>
<pre><code>--abcdef12 --
February April January
January March January
January January January
--abcdef12 --
</code></pre>
<p>How can I use sed to change the last occurrence of January in the file to July?<br />
Required output:</p>
<pre><code>--abcdef12 --
February April January
January March January
January January July
--abcdef12 --
</code></pre>
<p>I tried <a href="https://linuxhint.com/use-sed-replace-last-occurrence/" rel="nofollow noreferrer">https://linuxhint.com/use-sed-replace-last-occurrence/</a> - Below was the output:</p>
<pre><code>sed '$ s/January/July/' test.txt
--abcdef12 --
February April January
January March January
January January January
--abcdef12 --
</code></pre>
<p>Also tried <a href="https://unix.stackexchange.com/questions/187889/how-do-i-replace-the-last-occurrence-of-a-character-in-a-string-using-sed">https://unix.stackexchange.com/questions/187889/how-do-i-replace-the-last-occurrence-of-a-character-in-a-string-using-sed</a> - Below was the output:</p>
<pre><code>sed 's/\(.*\)January/\1July/' test.txt
--abcdef12 --
February April July
January March July
January January July
--abcdef12 --
</code></pre>
<p>I am also curious to know why the above two options do not work!</p>
|
[
{
"answer_id": 74521405,
"author": "Haleemur Ali",
"author_id": 2570261,
"author_profile": "https://Stackoverflow.com/users/2570261",
"pm_score": 3,
"selected": true,
"text": "np.split cut_points split_arr = np.split(arr, cut_points)\n\n# split_arr looks like:\n# [array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),\n# array([39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]),\n# array([66, 67, 68, 69, 70, 71])]\n import numpy as np\narr = np.array((0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 39, 40,\n 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 66, 67, 68, 69, 70, 71))\ncut_points = np.where(np.diff(arr) != 1)[0] + 1\nsplit_arr = np.split(arr, split_points)\nsplit_arr\n# outputs:\n[array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),\n array([39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]),\n array([66, 67, 68, 69, 70, 71])]\n"
},
{
"answer_id": 74521538,
"author": "ChatterOne",
"author_id": 1485311,
"author_profile": "https://Stackoverflow.com/users/1485311",
"pm_score": 1,
"selected": false,
"text": "l = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 66, 67, 68, 69, 70, 71)\ni = 0\ncurrent_index = -1\nprev_value = None\nresult = []\nfor k in l[::-1]:\n current_value = k + i\n if prev_value != current_value:\n prev_value = current_value\n current_index += 1\n result.append([])\n result[current_index].append(k)\n i += 1\nprint(result)\n [\n [71, 70, 69, 68, 67, 66],\n [55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39],\n [14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n]\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6604643/"
] |
74,521,327
|
<pre><code>private void button1_Click_1(object sender, EventArgs e)
{
lbl_startingTest.Text = "Flashing DUT..";
lbl_Result.Text = "Flash";
Process fls1 = new Process();
fls1.StartInfo.UseShellExecute = false;
fls1.StartInfo.FileName = "C:\\test\\test\\bin\\Debug\\flash.bat";
fls1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
fls1.Start();
fls1.WaitForExit();
}
</code></pre>
<p>I tried to use fls1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; to see if it hides CMD window. But when I run the application software it pops up CMD window when I click button on application. How can I hide the CMD window and still run .bat file in background?</p>
|
[
{
"answer_id": 74521379,
"author": "frankM_DN",
"author_id": 20034020,
"author_profile": "https://Stackoverflow.com/users/20034020",
"pm_score": -1,
"selected": false,
"text": "CreateNoWindow fls1.StartInfo.CreateNoWindow = true;"
},
{
"answer_id": 74523713,
"author": "apollosoftware.org",
"author_id": 937222,
"author_profile": "https://Stackoverflow.com/users/937222",
"pm_score": 0,
"selected": false,
"text": " private void button1_Click_1(object sender, EventArgs e)\n {\n\n lbl_startingTest.Text = \"Flashing DUT..\";\n lbl_Result.Text = \"Flash\";\n fls1.StartInfo.UseShellExecute = true;\n Process fls1 = new Process();\n fls1.StartInfo.FileName = \"C:\\\\test\\\\test\\\\bin\\\\Debug\\\\flash.bat\";\n fls1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\n fls1.Start();\n fls1.WaitForExit();\n }\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20564425/"
] |
74,521,333
|
<p>I have written following conversion that works okey in T-SQL :</p>
<pre><code>SELECT * FROM thetable
WHERE convert(datetime, SomeDate, 103) >= '2020-10-01 00:00:00.000
</code></pre>
<p>When downloading data from Sales Force using Azure Data Factory, I pasted the same command and it has returned syntax error.
Is there another SQL dialect that Sales Force recognizes ? If so, how can I rewrite varchar(string) to date conversion to use it in WHERE statement?</p>
|
[
{
"answer_id": 74521379,
"author": "frankM_DN",
"author_id": 20034020,
"author_profile": "https://Stackoverflow.com/users/20034020",
"pm_score": -1,
"selected": false,
"text": "CreateNoWindow fls1.StartInfo.CreateNoWindow = true;"
},
{
"answer_id": 74523713,
"author": "apollosoftware.org",
"author_id": 937222,
"author_profile": "https://Stackoverflow.com/users/937222",
"pm_score": 0,
"selected": false,
"text": " private void button1_Click_1(object sender, EventArgs e)\n {\n\n lbl_startingTest.Text = \"Flashing DUT..\";\n lbl_Result.Text = \"Flash\";\n fls1.StartInfo.UseShellExecute = true;\n Process fls1 = new Process();\n fls1.StartInfo.FileName = \"C:\\\\test\\\\test\\\\bin\\\\Debug\\\\flash.bat\";\n fls1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\n fls1.Start();\n fls1.WaitForExit();\n }\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13158157/"
] |
74,521,338
|
<p>I am consuming data from an API and whenever I try to do so, I keep getting this error.
Type List Dynamic Is Not A Subtype Of Type Map String Dynamic</p>
<p>In my attempt to find answers, I came across this <a href="https://stackoverflow.com/questions/51854891/error-listdynamic-is-not-a-subtype-of-type-mapstring-dynamic">Similar Question</a></p>
<p>I have also gone through this <a href="https://stackoverflow.com/questions/65272253/type-listdynamic-is-not-a-subtype-of-type-mapstring-dynamic-in-flutter-ap">Another Similar Question</a></p>
<p>And this as well <a href="https://stackoverflow.com/questions/68485753/type-list-dynamic-is-not-a-subtype-of-type-map-string-dynamic">A similar question again</a></p>
<p>From this similar question, I realized that there seems to be a data structure mismatch but I can't seem to get the solution to it.</p>
<p>Below are excerpts of my code</p>
<p>This is the Object Model</p>
<pre><code>
</code></pre>
<pre><code>class Book {
int? id = 0;
String? title = "";
String? description = "";
String? image = "";
String? author = "";
Book({
this.id,
this.title,
this.description,
this.image,
this.author,
});
Book.fromJson(Map<String, dynamic> parsedJson) {
id = parsedJson['id'];
title = parsedJson['title'];
description = parsedJson['description'];
image = parsedJson['image'];
author = parsedJson['author'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['title'] = this.title;
data['description'] = this.description;
data['image'] = this.image;
data['author'] = this.author;
return data;
}
}
</code></pre>
<pre><code>
</code></pre>
<p>This is the Controller Class that seems to contain the error. I am able to print the content coming from the backend though.</p>
<pre><code>
</code></pre>
<pre><code>import 'dart:io';
import 'package:elibrary/model/books.dart';
import 'package:elibrary/services/repository/book_repository.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class BookController extends GetxController {
BookRepository bookRepository = BookRepository();
RxBool isLoading = false.obs;
RxList<Book> bookList = <Book>[].obs;
@override
void onInit() {
super.onInit();
fetchBooksList();
}
Future<void> fetchBooksList() async {
isLoading(true);
try {
Response bookResponse = await bookRepository.fetchBooks();
if (bookResponse.statusCode == 200) {
for (var element in bookResponse.body) {
bookList.add(Book.fromJson(element));
}
} else {
Get.snackbar(
'Error Occurred',
bookResponse.statusText.toString(),
snackPosition: SnackPosition.BOTTOM,
colorText: Colors.white,
backgroundColor: Colors.red,
);
}
} catch (e) {
debugPrint(
e.toString(),
);
Get.snackbar(
"Error Occurred",
e.toString(),
snackPosition: SnackPosition.BOTTOM,
colorText: Colors.white,
backgroundColor: Colors.green,
duration: Duration(seconds: 5),
).show();
} finally {
isLoading(false);
}
}
}
</code></pre>
<pre><code>
</code></pre>
<p>I did try changing the model object to this</p>
<pre><code>
</code></pre>
<pre><code>import 'dart:convert';
Book bookFromJson(String str) => Book.fromJson(json.decode(str));
String bookToJson(Book data) => json.encode(data.toJson());
class Book {
Book({
this.id,
this.title,
this.description,
this.image,
this.author,
});
int id;
String title;
String description;
String image;
String author;
factory Book.fromJson(Map<String, dynamic> json) => Book(
id: json["id"],
title: json["title"],
description: json["description"],
image: json["image"],
author: json["author"],,
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"description": description,
"image": image,
"author": author,
};
}
</code></pre>
<pre><code>
</code></pre>
<p>And then I tried the controller this way also</p>
<pre><code>
</code></pre>
<pre><code>import 'dart:io';
import 'package:elibrary/model/books.dart';
import 'package:elibrary/services/repository/book_repository.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class BookController extends GetxController {
BookRepository bookRepository = BookRepository();
RxBool isLoading = false.obs;
RxList<Book> bookList = <Book>[].obs;
@override
void onInit() {
super.onInit();
fetchBooksList();
}
Future<void> fetchBooksList() async {
isLoading(true);
try {
Response bookResponse = await bookRepository.fetchBooks();
if (bookResponse.statusCode == 200) {
bookList.assAll(
bookFromJson(bookResponse.bodyString ?? ''),
)
} else {
Get.snackbar(
'Error Occurred',
bookResponse.statusText.toString(),
snackPosition: SnackPosition.BOTTOM,
colorText: Colors.white,
backgroundColor: Colors.red,
);
}
} catch (e) {
debugPrint(
e.toString(),
);
Get.snackbar(
"Error Occurred",
e.toString(),
snackPosition: SnackPosition.BOTTOM,
colorText: Colors.white,
backgroundColor: Colors.green,
duration: Duration(seconds: 5),
).show();
} finally {
isLoading(false);
}
}
}
```
```
Again I tried decoding the response this way
```
```
var jsonList = jsonDecode(bookResponse.bodyString ?? '')
.map((book) => Book.fromJson(book))
.toList();
bookList.assignAll(jsonList);
debugPrint('Total Book List is: ${bookList.length}');
</code></pre>
<pre><code>
</code></pre>
<p>All these attempts produce the same error.</p>
<p>These is the API Response</p>
<pre><code>I/flutter ( 5788): key = data, value = [{id: 1, name: dolore, icon: http://192.168.1.102:8000/images/categories/https://via.placeholder.com/640x480.png/007766?text=architecto}, {id: 2, name: repellat, icon: http://192.168.1.102:8000/images/categories/https://via.placeholder.com/640x480.png/004444?text=voluptatum}, {id: 3, name: est, icon: http://192.168.1.102:8000/images/categories/https://via.placeholder.com/640x480.png/005577?text=et}, {id: 4, name: quasi, icon: http://192.168.1.102:8000/images/categories/https://via.placeholder.com/640x480.png/00cc00?text=deserunt}, {id: 5, name: provident, icon: http://192.168.1.102:8000/images/categories/https://via.placeholder.com/640x480.png/008888?text=et}, {id: 6, name: quo, icon: http://192.168.1.102:8000/images/categories/https://via.placeholder.com/640x480.png/007777?text=dolorem}, {id: 7, name: expedita, icon: http://192.168.1.102:8000/images/categories/https://via.placeholder.com/640x480.png/00aa88?text=adipisci}, {id: 8, name: quia, icon: http://192.168.1.102:8000/images/categor
I/flutter ( 5788): result = {"data":[{"id":1,"name":"dolore","icon":"http:\/\/192.168.1.102:8000\/images\/categories\/https:\/\/via.placeholder.com\/640x480.png\/007766?text=architecto"},{"id":2,"name":"repellat","icon":"http:\/\/192.168.1.102:8000\/images\/categories\/https:\/\/via.placeholder.com\/640x480.png\/004444?text=voluptatum"},{"id":3,"name":"est","icon":"http:\/\/192.168.1.102:8000\/images\/categories\/https:\/\/via.placeholder.com\/640x480.png\/005577?text=et"},{"id":4,"name":"quasi","icon":"http:\/\/192.168.1.102:8000\/images\/categories\/https:\/\/via.placeholder.com\/640x480.png\/00cc00?text=deserunt"},{"id":5,"name":"provident","icon":"http:\/\/192.168.1.102:8000\/images\/categories\/https:\/\/via.placeholder.com\/640x480.png\/008888?text=et"},{"id":6,"name":"quo","icon":"http:\/\/192.168.1.102:8000\/images\/categories\/https:\/\/via.placeholder.com\/640x480.png\/007777?text=dolorem"},{"id":7,"name":"expedita","icon":"http:\/\/192.168.1.102:8000\/images\/categories\/https:\/\/via.placeholder.com\/640x480.png\/0
I/flutter ( 5788): Total Book List is: 0
I/flutter ( 5788): type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
</code></pre>
|
[
{
"answer_id": 74521379,
"author": "frankM_DN",
"author_id": 20034020,
"author_profile": "https://Stackoverflow.com/users/20034020",
"pm_score": -1,
"selected": false,
"text": "CreateNoWindow fls1.StartInfo.CreateNoWindow = true;"
},
{
"answer_id": 74523713,
"author": "apollosoftware.org",
"author_id": 937222,
"author_profile": "https://Stackoverflow.com/users/937222",
"pm_score": 0,
"selected": false,
"text": " private void button1_Click_1(object sender, EventArgs e)\n {\n\n lbl_startingTest.Text = \"Flashing DUT..\";\n lbl_Result.Text = \"Flash\";\n fls1.StartInfo.UseShellExecute = true;\n Process fls1 = new Process();\n fls1.StartInfo.FileName = \"C:\\\\test\\\\test\\\\bin\\\\Debug\\\\flash.bat\";\n fls1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\n fls1.Start();\n fls1.WaitForExit();\n }\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11439544/"
] |
74,521,356
|
<p>I have a table with information in column A and an appropriate value in column B. I want to write a macro that inserts a new row for each "Person" in dependence of the value in column B and copies the original information into that row, which for example means that in the end there are 5 rows with "Person A", 2 rows for "Person B" etc.</p>
<p><strong>original table:</strong></p>
<p><a href="https://i.stack.imgur.com/Kax10.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Kax10.png" alt="enter image description here" /></a></p>
<p><strong>result:</strong></p>
<p><a href="https://i.stack.imgur.com/Q6z4v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q6z4v.png" alt="enter image description here" /></a></p>
<p>My first approach looks like that. It doesn't work.</p>
<pre><code>Dim i, j, k As Integer
For i = Range("A" & Range("A:A").Rows.Count).End(xlUp).Row To 1 Step -1
For j = 1 To Range("B" & i)
Rows(i).Select
Selection.Insert Shift:=xlDown
k = k + j
Range(Cells(k, 1), Cells(k, 2)).Copy Destination:=Range("A" & i)
Next j
Next i
</code></pre>
|
[
{
"answer_id": 74521379,
"author": "frankM_DN",
"author_id": 20034020,
"author_profile": "https://Stackoverflow.com/users/20034020",
"pm_score": -1,
"selected": false,
"text": "CreateNoWindow fls1.StartInfo.CreateNoWindow = true;"
},
{
"answer_id": 74523713,
"author": "apollosoftware.org",
"author_id": 937222,
"author_profile": "https://Stackoverflow.com/users/937222",
"pm_score": 0,
"selected": false,
"text": " private void button1_Click_1(object sender, EventArgs e)\n {\n\n lbl_startingTest.Text = \"Flashing DUT..\";\n lbl_Result.Text = \"Flash\";\n fls1.StartInfo.UseShellExecute = true;\n Process fls1 = new Process();\n fls1.StartInfo.FileName = \"C:\\\\test\\\\test\\\\bin\\\\Debug\\\\flash.bat\";\n fls1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;\n fls1.Start();\n fls1.WaitForExit();\n }\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11535108/"
] |
74,521,374
|
<p>I am wondering how can I connect the borders between the gaps so it would look like this :</p>
<p><a href="https://imgur.com/a/cW2Qe3Q" rel="nofollow noreferrer">https://imgur.com/a/cW2Qe3Q</a></p>
<p>I tried to remake it in table instead of div table, but same issue appeared.</p>
<p>As a junior I am going to be happy for any help or advice.</p>
<p>when i tried using a could not still get the result of border-radius in corners and connecting the bottom lines.</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-css lang-css prettyprint-override"><code>* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100%;
width: 100vw;
overflow-x: hidden;
}
.container {
display: flex;
justify-content: center;
margin-top: 5rem;
flex-direction: column;
}
.vh {
visibility: hidden;
}
.table {
margin-bottom: 1rem;
display: flex;
justify-content: center;
}
.table-wrap {
display: flex;
align-items: center;
flex-direction: column;
}
.table__row {
min-width: 50px;
margin-right: 1rem;
}
.table__row__top {
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
.table p {
padding: 1rem 2rem;
border: 1px solid #dadada;
margin-top: -1px;
margin-left: -1px;
height: 55px;
}
.table__desc p {
padding: 1rem 2rem;
}
.table__btn--black {
background-color: #000;
}
.table__btns {
display: flex;
}
.table__btn {
display: flex;
justify-content: center;
padding: 1rem 0.5rem 0.5rem 0.5rem;
}
.table__btn__el {
width: 100%;
background-color: #1f48ff;
border: none;
border-radius: 5px;
padding: 1rem;
font-weight: 600;
color: #fff;
text-decoration: none;
text-align: center;
}
.table__btn__el:hover {
background-color: #152569;
}
.table__btn__el--black {
background-color: #000;
}
.table__btn:first-child {
padding-left: 0;
}
.radius-t-l {
border-top-left-radius: 5px;
}
.radius-b-l {
border-bottom-left-radius: 5px;
}
.radius-t-r {
border-top-right-radius: 5px;
}
.radius-b-r {
border-bottom-right-radius: 5px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="table-wrap">
<div>
<div class="table">
<div class="table__row__desc">
<p class="vh" aria-hidden="true">empty cell</p>
<p class="radius-t-l">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>
<p class="radius-b-l">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>
</div>
<div class="table__row">
<p class="table__row__top">company</p>
<p>✔️</p>
<p>✔️</p>
<p>✔️</p>
<p>✔️</p>
<p>✔️</p>
<p>✔️</p>
</div>
<div class="table__row">
<p class="table__row__top">company</p>
<p>❌</p>
<p>✔️</p>
<p>✔️</p>
<p>❌</p>
<p>✔️</p>
<p>❌</p>
</div>
<div class="table__row">
<p class="table__row__top">company</p>
<p>✔️</p>
<p>❌</p>
<p>✔️</p>
<p>✔️</p>
<p>❌</p>
<p>❌</p>
</div>
<div class="table__row">
<p class="table__row__top">company</p>
<p>✔️</p>
<p>✔️</p>
<p>❌</p>
<p>❌</p>
<p>✔️</p>
<p class="radius-b-r">✔️</p>
</div>
</div>
<div class="table__btns">
<div class="table__btn"><a href="#" class="table__btn__el">Get Started</a></div>
<div class="table__btn"><a href="#" class="table__btn__el table__btn__el--black">Get Started</a></div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 74521521,
"author": "陳禮文",
"author_id": 20412835,
"author_profile": "https://Stackoverflow.com/users/20412835",
"pm_score": 1,
"selected": false,
"text": "table {\n border-collapse: collapse;\n}\n\ntd {\n border: solid 1px;\n padding: 0 4px;\n} <table>\n <tr>\n <td>Hi</td>\n <td>Hi</td>\n <td>✔️</td>\n <td></td>\n <td>❌</td>\n <td>✔️</td>\n <td></td>\n <td>❌</td>\n <td>✔️</td>\n <td></td>\n <td>❌</td>\n </tr>\n</table>"
},
{
"answer_id": 74521781,
"author": "Adam",
"author_id": 12571484,
"author_profile": "https://Stackoverflow.com/users/12571484",
"pm_score": 1,
"selected": true,
"text": "* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nbody {\n height: 100%;\n width: 100vw;\n overflow-x: hidden;\n}\n\n.container {\n display: flex;\n justify-content: center;\n margin-top: 5rem;\n flex-direction: column;\n}\n\n.vh {\n visibility: hidden;\n}\n\n.table {\n margin-bottom: 1rem;\n display: flex;\n justify-content: center;\n}\n\n.table-wrap {\n display: flex;\n align-items: center;\n flex-direction: column;\n}\n\n.table__row {\n min-width: 50px;\n /* margin-right: 1rem; removed this */\n}\n\n.table__row__top {\n border-top-left-radius: 5px;\n border-top-right-radius: 5px;\n}\n\n.table p {\n padding: 1rem 2rem;\n border: 1px solid #dadada;\n margin-top: -1px;\n margin-left: -1px;\n height: 55px;\n}\n\n.table__desc p {\n padding: 1rem 2rem;\n}\n\n.table__btn--black {\n background-color: #000;\n}\n\n.table__btns {\n display: flex;\n}\n\n.table__btn {\n display: flex;\n justify-content: center;\n padding: 1rem 0.5rem 0.5rem 0.5rem;\n}\n\n.table__btn__el {\n width: 100%;\n background-color: #1f48ff;\n border: none;\n border-radius: 5px;\n padding: 1rem;\n font-weight: 600;\n color: #fff;\n text-decoration: none;\n text-align: center;\n}\n\n.table__btn__el:hover {\n background-color: #152569;\n}\n\n.table__btn__el--black {\n background-color: #000;\n}\n\n.table__btn:first-child {\n padding-left: 0;\n}\n\n\n/*added block */\n\n.table__separator p {\n width: 1rem;\n padding: 0;\n}\n\n.table__separator p:first-child {\n border-top-style: none;\n}\n\n\n/*end of added block */\n\n.radius-t-l {\n border-top-left-radius: 5px;\n}\n\n.radius-b-l {\n border-bottom-left-radius: 5px;\n}\n\n.radius-t-r {\n border-top-right-radius: 5px;\n}\n\n.radius-b-r {\n border-bottom-right-radius: 5px;\n} <br>\n\n<div class=\"table-wrap\">\n <div>\n <div class=\"table\">\n <div class=\"table__row__desc\">\n <p class=\"vh\" aria-hidden=\"true\">empty cell</p>\n <p class=\"radius-t-l\">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>\n <p>Lorem ipsum dolor sit amet consectetur </p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>\n <p class=\"radius-b-l\">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>\n </div>\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n </div>\n <!-- added this -->\n <div class=\"table__separator\">\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n </div>\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>❌</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>✔️</p>\n <p>❌</p>\n </div>\n <!-- added this -->\n <div class=\"table__separator\">\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n </div>\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>❌</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>❌</p>\n </div>\n <!-- added this -->\n <div class=\"table__separator\">\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n </div>\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>❌</p>\n <p>✔️</p>\n <p class=\"radius-b-r\">✔️</p>\n </div>\n\n </div>\n <div class=\"table__btns\">\n <div class=\"table__btn\"><a href=\"#\" class=\"table__btn__el\">Get Started</a></div>\n <div class=\"table__btn\"><a href=\"#\" class=\"table__btn__el table__btn__el--black\">Get Started</a></div>\n </div>\n </div>\n</div> * {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nbody {\n height: 100%;\n width: 100vw;\n overflow-x: hidden;\n}\n\n.container {\n display: flex;\n justify-content: center;\n margin-top: 5rem;\n flex-direction: column;\n}\n\n.vh {\n visibility: hidden;\n}\n\n.table {\n margin-bottom: 1rem;\n display: flex;\n justify-content: center;\n}\n\n.table-wrap {\n display: flex;\n align-items: center;\n flex-direction: column;\n}\n\n.table__row {\n min-width: 50px;\n margin-right: 1rem;\n}\n\n\n/* added this block */\n\n.table__row.gap p {\n position: relative;\n}\n\n.table__row.gap p::after {\n position: absolute;\n right: -1rem;\n bottom: -1px;\n content: \"\";\n border-bottom: 1px solid #dadada;\n width: 1rem;\n}\n\n\n/*end of added block */\n\n.table__row__top {\n border-top-left-radius: 5px;\n border-top-right-radius: 5px;\n}\n\n.table p {\n padding: 1rem 2rem;\n border: 1px solid #dadada;\n margin-top: -1px;\n margin-left: -1px;\n height: 55px;\n}\n\n.table__desc p {\n padding: 1rem 2rem;\n}\n\n.table__btn--black {\n background-color: #000;\n}\n\n.table__btns {\n display: flex;\n}\n\n.table__btn {\n display: flex;\n justify-content: center;\n padding: 1rem 0.5rem 0.5rem 0.5rem;\n}\n\n.table__btn__el {\n width: 100%;\n background-color: #1f48ff;\n border: none;\n border-radius: 5px;\n padding: 1rem;\n font-weight: 600;\n color: #fff;\n text-decoration: none;\n text-align: center;\n}\n\n.table__btn__el:hover {\n background-color: #152569;\n}\n\n.table__btn__el--black {\n background-color: #000;\n}\n\n.table__btn:first-child {\n padding-left: 0;\n}\n\n\n/*added block */\n\n\n/*end of added block */\n\n.radius-t-l {\n border-top-left-radius: 5px;\n}\n\n.radius-b-l {\n border-bottom-left-radius: 5px;\n}\n\n.radius-t-r {\n border-top-right-radius: 5px;\n}\n\n.radius-b-r {\n border-bottom-right-radius: 5px;\n} <br>\n\n<div class=\"table-wrap\">\n <div>\n <div class=\"table\">\n <div class=\"table__row__desc\">\n <p class=\"vh\" aria-hidden=\"true\">empty cell</p>\n <p class=\"radius-t-l\">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>\n <p>Lorem ipsum dolor sit amet consectetur </p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>\n <p class=\"radius-b-l\">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>\n </div>\n <div class=\"table__row gap\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n </div>\n\n <div class=\"table__row gap\">\n <p class=\"table__row__top\">company</p>\n <p>❌</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>✔️</p>\n <p>❌</p>\n </div>\n\n <div class=\"table__row gap\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>❌</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>❌</p>\n </div>\n\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>❌</p>\n <p>✔️</p>\n <p class=\"radius-b-r\">✔️</p>\n </div>\n\n </div>\n <div class=\"table__btns\">\n <div class=\"table__btn\"><a href=\"#\" class=\"table__btn__el\">Get Started</a></div>\n <div class=\"table__btn\"><a href=\"#\" class=\"table__btn__el table__btn__el--black\">Get Started</a></div>\n </div>\n </div>\n</div>"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20564325/"
] |
74,521,380
|
<p>How can we mask/hide password claim so the developers who are troubleshooting the journeys do not see users passwords?</p>
|
[
{
"answer_id": 74521521,
"author": "陳禮文",
"author_id": 20412835,
"author_profile": "https://Stackoverflow.com/users/20412835",
"pm_score": 1,
"selected": false,
"text": "table {\n border-collapse: collapse;\n}\n\ntd {\n border: solid 1px;\n padding: 0 4px;\n} <table>\n <tr>\n <td>Hi</td>\n <td>Hi</td>\n <td>✔️</td>\n <td></td>\n <td>❌</td>\n <td>✔️</td>\n <td></td>\n <td>❌</td>\n <td>✔️</td>\n <td></td>\n <td>❌</td>\n </tr>\n</table>"
},
{
"answer_id": 74521781,
"author": "Adam",
"author_id": 12571484,
"author_profile": "https://Stackoverflow.com/users/12571484",
"pm_score": 1,
"selected": true,
"text": "* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nbody {\n height: 100%;\n width: 100vw;\n overflow-x: hidden;\n}\n\n.container {\n display: flex;\n justify-content: center;\n margin-top: 5rem;\n flex-direction: column;\n}\n\n.vh {\n visibility: hidden;\n}\n\n.table {\n margin-bottom: 1rem;\n display: flex;\n justify-content: center;\n}\n\n.table-wrap {\n display: flex;\n align-items: center;\n flex-direction: column;\n}\n\n.table__row {\n min-width: 50px;\n /* margin-right: 1rem; removed this */\n}\n\n.table__row__top {\n border-top-left-radius: 5px;\n border-top-right-radius: 5px;\n}\n\n.table p {\n padding: 1rem 2rem;\n border: 1px solid #dadada;\n margin-top: -1px;\n margin-left: -1px;\n height: 55px;\n}\n\n.table__desc p {\n padding: 1rem 2rem;\n}\n\n.table__btn--black {\n background-color: #000;\n}\n\n.table__btns {\n display: flex;\n}\n\n.table__btn {\n display: flex;\n justify-content: center;\n padding: 1rem 0.5rem 0.5rem 0.5rem;\n}\n\n.table__btn__el {\n width: 100%;\n background-color: #1f48ff;\n border: none;\n border-radius: 5px;\n padding: 1rem;\n font-weight: 600;\n color: #fff;\n text-decoration: none;\n text-align: center;\n}\n\n.table__btn__el:hover {\n background-color: #152569;\n}\n\n.table__btn__el--black {\n background-color: #000;\n}\n\n.table__btn:first-child {\n padding-left: 0;\n}\n\n\n/*added block */\n\n.table__separator p {\n width: 1rem;\n padding: 0;\n}\n\n.table__separator p:first-child {\n border-top-style: none;\n}\n\n\n/*end of added block */\n\n.radius-t-l {\n border-top-left-radius: 5px;\n}\n\n.radius-b-l {\n border-bottom-left-radius: 5px;\n}\n\n.radius-t-r {\n border-top-right-radius: 5px;\n}\n\n.radius-b-r {\n border-bottom-right-radius: 5px;\n} <br>\n\n<div class=\"table-wrap\">\n <div>\n <div class=\"table\">\n <div class=\"table__row__desc\">\n <p class=\"vh\" aria-hidden=\"true\">empty cell</p>\n <p class=\"radius-t-l\">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>\n <p>Lorem ipsum dolor sit amet consectetur </p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>\n <p class=\"radius-b-l\">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>\n </div>\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n </div>\n <!-- added this -->\n <div class=\"table__separator\">\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n </div>\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>❌</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>✔️</p>\n <p>❌</p>\n </div>\n <!-- added this -->\n <div class=\"table__separator\">\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n </div>\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>❌</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>❌</p>\n </div>\n <!-- added this -->\n <div class=\"table__separator\">\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n </div>\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>❌</p>\n <p>✔️</p>\n <p class=\"radius-b-r\">✔️</p>\n </div>\n\n </div>\n <div class=\"table__btns\">\n <div class=\"table__btn\"><a href=\"#\" class=\"table__btn__el\">Get Started</a></div>\n <div class=\"table__btn\"><a href=\"#\" class=\"table__btn__el table__btn__el--black\">Get Started</a></div>\n </div>\n </div>\n</div> * {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nbody {\n height: 100%;\n width: 100vw;\n overflow-x: hidden;\n}\n\n.container {\n display: flex;\n justify-content: center;\n margin-top: 5rem;\n flex-direction: column;\n}\n\n.vh {\n visibility: hidden;\n}\n\n.table {\n margin-bottom: 1rem;\n display: flex;\n justify-content: center;\n}\n\n.table-wrap {\n display: flex;\n align-items: center;\n flex-direction: column;\n}\n\n.table__row {\n min-width: 50px;\n margin-right: 1rem;\n}\n\n\n/* added this block */\n\n.table__row.gap p {\n position: relative;\n}\n\n.table__row.gap p::after {\n position: absolute;\n right: -1rem;\n bottom: -1px;\n content: \"\";\n border-bottom: 1px solid #dadada;\n width: 1rem;\n}\n\n\n/*end of added block */\n\n.table__row__top {\n border-top-left-radius: 5px;\n border-top-right-radius: 5px;\n}\n\n.table p {\n padding: 1rem 2rem;\n border: 1px solid #dadada;\n margin-top: -1px;\n margin-left: -1px;\n height: 55px;\n}\n\n.table__desc p {\n padding: 1rem 2rem;\n}\n\n.table__btn--black {\n background-color: #000;\n}\n\n.table__btns {\n display: flex;\n}\n\n.table__btn {\n display: flex;\n justify-content: center;\n padding: 1rem 0.5rem 0.5rem 0.5rem;\n}\n\n.table__btn__el {\n width: 100%;\n background-color: #1f48ff;\n border: none;\n border-radius: 5px;\n padding: 1rem;\n font-weight: 600;\n color: #fff;\n text-decoration: none;\n text-align: center;\n}\n\n.table__btn__el:hover {\n background-color: #152569;\n}\n\n.table__btn__el--black {\n background-color: #000;\n}\n\n.table__btn:first-child {\n padding-left: 0;\n}\n\n\n/*added block */\n\n\n/*end of added block */\n\n.radius-t-l {\n border-top-left-radius: 5px;\n}\n\n.radius-b-l {\n border-bottom-left-radius: 5px;\n}\n\n.radius-t-r {\n border-top-right-radius: 5px;\n}\n\n.radius-b-r {\n border-bottom-right-radius: 5px;\n} <br>\n\n<div class=\"table-wrap\">\n <div>\n <div class=\"table\">\n <div class=\"table__row__desc\">\n <p class=\"vh\" aria-hidden=\"true\">empty cell</p>\n <p class=\"radius-t-l\">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>\n <p>Lorem ipsum dolor sit amet consectetur </p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>\n <p class=\"radius-b-l\">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>\n </div>\n <div class=\"table__row gap\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n </div>\n\n <div class=\"table__row gap\">\n <p class=\"table__row__top\">company</p>\n <p>❌</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>✔️</p>\n <p>❌</p>\n </div>\n\n <div class=\"table__row gap\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>❌</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>❌</p>\n </div>\n\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>❌</p>\n <p>✔️</p>\n <p class=\"radius-b-r\">✔️</p>\n </div>\n\n </div>\n <div class=\"table__btns\">\n <div class=\"table__btn\"><a href=\"#\" class=\"table__btn__el\">Get Started</a></div>\n <div class=\"table__btn\"><a href=\"#\" class=\"table__btn__el table__btn__el--black\">Get Started</a></div>\n </div>\n </div>\n</div>"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/273639/"
] |
74,521,382
|
<p>I have a Hashmap <code>HashMap <Integer, Integer> map</code> and I want to change the <code>keyset()</code> type to a BinaryTreeNode, which was declared beforehand already, instead of an int, which I am able to do. However, I was wondering how could I add the appropriate <code>map.values()</code> in the same order as it was in my original HashMap <code>map</code></p>
<p>Here is my code</p>
<pre><code>public static BinaryTreeNode parentMapToTree(Map<Integer, Integer> map) {
HashMap<BinaryTreeNode, Integer> l = new HashMap<>();
for (int i = 0; i < map.keySet().size(); i++){
BinaryTreeNode node = new BinaryTreeNode(i);
l.put(node, map.values());
}
</code></pre>
<p>What changes to my code should I make to ensure that this would compile and do as I want it o?</p>
|
[
{
"answer_id": 74521521,
"author": "陳禮文",
"author_id": 20412835,
"author_profile": "https://Stackoverflow.com/users/20412835",
"pm_score": 1,
"selected": false,
"text": "table {\n border-collapse: collapse;\n}\n\ntd {\n border: solid 1px;\n padding: 0 4px;\n} <table>\n <tr>\n <td>Hi</td>\n <td>Hi</td>\n <td>✔️</td>\n <td></td>\n <td>❌</td>\n <td>✔️</td>\n <td></td>\n <td>❌</td>\n <td>✔️</td>\n <td></td>\n <td>❌</td>\n </tr>\n</table>"
},
{
"answer_id": 74521781,
"author": "Adam",
"author_id": 12571484,
"author_profile": "https://Stackoverflow.com/users/12571484",
"pm_score": 1,
"selected": true,
"text": "* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nbody {\n height: 100%;\n width: 100vw;\n overflow-x: hidden;\n}\n\n.container {\n display: flex;\n justify-content: center;\n margin-top: 5rem;\n flex-direction: column;\n}\n\n.vh {\n visibility: hidden;\n}\n\n.table {\n margin-bottom: 1rem;\n display: flex;\n justify-content: center;\n}\n\n.table-wrap {\n display: flex;\n align-items: center;\n flex-direction: column;\n}\n\n.table__row {\n min-width: 50px;\n /* margin-right: 1rem; removed this */\n}\n\n.table__row__top {\n border-top-left-radius: 5px;\n border-top-right-radius: 5px;\n}\n\n.table p {\n padding: 1rem 2rem;\n border: 1px solid #dadada;\n margin-top: -1px;\n margin-left: -1px;\n height: 55px;\n}\n\n.table__desc p {\n padding: 1rem 2rem;\n}\n\n.table__btn--black {\n background-color: #000;\n}\n\n.table__btns {\n display: flex;\n}\n\n.table__btn {\n display: flex;\n justify-content: center;\n padding: 1rem 0.5rem 0.5rem 0.5rem;\n}\n\n.table__btn__el {\n width: 100%;\n background-color: #1f48ff;\n border: none;\n border-radius: 5px;\n padding: 1rem;\n font-weight: 600;\n color: #fff;\n text-decoration: none;\n text-align: center;\n}\n\n.table__btn__el:hover {\n background-color: #152569;\n}\n\n.table__btn__el--black {\n background-color: #000;\n}\n\n.table__btn:first-child {\n padding-left: 0;\n}\n\n\n/*added block */\n\n.table__separator p {\n width: 1rem;\n padding: 0;\n}\n\n.table__separator p:first-child {\n border-top-style: none;\n}\n\n\n/*end of added block */\n\n.radius-t-l {\n border-top-left-radius: 5px;\n}\n\n.radius-b-l {\n border-bottom-left-radius: 5px;\n}\n\n.radius-t-r {\n border-top-right-radius: 5px;\n}\n\n.radius-b-r {\n border-bottom-right-radius: 5px;\n} <br>\n\n<div class=\"table-wrap\">\n <div>\n <div class=\"table\">\n <div class=\"table__row__desc\">\n <p class=\"vh\" aria-hidden=\"true\">empty cell</p>\n <p class=\"radius-t-l\">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>\n <p>Lorem ipsum dolor sit amet consectetur </p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>\n <p class=\"radius-b-l\">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>\n </div>\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n </div>\n <!-- added this -->\n <div class=\"table__separator\">\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n </div>\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>❌</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>✔️</p>\n <p>❌</p>\n </div>\n <!-- added this -->\n <div class=\"table__separator\">\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n </div>\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>❌</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>❌</p>\n </div>\n <!-- added this -->\n <div class=\"table__separator\">\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n </div>\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>❌</p>\n <p>✔️</p>\n <p class=\"radius-b-r\">✔️</p>\n </div>\n\n </div>\n <div class=\"table__btns\">\n <div class=\"table__btn\"><a href=\"#\" class=\"table__btn__el\">Get Started</a></div>\n <div class=\"table__btn\"><a href=\"#\" class=\"table__btn__el table__btn__el--black\">Get Started</a></div>\n </div>\n </div>\n</div> * {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nbody {\n height: 100%;\n width: 100vw;\n overflow-x: hidden;\n}\n\n.container {\n display: flex;\n justify-content: center;\n margin-top: 5rem;\n flex-direction: column;\n}\n\n.vh {\n visibility: hidden;\n}\n\n.table {\n margin-bottom: 1rem;\n display: flex;\n justify-content: center;\n}\n\n.table-wrap {\n display: flex;\n align-items: center;\n flex-direction: column;\n}\n\n.table__row {\n min-width: 50px;\n margin-right: 1rem;\n}\n\n\n/* added this block */\n\n.table__row.gap p {\n position: relative;\n}\n\n.table__row.gap p::after {\n position: absolute;\n right: -1rem;\n bottom: -1px;\n content: \"\";\n border-bottom: 1px solid #dadada;\n width: 1rem;\n}\n\n\n/*end of added block */\n\n.table__row__top {\n border-top-left-radius: 5px;\n border-top-right-radius: 5px;\n}\n\n.table p {\n padding: 1rem 2rem;\n border: 1px solid #dadada;\n margin-top: -1px;\n margin-left: -1px;\n height: 55px;\n}\n\n.table__desc p {\n padding: 1rem 2rem;\n}\n\n.table__btn--black {\n background-color: #000;\n}\n\n.table__btns {\n display: flex;\n}\n\n.table__btn {\n display: flex;\n justify-content: center;\n padding: 1rem 0.5rem 0.5rem 0.5rem;\n}\n\n.table__btn__el {\n width: 100%;\n background-color: #1f48ff;\n border: none;\n border-radius: 5px;\n padding: 1rem;\n font-weight: 600;\n color: #fff;\n text-decoration: none;\n text-align: center;\n}\n\n.table__btn__el:hover {\n background-color: #152569;\n}\n\n.table__btn__el--black {\n background-color: #000;\n}\n\n.table__btn:first-child {\n padding-left: 0;\n}\n\n\n/*added block */\n\n\n/*end of added block */\n\n.radius-t-l {\n border-top-left-radius: 5px;\n}\n\n.radius-b-l {\n border-bottom-left-radius: 5px;\n}\n\n.radius-t-r {\n border-top-right-radius: 5px;\n}\n\n.radius-b-r {\n border-bottom-right-radius: 5px;\n} <br>\n\n<div class=\"table-wrap\">\n <div>\n <div class=\"table\">\n <div class=\"table__row__desc\">\n <p class=\"vh\" aria-hidden=\"true\">empty cell</p>\n <p class=\"radius-t-l\">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>\n <p>Lorem ipsum dolor sit amet consectetur </p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>\n <p class=\"radius-b-l\">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>\n </div>\n <div class=\"table__row gap\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n </div>\n\n <div class=\"table__row gap\">\n <p class=\"table__row__top\">company</p>\n <p>❌</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>✔️</p>\n <p>❌</p>\n </div>\n\n <div class=\"table__row gap\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>❌</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>❌</p>\n </div>\n\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>❌</p>\n <p>✔️</p>\n <p class=\"radius-b-r\">✔️</p>\n </div>\n\n </div>\n <div class=\"table__btns\">\n <div class=\"table__btn\"><a href=\"#\" class=\"table__btn__el\">Get Started</a></div>\n <div class=\"table__btn\"><a href=\"#\" class=\"table__btn__el table__btn__el--black\">Get Started</a></div>\n </div>\n </div>\n</div>"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18984687/"
] |
74,521,409
|
<p>I’m trying to move bits from starting register into eight consecutive registers. I’ve just started writing in assembly so I dont really know what to do.</p>
<p>I tried to use rol and lsr instructions. But my loop just reverses the bits. can i change the registry from r18 to r19 mid-loop?</p>
<pre><code>.equ sequen = 0x10001011
ldi r17
ldi r16, 0x8
next: lsr r17
rol r18
;is there a way to move
;to next register, not
; inc its value?
dec r16
brbc 1, next
rjmp pc
</code></pre>
|
[
{
"answer_id": 74521521,
"author": "陳禮文",
"author_id": 20412835,
"author_profile": "https://Stackoverflow.com/users/20412835",
"pm_score": 1,
"selected": false,
"text": "table {\n border-collapse: collapse;\n}\n\ntd {\n border: solid 1px;\n padding: 0 4px;\n} <table>\n <tr>\n <td>Hi</td>\n <td>Hi</td>\n <td>✔️</td>\n <td></td>\n <td>❌</td>\n <td>✔️</td>\n <td></td>\n <td>❌</td>\n <td>✔️</td>\n <td></td>\n <td>❌</td>\n </tr>\n</table>"
},
{
"answer_id": 74521781,
"author": "Adam",
"author_id": 12571484,
"author_profile": "https://Stackoverflow.com/users/12571484",
"pm_score": 1,
"selected": true,
"text": "* {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nbody {\n height: 100%;\n width: 100vw;\n overflow-x: hidden;\n}\n\n.container {\n display: flex;\n justify-content: center;\n margin-top: 5rem;\n flex-direction: column;\n}\n\n.vh {\n visibility: hidden;\n}\n\n.table {\n margin-bottom: 1rem;\n display: flex;\n justify-content: center;\n}\n\n.table-wrap {\n display: flex;\n align-items: center;\n flex-direction: column;\n}\n\n.table__row {\n min-width: 50px;\n /* margin-right: 1rem; removed this */\n}\n\n.table__row__top {\n border-top-left-radius: 5px;\n border-top-right-radius: 5px;\n}\n\n.table p {\n padding: 1rem 2rem;\n border: 1px solid #dadada;\n margin-top: -1px;\n margin-left: -1px;\n height: 55px;\n}\n\n.table__desc p {\n padding: 1rem 2rem;\n}\n\n.table__btn--black {\n background-color: #000;\n}\n\n.table__btns {\n display: flex;\n}\n\n.table__btn {\n display: flex;\n justify-content: center;\n padding: 1rem 0.5rem 0.5rem 0.5rem;\n}\n\n.table__btn__el {\n width: 100%;\n background-color: #1f48ff;\n border: none;\n border-radius: 5px;\n padding: 1rem;\n font-weight: 600;\n color: #fff;\n text-decoration: none;\n text-align: center;\n}\n\n.table__btn__el:hover {\n background-color: #152569;\n}\n\n.table__btn__el--black {\n background-color: #000;\n}\n\n.table__btn:first-child {\n padding-left: 0;\n}\n\n\n/*added block */\n\n.table__separator p {\n width: 1rem;\n padding: 0;\n}\n\n.table__separator p:first-child {\n border-top-style: none;\n}\n\n\n/*end of added block */\n\n.radius-t-l {\n border-top-left-radius: 5px;\n}\n\n.radius-b-l {\n border-bottom-left-radius: 5px;\n}\n\n.radius-t-r {\n border-top-right-radius: 5px;\n}\n\n.radius-b-r {\n border-bottom-right-radius: 5px;\n} <br>\n\n<div class=\"table-wrap\">\n <div>\n <div class=\"table\">\n <div class=\"table__row__desc\">\n <p class=\"vh\" aria-hidden=\"true\">empty cell</p>\n <p class=\"radius-t-l\">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>\n <p>Lorem ipsum dolor sit amet consectetur </p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>\n <p class=\"radius-b-l\">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>\n </div>\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n </div>\n <!-- added this -->\n <div class=\"table__separator\">\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n </div>\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>❌</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>✔️</p>\n <p>❌</p>\n </div>\n <!-- added this -->\n <div class=\"table__separator\">\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n </div>\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>❌</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>❌</p>\n </div>\n <!-- added this -->\n <div class=\"table__separator\">\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n <p></p>\n </div>\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>❌</p>\n <p>✔️</p>\n <p class=\"radius-b-r\">✔️</p>\n </div>\n\n </div>\n <div class=\"table__btns\">\n <div class=\"table__btn\"><a href=\"#\" class=\"table__btn__el\">Get Started</a></div>\n <div class=\"table__btn\"><a href=\"#\" class=\"table__btn__el table__btn__el--black\">Get Started</a></div>\n </div>\n </div>\n</div> * {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n}\n\nbody {\n height: 100%;\n width: 100vw;\n overflow-x: hidden;\n}\n\n.container {\n display: flex;\n justify-content: center;\n margin-top: 5rem;\n flex-direction: column;\n}\n\n.vh {\n visibility: hidden;\n}\n\n.table {\n margin-bottom: 1rem;\n display: flex;\n justify-content: center;\n}\n\n.table-wrap {\n display: flex;\n align-items: center;\n flex-direction: column;\n}\n\n.table__row {\n min-width: 50px;\n margin-right: 1rem;\n}\n\n\n/* added this block */\n\n.table__row.gap p {\n position: relative;\n}\n\n.table__row.gap p::after {\n position: absolute;\n right: -1rem;\n bottom: -1px;\n content: \"\";\n border-bottom: 1px solid #dadada;\n width: 1rem;\n}\n\n\n/*end of added block */\n\n.table__row__top {\n border-top-left-radius: 5px;\n border-top-right-radius: 5px;\n}\n\n.table p {\n padding: 1rem 2rem;\n border: 1px solid #dadada;\n margin-top: -1px;\n margin-left: -1px;\n height: 55px;\n}\n\n.table__desc p {\n padding: 1rem 2rem;\n}\n\n.table__btn--black {\n background-color: #000;\n}\n\n.table__btns {\n display: flex;\n}\n\n.table__btn {\n display: flex;\n justify-content: center;\n padding: 1rem 0.5rem 0.5rem 0.5rem;\n}\n\n.table__btn__el {\n width: 100%;\n background-color: #1f48ff;\n border: none;\n border-radius: 5px;\n padding: 1rem;\n font-weight: 600;\n color: #fff;\n text-decoration: none;\n text-align: center;\n}\n\n.table__btn__el:hover {\n background-color: #152569;\n}\n\n.table__btn__el--black {\n background-color: #000;\n}\n\n.table__btn:first-child {\n padding-left: 0;\n}\n\n\n/*added block */\n\n\n/*end of added block */\n\n.radius-t-l {\n border-top-left-radius: 5px;\n}\n\n.radius-b-l {\n border-bottom-left-radius: 5px;\n}\n\n.radius-t-r {\n border-top-right-radius: 5px;\n}\n\n.radius-b-r {\n border-bottom-right-radius: 5px;\n} <br>\n\n<div class=\"table-wrap\">\n <div>\n <div class=\"table\">\n <div class=\"table__row__desc\">\n <p class=\"vh\" aria-hidden=\"true\">empty cell</p>\n <p class=\"radius-t-l\">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>\n <p>Lorem ipsum dolor sit amet consectetur </p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere</p>\n <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>\n <p class=\"radius-b-l\">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, aut.</p>\n </div>\n <div class=\"table__row gap\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>✔️</p>\n </div>\n\n <div class=\"table__row gap\">\n <p class=\"table__row__top\">company</p>\n <p>❌</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>✔️</p>\n <p>❌</p>\n </div>\n\n <div class=\"table__row gap\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>❌</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>❌</p>\n </div>\n\n <div class=\"table__row\">\n <p class=\"table__row__top\">company</p>\n <p>✔️</p>\n <p>✔️</p>\n <p>❌</p>\n <p>❌</p>\n <p>✔️</p>\n <p class=\"radius-b-r\">✔️</p>\n </div>\n\n </div>\n <div class=\"table__btns\">\n <div class=\"table__btn\"><a href=\"#\" class=\"table__btn__el\">Get Started</a></div>\n <div class=\"table__btn\"><a href=\"#\" class=\"table__btn__el table__btn__el--black\">Get Started</a></div>\n </div>\n </div>\n</div>"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20564291/"
] |
74,521,421
|
<p>I have a list of data:</p>
<pre><code>$nPerm
[1] "1000"
$minGSSize
[1] "10"
$maxGSSize
[1] "100"
$by
[1] "DOSE"
$seed
[1] "TRUE"
</code></pre>
<p>This list is supposed to be flexible, so these values could be different and could be something else.</p>
<p>All the data in this list is in character class, the numbers and words also. I would like to know if it is possible to convert only the numbers to numeric, but leave the others as characters/strings.</p>
<p>Thank you in advance!</p>
|
[
{
"answer_id": 74521452,
"author": "r2evans - GO NAVY BEAT ARMY",
"author_id": 3358272,
"author_profile": "https://Stackoverflow.com/users/3358272",
"pm_score": 4,
"selected": true,
"text": "L <- list(a=\"1000\", b=\"DOSE\", c=\"99\")\ntype.convert(L, as.is = TRUE)\n# $a\n# [1] 1000\n# $b\n# [1] \"DOSE\"\n# $c\n# [1] 99\n"
},
{
"answer_id": 74521506,
"author": "Julian",
"author_id": 14137004,
"author_profile": "https://Stackoverflow.com/users/14137004",
"pm_score": 2,
"selected": false,
"text": "{purrr} L <- list(a=\"1000\", b=\"DOSE\", c=\"99\")\nL |> purrr::map(~ifelse(stringr::str_detect(.x,\"^[:digit:]+$\"), as.numeric(.x), .x))\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16749673/"
] |
74,521,431
|
<p>Having a component that accepts some props:</p>
<pre><code><MyComponent first="first" second="second" third="third" />
</code></pre>
<p>We can create an object:</p>
<pre><code>const mockData = {
first: 'test1',
second: 'test2',
third: 'test3'
};
</code></pre>
<p>and use it as props in the following way: <code><MyComponent {...mockData} /></code> and it works fine.</p>
<p>What I want is to use just first two elements from the <code>mockData</code> object as none of them are required/mandatory it should not be a problem.</p>
<p>So I've tried like this: <code><MyComponent {...mockData.first, ...mockData.second} /></code> but it doesn't work.</p>
<p>Of course it can be written like <code><MyComponent first={mockData.first} second={mockData.second} /></code> but this is just an example with few elements as my real problem has more elements.</p>
<p>Is there a way to do that?</p>
|
[
{
"answer_id": 74521515,
"author": "FromThePoop",
"author_id": 16874075,
"author_profile": "https://Stackoverflow.com/users/16874075",
"pm_score": 0,
"selected": false,
"text": "type MyComponentType = Pick<mockdata, \"first\">\n"
},
{
"answer_id": 74521527,
"author": "albjerto",
"author_id": 11999748,
"author_profile": "https://Stackoverflow.com/users/11999748",
"pm_score": 0,
"selected": false,
"text": "const {third, ...rest} = mockData;\n\n// now the variable rest has all the properties from mockData except third\n\n<MyComponent {...rest}/>\n const {third, fourth, fifth, /* etc */ ...rest} = mockData;\n"
},
{
"answer_id": 74521564,
"author": "Sumer Alhussein",
"author_id": 19583202,
"author_profile": "https://Stackoverflow.com/users/19583202",
"pm_score": -1,
"selected": false,
"text": " const mockData = {\n first: 'test1',\n second: 'test2',\n third: 'test3'\n };\n\n\n<MyComponent props={ mockData } />\n\nconst MyComponent = ({first, second, third}) => {\n return (\n <div>\n first = {first}\n second = {second}\n third = {third}\n </div>\n)};\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9099077/"
] |
74,521,436
|
<p>I have a pandas DataFrame with one feature, df['Computed Data'].</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Computed Data</th>
</tr>
</thead>
<tbody>
<tr>
<td>'{"stats":{"TypeCount":{"1</td>
</tr>
<tr>
<td>25":"31","8":"31"}},"plaintsCard":[{"root":"old","plaintsCount":1,"residencyCount":1}],"Count":62,"Status":{"activable":"10","activated":"18","inactivable":"3"},"Counta":0,"invoiCount":"31"}'</td>
</tr>
<tr>
<td>'{"Count":33,"invoiCount":"11","stats":{"TypeCount":{"1":"9","4":"22","11":"2"}},"plaintsCard":[],"Count":0,"Status":{"activated":"0","activable":"9","inactivable":"1"}}'</td>
</tr>
<tr>
<td>'{"Count":79,"invoiCount":"32","stats":{"TypeCount":{"1":"29","4":"32","18":"3","23":"15"}},"plaintsCard":[],"Count":0,"Status":{"activated":"0","activable":"28","inactivable":"2"}}'</td>
</tr>
<tr>
<td>'{"Count":80,"invoiCount":"32","stats":{"TypeCount":{"1":"31","4":"42","13":"1","23":"6"}},"plaintsCard":[],"Count":0,"Status":{"activated":"0","activable":"27","inactivable":"6"}}'</td>
</tr>
<tr>
<td>'{"stats": {"TypeCount": {"17": "27"}}, "plaintsCard": [], "parcelsCount": 27, "Status": {"activable": "9", "activated": "2", "inactivable": "16"}, "Count": 0, "invoiCount": "0"}'</td>
</tr>
</tbody>
</table>
</div>
<p>I want to extract the "membersStatus", "activable" part from every string and to put it in a new column.</p>
<p>I have tried to use ast.literal_eval() and it is working but only when I apply it to one value</p>
<pre><code>x = ast.literal_eval(df["Computed Data"][0])
x["membersStatus"]["activable"]
</code></pre>
<pre><code>'10'
</code></pre>
<p>It gives me : '10'. Which is what I want but for every dict in "Computed Data" and to put it in a new column.</p>
<p>I tried to do it with a for loop :</p>
<pre><code>for n, i in enumerate(df["Computed Data"]):
x = ast.literal_eval(df["Computed Data"][n])
</code></pre>
<pre><code>ValueError: malformed node or string: <_ast.Name object at 0x13699c610>
</code></pre>
<p>I don't know how can I change what I did to make it work.</p>
<p>Can you Help please ?</p>
|
[
{
"answer_id": 74521515,
"author": "FromThePoop",
"author_id": 16874075,
"author_profile": "https://Stackoverflow.com/users/16874075",
"pm_score": 0,
"selected": false,
"text": "type MyComponentType = Pick<mockdata, \"first\">\n"
},
{
"answer_id": 74521527,
"author": "albjerto",
"author_id": 11999748,
"author_profile": "https://Stackoverflow.com/users/11999748",
"pm_score": 0,
"selected": false,
"text": "const {third, ...rest} = mockData;\n\n// now the variable rest has all the properties from mockData except third\n\n<MyComponent {...rest}/>\n const {third, fourth, fifth, /* etc */ ...rest} = mockData;\n"
},
{
"answer_id": 74521564,
"author": "Sumer Alhussein",
"author_id": 19583202,
"author_profile": "https://Stackoverflow.com/users/19583202",
"pm_score": -1,
"selected": false,
"text": " const mockData = {\n first: 'test1',\n second: 'test2',\n third: 'test3'\n };\n\n\n<MyComponent props={ mockData } />\n\nconst MyComponent = ({first, second, third}) => {\n return (\n <div>\n first = {first}\n second = {second}\n third = {third}\n </div>\n)};\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20564336/"
] |
74,521,467
|
<p>this is the code I have right now</p>
<pre><code>fname = input(">>Please Enter a file name followed by .txt ")
def writedata():
i=0
for i in range(3):
f = open(f"{fname}", 'w')
stdname = input('>>\tStudent Name: \t')
marks = input('>>\tMark for exam: \t')
f.write(stdname)
f.write("\n")
f.write(marks)
f.close()
def main():
writedata()
</code></pre>
<p>the output that is intended</p>
<pre><code>>> Please Enter a file name, followed by .txt: studentRecord.txt
>> Enter record for student 1 in the format of [1. Name, 2. Mark]:
>> Student Name: James White
>> Mark for exam: 100
>> Enter record for student 2 in the format of [1. Name, 2. Mark]:
>> Student Name: James Brown
>> Mark for exam: 85
>> Enter record for student 3 in the format of [1. Name, 2. Mark]:
>> Student Name: James King
>> Mark for exam: 75
>> Student record writing completed!
</code></pre>
<p>I tried the above code and only got the last user input in the text file. I was supposed to pass file name from def main() but I don't know how to do that, I kept getting unreachable error. Can someone please help me and explain what I'm doing wrong? Thank you for your time and consideration.</p>
|
[
{
"answer_id": 74521493,
"author": "Thornily",
"author_id": 11443623,
"author_profile": "https://Stackoverflow.com/users/11443623",
"pm_score": -1,
"selected": false,
"text": "write (w) append (a) The argument mode points to a string beginning with one of the following\n sequences (Additional characters may follow these sequences.):\n\n ``r'' Open text file for reading. The stream is positioned at the\n beginning of the file.\n\n ``r+'' Open for reading and writing. The stream is positioned at the\n beginning of the file.\n\n ``w'' Truncate file to zero length or create text file for writing.\n The stream is positioned at the beginning of the file.\n\n ``w+'' Open for reading and writing. The file is created if it does not\n exist, otherwise it is truncated. The stream is positioned at\n the beginning of the file.\n\n ``a'' Open for writing. The file is created if it does not exist. The\n stream is positioned at the end of the file. Subsequent writes\n to the file will always end up at the then current end of file,\n irrespective of any intervening fseek(3) or similar.\n\n ``a+'' Open for reading and writing. The file is created if it does not\n exist. The stream is positioned at the end of the file. Subse-\n quent writes to the file will always end up at the then current\n end of file, irrespective of any intervening fseek(3) or similar.\n"
},
{
"answer_id": 74521499,
"author": "Wang Zerui",
"author_id": 16232205,
"author_profile": "https://Stackoverflow.com/users/16232205",
"pm_score": 0,
"selected": false,
"text": " f = open(f\"{fname}\", 'w')\n w a+"
},
{
"answer_id": 74528334,
"author": "noobatprogramming",
"author_id": 20470075,
"author_profile": "https://Stackoverflow.com/users/20470075",
"pm_score": 0,
"selected": false,
"text": " fname = str(input(\">> Please Enter a file name, followed by .txt: \"))\n f = open(f\"{fname}\",\"a+\")\n for i in range(1, 4):\n print(f\">> Enter record for student {i} in the format of [1. Name, 2. Mark]:\")\n stdname = str(input(\">> Student Name: \"))\n marks = str(input(\">> Mark for exam: \"))\n f.write(stdname)\n f.write(\"\\n\")\n f.write(marks)\n f.write(\"\\n\")\n print(\"Student record writing completed!\")\n f.close()\ndef main():\n writedata()\nif __name__ == '__main__':\n main()\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20470075/"
] |
74,521,470
|
<p>Having a dataframe with have the gender of specific names</p>
<pre><code>dfgender <- data.frame(name = c("Helen","Erik"), gender = c("F","M"))
</code></pre>
<p>How is it possible to use the previous data frame in order to check the names of another column of a dataframe and insert "Neutral" if the name is not in the list of gender dataframe:
Example of the dataframe with the names:</p>
<pre><code>dfnames <- data.frame(names = c("Helen", "Von", "Erik", "Brook"))
</code></pre>
<p>Example of expected output</p>
<pre><code>dfnames <- data.frame(name = c("Helen", "Von", "Erik", "Brook"), gender = c("F", "Neutral", "M", "Neutral"))
</code></pre>
|
[
{
"answer_id": 74521518,
"author": "Juan C",
"author_id": 9462829,
"author_profile": "https://Stackoverflow.com/users/9462829",
"pm_score": 2,
"selected": false,
"text": "left_join replace_na dfnames %>% left_join(dfgender, by=c('names' = 'name')) %>% \n mutate(gender = gender %>% as.character %>% replace_na('Neutral'))\n\n# names gender\n# 1 Helen F\n# 2 Von Neutral\n# 3 Erik M\n# 4 Brook Neutral\n"
},
{
"answer_id": 74522127,
"author": "harre",
"author_id": 4786466,
"author_profile": "https://Stackoverflow.com/users/4786466",
"pm_score": 1,
"selected": false,
"text": "rows_update library(dplyr)\n\ndfnames |>\n mutate(gender = \"Neutral\") |>\n rows_update(rename(dfgender, names = name), \"names\")\n names gender\n1 Helen F\n2 Von Neutral\n3 Erik M\n4 Brook Neutral\n"
},
{
"answer_id": 74575192,
"author": "Santiago",
"author_id": 13507658,
"author_profile": "https://Stackoverflow.com/users/13507658",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\nlibrary(tidyr)\n\ndfgender <- data.frame(name = c(\"Helen\",\"Erik\"), gender = c(\"F\",\"M\"))\ndfnames <- data.frame(names = c(\"Helen\", \"Von\", \"Erik\", \"Brook\"))\n\ndfnames %>%\n left_join(dfgender, by = c(\"names\" = \"name\")) %>%\n replace_na(list(gender = \"Neutral\"))\n# names gender\n# 1 Helen F\n# 2 Von Neutral\n# 3 Erik M\n# 4 Brook Neutral\n tidyr library(dplyr)\n\ndfgender <- data.frame(name = c(\"Helen\",\"Erik\"), gender = c(\"F\",\"M\"))\ndfnames <- data.frame(names = c(\"Helen\", \"Von\", \"Erik\", \"Brook\"))\n\ndfnames %>%\n left_join(dfgender, by = c(\"names\" = \"name\")) %>%\n mutate(gender = coalesce(gender, \"Neutral\"))\n# names gender\n# 1 Helen F\n# 2 Von Neutral\n# 3 Erik M\n# 4 Brook Neutral\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20224217/"
] |
74,521,481
|
<p>AndroidManifest.xml showing me 10 errors in the code below. I am unable to understand why it is showing these errors and how can I resolve this. Help me out from these errors.</p>
<pre><code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.buis_talk">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:requestLegacyExternalStorage="true"
android:label="buis_talk"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:exported="true"
android:usesCleartextTraffic="true"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
</code></pre>
<p><a href="https://i.stack.imgur.com/hi2VY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hi2VY.png" alt="These are the errors" /></a></p>
<p>Errors are:-</p>
<ol>
<li>android:requestLegacyExternalStorage="true" - "Attribute android:requestLegacyExternalStorage is not allowed here"</li>
<li>android:name="${applicationName}" - "Unresolvedclass:'{applicationName}'"</li>
<li>android:icon="@mipmap/ic_launcher"> - "Attribute android:icon is not allowed here"</li>
<li>android:name=".MainActivity" - "Unresolved class MainActivity"</li>
<li>android:usesCleartextTraffic="true" - "Attribute android:usesCleartextTraffic is not allowed here"</li>
<li>android:launchMode="singleTop" - "Attribute android:launchMode is not allowed here"</li>
<li>android:theme="@style/LaunchTheme" - "Attribute android:theme is not allowed here"</li>
<li>android:configChanges="....." - "Attribute android:configChanges is not allowed here"</li>
<li>android:hardwareAccelerated="true" - "Attribute android:hardwareAccelerated is not allowed here"</li>
<li>android:windowSoftInputMode="adjustResize"> - "Attribute android:windowSoftInputMode is not allowed here"</li>
</ol>
|
[
{
"answer_id": 74521518,
"author": "Juan C",
"author_id": 9462829,
"author_profile": "https://Stackoverflow.com/users/9462829",
"pm_score": 2,
"selected": false,
"text": "left_join replace_na dfnames %>% left_join(dfgender, by=c('names' = 'name')) %>% \n mutate(gender = gender %>% as.character %>% replace_na('Neutral'))\n\n# names gender\n# 1 Helen F\n# 2 Von Neutral\n# 3 Erik M\n# 4 Brook Neutral\n"
},
{
"answer_id": 74522127,
"author": "harre",
"author_id": 4786466,
"author_profile": "https://Stackoverflow.com/users/4786466",
"pm_score": 1,
"selected": false,
"text": "rows_update library(dplyr)\n\ndfnames |>\n mutate(gender = \"Neutral\") |>\n rows_update(rename(dfgender, names = name), \"names\")\n names gender\n1 Helen F\n2 Von Neutral\n3 Erik M\n4 Brook Neutral\n"
},
{
"answer_id": 74575192,
"author": "Santiago",
"author_id": 13507658,
"author_profile": "https://Stackoverflow.com/users/13507658",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\nlibrary(tidyr)\n\ndfgender <- data.frame(name = c(\"Helen\",\"Erik\"), gender = c(\"F\",\"M\"))\ndfnames <- data.frame(names = c(\"Helen\", \"Von\", \"Erik\", \"Brook\"))\n\ndfnames %>%\n left_join(dfgender, by = c(\"names\" = \"name\")) %>%\n replace_na(list(gender = \"Neutral\"))\n# names gender\n# 1 Helen F\n# 2 Von Neutral\n# 3 Erik M\n# 4 Brook Neutral\n tidyr library(dplyr)\n\ndfgender <- data.frame(name = c(\"Helen\",\"Erik\"), gender = c(\"F\",\"M\"))\ndfnames <- data.frame(names = c(\"Helen\", \"Von\", \"Erik\", \"Brook\"))\n\ndfnames %>%\n left_join(dfgender, by = c(\"names\" = \"name\")) %>%\n mutate(gender = coalesce(gender, \"Neutral\"))\n# names gender\n# 1 Helen F\n# 2 Von Neutral\n# 3 Erik M\n# 4 Brook Neutral\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19082619/"
] |
74,521,496
|
<p>Here's my code:</p>
<p><strong>SectionState.js:</strong></p>
<pre><code>import { React, useState, useEffect } from "react";
import QuestionContext from "./QuestionContext";
import questions from "../data/questions.json";
import { useNavigate } from "react-router-dom";
const SectionState = (props) => {
// set questions from json to an array of 4 elements
const newQuestions = Object.keys(questions.content).map(
(key) => questions.content[key].question
);
//useState for Question state
const [currentQuestion, setCurrentQuestion] = useState(0);
const newQuestionsArr = {
qID: 0,
questionTxt: newQuestions[currentQuestion],
}
const [questionCtx, setQuestionCtx] = useState(newQuestionsArr);
const navigate = useNavigate()
useEffect(() => {
setQuestionCtx(prevState => ({
...prevState,
qID: currentQuestion,
questionTxt: newQuestions[currentQuestion],
}));
}, [currentQuestion]);
const updateNextQuestion = () => {
if (!(currentQuestion >= newQuestions.length)) {
setCurrentQuestion((nextCurrentQuestion) => nextCurrentQuestion + 1);
}
else{
navigate('/result')
}
};
const updatePrevQuestion = () => {
if (currentQuestion <= 0) {
console.log(`No more questions`);
} else {
setCurrentQuestion((prevCurrentQuestion) => prevCurrentQuestion - 1);
}
};
return (
<QuestionContext.Provider
value={{ questionCtx, updateNextQuestion, updatePrevQuestion }}>
{props.children}
</QuestionContext.Provider>
);
};
export default SectionState;
</code></pre>
<p>Linter throws the following warning</p>
<blockquote>
<p>React Hook useEffect has a missing dependency: 'newQuestions'. Either include it or remove the dependency array</p>
</blockquote>
<p>If I add newQuestions in the dependency array, it results in re-rendering loop. I can't declare either newQuestions or questionCtx state inside useEffect as it is used elsewhere in the code.</p>
<p>I can see that I have to update the <code>questionTxt</code>. What should I do here to update the said value and remove the warning?</p>
|
[
{
"answer_id": 74521518,
"author": "Juan C",
"author_id": 9462829,
"author_profile": "https://Stackoverflow.com/users/9462829",
"pm_score": 2,
"selected": false,
"text": "left_join replace_na dfnames %>% left_join(dfgender, by=c('names' = 'name')) %>% \n mutate(gender = gender %>% as.character %>% replace_na('Neutral'))\n\n# names gender\n# 1 Helen F\n# 2 Von Neutral\n# 3 Erik M\n# 4 Brook Neutral\n"
},
{
"answer_id": 74522127,
"author": "harre",
"author_id": 4786466,
"author_profile": "https://Stackoverflow.com/users/4786466",
"pm_score": 1,
"selected": false,
"text": "rows_update library(dplyr)\n\ndfnames |>\n mutate(gender = \"Neutral\") |>\n rows_update(rename(dfgender, names = name), \"names\")\n names gender\n1 Helen F\n2 Von Neutral\n3 Erik M\n4 Brook Neutral\n"
},
{
"answer_id": 74575192,
"author": "Santiago",
"author_id": 13507658,
"author_profile": "https://Stackoverflow.com/users/13507658",
"pm_score": 0,
"selected": false,
"text": "library(dplyr)\nlibrary(tidyr)\n\ndfgender <- data.frame(name = c(\"Helen\",\"Erik\"), gender = c(\"F\",\"M\"))\ndfnames <- data.frame(names = c(\"Helen\", \"Von\", \"Erik\", \"Brook\"))\n\ndfnames %>%\n left_join(dfgender, by = c(\"names\" = \"name\")) %>%\n replace_na(list(gender = \"Neutral\"))\n# names gender\n# 1 Helen F\n# 2 Von Neutral\n# 3 Erik M\n# 4 Brook Neutral\n tidyr library(dplyr)\n\ndfgender <- data.frame(name = c(\"Helen\",\"Erik\"), gender = c(\"F\",\"M\"))\ndfnames <- data.frame(names = c(\"Helen\", \"Von\", \"Erik\", \"Brook\"))\n\ndfnames %>%\n left_join(dfgender, by = c(\"names\" = \"name\")) %>%\n mutate(gender = coalesce(gender, \"Neutral\"))\n# names gender\n# 1 Helen F\n# 2 Von Neutral\n# 3 Erik M\n# 4 Brook Neutral\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18679088/"
] |
74,521,526
|
<p>I have a dataframe like so:</p>
<pre><code> CREATED_AT COUNT
'1990-01-01' '2022-01-01 07:30:00' 5
'1990-01-02' '2022-01-01 07:30:00' 10
...
</code></pre>
<p>Where the index is a date and the <code>CREATED_AT</code> column is a datetime that is the same value for all rows.</p>
<p>How can I update the <code>CREATED_AT_COLUMN</code> such that it inherits its date portion from the index?
The result should look like:</p>
<pre><code> CREATED_AT COUNT
'1990-01-01' '1990-01-01 07:30:00' 5
'1990-01-02' '1990-01-02 07:30:00' 10
...
</code></pre>
<p>Attempts at this result in errors like:</p>
<pre><code>cannot add DatetimeArray and DatetimeArray
</code></pre>
|
[
{
"answer_id": 74521623,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "# ensure CREATED_AT is a datetime\ns = pd.to_datetime(df['CREATED_AT'])\n\n# subtract the date to only get the time, add to the index\n# ensuring the index is of datetime type\ndf['CREATED_AT'] = s.sub(s.dt.normalize()).add(pd.to_datetime(df.index))\n df['CREATED_AT'] = (df['CREATED_AT']\n .sub(df['CREATED_AT'].dt.normalize())\n .add(df.index)\n )\n CREATED_AT COUNT\n1990-01-01 1990-01-01 07:30:00 5\n1990-01-02 1990-01-02 07:30:00 10\n"
},
{
"answer_id": 74521878,
"author": "ADEL NAMANI",
"author_id": 9143046,
"author_profile": "https://Stackoverflow.com/users/9143046",
"pm_score": 2,
"selected": true,
"text": "df.reset_index() # Creating a test df\nimport pandas as pd\nfrom datetime import datetime, timedelta, date\n\ndf = pd.DataFrame.from_dict({\n \"CREATED_AT\": [datetime.now(), datetime.now() + timedelta(hours=1)],\n \"COUNT\": [5, 10]\n})\ndf_with_index = df.set_index(pd.Index([date.today() - timedelta(days=10), date.today() - timedelta(days=9)]))\n\n# Creating the column with the result\ndf_result = df_with_index.reset_index()\ndf_result[\"NEW_CREATED_AT\"] = pd.to_datetime(df_result[\"index\"].astype(str) + ' ' + df_result[\"CREATED_AT\"].dt.time.astype(str))\n index CREATED_AT COUNT NEW_CREATED_AT\n0 2022-11-11 2022-11-21 16:15:31.520960 5 2022-11-11 16:15:31.520960\n1 2022-11-12 2022-11-21 17:15:31.520965 10 2022-11-12 17:15:31.520965\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12821675/"
] |
74,521,534
|
<p>When running npx truffle compile, i get the above error message.</p>
<p>I am trying to transition an NFT smart contract into upgradeable form and have imported the relevant source codes. It deploys to testnet fine, but when replacing the constructor with "function Initialize() initializer pubic {" i get the above error message.</p>
<p>Can someone help?</p>
<p>I also get an "Identifier not found or not unique" by my "mapping(address=>bool) private _operatorEnabled;</p>
<pre><code>// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
contract ERC721CarbonAsset is ERC721URIStorage, Pausable, AccessControl {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
// Base URI
string private _baseUri;
address _forwarder;
mapping(uint256 => string) private _digests;
mapping(uint256 => string) private _infoRoots;
// Addresses under operator control
mapping(address => bool) private _operatorEnabled;
function initialize() initializer public {
// constructor() public ERC721("", "") Pausable() {
_baseUri = "";
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(PAUSER_ROLE, msg.sender);
_setupRole(MINTER_ROLE, msg.sender);
_setupRole(BURNER_ROLE, msg.sender);
_setupRole(OPERATOR_ROLE, msg.sender);
}
function pause() external onlyRole(PAUSER_ROLE) {
_pause();
}
function unpause() external onlyRole(PAUSER_ROLE) {
_unpause();
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
* Taken from ERC20Pausable
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
function mint(address to, uint256 tokenId, string memory tokenUri, string memory digest) public onlyRole(MINTER_ROLE) {
_mint(to, tokenId);
_setTokenURI(tokenId, tokenUri);
_digests[tokenId] = digest;
}
function burn(uint256 tokenId) public onlyRole(BURNER_ROLE) {
_burn(tokenId);
}
function setBaseURI(string memory uri) external onlyRole(OPERATOR_ROLE) {
_baseUri = uri;
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual override returns (string memory) {
return _baseUri;
}
function infoRoot(uint256 tokenId) external view virtual returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _infoRoot = _infoRoots[tokenId];
// If there is no infoRoot set, return an empty string.
if (bytes(_infoRoot).length == 0) {
return "";
}
return _infoRoot;
}
function setInfoRoot(uint256 tokenId, string memory _infoRoot) external onlyRole(OPERATOR_ROLE) whenNotPaused() {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_infoRoots[tokenId] = _infoRoot;
}
function digest(uint256 tokenId) external view virtual returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory digest = _digests[tokenId];
// If there is no digest set, return an empty string.
if (bytes(digest).length == 0) {
return "";
}
return digest;
}
function setDigest(uint256 tokenId, string memory digest) external onlyRole(OPERATOR_ROLE) whenNotPaused() {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_digests[tokenId] = digest;
}
// Operator initiatiated token transfer
function operatorTransfer(address recipient, uint256 tokenId) external onlyRole(OPERATOR_ROLE) whenNotPaused() returns (bool) {
address owner = ownerOf(tokenId);
require(isOperatorControlled(owner), "ERC721: sender not under operator control");
// Reset appoval
_approve(msg.sender, tokenId);
transferFrom(owner, recipient, tokenId);
return true;
}
// Address owner can enable their address for operator control
// Default state is operator disabled
function enableOperatorControl() external whenNotPaused() returns (bool) {
require(msgSender() != address(0), "ERC20: owner is a zero address");
require(!isOperatorControlled(msgSender()), "ERC20: owner already under operator control");
_operatorEnabled[msgSender()] = true;
return true;
}
// Operator role can remove operator control from an address
function disableOperatorControl(address owner) external onlyRole(OPERATOR_ROLE) whenNotPaused() returns (bool) {
require(owner != address(0), "ERC721: owner is a zero address");
require(isOperatorControlled(owner), "ERC721: owner not under operator control");
_operatorEnabled[owner] = false;
return true;
}
function isOperatorControlled(address owner) public view returns (bool) {
require(owner != address(0), "ERC721: owner is a zero address");
return _operatorEnabled[owner];
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, AccessControl) returns (bool) {
return super.supportsInterface(interfaceId);
}
function msgSender() internal view returns(address sender) {
if(msg.sender == _forwarder) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
} else {
sender = msg.sender;
}
return sender;
}
function setForwarder(address forwarder) external onlyRole(OPERATOR_ROLE) returns (bool) {
_forwarder = forwarder;
return true;
}
function getForwarder() external view returns (address) {
return _forwarder;
}
}
</code></pre>
<p>I tried to change the initializer function around a bit, inline with onlyInitializing functionality <a href="https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/releases/tag/v4.4.1" rel="nofollow noreferrer">https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/releases/tag/v4.4.1</a></p>
<p>But that also returned a similar error regarding identifier not found or not unique</p>
|
[
{
"answer_id": 74521623,
"author": "mozway",
"author_id": 16343464,
"author_profile": "https://Stackoverflow.com/users/16343464",
"pm_score": 0,
"selected": false,
"text": "# ensure CREATED_AT is a datetime\ns = pd.to_datetime(df['CREATED_AT'])\n\n# subtract the date to only get the time, add to the index\n# ensuring the index is of datetime type\ndf['CREATED_AT'] = s.sub(s.dt.normalize()).add(pd.to_datetime(df.index))\n df['CREATED_AT'] = (df['CREATED_AT']\n .sub(df['CREATED_AT'].dt.normalize())\n .add(df.index)\n )\n CREATED_AT COUNT\n1990-01-01 1990-01-01 07:30:00 5\n1990-01-02 1990-01-02 07:30:00 10\n"
},
{
"answer_id": 74521878,
"author": "ADEL NAMANI",
"author_id": 9143046,
"author_profile": "https://Stackoverflow.com/users/9143046",
"pm_score": 2,
"selected": true,
"text": "df.reset_index() # Creating a test df\nimport pandas as pd\nfrom datetime import datetime, timedelta, date\n\ndf = pd.DataFrame.from_dict({\n \"CREATED_AT\": [datetime.now(), datetime.now() + timedelta(hours=1)],\n \"COUNT\": [5, 10]\n})\ndf_with_index = df.set_index(pd.Index([date.today() - timedelta(days=10), date.today() - timedelta(days=9)]))\n\n# Creating the column with the result\ndf_result = df_with_index.reset_index()\ndf_result[\"NEW_CREATED_AT\"] = pd.to_datetime(df_result[\"index\"].astype(str) + ' ' + df_result[\"CREATED_AT\"].dt.time.astype(str))\n index CREATED_AT COUNT NEW_CREATED_AT\n0 2022-11-11 2022-11-21 16:15:31.520960 5 2022-11-11 16:15:31.520960\n1 2022-11-12 2022-11-21 17:15:31.520965 10 2022-11-12 17:15:31.520965\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19354886/"
] |
74,521,542
|
<p>I have build a driver simulator using Unity and I use as steering wheel the Logitech G29 controller.
So in my project to break and throttle I configured this:</p>
<p><a href="https://i.stack.imgur.com/qq6Z6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qq6Z6.png" alt="enter image description here" /></a></p>
<p>Vertical1 is used to Throttle function and Vertical2 is used to Break function. This configuration are working now.</p>
<p>Now I need to configure also another controller (HC1 3DRap). This is an Hand Controller. So I checked it on windows device and I can see this:</p>
<p><a href="https://i.stack.imgur.com/N3qoz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N3qoz.png" alt="enter image description here" /></a></p>
<p>Rotation Axis X and Rotation Axis Y have a value in sleep mode (without press the two levels).</p>
<p>Now I need to integrate also this new Controller in my project. So I try to make this:</p>
<p><a href="https://i.stack.imgur.com/xMMwP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xMMwP.png" alt="enter image description here" /></a></p>
<p>In this mode if I try to check value of Y axis value with the follow code ( in this moment I cannot press the levers) :</p>
<pre><code>Debug.Log("Input debug frenata: " + Input.GetAxis("Vertical2"));
</code></pre>
<p>I can display this:</p>
<p><a href="https://i.stack.imgur.com/FnJaE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FnJaE.png" alt="enter image description here" /></a></p>
<p>If I try to press a levers, I can display this values</p>
<p><a href="https://i.stack.imgur.com/cqpOF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cqpOF.png" alt="enter image description here" /></a></p>
<p>In this mode with thie new controller join on the system I m not able to run the car, because I think that there is every time the break pressed.</p>
<p>Could you suggest me, how can I fixed this bug ?</p>
|
[
{
"answer_id": 74619951,
"author": "thesupersoup",
"author_id": 11103924,
"author_profile": "https://Stackoverflow.com/users/11103924",
"pm_score": 1,
"selected": false,
"text": "private float _vertical2Zero = 0.0f; \n\nvoid Start()\n{\n this.CalibrateVertical2Zero();\n\n // ... more code ...\n}\n\nprivate void CalibrateVertical2Zero()\n{\n this._vertical2Zero = Input.GetAxis(\"Vertical2\")\n{\n private float _vertical2Deadzone = 0.05f;\n\nvoid HandleInput()\n{\n float newVertical2Value = Input.GetAxis(\"Vertical2\");\n bool vertical2Low = newVertical2Value <= ( this._vertical2Zero - _vertical2Deadzone );\n bool vertical2High = newVertical2Value >= ( this._vertical2Zero + _vertical2Deadzone ); \n\n\n if( vertical2Low || vertical2High )\n {\n // Input detected on Vertical2, accounting for the zero and deadzone\n }\n}\n"
},
{
"answer_id": 74638530,
"author": "Website Developer",
"author_id": 15546569,
"author_profile": "https://Stackoverflow.com/users/15546569",
"pm_score": 0,
"selected": false,
"text": "void Update() \n{ \n if (Input.GetKeyDown(KeyCode.Space)) \n { \n // Spacebar was pressed \n } \n if (Input.GetMouseButtonDown(0)) \n { \n // Left mouse was pressed \n } \n}\n using UnityEngine;\nusing UnityEngine.InputSystem;\npublic class ReportMousePosition : MonoBehaviour\n{\n void Update()\n {\n Vector2 mousePosition = Mouse.current.position.ReadValue();\n if(Keyboard.current.anyKey.wasPressedThisFrame)\n {\n Debug.Log(\"A key was pressed\");\n }\n if (Gamepad.current.aButton.wasPressedThisFrame)\n {\n Debug.Log(\"A button was pressed\");\n }\n }\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2405663/"
] |
74,521,565
|
<p>I have 3 tables -</p>
<p>Books -</p>
<pre><code>BookNo BookName BookType
123 ABC 1
555 XYZ 0
</code></pre>
<p>Shelf</p>
<pre><code>Shelf ShelfNo BookNo BookQuantity
XB XB01 123 5
XB XB02 555 3
XB XB03 123 8
</code></pre>
<p>BooksIssued</p>
<pre><code>ShelfNo BookName IssuedDate QuantityIssued
XB01 ABC 11/21/2022 2
XB02 XYZ 11/20/2022 1
XB03 ABC 11/21/2022 5
</code></pre>
<p>My goal is to find out total number of books stock we have. The output should be grouped by book. And I have to combine all <code>shelfNo</code> which contain the same book and sum their <code>Shelf.BookQuantity</code> and then add it to <code>BooksIssued.QuantityIssued</code> for that particular book. <code>Booktype</code> should be displayed as Children for 0 and 1 for adults.</p>
<p>For example,</p>
<p>Output</p>
<pre><code>BookNo BookName BookType Total Stock
123 ABC adults 20 //(5+8+2+5)
555 XYZ children 4 //(3+1)
</code></pre>
<p>So far, I have written this. I know I have chosen extra columns in my query than what I have mentioned in my output format. It is so because I was going step by step to understand the flow. I wanted to first group the data by book and sum the quantity but it isn't grouping the data by bookno . It is also not summing the <code>bi.quantityissued</code>.</p>
<pre><code>select s.bookno, b.booktype, s.shelfno, b.bookname, s.bookquantity,
sum(bi.quantityissued), bi.issueddate
from Shelf s
left outer join BooksIssued bi on s.shelfno = bi.shelfno
left outer join Books b on s.bookno=b.bookno
where s.shelf = 'XB'
and bi.issueddate between '11/01/2022' and '11/07/2022'
group by s.bookno, s.shelfno, b.booktype, b.bookname, s.bookquantity, bi.issueddate
</code></pre>
<p>Please guide me what do I do next. Thank you.</p>
|
[
{
"answer_id": 74619951,
"author": "thesupersoup",
"author_id": 11103924,
"author_profile": "https://Stackoverflow.com/users/11103924",
"pm_score": 1,
"selected": false,
"text": "private float _vertical2Zero = 0.0f; \n\nvoid Start()\n{\n this.CalibrateVertical2Zero();\n\n // ... more code ...\n}\n\nprivate void CalibrateVertical2Zero()\n{\n this._vertical2Zero = Input.GetAxis(\"Vertical2\")\n{\n private float _vertical2Deadzone = 0.05f;\n\nvoid HandleInput()\n{\n float newVertical2Value = Input.GetAxis(\"Vertical2\");\n bool vertical2Low = newVertical2Value <= ( this._vertical2Zero - _vertical2Deadzone );\n bool vertical2High = newVertical2Value >= ( this._vertical2Zero + _vertical2Deadzone ); \n\n\n if( vertical2Low || vertical2High )\n {\n // Input detected on Vertical2, accounting for the zero and deadzone\n }\n}\n"
},
{
"answer_id": 74638530,
"author": "Website Developer",
"author_id": 15546569,
"author_profile": "https://Stackoverflow.com/users/15546569",
"pm_score": 0,
"selected": false,
"text": "void Update() \n{ \n if (Input.GetKeyDown(KeyCode.Space)) \n { \n // Spacebar was pressed \n } \n if (Input.GetMouseButtonDown(0)) \n { \n // Left mouse was pressed \n } \n}\n using UnityEngine;\nusing UnityEngine.InputSystem;\npublic class ReportMousePosition : MonoBehaviour\n{\n void Update()\n {\n Vector2 mousePosition = Mouse.current.position.ReadValue();\n if(Keyboard.current.anyKey.wasPressedThisFrame)\n {\n Debug.Log(\"A key was pressed\");\n }\n if (Gamepad.current.aButton.wasPressedThisFrame)\n {\n Debug.Log(\"A button was pressed\");\n }\n }\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13208961/"
] |
74,521,588
|
<p>I'm trying to use <code>filter(grepl())</code> to match some words in my column. Let's suppose I want to extract the word "Guartelá". In my column, i have variations such as "guartela" "guartelá" and "Guartela". To match upper/lowercase words I'm using <code>(?i)</code>. However, I haven't found a good way to match accent/no-accent (i.e., "guartelá" and "guartela").</p>
<p>I know that I can simply substitute <code>á</code> by <code>a</code>, but is there a way to assign the accent-insensitive in the code? It can be base R/tidyverse/any, I don't mind.</p>
<p>Here's how my curent code line is:</p>
<pre><code>cobras <- final %>% filter(grepl("(?i)guartelá", NAME)
| grepl("(?i)guartelá", locality))
</code></pre>
<p>Cheers</p>
|
[
{
"answer_id": 74521636,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 3,
"selected": true,
"text": "OR [ > string <- c(\"Guartelá\", \"Guartela\", \"guartela\", \"guartelá\", \"any\")\n> grepl(\"[Gg]uartel[aá]\", string)\n[1] TRUE TRUE TRUE TRUE FALSE\n"
},
{
"answer_id": 74521648,
"author": "Julian",
"author_id": 14137004,
"author_profile": "https://Stackoverflow.com/users/14137004",
"pm_score": 1,
"selected": false,
"text": "str_detect() library(tidyverse)\ntibble(name = c(\"guartela\",\"guartelá\", \"Guartela\", \"Other\")) |> \n filter(str_detect(name, \"guartela|guartelá|Guartela\"))\n"
},
{
"answer_id": 74521818,
"author": "islem",
"author_id": 11952767,
"author_profile": "https://Stackoverflow.com/users/11952767",
"pm_score": 2,
"selected": false,
"text": "unaccent_chars= stringi::stri_trans_general(c(\"guartelá\",\"with_é\",\"with_â\",\"with_ô\") ,\"Latin-ASCII\")\nunaccent_chars\n# [1] \"guartela\" \"with_e\" \"with_a\" \"with_o\" \n# grepl(paste(unaccent_chars,collapse = \"|\"), string) \n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15108186/"
] |
74,521,601
|
<p>I am using twilio to call, in my laravel application. I have used webhook for that. When i click call button in web browser, it calls to specific phone number and when called user presses any digit, I get the digit as a response in webhook. I want to send question_id as parameter to twilio application and when user presses digit 3 in his phone. I will store 3 as answer along with the question_id in my db.
for exmple:
question_id: 1, Press 1 for sales, press 2 for account or press 3 for operator service</p>
<p>received digit: 3,
I have to store 1 as question_id and 3 as call_response in my db</p>
|
[
{
"answer_id": 74521636,
"author": "Jilber Urbina",
"author_id": 1315767,
"author_profile": "https://Stackoverflow.com/users/1315767",
"pm_score": 3,
"selected": true,
"text": "OR [ > string <- c(\"Guartelá\", \"Guartela\", \"guartela\", \"guartelá\", \"any\")\n> grepl(\"[Gg]uartel[aá]\", string)\n[1] TRUE TRUE TRUE TRUE FALSE\n"
},
{
"answer_id": 74521648,
"author": "Julian",
"author_id": 14137004,
"author_profile": "https://Stackoverflow.com/users/14137004",
"pm_score": 1,
"selected": false,
"text": "str_detect() library(tidyverse)\ntibble(name = c(\"guartela\",\"guartelá\", \"Guartela\", \"Other\")) |> \n filter(str_detect(name, \"guartela|guartelá|Guartela\"))\n"
},
{
"answer_id": 74521818,
"author": "islem",
"author_id": 11952767,
"author_profile": "https://Stackoverflow.com/users/11952767",
"pm_score": 2,
"selected": false,
"text": "unaccent_chars= stringi::stri_trans_general(c(\"guartelá\",\"with_é\",\"with_â\",\"with_ô\") ,\"Latin-ASCII\")\nunaccent_chars\n# [1] \"guartela\" \"with_e\" \"with_a\" \"with_o\" \n# grepl(paste(unaccent_chars,collapse = \"|\"), string) \n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11445496/"
] |
74,521,603
|
<p>I'm trying to make my own photo codecs, I made a 512 * 512 image,</p>
<p>I'm just trying to build with one color and arrange in a Container in Column and Row
My Code:</p>
<pre class="lang-dart prettyprint-override"><code> SizedBox(
height: 512,
width: 512,
child: Column(
children: List.generate(512, (index) {
return Row(
children: List.generate(512, (index) {
return Container(
height: 1,
width: 1,
color: Colors.blue,
);
}),
);
}),
),
),
</code></pre>
<p>I tried this code, it is very slow,</p>
<p>So how to build flutter widget fast?</p>
|
[
{
"answer_id": 74522072,
"author": "Guillaume Roux",
"author_id": 9942346,
"author_profile": "https://Stackoverflow.com/users/9942346",
"pm_score": 1,
"selected": true,
"text": "CustomPainter class ImageWidget extends StatelessWidget {\n final Color color;\n final Size size;\n\n const ImageWidget({\n super.key,\n this.color = Colors.blue,\n this.size = const Size(512, 512),\n });\n\n @override\n Widget build(BuildContext context) {\n return CustomPaint(\n painter: ImagePainter(color: color),\n size: size,\n );\n }\n}\n\nclass ImagePainter extends CustomPainter {\n final Color color;\n\n ImagePainter({required this.color});\n\n @override\n void paint(Canvas canvas, Size size) {\n final paint = Paint()..color = color;\n canvas.drawRect(Offset.zero & size, paint);\n }\n\n @override\n bool shouldRepaint(ImagePainter oldDelegate) => false;\n}\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20259643/"
] |
74,521,604
|
<p>I was studying the following piece of code and tried to write on paper the values that i and j receive at each step but I don't understand why at the 4th step, j's value decreses from 3 to 2 as there is no decrement operator (as far as I understand it):</p>
<pre><code>#include<stdio.h>
int main() {
int i, j, n;
int v[] = {
-7,
29,
76,
8
};
n = sizeof(v) / sizeof(int);
for (i = 0, j = 1; n > 1 && i < n;
(v[i] > v[j]) && (v[i] = v[i] + v[j] - (v[j] = v[i])), i++, j = j < n - 1 ? --i, j + 1 : i + 1)
printf("i=%d j=%d \n", i, j);
for (i = 0; i < n; i++) printf("%d\t", v[i]);
printf("\n");
return 0;
}
</code></pre>
<pre><code>Output:
i=0 j=1
i=0 j=2
i=0 j=3
i=1 j=2
i=1 j=3
i=2 j=3
i=3 j=4
i=3 j=5
i=3 j=6
-7 8 29
</code></pre>
<p>Tried to understand how i and j receive their value.</p>
|
[
{
"answer_id": 74522251,
"author": "KamilCuk",
"author_id": 9072753,
"author_profile": "https://Stackoverflow.com/users/9072753",
"pm_score": 1,
"selected": false,
"text": "v[i] = v[i] + v[j] - (v[j] = v[i]) v[j] v[j] j=4 v[j] v 3 i i++ i=1 j 2 i + 1 y=2 > i=0 j=3 n=4\n..., i++, j = j < n - 1 ? --i, j + 1 : i + 1\n> i++ -> i=1\n..., j = j < n - 1 ? --i, j + 1 : i + 1\n> j < n - 1 -> 3 < 3 -> false\nj = i + 1\n> i + 1 -> 1 + 1 -> 2\n> j = 2\n"
},
{
"answer_id": 74522383,
"author": "rentoulis",
"author_id": 19958403,
"author_profile": "https://Stackoverflow.com/users/19958403",
"pm_score": 1,
"selected": true,
"text": " (v[i] > v[j]) && (v[i] = v[i] + v[j] - (v[j] = v[i]))\n i++\n j = j < n - 1 ? --i, j + 1 : i + 1\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20564499/"
] |
74,521,614
|
<p>In <code>.rmd</code> Files we can display text <em>italic</em> by wrapping it inside single <code>*</code>-signs. But how is it possible to put a whole list to <em>italic</em>?</p>
<hr />
<p>I tried:</p>
<pre><code>---
title: "Untitled"
output: pdf_document
date: '2022-11-21'
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
My list:
i) One;
i) Two;
i) Three.
---
*My italic list, first try:
i) One;
i) Two;
i) Three.*
---
*My italic list, second try:*
*i) One;
i) Two;
i) Three.*
---
*My italic list, third try:*
*i) One;*
*i) Two;*
*i) Three.*
---
*My italic list, fourth try:*
i) *One;*
i) *Two;*
i) *Three.*
</code></pre>
<p>This produces:</p>
<p><a href="https://i.stack.imgur.com/HjZ4X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HjZ4X.png" alt="enter image description here" /></a></p>
<p>Version 4 is <em>nearly</em> what I need: The elements are <em>italic</em>, but the numbering isn't.</p>
<hr />
<p>How can I produce a numbered list that is entirely <em>italic</em>?</p>
<p>P.S.: I render to .pdf. So LaTex is welcome..</p>
|
[
{
"answer_id": 74521778,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "<i> </i> <i>\nMy list:\n\ni) One;\nii) Two;\niii) Three.\n\n</i>\n"
},
{
"answer_id": 74521792,
"author": "Julian",
"author_id": 14137004,
"author_profile": "https://Stackoverflow.com/users/14137004",
"pm_score": 2,
"selected": false,
"text": "\\itshape ---\ntitle: \"Italic Block\"\noutput: pdf_document\n---\n\n## Block\n\n\\begin{itemize}\n \\itshape\n\\item [i)] One\n\\item [ii)] Two\n\\item [iii)] Three\n\\end{itemize}\n"
},
{
"answer_id": 74532501,
"author": "symbolrush",
"author_id": 4706952,
"author_profile": "https://Stackoverflow.com/users/4706952",
"pm_score": 2,
"selected": true,
"text": "\\itshape \\normalfont ---\ntitle: \"Untitled\"\noutput: pdf_document\ndate: '2022-11-21'\n---\n\n```{r setup, include=FALSE}\nknitr::opts_chunk$set(echo = TRUE)\n```\n\n## R Markdown\n\n\n\\itshape\n\nMy italic list:\n\ni) One;\ni) Two;\ni) Three.\n\n\\normalfont\n\nAnd back to my normal font.\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4706952/"
] |
74,521,656
|
<p>I'm having trouble building a query where subitems occur. I attach below the data and the expected end result.
Important thing is fact that SubitemID is not a constant. So I cannot put in my query thing like "subitemid like itemid+1".
Here is my Table:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ItemID</th>
<th>SubitemID</th>
<th>Category</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>X</td>
<td>X1</td>
<td>116113</td>
<td>115</td>
</tr>
<tr>
<td>X</td>
<td>X2</td>
<td>116113</td>
<td>115</td>
</tr>
<tr>
<td>X</td>
<td>X1</td>
<td>222540</td>
<td>100</td>
</tr>
<tr>
<td>X</td>
<td>X2</td>
<td>222540</td>
<td>100</td>
</tr>
<tr>
<td>Y</td>
<td>Y1</td>
<td>116113</td>
<td>204,58</td>
</tr>
<tr>
<td>Y</td>
<td>Y2</td>
<td>116113</td>
<td>204,58</td>
</tr>
<tr>
<td>Y</td>
<td>Y4</td>
<td>222540</td>
<td>500</td>
</tr>
<tr>
<td>Y</td>
<td>Y5</td>
<td>222540</td>
<td>500</td>
</tr>
</tbody>
</table>
</div>
<p>I would like to sum Values for each type of Category. So the result should be:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ItemID</th>
<th>Category</th>
<th>Sum of Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>X</td>
<td>116113</td>
<td>115</td>
</tr>
<tr>
<td>X</td>
<td>222540</td>
<td>100</td>
</tr>
<tr>
<td>Y</td>
<td>116113</td>
<td>204,58</td>
</tr>
<tr>
<td>Y</td>
<td>222540</td>
<td>500</td>
</tr>
</tbody>
</table>
</div>
<p>In other words I need to sum 1 row from each Category, because Value is constant per every ItemID in every category.</p>
<hr />
<p>EDIT:
My query is below:</p>
<pre><code> SELECT ItemID
,Category
,SUM(CASE WHEN Category = 116113 THEN ROUND(Value,4) else 0 end) as "Summary_cat1"
,SUM(CASE WHEN Category = 222540 THEN ROUND(Value,4) else 0 end) as "Summary_cat2"
,SUM(CASE WHEN Category in (116113,222540) THEN ROUND(Value,4) else 0 end) as "Summary_cat3"
FROM TABLE
GROUP BY ItemID, Category
</code></pre>
<p>Expected results:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>ItemID</th>
<th>Category</th>
<th>Summary_cat1</th>
<th>Summary_cat2</th>
<th>Summary_cat3</th>
</tr>
</thead>
<tbody>
<tr>
<td>X</td>
<td>116113</td>
<td>115</td>
<td>100</td>
<td>215</td>
</tr>
<tr>
<td>X</td>
<td>222540</td>
<td>115</td>
<td>100</td>
<td>215</td>
</tr>
<tr>
<td>Y</td>
<td>116113</td>
<td>204,58</td>
<td>500</td>
<td>704,58</td>
</tr>
<tr>
<td>Y</td>
<td>222540</td>
<td>204,58</td>
<td>500</td>
<td>704,58</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"answer_id": 74521778,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "<i> </i> <i>\nMy list:\n\ni) One;\nii) Two;\niii) Three.\n\n</i>\n"
},
{
"answer_id": 74521792,
"author": "Julian",
"author_id": 14137004,
"author_profile": "https://Stackoverflow.com/users/14137004",
"pm_score": 2,
"selected": false,
"text": "\\itshape ---\ntitle: \"Italic Block\"\noutput: pdf_document\n---\n\n## Block\n\n\\begin{itemize}\n \\itshape\n\\item [i)] One\n\\item [ii)] Two\n\\item [iii)] Three\n\\end{itemize}\n"
},
{
"answer_id": 74532501,
"author": "symbolrush",
"author_id": 4706952,
"author_profile": "https://Stackoverflow.com/users/4706952",
"pm_score": 2,
"selected": true,
"text": "\\itshape \\normalfont ---\ntitle: \"Untitled\"\noutput: pdf_document\ndate: '2022-11-21'\n---\n\n```{r setup, include=FALSE}\nknitr::opts_chunk$set(echo = TRUE)\n```\n\n## R Markdown\n\n\n\\itshape\n\nMy italic list:\n\ni) One;\ni) Two;\ni) Three.\n\n\\normalfont\n\nAnd back to my normal font.\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8145314/"
] |
74,521,708
|
<p>New to zoo/xts. I'm trying to go from monthly values to quarterly aggregates, defined as the sum of monthly values over a 3-month period <em>ending on the last available month</em>.</p>
<p>Reproducible example:</p>
<pre class="lang-r prettyprint-override"><code>library(xts)
months <- as.yearmon(c(paste0("2021-", 11:12),
paste0("2022-", 1:10)))
values <- c(23, 21, 45, 63, 12, 45,
23, 91, 28, 17, 27, 28)
ts <- as.xts(values,
order.by = months,
dateFormat="yearmon")
ts
#> [,1]
#> Nov 2021 23
#> Dec 2021 21
#> Jan 2022 45
#> Feb 2022 63
#> Mar 2022 12
#> Apr 2022 45
#> May 2022 23
#> Jun 2022 91
#> Jul 2022 28
#> Aug 2022 17
#> Sep 2022 27
#> Oct 2022 28
</code></pre>
<p>Intended output:</p>
<pre><code>| | [,1] |
| -------- | ---- |
| Jan 2022 | 89 |
| Apr 2022 | 120 |
| Jul 2022 | 142 |
| Oct 2022 | 72 |
</code></pre>
<p>I can't get this to work because the <code>apply.quarterly</code> function uses calendar quarters, rather than generic 3-month periods:</p>
<pre class="lang-r prettyprint-override"><code>
apply.quarterly(ts, sum)
#> [,1]
#> Dec 2021 44
#> Mar 2022 120
#> Jun 2022 159
#> Sep 2022 72
#> Oct 2022 28
</code></pre>
<p>And <code>period.apply</code> doesn't accept custom periods:</p>
<pre class="lang-r prettyprint-override"><code>period.apply(ts, endpoints(ts, on = "3 months"), sum)
#> Error in match.arg(on, c("years", "quarters", "months", "weeks", "days", : 'arg' should be one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds", "microseconds", "ms", "us"
</code></pre>
|
[
{
"answer_id": 74521778,
"author": "TarJae",
"author_id": 13321647,
"author_profile": "https://Stackoverflow.com/users/13321647",
"pm_score": 2,
"selected": false,
"text": "<i> </i> <i>\nMy list:\n\ni) One;\nii) Two;\niii) Three.\n\n</i>\n"
},
{
"answer_id": 74521792,
"author": "Julian",
"author_id": 14137004,
"author_profile": "https://Stackoverflow.com/users/14137004",
"pm_score": 2,
"selected": false,
"text": "\\itshape ---\ntitle: \"Italic Block\"\noutput: pdf_document\n---\n\n## Block\n\n\\begin{itemize}\n \\itshape\n\\item [i)] One\n\\item [ii)] Two\n\\item [iii)] Three\n\\end{itemize}\n"
},
{
"answer_id": 74532501,
"author": "symbolrush",
"author_id": 4706952,
"author_profile": "https://Stackoverflow.com/users/4706952",
"pm_score": 2,
"selected": true,
"text": "\\itshape \\normalfont ---\ntitle: \"Untitled\"\noutput: pdf_document\ndate: '2022-11-21'\n---\n\n```{r setup, include=FALSE}\nknitr::opts_chunk$set(echo = TRUE)\n```\n\n## R Markdown\n\n\n\\itshape\n\nMy italic list:\n\ni) One;\ni) Two;\ni) Three.\n\n\\normalfont\n\nAnd back to my normal font.\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13968222/"
] |
74,521,723
|
<p>I made a special triangle (or whatever they're called). It works fine but a flaw is it prints out the same triangle in a different order. This is the code:</p>
<pre><code>SpecialTriangles = []
for i in range(15):
for j in range(15):
for k in range(15):
if i**2 + j**2 == k**2:
if i**2 + 0 != k**2:
if 0 + j**2 != k**2:
if 0 + 0 != k**2:
SpecialTriangles.append([i, j, k])
print(SpecialTriangles)
</code></pre>
<p>And this is what the output is:</p>
<pre><code>[[3, 4, 5], [4, 3, 5], [5, 12, 13], [6, 8, 10], [8, 6, 10], [12, 5, 13]]
</code></pre>
<p>So I want this to print just one of a kind in ascending order so:</p>
<pre><code>[[3, 4, 5], [5, 12, 13], [6, 8, 10]]
</code></pre>
|
[
{
"answer_id": 74521798,
"author": "joanis",
"author_id": 3216427,
"author_profile": "https://Stackoverflow.com/users/3216427",
"pm_score": 3,
"selected": false,
"text": "itertools.combinations from itertools import combinations\n\nfor i, j, k in combinations(range(15), 3):\n # do your logic with i, j, k\n combinations()"
},
{
"answer_id": 74521817,
"author": "Rabinzel",
"author_id": 15521392,
"author_profile": "https://Stackoverflow.com/users/15521392",
"pm_score": 1,
"selected": false,
"text": "itertools.combinations iterools.combinations import itertools\n\nout = list(\n filter(\n lambda x: x[0]**2 + x[1]**2 == x[2]**2, itertools.combinations([*range(15)], 3)\n )\n)\nprint(out)\n [(3, 4, 5), (5, 12, 13), (6, 8, 10)]\n out = [x for x in itertools.combinations([*range(15)],3) if x[0]**2 + x[1]**2 == x[2]**2]\nprint(out)\n"
},
{
"answer_id": 74521827,
"author": "Luca Clissa",
"author_id": 7678074,
"author_profile": "https://Stackoverflow.com/users/7678074",
"pm_score": -1,
"selected": false,
"text": "SpecialTriangles SpecialTriangles = []\n\nfor i in range(15):\n for j in range(15):\n for k in range(15):\n if (i**2 + j**2) == k**2:\n if (i**2 + 0) != k**2:\n if (0 + j**2) != k**2: \n if (0 + 0) != k**2:\n ordered_triplet = sorted([i, j, k])\n if ordered_triplet not in SpecialTriangles:\n SpecialTriangles.append(ordered_triplet)\n\nprint(SpecialTriangles)\n [[3, 4, 5], [5, 12, 13], [6, 8, 10]]\n"
},
{
"answer_id": 74522218,
"author": "Hobanator",
"author_id": 15324493,
"author_profile": "https://Stackoverflow.com/users/15324493",
"pm_score": 2,
"selected": true,
"text": "for i in range(3):\n for k in range(3):\n print(i, k)\n 0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2\n for i in range(3):\n for k in range(i, 3):\n print(i, k)\n 0 0\n0 1\n0 2\n1 1\n1 2\n2 2\n for i in range(15):\n for j in range(i, 15):\n for k in range(j, 15):\n"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20503795/"
] |
74,521,738
|
<p>I want to add a closing Parenthesis to each line in the text that ends with "CSQL_CREATE_VIEW (" + some words + ")"</p>
<p>So that the end result looks like this: CSQL_CREATE_VIEW (name of view) /n.
I am not able to get the closing bracket with my current code. Help!</p>
<pre><code> string[] Files = System.IO.Directory.GetFiles(@"filepath");
string path = @"outputTextPath";
foreach (string s in Files)
{
;
string fileCont = System.IO.File.ReadAllText(s);
if(fileCont.Contains("create view") == true)
{
File.AppendAllText(path, fileCont.Replace("create view","CSQL_CREATE_VIEW (") );
if (fileCont == "\r" && fileCont.Contains("CSQL_CREATE_VIEW ("))
{
File.AppendAllText(path, ")" + Environment.NewLine);
}
}
}
</code></pre>
|
[
{
"answer_id": 74521939,
"author": "pm100",
"author_id": 173397,
"author_profile": "https://Stackoverflow.com/users/173397",
"pm_score": 2,
"selected": true,
"text": "if (fileCont == \"\\r\" && fileCont.Contains(\"CSQL_CREATE_VIEW (\"))\n fileCont.Endwith(\"\\n\")"
},
{
"answer_id": 74522609,
"author": "Rufus L",
"author_id": 2052655,
"author_profile": "https://Stackoverflow.com/users/2052655",
"pm_score": 0,
"selected": false,
"text": "\"create view\" \"CSQL_CREATE_VIEW (\" public static void ReplaceCreateView(string inputFilePath, string outputFilePath)\n{\n List<string> newFileLines = new List<string>();\n\n foreach (string line in File.ReadLines(inputFilePath))\n {\n if (line.Contains(\"create view\"))\n {\n // Save a line where we replace 'create view' and add a closing parenthesis\n newFileLines.Add(line.Replace(\"create view\", \"CSQL_CREATE_VIEW (\") + \")\");\n }\n else\n {\n newFileLines.Add(line);\n }\n }\n\n File.WriteAllLines(outputFilePath, newFileLines);\n}\n \"_Updated\" public static void UpdateAllFiles(string directoryPath)\n{\n foreach(var filePath in Directory.GetFiles(directoryPath))\n {\n // Create a new name for the file by appending '_Updated' to the orginal\n var fileName = Path.GetFileNameWithoutExtension(filePath);\n var ext = Path.GetExtension(filePath);\n var newFilePath = Path.Combine(directoryPath, $\"{fileName}_Updated{ext}\");\n\n ReplaceCreateView(filePath, newFilePath);\n }\n}\n"
},
{
"answer_id": 74522656,
"author": "Idle_Mind",
"author_id": 2330053,
"author_profile": "https://Stackoverflow.com/users/2330053",
"pm_score": 0,
"selected": false,
"text": "String[] Files = System.IO.Directory.GetFiles(@\"filepath\");\nforeach (String s in Files)\n{\n Boolean changesMade = false;\n String[] lines = System.IO.File.ReadAllLines(s);\n for(int i=0; i<lines.Length; i++)\n {\n if (lines[i].Contains(\"create view\"))\n {\n changesMade = true;\n lines[i] = lines[i].Replace(\"create view\", \"CSQL_CREATE_VIEW (\");\n if (!lines[i].EndsWith(\")\"))\n {\n lines[i] = lines[i] + \")\";\n }\n }\n }\n if (changesMade)\n {\n System.IO.File.WriteAllLines(s, lines);\n }\n}\n"
},
{
"answer_id": 74522700,
"author": "Max",
"author_id": 13523921,
"author_profile": "https://Stackoverflow.com/users/13523921",
"pm_score": 0,
"selected": false,
"text": "((CSQL_CREATE_VIEW \\()(.*)(\\r|\\n|\\r\\n))"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18659251/"
] |
74,521,785
|
<p>I have a array like this:</p>
<pre><code>const arr = [['Dog', 'Cat', 'Fish', 'Bird'],[1, 4, 2, 3]];
</code></pre>
<p>How would I sort it so its in the order:</p>
<pre><code>const arr = [['Dog', 'Fish', 'Bird', 'Cat'],[1, 2, 3, 4]];
</code></pre>
|
[
{
"answer_id": 74521855,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 2,
"selected": false,
"text": "zip zip let zip = args => args[0].map((_, i) => args.map(a => a[i]))\n\n//\n\nconst arr = [['Dog', 'Cat', 'Fish', 'Bird'],[1, 4, 2, 3]];\n\nr = zip(zip(arr).sort((x, y) => x[1] - y[1]))\n\nconsole.log(r)"
},
{
"answer_id": 74521861,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 0,
"selected": false,
"text": "Array#reduce items Map Array#sort Map#get Array#sort const sort = ([ items, indices ]) => {\n const indexMap = items.reduce((map, item, index) => \n map.set(item, indices[index])\n , new Map);\n return [\n items.sort((a, b) => indexMap.get(a) - indexMap.get(b)),\n indices.sort()\n ];\n}\n\n\nconsole.log( sort([['Dog', 'Cat', 'Fish', 'Bird'], [1, 4, 2, 3]]) );"
},
{
"answer_id": 74521953,
"author": "Hedi Zitouni",
"author_id": 12285347,
"author_profile": "https://Stackoverflow.com/users/12285347",
"pm_score": 0,
"selected": false,
"text": "function deepSort(arr2d) {\n const [stringArr, indexArr] = arr2d\n const result = []\n indexArr.forEach((index, i) => result[index - 1] = stringArr[i])\n return [result, indexArr.sort()]\n}\n\n"
},
{
"answer_id": 74521969,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 0,
"selected": false,
"text": "const\n array = [['Dog', 'Cat', 'Fish', 'Bird'], [1, 4, 2, 3]],\n indices = [...array[1].keys()].sort((a, b) => array[1][a] - array[1][b]);\n\nfor (let i = 0; i < array.length; i++)\n array[i] = indices.map(j => array[i][j]);\n\nconsole.log(array); .as-console-wrapper { max-height: 100% !important; top: 0; }"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18217632/"
] |
74,521,830
|
<p>Using Tailwind, I am having trouble creating a table with a scrollable body that spans the full width. Currently the way I'm doing it is by setting the <code>tbody</code> to <code>display: block</code> but by doing that the <code>tbody</code> isn't the full width. How can I go about making it full width? I want the table body to be scrollable separately from the rest of the page.</p>
<p><a href="https://play.tailwindcss.com/2eJggerfCg?layout=horizontal" rel="nofollow noreferrer">Tailwind Playground</a></p>
|
[
{
"answer_id": 74521855,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 2,
"selected": false,
"text": "zip zip let zip = args => args[0].map((_, i) => args.map(a => a[i]))\n\n//\n\nconst arr = [['Dog', 'Cat', 'Fish', 'Bird'],[1, 4, 2, 3]];\n\nr = zip(zip(arr).sort((x, y) => x[1] - y[1]))\n\nconsole.log(r)"
},
{
"answer_id": 74521861,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 0,
"selected": false,
"text": "Array#reduce items Map Array#sort Map#get Array#sort const sort = ([ items, indices ]) => {\n const indexMap = items.reduce((map, item, index) => \n map.set(item, indices[index])\n , new Map);\n return [\n items.sort((a, b) => indexMap.get(a) - indexMap.get(b)),\n indices.sort()\n ];\n}\n\n\nconsole.log( sort([['Dog', 'Cat', 'Fish', 'Bird'], [1, 4, 2, 3]]) );"
},
{
"answer_id": 74521953,
"author": "Hedi Zitouni",
"author_id": 12285347,
"author_profile": "https://Stackoverflow.com/users/12285347",
"pm_score": 0,
"selected": false,
"text": "function deepSort(arr2d) {\n const [stringArr, indexArr] = arr2d\n const result = []\n indexArr.forEach((index, i) => result[index - 1] = stringArr[i])\n return [result, indexArr.sort()]\n}\n\n"
},
{
"answer_id": 74521969,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 0,
"selected": false,
"text": "const\n array = [['Dog', 'Cat', 'Fish', 'Bird'], [1, 4, 2, 3]],\n indices = [...array[1].keys()].sort((a, b) => array[1][a] - array[1][b]);\n\nfor (let i = 0; i < array.length; i++)\n array[i] = indices.map(j => array[i][j]);\n\nconsole.log(array); .as-console-wrapper { max-height: 100% !important; top: 0; }"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19626871/"
] |
74,521,835
|
<p>I work on a python project, and I would like to create a history where each history is erasable with a "delete" button placed in the Frame of the widget</p>
<p>I tried to add the « delete » button in the loop where the widget was generated but it didn’t work as planned</p>
<pre><code>history_files = os.listdir(history_directory)
history_files.sort(reverse=True)
number_of_h = 0
for file in history_files:
file_dat = open(history_directory+"\\"+file)
file_dat_lines = file_dat.readlines()
action_amount_h = file_dat_lines[0]
h_comment = file_dat_lines[1]
h_date = file_dat_lines[2]
h_time = file_dat_lines[3]
history_f = Frame(history_win_f, bg=bg_theme, height=120, width=485, highlightbackground=bg_theme_2, highlightthickness=1)
history_f.grid_propagate(False)
history_f.columnconfigure(1, weight=70)
history_f.columnconfigure(2, weight=30)
history_f.rowconfigure(1, weight=60)
history_f.rowconfigure(2, weight=40)
action_h_f = LabelFrame(history_f, bg=bg_theme, width=390, height=120, font='Courrier 13 bold', labelanchor="n")
action_h_f.grid_propagate(False)
action_h_f.rowconfigure(1, weight=30)
action_h_f.rowconfigure(2, weight=70)
action_h_f.columnconfigure(1, weight=100)
action_h_f.grid(row=1, column=1, sticky="w")
date_h_f = LabelFrame(history_f, bg=bg_theme, height=120, width=95, text=' Date ', labelanchor="n", font='Courrier 10 bold')
date_h_f.grid(row=1, rowspan=2, column=2, sticky="nesw")
date_h_f.rowconfigure(1, weight=50)
date_h_f.rowconfigure(2, weight=50)
date_h_f.columnconfigure(1, weight=100)
date_l = Label(date_h_f, text="Le "+h_date, bg=bg_theme, fg=fg_theme_2, font='Courrier 8').grid(row=1, column=1, sticky="nesw")
time_l = Label(date_h_f, text="A "+h_time, bg=bg_theme, fg=fg_theme_2, font='Courrier 8').grid(row=2, column=1, sticky="nesw")
date_h_f.grid_propagate(False)
h_edit_a = Label(action_h_f, bg=bg_theme, font="Courrier 11", justify="center")
h_edit_a_str = ""
</code></pre>
<p>I would appreciate any explanation, and if the code is simple, because I'm still a newbie. Thanks !</p>
|
[
{
"answer_id": 74521855,
"author": "gog",
"author_id": 3494774,
"author_profile": "https://Stackoverflow.com/users/3494774",
"pm_score": 2,
"selected": false,
"text": "zip zip let zip = args => args[0].map((_, i) => args.map(a => a[i]))\n\n//\n\nconst arr = [['Dog', 'Cat', 'Fish', 'Bird'],[1, 4, 2, 3]];\n\nr = zip(zip(arr).sort((x, y) => x[1] - y[1]))\n\nconsole.log(r)"
},
{
"answer_id": 74521861,
"author": "Majed Badawi",
"author_id": 7486313,
"author_profile": "https://Stackoverflow.com/users/7486313",
"pm_score": 0,
"selected": false,
"text": "Array#reduce items Map Array#sort Map#get Array#sort const sort = ([ items, indices ]) => {\n const indexMap = items.reduce((map, item, index) => \n map.set(item, indices[index])\n , new Map);\n return [\n items.sort((a, b) => indexMap.get(a) - indexMap.get(b)),\n indices.sort()\n ];\n}\n\n\nconsole.log( sort([['Dog', 'Cat', 'Fish', 'Bird'], [1, 4, 2, 3]]) );"
},
{
"answer_id": 74521953,
"author": "Hedi Zitouni",
"author_id": 12285347,
"author_profile": "https://Stackoverflow.com/users/12285347",
"pm_score": 0,
"selected": false,
"text": "function deepSort(arr2d) {\n const [stringArr, indexArr] = arr2d\n const result = []\n indexArr.forEach((index, i) => result[index - 1] = stringArr[i])\n return [result, indexArr.sort()]\n}\n\n"
},
{
"answer_id": 74521969,
"author": "Nina Scholz",
"author_id": 1447675,
"author_profile": "https://Stackoverflow.com/users/1447675",
"pm_score": 0,
"selected": false,
"text": "const\n array = [['Dog', 'Cat', 'Fish', 'Bird'], [1, 4, 2, 3]],\n indices = [...array[1].keys()].sort((a, b) => array[1][a] - array[1][b]);\n\nfor (let i = 0; i < array.length; i++)\n array[i] = indices.map(j => array[i][j]);\n\nconsole.log(array); .as-console-wrapper { max-height: 100% !important; top: 0; }"
}
] |
2022/11/21
|
[
"https://Stackoverflow.com/questions/74521835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20564759/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.