instruction
stringlengths
0
30k
Since you only want the side menu to show when a left-to-right drag happens on the first tab view, I would suggest applying the drag gesture to the content of view 1 only. And since we are talking about a left-to-right drag, it is probably reasonable to expect it to start on the left-side of the screen. In fact, I would expect that many users will probably "pull" the menu from near the left edge, if they know it's there. The example below uses an overlay that covers just the left-side of view 1. The width of the overlay is half the width of the menu. The overlay has an opacity of 0.001, which makes it effectively invisible, but this allows it to be used for capturing the drag gesture. Here is how the (white) overlay would look if the opacity would be 0.5 instead of 0.001: ![Screenshot](https://i.stack.imgur.com/bMcEE.png) When a drag gesture is detected that starts on the overlay and continues for a minimum of one-quarter of the menu width, the menu is brought into view. Any drag gesture from right-to-left that begins in the uncovered part of the view (on the right) will be handled by the `TabView` in the usual way. When the menu is showing, the overlay expands to cover the full width of the menu, so that any drag that starts over the menu can be detected. Here is how it looks when the opacity is 0.5 instead of 0.001: ![Screenshot](https://i.stack.imgur.com/PyLpU.png) The menu can be hidden again with a drag gesture from right-to-left that begins over the menu. A small part of view 1 is still visible on the right and the menu can also be hidden by tapping in this area. However, if a right-to-left drag gesture begins in this area then it is handled by the `TabView`. This allows view 2 to be brought into view without having to close the menu first. Views 2 and 3 are not impacted by the overlay on view 1, so drag gestures are handled by the `TabView` in the normal way with these views. The updated example is shown below. Some more notes: - A `GeometryReader` is used to measure the width of the screen, instead of using the first window scene as you were doing before. A `GeometryReader` also works on an iPad when split screen is used. - `MainView` is now integrated into `FeedBaseView`, but view 1 has been factored out as a separate view. The side-menu view is unchanged, but I gave it a capitalized name (which is more conventional). - You were applying a blur to view 1 when the menu is showing. This causes the background color of the screen to show through at the edges, so when the background is white, the edges get brighter. To mask this on the left edge where it is connected to the menu, a `zIndex` and also a shadow effect are applied to the menu. - I found that `.animation` modifiers did not seem to work when applied to the content of view1. I don't know why not, but suspect that it may be because the view is nested inside a `TabView`. However, animations work fine when changes are applied `withAnimation`. - I didn't understand what the first responder calls were doing in your original code so I stripped these out. If you really need them then hopefully it is clear where to put them back in. ```swift struct View1WithMenu: View { private let screenWidth: CGFloat private let sideBarWidth: CGFloat @State private var showMenu: Bool = false @GestureState private var dragOffset: CGFloat = 0 init(screenWidth: CGFloat) { self.screenWidth = screenWidth self.sideBarWidth = screenWidth - 90 } private func revealFraction(sideBarWidth: CGFloat) -> CGFloat { showMenu ? 1 : max(0, min(1, dragOffset / (sideBarWidth / 2))) } private var sideMenu: some View { SideMenu() .frame(width: sideBarWidth) .shadow( color: Color(white: 0.2), radius: revealFraction(sideBarWidth: sideBarWidth) * 10 ) .zIndex(1) // to cover the blur at the edge } private var mainContent: some View { ZStack { Color.blue Text("tab 0") } .frame(width: screenWidth) .blur(radius: revealFraction(sideBarWidth: sideBarWidth) * 4) .overlay { Color.black .opacity(revealFraction(sideBarWidth: sideBarWidth) * 0.2) .onTapGesture { if showMenu { UIImpactFeedbackGenerator(style: .light).impactOccurred() withAnimation { showMenu = false } } } } } private var draggableOverlay: some View { Color.white .opacity(0.001) //Change to 0.1 to see it .frame(width: sideBarWidth + (showMenu ? sideBarWidth / 2 : 0)) .gesture( DragGesture(minimumDistance: 1) .updating($dragOffset) { value, state, trans in let minOffset = showMenu ? -sideBarWidth : 0 let maxOffset = showMenu ? 0 : sideBarWidth state = max(minOffset, min(maxOffset, value.translation.width)) } .onEnded { value in withAnimation { showMenu = value.translation.width >= sideBarWidth / 4 } } ) } var body: some View { HStack(spacing: 0) { sideMenu mainContent } .offset(x: showMenu ? sideBarWidth / 2 : -sideBarWidth / 2) .offset(x: dragOffset) .overlay(alignment: .leading) { draggableOverlay } .onDisappear { showMenu = false } } } struct FeedBaseView: View { @State private var selection: Int = 0 var body: some View { GeometryReader { proxy in TabView(selection: $selection) { View1WithMenu(screenWidth: proxy.size.width) .tag(0) ZStack { Color.red Text("tab 1") } .tag(1) ZStack { Color.green Text("tab 2") } .tag(2) } .tabViewStyle(.page) } } } ``` ![Aniamtion](https://i.stack.imgur.com/1Hgp3.gif)
I need to match columns based on contains rather than "on" ```df1 = pd.merge(df_train, df, contains = 'Original_Source')```
Python string contains instead of on
|python|pandas|
TL;DR: `useTheme` + `useMemo` + 'stylesOverrides' I ran into a similar problem. The `styled` function applies its styles to the root of the component, but not to child- or pseudo-elements, which the tooltip is one of. This leaves us with the `sx` prop, which you don't want to use or with `stylesOverrides`. To make the latter reusable, you can provide a speed dial actions theme provider, which overrides the tooltip styles. Following is a similar speed dial component to what I use, so you may need to adapt it to your use case: ```ts import FileCopyIcon from '@mui/icons-material/FileCopyOutlined'; import SpeedDial from '@mui/material/SpeedDial'; import SpeedDialAction from '@mui/material/SpeedDialAction'; import SpeedDialIcon from '@mui/material/SpeedDialIcon'; import { createTheme, ThemeOptions, ThemeProvider, useTheme } from '@mui/material/styles'; import { useMemo } from 'react'; const speedDialActionOverrides: ThemeOptions = { components: { MuiSpeedDialAction: { styleOverrides: { staticTooltipLabel: { whiteSpace: 'nowrap', }, }, }, }, }; const TestDial = () => { // extend the existing theme with some overrides const existingTheme = useTheme(); const theme = useMemo(() => createTheme(existingTheme, speedDialActionOverrides), [existingTheme]); return ( <ThemeProvider theme={theme}> {/* apply the extended theme to this speed dial */} <SpeedDial ariaLabel="Example Speed Dial" icon={<SpeedDialIcon />}> <SpeedDialAction icon={<FileCopyIcon />} tooltipTitle="Copy the File" tooltipOpen /> </SpeedDial> </ThemeProvider> ); }; export default TestDial; ```
I missed the `content-type` part in headers, and language. Also do not use `urllib.parse` because it changes parameter names such as "itemid[0]" to "itemid%5B0%5D" which won't be parsed properly at steam end. The final codes example: conn = http.client.HTTPSConnection("partner.steam-api.com") headers = {'Content-Type': 'application/x-www-form-urlencoded'} orderid = uuid.uuid4().int & (1<<64)-1 print("orderid = ", orderid) key = "xxxxxxxxxxxxxxxxxxx" # omitted for security reason steamid = "xxxxxxxxxxxxxxxxxxx" # omitted for security reason pid = "testItem1" appid = "480" itemcount = 1 currency = 'CNY' amount = 350 language = 'zh-CN' description = 'testing_description' urlSandbox = "/ISteamMicroTxnSandbox/" s = f'{urlSandbox}InitTxn/v3/?key={key}&orderid={orderid}&appid={appid}&steamid={steamid}&itemcount={itemcount}&language={language}&currency={currency}&itemid[0]={pid}&qty[0]={1}&amount[0]={amount}&description[0]={description}' conn.request('POST', url=f'{urlSandbox}InitTxn/v3/', headers=headers, body=s) r = conn.getresponse() print("InitTxn result = ", r.read()) Thought I get to send the HTTPs request in proper format, I still got a 403 error ```b'<html><head><title>Forbidden</title></head><body><h1>Forbidden</h1>Access is denied. Retrying will not help. Please verify your <pre>key=</pre> parameter.</body></html>'```
Calculating EuclideanDistance in SQL for Deepface facial embeddings?
|python|python-3.x|sqlite|deepface|
Have the following scenario. Basically I want to use the item binded sheet init and bind it to an optional property which will be set when we want to show the sheet. On the outside it looks perfectly normal but something interesting I am noticing is that the item property isn't getting deinitialized, which leads to a retain cycle, here is a sample: ```swift class Item: Identifiable { var dismiss: () -> Void init(dismiss: @escaping () -> Void) { self.dismiss = dismiss print("init >> item \(Unmanaged.passUnretained(self).toOpaque())") } deinit { print("deinit >> item \(Unmanaged.passUnretained(self).toOpaque())") } func start() -> some View { ViewTwo(dismiss: dismiss) } } struct ContentView: View { @State private var item: Item? { didSet { print(item) } } var body: some View { Button("Show") { item = Item { item = nil } } .sheet(item: $item) { item in item.start() } } } struct ViewTwo: View { var dismiss: () -> Void var body: some View { VStack { Button("Dismiss") { dismiss() } } } } ```
Sheet binded item doesn't deinitialize SwiftUI
|ios|swift|swiftui|automatic-ref-counting|swiftui-sheet|
I had something in my mind to spice up the code that draw the pixels on the screen about what if I can make a condition that change the ***variable*** (dl register/data stack) value by 1, 2 and 5, then make the code to increase/decrease value by ***variable***. add dx, dl ; something like that Here's the full code, modified by me (OG code from the [video](https://youtu.be/HmoSg5p-AXc?si=Q9T06AqFtxSH1kn8)): bits 16 org 0x7c00 start: cli push 0x0A000 pop es xor di, di xor ax, ax mov ax, 0x13 int 0x10 jmp payload payload: add dl, 1 cmp dl, 3 jg condition mov ah, 0x0c add al, 1 mov bh, 0x00 add cx, 1 add dx, dl ; that's what I tried to do, the assembler gave me an error: incorrect/illegal combination of opcodes and operands int 0x10 jmp payload condition: mov dl, 0 jmp payload times 510 - ($-$$) db 0 dw 0xaa55 Waiting for your answers and feedback.
Seeking for the the method for adding the dl (data stack) value to dx register
|x86|virtualbox|nasm|bootloader|bios|
The problem is that when you use PartialType, it doesn't automatically add the @AutoMap decoration to fields, which you need for AutoMapper. To fix this, make a new file named custom-field-partial-type.ts and copy the code from this link. What the code does is simple: it lets you add custom decorators when you use the applyFields function. This means you can add the @AutoMap decorator, which is important for mapping. Now, you can do things like: ```typescript @InputType('UpdateTodoItemInput') export class UpdateTodoItemInput extends CustomFieldPartialType(CreateTodoItemInput, { customFields(partialObjectType, item) { AutoMap()(partialObjectType.prototype, item.name); // This adds the AutoMap annotation to the field. }, }) {} ``` Or you could even go a little more complex and do: ```typescript @InputType('UpdateTodoItemInput') export class UpdateTodoItemInput extends CustomFieldPartialType(CreateTodoItemInput, { customFields(partialObjectType, item) { if (item.name === 'text') { AutoMap()(partialObjectType.prototype, item.name); } }, }) {} ``` This code only adds the @AutoMap decorator to the "text" field. I have opened an issue on the @nestjs/graphql repository on GitHub, and maybe someone will be able to integrate this into the actual library. Here is the link to the issue: https://github.com/nestjs/graphql/issues/3201
I am looking for the most efficient way to represent small sets of integers in a given range (say 0-10) in Python. In this case, efficiency means fast construction (from an unsorted list), fast query (a couple of queries on each set), and reasonably fast construction of a sorted version (perhaps once per ten sets or so). A priori the candidates are: - use Python's builtin `set` type (fast query) - use a sorted array (perhaps faster to construct?) - use bit-array (fast everything if I was in C... but I doubt Python will be that efficient (?)). Any advice of which one to choose?
``` using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { [SerializeField] private float _enemySpeed = 1f; private float _kamikazeSpeed = 6f; private Player _player; // handle to animator component private Animator _animate; private AudioSource _explosionSX; private float _fireRate = 1.0f; private float _canFire = -1f; private float _enemyFrequency = 1.0f; private float _enemyAmplitude = 5.0f; private float _enemycycleSpeed = 1.0f; private float _enemyAggressive = 3.0f; [SerializeField] float _rayCastRad = 8.5f; [SerializeField] float _rayDistance = 8.0f; private Vector3 _enemyPos; private Vector3 _enemyAxis; [SerializeField] private GameObject _enemyLaser; [SerializeField] private GameObject _shieldVisualizer; private bool _isenemyshieldActive = false; private int _randomshieldedEnemies; [SerializeField] private SpriteRenderer _shieldRenderer; private int _shieldStrengh = 1; private bool _isLaserDetected; // Start is called before the first frame update void Start() { _player = GameObject.Find("Player").GetComponent<Player>(); _explosionSX = GetComponent<AudioSource>(); _enemyPos = transform.position; _enemyAxis = transform.right; _randomshieldedEnemies = Random.Range(0, 7); _enemyAggressive = Random.Range(0, 5); //null check player if (_player == null) { Debug.LogError("The Player is NULL."); } //assign the component _animate = GetComponent<Animator>(); if (_animate == null) { Debug.LogError("The aninator is NULL"); } _randomshieldedEnemies = Random.Range(0, 5); if(_randomshieldedEnemies == 3) { ActiveShield(); } } // Update is called once per frame void Update() { //move down at 4 meters per second //if bottom of screen //respawn at to with a new random x position CalculateMovement(); if (Time.time > _canFire) { _fireRate = Random.Range(1f, 3f); _canFire = Time.time + _fireRate; GameObject enemyFire = Instantiate(_enemyLaser, transform.position, Quaternion.identity); Laser[] lasers = enemyFire.GetComponentsInChildren<Laser>(); } } void CalculateMovement() { transform.Translate(Vector3.down * _enemySpeed * Time.deltaTime); _enemySpeed = Random.Range(3f, 5f); if (transform.position.y < -5f) { float randomX = Random.Range(-15f, 15f); transform.position = new Vector3(randomX, 15, 0); } if (transform.position.x < 1) { _enemyPos += Vector3.down * Time.deltaTime * _enemycycleSpeed; float randomX = Random.Range(-15f, 15f); transform.position = _enemyPos + _enemyAxis * Mathf.Sin(Time.time * _enemyFrequency) * _enemyAmplitude; _enemycycleSpeed = Random.Range(1f, 5.0f); } if(_player != null) { if (Vector3.Distance(transform.position, _player.transform.position)< _enemyAggressive) { KamikazePlayer(); } } } public void ActiveShield() { _isenemyshieldActive = true; _shieldVisualizer.SetActive(true); } private void KamikazePlayer() { if (transform.position.x < _player.transform.position.x) { transform.Translate(Vector3.right * _kamikazeSpeed * Time.deltaTime); } else if (transform.position.x > _player.transform.position.x) { transform.Translate(Vector3.left * _kamikazeSpeed * Time.deltaTime); } else if (transform.position.y > _player.transform.position.y) { transform.Translate(Vector3.down * _kamikazeSpeed * Time.deltaTime); } } private void OnTriggerEnter2D(Collider2D other) { // if other is Player //Destroy Us //damage the player if (other.gameObject.CompareTag("Player")) { //damage player Player player = other.transform.GetComponent<Player>(); if (player != null) { player.Damage(); } _animate.SetTrigger("OnEnemyDeath"); _enemySpeed = 0; _explosionSX.Play(); Destroy(this.gameObject, 2.8f); } //if other is laser //laser //destroy us if (other.gameObject.CompareTag ("Laser")) { if (_player != null) { _player.AddScore(10); } Destroy(other.gameObject); _shieldStrengh--; _shieldVisualizer.SetActive(false); return; } } public void EnemyDeath() { if (_shieldStrengh == 0) { return; } } } ``` This is what I have at the moment my shield does work as intended but, after the shield is destroyed the laser has no effect on the enemy ship. But when I add this ``` _animate.SetTrigger("OnEnemyDeath"); ``` ``` Destroy(this.gameObject, 2.8f); ``` to destroy the ship after the shield is down it will destroy both shield and ship instead what am I doing wrong because I had this working and it just stop so I rewrote it after some more research and still no luck. I was expecting my laser to destroy the shield and enemy separately not at the same time.
Why doesn't my enemy shield take damage first. Instead both enemy and shield are being destroyed together
|c++|unity-game-engine|
null
Based on your question, it seems like you are really new to using Redis as a Vector Database. For that reason, the first thing I suggest is install **redis-stack-server** on an instance outside of kubernetes before you attempt this in a kubernetes environment and verify connectivity of the new ACL feature available since redis 6. `ACLs` allow named users to be created and assigned fine-grained permissions. The advantage of ACLs is it limits certain connections in terms of the commands that can be executed and the keys that can be accessed. A client connecting is required to provide a username and password, and if authentication succeeds, the connection is associated with the given user and the limits the user has. From within the server you installed redis-stack-server, run the redis-cli utility in localhost and validate the default user exists: > ACL LIST "user default on nopass sanitize-payload ~* &* +@all” Here it indicates the default user is active, requires no password, has access to all keys and can access all commands. You can create your own user, and assign them permissions: > ACL SETUSER langchain on >secret allcommands allkeys Here we create a user called langchain, set them as active, defined a password called secret, and gave them access all keys and commands. Note depending if you want to validate this connection eventually outside of a kubernetes cluster, you must understand that protected node is enabled by default, which means outside of the cluster in a different network, you will still face issues connecting. In Rocky Linux, that could be addressed by editing `/etc/redis-stack.conf` and `protected-mode no`. This will disable protected mode. Since version 3.2.0, Redis enters a protected mode when it is executed with the default configuration and without any password. This was designed as a preventative guardrail, thus only allowing replies to queries from the loopback interface. Now with access set up correctly, you can verify connectivity both from the cli and from the Python script directly. From cli: redis-cli -h [host] -p 6379 —user [user] —pass [password] From Python Script: import redis from dotenv import load_dotenv load_dotenv() redis_config = { 'host': os.environ['REDIS_HOST'], 'port': os.environ['REDIS_PORT'], 'decode_responses': True, 'health_check_interval': 30, 'username': os.environ['REDIS_USERNAME'], 'password': os.environ['REDIS_PASSWORD'] } client = redis.Redis(**redis_config) res = client.ping() print(f'PING: {res}’) # >>> PING: True At this point, you should understand the authentication process of using redis-stack-server (which is what is layered in the Docker image redis/redis-stack:latest you referenced in your question). I want to draw your attention to what modules redis-stack-server loads. If you cat that some /etc/redis-stack.conf file, you will see the loaded modules: $ sudo cat /etc/redis-stack.conf port 6379 daemonize no protected-mode no loadmodule /opt/redis-stack/lib/rediscompat.so loadmodule /opt/redis-stack/lib/redisearch.so loadmodule /opt/redis-stack/lib/redistimeseries.so loadmodule /opt/redis-stack/lib/rejson.so loadmodule /opt/redis-stack/lib/redisbloom.so loadmodule /opt/redis-stack/lib/redisgears.so v8-plugin-path /opt/redis-stack/lib/libredisgears_v8_plugin.so I want to draw your attention specifically to **redisearch**. It is a module that extends Redis with **vector similarity search** features. If you check that module’s github page, notice it tags “vector-database”. What does it mean? You can use Redis’s support for Hierarchical Navigable Small World (HNSW) ANN or KNN (K Nearest Neighbor)) for vector embeddings. The bottom line is by installing Redis this way, at least first, you can get a deeper understanding of what it is installing, how what it is installing works, and how it functions as a vector store. Once you grasp those concepts, you can then decide to use your own or the one available in Docker Hub: https://hub.docker.com/r/redis/redis-stack. Either way, you end up with a Docker image that can be deployed in a Kubernetes cluster or preferably outside of the cluster (Kubernetes pods are stateless; **StatefulSet** is an alternative option). But I recommend **keeping the database outside of k8 cluster** (especially since this is the first time you tried this). Now, you would need to configure your application to be deployed in the Kubernetes cluster. In the context of Langchain, you typically use a `document loader` (e.g. from langchain.document_loaders.pdf import PyPDFLoader) to load the raw documents. Then you typically use a `text splitter` to break up the large documents in chunks with a specified chunk size, chunk overlap and separaters (e.g. from langchain.text_splitter import RecursiveCharacterTextSplitter). And then you load the `embeddings model` (e.g. from langchain.embeddings import HuggingFaceEmbeddings). In this example, I am using HuggingFace embeddings. Then you would use the Redis vectorstore that langchain provides: from langchain.document_loaders.pdf import PyPDFLoader from langchain.text_splitters import RecursiveCharacterTextSplitter from langchain.embeddings.huggingface import HuggingFaceEmbeddings from langchain_community.vectorstores.redis import Redis loader = PyPDFLoader(‘path-to-doc’) raw_documents = loader.load() text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=20, separaters=‘\n’) texts = text_splitter.split_documents(documents) rds = Redis.from_texts( texts, embeddings, metadatas=metadata, redis_url=os.environ['REDIS_URL'], index_name="users", ) Hence, our application is using Redis as a vector store. Now build a Docker image out of this. Now this Python application should **be part of your k8 cluster**. It should be deployed in a Deployment with a ReplicaSet that defines the number of pods to run in the Deployment and specify readiness and liveness probes as well to health check the pods in your Deployment. At this point, with the knowledge you now have, you can deploy this in a GKE cluster. [The Deploy an app in a container image to a GKE cluster][1] goes through the specifics of taking the application (in our case the Python app), containerizing the app with Cloud Build, creating a GKE cluster, and deploying to GKE. [1]: https://cloud.google.com/kubernetes-engine/docs/quickstarts/deploy-app-container-image#python_1
Here's a "prettier" version of all this. SpringDoc provides their own static method set to automatically add unresolved schemas to the components (and OpenAPI object respectively), so they can be referenced from other places. ```java import io.swagger.v3.core.util.AnnotationsUtils; @Bean public OpenApiCustomiser errorCustomizer() { return api -> api.getPaths().values().forEach(path -> path.readOperations() .forEach(operation -> addErrorToApi(operation, api.getComponents()))); } private void addErrorToApi(Operation operation, Components components) { MediaType mediaType = new MediaType().schema(AnnotationsUtils.resolveSchemaFromType(Error.class, components, null)); operation.getResponses().addApiResponse("500", new ApiResponse() .description("Unhandled Server Error") .content(APPLICATION_JSON_VALUE, mediaType); } ``` Tested with Java 8 + Spring Boot 2.7.18 + SpringDoc UI 1.8.0, no problems so far.
null
If you're using netframework 3.5, and call web API with https, you should use `ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc0 | 0x300 | 0xc00);` to enable TLS 1.1 and 1.2 to avoid this issue: ```cs public string SendGetRequest(string url) { ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc0 | 0x300 | 0xc00); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } } ```
I am trying to train a custom subclassed tensorflow model. The model takes a (batch_size, nH, nW,1,2) sized tensor as input and outputs a (batch_size, n) output. The training works smoothly if I store the training data as a tensor and feed it to ``` model = custom_model(), model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), loss = tf.keras.losses.MeanAbsoluteError(), ), model.fit(x = train, y = target,epochs=epochs) ``` However, I want to train larger datasets which don't fit in the GPU memory. To this end I define a training pipeline which uses tf.data.Dataset object as follows ``` tf_dataset = tf.data.Dataset.from_tensor_slices((range(100000)))#,range(36000))), tf_dataset = tf_dataset.map(data_pipeline_tf) tf_dataset = tf_dataset.batch(batch_size) ``` Each element of tf_dataset returns (batch_size, nH, nW,1,2) input and (batch_size, n) output I then train the model using ``` model.fit(x = tf_dataset,epochs = epochs) ``` However this gives me the following error ``` if input_shape.dims[channel_axis].value is None: TypeError: 'NoneType' object is not subscriptable ``` The dimensions of tensors retuned in tf_dataset seems to be correct since I get the output with desired shape if I do ``` for el in tf_dataset.take(1): model(el[0]) ``` It seems the problem is when I do model.fit(x = tf_dataset) Basically the exact same problem was reported [here](https://github.com/tensorflow/tensorflow/issues/45533) and [here](https://github.com/keras-team/tf-keras/issues/41) with no satisfactory resolution using the model.fit() method. I am using a Colab notebook with tf version 2.15.0 with a T4 GPU How do I resolve this issue? Any help appreciated. Thanks One of the suggestion was to use run_eagerly = True. That worked when I was testing the above process on CPU but was really slow. I also tried model.build((batch_size, nH, nW,1,2)) after I compiled the model but before calling model.fit(). This however led to another error.
The result of dereferencing a deleted pointer is undefined. That means anything can happen, including having a program appear to work. There is no promise that an exception will be thrown, or that an error message with be displayed.
We have this huge issue as a team in choosing a programming stack to develop a web application for a client, one group prefers Django, while the other prefer Springboot claiming that python is a loosely typed programming language, and that makes it less secure unlike Java. In terms of security is Java better than Python?
Does Python being a loosely typed programming language make it less secure?
|python|java|django|
null
I’m making an in app purchase for my game on Steam. On my server I use python 3. I’m trying to make an https request as follows: conn = http.client.HTTPSConnection("partner.steam-api.com") orderid = uuid.uuid4().int & (1<<64)-1 print("orderid = ", orderid) key = "xxxxxxxxxxxxxxxxxxx" # omitted for security reason steamid = "xxxxxxxxxxxxxxxxxxx" # omitted for security reason pid = "testItem1" appid = "480" itemcount = 1 currency = 'CNY' amount = 350 description = 'testing_description' urlSandbox = "/ISteamMicroTxnSandbox/" s = f'{urlSandbox}InitTxn/v3/?key={key}&orderid={orderid}&appid={appid}&steamid={steamid}&itemcount={itemcount}&currency={currency}&itemid[0]={pid}&qty[0]={1}&amount[0]={amount}&description[0]={description}' print("s = ", s) conn.request('POST', s) r = conn.getresponse() print("InitTxn result = ", r.read()) I checked the s in console, which is: ``` s = /ISteamMicroTxnSandbox/InitTxn/v3/?key=xxxxxxx&orderid=11506775749761176415&appid=480&steamid=xxxxxxxxxxxx&itemcount=1&currency=CNY&itemid[0]=testItem1&qty[0]=1&amount[0]=350&description[0]=testing_description ``` However I got a bad request response: ``` InitTxn result = b"<html><head><title>Bad Request</title></head><body><h1>Bad Request</h1>Required parameter 'orderid' is missing</body></html>" ```` How to solve this? Thank you! BTW I use almost the same way to call GetUserInfo, except changing parameters and replace POST with GET request, and it works well. Just read that I should put parameters in post. So I changed the codes to as follows, but still get the same error of "Required parameter 'orderid' is missing" params = { 'key': key, 'orderid': orderid, 'appid': appid, 'steamid': steamid, 'itemcount': itemcount, 'currency': currency, 'pid': pid, 'qty[0]': 1, 'amount[0]': amount, 'description[0]': description } s = urllib.parse.urlencode(params) # In console: s = key=xxxxx&orderid=9231307508782239594&appid=480&steamid=xxx&itemcount=1&currency=CNY&pid=testItem1&qty%5B0%5D=1&amount%5B0%5D=350&description%5B0%5D=testing_description print("s = ", s) conn.request('POST', url=f'{urlSandbox}InitTxn/v3/', body=s) ==== update ==== Format issue has been solved. Please see the answer below. Thought I get to send the HTTPs request in proper format, I still got a 403 error ```b'<html><head><title>Forbidden</title></head><body><h1>Forbidden</h1>Access is denied. Retrying will not help. Please verify your <pre>key=</pre> parameter.</body></html>'``` If anyone know how to solve this, please let me know, thank you!
null
Consider this: <!-- begin snippet: js hide: false console: false babel: false --> <!-- language: lang-css --> body { margin: 0; padding: 0; font-size: 100%; padding-left: 5em; background-color: #ecf0f1; } #sb { position: fixed; left: 0; top: 0; width: 5em; height: 100%; overflow-y: auto; z-index: 1000; background-color: #3498db; } #contents { margin: 0 auto; max-width: 20rem; background-color: #e67e22; } h1, p { background-color: #f1c40f; } p.large { background-color: #2ecc71; } <!-- language: lang-html --> <body> <div id="sb"></div> <div id="contents"> <h1>hello!</h1> <p> I'm baby slow-carb fam synth swag. Adaptogen farm-to-table air plant kickstarter put a bird on it chillwave authentic 3 wolf. </p> <p class="large"> Four dollar toast post-ironic intelligentsia, aesthetic taiyaki small batch succulents readymade shabby chic portland. </p> <p> Ascot lyft grailed 8-bit mlkshk. Fam cornhole woke tattooed offal hot chicken post-ironic hammock hell of chartreuse pok pok gluten-free leggings marxism. </p> </div> </body> <!-- end snippet --> How can I make the green (`large` class) paragraph as large as `body` (grey part), or at least larger than `#contents`? I tried the ``` position: relative; width: 150%; left: -25%; ``` trick, but you'll see that when you reduce the width of the whole page, the paragraph keeps that large width and adds a horizontal scrollbar, etc. In my situation, I can't control the HTML part, but I can override the CSS part.
How to make an element wider than its container?
|html|css|
Hello Stack Overflow Community, I'm developing a Flutter app with a Google Maps integration. My map is not displaying, even though the API hits are showing up in the Google Cloud Platform console, indicating that the requests are successful. Here's a rundown of what I've done so far: - Verified that my API key is correctly placed in the AndroidManifest.xml. - Set the necessary permissions for location and internet in AndroidManifest.xml. - Tested the app on a emulator. - Ensured the API key is activated for the correct project on the Google Cloud Platform without any restrictions. - Updated to the latest versions of Flutter and the google_maps_flutter plugin. Below is the core code snippet from my implementation in dart: ``` class CirclesPage extends StatefulWidget { const CirclesPage({Key? key}) : super(key: key); @override _CirclesPageState createState() => _CirclesPageState(); } class _CirclesPageState extends State<CirclesPage> { GoogleMapController? _controller; LatLng currentLocation = LatLng(46.8182, 8.2275); // Default to Switzerland @override void initState() { super.initState(); _determinePosition().then((_) => _goToCurrentLocation()); } void _onMapCreated(GoogleMapController controller) { _controller = controller; _goToCurrentLocation(); } Future<void> _goToCurrentLocation() async { if (_controller == null) return; _controller!.animateCamera(CameraUpdate.newLatLngZoom(currentLocation, 15.0)); } Future<void> _determinePosition() async { // Location service check and permission handling logic } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Maps Sample')), body: GoogleMap( onMapCreated: _onMapCreated, myLocationEnabled: true, initialCameraPosition: CameraPosition( target: currentLocation, zoom: 15.0, ), ), ); } } ``` Logs confirm that initState, onMapCreated, and build functions are called, but the screen where the map is supposed to appear remains blank. I would greatly appreciate any suggestions or insights on what I might be missing or what steps I should take next to resolve this issue. Thank you in advance!
I am using following generic interface to select matching key-value pair types of an interface: ```ts interface DefaultParams<T> { screen: keyof T; params?: T[keyof T]; } ``` and I want to use it with this navigation types so that I can pass respectively matching values in my navigate function: ```ts export type RootTabParamList = { Home: undefined | DefaultParams<HomeTabStackParamList>; Health: undefined | DefaultParams<HealthTabStackParamList>; }; export type HomeTabStackParamList = { Dashboard: { tab: 'feed' | 'recommended' }; Activity: undefined; } export type HealthTabStackParamList = { HealthScreen: undefined; SystemsList: undefined; SystemDetailsScreen: { tenetCode: TenetCodes; tenetResult?: string; }; SampleSummaryScreen: { range?: Range; tenetCode: TenetCodes; sampleCode: string; }; }; ``` But it allows me to use both `HomeTabStackParamList` and `HealthTabStackParamList` interchangeably between `Home` and `Health` keys
so i am new at coding and im trying to create a Clicker game. To sum it up its supposed to be like Cookie Clicker. Click something to get a point and with those points buy upgrades. But i ran into a little Problem, i want to create Infinite Upgrades. So that i can buy a Click upgrader a infinite amount of times. But I dont know how i can code that. I havent yet tried anything BUT i have researched. I read allot about Loops but i dont think it would fit because The upgrade part of my Code needs to go up in numbers with the Price of points and the amount of upgrades. Also i would need to somehow Fittingly change the Button Click of the "Cookie" ( cant really explain it well but i basically need to change the code of the thing i click as well ) Here is my COMPLETTE code of the Picture and just the code Picture ``` <Window x:Class="wieso.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:wieso" mc:Ignorable="d" Title="MainWindow" Height="1080" Width="1920" Background="LightCyan" > <Grid AutomationProperties.ItemType="" Margin="0,8,0,-8"> <Button Content="Click Mich!" Margin="812,453,812,462" Click="Button_Click"/> <Label x:Name="ClickAnzahlTEXT" HorizontalAlignment="Left" Margin="1423,0,0,0" VerticalAlignment="Top" Content="du hast so viele Clicks :" Height="43" RenderTransformOrigin="0.974,0.472" FontSize="18" Width="319"/> <Label x:Name="ClickAnzahl" Margin="1571,117,8,821" FontSize="36" Content="" RenderTransformOrigin="1.13,2.154"/> <Button x:Name="knopfding" Content="10 CLICKS FÜR EIN CLICK UPGRADE!" Margin="1508,243,0,719" Click="Button_Click_1"/> </Grid> </Window> Code using System.Linq.Expressions; using System.Printing; using System.Text; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace wieso { public partial class MainWindow : Window { long Score = 0; long Upgrade1 = 1; public MainWindow() { InitializeComponent(); ClickAnzahl.Content = Score.ToString(); } private void Button_Click(object sender, RoutedEventArgs e) { ClickAnzahlTEXT.Content = "du hast so viele Clicks :"; ClickAnzahl.Content = Score.ToString(); if (Upgrade1 == 1) { Score = Score + 1; ClickAnzahl.Content = Score.ToString(); } if (Upgrade1 == 2) { Score = Score + 2; ClickAnzahl.Content = Score.ToString(); } if (Upgrade1 == 3) { Score = Score + 3; ClickAnzahl.Content = Score.ToString(); } } private void Button_Click_1(object sender, RoutedEventArgs e) { if (Upgrade1 == 1 && Score >= 10) { Score -= 10; Upgrade1++; ClickAnzahl.Content = Score.ToString(); knopfding.Content = "50 CLICKS FÜR EIN CLICK UPGRADE!"; } if (Upgrade1 == 2 && Score >= 50) { Score -= 50; Upgrade1++; ClickAnzahl.Content = Score.ToString(); knopfding.Content = "Max Level!"; } } } } ```
{"Voters":[{"Id":6752050,"DisplayName":"273K"}]}
When updating a specific user i want to run ```unique``` validation for fields ```username``` and ```studentNumber``` but against other users not for the same user being updated because its already owned by them, if i use ```unique:users``` only it will cause errors when updating because it will run the validation against the user themselves, so i used ```Rule::unique('users')->ignore($user->id)``` to ignore the user being updated, but i need to pass the ```id``` of the user being updated to the ```Form Request```, how to accomplish that ? ```UserController.php``` ``` public function update(UpdateUserRequest $request, string $id) { try{ DB::table('users')->where('id',$id)->update($request->validated()); }catch(Exception $ex){ return response()->json(['message' => $ex->getMessage()], 409); } } ``` ```UpdateUserRequest.php``` ``` public function rules(): array { return [ 'username' => [ Rule::unique('users')->ignore($user->id), 'string', 'max:255'], 'studentNumber' => [ Rule::unique('users')->ignore($user->id), 'string'], ]; } ```
Laravel get ID of user being update inside Form Request to ignore validation when updating same user
|laravel|laravel-validation|
The problem is that when you use PartialType, it doesn't automatically add the @AutoMap decoration to fields, which you need for AutoMapper. To fix this, make a new file named custom-field-partial-type.ts and copy the code from this link: https://gist.github.com/Copystrike/bfc5010100aba362002616f9eca7fa25 What the code does is simple: it lets you add custom decorators when you use the applyFields function. This means you can add the @AutoMap decorator, which is important for mapping. Now, you can do things like: ```typescript @InputType('UpdateTodoItemInput') export class UpdateTodoItemInput extends CustomFieldPartialType(CreateTodoItemInput, { customFields(partialObjectType, item) { AutoMap()(partialObjectType.prototype, item.name); // This adds the AutoMap annotation to the field. }, }) {} ``` Or you could even go a little more complex and do: ```typescript @InputType('UpdateTodoItemInput') export class UpdateTodoItemInput extends CustomFieldPartialType(CreateTodoItemInput, { customFields(partialObjectType, item) { if (item.name === 'text') { AutoMap()(partialObjectType.prototype, item.name); } }, }) {} ``` This code only adds the @AutoMap decorator to the "text" field. I have opened an issue on the @nestjs/graphql repository on GitHub, and maybe someone will be able to integrate this into the actual library. Here is the link to the issue: https://github.com/nestjs/graphql/issues/3201
|json|sql-server|sql-server-2022|
I would like to create a method that returns an iframe's URL if the parent page is allowed to (because it is under the same domain), and return a falsy value if the parent page is not allowed to do so. I have the following code hosted by https://cjshayward.com: <!DOCTYPE html> <html> <head> </head> <body> <iframe name="test_frame" id="test_frame" src="https://cjshayward.com"></iframe> <script> setTimeout(function() { try { console.log(window.frames.testframe.location.href); } catch(error) { console.log('Not able to load.'); }); }, 1000); </script> </body> </html> The `setTimeout()` is used because if I specify an iframe and then immediately have JavaScript attempt to load the page's URL, it will load a URL of `about:blank`. But when I change the URL to the script in the same place to another domain (that has no restrictions on e.g. loading contents in a frame), Firefox logs the string specified in the catch block, and still logs an uncaught DOMException: <!DOCTYPE html> <html> <head> </head> <body> <iframe name="test_frame" id="test_frame" src="https://orthodoxchurchfathers.com"></iframe> <script> setTimeout(function() { try { console.log(window.frames.testframe.location.href); } catch(error) { console.log('Not able to load.'); }); }, 1000); </script> </body> </html> In the first case, it logs https://cjshayward.com. In the second case, it logs "Not able to load," but still shows an uncaught DOMException in the log. How can I make a function that returns the iframe's location.href if it is available, and returns something falsy like an empty string if the same is not available due to browser security restrictions? Or, taking a slight step back, is the logged DOMException unimportant? If I replace the console.log() calls with return calls from within a function, will my code be able to use the return value as the iframe's URL if such is available and a falsy value if it is not available? TIA,
TypeError: 'NoneType' object is not subscriptable when training with tf.dataset
|tensorflow2.0|tensorflow-datasets|
null
<!-- language-all: sh --> > Why is PowerShell failing when redirecting the output? The reason is that `python` (which underlies `html2text`) - like many other Windows CLIs - modifies its output behavior based on whether the output target is a *console (terminal)* or is _redirected_: * In the *former* case, such CLIs use the _Unicode_ version of the WinAPI [`WriteConsole`](https://learn.microsoft.com/en-us/windows/console/writeconsole) function, meaning that _any_ character from the global [Unicode](https://en.wikipedia.org/wiki/Unicode) alphabet is accepted. * This means that character-encoding problems do _not_ surface in this case, and the output usually _prints_ properly to the console (terminal) - that said, *exotic* Unicode characters may not print properly, necessitating switching to a different _font_. * In the *latter* case, CLIs _are expected to_ respect the legacy Windows _code page_ associated with the current console window, as reflected in the output from `chchp.com` and - by default - in `[Console]::OutputEncoding` inside a PowerShell session: * That is, they *encode* their output based on said code page, and if the text to output contains characters that cannot be represented in that code page - which for non-CJK locales is typically a _single_-byte encoding limited to _256_ characters in total - you'll get error messages like the one you saw. * To avoid this limitation, modern CLIs increasingly encode their output using UTF-8 instead, either by default (e.g., Node.js), or on an _opt-in_ basis (e.g., Python). Notably, Python exhibits nonstandard behavior even by default, by encoding redirected output based on the _ANSI_ code page rather than the _OEM_ code page (both of which are determined by the system's active legacy _system locale_, aka _language for non-Unicode programs_). --- In the context of PowerShell, an external program's (stdout) output is considered _redirected_ (*not* targeting the console/terminal) in one of the following cases: * capturing external-program output in a variable (`$text = wget ...`, as in your case), or using it as part an of _expression_ (e.g., `"foo" + (wget ...)`) * _relaying_ external-program output _via the pipeline_ (e.g., `wget ... | ...`) * in _Windows PowerShell_ and [_PowerShell (Core) 7_](https://github.com/PowerShell/PowerShell/blob/master/README.md) _up to v7.3.x_: also with `>`, the [redirection operator](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Redirection); in *v7.4+*, using `>` directly on an external-program call now _passes the raw bytes through_ to the target file. That is, in all those cases _decoding_ the external program-output comes into play, into _.NET strings_, based on the encoding stored in `[Console]::OutputEncoding`. In the case at hand, this stage wasn't even reached, because Python itself wasn't able to _encode_ its output. --- The **solution** in your case is two-pronged, as suggested by [zett42](https://stackoverflow.com/users/7571258/zett42): * Make sure that `html2text` outputs *UTF-8*-encoded text. * `html2text` is a Python-based script/executable, so (temporarily) set `$env:PYTHONUTF8=1` before invoking it. * Make sure that PowerShell interprets the output as UTF-8: * To that end, (temporarily) set `[Console]::OutputEncoding` to `[System.Text.UTF8Encoding]::new()` To put it all together: ``` $text = & { $prevEnv = $env:PYTHONUTF8 $env:PYTHONUTF8 = 1 $prevEnc = [Console]::OutputEncoding [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new() try { wget.exe -O - https://www.voidtools.com/forum/viewtopic.php?p=36618#p36618 | html2text } finally { $env:PYTHONUTF8 = $prevEnv [Console]::OutputEncoding = $prevEnc } } ```
how to create Infinite Upgrades in a clicker game
|c#|wpf|loops|
null
`app` defined in *app.py* and `app` created within the `client` fixture are **two different `Flask` instances**, and the instance form the fixture doesn't have the route applied via the `@app.route` decorator. The solution is to use the same `app` object from *app.py* in your tests. That obviously means that you would need to change the way the application is configured so that it uses `TestConfig`. Unfortunately, the way I used to configure Flask when I was working with it is too complex to describe in this answer, and I don't have an alternative good solution on hand. Therefore, take the following code sample rather as a crude fix and **NOT as a solid example for production code**: ```python import pytest from app import app as real_app from config import TestConfig @pytest.fixture(scope="session") def app(): # WARNING: existing config keys not specified in TestConfig # would not be removed real_app.config.from_object(TestingConfig) real_app.test_request_context().push() return real_app @pytest.fixture def client(app): with app.test_client() as client: yield client def test_login_get(client): response = client.get("/login") assert response.status_code == 200 ```
I've read countless posts here on StackExchange as well as countless tutorials across the Internet but I seem to be just off from understanding basic `Backbone` use and implementation. I'm attempting to build a custom Twitter timeline using pre-filtered JSON that is generated from a `PHP` file on my work's server. I feel close but I just can't seem to get things to work. At times I'm able to view 20 tweets in my console but am only able to get 1 tweet to render via my template. Here is my current Backbone setup: <!-- language: lang-js --> (function($){ if(!this.hasOwnProperty("app")){ this.app = {}; } app.global = this; app.api = {}; app.api.Tweet = Backbone.Model.extend({ defaults: {} }); app.api.Tweets = Backbone.Collection.extend({ model: usarugby.api.Tweet, url: "https://custom.path.to/api/tweets/index.php", parse: function(data){ return data; } }); app.api.TweetsView = Backbone.View.extend({ el: $('#tweet-wrap'), initialize: function(){ _.bindAll(this, 'render'); this.collection = new app.api.Tweets(); this.collection.bind('reset', function(tweets) { tweets.each(function(){ this.render(); }); }); return this; }, render: function() { this.collection.fetch({ success: function(tweets){ var template = _.template($('#tweet-cloud').html()); $(tweets).each(function(i){ $(this).html(template({ 'pic': tweets.models[i].attributes.user.profile_image_url, 'text': tweets.models[i].attributes.text, 'meta': tweets.models[i].attributes.created_at })); }); $(this.el).append(tweets); } }); } }); new app.api.TweetsView(); }(jQuery)); And here is my current HTML and template: <!-- language: lang-html --> <div id="header-wrap"></div> <div id="tweet-wrap"></div> <script type="text/template" id="tweet-cloud"> <div class="tweet"> <div class="tweet-thumb"><img src="<%= pic %>" /></div> <div class="tweet-text"><%= text %></div> <div class="tweet-metadata"><%= meta %></div> </div> </script> <script> if(!window.app) window.app = {}; </script> I also have a <a href="http://codepen.io/DaveyJake/pen/aZBKMo">`CodePen`</a> available for testing. Any advice would be greatly appreciated.
I am using an api which works but I am having trouble with the location header. The api document states - If a 201 response is returned it means successful and the location of the newly created data in the http response 'location' header. So I get the 201 response but no data. I assume the data is in the location header how to get that data. $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $api_url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); $result = curl_exec($ch);
Just set the major unit to 1 so the axis counts 1 - 8 by 1s. Add to the x-axis setting ``` chart.set_x_axis({'name': 'X Axis'}) ``` ``` chart.set_x_axis({ 'name': 'X Axis', 'major_unit': 1, # set major unit to 1 }) ``` [![Chart with major unit set to 1][1]][1] <br> You could also add a label to the Trend Line like; ``` # Add line series to the chart chart.add_series({ 'categories': '=Sheet1!$C$1:$C$2', # Adjusted for new data range 'values': '=Sheet1!$D$1:$D$2', # Adjusted for new data range 'line': {'type': 'linear'}, # Adding linear trendline 'data_labels': {'value': False, # Add Data Label 'position': 'below', 'category': True, } }) ``` All this is doing is labeling your trend line, with the lower label sitting on the X-Axis.<br> You'll notice the value is set at start and end points but I don't think there is any means to remove the top textbox using Xlsxwriter. It can be removed manually however simply by clicking the textbox twice and then use the delete key.<br> And for that matter you could manually move the bottom textbox to align with the other numbers too if you like [![enter image description here][2]][2] [1]: https://i.stack.imgur.com/cZLFl.png [2]: https://i.stack.imgur.com/wvyu6.png <br> **Other options to add vert line** <br> You could add a vertical line using Error Bars but it doesn't give you any addition features. In fact you would have to use the major unit change to see the 3 on the x-axis value since it has no data label.<br> Apart from that I suppose you could just add a drawing line/textbox on to the Chart.
{"Voters":[{"Id":10855893,"DisplayName":"Nông Minh"}]}
I had a working function to insert a new doc in my database but I reviewed my assignment and the instructions want a function that takes args, when I re-wrote the code I get a type error. (working code) ``` def create(): new_animal = {'animal_id': input('Enter animal_id'), 'rec_num': input('Enter rec_num'), 'age_upon_outcome': input('Enter age_upon_outcome')} print(new_animal) animals_collection = DbTools.db.animals result = animals_collection.insert_one(new_animal) document_id = result.inserted_id print(f"_id of inserted document: {document_id}") print(new_animal) document_to_find = {'_id': ObjectId(document_id)} result = animals_collection.find_one(document_id) print("Found :", document_id) print(result) ``` re wrote to this to align with assignment requirements "Input argument to function will be a set of key/value pairs in the data type acceptable to the MongoDB driver insert API call" (Main.py) ``` import CRUD CRUD new_animal = { 'animal_id': input('Enter animal_id'), 'rec_num': input('Enter rec_num'), 'age_upon_outcome': input('Enter age_upon_outcome')} for key,val in new_animal.items(): CRUD.DbTools.create(key,val) ``` (CRUD.py) ``` def create(key, value): new_animal = {key, value} print(new_animal) animals_collection = DbTools.db.animals result = animals_collection.insert_one(new_animal) document_id = result.inserted_id print(f"_id of inserted document: {document_id}") print(new_animal) document_to_find = {'_id': ObjectId(document_id)} result = animals_collection.find_one(document_id) print("Found :", document_id) print(result) ``` Output: ``` Pinged your deployment. You successfully connected to MongoDB! Enter animal_id111 Enter rec_num222 Enter age_upon_outcome333 {'111', 'animal_id'} Traceback (most recent call last): File "/Users/CS340WS/Main.py", line 28, in <module> CRUD.DbTools.create(key,val) File "/Users/CS340WS/CRUD.py", line 34, in create result = animals_collection.insert_one(new_animal) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/CS340WS/venv/lib/python3.11/site-packages/pymongo/collection.py", line 663, in insert_one common.validate_is_document_type("document", document) File "/Users/CS340WS/venv/lib/python3.11/site-packages/pymongo/common.py", line 552, in validate_is_document_type raise TypeError( TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping ``` I also wrote this to simplify what I was trying to do ``` import sys import test2 new_animal = { 'animal_id': input('Enter animal_id'), 'rec_num': input('Enter rec_num'), 'age_upon_outcome': input('Enter age_upon_outcome')} for key,val in new_animal.items(): test2.i.this(key,val) ``` ``` class i: def this(key, value): new_animal = {key, value} print(new_animal) ``` Output: ``` Enter animal_id111 Enter rec_num222 Enter age_upon_outcome333 {'111', 'animal_id'} {'rec_num', '222'} {'age_upon_outcome', '333'} ```
func runner(_ function: @autoclosure () -> Void) { function() } var myStruct = MyStruct() runner(myStruct.foo()) // Ok runner(myStruct.increase()) // ✅ Ok Not ideal, but better than "impossible"
I am kind of new to Flink and I need to connect an Apache Flink streaming to Apache Kudu as sink 1. the source is a CSV file with X records that has been read from the filesystem 2. the source is a Kafka connector (create a table using Kafka connector and CSV format.) it needs to be in Python (pyflink) can someone help me with a basic example of it or a guild? the docs lack this info related to KUDU
Connect Apache flink with Apache kude as sink
|python|apache-kafka|kudu|pyflink|
I'm trying to understand JWT-based authorization between applications, and it's a bit unclear to me. I have 2 applications: app1 is responsible for user authorization. Upon logging into app1, I receive a JWT token. When I want to retrieve resources from app2, for example, /api/get-data, I send the token in the header. App2 checks the validity of the format (header, payload, and signature), as well as its expiration date. If everything is okay, it sends a request to app1/api/token/verificate to verify the token. Upon receiving confirmation that the token exists, I receive resources from /api/get-data. Do I understand this correctly? Did I miss anything? Is signature verification of the token still needed here?
I'm trying to understand JWT-based authorization between applications
|jwt|
I want to design python web scraping code to scrape these data (https://www.nyc.gov/site/tlc/about/tlc-trip-record-data.page). Here is the code: ``` import os import requests import random import time import pyarrow.parquet as pq from bs4 import BeautifulSoup from urllib.parse import urljoin from fake_useragent import UserAgent # URL de la page contenant les liens vers les datasets base_url = "https://d37ci6vzurychx.cloudfront.net/trip-data/" response = requests.get(base_url) soup = BeautifulSoup(response.text, "html.parser") # Chemin où enregistrer les fichiers download_directory = "C:/Users/flosr/Engineering/Blent.ai Project/datas" # Fonction pour télécharger un fichier avec un en-tête utilisateur aléatoire et une pause aléatoire def download_file(url, file_path): user_agent = UserAgent().random headers = {"User-Agent": user_agent} time.sleep(random.uniform(1, 3)) # Ajouter une pause aléatoire entre 1 et 3 secondes response = requests.get(url, headers=headers) with open(file_path, "w") as f: f.write(response.content) # Parcourir chaque section contenant les liens pour chaque année for section in soup.find_all("div", class_="faq-answers"): year = section.find_previous_sibling("div", class_="faq-questions").text.strip() print(f"Downloading datasets for year {year}...") # Créer un sous-répertoire pour chaque année year_directory = os.path.join(download_directory, year) os.makedirs(year_directory, exist_ok=True) # Télécharger les fichiers pour chaque mois de l'année for link in section.find_all("a"): file_url = urljoin(base_url, link.get("href")) filename = os.path.basename(file_url) file_path = os.path.join(year_directory, filename) # Télécharger le fichier print(f"Downloading {filename}...") download_file(file_url, file_path) # Convertir le fichier Parquet pq.write_table(pq.read_table(file_path), file_path.replace('.parquet', '.csv')) print("Download and conversion complete.") ``` Here is the output : PS C:\Users\flosr\Engineering\Blent.ai Project\datas\WebScraping Code> & 'c:\Users\flosr\Engineering\Blent.ai Project\datas\WebScraping Code\env\Scripts\python.exe' 'c:\Users\flosr\.vscode\extensions\ms-python.debugpy-2024.2.0-win32-x64\bundled\libs\debugpy\adapter/../..\debugpy\launcher' '63645' '--' 'C:\Users\flosr\Engineering\Blent.ai Project\datas\WebScraping Code\env\main.py' Download and conversion complete. However, nothing appears in the said directory. No error appearing but it still doesnt work. and for some reason it never stops installing dependencies below without any end. cant try anything if i dont have any error appearing to know whats the problem
You should never test whether a file or directory exists before trying to do something with it. That has an inherent "race condition": in between the test and the actual action, another process can come in and change things, causing the action to malfunction. "Malfunction" doesn't just mean "fail", this kind of race bug can cause catastrophic damage to unrelated files and/or puncture security. It's such a common and severe bug that it has its very own [CWE](https://cwe.mitre.org/index.html) code, [CWE-367](https://cwe.mitre.org/data/definitions/367.html). What you should do instead is _go ahead and do the thing you want to do_ and see if that _failed_. In this case, you should always try to create the directory, and if it fails with errno code EEXIST ("File exists") then ignore the error and proceed (but don't ignore any other errors). The [`mkdir` shell utility](https://man7.org/linux/man-pages/man1/mkdir.1.html) has a `-p` option that makes it do exactly this, so your test program can be cut down to ``` #include <stdio.h> int main(void) { return system("mkdir -p ~/testdir") ? 1 : 0; } ``` You can do the same thing directly in C using the [`mkdir` _function_](https://man7.org/linux/man-pages/man2/mkdir.2.html) plus an explicit check of errno: ``` #include <errno.h> #include <stdio.h> #include <sys/stat.h> int ensure_directory(const char *name, mode_t mode) { if (mkdir(name, mode) == 0) return 0; if (errno == EEXIST) return 0; if (errno == ENOENT) { // parent directory doesn't exist, recurse up and create it // this is left as an exercise } perror(name); return 1; } ``` However, this will not convert a leading `~` to the name of the user's home directory. In principle you could use [`wordexp`](https://man7.org/linux/man-pages/man3/wordexp.3.html) to do that part without invoking a shell, but it's enough extra work that I would probably stick with `system("mkdir -p ~/testdir")`, _as long as the name of the directory to create is hardcoded_. If any part of `~/testdir` comes from user input (including config files) in your full program, then stuffing it into `system` becomes unsafe and you need to ask a new question about how to safely expand `~` and possibly also `$VARIABLE` without doing any of the other things `wordexp` does.
I'm currently trying to make a Loader for my React application, this loader has a grainy background made with a pseudo-element `::before` which has a background noise image with opacity to make the noise effect. Inside this container, I have 2 logos and a big circle which is a simple svg. At the end of my loading, I simply scale up my circle to fill the entire window and then render my page component. Here's the thing : in Safari, my big circle appears to be a square! and to be slightly transparent! Here's the JSX/CSS of my loader: ```html <div className="z-40 flex items-center justify-center bg-darker-gray grain"> <img ref={logoRef} src={Logo} className="z-50 w-28 absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 opacity-0"/> <img ref={letterLogoRef} src={LetterLogo} className="z-50 h-28 opacity-0 absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2"/> <img className="h-px w-px z-[1000] absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2" ref={bigRoundRef} src={CircleLoader}/> </div> ``` The CSS (grain is my container with noisy background: ```css .grain { position: relative; top: 0; left: 0; height: 100vh; width: 100vw; transform: translateZ(0); pointer-events: none; } .grain:before { content: ""; top: -10rem; left: -10rem; width: calc(100% + 20rem); height: calc(100% + 20rem); z-index: 45; position: absolute; background-image: url(https://upload.wikimedia.org/wikipedia/commons/3/30/256x256_Dissolve_Noise_Texture.png); opacity: 0.1; pointer-events: none; -webkit-animation: noise 1s steps(2) infinite; animation: noise 1s steps(2) infinite; } ``` I tried multiple things, such as 3D transforming my circle to make it go up front or putting an extra `opacity:1;` to it but nothing seemed to change a thing...
How can I catch all DOMExceptions thrown in Firefox?
|javascript|iframe|frames|
I am using react-bootstrap and have a `<Carousel>` that I am using to display images. I'd like for them to be contained within the container, such that the entire image is visible, except for in the case that the aspect ratio is greater than 1:2 (ie really tall images), in which case you can scroll to see the rest of the image. Here is the markup for the carousel: ```JSX <Col xs="6" className="image-carousel-container"> <Carousel activeIndex={activeIndex} onSelect={handleSelect} interval={null} className="image-carousel" > {orderItem.imageNames.map((imageName, index) => ( <Carousel.Item key={index}> <div className="image-container"> <img className="image-carousel-image" src={apiEndpoint + PATH.TEMP_IMAGES + imageName} alt={imageName} /> </div> </Carousel.Item> ))} </Carousel> <p className="image-count-text">{`Total Images: ${orderItem.imageNames.length}`}</p> </Col> ``` And the CSS I have defined: ```CSS .image-carousel-container { display: grid; flex-direction: column; margin: auto; min-height: 100%; height: auto; } .image-carousel { max-width: 100%; max-height: 60vh; display: flex; align-items: center; } .image-container { min-height: 60vh; width: auto; margin: auto; overflow-y: auto; } .image-carousel-image { max-width: 100%; min-width: 50% !important; height: 60vh; object-fit: contain; } ``` So you can see I am attempting to make these "tall images" take up half the width of the container, and then scroll to see the rest of the image. With this configuration, everything works except for the scroll. The `min-width` appears to be ignored, and the tall images are just shrunk to fit the container. If I switch `object-fit: cover`, then the tall images take up half the width, but I have 2 issues: 1. my "wide" images expand to fill the container vertically (I want a max width of 100%). 2. the top and bottom are just truncated, there is no scroll available. Is there a way to get the images to just fit the container and only scroll when necessary (while still taking up half the width of the container)? I have been struggling with this for a while now and none of the existing SO questions appear to address this specific case.
Image needs to maintain width between 50-100% and scroll if aspect ratio is greater than 1:2
{"OriginalQuestionIds":[78239093],"Voters":[{"Id":20860,"DisplayName":"Bill Karwin","BindingReason":{"GoldTagBadge":"mysql"}}]}
Based purely on [this documentation](http://re2c.org/manual/manual_c.html#regular-expressions), a form of lookahead is supported. So: ``` BINARY_NUM = "0b" ("0"|"1") ("_"? ("0"|"1"))* / [^_01] ; ``` or slightly more compactly: ``` BINARY_NUM = "0b" [01]+ ( "_" [01]+ )* / [^_01] ; ``` But you'll need something more sophisticated, as the example above implies: ``` 0b010101010222 ``` would be parsed as `0b010101010` followed by `222`.
{"Voters":[{"Id":10008173,"DisplayName":"David Maze"},{"Id":1940850,"DisplayName":"karel"},{"Id":213269,"DisplayName":"Jonas"}],"SiteSpecificCloseReasonIds":[18]}
{"Voters":[{"Id":10008173,"DisplayName":"David Maze"},{"Id":1940850,"DisplayName":"karel"},{"Id":213269,"DisplayName":"Jonas"}],"SiteSpecificCloseReasonIds":[18]}
you can try this way to ask for camera permission . public class MainActivity extends AppCompatActivity { private static final int PERMISSION_REQUEST_CODE = 100; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (checkPermission()) { //if permission grante } else { requestPermission(); } } private boolean checkPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { // Permission is not granted return false; } return true; } private void requestPermission() { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case PERMISSION_REQUEST_CODE: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_SHORT).show(); // execute logic if permission granted } else { Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_SHORT).show(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { showMessageOKCancel("You need to allow access permissions", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermission(); } } }); } } } break; } } private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) { new AlertDialog.Builder(MainActivity.this) .setMessage(message) .setPositiveButton("OK", okListener) .setNegativeButton("Cancel", null) .create() .show(); } }
The issues are happening as it tries to find some information from a null object and throws. My guess is that your template is trying to load the template before `pokemonDetails` is fully defined, and so it cannot find the values of certain fields. You can wrap your template in `*ngIf` to not show until the value is defined: ```html <div *ngIf="this.pokemonDetails"> ... </div> ``` Alternatively, you can use nullish operators to only go deeper in an object if the object is defined, ie. ```html <div> <p>Pokemon type:</p> <p>{{ this.pokemonDetails?.types[0]?.type?.name }}</p> <p>{{ this.pokemonDetails?.types[1]?.type?.name }}</p> </div> ``` Keep in mind that your template loads immediately and your service does not. The layout in the interim needs to be able to understand what to show.
I am trying to create a specialised photo sharing social network using CloudKit alone. The app will never need to be non iOS, so on the surface Cloudkit has seemed like a perfect backend. However, I've found at random but semi frequent times, the loading of CKAssets from records can be very slow. For example, at normal times, all of the assets can load in a second or less. However at other times, it can take from 5 to 15 seconds. This is on a public database using a fetch operation where I already have the record IDs. Here is my code that performs that: ``` func fetchPhotosForRecords (recordIDS: [CKRecord.ID], completion: @escaping (Result<([CKRecord]?), Error>) -> Void) { mainDatabase.fetch(withRecordIDs: recordIDS, desiredKeys: ["image"]) { results in var recordsToReturn: [CKRecord] = [] switch results { case .success(let success): for (_, result) in success { switch result { case .success(let record): // If the result is success, append the record to the successfulRecords array recordsToReturn.append(record) break case .failure(_): break } } completion(.success(recordsToReturn)) case .failure(let failure): completion(.failure(failure)) } } } ``` Of note, I **have also tried using a database operation** at set the qualityOfService to userInitiated, which has had the same noticeable load times. I have also tested this on different devices, on different networks (both cellular & different WiFi connections) and found also the same noticeable load times at random occurrences. Therefore, what I am trying to find out: - - Is this an expected behaviour from using CloudKit? - Is there a much better way to load CKAssets that would drastically help this load time issue? - Is CloudKit even a viable option for this kind of app, or is it not designed for this type of app? - What alternative approaches could be taken? (Eg. store assets in AWS...) Would truly appreciate any feedback & guidance on this issue.
Is it possible to fix slow CKAsset loading on Cloudkit?
|swift|cloudkit|
Not sure what I'm doing wrong. I cannot work out how to align the widgets on the page of my first tab. I have three tabs: ``` class Home extends StatelessWidget { const Home({Key? key}) : super(key: key); @override Widget build(BuildContext context) { const int tabsCount = 3; return DefaultTabController( initialIndex: 1, length: 3, child: Scaffold( appBar: AppBar( title: Text('TabBar'), bottom: TabBar( tabs: [ Tab( icon: Icon(Icons.cloud_outlined), ), Tab( icon: Icon(Icons.beach_access_sharp), ), Tab( icon: Icon(Icons.brightness_5_sharp), ), ], ), ), body: TabBarView( children: [ Center(child: Widget1()), //this is a full blank page to draw on Center(child: Widget2()), Center(child: Widget3()) ), ], ), ), ); } } ``` But I have `Widget4() //a CheckBoxList() I want to expand from top to bottom of the page` that I want to align down the right side of the first tab page. I tried various version of the below: ``` body: const TabBarView(children: [ Container( child: Align( alignment: Alignment.topRight, child: Widget4(), ), child: Widget1(), ), Widget2(), Widget3() ]), ``` EDIT: I am trying to create this (pardon the rudimentary drawing). The body of the `Tab 1` page has a "canvas feature" that a user can create text boxes in. This is Widget1 and is the majority of the page/screen. Then on the right hand side of the page and extending from bottom to the top of the page is a "Check Box List Widget" that allows a user to add "things to do" and then check them off. Like this: ``` _______ | | | TAB 1 | |_______| _______________________________________________ | | This side is | | | a check list | | | | | | [] item 1 | | | [] item 2 | | | | | This side is the "canvas" | | | | | | | | | | | | | | | | | | | | | | | |_______________________________|______________| ``` I would like for both of them to scroll independently. And I can't work out how to combine Widget1 and Widget4 so they are treated as "one" page when I add them to the body part of `TabBarView` like below: ``` body: const TabBarView(children: [ (Wiget1 + Widget4), Widget2(), Widget3() ]), ``` I haven't created the canvas Widget1. `CheckBoxListWidget` is a straight copy from Flutter docs: ``` ///////////////////////////////////////////////////////////////// // CheckBoxList ///////////////////////////////////////////////////////////////// class LabeledCheckbox extends StatelessWidget { const LabeledCheckbox({ super.key, required this.label, required this.padding, required this.value, required this.onChanged, }); final String label; final EdgeInsets padding; final bool value; final ValueChanged<bool> onChanged; @override Widget build(BuildContext context) { return InkWell( onTap: () { onChanged(!value); }, child: Padding( padding: padding, child: Row( children: <Widget>[ Expanded(child: Text(label)), Checkbox( value: value, onChanged: (bool? newValue) { onChanged(newValue!); }, ), ], ), ), ); } } class CheckBoxWidget extends StatefulWidget { const CheckBoxWidget({super.key}); @override State<CheckBoxWidget> createState() => _CheckBoxWidgetState(); } class _CheckBoxWidgetState extends State<CheckBoxWidget> { bool _isSelected = false; @override Widget build(BuildContext context) { return LabeledCheckbox( label: 'This is the label text', padding: const EdgeInsets.symmetric(horizontal: 20.0), value: _isSelected, onChanged: (bool newValue) { setState(() { _isSelected = newValue; }); }, ); } } ``` Do I use a `row` and split the two widgets? do I use two separate `sized boxes`, `stacked`, `container`??
Flutter: Align two widgets on a single TabBarView page
I have decided to go with Realm's built-in features that are created especially for SwiftUI. Therefore in every view which ViewModel's should have Realm's data I implemented @ObservedResults(ConversationObject.self) var conversationsObjects It is then passed to ViewModel with modifier .onChange(of: conversationsObjects) { _, updatedConversationsObjects in chatViewModel.getConversations(from: updatedConversationsObjects) } Later, the method `getConversations` converts it from Realm Object to my other structure that is assigned to `@Published var` and this data is displayed on screen The same technique is applied to **SettingsObjects**, **SettingsView** and **SettingsViewModel** respectively. By using this approach I was able to get automatically refreshing Realm data I want.
|java|neovim|java-21|
You can route stderr output to a temp file and then read the content of the temp file to get the log output and match it against the expected output. Example: ``` func TestNewLogger(t *testing.T) { // create a temporary file to redirect stderr file, err := os.CreateTemp(".", "temp") assert.NoError(t, err) defer os.Remove(file.Name()) os.Stderr = file // init the logger as normal logger, err := NewLogger(zapcore.DebugLevel, "test") assert.NoError(t, err) logger.Info("test") // read the file content for testing logOut, err := os.ReadFile(file.Name()) assert.NoError(t, err) assert.Regexp(t, `{"level":"info","ts":.*,"logger":"test","caller":".*","msg":"test","INITIAL_FIELD":"INITIAL_FIELD_VALUE"}`, string(logOut)) } ```
{"Voters":[{"Id":9952196,"DisplayName":"Shawn"},{"Id":2320961,"DisplayName":"Nic3500"},{"Id":4850040,"DisplayName":"Toby Speight"}],"SiteSpecificCloseReasonIds":[18]}
{"OriginalQuestionIds":[25585401],"Voters":[{"Id":147356,"DisplayName":"larsks"},{"Id":509868,"DisplayName":"anatolyg"},{"Id":354577,"DisplayName":"Chris","BindingReason":{"GoldTagBadge":"python"}}]}
{"Voters":[{"Id":9952196,"DisplayName":"Shawn"},{"Id":794749,"DisplayName":"gre_gor"},{"Id":4850040,"DisplayName":"Toby Speight"}],"SiteSpecificCloseReasonIds":[18]}
so i am new at coding and im trying to create a Clicker game. To sum it up its supposed to be like Cookie Clicker. Click something to get a point and with those points buy upgrades. But i ran into a little Problem, i want to create Infinite Upgrades. So that i can buy a Click upgrader a infinite amount of times. But I dont know how i can code that. I havent yet tried anything BUT i have researched. I read allot about Loops but i dont think it would fit because The upgrade part of my Code needs to go up in numbers with the Price of points and the amount of upgrades. Also i would need to somehow Fittingly change the Button Click of the "Cookie" ( cant really explain it well but i basically need to change the code of the thing i click as well ) Here is my code ``` using System.Linq.Expressions; using System.Printing; using System.Text; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace wieso { public partial class MainWindow : Window { long Score = 0; long Upgrade1 = 1; public MainWindow() { InitializeComponent(); ClickAnzahl.Content = Score.ToString(); } private void Button_Click(object sender, RoutedEventArgs e) { ClickAnzahlTEXT.Content = "du hast so viele Clicks :"; ClickAnzahl.Content = Score.ToString(); if (Upgrade1 == 1) { Score = Score + 1; ClickAnzahl.Content = Score.ToString(); } if (Upgrade1 == 2) { Score = Score + 2; ClickAnzahl.Content = Score.ToString(); } if (Upgrade1 == 3) { Score = Score + 3; ClickAnzahl.Content = Score.ToString(); } } private void Button_Click_1(object sender, RoutedEventArgs e) { if (Upgrade1 == 1 && Score >= 10) { Score -= 10; Upgrade1++; ClickAnzahl.Content = Score.ToString(); knopfding.Content = "50 CLICKS FÜR EIN CLICK UPGRADE!"; } if (Upgrade1 == 2 && Score >= 50) { Score -= 50; Upgrade1++; ClickAnzahl.Content = Score.ToString(); knopfding.Content = "Max Level!"; } } } } ```
This is [a bug of an old version][1] that used `async` as a variable name, which became a Python keyword on version 3.7. Just install the latest version of Tensorflow ([currently 2.15.0.post1][2]) and this should be fixed. [1]: https://github.com/tensorflow/tensorflow/issues/20690 [2]: https://pypi.org/project/tensorflow/
I have written a simple C program to solve UVA482 on an Online Judge. The program runs successfully on local tests and other platforms; however, I encounter a Runtime Error on the Online Judge. Here is my code: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char ch, permute[1001][101], ans[1001][101]; int i, j, testcases, pos[101]; scanf("%d", &testcases); while (testcases--) { ch = '\0'; for (i = 0; ch != '\n'; i++) { scanf("%d", &pos[i]); ch = getchar(); } for (j = 0; j < i; j++) { scanf("%s", permute[j]); } for (j = 0; j < i; j++) { strcpy(ans[pos[j] - 1], permute[j]); } for (j = 0; j < i; j++) { printf("%s\n", ans[j]); } if (testcases != 0) { printf("\n"); } memset(permute, 0, sizeof(permute)); memset(ans, 0, sizeof(ans)); memset(pos, 0, sizeof(pos)); } return 0; } ``` Can someone help me identify the issue or suggest other potential causes for the Runtime Error? Thank you! I encountered a Runtime Error on the Online Judge (Problem ID: UVA482). I tested locally, used memset for memory reset, and ensured compiler compatibility. Expected successful execution but still facing issues. Can anyone help identify the problem? Thank you!
Runtime Error in C program on Online Judge (Problem ID: UVA482), seeking assistance
|c|runtime-error|
null
as mentioned above you should add the audio file in the pubspec.ymal and need to run pub get to update the file. I’m updating my mediation app too, may I know if you try to play the audio in background/ lock screen? I used other package and really want to move to just audio and audio service if they support these features.
A nice tool, that also works offline is the thonny (debugging) editor. Start the action "Debug Current Script" and then let the students "Step Over" each line of code as it is highlighted. Values of output variable will appear in a right hand tab, while the output of all print statements would appear over the "Shell" window. <img> [thonny editor in action][1] [1]: https://i.stack.imgur.com/0a6UW.png
MacOS 12.7.2 I have a program that uses dlopen to load a dylib, it need DYLD_LIBRARY_PATH set to find it. But when I try to put the command in a shell script if fails because DYLD_LIBRARY_PATH is not inherited. Every other environment variable is. ``` ~/felix-lang.github.io>cat xx.sh echo $DYLD_LIBRARY_PATH ~/felix-lang.github.io>sh xx.sh ~/felix-lang.github.io>echo $DYLD_LIBRARY_PATH /Users/skaller/felix/build/release/host/lib/rtl ``` The dlopen uses a simple relative name so searching in the path is essential. Any clues what is going on? This is a workaround: ``` export XX=$DYLD_LIBRARY_PATH ~/felix-lang.github.io>cat xx.sh export DYLD_LIBRARY_PATH=$XX echo $DYLD_LIBRARY_PATH ``` That actually works, i.e. my program runs fine. But I shouldn't need to do this. ---- EDIT ---- Here is more data and tests thanks to @Charles Duffy. ``` ~/felix-lang.github.io>declare -p DYLD_LIBRARY_PATH declare -x DYLD_LIBRARY_PATH="/Users/skaller/felix/build/release/host/lib/rtl" ``` However ``` ~/felix-lang.github.io>printenv | grep LIBRARY CAML_LD_LIBRARY_PATH=/Users/skaller/.opam/5.1.1/lib/stublibs:/Users/skaller/.opam/5.1.1/lib/ocaml/stublibs:/Users/skaller/.opam/5.1.1/lib/ocaml LD_LIBRARY_PATH=/Users/skaller/felix/build/release/host/lib/rtl ``` `printenv` doesn't show it. It can be exported in the current terminal and is STILL not inherited in a subshell. ``` ~/felix-lang.github.io>export DYLD_LIBRARY_PATH="HelloWorld" ~/felix-lang.github.io>sh ~/felix-lang.github.io>echo $DYLD_LIBRARY_PATH ~/felix-lang.github.io> ``` Finally here is a quote from a man page that explains things and says explicitly DYLD_LIBRARY_PATH is an environment variable. > In general, dyld does not search for dylibs. Dylibs are specified via a > full path, either as a static dependent dylib in a mach-o file, or as a > path passed to dlopen() , But during development the env vars > DYLD_LIBRARY_PATH and DYLD_FRAMEWORK_PATH can be used to override the > specified path and look for the leaf framework/dylib name in the specified > directories. In most development you link against an installed library so the variable is not required. The lack of searching is a security measure to prevent hijacking. For `dlopen` you should give the full path. But my policy is to give only the basename of the path and let the system search because the program doesn't, in fact, know where plugins live, and indeed you might want to replace one (that is, allow hijacking). This is just to explain how the issue arises: I didn't want to write my own search procedure just to find an absolute pathname for `dlopen`.
All three functions give different result due to them having different algorithm for floating points sumation. The reason why for the difference is that floating point representation in computer program have limited precision and different algorithm is needed depending on the trade offs between performance and precision. You can learn more about the implementation of floating points operations in [this answer](https://stackoverflow.com/a/588014/7375347) - `sum += x` approach use regular approach of adding up the approximation value represented by the program. This approach is the most computationally efficient but also the most inaccurate. - `df[`value`].sum()` use [np.sum()](https://numpy.org/doc/stable/reference/generated/numpy.sum.html) under the hood which uses [pairwise summation algorithm](https://en.wikipedia.org/wiki/Pairwise_summation) . This approach is more accurate than regular sum operation but slower runtime - `math.fsum` is the most accurate algorithm for summation of floating points but also the most inefficient. You can learn more about its implementation [here](https://github.com/python/cpython/blob/main/Modules/mathmodule.c#L1321)
Actually there seems to be a misconception about ```cv2.imread()```, cv2 reads the image in BGR format Yes, **but** when prompted to save the image or showing it using ```cv2.imshow``` it correctly renders them, the problem is in matplotlib partially. Because cv2 uses BGR color format and matplotlib uses RGB color format. So what are essentially doing is : 1. Load an image in BGR 2. Convert the image into RGB 3. Save it as RGB. 4. Load it again as BGR 5. Viewing it inverted with matplotlib. A better solution would be to remove ```image3``` as below : ```Python from matplotlib import pyplot as plt import cv2 image1 = cv2.imread('rgb.png') image2 = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB) cv2.imwrite('test_img_bgr_cv.png', image2) plt.figure(figsize=(10, 10)) plt.subplot(1, 3, 1) plt.imshow(image1) plt.title('Image 1') plt.figure(figsize=(10, 10)) plt.subplot(1, 3, 2) plt.imshow(image2) plt.title('Image 1') plt.show() ```