instruction
stringlengths
0
30k
One of the 4 possibilities here: - No changes made to models that require migrations; - Models not registered. You need to register new models in the `admin.py` file; - Migrations already applied. If you've applied some migrations earlier, but then made some changed that don't require migrations on their own - you are back to first case of this list; - You're trying to apply migrations to the wrong app altogether.
Recast removes comments
null
I am trying formula `if` with multi conditions in Excel. but the result `#VALUE!`is there is something wrong with my formula please guide me Thanks | DATE | IN/OUT |TIME |DEF IN |DEF OUT |RESULT | | -------- | -------- |-------- |-------- |-------- |--------| | 13-03-24 | IN |7:35:41 |8:00:00 |15:30:00 | | | 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 | | | 13-03-24 | IN |8:35:41 |8:00:00 |15:30:00 | | | 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 | | | 13-03-24 | OUT |13:00:10 |8:00:00 |15:30:00 | | | | IN | | | | | ``` =IF(A2="",""),IF(AND(B2="OUT",E2<=C2),"NORMAL","LATE"),IF(AND(B2="IN",D2<=C2),"NORMAL","LATE") ``` Result from above formula | DATE | IN/OUT |TIME |DEF IN |DEF OUT |RESULT | | -------- | -------- |-------- |-------- |-------- |--------| | 13-03-24 | IN |7:35:41 |8:00:00 |15:30:00 |#VALUE! | | 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 |#VALUE! | | 13-03-24 | IN |8:35:41 |8:00:00 |15:30:00 |#VALUE! | | 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 |#VALUE! | | 13-03-24 | OUT |13:00:10 |8:00:00 |15:30:00 |#VALUE! | | | IN | | | |#VALUE! | [![enter image description here][1]][1] Desired Result | DATE | IN/OUT |TIME |DEF IN |DEF OUT |RESULT | | -------- | -------- |-------- |-------- |-------- |--------| | 13-03-24 | IN |7:35:41 |8:00:00 |15:30:00 |NORMAL | | 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 |NORMAL | | 13-03-24 | IN |8:35:41 |8:00:00 |15:30:00 |LATE | | 13-03-24 | OUT |15:42:10 |8:00:00 |15:30:00 |NORMAL | | 13-03-24 | OUT |13:00:10 |8:00:00 |15:30:00 |LATE | | | IN | | | | | [1]: https://i.stack.imgur.com/qCgFE.png
Getting the below error when connecting to Mongo Atlas. Though the warning is there connection is successful and able to access the database. I need to know how to get rid of this warning message CryptographyDeprecationWarning: This version of cryptography contains a temporary pyOpenSSL fallback path. Upgrade pyOpenSSL now.
CryptographyDeprecationWarning when trying to connect to Mongo Atlas
|python-3.x|mongodb|mongoatlas|
You're seeing the output twice because the python interpreter opens and runs main.py twice; - First when running `python main.py` - A second time when example.py imports main.py via `from main import mods` Each time main.py is interpreted , `printHello()` is then called. To prevent the second time, you can replace the last 4 lines in main.py with; ```python if __name__ == "__main__": exec(open("Welder/mods/example.py").read()) mods = list(set(mods)) # Removes weirdly added duplicates print(mods) printHello() ```
firstly I'm new to this, I wanna know which file is my data stored on 'we internet' app I'm curious to understand about which p language this app written by? I used apktool but it failed to load additional packages. what “classes” stand for? I know I'm asking more questions, sorry for this, all I need is some understanding for better. Thanks...
I have Ionic 7, Angular, Standalone app. I am currently trying to implement linking anonymous account to registered/loggedin account. First scenario is a user who doesn't have any registered account below. This works fine and I can see anonymous account merged with newly generated account. const anonymousUser: User = this.auth.currentUser! const credential = EmailAuthProvider.credential(email,password) return linkWithCredential(anonymousUser, credential) Problem is when this user logout and they try to log back in. When user navigates to the app after logout, we still generate anonymous credential. When we try to use above to link credential with existing user, I get following error: FirebaseError: Firebase: Error (auth/email-already-in-use) How can I handle the login situation where user is trying to log back in and we want to link this to existing anonymous account? Is this even possible?
Firebase link existing user to anonymous account?
|angular|ionic-framework|firebase-authentication|angular-standalone-components|
> I need my health.py to run in background As [David](https://stackoverflow.com/users/10008173/david-maze) [commented](https://stackoverflow.com/questions/78203542/how-to-run-a-background-process-inside-a-child-docker-image-in-docker-container#comment137873369_78203542), you need to make sure the [`CMD`](https://docs.docker.com/reference/dockerfile/#cmd) or [`ENTRYPOINT`](https://docs.docker.com/reference/dockerfile/#entrypoint) effectively manages *both* the Airflow scheduler and the `health.py` script without prematurely exiting. That means the `entrypoint.sh` script must initiate both the Airflow scheduler (or the primary process started by the parent image's `ENTRYPOINT`) and the `health.py` script as background processes, and then waits indefinitely to keep the container running. ```bash #!/bin/bash # Start the health monitoring script in the background ./scheduler_health.sh & # Start the main process in the background as well, if necessary # Example: /start-airflow.sh & # The original parent image's ENTRYPOINT is expected to start the airflow scheduler # and potentially block. If it is just an initialization script and does not block, # then you might need to start the scheduler manually here, similar to the commented-out line above. exec /usr/bin/dumb-init -- /entrypoint "$@" ``` The `scheduler_health.sh` script should directly run `health.py` as intended. When running your container, using [`docker run -d ...`](https://docs.docker.com/reference/cli/docker/container/run/#detach) ("detached mode") is recommended to make sure the container runs in the background. Since `health.py` runs as a background process, make sure you have adequate logging in place to monitor its output and health status: redirect its output to Docker's logging system (stdout/stderr) or to a file that can be accessed or tailed. ---- [Avatazjoe](https://stackoverflow.com/users/2008399/avatazjoe) suggests in [the comments](https://stackoverflow.com/questions/78203542/how-to-run-a-background-process-inside-a-child-docker-image-in-docker-container/78218894?noredirect=1#comment137957724_78218894): > ...or you can try another approach ussing python subprocess modelule. True, that is a good way to manage background processes within your Docker container, especially if you want to initiate and control these processes directly from Python. That should work for your scenario where you want `health.py` to run in the background alongside the main Airflow scheduler process. You can create a wrapper Python script (`start_processes.py`) that starts both the Airflow scheduler (if needed) and the `health.py` script as subprocesses. That script can use [Python's `subprocess` module](https://docs.python.org/3/library/subprocess.html) to start `health.py` as a background process and then proceeds to start or make sure the start of the Airflow scheduler process. ```python import subprocess import os def run_in_background(command): """Run the given command as a background process.""" return subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) if __name__ == "__main__": # Start health.py as a background process run_in_background("python3 /health.py") # Example: Start another process here if necessary, e.g., a custom Airflow start script # run_in_background("bash /start-airflow.sh") # The last command should block to keep the script running # If the Airflow scheduler is started by the parent image's ENTRYPOINT, you might not need to start it manually. # If you do, make sure the last process started here is blocking, or use a wait loop to keep the script alive. os.system("tail -f /dev/null") ``` Adjust your Dockerfile to include this new wrapper script and set it as the command or entry point to execute when the container starts. ```Dockerfile FROM parent_img:latest USER root # Copy necessary scripts and files COPY scripts/child_airflow.sh /child_airflow.sh COPY utils/health.py /health.py COPY start_processes.py /start_processes.py # Install any dependencies and run setup scripts RUN bash /child_airflow.sh && rm /child_airflow.sh # Set the Python wrapper as the entrypoint or CMD CMD ["python3", "/start_processes.py"] ``` That would have the benefit of keeping all process management within a single Python script, making it potentially easier to manage, especially if you are already working within a Python-centric environment like Airflow. And this approach can be more flexible if your processes need to communicate with each other or if their lifecycles are closely intertwined. Using the `subprocess` module in this way allows for more sophisticated process management strategies, such as monitoring the output of background processes, restarting failed processes, or gracefully shutting down processes when the container is stopped.
[This video][1] assisted me in finding a solution. Both the server and the client required modifications. This is the full implementation of the server: const http = require('http'); const express = require('express'); const { Server } = require('socket.io'); const app = express(); // Create an HTTP server const server = http.createServer(); app.use(express.static("public")); // Create a new instance of Socket.io by passing the HTTP server const io = new Server(server); // Listen for incoming socket connections io.on('connection', (socket) => { let data = socket.handshake.query.payload; console.log(`A user connected. payload=[${data}]`); // Listen for messages from the client socket.on('message', (message) => { console.log('Message received:', message); // Broadcast the message to all connected clients io.emit('message', message); }); // Listen for disconnection socket.on('disconnect', () => { console.log('A user disconnected'); }); }); // Start the server and listen on port 3000 const PORT = process.env.PORT || 3000; server.listen(PORT, () => { console.log(`Server listening on http://192.168.0.191 port ${PORT}`); }); On the Android app, I imported a different library. As of the time of this post, this is the latest version of the library: implementation("io.socket:socket.io-client:2.1.0") Finally, this is the full implementation, applicable to the socket: @Composable private fun createSocketIO() { val coroutineScope = rememberCoroutineScope() coroutineScope.launch(Dispatchers.IO) { try { val sc = SSLContext.getInstance("TLS") sc.init(null, arrayOf<TrustManager>(object : X509TrustManager { override fun checkClientTrusted( chain: Array<X509Certificate?>?, authType: String? ) { } override fun checkServerTrusted( chain: Array<X509Certificate?>?, authType: String? ) { } override fun getAcceptedIssuers(): Array<X509Certificate?> { return arrayOfNulls(0) } }), SecureRandom()) val builder = OkHttpClient.Builder() .hostnameVerifier { hostname: String?, session: SSLSession? -> true } .sslSocketFactory(sc.socketFactory, object : X509TrustManager { override fun checkClientTrusted( chain: Array<X509Certificate?>?, authType: String? ) { } override fun checkServerTrusted( chain: Array<X509Certificate?>?, authType: String? ) { } override fun getAcceptedIssuers(): Array<X509Certificate?> { return arrayOfNulls<X509Certificate>(0) } }) val okHttpClient = builder.build() IO.setDefaultOkHttpCallFactory(okHttpClient) IO.setDefaultOkHttpWebSocketFactory(okHttpClient) val opts: IO.Options = IO.Options() opts.secure = true opts.callFactory = okHttpClient opts.webSocketFactory = okHttpClient IO.socket(URI.create("http://192.168.0.10:3000?payload=348ritwnekrdgf43trkfn"), opts)?.let { socket -> this@MainActivity.socket = socket socket.on("connecting") { println("io.socket: Connecting from server") } socket.on(Socket.EVENT_CONNECT_ERROR) { println("io.socket: Connection error") it.map { println(it) } } socket.on("error") { println("io.socket: Event Error") } socket.on(Socket.EVENT_CONNECT) { println("io.socket: Connected to server") socket.emit("message", "Hi! My name is Android!") } socket.on("message") { args -> val message = args[0].toString() println("io.socket: Received message from server: $message") } socket.on(Socket.EVENT_DISCONNECT) { println("io.socket: Disconnected from server") } socket.connect() } } catch (e: URISyntaxException) { println("io.socket: Error: ${e.message}") return@launch } } } [1]: https://www.youtube.com/watch?v=N3NZ9hno66A
the problem is the display of LinearGradientBrush on the button, in Android it is correct, in iOS it is not ``` <Button Text="Войти" > <Button.Background> <LinearGradientBrush EndPoint="1,0"> <GradientStop Color="#DA8BFF" Offset="0.1" /> <GradientStop Color="#839BFF" Offset="1" /> </LinearGradientBrush> </Button.Background> </Button> ``` Photo:[Android](https://i.stack.imgur.com/VLSnj.png), [IOS](https://i.stack.imgur.com/StM8s.jpg) I tried to set sizes, add them to different containers
``` m = [[[math.inf] * 10] for i in range(10)] for i in range(len(m)): for j in range(len(m)): if(i == j): m[i][i] = 0 ``` [enter image description here](https://i.stack.imgur.com/YypkA.png) I try to insert zero And I used the debugger to watch the process go. Instead of changing it to [[[0,inf,inf,inf,inf,inf,inf,inf,inf,inf],[......],[.......]]] It changes it to [[0], [[inf,inf,inf,inf....],[inf,inf,....]] Which then causes an index out of bound error because it just reduced a 10x10 matrix to the top row being zero, as oppose to inf,inf,inf,inf,inf,inf,inf,inf,inf,inf Where my goal is to set a 10x10 matrix's diagonal to all zeros. I tried to use m = [[[math.inf] * 10] for i in range(10)]
Setting Diagnonal of a Matrix to Zero in Python
|matrix|diagonal|
null
Fan.cs ``` using System; namespace Fans { class Fan { private int speed; private double radius; private string color; //default constructor public Fan() { this.speed = 1; this.radius = 1.53; this.color = "green"; } //convenience constructor public Fan(double newRadius) { this.radius = newRadius; } public override string ToString() { return "A " + radius + " inch " + color " fan at a speed of " + speed; } public int speed { get { return speed; } set { speed = newSpeed; } } public double radius { get { return radius; } set { radius = newRadius; } } public string color { get { return color ; } set { color = newColor; } } } } ``` Program.cs ``` using System; namespace Fans { class Program { static void Main(string[] args) { Fan fan1 = new Fan(); fan1.speed = 3; fan1.radius = 10.26; fan1.color = "yellow"; Console.WriteLine(fan1); } } } ``` When I attempt to compile Program.cs, I am given two of the same error: - Program.cs(7,9): error CS0246: The type or namespace name 'Fan' could not be found (are you missing a using directive or an assembly reference?) - Program.cs(7,24): error CS0246: The type or namespace name 'Fan' could not be found (are you missing a using directive or an assembly reference?) Both files are in the same directory. Not sure what else is wrong.
#include Header files in C with definition too
|c++|c|linker|header|
null
Lets assume we have a map as below, map<string, map<string, int>> my_map; i want to use insert method in one single line like below my_map.insert("TEST", make_pair<string,int>("ONE",2)); and its not working. i would like to use inner maps for the syntax showed below cout << my_map["TEST"]["A"] << endl; what is the main problem here? should the second inner map be a pair instead?
how to insert inner map in one line insert method
|c++|
I'm new to NetLogo and I'm having some problems for which I couldn't find an answer in the internet. I have made colonies within which males and females live. Males have a constant size of 10 and females have sizes set by a random-normal distribution. I would like only females with size >= 10 to mate. However, when I run the model, all females (even those below size 10) are mating. Would much appreciate if the error in the code can be pointed-out. Below is my code. In the interest of your time, I'm pasting only the relevant parts. Also, please note that the model building is still in progress... colonies-own [Avg-primary-sex-ratios Adult-sex-ratios colony-size] males-own [Sperm-sex-ratios body-size home-colony num-of-children adult? genotype] females-own [primary-sex-ratios mating-status? body-size home-colony num-of-exes num-of-children adult?] to make-females ask colonies [hatch-females round ((initial-colony-size * 90) / 100) [ set shape "spider" set color yellow set home-colony myself set size 0.8] ] ask females [ set body-size mean (list 6 (random-normal 10 2) 14) set num-of-exes 0 set num-of-children 0 set adult? True set mating-status? False ] end to-report initial-colony-size report mean (list 20 (random-normal 60 5) 120) end to go make-male-adults make-female-adults make-sperm mate-with-an-adult-female tick end to make-male-adults ask males [ if body-size >= 10 [set adult? True] ] end to make-female-adults ask females [ if body-size >= 10 [set adult? True] ] end to make-sperm ; males make a range of sperm-sex ratios ranging from 50:50 to 100:0 female:male sperm ask males [if adult? [set sperm-sex-ratios mean (list (random-float 101)) ] if sperm-sex-ratios <= 50 [set color black] if sperm-sex-ratios > 50 and sperm-sex-ratios <= 70 [set color violet] if sperm-sex-ratios > 70 [set color orange] ] end to mate-with-an-adult-female ask males [ if adult? [ ask females [ if adult? and num-of-exes <= 4 [ set mating-status? True set num-of-exes num-of-exes + 1 set color white] ] ] ] end I would like only those female turtles which pass a certain condition to mate.However, all female turtles are mating ``` ```
All turtles are mating in NetLogo even after setting a condition
|netlogo|agent-based-modeling|
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(); ``` 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?
How to listen to "Backend" value change in tauri-leptos app?
|rust|rust-tokio|tauri|leptos|
make suitable changes as needed. ``` import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QTreeView, QFileSystemModel class FileTreeView(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("File Treeview") self.setGeometry(100, 100, 800, 600) # Create a QTreeView widget self.tree_view = QTreeView(self) self.tree_view.setGeometry(50, 50, 700, 500) # Create a QFileSystemModel instance self.model = QFileSystemModel() self.model.setRootPath('') self.tree_view.setModel(self.model) # Set the root path for the model folder_path = "/path/to/your/folder" # Change this to your folder path self.tree_view.setRootIndex(self.model.index(folder_path)) # Expand the treeview to show all contents self.tree_view.expandAll() if __name__ == '__main__': app = QApplication(sys.argv) file_treeview = FileTreeView() file_treeview.show() sys.exit(app.exec_()) ```
We have an online store and I would like to modify the label below the shipping method (hook: woocommerce_cart_shipping_method_full_label) based on the stock status of the products in the cart. Basically, if there is 1 product whose stock status is "to order", then the label for shipping method 1 = "48/72h" and the label for shipping method 2 = "48/72h". If there is 1 product that is "limited stock", then shipping method label 1 = "24/48h" and shipping method label 2 = "48/72h". Otherwise (that is, all products are "in stock") the label = ""Shipping by 4pm". My closest attempt was like this: (but it checks for each product, that is, it adds a label as many times as the number of products in the cart - which is wrong) add_filter( 'woocommerce_cart_item_name', 'custom_text_based_status_name', 10, 3 ); function custom_text_based_status_name( $item_name, $cart_item, $cart_item_key ) { if( ! ( is_checkout() ) ) return $item_name; $shipping_class_1 = 'onbackorder'; $shipping_class = $cart_item['data']->get_stock_status(); if( $shipping_class === $shipping_class_1 ) { add_filter( 'woocommerce_cart_shipping_method_full_label', 'custom_shipping_methods_label', 10, 2 ); function custom_shipping_methods_label( $label, $method ) { switch ( $method->id ) { case 'fish_n_ships:62': //Portugal Continental - Transportadora $txt = __('Expedição estimada: 24 a 48h úteis''); // <= Additional text break; case 'fish_n_ships:63': //Portugal Continental - Gratuito $txt = __('Expedição estimada: 72 a 96h úteis'); // <= Additional text break; default: //nos restantes casos $txt = __('Confirmaremos assim que possível'); // <= Additional text } return $label . '<br /><small style="color:#777777">' . $txt . '</small>'; } } return $item_name; }` I also tried but show critical error: add_filter( 'woocommerce_cart_shipping_method_full_label', 'custom_shipping_method_label', 10, 3 ); function custom_shipping_method_label( $label, $method, $cart_item ) { switch ([$method->id, $cart_item['data']->get_stock_status]) { case ['fish_n_ships:62', 'instock']: //Portugal Continental - Transportadora $txt = __('Expedição estimada: 24 a 48h úteis'); // <= Additional text break; case ['fish_n_ships:62', 'stock_limitado']: //Portugal Continental - Transportadora $txt = __('Expedição estimada: 24 a 48h úteis'); // <= Additional text break; default: //nos restantes casos $txt = __('Confirmaremos assim que possível'); // <= Additional text } return $label . '<br /><small style="color:#777777">' . $txt . '</small>'; }
I can't add text to VS Code when committing to GIT
|git|visual-studio-code|
I'm working on a tool for animating 3D objects, and I've run into an issue that I'm not sure how to solve: There is a rotation gizmo implemented, which works fine. However since it's an animation tool, I need to end up with euler angles after a rotation is performed. And the issue is, since I'm converting to quaternion to perform the rotation along an axis, and then back to euler. At certain angles I end up with flipped signs. (goes up to 180 degrees, and then switches to -180 degrees, and vice versa) While the rotation looks fine when rendered, the sign flipping causes issues when trying to do the animation interpolation, the object will spin in the opposite direction etc. The code looks something like this: ``` local rotation = object:GetQuaternionRotation(); rotation:RotateAroundAxis(direction, mouseDiff); local newRotation = rotation:ToEuler(); ``` - the direction is a direction vector (x,y,z), when rotating in world space Z direction would be (0, 0, 1) and when rotating in local space the vector is whatever the object's up vector is at that moment in time. - the mouseDiff is just +- increment based on how much the mouse moved - and finally RotateAroundAxis looks like this: ``` function Quaternion:RotateAroundAxis(axis, angle) -- Calculate half angle local halfAngle = angle * 0.5 -- Calculate sine and cosine of half angle local sinHalfAngle = math.sin(halfAngle) local cosHalfAngle = math.cos(halfAngle) -- Normalize the axis axis:Normalize() local rotationQuat = Quaternion:New( axis.x * sinHalfAngle, axis.y * sinHalfAngle, axis.z * sinHalfAngle, cosHalfAngle ) self:Multiply(rotationQuat) end ``` [A preview of what's going on](https://i.stack.imgur.com/5gKCE.gif) I tried just adding the euler values, but that obviously won't work when the direction vector is not axis aligned.
For the approach you want in your app you need to use protected routes you can learn more in this blog : [: https://blog.logrocket.com/authentication-react-router-v6/ Create normal routes import { createBrowserRouter } from 'react-router-dom'; //import all the page components here export const router = createBrowserRouter([ { path: '/', element: <Layout />, children: [ { index: true, element: <Login />, }, { path: 'signup', element: <SignUp />, }, { path: 'dashboard', element: ( <ProtectedRoute allowedRoles={roles.vendor}> <VendorDashboard /> </ProtectedRoute> ), }, { path: 'items', element:( <ProtectedRoute allowedRoles={roles.vendor}> <Items /> </ProtectedRoute> ), }, { path: 'buyer-dashboard', element:( <ProtectedRoute allowedRoles={roles.buyer}> <Dashboard /> </ProtectedRoute> ), }, { path: 'other', element:( <ProtectedRoute allowedRoles={roles.buyer}> <Other /> </ProtectedRoute> ), }, ],},]); const roles = { buyer: ['buyer-dashboard', 'other'], vendor: ['dashboard', 'items'], }; Make a function to retrieve to roles of the user on login const getUserRole = () => { return 'superAdmin'; }; now make a component for protected route import { Navigate } from 'react-router-dom'; const ProtectedRoute = ({ children, allowedRoles }) => { const userRole = getUserRole(); const isAuthenticated = true; if (!isAuthenticated) { return <Navigate to="/login" replace />; } if (!allowedRoles.includes(userRole)) { return <Navigate to="/unauthorized" replace />; } return children // <Outlet />; tyou can use Outlet here to }; export default ProtectedRoute;
Why is this namespace unable to be found?
|c#|class|namespaces|
null
I'm kinda new to python and it's the first time managing environments with Anaconda. There's some discrepancy that I can't figure out between my conda environment and my visual studio code, I'll explain: I created a conda environment with python 3.8.11, recognised by vscode: [![vscode config][1]][1] But if I open a terminal inside vscode, the environment selected is another one: ``` # conda environments: # base * /opt/homebrew/anaconda3 quant /opt/homebrew/anaconda3/envs/quant ``` And this to me is already strange, I would expect the terminal environment to match the conda environment that I'm using for my project but okay. So I switch to the "quant" environment: ``` ❯ conda activate quant ❯ conda info --envs # conda environments: # base /opt/homebrew/anaconda3 quant * /opt/homebrew/anaconda3/envs/quant ``` but if I run `python --version` I get: ``` ❯ python --version Python 3.11.8 ``` but I created the quant environment with python 3.8.11...why is it different? This trickle down to why I can't install new packages (I think), because if I try to install something, like "schedule" ``` ❯ pip install schedule Requirement already satisfied: schedule in /opt/homebrew/lib/python3.11/site-packages (1.2.1) ``` everything runs correctly, but then if I try to import the package I get: `Import "schedule" could not be resolved` What am I missing? [1]: https://i.stack.imgur.com/P0dXj.png
Can't install packages in python conda environment
|python|anaconda|
# aws_cognito_user_pool.user_pool will be updated in-place ~ resource "aws_cognito_user_pool" "user_pool" { id = "us-east-1_xxxyyy" name = "my-user-pool" tags = { "Name" = "my-user-pool" } # (10 unchanged attributes hidden) ~ password_policy { - temporary_password_validity_days = 7 -> null # (5 unchanged attributes hidden) } # (4 unchanged blocks hidden) } Whenever I run `terraform plan`, my user pool *always* appears as a change. There are no changes to this resource at all. Is this some bug? How can I prevent this?
Why does terraform aws_cognito_user_pool always show as "updated in-place" on every single terraform plan?
|terraform|amazon-cognito|aws-userpools|
guard let url = URL(string:"https://blaaaajo.de/getHiddenUsers.php") else { return } let postString = "blockedUsers=245,1150" var request = URLRequest(url: url) request.httpMethod = "POST" request.httpBody = postString.data(using: String.Encoding.utf8); do{ let (responseString, _) = try await URLSession.shared.data(for: request) if let decodedResponse = try? JSONDecoder().decode([HiddenUsersModel].self, from: responseString){ gettingBlockedUsers = false blockedUsers = decodedResponse } }catch{ print("data not valid") } the HiddenUsersModel: struct HiddenUsersModel: Codable { var userid: Int var nickname: String } I'm always getting `data not valid` The url and the POST key `blockedUsers` with the value `245,1150` is 100% correct, I'm also using this API for the web and Android app. The code on server side doesn't get executed though, not even at the beginning of the PHP script. So no JSON response is generated. Why could that be?
null
Basically your observations are correct. Here's my timings and notes Create 2 arrays, one much larger, and a list: In [254]: a = np.random.randint(0,1000,1000); b = a.tolist() In [255]: aa = np.random.randint(0,1000,100000) The method is faster, by about 7µs in both cases - that's basially the overhead of the function delegating the job to the method: In [256]: timeit a.min() 7.15 µs ± 16 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) In [257]: timeit np.min(a) 14.7 µs ± 204 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each) In [258]: timeit aa.min() 49.4 µs ± 174 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) In [259]: timeit np.min(aa) 57.4 µs ± 141 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) The extra time for calling `np.min` on the list is the time required to convert the list to an array: In [260]: timeit np.min(b) 142 µs ± 446 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) In [261]: timeit np.array(b) 120 µs ± 161 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) The native Python function does reasonably well with a list: In [262]: timeit min(b) 40.7 µs ± 92 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) It is slower when applied to the array. The extra time is basically the time it takes to iterate through array, treating it as a list: In [263]: timeit min(a) 127 µs ± 675 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) In [264]: timeit min(list(a)) 146 µs ± 1.43 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each) `tolist` is a faster way to create a list from an array: In [265]: timeit min(a.tolist()) 77.1 µs ± 82 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) In general, when there's a numpy function with the same name as a method, it is doing two things: - converting the argument(s) to array, if necessary - delegating the actual calculation to the method. Converting a list to an array takes time. Whether that extra time is worth it depends on the following task. Conversely, treating an array as a list, is usually slower. In [270]: timeit [i for i in b] 50 µs ± 203 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) In [271]: timeit [i for i in a] 126 µs ± 278 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) The actual item created in an iteration is different: In [275]: type(b[0]), type(a[0]) Out[275]: (int, numpy.int32) `b[0]` is the same object that is in `b`. That is, `b` contains references to `int` objects. `a[0]` is a new `np.int32` object each time it's called, with a new `id`. That 'unboxing' takes time. In sum, if you already have an array, it's fastest to use the method. But if for clarity or generality, using the function instead is no big deal, especially if the array is large. Treating an array as a list is usually slower. If you are starting with list, using the native python function is usually the best - if available.
Found the answer... For a Flutter web app, the horizontal scrolling is activated by holding down the shift key whilst using the mouse wheel.
# Option #1 We can do that with a [lifecycle precondition][1] in a null_resource A couple of things before we dive into the code: - Your code has two `sc1_default` variables I'm assuming that the second one was a typo and what you meant there is `sc2_default` - For additional validation use `type` in the variables, it's a good practice, makes the code more readable and if someone accidentally passes the wrong type the code fails gracefully. see sample code below ``` lang-hcl variable "sc1_default" { type = bool default = false } variable "sc2_default" { type = bool default = false } variable "sc3_default" { type = bool default = true } variable "sc4_default" { type = bool default = true } resource "null_resource" "validation" { lifecycle { precondition { condition = ( (var.sc1_default ? 1 : 0) + (var.sc2_default ? 1 : 0) + (var.sc3_default ? 1 : 0) + (var.sc4_default ? 1 : 0) ) < 2 error_message = "Only one sc can be true" } } } ``` You can see I set the `sc3_default` and `sc4_default` both to true just to trigger the error ... The condition is the core of this validation we are just adding all the true with the help of shorthand if syntax `(var.sc_default ? 1 : 0)` and the total should be less than two, I'm assuming that all false is OK, but if not you can change that logic to check that is precisely one. A terraform plan on that code will error out with the following message: ``` lang-txt Planning failed. Terraform encountered an error while generating this plan. ╷ │ Error: Resource precondition failed │ │ on main.tf line 24, in resource "null_resource" "validation": │ 24: condition = ( │ 25: (var.sc1_default ? 1 : 0) + │ 26: (var.sc2_default ? 1 : 0) + │ 27: (var.sc3_default ? 1 : 0) + │ 28: (var.sc4_default ? 1 : 0) │ 29: ) < 2 │ ├──────────────── │ │ var.sc1_default is false │ │ var.sc2_default is false │ │ var.sc3_default is true │ │ var.sc4_default is true │ │ Only one sc can be true ``` ____ # Option #2 If you can change the input variables we could reduce it to just one with a `list(bool)` the code will be smaller and the validation would be right on the variable ``` lang-hcl variable "sc_default" { type = list(bool) description = "list of sc default values" default = [false, false, false, false] validation { condition = length(var.sc_default) == 4 error_message = "Four defaults expected" } validation { condition = sum([for x in var.sc_default : x ? 1 : 0]) < 2 error_message = "Only one sc can be true" } } ``` [1]: https://developer.hashicorp.com/terraform/language/meta-arguments/lifecycle#custom-condition-checks
Encountering `Fatal error: Uncaught mysqli_sql_exception: Table 'kopsis.setting_email' doesn't exist in /www/wwwroot/kopsis/config.php:66 Stack trace: #0 /www/wwwroot/kopsis/config.php(66): mysqli->query() #1 /www/wwwroot/kopsis/index.php(2): include('...') #2 {main} thrown in /www/wwwroot/kopsis/config.php on line 66` This error occurs when running my code on a VPS with AAPanel. It works fine on cPanel hosting with PHP 7.4. How can I resolve this issue on the VPS with AAPanel and php 7.4 also?" I've already switched to PHP 7.3, 8.1, and still encountering the same issue, even triggering new errors This is Config.PHP code <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> oh sorry, this is my config.php code ' <?php // Menonaktifkan tampilan pesan kesalahan error_reporting(E_ALL); // Atur zona waktu ke "Asia/Jakarta" (Waktu Indonesia Barat) date_default_timezone_set('Asia/Jakarta'); // Tampilkan tanggal dan waktu dalam format yang diinginkan $currentDateTime = date('d M Y H:i:s'); // Memulai sesi session_start(); // Mendefinisikan path fisik ke file connection.php $path_to_connection = $_SERVER['DOCUMENT_ROOT']. "/connection.php"; // Melakukan include file menggunakan path fisik include $path_to_connection; // CEK LOGIN USER if (isset($_COOKIE['login'])) { $key_login = $_COOKIE['login']; $ciphering = "AES-128-CTR"; $iv_length = openssl_cipher_iv_length($ciphering); $options = 0; $decryption_iv = '1234567891011121'; $decryption_key = "ecommerce"; $decryption = openssl_decrypt($key_login, $ciphering, $decryption_key, $options, $decryption_iv); $iduser_key_login = explode("hcCTZvFLD7XIchiaMqEka0TLzGgdpsXB", $decryption); $id_user_login = $iduser_key_login[0]; $select_profile = $server - > prepare("SELECT * FROM `akun` WHERE `id`=?"); $select_profile - > bind_param("i", $id_user_login); $select_profile - > execute(); $result = $select_profile - > get_result(); $profile = $result - > fetch_assoc(); // Jika profil tidak ditemukan, redirect ke halaman logout if (!$profile) { header('Location: '.$url. '/system/logout.php'); exit(); // Pastikan untuk menghentikan eksekusi setelah melakukan redirect } // Simpan informasi pemilik toko yang sedang login $iduser = $profile['id']; // COUNT CART $count_cart_header = $server - > query("SELECT * FROM `keranjang` WHERE `id_user`='$iduser' "); $cek_cart_header = mysqli_num_rows($count_cart_header); // COUNT NOTIFICATION $count_notif_header = $server - > query("SELECT * FROM `notification` WHERE `id_user`='$iduser' AND `status_notif`='' "); $cek_notif_header = mysqli_num_rows($count_notif_header); // COUNT FAVORIT $count_favorit_header = $server - > query("SELECT * FROM `favorit` WHERE `user_id`='$iduser' "); $cek_favorit_header = mysqli_num_rows($count_favorit_header); // COUNT CHAT $count_chat_header = $server - > query("SELECT * FROM `chat` WHERE `penerima_user_id`='$iduser' AND `status`='' "); $cek_chat_header = mysqli_num_rows($count_chat_header); // COUNT PESANAN $count_pesanan_header = $server - > query("SELECT * FROM `invoice` WHERE `id_user`='$iduser' AND `tipe_progress`='' "); $cek_pesanan_header = mysqli_num_rows($count_pesanan_header); } // NOTIFIKASI JUMLAH PESAN BARU $count_unread_chat = $server - > query("SELECT * FROM `chat` WHERE `penerima_user_id`='1' AND `status`=''"); $cek_unread_chat = mysqli_num_rows($count_unread_chat); // NOTIFIKASI JUMLAH PERMINTAAN PENARIKAN $count_pending_rows = $server - > query("SELECT COUNT(*) as total FROM `riwayat_penarikan` WHERE `status`=0"); $row = $count_pending_rows - > fetch_assoc(); $total_pending_rows = $row['total']; // ADMIN MAIL $setting_email_query = $server - > query("SELECT * FROM `setting_email` WHERE `id`='1'"); $data_setting_email = mysqli_fetch_assoc($setting_email_query); $setfrom_smtp = $data_setting_email ? $data_setting_email['setfrom_smtp'] : null; // HEADER SETTING $setting_header = $server - > query("SELECT * FROM `setting_header` WHERE `id_hs`='1'"); $data_setting_header = mysqli_fetch_assoc($setting_header); $logo = $data_setting_header['logo']; $favicon = $data_setting_header['favicon']; $title_name = $data_setting_header['title_name']; $slogan = $data_setting_header['slogan']; $meta_description = $data_setting_header['meta_description']; $meta_keyword = $data_setting_header['meta_keyword']; $google_verification = $data_setting_header['google_verification']; $bing_verification = $data_setting_header['bing_verification']; $ahrefs_verification = $data_setting_header['ahrefs_verification']; $yandex_verification = $data_setting_header['yandex_verification']; $norton_verification = $data_setting_header['norton_verification']; // API KEY SETTING $setting_apikey = $server - > query("SELECT * FROM `setting_apikey` WHERE `id_apikey`='1'"); $data_setting_apikey = mysqli_fetch_assoc($setting_apikey); $google_client_id = $data_setting_apikey['google_client_id']; $google_client_secret = $data_setting_apikey['google_client_secret']; $midtrans_client_key = $data_setting_apikey['midtrans_client_key']; $midtrans_server_key = $data_setting_apikey['midtrans_server_key']; $rajaongkir_key = $data_setting_apikey['rajaongkir_key']; $tinypng_key = $data_setting_apikey['tinypng_key']; // LOKASI TOKO $lokasi_toko = $server - > query("SELECT * FROM `setting_lokasi` WHERE `id`='1'"); $data_lokasi_toko = mysqli_fetch_assoc($lokasi_toko); $provinsi_toko = $data_lokasi_toko['provinsi']; $provinsi_id_toko = $data_lokasi_toko['provinsi_id']; $kota_toko = $data_lokasi_toko['kota']; $kota_id_toko = $data_lokasi_toko['kota_id']; // TIPE PEMBAYARAN $tipe_pembayaran = $server - > query("SELECT * FROM `setting_pembayaran` WHERE `status`='active'"); $data_tipe_pembayaran = mysqli_fetch_array($tipe_pembayaran); $nama_tipe_pembayaran = $data_tipe_pembayaran['tipe']; $jumlahPesanan = array( 'Belum Bayar' => 0, 'Dikemas' => 0, 'Dikirim' => 0, 'Selesai' => 0, 'Dibatalkan' => 0, ); // Loop melalui tiap tipe progress dan hitung jumlah pesanan foreach($jumlahPesanan as $tipeProgress => & $jumlah) { // Gunakan prepared statement untuk keamanan $query = $server - > prepare("SELECT COUNT(*) AS jumlah FROM invoice INNER JOIN iklan ON invoice.id_iklan = iklan.id INNER JOIN akun ON iklan.user_id = akun.id WHERE(iklan.user_id = ? OR akun.id = ? ) AND invoice.tipe_progress = ? "); $query - > bind_param("iis", $iduser, $iduser, $tipeProgress); $query - > execute(); $result = $query - > get_result(); // Hitung jumlah pesanan $row = $result - > fetch_assoc(); $jumlah = $row['jumlah']; // Tutup prepared statement $query - > close(); } // Fungsi untuk mendapatkan jumlah tipe progress dari database function getJumlahTipeProgress($server) { $jumlahTipeProgress = array(); $query = $server - > prepare("SELECT `tipe_progress`, COUNT(*) AS jumlah FROM `invoice` GROUP BY `tipe_progress`"); $query - > execute(); $result = $query - > get_result(); while ($row = $result - > fetch_assoc()) { $tipeProgress = $row['tipe_progress']; $jumlah = $row['jumlah']; $jumlahTipeProgress[$tipeProgress] = $jumlah; } $query - > close(); return $jumlahTipeProgress; } // Dapatkan jumlah tipe progress $jumlahTipeProgress = getJumlahTipeProgress($server); // Array untuk menyimpan jumlah pesanan berdasarkan tipe progress $jumlahPesananTerbaru = array( 'Belum Bayar' => 0, 'Dikemas' => 0, 'Dikirim' => 0, 'Selesai' => 0, 'Dibatalkan' => 0, ); // Loop melalui tiap tipe progress dan hitung jumlah pesanan foreach($jumlahPesananTerbaru as $tipeProgressTerbaruKey => & $jumlahPesananTerbaruValue) { // Gunakan prepared statement untuk keamanan $queryPesanan = $server - > prepare("SELECT COUNT(*) AS jumlah FROM `invoice` WHERE `id_user` = ? AND `tipe_progress` = ?"); $queryPesanan - > bind_param("is", $iduser, $tipeProgressTerbaruKey); $queryPesanan - > execute(); // Dapatkan hasil query $resultPesanan = $queryPesanan - > get_result(); // Hitung jumlah pesanan $rowPesanan = $resultPesanan - > fetch_assoc(); $jumlahPesananTerbaruValue = $rowPesanan['jumlah']; // Tutup prepared statement $queryPesanan - > close(); } // Fungsi untuk mendapatkan jumlah tipe progress dari database function getJumlahTipeProgressTerbaru($server) { $jumlahTipeProgressTerbaru = array(); $query = $server - > prepare("SELECT `tipe_progress`, COUNT(*) AS jumlah FROM `invoice` GROUP BY `tipe_progress`"); $query - > execute(); $result = $query - > get_result(); while ($row = $result - > fetch_assoc()) { $tipeProgressTerbaru = $row['tipe_progress']; $jumlah = $row['jumlah']; $jumlahTipeProgressTerbaru[$tipeProgressTerbaru] = $jumlah; } $query - > close(); return $jumlahTipeProgressTerbaru; } // Dapatkan jumlah tipe progress $jumlahTipeProgressTerbaru = getJumlahTipeProgressTerbaru($server); ' <!-- end snippet -->
|mysql|
I submit the same text, but the similarity value is different. It feels like the model chooses one of 3-4 behavior patterns. How can I make the results deterministic? ``` if find(IMAGE_CLASS).get_attribute('class') == "keysMaker_picdiv": description = find(IMAGE_TITLE).get_attribute('title') description_value = MODEL.encode(description, convert_to_tensor=True) similarity_value = util.pytorch_cos_sim(input_value, description_value)[0][0] print(f'{index}. {description}\nСхожесть {similarity_value:.3f}. {"Проходит!" if similarity_value >= N_FACTOR else "Нет!"}') if similarity_value >= N_FACTOR: return True ``` Here I trying to make it deterministic on my own. Not showing results. ``` def get_model(SEED): random.seed(SEED) numpy.random.seed(SEED) torch.manual_seed(SEED) torch.cuda.manual_seed(SEED) torch.cuda.manual_seed_all(SEED) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False MODEL = SentenceTransformer("all-mpnet-base-v2") print(checksum(MODEL)) MODEL = MODEL.to('cpu') return MODEL ```
I get very different comparison results for the same texts. [sentence-transformers/all-mpnet-base-v2]
|comparison|sentence-transformers|
null
Change collab environment to GPU necessary and run this : !pip install git+https://github.com/huggingface/accelerate.git !pip install git+https://github.com/huggingface/transformers.git !pip install bitsandbytes
Whenever you have a [mapped type](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html) of the form `{[K in keyof T]: ⋯}`, with `in keyof` in there directly, it will be a *homomorphic mapped type* as described in https://stackoverflow.com/q/59790508/2887218. That means [`readonly`](https://www.typescriptlang.org/docs/handbook/2/objects.html#readonly-properties) and [optional](https://www.typescriptlang.org/docs/handbook/2/objects.html#optional-properties) properties in the input type will become readonly and optional properties in the output type. Optional properties will always include `undefined` in their domain. So that means your `KeyPath<T>` type will end up including `undefined` if any of the keys of `T` (or perhaps even subkeys, given the recursion) are optional. You can test the type to see this (it looks like you tried to do this but didn't fully expand the type. One way to do this is to [intersect](https://www.typescriptlang.org/docs/handbook/2/objects.html#intersection-types) with `{} | null | undefined`, a type more or less equivalent to [`unknown`](https://www.typescriptlang.org/docs/handbook/2/functions.html#unknown)): type TestKey = KeyPath<Domain> & ({} | null | undefined); // ^? type TestKey = "id" | "value" | "user" | "user.id" | "user.name" | // "user.emails" | "user.isActive" | "user.type" | "user.name.first" | // "user.name.last" | undefined Now, ideally, TypeScript would be smart enough to prevent you from using `undefined` as a key in an [indexed access type](https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html). But sometimes if generics are complicated enough, the compiler fails to see the problem: type Hmm<T> = { [K in keyof T]: K }[keyof T] type Grr<T> = T[Hmm<T>]; // <-- this should be an error but it's not type Okay = Grr<{a: string}> // string type Bad = Grr<{ a?: string }> // unknown The `unknown` is what happens when the compiler is trying to figure out `{a?: string}[undefined]`. Allowing `undefined` to sneak in as a key is probably a bug or design limitation in TS, but I haven't found a relevant GitHub issue yet. ---- Anyway, the fix here is to use the `-?` [mapping modifier](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#mapping-modifiers) to make keys required in the mapping and to prevent `undefined` from being included in the domain. (The `-?` modifier is used in the definition of [the `Required<T>` utility type](https://www.typescriptlang.org/docs/handbook/utility-types.html#requiredtype)): type KeyPath<T, TParentKey = undefined> = { [K in keyof T]-?: K extends string ? ( // ^^ TParentKey extends undefined ? `${K}` : `${TParentKey & string}.${K}` ) : never; }[keyof T] | { [K in keyof T]-?: T[K] extends object ? ( // ^^ K extends string ? KeyPath< T[K], TParentKey extends undefined ? `${K}` : `${TParentKey & string}.${K}` > : never ) : never; }[keyof T]; which removes `undefined` from the list of keys: type TestKey = KeyPath<Domain> & ({} | null | undefined); // ^? type TestKey = "id" | "value" | "user" | "user.id" | "user.name" | // "user.emails" | "user.isActive" | "user.type" | "user.name.first" | // "user.name.last" which unbreaks `SortKey`: type DomainSortKey = SortKey<Domain>; /* type DomainSortKey = { key: "id"; order: 'asc' | 'desc'; getter: Getter<Domain, "id">; comparer: Comparer<number>; } | { key: "value"; order: 'asc' | 'desc'; getter: Getter<Domain, "value">; comparer: Comparer<...>; } | ... 7 more ... | { ...; } */ [Playground link to code](https://www.typescriptlang.org/play?#code/C4TwDgpgBAwg9gWzAQwE4VQHgCoD4oC8UAFMgFxTYA0UARhdgJSH4B2ArgrRgNwBQfVsgQQAzigDG0APKoAlgHMoAbz5QooSFADSEEAAVkwABY4a2Q+lbBdIQlHasAJhABmc1hCf4iq9eoBtbSgPKABrPThXSgBdCmCIAA9gCGdRKFFgeVYlAH4SCzRUmz0oJJS0h2c3Dy8ofIADABJlbQBfBqgKZuVCqxK7ADIMrI8FNoA6FvaG5gpPADdeNSg2gIiQKNiV9QAfFR3-IJDWcMjo7DjKIJiy5NSndLhaACsICWB6nTuKx5HsvI6PSGEw4G7mSzFWw-B7pRwudyeJxfHozLpQHp9KGlYaZAGTaYdfDzCBLVDoxbLfyrdbnbbU-grAD0TKgADk4AB3KAAGwgwAA5OlMmhPilMmMNMZoNgAMoacBiCYrTQysQDey2EGmAAiiGQHnww2IyjaUH2HB5PPNVQRtScjH46hZ-gAevlVZR1bYAIz2ABEcic-pt-oWyB57AgIf2-vYogwMagcYTqAmQaTKYwEyEIhjzNZ1OT8ezEAQBp5okzJbTclEAEEPnIltXUxNVa3s7mIBN3KhMkmC0Xi23uxMecgBzb4TUkXw2gJPQAJBAIHA+FRQY6hDZbS7xGm7i4xPiegDiqCweHs2ACK7XeBiPCgLswAFo31K6xljHB2DzkW4KBkFODBUDgclaHYT45EFdJWDgYBT0VKBpDCZA7CIC8sGUYCKDxSU2nwF0CJyZCtAAIWQZEsMvTBcOQXJ8NGHJVmI1lHDCBDOVYARyOgLUjFMahKEhaxoSIGdES8Dc-C3YIdzpS43yY75ylhf5JXyYhDhdYc3VdQ4sXE0p1MqKT7RRQlOm6FpjI1XEWPGKZWg6FY5igSlUGfNYj3pG05MCBTTj85TVNvbRbjMv5njeD4vh04c9P0qBXUM4cEnuSpSMBQTQUOakIpiCEihMuxorhappORRprPRTExIczScgJVyGgKqBiU80kMEODyvKdQ8lKfRcUIANQjKN62AbUzCgbUN21GFKlClZ8lvbUT3UCgloqjEWg8VwMCBEBWsO46ACV1Tc9R8mhPbVtuqAJsjCBptmiK9GKqArsyXAVhJMkAe6slGXPfkUivGhMt+YUnI3YgEDgFweQYGgNniZgCHwF6ppmoS5u0XAwZQ2UIIGHAAFlkYgHlZJWbdTjy4TqZR3ArkCs4QHiQb1AglxUAoAVJwkAUbQFFxRFF3moAUCGMAoM95avVnaeh4nDgkRAUHQQXYG1oosFxt78dBbBVZ5dWNfUBc1mZqmabpkbRq0ABVVN7DkoN5k4bhvJWbsKE5vtMmYgEZYnUPmoUQa2kGssK1EVScoCEb1DrRtgGbCAKFoOA4D5EDBtVIWJHjYBEAwMX9iFdgwDAcmBXnEmtD1ctQl8FZvc832qSgcNXrDsZBprCh3eWOOXbVTIJJO2a24NVgjRIU0bUta19gspFHT4F1PWwb1SiIQNg1DAeo07VBL-TU-YxrHNhGjUN74TuRK0HZKR2zDOmxbZ+2w7P-Lsj9exyH7MAa+Y5I4QKnlABeHgyaoA1EQRBFN4FL34EyAAVAqVu+oEHk1npzDGyYMwy35grKAwspbVyoZLaWhw5bAEhorZWmB0E0BPv6a2-gtZIENhQeA-DdaYA4FwDAGszT7GIXoCgYZJrRnIagAWQsRa0IlmIBh1ImEsKgErZhGB2H4NYJw8+0YeHqD4TrShQjrFYAmA4yRNoHETCgAAdigEjdAUAXEBUOC4-gZosFMiAA)
React-router is very strict about what can be a child of `<Routes>`. You cannot put any custom component as a child, even if that child renders a `<Route>`. So you will need to redesign your `PrivateRoute` component to work *inside* the `<Route>`. For example: ``` export default function PrivateRoute({ children }) { const { currentUser } = useAuth() if (currentUser) { return children; } else { return <Navigate to="/login" /> } } ``` Used like: ``` <AuthProvider> <Routes> <Route path="/" element={<PrivateRoute><Dashboard /></PrivateRoute>} /> <Route path="/update-profile" element={<UpdateProfile />} /> // ... ```
Unreal Engine | [MULTIPLAYER] Possessing a pawn (thirdpersoncharacter), simple movement with WASD not working
|sql|mysql|
Encountering `Fatal error: Uncaught mysqli_sql_exception: Table 'kopsis.setting_email' doesn't exist in /www/wwwroot/kopsis/config.php:66 Stack trace: #0 /www/wwwroot/kopsis/config.php(66): mysqli->query() #1 /www/wwwroot/kopsis/index.php(2): include('...') #2 {main} thrown in /www/wwwroot/kopsis/config.php on line 66` This error occurs when running my code on a VPS with AAPanel. It works fine on cPanel hosting with PHP 7.4. How can I resolve this issue on the VPS with AAPanel and php 7.4 also?" I've already switched to PHP 7.3, 8.1, and still encountering the same issue, even triggering new errors This is Config.PHP code <!-- begin snippet: js hide: false console: true babel: false --> oh sorry, this is my config.php code: <!-- language: php --> <?php // Menonaktifkan tampilan pesan kesalahan error_reporting(E_ALL); // Atur zona waktu ke "Asia/Jakarta" (Waktu Indonesia Barat) date_default_timezone_set('Asia/Jakarta'); // Tampilkan tanggal dan waktu dalam format yang diinginkan $currentDateTime = date('d M Y H:i:s'); // Memulai sesi session_start(); // Mendefinisikan path fisik ke file connection.php $path_to_connection = $_SERVER['DOCUMENT_ROOT']. "/connection.php"; // Melakukan include file menggunakan path fisik include $path_to_connection; // CEK LOGIN USER if (isset($_COOKIE['login'])) { $key_login = $_COOKIE['login']; $ciphering = "AES-128-CTR"; $iv_length = openssl_cipher_iv_length($ciphering); $options = 0; $decryption_iv = '1234567891011121'; $decryption_key = "ecommerce"; $decryption = openssl_decrypt($key_login, $ciphering, $decryption_key, $options, $decryption_iv); $iduser_key_login = explode("hcCTZvFLD7XIchiaMqEka0TLzGgdpsXB", $decryption); $id_user_login = $iduser_key_login[0]; $select_profile = $server - > prepare("SELECT * FROM `akun` WHERE `id`=?"); $select_profile - > bind_param("i", $id_user_login); $select_profile - > execute(); $result = $select_profile - > get_result(); $profile = $result - > fetch_assoc(); // Jika profil tidak ditemukan, redirect ke halaman logout if (!$profile) { header('Location: '.$url. '/system/logout.php'); exit(); // Pastikan untuk menghentikan eksekusi setelah melakukan redirect } // Simpan informasi pemilik toko yang sedang login $iduser = $profile['id']; // COUNT CART $count_cart_header = $server - > query("SELECT * FROM `keranjang` WHERE `id_user`='$iduser' "); $cek_cart_header = mysqli_num_rows($count_cart_header); // COUNT NOTIFICATION $count_notif_header = $server - > query("SELECT * FROM `notification` WHERE `id_user`='$iduser' AND `status_notif`='' "); $cek_notif_header = mysqli_num_rows($count_notif_header); // COUNT FAVORIT $count_favorit_header = $server - > query("SELECT * FROM `favorit` WHERE `user_id`='$iduser' "); $cek_favorit_header = mysqli_num_rows($count_favorit_header); // COUNT CHAT $count_chat_header = $server - > query("SELECT * FROM `chat` WHERE `penerima_user_id`='$iduser' AND `status`='' "); $cek_chat_header = mysqli_num_rows($count_chat_header); // COUNT PESANAN $count_pesanan_header = $server - > query("SELECT * FROM `invoice` WHERE `id_user`='$iduser' AND `tipe_progress`='' "); $cek_pesanan_header = mysqli_num_rows($count_pesanan_header); } // NOTIFIKASI JUMLAH PESAN BARU $count_unread_chat = $server - > query("SELECT * FROM `chat` WHERE `penerima_user_id`='1' AND `status`=''"); $cek_unread_chat = mysqli_num_rows($count_unread_chat); // NOTIFIKASI JUMLAH PERMINTAAN PENARIKAN $count_pending_rows = $server - > query("SELECT COUNT(*) as total FROM `riwayat_penarikan` WHERE `status`=0"); $row = $count_pending_rows - > fetch_assoc(); $total_pending_rows = $row['total']; // ADMIN MAIL $setting_email_query = $server - > query("SELECT * FROM `setting_email` WHERE `id`='1'"); $data_setting_email = mysqli_fetch_assoc($setting_email_query); $setfrom_smtp = $data_setting_email ? $data_setting_email['setfrom_smtp'] : null; // HEADER SETTING $setting_header = $server - > query("SELECT * FROM `setting_header` WHERE `id_hs`='1'"); $data_setting_header = mysqli_fetch_assoc($setting_header); $logo = $data_setting_header['logo']; $favicon = $data_setting_header['favicon']; $title_name = $data_setting_header['title_name']; $slogan = $data_setting_header['slogan']; $meta_description = $data_setting_header['meta_description']; $meta_keyword = $data_setting_header['meta_keyword']; $google_verification = $data_setting_header['google_verification']; $bing_verification = $data_setting_header['bing_verification']; $ahrefs_verification = $data_setting_header['ahrefs_verification']; $yandex_verification = $data_setting_header['yandex_verification']; $norton_verification = $data_setting_header['norton_verification']; // API KEY SETTING $setting_apikey = $server - > query("SELECT * FROM `setting_apikey` WHERE `id_apikey`='1'"); $data_setting_apikey = mysqli_fetch_assoc($setting_apikey); $google_client_id = $data_setting_apikey['google_client_id']; $google_client_secret = $data_setting_apikey['google_client_secret']; $midtrans_client_key = $data_setting_apikey['midtrans_client_key']; $midtrans_server_key = $data_setting_apikey['midtrans_server_key']; $rajaongkir_key = $data_setting_apikey['rajaongkir_key']; $tinypng_key = $data_setting_apikey['tinypng_key']; // LOKASI TOKO $lokasi_toko = $server - > query("SELECT * FROM `setting_lokasi` WHERE `id`='1'"); $data_lokasi_toko = mysqli_fetch_assoc($lokasi_toko); $provinsi_toko = $data_lokasi_toko['provinsi']; $provinsi_id_toko = $data_lokasi_toko['provinsi_id']; $kota_toko = $data_lokasi_toko['kota']; $kota_id_toko = $data_lokasi_toko['kota_id']; // TIPE PEMBAYARAN $tipe_pembayaran = $server - > query("SELECT * FROM `setting_pembayaran` WHERE `status`='active'"); $data_tipe_pembayaran = mysqli_fetch_array($tipe_pembayaran); $nama_tipe_pembayaran = $data_tipe_pembayaran['tipe']; $jumlahPesanan = array( 'Belum Bayar' => 0, 'Dikemas' => 0, 'Dikirim' => 0, 'Selesai' => 0, 'Dibatalkan' => 0, ); // Loop melalui tiap tipe progress dan hitung jumlah pesanan foreach($jumlahPesanan as $tipeProgress => & $jumlah) { // Gunakan prepared statement untuk keamanan $query = $server - > prepare("SELECT COUNT(*) AS jumlah FROM invoice INNER JOIN iklan ON invoice.id_iklan = iklan.id INNER JOIN akun ON iklan.user_id = akun.id WHERE(iklan.user_id = ? OR akun.id = ? ) AND invoice.tipe_progress = ? "); $query - > bind_param("iis", $iduser, $iduser, $tipeProgress); $query - > execute(); $result = $query - > get_result(); // Hitung jumlah pesanan $row = $result - > fetch_assoc(); $jumlah = $row['jumlah']; // Tutup prepared statement $query - > close(); } // Fungsi untuk mendapatkan jumlah tipe progress dari database function getJumlahTipeProgress($server) { $jumlahTipeProgress = array(); $query = $server - > prepare("SELECT `tipe_progress`, COUNT(*) AS jumlah FROM `invoice` GROUP BY `tipe_progress`"); $query - > execute(); $result = $query - > get_result(); while ($row = $result - > fetch_assoc()) { $tipeProgress = $row['tipe_progress']; $jumlah = $row['jumlah']; $jumlahTipeProgress[$tipeProgress] = $jumlah; } $query - > close(); return $jumlahTipeProgress; } // Dapatkan jumlah tipe progress $jumlahTipeProgress = getJumlahTipeProgress($server); // Array untuk menyimpan jumlah pesanan berdasarkan tipe progress $jumlahPesananTerbaru = array( 'Belum Bayar' => 0, 'Dikemas' => 0, 'Dikirim' => 0, 'Selesai' => 0, 'Dibatalkan' => 0, ); // Loop melalui tiap tipe progress dan hitung jumlah pesanan foreach($jumlahPesananTerbaru as $tipeProgressTerbaruKey => & $jumlahPesananTerbaruValue) { // Gunakan prepared statement untuk keamanan $queryPesanan = $server - > prepare("SELECT COUNT(*) AS jumlah FROM `invoice` WHERE `id_user` = ? AND `tipe_progress` = ?"); $queryPesanan - > bind_param("is", $iduser, $tipeProgressTerbaruKey); $queryPesanan - > execute(); // Dapatkan hasil query $resultPesanan = $queryPesanan - > get_result(); // Hitung jumlah pesanan $rowPesanan = $resultPesanan - > fetch_assoc(); $jumlahPesananTerbaruValue = $rowPesanan['jumlah']; // Tutup prepared statement $queryPesanan - > close(); } // Fungsi untuk mendapatkan jumlah tipe progress dari database function getJumlahTipeProgressTerbaru($server) { $jumlahTipeProgressTerbaru = array(); $query = $server - > prepare("SELECT `tipe_progress`, COUNT(*) AS jumlah FROM `invoice` GROUP BY `tipe_progress`"); $query - > execute(); $result = $query - > get_result(); while ($row = $result - > fetch_assoc()) { $tipeProgressTerbaru = $row['tipe_progress']; $jumlah = $row['jumlah']; $jumlahTipeProgressTerbaru[$tipeProgressTerbaru] = $jumlah; } $query - > close(); return $jumlahTipeProgressTerbaru; } // Dapatkan jumlah tipe progress $jumlahTipeProgressTerbaru = getJumlahTipeProgressTerbaru($server); <!-- end snippet -->
If you build an application using Flutter, There are many possibilities for sound not to play > 1. You may be using an older version of flutter_local_notifications Please Update it to the latest. > 2. Missing sound in apns payload If you want to play a custom sound, you can add your sound file inside the resource in iOS and pass the file name conditionally inside the payload. 1. If you pass the **default** then the default ringtone will play. 2. If you pass **file name** which is inside iOS resources folder then that sound ring. Code Example: const message = { token: to, notification: { title, body, // sound: "ringtone.wav", }, apns: { headers: { "apns-priority": "10", }, payload: { aps: { sound: body != "You have one Booking Request" ? "default" : "ringtone.wav", }, }, }, android: { priority: "high", notification: { channelId: body != "You have one Booking Request" ? "normal" : "Sound", sound: "ringtone.mp3", }, }, data: { click_action, }, }; Replace **body != "You have one Booking Request" ? "default" : "ringtone.wav"** with your requirment
|php|woocommerce|
Well, I might be oversimplifying this. But, you can invoke a lambda function from within the same lambda function. With the approach I'm explaining below, there's only one lambda function and no other services. 1. Lambda is triggered with email address and `index` value `1` as event parameters 2. Lambda sends the first external API request and if it succeeds, it stops there. If it doesn't, it invokes itself with `index` value `2`. 3. This goes on until you get to `index` value `100`. Also, how much time does these external APIs take to respond? Because, 15 minutes sounds good enough to me for 100 API requests(\~9 seconds for each API).
null
Currently in our app we do not override the system’s default method for alphabetizing data, it will sort capital letters over lowercase letters. How to enable case-insensitive across the application without changing the collation? Database: PostgreSQL Any idea on this ?
# Eror ``` FAILED tests/users/api/test_auth.py::test_create_user_failed_unique_phone_number - RuntimeError: Task <Task pending name='Task-22' coro=<test_create_user_failed_unique_phone_number() running at /app/tests/users/api/test_auth.py:36> cb=[_run_until_complete_cb() at /usr/local/lib/python3.12/asyncio/base_events... ``` Error happens all time when I try to call db.commit. For database connection I use for database url postgresql+asyncpg. ``` # conftest.py pytest_plugins = [ "tests.users.factories.users", ] async def init_db(engine): async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) async def close_db(engine): async with engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) @pytest.fixture(scope="session", autouse=True) async def db_engine(): engine = create_async_engine(settings.DATABASE_URL) await init_db(engine) yield engine await close_db(engine) await engine.dispose() @pytest.fixture async def db() -> AsyncIterable[AsyncSession]: async with SessionLocal() as session: yield session @pytest.fixture async def db_ins(db: AsyncSession) -> AsyncIterable[DBInsert]: async def insert(factory: SQLAlchemyModelFactory, **kwargs: Any) -> Any: instance = factory.build(**kwargs) db.add(instance) await db.commit() return instance yield insert @pytest.fixture(scope="session") async def client() -> AsyncIterable[AsyncClient]: async with AsyncClient(app=app, base_url="http://testserver") as client: yield client ``` ``` # tests.users.factories.users class UserFactory(SQLAlchemyModelFactory): class Meta: model = Users abstract = True first_name = factory.Faker("first_name") last_name = factory.Faker("last_name") email = factory.Faker("email") phone = factory.Sequence(lambda n: fake_phone_number()) is_active = True hash_password: str = factory.LazyAttribute(lambda _: PasswordHelper().hash("12345678")) class AdminUserFactory(UserFactory): role = Role.ADMIN ``` ``` @pytest.fixture async def admin_user(db_ins: DBInsert) -> Users: user = await db_ins(AdminUserFactory) return user ``` When I use admin_user fixture, I receive RuntimeError: Event loop is closed exception. It happened when we call db.commit() in db_ins fixture. I want to fix this problem with database
--Remove Duplciates[SKR] --Option A: select * --delete t from(select rowNumber=row_number() over (partition by Member_Key order by Member_Key) , Member_Key, MemberID from dbo.Member m )t where rowNumber > 1 --Option B: with cte as ( select rowNumber=row_number() over (partition by Member_Key order by Member_Key) , Member_Key, MemberID from dbo.Member m ) --delete from cte where rowNumber > 1 select * from cte where rowNumber > 1
First `pivot` the data to a long format, then you can plot the values on the y-axis for each month, defining the groups by the `day_of_week`. ``` r library(tidyverse) df %>% pivot_longer(-day_of_week, names_to = 'month') %>% ggplot(aes(x = month, y = value, color = day_of_week, group = day_of_week)) + geom_point() + geom_line() ``` ![](https://i.imgur.com/AlMthZ5.png)<!-- --> ### Data ``` r df <- read.table(header = TRUE, text = 'day_of_week feb_23 mar_23 apr_23 may_23 jun_23 sunday 24575 48314 83366 84074 116821 monday 32208 46043 78434 85285 122528 tuesday 41347 56317 101060 76440 101694 wednesday 25792 51056 61445 98910 94837 thursday 21852 46027 71823 83957 117189 friday 38517 69504 75012 131155 104023 saturday 24284 24948 73140 84078 130631 ' ) ```
{"OriginalQuestionIds":[75828537],"Voters":[{"Id":7644018,"DisplayName":"Paul T."},{"Id":7209631,"DisplayName":"vitruvius"},{"Id":22180364,"DisplayName":"Jan"}]}
Input and output of signed single-digit decimal numbers
I have imported 1000 sample rows from various tables into a SQL Server (let's call it `SQLServer1`). I have also imported the rows into the second SQL Server (`SQLServer2`). When I execute the following query on `SQLServer2`, I get no results, however when I execute the same query on `SQLServer1`, I get the expected results. This is because I haven't imported all the rows from `SQLServer1` to `SQLServer2`. The problem is that I can't import all the data from `SQLServer1` to `SQLServer2` because some tables contain over 3 million rows. Therefore, can someone let me know if there is a way to find out exactly data is required from the tables in `SQLServer1` to get a result from `SQLServer2`? Basically, I need to import only those rows into `SQLServer2`, that will produce the same result in `SQLServer1`. I believe I would need to do apply some kind of `DISTINCT` clause or a `LEFT / RIGHT JOIN` to determine the rows/columns/data that is present in `SQLServer1` that is not present in `SQLServer2`, but I'm not sure. The tables look like the following: [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/zjRrR.png Sample code is as follows: CREATE TABLE #tmpTable ( MakeName nvarchar(100), ModelName nvarchar(150), Cost money ) INSERT #tmpTable VALUES (N'Ferrari', N'Testarossa', 52000.00), (N'Ferrari', N'355', 176000.00), (N'Porsche', N'911', 15600.00), (N'Porsche', N'924', 9200.00), (N'Porsche', N'944', 15960.00), (N'Ferrari', N'Testarossa', 176000.00), (N'Aston Martin', N'DB4', 23600.00), (N'Aston Martin', N'DB5', 39600.00) Any thoughts? The code is as follows: ``` SELECT Make.MakeName, Model.ModelName, Stock.Cost FROM Data.Stock INNER JOIN Data.Model ON Model.ModelID = Stock.ModelID INNER JOIN Data.Make ON Make.MakeID = Model.MakeID ```
RuntimeError: Event loop is closed when I call db.comit()
|sqlalchemy|pytest|fastapi|factory-boy|pytest-asyncio|
null
As I understand from your question, you store the `date` in Firestore in the following format: 2024/02/29 00:00:00 GMT05.30 Which is not quite correct. Such a field can exist inside a document in Firestore only as a string. I'm saying that because `GMT (Greenwich Mean Time)` is a timezone and the timestamps in Firestore don't encode timezones. The timezone of the Firestore timestamp is UTC. If you need to work with date and time, then you should use a [Firestore Timestamp][1], which is a [supported data type][2] in Firestore. So once you set the field with the correct data type, you can then perform a query. Please also note that when you call `where()` you have to pass a timestamp object and **not** a `DateTime`. If you do so, you'll never get the desired results. [1]: https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/Timestamp-class.html [2]: https://firebase.google.com/docs/firestore/manage-data/data-types
null
if you are facing the same issue again, try manually copy pasting main.jsbundle in ios xcodeworkspace then run it again
How can I trigger the **handle_generate_automatic_ticket** jQuery function on the processed order once the customer lands on the WooCommerce thank-you.php page? **The problem:** I currently have to click a button on the WooCommerce back end to generate the lottery ticket number that has just been ordered. I need this to be automatic once the order is placed. I want to run this add_action within the functions.php to auto generate tickets: add_action('woocommerce_thankyou', 'generate_ticket_on_thankyou_page'); Which will trigger the handle_auto_generate_ticket jQuery script once the user lands on the order thank you page: generate_automatic_ticket: function (event) { let $this = $(event.currentTarget); LTY_Shop_Order.handle_generate_automatic_ticket($this.data('item_id')); }, handle_generate_automatic_ticket: function (item_id) { LTY_Shop_Order.block($('.woocommerce_order_items').find('#order_line_items')); var data = ({ action: 'lty_generate_automatic_ticket_edit_order', item_id: item_id, order_id: $('.lty-order-id').val(), answer_id: $('.lty-question-answer-id').val(), lty_security: lty_shop_order_params.lty_automatic_ticket_nonce, }); $.post(ajaxurl, data, function (res) { LTY_Shop_Order.unblock($('.woocommerce_order_items').find('#order_line_items')); if (true === res.success) { alert(lty_shop_order_params.lty_success_message); location.reload(); } else { alert(res.data.error); } } ); }, Thank you in advance for any help. I've written the following to try trigger the auto generate ticket function. The order goes through but doesn't auto generate the ticket still. I still have to go to the order on the back end and click the Generate Ticket(s) button: add_action('woocommerce_thankyou', 'generate_ticket_on_thankyou_page'); function generate_ticket_on_thankyou_page() { ?><script> jQuery( function( $ ) { $(document).ready(function() { let $this = $(event.currentTarget); LTY_Shop_Order.handle_generate_automatic_ticket($this.data('item_id')); }, handle_generate_automatic_ticket: function (item_id) { LTY_Shop_Order.block($('.woocommerce_order_items').find('#order_line_items')); var data = ({ action: 'lty_generate_automatic_ticket_edit_order', item_id: item_id, order_id: $('.lty-order-id').val(), answer_id: $('.lty-question-answer-id').val(), lty_security: lty_shop_order_params.lty_automatic_ticket_nonce, }); $.post(ajaxurl, data, function (res) { LTY_Shop_Order.unblock($('.woocommerce_order_items').find('#order_line_items')); if (true === res.success) { alert(lty_shop_order_params.lty_success_message); location.reload(); } else { alert(res.data.error); } } ); }, ); }); </script> <?php }
it seems to me you could achieve your goal by means of formulas if you insert one column and one row you could use this formula =IF(SUM(G$5:G5)<G$2;IF(SUM(F6:$F6)<8;1;"");"") [![enter image description here][1]][1] or you can keep your original rows and columns layout and adopt this other formula: =IF(ROW()=5; IF(COLUMN()=7; 1; IF(SUM(F5:$G5)<8;1;"")); IF(SUM(G4:G$5)<G$2; IF(COLUMN()=7; 1; IF(SUM(F5:$G5)<8;1;"")); "") ) [![enter image description here][2]][2] Finally here's the corresponding amendment of your code (forgive the polish): Sub AutoFill() Dim ws As Worksheet Dim col As Integer Dim row As Integer Dim suma As Integer Dim liczba_osob As Integer ' Ustaw arkusz, na którym chcesz dzialac Set ws = ThisWorkbook.Sheets("01") ' Wyczysc zakres G5:AD36 ws.Range("G5:AD36").ClearContents ' Iteruj przez kolumny od G do Y For col = 7 To 30 ' Pobierz liczbe osób w pracy w danej godzinie liczba_osob = ws.Cells(2, col).Value ' Ustaw sume kolumny na 0 suma = 0 ' Uzupelnij komórki wartoscia 1 do momentu, gdy suma wiersza bedzie równa liczbie osób w pracy For row = 5 To 36 ' Sprawdz, czy w biezacym wierszu nie przekracza liczby osób w pracy '<-----| If WorksheetFunction.Sum(ws.Range(ws.Cells(row, 7), ws.Cells(row, WorksheetFunction.Max(7, col - 1)))) < 8 Then '<-----| ' Sprawdz, czy suma nie przekracza liczby osób w pracy If suma < liczba_osob Then ws.Cells(row, col).Value = 1 suma = suma + 1 End If End If '<-----| Next row Next col End Sub and here's a refactoring of that code: Option Explicit Sub AutoFill() Const MAX_HOURS As Long = 8 Const DATA_ADDRESS As String = "G5:AD36" With ThisWorkbook.Sheets("01") Dim dataRng As Range Set dataRng = .Range(DATA_ADDRESS) With dataRng Dim firstCol As Long firstCol = .Columns(1).Column Dim firstRow As Long firstRow = .Rows(1).row .ClearContents End With Dim columnRng As Range For Each columnRng In dataRng.Columns Dim currentCol As Long currentCol = columnRng.Column Dim currentColHoursLimit As Long currentColHoursLimit = .Cells(2, currentCol).Value Dim rowCel As Range For Each rowCel In columnRng.Rows If WorksheetFunction.Sum(.Range(.Cells(rowCel.row, firstCol), .Cells(rowCel.row, WorksheetFunction.Max(firstCol, currentCol - 1)))) < MAX_HOURS Then If WorksheetFunction.Sum(.Range(.Cells(firstRow, currentCol), .Cells(WorksheetFunction.Max(firstRow, rowCel.row - 1), currentCol))) < currentColHoursLimit Then rowCel.Value = 1 End If End If Next Next End With End Sub [1]: https://i.stack.imgur.com/we5Ul.png [2]: https://i.stack.imgur.com/I4Ouv.png
|python|tkinter|
Call [`Language.Haskell.TH.Syntax.addDependentFile`](https://hackage.haskell.org/package/template-haskell-2.8.0.0/docs/Language-Haskell-TH-Syntax.html#v:addDependentFile).
I came across this problem on the internet of c language. The question was that will this code compile successfully compile or will return an error. ``` #include <stdio.h> int main(void) { int first = 10; int second = 20; int third = 30; { int third = second - first; printf("%d\n", third); } printf("%d\n", third); return 0; } ``` I personally think that this code should give an error as we are re initializing the variable third in the main function whereas the answer to this problem was this code will run successfully with output 10 and 30. then I compiled this code on vs code and it gave an error but on some online compilers it ran successfully with no errors can somebody please explain. I don't think there can be two variables with same name inside the curly braces inside main. if the third was initialized after the curly braces instead before it would work completely fine. like this :- ``` #include <stdio.h> int main(void) { int first = 10; int second = 20; { int third = second - first; printf("%d\n", third); } int third = 30; printf("%d\n", third); return 0; } ```
You are calling `setVal("")`, which is changing the data type from an array to a string.
I would like to create a function that takes three arguments (n,m,d) and it should output a matrix with n rows and m columns. The matrix should be populated with values 0 and 1 at random, in order to ensure that you have a density d of ones. This is what I have come up with so far, just can't seem to work out how to integrate the density variable. ``` def create_matrix(n, m): count = 1 grid = [] while count <= n: for i in range(m): x = [random.randrange(0,2) for _ in range(m)] grid.append(x) count += 1 return grid ```
You have to import androidx library like import androidx.preference.PreferenceManager For kotlin DSL: implementation("androidx.preference:preference:1.2.1") For KSP: implementation("androidx.preference:preference-ktx:1.2.1") For more info, you can visit official document of [Preference][1]. [1]: https://developer.android.com/jetpack/androidx/releases/preference
I am using PrivateGPT to chat with a PDF document. I ask a question and get an answer. If I am okay with the answer, and the same question is asked again, I want the previous answer instead of creating a new one. How can I handle this? Are there any options available? settings-local.yaml llm: mode: llamacpp max_new_tokens: 512 context_window: 3900 tokenizer: mistralai/Mistral-7B-Instruct-v0.2 llamacpp: prompt_style: "mistral" llm_hf_repo_id: TheBloke/Mistral-7B-Instruct-v0.2-GGUF llm_hf_model_file: mistral-7b-instruct-v0.2.Q4_K_M.gguf embedding: mode: huggingface huggingface: embedding_hf_model_name: BAAI/bge-small-en-v1.5 vectorstore: database: qdrant qdrant: path: local_data/private_gpt/qdrant
How to locate relevant tables or columns in a SQL Server database
|sql-server|t-sql|
I have been struggling with this issue as well when trying to set up a VSCode remote development container (docker compose build but should not make a big difference) with x11 support. My requirements were as follows, since I intended not to expose my development machine too much to the open internet: - No `network_mode: host` or `--net=host` respectively - No `X11UseLocalhost no` - No `xhost` **Please note that using the host network potentially (depending on your firewall configuration) exposes anything running on some port in your devcontainer to ANYONE being able to reach your machine.** I ended up spinning up a daemonized `socat` process on the remote host at devcontainer initialization, tunneling the TCP x11 traffic from port 6XXX used for x11 with SSH to an x11 UNIX socket that I share with my container. Solution is best described in a commit: https://github.com/flxtrtwn/devious/pull/16/commits/c6a233eb7312ca606f9d53a102bea8c1f8282578
I have been struggling with this issue as well when trying to set up a VSCode remote development container (docker compose build but should not make a big difference) with x11 support. My requirements were as follows, since I intended not to expose my development machine too much to the open internet: - No `network_mode: host` or `--net=host` respectively - No `X11UseLocalhost no` - No `xhost` **Please note that using the host network potentially (depending on your firewall configuration) exposes anything running on some port in your devcontainer to anyone being able to reach your machine.** I ended up spinning up a daemonized `socat` process on the remote host at devcontainer initialization, tunneling the TCP x11 traffic from port 6XXX used for x11 with SSH to an x11 UNIX socket that I share with my container. Solution is best described in a commit: https://github.com/flxtrtwn/devious/pull/16/commits/c6a233eb7312ca606f9d53a102bea8c1f8282578
{"Voters":[{"Id":3403834,"DisplayName":"user58697"},{"Id":6243352,"DisplayName":"ggorlen"},{"Id":22180364,"DisplayName":"Jan"}]}
I'm developing a clock widget in Flutter that displays the current time. I want to provide two methods for updating the time asynchronously: one using a continuous stream of time updates, and the other using a timer that updates the time at regular intervals. **Code Explanation:** *clock() Method:* 1. This method returns a continuous stream of time updates asynchronously. 2. It uses a while loop to continuously update the current time using DateTime.now() and formats it using DateFormat. 3. The time is yielded as a String and printed to the console. 4. It includes a delay using Future.delayed() to control the update frequency *timer() Method:* - This method returns a stream of time updates asynchronously using a timer. - It initializes the current time and formats it. - Inside a while loop, it checks if the current time differs from the last recorded time. If so, it updates the time and yields it. Otherwise, it repeats the same time for a maximum of 5 iterations. - This method also includes a delay using Future.delayed(). ``` import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; class Clock extends StatefulWidget { const Clock({super.key}); @override State<Clock> createState() => _ClockState(); } class _ClockState extends State<Clock> { //first methode, returns time as String Stream<String> clock() async* { DateTime time; String current; while (true) { time = DateTime.now(); current = DateFormat('hh : mm : ss').format(time); yield current; print(current); await Future.delayed( Duration(milliseconds: 100), ); } } //seconde one Stream<String> timer() async* { DateTime time = DateTime.now(); String current = DateFormat('hh : mm : ss').format(time); while (true) { if (current != DateFormat('hh : mm : ss').format(DateTime.now())) { current = DateFormat('hh : mm : ss').format(DateTime.now()); yield current; print(current); await Future.delayed( Duration(milliseconds: 200), ); } else { yield current; //this command repeats 5 time maximum print(current); await Future.delayed( Duration(milliseconds: 200), ); } } } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: StreamBuilder( stream: timer(), builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return Container( height: 350, width: 350, decoration: BoxDecoration( border: Border.all( color: Colors.blue, width: 4, ), shape: BoxShape.circle), child: Center( child: Text( '${snapshot.data}', style: TextStyle( fontSize: 30, fontWeight: FontWeight.w500, ), ), ), ); } else { return Text('waiting...'); } }, ), ), ); } } ``` both methods rely on while loops where *print statement* in **clock()** repeats 10 times maximum and 5 times maximum in **timer** methode
From the docs ![](https://i.imgur.com/WQgtocU.png) It is the browser in charge of rendering text, you have to analyze where text is rendered. With Canvas or SPAN Far from perfect. This one: * wraps each word in a ``<span>`` * calculates by ``offsetHeight`` if a SPAN spans multiple lines * of so it found a hyphened word * it then **removes** each _last_ character from the ``<span>`` to find when the word wrapped to a new line ![](https://i.imgur.com/zvCwk1H.png) The _Far from perfect_ is the word "demonstrate" which _**"fits"**_ when shortened to "demonstr" **-** "ate" But is not the English spelling ![](https://i.imgur.com/WtZTaiF.png) Needs some more JS voodoo <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-html --> <style> .hyphen { background: pink } .remainder { background: lightblue } </style> <process-text lang="en" style="display:inline-block; overflow-wrap: word-break; hyphens: auto; zoom:1.2; width: 7em"> By using words like "incomprehensibilities", we can demonstrate word breaks. </process-text> <script> customElements.define('process-text', class extends HTMLElement { connectedCallback() { setTimeout(() => { let words = this.innerHTML.trim().split(/(\W+)/); let spanned = words.map(w => `<span>${w}</span>`).join(''); this.innerHTML = spanned; let spans = [...this.querySelectorAll("span")]; let defaultHeight = spans[0].offsetHeight; let hyphend = spans.map(span => { let hyphen = span.offsetHeight > defaultHeight; console.assert(span.offsetHeight == defaultHeight, span.innerText, span.offsetWidth); span.classList.toggle("hyphen", hyphen); if (hyphen) { let saved = span.innerText; while (span.innerText && span.offsetHeight > defaultHeight) { span.innerText = span.innerText.slice(0, -1); } let remainder = document.createElement("span"); remainder.innerText = saved.replace(span.innerText, ""); remainder.classList.add("remainder"); span.after(remainder); } }) console.log(this.querySelectorAll("span").length, "<SPAN> created" ); }) //setTimeout to read innerHTML } // connectedCallback }); </script> <!-- end snippet -->
I am learning vhdl and fpga, I have a digilent board Nexys 4 , what I am trying to do is sending via UART a string, I have been sucessfull in sending a character everytime a button is clicked on the board, now I want to send the whole string after every button click but I dont get any output from the terminal(I use putty), below is my code can please somebody help me? This is the top module I beleive the problem may be here but I am not 100% sure. ``` library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all; entity UART_tx_top is port(btnC : in std_logic; clk : in std_logic; RsTx : out std_logic); end UART_tx_top; architecture behavioral of UART_tx_top is signal string_to_send : string := "Hello World!"; constant string_length : integer := 12; signal tx_index : integer := 0; type state_type is (TX_WAIT_BTN, TX_SEND_CHAR, TX_SEND_WAIT); signal state : state_type := TX_WAIT_BTN; signal uartRdy : std_logic; signal uartSend: std_logic; signal uartData: std_logic_vector (7 downto 0); signal initStr : std_logic_vector (7 downto 0) := x"41"; signal btnCclr : std_logic; signal btnC_prev : std_logic; component UART_tx_ctrl generic(baud : integer); port(send : in std_logic; clk : in std_logic; data : in std_logic_vector (7 downto 0); ready : out std_logic; uart_tx : out std_logic); end component; component debounce is port(clk : in std_logic; btn : in std_logic; btn_clr : out std_logic); end component; begin process(clk) begin if rising_edge(clk) then btnC_prev <= btnCclr; case state is when TX_WAIT_BTN => if btnC_prev = '0' and btnCclr = '1' then state <= TX_SEND_CHAR; end if; when TX_SEND_CHAR => if tx_index < string_length then uartData <= std_logic_vector(to_unsigned(character'pos(string_to_send(tx_index + 1)), 8)); --initStr <= std_logic_vector(unsigned(initStr) + 1); tx_index <= tx_index + 1; --state <= TX_SEND_WAIT; else uartData <= (others => '0'); tx_index <=0; state <= TX_WAIT_BTN; end if; when TX_SEND_WAIT => if uartRdy = '1' then state <= TX_WAIT_BTN; end if; end case; end if; end process; uartSend <= '1' when (state = TX_SEND_CHAR) else '0'; SX : UART_tx_ctrl generic map(baud => 19200) port map(send => uartSend, data => uartData, clk => clk, ready => uartRdy, uart_tx => RsTx); dbc : debounce port map(clk => clk, btn => btnC, btn_clr => btnCclr); end behavioral; ```
How can I trigger handle_generate_automatic_ticket jQuery function in WooCommerce thank-you.php page instead of manually generating a ticket number?