instruction
stringlengths
0
30k
CSS Checkboxes Side By Side
|html|css|
``` package main import "fmt" func square(c chan int) { fmt.Println("[square] reading") num := <-c fmt.Println("[square] before writing") c <- num * num fmt.Println("[square] after writing") } func cube(c chan int) { fmt.Println("[cube] reading") num := <-c fmt.Println("[cube] before writing") c <- num * num * num fmt.Println("[cube] after writing") } func main() { fmt.Println("[main] main() started") squareChan := make(chan int) cubeChan := make(chan int) go square(squareChan) go cube(cubeChan) testNum := 3 fmt.Println("[main] sent testNum to squareChan") squareChan <- testNum fmt.Println("[main] resuming") fmt.Println("[main] sent testNum to cubeChan") cubeChan <- testNum // Why main not blocked here? fmt.Println("[main] resuming") fmt.Println("[main] reading from channels") squareVal, cubeVal := <-squareChan, <-cubeChan sum := squareVal + cubeVal fmt.Println("[main] sum of square and cube of", testNum, " is", sum) fmt.Println("[main] main() stopped") } ``` Why is it printed like that ??? Output: ``` 1.[main] main() started 2. [main] sent testNum to squareChan 3. [cube] reading 4. [square] reading 5. [square] before writing 6. [main] resuming 7. [main] sent testNum to cubeChan 8. [main] resuming 9. [main] reading from channels 10. [square] after writing 11. [cube] before writing 12. [cube] after writing 13. [main] sum of square and cube of 3 is 36 14. [main] main() stopped ``` 2 questions: 1) Why after call "squareChan <- testNum" scheduler first check cube goroutine instead of square goroutine? 2) Why after call "cubeChan <- testNum" main goroutine not blocked? Please can somebody explain by steps - How exactly scheguler switch between square, cube and main goroutines in this code?
Flutter video_player Shown Meaningless Video Images in Emulator But It Can Seen On Real Device
{"Voters":[{"Id":3889449,"DisplayName":"Marco Bonelli"},{"Id":1687119,"DisplayName":"dbush"},{"Id":12002570,"DisplayName":"user12002570"}]}
|unity-game-engine|game-development|multiplayer|unity3d-mirror|
Most likely the `int32_t * SIZE` in the `malloc` call. If you use a bit-shift like `SIZE << 2` instead, your code should be much faster and more efficient.
Spring Data JPA doesn't support aggregate functions in queries using method names. The suggested approach is to use `@Query` as mentioned in your question. Why do you consider it dirty? It isn't IMHO.
Five batch jobs A, B, C, D and E arrive at a computer centre at almost at the same time. They have estimated running times of 10,6,2,4 and 8 minutes. Their priorities are 3,5,2,1 and 4 respectively, with 5 being the highest priority. For each of the following scheduling algorithm determine the turnaround time of each process and waiting time of each process. Ignore process switching overhead. Mention which algorithm results in minimal average waiting time. 1. Round Robin 2. Priority scheduling 3. First come first served 4. Shortest job first. For case i) assume that system is multiprocessing and each job gets its fair share of the CPU. (time quantum 2 minutes0. For cases (ii),(iii) and (iv) assume that only one job runs at a time, until it finishes. All jobs are completely CPU bound. proper answer with partition required
Problem on CPU scheduling algorithms in OS
|linux|operating-system|cpu|scheduling|
null
change cli php version, i had the same error when running it with cli 8.1 on my hosting provider. see which version by running `php -v`
i am making a multiplayer game using Mirror, the premise of this action is simple : if a player walks in front of a patrolling enemy, the enemy will start following the player, in a single player context it all works fine, however when in a multiplayer setting it all goes bad : - The client player walks in front of the patrolling enemy - The patrolling enemy goes to the host player's position (this update only happens on the host's POV, nothing changes on the client side) this is my patrolling code : ``` csharp using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; using Mirror; public class PatrolNavigation : NetworkBehaviour { private NavMeshAgent agent; public FieldOfView fov; [SerializeField] Transform[] posPoints; int posInt; Vector3 dest; // Boolean that activates the first time you see the player public bool hasSeenPlayer = false; [SerializeField] float targetTime; [SerializeField] float PosTime; private Vector3 startPosition; public GameObject PatrolPoints; private bool hasSpawnedPatrolPoints = false; // Start is called before the first frame update void Start() { posInt = Random.Range(0, posPoints.Length); agent = GetComponent<NavMeshAgent>(); startPosition = gameObject.transform.position; StartCoroutine(GoPosPoints()); } // Update is called once per frame void Update() { /*if (!isServer) return;*/ if (fov.canSeePlayer) { GoToPlayer(); } else if (hasSeenPlayer && !fov.canSeePlayer) { Patrol(); if (targetTime < 0) { GoBackToSpawn(); } } } [Command(requiresAuthority = false)] private void GoToPlayer() { GameObject[] players = GameObject.FindGameObjectsWithTag("Player"); if (players.Length > 0) { // Set destination to the first player found (you might want to implement logic to select the closest player) agent.destination = players[0].transform.position; hasSeenPlayer = true; targetTime = 10.0f; SpawnPatrolPoints(); } } [Command(requiresAuthority = false)] private void SpawnPatrolPoints() { if (!hasSpawnedPatrolPoints) { PatrolPoints.transform.position = agent.destination; hasSpawnedPatrolPoints = true; } } [Command(requiresAuthority = false)] private void Patrol() { targetTime -= Time.deltaTime; dest = posPoints[posInt].position; agent.SetDestination(dest); hasSpawnedPatrolPoints = false; } [Command(requiresAuthority = false)] public void GoBackToSpawn() { agent.SetDestination(startPosition); } IEnumerator GoPosPoints() { yield return new WaitForSeconds(PosTime); posInt = Random.Range(0, posPoints.Length); StartCoroutine(GoPosPoints()); } } ``` Field of view : ``` csharp using System.Collections; using UnityEngine; using Mirror; public class FieldOfView : NetworkBehaviour { public float radius; [Range(0, 360)] public float angle; public LayerMask targetMask; public LayerMask obstructionMask; [SyncVar] public bool canSeePlayer; private void Start() { StartCoroutine(FOVRoutine()); } private IEnumerator FOVRoutine() { WaitForSeconds wait = new WaitForSeconds(0.2f); while (true) { yield return wait; FieldOfViewCheck(); } } private void FieldOfViewCheck() { Collider[] rangeChecks = Physics.OverlapSphere(transform.position, radius, targetMask); if (rangeChecks.Length != 0) { foreach (Collider col in rangeChecks) { if (!col.CompareTag("Player")) continue; Transform target = col.transform; Vector3 directionToTarget = (target.position - transform.position).normalized; if (Vector3.Angle(transform.forward, directionToTarget) < angle / 2) { float distanceToTarget = Vector3.Distance(transform.position, target.position); if (!Physics.Raycast(transform.position, directionToTarget, distanceToTarget, obstructionMask)) { canSeePlayer = true; return; // If the player is seen, exit early } } } } canSeePlayer = false; // If no player is seen, update to false } } ``` i added NetworkIdentity to all the enemies but still nothing changed
I'm encountering an issue with Hibernate where I'm getting the following SQL error: Please help me to resolve error SQL Error: 0, SQLState: 42P01 ERROR: missing FROM-clause entry for table "th1_1" Position: 14 I'm working on a Spring Boot application where I'm using Hibernate for ORM mapping. I have entities defined for dx_entity and dx_temporary_hazard, and I'm using a join strategy inheritance between them. I'm attempting to retrieve data using Hibernate's findAll method. `@Getter @Setter @Entity @Table(name = "dx_entity") @Inheritance(strategy = InheritanceType.JOINED) @DiscriminatorColumn(name = "table_name", discriminatorType = DiscriminatorType.STRING) @Where(clause = "deleted_at is null") @NoArgsConstructor public class DxEntity extends MultiTenantEntity implements Serializable { // Entity fields... } @Entity @Table(name = "dx_temporary_hazard") @Setter @Getter @DiscriminatorValue("dx_temporary_hazard") public class TemporaryHazard extends DxEntity { // Entity fields... }` **test controller: ** `@RestController public class TController { private final TemporaryHazardRepository temporaryHazardRepository; public TController(TemporaryHazardRepository temporaryHazardRepository) { this.temporaryHazardRepository = temporaryHazardRepository; } @GetMapping("/test") public Page<TemporaryHazard> test() { return temporaryHazardRepository.findAll(PageRequest.of(0,20)); } }` When we trigger /test controller, Quires performed in console: `SELECT th1_1.pk_id, th1_0.changed_at, th1_0.changed_by, th1_0.created_at, th1_0.created_by, th1_0.created_layout, th1_0.deleted_at, th1_0.module_name, th1_0.status, th1_0.tag, th1_0.tenant_id, th1_0.updated_layout, th1_1.abc, th1_1.xyz, th1_1.abc1, th1_1.control_measures_required, th1_1.xyz1, th1_1.type FROM PUBLIC.dx_entity th1_0 JOIN PUBLIC.dx_temporary_hazard th1_1 ON th1_0.pk_id=th1_1.pk_id WHERE th1_0.tenant_id = ? AND ( th1_0.deleted_at IS NULL) AND th1_0.table_name='dx_temporary_hazard' offset ? rowsFETCH first ? rows only` ` SELECT count(th1_1.pk_id) FROM PUBLIC.dx_entity th1_0 WHERE th1_0.tenant_id = ? AND ( th1_0.deleted_at IS NULL) AND th1_0.table_name='dx_temporary_hazard' ` **Error:** SQL Error: 0, SQLState: 42P01 ERROR: missing FROM-clause entry for table We can see that "th1_1.pk_id" is wrong alias name in count query. Hence query failing to return result. I tried with hibernate 6.2.x and 6.4.x version, No luck
How to iteratively create matrices/vectors from columns/unique row values of dataframe, and pass them to subsequent code?
|r|dataframe|loops|for-loop|dplyr|
I am trying to set up SMTP for my service now instance by trying to connect to a specific SMTP host. I am able to test connection from the midserver. But when I try from the service now portal, its failing to connect. [![enter image description here][1]][1] Is there any option in service now to make sure this connection is happening via the midserver instance. [1]: https://i.stack.imgur.com/ORJxn.png
Service now SMTP test connection failing even though I am able to test connection from midserver
|servicenow|servicenow-rest-api|
I created next component: ``` import React from 'react'; import { Document, Page, pdfjs } from 'react-pdf'; import 'react-pdf/dist/esm/Page/AnnotationLayer.css'; pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`; interface PdfViewerProps { url: string; } const PdfViewer: React.FC<PdfViewerProps> = ({ url }) => { const [numPages, setNumPages] = React.useState<number | null>(null); function onDocumentLoadSuccess({ numPages }: { numPages: number }) { setNumPages(numPages); } return ( <div> <Document file={url} onLoadSuccess={onDocumentLoadSuccess} > {Array.from(new Array(numPages), (el, index) => ( <Page key={`page_${index + 1}`} pageNumber={index + 1} /> ))} </Document> </div> ); }; export default PdfViewer; ``` And used it in App.tsx ``` import './App.css'; import PdfViewer from './PdfViewer'; function App() { return ( <div className="App"> <h1>Перегляд PDF</h1> <PdfViewer url="https://localhost:7008/local/stream" /> </div> ); } export default App; ``` On the application page, I got the following result: [![enter image description here][1]][1] It is unexpected, because as you can see on next photo, pdf file itself does not contain the page I circled in blue. It contains only the pages like I circled in red. [![enter image description here][3]][3] And as you can see from next photo, this is repeated for each page: [![enter image description here][2]][2] The most interesting thing is that this page consists of html tags [![enter image description here][4]][4] I have no idea what could be the reason for this [1]: https://i.stack.imgur.com/EGAH2.png [2]: https://i.stack.imgur.com/XBaVd.png [3]: https://i.stack.imgur.com/59uOk.png [4]: https://i.stack.imgur.com/2INi4.png
'react-pdf' works unexpectedly. Adds text in html tag format after each page
|reactjs|typescript|react-pdf|
How do I stream data from TUM RGB-D to ORB-SLAM3 and analyse/record data from that
I've managed to run Visual Studio 2019 from WSL2 this way: ```bash # Path to Visual Studio executable VSRUN='C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Visual Studio 2022.lnk' function open_in_vs() { # Take first passed argument and generate absolute path FIRST_ARG=`realpath $1` # Convert path (which is now in Unix style) to Windows path PATH_TO_FILE=`wslpath -w $FIRST_ARG` # Run process using PowerShell powershell.exe "Start-Process '${VSRUN}' '${PATH_TO_FILE}'" } # open_in_vs ./testfile.txt # This adds an `openvs` alias you can use in your terminal to open any file in VS alias openvs=open_in_vs ```
Flexbox is actually easier to use to achieve this output. Example below. <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-css --> #result-images{ display:flex; flex-flow: row wrap; justify-content:center; align-content:center; align-items:center; border: 2px solid black; max-width:360px; } #result-images img{ min-width: 120px; max-width: 120px; min-height: 120px; max-height: 120px; flex: 0 1 auto align-self:center; } <!-- language: lang-html --> <section id="result-images"> <img src="https://www.gstatic.com/webp/gallery/1.jpg"> <img src="https://www.gstatic.com/webp/gallery/2.jpg"> <img src="https://www.gstatic.com/webp/gallery/3.jpg"> <img src="https://www.gstatic.com/webp/gallery/4.jpg"> <img src="https://www.gstatic.com/webp/gallery/5.jpg"> </section> <!-- end snippet --> 1. List item
null
{"OriginalQuestionIds":[709669],"Voters":[{"Id":285587,"DisplayName":"Your Common Sense","BindingReason":{"GoldTagBadge":"php"}}]}
Pls. try this formula in C10 and copy down. `=LET(rng,C$2:I$5,client1,B10,SUM(IF(TOROW(CHOOSEROWS(rng,SEQUENCE(1,ROWS(rng)/2,1,2)))=client1,TOROW(CHOOSEROWS(rng,SEQUENCE(1,ROWS(rng)/2,2,2))),0)))` Adjust `rng` to the actual size of the client/Has worked data range. `client1` to the first name cell of the result table.
Below code worked for me. Little trick from [OLEObject label not displaying when executing Word macro from Powershell][1] helped. Sub Attach_REL_BUS_Extract_To_Word() 'Declare Word Variables Dim WrdApp, WrdDoc Dim strdocname On Error Resume Next 'Declare Excel Variables Dim WrkSht Dim Rng ' Define paths to Excel and Word files wordFilePath = "D:\GIT\modules\core\bin/logs\Test.docx" ' VBScript to read data from Excel and export tables to Word with formatting ' Create Excel and Word objects Set objExcel = CreateObject("Excel.Application") ' Open Excel workbook 'Create a new instance of Word Set WrdApp = CreateObject("Word.Application") WrdApp.Visible = False WrdApp.Activate 'Create a new word document 'Set WrdDoc = WrdApp.Documents.Add Set WrdDoc = WrdApp.Documents.Open(wordFilePath) Const ClassType = "Excel.Sheet.12" Const DisplayAsIcon = True Const IconFileName = "C:\WINDOWS\Installer\{90160000-000F-0000-1000-0000000FF1CE}\xlicons.exe" Const IconIndex = 1 Const LinkToFile = False Const relFilename = "D:\GIT\modules\core\src\main\resources\config\relCount.xlsx" Const relIconLabel = "Rel Count Extract" Const busFilename = "D:\GIT\modules\core\src\main\resources\config\busCount.xlsx" Const busIconLabel = "Bus Count Extract" Set WrdRng1 = WrdDoc.Bookmarks("s_Bus_Count_Attachment").Range With WrdRng1 Set newole = .InlineShapes.AddOLEObject(ClassType, busFilename, LinkToFile, DisplayAsIcon, IconFileName, IconIndex, busIconLabel) newole.Delete End With With WrdRng1 Set newole = .InlineShapes.AddOLEObject(ClassType, busFilename, LinkToFile, DisplayAsIcon, IconFileName, IconIndex, busIconLabel) With newole .Height = 80 .Width = 140 End With End With Set WrdRng = WrdDoc.Bookmarks("s_Rel_Count_Attachment").Range With WrdRng Set newole = .InlineShapes.AddOLEObject(ClassType, relFilename, LinkToFile, DisplayAsIcon, IconFileName, IconIndex, relIconLabel) With newole .Height = 80 .Width = 140 End With End With WrdDoc.SaveAs wordFilePath objExcel.Quit WrdApp.Quit Set objExcel = Nothing Set WrdApp = Nothing End Sub [1]: https://stackoverflow.com/a/77237043
{"Voters":[{"Id":4267244,"DisplayName":"Dalija Prasnikar"}]}
|mysql|
In regular regex style: ^0b([01]_?)*[01]$ The regex: - `0b` literal "0b" - `[01]_?` binary digit optionally followed by an underscore - `(...)*` zero or more of - `[01]` binary digit See [live demo][1]. Expressed as RE2C (I think): BINARY_NUM = "0b" ([01]"_"?)* [01]; [1]: https://rubular.com/r/eAAL7AcQp9WrH0
You'd have to edit file `gradle/libs.versions.toml` and add in TOML format: [versions] androidx_media3 = '1.3.0' androidx_compose_bom = '2024.03.00' androidx_compose_uitest = '1.6.4' # ... [libraries] androidx_media3_exoplayer = { module = "androidx.media3:media3-exoplayer", version.ref = "androidx_media3" } androidx_media3_exoplayer_dash = { module = "androidx.media3:media3-exoplayer-dash", version.ref = "androidx_media3" } androidx_media3_exoplayer_ui = { module = "androidx.media3:media3-exoplayer-ui", version.ref = "androidx_media3" } androidx_compose_bom = { module = "androidx.compose:compose-bom", version.ref = "androidx_compose_bom" } androidx_compose_uitest = { module = "androidx.compose.ui:ui-test-junit4", version.ref = "androidx_compose_uitest" } # ... And one can even bundle these (optional): [bundles] exoplayer = ["androidx_media3_exoplayer", "androidx_media3_exoplayer_dash", "androidx_media3_exoplayer_ui"] Which means, you can't just copy & paste, but have to convert to TOML.<br/> Be aware that for BOM dependencies, this only works for the BOM itself.<br/> When there's no version number, one can use: `//noinspection UseTomlInstead`. The names of the definitions of the default empty activity app are kind of misleading since they're not explicit enough, there `androidx` should better be called `androidx_compose`... because eg. `libs.androidx.ui` does not provide any understandable meaning (readability), compared to `libs.androidx.compose.ui`. Proper labeling is important there. Further reading: - [Sharing dependency versions between projects](https://docs.gradle.org/current/userguide/platforms.html) - [Migrate your build to version catalogs](https://developer.android.com/build/migrate-to-catalogs)
You can simplify your query and just use `STRING_AGG`, so you get rid of your subquery. By the way, please take care to always put the table alias before the column name, not only sometimes. SELECT p.post_id, COALESCE(STRING_AGG(k.topic_id::varchar,',' ORDER BY k.topic_id), 'Vague!') AS topic FROM Posts p LEFT JOIN Keywords k ON LOWER(p.content) LIKE '% ' || k.keyword || ' %' OR p.content LIKE k.keyword || ' %' OR p.content LIKE '% ' || k.keyword GROUP BY p.post_id ORDER BY p.post_id; See this [db<>fiddle][1] with your data. The fiddle also shows you could use `CASE` rather than `COALESCE` in your orignal query which would solve your issue too. The issue was `COALESCE` replaces `NULL` values, but you got an empty string, not `NULL`. Anyway, your previous query is far too complicated for your use case. You might also be able to simplify those `LIKE` conditions and rather use a Regex approach. Since I don't use Pie DB and am not sure about regex functionality there, I leave this part up to you. [1]: https://dbfiddle.uk/D-BqtPYo
|shell|fish|
Remove the bin from MAVEN_HOME, when the path is building you add bin again, then the path the machine is looking for is C:\Program Files (x86)\Common Files\Oracle\Java\javapath;%MAVEN_HOME%\bin\bin; which is wrong
{"Voters":[{"Id":2511795,"DisplayName":"0andriy"},{"Id":17562044,"DisplayName":"Sunderam Dubey"},{"Id":16217248,"DisplayName":"CPlus"}]}
I am trying to take a string like `php,mysql,css`<br> and turn it into `#php #mysql #css` What I have so far: $hashTagStr = "php,mysql,css"; $hashTags = explode(",", $hashTagStr); foreach($hashTags as $k => $v){ $hashTagsStr = ''; $hashTagsStr .= '#'.$v.' '; } echo $hashTagsStr; Problem is it only prints `#css`
Prepend character to each value in a delimited string
|php|prefix|delimited|
null
PHP's `nl2br()` function can convert newline characters to `<br>` tags. This will preserve the line breaks when displaying the text in HTML. You can further modify the code to remove any trailing `<br />` tags from each line. This can be done by using the `rtrim()` function in PHP, which removes specified characters from the end of a string. ```php {!! Form::textarea('mline', isset($mline) ? rtrim(str_replace('<br />', "\n", nl2br(strip_tags($mline))), "\n") : null, ['style'=>'height: 113px;width:150%;','class'=>'p-2']) !!} ``` Here, `rtrim(..., "\n")` removes any trailing newline characters from the text. This will ensure no extra line breaks at the end of the text.
I have to remove a student from a Sensei Pro course if they have completed the course. When they try to purchase the course again and WooCommerce generates an error preventing them from purchasing because they already have the course, I check if they have already completed the course, and if so, I remove them from the course. So far, I can get the course ID, which is the same as the page ID, but I can't get the course related to that product. ``` function alterar_mensagem_restricao_compra( $error ) { // Verifica se a mensagem padrão está presente if ( strpos( $error, 'Você já possui todos os cursos associados a este produto' ) !== false ) { global $post; $user = wp_get_current_user(); //$status = Sensei_Utils::user_started_course( intval( $course_id ), intval( $user->ID ) ); $produtos = Sensei_Course::get_product_courses(168); //$course = get_post_meta($post->ID, '_related_course', true); //return $status; if($produtos){ $error = 'Você ainda tem redações a serem enviadas/corrigidas. Você precisa enviar e receber todas as redações do pacote para poder adiquirir o mesmo pacote ou você pode adiquirir um pacote diferente.'.$status; }else{ $error = 'Você ainda tem redações '; } } return $error; } add_filter( 'woocommerce_add_error', 'alterar_mensagem_restricao_compra' ); ```
**Update** With `usmap >= 0.7.0` the issue is no longer reproducible as data objects are now returned as simple features. ``` r library(usmap) library(ggplot2) set.seed(123) # Merge state polygons with ranking data state_map_rankings <- merge(state_map, state_rankings, by.x = "abbr", by.y = "state" ) # Create the ggplot2 map ggplot(state_map_rankings, aes( fill = ranking )) + geom_sf(color = "black") + scale_fill_gradient2( low = "red", mid = "white", high = "green", midpoint = 0 ) + theme_void() + theme(legend.position = "bottom") ``` ![](https://i.imgur.com/I9kfDgx.png)<!-- --> **Original answer** The issue is that the points which define the polygon get connected in the order as in your data. However, the `merge` will reorder you data and the rows are no longer in the right order To fix that reorder or rearrange your data by both `group` and `order`: ``` r library(usmap) library(ggplot2) # Merge state polygons with ranking data state_map_rankings <- merge(state_map, state_rankings, by.x = "abbr", by.y = "state") state_map_rankings <- state_map_rankings[order(state_map_rankings$group, state_map_rankings$order), ] # Create the ggplot2 map ggplot(state_map_rankings, aes( x = x, y = y, group = group, fill = ranking )) + geom_polygon(color = "black") + scale_fill_gradient2( low = "red", mid = "white", high = "green", midpoint = 0 ) + theme_void() + theme(legend.position = "bottom") ``` ![](https://i.imgur.com/8cJhJY0.png)<!-- --> **DATA** ``` set.seed(123) state_rankings <- data.frame( state = c( "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY" ), ranking = runif(50, min = -2, max = 2) ) # Get state polygons state_map <- usmap::us_map(regions = "states") ```
null
How to install Microsoft.Build.CopyOnWrite into Visual Studio projects for optimizing a DevDrive?
Sure. Try this ``` SELECT XP, name, RANK() OVER (ORDER BY XP DESC) AS Ranking FROM UserExperience; ```
Assuming that your project is something like this: ``` ├── docker-compose.yml ├── Dockerfile ├── ormconfig.json ├── package.json ├── package-lock.json ├── src │   └── main.ts └── tsconfig.json ``` `docker-compose.yml` ``` version: "3.8" services: db: image: postgres environment: - POSTGRES_DB=taskmanagerdb - POSTGRES_USER=admin - POSTGRES_PASSWORD=mysecretpassword ports: - "5432:5432" logging: driver: "none" server: container_name: server build: . ports: - "3000:3000" depends_on: - db environment: - PGHOST=db ``` `Dockerfile` ``` FROM node:alpine COPY package*.json ./ RUN npm install COPY . . CMD npm start ``` `ormconfig.json` ``` { "type": "postgres", "host": "db", "port": 5432, "username": "admin", "password": "mysecretpassword", "database": "taskmanagerdb", "synchronize": true, "logging": false } ``` `package.json` ``` { "name": "TaskManager", "version": "0.0.1", "description": "Awesome project developed with TypeORM.", "devDependencies": { "@types/express": "^4.17.21", "@types/node": "^16.18.93", "ts-node": "^10.9.2", "typescript": "^4.9.5" }, "dependencies": { "class-transformer": "^0.5.1", "class-validator": "^0.14.1", "express": "^4.19.2", "pg": "^8.11.3", "reflect-metadata": "^0.1.14", "typeorm": "^0.3.20" }, "scripts": { "start": "ts-node src/main.ts", "typeorm": "typeorm-ts-node-commonjs" } } ``` `src/main.ts` (A script that connects to the database and executes a simple query.) ``` import "reflect-metadata"; import {createConnection} from "typeorm"; console.log("Connecting to DB..."); createConnection().then(async connection => { console.log("Done!"); const simpleQueryResult = await connection.query('SELECT 1;'); console.log('Simple query result:', simpleQueryResult); const tablesQueryResult = await connection.query('SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname=\'public\';'); console.log('Tables in public schema:', tablesQueryResult); }).catch(error => console.log(error)); ``` [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/MSsgq.png
|c++|function|lambda|c++17|
{"OriginalQuestionIds":[50548492],"Voters":[{"Id":5494370,"DisplayName":"Alan Birtles","BindingReason":{"GoldTagBadge":"c++"}}]}
```go package main import "fmt" func square(c chan int) { fmt.Println("[square] reading") num := <-c fmt.Println("[square] before writing") c <- num * num fmt.Println("[square] after writing") } func cube(c chan int) { fmt.Println("[cube] reading") num := <-c fmt.Println("[cube] before writing") c <- num * num * num fmt.Println("[cube] after writing") } func main() { fmt.Println("[main] main() started") squareChan := make(chan int) cubeChan := make(chan int) go square(squareChan) go cube(cubeChan) testNum := 3 fmt.Println("[main] sent testNum to squareChan") squareChan <- testNum fmt.Println("[main] resuming") fmt.Println("[main] sent testNum to cubeChan") cubeChan <- testNum // Why main not blocked here? fmt.Println("[main] resuming") fmt.Println("[main] reading from channels") squareVal, cubeVal := <-squareChan, <-cubeChan sum := squareVal + cubeVal fmt.Println("[main] sum of square and cube of", testNum, " is", sum) fmt.Println("[main] main() stopped") } ``` Why is it printed like that ??? Output: ``` 1.[main] main() started 2. [main] sent testNum to squareChan 3. [cube] reading 4. [square] reading 5. [square] before writing 6. [main] resuming 7. [main] sent testNum to cubeChan 8. [main] resuming 9. [main] reading from channels 10. [square] after writing 11. [cube] before writing 12. [cube] after writing 13. [main] sum of square and cube of 3 is 36 14. [main] main() stopped ``` 2 questions: 1) Why after call "squareChan <- testNum" scheduler first check cube goroutine instead of square goroutine? 2) Why after call "cubeChan <- testNum" main goroutine not blocked? Please can somebody explain by steps - How exactly scheguler switch between square, cube and main goroutines in this code?
|node.js|mongodb|mongoose|mongoose-schema|
If you want to use chrono for time stampping, add chrono in Cargo.toml file. ex) [dependencies] chrono = "=0.4.37"
I have been asked in one of the Top company below question and I was not able to answer. Just replied : I need to update myself on this topic **Question :** **If you create a composite indexing on 3 columns (eid , ename , esal ) ?** - If i mention only eid=10 after where clause will the indexing be called ? - If I mention only eid=10 and ename='Raj' will the indexing be called ? - If I mention in different order like esal=1000 and eid=10 will the indexing be called ? - If I mention in reverse order like esal = 1000 and ename = 'Raj' and eid = 20 will the indexing be called ? Need a solution for this need with detail table representation with data how it does?
Need some detail explanation regarding index skip scan
|oracle|indexing|
You change the event listener so that it listens for the submit event: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> class Transaction { constructor(getal, afzender, ontvanger) { this.getal = getal; this.afzender = afzender; this.ontvanger = ontvanger; // Set the clicker this.form = document.forms.form01; this.form.addEventListener('submit', this.handleSubmit); } print() { console.log(`${this.afzender} sent ${this.getal} bits to ${this.ontvanger}`); } emptyInputs() { document.querySelector('#bedrag').value = ''; document.querySelector('#verzender').value = ''; document.querySelector('#ontvanger').value = ''; } handleSubmit(event) { event.preventDefault(); const p = document.querySelector('.confirmation'); p.style.color = 'green'; const bedrag = document.querySelector('#bedrag').value; const verzender = document.querySelector('#verzender').value; const ontvanger = document.querySelector('#ontvanger').value; const transaction = new Transaction(bedrag, verzender, ontvanger); transaction.print(); // Optionally, print the transaction details transaction.emptyInputs(); // Clear the input fields p.innerText = "Transaction made!"; } } const transaction = new Transaction("", "", ""); <!-- 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>Document</title> <link href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha2/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container d-flex justify-content-center align-items-center flex-column"> <h2>Maak een transactie</h2> <form name="form01" class="form-group"> <div> <label for="bedrag">Bedrag:</label> <input type="number" class="form-control" id="bedrag" name="bedrag"> </div> <div> <label for="verzender">Verzender:</label> <input type="text" class="form-control" id="verzender" name="verzender"> </div> <div> <label for="ontvanger">Ontvanger:</label> <input type="text" class="form-control" id="ontvanger" name="ontvanger"> </div> <button type="submit" id="clicker" class="btn btn-primary mt-2 ">Submit</button> </form> <p class="confirmation"></p> </div> <script src="Transaction.js" type="module"></script> </body> </html> <!-- end snippet -->
Hibernate SQL Error: Missing FROM-clause entry for table "th1_1"
|java|spring-boot|hibernate|jpa|spring-data-jpa|
null
There you go(exactly as you want): [`JSFiddle`][1] [1]: http://jsfiddle.net/BANDP/2/ ------------ ##CSS## ``` css body { width: 500px; font-family: helvetica; font-size: 12px; counter-reset: section; } ol li ol { padding-left: 0px; } ol li ol li { padding-left: 20px; } ``` ##HTML## ``` html <ol> <li> <strong>The Card</strong> <ol> <li> <p>When you receive your Card, you will receive a PUK and you must choose a PIN.</p> </li> <li> <p>You must either memorise the PIN or keep record of it in a safe place, separate from your Card. Do not tell anyone your PUK or PIN.</p> </li> </ol> </li> </ol> ```
null
There you go (exactly as you want): [JSFiddle][1] [1]: http://jsfiddle.net/BANDP/2/ ------------ CSS ``` css body { width: 500px; font-family: helvetica; font-size: 12px; counter-reset: section; } ol li ol { padding-left: 0px; } ol li ol li { padding-left: 20px; } ``` HTML ``` html <ol> <li> <strong>The Card</strong> <ol> <li> <p>When you receive your Card, you will receive a PUK and you must choose a PIN.</p> </li> <li> <p>You must either memorise the PIN or keep record of it in a safe place, separate from your Card. Do not tell anyone your PUK or PIN.</p> </li> </ol> </li> </ol> ```
I gave it the Wikipedia article about Power BI. I then asked my Copilot a basic question like "What is Power BI?", and it said that it can't help me with that. Either this thing is completely useless or I'm doing something wrong. For some reason, I didn't find any articles about this issue online. Has anyone had this issue? How do you fix it?
Microsoft Copilot Studio is ignoring the sources that I'm feeding it
|microsoft-copilot|
You should sort the list of integers in descending order and then iterate through it, adding each number to the list with the smaller current sum, like the following: ```python import random intList = [] for i in range(10): intList.append(random.randint(10, 200)) listX = [] listY = [] intList.sort(reverse=True) sumX = 0 sumY = 0 for num in intList: if sumX <= sumY: listX.append(num) sumX += num else: listY.append(num) sumY += num print(f"listx = {listX} \nlisty = {listY}\n sum x = {sumX}, y = {sumY}") ``` ## Edit To ensure that both lists have exactly 5 elements and maintain balanced lengths, you can modify the algorithm to distribute the numbers based on the lengths of the lists. If one list has fewer than 5 elements, prioritize it adding numbers to that list until it reaches 5 elements. Try this: ```python import random intList = [] listX = [] listY = [] for i in range(10): num = random.randint(0, 5) intList.append(num) intList.sort(reverse=True) sumX = 0 sumY = 0 for num in intList: if len(listX) < 5: listX.append(num) sumX += num elif len(listY) < 5: listY.append(num) sumY += num elif sumX <= sumY: listX.append(num) sumX += num else: listY.append(num) sumY += num print(f"listx = {listX} \nlisty = {listY}\n sum x = {sumX}, y = {sumY}") ```
I have two identical C++ classes that are instantiated from within a lambda which is run in a separate thread. Below are the two classes: ```c++ class A : public C { std::thread thr; void thrFunction(X &x) { while(atomic<bool>){ //long running process } } public: A(); int start(X &x) { thr = std::thread(&A::thrFunction, this, std::ref(x)); //Throwing Error C2672 at compile-time return 0; } }; class B : public C { void thrFunction(X &x) { while(atomic<bool>){ //long running process } } public: A(); int start(X &x) { thrFunction(x); //blocking call return 0; } }; ```` These classes' objects are used from within another class `X`: ```c++ class X { A *a; B *b; public: X(); void cleanup(); int callMembers() { a->start(*this); b->start(*this); } }; ```` This is how these classes are used: ```c++ int main() { X *api = new X() auto lbda = [](X *api) { api->callMembers(); //meant to block here api->cleanup(); } std::thread(lbda, api); while(true) { sleep(10); } } ```` This code doesn't compile and throws this error: > C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.39.33519\include\thread(60,14): error C2672: std::invoke': no matching overloaded function found The error is due to the thread constructor call in `class A`. I have tried to fix it by searching for a solution on the Internet, but to no avail. Almost all of the solutions suggested are changing the thread instantiation syntax, but nothing has worked so far. After some changes, the compiler error changes to: > C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.39.33519\include\memory(3434,35): error C2661: 'std::tuple\<void (__cdecl A::* )(X &),A *,X>::tuple': no overloaded function takes 3 arguments No matter what I try, I cannot get it to compile. Maybe there is something related to the class hierarchy which is causing this error? That is why I shared the whole structure of the involved classes and members. Can someone please help me resolve this error?
I've been enjoying the convenience of the Black Formatter extension in Visual Studio Code, especially its "Format on Save" feature for Python files. Being able to automatically format my code upon saving with Ctrl+S has significantly streamlined my workflow. However, I've encountered a limitation when working with Jupyter notebooks (.ipynb files) in VSCode. While the Black Formatter seamlessly formats .py files on save, I've noticed that formatting code within Jupyter notebooks requires manually triggering the format command for each cell using Alt+Shift+F. This inconsistency in the user experience between .py files and .ipynb files disrupts the workflow and diminishes the efficiency gained from the "Format on Save" feature for Python scripts. I'm reaching out to see if anyone has found a solution or a workaround to extend the "Format on Save" functionality to Jupyter notebooks within VSCode. Ideally, I'm looking for a method to automatically format all code cells in a notebook when saving the notebook file, similar to how it works for .py files. Has anyone else experienced this issue or found a way to make code formatting as effortless in .ipynb files as it is in .py files within VSCode? Any advice, plugins, or settings recommendations that could help achieve this would be greatly appreciated. In my quest to streamline my development workflow, I've successfully configured the Black Formatter extension in VSCode to automatically format Python (.py) files on save, using the following settings in my settings.json: ```json "[python]": { "editor.defaultFormatter": "ms-python.black-formatter", "editor.formatOnSave": true } ``` This setup works perfectly for Python scripts, automatically formatting them each time I press Ctrl+S, aligning with my expectations for a seamless and efficient coding experience. Transitioning to Jupyter notebooks within VSCode, my expectation was to replicate this level of automation. Given the widespread use of notebooks for data science and machine learning projects, automating code formatting within these notebooks would greatly enhance productivity. I anticipated that either the same settings would apply or there would be a straightforward alternative for .ipynb files. What I tried was to apply the same logic and settings, hoping VSCode would interpret and extend the "Format on Save" feature to the cells of Jupyter notebooks. I explored the VSCode and Black Formatter extension settings but found no direct reference or solution for applying automatic formatting to .ipynb files upon saving, similar to .py files. What I'm seeking is either a confirmation that this functionality currently doesn't exist for .ipynb files in VSCode or guidance on a workaround. Perhaps a different configuration or an extension that bridges this functionality gap? Any shared experience, advice, or solution that would allow for automatic formatting of Jupyter notebook cells on save, enhancing the consistency and efficiency of the development process within VSCode, would be invaluable.
How to get course_id of a woocommerce product page?
|woocommerce|woothemes|
null
{"OriginalQuestionIds":[17226762],"Voters":[{"Id":2943403,"DisplayName":"mickmackusa","BindingReason":{"GoldTagBadge":"php"}}]}
Return a pointer to the `Node` of interest instead of updating the out parameter `head_dest`. The current implementation changes the original list. To create a new list you need to return a pointer to copy of the smallest node or NULL. To emphasize that I made the argument constant with `const Node *head`. ``` #include <stdio.h> #include <stdlib.h> typedef struct Node { int val; struct Node *pt_next; } Node; Node *linked_list_new(int val) { Node *n = malloc(sizeof *n); if(!n) { printf("malloc failed\n"); exit(1); } n->val = val; return n; } Node *linked_list_create(size_t n, int *vals) { Node *head = NULL; Node **cur = &head; for(size_t i=0; i < n; i++) { *cur = linked_list_new(vals[i]); if(!head) head = *cur; cur = &(*cur)->pt_next; } *cur = NULL; return head; } void linked_list_print(Node *head) { for(; head; head=head->pt_next) printf("%d->", head->val); printf("NULL\n"); } void linked_list_free(Node *head) { while(head) { Node *tmp = head->pt_next; free(head); head=tmp; } } Node *pairWiseMinimumInNewList_Rec(const Node* head) { Node *tmp; if ( (head && head->pt_next && head->val < head->pt_next->val) || (head && !head->pt_next) ) { tmp = linked_list_new(head->val); tmp->pt_next = pairWiseMinimumInNewList_Rec(head->pt_next ? head->pt_next->pt_next : NULL); } else if (head && head->pt_next) { tmp = linked_list_new(head->pt_next->val); tmp->pt_next = pairWiseMinimumInNewList_Rec(head->pt_next->pt_next); } else tmp = NULL; return tmp; } int main() { Node *head=linked_list_create(7, (int []) {2,1,3,4,5,6,7}); Node* head_dest=pairWiseMinimumInNewList_Rec(head); linked_list_print(head); linked_list_free(head); linked_list_print(head_dest); linked_list_free(head_dest); } ``` If you want you can compress the implementation by observing that it returns a NULL (base case) or a copy of a either the first or the 2nd node. The recursive call is either two nodes ahead or we are done: ``` Node *pairWiseMinimumInNewList_Rec(const Node* head) { if(!head) return NULL; Node *tmp = linked_list_new( (head->pt_next && head->val < head->pt_next->val) || (!head->pt_next) ? head->val : head->pt_next->val ); tmp->pt_next = pairWiseMinimumInNewList_Rec(head->pt_next ? head->pt_next->pt_next : NULL); return tmp; } ``` I used a little more interesting test case that exercises the main two code paths: ``` 2->1->3->4->5->6->7->NULL 1->3->5->7->NULL ```
Im trying to increase the accuracy of my model, in order to predict x-ray images, and im working with a mobileNetv3, as my backbone model, as well, as using a customised CNN to make the prediction. [my val_accurary is very volatile](https://i.stack.imgur.com/QqoNL.png) how can i increase the accuracy/performance of my model, using this following architcture:[my model architcture](https://i.stack.imgur.com/gGxv7.png)
Pneumonia detection, using transfer learning
I had to use "OriginValidator" instaed of "AllowedHostsOriginValidator" and set a list of valid domains. [here][1] [1]: https://channels.readthedocs.io/en/latest/topics/security.html
The bellow Java Vector API code has a DoubleVector filled with doubles, named "A1". I am trying to convert this DoubleVector (A1) to IntVector (RESULT), so far unsuccessful. ``` double[] v1 = {10237, 10709, 11340, 11468, 11771, 12003, 12196, 12456, 13904, 14557, 14636, 14811, 15337, 15468, 15719, 15990}; double[] v2 = {150, 171, 180, 183, 184, 289, 301, 306, 358, 449, 486, 539, 567, 605, 643}; int[] result = new int[v1.length]; var species = DoubleVector.SPECIES_PREFERRED; for (int index = 0; index < v1.length; index += species.length()) { var V1 = DoubleVector.fromArray(species, v1, index); var V2 = DoubleVector.fromArray(species, v2, index); DoubleVector A1 = V1.div(V2).pow(2); //Create IntVector RESULT by the convertion of DoubleVector A1 to IntVector. RESULT.intoArray(result, index); } ``` EDIT 1: After more research on the subject, the updated code is: ``` double[] v1 = {10237, 10709, 11340, 11468, 11771, 12003, 12196, 12456, 13904, 14557, 14636, 14811, 15337, 15468, 15719, 15990}; double[] v2 = {150, 171, 180, 183, 184, 289, 301, 306, 358, 449, 486, 539, 567, 605, 643}; int[] result = new int[v1.length]; var species = DoubleVector.SPECIES_PREFERRED; for (int index = 0; index < v1.length; index += species.length()) { var V1 = DoubleVector.fromArray(species, v1, index); var V2 = DoubleVector.fromArray(species, v2, index); DoubleVector A1 = V1.div(V2).pow(2); //Create IntVector RESULT by the convertion of DoubleVector A1 to IntVector. IntVector RESULT = A1.convert(VectorOperators.D2I, index).reinterpretAsInts(); // <--- I need help to write this line correctly. RESULT.intoArray(result, index); } ``` There is an error message related to the size difference between double and int, that says: `bad part number 4 converting Species[double, 4, S_256_BIT] -> Species[int, 8, S_256_BIT] (lanes are contracting by 2)`.
You can reduce your set of interfaces as `{ a: A; } | { a: A; b: B; }` is `{ a: A; b?: B; }`: interface ButtonOnlyText extends React.ButtonHTMLAttributes<HTMLButtonElement> { text: string; } interface ButtonOnlyIcon extends React.ButtonHTMLAttributes<HTMLButtonElement> { Icon: React.FunctionComponent<React.SVGProps<SVGSVGElement>>; iconProps?: React.SVGProps<SVGSVGElement>; } interface ButtonTextAndIcon extends React.ButtonHTMLAttributes<HTMLButtonElement> { text: string; Icon: React.FunctionComponent<React.SVGProps<SVGSVGElement>>; iconProps?: React.SVGProps<SVGSVGElement>; } Then you can't declare `Button` as function Button({ text, Icon, iconProps, ...buttonProps }: ButtonProps) Simply because there are interfaces in your disjunction that don't have the props you're trying to access. Typescript will tell you that these properties are not defined. All you can do is declare it as function Button(props: ButtonProps) And then have some code that'd work like this: const buttonProps = restrict(props).toAllBut(["text", "Icon", "iconProps"]); And query for the props you want to access like this: if ("text" in props && "Icon" in props) // ButtonTextAndIcon And handle all cases as you please.
what is it" same network meta-analysis object is used for arguments x and y" from netleague order?
|r|
null
I manage Firefox settings under Linux with a file policies.json placed in `/etc/firefox/policies`. I now also installed Firefox Nightly on the same machine. It also seems to use the policies.json file. Is it possible to make the policies.json directives apply only to Firefox but not to Firefox Nightly? How?
Apply Firefox policies.json only to Firefox but not to Nightly
|firefox|
I'm trying to add service principal Databricks managed on azure and put account level permissions with terraform like this: [![enter image description here][1]][1] **Error: cannot create mws permission assignment: Endpoint not found for /2.0/accounts/4f93b050-9cee-4668-8136-7937fe98f18e/workspaces/6491331033656740/permissionassignments/principals/187629890527464** **terraform:** ``` provider "databricks" { azure_workspace_resource_id = azurerm_databricks_workspace.tramontina_workspace.id host = azurerm_databricks_workspace.tramontina_workspace.workspace_url auth_type = "azure-cli" } resource "azurerm_databricks_workspace" "xxxxx_workspace" { name = "ADM-Databricks-xxxx" resource_group_name = var.resource_group_name location = var.region sku = "premium" custom_parameters { storage_account_name = "admdatalakedevxxxxx${random_string.naming.result}" } } resource "databricks_service_principal" "principal" { display_name = "databricks-adm" allow_cluster_create = true workspace_access = true databricks_sql_access = true } resource "databricks_group_member" "i-am-admin" { group_id = data.databricks_group.admins.id member_id = databricks_service_principal.principal.id } resource "databricks_mws_permission_assignment" "add_admin_group" { workspace_id = azurerm_databricks_workspace.xxxxx_workspace.workspace_id principal_id = databricks_service_principal.principal.id permissions = ["ADMIN"] } ``` [1]: https://i.stack.imgur.com/YkOTH.png
Problem to add service principal permissions with terraform
|azure|terraform|databricks|azure-databricks|
I have a NSString that has two characters. The NSSring looks something like this > FW I use this code to capture the first character: NSString *firstStateString = [totInstStateString substringToIndex:1]; This piece of code returns F, I would like to know how to return the second character to its own string using substringToIndex.
How to capture a single character from NSString using substringToIndex
I have a data table I've imported into PowerBI from an csv that is a large list of exam results. Each row represents the details of when that particular exam was taken by a particular student. Some students will have taken the same exam more than once resulting in multiple rows for the same student/subject. | SUBJECT | STUDENT | DATE | | -------- | -------- | -------- | | English | Fred | Feb | | Maths | Stuart | May | | Science | Fred | Feb | | Maths | Simon | Mar | | Science | Peter | June | | English | Peter | June | | English | Fred | Oct | | Maths | Paul | June | | Maths | Fred | Jan | | English | Stuart | June | I'm trying to find a query that will return a count of the unique number of students that have taken a particular combination of subjects. So, for the example above, how many students have taken both English **and **Maths? The correct return would be **2** as only fred and stuart have taken both subjects. I'm very new to DAX and have tried nesting a range of different statements but just can't figure this out? Nothing seems to get even close to the result needed.
{"OriginalQuestionIds":[77850320],"Voters":[{"Id":5825294,"DisplayName":"Enlico"},{"Id":-1,"DisplayName":"Community","BindingReason":{"DuplicateApprovedByAsker":""}}]}
You need to set the selected value in OnValueChange() event like const [selectedCourse,setSelectedCourse]=useState(state.courses[0]); <Picker style={styles.picker} selectedValue={selectedCourse} onValueChange={(itemValue) => { setSelectedCourse(itemValue); getUserScores(itemValue); }} > {state.courses.map((course) => ( <Picker.Item key={course.name} label={course.name} value={course} /> ))} </Picker>
If I want to use borrowed parameters in ```tokio::spwan```, as in the following function, how to solve the error of "borrowed data escapes outside of function"? ``` async fn error(param: &str){ let _ = tokio::spawn(async move { println!("string is {:?}", param); }).await; } ``` full error ``` error[E0521]: borrowed data escapes outside of function --> src/main.rs:11:13 | 10 | async fn error(param: &str){ | ----- - let's call the lifetime of this reference `'1` | | | `param` is a reference that is only valid in the function body 11 | let _ = tokio::spawn(async move { | _____________^ 12 | | println!("string is {:?}", param); 13 | | }).await; | | ^ | | | | |______`param` escapes the function body here | argument requires that `'1` must outlive `'static` ``` Since the database connection is passed as a borrowed parameter, I'm not quite sure how this can be resolved...
A tokio::spawn related lifetime issue
|lifetime|rust-tokio|
null
I need a solution to my problem. i need a way for my navmesh_agent. to detect and follow a prefab clone instead of a gameobject already inside of the scene. to give some intel i am trying to add multiplayer to my zombie game, and as you may know to use multiplayer in unity you will need to spawn a new player each time incase of player joining. ive tried, creating a prefab of the player, and deleting the one in the scene having the nav mesh straight up, follow the prefab starting runtime, and dragging the prefab into the scene. Unfortunately i am not able to think of another solution. ``` using UnityEngine; using UnityEngine.AI; public class ZomWalkerAI : MonoBehaviour { public GameObject Zom1DW; public GameObject Zom1I; public GameObject Zom1NB; public Transform Playerpos; public bool TouchingPlayer = false; UnityEngine.AI.NavMeshAgent agent; public bool inRange = false; // Start is called before the first frame update void Start() { agent = GetComponent<UnityEngine.AI.NavMeshAgent>(); Zom1DW.SetActive(false); Zom1NB.SetActive(false); Zom1I.SetActive(false); } void Update() { if (TouchingPlayer == true) { Zom1I.SetActive(false); Zom1NB.SetActive(true); Zom1DW.SetActive(false); } if (inRange == false) { Zom1I.SetActive(true); Zom1NB.SetActive(false); Zom1DW.SetActive(false); } if (inRange == true) { if(TouchingPlayer == false) { Zom1DW.SetActive(true); Zom1I.SetActive(false); Zom1NB.SetActive(false); agent.destination = Playerpos.position; } } } void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "Player") { inRange = true; } } void OnTriggerExit(Collider other) { if (other.gameObject.tag == "Player") { inRange = false; Zom1DW.SetActive(false); ```
**i try to send email with set email image ** > Next to the message title there is a small picture. I am trying to change it to reflect the nature of the email sent in each sending process > [enter image description here](https://i.stack.imgur.com/23PpW.jpg) ``` def check(line): arre = str(line).split(':') print(arre) mail_username="username" mail_password="password" try: from_addr = mail_username to_addrs=('myemail@gmail.com') HOST = "smtpDomain" print(HOST) PORT = 587 smtp = smtplib.SMTP(HOST) smtp.connect(HOST,PORT) time.sleep(2) smtp.ehlo() smtp.starttls() try: smtp.login(mail_username,mail_password) print ("goodlogin") smtp.set_debuglevel(1) msg = MIMEMultipart() msg['From'] = "emample@example.com" msg['To'] = to_addrs msg['Reply-to'] = "emample@example.com" msg['Subject']='test message' msg.add_header('Content-Type', 'text/html') data = line msg.attach(MIMEText(data, 'html', 'utf-8')) print(smtp) smtp.sendmail(from_addr,[msg['To']],msg.as_string()) print ("done") except Exception as ee: print( ee) smtp.quit() except Exception as ee: print ("asd") print (ee) ``` I need help on how to send a different image