instruction
stringlengths
0
30k
As the title says, I use next-sanity for my Next.js blog. I recently wanted to update all npm packages. Now I can´t run `npm run build` as the one of the dependncies itself throws a type error as follows: ```console ./node_modules/@sanity/types/lib/dts/src/index.d.ts:756:3 Type error: Type parameter declaration expected. 754 | */ 755 | export declare function defineArrayMember< > 756 | const TType extends string | IntrinsicTypeName, // IntrinsicTypeName here improves autocompletion in _some_ IDEs (not VS Code atm) | ^ 757 | const TName extends string, 758 | TSelect extends Record<string, string> | undefined, 759 | TPrepareValue extends Record<keyof TSelect, any> | undefined, ``` I tried manually adding older versions of the package in question but I could not find a suitable solution so far. Deleting node_modules or package.json and then running `npm i`again also did nothing to change the outcome. Has anyone also had the same problem? I had this problem after I ran `npm update`, then I fixed the issues due to some changes mentioned in the docs. But the main issue is, that previously normally functioning features are not working despite no change inside the docs suggesting I did something wrong.
Sanity npm package throws type error on build
|typescript|next.js|sanity|
null
I have my own little graph class and I want to create a graph by reading in a file, containing the necessary information like number of vertices, edges, etc. The files are in the STP format. The code works fine, if I just read in the file word by word. Now I need to identify certain keywords like "Nodes", followed by the number of vertices. When reaching such a keyword, I read in the next word which I then store as the number of vertices. This results in a segmentation fault Here's the code: ``` #include <iostream> #include <fstream> #include <sstream> #include <string> #include "graph2.h" Graph readin(char const * filename) { Graph mygraph(0); std::ifstream file (filename); if (not file) throw std::runtime_error("Couldn't open file."); std::string line, word; int head, tail; // magic password std::getline(file,line); if (line == "33D32945 STP File, STP Format Version 1.0") { while (file >> word) { if (word == "Nodes") { file >> mygraph.numvertices; } else if (word == "E") { file >> tail; file >> head; mygraph.edge(tail,head,Graph::add); } else if (word == "EOF") break; } } else throw std::runtime_error("File is not in STP file format."); return mygraph; } int main(int argc, char* argv[]) { if (argc > 1) { Graph mygraph = readin(argv[1]); mygraph.print(); } return 0; } It works fine like that: if (line == "33D32945 STP File, STP Format Version 1.0") { while (file >> word) { std::cout << word << std::endl; } } ``` Anybody got any idea?
segmentation fault while reading in text file ( c++ )
|c++|file|segmentation-fault|
null
<!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> function palendrom(str){ let data = str.split(" ") let res = []; for(let a=0; a<data.length; a++){ let rev = ''; let subStr = data[a]; for(let i = subStr.length-1; i >= 0; i--){ rev += subStr[i] } rev === subStr ? res.push(subStr) : ""; } return res.reduce((acc, item)=> acc.length > item.length ? acc : item, '') } console.log(palendrom("RajaR ama test")) <!-- end snippet --> <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> function palendrom(str){ let data = str.split(" ") let res = []; for(let a=0; a<data.length; a++){ let rev = ''; let subStr = data[a]; for(let i = subStr.length-1; i >= 0; i--){ rev += subStr[i] } rev === subStr ? res.push(subStr) : ""; } return res.reduce((acc, item)=> acc.length > item.length ? acc : item, '') } console.log(palendrom("That trip with a kayak was quite an adventure!")) <!-- end snippet -->
I have to click on "choose File" button and it opens the fileopen dialog. I need to check if file exists or not. Here is the code ```cs public static void UploadFile(IWebDriver driver, string photoLocation, string photoName) { driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20); IJavaScriptExecutor js = (IJavaScriptExecutor)driver; js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight)"); IWebElement element = driver.FindElement(By.XPath("//*[text() ='Choose File']")); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30); js.ExecuteScript("arguments[0].click();", element); // using "HandleOpenDialog" to locate and upload file HandleOpenDialog hndOpen = new HandleOpenDialog(); hndOpen.fileOpenDialog(photoLocation, photoName); Thread.Sleep(3000); } ``` This code works properly if the file exists in the location. if it doesn't exists, i want code to look someplace else. The test is stuck there for long time and fails the test. Can someone help me here?
I don't understand why My http PUT requests can't send data back to the database even though I checked in the console and made sure the data has changed. ``` import React, { useEffect, useState } from 'react' import './Win_Put_Data.css' import axios from 'axios' const Win_Put_Data = ({databaseRow}) => { const [post, setPost] = useState({ _id: {}, name: '', }); console.log("post test",post,databaseRow) useEffect(() => { setPost(databaseRow) },[]) const handlechange= (e) => { const dataClone = {...post} dataClone[e.target.name] = e.target.value; setPost(dataClone) console.log("setpost",post,post.name) } const putdata = (e,id) => { e.preventDefault(); axios.put(`http://localhost:5000/Data_Product/${id}`,{post}) .then((res) => console.log('true',res,post)) .catch((err) => console.log(err)) } return ( <div> <div className='model-container'> <div className='model'>Solve_Data <form> <div className='form-group'> <label htmlFor='ID'>ID</label> {/* <input name='ID' value={i.id}/> */} </div> <div className='form-group'> <label htmlFor='NAME'>NAME</label> <input type='text' name='name' onChange={handlechange} value={post.name} /> </div> <div className='form-group'> <label htmlFor='PRICE'>PRICE</label> {/* <input type='text' name='PRICE' value={prices}/> */} </div> <div className='form-group'> <label htmlFor='QUANTITY'>QUANTITY</label> {/* <input name='QUANTITY' value={i.quantity}/> */} </div> <button type='submit' className='btn' onClick={(e) => {putdata(e,post._id)}}>Submit</button> </form> </div> </div> </div> ) } export default Win_Put_Data ``` The frontend I'm using is react, backend is js and database is mongodb. I've tried testing the system in the console by comparing the post interpreter with the databaseRow interpreter. Done and make sure the data has been changed. Of course, the console when doing the PUT requests had the data changed but it wasn't recorded in the database at all. Right now I have 4 pieces of data, but I'm only testing one. Pretty sure this has nothing to do with the error I'm experiencing right now. Because the data in the post translator has no empty fields, even the param.id field. databaseRow interpreter Taken from the GET requests information from the previous page. I want to solve this problem by using axios and don't want to use fetch. But if really can't. I can switch to fetch. If this is an easy problem for you guys, I apologize here.
I have a domain model of user where I store `original` user state and `current`. If property from current state doesn't match original - it needs to be updated in database and included in sql query. Creating similar compare methods for each property becomes repetitive and I wanted to know, is there a way to replace this compare methods with some generic shared one? Note: original can be changed to non-optional if it will be simpler to implement. It is used to distinguish insert vs update sql operation for just created model [Playground][1] ``` #[derive(Debug, Clone)] struct UserProps { pub age: i32, pub name: String, } struct User { pub original: Option<UserProps>, pub current: UserProps, } impl User { // creating similar function for each property is burthersome // is there a way to create a generic one? pub fn age_changed(&self) -> bool { self.original .as_ref() .map_or(true, |val| val.age != self.current.age) } pub fn name_changed(&self) -> bool { self.original .as_ref() .map_or(true, |val| val.name != self.current.name) } } fn x() { let props = UserProps { age: 12, name: "x".to_owned(), }; let mut user = User { original: Some(props.clone()), current: props.clone(), }; user.current.age = 22; assert!(user.age_changed()); if user.age_changed() { // add property to sql query update operation } } ``` For exmaple in javascript I would do something like this: ``` propertyChanged(propName: string): boolean { if (this.original === undefined){ return true } return this.original[propName] !== this.current[propName] } ``` [1]: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=473af167f37d54769bc567797c15d9d1
I started gVim lately in offline window pc. Specification is below... gVim - 9.1.0211 -64bit python - windows embedded 3.11.8 (pandas 2.2.1) - 64bit vimrc - filetype plugin indent on &_ set omnifunc=syntaxcomplete#Complete After typing "import pandas as pd pd.", I pressed <C-x><C-o> then it shows "pattern not matched" So I tested in vim ":echo has("python3") then it returns 1" And ":python3 import pandas" then it says "ImportError: DLL load failed while importing aggregations" In terminal, pandas is normally imported (python3 >> import pandas as pd >> ...) Import numpy and omnifunc works well, modules related to pandas doesn't work. I installed vc_redist.64x but not solved. Has anyone this problem like this? I need some help, Thanks. since my pc is local (no internet connection) and remote environment, so I don't have any verbose. sorry. 1. Check c:\windows\system32 and found msvcp140.dll and concrt140.dll 2. Install jedi-vim and failed load module(pandas) but after quit the error message autocompleting works partially and the error occurs again and again 3. Try Neovim (installed pynvim) and omnifunc works
vim python omnifunc not working some modules
|pandas|vim|
null
I used this code snippet inside one of my useEffect hooks. But it mutates the object and shows me the message to be appeared twice. setConversations((prev) => { const oldConversation = room in prev ? prev[room] : []; const newConversation = [ ...oldConversation, { sender: from, message: msg, time: new Date().toLocaleString(), }, ]; return { ...prev, [room]: newConversation }; }); What am I missing? Any suggestions would be much appreciated.
Recently, I've been trying to learn ARM assembly (ARM because my Mac can run it), but all the tutorials and recources that I can find all have slightly different variations, and the version that I have working is different again! Some of the versions I've seen have `.section .text` and `.section .data`, and other websites have a bunch of `svc` calls (or whatever they're called) that are completly different for what I have. I haven't found any places that have code that works with me (except [this video](https://www.youtube.com/watch?v=d0OXp0zqIo0), but I already know how to do everything in it) Here's my hello world program that runs on my laptop: ``` // Print 'Hello, world!" to stdout" .global _main .p2align 3 // no bus error idk _main: // Print 'Hello, world!' mov x0, #1 // Use file stdout mov x16, #4 // Write to stdout adr x1, message // Address of message to print mov x2, #13 // Length of message svc 0 // Execute // Exit mov x0, #0 // Move return code to register 0 mov x16, #1 // Service command code 1 terminates this program svc 0 // Call service call 0 (exit program) message: .ascii "Hello, world!" ``` Input to terminal: ```zsh user@laptop folder % make src=helloWorld as -o helloWorld.o helloWorld.s ld -o helloWorld helloWorld.o make clean rm *.o user@laptop folder % ./helloWorld Hello, world!% ``` In summary, I need some sources that can teach me how to write assembly for my M1 Mac (2020 touchbar)
Which version of ARM does the M1 chip run on?
|assembly|arm|
null
|google-apps-script|libraries|external|luxon|
|google-apps-script|momentjs|libraries|external|
1. How can I run a bat file in tablet? 2. if not, have any file can instead bat file to run in tablet? I want to run a website by **bat** file in tablet. because don't want customer using tablet to run other application. It allow a web pop-up window.
Is there BAT file can run in TABLET?
|tablet|
null
Here the pg_available_extensions word is selected: ![enter image description here](https://i.stack.imgur.com/nWtnd.png) The selection is not visible I tried to find a configuration parameter that would address this issue and could not find one. I lost hours trying to fix this as there are behavior associated to selected text that I use all the time. This issue makes the whole application unusable to me. The following image has the word configuration selected with a blue background: [enter image description here][1] [1]: https://i.stack.imgur.com/7Y9ed.png
I have a dataset with 3 variables: `test_date`, `unique_ID`, and `location`, which provides location of testing and can be either `"department"` or `"practice"`. I want to exclude data from my dataset if the unique ID is present for more than one occasion within a 30 day period. Also the location must be `"practice"`.
{"Voters":[{"Id":874188,"DisplayName":"tripleee"},{"Id":286934,"DisplayName":"Progman"},{"Id":354577,"DisplayName":"Chris"}],"SiteSpecificCloseReasonIds":[18]}
How to have multiple rules file on Loki (Kubernetes)?
|prometheus|grafana-loki|observability|
React Native developers are frequently confronted with the decision between utilizing Expo CLI or opting for a bare React Native app. Expo CLI offers a streamlined development experience, bundling essential tools and components to expedite the development process. It simplifies tasks such as project setup, deployment, and managing dependencies, making it an attractive option for developers aiming for rapid prototyping and straightforward development cycles. On the other hand, building a bare React Native app provides developers with more control and flexibility over the project configuration. With a bare React Native setup, developers have direct access to native modules and can customize the project according to specific requirements. This approach is favored by developers seeking fine-grained control over their applications and aiming for optimized performance. Considering these core concepts and major advantages of both sides, it prompts several questions for discussion: - What specific projects or use cases do you find Expo CLI most suitable for? - In what scenarios do you prefer developing bare React Native apps over utilizing Expo CLI? - Have you encountered any limitations or drawbacks while using Expo CLI or developing bare React Native apps? - How do considerations such as project complexity, performance requirements, and ecosystem integrations influence your choice between Expo CLI and bare React Native development? - What are some best practices or tips you would recommend to developers making the decision between Expo CLI and bare React Native apps?
Which is better for developers to develop? React Native with expo CLI or Bare React Native app.
|android|expo|hybrid-mobile-app|ios|react-native|
I need to set the value of a boolean to True if the value of any order_line is 11, however it does not work if I set the line using "l.route_id == 11", if I set the line to "lambda l: l.route_id" it works but it could have other number different than 11. route_id will be Null usually. The database format of route_id is int4 ``` def _compute_dropship_notes_ind(self): for order in self: # Check if any line has dropshipping activated any_dropship_lines = order.order_line.filtered(lambda l: l.route_id ) #any_dropship_lines = order.order_line.filtered(lambda l: l.route_id == 11) order.dropship_notes_ind = bool(any_dropship_lines) ``` If I use this line --> `any_dropship_lines = order.order_line.filtered(lambda l: l.route_id == 11)` order.dropship_notes_ind will be False But if I use `any_dropship_lines = order.order_line.filtered(lambda l: l.route_id)` order.dropship_notes_ind will be True The values in the database for that column and that order are 11 and Null, a mix of both of them. route_id is a foreign key also.
Comparing value from a foreign key in Odoo
|python|mysql|odoo|
null
I'm trying to set up a conversation ender for my botpress bot. So anytime the user would type end, a workflow should be triggered that will end the conversation. I've tried to add intents, triggers... but nothing seems to work.
Updating objects of key array pairs without mutation
|reactjs|react-hooks|
After going through the replies and reading the official documentation extensively, I found that the @annotation value requires the custom annotation's object rather than class. Ref - https://docs.spring.io/spring-framework/docs/2.5.x/reference/aop.html#aop-ataspectj-around-advice (Heading 6.2.4) so my Aspect class becomes -> @Aspect @Component public class AuthAspect { private static final Logger logger = LoggerFactory.getLogger(AuthAspect.class); @Autowired PtbUtils ptbUtils; @Around("@annotation(validateUser)") public Object authValidation(ProceedingJoinPoint joinPoint, ValidateUser validateUser) throws Throwable { logger.info("Inside authValidation class"); String headerName = validateUser.headerName().isEmpty() ? HttpHeaders.AUTHORIZATION : validateUser.headerName(); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); logger.info("headerName = " + headerName); logger.info("request = " + request); String token = request.getHeader(headerName); logger.info("token = " + token); Boolean value = ptbUtils.validateJwtToken(token); System.out.println("value = " + value); return joinPoint.proceed(); } } Edit - The fix initial issue as highlighted in my question, it required removing the @Component tag from @interface. After removing @Component from @interface and then adding it to the Aspect class, it gave a new error - error at::0 formal unbound in pointcut To fix that, the solution provided before "Edit" worked.
{"OriginalQuestionIds":[73754664],"Voters":[{"Id":17865804,"DisplayName":"Chris","BindingReason":{"GoldTagBadge":"fastapi"}}]}
`props<{ value: number }>()` it's generics, not an embedded DSL. You get that error because `{ value = 0 }` is not a valid type. `{ value: 0 }` is, but it means that `value` is always `0`. If you want to signify that there's a default value, use `props<{ value?: number }>()` or `props<{ value?: number|0 }>()`. Then in your reducer you can have something like: export const myReducer = createReducer( initialState, // [...] on(set, (state, { value = 0 } = {}) => { /* [...] */ }), // [...] )
Add a Box element inside of the Card element and use the minHeight property: https://polaris.shopify.com/components/layout-and-structure/box Your layout section should look something like this. If you have three of these Layout.Sections next to each other, they would all have the same height unless one extends pass the minHeight. <Layout.Section variant="oneThird"> <Card> <Box minHeight="460px"> <BlockStack gap="500"> <Text as="h2" variant="headingMd"> Small Header </Text> <Text as="h3" variant="headingXl"> Big Header </Text> <Text variant="bodyMd"> Body Text </Text> </BlockStack> </Box> </Card> </Layout.Section>
Why I Cann't use PUT requests?
|reactjs|react-native|http|frontend|put|
null
Within the function `sumAtBis` int sumAtBis(tree a, int n, int i){ if(i==n){ if(isEmpty(a)) return 0; else return root(a); } return sumAtBis(left(a),n,i+1)+sumAtBis(right(a),n,i+1); } there is no check whether `left( a )` or `right( a )` are null pointers. So the function can invoke undefined behavior.
Here is what I implemented form last time and this code is working for most of my test cases but it is not working for these cases. ``` #include <climits> #include <cmath> #include <iostream> #include <limits> #include <stdexcept> #include <string> #include <vector> long long ConvertStringToNumber(std::string number) { long long int finalNumber = 0; bool isNegative = false; int i = 0; if (number.at(0) == '-') { isNegative = true; i++; } for (; i < number.length(); i++) { if (number.at(i) < '0' || number.at(i) > '9') { throw std::invalid_argument("Some error..."); } if (finalNumber > (std::numeric_limits<long long int>::max() - (number.at(i) - '0')) / 10) { throw std::overflow_error("Input string contains a number that is too large!!!"); throw std::range_error("Number is too large"); } finalNumber = finalNumber * 10 + (number.at(i) - '0'); } return isNegative ? -finalNumber : finalNumber; } std::vector<long long int> NumbersInString(std::string s) { std::vector<long long int> numbers; std::string currentNumber = ""; bool isNumber = true; for (int i = 0; i < s.length(); i++) { char c = s.at(i); if ((c >= '0' && c <= '9') || c == '-') { currentNumber += c; isNumber = true; } else if (isNumber) { if (!(currentNumber.size() == 0) && ((currentNumber != "-" && currentNumber.at(0) == '-') || (currentNumber.at(0) >= '0' && currentNumber.at(0) <= '9'))) { if (i == s.length() || ((s.at(i) < 'a' || s.at(i) > 'z') && (s.at(i) < 'A' || s.at(i) > 'Z'))) { try { long long int number = ConvertStringToNumber(currentNumber); numbers.push_back(number); } catch (std::domain_error &k) { // skip it } } } currentNumber = ""; isNumber = false; } } if (isNumber && !currentNumber.empty()) { try { long long int number = ConvertStringToNumber(currentNumber); numbers.push_back(number); } catch (std::domain_error &e) { } // skip again } return numbers; } int main() { std::string input; std::cout << "Enter a string: "; std::getline(std::cin, input); try { std::vector<long long int> numbers = NumbersInString(input); if (numbers.empty()) { std::cout << "The entered string does not contain any numbers!\n"; } else { std::cout << "Numbers within the string: "; for (long long int number : numbers) { std::cout << number << " "; } std::cout << std::endl; } } catch (std::overflow_error &e) { std::cout << "PROBLEM: " << e.what() << std::endl; } catch (std::range_error &k) { std::cout << "Exception with message:" << k.what(); } return 0; } ``` Can someone please give explanation and help for these cases here is the output: Enter a string: -123 123-123 123- 123 terminate called after throwing an instance of 'std::invalid_argument' what(): Some error... Aborted === Code Exited With Errors === Here is the correct output: -123 123-123 123- 123 and Enter a string: Ovo je 123456789012345678901234563 -90 test. PROBLEM: Input string contains a number that is too large!!! === Code Execution Successful === But output needs to be: Number too big! Can someone explain how to catch the exception and write different message then?
Bitbaking recipe doesn't install DEPENDS
|yocto|bitbake|yocto-recipe|yocto-kirkstone|
null
I do not have a lot of experience with AWS Cognito. In Javascript, I can authenticate with other user's pool using below code: import dotenv from 'dotenv'; dotenv.config(); import { CognitoUserPool, CognitoUser, AuthenticationDetails } from 'amazon-cognito-identity-js'; export async function getJwtToken() { const UserPoolId = process.env.COGNITO_USER_POOL_ID; const ClientId = process.env.COGNITO_APP_CLIENT_ID; const Username = process.env.COGNITO_USERNAME; const Password = process.env.COGNITO_PASSWORD; const userPool = new CognitoUserPool({ UserPoolId, ClientId }); const cognitoUser = new CognitoUser({ Username, Pool: userPool }); const authenticationDetails = new AuthenticationDetails({ Username, Password }); return new Promise((resolve) => { cognitoUser.authenticateUser(authenticationDetails, { onSuccess: function (result) { const token = result.getIdToken().getJwtToken(); resolve(token); }, onFailure: function (err) { console.error('Error obtaining JWT token:', err); resolve(null); } }); }); } But in Python, I need `cognito_idp_client` for authenticating. I refer to this code [github link][1] def start_sign_in(self, user_name, password): """ Starts the sign-in process for a user by using administrator credentials. This method of signing in is appropriate for code running on a secure server. If the user pool is configured to require MFA and this is the first sign-in for the user, Amazon Cognito returns a challenge response to set up an MFA application. When this occurs, this function gets an MFA secret from Amazon Cognito and returns it to the caller. :param user_name: The name of the user to sign in. :param password: The user's password. :return: The result of the sign-in attempt. When sign-in is successful, this returns an access token that can be used to get AWS credentials. Otherwise, Amazon Cognito returns a challenge to set up an MFA application, or a challenge to enter an MFA code from a registered MFA application. """ try: kwargs = { "UserPoolId": self.user_pool_id, "ClientId": self.client_id, "AuthFlow": "ADMIN_USER_PASSWORD_AUTH", "AuthParameters": {"USERNAME": user_name, "PASSWORD": password}, } if self.client_secret is not None: kwargs["AuthParameters"]["SECRET_HASH"] = self._secret_hash(user_name) response = self.cognito_idp_client.admin_initiate_auth(**kwargs) challenge_name = response.get("ChallengeName", None) if challenge_name == "MFA_SETUP": if ( "SOFTWARE_TOKEN_MFA" in response["ChallengeParameters"]["MFAS_CAN_SETUP"] ): response.update(self.get_mfa_secret(response["Session"])) else: raise RuntimeError( "The user pool requires MFA setup, but the user pool is not " "configured for TOTP MFA. This example requires TOTP MFA." ) except ClientError as err: logger.error( "Couldn't start sign in for %s. Here's why: %s: %s", user_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: response.pop("ResponseMetadata", None) return response Without cognito_idp_client, Python authentication do not work. I can create my own cognito_idp_client using below code: cognito_client = boto3.client( 'cognito-idp', aws_access_key_id=os.environ.get('AWS_ACCESS_KEY'), aws_secret_access_key=os.environ.get('AWS_SECRET_KEY'), region_name=os.environ.get('AWS_REGION'), ) But it will not work because user_pool_id is not my AWS Cognito. Is it possible to achieve results as in Javascript? Authenticating to another service user pool? [1]: https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/python/example_code/cognito/cognito_idp_actions.py#L187
Python AWS Cognito authenticate to other user pool as in Javascript
|python|amazon-web-services|amazon-cognito|
I'm attempting to retrieve user data, but the method is returning an empty object. bot.py ``` menuId = "id" server = "http://127.0.0.1:3000/" webapp = "https://localhost" + "/" + menuId bot = telebot.TeleBot(API_TOKEN) def webAppKeyboardInline(): keyboard = types.InlineKeyboardMarkup(row_width=1) webApp = types.WebAppInfo(webapp) one = types.InlineKeyboardButton(text="Open", web_app=webApp) keyboard.add(one) return keyboard # Handle '/start' command @bot.message_handler(commands=['start']) def handle_start(message): bot.send_message(message.chat.id, "hello!", reply_markup=webAppKeyboardInline()) bot.infinity_polling() ``` There is nothing interesting on the website, I simply get an object. But, despite the button type, it is always an empty object. I've experimented with various button techniques.
When I try to call the Telegram.WebApp.initDataUnsafe method in inline mode, the Telegram web app API returns an empty object - python
|python|telegram|python-telegram-bot|py-telegram-bot-api|telebot|
null
if [ "$req" = 1 ] or even better if [ "$req" -eq 1 ] See the syntax and operators in [man test](https://linux.die.net/man/1/test).
I have a set of functions which all accept a `value` named parameter, plus arbitrary other named parameters. I have a decorator: `lazy`. Normally the decorated functions return as normal, but return a partial function if `value` is None. How do I type-hint the decorator, whose output depends on the value input? ```python from functools import partial def lazy(func): def wrapper(value=None, **kwargs): if value is not None: return func(value=value, **kwargs) else: return partial(func, **kwargs) return wrapper @lazy def test_multiply(*, value: float, multiplier: float) -> float: return value * multiplier @lazy def test_format(*, value: float, fmt: str) -> str: return fmt % value print('test_multiply 5*2:', test_multiply(value=5, multiplier=2)) print('test_format 7.777 as .2f:', test_format(value=7.777, fmt='%.2f')) func_mult_11 = test_multiply(multiplier=11) # returns a partial function print('Type of func_mult_11:', type(func_mult_11)) print('func_mult_11 5*11:', func_mult_11(value=5)) ``` I'm using `mypy` and I've managed to get most of the way using mypy extensions, but haven't got the `value` typing working in `wrapper`: ```python from typing import Callable, TypeVar, ParamSpec, Any, Optional from mypy_extensions import DefaultNamedArg, KwArg R = TypeVar("R") P = ParamSpec("P") def lazy(func: Callable[P, R]) -> Callable[[DefaultNamedArg(float, 'value'), KwArg(Any)], Any]: def wrapper(value = None, **kwargs: P.kwargs) -> R | partial[R]: if value is not None: return func(value=value, **kwargs) else: return partial(func, **kwargs) return wrapper ``` How can I type `value`? And better still, can I do this without mypy extensions?
ultralytics_crop_objects is a list with like 20 numpy.ndarray, which are representing pictures (59, 381, 3) e.g.:[ultralytics_crop_objects[5]](https://i.stack.imgur.com/x6QvJ.png). I started passing a single picture out of the list to recognize. pipeline.recognize([ultralytics_crop_objects[5]]) --> ji856931 The result is "ji856931". So not all characters where detected. But when I pass the entire list of pictures and look at the result for the 6th picture, the result is different. See: [Different Results][1] results = pipeline.recognize(ultralytics_crop_objects) results[5] --> ji8569317076 I don't understand it at all. I would be super happy if someone could provide a hint. My only explanation would be that Keras OCR is using a different detection threshold for a single picture than for a list of more than one picture. Could that be the case? I have checked multiple times to ensure that I did not accidentally use another pipeline or that the input pictures are different. However, they are the same. I have also done extensive research online. Heres the complete Code: import keras_ocr pipeline = keras_ocr.pipeline.Pipeline() results = pipeline.recognize([ultralytics_crop_objects[5]]) print(results) results = pipeline.recognize(ultralytics_crop_objects) print(results[5])
I would like to do ldap authentication in spring boot security but take roles and other information ( like user region ) from a db. I came up to a UserDetaisContextMapper impl like: @Component public class UserDetailsContextMapperImpl implements UserDetailsContextMapper { @Autowired private UserService userService; @Override public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) { UserDetails userWithRoles = userService.enhanceWithRoles(username, new String((byte[]) ctx.getObjectAttribute("userPassword"))); return userWithRoles; } @Override public void mapUserToContext(UserDetails user, DirContextAdapter ctx) { } } This component is being used like this: @Configuration @EnableMethodSecurity public class LdapSecurityConfig { private final UserDetailsContextMapperImpl userDetailsContextMapperImpl; public LdapSecurityConfig(UserDetailsContextMapperImpl userDetailsContextMapperImpl) { this.userDetailsContextMapperImpl = userDetailsContextMapperImpl; } @Bean public UserDetailsService userDetailsService() { var cs = new DefaultSpringSecurityContextSource( "ldap://127.0.0.1:33389/dc=springframework,dc=org"); cs.afterPropertiesSet(); var manager = new LdapUserDetailsManager(cs); manager.setUsernameMapper(new DefaultLdapUsernameToDnMapper("ou=groups", "uid")); manager.setUserDetailsMapper(userDetailsContextMapperImpl); manager.setGroupSearchBase("ou=groups"); return manager; } @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } } In the UserDetailsContextMapperImpl I am forced to pass the password to the service because you can't construct a UserDetail with an empty password. But I find this to be a hack, because I don't need the password since I know that the authentication succeeded. What can I do in order to use LDAP authentication but don't care about the password and retrieve the roles from a user repository ?
The documentation shows you how it works in one file, but in a real-life project you will need to separate the models in different files and their logic will be in separate files as well. You need to connect to sequelize and then register the models in your entry point file like that ```js // app.js setupSequelize(app); registerModels(app); ``` The register models file should be like that ```js // models/index.js const createTodoModel = require('./todo.model'); function getModel(modelName) { const sequelize = this.get('sequelizeClient'); return sequelize.models[modelName]; } module.exports = function registerModels(app) { createTodoModel(app); const sequelize = app.get('sequelizeClient'); const { models } = sequelize; Object.keys(models).forEach(name => { if ('associate' in models[name]) { models[name].associate(models); } }); app.getModel = getModel; } ``` Then in your Todo you will need to do that ```js export const getAllTodos = async (req: Request, res: Response) => { const TodoModel = app.getModel('TodoModel'); try { const todos = await TodoModel.findAll() } catch (e) { console.log(e); } }; ``` For more information about the whole flow and how to configure sequelize to work in your project and how to manage the relations among the models avoiding the circular dependency issues please check this [repository][1] and the implementation of [sequelize setup][2], also you can check how to create a model from [here][3] [1]: https://github.com/muhammedkamel/chat-app [2]: https://github.com/muhammedkamel/chat-app/blob/master/src/app.js#L10-L12 [3]: https://github.com/muhammedkamel/chat-app/blob/master/src/models/apps.model.js
If you're writing something that does "the same thing, with just one thing changing at each step", that's a loop. You don't use separate `if` statements. Not even "when you're lazy": being lazy is an _excellent_ property to have when you're a programmer, because it means you want to do as little work as possible. Of course, in this case that means "why am I even doing this, [`npm install marked`](https://www.npmjs.com/package/marked), oh look I'm done", but even if you insist on implementing a markdown parser yourself (because sometimes you just want to write code to see if you can do it) you don't use a sequence of `if` statements, it takes more time to write, and takes more time to maintain/update. However, even if you _do_ use `if` statements, resolve them either such that you handle "the largest thing first", to ensure there's no fall-through, _or_ with if-else statements, so there's no fall-though. (And based on your question about whether to use a switch: why stop there? Why not just use a mapping object with `#` sequences as keys instead so the lookup runs in O(1)?) However, you don't need any of this, because what you're really doing is simple text matching, so you can use the best tool in the toolset for that: you can trivially get both the `#` sequence and "remaining text" with a dead simple regex, and then generate the replacement HTML [using the captured data](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#replacement): <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> function markdownToHTML(doc) { return convertMultiLineMD(doc.split(`\n`)).join(`\n`); } function convertMultiLineMD(lines) { // convert tables, lists, etc, while also making sure // to perform inline markup conversion for any content // that doesn't span multiple lines. For the purpose of // this answer, we're going to ignore multi-line entirely: return convertInlineMD(lines); } function convertInlineMD(lines) { return lines.map((line) => { // convert headings line = line.replace( // two capture groups for the markup, and the heading, /^(#+)\s+(.+)/, // and we extract the first group's length immediately (_, { length: h }, text) => `<h${h}>${text.trim()}</h${h}>` ); // then wrap bare text in <p>, convert bold, italic, etc. etc. return line; }); } // And a simple test based on what you indicated: const docs = [`## he#llo\nthere\n# yooo`, `# he#llo\nthere\n## yooo`]; docs.forEach((doc, i) => console.log(`[doc ${i + 1}]\n`, markdownToHTML(doc))); <!-- end snippet --> However, this is also a naive approach to writing a transpiler, and will have dismal runtime performance compared to writing a DFA based on the markdown grammar (the "markup language specification" grammar, i.e. the rules that say which tokens can follow which other tokens), where you run through your document by tracking what kind of token we're dealing with, and convert on the fly as we pass token terminations. That's wildly beyond the scope of this answer, but worth digging into if you're doing this just to see if you can do it: anyone can write code "that works" but is extremely inefficient, so that's not an exercise that's going to improve your skill as a programmer.
PROGRAM 4: Rolling Table Using the ROL and ROR instructions, write a program to produce a rolling table. This table should be built from a single int8 value provided by the user and print 3 rows from the starting value, each offset by one from the starting value. In each individual row, the entered number should be ROL'ed and then ROR'ed and then ROL'ed and then ROR'ed, as shown below. For example, the following output should be produced when the user inputs the starting value 4: Gimme a starting value: 4 Rolling Table 4: 8 2 16 1 5: 10 2 20 1 6: 12 3 24 1 This is my current code program RollingTable; #include ("stdlib.hhf" ); //Declaring Variables static value: int8; num: int8; begin RollingTable; //Getting user's input stdout.put( "Enter an integer value: "); stdin.get( value ); stdout.put( "Rolling Table",nl); //first row stdout.put( value, ":" ); mov(value, ah); rol(1, ah); mov(ah, num); stdout.put( num, " " ); mov(value, ah); ror(1, ah); mov(ah, num); stdout.put( num, " " ); mov(value, ah); rol(2, ah); mov(ah, num); stdout.put( num, " " ); shr(4, ah); mov(ah, num); stdout.put ( num, nl ); //Adding 1 to user's input inc( value ); stdout.put( value, ":" ); //second row mov(value, ah); rol(1, ah); mov(ah, num); stdout.put( num, " " ); mov(value, ah); ror(1, ah); mov(ah, num); stdout.put( num, " " ); mov(value, ah); rol(2, ah); mov(ah, num); stdout.put( num, " " ); shr(4, ah); mov(ah, num); stdout.put ( num, nl ); When I input 4 I get Rolling Table 4:8 2 16 1 5:10 -126 20 1 I tried rol(0,ah) instead of rol(1,ah) and this was my output 4:8 2 16 1 5:10 5 20 1
How can I fix the middle row to be printed out correctly?
|hla|
null
You need a single SELECT joining the two tables: INSERT INTO ROLE_AUTHORITY_MAPPING (authority_id, role_id) (SELECT security_authorities.id, security_roles.id FROM SECURITY_AUTHORITIES cross join SECURITY_ROLES WHERE authority = 'READ_SELF' and name = 'USER');
I have a problem with integrating Firebase into my Flutter project. As soon as I add the firebase_core in my project in the pubspec.yaml file, I get two errors. One of them is multidex support which can be fixed and it's okay. But the other one is a compilation error. Here is the error: ``` e: C:/Users/DELL/.gradle/caches/transforms-3/8c29013e1aed588339a4f98b518cda7c/transformed/jetified-play-services-measurement-api-21.6.1-api.jar!/META-INF/java.com.google.android.gmscore.integ.client.measurement_api_measurement_api.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.9.0, expected version is 1.7.1. ``` along with the following: ``` [!] Your project requires a newer version of the Kotlin Gradle plugin. │ │ Find the latest version on https://kotlinlang.org/docs/releases.html#release-details, then │ │ update C:\Users\DELL\Desktop\newfer\android\build.gradle: │ │ ext.kotlin_version = '<latest-version>' │ ``` Note that my Kotlin version is **higher **, and the latest version available and all the other problems are caused by the old incompatible versions. And as soon as I remove the firebase_core, I have no problems and the code is compiled correctly. What can be the problem? Thanks in advance for any help. I have been stuck in this phase for a while now.
I'm dealing with a little problem that I need to solve. I have an application in Django and I need a websocket, but I don't like Django channels, so I created a socket server in Flask and I'm trying to connect Django to it, by creating middleware that when called starts a process that sends messages through the process what it has in the queue But either the shared variable doesn't work or the process itself doesn't work properly. Please if you have any advice or solution write also how to terminate the process with socket when django terminates This is my code: ```python socket.py --- import socketio import json from project.settings import SOCKET_CONFIG, MANAGER from multiprocessing import Process sio = socketio.Client() class Socket: queue = MANAGER.list() def __init__(self, get_response): self.get_response = get_response thread = Process(target=Socket.process_loop, args=()) thread.start() def __call__(self, request): return self.get_response(request) @staticmethod def process_loop(): sio.connect('http://{}:{}'.format(SOCKET_CONFIG["host"],SOCKET_CONFIG["port"])) while True: try: import time time.sleep(1) data = Socket.queue.pop(0) sio.emit('message', data) except BaseException as e: print(e) settings.py --- import os, subprocess from multiprocessing import Process, Manager MANAGER = Manager() SOCKET_CONFIG={ "host":"localhost", "port":8001 } MIDDLEWARE = [ ... '_middlewares.socket.Socket' ] ... ```
In trying to understand how to work with classes, objects, and methods, Please explain why print(list.sort()) does not work like list.sort() followed by print(list). list = \[5, 1, 2\] print(list.sort()) #output is None VS. list.sort() print(list) #output is \[1, 2, 5\] Explained above: I expected print(list.sort()) to output a sorted list instead of None
Why does print(list.sort()) result in None?
|list|methods|printing|
null
When I checked the responses I saw that I get the same page over and over. If we use BurpSuite to inspect the requests and compare them we can see this part: [![BurpSuite comparer][1]][1] You can see on the RHS the the value "Next", but if we inspect the form data in the response we can see that the value is missing. We just need to add it: ```python import scrapy class LegonSpider(scrapy.Spider): name = "legon" def start_requests(self): yield scrapy.Request( url="https://mylegion.org/PersonifyEbusiness/Find-a-Post", callback=self.parse ) def parse(self, response): # Select distance and country yield scrapy.FormRequest.from_response( response, formid='aspnetForm', formdata={'dnn$ctr2802$DNNWebControlContainer$ctl00$DistanceList': '100', '@IP_COUNTRY': 'USA', '@IP_DEPARTMENT': '00000000001L'}, callback=self.parse_post_page ) def parse_post_page(self, response): post_elements = response.xpath("//div[@class='membership-dir-result-item']") for post_element in post_elements: post_num = post_element.xpath(".//div[contains(@class,'POST_NAME')]/text()").get().strip() post_link = post_element.xpath("./a/@href").get() yield response.follow(post_link, callback=self.parse_post_detail, meta={'post_num': post_num}) next_page_button = response.xpath("//input[@id='dnn_ctr2802_DNNWebControlContainer_ctl00_Next']") if next_page_button: form_data = {'dnn$ctr2802$DNNWebControlContainer$ctl00$Next': 'Next'} yield scrapy.FormRequest.from_response(response, formdata=form_data, callback=self.parse_post_page) def parse_post_detail(self, response): leader1 = response.xpath("(//div[contains(@class,'Leadership')]/div[2]/text())[1]").get() leader2 = response.xpath("(//div[contains(@class,'Leadership')]/div[2]/text())[2]").get() address = response.xpath("//div[contains(@class,'Address')]/div[2]/text()").get() typ = response.xpath("//div[contains(@class,'Type')]/div[2]/text()").get() yield { "post_num": response.meta['post_num'], "leader1": leader1, "leader2": leader2, "address": address, "type": typ } ``` See the differences between my form data and yours. BTW you missed a `/` in the selector of `next_page_button`. [1]: https://i.stack.imgur.com/dRXHZ.png
|r|data-analysis|
`forumsite.com##li:has(a.username[title*="NaughtySpammer"])` did the trick for my needs, but I wouldn't hate to see other solutions, especially if they are more expedient or would allow multiple spammer names included on one line.
{"Voters":[{"Id":2123530,"DisplayName":"β.εηοιτ.βε"},{"Id":9214357,"DisplayName":"Zephyr"},{"Id":354577,"DisplayName":"Chris"}],"SiteSpecificCloseReasonIds":[13]}
The sigmas and pis aren't random. They're from SQL nomenclature. See [here](https://cs.nyu.edu/~jcf/classes/CSCI-GA.2433-001_sp15/slides/session5/RelationalAlgebra-RelationalCalculus-SQL.pdf) The sigma is a selection criteria and the pi is an attribute list. As to the sizing, [the docs](https://pola-rs.github.io/polars/py-polars/html/reference/lazyframe/api/polars.LazyFrame.show_graph.html#polars.LazyFrame.show_graph) show there's a figsize parameter whose default is `(16.0, 12.0)` so maybe try with `(32.0, 12.0)` and try different settings there.
{"OriginalQuestionIds":[46270274],"Voters":[{"Id":28128,"DisplayName":"David Grayson"},{"Id":633440,"DisplayName":"Karl Hill"},{"Id":354577,"DisplayName":"Chris"}]}
When i write "." in IntelliJ no text comes. Heres what it looks like for me: [enter image description here](https://i.stack.imgur.com/7wlKd.png) And here is what im trying to get: [enter image description here](https://i.stack.imgur.com/uC98f.png) I have searched all over the place, but i just cant seem to find an answer...
Why is there no help text when i write "." in IntelliJ?
|java|intellij-idea|
null
Hello I wrote a program that creates 6 customized widgets which I called `Cell` and I want them to swap locations if one of them overlaps another. So I wrote a function called `swap_locations` and it works properly at first but when I try to swap the Cell (which I first selected) again it takes the target Cell's place but the target cell doesn't change its place. Here is my code parts that I think suspicious: ``` class Cell (FloatLayout, DragBehavior): def __init__(self,**kwargs): super(Cell, self).__init__(**kwargs) self.previous_pos = [0,0] def swap_locations(self, target): target_pos = target.pos self.pos = target_pos target.pos = self.previous_pos self.previous_pos = self.pos target.previous_pos = target_pos class BaseLayout (GridLayout): clock = StringProperty() day = StringProperty() date = StringProperty() temp = StringProperty() icon = StringProperty() selected_cell = Cell target = Cell def __init__(self, **kwargs): super(BaseLayout, self).__init__(**kwargs), Clock.schedule_once(self.calculate_cell_positions) def calculate_cell_positions(self, dt): cell_count = len(self.children) if cell_count == 0: return cols = self.cols rows = self.rows cell_width = self.width / cols cell_height = self.height / rows for i, cell in enumerate(self.children): if i % 2 == 0: factor = 1 else: factor = 0 row = i // cols cell.previous_pos = [factor * cell_width, row * cell_height ] cell.pos = cell.previous_pos def on_touch_down(self, touch): x, y = touch.pos for child in self.children: if child.collide_point(x,y): target = child self.selected_cell = target return True return True def on_touch_move(self, touch): if self.selected_cell: x, y = touch.pos self.selected_cell.pos = (x - self.selected_cell.width / 2, y - self.selected_cell.height / 2) return True return True def on_touch_up(self, touch): if self.selected_cell: for child in self.children: if child.collide_point(*touch.pos) and self.selected_cell != child: self.selected_cell.swap_locations(child) elif child.collide_point(*touch.pos) == None: self.selected_cell.pos = self.selected_cell.previous_pos else: self.selected_cell.pos = self.selected_cell.previous_pos return True ``` I wrote `calculate_cell_positions` method in order to calculate the positions of cells manually because my Cells doesn't have initial positions. It may be a dumb idea and if you have a better solution please do not hesitate to tell. Thank you! In order to dig down and modelize the problem I attached some photos of my program[1](https://i.stack.imgur.com/LeOXg.png) [2](https://i.stack.imgur.com/cGN3M.png) [3](https://i.stack.imgur.com/jng3F.png) ``` ```
Botpress conversation ender
|bots|robot|botpress|
null
Just found out that the GC is not all that great at handling cyclic references in some cases... Use a ```WeakReference<RefType>``` and this creates a dead end anyway. Coming from C++ its been a bumpy road with the GC. In c++ unique and shared pointer are just more powerful. GC is ok but then... meh... :)
I'm using roproxy instead of roblox to get around cord measures, requestbody is username,ctype ,password and useridand for the headers I'm just doing xcrs token:xcrs. It's just returning 403(). Is this an xcrs token thing? Couldn't find anything about it online. Ideally, it would print the incorect password error, or anything but 403() 0 heres the code im using const passwordcheck = { ctype: "Username", cvalue: "usernametomyaccount", password: "passwordtomyaccount", captchaToken: "CaptchaFromFuncaptcha", captchaId: "Captcha", captchaprovider: "PROVIDER_ARKOSE_LABS", userId: 889124, }; const request = { method: "POST", headers: { "Content-type": "application/json", "X-csrf-token": "wiXzYTbS/xF3", Cookie: "", }, body: JSON.stringify(passwordcheck), }; the url is roproxy v2 login I've tried using different proxies, but nothing came off it. Filling out the requestbody with all the stuff in the Roblox auth documentation didn't work either.
The `results` Mongo collection contains the following documents: ```json [ { "id": 1, "failures": [ { "level": "BASIC", "message": "failure", }, { "level": "BASIC", "message": "failure", }, { "level": "WARNING", "message": "failure", }, ], "rules": ["X", "Y"] }, { "id": 2, "failures": [ { "level": "BASIC", "message": "failure", }, { "level": "WARNING", "message": "failure", } ], "rules": ["X"] }, { "id": 3, "failures": [], "rules": ["X", "Y"] }, ] ``` I would like to create a Mongo query that selects the documents matching the provided IDs, counts the level of each elements of the failures array into a object, and project the rules property. Given the collection above, and when providing as input the IDs [1, 2, 3], this should be the expected output: ```json [ { "id": 1, "counts": { "BASIC": 2, "WARNING": 1 } "rules": ["X", "Y"] }, { "id": 2, "counts": { "BASIC": 1, "WARNING": 1 }, "rules": ["X"] }, { "id": 3, "counts": {}, "rules": ["X", "Y"] }, ] ``` This is the Mongo query I am building: ``` db.collection.aggregate([ { $match : { "id": $in: ["1", "2", "3"] } }, { $unwind: { path: "$failures", preserveNullAndEmptyArrays: true } }, { $group: { _id: { id: "$id", level: "$failures.level" }, count: { $sum: 1 }, rules: { $first: "$rules" } } } }, { $group: { _id: "$_id.id", count: { $push: { k: "$_id.level", v: "$count" } }, rules: { $first: "$rules" } } }, { $project: { "_id": 0, "id": $_id.id, "count": { $arrayToObject: "$count" }, "rules": 1 } } ]) ``` However, this query fails when applying the `$arrayToObject` operator with the following error: ``` $arrayToObject requires an object keys of 'k' and 'v' ``` This is because documents with no elements in the failures array have no key "k" when pushing the "_id.level" property. How can I fall back on an empty object if any of these keys are not present? Thanks in advance.
Kotlin Version Error in Integration of Firebase
|flutter|firebase|kotlin|google-cloud-firestore|
null
If this error occurs from the start of the script run and before any video frames have been successfully processed, the problem may be in the incorrect video path. You can try to specify the full path instead of the relative one, and even test different videos to check if the error still exists. If the error occurs at the end of the video file processing, the problem is in the **while** loop logic: even if the *condition* is *false* and `capture.read()` didn't return any frame (like at the end of the video), your code still tries to track this nonexistent frame before the *while* condition will do its job: ```python while condition: condition, frame = capture.read() results = model.track(frame, persist=True) ``` So here I would propose to use the usage example from Ultralytics documentation: https://docs.ultralytics.com/modes/track/#persisting-tracks-loop. This code will end the process in both cases: when the video ends or when "q" is pressed, and will not try to process the frames after the end of the video. ```python import cv2 from ultralytics import YOLO # Load the YOLOv8 model model = YOLO('yolov8n.pt') # Open the video file video_path = "./Vine_Golvo.mp4" cap = cv2.VideoCapture(video_path) # Loop through the video frames while cap.isOpened(): # Read a frame from the video success, frame = cap.read() if success: # Run YOLOv8 tracking on the frame, persisting tracks between frames results = model.track(frame, persist=True) # Visualize the results on the frame annotated_frame = results[0].plot() # Display the annotated frame cv2.imshow("Paul", annotated_frame) # Break the loop if 'q' is pressed if cv2.waitKey(1) & 0xFF == ord("q"): break else: # Break the loop if the end of the video is reached break # Release the video capture object and close the display window cap.release() cv2.destroyAllWindows() ```
I am trying to develop a plugin to export markdown file to PDF. Here is a sample markdown content: ``` # What is Obsidian ? Obsidian is a **markdown** editor. ``` I am using `marked` library to convert `markdown => html string` after which using `html` function of `JSPDF` library to convert to PDF and save The code snippet is as follows: ``` const pdf = new jsPDF() //converting markDown text to html const htmlContent = await marked(markedDownContent); pdf.html(htmlContent, { callback: (doc) => { doc.save("output.pdf"); }, x: 0, y: 0, margin: 10 }); ``` However, the text generated in PDF is poorly formatted as seen below: [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/POGm6.png I need help in fixing the styling of the text generated in the PDF document.