instruction
stringlengths
0
30k
https://www.zaproxy.org/ The Zed Attack Proxy (ZAP) is an easy to use integrated penetration testing tool for finding vulnerabilities in web applications. It is designed to be used by people with a wide range of security experience and as such is ideal for developers and functional testers who are new to penetration testing. ZAP provides automated scanners as well as a set of tools that allow you to find security vulnerabilities manually.
|git|github|repository|
|perl|openssl|pbkdf2|
Perhaps there is a more elegant way, but I see that it can be done with [media queries][1]<br> You can decide which minimal gap should be between plots, add it for their overall width and make this value as `max-width` of a query.<br> Example:<br> > if 3 charts 900x600 can fit the screen then place them We need to have 3 charts with 900 width, so their overall width is **900px * 3 = 2700px**.<br> And minimal gap should be something like **10px** (it can be any value that you want). You want have 3 items so it will be 2 gaps between them. And you have `justify-content: space-around;` so you need 2 halfs of the gap that is **5px** each to make gaps minimal value **10px**. Therefore 2 gaps and 2 half gaps at the borders of a line and it is **(10px * 2) + (5px * 2) = 30px**. <br> We got whole minimal width for your line: **2700px + 30px = 2730px** <br> @media (max-width: 2730px){ .chart { width: 600px; height: 400px; } } And you need to create such queries for all your cases.<br> Each query will handle the case when the minimal possible width was overcome and we need to show smaller charts [1]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries
I am trying to php artisan queue:work command but it's killed the process and give me an error like this [2024-03-28 10:10:20] local.ERROR: Call to a member function beginTransaction() on null {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call to a member function beginTransaction() on null at /vendor/laravel/framework/src/Illuminate/Database/Concerns/ManagesTransactions.php:108) I am using worker in server but that is not my issue but when i custom try PHP artisan queuq:work its' give an error. thanks in advanced I want to run the command and do the job work in laravel.
When am trying to php artisan queue:work it's kill the process and give me error log Call to a member function beginTransaction()
|laravel|jenssegers-mongodb|
null
**Edit #3: Final update:**<br> @SupportUkraine recently updated their (OP accepted) answer to provide two solutions; one version using a `struct`, and the other without using a compound datatype (with the inevitable cost of foreseeably lower performance.) Below is a similar solution employing a data manipulation technique that some might find somewhat easier to understand. The OP's code mistakenly focuses on the _Most Significant Digit_ when, as demonstrated by debugging values down below, it is the _Least Significant Digit_ that "levels out" values of different magnitudes for those values to be sorted into the positions that solve this task. ``` #include <stdio.h> #include <stdint.h> /* uint##_t */ #include <stdlib.h> /* qsort() */ uint32_t cnvrt( uint32_t x ) { // convert value for comparison // EG: // single digit 7: ( 76 => 7666) < ( 7 => 7777) < (779 => 7799) // or // double digit 55: (520 => 5200) < (55 => 5555) < (556 => 5566) // or double digit resulting in duplication: // 10 => 1000 so: (10 => 1000) == (1000)... What to do?? // ... tie breaker in cmp() returns original "10" vs "1000" // ... and considers 10 > 1000 to achieve desired DESCENDING sequencing if( x < 10 ) x = x * 1111; // 4 digits. 3 ==> 3333 else if( x < 100 ) x = x * 100 + x%10*11; // 4 digits. 27 ==> 2777 else if( x < 1000 ) x = x * 10 + x%10; // 4 digits. 734 ==> 7344 // else x = 1000; // not needed return x; } int cmp( const void *p0, const void *p1 ) { uint32_t xOrg = *(uint32_t*)p0, xCnv = cnvrt( xOrg ); uint32_t yOrg = *(uint32_t*)p1, yCnv = cnvrt( yOrg ); // NB: descending sort order wanted here return (xCnv < yCnv) ? 1 : (xCnv > yCnv) ? -1 : (xOrg > yOrg) // converted are equal, so original determines sort order ? 1 : (xOrg < yOrg) ? -1 : 0; // only 1000 vs 1000 requires this 0 ('equal') return value } uint32_t arr[] = { 5, 5, 532, 10, 55, 56, 1000, 54, 54, 78, }; const size_t n = sizeof arr/sizeof arr[0]; int main( void ) { size_t i; // original sequence for( i = 0; i < n; i++ ) printf( ",%u" + !i, arr[ i ] ); puts( "" ); qsort( arr, n, sizeof arr[0], cmp ); // reordered with separators to check for( i = 0; i < n; i++ ) printf( ",%u" + !i, arr[ i ] ); puts( "" ); // compressed result for( i = 0; i < n; i++ ) printf( "%u", arr[ i ] ); puts( "" ); return 0; } ``` Credit and thanks to @SupportUkraine for pointing out a productive direction for achieving the desired outcome while doing data manipulation "_on-the-fly_". It would be remiss of me to not acknowledge the heavier burden imposed on the processor by the modulo calculations used in this code. On the other hand, this technique would continue to work (still using only `uint32_t` values) if the data range was increase from 1-to-1000 up to 1-to-100'000'000 (ie. 9 digits instead of only 4.) Following are two older versions of this answer submitted in recent days. <hr> >Or is there any easier and obvious method to solve this problem ? The OP's code demonstrates a valiant attempt to transform array values for ordering to fulfill the task. As often happens, fixating on given parameters blinds one to simpler alternatives. Sadly, trying to debug the OP's code would only contribute to venturing farther down the rabbit hole. This problem is a case study for brute-force "permutations" seeking a "_best_" value.<br>It is a variation of "The Travelling Salesman Problem." The "_nut to be cracked_" is finding/coding an algorithm to solve the problem. The gathering and verification of numeric user input is not the issue. For simplicity, the code below uses compile-time _string_ representations of sample data. Conversion of an array of values to its equivalent as strings is left as an exercise for the reader. ``` #include <stdio.h> #include <string.h> char *elements[] = { "532", "5", "55", "56" }; // sample data const int nElements = sizeof elements/sizeof elements[0]; int used[ nElements ]; // flags denoting availability of each element during recursion char out[ 128 ]; // big enough to serve this example void go( size_t k, char *p ) { // working copy of string, so far char wrk[ 128 ], *at = wrk + strlen( strcpy( wrk, p ) ); for( size_t i = 0; i < nElements; i++ ) if( !used[i] ) { // grab next available element strcpy( at, elements[ i ] ); // in turn, 'tack' each element as a suffix if( k+1 == nElements ) { // at the extent of recursion if( strcmp( wrk, out ) > 0 ) { // is this "better" (ie. "larger")? strcpy( out, wrk ); // preserve as "best so far" // puts( out ); // debugging showing improving results } return; } used[i] = 1; // mark this element 'used' go( k+1, wrk ); // next level, please used[i] = 0; // this element now available } } int main( void ) { go( 0, out ); puts( out ); // the final result return 0; } ``` Result with "progress debugging" enabled: ```none 53255556 // notice each reported value is larger than the previous 53255655 53256555 55325556 55325655 55553256 55556532 55653255 55655532 56532555 56553255 56555532 56555532 // final result ``` The usual prohibition against using "global variables" has been ignored here for the sake of clarity. The variables could be passed to `go()` as (cluttering) parameters. NB: Were there 1000 elements, each possibly 3 digits long, it's obvious this code's tiny buffers would not work. Perhaps another exercise is to judiciously allocate enough dynamic storage. Perhaps another exercise is to use just two buffers; one for the "so far" achieved result, and the other that is "cleaned up" (re-terminated) when one level of recursion is 'popped'. **EDIT:**<br>The code above will try ALL permutations, even when a previous permutation may be, for instance, "345678..." and the current version is prefixed "345111...". Obviously, the finished result of this exploration will compare as less than what has already been achieved. Further work on this (many levels of permuting to go) will be senseless. Another exercise for the reader may be to detect this condition early and 'prune' the search of that branch of the tree. **EDIT #2:**<br>Motivated by the (frightening) insight shared by @SimonGoater below, here's another version that won't occupy a processor with examining (worst case) 100! permutations. <br>(100! is 93326215 x 10<sup>150</sup> plus change. Thanks, Simon!) >"_I have no knowledge of data structures or something like that._" There's no time like the present to start learning. A term related to "_programming_" is "_data processing_". In order to work with data, one must learn about _data structures_. The following uses a simple C `struct` to _bind_ each original value in the data array to an appropriate generated value useful for sorting. (Note the use of the thoroughly tested library function `qsort()`. DIY sorting implementations are hard for a reader to trust.) Note: the (magic) constant `1000`. Base10 comes from the problem constraint `1 <= x <= 1000`. Zero is an invalid value, as are values greater than 1000. Because of the _promotion_ of smaller values to a value useful for sorting, care must be taken to not overflow the decimal representation provided by, in this example, an `unsigned long`. Eg: if the problem changed and the range maximum increased, the value `9` might be _promoted_ to `99'999`. As this is `>65'535`, a `uint16_t` datatype would overflow. Be forewarned. ``` #include <stdio.h> #include <stdint.h> #include <stdlib.h> /* qsort() */ typedef struct { uint32_t org; // original value uint32_t nrm; // 'normalised' (prefix) } Arr; int cmp( const void *p0, const void *p1 ) { Arr *px = (Arr*)p0; Arr *py = (Arr*)p1; // if normalised are equal, use original to determine if one is larger if( px->nrm == py->nrm ) return px->org - py->org; // NB: descending return py->nrm - px->nrm; // NB: descending } Arr arr[] = { {5}, {5}, {532}, {10}, {55}, {56}, {1000}, {54}, {54}, {78}, }; const size_t n = sizeof arr/sizeof arr[0]; int main( void ) { size_t i; // show original sequence for( i = 0; i < n; i++ ) printf( "%s%d", "," + !i, arr[ i ].org ); puts( "" ); // 'normalise' small values of arr[] so all are in a "prefix" range for( i = 0; i < n; i++ ) { arr[ i ].nrm = arr[ i ].org; // duplicate value here while( arr[i].nrm < 1000 ) arr[i].nrm = (uint32_t)( arr[i].nrm*10 + arr[i].nrm%10 ); // reproduce low value digit printf( "%4d (%d)\n", arr[ i ].org, arr[ i ].nrm ); // debugging } qsort( arr, n, sizeof arr[0], cmp ); // show reordered with separators to check for( i = 0; i < n; i++ ) printf( "%s%d", "," + !i, arr[ i ].org ); puts( "" ); // show compressed result for( i = 0; i < n; i++ ) printf( "%d", arr[ i ].org ); puts( "" ); return 0; } ``` Result: ```none 5,5,532,10,55,56,1000,54,54,78 // original sqnc 5 (5555) // debugging reveal 5 (5555) 532 (5322) 10 (1000) 55 (5555) 56 (5666) 1000 (1000) 54 (5444) 54 (5444) 78 (7888) 78,56,5,5,55,54,54,532,10,1000 // reordered 785655555454532101000 // compressed ``` Upon reflection, the OP's _intent_ comes into view. Kudos for the effort! Hopefully this code demonstrates another approach wherein it is not attempting to do mysterious things with values _on-the-fly_.
One may argue that JavaScript does not have "nested" classes as such -- there is no way for a class to use parent class scope, for instance, nor would it be meaningful for anything but accessing parent class properties (`static` elements). A class in JavaScript is just an object like any other, so you may as well define one and refer to it with a property on another class: class Chess { } Chess.Square = class { }; (yes, a name for a class is optional -- above, the `Square` property on `Chess` refers to a class _without name_; not necessarily great for debugging and introspection, but just illustrating a point here) Having the above, you can do things like: new Chess.Square(); And generally everything else you do with a class or objects of a class -- `new` simply expects a function that will act as a constructor, and `class` declarations actually "decay" into constructor functions when program is run -- values of all of the following expressions are true: * `Chess instanceof Function` * `typeof Chess == "function"` * `Chess.Square instanceof Function` * `typeof Chess.Square == "function"` * `Chess.prototype.constructor == Chess` * `Chess.Square.prototype.constructor == Chess.Square` So have nested *constructors*, then -- now that we've established that a JavaScript class is essentially its constructor. Well, there is _some_ extra metadata associated with every class by ECMAScript, and *some* differences, but it has no negative implications on being able to nest constructors to access outer scope: ``` function Chess() { const chess = this; function Square() { /// Obviously, this function/constructor/class is only available to expressions and statements in the Chess function/constructor/class (and if explicitly "shared" with other code). Chess; /// Refers to the outer constructor/class -- you can do `new Chess()` etc this; /// Refers to this Square object being created chess; /// Refers to what `chess` declared outside this method, refers to at the time of creating this Square object } } ``` The above uses what is known as "closures", which kind of require you to have a good grasp on how _scoping_ works in JavaScript. In Java, the `Square` class as specified above, would be known as a nested *instance* class, as opposed to a nested *static* class. The first example at the very top of the answer, using `class` keyword, does specify a form of the latter, though (a "static" class). Here is yet another way to define an "instance" class `Square`: ```javascript class Chess { constructor() { this.Square = class { constructor() { /// Be vigilant about `this` though -- in every function (except arrow functions) `this` is re-bound, meaning `this` in this constructor refers to an instance of the anonymous class, not to an instance of the `Chess` class; if you want to access the latter instance, you must have a reference to it saved for this constructor to access, e.g. with the `const chess = this;` statement in `Chess` constructor somewhere } }; /// Every `Chess` object gets a _distinct_ anonymous class referred to with a property named `Square`; is a class for every object expensive? is it needed? is it useful? } } ``` The thing with JavaScript is that it, for better or worse, makes it possible to implement OOP in a bit more than one way, certainly more so than some of the other "OOP languages" allow, and "nested classes" can mean different things, to different people, and in different programs. This is known as "having a lot of rope to hang yourself with" -- a lot of facility that may either help you implement your intended model elegantly, and/or make your code hard to read (especially to people who don't know as much JavaScript as you) and debug. It's a trade-off one needs to address before going all in with "nested classes".
I am using vue-3 and I like to insert a emoji into a textarea. I have a EmojiPicker component to select emojis. It works well. My problem is that, after I insert a emoji, the textarea shows the text with emoji, but the ref 'message' is not updated with that value. I have a case where I can't use message.value directly to update the value. I need to use the ref 'refInputEnvioMensagem' // vue 3 - template <EmojiPicker @select="onSelectEmoji" /> <textarea ref="refInputEnvioMensagem" @input="(v) => (message = v.target.value)" :value="messsage" /> // insert emoji setup(){ let message =ref(''); let refInputEnvioMensagem=ref(null); function onSelectEmoji(emoji) { const tArea = refInputEnvioMensagem.value; tArea.focus(); const startPos = tArea.selectionStart; const endPos = tArea.selectionEnd; const tmpStr = tArea.value || ""; if (!emoji.i) return; tArea.value = tmpStr.substring(0, startPos) + emoji.i + tmpStr.substring(endPos, tmpStr.length); } return {message, refInputEnvioMensagem, onSelectEmoji} } ...
null
From my understanding of two-dimensional arrays, let's say if I declare ```int a[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9};```, it will be stored in a memory in exact order. And the address of each row can be written like this: `a[0]` is equal to `&a[0][0]`, `a[1]` is equal to `&a[1][0]`, and `a[2]` is equal to `&a[2][0]`. So each `a[n]` is a `int*` type variable. And since array name `a` is originally `&a[0]`, it will be a `int**` type variable. From this knowledge, I assumed that writing code like this will occur error when assigning `a` to `p`, since the type is different. ``` #include <stdio.h> int main() { int a[3][3] = { 72, 4, 5, 6, 7, 8, 9, 10, 11 }; int* p; p = a; //possible error, from int** to int* printf("*p : %d\n", *p); return 0; } ``` But somehow the result shows the value of `a[0][0]`, which is 72. What happened here? Am I understanding something wrong about two-dimensional matrix?
Unexpected result when assigning and printing pointer value of two-dimensional array with its name
|arrays|c|pointers|multidimensional-array|integer|
I want to code a downloader app that saves pictures to a folder. The app should work on windows and mac/os, and maybe later on android and ios. I haven't found a way to pick the target folder. Any idea on how it can be achieve either with blazor or xaml .NET MAUI app?
|c#|maui|.net-6.0|maui-blazor|
null
I am trying to add schema to a product page. The product is shackles used in lifting and rigging equipments. However, in the footer of the page there is the address of the organization and also in the menu bar the links to all the other products is present. I was wondering whether I should add organization schema to the product as the address and other products are present on the page. The below is the schema ``` <script type="application/ld+json"> { "@context": "https://schema.org", "@graph": [ { "@type": "ProductGroup", "name": "Shackles", "description": "SVIBO industries is one of the top D Shackles,bow Shackles manufacturers in India ", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "18" }, "url": "https://sviboindustries.in/shackles/", "hasVariant": [ { "@type": "Product", "name": "Dee shackles", "image": "https://sviboindustries.in/wp-content/uploads/2023/05/Dee-shackles.jpg", "description": "D shackles, offer unmatched strength, versatility, and durability for a wide range of lifting, rigging, and fastening needs. Let’s explore why Dee Shackles are a preferred option for professionals worldwide.", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "18" }, "review": [ { "@type": "Review", "author": { "@type": "Person", "name": "Omkar Rawool" }, "datePublished": "2021-05-18", "reviewBody": "Don't Break", "name": "Strong and reliable", "reviewRating": { "@type": "Rating", "bestRating": "5", "ratingValue": "4.9", "worstRating": "1" } }, { "@type": "Review", "author": { "@type": "Person", "name": "Prashant Sandwa" }, "datePublished": "2022-01-01", "reviewBody": "Good Quality Product from Svibo Industries.", "name": "Good Service", "reviewRating": { "@type": "Rating", "bestRating": "5", "ratingValue": "4.9", "worstRating": "1" } } ] }, { "@type": "Product", "name": "Bow Shakles", "image": "https://sviboindustries.in/wp-content/uploads/2023/05/Bow-Shackles.jpg", "description": "Bow shackles, also known as anchor shackles, are essential components in lifting and rigging applications where secure connections and load distribution are paramount. ", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "21" }, "review": [ { "@type": "Review", "author": { "@type": "Person", "name": "Manthan Wadkar" }, "datePublished": "2017-11-07", "reviewBody": "Very Good", "name": "This is a very good product", "reviewRating": { "@type": "Rating", "bestRating": "5", "ratingValue": "4.9", "worstRating": "1" } }, { "@type": "Review", "author": { "@type": "Person", "name": "Manthan Wadkar" }, "datePublished": "2019-01-07", "reviewBody": "Excellent", "name": "Excellent", "reviewRating": { "@type": "Rating", "bestRating": "5", "ratingValue": "4.9", "worstRating": "1" } } ] } ] }, { "@type": "Organization", "name": "Svibo Industries", "url": "https://sviboindustries.in/", "logo": "https://sviboindustries.in/wp-content/uploads/2023/04/svibo-1.png", "image": "https://sviboindustries.in/wp-content/uploads/2023/04/svibo-1.png", "description": "Svibo Industries is broadly involved in manufacturing and supplying all types of Wire Ropes. Svibo provides all types of wire rope constructions of all grades.", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "355" }, "areaServed": { "@type": "State", "name": "MH" }, "address": { "@type": "PostalAddress", "streetAddress": "111,112,113 Mahatma Phule Peth, Block No 101, Sevadham Building, 1st Floor, Pune, Maharashtra 411042", "addressLocality": "Pune", "addressRegion": "Maharashtra", "postalCode": "411042", "addressCountry": "IN" }, "hasOfferCatalog": { "@type": "OfferCatalog", "name": "Products", "itemListElement": [ { "@type": "Product", "name": "Stainless Steel SS wire rope", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "38" } }, { "@type": "Product", "name": "PVC Coated wire rope", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "21" } }, { "@type": "Product", "name": "Galvanized wire rope", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "10" } }, { "@type": "Product", "name": "Ungalvanized wire rope", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "38" } }, { "@type": "Product", "name": "Polythene Slings", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "40" } }, { "@type": "Product", "name": "Chain Sling and Alloy Chain", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "40" } }, { "@type": "Product", "name": "Chain Pulley Block", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "23" } }, { "@type": "Product", "name": "Lifting and Chain Hooks", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "32" } }, { "@type": "Product", "name": "Electric Chain Hoist", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "22" } }, { "@type": "Product", "name": "Eye Bolt", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "15" } }, { "@type": "Product", "name": "Mini Electric Hoist", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "32" } }, { "@type": "Product", "name": "Pulley, Pulleys Block and Chain Wheel", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "56" } }, { "@type": "Product", "name": "Pulling and Lifting Machine", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "21" } }, { "@type": "Product", "name": "Hand Puller", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "10" } }, { "@type": "Product", "name": "Ratchet Lever Lifting Hoist", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "32" } }, { "@type": "Product", "name": "Plate Lifting Clamps", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "12" } }, { "@type": "Product", "name": "Trolley", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "12" } }, { "@type": "Product", "name": "Winches", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "32" } }, { "@type": "Product", "name": "Shackles", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "40" } }, { "@type": "Product", "name": "Wire Rope Clamps", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "31" } }, { "@type": "Product", "name": "Wire Rope Thimble", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "42" } }, { "@type": "Product", "name": "Turnbuckle", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "28" } }, { "@type": "Product", "name": "Safety Items", "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.9", "reviewCount": "15" } } ] }, "contactPoints": [ { "@type": "ContactPoint", "telephone": "+91 8208803755", "contactType": "Customer support", "email": "info@sviboindustries.com" }, { "@type": "ContactPoint", "telephone": "+91 7447449114", "contactType": "Customer support" }, { "@type": "ContactPoint", "telephone": "+91 9637545481", "contactType": "Customer support" } ] } ] } </script> ```
Should Organization schema be on every page?
|html|seo|schema|json-ld|
I want to run docker in my homelab for any python related projects. To save diskspace and keep installed python packages across dockers consistent, I am looking for a way to share the installed python packages across the different services. Services: - Juypterlab (to create python scripts) - Kestra (for automated execution of scripts) - Couple of Flask apps Expectation: If I install `pip install pandas` in Jupyterlab, this package will also be available immediately in the Kestra container I am quite new to docker and docker-compose.
Docker: keep python packages consistent
|python|docker|docker-compose|
I have e-commerce product data in JSON format. This data is frequently updated. I am planning to load this data into BigQuery. Given that the JSON files are huge (a few hundred attributes) and there are many updates, I found that it is not very cost-effective to store the entire data in BigQuery and update it frequently using merge queries.  I am now planning to store the frequently used attributes in individual columns in a BigQuery table. However, I also need to support the use cases when somebody wants to access any other attribute of the JSON for some ad hoc analysis. To address this, can I use the following strategy: Store the JSON for a product in its own file in GCP in a specific directory. Create an external table using all the files in that directory. Each file's content becomes a row in the external table describing a single product. When updates happen to a product, I update the BigQuery table and also replace the existing file for that product with a new file. Is this a reasonable approach? If yes, how can I create the external table from the directory?
[![picture of the white space][1]][1] I want to make the white space around flex items smaller. This is essentially a parent flex box with child flex boxes. heres my html: ``` <div class="parent-box"> <div class="contain"> <div class="modal"> <h2>Plans For The Site</h2> <p><span class="date">~12-03-24 00:57~</span><br><span class=body>so, in order, i want to get this little blog thing working and looking the way i want, create the gifs and pictures for the background and buttons, create a font and add it, add some little music effects to everything, add some content to the different pages, add a little gir cursor, and then i think ill put the link up on my socials. once i get to the point of putting it up on my socials, ill subscirbe and get a domain name that i like... before that im just gonna keep working on the free subscription unless i run out of space. eta with the way im working looks to be about a week- 3 weeks, esp with the clothing im working on.</span> </div> </div> <div class="contain"> <div class="modal"> <h2>Plans For The Site</h2> <p><span class="date">~11-03-24 01:38~</span><br><span class=body>Just got the website front page done superficially, need to create the gifs and pictures and background, and need to figure out how to format this blog better than it is atm... make take a day or so... going to bed right now though</span></p> </div> </div> </div> ``` and heres the css: ``` .contain { width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center; } .modal { width: 50vw; height: 50%; margin:30px; padding: 1rem; background-color: aqua; border: 1px solid black; border-top: 15px solid black; color: black; overflow: scroll; overflow-x: hidden; display: flex; flex-direction: column; text-align: left; } .parent-box { display: flex; width: 70%; height: 50vh; margin-left:auto; margin-right:auto; margin-bottom:10px; margin-top:10px; overflow: scroll; overflow-x: hidden; justify-content: space-between; align-items: center; flex-direction: column; font-size: 30px; text-align: center; background-color: #7d7d7d; color: #000000; font-weight: bold; } ``` Ive tried using margins in all three css styles, but it seems to do nothing. Im just trying to make the gray space at the top smaller and responsive. [1]: https://i.stack.imgur.com/OsWrx.png
Thanks to @yaakov-bressler, I was able to use Literal from typing_extensions to solve this, See the code below from typing_extensions import Literal class CookingModel_1(BaseModel): fruit: Literal[FruitEnum.pear, FruitEnum.grapes] class CookingModel_2(BaseModel): fruit: Literal[FruitEnum.banana, FruitEnum.grapes]
Error Code; [![enter image description here][1]][1] I press the send message key, everything works normally, I press the stop key, again normal, but app.stop does not stop, I get an error when sending a message again Code; ``` from customtkinter import * import customtkinter as ctk from threading import Thread import time, os, asyncio from pyrogram import Client from pyrogram.enums import MessageMediaType run = True path = os.getcwd() app = Client(path + "\\users\\" + "user") async def tg_bot(): global run global app # Reference the global app variable s = 0 await app.start() async for ii in app.get_chat_history(-1002070231241): if ii.media == MessageMediaType.VIDEO: if run: s = s + 1 await app.copy_message(-1002142940185, -1002070231241, ii.id, caption="") print(s, "sended.") await asyncio.sleep(1) await app.stop() def start(): global run run = True def don(dongu, _e): try: dongu.run_until_complete(tg_bot()) finally: dongu.close() loop = asyncio.get_event_loop() event = asyncio.Event() oto = Thread(target=don, args=(loop, event)) oto.daemon = True oto.start() def stop(): global run run = False global app app.stop root = ctk.CTk() root.geometry("300x300") basla = CTkButton(root, text="message send", command=start) basla.place(x=75, y=100) dur = CTkButton(root, text="stop", command=stop) dur.place(x=75, y=200) root.mainloop() ``` Video; https://drive.google.com/file/d/1tTuNKZ_WR9KK7WOjXbdzP3-M_TC4l6yk/view?usp=drive_link [1]: https://i.stack.imgur.com/S8cEm.png
I plan to create a plugin for Intellij (Android Studio to be more specific) that amongst other things shall modify existing code, e.g. I want to add a new case to a when statement in a given function of an already existing Kotlin file: ``` fun test() { val num = 1 when(num) { 1 -> NumberOne() 2 -> NumberTwo() // want to add 3 -> NumberThree() here } } ``` I already did some research and stumbled across the [Intellij PSI][1]. However the linked docs only mention Java, it's unclear to me whether I could modify Kotlin code with the PSI. Can someone with more experience in this topic share his knowledge on this? By the way I only need to modify Kotlin code, no need to be able to modify Java *and* Kotlin code. [1]: https://plugins.jetbrains.com/docs/intellij/modifying-psi.html
How can I modify Kotlin code from a self-developed Intellij plugin?
|kotlin|android-studio|intellij-plugin|intellij-platform-psi|
if(tid\<n) { gain = in_degree[neigh]*out_degree[tid] + out_degree[neighbour]*in_degree[tid]/total_weight //here let say node 0 moves to 2 atomicExch(&node_community[0, node_community[2] // because node 0 is in node 2 now atomicAdd(&in_degree[2],in_degree[0] // because node 0 is in node 2 now atomicAdd(&out_degree[2],out_degree[0] // because node 0 is in node 2 now } } this is the process, in this problem during calculation of gain all the thread should see the update value of 2 which values of 2+values 0 but threads see only previous value of 2. how to solve that ? here is the output: node is: 0 node is: 1 node is: 2 node is: 3 node is: 4 node is: 5 //HERE IS THS PROBLEM (UPDATED VALUES ARE NOT VISIBLE TO THE REST OF THREDS WHO EXECUTED BEFORE THE ATOMIC WRITE) updated_node is: 0 // this should be 2 updated_values are: 48,37. // this should be(48+15(values of 2))+(37+12(values of 0)) I have tried using , __syncthreads(), _threadfence() and shared memory foe reading writing values can any one tell what could be the issue ??
I also suffered with this problem. It earned it for me. I declared in the fragment activity public static String customerId; and in the fragment I received referring simply by writing customerId I'm not good at programming. Maybe this will help someone
If you have your file inside a sharepoint / OneDrive folder or something similar, this may also be the root cause of the issue. I had the same issue and after moving it out of my OneDrive to a local folder, reading the workbook with `pd.read_excel` as is (no other engine, no copying beforehand) worked fine.
This can be done in a single traversal, without finding the length of linked list. Please refer the steps below:- - Append a dummy node at the start, because in order to delete ith node we should have a pointer at i-1th node (case:- N = length of linked list) - Take two pointers slow and fast, both pointing to dummy node - Make fast pointer N steps ahead of slow pointer - Now move slow and fast pointers together till the fast pointer reached end - When fast pointer will be at the end of linked list, slow pointer will be pointing to (N-1)th node from end - slow.next will be pointing to the node which is supposed to be deleted - Now we can simply delete the Nth node by changing slow->next = slow->next->next C++ code Sample:- <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-html --> ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* dummy = new ListNode(); dummy->next = head; ListNode* slow = dummy; ListNode* fast = dummy; int cnt = 0; while(cnt < n){ fast = fast->next; cnt++; } while(fast->next != NULL){ slow = slow->next; fast = fast->next; } slow->next = slow->next->next; return dummy->next; } <!-- end snippet -->
{"OriginalQuestionIds":[14173717],"Voters":[{"Id":580083,"DisplayName":"Daniel Langr","BindingReason":{"GoldTagBadge":"c++"}}]}
GlobalScope.launch(Dispatchers.Default) { runCatching { // Your API call and data processing code here... // Move notifyDataSetChanged inside the Main thread block launch(Dispatchers.Main) { orderAdapter?.notifyDataSetChanged() } } } By doing this, you ensure that the adapter is notified of the data change on the main thread, allowing the UI to update properly. Additionally, please ensure that you initialize the orderAdapter before making the API call to avoid potential NullPointerException. You can do this by moving the adapter initialization before the API call: recyclerView.layoutManager = LinearLayoutManager(this@OrderHistoryActivity) orderAdapter = OrderAdapter(this@OrderHistoryActivity, models) recyclerView.adapter = orderAdapter
I have tauri command on backend(tauri) that returns a string(light theme value from windows registry). I need to get it on frontend + listen if this string changes. I couldn't find needed functions in leptos or tauri docs. So I came up with this crutch on frontend: ```rust let (is_light_theme, set_is_light_theme) = create_signal(String::new()); let is_light_theme_fn = move || { spawn_local(async move { let is_light_theme_fetch = invoke("is_light_theme", to_value("").unwrap()) .await .as_string() .unwrap(); set_is_light_theme.set(_is_light_theme_); loop { let old_value = is_light_theme.get(); let new_value = invoke("is_light_theme", to_value("").unwrap()) .await .as_string() .unwrap(); if new_value != old_value { set_is_light_theme.set(new_value); }; // sleep(Duration::from_millis(2000)).await; // breaks loop } }); }; is_light_theme_fn(); ``` tauri command on the backend: ```rust #[tauri::command] fn is_light_theme() -> String { let theme = helpers::is_light_theme(); format!("{}", theme) } ``` `is_light_theme` in helpers: ```rust pub fn is_light_theme() -> bool { let val = CURRENT_USER .open(r#"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"#) .expect("Failed to get registry key") .get_u32("AppsUseLightTheme") .expect("Failed to get registry value"); println!("{}", val); val != 0 } ``` This runs somewhat okay but this loop is very process-intensive. I tried adding sleep from std:thread and tokio to loop, both of them are breaking it. Maybe there's a better a way to listen for value changes in backend?
null
As KDE Plasma Linux Desktop Environment is built on Qt and therefore Qt baked into the system. Are there any extra overheads and extra complexities by running a Qt application on Gnome with Qt installed separately. Apologies if this question has been asked previously. Many thanks. I have been running my Qt application on Gnome for a good few years with no major problems, so my question is purely an academic one for the moment.
Here's the first thing that I came up with. 1. Pass the separate arrays into your recursive function as separate parameters. 2. Receive the first array as the "master" array, then loop over the subsequent arrays and determine the best course of action case-by-case. 3. If a level of data in an iterated array is an indexed array, then merely push all values into the related level of the master. If not an indexed array, then make key-based declarations (potentially recursively). Code: ([Demo][1]) function mergeNestedArraysInefficient(array $array, array ...$otherArrays) { foreach ($otherArrays as $other) { if (array_is_list($other)) { array_push($array, ...$other); continue; } foreach ($other as $k => $v) { if (is_array($v)) { $array[$k] = !key_exists($k, $array) ? $v : mergeNestedArraysInefficient($array[$k], $v); } else { $array[$k] = $v; } } } return $array; } var_export(mergeNestedArraysInefficient($array1, $array2, $array3)); I don't know if this still provides a performance problem, but it correctly processes the data as you've described. [1]: https://3v4l.org/ZVU5m
null
I am trying to style my own components i have 2 themes defined each in its own style file Dark theme ```ts @use "@angular/material" as mat; @include mat.core(); $dark-theme: mat.define-dark-theme( // Removed for brevity ); @include mat.core-theme($dark-theme); @include mat.all-component-themes($dark-theme); ``` Light Theme ```ts @use "@angular/material" as mat; @include mat.core(); $light-theme: mat.define-light-theme( // Removed for brevity ); @media (prefers-color-scheme: light) { @include mat.core-color($light-theme); } ``` I am trying to get a primary color from each themes is there a shorthand solution to this. I don't understand material styling that much. ``` @use "@angular/material" as mat; @use "../../../styles/variables.scss" as vars; @use "../../../styles/light-theme.scss" as light; @use "../../../styles/dark-theme.scss" as dark; $type: mat.get-theme-type(dark.$dark-theme); $primary-light: mat.get-theme-color(light.$light-theme, primary, default); $primary-dark: mat.get-theme-color(dark.$dark-theme, primary, default); $primary: if($type == dark, $primary-light, $primary-dark); input::placeholder { color: $primary; } ```
Angular material getting colors based on theme
|angular|angular-material|
We have an Express application with authentication routes (postLogin and getLogin) and session configuration set up using express-session. Despite configuring sessions, I encounter an issue where session data is not persisting between requests. PostLogin: I am creating the session for the user here. ``` const postLogin = async (req, res) => { const { username, password } = req.body; try { // Query database for user const user = await getUserByUsername(username); // Validate password const passwordMatch = await bcrypt.compare(password, user.password); if (!passwordMatch) { res.status(401).json({ error: 'Invalid username or password' }); return; } // Set session data req.session.user = { id: user.id, username: user.username }; req.session.save(); res.json({ loggedIn: true, username: user.username }); } catch (error) { console.error('Login error:', error); res.status(500).json({ error: 'Internal server error' }); } }; ``` GetLogin: Checking for user session data on page refresh in my front end to see if user session is available. This always returns null for some reason. ``` const getLogin = (req, res) => { if (req.session.user && req.session.user.username) { res.json({ loggedIn: true, username: req.session.user.username }); } else { res.json({ loggedIn: false }); } }; ``` Express Session Config: (Update): edited cors to allow origin requests. ``` const express = require('express'); const session = require('express-session'); const cors = require('cors'); const app = express(); app.use(cors({ origin: ['http://localhost:5173'], // cannot be '*' credentials: true, })); app.use(session({ secret: process.env.COOKIE_SECRET, resave: false, saveUninitialized: false, cookie: { secure: process.env.ENVIRONMENT === 'production', sameSite: process.env.ENVIRONMENT === 'production' ? 'none' : 'lax' } })); ``` Front-end axios request (React JSX) ``` import { createContext, useState, useEffect } from "react"; import { useNavigate } from "react-router-dom"; export const AccountContext = createContext(); const UserContext = ({ children }) => { const [user, setUser] = useState({ loggedIn: null }); const navigate = useNavigate(); useEffect(() => { console.log("Using effect"); fetch("http://localhost:8080/api/v1/auth/login", { method: "GET", credentials: "include", // Include credentials in the request }) .then((response) => { if (!response || !response.ok) { setUser({ loggedIn: false }); return null; } return response.json(); }) .then((data) => { if (data) { setUser(data); navigate("/home"); } }) .catch((error) => { console.error("Error fetching user data:", error); setUser({ loggedIn: false }); }); }, []); return ( <AccountContext.Provider value={{ user, setUser }}> {children} </AccountContext.Provider> ); }; export default UserContext; ```
In a customer Zendesk form, set subject field to the values of dropdown fields
|jquery|zendesk|
Great question! I tried by writing some code and generated the tokens using both Tiktoken and Azure OpenAI SDK. Unfortunately the results are different, so the answer is no. You cannot use Tiktoken to generate the embedding. Here's my sample code: ``` using Azure; using Azure.AI.OpenAI; using Tiktoken; var stringToEncode = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; var encoder = Tiktoken.Encoding.TryForModel("text-embedding-ada-002"); var data1 = encoder!.Encode(stringToEncode);//produced a 96 element array. var openAIClient = new OpenAIClient(new Uri("https://xyz.openai.azure.com/"), new AzureKeyCredential("my-azure-openai-key")); var embeddings = openAIClient.GetEmbeddings(new EmbeddingsOptions() { DeploymentName = "text-embedding-ada-002", Input = { stringToEncode } }); var data2 = embeddings.Value.Data[0].Embedding;//produced a 1536 element array. Console.WriteLine($"Data 1 length: {data1.Count}; Data 2 length: {data2.Length}"); ```
Also, just for the readers after Nov 2023. From your template, you cannot do: <a href="{% url 'logout' %}>Logout</a> #won't work GET method for /logout has been deprecated. [check here][1] **New Implementation:** <form method="post" action="{% url 'logout' %}"> {% csrf_token %} <button type="submit">logout</button> </form> [1]: https://forum.djangoproject.com/t/deprecation-of-get-method-for-logoutview/25533
In this case calling wrapper() would **immediately** execute the function. if you just return wrapper, then you are returning the function itself so that it can be called later by another part of the code
I have a json response where I need to extract the list of values for **files** and **folders**, however both the number of elements in each list and properties in the json response is not fixed as shown below: JSON Response: ``` "config.yml" : "project: \n files: \n - file1\n - file2\n folders: \n - folder1\n - folder2\n random1: \n random2:\n - redundant1" ``` How can I parse the string and extract the list for files and folders into a []string? For reference: config.yml ``` project: files: - file1 - file2 folders: - folder1 - folder2 random1: random2: - redundant1 ``` I tried yaml.unmarshalling the string, then json.marshal and json.unmarshal to get a nest map. But I am not sure if this is the right way to go about it.
How to parse a string of a yaml file's content in Go?
|json|string|go|parsing|yaml|
null
I've been trying to achieve the result in the table (I've attached an image ) with no luck so far .. I have a table called Nodes consists of ( base doc, current done and target doc). BaseDocType . BaseDocID DocType . DocID TargetDocType . TargetDocID .. I want to fetch all the related nodes for any specific node if that's possible ..if any one can help I will be appreciate it a lot .. it's a sql server database . ` With CTE1 (ID, BaseDocType, BaseDocID, DocType, DocID, TargetDocType, TargetDocID) As ( Select ID, BaseDocType, BaseDocID, DocType, DocID, TargetDocType, TargetDocID From Doc.Nodes Where DocType=8 and DocID = 2 Union All Select a.ID, a.BaseDocType, a.BaseDocID, a.DocType, a.DocID, a.TargetDocType, a.TargetDocID From Doc.Nodes a Inner Join CTE1 b ON (a.BaseDocType = a.BaseDocType and a.BaseDocID = b.BaseDocID and a.DocType != b.DocType and a.DocID != b.DocID) ) Select * From CTE1` this query is not working .. says Msg 530, Level 16, State 1, Line 8 The statement terminated. The maximum recursion 100 has been exhausted before statement completion. [Example][1] [1]: https://i.stack.imgur.com/t3q8u.jpg
Do Qt based applications run better on KDE Plasma than on Gnome with Qt installed as a dependency?
|linux|qt|gnome|kde-plasma|
null
I have an Azure Function with an HTTP Trigger (Java, Runtime Version ~4) and want to override the logging level of this specific function: ``` @FunctionName("Stores") public HttpResponseMessage getStores( @HttpTrigger(... ... context.getLogger().log(Level.FINE, "Test message with level " + Level.FINE); ... ``` I can set a function-specific log level in the host.json, this works fine (locally **and** in the cloud): ``` "logging": { "logLevel": { "Function.Stores.User": "Trace" } } ``` Overriding the log level in the local.settings.json also works fine (as documented here: https://learn.microsoft.com/en-us/azure/azure-functions/configure-monitoring?tabs=v2) ``` "AzureFunctionsJobHost__logging__logLevel__Function.Stores.User": "Trace" ``` But when I add the setting ```AzureFunctionsJobHost__logging__logLevel__Function.Stores.User``` with value ```Trace``` to the application settings in the cloud portal, it has no effect. Is this a bug or is there anything wrong with my settings?
Overriding function log level not working
|azure-functions|
I have some python code: ``` class Meta(type): def __new__(cls, name, base, attrs): attrs.update({'name': '', 'email': ''}) return super().__new__(cls, name, base, attrs) def __init__(cls, name, base, attrs): super().__init__(name, base, attrs) cls.__init__ = Meta.func def func(self, *args, **kwargs): setattr(self, 'LOCAL', True) class Man(metaclass=Meta): login = 'user' psw = '12345' ``` How do I write this statement as OOP-true (Meta.func)? In the row: `cls.__init__ = Meta.func` If someone wants to change the name of the metaclass, it will stop working. Because it will be necessary to make changes inside this metaclass. Because I explicitly specified his name in the code. I think it won't be right. But I do not know how to express it in another way. I tried `cls.__init__ = cls.func`, but it doesn't create local variables for the Man class object.
The most important thing is to have standard options. Don't try to be clever; be simply consistent with [already existing tools][1]. How to achieve this is also important, but only comes second. Actually, this is quite generic to all CLI interfaces. [1]: http://www.gnu.org/prep/standards/html_node/Option-Table.html#Option-Table "GNU common options table"
I want to build a memory game with cards. And one of the things i have to do is select an image from an map called img and write it as a url. Also i don't know if my code is correct, this is what i tried: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-html --> <!doctype html> <html> <head> <meta charset="utf-8"> <title>Cardgame</title> <link href="css/game.css" rel="stylesheet"> </head> <body> <div id="field"><img src="../begin/img/calf.jpg" alt="" name="calf"> <img src="../begin/img/cat.jpg" alt="" name="cat"> <img src="../begin/img/chick.jpg" alt="" name="chick"> <img src="../begin/img/cow.jpg" alt="" name="cow"> <img src="../begin/img/dog.jpg" alt="" name="dog"> <img src="../begin/img/duck.jpg" alt="" name="duck"> <img src="../begin/img/goat.jpg" alt="" name="goat"> <img src="../begin/img/goose.jpg" alt="" name="goose"> <img src="../begin/img/hen.jpg" alt="" name="hen"> <img src="../begin/img/horse.jpg" alt="" name="horse"> <img src="../begin/img/kitten.jpg" alt="" name="kitten"> <img src="../begin/img/lamb.jpg" alt="" name="lamb"> <img src="../begin/img/pig.jpg" alt="" name="pig"> <img src="../begin/img/piglet.jpg" alt="" name="piglet"> <img src="../begin/img/puppy.jpg" alt="" name="puppy"> <img src="../begin/img/rooster.jpg" alt="" name="rooster"> <img src="../begin/img/sheep.jpg" alt="" name="sheep"> <img src="../begin/img/veal.jpg" alt="" name="veal"> <img src="../begin/img/cat.jpg" alt="" name="cat"> <img src="../begin/img/chick.jpg" alt="" name="chick"> <img src="../begin/img/cow.jpg" alt="" name="cow"> <img src="../begin/img/dog.jpg" alt="" name="dog"> <img src="../begin/img/duck.jpg" alt="" name="duck"> <img src="../begin/img/goat.jpg" alt="" name="goat"> <img src="../begin/img/goose.jpg" alt="" name="goose"> <img src="../begin/img/hen.jpg" alt="" name="hen"> <img src="../begin/img/horse.jpg" alt="" name="horse"> <img src="../begin/img/kitten.jpg" alt="" name="kitten"> <img src="../begin/img/lamb.jpg" alt="" name="lamb"> <img src="../begin/img/pig.jpg" alt="" name="pig"> <img src="../begin/img/piglet.jpg" alt="" name="piglet"> <img src="../begin/img/puppy.jpg" alt="" name="puppy"> <img src="../begin/img/rooster.jpg" alt="" name="rooster"> <img src="../begin/img/sheep.jpg" alt="" name="sheep"> <img src="../begin/img/veal.jpg" alt="" name="veal"> </div> <script src="js/memory.js" type="module"></script> </body> </html> <!-- end snippet --> <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-css --> "use strict"; const myCardSet = ["duck", "kitten", "piglet", "puppy", "calf", "veal", "lamb", "rooster", "horse", "mouse", "dog", "cat", "goose", "goat", "sheep", "pig", "cow", "chick", "hen"]; document.addEventListener('onload', function () { populatieField() }) class card { constructor(card1) { this.card1 = myCardSet[0] } } function populateField() { for (let i = 0; i < myCardSet.length; i++) { let newTile = document.createElement('div'); let newCard = document.createElement('img'); let imageURL = 'img' + card.card1 + '.jpg' newCard.setAttribute('src', imageURL) newCard.setAttribute('name', imageURL) newTile.appendChild(newCard) myField.appendChild(newTile) } } const myField = document.getElementById('field').addEventListener('click', function onClickCard(e) { this.getAttribute(e.target.name) console.log(e.target.name) } ) function shuffle(arr) { var i = arr.length, j, temp; while (--i > 0) { j = Math.floor(Math.random() * (i + 1)) temp = arr[j]; arr[j] = arr[i] arr[i] = temp } } shuffle(myCardSet) populateField() <!-- end snippet --> I keep getting the error: Cannot read properties of undefined (reading 'appendChild') at populateField Please help me, thanks already!
how do i select an image as an url from my map called img?
|javascript|html|css|
In my case I mistakened the client Id (a string that looks like `xxxxx-xxx-xxxx-xxxx-xxxxxxx`) with the tenant Id (a string that looks like `myproject.onmicrosoft.com`)
**Problem Description:** I'm trying to install the audio.whisper package from GitHub in RStudio using the command remotes::install_github("bnosac/audio.whisper"), but I'm getting an error message that says “Could not find tools necessary to compile a package”. **R Version:** R version 4.3.3 (2024-02-29 ucrt) **Rtools Version**: I have installed Rtools 4.4 (as indicated by the path C:\\Rtools44\\usr\\bin). **Error Message:** The exact error message I'm getting is “Could not find tools necessary to compile a package”. **Code:** ``` options(repos = c(CRAN = "https://cloud.r-project.org/")) install.packages("remotes") install.packages("av") remotes::install_github("bnosac/audio.whisper") ``` Steps Already Tried: I have tried adding the path to Rtools to my PATH variable in R using Sys.setenv(), and I have confirmed that the path to Rtools is included in your PATH by checking Sys.getenv("PATH"). I have tried reinstalling Rtools and restarting RStudio, but none of these steps have resolved the problem.
BigQuery external table using JSON files
|google-bigquery|external-tables|
I am observing a strange behaviour where GCC (but not clang) will skip a pointer-reset-after-free expression in the global destruction phase and with certain values of `-O?`. I can reproduce this with every version I tried (7.2.0, 9.4.0, 12.3.0 and 13.2.0) and I'm trying to understand if this is a bug or not. The phenomenon occurs in the [C++ wrapper for lmdb][1]; here are the functions that are involved directly: static inline void lmdb::env_close(MDB_env* const env) noexcept { delete ::mdb_env_close(env); } class lmdb::env { protected: MDB_env* _handle{nullptr}; public: ~env() noexcept { try { close(); } catch (...) {} } MDB_env* handle() const noexcept { return _handle; } void close() noexcept { if (handle()) { lmdb::env_close(handle()); _handle = nullptr; // std::cerr << " handle now " << handle(); } // std::cerr << "\n"; } I use this wrapper in a class `LMDBHook` of which I create a single, static global variable: class LMDBHook { public: ~LMDBHook() { if (s_envExists) { s_lmdbEnv.close(); s_envExists = false; delete[] s_lz4CompState; } } static bool init() { if (!s_envExists) { try { s_lmdbEnv = lmdb::env::create(); //snip } catch (const lmdb::error &e) { // as per the documentation: the environment must be closed even if creation failed! s_lmdbEnv.close(); } } return false; } //snip static lmdb::env s_lmdbEnv; static bool s_envExists; static char* s_lz4CompState; static size_t s_mapSize; }; static LMDBHook LMDB; lmdb::env LMDBHook::s_lmdbEnv{nullptr}; bool LMDBHook::s_envExists = false; char *LMDBHook::s_lz4CompState = nullptr; // set the initial map size to 64Mb size_t LMDBHook::s_mapSize = 1024UL * 1024UL * 64UL; I first came across this issue because an application using `LMDBHook` would crash just before exit when built with GCC but not with clang, and initially thought that this was some subtle compiler influence on the order of calling dtors in the global destruction phase. Indeed, allocating `LMDH` *after* initialising the static member variables will not trigger the issue. But the underlying issue here is that the line `_handle = nullptr;` from `lmdb::env::close()` will be skipped by GCC in the global destruction phase (but not when called e.g. just after `lmdb::env::create()` in `LMDBHook::init()`) and "only" when compiled with -O1, -O2 -O3 or -Ofast (so not with -O0, -Og, -Os or -Oz). The 2 trace output exprs in `lmdb::env::close()` are mine; if I outcomment them the reset instruction is not skipped. The fact that it only happens under specific circumstances during global destruction makes me think it is maybe not a bug though if so the behaviour should not depend on the optimisation level. I have made a self-contained/standalone demonstrator that contains the `lmdb++` headerfile extended with trace output exprs and where the create and close functions simply allocate the `MDB_env` structure with `new` and `delete`, plus the `lmdb` headerfile with an added definition of the `MDB_env` structure (normally it's opaque) : https://github.com/RJVB/gcc_potential_optimiser_bug.git . The README has instructions how to use the Makefile but it should be pretty self-explanatory. Here's some example output: > make -B CXX=g++-mp-12 && lmdbhook g++-mp-12 --version g++-mp-12 (MacPorts gcc12 12.3.0_4+cpucompat+libcxx) 12.3.0 Copyright (C) 2022 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. g++-mp-12 -std=c++11 -O3 -o lmdbhook lmdbhook.cpp LMDBHook::LMDBHook() s_lmdbEnv=0x404248 lmdb::env::env(MDB_env*) this=0x404248 handle=0 lmdb::env::env(MDB_env*) this=0x7ffec95f40f8 handle=0x1333020 lmdb::env::~env() this=0x7ffec95f40f8 void lmdb::env::close() this=0x7ffec95f40f8 handle=0 static bool LMDBHook::init() s_lmdbEnv=0x1333020 handle=0x1333020 void lmdb::env::close() this=0x404248 handle=0x1333020 void lmdb::env_close(MDB_env*) env=0x1333020 static bool LMDBHook::init() s_lmdbEnv=0 handle=0 lmdb::env::env(MDB_env*) this=0x7ffec95f40f8 handle=0x1333020 lmdb::env::~env() this=0x7ffec95f40f8 void lmdb::env::close() this=0x7ffec95f40f8 handle=0 static bool LMDBHook::init() s_lmdbEnv=0x1333020 handle=0x1333020 mapsize=67108864 LZ4 state buffer:16384 LMDB instance is 0x404248 lmdb::env::~env() this=0x404248 void lmdb::env::close() this=0x404248 handle=0x1333020 void lmdb::env_close(MDB_env*) env=0x1333020 LMDBHook::~LMDBHook() void lmdb::env::close() this=0x404248 handle=0x1333020 void lmdb::env_close(MDB_env*) env=0x1333020 *** Error in `lmdbhook': double free or corruption (!prev): 0x0000000001333020 *** Abort > make -B CXX=clang++-mp-12 && lmdbhook clang++-mp-12 --version clang version 12.0.1 Target: x86_64-unknown-linux-gnu Thread model: posix InstalledDir: /opt/local/libexec/llvm-12/bin clang++-mp-12 -std=c++11 -O3 -o lmdbhook lmdbhook.cpp LMDBHook::LMDBHook() s_lmdbEnv=0x205090 lmdb::env::env(MDB_env *const) this=0x205090 handle=0 lmdb::env::env(MDB_env *const) this=0x7ffef6c06ca0 handle=0x2e8c20 lmdb::env::~env() this=0x7ffef6c06ca0 void lmdb::env::close() this=0x7ffef6c06ca0 handle=0 static bool LMDBHook::init() s_lmdbEnv=0x2e8c20 handle=0x2e8c20 void lmdb::env::close() this=0x205090 handle=0x2e8c20 void lmdb::env_close(MDB_env *const) env=0x2e8c20 static bool LMDBHook::init() s_lmdbEnv=0 handle=0 lmdb::env::env(MDB_env *const) this=0x7ffef6c06ca0 handle=0x2e8c20 lmdb::env::~env() this=0x7ffef6c06ca0 void lmdb::env::close() this=0x7ffef6c06ca0 handle=0 static bool LMDBHook::init() s_lmdbEnv=0x2e8c20 handle=0x2e8c20 mapsize=67108864 LZ4 state buffer:16384 LMDB instance is 0x205090 lmdb::env::~env() this=0x205090 void lmdb::env::close() this=0x205090 handle=0x2e8c20 void lmdb::env_close(MDB_env *const) env=0x2e8c20 LMDBHook::~LMDBHook() void lmdb::env::close() this=0x205090 handle=0 EDIT: The above examples are with self-built compilers on Linux but the system compilers show the same behaviour, also on Mac, and the choice of C++ runtime (libc++ or libstdc++) has no influence on either platform. [1]: https://github.com/bendiken/lmdbxx
Is this a GCC optimiser bug or a feature?
|optimization|g++|clang++|object-destruction|
you need to kill all running processing for that port, the one your app is using ex: lsof -i :3000 kill <PID> if you are running more then one next js apps in droplet or system, for me stopping them all then building worked.
How to reference Swift Playground itself? I am trying to use `NSNotificationCenter` to observe some variable, but i do not know how to implement it on `Playground`. Here is my code. I just want to observe the `timeout` variable, but without the `willSet` method. var timeout = false var cont: Int8 = 1 NSNotificationCenter.defaultCenter().addObserver(self, forKeyPath: timeout, options: NSKeyValueObservingOptions.New, context: &cont) Is there any way to do it on playground?
From https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html : {CHAR_BIT} Number of bits in a type char. [CX] [Option Start] Value: 8 [Option End] The POSIX issues 7 and 6 specifications state that char has 8 bits. POSIX standard before issue 6 did _not_ require that. From the same site: > CHANGE HISTORY > > Issue 6 > > The values for the limits {CHAR_BIT}, {SCHAR_MAX}, and {UCHAR_MAX} are now required to be 8, +127, and 255, respectively. ---- > I don't know to what extent Linux and *BSD systems "must" conform to it To no extent. Linux and BSD systems may not conform to any standard and may break any conformance at any time. There is no "POSIX standard police" that would enforce anything. POSIX certifications are very rare. Both systems come with a license that clearly states that there are no guaranteeing nothing. Example from BSD: > THIS SOFTWARE IS PROVIDED `'AS IS″ AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
The reason that it only works for only one subdomain is that `next auth` by default sets the cookies on the domain that the signIn has performed on. To change the default behavior and give it a custom domain (e.g. domain with empty subdomain which means all subdomains `.my-site.com`) while using next auth version 5 we should config the cookies' options like so: ```js const nextAuthUrl = process.env.NEXTAUTH_URL NextAuth({ cookies: { sessionToken: { name: `${nextAuthUrl.startsWith('https://') ? "__Secure-": ""}next-auth.session-token`, options: { domain: nextAuthUrl === "localhost" ? "." + nextAuthUrl : "." + new URL(nextAuthUrl).hostname, // support all subdomains httpOnly: true, sameSite: 'lax', path: '/', secure: nextAuthUrl.startsWith('https://'), } } } }) ``` You might also need to config other cookies as well depending on your use case. you can read more about it in the official documentation: https://next-auth.js.org/configuration/options#cookies **EDIT:** I searched more in next auth's github discussions and looks like some people already had this issue. The solution is here: https://github.com/nextauthjs/next-auth/discussions/4089#discussioncomment-2297717 In short: You should set another dummy domain like a real one instead of just localhost (e.g. `localhost.home` or `dev.home` instead of `localhost`). Note that it's better to use a unique domain so it won't be a problem in the future if you open a website that its domain or its API's domain is common with your local host name
I am new to rust and trying to calculate the covariance matrix of an NxM Polars DataFrame. The docs seem to suggest there is covariance functionality as a crate feature, but I cant find any implementation for it. I looked at other implementations including `ndarray_stats::CorrelationExt` or even RustQuant but seems to be just across 2 vectors. `fn covariance_matrix(matrix: &DataFrame) -> Result<ndarray::Array2<f64>, PolarsError> { // Convert DataFrame to ndarray let matrix_arr = matrix.to_ndarray::<Float64Type>(IndexOrder::C)?; let covariance = matrix_arr.cov(0.).unwrap(); return Ok(covariance);` I was playing with this by converting to an ndarray, but I need it ndimensional not 2D. Maybe you can do this with generics, but I cant figure it out. I would also like to do it without converting to an ndarray if possible.
Calculating Dataframe Covariance in Rust Polars
|rust|data-science|rust-polars|
null
### As far as your question, "what is going on?" This appears to happen if memory is exhausted during the course of a PDO query. I believe it has something to do with the memory used by PDO Buffered queries and the way the PHP internal code frees up memory after memory is exhausted. I can reproduce the condition you have experienced with the following code, (note: this is using `register_shutdown_function`. Both the session_close code and the `register_shutdown_function` will run after a memory exhausted error): ```php <?php class TestingClass { private int $something_private; public function getThisDone(): void { $this->something_private = 0; } } // get a reference to the testing class $obj = new TestingClass(); register_shutdown_function(fn() => $obj->getThisDone()); // get a pdo connection and run a query that returns a lot of data $pdoConnection = get_db_read_connection(); $pdoStatement = $pdoConnection->prepare('SELECT * FROM your_table_with_a_lot_of_records LIMIT 100000'); $results = $pdoStatement->fetchAll(PDO::FETCH_CLASS, '\stdClass'); ``` And the resulting fatal error: [![enter image description here][1]][1] ### Note: I cannot reproduce the error if I simply trigger an out of memory error with string concatenation, like below. ```php // use code above but replace pdo connection and query with this while(true) { $data .= str_repeat('#', PHP_INT_MAX); } ``` ### As far as "why is this happening?" I don't think it should be. It seems like this is a good candidate for a PHP bug report. [1]: https://i.stack.imgur.com/eAXUq.png
The EWS Api supports this through using ExportItems and UploadItems https://learn.microsoft.com/en-us/exchange/client-developer/web-service-reference/uploaditems-operation, most of the blueprism examples for EWS seem to use the EWS Managed API which doesn't support these two operations however there is a Branch where someone has implemented support for it https://github.com/search?q=repo%3AOfficeDev%2Fews-managed-api+exportitems&type=pullrequests so you could compile a dll from that branch and use the code sample in the pull request. If this is Exchange Online then EWS is going away at some point in future so this code may break in 2026 if its onPrem you should be good.
I have a react Application where I am trying to add the AWS Chat Widget. It is working but I want to add some additional styling to the launch icon which doesnt seem to be their out of the box - https://docs.aws.amazon.com/connect/latest/adminguide/customize-widget-launch.html I want too add a tool tip as I have mocked up in the image: [![enter image description here][1]][1] This is the code I have added to useEffect method: useEffect(() => { const widgetEle = document.getElementById('amazon-connect-chat-widget'); debugger; if (widgetEle) { widgetEle.innerHTML = '<span class="tooltip-text" id="left">Chat with us!<button id="chatToolTipClose" type="button" class="close">x</button></span>'; } }, []); I thought this should only run after the DOM has fully rendered - but on my debugger the widgetEle is always null. But when I run the exit the debugger the default google chat icon is displayed - and when I inspect the element I can see there is no typo in the id - it is exactly what I specify. Is there something I am missing? [1]: https://i.stack.imgur.com/uQZ0m.png
The CNN website includes a chart for each stock with a price forecast. I was unable to scrape the forecast figure with the following code. For example: the URL about Tesla stock is: [https://edition.cnn.com/markets/stocks/TSLA ](https://stackoverflow.com) The code is: ``` Sub CNN_Data() Dim request As Object Dim response As String Dim html As New HTMLDocument Dim website As String Dim price As Variant stock = "TSLA" website = "https://edition.cnn.com/markets/stocks/" & stock Set request = CreateObject("MSXML2.XMLHTTP") request.Open "GET", website, False request.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" request.send response = StrConv(request.responseBody, vbUnicode) html.body.innerHTML = response price = html.getElementByClassName("high-price").Item(0).innerText End Sub ``` I get an error message when the code reaches the line: "price = html.getElementByClassName("high-price").Item(0).innerText" The error message is: "Object doesn't support this property or method". What is wrong on my code or does anyone know to suggest a helpful code?
I have the following command adb -s 077743323A102985 shell am start -n com.instagram.android/.MainActivity i am trying to start the instagram app via command line, but why does it gives me this error: Starting: Intent { cmp=com.instagram.android/.MainActivity } Error type 3 Error: Activity class {com.instagram.android/com.instagram.android.MainActivity} does not exist. the app is installed
starting an app using adb command error type 3
|android|adb|
if(tid\<n) { gain = in_degree[neigh]*out_degree[tid] + out_degree[neighbour]*in_degree[tid]/total_weight //here let say node 0 moves to 2 atomicExch(&node_community[0, node_community[2] // because node 0 is in node 2 now atomicAdd(&in_degree[2],in_degree[0] // because node 0 is in node 2 now atomicAdd(&out_degree[2],out_degree[0] // because node 0 is in node 2 now } } this is the process, in this problem during calculation of gain all the thread should see the update value of 2 which values of 2+values 0 but threads see only previous value of 2. how to solve that ? here is the output: node is: 0 node is: 1 node is: 2 node is: 3 node is: 4 node is: 5 //HERE IS THS PROBLEM (UPDATED VALUES ARE NOT VISIBLE TO THE REST OF THREDS WHO EXECUTED BEFORE THE ATOMIC WRITE) updated_node is: 0 // this should be 2 updated_values are: 48,37. // this should be(48+15(values of 2))+(37+12(values of 0)) I have tried using , __syncthreads(), _threadfence() and shared memory foe reading writing values can any one tell what could be the issue ??
I tried to run a program but it was using ncurses library and that library was not installed in my system I tried to run a program but it was using ncurses library and I was unable to run it I expected it will work properly
how to install ncurses library in Android
|c++|c|installation|ncurses|replit|
If someone is still looking for a simple solution! index.html ---------- ```html <link id="theme-link" rel="stylesheet" href="/themes/aura-dark-teal/theme.css"> ``` ---------- Options API --------------------- ```javascript data() { return { currentTheme: 'aura-dark-teal', nextTheme: 'aura-light-blue', } }, methods: { toggleTheme() { [this.currentTheme, this.nextTheme] = [this.nextTheme, this.currentTheme] this.$primevue.changeTheme(this.currentTheme, this.nextTheme, 'theme-link', () => {}) } } ``` ---------- Composition API --------------- ```javascript let currentTheme = 'aura-dark-teal' let nextTheme = 'aura-light-blue' const primeVue = usePrimeVue(); toggleTheme() { [this.currentTheme, this.nextTheme] = [this.nextTheme, this.currentTheme] primeVue.changeTheme(currentTheme.value, nextTheme, 'id-to-link', () => {}); ``` ---------- And you can save the `currentTheme` and `nextTheme` in the browser's localStorage to preserve the users' theme selection between sessions.
Endeavor to both TRIM and apply IN and OUT fades to a number of MP3 files using ffmpeg. Specifically trimming off a [400mS] length from the start, followed by a [400mS] fade up to full volume, then a [400mS] fade down at the conclusion of the recording. My obstacle is making the fade out function correctly. Have employed ffprobe to determine the total length of the file which is used in the $END variable. The following command appears to work correctly for the trim and the afade-in. `ffmpeg -ss 00:00.4 -i "$FILENAME" -af "afade=t=in:st=0:d=0.4" -c:a libmp3lame "$NEWFILENAME"` However, adding the afade-out breaks the command and results in error with "Conversion failed!". `-af "afade=t=in:st=0:d=0.4,afade=t=out:st=$END:d=0.4"` Typical transaction follows with error details. ``` type [mp3 @ 0x557572b829c0] Estimating duration from bitrate, this may be inaccurate Input #0, mp3, from 'kef.reports-know.how.mp3': Metadata: artist : KEF Reports title : Know how encoded_by : Layer 3, Codec track : 617 Duration: 00:03:48.62, start: 0.000000, bitrate: 128 kb/s Stream #0:0: Audio: mp3, 44100 Hz, stereo, fltp, 128 kb/s Stream mapping: Stream #0:0 -> #0:0 (mp3 (mp3float) -> mp3 (libmp3lame)) Press [q] to stop, [?] for help [afade @ 0x557572ba0880] Value 3.000000 for parameter 'type' out of range [0 - 1] Last message repeated 1 times [afade @ 0x557572ba0880] Error setting option type to value 03. [Parsed_afade_0 @ 0x557572ba0780] Error applying options to the filter. [AVFilterGraph @ 0x557572b864c0] Error initializing filter 'afade' with args 't=out:st=00:03:48.620:d=0.3' Error reinitializing filters! Failed to inject frame into filter network: Numerical result out of range Error while processing the decoded data for stream #0:0 Conversion failed!here ``` Bewildered by, "Value 3.000000 for parameter 'type' out of range [0 - 1]". Thanks in advance, Have experimented with the afade-out parameters without success.
Implementing trim and fade filters with ffmpeg - MP3
|audio|ffmpeg|mp3|
null
> I don't understand the `temp` part. How the indexes are adding to `temp`? example `arr = 1,2,3,4,3`: it should return `4,2` but it returns `2,4`. `temp` captures the array list that the recursive call returns: it contains the matching indices, but only from the given index (`index+1`) onward. With `addAll` all these matching indices are appended to (after!) the content we already have. The content we already have is either an empty list, or (if the current index has a match) it has one element, which is `index`. As `addAll` adds indices *after* that first element, and those additional indices are guaranteed to be at least `index+1` (as the recursive call only looks from that index onward), we can be certain that `iList` will have the indices in *increasing* order. Notice where your code is different. In essence you *first* make the recursive calls and collect the indices it returns, and only *then* you check whether the current index `index` has a matching value, and add it *after* those if it matches. If we were to take your instructor's code and just change the order to of adding the recursive results with the (optional) adding of the `index`...: ``` static ArrayList<Integer> LinearSearch(int[] arr,int index,int target) { ArrayList<Integer> iList = new ArrayList<>(); if(index == arr.length){ return iList; } ArrayList<Integer> temp = LinearSearch(arr,index+1,target); iList.addAll(temp); // Moved the addition of the current index AFTER // the recursive results were added: if(arr[index] == target){ iList.add(index); } return iList; } ``` ...then the result for the example input will be `4,2`.
React useEffect not running after all DOM has loaded