instruction
stringlengths
0
30k
The STRICT_TRANS_TABLES sql_mode (which *should* be used wherever possible) unfortunately promotes some warnings to errors when in an insert/update/etc, even where you guard against it with checking the results of a function call. You could temporarily disable it before your update: set session sql_mode=replace(@@sql_mode, 'STRICT_TRANS_TABLES', ''); update ... set session sql_mode=concat(@@sql_mode, ',STRICT_TRANS_TABLES'); but I prefer using a regexp (as you suggest).
To group by `tagValue`, since this is an array field, you need to apply the [`$unwind`][1] pipeline step before the group to split the array so that you can get the actual count: db.feed.aggregate([ {'$unwind': '$feedTag'}, {'$group': { '_id': '$feedTag.tagValue', 'number': { '$sum' : 1 } }}, {'$sort': { '_id' : 1 }} ]) The following is the equivalent example in **[Spring Data MongoDB][2]**: import static org.springframework.data.mongodb.core.aggregation.Aggregation.*; Aggregation agg = newAggregation( unwind("feedTag"), group("feedTag.tagValue").count().as("number"), sort(ASC, "_id") ); // Convert the aggregation result into a List AggregationResults<Feed> results = mongoTemplate.aggregate(agg, "feed", Feed.class); List<Feed> feedCount = results.getMappedResults(); From the above, a new aggregation object is created via the **[`newAggregation`][3]** static factory method which is passed a list of aggregation operations that define the aggregation pipeline of your Aggregation. The firt step uses the unwind operation to generate a new document for each tag within the "feedTag" array. In the second step the group operation defines a group for each embedded `"feedTag.tagValue"`-value for which the occurrence count is aggregated via the count aggregation operator. As the third step, sort the resulting list of **`feedTag`** by their **`tagValue`** in ascending order via the sort operation. Finally call the aggregate Method on the MongoTemplate to let MongoDB perform the actual aggregation operation with the created Aggregation as an argument. Note that the input collection is explicitly specified as the `"feed"` parameter to the aggregate Method. If the name of the input collection is not specified explicitly, it is derived from the input-class passed as first parameter to the newAggreation Method. [1]: http://docs.mongodb.org/manual/reference/operator/aggregation/unwind [2]: http://docs.spring.io/spring-data/mongodb/docs/1.3.x/reference/html/mongo.core.html [3]: http://docs.spring.io/spring-data/data-mongodb/docs/current/api/org/springframework/data/mongodb/core/aggregation/Aggregation.html#newAggregation-org.springframework.data.mongodb.core.aggregation.AggregationOperation...-
I am building a simple budget tracker, and I'd like to let user to filter by apps name. Below is my code. ```json [ { "status": "on", "id": "NZMwD83Nxg", "name": "GTA_UA_UAC_Android_01_DAU", "dailyBudget": 800, "apps": [ { "name": "app 1", "icon": "https://marketing-0-7-0-85-220.png/230x0w.webp" }, { "name": "app 2", "icon": "https://marketing-0-7-0-99-220.png/230x0w.webp" } ], "currency": "USD", }, { "status": "on", "id": "aXly0x0vX6", "name": "GTA_UA_UAC_Android_02_DAU", "dailyBudget": 65, "apps": [ { "name": "app 3", "icon": "https://marketing-0-7-0-85-220.png/230x0w.webp" } ], "currency": "USD", } ] ``` And this is my column type. ```javascript type AppsType = { name: string; icon: string; }; export type MainCampaign = { id: string; name: string; status: string; apps: AppsType[]; dailyBudget: number; currency: string; }; export const columns: ColumnDef<MainCampaign>[] = [ { accessorKey: "icon", header: ({ column }) => ( <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} > Apps <ArrowUpDown className="ml-2 h-4 w-4" /> </Button> ), cell: ({ row }) => { const apps: AppsType[] = row.getValue("apps"); return ( <div style={{ display: "flex", gap: "10px" }}> {apps.map((app, index) => ( <Avatar key={index}> <AvatarImage src={app.icon} alt={app.name} /> <AvatarFallback>{app.name}</AvatarFallback> </Avatar> ))} </div> ); }, }, { accessorKey: "apps", header: ({ column }) => ( <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} > App Names <ArrowUpDown className="ml-2 h-4 w-4" /> </Button> ), cell: ({ row }) => { const apps: AppsType[] = row.getValue("apps"); return apps.map((app, index) => <div key={index}>{app.name}</div>); }, }, { accessorKey: "name", header: ({ column }) => { return ( <Button variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} > Campaign Name <ArrowUpDown className="ml-2 h-4 w-4" /> </Button> ); }, }, ... ] ``` This is my Input inside data-table for now, and it's worked when using `apps`, no result after typing. ```javascript <div className="flex items-center py-4"> <Input id="filter-app" placeholder="Filter App..." value={table.getColumn("apps")?.getFilterValue()?.toString() ?? ""} onChange={(event) => table.getColumn("apps")?.setFilterValue(event.target.value) } className="max-w-sm" /> </div> ``` I have logged the app names, and the result looks like this: ["app1", "app2"], ["app3"]. My initial thought was to check if they include the filter value, then return the string, but I got stuck when implementing the function. Would really appreciate your guidance.
I'm currently working on a CSS layout where I have a **fixed parent div** containing another div. I want the inner div to be **fixed relative to the body**, not its parent. Code (Tailwind): ``` <div class="h-screen bg-red-100"> <div class="fixed left-1/2 top-1/2 h-80 w-80 -translate-x-1/2 -translate-y-1/2 bg-red-300"> <div class="fixed top-10 h-40 w-40 bg-red-600">I want to make this div fixed relative to body</div> </div> </div> ``` [Tailwind Playground][1] Is there a way to achieve this without JavaScript? If not, how can I accomplish it using JavaScript? I've also researched extensively and searched on Stack Overflow, but I couldn't find a solution that fits my exact requirements. Thank you! [1]: https://play.tailwindcss.com/mebT9Uz05X
I have a firebase project. I am calling an external api via cloud function in the hope the api key (stored in env variable) will be less discoverable. While I have managed to get the following code working in the emulator, it doesn't work after deployment. ``` const {onRequest} = require("firebase-functions/v2/https"); const fetch = require("node-fetch"); const makeRequest = async (req, res) => { const apiKey = process.env.KEY1; const apiUrl = `[externalAPIurl]&key=${apiKey}`; try { const response = await fetch(apiUrl); const data = await response.json(); res.set("Content-Type", "application/json"); res.status(200).send(JSON.stringify(data)); } catch (error) { console.error("Error:", error); res.status(500).send("Internal Server Error"); } }; exports.helloWorld = onRequest(makeRequest); ``` Postman tells me that it's a lack of authentication being passed in the header (error 403). I have struggled to adapt existing code (Google samples/turtorials, and community-provided excerpts). For example: 1. The following excludes req, res parameters and isn't obviously amenable to calling an external api (url) https://cloud.google.com/functions/docs/samples/functions-bearer-token?hl=en 2. The following documents how one might create authenticated functions: https://stackoverflow.com/questions/57589339/how-to-invoke-authenticated-functions-on-gcp-cloud-functions But the linked documentation suggests the approach is for development purposes (only?): https://cloud.google.com/functions/docs/securing/authenticating 3. This is very close, but is 1st gen and lacks the external api call: https://github.com/firebase/functions-samples/blob/main/Node-1st-gen/authorized-https-endpoint/functions/index.js For context, the plan is to anonymously authenticate all users of the website. If anyone can point me in the right direction, that would be sweet.
{"OriginalQuestionIds":[48304195],"Voters":[{"Id":11107541,"DisplayName":"starball","BindingReason":{"GoldTagBadge":"visual-studio-code"}}]}
**Description:** I recently completed my first JavaScript project, a Pomodoro clock, without relying on tutorials. I'd like feedback on my code to improve my skills further. Here's a detailed overview of how I implemented it: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> console.log("Happy Coding, with Pomodoro Timer!"); const break_time_adjustments = () => { // Getting all elements to set the length of Break const increase_break_time_button = document.querySelector( ".break-length-div .value-adjustment .plus" ), decrease_break_time_button = document.querySelector( ".break-length-div .value-adjustment .minus" ), break_time_value = document.querySelector( ".break-length-div .value-adjustment .minutes" ); // Performing Operations on the elements let break_time = 5; break_time_value.innerHTML = break_time; // Getter function to retrieve the current brake time const get_break_time = () => break_time; // Setter funtion to set the update the break time and display it const set_break_time = (new_time) => { break_time = new_time; break_time_value.innerHTML = break_time; }; // Increasing the length of Break function increase_break_time() { set_break_time(break_time + 5); // Increasing the break time by 5 } increase_break_time_button.addEventListener("click", increase_break_time); // Decreasing the length of Break function decrease_break_time() { if (break_time <= 0) { break_time = 0; } else { set_break_time(break_time - 5); // Decreasing the break time by 5 } } decrease_break_time_button.addEventListener("click", decrease_break_time); return { get_break_time, set_break_time }; }; const { get_break_time, set_break_time } = break_time_adjustments(); break_time_adjustments(); const session_time_adjustments = () => { // Getting all elements to set the length of a session const increase_session_time_button = document.querySelector( ".session-length-div .value-adjustment .plus" ), decrease_session_time_button = document.querySelector( ".session-length-div .value-adjustment .minus" ), session_time_value = document.querySelector( ".session-length-div .value-adjustment .minutes" ); // Performing Operations on the elements let session_time = 25; session_time_value.innerHTML = session_time; // Getter function to retrieve the current session time const get_session_time = () => session_time; // Setter function to update the session time and display it const set_session_time = (newTime) => { session_time = newTime; session_time_value.innerHTML = session_time; }; // Increasing the length of Session function increase_session_time() { set_session_time(session_time + 5); // Increasing length of Session time by 5 } increase_session_time_button.addEventListener("click", increase_session_time); // Decreasing the length of Session function decrease_session_time() { if (session_time <= 0) { session_time = 0; } else { set_session_time(session_time - 5); // Decreasing length of Session time by 5 } } decrease_session_time_button.addEventListener("click", decrease_session_time); // Return getter and setter functions return { get_session_time, set_session_time }; }; const { get_session_time, set_session_time } = session_time_adjustments(); // Initializing a variable to store session interval id let session_interval_id; const update_time = (session_duration) => { // Getting elements to update the Time const Time = document.querySelector(".time"); const heading = document.querySelector(".session .heading"); heading.innerHTML = "Session"; let minutes = session_duration; let seconds = 0; // Updating Time const timer = setInterval(() => { if (minutes === 0 && seconds === 0) { clearInterval(timer); // Stop the timer when it reaches 0 break_time(get_break_time()); // Start the break // break_time(1); // For testing return; } if (seconds === 0) { minutes--; seconds = 59; } else { seconds--; } Time.innerHTML = `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`; }, 1000); session_interval_id = timer; return timer; }; // Initializing a varibale to store break time interval id let break_interval_id; const break_time = (break_duration_time) => { //Getting elements to start break time const Time = document.querySelector(".time"); const heading = document.querySelector(".session .heading"); heading.innerHTML = "Break"; // Starting Break time let break_duration = break_duration_time; let minutes = break_duration; let seconds = 0; const break_timer = setInterval(() => { if (minutes === 0 && seconds === 0) { clearInterval(break_timer); // Stop the timer when it reaches 0 update_time(get_session_time()); // update_time(1); // For Testing return; } if (seconds === 0) { minutes--; seconds = 59; } else { seconds--; } Time.innerHTML = `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`; }, 1000); break_interval_id = break_timer; return break_timer; }; const start = () => { // Getting elements to start the clock const start_button = document.querySelector(".controls .start-button button"); // Flag to check if previous session is already running let is_session_running = false; // Starting the clock function start_clock() { if (is_session_running) { clearInterval(session_interval_id); // Clearing previous session clearInterval(break_interval_id); // Clearing previous break } update_time(get_session_time()); // update_time(1); // For Testing is_session_running = true; } start_button.addEventListener("click", start_clock); }; start(); const stop = () => { // Getting Elements to stop the clock const reset_button = document.querySelector(".controls .reset-button button"); const heading = document.querySelector(".session .heading"); const Timer = document.querySelector(".session .time"); // Adding funcionality to stop button function reset_the_timer() { clearInterval(session_interval_id); clearInterval(break_interval_id); heading.innerHTML = "Start"; Timer.innerHTML = "00:00"; } reset_button.addEventListener("click", reset_the_timer); }; stop(); <!-- language: lang-css --> * { padding: 0; margin: 0; box-sizing: border-box; } body { background-color: #0e9aa7; font-family: sans-serif; height: 100%; margin: 0; padding-top: 40px; display: flex; justify-content: center; } .container { width: 100vh; height: 90vh; display: flex; flex-direction: column; align-items: center; } .app-title { display: flex; align-items: center; } .double-line { height: 5px; width: 200px; border-top: 2px solid white; border-bottom: 2px solid white; } .app-title p { color: white; font-size: 26px; font-weight: bold; padding: 0 15px 0 15px; } .adjustment-div { display: flex; justify-content: space-between; width: 80%; } .break-length-div, .session-length-div { display: flex; flex-direction: column; align-items: center; margin-top: 40px; width: 130px; } .break-length-div .heading, .session-length-div .heading { color: white; font-size: 15px; font-weight: 600; } .value-adjustment { display: flex; align-items: center; justify-content: space-between; margin-top: 8px; width: 90%; } .minus, .plus { background: transparent; height: 30px; width: 30px; color: #3db9c5; border: 1px #3db9c5 solid; border-radius: 3px; cursor: pointer; } .minus:hover, .plus:hover { color: #2dd6e6; border-color: #2dd6e6; } .value-adjustment .minutes { background-color: white; height: 38px; width: 38px; border-radius: 50%; display: flex; align-items: center; justify-content: center; } .session { margin-top: 30px; height: 280px; width: 280px; border-radius: 50%; border: 5px solid #3db9c5; display: flex; flex-direction: column; align-items: center; justify-content: center; color: white; position: relative; } .session .heading { font-size: 26px; font-weight: bold; position: absolute; top: 60px; } .session .time { font-size: 76px; font-weight: bolder; margin-top: 40px; } .controls { display: flex; justify-content: space-between; padding: 0 10px; margin-top: 30px; width: 200px; } .start-button button, .reset-button button { width: 80px; height: 30px; background: transparent; color: white; border: 2px solid #3db9c5; border-radius: 5px; font-size: 18px; cursor: pointer; } .start-button button:hover, .reset-button button:hover { border-color: #2dd6e6; } .remarks { margin-top: 40px; color: #80e4eb; } <!-- language: lang-html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Pomodoro Clock</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <div class="app-title"> <div class="double-line"></div> <p>Pomodoro Clock</p> <div class="double-line"></div> </div> <div class="adjustment-div"> <div class="break-length-div"> <p class="heading">Break Length</p> <div class="value-adjustment"> <button class="minus">-</button> <div class="minutes"></div> <button class="plus">+</button> </div> </div> <div class="session-length-div"> <p class="heading">Session Length</p> <div class="value-adjustment"> <button class="minus">-</button> <div class="minutes"></div> <button class="plus">+</button> </div> </div> </div> <div class="session"> <div class="heading"> Start </div> <div class="time"> 00:00 </div> </div> <div class="controls"> <div class="reset-button"> <button>Reset</button> </div> <div class="start-button"> <button>Start</button> </div> </div> <div class="remarks"> Designed based on a pen by <u>Edd Yerburgh</u> and code by <u>Crying Wolfe</u> </div> </div> <script src="main.js"></script> </body> </html> <!-- end snippet --> **Key Features:** **Modularization:** I modularized my code by breaking it down into functions for adjusting break and session times, updating the time display, starting the session, and stopping/resetting the clock. This approach promotes code reuse and maintainability. **Event Handling:** Event listeners are used to handle user interactions, such as increasing/decreasing break and session times, starting the clock, and resetting it, making the application interactive and user-friendly. **Error Handling:** I implemented basic error handling to ensure that session and break times do not become negative and are capped at a minimum of 0. **Functionality:** The Pomodoro clock alternates between session and break periods based on user-defined times, providing a functional and intuitive experience. **Request for Feedback:** I would appreciate feedback on the overall structure and readability of my code, as well as suggestions for optimization and improvement. Additionally, any advice on best practices or alternative approaches would be valuable for my learning journey. Thank you for your time and assistance!
https://stackblitz.com/edit/vitejs-vite-myutvi?file=src%2FApp.jsx Hello, I’m currently integrating a custom export functionality. My goal is to add an export button to display “Save as CSV” but the text is rendering as undefined. import React, { useEffect, useState } from 'react'; import CanvasJSReact from '@canvasjs/react-charts'; const { CanvasJSChart } = CanvasJSReact; function Chart({ isLoading, data }) { // Default chart options setup const defaultOptions = { animationEnabled: true, exportEnabled: true, theme: 'dark2', // Additional options... }; const [chartOptions, setChartOptions] = useState(defaultOptions); useEffect(() => { // Conditional logic based on <code>isLoading</code> and <code>data</code> if (isLoading) { setChartOptions({ ...defaultOptions, /* Loading state */ }); } else if (data?.length > 0) { setChartOptions({ ...defaultOptions, /* Data available state */ }); } else { setChartOptions({ ...defaultOptions, /* No data state */ }); } }, [isLoading, data]); return ( <CanvasJSChart options={chartOptions} onRef={(chart) => { if (chart?.get("exportEnabled")) { const text = document.createTextNode("Save as CSV"); const exportCSV = document.createElement("div"); exportCSV.appendChild(text); exportCSV.setAttribute('style', <code>padding: 12px 8px; background-color: ${chart.toolbar.itemBackgroundColor}; color: ${chart.toolbar.fontColor}</code>); exportCSV.addEventListener('mouseover', () => { exportCSV.setAttribute('style', <code>padding: 12px 8px; background-color: ${chart.toolbar.itemBackgroundColorOnHover}; color: ${chart.toolbar.fontColorOnHover}</code>); }); exportCSV.addEventListener('mouseout', () => { exportCSV.setAttribute('style', <code>padding: 12px 8px; background-color: ${chart.toolbar.itemBackgroundColor}; color: ${chart.toolbar.fontColor}</code>); }); chart._toolBar.lastChild.appendChild(exportCSV); } }} /> ); } function App() { return <div className="App"><Chart isLoading={true} data={[]} /></div>; } export default App;
On Windows 10: Click start, search for "environment variables". or Use windows + R key to run command, run the following "sysdm.cpl" then (if used win+R key): go to advanced tab, theres a box (system variables) Then in system variables search for "Path", click on it, click "Edit". A new window pops up. Click "New" and paste in "C:\Program Files (x86)\Python\Scripts". If the box does not have a variable named "path" click New to create one, set the name to "Path", and the value to "C:\Program Files (x86)\Python\Scripts".
null
I'm trying to work with HMVC in CodeIgniter 4. I worked with it previously but in version 3.10. I can't find the HMVC plugin for CI4. Somebody can help me? Thanks. I want to work with modules for each class and add their respective views and controllers.
CodeIgniter 4 with hmvc
|codeigniter|codeigniter-4|hmvc|
null
|php|linux|bash|
To me, the only difference is that the regular operation needs one more instantiation, and the result is held by this new instance. And thus the regular implementation should call the other. [But](https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types) : *these (in-place) methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, or if that method returns NotImplemented, the augmented assignment falls back to the normal methods.* Here, i understand that the standard way is the opposite of mine : iadd relies on add. Why ? A bit of context : the question came while implementing a Polynomial class, for learning purpose. I have written: ``` class A: ... def __iadd__(self, other): "processing resulting in modification of attributes of self" returning self def __add__(self, other): res = self.copy() # copy() being implemented as well res += other returning res ```
Why regular operations are not based on their in-place corresponding operation?
|python|operator-overloading|in-place|
null
I have recently authored a new hierarchical clustering algorithm specifically for 1D data. I think it would be suitable to the case in your question. It is called `hlust1d` and it is written in `R`. It is available under [this link](https://CRAN.R-project.org/package=hclust1d). The algorithm addresses @Anony-Mousse's concern: it takes advantages of the particular structure of 1D data and runs in O(n*log n) time. This is much faster than general-purpose hierarchical clustering algorithms. To segment your data into 3 bins (clusters) as you require in your question, you could run the following code ``` library(hclust1d) dendrogram <- hclust1d(c(1, 1, 2, 3, 10, 11, 13, 67, 71)) plot(dendrogram) ``` I can't post images, but it produces the output which can be [accessed here](https://i.stack.imgur.com/jAf3k.png). Now, having a look at the dendrogram tree one can see that cutting at the height of aprox. 10 results in the segmentation required. ``` cutree(dendrogram, h=10) # 1 1 2 3 10 11 13 67 71 # 1 1 1 1 2 2 2 3 3 ``` The clustering is hierarchical, meaning that what you get is a hierarchy of clusters (a dendrogram) and it is up to you to decide, which number of clusters fits your particular data best. It is both an advantage (flexibility) and disadvantage (you have to decide something) of this method. For instance, another good cut of the dendrogram, as can be seen on a plot, is located somewhere between the heights of 20 and 60, resulting in two clusters: ``` cutree(dendrogram, h=20) # 1 1 2 3 10 11 13 67 71 # 1 1 1 1 1 1 1 2 2 ``` For more complex data, you could also experiment with other linkage functions using the `method` argument, like this: ``` dendrogram <- hclust1d(c(1, 1, 2, 3, 10, 11, 13, 67, 71), method="ward.D2") ``` Generally, Ward linkage method would give you a clustering similar to K-Means (the loss function in both methods is the same with Ward hierarchical clustering being a greedy implementation) but the hierarchical clustering let's you decide what is an appropriate number of clusters with a dendrogram in front of you, while you have to provide that number for K-Means up front. The list of all supported linkage methods can be read with a use of ``` > supported_methods() # [1] "complete" "average" "centroid" "true_median" "median" "mcquitty" "ward.D" "ward.D2" "single" ```
How can I position a div fixed relative to the body, when it's inside a fixed parent div?
|javascript|html|css|tailwind-css|
Many of the answers above already mention it, just to reiterate. Using Ansible on a system with multiple versions of python, for instance following these steps on Rocky 9.3: ``` python3.11 -m venv venv source venv/bin/activate pip install -U pip pip install ansible pip install selinux ``` And following that with `yum install libselinux-python3` makes a skew in the libraries. The error pops up because 'selinux' (using python3.11) cant find 'libselinux' which is installed on a system using python3.9 . So far the path of least resistance would be to reinstall ansible with the system level python3.
Your code might compile now, but it will not work as you expect. `INT_MIN`/`INT_MAX` are the min/max values for an `int`. It is typically **32 bit** and therefore the values that you used before were probably **–2147483648** and **2147483647** respectively (they could be larger for 64 bit integers). On the other hand `INT8_MIN`/`INT8_MAX` are min/max values for a **8 bit** signed integer (AKA `int8_t`), which are **-128** and **127** respectively. In order to get the behavior you had before, you should use `std::numeric_limits<int>::min()` and `std::numeric_limits<int>::max()`, from the [<numeric_limits> header][1]. [1]:https://en.cppreference.com/w/cpp/types/numeric_limits
Although @oguz-ismail's answer would work with the sample output provided, it seems that actual `equery` output is very strange when fed into a pipe. This convoluted commandline seems to work around the problems: ``` script -B /dev/null -E never -f -q -c ' eix-installed -a | xargs equery depends ' | tr -d '\r' | grep -v 'Unmatched removal atom' | awk '!/\n/' RS= ORS='\r\n' ``` * `script` makes `equery` believe it is talking to a terminal * `tr` strips the carriage returns added by `script` * `grep` filters some non-dependency info (per @konsolebox comment) * `awk` splits on empty lines and filters out multi-line records - setting `ORS` is only needed for terminal output
We have also faced the same issue, we removed "^" from the version number to avoid installing the latest version, the below is what we did and it worked. The latest msal version is having some breaking changes it seems. **Old Code**: "@azure/msal-angular": "^2.3.0", "@azure/msal-browser": "^2.24.0", **New Code:** "@azure/msal-angular": "2.3.0", "@azure/msal-browser": "2.24.0"
I am encountering a Fatal error message stating "Failed to listen on tcp://0.0.0.0:8080: Address already in use" when trying to create a server for websockets on my website. How can I resolve this issue? Problem: I am trying to set up a websocket server on my website, but I am receiving the following error message: "Fatal error: Uncaught RuntimeException: Failed to listen on "tcp://0.0.0.0:8080": Address already in use." This error is occurring in the TcpServer.php file on line 184. How can I troubleshoot and fix this issue to successfully set up the websocket server on my website? I'm trying to make real-time send data between admin python and the python clients throw php server **this is admin python script (Sender)** ``` import asyncio import websockets import json async def send_array(): uri = "ws://example.com:8080" async with websockets.connect(uri, timeout=60.0) as websocket: array_data = [1, 2, 3, "hello"] await websocket.send(json.dumps(array_data)) asyncio.run(send_array()) ``` and the error when i run it it's > raise TimeoutError from exc_val TimeoutError **this is the php file server** ``` require_once 'vendor/autoload.php'; use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; class WebSocketServer implements MessageComponentInterface { protected $clients; public function __construct() { $this->clients = new \SplObjectStorage; } public function onOpen(ConnectionInterface $conn) { $this->clients->attach($conn); echo "New connection! ({$conn->resourceId})\n"; } public function onMessage(ConnectionInterface $from, $msg) { $data = json_decode($msg, true); if (is_array($data)) { // Process the array data as needed echo "Received array data: " . print_r($data, true) . "\n"; // Send the array data to all connected clients foreach ($this->clients as $client) { if ($from !== $client) { $client->send(json_encode($data)); } } } } public function onClose(ConnectionInterface $conn) { $this->clients->detach($conn); echo "Connection {$conn->resourceId} has disconnected\n"; } public function onError(ConnectionInterface $conn, \Exception $e) { echo "An error has occurred: {$e->getMessage()}\n"; $conn->close(); } } ``` php file error is > Fatal error message stating "Failed to listen on tcp://0.0.0.0:8080: Address already in use **and this is the python client (Receiver)** ``` import asyncio import json import websockets # Replace this URL with the URL of your PHP server url = "ws://example:8080" async def receive_array(): async with websockets.connect(url) as websocket: while True: # Receive data from the server data = await websocket.recv() array_data = json.loads(data) # Print the received data for demonstration purposes print("Received data: ", array_data) # Run the real-time client asyncio.get_event_loop().run_until_complete(receive_array()) asyncio.get_event_loop().run_forever() ``` I am expecting to receive guidance on how to troubleshoot and resolve the "Failed to listen on tcp://0.0.0.0:8080: Address already in use" error when setting up a websocket server on my website I'm trying to make real-time send data between admin python and the python clients throw php server
{"OriginalQuestionIds":[9674815],"Voters":[{"Id":4108803,"DisplayName":"blackgreen"}]}
Weird no one mentioned this but, you can get location from `react-router-dom` using the `useLocation` hook. So you can just use that in the dependency array. [Docs here][1] ```lang-js const location = useLocation(); useEffect(() => { console.log(location); }, [location.pathname]); ``` Edit: This is a solution only for using react with web and you are using the `react-router-dom` library for web. If you want to achieve this for cases where you don't have that library installed, and the other answers didn't work for you, you would need to do the following:- 1. Add a context<sup>{1}</sup> to the top level of your App. ```lang-js export const LocationContext = React.createContext<LocationContextObject>( null! ); ``` 2. Set the value of this context provider with the location 3. When navigating, you need to update this context value with the new location, (create a custom navigation function and use it everywhere) ** Inspired from the source code of [remix-run/react-router][2] (react-router-dom) {1} - You may want to search a bit more if you want to use a context at the top level since there are [pitfalls](https://blog.logrocket.com/pitfalls-of-overusing-react-context/) you need to keep in mind. You could also store it in a state management library of your choice. [1]: https://reactrouter.com/docs/en/v6/api#uselocation [2]: https://github.com/remix-run/react-router
{"Voters":[{"Id":13061224,"DisplayName":"siggemannen"},{"Id":14868997,"DisplayName":"Charlieface","BindingReason":{"GoldTagBadge":"sql-server"}}]}
I'm optimizing some work I did moving from Orange to Python code, but I'm having some problems with image Embedders. I'm trying to recreate my work using Tensorflow/Keras, but the outputs of the VGG16 networks but the 4096 outputs of the activation layer of the penultimate FC layer for this architecture, using Orange and Keras, are different. [In the Orange documentation it is written:](https://i.stack.imgur.com/X1Kya.png) For python: ``` model_vgg = VGG16(include_top=True, weights='imagenet', pooling=None, input_shape=(224, 224, 3)) model_vgg16 = Model(inputs=model_vgg.input, outputs=model_vgg.layers[-2].output) ``` [Keras VGG16](https://i.stack.imgur.com/31umC.png) To reshape some images to 224x244 pixels i use the same package and code of function load_image_or_none -> https://github.com/biolab/orange3-imageanalytics/blob/master/orangecontrib/imageanalytics/utils/embedder_utils.py And get the same image resized to 224x224 used for VGG16 in Orange, by widget Save Image. [My resized images and Orange images are the same](https://i.stack.imgur.com/GBO7o.png) Perhaps I'm making a mistake during preprocessing, since in the Orange documentation it is written that they use the original weights of the model. To preprocess the images i try the Keras preprocess_input of VGG16, and manually ``` def process_vgg16(imgs): output = np.zeros(imgs.shape) VGG_MEAN = np.array([103.939, 116.779, 123.68], dtype=np.float32) for i in range(0, imgs.shape[0]): b = np.array(imgs[i,:,:,2], dtype=np.float32) g = np.array(imgs[i,:,:,1], dtype=np.float32) r = np.array(imgs[i,:,:,0], dtype=np.float32) output[i,:,:,0] = b - VGG_MEAN[0] output[i,:,:,1] = g - VGG_MEAN[1] output[i,:,:,2] = r - VGG_MEAN[2] #output = output/255 return output ``` Note: The images are in gray scale, so all channels are the same. Results: [First three output of an image in orange (VGG16)](https://i.stack.imgur.com/Jex5Z.png) [First three output of an image in Keras (VGG16)](https://i.stack.imgur.com/T29ph.png) Would anyone know the reason?
Custom Export Button Text Becomes Undefined When Using useEffect in Canvasjs
|reactjs|react-hooks|canvasjs|
`gcc <YourFileName>.cpp -o output.exe` Now you can run `output.exe`
This is not another of those questions, this is about parsing and interpreting PHP in the browser with JS. How can you run PHP in JavaScript? I am not asking about running PHP in the server and then send the resulting string to the browser as JavaScript. I am literally talking about JavaScript parsing and running PHP. This might be useful in many places: - An express Node.js app that has to use a PHP module. - A small REPL for the browser that does not need a whole VM per instance. Ideal for learning PHP. - Making a template engine for a static site constructor. I've searched around and found [`php-parser`](https://github.com/glayzzle/php-parser) and [`babel-preset-php`](https://gitlab.com/kornelski/babel-preset-php), but nothing to run it. Ideally I'm looking for something like this, though I couldn't find anything through Google/SO/etc: <!-- language-js --> // No server needed, "just" Javascript parsing PHP alert(php(`<?= "Hello world" ?>`)); If you know a better way than my own answer, please feel free to share it! I'm very curious about what the community thinks.
Here's my two cents on the matter, Dependency Injection is about passing the required dependencies (objects or services) into a class from an external source, rather than creating instances of those dependencies within the class itself. Why? So that we can achieve loose coupling between classes by taking advantage of interfaces and abstract classes. (or one can say to achieve IoC) Why? Because this allows us to: 1. Adhere to the Open/Closed Principle. 2. Write polymorphic code. 3. Facilitate unit testing of classes that depend on external APIs or services by providing mock or stub implementations of those dependencies. 4. Clearly define and manage the dependencies of classes. There is a concept part of it and a design pattern part of it The concept part of it is that understanding DI can achieves separating concern, IoC. Above are few benefits (from many that SoC gives), It’s about what you trying to achieve by delegating object creation. The design pattern is how to achieve it in terms of managing dependencies; by controlling the object creation and "injecting" into a class rather than the class creating its dependencies. > Design patterns are half-baked solutions for common problems. Example of DI design pattern implementation. In the .NET Framework, controller objects are managed by the .NET Core framework itself, it provides a means to inject objects into controllers using the `services.AddScoped` method. So we can see .NET Framework itself implements its version of the DI design pattern providing us a way to register our dependencies and make it available to all of our controllers.
For setting up FSLogix with Azure Files for Azure Virtual Desktop. You can follow the steps below- *Prerequisites* - Azure subscription with permissions to create resources. - Azure Virtual Desktop environment set up. - Azure Files share created for FSLogix profiles. - FSLogix agent installed on AVD VMs. create a new storage account if you haven’t. az storage account create --name <YourStorageAccountName> --resource-group <YourResourceGroupName> --location <Location> --sku Standard_ZRS --kind StorageV2 ![enter image description here](https://i.imgur.com/5buDbnI.png) Create the file share az storage share create --name <YourFileShareName> --account-name <YourStorageAccountName> ![enter image description here](https://i.imgur.com/QnZm55R.png) Get storage account key $storageKey = az storage account keys list --resource-group <YourResourceGroupName> --account-name <YourStorageAccountName> --query "[0].value" --output tsv ![enter image description here](https://i.imgur.com/kYFDXXy.png) Assign appropriate permissions to the Azure File Share for your AD domain service. In your AVD host pool, create a logon script to mount the file share when the user logs in. ``` $storageAccountName = "<YourStorageAccountName>" $fileShareName = "<YourFileShareName>" $driveLetter = "F" $storageKey = "<YourStorageKey>" #Mapping the drive New-PSDrive -Name $driveLetter -PSProvider FileSystem -Root "\\$storageAccountName.file.core.windows.net\$fileShareName" -Persist -Credential (New-Object System.Management.Automation.PSCredential ("Azure\$storageAccountName", (ConvertTo-SecureString $storageKey -AsPlainText -Force))) ``` ![enter image description here](https://i.imgur.com/HdksUPG.png) Configure FSLogix via PowerShell i.e. on the AVD VMs, set the FSLogix registry keys. ``` $regPath = "HKLM:\SOFTWARE\FSLogix\Profiles" $fileSharePath = "\\$storageAccountName.file.core.windows.net\$fileShareName" # Ensure the registry path exists if (-not (Test-Path $regPath)) { New-Item -Path $regPath -Force } # Configure the VHDLocations registry key Set-ItemProperty -Path $regPath -Name "VHDLocations" -Value $fileSharePath # Enable FSLogix Profile Containers Set-ItemProperty -Path $regPath -Name "Enabled" -Value 1 ``` ![enter image description here](https://i.imgur.com/sAmlfR2.png) Done. You can now log in to your AVD session and ensure that the F: drive is mounted and points to your Azure File Share. References: - [Using FSLogix Group Policy Template Files](https://learn.microsoft.com/en-us/fslogix/how-to-use-group-policy-templates#group-policy-management-console) - [Prepare and customize a VHD image for Azure Virtual Desktop](https://learn.microsoft.com/en-us/azure/virtual-desktop/set-up-customize-master-image#software-preparation-and-installation) - [Storage options for FSLogix profile containers in Azure Virtual Desktop](https://learn.microsoft.com/en-us/azure/virtual-desktop/store-fslogix-profile#storage-options-for-fslogix-profile-containers-in-azure-virtual-desktop)
Is there a way to manually set the values shown in the legend of a seaborn (or matplotlib) scatterplot when the legend contains a continuous variable (hue)? For example, in the plot below I might like to show the colors corresponding to values of `[0, 1, 2, 3]` rather than `[1.5, 3, 4.5, 6, 7.5]` ``` np.random.seed(123) x = np.random.randn(500) y = np.random.randn(500) z = np.random.exponential(1, 500) fig, ax = plt.subplots() hue_norm = (0, 3) sns.scatterplot( x=x, y=y, hue=z, hue_norm=hue_norm, palette='coolwarm', ) ax.grid() ax.set(xlabel="x", ylabel="y") ax.legend(title="z") sns.despine() ``` [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/E6ssv.png
Manually set values shown in legend for continuous variable of seaborn/matplotlib scatterplot
|python|matplotlib|plot|seaborn|visualization|
I have this piece of code: <h2 class="title" > <a th:href="${blogItem.getLink()}" th:text="${blogItem.getTitle()}"><style>h1 {color:'${blogItem.getTitleColor()}';} Title</style></a> </h2> but I have this error: `Mismatched property value (<color> | [initial | inherit | unset | revert])`
style tag with Thymeleaf
|html|css|spring-boot|thymeleaf|spring-thymeleaf|
I'm looking at this query: PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX schema: <http://schema.org/> PREFIX ex: <https://example.org/> SELECT distinct ?person WHERE {GRAPH ex:someGraph { ?name <http://www.ontotext.com/plugins/autocomplete#query> "bar". ?person ex:hasSibling ?sibling. ?sibling ex:name ?name . } } as I want this to fetch the IRI of a person, who's sibling's name is somehow highly related to "bar". If I remove `?person ex:hasSibling ?sibling` and `?sibling ex:name ?name` triples, and change `?name` to `?person` this works fine - I am returned all IRI's that have some indexed property containing the string "bar". Is it possible to further specify the IRI using other SPARQL statements? If so, what am I doing wrong in my syntax?
How to combine ontotext GraphDB autocomplete and SPARQL to refine searching?
|autocomplete|sparql|graphdb|
I addressed this issue (twice now) by using `fastlane` and reinstalling all simulators. You can install fastlane with `brew install fastlane` and then reset all your simulators: fastlane snapshot reset_simulators This will wipe out all your current simulators so just make sure you haven't done any special configuration in/on them that you'll need to keep. But otherwise it should be a quickfix.
Looking at `retry`'s [`RetryConfig#delay`](https://rxjs.dev/api/index/interface/RetryConfig) property I noticed you can pass a function instead of a number. const CONDITION_NOT_REACHED = 'CONDITION_NOT_REACHED'; export function poll<TApiArgs, TApiResponse>( input: PollCmd<TApiArgs, TApiResponse> ): Observable<TApiResponse> { return input.apiCall().pipe( switchMap((apiResponse) => { if (input.shouldContinuePolling(apiResponse)) { return throwError(() => CONDITION_NOT_REACHED); } return of(apiResponse); }), retry({ delay: (err, retryCount) => { if (err === CONDITION_NOT_REACHED) { return throwError(() => CONDITION_NOT_REACHED); } return timer(input.intervalInSeconds * CONVERT_SECONDS_TO_MS).pipe(take(1)); } }), timeout({ first: input.timeoutInSeconds * CONVERT_SECONDS_TO_MS }) /* At some point, manualForceStop passes from "false" to "true" and then, I would like to unsubscribe and throw a specific error */ ); } The observable returned from the function passed to `delay` has these properties: * When it emits, the retry occurs * If it throws, the error will be propagated * If it doesn't emit, the error won't be propagated and it completes without errors Then later on you can use it like this: const myPoll$ = poll(/* [...] */); myPoll$.subscribe({ error: err => { if (err === CONDITION_NOT_REACHED) { // do something here } }, });
I'm currently working on a React application where I'm using React Router for navigation. However, I'm facing an issue where the components associated with routes are not rendering properly. **index.js** ``` import React from 'react'; import ReactDOM from 'react-dom'; import App from '../components/App'; import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; document.addEventListener('DOMContentLoaded', () => { const rootElement = document.getElementById('root'); if (rootElement) { ReactDOM.render( <Router> <Routes> <Route path="/" element={<App />} /> </Routes> </Router>, rootElement ); document.body.appendChild(document.createElement('div')); } }); ``` **App.js** ``` import React from "react" import {Route, Routes, } from "react-router-dom" import Gyms from "./Gyms/Gyms" import Gym from "./Gym/Gym" const App = () => { return ( <Routes> <Route path="/" component={Gyms}/> <Route path="/gyms/:slug" component={Gym}/> </Routes> ) } export default App; ``` **Gym.js** ``` import React from 'react' const Gym = () => { return <div>This is the Gym#show view for our app.</div> } export default Gym ``` **Gyms.js** ``` import React from 'react' const Gyms = () => { return <div>This is the Gyms#index view for our app.</div> } export default Gyms ``` Despite setting up the routes as above, when I navigate to the routes, I'm not seeing the expected components rendering. Instead, I just see a blank page.
React Routes not Rendering Components
|javascript|reactjs|routes|
I have a simple section a vue3 form which I would like to perform some validation on. I would like to render an error message based on what error condition is being met. When there is only one error condition to be met - the error message renders fine. however when there are multiple possible error messages, only an empty div renders, regardless of what error is being met <label for="first_name">First Name:</label> <input type="text" id="first_name" name="first_name" required alpha v-model="firstName" @blur="v.firstName.$touch()"> <div v-if="v.firstName.$error" class="error"> <p v-if="!v.firstName.$dirty">Please enter your first name.</p> <p v-else-if="!v.firstName.minLength">First name must be at least 2 characters long.</p> <p v-else-if="!v.firstName.alpha">First name can be characters only.</p> </div> <label for="last_name">Last Name:</label> <input type="text" id="last_name" name="last_name" required alpha v-model="lastName" @blur="v.lastName.$touch()"> <div v-if="v.lastName.$error && v.lastName.$dirty" class="error"> <p>Last name must be at least 2 characters long.</p> </div> <script> import { required, minLength, helpers, alpha } from '@vuelidate/validators'; import useVuelidate from '@vuelidate/core'; export default { setup() { const v = useVuelidate(); return { v }; }, data() { return { firstName: '', lastName: '', }; }, validations: { firstName: { required, alpha, minLength: minLength(2) }, lastName: { required, alpha, minLength: minLength(2) }, }, }; </script> In this example, when i enter 1 letter into last_name, the apt error message "Last name must be at least 2 characters long." however if nothing/less than 2 letters/a non-alpha character is entered into first_name, an empty div renders with no p text inside. here is the rendered html when i inspect [![rendered html inspect][1]][1] [1]: https://i.stack.imgur.com/aroSv.png i would like to have the correct error message rendering
websocket Fatal error message stating "Failed to listen on tcp://0.0.0.0:8080: Address already in use
|python|php|websocket|phpwebsocket|
null
[Product description is mixed in shortcodes](https://i.stack.imgur.com/eU0k3.png) I am trying to remove the shortcode in the google feed description. Descpription is not looking very good.If anyone can help , I tried searching on google but its not helping. I tried searching google and I couldnt find the possible solution. I need to strip the shortcodes from the description. in the google product feed.
Wordpress Salient theme is pushing Shortcodes in Google feed description
|php|wordpress|feed|
null
Start camera int currentapiVersion = android.os.Build.VERSION.SDK_INT; Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); String fileName = System.currentTimeMillis() + ".jpg"; tempFile = new File(Environment.getExternalStorageDirectory() + savePath, fileName); if (currentapiVersion < 24) { Uri fileUri = Uri.fromFile(tempFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); onActivityResult } else { ContentValues contentValues = new ContentValues(1); contentValues.put(MediaStore.Images.Media.DATA, tempFile.getAbsolutePath()); Uri fileUri = getApplication().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); } startActivityForResult(intent, TAKE_PHOTOS_CODE); Read pictures and display them to ImangView imageView.setImageURI(Uri.fromFile(tempFile));
To work nice on all browsers, I'd suggest this solution using jQuery : HTML ``` html <img src='./templates/lights3.jpg' alt="bg" id="bg"/> ``` CSS ``` css #bg { position: fixed; top: 0; left: 0; z-index: -5000; // Yes I always overdo ^^ (that's not very clean) } .bgwidth { width: 100%; } .bgheight { height: 100%; } ``` JQUERY ``` js $(window).load(function() { var theWindow = $(window), $bg = $("#bg"), aspectRatio = $bg.width() / $bg.height(); function resizeBg() { if ( (theWindow.width() / theWindow.height()) < aspectRatio ) { $bg.removeClass() .addClass('bgheight'); } else { $bg.removeClass() .addClass('bgwidth'); } } theWindow.resize(resizeBg).trigger("resize"); }); ``` This solution would be responsive and resize your background image relative to the size of browser window.
null
|python|palindrome|
# Background After upgrading to Windows 11, I've encountered an issue where I cannot open PowerShell in administrator mode directly from toolbar. This method is mentioned here: [How to run PowerShell with admin privileges from the current folder?](https://stackoverflow.com/questions/40599282/how-to-run-powershell-with-admin-privileges-from-current-folder) # Workaround I found a workaround that typing `powershell` in the file explorer's address bar, which opens PowerShell in the current folder but not with administrator privileges. # Seeking Solutions However, I'm specifically looking for a solution or an alternative method to open PowerShell with administrative rights directly from the toolbar or anywhere else conveniently. Does anyone know of a way to achieve this in Windows 11?
Conditional rendering error message failing when more than one possible error in vue3 with vuelidate
|vue.js|vuelidate|laravel-mix-vue3|
{"Voters":[{"Id":4799172,"DisplayName":"roganjosh"},{"Id":535275,"DisplayName":"Scott Hunter"},{"Id":550094,"DisplayName":"Thierry Lathuille"}],"SiteSpecificCloseReasonIds":[13]}
My data is two different lists and they seem as following: [List 1](https://i.stack.imgur.com/97EtI.png) [List 2](https://i.stack.imgur.com/THHie.png) in the attached pictures, are two lists, so I am trying to compare Date column in List 1 with Date column in List 2. If they match then multiply corresponding cells for (NG rate X Weight) and return results in Approved column. **OBS** List 1 has always uniqe date while List 2 has several cells with same date. However, I want to multiply NG Rate for the corresponding date with Weight in List 2 which has the same date so the result will be as presented in pic of List 2. I will appreciate your help BR I tried VLOOKUP but didn't work.
Compare two columns if 1st cell matches with 2nd cell then
|excel|
null
The explanation of the two eggs problem can make some people confused in the first time, so we can understand the solution as follows: Given x is the floor we start dropping the eggs. - If it breaks, the total of trials in the worst case is **(x - 1)** - If it doesn't break, how should we step up to the next floor? We can jump to floor **(x + x)th**, **(x + x + 1)th**... But it will increase the number of trials, we can try at x = 10: . If it does break, we must try 10 times total in the worst case. . If it does not break, and we step up to 10th + 10th = 20th and try, and if it breaks, we must try 1 (at floor 10th) + 1 (at floor 20th) + 9 = 11 times. Similarly, if we step up to x + 1, or x + 2 floor it will increase the number of trials. Actually, we want the number of trials being equal in both cases, for that reason we will step up to x - 1 floor instead of x, x + 1.,etc. Finally, we will have an expression in general: x + (x - 1) + (x - 2) + ... + 1. And that's it.
I have made one discord bot in the past it work perfectly but when I tried makeing another just like that it don't work it doesn't respond to my messages in the server but it respond in the private dms I tried to debug it by print statements but it don't receive the message from the server, I have checked the permissions and remove and add the bot again and also made another one and new servers but both of them don't message in servers It's the code I written. ``` import discord import os intents = discord.Intents.default() intents.messages = True # Enable message events key = os.environ['Key'] client = discord.Client(intents=intents) @client.event async def on_ready(): print('Connected!') @client.event async def on_message(message): if message.author == client.user: return print(f"Received message: {message.content}") # Debug print statement if message.content.startswith('hello'): print('Responding to hello message') # Debug print statement await message.channel.send('Hello!') client.run(key) ``` Thank-you The bot works fine when I chat in the dms but it can't read the messages on a server
I am using this plugin, but I wanted to modify the php to redirect my uploads to a specific 'clientsimages' folder. However I can't seem to get it to work, any suggestions? I'm using this code: https://github.com/ruvictor/wc-file-attribute/blob/master/att.php This is the code I tried, but it isn't uploading my images anymore. Prior to this it was just uploading everything to my normal media library: if( ! empty( $_FILES['vicode-file-field']["name"] ) ) { // WordPress environment require( dirname(__FILE__) . '/../../../wp-load.php' ); $wordpress_upload_dir = wp_upload_dir(); // $wordpress_upload_dir['path'] is the full server path to wp-content/uploads/2017/05, for multisite works good as well // $wordpress_upload_dir['url'] the absolute URL to the same folder, actually we do not need it, just to show the link to file $i = 1; // number of tries when the file with the same name already exists $file_image = $_FILES['vicode-file-field']; $new_file_path = $wordpress_upload_dir['/wp-content/uploads/clientimages'] . '/' . $file_image['name']; $new_file_mime = mime_content_type( $file_image['tmp_name'] ); if( empty( $file_image ) ) die( 'File is not selected.' ); if( $file_image['error'] ) die( $file_image['error'] ); if( $file_image['size'] > wp_max_upload_size() ) die( 'It is too large than expected.' ); if( !in_array( $new_file_mime, get_allowed_mime_types() ) ) die( 'WordPress doesn\'t allow this type of uploads.' ); while( file_exists( $new_file_path ) ) { $i++; $new_file_path = $wordpress_upload_dir['/wp-content/uploads/clientimages'] . '/' . $i . '_' . $file_image['name']; }
How to redirect uploads from customers to go into specific folder?
|php|wordpress|plugins|
null
Finally I found this cheeky hack: ``` test: | exec 3<>/dev/tcp/localhost/8080 echo -e "GET /ready HTTP/1.1\nhost: localhost:8080\n" >&3 timeout --preserve-status 1 cat <&3 | grep -m 1 status | grep -m 1 UP ERROR=$? exec 3<&- exec 3>&- exit $ERROR ```
Using gdal-async in nodejs, im trying to convert verctor files from geojson to dxf. ``` const dsGeoJSON2 = gdal.open('./upload2/objects.geojson'); const out2 = gdal.vectorTranslate('./upload2/objects.dxf', dsGeoJSON2, ['-f', 'DXF']); ``` the output file is emty, even with .kml but when i change to gpx for example it work.
I have developed an app in .net Maui and would now like to hand it over to my customers. The only problem is that the company's laptops only allow apps to be installed that are from trustworthy authors. Even if I create an author certificate in visual studio and install it manually on a customer's laptop, the author (me) is still not recognized during the installation (Errorcode 0x800B010A). Is there a way to fix this error? Tried to create a certificate manually and installed it.
Unknown Author error while deployment in .net MAUI Win App
I am working on a custom board with two IMX7ULP. The thing I'm trying to do seems quite simple, the A7 from one IMX7ULP send a signal to the M4 of the other IMX7ULP, just an electrical signal, one of the pin of the A7 as output, one of the pin of the M4 as input (PTA16), no special communication protocol. We manage to set the pin of the A7 as an output (even checked with the multimeter) and we do what seems correct to set the pin as an input but nothing is read and it keeps returning me a value of 0. The code I made looks like this ``` #define GPIO_HEARTBEAT_READ 16U gpio_pin_config_t digitalInput = { //set as input kGPIO_DigitalInput, }; /* Init board hardware. */ BOARD_InitPins(); BOARD_BootClockRUN(); BOARD_InitDebugConsole(); CLOCK_EnableClock(kCLOCK_Rgpio2p0); /* Init input GPIO. */ GPIO_PinInit(GPIOA, GPIO_HEARTBEAT_READ, &digitalInput); int value = GPIO_PinRead(GPIOA, GPIO_HEARTBEAT_READ); PRINTF("Value of HEARTBEAT_READ : %d\n", value); PRINTF("Value of register of heartbeat : %x\n", READ_reg()); ``` and value is set as 0 while the register read 0x10100 which is what I am expecting for a pin set as input. I also checked the IOMUXC mode to make sure it is correctly set as GPIO : ``` void BOARD_InitPins(void) { IOMUXC_SetPinMux(IOMUXC_PTA16_PTA16, 0U); } ``` I even tried forcing it in pull-down to create a difference in potential at the pin but nothing changed. I'm currently running out of ideas, is there something I'm missing ? Is it more a hardware problem than software (if it's the case, I apologize and I'll be looking somewhere else) Thank you in advance
Unable to read value from gpio set as input
|c|gpio|cortex-m|imx7|
null
The only issue which i see might be intefering with your ObjectMapper is the 2 extra modules which are added. mapper.registerModules(securityModules()); mapper.registerModule(authorizationServerJackson2Module()); try removing these 2 and then try again.
I am using Vue3 and Vue router 4, while tyring to run this.$router.push it throws `leaveGuards.forEach is not a function` I see that https://github.com/vuejs/router/blob/f776cbe1098596f53b5c2f696d29e1c02afd1fc1/packages/router/src/router.ts#L824 at this particular line for my application the leaveGuards is an empty object. Why is that? How can I resolve my error? I tried this.$router.push({ path: // query: // }) And router.js seems to be configured properly
this.$router.push is causing a leaveGuards.forEach is not a function error
|vuejs3|vue-router4|
null
You can define a new method on `Array` object's prototype. E.g: Array.prototype.IsTrue = function () { return true; } Then use it: product.attributes.IsTrue() But this method will exist on every instance of Array object. E.g: `[1,'abc'].IsTrue()` is a valid usage. You can't define the extension method for only one interface of your choice, because javascript actually don't have the notion of `Interface` or `Type`. It's just a language feature that Typescript bring up to help your developer life easier. The recommended approach in React world would be some Utility functions, you import and use them on demand.
Discord bot can't send messages from the server but sends messages from dm
|python|discord|discord.py|bots|
null
I am testing the m.if3 function in gekko by using conditional statements of if-else but I get two different outputs. The enroll_rate is 0.1 for the first 5 months and it switches to 0.3 for the remaining 45 months. ``` m = GEKKO(remote=False) # parameters sitecost = 9 # Cost per site patcost = 12 # Cost per patient num_pat = 50 # Required number of patients recruit_duration = 50 # Duration of recruitment # Define a piecewise function for the enrollment rate enroll_rate = m.if3(recruit_duration - 5, 0.3, 0.1) x = m.Var(integer=True, lb=1) # Number of sites cost = m.if3(recruit_duration - 5, (0.3 * patcost * recruit_duration + sitecost) * x, (0.1 * patcost * recruit_duration + sitecost) * x) pat_count = m.if3(recruit_duration - 5, (0.3 * recruit_duration * x), (0.1 * recruit_duration * x)) m.Minimize(cost) m.Equation(pat_count >= num_pat) m.solve(disp=False) num_sites = int(x.value[0]) print(f'num_sites = {num_sites}') print(cost.value[0]) print(pat_count.value[0]) ``` ``` # Parameters sitecost = 9 # Cost per site patcost = 12 # Cost per patient num_pat = 50 # Required number of patients recruit_duration = 50 # Duration of recruitment # Define an enrollment rate based on recruit_duration if recruit_duration > 5: enroll_rate = 0.1 else: enroll_rate = 0.3 # GEKKO Variables x = 10 # Number of sites # Calculate cost based on enrollment rate and site cost cost1 = (0.1 * patcost * 45 + sitecost) * 12 cost2 = (0.3 * patcost * 5 + sitecost) * 12 cost = cost1 + cost2 # Calculate total patient count pat_count1 = 0.1 * 5 * 12 pat_count2 = 0.3 * 45 * 12 pat_count = pat_count1 + pat_count2 print(pat_count) print(cost) ``` I get different outputs even though I am doing the same thing in both of them. I tried everything from using if-else statements to using if2 statements.
Why does it provide two different outputs? [gekko]
|gekko|
null
You can use the [`sx` prop][1]: ```javascript const boxStyle = { my: 4, display: "flex", alignItems: "top", gap: 1, p: 2, ... }; ... <Box sx={boxStyle}></Box> ``` Alternatively, you can create a separate component for your specific box, like: ```javascript const StyledBox = ({ children }) => ( <Box my={4} display="flex" alignItems="top" gap={1} p={2} > {children} </Box> ); ... <Stack direction="row" spacing={2} border={1} borderColor="divider"> <StyledBox> <TargetMetricIcon fontSize="medium" /> Target Metric </StyledBox> </Stack> ``` [1]: https://mui.com/system/getting-started/the-sx-prop/
I am trying to execute the following script. but I don't get neither the desired results nor a error message ,and I can't figure out where I'm doing wrong. import pyodbc cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};" "Server=mySRVERNAME;" "Database=MYDB;" "uid=sa;pwd=MYPWD;" "Trusted_Connection=yes;") cursor = cnxn.cursor() cursor.execute('select DISTINCT firstname,lastname,coalesce(middlename,\' \') as middlename from Person.Person') for row in cursor: print('row = %r' % (row,)) any ideas ? any help is appreciated :)