instruction
stringlengths
0
30k
βŒ€
New Blazor Web App, Password Reset "A valid antiforgery token was not provided"
|blazor|.net-8.0|
I'm currently working on integrating Microsoft Graph APIs into my Java application to retrieve license details for users in my Microsoft 365 tenant. I referred to the official Microsoft documentation [here](https://learn.microsoft.com/en-us/graph/api/user-list-licensedetails?view=graph-rest-1.0&tabs=java) to understand the usage of the Microsoft Graph Java SDK for this purpose. However, despite following the provided guidance, I'm encountering difficulties in implementing the solution within my Java codebase. **Context:** - I'm utilizing the Microsoft Graph Java SDK to interact with Microsoft 365 APIs. - Specifically, I'm referring to the documentation for listing license details for a user [here](https://learn.microsoft.com/en-us/graph/api/user-list-licensedetails?view=graph-rest-1.0&tabs=java). - My authentication setup and GraphServiceClient instantiation are already in place, following the documentation. **Issue:** The code snippet provided in the documentation is as follows: ```java // Code snippets are only available for the latest version. Current version is 6.x GraphServiceClient graphClient = new GraphServiceClient(requestAdapter); LicenseDetailsCollectionResponse result = graphClient.users().byUserId("{user-id}").licenseDetails().get(); ``` I've attempted to integrate this code into my Java application. While I can successfully query the Microsoft Graph API using tools like Postman, I'm unable to replicate the functionality within my Java codebase. **Expectation:** I'm seeking assistance in understanding and resolving the following: 1. How can I properly configure the `requestAdapter` required for initializing the `GraphServiceClient` instance in Java? 2. Are there any additional configurations or dependencies required to make the Microsoft Graph Java SDK work seamlessly within a Java application? I appreciate any insights or guidance on how to resolve this issue and successfully retrieve license details for users using the Microsoft Graph Java SDK within my Java application.
mp4 embedded videos within github pages website not loading
|javascript|html|css|github-pages|embedded-video|
null
It's an array of pointers to C strings (or char arrays). Where each string in the array is in the first[] and each character is in a second [], and each string of chars is an array of characters typically terminated by a null character or a zero byte. In main() the argc parameter specifies how many strings there are in the char *arcv[] array. The operating system when calling into main will specify the number of parameters, the int argc value as well as the command line parameters provided to main() in the char *argv[] parameter. The first argv parameter is typically the program name itself, and this is followed by any additional parameters specified on the command line. So for instance if you did: ./program.bin parameter1 --option1 And the data in it would be dereferenced like this: puts(argv[0]) // would be "./program.bin" puts(argv[1]) // would be "parameter1" puts(argv[2]) // would be "--option1" and argc would be 3. The way i'd think of this is as char **argv, in fact you can replace char *argv[] as char **argv. And I would think of this in the layout `char *(argv[stringnum])` or `char (argv[stringnum])[letternum]` or just `char argv[stringnum][letternum]` Now, the reason: (char *argv)[] doesn't work is, is because your declaration of the variable argv is embedded within some code to dereference it and the compiler is confused about whether it's a declaration or a function. In the error message it thinks it should be a declaration, but it doesn't understand the format. Instead use `char *argv[]` or `char **argv`
The issue with your regex is that you have `\d` and `\)` which appear in the regex as `d` and `)` (due to string parsing prior to the regex engine) the latter then causes an "unmatched closing parenthesis" error at the next `)`. You need to escape the `\` to ensure you get `\d` and `\)` into the regex i.e.: ```regex '/(\\d+)(?![^(]*\\))' ``` Note the `.*` at the beginning of the regex is not necessary as you are not interested in those characters anyway. Assuming you are using MySQL > 8.0.4, when the switch was made to the ICU engine, this will work fine, although it will give you a string ending with the last digits following a `/` but not inside brackets. You then just need to extract those digits, which you can do with another regex: ``` \\d+$ ``` In SQL: ```sql SELECT REGEXP_SUBSTR(REGEXP_SUBSTR(myStr, '/(\\d+)(?![^(]*\\))'), '\\d+$') FROM myTable; ``` Demo on [dbfiddle.uk][1] [1]: https://dbfiddle.uk/Ojz93dEF
When you are using Express edition you can try this: #if DEBUG if (fooVariable == true ) System.Diagnostics.Debugger.Break(); #endif The **#if-statement** makes sure that in the release build, breakpoint will not be present.
I understand that a ternary conditional operator can be used to shorten the following: if x > a: y += 12 else: y += 10 re-written as: y += 12 if x > a else 10 Is there something to shorten a statement if it's just the if portion with no else? i.e.: if x > a: y += 12 can be re-written as: y += 12 if x > a else 0 But I'm curious if there is an operator that doesn't add an else condition to a simple if statement with no else block.
Having trouble implementing Microsoft Graph Java SDK to list licenses assigned to user
|java|charts|licensing|azure-java-sdk|azure-identity|
null
I have an xarray.Dataset that looks like: print(ds2) <xarray.Dataset> Dimensions: (time: 46, latitude: 360, longitude: 720) Coordinates: * time (time) datetime64[ns] 1976-01-01 1977-01-01 ... 2021-01-01 * latitude (latitude) float64 89.75 89.25 88.75 ... -88.75 -89.25 -89.75 * longitude (longitude) float64 -179.8 -179.2 -178.8 ... 178.8 179.2 179.8 Data variables: Glacier (time, latitude, longitude) float64 dask.array<chunksize=(1, 360, 720), meta=np.ndarray> Uncertainty (time, latitude, longitude) float64 dask.array<chunksize=(1, 360, 720), meta=np.ndarray> I also have a raster with similar dimensions: print(np.shape(rgi_raster)) (1, 360, 720) How do I add rgi_raster to the xarray.Dataset so that it has the same time,lat,lon coordinates at the Glacier and Uncertainty variable? I tried: ds2=ds2.assign(rgi_raster=rgi_raster) But this gives: <xarray.Dataset> Dimensions: (time: 46, latitude: 360, longitude: 720, band: 1, x: 720, y: 360) Coordinates: * time (time) datetime64[ns] 1976-01-01 1977-01-01 ... 2021-01-01 * latitude (latitude) float64 89.75 89.25 88.75 ... -88.75 -89.25 -89.75 * longitude (longitude) float64 -179.8 -179.2 -178.8 ... 178.8 179.2 179.8 * band (band) int64 1 * x (x) float64 -179.8 -179.2 -178.8 -178.2 ... 178.8 179.2 179.8 * y (y) float64 -89.75 -89.25 -88.75 -88.25 ... 88.75 89.25 89.75 spatial_ref int64 0 Data variables: Glacier (time, latitude, longitude) float64 dask.array<chunksize=(1, 360, 720), meta=np.ndarray> Uncertainty (time, latitude, longitude) float64 dask.array<chunksize=(1, 360, 720), meta=np.ndarray> rgi_raster (band, y, x) float64 19.0 19.0 19.0 19.0 ... 10.0 10.0 10.0
How to add a new variable to xarray.Dataset in Python with same time,lat,lon dimensions with assign?
|python|dataset|python-xarray|assign|
I know my answer is not about fixing certificate validation from the source but the google landed me here because an error message I faced was the same. Given: 1. Windows 10 2. company's proxy behind (don't know exactly what's going on behind corporate's network but have Symantic Endpoint Protection is being run locally) 3. several JDKs installed locally (8-21). JAVA_HOME points out the coretto-17. 4. a simple brand new spring boot project generated from the spring-initializer.io (old gradle projects behave the same). 5. build.gradle plugins { id 'java' id 'io.spring.dependency-management' version '1.1.4' id 'org.springframework.boot' version '3.2.3' } group = 'com.test' version = '0.0.1-SNAPSHOT' java { sourceCompatibility = '17' } configurations { compileOnly { extendsFrom annotationProcessor } } repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' compileOnly 'org.projectlombok:lombok:1.18.32' annotationProcessor 'org.projectlombok:lombok:1.18.32' } settings.gradle rootProject.name = 'gradle-fail' The output I was trying to fix: FAILURE: Build failed with an exception. * What went wrong: A problem occurred configuring root project 'gradle'. > Could not resolve all files for configuration ':classpath'. > Could not resolve org.springframework.boot:spring-boot-buildpack-platform:3.2.3. Required by: project : > org.springframework.boot:org.springframework.boot.gradle.plugin:3.2.3 > org.springframework.boot:spring-boot-gradle-plugin:3.2.3 > Could not resolve org.springframework.boot:spring-boot-buildpack-platform:3.2.3. > Could not get resource 'https://plugins.gradle.org/m2/org/springframework/boot/spring-boot-buildpack-platform/3.2.3/spring-boot-buildpack-platform-3.2.3.pom'. > Could not GET 'https://jcenter.bintray.com/org/springframework/boot/spring-boot-buildpack-platform/3.2.3/spring-boot-buildpack-platform-3.2.3.pom'. > PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target I tried to build project via idea, gradle 8.5(7.5, 8.7) and gradle wrapper 8.5. I have to admit that the same project built via maven was compiled successfully. The most voted solution didn't help. The gradle plugin portal is being redirected to jcenter repo even though it has been deprecated. Local build is still attempting to download libs from the jcenter. My workaround was to disable jcenter repo and enforce using maven central or another maven repo for plugin resolution. Eventually I managed to fix it. The final solution is pretty simple. Just needed to add mavenCentral to plugin management repository config: settings.gradle pluginManagement { repositories { mavenCentral() } } rootProject.name = 'gradle-failed'
Basic Python Question: Shortening If Statements
|python|if-statement|conditional-statements|conditional-operator|
null
You can use `printf` with the space and then a separate line feed. Also `putchar` is a thing. Furthermore you should keep stack 16 byte aligned and using the exit syscall is bad practice. A possible solution: extern printf extern putchar global main section .data format_specifier: db '%X', 0x20, 0 ;format specifier for printf with trailing space section .text main: push rbx ; rbx is callee-saved. Also aligns stack. mov ebx, 15 ; 32 bits is enough loop1: ;loop to decrement and print number in ebx lea rdi, [rel format_specifier] ; use position independent code mov esi, ebx xor eax, eax ; 32 bit ops zero extend call printf wrt ..plt ; PIC dec ebx jns loop1 mov edi, 10 ; LF call putchar wrt ..plt xor eax, eax ; exit code pop rbx ret Caveat: this will print a space after the final `0`. Or, you can avoid `printf` altogether: extern putchar global main main: push rbx ; rbx is callee-saved. Also aligns stack. mov ebx, 'F' loop1: ;loop to decrement and print char in ebx mov edi, ebx call putchar wrt ..plt ; PIC dec ebx cmp ebx, '0' jb done cmp ebx, 'A' - 1 jne space mov ebx, '9' space: mov edi, ' ' call putchar wrt ..plt jmp loop1 done: mov edi, 10 ; LF call putchar wrt ..plt xor eax, eax ; exit code pop rbx ret
- In Desktop (The emulator turns on automatically) [npm start video](https://youtu.be/uUhNKguiao4) [terminal(?) image](https://i.stack.imgur.com/k913N.png) [emulator image](https://i.stack.imgur.com/GY4MG.png) - On the laptop After turning on the emulator can activate the React-Native Which program is the terminal image among the images? (Powershell X, Azure X, cmd X, ...) I want to use it like a desktop - case of me * What went wrong: Execution failed for task ':app:installDebug'. > com.android.builder.testing.api.DeviceException: No connected devices! Why do you press "DownButton" when you didn't explain it to me? If there is a lack of explanation, which part is it? (It may be because of my English skills.)
I have a list of items which i am able to drag and drop. When picking up the item it's hidden and i want to it to be revealed again on released wherever even outside the app window. Im using onDrag and am yet to find a way to detect when the item is released except when in a .drop area.
When using onDrag in SwiftUI on Mac how can detect when the dragged object has been released anywhere?
|swift|macos|swiftui|
null
How to extend Navigation View to show beyond safe area in swiftUI
I understand that a ternary conditional operator can be used to shorten the following: ``` if x > a: y += 12 else: y += 10 ``` re-written as: ``` y += 12 if x > a else 10 ``` Is there something to shorten a statement if it's just the if portion with no else? i.e.: ``` if x > a: y += 12 ``` can be re-written as: ``` y += 12 if x > a else 0 ``` But I'm curious if there is an operator that doesn't add an else condition to a simple if statement with no else block.
I am using xml-crypto version 6 to digitally sign xml in nodejs. But the package automatically add `Id="_0"` and `URI="#_0"` attribute to the elements being signed. Can anyone one help how to disable the addition of attributes. I am trying to digitally sign a xml code using `pem` file with the `xml-crypto` package in nodejs. It successfully sign the package and verify the xml also. But it automatically add the attributes, that is not required in the next flow.
null
Right click on InvokeAsync in the controller and from there create a view it will work
Try this ```dart class MyCustomClipper extends CustomPainter { @override void paint(Canvas canvas, Size size) { Path path_0 = Path(); path_0.moveTo(111.858,1.73511); path_0.lineTo(111.434,1.05619); path_0.lineTo(111.01,1.73512); path_0.lineTo(107.096,8); path_0.lineTo(5.997,8); path_0.cubicTo(2.96081,8,0.5,10.4627,0.5,13.5); path_0.lineTo(0.5,103.5); path_0.cubicTo(0.5,106.537,2.96081,109,5.997,109); path_0.lineTo(125.925,109); path_0.cubicTo(128.961,109,131.422,106.537,131.422,103.5); path_0.lineTo(131.422,13.5); path_0.cubicTo(131.422,10.4627,128.961,8,125.925,8); path_0.lineTo(115.771,8); path_0.lineTo(111.858,1.73511); path_0.close(); Paint paint_0_stroke = Paint()..style=PaintingStyle.stroke..strokeWidth=2; paint_0_stroke.color=Color(0xffEAECEE).withOpacity(1.0); canvas.drawPath(path_0,paint_0_stroke); Paint paint_0_fill = Paint()..style=PaintingStyle.fill; paint_0_fill.color = Colors.white.withOpacity(1.0); canvas.drawPath(path_0,paint_0_fill); ``` using [Flutter Shape Maker][1] you can create CustomPainter code from any svg. [1]: https://fluttershapemaker.com/#/
I have created a report with JasperReport, when I tried it on localserver everything went well. However, when I tested on the server, the following error occurred. "Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class net.sf.jasperreports.engine.util.JRStyledTextParser". The server I use is Linux OS I want jasperReport to be successful on my server
Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: . .
|java|spring|spring-boot|jasper-reports|
null
while in a specific page i need to know the name of the page, which was set by named routes. i caould know with normal 'context', but i couldn't do using global context. my code: ``` // ModalRoute.of(context)?.settings.name with global context, trying! import 'package:flutter/material.dart'; void main(){runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); static GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); // <--- @override Widget build(BuildContext context) { return MaterialApp( navigatorKey: MyApp.navigatorKey, // set property // <--- //home: const HomeScreen(), initialRoute: '/home', routes: { // ---------------> hash routing '/home':(context)=> const HomeScreen(), '/details':(context)=> const DetailsScreen(), }, ); } } class HomeScreen extends StatefulWidget { const HomeScreen({super.key}); @override State<HomeScreen> createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { @override Widget build(BuildContext context) { //MyApp.navigatorKey.currentState!.context =context, return Scaffold( appBar: AppBar(title: const Text('Home Page'),backgroundColor: Colors.blue,), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: (){ print("print context: ${MyApp.navigatorKey.currentContext}"); //print context: Navigator-[LabeledGlobalKey<NavigatorState>#a6af1](dependencies: [HeroControllerScope, UnmanagedRestorationScope], state: NavigatorState#d0a98(tickers: tracking 1 ticker)) }, child: const Text('button 1.1') ), ElevatedButton( onPressed: (){ print(ModalRoute.of(MyApp.navigatorKey.currentContext!)?.settings.name ?? "Unknown"); //Unknown //or, MyApp.navigatorKey.currentState!.context }, child: const Text('button 1.2') ), ElevatedButton( onPressed: (){ print("${ModalRoute.of(context)?.settings.name}"); //: /home }, child: const Text('button 1.3') ), ElevatedButton( // onPressed: () { // Navigator.push(context, MaterialPageRoute( // settings: const RouteSettings(name: "/detailsScreen"), // builder: (context)=> const DetailsScreen()) // ); // //Navigator.pushReplacement(context,MaterialPageRoute(builder: (context)=> const DetailsScreen())); // }, onPressed: (){ Navigator.pushNamed(context, '/details'); }, child: const Text('go to details page'), ), ], ), ), ); } @override void dispose() { print("Dispose called"); super.dispose(); } } class DetailsScreen extends StatefulWidget { const DetailsScreen({super.key}); @override State<DetailsScreen> createState() => _DetailsScreenState(); } class _DetailsScreenState extends State<DetailsScreen> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Details Page'), backgroundColor: Colors.blue, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: (){ print("print context: ${MyApp.navigatorKey.currentContext}"); //print context: Navigator-[LabeledGlobalKey<NavigatorState>#ebadf](dependencies: [HeroControllerScope, UnmanagedRestorationScope], state: NavigatorState#5dfff(tickers: tracking 2 tickers)) }, child: const Text('button 2.1') ), ElevatedButton( onPressed: (){ print(ModalRoute.of(MyApp.navigatorKey.currentContext!)?.settings.name ?? "Unknown"); //Unknown }, child: const Text('button 2.2') ), ElevatedButton( onPressed: (){ print("${ModalRoute.of(context)?.settings.name}"); }, child: const Text('button 2.3') //: /details ), ], ), ), ); } } ``` in above example button 1.2 and 2.2 should print their corresponding page name. looks like button 1.3 and 2.3 are printing as expected. but ``` ModalRoute.of(MyApp.navigatorKey.currentContext!)?.settings.name is sending null value. ```
flutter, find route name of a page using global context while using named routes
|flutter|navigation|
null
I have used recast for my code generation with babel as i have checked it is compatible with babel but recast is removing all my comments Here is my recast code const generatedAst = recast.print(ast, { tabWidth: 2, quote: 'single', }); I am passing AST generated from babel parse and directly if i use babel generate to generate my code then parenthesis are removed Can anyone help me with this Thank you in advance I don't know any other package that is compatible with babel i used recast because i have checked this [text](https://github.com/babel/babel/issues/8974) and in this it is mentioned that babel removes parenthesis
I am using the [Llama-2-7b-hf][1] model with the `model.generate` function from the transformers library (v4.38.2) and it's returning the outputs as a single tensor, instead of the dict I expected. I have a copy of the model stored locally: ``` [Llama-2-7b-hf]$ ls -1 config.json generation_config.json LICENSE.txt model-00001-of-00002.safetensors model-00002-of-00002.safetensors model.safetensors.index.json README.md Responsible-Use-Guide.pdf special_tokens_map.json tokenizer_config.json tokenizer.json tokenizer.model USE_POLICY.md ``` This is the code where the model is initialized and then called: ``` model_path = "Llama-2-7b-hf" model = AutoModelForCausalLM.from_pretrained(model_path, return_dict_in_generate=True, local_files_only=True).to(device) tokenizer = AutoTokenizer.from_pretrained(engine, local_files_only=True) input_ids = tokenizer(model_path, return_tensors="pt").input_ids.to(device) outputs = model.generate(input_ids, top_k=1, max_length=max_len, num_return_sequences=1, output_scores=True) sequences, scores = outputs.sequences, outputs.scores ``` I have used this code with several other models like [Mistral][2] and [Occiglot][3] and they return ModelOutput objects with these attributes, `sequences` and `scores`, but not Llama. Can anyone help me understand what is wrong? [1]: https://huggingface.co/meta-llama/Llama-2-7b-hf [2]: https://huggingface.co/mistralai/Mistral-7B-v0.1 [3]: https://huggingface.co/occiglot/occiglot-7b-eu5
meta-llama/Llama-2-7b-hf returning tensor instead of ModelOutput
|huggingface-transformers|llama|
You have to manually change data in double list comprehension: L = [b['Conversion'] for k, v in input['data'].items() for a, b in v.items()] print (L) [{'id': '1', 'datetime': '2024-03-26 08:30:00'}, {'id': '50', 'datetime': '2024-03-27 09:00:00'}] out = pd.json_normalize(L) print (out) id datetime 0 1 2024-03-26 08:30:00 1 50 2024-03-27 09:00:00
I want to use Web Audio API to simulate sound like guitar or something. Currently, I am using OscillatorNode to make sound by changing frequency. But I have no idea which node should I use and how to use it to make sound like guitar or something. Should I change waveform or what? and how? Here is some reference https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
|html5-audio|
Whether a thread created using Linux's pthread library is a user-level thread or a kernel-level thread? I hope to get a professional answer to this question. Because I've heard that different versions of the Linux kernel as well as different compiler versions can have an impact on the answer to the question.
thread created by pthread in Linux belongs to ULT or KLT?
|linux|pthreads|
null
I am store ~1500 last events in Redis in soreted set. When set is more than 1500 elements, which is better (least loaded) way to clear first events? Im using redis:6.0.2 Several options come to mind: 1. Simplest is using something like CRON or some interval to clear it 2. Using some global count and increment it in every request to this table. And clear it when this count are more than 100 or is there another better way?
To simplify the example, I consider a dataframe with 3 10-Q and 2 10-K entries for each of two values of *cik*. I'll filter for the 2 most recent 10-K rows and the most recent 10-Q row for each group defined by *cik*. ```python import polars as pl import datetime df = pl.DataFrame({ "cik": [0] * 5 + [1] * 5, "form": (["10-Q"] * 2 + ["10-K"] * 3) * 2, "period": [datetime.date(2021, 1, 1+day) for day in range(10)], }) ``` ``` shape: (10, 3) β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ cik ┆ form ┆ period β”‚ β”‚ --- ┆ --- ┆ --- β”‚ β”‚ i64 ┆ str ┆ date β”‚ β•žβ•β•β•β•β•β•ͺ══════β•ͺ════════════║ β”‚ 0 ┆ 10-Q ┆ 2021-01-01 β”‚ β”‚ 0 ┆ 10-Q ┆ 2021-01-02 β”‚ β”‚ 0 ┆ 10-K ┆ 2021-01-03 β”‚ β”‚ 0 ┆ 10-K ┆ 2021-01-04 β”‚ β”‚ 0 ┆ 10-K ┆ 2021-01-05 β”‚ β”‚ 1 ┆ 10-Q ┆ 2021-01-06 β”‚ β”‚ 1 ┆ 10-Q ┆ 2021-01-07 β”‚ β”‚ 1 ┆ 10-K ┆ 2021-01-08 β”‚ β”‚ 1 ┆ 10-K ┆ 2021-01-09 β”‚ β”‚ 1 ┆ 10-K ┆ 2021-01-10 β”‚ β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` To filter the dataframe for each group defined by *cik*, we can simply use `pl.DataFrame.filter` together with `pl.Expr.over` (to define the groups) as follows. ```python ( df .sort(by=["cik", "form", "period"], descending=[False, False, True]) .filter( ( ((pl.col("form") == "10-Q") & (pl.int_range(pl.len()) == 0)) | ((pl.col("form") == "10-K") & (pl.int_range(pl.len()) < 2)) ) .over("cik", "form") ) ) ``` ``` shape: (6, 3) β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ cik ┆ form ┆ period β”‚ β”‚ --- ┆ --- ┆ --- β”‚ β”‚ i64 ┆ str ┆ date β”‚ β•žβ•β•β•β•β•β•ͺ══════β•ͺ════════════║ β”‚ 0 ┆ 10-K ┆ 2021-01-05 β”‚ β”‚ 0 ┆ 10-K ┆ 2021-01-04 β”‚ β”‚ 0 ┆ 10-Q ┆ 2021-01-02 β”‚ β”‚ 1 ┆ 10-K ┆ 2021-01-10 β”‚ β”‚ 1 ┆ 10-K ┆ 2021-01-09 β”‚ β”‚ 1 ┆ 10-Q ┆ 2021-01-07 β”‚ β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` **Explanation.** 1. We sort the DataFrame in descending order by *date* for each group defined by *cik* and *form*. 2. We filter the dataframe for rows with *form* being 10-K and the row index being less than 2 (0 or 1 - **with your data, you'd filter rows with row index less than 10**) or *form* being 10-K and the row index being 0, i.e. the most recent entry. We use `pl.Expr.over` to do this filtering separately for each group defined *cik* and *form* (to ensure the index is being reset properly for each form).
I understand that a ternary conditional operator can be used to shorten the following: ``` if x > a: y += 12 else: y += 10 ``` re-written as: ``` y += 12 if x > a else 10 ``` Is there something to shorten a statement if it's just the if portion with no else? i.e.: ``` if x > a: y += 12 ``` can be re-written as: ``` y += 12 if x > a else 0 ``` But I'm curious if there is an operator that doesn't add an else condition to a simple if statement with no else block Something similar to the idea of: ``` y += 12 if x > a ``` even though I know this is syntactically incorrect.
{"Voters":[{"Id":5910058,"DisplayName":"Jesper Juhl"},{"Id":3581217,"DisplayName":"Bart"},{"Id":6752050,"DisplayName":"273K"}]}
I am trying to find the numbers that ends with 4 in a list of numbers. I tried the following code but getting an error message saying *TypeError: list indices must be integers or slices, not str* ``` x = [12, 44, 4, 1, 6, 343, 10, 34, 12, 94, 783, 330, 896, 1, 55] x_str = list(map(str, x)) for ele in x_str: if x_str[ele][-1] == "4": print(ele) ``` I tried to modify the code by making ```x_str[ele][-1]``` an integer. But now I am getting another error message saying *TypeError: 'int' object is not iterable* ``` x = [12, 44, 4, 1, 6, 343, 10, 34, 12, 94, 783, 330, 896, 1, 55] x_str = list(map(str, x)) for ele in x_str: if int(x_str[ele][-1]) == 4: print(ele) ``` Would be really grateful to receive any help or suggestion
This is my (untested) code to perform this operation on nested directories: def latest(file: File): File = if (file.isDirectory) { latest(file.listFiles.maxByOption(_.lastModified).getOrElse(file)) } else { file } This is tail recursive and will compile to a simple loop.
I'm developing a web compiler in TypeScript and I've encountered a small, but still irritating issue: I have a progress bar inside an iframe element which keeps rendering for a short amount of time. I want that progress bar to be rendered only when there's a code bundling process. Here's a piece of that TypeScript code: codeCell.tsx(The CodeCell component) ``` const bundle = useTypedSelector((state) => state.bundles[cell.id]); return( <> <Resizable direction="vertical"> <div className="h-100 d-flex flex-row position-relative"> <Resizable direction="horizontal"> <div className="position-relative w-100"> <CodeEditor initialValue={cell.content} onChange={handleEditorChange}/> </div> </Resizable> <div className="progress-wrapper"> {!bundle || bundle.loading ? ( <div className="progress-cover"> <progress hidden={!bundle} max="100"/> </div> ) : ( <Preview code={bundle.code} err={bundle.err} cell={cell}/> )} </div> </div> </Resizable> </> ); ``` useTypedSelector.ts(useTypedSelector hook): ``` export const useTypedSelector: TypedUseSelectorHook<RootState> = (selector) =>{ const result = useSelector(selector, shallowEqual); return useMemo(() => result, [result]); }; const shallowEqual = (a: any, b: any) =>{ if (a === undefined || b === undefined){ return false; } for(let key in a){ if(a[key] !== b[key]){ return false; } } for(let key in b){ if(!(key in a)){ return false; } } return true; }; ``` preview.tsx (Preview component): ``` interface PreviewProps{ code: string; err: string; cell: Cell; } const Preview: React.FC<PreviewProps> = ({ code, err, cell }) =>{ const iframe = useRef<any>(); useEffect(() =>{ iframe.current.srcdoc = html; setTimeout(() =>{ iframe.current.contentWindow.postMessage(code, '*'); // Posts the result from the code bundling }, 10); }, [code]); return( <div className="preview-wrapper"> <iframe title="code preview" ref={iframe} sandbox="allow-scripts" srcDoc={html}/> {err && ( <div className="preview-error"> {err} </div> )} <div style={{ display: "none" }}> <div className="action-bar"> <ActionBar id={cell.id}/> </div> </div> </div> ); } export default Preview; ``` One of the approaches I tried is using a ternary operator inside the Preview component's props stating that if there's a code bundling process you'll see the progress bar (the same if there's a code error) and if not (there's no code at all), you'll see an empty string (meaning you'll see an empty iframe element).
Persisted progress bar
|typescript|react-hooks|react-typescript|
null
I receive a file from a third party. The file seems to contain both ANSI and UTF-8 encoded characters (not sure if my terminology is correct). Changing the encoding in Notepad++ yields the following: [![Notepad++ screenshot][1]][1] [1]: https://i.stack.imgur.com/G0hcd.png So when using ANSI encoding, Employee2 is incorrect. And when using UTF-8 encoding, Employee1 is incorrect. Is there a way in C# to set 2 encodings for a file? Whichever encoding I set in C#, one of the two employees is incorrect: string filetext = ""; filetext = File.ReadAllText(@"C:\TESTFILEx.txt", Encoding.GetEncoding("ISO-8859-1")); // Employee1 is correct, Employee2 is wrong filetext = File.ReadAllText(@"C:\TESTFILEx.txt", Encoding.GetEncoding("Windows-1252")); // Employee1 is correct, Employee2 is wrong filetext = File.ReadAllText(@"C:\TESTFILEx.txt", Encoding.UTF7); // Employee1 is correct, Employee2 is wrong filetext = File.ReadAllText(@"C:\TESTFILEx.txt", Encoding.Default); // Employee1 is correct, Employee2 is wrong filetext = File.ReadAllText(@"C:\TESTFILEx.txt", Encoding.UTF8); // Employee1 is wrong, Employee2 is correct Has anyone else encountered this and found a solution?
The IsShuttingDown property is an internal static property of the Application class therefore you can access to value it with below code var isShuttingDownProp = typeof(Application).GetProperty("IsShuttingDown", BindingFlags.Static | BindingFlags.NonPublic); var isShuttingDown = isShuttingDownProp.GetValue(Application.Current, null);
{"Voters":[{"Id":23918954,"DisplayName":"payam jabbari"}]}
Recently I Found This Error For log in to my mysql and mariadb on My UnixBase MacOS. And i try similar Ways in StackOverFlow To fix this problem. but problem not solved. [![Terminal Error](https://i.stack.imgur.com/YfKZl.png)](https://i.stack.imgur.com/YfKZl.png) i try systemctl to check mariadb or mysql is running. [![enter image description here](https://i.stack.imgur.com/KrASV.png)](https://i.stack.imgur.com/KrASV.png) But it seems systemctl command is not available on macOS system. Then i try to look at mariadb version. [![enter image description here](https://i.stack.imgur.com/peWTN.png)](https://i.stack.imgur.com/peWTN.png) i use this [StackOverFlowLink](https://stackoverflow.com/questions/15450091/error-2002-hy000-cant-connect-to-local-mysql-server-through-socket-tmp-mys). But Nothing Changes Actually i use my mariadb server for about one year on my MacOS, And I dont know why this trouble happened recently.
Can't Fix Mariadb & Mysql ERROR 2002 (HY000): Can't connect to local server through socket '/tmp/mysql.sock' (2) On MacOs
|mysql|mariadb|
null
I am using this code to generate an automatic table of contents in docx ``` <w:sdt> <w:sdtPr> <w:alias w:val="Summary" /> </w:sdtPr> <w:sdtContent> <w:p> <w:r> <w:fldChar w:fldCharType="begin" w:dirty="true" /> <w:instrText xml:space="preserve">TOC h o &quot;1-5&quot;</w:instrText> <w:fldChar w:fldCharType="separate" /> </w:r> </w:p> <w:p> <w:r> <w:fldChar w:fldCharType="end" /> </w:r> </w:p> </w:sdtContent> </w:sdt> ``` And so far everything is fine. The problem is that the table of contents text that is generated when opening Microsoft Word is in bold. I don't want it to be in bold.
How can I create an automatic table of contents in docx without the text being bold?
|xml|ms-word|ms-office|openxml|docx|
I have got the code for a react native app, and want to publish this to appstore. After importing into Xcode, opening the ios folder I am running into over 200 Yellow warnings and 15 Red warning. I dont know if this means that there is an issue with react code or just how i have set it up. Currently the warning i am getting are attached below. How do i proceed to resolve them, and does this really matter if it cant build in Xcode given that i just want to upload to app store. Thanks for any advice.[Yellow Errors](https://i.stack.imgur.com/st14h.png) and [Red Errors](https://i.stack.imgur.com/cyhnl.png) I tried cleaning and rebuilding but still same errors
List of numbers converted to list of strings to iterate over it. But receiving TypeError messages
|python|
Trying to put multiple arguments into a string in Bash is generally not a good idea. Sometimes the only way to make it work is to use `eval`, and that often just gives you more problems (some of which may be very unobvious). See [Why should eval be avoided in Bash, and what should I use instead?](https://stackoverflow.com/q/17529220/4154375). In this case I'd avoid the problem by defining the (Bash) function like this: function myFunc { codesign "${@:2}" "$1" } and calling it like this: myFunc "/MyFolder/MyFile.dylib" -f -vvvv --strict --deep --timestamp -s "Developer ID Application: My Company Inc. (123456)" --options runtime I.e. put the path of the file to be signed as the first argument and the arguments to `codesign` as the following, all separate, arguments. Any arguments that work with `codesign` itself are guaranteed to work when provided as arguments (2 and following) to `myFunc`. Note that if the intention in using a function like this is to make it easy to use different sets of options with `codesign` for different files, then it is important to keep lists of options in arrays instead of strings. This code demonstrates how to use an array to build up the full list of options in stages before calling the function: codesign_opts=( -f -vvvv --strict --deep --timestamp ) codesign_opts+=( -s "Developer ID Application: My Company Inc. (123456)" ) codesign_opts+=( --options runtime ) myFunc "/MyFolder/MyFile.dylib" "${codesign_opts[@]}"
I have an array like this: $sports = array( 'Softball - Counties', 'Softball - Eastern', 'Softball - North Harbour', 'Softball - South', 'Softball - Western' ); I would like to find the longest common prefix of the string. In this instance, it would be `'Softball - '` I am thinking that I would follow this process $i = 1; // loop to the length of the first string while ($i < strlen($sports[0]) { // grab the left most part up to i in length $match = substr($sports[0], 0, $i); // loop through all the values in array, and compare if they match foreach ($sports as $sport) { if ($match != substr($sport, 0, $i) { // didn't match, return the part that did match return substr($sport, 0, $i-1); } } // foreach // increase string length $i++; } // while // if you got to here, then all of them must be identical Questions 1. Is there a built-in function or a much simpler way of doing this? 2. For my 5 lines array that is probably fine, but **if I were to do several thousand lines arrays**, there would be a lot of overhead, so I would have to be move calculated with my starting values of `$i`, eg `$i` = halfway of string, if it fails, then `$i/2` until it works, then increment `$i` by 1 until we succeed. So that we are doing the least number of comparisons to get a result. Is there a formula/algorithm out already out there for this kind of problem?
|php|string|algorithm|prefix|
The code setup is as follows: - Module ui_theme.py defines a theme and variant selector. - variant_selector has an on_change event handler. - Module cards_page.py imports ui_theme.py and has a handler on_variant_change. Now, what I want to achieve that when ui_theme.on_change event is invoked then it should somehow call the cards_page.on_variant_change event. Constraint: I definitely do not want to create a function to generate variant_selector. That makes the code-org bit messy. I also, can not post initialization, set the event handler. My current solution is as follows: - ui_theme.py ``` on_change_variant_callback = None def on_change_variant_click(dbref, msg, to_ms): print ("button clicked:", msg.value) if on_change_variant_callback: on_change_variant_callback(dbref, msg, to_ms) pass ``` - in cards.py ``` import ui_theme def on_variant_select(): pass ui_theme.on_change_variant_callback = on_variant_select ``` Seems to me that there should be a better way -- probably this where dependency injection can help, although i don't understand that concept well enough.
I was trying to run this java code as a script to generate sub-classes in /home/ankit/Dev/Zealot/com/piscan/Zealot directory. But it is not running and constantly giving the same error. This is the error: cd "/home/ankit/Dev/Zealot/com/piscan/tool/" && javac GenerateAst.java && java GenerateAst Error: Could not find or load main class GenerateAst Caused by: java.lang.NoClassDefFoundError: GenerateAst (wrong name: com/piscan/tool/GenerateAst) Here's the code for reference: ``` package com.piscan.tool; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.List; // this code will generate sytanx tree subclasses public class GenerateAst { public static void main(String[] args) throws IOException { if (args.length != 1) { System.out.println("Usage: generate_ast <output directory>"); System.exit(64); } String outputDir = args[0]; defineAst(outputDir, "Expr", Arrays.asList( "Binary : Expr left , Token operator, Expr right", "Grouping : Expr expression", "Literal : Object value", "Unary : Token operator, Expr right")); } // this will create a new file expr.java and put the basic code there private static void defineAst(String outputDir, String baseName, List<String> types) throws IOException { String path = outputDir + "/" + baseName + ".java"; PrintWriter writer = new PrintWriter(path, "UTF-8"); writer.println("package com.piscan.Zealot;"); writer.println(); writer.println("import java.util.List;"); writer.println(); writer.println("abstract class " + baseName + "{"); /* * When we call this, baseName is β€œExpr”, which is both the name of the class * and the name of the file it outputs. We pass this as an argument instead of * hardcoding the name because we’ll add a separate family of classes later for * statements. */ // The AST classes for (String type : types) { String className = type.split(":")[0].trim(); String fields = type.split(":")[1].trim(); defineType(writer, baseName, className, fields); } writer.println("}"); writer.close(); } private static void defineType(PrintWriter writer, String baseName, String className, String fieldList) { writer.println(" static class " + className + " extends " + baseName + " {"); // constructor writer.println(" " + className + "(" + fieldList + ") {"); // Store parameters in fields. String[] fields = fieldList.split(", "); for (String field : fields) { String name = field.split(" ")[1]; writer.println(" this." + name + " = " + name + ";"); } writer.println(" }"); // Fields. writer.println(); for (String field : fields) { writer.println(" final " + field + ";"); } writer.println(" }"); } } ```
`char *second = "test5";` initializes `second` to point to the first character of the array created by a string literal. About string literals, C 2018 6.4.5 7 says: > … If the program attempts to modify such an array, the behavior is undefined. Since your program attempts to modify the array when it calls `strcpy(second, first);`, the behavior of your program is not defined. A common behavior of C implementations is to put the arrays of string literals in memory marked as read-only for the process, so attempting to modify such an array causes a memory access violation. Compiler optimization may also cause other behaviors initially surprising to programmers as optimization may assume that no attempt to modify the array of a string literal occurs and hence may transform the program based on that assumption.
Well I'm trying to enable my users to login with their gmail accounts like I saw in some sites on the top right of the browser windows as I show in the image. The only thing I could get searching was use the Google Sign-in API but that let me create a button which open a popup with my accounts but I want to show it when the user get to the site without a new window, maybe a iframe or popup I don't know. Do anyone knows if what the image show can be done with Google Sign-In or it's maybe with another API or something? [![Example][1]][1] [1]: https://i.stack.imgur.com/PHqjl.png
Google sign-in in web site detecting user accounts and display in iframe/popup
|html|google-signin|
Detect click outside multiple components
You have to manually change data in double list comprehension: L = [b['Conversion'] for k, v in input['data'].items() for a, b in v.items()] print (L) [{'id': '1', 'datetime': '2024-03-26 08:30:00'}, {'id': '50', 'datetime': '2024-03-27 09:00:00'}] out = pd.json_normalize(L) print (out) id datetime 0 1 2024-03-26 08:30:00 1 50 2024-03-27 09:00:00 Here is `json_normalize` not necessary, working `DataFrame` constructor: out = pd.DataFrame(L) print (out) id datetime 0 1 2024-03-26 08:30:00 1 50 2024-03-27 09:00:00 In [`json_normalize`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.json_normalize.html) is parameter `max_level`, but working different: >Max number of levels(depth of dict) to normalize. if None, normalizes all levels. out = pd.json_normalize(input['data'], max_level=1) print (out) data.1 \ 0 {'Conversion': {'id': '1', 'datetime': '2024-0... data.50 0 {'Conversion': {'id': '50', 'datetime': '2024-... out = pd.json_normalize(input['data'], max_level=2) print (out) data.1.Conversion \ 0 {'id': '1', 'datetime': '2024-03-26 08:30:00'} data.50.Conversion 0 {'id': '50', 'datetime': '2024-03-27 09:00:00'} out = pd.json_normalize(input['data'], max_level=3) print (out) data.1.Conversion.id data.1.Conversion.datetime data.50.Conversion.id \ 0 1 2024-03-26 08:30:00 50 data.50.Conversion.datetime 0 2024-03-27 09:00:00
null
As others mentioned before, in 2 steps: 1. Dex2jar 2. Pick up a decompiler I will focus on step 2. Take a look at this research paper : [The Strengths and Behavioral Quirks of Java Bytecode Decompilers][1] Understand the strength and weaknesses of each decompiler. 1. [CFR][2]: Considered by many as the absolute best decompiler, its specificity is that it takes a lot a liberty in graph transformations to maximise the chance of good results, at the expense of original code ordering, and has a lot of technical settings. The last version has a line number mapping but no line number realignment. 2. [Procyon][3]: This one has the best chances to produce well structured code, adds final keywords everywhere it can, but often adds unexpected illegal casts. It has also a GUI project [Luyten][4]. 3. [Fernflower][5]: It's the decompiler from the popular IDE Intellij Idea. It often decompiles right but code is sometimes not ideally structured and has very bad naming of exception variables var1..n. 4. [Vineflower][6]: It's a fork of fernflower which brings improvements and bug fixes, with a test suite borrowed to CFR. 5. [JD-GUI][7]: It's the GUI of the [JD-CORE][8] project. The new version of JD-CORE structures the code into a control flow graph and an abstract syntax tree. The previous version which was present until v1.4.2 of JD-GUI was another decompiler based on bytecode pattern matching like [JAD][9]. JD-CORE is focused on producing a recompilable output on many open source projects and also on getting line number realignment right for a debug-ready output. 6. [JADX][10]: This project looks actively maintained and promising, but for the time being, the results are not very solid. The following GUI projects support several decompilers: - [Recaf][11]: provides support for the following decompilers: CFR Β· FernFlower Β· Procyon - [Bytecodeviewer][12]: A Java 8+ Jar & Android APK Reverse Engineering Suite (Editor, Debugger, decompilers like CFR, JD-GUI etc.) - [JD-GUI-DUO][13] : this project uses forks of JD-CORE projects and revives the old algorithm in project named [jd-core-v0][14] and brings improvements and bug fixes in a fork of [jd-core v1][15]. Also supports CFR, Procyon, Vineflower & JADX. Also Eclipse plugins are worth mentioning: - [ECD][16] and this [fork][17] - [JD-Eclipse][18] and this [fork][19] See also this [answer][20] [1]: https://www.researchgate.net/profile/Cesar_Soto-Valero/publication/334465294_The_Strengths_and_Behavioral_Quirks_of_Java_Bytecode_Decompilers/links/ [2]: https://github.com/leibnitz27/cfr [3]: https://github.com/mstrobel/procyon [4]: https://github.com/deathmarine/Luyten [5]: https://github.com/JetBrains/intellij-community/tree/master/plugins/java-decompiler/engine [6]: https://github.com/Vineflower/vineflower [7]: https://github.com/java-decompiler/jd-gui [8]: https://github.com/java-decompiler/jd-core [9]: http://www.kpdus.com/jad.html [10]: https://github.com/skylot/jadx [11]: https://github.com/Col-E/Recaf [12]: https://github.com/Konloch/bytecode-viewer [13]: https://github.com/nbauma109/jd-gui-duo [14]: https://github.com/nbauma109/jd-core-v0 [15]: https://github.com/nbauma109/jd-core [16]: https://github.com/ecd-plugin/ecd [17]: https://github.com/nbauma109/ecd [18]: https://github.com/java-decompiler/jd-eclipse [19]: https://github.com/nbauma109/jd-eclipse [20]: https://stackoverflow.com/a/78249357/8315843
|javascript|typed-arrays|
null
Single backtick is working in the browser or anywhere else with the combination Shift + ^ but in VSCode I am unable to type a single backtick, I need to do this combination twice & get 2 backticks and the cursor jumps to the right of the second backtick then when I try to go back with the left arrow key I get a special symbol as in the image; FS in a red square, I think some other key combination must be in conflict with the backtick. I'm using a Macbook with Swiss keyboard layout. I tried to assign commands which use Shift + ^ combination to another key combination without ^ but with no success [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/hHoGi.png
Enviroment: Linux Subsystem for Windows, Ubuntu 20.04. What I want to achieve is to make my buttom split smaller. [After using Shift+F2](https://i.stack.imgur.com/cYrL2.png) And I just couldn't use the hotkeys `Shift+Alt+[←↑→↓]` to resize. Along the way of finding a solution, I suddenly recall that I can use the `Shift+Alt` to change my language. So I went to the Windows settings to disable the hotkeys and restart my computer but nothing changed. Whatsmore, I also tried to remap my hotkey for the resizing to Alt+up in Windows terminal setting. Still nothing changed. I hope someone who has encountered the same problem and dealt with it could help nme out.
Couldn't Use Shift+Alt+[←↑→↓] to Resize the Splits in Byobu
|bash|ubuntu|terminal|hotkeys|byobu|
null
I'm probably missing something obvious or simple, but i'm struggling to add an 'if self.cut_scene_manager.cut_scene is None:' into my input of my player class Here is my main.py and player.py: ``` import pygame import sys from settings import * from level import Level from player import Player from npc import NPC from cut_scenes import CutSceneManager, CutSceneOne class Game: def __init__(self): pygame.init() self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('Passerine') self.clock = pygame.time.Clock() self.level = Level() self.npc_group = pygame.sprite.Group() self.player = Player((640, 360), self.level.all_sprites, self.level) self.npc1 = NPC((1460, 530),self.level.all_sprites, self.level) self.cut_scene_manager = CutSceneManager(self.screen) def run(self): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() dt = self.clock.tick() / 1000 self.npc_group.update(dt) self.npc_group.draw(self.screen) self.level.run(dt) self.cut_scene_manager.update() self.cut_scene_manager.draw() self.player.update(self.cut_scene_manager) pygame.display.update() if __name__ == '__main__': game = Game() game.run() import pygame from settings import * from support import * from cut_scenes import * class Player(pygame.sprite.Sprite): def __init__(self, pos, group, level): super().__init__(group) self.import_assets() self.status = 'down_idle' self.frame_index = 0 #general setup self.image = self.animations[self.status][self.frame_index] self.rect = self.image.get_rect(center = pos) self.hitbox = self.rect.copy().inflate((-126, -70)) self.z = LAYERS['main'] #movement attribtes self.direction = pygame.math.Vector2() self.pos = pygame.math.Vector2(self.rect.center) self.speed = 200 self.level = level self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # spawn point self.spawn_point = 30,440 self.cut_scene_manager = CutSceneManager(self.screen) # Set initial position to spawn point self.reset_position() def import_assets(self): self.animations = {'up': [], 'down':[], 'left':[], 'right':[], 'right_idle':[], 'left_idle':[], 'up_idle':[], 'down_idle':[]} for animation in self.animations.keys(): full_path = 'graphics/character/' + animation self.animations[animation] = import_folder(full_path) def reset_position(self): self.pos = pygame.math.Vector2(self.spawn_point) self.hitbox.center = self.pos self.rect.center = self.hitbox.center def set_spawn_point(self, new_spawn_point): self.spawn_point = new_spawn_point def animate(self, dt): self.frame_index += 4 * dt if self.frame_index >= len(self.animations[self.status]): self.frame_index = 0 self.image = self.animations[self.status][int(self.frame_index)] def input(self): keys = pygame.key.get_pressed() if self.cut_scene_manager.cut_scene is None: if keys[pygame.K_UP]: self.direction.y = -1 self.status = 'up' elif keys[pygame.K_DOWN]: self.direction.y = 1 self.status = 'down' else: self.direction.y = 0 if keys[pygame.K_RIGHT]: self.direction.x = 1 self.status = 'right' elif keys[pygame.K_LEFT]: self.direction.x = -1 self.status = 'left' else: self.direction.x = 0 def get_status(self): #checks if player should be idle if self.direction.magnitude() == 0: self.status = self.status.split('_')[0] + '_idle' def check_collision(self, new_pos): # Create a rect for the new position player_rect = pygame.Rect(new_pos[0] - self.rect.width / 2, new_pos[1] - self.rect.height / 2, self.rect.width, self.rect.height) # Iterate over the sprites in the 'Ground/walls' layer for sprite in self.level.all_sprites: if sprite.z == LAYERS['Walls'] and sprite.rect.colliderect(player_rect): #print("collision with wall") return True # Collision detected return False # No collision def move(self,dt): # normalizing a vector if self.direction.magnitude() > 0: self.direction = self.direction.normalize() # vertical movement new_y = self.pos.y + self.direction.y * self.speed * dt # Check if the new y position is within bounds if 430 <= new_y <= 675: # Replace MIN_Y_AXIS and MAX_Y_AXIS with your desired y-axis bounds self.pos.y = new_y self.hitbox.centery = round(self.pos.y) self.rect.centery = self.hitbox.centery # horizontal movement self.pos.x += self.direction.x * self.speed * dt self.hitbox.centerx = round(self.pos.x) self.rect.centerx = self.hitbox.centerx # Update hitbox and rect self.hitbox.center = self.pos self.rect.center = self.hitbox.center def update(self, dt): self.input() self.get_status() self.move(dt) self.animate(dt) if self.rect.centerx > 800: self.cut_scene_manager.start_cut_scene(CutSceneOne(self)) ``` I've tried defining cut_scene_manager within the Player class, but more problems keep occurring, usually with Player lacking attributes, or with CutSceneManager having 'unsupported opperand types'. Apologies if the problem is very obvious, I'm fairly new to Pygame and OOP, but this is a school project. Thank you!
creating cutscenes using OOP and pygame
|python|oop|pygame|
null
{"Voters":[{"Id":3001761,"DisplayName":"jonrsharpe"},{"Id":1940850,"DisplayName":"karel"},{"Id":1377002,"DisplayName":"Andy"}],"SiteSpecificCloseReasonIds":[13]}
When attempting to SSH into a remote host, if you encounter an issue where the connection fails with an error message, it's possible that the host's key has changed since the last connection. One solution to resolve this issue is to remove the entry associated with the remote host from the `known_hosts` file. Here are the steps to follow: 1. Locate the known_hosts file on your local machine. This file is typically located in the `.ssh` directory within your home directory. 1. Open the `known_hosts` file using a text editor. 1. Search for the entry corresponding to the remote host that you are trying to SSH into. 1. Delete the entire line containing the entry for the remote host. 1. Save the changes to the `known_hosts` file. 1. After removing the outdated entry from the known_hosts file, you should be able to SSH into the remote host without encountering any further issues.