qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
74,288,416 | <p>I want to use ESAPI in my project and have added following dependency in the <code>pom.xml</code></p>
<p>pom.xml with dependency:</p>
<pre><code> <dependency>
<groupId>org.owasp.encoder</groupId>
<artifactId>encoder</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>2.5.0.0</version>
</dependency>
</code></pre>
<p>But when I import <code>org.owasp.esapi.*</code> intellij give me warning as shown in image.
<a href="https://i.stack.imgur.com/DFADw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DFADw.png" alt="enter image description here" /></a></p>
<p>I want to use ESAPI logger to prevent CRLF injection possibilities in log statements.
My current project uses <code>slf4j.Logger</code></p>
<p>I am very new to this ESAPI and OWASP and have never used it and have tried from here
<a href="https://github.com/ESAPI/esapi-java-legacy/wiki/Using-ESAPI-with-SLF4J#configuring-esapi-to-use-slf4j" rel="nofollow noreferrer">https://github.com/ESAPI/esapi-java-legacy/wiki/Using-ESAPI-with-SLF4J#configuring-esapi-to-use-slf4j</a></p>
<p>Please tell me if im doing something wrong and how to correctly use ESAPI in project.</p>
| [
{
"answer_id": 74300731,
"author": "jdk",
"author_id": 12611597,
"author_profile": "https://Stackoverflow.com/users/12611597",
"pm_score": 1,
"selected": true,
"text": "<dependencyManagement>"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12611597/"
] |
74,288,417 | <p>Route:</p>
<pre><code>Route::get('/posts/{post}', [PostController::class, 'show']);
</code></pre>
<p>Controller:</p>
<pre><code>public function show(Post $post){
$postData = $post->load(['author' => function($query){
$query->select('post_id', 'name');
}])
->get(['title', 'desc', 'created_date'])
->toArray();
}
</code></pre>
<p>This returns all the posts in the database, While I only want to get the selected post passed to the <code>show</code> function.</p>
<p>So if I visit <code>/posts/3</code>, It should show data related to the post with <code>id</code> = 3, not all posts.</p>
<p>The result should be an array with only the selected post.</p>
| [
{
"answer_id": 74300731,
"author": "jdk",
"author_id": 12611597,
"author_profile": "https://Stackoverflow.com/users/12611597",
"pm_score": 1,
"selected": true,
"text": "<dependencyManagement>"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18570839/"
] |
74,288,431 | <p>I've got two lists:</p>
<pre><code>lst1 = [{"name": "Hanna", "age":3},
{"name": "Kris", "age": 18},
{"name":"Dom", "age": 15},
{"name":"Tom", "age": 5}]
</code></pre>
<p>and the second one contains a few of above key <code>name</code> values under different key:</p>
<pre><code>lst2 = [{"username": "Kris", "Town": "Big City"},
{"username":"Dom", "Town": "NYC"}]
</code></pre>
<p>I would like to merge them with result:</p>
<pre><code>lst = [{"name": "Hanna", "age":3},
{"name": "Kris", "age": 18, "Town": "Big City"},
{"name":"Dom", "age": 15, "Town": "NYC"},
{"name":"Tom", "age":"5"}]
</code></pre>
<p>The easiest way is to go one by one (for each element from lst1, check whether it exists in lst2), but for big lists, this is quite ineffective (my lists have a few hundred elements each). What is the most effective way to achieve this?</p>
| [
{
"answer_id": 74288543,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 1,
"selected": false,
"text": "lst1 = [{\"name\": \"Hanna\", \"age\":3},\n {\"name\": \"Kris\", \"age\": 18},\n {\"name\":\"Dom\", \"age\": 15},\n {\"name\":\"Tom\", \"age\": 5}]\nlst2 = [{\"username\": \"Kris\", \"Town\": \"Big City\"},\n {\"username\":\"Dom\", \"Town\": \"NYC\"}]\n\nname_index = { dic['username'] : idx for idx, dic in enumerate(lst2) if dic.get('username') }\n\nfor dic in lst1:\n name = dic.get('name')\n if name in name_index:\n dic.update(lst2[name_index[name]]) # update in-place to further save time\n dic.pop('username')\n\nprint(lst1)\n"
},
{
"answer_id": 74288976,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 0,
"selected": false,
"text": "lst1"
},
{
"answer_id": 74289140,
"author": "Carmoreno",
"author_id": 4508767,
"author_profile": "https://Stackoverflow.com/users/4508767",
"pm_score": 0,
"selected": false,
"text": "zip"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3449093/"
] |
74,288,434 | <p>I would like to <em>relabel</em> the levels of factors as follows:</p>
<p><code>i. If the level is of length 3 and above relabel it to sentence case otherwise do title case</code></p>
<p>ie <code>home doing nothing</code> becomes <code>Home doing nothing</code>, <code>yes</code> becomes <code>Yes</code> and <code>good practice</code> becomes <code>Good Practice</code></p>
<p>Is there any way to do this?</p>
<pre><code>library(tidyverse)
vars <- c("a", "b", "c", "d", "e")
mydata <- tribble(
~"a", ~"b", ~"c", ~"d", ~"e", ~"id",
"yes", "school in Kenya", "r", 10, "good practice", 1,
"no", "home doing nothing", "python", 12, "doing well", 3,
"no", "school in Tanzania", "c++", 35, "by walking", 4,
"yes", "home practising", "c", 65, "practising everyday", 5,
"no", "home", "java", 78, "sitting alone", 7
) %>%
mutate(across(.cols = vars, ~as_factor(.)))
# mydata %>%
# mutate(across(where(is.factor), ~fct_relabel(., str_to_sentence(.))))
</code></pre>
| [
{
"answer_id": 74288543,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 1,
"selected": false,
"text": "lst1 = [{\"name\": \"Hanna\", \"age\":3},\n {\"name\": \"Kris\", \"age\": 18},\n {\"name\":\"Dom\", \"age\": 15},\n {\"name\":\"Tom\", \"age\": 5}]\nlst2 = [{\"username\": \"Kris\", \"Town\": \"Big City\"},\n {\"username\":\"Dom\", \"Town\": \"NYC\"}]\n\nname_index = { dic['username'] : idx for idx, dic in enumerate(lst2) if dic.get('username') }\n\nfor dic in lst1:\n name = dic.get('name')\n if name in name_index:\n dic.update(lst2[name_index[name]]) # update in-place to further save time\n dic.pop('username')\n\nprint(lst1)\n"
},
{
"answer_id": 74288976,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 0,
"selected": false,
"text": "lst1"
},
{
"answer_id": 74289140,
"author": "Carmoreno",
"author_id": 4508767,
"author_profile": "https://Stackoverflow.com/users/4508767",
"pm_score": 0,
"selected": false,
"text": "zip"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13734451/"
] |
74,288,484 | <p>I am trying to implement an increment button in React that will update the value of a field in a table by one. Specifically, I am trying to increment the "stock" by one</p>
<p>This is what I'm currently trying:</p>
<pre><code>class App extends React.Component {
constructor(props) {
super(props);
this.state = {
cars: [
{
"manufacturer": "Toyota",
"model": "Rav4",
"year": 2008,
"stock": 3,
"price": 8500
},
{
"manufacturer": "Toyota",
"model": "Camry",
"year": 2009,
"stock": 2,
"price": 6500
},
{
"manufacturer": "Toyota",
"model": "Tacoma",
"year": 2016,
"stock": 1,
"price": 22000
},
{
"manufacturer": "BMW",
"model": "i3",
"year": 2012,
"stock": 5,
"price": 12000
},
{
"manufacturer": "Chevy",
"model": "Malibu",
"year": 2015,
"stock": 2,
"price": 10000
},
{
"manufacturer": "Honda",
"model": "Accord",
"year": 2013,
"stock": 1,
"price": 9000
},
{
"manufacturer": "Hyundai",
"model": "Elantra",
"year": 2013,
"stock": 2,
"price": 7000
},
{
"manufacturer": "Chevy",
"model": "Cruze",
"year": 2012,
"stock": 2,
"price": 5500
},
{
"manufacturer": "Dodge",
"model": "Charger",
"year": 2013,
"stock": 2,
"price": 16000
},
{
"manufacturer": "Ford",
"model": "Mustang",
"year": 2009,
"stock": 1,
"price": 8000
},
]
};
}
onHeaderClick(){
}
increaseStock(event){
this.setState({cars: this.state.cars.stock + 1})
}
decreaseStock(event){
this.setState({cars: this.state.cars.stock + 1})
}
render() {
return (
<table>
<tr>
<th>Manufacturer</th>
<th>Model</th>
<th onClick={()=> this.onHeaderClick}>Year</th>
<th>Stock</th>
<th>Price</th>
<th>Options</th>
<th></th>
</tr>
{
this.state.cars.map(car => (
<tr key={car.model}>
<td>{car.manufacturer}</td>
<td>{car.model}</td>
<td>{car.year}</td>
<td>{car.stock}</td>
<td>${car.price}.00</td>
<td><button type="button" onClick={this.increaseStock.bind(this)}>Increment</button></td>
<td><button type="button" onClick={this.decreaseStock.bind(this)}>Decrement</button></td>
</tr>
))
}
</table>
);
};
}
ReactDOM.render(<App />, document.getElementById("app"))
</code></pre>
<p>I have tried a bunch of different implementations all to no avail. Where am I going wrong?</p>
| [
{
"answer_id": 74288543,
"author": "ILS",
"author_id": 10017662,
"author_profile": "https://Stackoverflow.com/users/10017662",
"pm_score": 1,
"selected": false,
"text": "lst1 = [{\"name\": \"Hanna\", \"age\":3},\n {\"name\": \"Kris\", \"age\": 18},\n {\"name\":\"Dom\", \"age\": 15},\n {\"name\":\"Tom\", \"age\": 5}]\nlst2 = [{\"username\": \"Kris\", \"Town\": \"Big City\"},\n {\"username\":\"Dom\", \"Town\": \"NYC\"}]\n\nname_index = { dic['username'] : idx for idx, dic in enumerate(lst2) if dic.get('username') }\n\nfor dic in lst1:\n name = dic.get('name')\n if name in name_index:\n dic.update(lst2[name_index[name]]) # update in-place to further save time\n dic.pop('username')\n\nprint(lst1)\n"
},
{
"answer_id": 74288976,
"author": "bn_ln",
"author_id": 10535824,
"author_profile": "https://Stackoverflow.com/users/10535824",
"pm_score": 0,
"selected": false,
"text": "lst1"
},
{
"answer_id": 74289140,
"author": "Carmoreno",
"author_id": 4508767,
"author_profile": "https://Stackoverflow.com/users/4508767",
"pm_score": 0,
"selected": false,
"text": "zip"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20392334/"
] |
74,288,486 | <p>i'm new of this framework :(
the problem is here because i've tried to put the component in another page and work it.</p>
<p>It sign error the component</p>
<p>this is my index.vue page
<a href="https://i.stack.imgur.com/S8Y7W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S8Y7W.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74288544,
"author": "kissu",
"author_id": 8816585,
"author_profile": "https://Stackoverflow.com/users/8816585",
"pm_score": -1,
"selected": false,
"text": "template"
},
{
"answer_id": 74288596,
"author": "Amini",
"author_id": 15351296,
"author_profile": "https://Stackoverflow.com/users/15351296",
"pm_score": 0,
"selected": false,
"text": "<template>\n <main>\n <navbar />\n <slideshow />\n </main>\n</template>\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19972485/"
] |
74,288,542 | <p>How do I align text to the right if it is only one line, but otherwise align to the left (so that new lines start from the left, not right)? Is it possible to do it in the xml (non-programatically)?</p>
<p>What I want:</p>
<p><a href="https://i.stack.imgur.com/ST2vx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ST2vx.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/lCn1U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lCn1U.png" alt="enter image description here" /></a></p>
<p>What I have:</p>
<p><a href="https://i.stack.imgur.com/pCr1V.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pCr1V.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/XZZ04.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XZZ04.png" alt="enter image description here" /></a></p>
<p>Code:</p>
<pre><code><androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Label" />
<TextView
android:id="@+id/content"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/label"
app:layout_constraintTop_toTopOf="@id/label"
tools:text="Lorem ipsum" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code></pre>
| [
{
"answer_id": 74298339,
"author": "Abin Stanly",
"author_id": 6037916,
"author_profile": "https://Stackoverflow.com/users/6037916",
"pm_score": 0,
"selected": false,
"text": " <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:gravity=\"start\"\n android:layout_gravity=\"end\"\n android:text=\"Lorem ipsum\" />\n"
},
{
"answer_id": 74299126,
"author": "MariosP",
"author_id": 14434976,
"author_profile": "https://Stackoverflow.com/users/14434976",
"pm_score": 3,
"selected": true,
"text": "layout_constraintHorizontal_bias=\"1\""
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4953867/"
] |
74,288,550 | <p>I have a dataframe of genetic data called 'windows'</p>
<pre><code>glimpse(windows)
Rows: 3,000
Columns: 5
$ chrpos <chr> "1:104159999-104168402", "1:104159999-104168402", "1:104159999-104168402"
$ target <chr> "AMY2A", "CFD13", "PUTA"
$ name <chr> "rs5753", "rs70530", "rs21111"
$ chr <chr> "1", "1", "1"
$ pos <int> 104560629, 104562750, 104557705
</code></pre>
<p>I want to make them in to separate dataframes by the row in the column 'target'</p>
<pre><code>AMY2A<- filter(windows, target == 'AMY2A')
write.table("am2ya.txt", header=T)
</code></pre>
<p>Which works fine, but is laborious doing for each element row of 'target'</p>
<p>But how do I loop through all of these, and then save them out as text files, in one go?</p>
<pre><code>list <- windows$target
for(i in list)
df.list[[i]]<-filter(windows, target == list[[i]])
</code></pre>
<p>Which gives the error:</p>
<pre><code>Error in `filter()`:
! Problem while computing `..1 = target == list[[i]]`.
Caused by error in `list[[i]]`:
! subscript out of bounds
</code></pre>
<p>And when I google saving out multiple txt files, it just comes up how to read in multiple text files.</p>
<p>Any help would be great, thanks!</p>
| [
{
"answer_id": 74288699,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 2,
"selected": true,
"text": "lst <- windows$target\n\nfor(i in seq_along(lst)){\n dat <- filter(windows, target == lst[[i]])\n write.table(dat, paste0(tolower(lst[[i]]), \".txt\"))\n}\n\n"
},
{
"answer_id": 74288868,
"author": "Limey",
"author_id": 13434871,
"author_profile": "https://Stackoverflow.com/users/13434871",
"pm_score": 2,
"selected": false,
"text": "windows %>% \n group_by(target) %>% \n group_walk(\n function(.x, .y) {\n write.table(.x, paste0(tolower(.y$target[1]), \".txt\"))\n },\n .keep=TRUE\n )\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10054013/"
] |
74,288,555 | <p>but I get lot of error in it.<a href="https://i.stack.imgur.com/aQo8q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aQo8q.png" alt="enter image description here" /></a></p>
<p>I could not understand where there problem is, is it the a</p>
| [
{
"answer_id": 74288655,
"author": "amalloy",
"author_id": 625403,
"author_profile": "https://Stackoverflow.com/users/625403",
"pm_score": 2,
"selected": false,
"text": "<-"
},
{
"answer_id": 74289014,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 2,
"selected": false,
"text": "UnicodeSyntax"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20397117/"
] |
74,288,566 | <p>I'm trying to get the total income of a specific seller. I already computed the total gross/income, but the problem here is instead of showing it only to the specific seller, it's also being shown to others. <strong>(please ignore the spent)</strong></p>
<p><a href="https://i.stack.imgur.com/GfKC7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GfKC7.png" alt="enter image description here" /></a></p>
<pre><code>router.get("/total/:id", async (req, res) => {
const { id } = req.params;
const date = new Date();
const lastMonth = new Date(date.setMonth(date.getMonth() - 1));
const previousMonth = new Date(new Date().setMonth(lastMonth.getMonth() - 1));
try {
const income = await Order.aggregate([
{$group: {_id: "6360d4d5bd860240e258c582", total: {$sum: "$amount"} }}
])
res.status(200).json(income);
} catch (err) {
res.status(500).json(err);
}
});
</code></pre>
<p>OrderSchema</p>
<pre><code>const OrderSchema = new mongoose.Schema({
userId: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
products: [
{
productId:{
type: mongoose.Schema.Types.ObjectId, ref: 'Product'
},
quantity: {
type: Number,
default: 1,
},
sellerId: {
type: String
}
}
],
amount: {type: Number,required: true},
location:{type: Object, required:true},
time: {type: String, required: true},
status: {type:String, default: "pending"},
tax: {type: Number,}
}, {timestamps: true}
)
export default mongoose.model('Order', OrderSchema)
</code></pre>
<p>But the problem is, other accounts can also see the total income</p>
<p><a href="https://i.stack.imgur.com/oWz3f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oWz3f.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74288723,
"author": "Charchit Kapoor",
"author_id": 12368154,
"author_profile": "https://Stackoverflow.com/users/12368154",
"pm_score": 2,
"selected": true,
"text": "router.get(\"/total/:id\", async (req, res) => {\nconst { id } = req.params;\nconst date = new Date();\nconst lastMonth = new Date(date.setMonth(date.getMonth() - 1));\nconst previousMonth = new Date(new Date().setMonth(lastMonth.getMonth() - 1));\n\ntry {\n const income = await Order.aggregate([\n { $match: {_id: id}},\n {$group: {_id: \"$_id\", total: {$sum: \"$amount\"} }}\n ])\n res.status(200).json(income);\n} catch (err) {\n res.status(500).json(err);\n}\n});\n"
},
{
"answer_id": 74289045,
"author": "Stykgwar",
"author_id": 20088885,
"author_profile": "https://Stackoverflow.com/users/20088885",
"pm_score": 0,
"selected": false,
"text": "router.get(\"/total/:id\", async (req, res) => {\n const { id } = req.params;\n const date = new Date();\n const lastMonth = new Date(date.setMonth(date.getMonth() - 1));\n const previousMonth = new Date(new Date().setMonth(lastMonth.getMonth() - 1));\n \n try {\n const income = await Order.aggregate([\n {$match: {'products.sellerId': id},},\n {$group: {_id: \"$products.sellerId\", total: {$sum: \"$amount\"} }}\n ])\n console.log(id)\n res.status(200).json(income);\n } catch (err) {\n res.status(500).json(err);\n }\n });\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20088885/"
] |
74,288,585 | <p>I am using the DropdownButtonFormField. It seems to have no way to customise the padding. With the TextFormField, if I set dense to true, I can customise the padding, etc. to make it the size I want. I set dense to true on the DropdownButtonFormField and nothing happens.</p>
<p>See screenshot below</p>
<p><a href="https://i.stack.imgur.com/BTRHU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BTRHU.png" alt="enter image description here" /></a></p>
<p>Edit:</p>
<p>I can control the height with a container</p>
<p><a href="https://i.stack.imgur.com/YueER.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YueER.png" alt="enter image description here" /></a></p>
<p>but when there is an error, it shrinks in an extremely weird way, likely because the container wraps the whole dropdown button.</p>
<p><a href="https://i.stack.imgur.com/hFuuU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hFuuU.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74288888,
"author": "harizh",
"author_id": 16240306,
"author_profile": "https://Stackoverflow.com/users/16240306",
"pm_score": 1,
"selected": false,
"text": "Tooltip(\n message: \"Maker dropdown\",\n child: Container(\n padding: const EdgeInsets.only(left: 5.0),\n decoration: BoxDecoration(\n color: Theme.of(context).hoverColor,\n shape: BoxShape.rectangle,\n borderRadius: BorderRadius.circular(5),\n ),\n child: DropdownButtonHideUnderline(\n key: UniqueKey(),\n child: ButtonTheme(\n key: UniqueKey(),\n alignedDropdown: true,\n child: DropdownButtonFormField<Makers>(\n key: UniqueKey(),\n style: Theme.of(context).textTheme.headline2,\n dropdownColor: Theme.of(context).backgroundColor,\n decoration: InputDecoration(\n icon: FaIcon(\n FontAwesomeIcons.screwdriverWrench,\n color: Theme.of(context).hintColor,\n ),\n focusedBorder: const UnderlineInputBorder(\n borderSide: BorderSide(color: Colors.transparent)),\n enabledBorder: const UnderlineInputBorder(\n borderSide: BorderSide(color: Colors.transparent)),\n fillColor: Colors.transparent),\n value: _myMaker,\n iconSize: 15.0,\n isExpanded: true,\n icon: Icon(Icons.arrow_forward_ios,\n color: Theme.of(context).hintColor),\n elevation: 8,\n hint: AutoSizeText(\"Select Maker\",\n style: Theme.of(context).textTheme.headline3),\n onChanged: (Makers? newValue) {\n setState(() {\n _myMaker = newValue;\n });\n },\n validator: (value) => Validator.validateMakers(\n myMaker: _myMaker,\n ),\n items: items = _makersList\n .map((item) => DropdownMenuItem<Makers>(\n key: UniqueKey(),\n value: item,\n child: Text(item!.name),\n ))\n .toList(),\n ))),\n ),\n );\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10410570/"
] |
74,288,616 | <p>So I've got an array of arrays, each with a value and a name corresponding to said value.
Here I hard-coded it, but in reality it's not.</p>
<p>I have a function which is supposed to return the array it was given, but with only ONE of each value. However, the function is removing other values too. Here is the code:</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>const scorersArr = [
[2, 'Lewandowski'],
[1, 'Gnarby'],
[2, 'Lewandowski'],
[1, 'Hummels'],
]
const returnNoDupes = (arr) => {
let returnArr = arr;
for (const arrVal1 of arr) {
for (const arrValLoop of arr) {
if (arrVal1 === arrValLoop) returnArr.splice(arrVal1, 1)
}
}
return returnArr;
}
console.log(returnNoDupes(scorersArr)); //. Expected: [[2, "Lewandowski"], [1, "Hummels"], [1, "Gnarby"]]</code></pre>
</div>
</div>
</p>
<p>I know that the bug has something to do with the fact that I have a 2D array, as this function works on a 1D array but I can't quite put my finger on what it is.</p>
| [
{
"answer_id": 74288716,
"author": "Ankit",
"author_id": 19757319,
"author_profile": "https://Stackoverflow.com/users/19757319",
"pm_score": 1,
"selected": true,
"text": " const scorersArr = [\n [2, 'Lewandowski'],\n [1, 'Gnarby'],\n [2, 'Lewandowski'],\n [1, 'Hummels'],\n ]\n\n const returnNoDupes = (arr) => {\n for (let i =0 ; i<arr.length ; i++){\n for (let j =0 ; j<arr.length ; j++) {\n if (arr[i][1] === arr[j][1] && i!==j){ \n arr.splice(j, 1)\n }\n }}\n return arr;\n }\n console.log(returnNoDupes(scorersArr));"
},
{
"answer_id": 74288791,
"author": "Waleed Iqbal",
"author_id": 4758651,
"author_profile": "https://Stackoverflow.com/users/4758651",
"pm_score": 1,
"selected": false,
"text": "const scorersArr = [\n [2, 'Lewandowski'],\n [1, 'Gnarby'],\n [2, 'Lewandowski'],\n [1, 'Hummels'],\n]\n\nconst duplicatesRemoved = Array.from(new Set(scorersArr.map(JSON.stringify)), JSON.parse)\n\nconsole.log(duplicatesRemoved)\n"
},
{
"answer_id": 74288813,
"author": "Wazeed",
"author_id": 6394979,
"author_profile": "https://Stackoverflow.com/users/6394979",
"pm_score": -1,
"selected": false,
"text": "Array.reduce()"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,288,671 | <p>I am working on a Blazor project and some of the grids we are creating can have many columns and/or rows. I had read that lambda functions are "expensive" and read <a href="https://learn.microsoft.com/en-us/aspnet/core/blazor/performance?view=aspnetcore-6.0#avoid-recreating-delegates-for-many-repeated-elements-or-components" rel="nofollow noreferrer">here</a> that an <code>Action</code> is the way to go.</p>
<p>So using that example I added a property to my <code>Cell</code> class as such:</p>
<p><code>public Action<MouseEventArgs> Action { get; set; } = (e) => { };</code></p>
<p>And then to use this property while setting up the cells I do:</p>
<p><code>someRow.FixedCells[0].Action = (e) => { SwapIngredientRows(someRow, false); };</code></p>
<p>Prior to this change the Razor code was:</p>
<p><code>@onclick="@(() => SwapIngredientRows(row, false))"</code></p>
<p>This <code>SwapIngredientRows</code> method is <code>async</code> and does await 2 calls internally and graphically updates the screen.</p>
<p>Once I changed it to:</p>
<p><code>@onclick="cell.Action"</code></p>
<p>The actual database is updated but the UI is not updated when calling the <strong>exact same</strong> method.</p>
<p>I am wondering if I could change the <code>Action</code> to a <code>Func</code> or <code>EventCallback</code> or something so it behaves just like the original lambda method I started with?</p>
<h1>Updated with Enhancement</h1>
<p>After using the @hank-holterman solution for a while and loving it, I eventually needed to know when the <code>Control</code> key was pressed while clicking. The following is the adjusted property:</p>
<pre><code>public Func<MouseEventArgs, Task> Action { get; set; }
</code></pre>
<p>And I use it like:</p>
<pre><code>Action = (e) => ProcessClick(e, my, other, properties)
</code></pre>
<p>Where <code>e</code> are the <code>MouseEventArgs</code>. If you do not need the <code>MouseEventArgs</code> then just do not pass them into your method:</p>
<pre><code>Action = (e) => DumbClick(my, other, properties)
</code></pre>
<p>And the <code>razor</code> syntax does not need to change:</p>
<pre><code>@onclick="cell.Action"
</code></pre>
| [
{
"answer_id": 74288753,
"author": "rotgers",
"author_id": 2223566,
"author_profile": "https://Stackoverflow.com/users/2223566",
"pm_score": 2,
"selected": false,
"text": "Action"
},
{
"answer_id": 74289030,
"author": "Henk",
"author_id": 60761,
"author_profile": "https://Stackoverflow.com/users/60761",
"pm_score": 3,
"selected": true,
"text": "someRow.FixedCells[0].Action = (e) => { SwapIngredientRows(someRow, false); };"
},
{
"answer_id": 74289190,
"author": "MrC aka Shaun Curtis",
"author_id": 13065781,
"author_profile": "https://Stackoverflow.com/users/13065781",
"pm_score": 1,
"selected": false,
"text": "IHandleEvent"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373438/"
] |
74,288,685 | <p>I am reading impala parquet from HDFS into Clickhouse. Target table in clickhouse has 2 complex types:</p>
<pre><code>target_type1 Array(Tuple( LowCardinality(String),
Int 8,
Int 32,
Int 32,
Int 32
))
</code></pre>
<pre><code>target_type2 Array(Tuple( LowCardinality(String),
LowCardinality(String),
LowCardinality(String)
))
</code></pre>
<p>Source table's type is <code>String</code>. How should I construct souce table's <code>String</code> and transform it into the target type?</p>
<p>For example,</p>
<p>Target table</p>
<pre><code>create table test (
a String,
b Array(String),
c Array(Tuple(Int, String, String))
) engine = MergeTree order by tuple()
</code></pre>
<p>Source</p>
<pre><code>with t as (
select '123#def#aaa|456#xxx#aaa|789#bbbb#aaaa|3333#www#aaaa' as x, splitByChar('|', x) as y, splitByChar('#', y[1]) as z
) select * from t;
</code></pre>
<p>How should I construct the source string <code>x</code> and transform it, so as to load into <code>c Array(Tuple(Int, String, String))</code>?</p>
| [
{
"answer_id": 74292420,
"author": "JustMe",
"author_id": 644511,
"author_profile": "https://Stackoverflow.com/users/644511",
"pm_score": 2,
"selected": true,
"text": "INSERT INTO test (c) SELECT groupArray(new) AS val\nFROM\n(\n SELECT\n '123#def#aaa|456#xxx#aaa|789#bbbb#aaaa|3333#www#aaaa' AS x,\n splitByChar('|', x) AS y,\n splitByChar('#', arrayJoin(y)) AS s,\n (toInt32(s[1]), s[2], s[3]) AS new\n)\n"
},
{
"answer_id": 74292759,
"author": "Rick",
"author_id": 5983841,
"author_profile": "https://Stackoverflow.com/users/5983841",
"pm_score": 0,
"selected": false,
"text": "select '123|bbb|ccc;111|abc|deee;123|BB|CC;123|feq|ffdfa;848|ddkz|djkf' as t0,\n splitByChar(';', t0) as t,\n arrayJoin(t) as t1,\n tuple(toInt32(splitByChar('|', t1)[1]), splitByChar('|', t1)[2], splitByChar('|', t1)[3]) as t2,\n groupArray(t2) as t3,\n toTypeName(t3);\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5983841/"
] |
74,288,691 | <p>I have a value in a column 'ACCOUNT_N0', it consists of 14 digits I want them to be 16 digits by inserting 2 zeros in the middle, one in the 4th position and the other in the 8th position
example:
This is the value: 33322288888888
The output: 3330222088888888</p>
<p>What i have found is inserting zeros at the beginning of the number, using:</p>
<pre><code>df['ACCOUNT_NO'].astype(str).str.zfill(16)
</code></pre>
<p>I want to know how to insert in the 4th position and the 8th position</p>
| [
{
"answer_id": 74288904,
"author": "Adam Jaamour",
"author_id": 5609328,
"author_profile": "https://Stackoverflow.com/users/5609328",
"pm_score": 1,
"selected": false,
"text": "0"
},
{
"answer_id": 74288987,
"author": "Frex8",
"author_id": 19143337,
"author_profile": "https://Stackoverflow.com/users/19143337",
"pm_score": 0,
"selected": false,
"text": "def insert_0(text):\n tmp = text\n text = tmp[0:3] + '0' + tmp[3:7] + '0' + tmp[7:]\n return text\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20397196/"
] |
74,288,704 | <p>I have the following code with me which was shared by another user on this forum:</p>
<pre><code>ods exclude all;
ods output nlevels=nlevels;
proc freq data=sashelp.cars nlevels;
tables _all_ / noprint ;
run;
ods select all;
proc contents data=sashelp.cars noprint out=contents;
run;
proc sql;
create table want(drop=table:) as
select c.varnum,c.name,c.type,n.*
from contents c inner join nlevels n
on c.name=n.TableVar
order by varnum
;
quit;
filename code temp;
data _null_;
set contents end=eof;
length nliteral $65 dsname $80;
nliteral=nliteral(name);
dsname = catx('.',libname,nliteral(memname));
file code;
if _n_=1 then put 'create table counts as select ' / ' ' @ ;
else put ',' @;
put 'nmiss(' nliteral ') as missing_' varnum
/',count(distinct ' nliteral ') as distinct_' varnum
;
if eof then put 'from ' dsname ';';
run;
proc sql;
%include code /source2;
quit;
proc transpose data=counts out=count2 name=name ;
run;
proc sql ;
create table want as
select c.varnum, c.name, c.type
, m.col1 as nmissing
, d.col1 as ndistinct
from contents c
left join count2 m on m.name like 'missing%' and c.varnum=input(scan(m.name,-1,'_'),32.)
left join count2 d on d.name like 'distinct%' and c.varnum=input(scan(d.name,-1,'_'),32.)
order by varnum
;
quit;
</code></pre>
<p>The above code gives the following output:</p>
<pre><code>|Obs| VARNUM | NAME | TYPE| nmissing| ndistinct|
1 1 Make 2 0 38
2 2 Model 2 0 425
3 3 Type 2 0 6
...
</code></pre>
<p>My question is what does the following part of the above code do:</p>
<pre><code>filename code temp;
data _null_;
set contents end=eof;
length nliteral $65 dsname $80;
nliteral=nliteral(name);
dsname = catx('.',libname,nliteral(memname));
file code;
if _n_=1 then put 'create table counts as select ' / ' ' @ ;
else put ',' @;
put 'nmiss(' nliteral ') as missing_' varnum
/',count(distinct ' nliteral ') as distinct_' varnum
;
if eof then put 'from ' dsname ';';
run;
proc sql;
%include code /source2;
quit;
</code></pre>
<p>Could someone please explain what each line of the above portion of the code is doing? Thank you.</p>
| [
{
"answer_id": 74288904,
"author": "Adam Jaamour",
"author_id": 5609328,
"author_profile": "https://Stackoverflow.com/users/5609328",
"pm_score": 1,
"selected": false,
"text": "0"
},
{
"answer_id": 74288987,
"author": "Frex8",
"author_id": 19143337,
"author_profile": "https://Stackoverflow.com/users/19143337",
"pm_score": 0,
"selected": false,
"text": "def insert_0(text):\n tmp = text\n text = tmp[0:3] + '0' + tmp[3:7] + '0' + tmp[7:]\n return text\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20396712/"
] |
74,288,742 | <p>I am trying to push an object to a list of objects in vuetify. Im using Vue 3.</p>
<p>This is my html code:</p>
<pre><code> <a to="#" data-toggle="tooltip" data-placement="top" title="Add to cart"
@click.stop.prevent="handleAddToCart(product)">
<v-icon class="icon-bag2">mdi-medical-bag</v-icon>
</a>
</code></pre>
<p>Note: I have used stop.prevent cause the icon is inside a div which is clickable.</p>
<p>This is what I have tried in my click event method:
declared in data: productList = []</p>
<pre><code> handleAddToCart(product) {
this.productList.push(product)
console.log('product list', this.productList)
this.$cookies.set('cart', JSON.stringify(this.productList))
}
</code></pre>
<p>I want to save this array in cookies but it keeps replacing object and not pushing the object one after another.</p>
<p><a href="https://i.stack.imgur.com/NLt7k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NLt7k.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74288904,
"author": "Adam Jaamour",
"author_id": 5609328,
"author_profile": "https://Stackoverflow.com/users/5609328",
"pm_score": 1,
"selected": false,
"text": "0"
},
{
"answer_id": 74288987,
"author": "Frex8",
"author_id": 19143337,
"author_profile": "https://Stackoverflow.com/users/19143337",
"pm_score": 0,
"selected": false,
"text": "def insert_0(text):\n tmp = text\n text = tmp[0:3] + '0' + tmp[3:7] + '0' + tmp[7:]\n return text\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11764338/"
] |
74,288,762 | <p>I have a dataframe with a column <code>distances</code> with integer values between 1 and 3500. I want to assign a weight in <code>(0.25, 0.5, 1, 2)</code> to each sample based on the <code>distance</code> value.</p>
<pre><code>| Distances | weights |
| --------- | ------- |
| >= 3000 | 0.25 |
| >= 2000 and < 3000 | 0.5 |
| >= 1000 and < 2000 | 1 |
| < 1000 | 2 |
</code></pre>
<p>For the dataframe as below,</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>sample</th>
<th>distances</th>
</tr>
</thead>
<tbody>
<tr>
<td>First</td>
<td>3234</td>
</tr>
<tr>
<td>Second</td>
<td>465</td>
</tr>
<tr>
<td>Third</td>
<td>1200</td>
</tr>
</tbody>
</table>
</div>
<p>the weights should be <code>{0.25, 2, 1}</code>. What is a good way to do this?</p>
| [
{
"answer_id": 74288795,
"author": "Gonçalo Peres",
"author_id": 7109869,
"author_profile": "https://Stackoverflow.com/users/7109869",
"pm_score": 0,
"selected": false,
"text": "df"
},
{
"answer_id": 74289341,
"author": "Chrysophylaxs",
"author_id": 9499196,
"author_profile": "https://Stackoverflow.com/users/9499196",
"pm_score": 1,
"selected": false,
"text": "df = pd.DataFrame({\n \"sample\": [\"First\", \"Second\", \"Third\"],\n \"distances\": [3234, 465, 1200]\n})\n\nmapping = {\n pd.Interval(3000, np.inf, closed=\"left\"): 0.25,\n pd.Interval(2000, 3000, closed=\"left\"): 0.5,\n pd.Interval(1000, 2000, closed=\"left\"): 1.0,\n pd.Interval(-np.inf, 1000, closed=\"left\"): 2.0,\n}\n\nseries = pd.Series(data=mapping.values(), index=mapping.keys())\n\ndf[\"weight\"] = pd.cut(df[\"distances\"], series.index).map(series)\n\n# sample distances weight\n# 0 First 3234 0.25\n# 1 Second 465 2.00\n# 2 Third 1200 1.00\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5959374/"
] |
74,288,790 | <p>The simplest example I can give, is a User that can create multiple Posts. A one-to-many relationship where multiple posts can be tied to a single user.</p>
<p>But what if I want the User to only be able to have a max of 10 Posts? Ideally there'd be some kind of query I can run when creating a new Post, and if the limit has been reached, to reject creating that Post (or possibly replace a Post).</p>
<p>I'm kind of stumped on this. And I'm not sure if there is a way I can model this to create the desired outcome.</p>
<p>Otherwise, the only real solution I see is to fetch all Posts for a User, and count them before trying to create a new Post. But that would require two calls to the db instead of one which is the problem I am trying to avoid.</p>
| [
{
"answer_id": 74289257,
"author": "Mal",
"author_id": 13088508,
"author_profile": "https://Stackoverflow.com/users/13088508",
"pm_score": 2,
"selected": false,
"text": "CREATE OR REPLACE FUNCTION check_number_of_row()\nRETURNS TRIGGER AS\n$body$\nBEGIN\n IF (SELECT count(*) FROM your_table) > 10\n THEN \n RAISE EXCEPTION 'INSERT statement exceeding maximum number of rows for this table' \n END IF;\nEND;\n$body$\nLANGUAGE plpgsql;\n\nCREATE TRIGGER tr_check_number_of_row \nBEFORE INSERT ON your_table\nFOR EACH ROW EXECUTE PROCEDURE check_number_of_row();\n"
},
{
"answer_id": 74292933,
"author": "Hoàng Huy Khánh",
"author_id": 9711476,
"author_profile": "https://Stackoverflow.com/users/9711476",
"pm_score": 2,
"selected": true,
"text": "const createPost = async (post, userId) => {\n return prisma.$transaction(async (prisma) => {\n // 1. Count current total user posts\n const currentPostCount = await prisma.posts.count({\n where: {\n user_id: userId,\n },\n })\n\n // 2. Check if user can create posts\n if (currentPostCount >= 10) {\n throw new Error(`User ${userId} has reached maximum posts}`)\n }\n\n // TODO\n // 3. Create your posts here\n await prisma.posts.create({\n data: post\n })\n })\n}\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16468170/"
] |
74,288,798 | <p>There is incoming response like this;</p>
<pre><code>{
"response_code":23
}
</code></pre>
<p>there is no issue reading data,</p>
<p>and I am able to read this value with this object;</p>
<pre><code>public class APIResponse
{
[JsonProperty("response_code")]
public HttpStatusCode ResponseCode { get; set; }
}
</code></pre>
<p>But when I need to return this object to client as JSON it should look like this;</p>
<pre><code>{
"responseCode":23
}
</code></pre>
<p>so basically I want to change property name for serialization only, how can I do that?</p>
| [
{
"answer_id": 74290229,
"author": "n-azad",
"author_id": 5997281,
"author_profile": "https://Stackoverflow.com/users/5997281",
"pm_score": 0,
"selected": false,
"text": "[JsonProperty(\"response_code\")]"
},
{
"answer_id": 74301190,
"author": "Peter Csala",
"author_id": 13268855,
"author_profile": "https://Stackoverflow.com/users/13268855",
"pm_score": 2,
"selected": true,
"text": "public class APIResponse\n{\n [JsonProperty(\"response_code\")]\n public HttpStatusCode ResponseStatusCode { get; set; } //For deserialization\n \n public bool ShouldSerializeResponseStatusCode() => false;\n\n //[JsonProperty(\"ResponseCode\")]\n public HttpStatusCode ResponseCode => ResponseStatusCode; //For serialization\n}\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2959783/"
] |
74,288,802 | <p>Today, the Deployment jobs in our Azure Devops pipelines are all showing the warning:</p>
<p><code>##[warning]Resource file has already set to: D:\a\_tasks\AzureKeyVault_1e244d.........\1.212.0\node_modules\azure-pipelines-tasks-azure-arm-rest-v2\module.json</code></p>
<p><strike>Additionally, variables passed into the jobs are being passed as empty strings, resulting in failures.</strike> - This seems to be resolved as of 3rd November.</p>
<p>Needless to say, we have re-run our pipelines multiple times to no avail, and have reviewed the Azure Devops status page - which shows no issues.</p>
<p>The pipelines were all working normally yesterday (1st November).</p>
<p>The warnings seem to appear for any deployment job referencing a variable group linked to a key vault, e.g.</p>
<pre class="lang-yaml prettyprint-override"><code> - deployment: MyDeployment
pool:
vmImage: ubuntu-20.04
variables:
- group: MyKeyVaultLinkedVariableGroup
</code></pre>
| [
{
"answer_id": 74383177,
"author": "Ceeno Qi-MSFT",
"author_id": 18361074,
"author_profile": "https://Stackoverflow.com/users/18361074",
"pm_score": 1,
"selected": true,
"text": "- task: AzureKeyVault@2"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19734178/"
] |
74,288,822 | <p>how to use Sed to add spicial charectar ?</p>
<p>script shell: the chalange is:</p>
<p>I have a large file xx.html:</p>
<p>
...
...
...</p>
<p>my quastion is how can I use sed command to insert this line:
secure_token = ''
function getipInfo()</p>
<p>to xx.html file before</p>
<pre><code></body> line
I try to much scinario , alwase there is issue in php charectar
sed -i '102i secure_token = \'\<\?php \e\cho file_get_contents\(\"token.txt\"\); \?\>\'\n
function getipInfo()' xx.html
</code></pre>
| [
{
"answer_id": 74383177,
"author": "Ceeno Qi-MSFT",
"author_id": 18361074,
"author_profile": "https://Stackoverflow.com/users/18361074",
"pm_score": 1,
"selected": true,
"text": "- task: AzureKeyVault@2"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
74,288,846 | <p>I currently have a problem where I'm keeping a json file in the internal storage, and I wish to append a new object into that file.</p>
<p>This is how I make the file:</p>
<pre class="lang-kotlin prettyprint-override"><code>val fOut = openFileOutput("notes.txt", MODE_PRIVATE)
val str = "[]"
fOut.write(str.toByteArray())
fOut.close()
</code></pre>
<p>Which results in the file looking like this:</p>
<pre><code>[]
</code></pre>
<p>So far so good, now I need to append a new object to that json file:</p>
<pre class="lang-kotlin prettyprint-override"><code>val fileOutputSream = openFileOutput("jsonfile.json", MODE_APPEND)
fileOutputSream.write(obj.toString().toByteArray())
fileOutputSream.close()
</code></pre>
<p>But it always ends up looking like this:</p>
<pre><code>[]{"item1": "value1", "item2": "value2", "item3": "value3"}
</code></pre>
<p>And not like this:</p>
<pre><code>[
{"item1": "value1", "item2": "value2", "item3": "value3"}
]
</code></pre>
| [
{
"answer_id": 74289006,
"author": "Somnath",
"author_id": 15660680,
"author_profile": "https://Stackoverflow.com/users/15660680",
"pm_score": 0,
"selected": false,
"text": " JSONObject jsonObject;\n \n\n try {\n Writer output = null;\n File file = new File(Path +\"/jsonfile.json\");\n output = new BufferedWriter(new FileWriter(file));\n output.write(jsonObject.toString());\n output.close();\n Toast.makeText(getApplicationContext(), \"Composition saved\", Toast.LENGTH_LONG).show();\n\n } catch (Exception e) {\n Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();\n }\n"
},
{
"answer_id": 74291851,
"author": "Sam Chen",
"author_id": 3466808,
"author_profile": "https://Stackoverflow.com/users/3466808",
"pm_score": 1,
"selected": false,
"text": "JSONArray"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17626607/"
] |
74,288,852 | <p>Here is my code can anybody suggest me what to do also NOTE: My app only supports from android 6 to 10 devices only so suggest me accordingly</p>
<pre><code>private fun shareInvoice(){
binding.consLayout1.isDrawingCacheEnabled = true
binding.consLayout1.buildDrawingCache()
binding.consLayout1.drawingCacheQuality = View.DRAWING_CACHE_QUALITY_HIGH
val bitmap:Bitmap = binding.consLayout1.drawingCache
val sdf = SimpleDateFormat("dd-MM-yyyy hh:mm:ss", Locale.getDefault())
val root = Environment.getExternalStorageDirectory().absoluteFile
val file = File(root,"/Pictures")
val imageName = "ServiceInvoice_${businessName}_${sdf.format(System.currentTimeMillis())}"
val myFile = File(file,imageName)
if (myFile.exists()){
myFile.delete()
}
try {
val fos = FileOutputStream(myFile)
bitmap.compress(Bitmap.CompressFormat.JPEG,100, fos)
fos.flush()
fos.close()
showMessage("Invoice generated successfully")
binding.consLayout1.isDrawingCacheEnabled = false
Log.e("INVOICE TAG", "shareInvoice:$myFile")
}catch (e:Exception){
Log.e("FOS TAG", "shareInvoice:$e")
}
}
</code></pre>
| [
{
"answer_id": 74289006,
"author": "Somnath",
"author_id": 15660680,
"author_profile": "https://Stackoverflow.com/users/15660680",
"pm_score": 0,
"selected": false,
"text": " JSONObject jsonObject;\n \n\n try {\n Writer output = null;\n File file = new File(Path +\"/jsonfile.json\");\n output = new BufferedWriter(new FileWriter(file));\n output.write(jsonObject.toString());\n output.close();\n Toast.makeText(getApplicationContext(), \"Composition saved\", Toast.LENGTH_LONG).show();\n\n } catch (Exception e) {\n Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();\n }\n"
},
{
"answer_id": 74291851,
"author": "Sam Chen",
"author_id": 3466808,
"author_profile": "https://Stackoverflow.com/users/3466808",
"pm_score": 1,
"selected": false,
"text": "JSONArray"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19732840/"
] |
74,288,856 | <p>I have a react element to which I assign a ref, and when clicking I would like to get the position of the element (just the y). That code works:</p>
<pre><code><InnerElement
ref={myRef}
onClick={() => {
console.log(myRef.current?.offsetTop);
}}
/>
</code></pre>
<p>But it doesn't take into account if the element is inside of a div that is scrolled. If that parent div is scrolling, the value of <code>myRef.current?.offsetTop</code> will remain the same</p>
<p>Is there a way to get the absolute position of that ref in the viewport?</p>
| [
{
"answer_id": 74289017,
"author": "Andrew Parks",
"author_id": 5898421,
"author_profile": "https://Stackoverflow.com/users/5898421",
"pm_score": 1,
"selected": false,
"text": "getBoundingClientRect().y + window.scrollY\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9856049/"
] |
74,288,877 | <p>In my NEXT.JS project, I want a simple <code><p></code> element to show below my button for x amount of time, and then I want it to disappear. I don't want to use alert() function. How can I manage that?</p>
| [
{
"answer_id": 74289017,
"author": "Andrew Parks",
"author_id": 5898421,
"author_profile": "https://Stackoverflow.com/users/5898421",
"pm_score": 1,
"selected": false,
"text": "getBoundingClientRect().y + window.scrollY\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20137771/"
] |
74,288,885 | <p>with this formula:</p>
<pre><code>datanew <- df_bsp %>%
group_by(id_mother) %>%
dplyr::mutate(Family = cur_group_id())
</code></pre>
<p>I got this output:</p>
<pre><code>datanew <- data.frame(id_pers=c(1, 2, 3, 4, 5, 6),
id_mother=c(11, 11, 11, 12, 12, 12),
FAMILY=c(1,1,1,2,2,2)
</code></pre>
<p>now the problem:</p>
<p>There are also some NA's in the id_mother-variable</p>
<p>it looks like this:</p>
<pre><code>datanew_1 <- data.frame(id_pers=c(1, 2, 3, 4, 5, 6, 7, 8, 9,10),
id_mother=c(11, 11, 11, 12, 12, 12, NA, NA, NA, NA)
</code></pre>
<p>How can i get this result:</p>
<pre><code>datanew <- data.frame(id_pers=c(1, 2, 3, 4, 5, 6, 7, 8, 9,10),
id_mother=c(11, 11, 11, 12, 12, 12, NA, NA, NA, NA),
FAMILY=c(1,1,1,2,2,2,3,4,5,6)
</code></pre>
<p>THX</p>
| [
{
"answer_id": 74289017,
"author": "Andrew Parks",
"author_id": 5898421,
"author_profile": "https://Stackoverflow.com/users/5898421",
"pm_score": 1,
"selected": false,
"text": "getBoundingClientRect().y + window.scrollY\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20018384/"
] |
74,288,903 | <p>I know it is not related to coding but really need to know this. Already googled it but no concrete answer was found.</p>
<p>The client wants to know whether our application is vulnerable to the latest vulnerability which is found in OpenSSL.
CVE-2022-3786
CVE-2022-3602</p>
<p>Reference: <a href="https://snyk.io/blog/new-openssl-critical-vulnerability/" rel="nofollow noreferrer">https://snyk.io/blog/new-openssl-critical-vulnerability/</a></p>
| [
{
"answer_id": 74289460,
"author": "SoySolisCarlos",
"author_id": 2620025,
"author_profile": "https://Stackoverflow.com/users/2620025",
"pm_score": 2,
"selected": false,
"text": "openssl version"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/854440/"
] |
74,288,917 | <p>I updated my project to angular v14 from v9. Until v12 there was no problem but now I can't build it anymore. It failes with an <code>Error: Optimization error [default-src_app_main_collection_module_ts.js]: SyntaxError: Unexpected token: punc ({)</code>.</p>
<p>If in <code>angular.json</code> I disable scripts optimization ( <code>{ "configurations": { "production": { "optimization": { "scripts": false }}}}</code> ), the error does not appear. I think it might has something to do with the transcription from ts to js files but I do not know whats causing the problem.</p>
<p>So there are two questions:</p>
<ol>
<li>Do you know something about this error? (There may be an incompatibility of typescript transcription methode I use and the angular 14 optimizer but I could not find it.)</li>
<li>What does script optimization do? If the scripts optimization is not important I will just disable it.</li>
</ol>
<p>Thanks for your help in advance!</p>
<pre><code>"dependencies": {
"@angular/animations": "^14.2.7",
"@angular/cdk": "14.2.5",
"@angular/common": "^14.2.7",
"@angular/compiler": "^14.2.7",
"@angular/core": "^14.2.7",
"@angular/flex-layout": "^14.0.0-beta.41",
"@angular/forms": "^14.2.7",
"@angular/material": "^14.2.5",
"@angular/platform-browser": "^14.2.7",
"@angular/platform-browser-dynamic": "^14.2.7",
"@angular/router": "14.2.7",
"@auth0/angular-jwt": "^5.0.1",
"@editorjs/editorjs": "^2.25.0",
"@editorjs/paragraph": "^2.8.0",
"@flowjs/flow.js": "2.14.1",
"@nicky-lenaers/ngx-scroll-to": "^14.0.0",
"@stomp/stompjs": "^6.1.0",
"@types/jquery": "3.5.14",
"@types/resize-observer-browser": "^0.1.7",
"@types/sockjs-client": "^1.5.0",
"angular-resizable-element": "^3.4.0",
"angular-resize-event": "^2.1.0",
"angular-shepherd": "^14.0.0",
"angular-svg-round-progressbar": "^9.0.0",
"angular2-virtual-scroll": "0.4.16",
"copy-image-clipboard": "^2.1.2",
"core-js": "^3.26.0",
"dompurify": "^2.1.1",
"event-source-polyfill": "^1.0.21",
"fs-extra": "^10.1.0",
"git-describe": "^4.0.4",
"html2canvas": "^1.4.1",
"jquery": "^3.5.1",
"jquery.scrollto": "2.1.3",
"jstree": "^3.3.10",
"material-design-icons": "^3.0.1",
"material-icons": "^1.10.8",
"moment": "^2.29.3",
"ng-recaptcha": "^10.0.0",
"ngx-clipboard": "14.0.1",
"ngx-contextmenu": "^6.0.0",
"ngx-infinite-scroll": "^14.0.0",
"ngx-perfect-scrollbar": "^10.0.1",
"ngx-scrollbar": "^10.0.1",
"overlayscrollbars": "1.13.0",
"rxjs": "^6.6.7",
"shepherd.js": "^10.0.1",
"sockjs-client": "^1.5.1",
"tslib": "^2.4.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "^14.2.6",
"@angular/cli": "14.2.6",
"@angular/compiler-cli": "^14.2.7",
"@angular/language-service": "^14.2.7",
"@types/jasmine": "^4.3.0",
"@types/node": "^16.11.7",
"codelyzer": "^6.0.0",
"hammerjs": "^2.0.8",
"husky": "^4.3.8",
"jasmine-core": "^4.4.0",
"jasmine-reporters": "^2.5.0",
"jasmine-spec-reporter": "^7.0.0",
"karma": "~6.4.1",
"karma-chrome-launcher": "^3.1.1",
"karma-coverage-istanbul-reporter": "^3.0.3",
"karma-jasmine": "^5.1.0",
"karma-jasmine-html-reporter": "^2.0.0",
"karma-junit-reporter": "2.0.1",
"lint-staged": "^13.0.3",
"ng-mocks": "^14.3.1",
"ng-packagr": "^14.2.2",
"prettier": "^1.19.1",
"protractor": "~7.0.0",
"puppeteer": "^19.2.0",
"sonar-scanner": "^3.1.0",
"ts-node": "^10.9.1",
"tslint": "~6.1.0",
"tslint-config-prettier": "^1.18.0",
"typescript": "^4.8.4"
},
</code></pre>
| [
{
"answer_id": 74289460,
"author": "SoySolisCarlos",
"author_id": 2620025,
"author_profile": "https://Stackoverflow.com/users/2620025",
"pm_score": 2,
"selected": false,
"text": "openssl version"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18972072/"
] |
74,288,950 | <p>I have a dynamic array of ng-select controls. Each control represented by class <a href="https://github.com/ng-select/ng-select/blob/master/src/ng-select/lib/ng-select.component.ts#L73" rel="nofollow noreferrer">NgSelectComponent</a>.</p>
<p>When select value changes I want to subscribe to all controls.</p>
<p>Template</p>
<pre><code> <ng-select #select">
<ng-option *ngFor="let option of options" [value]="select.id">{{ option.name }}</ng-option>
</ng-select>
</code></pre>
<p>Class</p>
<pre><code> @ViewChildren('select') controls: QueryList<NgSelectComponent>;
ngAfterViewInit() {
concat(this.controls.toArray()).subscribe(x => {
console.log(x);
});
}
</code></pre>
<p>I try that, but does not work.</p>
<pre><code>concat(this.components.toArray()).subscribe(x => {
console.log(x);
});
</code></pre>
<p>I believe it does not work because I had to subscribe to the values produced by each control corresponded by <a href="https://github.com/ng-select/ng-select/blob/master/src/ng-select/lib/ng-select.component.ts#L156" rel="nofollow noreferrer">changeEvent</a> but struggling to do that.</p>
<p>Any ideas how to solve?</p>
| [
{
"answer_id": 74289460,
"author": "SoySolisCarlos",
"author_id": 2620025,
"author_profile": "https://Stackoverflow.com/users/2620025",
"pm_score": 2,
"selected": false,
"text": "openssl version"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2926340/"
] |
74,288,966 | <p>I have sample data set as follows,</p>
<pre><code>| Customer | |Detail | |DataValues |
|----------| |-------| |-----------|
| ID | |ID | |CustomerID |
| Name | |Name | |DetailID |
|Values |
| Customer | |Detail | |DataValues |
|----------| |---------| |-----------|
| 1 | Jack | | 1 | sex | | 1 | 1 | M |
| 2 | Anne | | 2 | age | | 1 | 2 | 30|
| 2 | 1 | F |
| 2 | 2 | 28|
</code></pre>
<p>and my desired outcome is below,</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Name</th>
<th>Sex</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jack</td>
<td>M</td>
<td>30</td>
</tr>
<tr>
<td>Anne</td>
<td>F</td>
<td>28</td>
</tr>
</tbody>
</table>
</div>
<p>I have failed to come up with a correct SQL Query that returns anything.</p>
<p>Thanks in advance.</p>
<pre><code>select Customers.Name, Details.Name, DataValues.Value from Customers
inner join DataValues on DataValues.CustomersID = Customers.ID
inner join Details on DataValues.DetailsID = Details.ID
</code></pre>
| [
{
"answer_id": 74289460,
"author": "SoySolisCarlos",
"author_id": 2620025,
"author_profile": "https://Stackoverflow.com/users/2620025",
"pm_score": 2,
"selected": false,
"text": "openssl version"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20397235/"
] |
74,288,977 | <p>I am trying to update a global list from inside a function.</p>
<p>Here is the code that does not work (can be sourced as a whole file):</p>
<pre><code>require(rlang)
(my_list <- list(a = 1, b = "two", c = "set outside"))
print( paste("my_list$c is" , my_list$c) )
my_function <- function(x = 1, y = 2, parent_object_name = "my_list") {
z <- x + y # do some stuff (irrelevant here)
some_names <- "updated inside"
upper_env_object_name <- paste0(parent_object_name, "$c")
# browser()
# env_poke(env = env_tail(), upper_env_object_name, some_names) # does not work
# env_poke(env = env_parents()[[1]], upper_env_object_name, some_names) # does not work
env_poke(env = caller_env(), upper_env_object_name, some_names ) # creates `my_list$c` character vector
# force(env_poke(env = caller_env(), upper_env_object_name, some_names )) # creates `my_list$c` character vector
# browser()
# env_poke(env = caller_env(), paste0("as.list(",upper_env_object_name,")"), some_names) # creates as.list(my_list$c)` character vector
return(z)
}
my_function(x = 1, y = 2, parent_object_name = "my_list")
print(class(`my_list$c`))
print( `my_list$c`)
print( paste("my_list$c is" , my_list$c) )
</code></pre>
<p>I found this but it does not help:
<a href="https://stackoverflow.com/questions/69934750/updating-a-nested-list-object-in-the-global-environment-from-within-a-function-i">Updating a nested list object in the global environment from within a function in R</a></p>
<p>Tried also with assign, and specifying the environment.</p>
<p>Background: I have some S3- subclases and want to keep track of them in the parent class object, which is also a list. The subclass objects are created "on-demand" and I want to have an overview what was created. My workaround for now is to create a new vector in the global environment and update it with :</p>
<pre><code>if (exists("global_names_list")) global_names_list <<- unique(rbind(global_names_list, some_names)) else global_names_list <<- some_names
</code></pre>
| [
{
"answer_id": 74289089,
"author": "AndS.",
"author_id": 9778513,
"author_profile": "https://Stackoverflow.com/users/9778513",
"pm_score": 1,
"selected": true,
"text": "my_list <- list(a = 1, b = \"two\", c = \"set outside\")\n\nmy_function <- function(x = 1, y = 2, parent_object_name = \"my_list\"){\n z <- x+y\n \n some_names <- \"updated inside\"\n lst <- get(parent_object_name)\n lst$c <- some_names\n assign(parent_object_name, lst, envir = .GlobalEnv)\n \n return(z)\n \n}\n\nmy_function()\n#> [1] 3\n\n#check\nmy_list\n#> $a\n#> [1] 1\n#> \n#> $b\n#> [1] \"two\"\n#> \n#> $c\n#> [1] \"updated inside\"\n"
},
{
"answer_id": 74290041,
"author": "G. Grothendieck",
"author_id": 516548,
"author_profile": "https://Stackoverflow.com/users/516548",
"pm_score": 1,
"selected": false,
"text": "f <- function(listname = \"my_list\", envir = .GlobalEnv) {\n envir[[listname]]$c <- \"some value\"\n}\n\n# test\nmy_list <- list(a = 1, b = \"two\", c = \"set outside\")\nf()\nstr(my_list)\n## List of 3\n## $ a: num 1\n## $ b: chr \"two\"\n## $ c: chr \"some value\"\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74288977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4554888/"
] |
74,289,021 | <p>I am trying to get individual dates ("2022-10-10") and hours ("2022-10-10T09") between an interval in UTC. I could get the individual dates by the following -</p>
<pre class="lang-js prettyprint-override"><code>function getDatesInRange(startDate, endDate) {
const date = new Date(startDate.getTime());
const dates = [];
while (date <= endDate) {
const day = new Date(date).toISOString().split(':')[0].split('T')[0];
dates.push(day);
date.setDate(date.getDate() + 1);
}
return dates;
}
console.log(getDatesInRange(new Date('2022-10-10T20:50:59.938Z'), new Date('2022-10-15T23:50:59.938Z')));
</code></pre>
<p>Hence, the above returns - <code>["2022-10-10", "2022-10-11", "2022-10-12", "2022-10-13", "2022-10-14", "2022-10-15"]</code></p>
<p>I also want to return the hours of the start and end date and the rest should be dates. So i want to get in return - <code>["2022-10-10T20", "2022-10-10T21", "2022-10-10T22", "2022-10-10T23" "2022-10-11", "2022-10-12", "2022-10-13", "2022-10-14", "2022-10-15T00", "2022-10-15T01"]</code></p>
<p>Here is what i have as of now -</p>
<pre class="lang-js prettyprint-override"><code>function getHoursInRange(startDate, endDate) {
let startDatePlusOne = new Date(startDate);
startDatePlusOne.setDate(startDatePlusOne.getDate() + 1);
let endDateMinusOne = new Date(endDate);
endDateMinusOne.setDate(endDateMinusOne.getDate() - 1);
const date = new Date(startDate.getTime());
console.log("Start date :", date);
let dates = getDatesInRange(startDatePlusOne, endDateMinusOne);
console.log("Only days : ", dates);
startDatePlusOne.setHours(0);
while (date < startDatePlusOne) {
const day = new Date(date).toISOString().split(':')[0];
dates.push(day);
date.setHours(date.getHours() + 1);
}
endDateMinusOne.setHours(23);
const edate = endDateMinusOne.getTime();
while (edate < endDate) {
const day = new Date(edate).toISOString().split(':')[0];
dates.push(day);
date.setHours(date.getHours() + 1);
}
return dates
}
</code></pre>
<p>For this use case, i am getting the days back excluding the start and end dates. But for getting each hour of start and end date it gets stuck somehow. Somehow i feel there is a better way to do this. Any ideas ?</p>
| [
{
"answer_id": 74289301,
"author": "Andrew Parks",
"author_id": 5898421,
"author_profile": "https://Stackoverflow.com/users/5898421",
"pm_score": 2,
"selected": true,
"text": "function getDatesInRange(startDate, endDate) {\n let h = new Set(), d = new Set(), t = [];\n for(let i=startDate.getTime(); i<endDate.getTime(); i+=1000*1800) t.push(i);\n [...t, endDate.getTime()].forEach(i=>{\n let s = new Date(i).toISOString();\n [[s.split(':')[0], h], [s.split('T')[0], d]].forEach(([s,r])=>r.add(s));\n });\n let firstDate = [...d.values()][0], lastDate = [...d.values()].pop();\n return d.size===1 ? [...h.values()] : [\n ...[...h.values()].filter(v=>v.startsWith(firstDate)),\n ...[...d.values()].filter(v=>v!==firstDate && v!==lastDate),\n ...[...h.values()].filter(v=>v.startsWith(lastDate))];\n}\nconsole.log(getDatesInRange(\n new Date('2022-10-10T20:50:59.938Z'), new Date('2022-10-15T23:50:59.938Z')));"
},
{
"answer_id": 74290167,
"author": "Ben Aston",
"author_id": 38522,
"author_profile": "https://Stackoverflow.com/users/38522",
"pm_score": 0,
"selected": false,
"text": "dateRange"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15944854/"
] |
74,289,040 | <p>I have been trying to pass a simple value from the child component to the parent component, but every time I trigger the function passed from parent to child, I get an error: Cannot read properties of undefined. I have looked at examples and I don't see what is wrong. I know a simple dropdown menu could easily be implemented into one component but I want to keep the separate.
Here is the code of the parent component:</p>
<pre><code>import React, { useState } from "react";
import Axios from "axios";
import "../css/app.css";
import ClassesDropdown from "./ClassesDropdown";
function CreateCharacter() {
const [name, setName] = useState("");
const [race, setRace] = useState("");
const [classId, setClassId] = useState("1");
const [level, setLevel] = useState("");
const [creatorId, setCreatorId] = useState("");
const [campaignId, setCampaignId] = useState("");
const [description, setDescription] = useState("");
const submitPost = () => {
Axios.post("http://localhost:3002/api/characters/create", {
name: name,
race: race,
classId: classId,
level: level,
creatorId: creatorId,
campaignId: campaignId,
description: description,
});
};
const getClassDropdown = (selectedClass) => {
setClassId(selectedClass);
console.log("Class is selected!");
};
return (
<div>
<div className="boxed">
<span className="formTitle">Create a character:</span>
<div>
<label>Name: </label>
<input
type="text"
onChange={(e) => {
setName(e.target.value);
}}
/>
</div>
<div>
<label>Race: </label>
<input
type="text"
onChange={(e) => {
setRace(e.target.value);
}}
/>
</div>
<div>
<label>Class: </label>
<ClassesDropdown onClassFetch={getClassDropdown} />
</div>
<div>
<label>Level: </label>
<input
type="number"
onChange={(e) => {
setLevel(e.target.value);
}}
/>
</div>
<div>
<label>Creator:</label>
<input
type="number"
onChange={(e) => {
setCreatorId(e.target.value);
}}
/>
</div>
<div>
<label>Campaign: </label>
<input
type="number"
onChange={(e) => {
setCampaignId(e.target.value);
}}
/>
</div>
<div>
<label>Description: </label>
<textarea
onChange={(e) => {
setDescription(e.target.value);
}}
/>
</div>
<div>
<label>Image: </label>
<input
type="file"
onChange={(e) => {
console.log("Image:", e);
}}
/>
</div>
<button onClick={submitPost}>Create a Character</button>
</div>
</div>
);
}
export default CreateCharacter;
</code></pre>
<p>And the code of the child component:</p>
<pre><code>import React, { useState, useEffect } from "react";
import Axios from "axios";
import "../css/app.css";
function ClassesDropdown({ props }) {
const [classList, setClassList] = useState([]);
useEffect(() => {
Axios.get("http://localhost:3002/api/classes/get").then((data) => {
console.log(data);
setClassList(data.data);
});
}, []);
const selectHandler = (e) => {
props.onClassFetch(e.target.value);
};
return (
<div>
<select name="classesSelect" onChange={selectHandler}>
{classList.map((val, key) => {
return (
<option key={key} value={val.id}>
{val.class}
</option>
);
})}
</select>
</div>
);
}
export default ClassesDropdown;
</code></pre>
<p>I tried just console logging the selected value from the dropdown menu and It is getting the correct value it's just when I try executing props.onClassFetch I get the error.</p>
| [
{
"answer_id": 74289287,
"author": "Austin",
"author_id": 11482313,
"author_profile": "https://Stackoverflow.com/users/11482313",
"pm_score": 2,
"selected": true,
"text": "ClassesDropdown"
},
{
"answer_id": 74289482,
"author": "Shreyansh Gupta",
"author_id": 18046485,
"author_profile": "https://Stackoverflow.com/users/18046485",
"pm_score": 0,
"selected": false,
"text": "// ..... above code\nfunction ClassesDropdown({ props }) {\n const [classList, setClassList] = useState([]);\n\n useEffect(() => {\n\n//..... below code\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20397409/"
] |
74,289,047 | <p>I am getting error while running a function get_users() in my custom plugin</p>
<p>PHP Fatal error: Uncaught Error: Call to undefined function cache_users() in /Users/priyankgohil/sites/upw-new/wp-includes/class-wp-user-query.php:843</p>
<p>Stack trace:
#0 /Users/priyankgohil/sites/upw-new/wp-includes/class-wp-user-query.php(79): WP_User_Query->query()
#1 /Users/priyankgohil/sites/upw-new/wp-includes/user.php(763): WP_User_Query->__construct(Array)
#2 /Users/priyankgohil/sites/upw-new/wp-content/plugins/my-plugin/Inc/BaseController.php(214): get_users(Array)</p>
<p>is anyone have solution or facing same issue after upgrade to wordpress 6.1</p>
| [
{
"answer_id": 74290622,
"author": "Allison Stec",
"author_id": 4950413,
"author_profile": "https://Stackoverflow.com/users/4950413",
"pm_score": 3,
"selected": false,
"text": "if ( ! function_exists( 'cache_users' ) ) {\n require_once ABSPATH . WPINC . '/pluggable.php';\n}\n"
},
{
"answer_id": 74307521,
"author": "Kevinleary.net",
"author_id": 172870,
"author_profile": "https://Stackoverflow.com/users/172870",
"pm_score": 1,
"selected": false,
"text": "/wp-content/mu-plugins/cache-users.php"
},
{
"answer_id": 74425512,
"author": "David F. Carr",
"author_id": 10959390,
"author_profile": "https://Stackoverflow.com/users/10959390",
"pm_score": 2,
"selected": false,
"text": "add_action('pre_get_users','fix_cache_users_bug');\n\nfunction fix_cache_users_bug($query) {\n if ( ! function_exists( 'cache_users' ) ) {\n require_once ABSPATH . WPINC . '/pluggable.php';\n } \n}\n\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3559070/"
] |
74,289,050 | <p>Is it possible to make an API call to S3 to fetch a file and then pipe the result into an API call to GCP cloud storage(Object storage) to put an object. This will effectively copy the file from S3 to Azure blob.</p>
<p>My goal is to do this completely in-memory without writing anything to disk and also being able to handle files larger than memory.
Is this even possible?</p>
<p>I have tried looking in the python docs for any such option but did not find any. I did come across BytesIO which may be helpful.</p>
| [
{
"answer_id": 74290622,
"author": "Allison Stec",
"author_id": 4950413,
"author_profile": "https://Stackoverflow.com/users/4950413",
"pm_score": 3,
"selected": false,
"text": "if ( ! function_exists( 'cache_users' ) ) {\n require_once ABSPATH . WPINC . '/pluggable.php';\n}\n"
},
{
"answer_id": 74307521,
"author": "Kevinleary.net",
"author_id": 172870,
"author_profile": "https://Stackoverflow.com/users/172870",
"pm_score": 1,
"selected": false,
"text": "/wp-content/mu-plugins/cache-users.php"
},
{
"answer_id": 74425512,
"author": "David F. Carr",
"author_id": 10959390,
"author_profile": "https://Stackoverflow.com/users/10959390",
"pm_score": 2,
"selected": false,
"text": "add_action('pre_get_users','fix_cache_users_bug');\n\nfunction fix_cache_users_bug($query) {\n if ( ! function_exists( 'cache_users' ) ) {\n require_once ABSPATH . WPINC . '/pluggable.php';\n } \n}\n\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20397374/"
] |
74,289,063 | <p>I have this problem that I can´t solve.
I have this function:</p>
<pre><code>def ex2(tex_ori):
let = ("a" or "A")
text_troc = tex_ori.replace(let, "x")
return text_troc
</code></pre>
<p>And the execution for this is:</p>
<pre><code>text_ori = input("Write a sentence: ")
text_1 = ex2(text_ori)
print(text_1)
</code></pre>
<p>But the only letter being replaced is just "a".
What am I doing wrong and what should i do?</p>
<p>I am expecting that all letters "a" and "A" are replaced with the letter "x".
For an example:
Sentence: Hi my name is Alex.
The return should be: Hi my nxme is xlex.</p>
<p>Thanks for the attention and help.</p>
| [
{
"answer_id": 74289132,
"author": "Christian",
"author_id": 9984846,
"author_profile": "https://Stackoverflow.com/users/9984846",
"pm_score": 0,
"selected": false,
"text": "let = (\"a\" or \"A\")"
},
{
"answer_id": 74289141,
"author": "Petr Hofman",
"author_id": 7211501,
"author_profile": "https://Stackoverflow.com/users/7211501",
"pm_score": 2,
"selected": true,
"text": "let = (\"a\" or \"A\")"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20391568/"
] |
74,289,065 | <p>I have such element within my template:</p>
<pre><code>value="{{option.id}}"
</code></pre>
<p>I want to turn the param value into a json object using template literals</p>
<pre><code>value="{{`id: ${option.id}, field: ${otherParam}`}}"
</code></pre>
<p>So the value would looks like <code>{ id: 'bla', field: 'other' }</code>, is it possible to do that?</p>
<p>I also tried {{ JSON.parse(....)} } by creating a component variable <code>JSON = JSON</code> but still having difficulties using template literals.</p>
| [
{
"answer_id": 74289093,
"author": "Fabian Strathaus",
"author_id": 17298437,
"author_profile": "https://Stackoverflow.com/users/17298437",
"pm_score": -1,
"selected": false,
"text": "value"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2926340/"
] |
74,289,080 | <p>I have <em>webpack/encore</em> installed on my symfony project.</p>
<p><em>public/build</em> has been added to <em>gitignore</em> but when I deploy on a PaaS like platform.sh, without this folder, my website design is broken.</p>
<p>Should I remove <em>public/build</em> folder from <em>gitignore</em> ?</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 74290072,
"author": "TylersSN",
"author_id": 1812580,
"author_profile": "https://Stackoverflow.com/users/1812580",
"pm_score": 3,
"selected": true,
"text": ".gitignore"
},
{
"answer_id": 74291541,
"author": "Danilo Carta",
"author_id": 13167588,
"author_profile": "https://Stackoverflow.com/users/13167588",
"pm_score": 1,
"selected": false,
"text": "//.platform.app.yaml\nname: node-app\ntype: nodejs:16\ndisk: 512\n\ndependencies:\n nodejs:\n yarn: \"*\"\n\nhooks:\n build: |\n npm install --force\n npm run build \n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2572177/"
] |
74,289,096 | <p>I have followed the Dapr docs and am trying to set up an azure storage queue input binding for a dotnet 6 webapi project. The webapi project works as expected when run locally but when run through dapr fails to initialze and exist with the following error. Because Dapr issues an options method ond the binding endpoint I have includeded a options endpoint of my own. I have also added cors support (commented ot now). But nothing seems to help. Has anyone encountered this before. All help welcomed.</p>
<pre><code>"could not invoke OPTIONS method on input binding subscription endpoint \"Process\": %!w(*errors.errorString=&{the server closed connection before returning the first response byte. Make sure the server returns 'Connection: close' response header before closing the connection})"
</code></pre>
<p>.\Component\binding.yaml (redacted connection details)</p>
<pre><code>apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: Process
namespace: default
spec:
type: bindings.azure.storagequeues
version: v1
metadata:
- name: accountName
value: "******"
- name: accountKey
value: "******"
- name: queueName
value: "queue-name"
- name: ttlInSeconds
value: "60"
- name: decodeBase64
value: "true"
</code></pre>
<p>.\program.cs</p>
<pre><code> var builder = WebApplication.CreateBuilder(args);
//var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
//builder.Services.AddCors(options =>
//{
// options.AddPolicy(name: MyAllowSpecificOrigins,
// policy =>
// {
// policy.WithOrigins("http://localhost", "*");
// });
//});
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
//app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.MapControllers();
app.Run();
</code></pre>
<p>.\Controller\TestController.cs</p>
<pre><code>using Microsoft.AspNetCore.Mvc;
[ApiController]
public class TestController : ControllerBase
{
private readonly ILogger<TestController> _logger;
public TestController(ILogger<TestController> logger)
{
_logger = logger;
}
[HttpPost("Process")]
public ActionResult<string> Process([FromBody] Message message)
{
try
{
var messageJson = System.Text.Json.JsonSerializer.Serialize(message);
_logger.LogInformation($"SUCCESS: MessageArrived: {messageJson}");
return Ok(message.Id);
}
catch (Exception ex)
{
_logger.LogError(ex, "ERROR: ");
return BadRequest(ex.Message);
}
}
[HttpOptions("Process")]
public ActionResult<string> ProcessOptions([FromBody] object message)
{
return Ok();
}
}
public class Message
{
public string Id { get; set; }
public string Name { get; set; }
}
</code></pre>
<p>Startup command</p>
<pre><code>dapr run --log-level debug --app-id dnx --app-port 7221 --dapr-http-port 3500 dotnet run test.csproj
</code></pre>
| [
{
"answer_id": 74290072,
"author": "TylersSN",
"author_id": 1812580,
"author_profile": "https://Stackoverflow.com/users/1812580",
"pm_score": 3,
"selected": true,
"text": ".gitignore"
},
{
"answer_id": 74291541,
"author": "Danilo Carta",
"author_id": 13167588,
"author_profile": "https://Stackoverflow.com/users/13167588",
"pm_score": 1,
"selected": false,
"text": "//.platform.app.yaml\nname: node-app\ntype: nodejs:16\ndisk: 512\n\ndependencies:\n nodejs:\n yarn: \"*\"\n\nhooks:\n build: |\n npm install --force\n npm run build \n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/991276/"
] |
74,289,099 | <p>In order to track our memory usage and display some runtime statistics to the user (in a performant way) I'm overriding global new/delete (with a #define in a header - adding that header on top of every source file where we need to allocate/deallocate memory is going to ensure we can track all allocations going on).</p>
<p>I have two questions at this point since it's a multi-platform C++ codebase:</p>
<ul>
<li>this is old code and some places still use <code>malloc</code> next to <code>new</code>. I think I also need to override global malloc/free/calloc/realloc, is that correct?</li>
<li>STL containers: we use them a lot (e.g. <code>std::vector</code>). If I include my re-#defining header at the top of every source file, do I still need to pass a custom allocator like <code>std::vector<int, my_allocator<int>></code>? Or are the globally re-defined <code>new/delete</code> enough? I think I still need the custom allocator but I'm not sure.</li>
</ul>
| [
{
"answer_id": 74289601,
"author": "Alex Vergara",
"author_id": 14075508,
"author_profile": "https://Stackoverflow.com/users/14075508",
"pm_score": 2,
"selected": false,
"text": "new"
},
{
"answer_id": 74289864,
"author": "A M",
"author_id": 9666018,
"author_profile": "https://Stackoverflow.com/users/9666018",
"pm_score": 1,
"selected": false,
"text": "std::vector"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834459/"
] |
74,289,104 | <p>with the following html:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Company Home Page with Flexbox</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<header>
<div class="about">
<h4><span>A work selection by </span><a class="sobre" href="">sfgndfyj</a></h4>
</div>
</header>
<main>
<article class="uno">
<h1>
<span id="ppal" class="title_part" style="display: block; font-size: 12vw";>stills & moving image</span>
<span id="sec" class="title_part" style="display: block; font-size: 11vw";>TECHNICAL PRODUCTION</span>
</h1>
</article>
<article class="dos">
</article>
</main>
</body>
</html>
</code></pre>
<p>and the following css:</p>
<pre><code>html {
box-sizing: border-box;
font-size: 16px;
}
body {
max-width: 1500px;
margin: 0 auto;
}
/* -------------------------------------- fonts */
@font-face {
font-family: 'Alternate Gothic';
src: url('Alternate Gothic W01 No 3.ttf') format('truetype');
}
@font-face {
font-family: 'Times Roman';
src: url('OPTITimes-Roman.otf') format('opentype');
}
.sobre {
color: black;
}
.sobre:hover {
transition: background-color .1s ease-out,color .1s ease-out;
position: relative;
overflow: hidden;
text-decoration: underline;
background-color: black;
color: white;
}
h1 {
font-family: 'Alternate Gothic';
text-align: center;
display: flex;
flex-direction: column;
justify-content: center;
font-size: clamp(.5rem, 10vw, 1rem);
}
h4 {
font-weight: lighter;
letter-spacing: .1rem;
}
#ppal {
word-spacing: 90%;
}
.title_part {
display: inline;
position: relative;
}
/* --------------------------------- spacing */
.about {
text-align: center;
margin: 0 5vw;
}
header {
border-width: 0 0 1px 0;
border-style: solid;
border-color: #000;
margin: 0 2.5rem;
}
.dos {
border-width: 1px 0 0 0;
border-style: solid;
border-color: #000;
margin: 0 2.5rem;
}
</code></pre>
<p>I have tried for hours to find out why the h1 goes beyond the limits of its parent.</p>
<p>I am trying to keep h1 in two lines of (responsive) text. When you grow the window it goes above the 1600px limit placed on the body.
No matter if I try max-width, overflow, etc that it keeps getting out the box.</p>
<p>Can anybody tell me what am I doing wrong? Im trying to figure out how to stop the h1 to go beyond the above limit.</p>
<p>Best</p>
| [
{
"answer_id": 74289159,
"author": "Nitheesh",
"author_id": 6099327,
"author_profile": "https://Stackoverflow.com/users/6099327",
"pm_score": 1,
"selected": false,
"text": " white-space: nowrap;"
},
{
"answer_id": 74289163,
"author": "Helmi",
"author_id": 19195226,
"author_profile": "https://Stackoverflow.com/users/19195226",
"pm_score": 0,
"selected": false,
"text": "white-space: wrap;\n"
},
{
"answer_id": 74291279,
"author": "Shiven Nayee",
"author_id": 19775901,
"author_profile": "https://Stackoverflow.com/users/19775901",
"pm_score": 0,
"selected": false,
"text": ".uno {\n border-width: 0 0 1px 0;\n border-style: solid;\n border-color: #000;\n max-width: 1600px;\n position: relative;\n}\n\n.title_part {\n margin: 0 auto;\n}\n\n<div class=\"fulltitle\">\n <h1 class=\"title_part\" style=\"display: block; font-size: 5vw;\";>stills & moving image</h1>\n <h2 class=\"title_part\" style=\"display: block; font-size: 3vw; text-align: center; \">TECHNICAL PRODUCTION</h2>\n</div>\n"
},
{
"answer_id": 74302261,
"author": "petrus",
"author_id": 15893917,
"author_profile": "https://Stackoverflow.com/users/15893917",
"pm_score": 1,
"selected": true,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Company Home Page with Flexbox</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">\n</head>\n\n<body>\n\n <header>\n <div class=\"about\">\n <h4><span>A work selection by </span><a class=\"sobre\" href=\"\">sfgndfyj</a></h4>\n </div>\n </header>\n\n <main>\n\n <article class=\"uno\">\n <h1>\n <span id=\"ppal\" class=\"title_part\" style=\"display: block;\";>stills & moving image</span>\n\n <span id=\"sec\" class=\"title_part\" style=\"display: block;\";>TECHNICAL PRODUCTION</span>\n </h1>\n </article>\n\n <article class=\"dos\"> \n </article>\n\n </main>\n\n</body>\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15893917/"
] |
74,289,119 | <p>I have a spreadsheet that has the following columns:
Tactic, Impressions, Engagement, Clicks and Forms. The tactic column contains a dropdown menu on each cell that has x amount values, for simplicity lets say it has 2, Value1= "A" and value2= "B".
if cell A1(where the Tactic column is) contains the value "A" then I want to highlight in say "Yellow" colour the adjacent cells of the Impressions and Engagement columns and if the value of cell A1 is "B" I want to highlight the adjacent cell of teh Forms colum in yellow but not any other column.
Basically, I need to be able to select a Tactic and the columns that require data to be entered based on that tactic to be highlighted to the user. And this needs to be applied to x number of rows in the spreadsheet?</p>
<p>I can accomplish this partially by using conditional formatting and using a custom formula. please see picture below but the problem is that the rule only applies to that particular range, in this case E2-F2. I need excel to "Know" that when the value of the Tactic column in any row changes or it is filled up for the adjacent cells to be highlighted based on the formula.
Is there a way to make this conditional formatting dynamically obtain the row index where the Tactic selection was made and apply the cell colour to columns E and F but only on the row where the selection was made without having to hardcode each row with this conditional formatting?</p>
<p><a href="https://i.stack.imgur.com/f6jSe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f6jSe.png" alt="enter image description here" /></a></p>
<p>Thanks for your help!</p>
| [
{
"answer_id": 74289323,
"author": "Toby_Stoe",
"author_id": 19735003,
"author_profile": "https://Stackoverflow.com/users/19735003",
"pm_score": 2,
"selected": false,
"text": "=$D2=\"A\""
},
{
"answer_id": 74291123,
"author": "Max R",
"author_id": 19662289,
"author_profile": "https://Stackoverflow.com/users/19662289",
"pm_score": 0,
"selected": false,
"text": "=$D2=\"A\""
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5810060/"
] |
74,289,152 | <p>I have an integer with me, I need to convert into MAC address. I check for <code>hwaddr</code> in Ansible, did not worked for me. Please help me out.</p>
<p>I tried in built module like <code>ipmath</code> and <code>hwaddr</code>. Nothing came handy.</p>
| [
{
"answer_id": 74294702,
"author": "Kevin C",
"author_id": 4834431,
"author_profile": "https://Stackoverflow.com/users/4834431",
"pm_score": 2,
"selected": false,
"text": "netaddr"
},
{
"answer_id": 74299925,
"author": "U880D",
"author_id": 6771046,
"author_profile": "https://Stackoverflow.com/users/6771046",
"pm_score": 2,
"selected": false,
"text": "netaddr"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18415723/"
] |
74,289,191 | <p>We found interesting problem. Our environment is configured by using ansible, which in turn installs gems.</p>
<p>Some of the gems, we want version that is newer than something. For example, aws-sdk-core version >= 3.104.</p>
<p>This ansible tasks runs:</p>
<pre><code>gem install -v '>= 3.104' aws-sdk-core
</code></pre>
<p>Then, we have a cronjob that every 5 minutes (but across couple of thousand servers) runs a script that does 'require aws-sdk-core'.</p>
<p>And, every so often, it breaks with:</p>
<pre><code>/var/lib/gems/2.5.0/gems/aws-sdk-core-3.166.0/lib/seahorse.rb:3:in `require_relative': cannot load such file -- /var/lib/gems/2.5.0/gems/aws-sdk-core-3.166.0/lib/seahorse/util (LoadError)
...
</code></pre>
<p>I made trivial script that shows the problem on another, much smaller gem:</p>
<pre><code>#!/usr/bin/env ruby
# frozen_string_literal: true
require 'progressbar'
puts 1
</code></pre>
<p>If you'll save it as z.rb, and then run in shell: <code>while true; do ./z.rb; done</code>, and then in another shell: <code>while true; do gem install -v '>= 1.0.0' progressbar; done</code>, eventually (after a minute or two) you will get, in the shell that runs z.rb:</p>
<pre><code>1
1
<internal:/usr/lib/ruby/vendor_ruby/rubygems/core_ext/kernel_require.rb>:85:in `require': cannot load such file -- progressbar (LoadError)
from <internal:/usr/lib/ruby/vendor_ruby/rubygems/core_ext/kernel_require.rb>:85:in `require'
from ./z.rb:3:in `<main>'
1
1
1
</code></pre>
<p>Is there any way to avoid this problem, other than begin/rescue and retry after 1 second sleep (which I can do, but it's OH SO UGLY)?</p>
<p>The problem, for us, is that we need to install with at least some specific version (if we'd provide version = SOMETHING, ansible avoids calling gem install altogether, but we want new releases installed too), and while the window for race condition is small, with many thousand servers, and cronjob that runs every 5 minutes, (ansible runs every 4 hours), we get ~ dozen mails per day with cronjob fails.</p>
| [
{
"answer_id": 74294702,
"author": "Kevin C",
"author_id": 4834431,
"author_profile": "https://Stackoverflow.com/users/4834431",
"pm_score": 2,
"selected": false,
"text": "netaddr"
},
{
"answer_id": 74299925,
"author": "U880D",
"author_id": 6771046,
"author_profile": "https://Stackoverflow.com/users/6771046",
"pm_score": 2,
"selected": false,
"text": "netaddr"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9210009/"
] |
74,289,239 | <p>I wanted to show text below these icons in my website. Can someone guide me how to do it please</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-html lang-html prettyprint-override"><code><div class="bottom-bar div-only-mobile" style="position: fixed; bottom: 0; width:100%">
<a href="Dashboard">
<ion-icon name="home-outline" class="icon" onclick="change(this)">
</ion-icon>Dashboard</a>
<a href="Profile">
<ion-icon name="person-outline" class="icon" onclick="change(this)">
</ion-icon>Profile</a>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 74294702,
"author": "Kevin C",
"author_id": 4834431,
"author_profile": "https://Stackoverflow.com/users/4834431",
"pm_score": 2,
"selected": false,
"text": "netaddr"
},
{
"answer_id": 74299925,
"author": "U880D",
"author_id": 6771046,
"author_profile": "https://Stackoverflow.com/users/6771046",
"pm_score": 2,
"selected": false,
"text": "netaddr"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11571708/"
] |
74,289,318 | <pre><code>import io.vertx.core.Vertx
import io.vertx.core.http.HttpMethod
import io.vertx.ext.web.Router
import io.vertx.ext.web.handler.CorsHandler
class RestfulServer(
vertx: Vertx,
private val ipAddress: String,
private val port: Int
) {
private val httpServer = vertx.createHttpServer()
private val router: Router = Router.router(vertx)
init {
corsHandling()
createRouter()
}
private fun corsHandling(): Route =
router.route().handler {
CorsHandler
.create("*")
.allowedMethods(mutableSetOf(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS))
}
private fun createRouter() =
router.get("/").blockingHandler { ctx ->
val response = ctx.response()
response.putHeader("content-type", "application/json")
response.end("""{}""")
}
fun listen() {
httpServer.requestHandler(router).listen(port, ipAddress)
}
fun close() {
httpServer.close()
}
}
</code></pre>
<p>When I run the above code, the rest API call hangs in the browser, But if I comment out the function <code>corsHandling()</code>, everything works fine.</p>
<p>I found that it's not a problem with <code>CorsHandler</code> but with how I call that function in kotlin.</p>
<p><strong>Working function:</strong></p>
<pre><code>private fun corsHandling(): Route =
router.route().handler( // here I use ()
CorsHandler
.create("*")
.allowedMethods(mutableSetOf(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS))
)
</code></pre>
<p><strong>This one hangs:</strong></p>
<pre><code>private fun corsHandling(): Route =
router.route().handler{ // here I use {}
CorsHandler
.create("*")
.allowedMethods(mutableSetOf(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS))
}
</code></pre>
<p>As you can see the only difference is {} instead of () in <code>router.route().handler</code> call. In kotlin, you can omit the function call if the lambda is your last argument.</p>
<p>Might be this question more to Kotlin instead of Vert.x</p>
<p>It's the function definition of handler <a href="https://vertx.io/docs/apidocs/io/vertx/ext/web/Route.html#handler-io.vertx.core.Handler-" rel="nofollow noreferrer">https://vertx.io/docs/apidocs/io/vertx/ext/web/Route.html#handler-io.vertx.core.Handler-</a></p>
<hr />
<p>The actual problem is I'm calling handler function like handler({{lambda}})</p>
<p>@ivo has the answer already but just clarify with a simple example,</p>
<pre><code>fun takesSingleLambda(func: ()-> Unit) {
func()
}
fun main() {
println("1")
takesSingleLambda(
returnsLambda()
)
println("2")
takesSingleLambda{
returnsLambda()
}
println("3, which does exactly the same as 2")
takesSingleLambda({
returnsLambda()
})
}
fun returnsLambda() = { //this is similar to CorsHandler.create("*").allowedMethods(mutableSetOf(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS))
println("executing")
}
</code></pre>
| [
{
"answer_id": 74289400,
"author": "Ivo",
"author_id": 1514861,
"author_profile": "https://Stackoverflow.com/users/1514861",
"pm_score": 3,
"selected": true,
"text": "functionName{\n\n}\n"
},
{
"answer_id": 74290873,
"author": "TheLibrarian",
"author_id": 3434763,
"author_profile": "https://Stackoverflow.com/users/3434763",
"pm_score": 0,
"selected": false,
"text": "interface OnClickListener {\n void onClick(View view)\n}\n\nOnClickListener listener = new OnClickListener() {\n override void onClick(View view) {\n //on click stuff\n }\n}\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10334333/"
] |
74,289,319 | <p>I am writing an application in C# using EFCore.</p>
<p>I have the Entities <code>Customer</code>, <code>Order</code>, <code>OrderItem</code> and <code>Product</code>.
<code>OrderItem</code> is a associative table connecting <code>Order</code> with <code>Product</code> so an order can have multiple products.</p>
<p><code>Order</code> contains a reference to customer.</p>
<p><code>OrderItem</code> contains a reference to <code>Product</code> and <code>Order</code>.</p>
<p>By reference I mean a foreign-key constraint.</p>
<p>The problem is that when I try to execute the following method, I get the following error:</p>
<pre class="lang-cs prettyprint-override"><code>public static List<SalesStatistic> GetInvoices()
{
using ApplicationDbContext context = new ApplicationDbContext();
return context.Customers.Select(c => new SalesStatistic()
{
FirstName = c.FirstName,
LastName = c.LastName,
TotalPrice = context.Orders.Where(o => o.CustomerId == c.Id).Sum(oo => GetSalesPerOrder(oo.Nr))
}).ToList();
}
</code></pre>
<pre><code>System.InvalidOperationException: The LINQ expression 'DbSet<Order>()
.Where(o => o.CustomerId == EntityShaperExpression:
Core.Entities.Customer
ValueBufferExpression:
ProjectionBindingExpression: EmptyProjectionMember
IsNullable: False
.Id)
.Sum(o => Repository.GetSalesPerOrder(o.Nr))' could not be translated. Additional information: Translation of method 'Persistence.Repository.GetSalesPerOrder' failed. If this method can be mapped to your custom function, see https://go.microsoft.com/fwlink/?linkid=2132413 for more information. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
</code></pre>
<p>The method <code>GetSalesPerOrder</code> works as I have Unit-Tests set up for these methods.</p>
<pre class="lang-cs prettyprint-override"><code>public static double GetSalesPerOrder(string orderNr)
{
using ApplicationDbContext context = new ApplicationDbContext();
return context.Orders.Include(o => o.OrderItems).Where(o => o.Nr == orderNr).First().OrderItems!.Sum(oi => context.OrderItems.Include(o => o.Product).Where(oii => oii.Id == oi.Id).First().Product.Price * oi.Amount);
}
</code></pre>
<p>I tried to modify <code>GetInvoices</code> so it doesn't call <code>GetSalesPerOrder</code> and then no exception was thrown.</p>
<p>I want to know what I am doing wrong in the above code.</p>
| [
{
"answer_id": 74289433,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 2,
"selected": false,
"text": "GetSalesPerOrder()"
},
{
"answer_id": 74292784,
"author": "Svyatoslav Danyliv",
"author_id": 10646316,
"author_profile": "https://Stackoverflow.com/users/10646316",
"pm_score": 1,
"selected": false,
"text": "var query = \n from c in context.Customers\n join o in context.Orders on c.Id equals o.CustomerId\n from oi in o.OrderItems\n group new { oi.Amount, oi.Product.Price } by new { c.Id, c.Firstname, c.LastName } into g\n new SalesStatistic\n {\n FirstName = g.Key.FirstName,\n LastName = g.Key.LastName,\n TotalPrice = g.Sum(x => x.Price * x.Amount)\n };\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13145959/"
] |
74,289,350 | <p><strong>Hi guys,</strong></p>
<p>I am basically new to coding in general so bare with me.</p>
<p><strong>I am trying to retrieve the table headers for this table:</strong>
<a href="https://www.transfermarkt.co.uk/manchester-united-fc/leistungsdaten/verein/985/reldata/%262022/plus/1" rel="nofollow noreferrer">https://www.transfermarkt.co.uk/manchester-united-fc/leistungsdaten/verein/985/reldata/%262022/plus/1</a></p>
<p><a href="https://i.stack.imgur.com/rv6JT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rv6JT.png" alt="enter image description here" /></a></p>
<p>First i tried with pandas but i could not get my data so i learned about beautifull soup and tried my luck with it.</p>
<p>The problem is that some headers are text and i could get the info pretty easily using this:</p>
<pre><code>from bs4 import BeautifulSoup as bs
import requests
url = 'https://www.transfermarkt.co.uk/manchester-united-fc/leistungsdaten/verein/985/reldata/%262022/plus/1'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
response = requests.get(url, headers=headers)
response.content
soup = bs(response.content, 'html.parser')
soup.prettify().splitlines()
tabela_equipa = soup.find('table', {'class': 'items'} )
headers_tabela = [th.text.encode("utf-8") for th in tabela_equipa.select("tr th")]
print(headers_tabela)
</code></pre>
<p>Output:
[b'#', b'player', b'Age', b'Nat.', b'In squad', b'\xc2\xa0', b'\xc2\xa0', b'\xc2\xa0', b'\xc2\xa0', b'\xc2\xa0', b'\xc2\xa0', b'\xc2\xa0', b'\xc2\xa0', b'PPG', b'\xc2\xa0']</p>
<p>The thing is that most of those headers are icons and the info i need is actually in the span title, and there is where my problem resides, because i am not being able to find anywhere how to get all that info in order to build my table headers so then i can scrape the rest of the table.</p>
<p><a href="https://i.stack.imgur.com/ZCcfM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZCcfM.png" alt="enter image description here" /></a></p>
<p>Anyone knows a way of doing it?
been trying for 4 days without success before posting here.</p>
<p>Then i tried to get all the spans using this code:</p>
<pre><code>thead = soup.thead
Theaders = thead.find_all('span')
print(Theaders)
</code></pre>
<p>Output:</p>
<pre><code>[<span class="icons_sprite icon-einsaetze-table-header sort-link-icon" title="Appearances"> </span>, <span class="icons_sprite icon-tor-table-header sort-link-icon" title="Goals"> </span>, <span class="icons_sprite icon-vorlage-table-header sort-link-icon" title="Assists"> </span>, <span class="icons_sprite icon-gelbekarte-table-header sort-link-icon" title="Yellow cards"> </span>, <span class="icons_sprite icon-gelbrotekarte-table-header sort-link-icon" title="Second yellow cards"> </span>, <span class="icons_sprite icon-rotekarte-table-header sort-link-icon" title="Red cards"> </span>, <span class="icons_sprite icon-einwechslungen-table-header sort-link-icon" title="Substitutions on"> </span>, <span class="icons_sprite icon-auswechslungen-table-header sort-link-icon" title="Substitutions off"> </span>, <span class="icons_sprite icon-minuten-table-header sort-link-icon" title="Minutes played"> </span>]
</code></pre>
<p>Getting close i thought as i could see all the info i needed was there.
But then i hit the wall, i can get one span title but not all in a list:</p>
<p>thead = soup.thead
Theaders = thead.find('span')['title']
print(Theaders)</p>
<p>Output:
Appearances</p>
<pre><code>thead = soup.thead
Theaders = thead.find_all('span')['title']
print(Theaders)
</code></pre>
<p>Output:</p>
<pre><code>---> 23 Theaders = thead.find_all('span')['title']
24 print(Theaders)
TypeError: list indices must be integers or slices, not str
</code></pre>
<p>and even then i will run into the problem of it not being in the same order as it was on the original table.</p>
<p>Maybe i am just being dumb but any help would be much aprecciated</p>
| [
{
"answer_id": 74289433,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 2,
"selected": false,
"text": "GetSalesPerOrder()"
},
{
"answer_id": 74292784,
"author": "Svyatoslav Danyliv",
"author_id": 10646316,
"author_profile": "https://Stackoverflow.com/users/10646316",
"pm_score": 1,
"selected": false,
"text": "var query = \n from c in context.Customers\n join o in context.Orders on c.Id equals o.CustomerId\n from oi in o.OrderItems\n group new { oi.Amount, oi.Product.Price } by new { c.Id, c.Firstname, c.LastName } into g\n new SalesStatistic\n {\n FirstName = g.Key.FirstName,\n LastName = g.Key.LastName,\n TotalPrice = g.Sum(x => x.Price * x.Amount)\n };\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20397340/"
] |
74,289,362 | <p>Im new in react, i try the reference mode or state mode, but the page render a lot of times, or when i click in my checkbox, dont change the checked option.
Im using tailwind darkmode</p>
<p>when i load the page, there are a conditional that check if darkmode is activated or not,
so if loadind the page darkmode is enabled, the checkbox must be true and if not must be false, simply</p>
<pre><code>import React, {useEffect, useState} from "react";
function Header() {
const [darkMode, setDarkMode] = useState(false);
useEffect(() =>{
if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
document.documentElement.classList.add('dark')
localStorage.theme = 'dark'
setDarkMode(!darkMode)
} else {
document.documentElement.classList.remove('dark')
localStorage.theme = 'light';
console.log('modo luz activado')
}
},[])
const changeTheme = () => {
if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
document.documentElement.classList.remove("dark");
localStorage.theme = "light";
} else {
document.documentElement.classList.add("dark");
localStorage.theme = "dark";
}
};
return (
<header>
<nav>
<input checked={darkMode} type="checkbox" onChange={changeTheme} />
</nav>
</header>
);
}
export default Header;
</code></pre>
| [
{
"answer_id": 74289752,
"author": "Shreyansh Gupta",
"author_id": 18046485,
"author_profile": "https://Stackoverflow.com/users/18046485",
"pm_score": 1,
"selected": true,
"text": "change theme"
},
{
"answer_id": 74289969,
"author": "Rubek Joshi",
"author_id": 10753343,
"author_profile": "https://Stackoverflow.com/users/10753343",
"pm_score": 1,
"selected": false,
"text": "React.useContext()"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15407192/"
] |
74,289,367 | <pre><code>javascript:function gcloak() { var link = document.querySelector("link[rel*='icon']") || document.createElement('link');link.type = 'image/x-icon';link.rel = 'shortcut icon';link.href = 'https://ssl.gstatic.com/docs/doclist/images/infinite_arrow_favicon_5.ico';document.title = 'My Drive - Google Drive';console.log(document.title);document.getElementsByTagName('head')[0].appendChild(link) };gcloak();setInterval(gcloak, 1000);
</code></pre>
<p>I am trying to add this code to a hyperlink so i will be able to drag it to my bookmarks bar. The issue is that it won't include the double quotation marks at</p>
<pre><code>("link[rel*='icon']")
</code></pre>
<p>and just ends at</p>
<pre><code>javascript:function gcloak() { var link = document.querySelector(
</code></pre>
<p>I have tried changing the double quotes to single quotes but that makes the javascript not work.</p>
| [
{
"answer_id": 74289509,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 1,
"selected": false,
"text": """
},
{
"answer_id": 74289542,
"author": "Shreyansh Gupta",
"author_id": 18046485,
"author_profile": "https://Stackoverflow.com/users/18046485",
"pm_score": 2,
"selected": false,
"text": "\n`link[rel*='icon']`\n\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20393634/"
] |
74,289,401 | <p>I have two tables in my database that looks like this</p>
<p>learner_lessons</p>
<pre><code>learnerlessonid learnerid lessonid
1 24 42
</code></pre>
<p>learner_lesson_logs</p>
<pre><code>lessonlogid learnerlessonid progress maxprogress interaction createdAt
1 1 0 15 Start 2022-11-02 07:51:30
2 1 4 15 Pause 2022-11-02 07:51:34
3 1 4 15 Play 2022-11-02 07:52:20
4 1 14 15 Run 2022-11-02 07:52:30
5 1 15 15 Stop 2022-11-02 07:52:31
</code></pre>
<p>Basically, when a user clicks on a video it starts playing and the interaction is recorded as 'Start' and a timestamp is created accordingly. Now when a user pauses the video another interaction 'Pause' is created and the timestamp is recorded. The user might come back later and resume the video thus creating a 'Play' interaction. After every 10 seconds of the video if it isn't paused another interaction 'Run' is logged in the database. Finally when the video ends 'Stop' interaction is created.</p>
<p>What I am aiming to achieve is the difference in timestamps when a video is 'Started' or 'Played' till the video is 'Paused' or 'Stopped'. The interactions could be 'Start', and 'Stop' as well.</p>
<p>This is the query I am working on now</p>
<pre><code>select ll.learnerId ,lll.createdAt,
(case when interactionType = 'Start' or interactionType = 'Play'
then DATEDIFF(SECOND,
lll.createdAt,
(case when interactionType = 'Stop' or interactionType = 'Pause' then lll.createdAt end) over (order by lll.createdAt desc)
)
end) as diff_minutes
from learner_lesson_log lll join learner_lessons ll on ll.learnerLessonId = lll.learnerLessonId
order by lll.createdAt
</code></pre>
<p>But is throwing me the error</p>
<blockquote>
<p>SQL Error [1064] [42000]: You have an error in your SQL syntax; check
the manual that corresponds to your MySQL server version for the right
syntax to use near '(order by createdAt desc)
)
end) as diff_minut' at line 5</p>
<p>Error position: line: 4</p>
</blockquote>
<p>I want the end result to look like this for each learner</p>
<pre><code>learnerid Length of interaction start_timestamp
24 4 2022-11-02 07:51:30
24 11 2022-11-02 07:52:20
</code></pre>
| [
{
"answer_id": 74290488,
"author": "DannySlor",
"author_id": 19174570,
"author_profile": "https://Stackoverflow.com/users/19174570",
"pm_score": 0,
"selected": false,
"text": "select learnerid\n ,max(createdAt)-min(createdAt) as Length_of_interaction\n ,min(createdAt) as start_timestamp\nfrom\n(\nselect *\n ,count(case when interaction in('Pause', 'Stop') then 1 end) over(partition by learnerid order by createdAt desc) as grp\nfrom learner_lessons l1 join learner_lesson_logs l2 using(learnerlessonid)\n) l3\ngroup by learnerid, grp\norder by start_timestamp\n"
},
{
"answer_id": 74290795,
"author": "GRIV",
"author_id": 3092847,
"author_profile": "https://Stackoverflow.com/users/3092847",
"pm_score": 2,
"selected": true,
"text": "createdAt"
},
{
"answer_id": 74292004,
"author": "DannySlor",
"author_id": 19174570,
"author_profile": "https://Stackoverflow.com/users/19174570",
"pm_score": 0,
"selected": false,
"text": "select learnerid\n ,max(flg)-min(flg) as Length_of_interaction\n ,min(flg) as start_timestamp \nfrom\n (\n select learnerlessonid\n ,case when interaction not in('Run') then createdAt end as flg\n from learner_lesson_logs l2 \n where case when interaction not in('Run') then createdAt end is not null\n order by createdAt\n ) t \n join learner_lessons using(learnerlessonid) join (select @rn := 0) i\ngroup by learnerid, ceiling((@rn := @rn + 1)/2) \norder by start_timestamp\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4502950/"
] |
74,289,420 | <p>I've followed the instructions in <a href="https://tsmx.net/docker-local-mongodb/" rel="nofollow noreferrer">https://tsmx.net/docker-local-mongodb/</a> but I still get the following error:</p>
<p>**panic: unable to connect to MongoDB (local): no reachable servers
**</p>
<p>I even tried the following but still get the same error:</p>
<pre><code>_ = pflag.String("mongodb-addr", "127.0.0.1:27017", "MongoDB connection address")
</code></pre>
<p>My connection code is as follows:</p>
<pre><code>dbAddr := d.cfg.GetString("mongodb-addr")
session, err := mgo.Dial(dbAddr)
</code></pre>
<p>And my docker run command is as follows:</p>
<pre><code>docker run image_name
</code></pre>
<p>I'm using macOS Monterey. Any help would be greatly appreciated. Thanks.</p>
| [
{
"answer_id": 74290488,
"author": "DannySlor",
"author_id": 19174570,
"author_profile": "https://Stackoverflow.com/users/19174570",
"pm_score": 0,
"selected": false,
"text": "select learnerid\n ,max(createdAt)-min(createdAt) as Length_of_interaction\n ,min(createdAt) as start_timestamp\nfrom\n(\nselect *\n ,count(case when interaction in('Pause', 'Stop') then 1 end) over(partition by learnerid order by createdAt desc) as grp\nfrom learner_lessons l1 join learner_lesson_logs l2 using(learnerlessonid)\n) l3\ngroup by learnerid, grp\norder by start_timestamp\n"
},
{
"answer_id": 74290795,
"author": "GRIV",
"author_id": 3092847,
"author_profile": "https://Stackoverflow.com/users/3092847",
"pm_score": 2,
"selected": true,
"text": "createdAt"
},
{
"answer_id": 74292004,
"author": "DannySlor",
"author_id": 19174570,
"author_profile": "https://Stackoverflow.com/users/19174570",
"pm_score": 0,
"selected": false,
"text": "select learnerid\n ,max(flg)-min(flg) as Length_of_interaction\n ,min(flg) as start_timestamp \nfrom\n (\n select learnerlessonid\n ,case when interaction not in('Run') then createdAt end as flg\n from learner_lesson_logs l2 \n where case when interaction not in('Run') then createdAt end is not null\n order by createdAt\n ) t \n join learner_lessons using(learnerlessonid) join (select @rn := 0) i\ngroup by learnerid, ceiling((@rn := @rn + 1)/2) \norder by start_timestamp\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3825948/"
] |
74,289,437 | <p>I am building Django app where I want to run Django and playwright images in 1 container in Docker Desktop (locally).</p>
<p>Below you can see my <code>docker-compose.yml</code> file:</p>
<pre><code>version: '3.8'
services:
web:
build: ./docker_playwright_test
command: python manage.py runserver 0.0.0.0:8000
volumes:
- ./docker_playwright_test/:/usr/src/docker_playwright_test/
ports:
- 8000:8000
</code></pre>
<p>Django is running fine on my localhost but I am not sure how to add <a href="https://playwright.dev/docs/docker" rel="nofollow noreferrer">Playwright image</a> to docker-compose file?</p>
| [
{
"answer_id": 74289888,
"author": "Eenyi",
"author_id": 20397830,
"author_profile": "https://Stackoverflow.com/users/20397830",
"pm_score": 3,
"selected": true,
"text": "C:\\Users\\[User Name]\\.docker\\config.json"
},
{
"answer_id": 74290177,
"author": "Alez",
"author_id": 5317332,
"author_profile": "https://Stackoverflow.com/users/5317332",
"pm_score": 2,
"selected": false,
"text": "web:\n build:\n context: .\n dockerfile: Dockerfile\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8318946/"
] |
74,289,477 | <p>Normally my input has an audio. When I convert my input with following code, the output is muted.</p>
<pre><code>ffmpeg.input("input.webm").filter("scale", force_original_aspect_ratio="decrease", force_divisible_by=2).output(("out.mp4"), vcodec="libx264", r=60, preset='fast').run()
</code></pre>
<p><code>.filter()</code> function causes it and I don't know how to fix it. I want to use filter, but I want to keep the audio same also.</p>
<p>Thank you for your help.</p>
| [
{
"answer_id": 74289888,
"author": "Eenyi",
"author_id": 20397830,
"author_profile": "https://Stackoverflow.com/users/20397830",
"pm_score": 3,
"selected": true,
"text": "C:\\Users\\[User Name]\\.docker\\config.json"
},
{
"answer_id": 74290177,
"author": "Alez",
"author_id": 5317332,
"author_profile": "https://Stackoverflow.com/users/5317332",
"pm_score": 2,
"selected": false,
"text": "web:\n build:\n context: .\n dockerfile: Dockerfile\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19398267/"
] |
74,289,523 | <p>I'm trying to create function that can pull information from an API library and I am having a hard time figuring out how to pass a variable selection into the function without being read as a value.</p>
<p>code example:</p>
<pre><code>def get_list(api, val = None):
response =[]
list = api
for i in list:
response.append(f'i.{val}')
return (response)
devices = get_list(api.devices.all(), 'name')
print(devices )
</code></pre>
<p>Give me a long list of "i.name"</p>
<p>I need to resolve <strong>i.name</strong> as a variable selection and not as an actual value</p>
<p>I have tired:</p>
<pre><code>response.append(vars()[f'i.{val}']) # locals(), globals()
</code></pre>
<p>But I I get the error: "KeyError: 'i.name'"</p>
<p>I think the problem is the 'i.name' doesn't really exist as a variable within the function.</p>
| [
{
"answer_id": 74290027,
"author": "Skylark",
"author_id": 20397599,
"author_profile": "https://Stackoverflow.com/users/20397599",
"pm_score": 0,
"selected": false,
"text": "ip_list []\nfor device in lnms.devices.all():\n ip_list.append(device.ip)\n\nname_list []\nfor device in lnms.devices.all():\n ip_list.append(device.sysName)\n"
},
{
"answer_id": 74290458,
"author": "PanTrakX",
"author_id": 13564014,
"author_profile": "https://Stackoverflow.com/users/13564014",
"pm_score": 1,
"selected": true,
"text": "for"
},
{
"answer_id": 74292108,
"author": "Skylark",
"author_id": 20397599,
"author_profile": "https://Stackoverflow.com/users/20397599",
"pm_score": 0,
"selected": false,
"text": "\n\ndef get_data(devices, key):\n response = []\n for device in devices:\n response.append(device.key)\n return response\n\n# => Endpoint devices/29/key does not exists\n\ndef get_data(devices, key):\n response = []\n for device in devices:\n response.append(f'device.{key}')\n return response\n\n# => ['device.sysName', 'device.sysName', 'device.sysName', 'device.sysName']\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20397599/"
] |
74,289,527 | <p>I wanted to host a API in WPF. I have tried implementing Self hosted api using below article.</p>
<p><a href="https://learn.microsoft.com/en-us/aspnet/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/aspnet/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api</a></p>
<p>When i have done the implementation for Console application. I was able to verify with PostMan tool to verify get API and it works fine.</p>
<p>But if i implement the same in WPF like below:</p>
<p>MainWindow() in WPF:</p>
<pre><code> string baseAddress = "http://localhost:4444/";
public MainWindow()
{
InitializeComponent();
WebApp.Start<StartUp>(baseAddress);
GetCall();
}
</code></pre>
<p>StartUp class:</p>
<pre><code>using Owin;
using System.Web.Http;
namespace WpfApp3
{
public class StartUp
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.MapHttpAttributeRoutes();
appBuilder.UseWebApi(config);
Owin.CorsExtensions.UseCors(appBuilder,
Microsoft.Owin.Cors.CorsOptions.AllowAll);
}
}
}
</code></pre>
<p>GET API implementation like below.</p>
<pre><code>string baseAddress = "http://localhost:4444/";
HttpClient client = new HttpClient();
var res = await client.GetStringAsync(baseAddress + "api/demo");
</code></pre>
<p>After Get API called: I got below exception.</p>
<p>Exception :System.Threading.Tasks.TaskCanceledException: 'The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing.'</p>
<p>Four Inner Exceptions:</p>
<ul>
<li>TimeoutException: The operation was canceled.</li>
<li>TaskCanceledException: The operation was canceled.</li>
<li>IOException: Unable to read data from the transport connection: The
I/O operation has been aborted because of either a thread exit or an
application request..</li>
<li>SocketException: The I/O operation has been aborted because of either
a thread exit or an application request.</li>
</ul>
<p>So, I am struggling to find a solution for this. Please provide a solution on this. am i going in the right way or not.</p>
<p>Or Is there any other solution for WPF to host api which will help a lot.</p>
| [
{
"answer_id": 74291355,
"author": "mm8",
"author_id": 7252182,
"author_profile": "https://Stackoverflow.com/users/7252182",
"pm_score": 0,
"selected": false,
"text": "DemoController"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8070342/"
] |
74,289,557 | <p>I have a set of files (<em>web components</em>). Some of those files define an optional type (it is in fact an interface with type definitions of the <code>event.detail</code> property for every custom event the component triggers, but let's for simplicity call it <code>OptionalType</code>).</p>
<p>There is another set of files, which are <em>generated</em> automatically. Each of those file corresponds to one web component and provides Preact types for that component.</p>
<p>I am looking for a way to conditionally define some of the types in the second, generated set of files, based on whether the original web component file exported <code>OptionalType</code> or not.</p>
<p>To give you a simplified example, this code could be in a component file:</p>
<pre><code>export interface OptionalType {
name: string
}
</code></pre>
<p>I figured initially that I could <code>import * as all</code> and then to check if <code>all['OptionalType']</code> (or <code>typeof all['OptionalType']</code>, or <code>all.OptionalType</code>) exists. This is how I intend to use that type in the generated file:</p>
<pre><code>import * as all from "./my-component"
type OptionalType = typeof all extends {
OptionalType: unknown
}
? typeof all["OptionalType"]
: never
// Do something with OptionalType
</code></pre>
<p>Unfortunately, this doesn't work. In JS <code>all</code> would be an object holding all the exports as properties. But in TS it is what seems to be a namespace. And I have no idea how to deal with those.</p>
<p>If I try to define those types inline for testing purposes, everything works as expected:</p>
<pre><code>interface All {
OptionalType: {
name: string
}
}
type OptionalTypeInline = All extends {
OptionalType: unknown
}
? All["OptionalType"]
: never
// Do something with OptionalType
</code></pre>
<p>You can also check or tweak <a href="https://codesandbox.io/s/importing-a-type-if-defined-forked-xkfjtd?file=/index.ts" rel="nofollow noreferrer">this example demo</a>.</p>
<h2>Update</h2>
<p>There was a problem in the accepted solution, which I marked out in my first comment to it. However, later I worked around that problem further in my code. You see, I used that OptionalType (which is really CustomEvents) in a "loop", and I managed to rewrite it to something like this:</p>
<pre><code>[K in keyof Events]: (
e: Events[K] extends keyof all.CustomEvents
? TargetedEvent<Component> & { detail: all.CustomEvents[Events[K]] }
: TargetedEvent<Component>
) => void
</code></pre>
<p>Sorry for not sharing all the details in the question from the very beginning.</p>
| [
{
"answer_id": 74290148,
"author": "Archigan",
"author_id": 14333778,
"author_profile": "https://Stackoverflow.com/users/14333778",
"pm_score": -1,
"selected": false,
"text": "import { OptionalType } from './my-component';\n\n// ...\n"
},
{
"answer_id": 74290517,
"author": "Garuno",
"author_id": 5625089,
"author_profile": "https://Stackoverflow.com/users/5625089",
"pm_score": 2,
"selected": true,
"text": "import * as all from \"./types\";\n\n// This declares that there is an interface 'OptionalType' in \"./types\"\n// If OptionalType does NOT exist in \"./types\" it will be declared as {}\n// If OptionalType does exist in \"./types\" our declaration will be merged and it will have the type { name: string; }\ndeclare module \"./types\" {\n interface OptionalType {\n }\n}\n\n// Here we check if it has the name attribute to know wether it was the declaration by us or the merged declaration.\ntype OptionalTypeConditional = all.OptionalType extends {\n name: string\n} ? all.OptionalType\n : never;\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2296470/"
] |
74,289,602 | <p>I've written two methods to find the smallest and largest int in an array, but they're nearly identical, so I feel like there should be some way to simplify this, perhaps as one method?</p>
<pre><code>private int findMin(){
int min = arr[0];
for(int num : arr){
if(num<min) {
min = num;
}
}
return min;
}
private int findMax(){
int max = arr[0];
for(int num : arr){
if(num>max){
max = num;
}
}
return max;
}
</code></pre>
<p>I'm not sure how to approach this sort of issue, so I'd love to see your responses!</p>
<p>While <a href="https://stackoverflow.com/questions/2902458/is-it-possible-to-pass-arithmetic-operators-to-a-method-in-java">this question on how to pass arithmetic operators to a method</a> and <a href="https://stackoverflow.com/questions/41816264/concise-way-to-get-both-min-and-max-value-of-java-8-stream">this question on how to get both min and max value of Java 8 stream</a> answer the literal programming problem, my question is on a more fundamental level about to how to approach the problem of methods doing similar things, and ways to compare arrays in general. The answers to this post have been significantly more helpful to me than the answers to those questions.</p>
| [
{
"answer_id": 74289730,
"author": "Matthew S.",
"author_id": 4789766,
"author_profile": "https://Stackoverflow.com/users/4789766",
"pm_score": 0,
"selected": false,
"text": "private int findExtreme(boolean findMin) {\n int solution = arr[0];\n for(int num : arr){\n if (findMin){\n if(num<min){\n solution = num;\n }\n } else {\n if(num>max){\n solution = num;\n }\n }\n }\n return solution;\n}\n"
},
{
"answer_id": 74289753,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 5,
"selected": false,
"text": "findMax"
},
{
"answer_id": 74289850,
"author": "John Kugelman",
"author_id": 68587,
"author_profile": "https://Stackoverflow.com/users/68587",
"pm_score": 1,
"selected": false,
"text": "(num < best)"
},
{
"answer_id": 74290193,
"author": "Joop Eggen",
"author_id": 984823,
"author_profile": "https://Stackoverflow.com/users/984823",
"pm_score": 4,
"selected": false,
"text": "IntStream"
},
{
"answer_id": 74290899,
"author": "Hiran Chaudhuri",
"author_id": 4222206,
"author_profile": "https://Stackoverflow.com/users/4222206",
"pm_score": 3,
"selected": false,
"text": "class MinMaxResult {\n public int min = 0;\n public int max = 0;\n}\n\nMinMaxResult findMinMax() {\n MinMaxResult result = new MinMaxResult();\n result.min = arr[0];\n result.max = arr[0];\n\n for (int num: arr) {\n if (num < result.min) {\n result.min = num;\n } else if (num > result.max) {\n result.max = num;\n }\n }\n\n return result;\n}\n"
},
{
"answer_id": 74300043,
"author": "russianroadman",
"author_id": 13051589,
"author_profile": "https://Stackoverflow.com/users/13051589",
"pm_score": 4,
"selected": false,
"text": "public int min(int[] array){\n return most(array, (a, b) -> a < b)\n}\n\npublic int max(int[] array){\n return most(array, (a, b) -> a > b)\n}\n\nprivate int most(int[] array, Fuction2 compare){\n int most = array[0];\n for (int num : array) {\n if (compare(num, most)) {\n most = num;\n }\n }\n return most;\n}\n"
},
{
"answer_id": 74304553,
"author": "WJS",
"author_id": 1552534,
"author_profile": "https://Stackoverflow.com/users/1552534",
"pm_score": 2,
"selected": false,
"text": "Math.min"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20397710/"
] |
74,289,611 | <p>Assume that I have a list of 10 thousand random numbers chosen in this way:</p>
<p><code>random_num = list(np.random.choice(2**16, 10000, replace=False))</code></p>
<p>Now, I have a key in the same range (e.g., 1024), and I need to find 10 numbers from the sorted list that have minimum value with the key based on the <code>xor</code> distance:</p>
<p><code>xor_dist = key ^ random_num[i]</code></p>
<p>Any suggestion?</p>
<p>I tried to <code>sort</code> the <code>random_num</code> list and then find the <code>xor</code> distance. Because of the <code>xor</code> nature, it doesn't work for all keys.</p>
<p>Also, I was thinking to use <code>banary search</code> to find the key in the list and then check with the neighbors, but again, it doesn't make the correct result for all keys and depends on where the key is in the range.</p>
| [
{
"answer_id": 74289717,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 2,
"selected": true,
"text": "heapq"
},
{
"answer_id": 74289722,
"author": "John Coleman",
"author_id": 4996248,
"author_profile": "https://Stackoverflow.com/users/4996248",
"pm_score": 0,
"selected": false,
"text": "sort"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8013881/"
] |
74,289,649 | <p>I want to count the number of occurrences of each character in a string and print the ones that occur at least Y times.</p>
<p>Example :</p>
<pre><code>Examples func(X: string, Y: int):
func("UserGems",2) => ["s" => 2, "e" => 2]
func("UserGems",3) => []
</code></pre>
<p>This what I could achieve so far:</p>
<pre><code>$str = "PHP is pretty fun!!";
$strArray = count_chars($str, 1);
$num = 1;
foreach ($strArray as $key => $value) {
if ($value = $num) {
echo "The character <b>'".chr($key)."'</b> was found $value time(s)
<br>";
}
}
</code></pre>
| [
{
"answer_id": 74289717,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 2,
"selected": true,
"text": "heapq"
},
{
"answer_id": 74289722,
"author": "John Coleman",
"author_id": 4996248,
"author_profile": "https://Stackoverflow.com/users/4996248",
"pm_score": 0,
"selected": false,
"text": "sort"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10634422/"
] |
74,289,687 | <p>I trying to implement a LeafLet map component in my Next JS 13.0.1 project, but I'm having a problem with the render of the map component.</p>
<p>In the first load of the map component, this error appears:</p>
<pre><code>ReferenceError: window is not defined
at eval (webpack-internal:///(sc_client)/./node_modules/leaflet/dist/leaflet-src.js:229:19)
at eval (webpack-internal:///(sc_client)/./node_modules/leaflet/dist/leaflet-src.js:7:11)
at eval (webpack-internal:///(sc_client)/./node_modules/leaflet/dist/leaflet-src.js:9:3)
at Object.(sc_client)/./node_modules/leaflet/dist/leaflet-src.js (C:\desenvolvimento\estacionai-front\.next\server\app\page.js:482:1)
at __webpack_require__ (C:\desenvolvimento\estacionai-front\.next\server\webpack-runtime.js:33:43)
at eval (webpack-internal:///(sc_client)/./node_modules/leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.js:2:18)
at eval (webpack-internal:///(sc_client)/./node_modules/leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.js:4:2)
at Object.(sc_client)/./node_modules/leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.js (C:\desenvolvimento\estacionai-front\.next\server\app\page.js:472:1)
at __webpack_require__ (C:\desenvolvimento\estacionai-front\.next\server\webpack-runtime.js:33:43)
at eval (webpack-internal:///(sc_client)/./components/Mapa.tsx:11:91)
</code></pre>
<p>anyways, the map loads, but things like markes do not appear</p>
<p><a href="https://i.stack.imgur.com/A9BPV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A9BPV.png" alt="enter image description here" /></a></p>
<p>the real problem is when the page is reloaded, being a hard reload or a Link reference.
this error appears:</p>
<pre><code>TypeError: Cannot read properties of undefined (reading 'default')
at resolveModuleMetaData (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/react-server-dom-webpack/server.browser.js:195:82)
at serializeModuleReference (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/react-server-dom-webpack/server.browser.js:1298:50)
at resolveModelToJSON (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/react-server-dom-webpack/server.browser.js:1660:40)
at Array.toJSON (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/react-server-dom-webpack/server.browser.js:1081:40)
at stringify (<anonymous>)
at processModelChunk (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/react-server-dom-webpack/server.browser.js:163:36)
at retryTask (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/react-server-dom-webpack/server.browser.js:1823:50)
at performWork (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/react-server-dom-webpack/server.browser.js:1856:33)
at AsyncLocalStorage.run (node:async_hooks:330:14)
at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/react-server-dom-webpack/server.browser.js:1934:55) {
digest: '699076802'
}
</code></pre>
<p>After this error, the page do not load</p>
<p><a href="https://i.stack.imgur.com/6Oowo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6Oowo.png" alt="blank page" /></a>
<a href="https://i.stack.imgur.com/fuRvC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fuRvC.png" alt="enter image description here" /></a></p>
<ul>
<li>Project Structure:</li>
</ul>
<p><a href="https://i.stack.imgur.com/z0v69.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z0v69.png" alt="project structure" /></a></p>
<ul>
<li>Mapa.tsx(map component)</li>
</ul>
<pre class="lang-js prettyprint-override"><code>'use-client';
import { useState } from 'react';
import 'leaflet/dist/leaflet.css';
import 'leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.css'
import "leaflet-defaulticon-compatibility";
import { MapContainer, TileLayer, Marker, useMap } from 'react-leaflet';
export default function Map() {
const [geoData, setGeoData] = useState({ lat: 64.536634, lng: 16.779852 });
return (
<MapContainer center={[geoData.lat, geoData.lng]} zoom={12} style={{ height: '90vh' }}>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{geoData.lat && geoData.lng && (
<Marker position={[geoData.lat, geoData.lng]} />
)}
</MapContainer>
);
}
</code></pre>
<ul>
<li>Home component (app/page.tsx)</li>
</ul>
<pre class="lang-js prettyprint-override"><code>'use client';
import Link from "next/link";
import { useEffect, useState } from "react";
import Mapa from "../components/Mapa";
export default function Home(){
return (
<div>
<Link href='/pontos'>Pontos</Link>
<Mapa />
</div>
)
}
</code></pre>
<ul>
<li>package.json</li>
</ul>
<pre class="lang-js prettyprint-override"><code>{
"name": "estacionai-front",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@types/node": "18.11.9",
"@types/react": "18.0.24",
"@types/react-dom": "18.0.8",
"leaflet": "^1.9.2",
"leaflet-defaulticon-compatibility": "^0.1.1",
"leaflet-geosearch": "^3.7.0",
"next": "^13.0.1",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-leaflet": "^4.1.0",
"typescript": "4.8.4"
},
"devDependencies": {
"@types/leaflet": "^1.9.0",
"autoprefixer": "^10.4.13",
"postcss": "^8.4.18",
"tailwindcss": "^3.2.1"
}
}
</code></pre>
<p>I tried to use the dynamic() and import() function from Next but without successm, i think the only way to load the component is using the 'use client' directive in both the map component and page component</p>
| [
{
"answer_id": 74289717,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 2,
"selected": true,
"text": "heapq"
},
{
"answer_id": 74289722,
"author": "John Coleman",
"author_id": 4996248,
"author_profile": "https://Stackoverflow.com/users/4996248",
"pm_score": 0,
"selected": false,
"text": "sort"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11536818/"
] |
74,289,689 | <p>I want to fit better my model to my data. Now I use this code:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit as sc
x_value=np.array([30000,27850,25590,23900,22400,20470,19450,18120,17130,16180,15340,14620,13730,13400,12790,12460,12060,11760,11440,11200,10940,10780,10720,10530])
y_value =np.array([23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0])
p = np.polyfit( y_value, np.log10((x_value)), 1)
# Convert the polynomial back into an exponential
a = 10**(p[1])
le=len(x_value)
a= a+(x_value[le-1]-a)
b = p[0]
x_fitted_polyfit = np.linspace(np.min(y_value), np.max(y_value), 24)
y_fitted_polyfit = a * 10**(b * x_fitted_polyfit+np.min(y_value))
plt.scatter( y_value, x_value, label= "zisk", color= "blue", marker= "x",s=30)
plt.plot( x_fitted_polyfit,y_fitted_polyfit, 'r', label='polyfit - unweighted')
plt.xlabel('frekvence [Hz]')
plt.ylabel('zisk [dBm]')
# plot title
plt.title('My scatter plot!')
# showing legend
plt.legend()
</code></pre>
<p>My exit is now this graph <a href="https://i.stack.imgur.com/yw9oZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yw9oZ.jpg" alt="enter image description here" /></a>
I have ready tried</p>
<pre><code>popt, pcov = sc(lambda t, a, b: a * np.exp(b * t),y_value , x_value)
# Extract the optimised parameters
a = popt[0]+1000
b = popt[1]
x_fitted_curve_fit = np.linspace(np.min(y_value ), np.max(y_value ), 10000)
y_fitted_curve_fit = a * np.exp(b * x_fitted_curve_fit)
</code></pre>
<p>but it looks similar.</p>
| [
{
"answer_id": 74289717,
"author": "chepner",
"author_id": 1126841,
"author_profile": "https://Stackoverflow.com/users/1126841",
"pm_score": 2,
"selected": true,
"text": "heapq"
},
{
"answer_id": 74289722,
"author": "John Coleman",
"author_id": 4996248,
"author_profile": "https://Stackoverflow.com/users/4996248",
"pm_score": 0,
"selected": false,
"text": "sort"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18180826/"
] |
74,289,691 | <p>I have a DF whereby I need to compute the arctan of two north/south wind components. However, it seems that the arctan2 function only takes 2 arguments x,y such according to the documentation:</p>
<pre><code>numpy.arctan2(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'arctan2'>
</code></pre>
<p>However, I need to divide the x, y components to obtain my desired answer. So, I need to do this -</p>
<p>dfout = np.arctan2(x/y) using 1 argument but the documentation says that I need 2 arguments x,y.</p>
<p>I see the "/" symbol as an option but I'm not sure if that applies or how to do that. Any ideas?</p>
<p>My data looks like this in df:</p>
<pre><code>day hour Cns Cew
1 0 126.002 -100.812
1 1 -42.3775 18.6631
1 2 64.3313 -121.167
</code></pre>
<p>I need to do this in the example above:</p>
<pre><code>dfout = np.arctan2(df.Cew/df.Cns)
</code></pre>
<p>but I get this error -</p>
<pre><code>TypeError: arctan2() takes from 2 to 3 positional arguments but 1 were given
</code></pre>
<p>I have tried this but I get a syntax error.</p>
<pre><code>dfout = np.arctan2(df.Cew,df.Cns,/)
</code></pre>
<p>Using this below does not provide the correct answer as I am trying to compute the average wind direction using the Cew (EAST-WEST) and Cns (NORTH-SOUTH) components of the wind.</p>
<p>This will NOT work -</p>
<p>dfout = np.arctan2(Cew, Cns).</p>
<p>And, my angles range from -180 to + 180 wind direction angles in degrees.</p>
<p>thanks much,</p>
| [
{
"answer_id": 74289790,
"author": "norok2",
"author_id": 5218354,
"author_profile": "https://Stackoverflow.com/users/5218354",
"pm_score": 0,
"selected": false,
"text": "dfout = np.arctan2(df.Cew, df.Cns)\n"
},
{
"answer_id": 74289967,
"author": "chrslg",
"author_id": 20037042,
"author_profile": "https://Stackoverflow.com/users/20037042",
"pm_score": 1,
"selected": false,
"text": "np.arctan"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2100039/"
] |
74,289,707 | <p>I am trying to find data between two given heights. I am storing heights data in separate Mongodb schema, in which the height's unique <code>_id</code> is what I store in a <code>user-schema</code>. So I do populate() in the GET Apis and all.</p>
<p>The problem is when I am working on the filter api like finding users based on given two heights, How can I find the users data between two input height? should I pass the two heights <code>_id</code> to find ? If so may i know the method or some suggestion or Raw data like 5.1 to 6? If I pass raw data like 5.1 and 5.8 but how will I find users data because I am not storing raw data in <code>user-schema</code> instead I am storing height's id.</p>
<p><strong>Config Schema</strong></p>
<pre><code>const appconfigSchema = mongoose.Schema({
configValue: {
type: String,
required: true,
},
configDesc: {
type: String,
},
...
</code></pre>
<p><strong>Config Sample Data</strong></p>
<pre><code>[
{
"_id": "636261302187d07f920b1174",
"configValue": "5.1",
"configDesc": "5ft 1in",
"metaDataType": "Height",
"isParent": false,
"parentPrimaryId": "636260f82187d07f920b1171",
"isActive": true,
"createdAt": "2022-11-02T12:23:12.999Z",
"updatedAt": "2022-11-02T12:23:12.999Z",
"__v": 0
}
]
</code></pre>
<p><strong>User Schema</strong></p>
<pre><code>...
Height: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'appconfigs'
},
...
</code></pre>
<p><strong>User Sample Data</strong></p>
<pre><code>...
"Country": "India",
"State": "Tamil Nadu",
"City": "Trichy",
"Height": "636261302187d07f920b1174",
...
</code></pre>
<p>So How to find users data between two given heights ? Should I pass heights Id only or heights raw data like 5.1 & 5.8, If so please teach me the method</p>
| [
{
"answer_id": 74300602,
"author": "Pawan Yadav",
"author_id": 16764381,
"author_profile": "https://Stackoverflow.com/users/16764381",
"pm_score": 0,
"selected": false,
"text": "const userData=await users.find({$and:[{\"Height._id\":{$gte:\"smaller_id\"}},{\"Height._id\":{$lte:\"larger_id\"}}]});\n"
},
{
"answer_id": 74300655,
"author": "Thomas Zimmermann",
"author_id": 13527621,
"author_profile": "https://Stackoverflow.com/users/13527621",
"pm_score": 2,
"selected": true,
"text": "const filteredUsers = await User.aggregate([\n // Lookup to get height information from ID \n {\n $lookup: {\n from: \"configs\", // Looking in the config table\n localField: \"Height\",\n foreignField: \"_id\",\n pipeline: [{\n // Convert value to double (was string)\n $project: {\n valueAsDouble: {$toDouble: \"$configValue\"}\n }\n }],\n as: \"heightLookup\"\n }\n },\n {\n // Match users with condition 5.1 <= Height value <= 5.8\n $match: {\n \"heightLookup.0.valueAsDouble\": {$gte: 5.1, $lte: 5.8}\n }\n } \n]);\n\n// Expected output\n\n[\n {\n \"City\": \"Trichy\",\n \"Country\": \"India\",\n \"Height\": \"636261302187d07f920b1174\",\n \"State\": \"Tamil Nadu\",\n \"_id\": 1,\n \"heightLookup\": [\n {\n \"_id\": \"636261302187d07f920b1174\",\n \"valueAsDouble\": 5.1\n }\n ]\n },\n ...\n]\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19554161/"
] |
74,289,725 | <p>I have 3 strings. I need to create an array out of those 3 strings, when I do it, it gets shown to me that the memory adresses of the strings are different than the ones of the array. Meaning that they dont point to the same thing. But I want that if I change the strings out of which I made the array, after the array creation, that the array will automatically update. And vice-versa.
Is this possible and how can I do this.
This is my code to show that they dont use the same Memory adresses, hence, they arent the same:</p>
<pre><code> std::string x = "x";
std::string y = "y";
std::string z = "z";
std::string letters[3] = {x, y, z};
std::cout << &x << "\t" << &y << "\t" << &z << "\n";
std::cout << &letters[0] << "\t" << &letters[1] << "\t" << &letters[2] << "\n";
</code></pre>
<p>The output is:</p>
<pre><code>0x20b1bff730 0x20b1bff710 0x20b1bff6f0
0x20b1bff690 0x20b1bff6b0 0x20b1bff6d0
</code></pre>
| [
{
"answer_id": 74289832,
"author": "Vlad from Moscow",
"author_id": 2877241,
"author_profile": "https://Stackoverflow.com/users/2877241",
"pm_score": 3,
"selected": false,
"text": "std::string letters[3] = {x, y, z};\n"
},
{
"answer_id": 74289898,
"author": "john",
"author_id": 882003,
"author_profile": "https://Stackoverflow.com/users/882003",
"pm_score": 3,
"selected": true,
"text": "std::string* xp = new std::string(\"x\");\nstd::string* yp = new std::string(\"y\");\nstd::string* zp = new std::string(\"z\");\n\nstd::string* letters[3] = { xp, yp, zp };\n\n*xp = \"X\"; // changes *xp and *letters[0], since xp == letters[0]\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17895488/"
] |
74,289,737 | <p>I have a macro variable:</p>
<pre><code>%let names = name1, name2, name3, name4
</code></pre>
<p>The real variable can vary in length. What I want to do is make a new variable datalist, which looks like this:</p>
<pre><code>‘name1’,‘name2’,‘name3’,‘name4’
</code></pre>
<p>I have tried to make this variable in the following way:</p>
<pre><code>%str(%’)%sysfunc(tranwrd(%quote(&names.),%str(,),%str(%’ ,%’)))%str(%’))
</code></pre>
<p>When I run the code I get the following error:</p>
<pre><code>The meaning of an identifier after a quoted string might change in a future SAS release. Inserting white space between a quoted string and the succeeding identifier is recommended.
</code></pre>
<p>Adding white spaces does not help though. Does anyone know a different method to construct my desired macro variable?</p>
<p>PS: I have seen the following question, but in that one there were no commas separating the elements in the list. <a href="https://stackoverflow.com/questions/42426109/sas-macro-variable-quotes">SAS macro variable quotes</a></p>
| [
{
"answer_id": 74289861,
"author": "data _null_",
"author_id": 2196220,
"author_profile": "https://Stackoverflow.com/users/2196220",
"pm_score": 0,
"selected": false,
"text": "38 proc sql noprint;\n39 select quote(strip(name),\"'\") into :namelist separated by ', ' from sashelp.class;\n40 quit;\nNOTE: PROCEDURE SQL used (Total process time):\n real time 0.01 seconds\n cpu time 0.00 seconds\n \n\n41 \n42 %put NOTE: &=namelist;\nNOTE: NAMELIST='Alice', 'Barbara', 'Carol', 'Jane', 'Janet', 'Joyce', 'Judy', 'Louise', 'Mary', 'Alfred', 'Henry', 'James', \n'Jeffrey', 'John', 'Philip', 'Robert', 'Ronald', 'Thomas', 'William'\n"
},
{
"answer_id": 74290695,
"author": "Tom",
"author_id": 4965549,
"author_profile": "https://Stackoverflow.com/users/4965549",
"pm_score": 2,
"selected": true,
"text": "%let names = name1, name2, name3, name4 ;\n%let qnames = %sysfunc(tranwrd(%bquote('&names'),%str(, ),', '));\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5691725/"
] |
74,289,742 | <p>I have a list of domains and I want to extract country codes from the URLs, if they are available. Is there a formula that I can use in Google sheets or Excel to quickly get this?</p>
<p>Expected output from the domains are mentioned below:</p>
<ul>
<li>mk.ru -> ru</li>
<li>news.yahoo.co.jp -> jp</li>
<li>nabdn.com -> NA</li>
<li>247.libero.it -> it</li>
<li>zazoom.it -> it</li>
<li>news.goo.ne.jp -> jp</li>
<li>tw.news.yahoo.com -> tw</li>
<li>topics.smt.docomo.ne.jp -> jp</li>
<li>excite.co.jp -> jp</li>
</ul>
<p>I tried to split the columns but it is not consistent and is manual to collate the country codes.</p>
| [
{
"answer_id": 74289861,
"author": "data _null_",
"author_id": 2196220,
"author_profile": "https://Stackoverflow.com/users/2196220",
"pm_score": 0,
"selected": false,
"text": "38 proc sql noprint;\n39 select quote(strip(name),\"'\") into :namelist separated by ', ' from sashelp.class;\n40 quit;\nNOTE: PROCEDURE SQL used (Total process time):\n real time 0.01 seconds\n cpu time 0.00 seconds\n \n\n41 \n42 %put NOTE: &=namelist;\nNOTE: NAMELIST='Alice', 'Barbara', 'Carol', 'Jane', 'Janet', 'Joyce', 'Judy', 'Louise', 'Mary', 'Alfred', 'Henry', 'James', \n'Jeffrey', 'John', 'Philip', 'Robert', 'Ronald', 'Thomas', 'William'\n"
},
{
"answer_id": 74290695,
"author": "Tom",
"author_id": 4965549,
"author_profile": "https://Stackoverflow.com/users/4965549",
"pm_score": 2,
"selected": true,
"text": "%let names = name1, name2, name3, name4 ;\n%let qnames = %sysfunc(tranwrd(%bquote('&names'),%str(, ),', '));\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20397918/"
] |
74,289,745 | <p>I am currently learning about the functionalities of the Optional class, and I am trying to build a simplified version of the Optional class. I was able to code <code>ifPresent()</code>, <code>filter()</code>, <code>of()</code>, <code>map()</code> and so on. However, I am currently stuck with the implementing <code>or()</code>.</p>
<p>I know that <code>or()</code> have the signature <code>Optional<T> or(Supplier<? extends Optional<? extends T>> supplier)</code>. However, my implementation assumed that I can access the contents of the Optional. As show below:</p>
<pre><code>class Optional<T> {
private final T item;
...
Optional<T> or(Supplier<? extends Optional<? extends T>> supplier) {
if (this.item == null) {
T item = supplier.get().item;
return Maybe.<T>of(item);
} else {
return this;
}
}
}
</code></pre>
<p>As you can see, <code>T item = supplier.get().item</code> would throw an error saying that <code>.item</code> is inaccessible due to it being private. How am I able to access the <code>item</code> without causing this error?</p>
| [
{
"answer_id": 74290239,
"author": "talex",
"author_id": 3656904,
"author_profile": "https://Stackoverflow.com/users/3656904",
"pm_score": 0,
"selected": false,
"text": " T item = supplier.get().item;\n return Maybe.<T>of(item);\n"
},
{
"answer_id": 74320648,
"author": "Holger",
"author_id": 2711488,
"author_profile": "https://Stackoverflow.com/users/2711488",
"pm_score": 3,
"selected": true,
"text": "private"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16779934/"
] |
74,289,746 | <p>I want to get from the SpriteRenderer these positions from the screenshot, this is the top center point and the bottom center point to create objects at these positions, so I need the global position of these points.</p>
<p><a href="https://i.stack.imgur.com/khOm1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/khOm1.png" alt="enter image description here" /></a></p>
<p>I already tried to use Bounds, but they did not give me the result I needed, they show the wrong center, min and max positions, or rather they were created in other places. Maybe I misunderstood something? The search logic is written in a different object, and the SpriteRenderer is on a different object,</p>
<pre><code> Bounds spriteBounds = SpriteRenderer.sprite.bounds;
_centerPointValue = spriteBounds.center;
_rightUpPointValue = spriteBounds.max;
_leftBottomPointValue = spriteBounds.min;
</code></pre>
| [
{
"answer_id": 74290239,
"author": "talex",
"author_id": 3656904,
"author_profile": "https://Stackoverflow.com/users/3656904",
"pm_score": 0,
"selected": false,
"text": " T item = supplier.get().item;\n return Maybe.<T>of(item);\n"
},
{
"answer_id": 74320648,
"author": "Holger",
"author_id": 2711488,
"author_profile": "https://Stackoverflow.com/users/2711488",
"pm_score": 3,
"selected": true,
"text": "private"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16283338/"
] |
74,289,796 | <p>I have a simple program that takes data from the user. Here is an abbreviated version of it:</p>
<pre><code>a = "0-1"
b = "0‑1"
print(a in b) # prints False
</code></pre>
<p>Problem:</p>
<blockquote>
<p>ord('-') for a = 45</p>
</blockquote>
<blockquote>
<p>ord('‑') for b = 8209</p>
</blockquote>
<p>How can I make sure that the "-" sign is always the same and checking a in b returns True?</p>
| [
{
"answer_id": 74290239,
"author": "talex",
"author_id": 3656904,
"author_profile": "https://Stackoverflow.com/users/3656904",
"pm_score": 0,
"selected": false,
"text": " T item = supplier.get().item;\n return Maybe.<T>of(item);\n"
},
{
"answer_id": 74320648,
"author": "Holger",
"author_id": 2711488,
"author_profile": "https://Stackoverflow.com/users/2711488",
"pm_score": 3,
"selected": true,
"text": "private"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19940890/"
] |
74,289,826 | <p>In my <code>nextjs</code>-app I want to use <code>localstorage</code>, to store some values across my application.</p>
<p>so inside the <code>pages</code>-folder I have a <code>[slug].tsx</code>-file where I do this:</p>
<pre><code>export default function Page({ data}) {
useEffect(() => {
const page = {
title: data.page.title,
subtitle: data.page.subtitle,
slug: data.page.slug,
}
localStorage.setItem("page", JSON.stringify(page))
})
return ( ... some html....)
}
</code></pre>
<p>this basically stores the title, subtitle and slug for the current route.</p>
<p>Now, inside my <code>components</code>-folder I have a <code>Nav.tsx</code>-file, where I do this:</p>
<pre><code>const Nav= () => {
const [pageData, setPageData] = useState()
useEffect(() => {
const current = JSON.parse(localStoraget.getItem('page'))
if(current){
setPageData(current)
}
},[])
return(...some html)
}
</code></pre>
<p>So far, the <code>setItem</code> works and in the <code>application</code>-tab of the google inspector I can see, that the key-values changes, each time a new route/page gets rendered BUT the <code>getItem</code>- always returns the same e.g. the key values do not change at all. What am I doing wrong? Is it maybe because the <code>Nav</code> component only gets rendered once?</p>
<p>Can someone help me out?</p>
| [
{
"answer_id": 74289986,
"author": "DᴀʀᴛʜVᴀᴅᴇʀ",
"author_id": 1952287,
"author_profile": "https://Stackoverflow.com/users/1952287",
"pm_score": 1,
"selected": false,
"text": "localStoraget.getItem('page')\n"
},
{
"answer_id": 74290191,
"author": "Ilê Caian",
"author_id": 19330762,
"author_profile": "https://Stackoverflow.com/users/19330762",
"pm_score": 0,
"selected": false,
"text": "localStorage"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3955607/"
] |
74,289,835 | <p>I have a dataframe with multiple columns, two of these columns have the same name ('mobilephone'), some values are empty, and some aren't but there will always be one of the two columns populated with a phone number:</p>
<pre><code> mobilephone mobilephone
0 999000111 999000111
1 999000222
2 999000333
3 999000444 999000444
</code></pre>
<p>How would I keep only one of these columns but populate the empty values in the first column with the values in the second column?</p>
| [
{
"answer_id": 74290096,
"author": "T C Molenaar",
"author_id": 8814131,
"author_profile": "https://Stackoverflow.com/users/8814131",
"pm_score": 2,
"selected": true,
"text": ".loc[]"
},
{
"answer_id": 74290186,
"author": "Devam Sanghvi",
"author_id": 16921041,
"author_profile": "https://Stackoverflow.com/users/16921041",
"pm_score": 0,
"selected": false,
"text": "# renaming the columns\ndf.columns = ['mobilephone1', 'mobilephone2']\n# filling blank cell with second column data\ndf['mobilephone1']=df['mobilephone1'].fillna(df['mobilephone2'])\n# if you want you canrenam the columns again\ndf.columns = ['mobilephone', 'mobilephone']\n"
},
{
"answer_id": 74290232,
"author": "Bushmaster",
"author_id": 15415267,
"author_profile": "https://Stackoverflow.com/users/15415267",
"pm_score": 0,
"selected": false,
"text": "df = df.replace(r'^\\s*$', np.nan, regex=True)\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18152569/"
] |
74,289,872 | <p>I am working on calculating the area of flowering parts in certain plots. However, different types of plants have different types of measurements (for example, some flowers, we have the size of the whole inflorescence and some we have only the size of individual flowers). I would like to create a column with the calculated area using different conditional statements. Here is an example data frame:</p>
<pre><code>
inflorescence_mm <- c("5", "NA", "NA")
flower_mm <- c("NA", "NA", "3")
corolla_mm <- c("NA", "2", "NA")
count <- c("100", "75", "80")
df <- data.frame(inflorescence_mm, flower_mm, corolla_mm, count)
</code></pre>
<p>I would like to create a column called "flower_area_mm2" using mutate and ifelse, but since I am using a formula to calculate area, I am having trouble.</p>
<p>If there is data in inflorescence_mm, then I would use (0.5<em>inflorescence_mm)^2 * pi * count. If there is an NA in inflorescence, then I would use (0.5</em>flower_mm)^2 * pi * count. And if there is an NA in flower_mm then I would use (0.5*corolla_mm)^2 * pi * count.</p>
<p>Can anyone help write such a conditional statement?</p>
<p>I tried creating an ifelse statement within mutate and using is.na, but this did not fill in the new column.</p>
| [
{
"answer_id": 74290560,
"author": "Isaac",
"author_id": 16765847,
"author_profile": "https://Stackoverflow.com/users/16765847",
"pm_score": 1,
"selected": false,
"text": "df"
},
{
"answer_id": 74299921,
"author": "KNieder",
"author_id": 17045654,
"author_profile": "https://Stackoverflow.com/users/17045654",
"pm_score": 0,
"selected": false,
"text": "mutate(flower_area_mm2 = case_when(!is.na(inflorescence_mm) ~ \n (0.5*inflorescence_mm)^2 * pi*count,\n is.na(flower_mm) ~ (0.5*corolla_mm)^2 * pi * count,\n is.na(inflorescence_mm) ~ (0.5* flower_mm)^2 * pi*count))\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17045654/"
] |
74,289,881 | <p>I'm trying to create a Regex String with the following rules</p>
<ol>
<li>The username is between 4 and 25 characters.</li>
<li>It must start with a letter.</li>
<li>It can only contain letters, numbers, and the underscore character.</li>
<li>It cannot end with an underscore character.</li>
</ol>
<p>when it meets this criterion I want the output to be true otherwise false, but I only get false for my test cases, here is my code</p>
<pre><code>public class Profile {
public static String username(String str) {
String regularExpression = "^[a-zA-Z][a-zA-Z0-9_](?<=@)\\w+\\b(?!\\_){4,25}$";
if (str.matches(regularExpression)) {
str = "true";
}
else if (!str.matches(regularExpression)) {
str = "false";
}
return str;
}
</code></pre>
<p>Main class</p>
<pre><code>Profile profile = new profile();
Scanner s = new Scanner(System.in);
System.out.print(profile.username(s.nextLine()));
</code></pre>
<p>input</p>
<pre><code>"aa_"
"u__hello_world123"
</code></pre>
<p>output</p>
<pre><code>false
false
</code></pre>
<p>Fixed: thanks to everyone who contributed</p>
| [
{
"answer_id": 74289913,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 3,
"selected": true,
"text": "^[a-zA-Z][a-zA-Z0-9_]{3,24}$(?<!_)\n^[a-zA-Z]\\w{3,24}$(?<!_)\n^[a-zA-Z][a-zA-Z0-9_]{2,23}[a-zA-Z0-9]$\n^\\p{Alpha}[a-zA-Z0-9_]{2,23}\\p{Alnum}$\n"
},
{
"answer_id": 74290847,
"author": "bobble bubble",
"author_id": 5527985,
"author_profile": "https://Stackoverflow.com/users/5527985",
"pm_score": 0,
"selected": false,
"text": "\\p{L}"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17266758/"
] |
74,289,905 | <pre><code>@echo off
REM turning off the output of commands to the screen
Set /P "%~1=Extension: "
if "%~1" == "" echo Extension not introduced
REM if you do not enter anything, the extension is not entered
if not exist "*.%~1" echo No files found
REM if you entered an extension that does not exist, it will give you no files found.
DEL /Q "*.%~1"
REM delete files with the specified extension without confirmation
</code></pre>
<p>I can't figure out how "set" works. Help to make it so that: after launching batch, you had to enter the extension and then it would be deleted or output that it was not found.</p>
| [
{
"answer_id": 74289913,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 3,
"selected": true,
"text": "^[a-zA-Z][a-zA-Z0-9_]{3,24}$(?<!_)\n^[a-zA-Z]\\w{3,24}$(?<!_)\n^[a-zA-Z][a-zA-Z0-9_]{2,23}[a-zA-Z0-9]$\n^\\p{Alpha}[a-zA-Z0-9_]{2,23}\\p{Alnum}$\n"
},
{
"answer_id": 74290847,
"author": "bobble bubble",
"author_id": 5527985,
"author_profile": "https://Stackoverflow.com/users/5527985",
"pm_score": 0,
"selected": false,
"text": "\\p{L}"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20390142/"
] |
74,289,912 | <p>I'm trying to pass a frame read from a camera using opencv as an argument to another python script but I cannot get it to work.</p>
<p>Running the following script stores a camera frame on my network every 5 seconds:</p>
<pre><code>
</code></pre>
<pre><code>#!/usr/bin/python
import cv2
import threading
import subprocess
import time
import datetime
def camera():
camera = cv2.VideoCapture("/dev/video0")
if not camera.isOpened():
print("Cannot open camera.")
raise SystemExit
camera.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 320)
camera.set(cv2.CAP_PROP_FPS, 15)
return camera
try:
camera = camera()
while True:
frame = camera.read()[1]
#subprocess.call(["python", "/home/user/test2.py", frame])
server = "/net/192.168.4.51/mnt/LAN4Storage/EC/Camera/"
cv2.imwrite(server + "temp.jpg", frame)
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cv2.imwrite(server + timestamp + ".jpg", frame)
time.sleep(5)
except Exception as error:
print(error)
finally:
camera.release()
</code></pre>
<pre><code>
</code></pre>
<p>If I uncomment the subprocess.call line and comment the next 4 lines I expect the frame to be passed to my test2.py script:</p>
<p>`</p>
<pre><code> #/usr/bin/env python
import cv2
import sys
import os
import time
import datetime
try:
frame = cv2.imread(sys.argv[1])
server = "/net/192.168.4.51/mnt/LAN4Storage/EC/Camera/"
cv2.imwrite(server + "temp.jpg", frame)
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cv2.imwrite(server + timestamp + ".jpg", frame)
except Exception as error:
print(error)
finally:
pass
</code></pre>
<p>`
But on starting test1.py, I get the following error:</p>
<pre><code>`expected str, bytes or os.PathLike object, not ndarray`
</code></pre>
| [
{
"answer_id": 74290066,
"author": "Pablo Estevez",
"author_id": 18203813,
"author_profile": "https://Stackoverflow.com/users/18203813",
"pm_score": 0,
"selected": false,
"text": "subprocess.call([\"python\", \"/home/user/test2.py\", frame.tostring()]) should work.\n"
},
{
"answer_id": 74299465,
"author": "Mark Setchell",
"author_id": 2836621,
"author_profile": "https://Stackoverflow.com/users/2836621",
"pm_score": 1,
"selected": false,
"text": "tmpfs"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19407020/"
] |
74,289,952 | <p>Is there any way to call a function by reference not by values in flutter.</p>
| [
{
"answer_id": 74290102,
"author": "IonicFireBaseApp",
"author_id": 19303836,
"author_profile": "https://Stackoverflow.com/users/19303836",
"pm_score": 1,
"selected": false,
"text": "typedef ProfileFormSubmitCallback = void Function(\n String? photoUrl,\n String firstName,\n String lastName,\n String email,\n);\nthen\n"
},
{
"answer_id": 74290250,
"author": "blackkara",
"author_id": 1281180,
"author_profile": "https://Stackoverflow.com/users/1281180",
"pm_score": 0,
"selected": false,
"text": "class ButtonPrimary extends StatelessWidget {\n final String text;\n final double? height;\n final double? width;\n final VoidCallback onPressed;\n \n\n const ButtonPrimary({\n Key? key,\n required this.onPressed,\n required this.text,\n this.height,\n this.width,\n }) : super(key: key);\n\n @override\n Widget build(BuildContext context) {\n return SizedBox(\n height: height ?? 50,\n width: width ?? MediaQuery.of(context).size.width * .6,\n child: ElevatedButton(\n onPressed: onPressed,\n child: Widget(...),\n ),\n );\n }\n}\n"
},
{
"answer_id": 74293138,
"author": "jamesdlin",
"author_id": 179715,
"author_profile": "https://Stackoverflow.com/users/179715",
"pm_score": 3,
"selected": true,
"text": "class Reference<T> {\n T value;\n\n Reference(this.value);\n}\n\nvoid trimString(Reference<String> string) {\n string.value = string.value.trim();\n}\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19661715/"
] |
74,289,972 | <p>I am using VQGAN+CLIP_(Zooming)_(z+quantize_method_with_addons).ipynb Google Repository and when I click the cell "Loading of libraries and definitions"</p>
<p>It sent an error :</p>
<pre><code>ImportError Traceback (most recent call last)
<ipython-input-6-fe8fafeed45d> in <module>
24 from omegaconf import OmegaConf
25 from PIL import Image
---> 26 from taming.models import cond_transformer, vqgan
27 import torch
28 from torch import nn, optim
1 frames
/content/taming-transformers/main.py in <module>
10 from pytorch_lightning.trainer import Trainer
11 from pytorch_lightning.callbacks import ModelCheckpoint, Callback, LearningRateMonitor
---> 12 from pytorch_lightning.utilities.distributed import rank_zero_only
13
14 from taming.data.utils import custom_collate
ImportError: cannot import name 'rank_zero_only' from 'pytorch_lightning.utilities.distributed' (/usr/local/lib/python3.7/dist-packages/pytorch_lightning/utilities/distributed.py)
</code></pre>
<p>I don't know how to solde this problem. I don't know how to manually install Pytorch as it said "NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.</p>
<p>To view examples of installing some common dependencies, click the
"Open Examples" button below."</p>
<p>Thank you in advance if you have the solution.</p>
<p>Inès</p>
<p>I triad !pip install but I may not really know where to put this cell/line of code</p>
| [
{
"answer_id": 74296408,
"author": "Decoder",
"author_id": 17614194,
"author_profile": "https://Stackoverflow.com/users/17614194",
"pm_score": 1,
"selected": false,
"text": "conda install pytorch-lightning -c conda-forge\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20398063/"
] |
74,289,988 | <p>I'm getting <code>StackOverflowException</code> when I run below program. My doubt is how this program recursively calling each classes(<code>ArrayTest1</code>, <code>ArrayTest2</code>) fields without executing constructor method?</p>
<pre><code>using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var arraryTest = new ArrayTest1();
}
}
public class ArrayTest1
{
ArrayTest2 arrayTest2 = new ArrayTest2();
public ArrayTest1()
{
Console.WriteLine($"{nameof(ArrayTest1)} Class Contructor Executed");
}
}
public class ArrayTest2
{
ArrayTest1 arrayTest1 = new ArrayTest1();
public ArrayTest2()
{
Console.WriteLine($"{nameof(ArrayTest2)} Class Contructor Executed");
}
}
</code></pre>
| [
{
"answer_id": 74290020,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 2,
"selected": false,
"text": "new ArrayTest1()\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13995181/"
] |
74,289,995 | <p>I'm trying to create a simple action, that when the page loads, the page will scroll to a certain position.</p>
<p>But no matter what I do, the action does not fire.</p>
<p>Is there another way to do this in a React app?</p>
<p>for example:</p>
<p><code>window.scrollBy(0, 850);</code></p>
| [
{
"answer_id": 74290020,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 2,
"selected": false,
"text": "new ArrayTest1()\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74289995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19327759/"
] |
74,290,004 | <p>I have an <code>enum</code> that map a given keyword to a CSS class.</p>
<pre class="lang-js prettyprint-override"><code>enum Colors {
WHT = 'color--white'
}
</code></pre>
<p>and inside the component I created a new property with that value <code>colors = Colors</code>
and I'm using it as it follows</p>
<pre class="lang-html prettyprint-override"><code> <p [ngClass]="[colors['WHT']]">My paragraph</p>
</code></pre>
<p>In this scenario it works as expected.</p>
<p>The problem is when I try to add a condition to this class binding.</p>
<pre class="lang-html prettyprint-override"><code> <p [ngClass]="{ [colors['WHT']]: false }> My paragraph </p>"
</code></pre>
<p>The official <a href="https://angular.io/api/common/NgClass" rel="nofollow noreferrer">documentation</a> doesn't provide any information about this use case, but it doesn't provide an example for <code><p [ngClass]="[componentColors['WHT']]"> My paragraph</p></code> either and this approach works fine.</p>
<p><strong>Update:</strong>
The <code>false</code> condition is just demo purposes, in the real scenario it will use a variable.</p>
| [
{
"answer_id": 74290020,
"author": "David",
"author_id": 328193,
"author_profile": "https://Stackoverflow.com/users/328193",
"pm_score": 2,
"selected": false,
"text": "new ArrayTest1()\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11152509/"
] |
74,290,032 | <p>I have multiple databases setup. I want to change the default folder for migration run i.e. I want that if I run <code>php artisan migrate</code>. It should run the new migrations in <code>/database/migrations/master_database</code> instead of <code>/database/migrations</code> as I have migrations for child databases in main <code>/database/migrations</code> folder which I'm successfully running using <code>php artisan migrate --all</code>.</p>
<p>What I have done in AppServiceProvider:</p>
<p><code>$masterDatabasePath = database_path('migrations/master_database');</code></p>
<p><code>$this->loadMigrationsFrom($masterDatabasePath);</code></p>
<p>It works but it take migrations from both <code>/database/migrations</code> and <code>/database/migrations/master_database</code> folders while I want that it should only take migrations from <code>/database/migrations/master_database</code>.</p>
<p>Any Idea what I'm doing wrong or how it can be fixed?</p>
| [
{
"answer_id": 74290265,
"author": "Ramil Huseynov",
"author_id": 6711823,
"author_profile": "https://Stackoverflow.com/users/6711823",
"pm_score": 0,
"selected": false,
"text": "php artisan make:migration \"create users table\" --path=/var/www/html/custom_migration\n\nphp artisan migrate --path=/var/www/html/custom_migration\n"
},
{
"answer_id": 74300898,
"author": "pasindu",
"author_id": 16484935,
"author_profile": "https://Stackoverflow.com/users/16484935",
"pm_score": 0,
"selected": false,
"text": "AppServiceProvider"
},
{
"answer_id": 74313644,
"author": "Engr. Umar Ejaz",
"author_id": 9833118,
"author_profile": "https://Stackoverflow.com/users/9833118",
"pm_score": -1,
"selected": true,
"text": "vendor\\laravel\\framework\\src\\Illuminate\\Database\\Console\\Migrations\\BaseCommand.php"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9833118/"
] |
74,290,034 | <p>Say, I have an array</p>
<pre><code>a = { 1, 2, 10, 15 }
</code></pre>
<p>I would like to divide each element by 3 and store the result in a new array. Is there a more efficient / elegant way of doing that than this:</p>
<pre><code>b = { }
for i,x in pairs(a) do
b[i] = x / 3
end
</code></pre>
<p>In R, I would simply do <code>b <- a/3</code>. Is there anything like that in lua, or maybe a way of applying a function to each element of a table?</p>
| [
{
"answer_id": 74290586,
"author": "shingo",
"author_id": 6196568,
"author_profile": "https://Stackoverflow.com/users/6196568",
"pm_score": 3,
"selected": true,
"text": "local mt_vectorization = {\n __div = function (dividend, divisor)\n local b = {}\n for i,x in pairs(dividend) do\n b[i] = x / divisor\n end\n return b\n end\n}\n\na = setmetatable({ 1, 2, 10, 15 }, mt_vectorization)\n\nb = a / 3\n"
},
{
"answer_id": 74316413,
"author": "January",
"author_id": 1686814,
"author_profile": "https://Stackoverflow.com/users/1686814",
"pm_score": 0,
"selected": false,
"text": "function map(x, f)\n local ret = { }\n for k, v in pairs(x) do\n ret[k] = f(v)\n end\n return ret\nend\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1686814/"
] |
74,290,042 | <p>I just want to know how to find and replace empty columns into na for a whole data frame</p>
<p>sample data</p>
<pre><code>structure(list(id = structure(8.44425875736171e-318, class = "integer64"),
project_id = 11L, experiment_id = 85L,
gene = "", si = -0.381, pi = ""
on1 = "CC",
on2 = "GG",
on3 = "aa",
created_at = structure(1618862091.85075, class = c("POSIXct",
"POSIXt"), tzone = "UTC")), row.names = c(NA, -1L), class = c("data.table",
"data.frame"), .internal.selfref = <pointer: 0x000001ba09da3590>)
</code></pre>
<p>i have a solution to check for a particular column but i dont how to apply this for whole dataframe</p>
<pre><code>data$gene <- ifelse((is.na(data$gene) == TRUE),'NA',data$gene)
</code></pre>
| [
{
"answer_id": 74290252,
"author": "Quinten",
"author_id": 14282714,
"author_profile": "https://Stackoverflow.com/users/14282714",
"pm_score": 3,
"selected": true,
"text": "lapply"
},
{
"answer_id": 74290382,
"author": "Hansel Palencia",
"author_id": 10897981,
"author_profile": "https://Stackoverflow.com/users/10897981",
"pm_score": 2,
"selected": false,
"text": "dplyr"
},
{
"answer_id": 74291028,
"author": "akrun",
"author_id": 3732271,
"author_profile": "https://Stackoverflow.com/users/3732271",
"pm_score": 2,
"selected": false,
"text": "na_if"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14784770/"
] |
74,290,053 | <p>I have a table of item values with a category of color In row 1 with color codes in the column that correspond to that category. Ex column A is red and in cell A20 is color code 221. But there a some color codes where 221 is red but 222(a slightly more darker tone) is under the brown column even though I would classify it as a red.</p>
<p>The table I have now has color categories in A1:L1 color codes from A2:L67 but most of those cells are blank. Column G has 66 values while Column F only has 23. If that’s going to play a factor.</p>
<p>For ease of sorting these items i would like to use lookup or match to enter in a color code and it give what color category it belongs too. So if I enter color code 321 it would give Brown as the color category. And id rather not just do control F and typing the code to see what column it’s in</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Red</th>
<th>Brown</th>
</tr>
</thead>
<tbody>
<tr>
<td>221</td>
<td>321</td>
</tr>
<tr>
<td>56</td>
<td>788</td>
</tr>
<tr>
<td>334</td>
<td>222</td>
</tr>
<tr>
<td></td>
<td>444</td>
</tr>
<tr>
<td></td>
<td>567</td>
</tr>
</tbody>
</table>
</div><div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Code</th>
<th>Color</th>
</tr>
</thead>
<tbody>
<tr>
<td>321</td>
<td>Brown</td>
</tr>
</tbody>
</table>
</div>
<p>I have watched a few videos on v v lookup and I have tried transposing the table to correspond to the video. But since my idea calls for a variable column index number based on what cell value I give it doesn’t work as I intend. So I’m stuck with that aspect.</p>
| [
{
"answer_id": 74290286,
"author": "Foxfire And Burns And Burns",
"author_id": 9199828,
"author_profile": "https://Stackoverflow.com/users/9199828",
"pm_score": 1,
"selected": false,
"text": "=INDEX($A$1:$C$1;1;SUMPRODUCT(--($A$2:$C$6=A11)*COLUMN($A$1:$C$1)))\n"
},
{
"answer_id": 74290363,
"author": "Harun24hr",
"author_id": 5514747,
"author_profile": "https://Stackoverflow.com/users/5514747",
"pm_score": 2,
"selected": false,
"text": "FILTER()"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6477341/"
] |
74,290,068 | <p>The only way that I succee to update .mat-dialog-container style is by adding ::ng-deep</p>
<pre><code>::ng-deep .mat-dialog-container {
overflow: hidden
}
</code></pre>
<p>as I understand it is recommended to avoid using :ng-deep.</p>
<p>How I can update the style without it?
Thanks</p>
<p><a href="https://i.stack.imgur.com/vLd7j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vLd7j.png" alt="enter image description here" /></a></p>
| [
{
"answer_id": 74290286,
"author": "Foxfire And Burns And Burns",
"author_id": 9199828,
"author_profile": "https://Stackoverflow.com/users/9199828",
"pm_score": 1,
"selected": false,
"text": "=INDEX($A$1:$C$1;1;SUMPRODUCT(--($A$2:$C$6=A11)*COLUMN($A$1:$C$1)))\n"
},
{
"answer_id": 74290363,
"author": "Harun24hr",
"author_id": 5514747,
"author_profile": "https://Stackoverflow.com/users/5514747",
"pm_score": 2,
"selected": false,
"text": "FILTER()"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9088906/"
] |
74,290,080 | <p>I have this dataset where I have some columns (not important to the calculations) and then many columns with same starting name. I want to calculate the sum of those columns per one row which contains else than NaN-value. The set looks something like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>something</th>
<th>number1</th>
<th>number2</th>
<th>number3</th>
<th>number4</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>105</td>
<td>200</td>
<td>NaN</td>
<td>NaN</td>
<td>50</td>
</tr>
<tr>
<td>2</td>
<td>300</td>
<td>2</td>
<td>1</td>
<td>1</td>
<td>33</td>
</tr>
<tr>
<td>3</td>
<td>20</td>
<td>1</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
</tr>
</tbody>
</table>
</div>
<p>So I want to create new column that contains the length of the number columns that have a value. So the final dataset would look like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>id</th>
<th>something</th>
<th>number1</th>
<th>number2</th>
<th>number3</th>
<th>number4</th>
<th>sum_columns</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>105</td>
<td>200</td>
<td>NaN</td>
<td>NaN</td>
<td>50</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>300</td>
<td>2</td>
<td>1</td>
<td>1</td>
<td>33</td>
<td>4</td>
</tr>
<tr>
<td>3</td>
<td>20</td>
<td>1</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>I know I can calculate the length of columns that start by specific name something like this:</p>
<pre><code>df[df.columns[pd.Series(df.columns).str.startswith('number')]]
</code></pre>
<p>but I cant figure out, how can I add condition that there has to be other than NaN value and also how to apply it to every row. I think it could be done with lambda? but haven't succeeded yet.</p>
| [
{
"answer_id": 74290176,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 2,
"selected": true,
"text": "# filter column on 'number' and count\ndf['sum_columns']=df.filter(like='number').count(axis=1)\ndf\n"
},
{
"answer_id": 74290218,
"author": "T C Molenaar",
"author_id": 8814131,
"author_profile": "https://Stackoverflow.com/users/8814131",
"pm_score": 1,
"selected": false,
"text": "df[df.columns[df.columns.str.startswith('number')]]"
},
{
"answer_id": 74290251,
"author": "Will",
"author_id": 12829151,
"author_profile": "https://Stackoverflow.com/users/12829151",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\n\ndf = {'something':[105, 300,20],\n 'number1':[200,2,1],\n 'number2':[np.nan,1,np.nan],\n 'number3':[np.nan,1,np.nan],\n 'number4':[50,33,np.nan]}\n\ndf = pd.DataFrame(df)\n\ntmp = df[df.columns[pd.Series(df.columns).str.startswith('number')]]\n\ndf['sum_columns'] = tmp.notnull().sum(axis=1).tolist()\ndf\n"
},
{
"answer_id": 74290337,
"author": "Gonçalo Peres",
"author_id": 7109869,
"author_profile": "https://Stackoverflow.com/users/7109869",
"pm_score": 0,
"selected": false,
"text": "pandas.DataFrame.iloc"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20339814/"
] |
74,290,108 | <p>I have a dictionary disease_dict with values in a list element. I would like to fetch key and value for specific keys and then check if the value (as a substring) exists in other keys and fetch all the key --> value pair.</p>
<p>For example this is the dictionary. I would like to see if the 'Stroke' or 'stroke' exist in the dictionary and then match if the value of this key is a substring of other value (like 'C10.228.140.300.775' exists in 'C10.228.140.300.275.800', 'C10.228.140.300.775.600')</p>
<pre><code>'Stroke': ['C10.228.140.300.775', 'C14.907.253.855'], 'Stroke, Lacunar': ['C10.228.140.300.275.800', 'C10.228.140.300.775.600', 'C14.907.253.329.800', 'C14.907.253.855.600']
</code></pre>
<p>I have the following lines of code for fetching the key and value for a specific term.</p>
<pre><code>#extract all child terms
for k, v in dis_dict.items():
if (k in ['Glaucoma', 'Stroke']) or (k in ['glaucoma', 'stroke']):
disease = k
tree_id = v
print (disease, tree_id)
else:
disease = ''
tree_id = ''
continue
</code></pre>
<p>Any help is highly appreciated!</p>
| [
{
"answer_id": 74290176,
"author": "Naveed",
"author_id": 3494754,
"author_profile": "https://Stackoverflow.com/users/3494754",
"pm_score": 2,
"selected": true,
"text": "# filter column on 'number' and count\ndf['sum_columns']=df.filter(like='number').count(axis=1)\ndf\n"
},
{
"answer_id": 74290218,
"author": "T C Molenaar",
"author_id": 8814131,
"author_profile": "https://Stackoverflow.com/users/8814131",
"pm_score": 1,
"selected": false,
"text": "df[df.columns[df.columns.str.startswith('number')]]"
},
{
"answer_id": 74290251,
"author": "Will",
"author_id": 12829151,
"author_profile": "https://Stackoverflow.com/users/12829151",
"pm_score": 0,
"selected": false,
"text": "import pandas as pd\nimport numpy as np\n\ndf = {'something':[105, 300,20],\n 'number1':[200,2,1],\n 'number2':[np.nan,1,np.nan],\n 'number3':[np.nan,1,np.nan],\n 'number4':[50,33,np.nan]}\n\ndf = pd.DataFrame(df)\n\ntmp = df[df.columns[pd.Series(df.columns).str.startswith('number')]]\n\ndf['sum_columns'] = tmp.notnull().sum(axis=1).tolist()\ndf\n"
},
{
"answer_id": 74290337,
"author": "Gonçalo Peres",
"author_id": 7109869,
"author_profile": "https://Stackoverflow.com/users/7109869",
"pm_score": 0,
"selected": false,
"text": "pandas.DataFrame.iloc"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12436050/"
] |
74,290,109 | <p>I am using the FortiManager provider and I can create new addresse and assign them as member to a group.</p>
<p>When I remove an addresse from the map, terraform want to delete the addresse before removing it from the group members which cause an error.</p>
<p>I use the "depends_on" parameters on the fortimanager_object_firewall_addrgrp ressource so the fortimanager_object_firewall_address ressource is always done first when creating the deleted last when destroying.</p>
<p>In practice, when removing an object from the addresse_map, I can see terraform is trying to delete first the addresse and then update the group membership which raised an error.</p>
<p>How can I order it correctly ?</p>
<pre><code>addresses_map = {
"terra-test1" = {
ip = "10.10.20.11"
mask = "255.255.255.255"
}
"terra-test2" = {
ip = "10.10.20.12"
mask = "255.255.255.255"
}
"terra-test3" = {
ip = "10.10.20.13"
mask = "255.255.255.255"
}
# "terra-test4" = {
# ip = "10.10.20.14"
# mask = "255.255.255.255"
# }
}
</code></pre>
<pre><code>variable "addresses_map" {
type = map (object({
ip = string,
mask = string
}))
}
</code></pre>
<pre><code># Provider declaration
terraform {
required_providers {
fortimanager = {
source = "fortinetdev/fortimanager"
}
}
}
# Configure the Provider for FortiManager
provider "fortimanager" {
...
}
# Manage addresses
resource "fortimanager_object_firewall_address" "address" {
for_each = var.addresses_map
name = each.key
obj_type = "ip"
subnet = [
each.value.ip,
each.value.mask,
]
type = "ipmask"
}
# Manage addresse group
resource "fortimanager_object_firewall_addrgrp" "group" {
allow_routing = "disable"
member = [for k, v in var.addresses_map : k]
name = "terraform-addrgrp4"
depends_on = [
fortimanager_object_firewall_address.address
]
}
</code></pre>
<p>Thank you</p>
<p>I tried using direct reference of ressource in the member list like this :</p>
<pre><code> member = [for k, v in var.addresses_map : fortimanager_object_firewall_address.address[k].name]
</code></pre>
<p>But issue still the same :</p>
<pre><code>$ terraform apply
fortimanager_object_firewall_address.address["terra-test2"]: Refreshing state... [id=terra-test2]
fortimanager_object_firewall_address.address["terra-test1"]: Refreshing state... [id=terra-test1]
fortimanager_object_firewall_address.address["terra-test4"]: Refreshing state... [id=terra-test4]
fortimanager_object_firewall_address.address["terra-test3"]: Refreshing state... [id=terra-test3]
fortimanager_object_firewall_addrgrp.group: Refreshing state... [id=terraform-addrgrp4]
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
~ update in-place
- destroy
Terraform will perform the following actions:
# fortimanager_object_firewall_address.address["terra-test4"] will be destroyed
# (because key ["terra-test4"] is not in for_each map)
- resource "fortimanager_object_firewall_address" "address" {
- allow_routing = "disable" -> null
- associated_interface = "any" -> null
- cache_ttl = 0 -> null
- clearpass_spt = "unknown" -> null
- color = 0 -> null
- dynamic_sort_subtable = "false" -> null
- end_mac = "00:00:00:00:00:00" -> null
- fabric_object = "disable" -> null
- global_object = 0 -> null
- id = "terra-test4" -> null
- macaddr = [] -> null
- name = "terra-test4" -> null
- obj_type = "ip" -> null
- scopetype = "inherit" -> null
- start_mac = "00:00:00:00:00:00" -> null
- subnet = [
- "10.10.20.14",
- "255.255.255.255",
] -> null
- type = "ipmask" -> null
- uuid = "5515194c-5aa5-51ed-6639-28f8c5f94598" -> null
}
# fortimanager_object_firewall_addrgrp.group will be updated in-place
~ resource "fortimanager_object_firewall_addrgrp" "group" {
id = "terraform-addrgrp4"
~ member = [
# (2 unchanged elements hidden)
"terra-test3",
- "terra-test4",
]
name = "terraform-addrgrp4"
# (10 unchanged attributes hidden)
}
Plan: 0 to add, 1 to change, 1 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
fortimanager_object_firewall_address.address["terra-test4"]: Destroying... [id=terra-test4]
╷
│ Error: Error deleting ObjectFirewallAddress resource:
│ err -10015: used
</code></pre>
| [
{
"answer_id": 74290503,
"author": "Marko E",
"author_id": 8343484,
"author_profile": "https://Stackoverflow.com/users/8343484",
"pm_score": 1,
"selected": false,
"text": "# Manage addresses\nresource \"fortimanager_object_firewall_address\" \"address\" {\n for_each = var.addresses_map\n name = each.key\n obj_type = \"ip\"\n subnet = [\n each.value.ip,\n each.value.mask,\n ]\n type = \"ipmask\"\n}\n\n # Manage addresse group\nresource \"fortimanager_object_firewall_addrgrp\" \"group\" {\n allow_routing = \"disable\"\n member = keys(fortimanager_object_firewall_address.address)\n name = \"terraform-addrgrp4\"\n}\n"
},
{
"answer_id": 74303058,
"author": "Pascal",
"author_id": 20398069,
"author_profile": "https://Stackoverflow.com/users/20398069",
"pm_score": 0,
"selected": false,
"text": "lifecycle {\n create_before_destroy = true\n}\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20398069/"
] |
74,290,123 | <p>I am facing problem in allocating matrix using vector library globally.
However, in my code, I am allocating vector as an array, which you can see below.</p>
<pre><code>matrix = new double*[row*col];
for (int i = 0; i < row*col; i++){
Matrix[i] = new double[col];
}
</code></pre>
<p>Please suggest a possible way to allocate matrix globally (preferably using build-in vector or user classes)</p>
<pre><code>matrix = new double*[row*col];
for (int i = 0; i < row*col; i++){
Matrix[i] = new double[col];
}
</code></pre>
| [
{
"answer_id": 74290194,
"author": "A M",
"author_id": 9666018,
"author_profile": "https://Stackoverflow.com/users/9666018",
"pm_score": 2,
"selected": false,
"text": "std::vector"
},
{
"answer_id": 74290549,
"author": "Nikola",
"author_id": 9835141,
"author_profile": "https://Stackoverflow.com/users/9835141",
"pm_score": 0,
"selected": false,
"text": "double matrix[row*col];\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19923996/"
] |
74,290,125 | <p>I’m trying to make 6 dots along a line(0, random(height), width, random(height)). The dots should be evenly spaced.</p>
| [
{
"answer_id": 74290312,
"author": "nikname",
"author_id": 20398320,
"author_profile": "https://Stackoverflow.com/users/20398320",
"pm_score": 0,
"selected": false,
"text": "point(0, random(height))\npoint(width/5, random(height))\npoint(width/5*2, random(height))\npoint(width/5*3, random(height))\npoint(width/5*4, random(height))\npoint(width, random(height))\n"
},
{
"answer_id": 74291372,
"author": "George Profenza",
"author_id": 89766,
"author_profile": "https://Stackoverflow.com/users/89766",
"pm_score": 2,
"selected": true,
"text": "lerp(start, end, t)"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20398170/"
] |
74,290,189 | <p>Perhaps I am missing something or tried something improperly, but I thought I would reach out.</p>
<p>I have a singleton service that I want to create multiple times. The service has the same logic except for a configuration parameter. So I want to inject a parameter at runtime into the service constructor.</p>
<p>Is this possible, or will I have to do something more elaborate?</p>
<p>Thanks for your input.</p>
<p>For example…</p>
<pre><code>
</code></pre>
<pre><code>// I am creating three different configurations
services.Configure<ProfileCacheOptions>(
ProfileCacheOptions.Key1,
config.GetSection(ProfileCacheOptions.Key1));
services.Configure<ProfileCacheOptions>(
ProfileCacheOptions.Key2,
config.GetSection(ProfileCacheOptions.Key2));
services.Configure<ProfileCacheOptions>(
ProfileCacheOptions.Key2,
config.GetSection(ProfileCacheOptions.Key3));
.
.
.
// I have tried multiple ways to inject a parameter, but as you can see
// my last attempt was a simple string representing the key
services.AddSingleton<ICachedDataSource<Class1>,
MemoryCacheData<Class1>>(ProfileCacheOptions.Key1);
services.AddSingleton<ICachedDataSource<Class2>,
MemoryCacheData<Class2>>(ProfileCacheOptions.Key2);
services.AddSingleton<ICachedDataSource<Class3>,
MemoryCacheData<Class3>>(ProfileCacheOptions.Key3);
// The proposed argument, whatever it may be
public MemoryCacheData(
IMemoryCache cache,
IOptionsSnapshot<CachedDataBaseClassOptions> options,
string TheArgument
{
_options = options.Get(TheArgument);
}
</code></pre>
<pre><code>
</code></pre>
<p>I have tried creating an argument class and multiple attempts to create a runtime injected parameter.</p>
| [
{
"answer_id": 74290312,
"author": "nikname",
"author_id": 20398320,
"author_profile": "https://Stackoverflow.com/users/20398320",
"pm_score": 0,
"selected": false,
"text": "point(0, random(height))\npoint(width/5, random(height))\npoint(width/5*2, random(height))\npoint(width/5*3, random(height))\npoint(width/5*4, random(height))\npoint(width, random(height))\n"
},
{
"answer_id": 74291372,
"author": "George Profenza",
"author_id": 89766,
"author_profile": "https://Stackoverflow.com/users/89766",
"pm_score": 2,
"selected": true,
"text": "lerp(start, end, t)"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14422586/"
] |
74,290,201 | <p>We are reading files from ADLS through this kind of command:</p>
<pre><code>relative_path = "ContainerName/"
input_file_name = "ss_old_data_Amazon_Blast_202211093837474.csv"
</code></pre>
<p>How can we fetch a substring from a file name that we are getting for processing.</p>
<pre class="lang-none prettyprint-override"><code>For example:
1st filename: vm_Path_Accenture_Complex_Union_202211027373.csv
2nd filename: vm_path_Google_is_a_good_company_20221109473.csv
3rd filename: ss_old_data_Amazon_Blast_202211093837474.csv
4th filename: ss_old_data_Black_Adam_(TY)_2022847093837474.csv
5th filename: ss_old_data_Man_of_steel_(PQ)_2022847093837474.csv
</code></pre>
<p>We need to pick specific substring from the filename and remove <code>_</code> from substring and make it upper case. I don't need to pick the date format (numbers) or <code>.csv</code> - just the company name.
<code>vm_path</code> will be there at the beginning for most of the files, and sometimes <code>ss_old_data</code>. We need to remove this part too.</p>
<pre class="lang-none prettyprint-override"><code>Expected output:
1st filename should become: ACCENTURECOMPLEXUNION
2nd filename should become: GOOGLEISAGOODCOMPANY
3rd filename should become: AMAZONBLAST
4th filename should become : BLACKADAM
5th filename should become: MANOFSTEEL
</code></pre>
<p>How can we achieve it in PySpark?</p>
| [
{
"answer_id": 74291467,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 0,
"selected": false,
"text": "str.replace"
},
{
"answer_id": 74292287,
"author": "ZygD",
"author_id": 2753501,
"author_profile": "https://Stackoverflow.com/users/2753501",
"pm_score": 2,
"selected": true,
"text": "lit"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20216373/"
] |
74,290,220 | <p>I have a list like this:</p>
<pre><code>list = [{"name": "name1", "zipcode": "zipcode1", "id": "id1"},{"name": "name2", "zipcode": "zipcode2", "id": "id2"}, {"name": "name1", "zipcode": "zipcode3", "id": "id1"}]
</code></pre>
<p>I want to remove dicts which has same ids. I know how to remove duplicates but notice they are not duplicates, they have different zipcodes.</p>
<p>I expect this:</p>
<pre><code>list2 = [{"name": "name1", "zipcode": "zipcode1", "id": "id1"},{"name": "name2", "zipcode": "zipcode2", "id": "id2"}
</code></pre>
| [
{
"answer_id": 74291467,
"author": "Tim Biegeleisen",
"author_id": 1863229,
"author_profile": "https://Stackoverflow.com/users/1863229",
"pm_score": 0,
"selected": false,
"text": "str.replace"
},
{
"answer_id": 74292287,
"author": "ZygD",
"author_id": 2753501,
"author_profile": "https://Stackoverflow.com/users/2753501",
"pm_score": 2,
"selected": true,
"text": "lit"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18805039/"
] |
74,290,233 | <p>I have recently started learning Haskell and had some questions about ghci> prompt vs prelude> prompt?</p>
<p>When typing ghci i get this:</p>
<pre><code>ghci
GHCi, version 9.2.4: https://www.haskell.org/ghc/ :? for help
ghci>
</code></pre>
<p>when checking documentation I see things like this:</p>
<pre><code> $ ghci
GHCi, version 6.12.3: http://www.haskell.org/ghc/ :? for help
Loading package base ... linking ... done.
Prelude>
</code></pre>
<p>also in addition to this I do not get into a module once I've loaded it</p>
<pre><code>ghci> :load main
[1 of 1] Compiling Main ( main.hs, interpreted )
Ok, one module loaded.
ghci>
</code></pre>
<p>should look something like this?</p>
<pre><code>ghci> :load main
[1 of 1] Compiling Main ( main.hs, interpreted )
Ok, one module loaded.
*Main>
</code></pre>
<p>I have tried looking online, tried compiling the program</p>
| [
{
"answer_id": 74290263,
"author": "Noughtmare",
"author_id": 15207568,
"author_profile": "https://Stackoverflow.com/users/15207568",
"pm_score": 2,
"selected": false,
"text": "ghci>"
},
{
"answer_id": 74290347,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 2,
"selected": false,
"text": "ghci>"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20397507/"
] |
74,290,254 | <p>I am new to Laravel and looked already for a similiar thread but I didnt find something.
I want to use Eloquent and I got 3 Models and Tables: Testseries, Devices and Users.</p>
<p>The Users has a many to many relation to devices. (One User has many devices and vica versa)
And Devices has a one to many relation to testseries. (One Device has many testseries and many testeries has one device)</p>
<p>**
Table structure Users:**</p>
<pre><code>id
username
</code></pre>
<p><strong>Table structure Devices:</strong></p>
<pre><code>id
serial_number <-- its a string, not important for the structure
</code></pre>
<p><strong>Table structure Testseries:</strong></p>
<pre><code>id
device_id
</code></pre>
<p>Devices and Users are connected via Pivot</p>
<p><strong>device_user:</strong></p>
<pre><code>id
user_id
device_id
</code></pre>
<p>If a User is logged in, I want to show all Testseries from all Devices that are connected to the User.</p>
<p>I defined in the User Model:</p>
<pre><code>public function devices(): \Illuminate\Database\Eloquent\Relations\BelongsToMany {
return $this->belongsToMany(Device::class);
}
</code></pre>
<p>And in the Device Model:</p>
<pre><code>public function users(): \Illuminate\Database\Eloquent\Relations\BelongsToMany {
return $this->belongsToMany(User::class);
}
public function testseries(): \Illuminate\Database\Eloquent\Relations\HasMany {
return $this->hasMany(Testserie::class);
}
</code></pre>
<p>Is there any way to create function inside the User Model which can easily access to the testserie?</p>
<p>If someone doesnt understand what I want because my English isnt good. This function should tell what I want inside the User Model:</p>
<pre><code>public function testseries() {
return $this->devices()->testseries();
}
</code></pre>
<p>Also I want all testseries at one query.</p>
<p>I tried with the each method. But its doing for each device a single query to the testserie.</p>
<p>I also tried it with the with method. It works, but I want all Columns from the Testseries Table, but then I have to tell all table names inside the array and I dont want the columns from the Devices table.</p>
<p>I expected to get a query when I call the ->get Method that I'll get all Testseries at once with a single query.</p>
| [
{
"answer_id": 74290263,
"author": "Noughtmare",
"author_id": 15207568,
"author_profile": "https://Stackoverflow.com/users/15207568",
"pm_score": 2,
"selected": false,
"text": "ghci>"
},
{
"answer_id": 74290347,
"author": "Willem Van Onsem",
"author_id": 67579,
"author_profile": "https://Stackoverflow.com/users/67579",
"pm_score": 2,
"selected": false,
"text": "ghci>"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17692831/"
] |
74,290,259 | <p>I wanted to count the number of three way conversations that have occured in a dataset.
A chat <code>group_x</code> can consist of multiple members.</p>
<p>What is a three way conversation?</p>
<ol>
<li>1st way - <code>red</code>_x sends a message in the group_x.</li>
<li>2nd way - <code>green</code>_x replies in the same group_x.</li>
<li>3rd way - <code>red</code>_x sends a reply in the same group_x.</li>
</ol>
<p>This can be called a three way conversation.</p>
<p>The sequence has to be exactly red_#, green_#, red_#.</p>
<p>What is touchpoint?</p>
<ol>
<li>Touchpoint 1 - red_x's first message.</li>
<li>Touchpoint 2 - green_x's first message.</li>
<li>Touchpoint 3 - red_x's second message.</li>
</ol>
<p>Code to easily generate a sample dataset I'm working with.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
from pandas import Timestamp
t1_df = pd.DataFrame({'from_red': [True, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, False, True],
'sent_time': [Timestamp('2021-05-01 06:26:00'), Timestamp('2021-05-04 10:35:00'), Timestamp('2021-05-07 12:16:00'), Timestamp('2021-05-07 12:16:00'), Timestamp('2021-05-09 13:39:00'), Timestamp('2021-05-11 10:02:00'), Timestamp('2021-05-12 13:10:00'), Timestamp('2021-05-12 13:10:00'), Timestamp('2021-05-13 09:46:00'), Timestamp('2021-05-13 22:30:00'), Timestamp('2021-05-14 14:14:00'), Timestamp('2021-05-14 17:08:00'), Timestamp('2021-06-01 09:22:00'), Timestamp('2021-06-01 21:26:00'), Timestamp('2021-06-03 20:19:00'), Timestamp('2021-06-03 20:19:00'), Timestamp('2021-06-09 07:24:00'), Timestamp('2021-05-01 06:44:00'), Timestamp('2021-05-01 08:01:00'), Timestamp('2021-05-01 08:09:00')],
'w_uid': ['w_000001', 'w_112681', 'w_002516', 'w_002514', 'w_004073', 'w_005349', 'w_006803', 'w_006804', 'w_008454', 'w_009373', 'w_010063', 'w_010957', 'w_066840', 'w_071471', 'w_081446', 'w_081445', 'w_106472', 'w_000002', 'w_111906', 'w_000003'],
'user_id': ['red_00001', 'green_0263', 'red_01071', 'red_01071', 'red_01552', 'red_01552', 'red_02282', 'red_02282', 'red_02600', 'red_02854', 'red_02854', 'red_02600', 'red_00001', 'red_09935', 'red_10592', 'red_10592', 'red_12292', 'red_00002', 'green_0001', 'red_00003'],
'group_id': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
'touchpoint': [1, 2, 1, 3, 1, 3, 1, 3, 1, 1, 3, 3, 3, 1, 1, 3, 1, 1, 2, 1]},
columns = ['from_red', 'sent_time', 'w_uid', 'user_id', 'group_id', 'touchpoint'])
t1_df['sent_time'] = pd.to_datetime(t1_df['sent_time'], format = "%d-%m-%Y")
t1_df
</code></pre>
<p>The dataset looks like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>from_red</th>
<th>sent_time</th>
<th>w_uid</th>
<th>user_id</th>
<th>group_id</th>
<th>touchpoint</th>
</tr>
</thead>
<tbody>
<tr>
<td>True</td>
<td>2021-05-01 06:26:00</td>
<td>w_000001</td>
<td>red_00001</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>False</td>
<td>2021-05-04 10:35:00</td>
<td>w_112681</td>
<td>green_0263</td>
<td>0</td>
<td>2</td>
</tr>
<tr>
<td>True</td>
<td>2021-05-07 12:16:00</td>
<td>w_002516</td>
<td>red_01071</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>True</td>
<td>2021-05-07 12:16:00</td>
<td>w_002514</td>
<td>red_01071</td>
<td>0</td>
<td>3</td>
</tr>
<tr>
<td>True</td>
<td>2021-05-09 13:39:00</td>
<td>w_004073</td>
<td>red_01552</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>True</td>
<td>2021-05-11 10:02:00</td>
<td>w_005349</td>
<td>red_01552</td>
<td>0</td>
<td>3</td>
</tr>
<tr>
<td>True</td>
<td>2021-05-12 13:10:00</td>
<td>w_006803</td>
<td>red_02282</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>True</td>
<td>2021-05-12 13:10:00</td>
<td>w_006804</td>
<td>red_02282</td>
<td>0</td>
<td>3</td>
</tr>
<tr>
<td>True</td>
<td>2021-05-13 09:46:00</td>
<td>w_008454</td>
<td>red_02600</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>True</td>
<td>2021-05-13 22:30:00</td>
<td>w_009373</td>
<td>red_02854</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>True</td>
<td>2021-05-14 14:14:00</td>
<td>w_010063</td>
<td>red_02854</td>
<td>0</td>
<td>3</td>
</tr>
<tr>
<td>True</td>
<td>2021-05-14 17:08:00</td>
<td>w_010957</td>
<td>red_02600</td>
<td>0</td>
<td>3</td>
</tr>
<tr>
<td>True</td>
<td>2021-06-01 09:22:00</td>
<td>w_066840</td>
<td>red_00001</td>
<td>0</td>
<td>3</td>
</tr>
<tr>
<td>True</td>
<td>2021-06-01 21:26:00</td>
<td>w_071471</td>
<td>red_09935</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>True</td>
<td>2021-06-03 20:19:00</td>
<td>w_081446</td>
<td>red_10592</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>True</td>
<td>2021-06-03 20:19:00</td>
<td>w_081445</td>
<td>red_10592</td>
<td>0</td>
<td>3</td>
</tr>
<tr>
<td>True</td>
<td>2021-06-09 07:24:00</td>
<td>w_106472</td>
<td>red_12292</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>True</td>
<td>2021-05-01 06:44:00</td>
<td>w_000002</td>
<td>red_00002</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>False</td>
<td>2021-05-01 08:01:00</td>
<td>w_111906</td>
<td>green_0001</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>True</td>
<td>2021-05-01 08:09:00</td>
<td>w_000003</td>
<td>red_00003</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
<p>Here is what I have tried, but the query is taking too long. Is there a faster way to achieve the same?</p>
<pre class="lang-py prettyprint-override"><code>test_df = pd.DataFrame()
for i in range(len(t1_df['sent_time'])-1):
if t1_df.query(f"group_id == {i}")['from_red'].nunique() == 2:
y = t1_df.query(f"group_id == {i} & touchpoint == 2").loc[:, ['sent_time']].values[0][0]
x = t1_df.query(f"group_id == {i} & sent_time > @y & (touchpoint == 3)").sort_values('sent_time')
test_df = pd.concat([test_df, x])
test_df.merge(x, how = "outer")
else:
pass
test_df
</code></pre>
| [
{
"answer_id": 74325027,
"author": "Pavloski",
"author_id": 19665312,
"author_profile": "https://Stackoverflow.com/users/19665312",
"pm_score": 2,
"selected": false,
"text": ".groupby"
},
{
"answer_id": 74401453,
"author": "Andrew",
"author_id": 15330539,
"author_profile": "https://Stackoverflow.com/users/15330539",
"pm_score": 2,
"selected": true,
"text": "input"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16115829/"
] |
74,290,275 | <p>Recently I updated Python version Python 3.9.14 from Python3.6.
I am running django project, so while running it and also while installing any dependencies, getting this error message - ModuleNotFoundError: No module named 'pip._internal'
How to solve this.
Getting the below error for <code>pip3 version</code>:</p>
<pre><code>Traceback (most recent call last):
File "/usr/local/bin/pip3", line 5, in <module>
from pip._internal.cli.main import main
ModuleNotFoundError: No module named 'pip._internal'
</code></pre>
<p>I tried <code>python3 -m pip3 install --upgrade pip3</code> , but I got:</p>
<pre><code>/usr/bin/python3: No module named pip
/usr/bin/python3: No module named pip3
</code></pre>
<p>Thank you</p>
| [
{
"answer_id": 74325027,
"author": "Pavloski",
"author_id": 19665312,
"author_profile": "https://Stackoverflow.com/users/19665312",
"pm_score": 2,
"selected": false,
"text": ".groupby"
},
{
"answer_id": 74401453,
"author": "Andrew",
"author_id": 15330539,
"author_profile": "https://Stackoverflow.com/users/15330539",
"pm_score": 2,
"selected": true,
"text": "input"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16898710/"
] |
74,290,277 | <p>So in a React project I have a line:</p>
<pre><code><div className="star-rating fas fa-star">{data?.starRating}</div>
</code></pre>
<p>This returns a Number between 1-5, but how do I replace that Number with a number of Star Icons? For example, a 3 Returns 3 Stars, 4 Returns 4 Stars etc.</p>
<p>Currently the CSS for this:</p>
<pre><code>.star-rating{
float: right;
width: 50%;
margin-bottom: 1em;
font-family: FontAwesome;
content: "\f005";
font-size: 1.5em;
color: #FFD700;
}
</code></pre>
<p>But all this does is make the Number Yellow and not replace it with any icon</p>
| [
{
"answer_id": 74290465,
"author": "caTS",
"author_id": 18244921,
"author_profile": "https://Stackoverflow.com/users/18244921",
"pm_score": 2,
"selected": false,
"text": "repeat"
},
{
"answer_id": 74291408,
"author": "Oleg Brazhnichenko",
"author_id": 7028321,
"author_profile": "https://Stackoverflow.com/users/7028321",
"pm_score": 1,
"selected": false,
"text": "<div className=\"star-rating fas fa-star\">\n {data?.starRating.map(_ => (\n <YourStarComponent />\n ))}\n</div>\n"
}
] | 2022/11/02 | [
"https://Stackoverflow.com/questions/74290277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12694209/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.