instruction
stringlengths
0
30k
βŒ€
How do you turn on flags for a capturing subgroup using re2 regular expressions with BigQuery
|regex|google-bigquery|re2|
Use a nested capturing group within the non-capturing group like this `(?is:(My name is ))(\w+)` `REGEXP_REPLACE(str, r'(?is:(My name is ))(\w+). ', r'\1 C')`
That is a **very** bad idea. A randomized delay would change the ordering of the packets passed between the layers. That is definitely something that does not happen in real life systems. A fixed, non-random delay may or may not be ok. INET supports modeling processing delay in Switches where it models the processing time requires to do the work to decide where to forward the packet. But still, the delay must be constant.
I am creating a report for Business Central and unfortunately this change can't be made within AL so I'm having to try an expression change for the field in RDLC. The field is currently, =Fields!HighDescription.Value I need to get rid of leading values if the value pulled in begins with: RS-BE Here is what I have tried with no success yet: =IIf(Left(Fields!HighDescription.Value, 6) = "RS-BE", Mid(Fields!HighDescription.Value, 6), Fields!HighDescription.Value) =Switch(Left(Fields!HighDescription.Value, 6) = "RS-BE", Mid(Fields!HighDescription.Value, 6), True, Fields!HighDescription.Value) =IIf(Left(Trim(Fields!HighDescription.Value), 6) = "RS-BE", Trim(Mid(Fields!HighDescription.Value, 6)), Trim(Fields!HighDescription.Value)) These expressions did not change anything and brought in the values as normal.
{"Voters":[{"Id":17303805,"DisplayName":"zephryl"},{"Id":2530121,"DisplayName":"L Tyrone"},{"Id":466862,"DisplayName":"Mark Rotteveel"}],"SiteSpecificCloseReasonIds":[11]}
QueryAsync returns intermittent errors 'This MySqlConnection is already in use.' and 'Connection must be Open; current state is Connecting'
|c#|mysql|dapper|pomelo-entityframeworkcore-mysql|
{"Voters":[{"Id":7758804,"DisplayName":"Trenton McKinney"},{"Id":9214357,"DisplayName":"Zephyr"},{"Id":466862,"DisplayName":"Mark Rotteveel"}]}
How would I write *n* nested *for* loops without knowing what *n* is? For example, how would I write the following using recursion or another method? for (int i = 0; cond1; i++) { for (int j = 0; cond2; j++) { for (int k = 0; cond3; k++) ... for (int l = 0; cond_N; l++) { if (.....) break; } } } } Here, there are *n* loops with some condition (not necessarily the same condition for each variable) and I'm not sure how to transform this into code using recursion without knowing what *n* is.
Multiple nested 'for' loops without knowing the number of 'for' loops
I'm facing intermittent issues like: > This MySqlConnection is already in use. and > Connection must be Open; current state is Connecting They are hard to reproduce but in logs I can see a lot of them. I'm using the library `Pomelo.EntityFrameworkCore.MySql` and running queries with dapper `QueryAsync`. connectionstring: Server=****;DataBase=*****;Uid=***;Pwd=****;default command timeout=0;SslMode=none;max pool size=1000;Connect Timeout=300;convert zero datetime=True;ConnectionIdleTimeout=5;Pooling=true;MinimumPoolSize=25 Code example: var query = $@" SELECT at.*, dpt.*, c.*, cnt.*, mEnc.*, atUsr.*, usr.* FROM Atendimento AS at INNER JOIN Departamento AS dpt ON at.DepartamentoId = dpt.Id INNER JOIN Canal AS c ON at.CanalId = c.Id LEFT JOIN Contato AS cnt ON at.ContatoId = cnt.Id LEFT JOIN MotivoEncerramento as mEnc ON at.MotivoEncerramentoId = mEnc.id LEFT JOIN ( AtendimentoUsuario AS atUsr INNER JOIN Users AS usr ON atUsr.UserId = usr.Id ) ON at.Id = atUsr.AtendimentoId WHERE at.IdRef = '{idRef}' ORDER BY dpt.Id, c.Id, atUsr.Id, usr.Id;"; var atendimentos = await Dapper.SqlMapper.QueryAsync<Atendimento, Departamento, Canal, Contato, MotivoEncerramento, AtendimentoUsuario, Usuario, Atendimento>( _dbContext.Database.GetDbConnection(), query, (atendimento, departamento, canal, contato, motivoEncerramento, atUsuario, usuario) => { atendimento.Departamento = departamento; atendimento.Contato = contato; atendimento.MotivoEncerramento = motivoEncerramento; atendimento.Canal = canal; atendimento.AtendimentoUsuarios = new List<AtendimentoUsuario>(); if (atUsuario is not null) { atUsuario.Usuario = usuario; atendimento.AtendimentoUsuarios.Add(atUsuario); } return atendimento; }); var result = atendimentos.GroupBy(a => a.Id).Select(g => { var groupedAtendimento = g.First(); if (g.Any(c => c.AtendimentoUsuarios.Count > 0)) { groupedAtendimento.AtendimentoUsuarios = g.Select(a => a.AtendimentoUsuarios.SingleOrDefault()).ToList(); } return groupedAtendimento; }); atendimento = result.First(); This `_dbContext.Database.GetDbConnection()` method: // // Summary: // Gets the underlying ADO.NET System.Data.Common.DbConnection for this Microsoft.EntityFrameworkCore.DbContext. // This connection should not be disposed if it was created by Entity Framework. // Connections are created by Entity Framework when a connection string rather than // a DbConnection object is passed to the 'UseMyProvider' method for the database // provider in use. Conversely, the application is responsible for disposing a DbConnection // passed to Entity Framework in 'UseMyProvider'. // // Parameters: // databaseFacade: // The Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade for the context. // // Returns: // The System.Data.Common.DbConnection // // Remarks: // See Connections and connection strings for more information. public static DbConnection GetDbConnection(this DatabaseFacade databaseFacade) { return GetFacadeDependencies(databaseFacade).RelationalConnection.DbConnection; } I see some people saying to use `ToList()` after the `Select` method but they weren't using dapper.
|asp.net|assembly|dll|.net-4.8|.net-standard-2.1|
|loops|if-statement|merge|
Is there a way to make this request with UrlFetchApp in app script? `curl -X GET http://test.com/api/demo -H 'Content-Type: application/json' -d '{"data": ["words"]}'` I attempted it with this code: ``` const response = UrlFetchApp.fetch(API_URL, { method: "GET", headers: { "Content-Type": "application/json" }, payload: JSON.stringify(payload) }); ``` *The payload and the endpoint are the exact same as the curl request which I tested* However I got this error "Failed to deserialize the JSON body into the target type: missing field \`name` at line 1 column 88".
As [ltk][1] said, you can add shadow. I just show you example with SliverAppBar that worked for me. ``` SliverAppBar( bottom: PreferredSize( preferredSize: Size.fromHeight(0), child: Container( decoration: const BoxDecoration( color: Colors.white, boxShadow: [ BoxShadow( color: Colors.white, blurRadius: 0.0, spreadRadius: 1.0, offset: Offset(0, 0), ), ], ), child: ...)) ``` [1]: https://stackoverflow.com/a/69787650/12979518
I have seen a few other questions here but none of them really achieve what I want them to. I guess I'm open to using Javascript or jQuery here, whatever works best. Question: I have a page with a link that redirects the user to a FAQ page, if this link is clicked, I want the user to be redirected to the new page AND to scroll down to a specific element(one of the drop-down questions), and open it (simulate a click). Is this possible? Here is the link from the initial page: ```https://somethinghere.com#q5-section``` As you can see I have already added the anchor tag at the end, doesn't seem to be working (does it matter if link is opened in a new tab or same window? Currently it opens a new tab And the ID of the drop-down that should be opened on the new page when that link is clicked is ```#q5-section``` Here is the HTML code from the entire FAQ drop-down: ```HTML <div class="faq-question" id="q5-section"> <input id="q5" type="checkbox" class="panel"> <div class="plus">+</div> <label for="q5" class="panel-title">................</label> <div class="panel-content"> <span> ....................Β» <ul> <li>.........................</li> <li>..........................</li> </ul> <br><br> .......................Β» <ul> <li>...................</li> </ul> </span> </div> </div> ``` If there is any missing info to achieve this please let me know.
Scroll to DIV on click from another page and open FAQ-dropdown
|javascript|html|jquery|css|
import 'package:flutter/material.dart'; import 'package:hlibrary/main.dart'; class Panel extends StatelessWidget { const Panel({Key? key}); @override Widget build(BuildContext context) { return Stack( children: [ Scaffold( appBar: AppBar( centerTitle: false, title: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text("Hlibrary", style: Theme.of(context).textTheme.bodyLarge!.copyWith( color: Colors.orangeAccent, ),), Text("Admin Panel", style: Theme.of(context).textTheme.titleLarge!.copyWith( color: Colors.orangeAccent, ),), ],) ), floatingActionButton: FloatingActionButton( onPressed: (){}, backgroundColor: Colors.orangeAccent, child: const Icon(Icons.add), ), drawer: Drawer( child: ListView( padding: EdgeInsets.zero, children: <Widget>[ const DrawerHeader( decoration: BoxDecoration( color: Color(0xFFFFB800), ), child: Text( 'Admin Tengis', style: TextStyle( color: Colors.white, fontSize: 24, ), ), ), ListTile( leading: Icon(Icons.add), title: const Text('Add'), onTap: () { // Handle Option 1 }, ), ListTile( leading: Icon(Icons.list), title: const Text('Added files'), onTap: () { // Handle Option 2 }, ), ListTile( leading: Icon(Icons.arrow_back), title: const Text('Go back'), onTap: () { Navigator.pop(context); }, ), // Add more ListTile for additional options ], ), ), body: ListView( ), ), ], ); } } [enter image description here](https://i.stack.imgur.com/TCOAB.png) it looks like this and I want to add categories of book when I tap the add button which is on right down corner
how can I add list of categories to my body in flutter? please I'm new to it
|flutter|dart|listview|categories|
null
You would create a base `projen` configuration, then make it available for target projects, e.g. as a package published to a shared NPM registry. When you make changes to the base configuration, you would go to the target repositories, update the package, make any necessary updates, e.g. for breaking changes, re-apply the changes and push a pull request. In a sense, it's not much of a different workflow as you're already accustomed with for, say, having a shared ESLint configuration package.
DB_CONNECTION=sqlite3 worked for me
Should I train my model with a set of pictures as one input data or I need to crop to small one using Pytorch
I wanted to add a modern, functional-style recursive function based on @AndrewMoore's script. None of the logic has changed. Iterate over all keys of a level. If the value is an array, traverse into the array. Prepend the carried prefix to each encountered key. `array_map()` version: ([Demo][1]) function getKeyPaths(array $array, string $prefix = ''): string { return implode( ',', array_map( fn($k, $v) => is_array($v) ? getKeyPaths($v, "$prefix$k") : "$prefix$k", array_keys($array), $array ) ); } var_export(getKeyPaths($array)); --- `array_reduce()` version: ([Demo][2]) function getKeyPaths(array $array, string $prefix = ''): string { return implode( ',', array_reduce( array_keys($array), fn($carry, $k) => $carry + [ $k => is_array($array[$k]) ? getKeyPaths($array[$k], "$prefix$k") : "$prefix$k" ], [] ) ); } var_export(getKeyPaths($array)); [1]: https://3v4l.org/mq9QN [2]: https://3v4l.org/uELPi
null
Hovering doesn't want to work by any way. Code Below: - ``` self.setStyleSheet(""" QMenuBar { background-color: white; color: black; border: 3px solid silver; font-weight: bold; font-size: 23px; } QMenuBar::item { background-color: white; border: 2px solid silver; } QMenuBar::item::selected { background-color: grey; } QLabel:hover { #I tried both QLabel and QWidgetAction background-color: grey; } """) ``` And here the QWidgetAction and QLabel below: - ``` self.Menu = QMenuBar(self) self.Menu.resize(self.width(), 40) self.Menu.move(0, 0) self.File = self.Menu.addMenu('File') self.FileNew = QWidgetAction(self.File) self.New = QLabel("New") self.New.setMouseTracking(True) self.New.setAlignment(QtCore.Qt.AlignCenter) self.New.setStyleSheet("border: 2px solid silver; background-color: white; color: black; padding: 4 4 4 4px") self.FileNew.setDefaultWidget(self.New) ``` I searched in many threads and docs abt :hover method and tried it but it didn't work for me. And when I hover with my mouse on the QWidgetAction it stills frozen. Thanks for your time.
I am trying coding a test automation for a mobile application but this application has a restriction about the root devices so when I try running the application on the device, the application take me out.... is there a way to start the mobile on andriod studio as unroot device?
how to remove the root on a simulate android studio device
|testing|automation|appium-android|
I'm buiding a React component that changes state on button click *AND* after some timed interval, after button click, changes back to its original state. Here is my simple code: import React, { useState, useEffect } from "react"; const TimedButton = (props) => { const [user_id, setUserId] = useState("FIRST"); const handleClick = (event) => { setUserId("SECOND"); setTimeout(() => { console.log("Trigger..."); console.log(user_id) if (user_id) this.setUserId("FIRST"); }, 1000); }; return ( <div> <button onClick={handleClick}> {user_id} </button> </div> ); }; export default TimedButton; On click, `FIRST` changes to `SECOND`, fine. After timeout (1 second), `user_id` is set back to `FIRST`, but for some reason it's not re-rendering the screen, that remains as `SECOND` (but at that point user_id is `FIRST`). Help appreciated to solve this.
null
I have a simple question. I'm using "**app folder**" in my Next js 14 project. In the **layout.tsx** file (**can also be page.tsx**) I get data from the server side API and pass it to the child components using props. This gets annoying when there are many nested children components. In addition, I also need to type the data that I pass using props. Yes, I know, if I make the same request on the server components, Next js does not send a new request, it pulls it from the cache. However, I can't do this because **my children components are on the client side**. How do you cope in such situations? Thank you in advance. [![enter image description here](https://i.stack.imgur.com/y0THB.jpg)](https://i.stack.imgur.com/y0THB.jpg) I searched everywhere but couldn't get the result I wanted.
Next js 14 - prop drilling
|reactjs|next.js|
null
#include <stdio.h> #include <math.h> #define MAX_BITS 32 int counter = 0, dec_eqv = 0; int runcounter = 1; int binToDec(char *bit) { printf("dec_eqv is %d\n", dec_eqv); if (counter == 0 && runcounter) { dec_eqv = 0; int i = 0; while (*(bit + i++)) ; counter = (i - 1) - 1; runcounter = 0; printf("counter is %d\n", counter); } if (*bit != 0) { printf("*bit not zero\n"); if (*bit == '1') { dec_eqv += (int)pow(2, counter--); } else { counter--; } binToDec(bit + 1); } else { printf("here *bit is 0\n"); runcounter = 1; printf ("here dec_eqv is %d\n", dec_eqv); return dec_eqv; printf ("Skipping return\n"); } return -1; } int main() { char bin[MAX_BITS]; printf("Enter binary number (%d-bit max): ", MAX_BITS); scanf("%[^\n]s", bin); int result = binToDec(bin); printf("Decimal equivalent of 0b%s is %d.", bin, result); return 0; } I've added the ```printf()``` statements in ```binToDec()``` for debugging, and it seems that the compiler is ignoring the ```return dec_eqv;``` statement in the final ```else``` block and directly executing the ```return -1;``` at the end. What could be possibly wrong? I am using Clang/LLVM compiler in Ubuntu 23.10 AMD64 and no errors or warnings were generated during compilation.
Clang possibly skipping line(s) of code while compiling
I have tried to isolate my problem in a very simple (and working) project. Let's say I have a simple model with 2 fields, and I have configured its properties and a `PropertyChanged` event. This is a simplified implementation of my model, please notice the last method just gets a new client object from a list and returns it: public class Clients : INotifyPropertyChanged { private long _Id = 0; public long Id { get { return this._Id; } set { this._Id = value; RaisePropertyChanged("Id"); } } private String _Name = string.Empty; public String Name { get { return this._Name; } set { if (value is null) this._Name = string.Empty; else this._Name = value; RaisePropertyChanged("Name"); } } public event PropertyChangedEventHandler? PropertyChanged; internal void RaisePropertyChanged(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } // Let's say this is a populated list with 100 clients with different ids and names public static List<Clients> clients = new List<Clients>(); // ...method for loading the list with DB data public static Clients? LoadClient(long id) { return clients.FirstOrDefault(x => x.Id == id); } } And I have a simple `.xaml` file in order to display one client data (id and name). Each UI control has a binding with the client property and the trigger for updating. I have also 2 configured buttons that will make changes to the client values: <TextBox x:Name="txtClientId" Text="{Binding Id, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> </TextBox> <TextBox x:Name="txtClientName" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> </TextBox> <Button Name="btnNext" Click="btnNext_Click">Next</Button> <Button Name="btnRandom" Click="btnRandom_Click">Random</Button> Now let's take a look to my `.xaml.cs` code. Here is the initializing and the code for the 2 buttons: one of them just modify the client properties in the `DataContext` object directly, and the other just assigns a new client object to the `DataContext` client: public partial class ClientsPage : Page { private Models.Clients? client = null; public ClientsPage() { InitializeComponent(); // Load all clients data in Models.Clients.clients list... client = new Models.Clients(); DataContext = client; } private void btnNext_Click(object sender, RoutedEventArgs e) { client = Models.Clients.LoadClient(client.Id + 1); } private void btnRandom_Click(object sender, RoutedEventArgs e) { Random random = new Random(); client.Id = random.Next(999); client.Name = "RANDOM"; } } - When I set the DataContext, data is displayed correctly in the UI -> OK - When I make changes directly in the properties of the client object changes are reflected correctly in the UI -> OK - But... when I load a new client object, and assign it to the variable set as `DataContext`, the `PropertyChanged` event is not raised. Of course this situation can be solved by assigning property values instead of assigning a new object directly: private void btnNext_Click(object sender, RoutedEventArgs e) { Models.Clients newClient = Models.Clients.LoadClient(client.Id + 1); this.client.Id = newClient.Id; this.client.Name = newClient.Name; } But it is so tedious in a real project with many models and methods that can load/modify an object with a lot of fields. I'm looking for an easy/scalable way for making the `PropertyChanged` event fire when I assign a new object to the `DataContext` variable. If you need more detail of my code or have any question I'll be happy to ask.
Assigning an object to another doesn't raise PropertyChanged event in WPF
Is your code using the defined `AppDataSource`? I suggest just providing a `ormconfig.json` file with the details. See example with full working stack below. 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
Using VLCKit I am able to display subtitles by setting the current video subtitle index. But I can't find an option in the documentation that allows to change the font and font size. So I have know idea how to increase or decrease the font size. ```Swift import VLCKit let player = VLCMediaPlayer() let media = VLCMedia! media = VLCMedia(url: mediaURL) player.media = media player.play() //Set subtitle player.currentVideoSubTitleIndex = 1 //Change font size ?? ```
VLCKit: How to adjust subtitle font size in Swift macOS?
|macos|swiftui|subtitle|vlckit|
The [accepted answer](https://stackoverflow.com/a/71094531/6243352) logs an empty refs array in Vue < 3.2.32: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> const {ref, onMounted} = Vue; Vue.createApp({ setup() { const items = [ {id: 1, name: "item name 1"}, {id: 2, name: "item name 2"}, {id: 3, name: "item name 3"}, ]; const elements = ref([]); onMounted(() => { console.log( elements.value.map(el => el.textContent) ); }); return {elements, items}; } }).mount("#app"); <!-- language: lang-html --> <div id="app"> <div v-for="(item, i) in items" ref="elements" :key="item.id"> <div>ID: {{item.id}}</div> <div>Name: {{item.name}}</div> </div> </div> <script src="https://unpkg.com/vue@3.2.31/dist/vue.global.prod.js"></script> <!-- end snippet --> A workaround is replacing `refs="elements"` with `:ref="el => elements[i] = el"`: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> const {ref, onMounted} = Vue; Vue.createApp({ setup() { const items = [ {id: 1, name: "item name 1"}, {id: 2, name: "item name 2"}, {id: 3, name: "item name 3"}, ]; const elements = ref([]); onMounted(() => { console.log( elements.value.map(el => el.textContent) ); }); return {elements, items}; } }).mount("#app"); <!-- language: lang-html --> <div id="app"> <div v-for="(item, i) in items" :ref="el => elements[i] = el" :key="item.id"> <div>ID: {{item.id}}</div> <div>Name: {{item.name}}</div> </div> </div> <script src="https://unpkg.com/vue@3.2.31/dist/vue.global.prod.js"></script> <!-- end snippet -->
Architecture: Flask app running in its own container, Celery running in its own container. Message broker is Redis. This is all python btw. Problem: I cant figure out how to register a class based task with a custom name. Versions: ``` celery==5.2.7 redis==5.0.3 ``` Details: I want to build class based tasks as I want to be able to use the `on_success` handler on every task. Note all class based tasks are defined in the celery container, so the flask app has no way to know what they are. The flask app must be able to call them by a "name". I tried using the default name, which I could not get to work with celery based classes, it required a name. I also tried to configure a custom name. Every time I try to do this I get this error ``` [2024-03-12 22:53:01,292: CRITICAL/MainProcess] Unrecoverable error: AttributeError("'NoneType' object has no attribute 'push'") Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/celery/worker/worker.py", line 203, in start self.blueprint.start(self) File "/usr/local/lib/python3.9/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/usr/local/lib/python3.9/site-packages/celery/bootsteps.py", line 365, in start return self.obj.start() File "/usr/local/lib/python3.9/site-packages/celery/worker/consumer/consumer.py", line 332, in start blueprint.start(self) File "/usr/local/lib/python3.9/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/usr/local/lib/python3.9/site-packages/celery/worker/consumer/tasks.py", line 26, in start c.update_strategies() File "/usr/local/lib/python3.9/site-packages/celery/worker/consumer/consumer.py", line 562, in update_strategies task.__trace__ = build_tracer(name, task, loader, self.hostname, File "/usr/local/lib/python3.9/site-packages/celery/app/trace.py", line 361, in build_tracer push_request = request_stack.push AttributeError: 'NoneType' object has no attribute 'push' ``` Really I just want to find a way to have celery tasks perform an operation after they complete their tasks. `on_success` seems like the right thing to do, but I cant figure out how to use it outside of a class based task, and I cant get class based tasks working. Can anyone help?
React setState inside handleClick after setTimeout
|javascript|reactjs|
|html|css|html-table|css-selectors|
i Do this on Ubuntu(WSL on Windown *normaly it should work on Ubuntu*) : `sudo apt install libgl1-mesa-dev`
Here is one solution assuming that your structure is only 3 levels deep ``` lang-txt variable "input_list" { default = { "a" = { "a1" = {} "a2" = {} } "b" = { "b1" = {} "b2" = { "b21" = {} } } } } locals { paths = flatten([ for k0 in keys(var.input_list) : [ for k1 in keys(var.input_list[k0]) : [ length(keys(var.input_list[k0][k1])) > 0 ? [for k2 in keys(var.input_list[k0][k1]) : "${k0}/${k1}/${k2}"] : ["${k0}/${k1}"] ] ] ]) } output "paths" { value = local.paths } ``` when we do a terraform plan on that we will get: ``` lang-txt terraform plan Changes to Outputs: + paths = [ + "a/a1", + "a/a2", + "b/b1", + "b/b2/b21", ] ``` That should give you an idea what to do **IF** your structure has a max amount of levels, you can use this same technique to extract what you need, just add more nested loops to match your max. If you do not know the amount of levels, you will need a recursive way to navigate the directory and I honestly don't think that is possible with the builtin functions from Terraform, you might need to extract that with some other tool/script then pass it as an input parameter.
What are you trying to do is called _pivoting_, so use [`DataFrame.pivot()`][1]: ```py import pandas as pd df = pd.read_csv("your_file.csv", header=None) out = ( df.pivot(index=1, columns=0, values=2) .rename_axis(index="ID", columns=None) .reset_index() ) print(out) ``` Prints: ```none ID 1:100011159-T-G 1:10002775-GA 1:100122796-C-T 1:100152282-CAAA-T 0 CDD3-597 GG GG TT CC 1 CDD3-598 GG NaN NaN CC ``` --- EDIT: With your updated input: ```py import pandas as pd df = pd.read_csv("your_file.csv", header=None) df["tmp"] = df[[2, 3]].agg("".join, axis=1) # <-- join the two columns together out = ( df.pivot(index=1, columns=0, values="tmp") .rename_axis(index="ID", columns=None) .reset_index() ) print(out) ``` [1]: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html#pandas-dataframe-pivot
Given an linear system Ax=b, x = [x1; x2], where A,b are given and x1 is also given. A is symmetric. I want to compute the gradient of x1 in terms of A,b, i.e. dx1/dA, dx1/db. It seems that torch.autograd.backward() can only compute the gradient by solving the whole linear system. But I want to make it more efficient by not solving x1 again since it is already given. Is it feasible? If so, how to implement it using pytorch? For now, I only know how to get the gradient by solving the whole system: ``` #[A1 A2; A3 A4] * [x1; x2] = [b1; b2] m1 = 10 n1 = 10 m3 = 5 n3 = n1 m2 = m1 n2 = m1 + m3 - n1 m4 = m3 n4 = n2 A = torch.rand((m1+m3,n1+n2)).clone().detach().requires_grad_(True) A1 = A[:m1,:n1] A2 = A[:m1,n1:] A3 = A[m1:,:n1] A4 = A[m1:,n1:] # x1 is already given x1 = torch.ones((n1,1)).clone().detach().requires_grad_(True) # x2 needs to be solved x2_gt = torch.rand((n2,1)) b1 = (A1 @ x1 + A2 @ x2_gt).detach().requires_grad_(True) b2 = (A3 @ x1 + A4 @ x2_gt).detach().requires_grad_(True) b = torch.vstack((b1,b2)) x = torch.linalg.solve(A,b) x.backward(torch.ones(m1+m3,1)) ```
I have a problem where my table users have: @OneToMany(mappedBy = "id.utenti", cascade = {CascadeType.ALL}, orphanRemoval = true) private List<UtentiCatenaRuoli> ruoliUtente = new ArrayList<>(); that is linked to a relation table with 3 foreign keys, user, role and section where role apply. Using mapstruct i map DTO to Entity and vice-versa, for example creating an user works like that: { "nome": "test", "ruoli": [ # Translate for roles { "1": "ANAGRAF" # Pair for section and role }, { "1": "ASSEGNA" } ] } That works on create, no problems. The same code dosn't work when I try to update. I get the EntityByReference, pass it to mapstruct update method, use the same "qualifiedByName" used in create but hibernate dosn't fill the "user" field on relation. I'll try to explain more: @Named("toUtenteRuoloCatenaList") default List<UtentiCatenaRuoli> toUtenteRuoloCatenaList(List<Map.Entry<Long, String>> values, @Context RuoliRepository ruoliRepository, @Context CatenaComandoRepository catenaComandoRepository) { List<UtentiCatenaRuoli> utentiCatenaRuolis = new ArrayList<>(); values.forEach(pair -> { UtentiCatenaRuoliPK utentiCatenaRuoliPK = new UtentiCatenaRuoliPK(catenaComandoRepository.getReferenceById(pair.getKey()), ruoliRepository.getReferenceById(pair.getValue())); UtentiCatenaRuoli utentiCatenaRuoli = new UtentiCatenaRuoli(utentiCatenaRuoliPK); utentiCatenaRuolis.add(utentiCatenaRuoli); }); return utentiCatenaRuolis; } This is what my mapstruct function uses for conversion from DTO roles to Entity, utentiCatenaRuoliPK is missing the user reference id that hibernate fills alone on INSERT, same thing dosn't happend on UPDATE. Result: Update throw exception cause relation table user filed can't be null. Why there is a different treatment for insert and update? EDIT: I'm using something similiar with a relation table that have only 2 foreign keys and all works fine(user_ref get autofilled in both situations)
Entity relation isn't updated when referencing more than one field
|spring-boot|hibernate|mapstruct|
I am trying to create a custom widget for DropDownButton. It seems to work fine. The onChanged() func is also working when I take console print of the changed value. However, I am not able to view the text in the box after the Onchanged() func. Can someone let me know what could be wrong with the same? My code with the widget is below: import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; class InputScreen2 extends StatefulWidget { final List<double> sizes; const InputScreen2({Key? key, required this.sizes}) : super(key: key); @override State<InputScreen2> createState() => _InputScreen2State(); } class _InputScreen2State extends State<InputScreen2> { Future? future; double screenwd = 0, screenht = 0; List<String> listsex = ['Male', 'Female']; String? sex; @override void initState() { // TODO: implement initState future = _future(); super.initState(); } Future<int> _future() async { SharedPreferences prefs = await SharedPreferences.getInstance(); screenwd = widget.sizes[0]; screenht = widget.sizes[1]; return 0; } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.orange, body: FutureBuilder( future: future, builder: (context, snapshot) { if (snapshot.hasError) { return Center( child: Text( 'Data Error...Please try again', style: Theme.of(context).textTheme.titleSmall, )); } else if (snapshot.connectionState == ConnectionState.waiting) { return Text( 'Waiting', style: Theme.of(context).textTheme.titleSmall, ); } else if (!snapshot.hasData) { return Text( 'No Data', style: Theme.of(context).textTheme.titleSmall, ); } else if (snapshot.hasData) { //Block I==================================================== return SafeArea( child: Center( child: Container( padding: const EdgeInsets.all(20.0), decoration: BoxDecoration( border: Border.all(width: 2.0), color: Colors.blue), width: screenwd * .8, height: screenht * .75, child: SingleChildScrollView( child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.start, children: [ const Text( 'Personal Details', ), const SizedBox( width: 23, ), dropDownMenu('Sex', sex, listsex), ], ), ], ), ), ), ), ); } return const Text('No DATA'); })); } Widget dropDownMenu(String title, String? inputTxt, List<String> stringList) { return Container( margin: const EdgeInsets.only(top: 10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( title, ), Container( width: 80, height: 35, decoration: BoxDecoration( border: Border.all(color: Colors.white, width: 1.0), borderRadius: const BorderRadius.all(Radius.circular(5.0))), child: DropdownButton<String>( value: inputTxt, dropdownColor: Colors.amber, items: stringList.map<DropdownMenuItem<String>>((String value) { return DropdownMenuItem<String>( value: value, child: Text( value, style: const TextStyle(color: Colors.white), )); }).toList(), onChanged: (String? value) { setState(() { inputTxt = value!; }); }), ), ], ), ); } }
DropdownMenu Widget issues = Flutter
|flutter|widget|dropdown|dropdownbutton|
I was able to solve this issue by installing .NET 6.0 WebAssembly Build Tools.
You're using a string as `src` instead of the actual import. Use the imports as the `src`. ``` import React from "react"; import ReactLogo from "./image/react.svg"; import TypeScript from "./image/typescript.svg"; import MongoDB from "./image/logo_mongodb_icon.svg"; import JavaScript from "./image/logo-javascript.svg"; import NodeJS from "./image/logo_nodejs_icon.svg"; import Express from "./image/expressjs-icon.svg"; import Python from "./image/python-4.svg"; function Main() { const images = [ { src: ReactLogo, alt: "react" }, { src: Typescript, alt: "typescript" }, { src: MongoDB, alt: "mngodb" }, { src: Javascript, alt: "javascript" }, { src: NodeJS, alt: "nodejs" }, { src: Express, alt: "express" }, { src: Python, alt: "python" }, ]; return ( <div> <div> {images.map((image, index) => ( <img key={index} src={image.src} alt={image.alt} /> ))} </div> </div> ); } ```
I have a pretty simple queue which happens to have heaps of messages on it (by design). Heaps can be "thousands" here. Right now I'm playing around with using Azure Web Jobs with a Queue Trigger to process the messages. Works fine. I'm worried about performance though. Let's assume my method that processes the message takes 1 sec. With so many messages, this all adds up. I know I can manually POP a number of messages at the same time, then parallel process them .. but I'm not sure how we do this with web jobs? I'm _assuming_ the solution is to scale _out_? which means I would create 25 instances of the webjob? Or is there a better way where I can trigger on a message but pop 25 or so messages at once, then parallel them myself. NOTE: Most of the delay is I/O (ie. a REST call to a 3rd party). not CPU. I'm thinking -> create 25 tasks and `await Task.WhenAll(tasks);` to process all the data that I get back. So, what are my options? NOTE #2: If the solution is scale out .. then I also need to make sure that my web job project only has _one_ function in it, right? otherwise _all_ the functions (read: triggers, etc) will also _all_ be scaled out.
I am using the following code to call my REST API from SQL Server but I am getting empty string in the response message. I put a breakpoint in visual studio on getTravelerInfoById method but it is also not triggered. Can you please check and let me know what am I doing wrong? DECLARE @URL NVARCHAR(MAX) = 'https://localhost:7128/api/TravelerBase/getTravelerInfoById'; DECLARE @Object AS INT; DECLARE @ResponseText AS VARCHAR(8000); DECLARE @Body AS VARCHAR(8000) = '{ "var1": "2024-03-16 16:56:59", "var2": "+0200", "var3": "856" }' EXEC sp_OACreate 'MSXML2.XMLHTTP', @Object OUT; EXEC sp_OAMethod @Object, 'open', NULL, 'post', @URL, 'false' EXEC sp_OAMethod @Object, 'setRequestHeader', null, 'Content-Type', 'application/json' EXEC sp_OAMethod @Object, 'send', null, @body EXEC sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT SELECT @ResponseText As 'ResponseText' IF CHARINDEX('false',(SELECT @ResponseText)) > 0 BEGIN SELECT @ResponseText As 'Message' END ELSE BEGIN SELECT @ResponseText As 'customer Details' END EXEC sp_OADestroy @Object I enabled the procedures as below: sp_configure 'show advanced options', 1; GO RECONFIGURE; GO sp_configure 'Ole Automation Procedures', 1; GO RECONFIGURE; GO I tried a GET api https://localhost:7128/api/TravelerBase/getVersion as well but it is also not triggered. Thanks.
Calling a REST API from SQL Server
|sql-server|t-sql|stored-procedures|
null
> I'm not a native English speaker, so please try to avoid abbreviations or slang in your answers. I want to try to declare an abstract class field in a Python base class. I know that python can declare an abstract object field via `@property` and `@abstractmethod`, but I haven't checked for a viable abstract class field. I want to be able to implement such use case: ```python class AbcClass(metaclass=ABCMeta): @abstractproperty class_field: int # class-level static field # inherite abstract class class MyClass(AbcClass): class_field = 42 ``` About related thread: [Python: Create Abstract Static Property within Class](https://stackoverflow.com/questions/49022656/python-create-abstract-static-property-within-class): This post does give some viable options, but since I'm trying metaprogramming, using `__init_subclass__` causes IDE support to become difficult.
How to register celery class based task with a custom name in 5.x?
|class|celery|task|naming|
I hope method with @Transactional of CommandLineRunner, or ApplicationRunner can resolve this problem. Am I right?
> for POC purposes, as mentioned I'm using: - NodeJS v20 - Typescript 5.3 - using [ESM][1] - stage 3 TC39 Proporsal Decorators ```js class LambdaFunctionExample { lambdaResponse = [1, 2, 3] @tryCatchWrapper async handler(event) { const data = this.lambdaResponse; const result = await fetch(...) return { statusCode: 200, data, result }; } } export const handler = (event) => new LambdaFunctionExample().handler(event) ``` decorator function: ```js export function tryCatchWrapper<T>(target: Function, { kind, name, ...context }) { if (kind === 'method') return async function (this: unknown, ...args: any) { try { console.log('name', name) return await target.call(this, ...args) } catch (error) { console.log('error catched') return {} } } } ``` and running ```sh npm start # node index.js (as usual) ``` .tsconfig ```json "compilerOptions": { // Module Setup "target": "ES2022", // as of today, I tried with ESNext and it did't work, so I need to use strictly ES2022 //"module": "NodeNext", (also optional, but you imporant if you are using ESM) //"moduleResolution": "NodeNext", (also optional, but you imporant if you are using ESM) ... } ``` [1]: https://nodejs.org/api/esm.html#modules-ecmascript-modules
I have a large dataset that is difficult to investigate without analysis tools. It's general form is this, but with 16 "ItemType0" columns and 16 "ItemType1", "ItemType2", etc columns. It represents the properties (many of them) of up to 16 different items recorded at a single timestep, then properties of that timestep. |Time|ItemType0[0].property|ItemType0[1].property|Property| |:--:|:-------------------:|:-------------------:|:------:| |1 |1 |0 |2 | |2 |0 |1 |2 | |3 |3 |3 |2 | I'd like to receive: |Time|ItemType0.property|Property| |:--:|:----------------:|:------:| |1 |1 |2 | |2 |0 |2 | |3 |3 |2 | |1 |0 |2 | |2 |1 |2 | |3 |3 |2 | What I've tried: ``` import pandas as pd wide_df = pd.DataFrame({ "Time":[1,2,3], "ItemType0[0].property":[1,0,3], "ItemType0[1].property":[0,1,3], "Property":[2,2,2]}) ``` 1. ``` ids = [col for col in wide_df.columns if "[" not in col] inter_df = pd.melt(wide_df,id_vars=ids,var_name="Source") ``` MemoryError: Unable to allocate 28.3 GiB for an array with shape (15,506831712) and data type uint32 2. I wouldn't even know where to begin with pd.wide_to_long as everything doesn't start with the same.
Pandas - Python: Using either melt or wide_to_long for large dataset with inconsistent naming
|python|pandas|pandas-melt|
I'm writing a Tkinter program that so far creates a window with a menu bar, a File menu, and a single item. The menu is successfully created, but with two items, the first being one that I did not specify, whose name is "-----". If I don't add an item, the spontaneous one is still added. This still happens if I specify tearoff=0. Any idea why this is happening? Windows 11, Python 3.12.2, Tkinter and Tcl 8.6. import tkinter as tk window = tk.Tk() window.geometry("800x600") menubar = tk.Menu(window) window.config(menu=menubar) fileMenu = tk.Menu(menubar) fileMenu.add_command( label="Exit", command=window.destroy, ) menubar.add_cascade(label="File", menu=fileMenu, underline=0) window.mainloop()
I ask same question to chatgpt and below code is working for me import threading import time from selenium import webdriver from selenium.webdriver.chrome.service import Service def send_whatsapp_message(): # Path to your Chrome WebDriver executable chrome_driver_path = "path_to_your_chromedriver.exe" # Create Chrome options chrome_options = webdriver.ChromeOptions() # Create Chrome WebDriver instance service = Service(chrome_driver_path) driver = webdriver.Chrome(service=service, options=chrome_options) # Open WhatsApp Web driver.get("https://web.whatsapp.com") # Wait for user to scan QR code and log in manually input("Scan the QR code and then press Enter to continue...") # Find the chat input field chat_input = driver.find_element_by_xpath('//div[@contenteditable="true"][@data-tab="6"]') # Enter the contact name or group name you want to send message to contact_name = "Contact Name or Group Name" # Find the contact/group by searching search_box = driver.find_element_by_xpath('//div[@contenteditable="true"][@data-tab="3"]') search_box.send_keys(contact_name) # Wait for search results to load time.sleep(2) # Click on the contact/group contact = driver.find_element_by_xpath(f'//span[@title="{contact_name}"]') contact.click() # Find the message input field message_input = driver.find_element_by_xpath('//div[@contenteditable="true"][@data-tab="1"]') # Enter the message you want to send message = "Your message here" # Type and send the message message_input.send_keys(message) message_input.send_keys(webdriver.common.keys.Keys.RETURN) # Close the WebDriver session driver.quit() # Start a new thread for WebDriver whatsapp_thread = threading.Thread(target=send_whatsapp_message) whatsapp_thread.start() # Continue with the main thread print("Main thread continues to execute...") # You can continue with other tasks here # Wait for the WebDriver thread to finish whatsapp_thread.join() # All tasks completed print("All tasks completed.")
You have to make a clean build. Go to File > Build Settings. Click on the arrow right to the Build button then click on "Clean Build..." Here's an image[![enter image description here][1]][1] [1]: https://i.stack.imgur.com/jOrJZ.png
|python|python-3.x|properties|ttkwidgets|
I need to add a space between the data on the X axis where in the print there are markings in red I need a margin that doesn't let the data touch, I'm using the heatmap to make a graph with a lot of data and I need this to make it cleare, But I couldn't add. I already looked in the documentation, I couldn't find a feature that can add this improvement to my graph [enter image description here](https://i.stack.imgur.com/2WC5H.png) ``` var dom = document.getElementById('chart-container'); var myChart = echarts.init(dom, null, { renderer: 'canvas', useDirtyRect: false }); var app = {}; var option; // prettier-ignore const hours = [ '12a', '1a', '2a', '3a', '4a', '5a', '6a', '7a', '8a', '9a', '10a', '11a', '12p', '1p', '2p', '3p', '4p', '5p', '6p', '7p', '8p', '9p', '10p', '11p' ]; // prettier-ignore const days = [ 'Saturday', 'Friday', 'Thursday', 'Wednesday', 'Tuesday', 'Monday', 'Sunday' ]; // prettier-ignore const data = [[1, 0, 5], [0, 0, 1]] .map(function (item) { return [item[1], item[0], item[2] || '-']; }); option = { tooltip: {}, grid: { height: '50%', top: '10%' }, xAxis: { type: 'category', data: hours, borderWidth: '10px', splitArea: { show: true } }, yAxis: { type: 'category', data: days, splitArea: { show: true } }, visualMap: { min: 0, max: 10, calculable: true, orient: 'horizontal', left: 'center', bottom: '15%' }, series: [ { name: 'Punch Card', type: 'heatmap', data: data, label: { show: true }, emphasis: { itemStyle: { margin: 10, shadowBlur: 10, shadowColor: 'rgba(0, 0, 0, 0.5)' } } } ] }; if (option && typeof option === 'object') { myChart.setOption(option); } window.addEventListener('resize', myChart.resize); ```
I need to add a space between the X axis data in heatmap echarts
|heatmap|echarts|
null
There are two types of errors can be occured in our server. So try catch block can handle Synchronous errors. try { my_function(); } catch(e){ }; But for asynchronous errors try { my_function(); } catch(e){ next(e); }; also you chan use .then() instead of try catch Promise.resolve().then(() => { throw new Error('BROKEN') }).catch(next) documentation - [Express error handling][1] you can use express-async-handler for handle this very easy [express-async-handler][2] [1]: https://expressjs.com/en/guide/error-handling.html [2]: https://www.npmjs.com/package/express-async-handler
Use SELECT `Order ID` FROM Returnedsss; or SELECT [Order ID] FROM Returnedsss; or SELECT "Order ID" FROM Returnedsss; The issue is how single quotes are used to enclose a literal value character string in preference to enclosing a component name (column table etc).
I was getting the same error. I tried a lot of fixes from the internet but nothing worked but thanks to our teacher, with his help i was able to fix it. so the error i was getting said that > my worker node has python3.10 while the driver has python3.11 that's not the exact wording of the error but you get the point, its the same error. What i had to do was to navigate to `/usr/bin/` and execute `ls -l` there. i got the following output: ``` lrwxrwxrwx 1 root root 7 Feb 12 19:50 python -> python3 lrwxrwxrwx 1 root root 9 Oct 11 2021 python2 -> python2.7 -rwxr-xr-x 1 root root 14K Oct 11 2021 python2.7 -rwxr-xr-x 1 root root 1.7K Oct 11 2021 python2.7-config lrwxrwxrwx 1 root root 16 Oct 11 2021 python2-config -> python2.7-config lrwxrwxrwx 1 root root 10 Feb 12 19:50 python3 -> python3.10 -rwxr-xr-x 1 root root 15K Feb 12 19:50 python3.11 -rwxr-xr-x 1 root root 3.2K Feb 12 19:50 python3.11-config lrwxrwxrwx 1 root root 17 Feb 12 19:50 python3-config -> python3.11-config -rwxr-xr-x 1 root root 2.5K Apr 8 2023 python-argcomplete-check-easy-install-script -rwxr-xr-x 1 root root 383 Apr 8 2023 python-argcomplete-tcsh lrwxrwxrwx 1 root root 14 Feb 12 19:50 python-config -> python3-config ``` notice the line `lrwxrwxrwx 1 root root 10 Feb 12 19:50 python3 -> python3.10` I realized that my python was pointing python3.10 even though i had python3.11 installed. so it should be pointing to python3.11 instead. If that's the same case with you then you've figured out the problem and the **following fix should work just fine for you.** 1. **Locate Python 3.11:** First, ensure that Python 3.11 is installed on your system. You mentioned it's installed, so you can proceed to locate its path. You can usually find it in `/usr/bin/` or `/usr/local/bin/`. Let's assume it's in `/usr/bin/python3.11`. 2. **Update the Symbolic Link:** You need to update the python3 symbolic link to point to Python 3.11. You can do this using the ln command in the terminal. Open a terminal and type:<br> `sudo ln -sf /usr/bin/python3.11 /usr/bin/python3` 3. **Verify the Update:** After running the command, you can verify that the symbolic link has been updated correctly by typing: <br> `ls -l /usr/bin/python3` <br> <br> This should show something like:<br> `lrwxrwxrwx 1 root root XX XXX XX:XX /usr/bin/python3 -> /usr/bin/python3.11` <br><br>This indicates that python3 now points to Python 3.11. Now, when you run your PySpark code, it should use Python 3.11 on both the worker nodes and the driver, resolving the version mismatch issue.
Let's consider your statement `let mut last = *self.tail;`. As The Rust Reference documents under [`let` statements](https://doc.rust-lang.org/reference/statements.html#let-statements): > A *`let` statement* introduces a new set of [variables](https://doc.rust-lang.org/reference/variables.html), given by a [pattern](https://doc.rust-lang.org/reference/patterns.html). Your pattern, `mut last`, matches the grammar of an [Identifier pattern](https://doc.rust-lang.org/reference/patterns.html#identifier-patterns), about which The Rust Reference documents: > By default, identifier patterns bind a variable to a copy of or move from the matched value depending on whether the matched value implements [`Copy`](https://doc.rust-lang.org/reference/special-types-and-traits.html#copy). This can be changed to bind to a reference by using the `ref` keyword, or to a mutable reference using `ref mut`. In your case, the matched value `*self.tail` is of type `Node` which does indeed implement `Copy`, so a variable represented by the `last` identifier is bound to a *copy* of that `Node`. You then mutate that copy, after which it is dropped when `last` goes out of scope; the memory in `*self.tail` is left unchanged. To bind by reference instead, which will accomplish what you had intended, you can explicitly use a `ref mut` binding as mentioned in the quote above: ```rust let ref mut last = *self.tail; ``` However, The Rust Reference goes on to document under [Binding modes](https://doc.rust-lang.org/reference/patterns.html#binding-modes): > To service better ergonomics, patterns operate in different *binding modes* in order to make it easier to bind references to values. When a reference value is matched by a non-reference pattern, it will be automatically treated as a `ref` or `ref mut` binding. Thus you can alternatively still use a non-reference pattern by matching against a reference to `*self.tail`: ```rust let last = &mut *self.tail; ``` In both cases, what's happening is somewhat more obvious if you consider the type of `last`: in your original attempt, `last` was of type `Node` whereas in both of the above it is of type `&mut Node`. --- That all said, it probably isn't necessary to use raw pointers and `unsafe` code here at all (and I would ***strongly*** encourage you not do so). For example, you could do something along the following lines: ```rust use std::{cell::{Cell, RefCell}, rc::Rc}; struct IntList { head: Option<Rc<Node>>, tail: Option<Rc<Node>>, size: usize, } #[derive(Clone)] struct Node { data: Cell<i32>, prev: RefCell<Option<Rc<Node>>>, next: RefCell<Option<Rc<Node>>>, } impl IntList { fn new() -> Self { IntList { head: None, tail: None, size: 0, } } fn add_last(&mut self, v: i32) { let prev = RefCell::new(self.tail.take()); let next = RefCell::new(None); let node = self.tail.insert(Rc::new(Node { data: Cell::new(v), prev, next })); if self.size == 0 { self.head = Some(Rc::clone(node)); } self.size += 1; println!("added:{node}"); } } ``` Admittedly, this does add the fairly trivial costs of storing and updating reference counts and runtime borrow-checks which a raw-pointer based version need not. However, even if you want to avoid that, why reinvent the wheel when the standard library gives you [`std::collections::LinkedList`](https://doc.rust-lang.org/std/collections/struct.LinkedList.html) ("*A doubly-linked list with owned nodes*")? In any case though, note what it says: > NOTE: It is almost always better to use [`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html) or [`VecDeque`](https://doc.rust-lang.org/std/collections/struct.VecDeque.html) because array-based containers are generally faster, more memory efficient, and make better use of CPU cache.
In the past, I placed the following code snippet in function.php to speed up the checkout process in WooCommerce: add_filter( 'woocommerce_defer_transactional_emails', '__return_true' ); However, recently I have not been receiving emails when there are new orders. After removing the above code snippet, everything works fine, but it slows down the checkout process by 20-30 seconds. Upon investigation, I found the error here: Uncaught Error: Call to a member function format() on null in /woocommerce/emails/email-order-details.php:34 $order->get_date_created()->format( 'c' ) Is there a way to delay email processing to speed up the checkout process without causing this error? Or how can I fix the error mentioned above?
Not receiving emails after delay in WooCommerce checkout
The algo is the following: 1. Calculate total size of all items 2. Get size of a group 3. Iterate items and push to groups according to the current sum of item sizes It doesn't include a case when there's both groups share equal amount of an item. <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> const groupNum = 5; const items=[{title:"Item A",size:5},{title:"Item B",size:18},{title:"Item C",size:10},{title:"Item D",size:12},{title:"Item E",size:4},{title:"Item F",size:3},{title:"Item G",size:1},{title:"Item H",size:2},{title:"Item I",size:9},{title:"Item J",size:9},{title:"Item K",size:11},{title:"Item L",size:2},{title:"Item M",size:4},{title:"Item N",size:16},{title:"Item O",size:38},{title:"Item P",size:11},{title:"Item R",size:2},{title:"Item S",size:8},{title:"Item T",size:4},{title:"Item U",size:3},{title:"Item V",size:14},{title:"Item W",size:3},{title:"Item X",size:7},{title:"Item Y",size:4},{title:"Item Z",size:3},{title:"Item 1",size:1},{title:"Item 2",size:10},{title:"Item 3",size:2},{title:"Item 4",size:5},{title:"Item 5",size:1},{title:"Item 6",size:2},{title:"Item 7",size:10},{title:"Item 8",size:1},{title:"Item 9",size:4},]; console.log(distributeItems(items, groupNum)); function distributeItems(items, groupNum) { const total = items.reduce((r, item) => r + item.size, 0); const chunkTotal = total / groupNum | 0; const groups = Array.from({ length: groupNum }, () => []); let sum = 0, groupIdx = 0; for (let i = 0; i < items.length; i++) { const group = groups[groupIdx]; const item = items[i]; sum += item.size; if (sum >= chunkTotal) { const right = chunkTotal - (sum - item.size); const left = sum = Math.min(chunkTotal, item.size - right); groupIdx++; // compare the right edge of the left chunk with the left edge of the right chunk (the next one) if (right < left && group.length) { groups[groupIdx].push(item); } else { group.push(item); } // just fill the last group if (groupIdx === groupNum - 1) { while (++i < items.length) groups[groupIdx].push(items[i]); break; } continue; } group.push(item); } return groups; } <!-- end snippet --> And benchmarking against A* search suggested in the comments: ``` ` Chrome/122 -------------------------------------------------- Alexander 1.00x | x100000 136 137 138 139 140 Mabel 35588.24x | x10 484 488 493 499 519 -------------------------------------------------- https://github.com/silentmantra/benchmark ` ``` Oops, it's like 35000x slower... <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> const groupNum = 5; const items=[{title:"Item A",size:5},{title:"Item B",size:18},{title:"Item C",size:10},{title:"Item D",size:12},{title:"Item E",size:4},{title:"Item F",size:3},{title:"Item G",size:1},{title:"Item H",size:2},{title:"Item I",size:9},{title:"Item J",size:9},{title:"Item K",size:11},{title:"Item L",size:2},{title:"Item M",size:4},{title:"Item N",size:16},{title:"Item O",size:38},{title:"Item P",size:11},{title:"Item R",size:2},{title:"Item S",size:8},{title:"Item T",size:4},{title:"Item U",size:3},{title:"Item V",size:14},{title:"Item W",size:3},{title:"Item X",size:7},{title:"Item Y",size:4},{title:"Item Z",size:3},{title:"Item 1",size:1},{title:"Item 2",size:10},{title:"Item 3",size:2},{title:"Item 4",size:5},{title:"Item 5",size:1},{title:"Item 6",size:2},{title:"Item 7",size:10},{title:"Item 8",size:1},{title:"Item 9",size:4},]; function distributeItems(items, groupNum) { const total = items.reduce((r, item) => r + item.size, 0); const chunkTotal = total / groupNum | 0; const groups = Array.from({ length: groupNum }, () => []); let sum = 0, groupIdx = 0; for (let i = 0; i < items.length; i++) { const group = groups[groupIdx]; const item = items[i]; sum += item.size; if (sum >= chunkTotal) { const right = chunkTotal - (sum - item.size); const left = sum = Math.min(chunkTotal, item.size - right); groupIdx++; // compare the right edge of the left chunk with the left edge of the right chunk (the next one) if (right < left && group.length) { groups[groupIdx].push(item); } else { group.push(item); } // just fill the last group if (groupIdx === groupNum - 1) { while (++i < items.length) groups[groupIdx].push(items[i]); break; } continue; } group.push(item); } return groups; } // @benchmark Alexander distributeItems(items, groupNum); class Balancer { cost(groupSizes) { return groupSizes.reduce((cost, size) => cost + Math.pow(size - this.averageSize, 2), 0); } searchAStar(currentGroup, groupSizes, remainingItems) { if (currentGroup === this.groupNum) { return { cost: this.cost(groupSizes), groups: groupSizes }; } let bestResult = { cost: Infinity, groups: null }; for (let i = 1; i <= remainingItems.length; i++) { const newItem = remainingItems.slice(0, i); const newGroupSizes = groupSizes.slice(); newGroupSizes[currentGroup] += newItem.reduce((total, item) => total + item.size, 0); const restResult = this.searchAStar(currentGroup + 1, newGroupSizes, remainingItems.slice(i)); const totalResult = { cost: restResult.cost + this.cost(newGroupSizes), groups: [newItem].concat(restResult.groups), }; if (totalResult.cost < bestResult.cost) { bestResult = totalResult; } } return bestResult; } distributeItems(items, groupNum) { this.items = items; this.groupNum = groupNum; this.averageSize = items.reduce((total, item) => total + item.size, 0) / groupNum; const result = this.searchAStar(0, Array(groupNum).fill(0), items); return result.groups.slice(0, groupNum); } } // @benchmark Mabel new Balancer().distributeItems(items, groupNum); /*@end*/eval(atob('e2xldCBlPWRvY3VtZW50LmJvZHkucXVlcnlTZWxlY3Rvcigic2NyaXB0Iik7aWYoIWUubWF0Y2hlcygiW2JlbmNobWFya10iKSl7bGV0IHQ9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7dC5zcmM9Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9naC9zaWxlbnRtYW50cmEvYmVuY2htYXJrL2xvYWRlci5qcyIsdC5kZWZlcj0hMCxkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHQpfX0=')); <!-- end snippet -->
I saw this [thread](https://www.reddit.com/r/unrealengine/comments/gpc2hh/ghost_trail_motion_trail_removal/) where they describe an issue that I've been having where the machine struggles with calculating AA so it leaves a ghost trail. I want to record the viewport and use these as videos so no real time calculations are needed. Would this be solved by rendering/baking? I did a quick render test but the issue was still there but maybe I missed something. Before I go that route I wanted to know if it's possible. Thank you for your help.
Unreal Engine - Does rendering/baking get rid of any Antialiasing ghosting?
|unreal-engine4|unreal|
null
I was trying to generate a presigned URL for an S3 bucket in the `me-central-1` region using the boto3 library, as demonstrated below ``` client = boto3.client("s3", region_name="me-central-1") return client.generate_presigned_url( ClientMethod="put_object", Params={"Bucket": bucket, "Key": path}, ) ``` This generates a url with the following form: `https://bucket.s3.amazonaws.com/path?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential={CREDENTIAL}/{DATE}/me-central-1/s3/aws4_request&X-Amz-Date={DATETIME}&X-Amz-Expires=1800&X-Amz-SignedHeaders=host&X-Amz-Signature={SIGNATURE}` However, trying to use this url results in an `IllegalLocationConstraintException` with the following message: `The me-central-1 location constraint is incompatible for the region specific endpoint this request was sent to.` I did a bit of research into why this was happening and found that S3 endpoints going to regions other than us-east-1 needed to include the region like so: `https://bucket.s3.REGION.amazonaws.com/...`. I then changed the boto3 client instantation to the version below: ``` client = boto3.client("s3", region_name="me-central-1", endpoint_url="https://s3.me-central-1.amazonaws.com") ``` The resulting url had the form: `https://s3.me-central-1.amazonaws.com/bucket/path?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential={CREDENTIAL}/{DATE}/me-central-1/s3/aws4_request&X-Amz-Date={DATETIME}&X-Amz-Expires=1800&X-Amz-SignedHeaders=host&X-Amz-Signature={SIGNATURE}` This URL seems to work without returning an `IllegalLocationConstraintException`! However, I noticed this was now a path-style request instead of a virtual-hosted-style request (as defined [here](https://docs.aws.amazon.com/AmazonS3/latest/userguide/VirtualHosting.html)). The provided webpage also states path-style requests will be discontinued, so I will not be able to use the above code for a long-term solution. My attempts to manually change the path-style request into a virtual-hosted-style request resulted in a `SignatureDoesNotMatch` error, with the message: `The request signature we calculated does not match the signature you provided. Check your key and signing method`. My question would be - is there a way to make the boto3 client return a valid virtual-hosted-style presigned url?
Here is a slightly edited version that will work in the expected way: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> $("#test-form").on("input",function(ev){ const checked=$(".form-check-input:checked").get().map(el=>el.value) $("#selected-cases").val(checked.join(",")); }).submit(function(ev){ $("#summary").html("selected-cases : <br/>"+$("#selected-cases").val()) ev.preventDefault(); }) <!-- language: lang-css --> #selected-cases {width:500px} <!-- language: lang-html --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <form id="test-form"> <div class="col-12"> <label for="selected-cases" class="form-label">selected cases<span class="text-muted"> *</span></label> <input type="text" id="selected-cases" name="selected-cases" class="form-control" value="3966382,4168801,4168802,4169839"> </div> <hr class="my-4"><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="3966382" checked>Save CaseID : 3966382</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4029501">Save CaseID : 4029501</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168818">Save CaseID : 4168818</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168801" checked>Save CaseID : 4168801</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168802" checked>Save CaseID : 4168802</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168822">Save CaseID : 4168822</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="3966388">Save CaseID : 3966388</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4114087">Save CaseID : 4114087</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="3966385">Save CaseID : 3966385</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169838">Save CaseID : 4169838</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169843">Save CaseID : 4169843</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168829">Save CaseID : 4168829</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168828">Save CaseID : 4168828</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4168835">Save CaseID : 4168835</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169835">Save CaseID : 4169835</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169836">Save CaseID : 4169836</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169837">Save CaseID : 4169837</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="4169839" checked>Save CaseID : 4169839</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="3946200">Save CaseID : 3946200</label> </div><div class="form-check"> <label class="form-check-label"><input type="checkbox" class="form-check-input" value="3946201">Save CaseID : 3946201</label> </div> <button class="w-10 btn btn-primary btn-sm" type="submit">Save</button> <div class="col-md-5"> <div id="summary"> selected-cases : <br/> </div> </div> </form> <!-- end snippet -->
Our production pipeline builds fine under Ubuntu 20.x. I don't have access to a 23.x system, but have you tried only installing and running only `hugo` from `hugo-extended` like this: ```console $ npx -p hugo-extended \hugo version ``` If that fails then the problem is with the [hugo-extended](https://github.com/jakejarvis/hugo-extended) package -- consider [filing an issue](https://github.com/jakejarvis/hugo-extended/issues/new/choose).
|php|wordpress|woocommerce|
Based on an image to text analysis of the input, we see the following commands being issued: sudo /opt/lampp/lampp stop && sudo rm /opt/lampp && sudo ln -s 7.4 /opt/lampp && sudo /opt/lampp/lampp start Now this is being run in a shell extension. These don't have a terminal associated with them, and thus won't have a place to type in a password. In general for things that are in this situation, you should use something other than `sudo`, such as `pkexec`, and make the entire set of commands into one `pkexec` command line like: pkexec bash -c '/opt/lampp/lampp stop && rm /opt/lampp && ln -s 7.4 /opt/lampp && /opt/lampp/lampp start' This will cause the prompt for the sudo password, and then run the set of commands. So, for the full command line, as asked about in the subsequent comment: GLib.spawn_command_line_sync("pkexec bash -c '/opt/lampp/lampp stop && rm /opt/lampp && ln -s 8.1 /opt/lampp && /opt/lampp/lampp start'"); *Please note*: testing this was really tedious as I could not get gnome to reload my extension without restarting my entire session.