content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
sequence
answers_scores
sequence
non_answers
sequence
non_answers_scores
sequence
tags
sequence
name
stringlengths
30
130
Q: Flutter SafeArea overlaps camera hole in Android simulator I am using SafeArea and my expectation that it would squeeze everything down below "brows", cameras, status bars, and what not... Unfortunately, when I run my app in Android simulator (Pixel 6 Pro), the camera overlaps my safe area. I don't have a real Android phone to confirm if the problem is real. Is it a simulator's artifact? If not, what should I do to give my SafeArea additional padding to account for the camera hole? A: It is likely that the issue you are experiencing is due to the differences in the physical design of different Android devices. Some devices, such as the Pixel 6 Pro, have a camera cutout or "hole" in the display, which can cause the SafeArea widget to not cover the entire screen as intended. To account for this and ensure that your app's content is not overlapped by the camera cutout, you can use the MediaQuery.of(context).padding property to get the padding values for the top, bottom, left, and right of the screen. You can then use these padding values to give your SafeArea widget additional padding to account for the camera cutout. Here's an example of how you could use the MediaQuery.of(context).padding property to give your SafeArea widget additional padding: SafeArea( // Use the MediaQuery.of(context).padding property to get the padding values for the top, bottom, left, and right of the screen top: MediaQuery.of(context).padding.top + 20, bottom: MediaQuery.of(context).padding.bottom + 20, left: MediaQuery.of(context).padding.left + 20, right: MediaQuery.of(context).padding.right + 20, child: YourAppContent(), ) In this example, the SafeArea widget is given additional padding for the top, bottom, left, and right of the screen using the MediaQuery.of(context).padding property. The additional padding values are added to the padding values returned by MediaQuery.of(context).padding to ensure that the camera cutout is covered by the SafeArea widget. I hope this helps! Let me know if you have any other questions.
Flutter SafeArea overlaps camera hole in Android simulator
I am using SafeArea and my expectation that it would squeeze everything down below "brows", cameras, status bars, and what not... Unfortunately, when I run my app in Android simulator (Pixel 6 Pro), the camera overlaps my safe area. I don't have a real Android phone to confirm if the problem is real. Is it a simulator's artifact? If not, what should I do to give my SafeArea additional padding to account for the camera hole?
[ "It is likely that the issue you are experiencing is due to the differences in the physical design of different Android devices. Some devices, such as the Pixel 6 Pro, have a camera cutout or \"hole\" in the display, which can cause the SafeArea widget to not cover the entire screen as intended.\nTo account for this and ensure that your app's content is not overlapped by the camera cutout, you can use the MediaQuery.of(context).padding property to get the padding values for the top, bottom, left, and right of the screen. You can then use these padding values to give your SafeArea widget additional padding to account for the camera cutout.\nHere's an example of how you could use the MediaQuery.of(context).padding property to give your SafeArea widget additional padding:\nSafeArea(\n // Use the MediaQuery.of(context).padding property to get the padding values for the top, bottom, left, and right of the screen\n top: MediaQuery.of(context).padding.top + 20,\n bottom: MediaQuery.of(context).padding.bottom + 20,\n left: MediaQuery.of(context).padding.left + 20,\n right: MediaQuery.of(context).padding.right + 20,\n child: YourAppContent(),\n)\n\nIn this example, the SafeArea widget is given additional padding for the top, bottom, left, and right of the screen using the MediaQuery.of(context).padding property. The additional padding values are added to the padding values returned by MediaQuery.of(context).padding to ensure that the camera cutout is covered by the SafeArea widget.\nI hope this helps! Let me know if you have any other questions.\n" ]
[ 1 ]
[]
[]
[ "flutter" ]
stackoverflow_0074671513_flutter.txt
Q: Enable CORS for Spring Cloud Function with Angular I have a Spring Boot application which is using Spring Cloud function to expose the functions as an end points. Currently we are using angular application as a consumer of the functions from the spring boot application. When we call the end point using httpClient module in angular, Its showing CORS error. I have tried different Bean configuration to enable the cors. Spring Boot App: @CrossOrigin("*") -> This did not work @SpringBootApplication public class CloudFunctionApplication { public static void main(String[] args) { SpringApplication.run(CloudFunctionApplication.class, args); } @Bean public Function<String, String> reverseString() { return value -> new StringBuilder(value).reverse().toString(); } @Bean --> This did not work public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/greeting-javaconfig").allowedOrigins("*"); } }; } } Angular Application. @Injectable() export class HttpService { constructor(private http: Http) { } getReverseStr(): Observable<Response> { const body = {"code": 123} return this.http.post("http://localhost:8080/reverseString", body); --> Giving cors error } } It would be great If some one could help to resolve CORS issue A: Remove @CrossOrigin("*") and try using this: public class DevCorsConfiguration implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/greeting-javaconfig").allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"); } } instead of this: public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/greeting-javaconfig").allowedOrigins("*"); } }; } This configuration enables CORS requests from any origin to the /greeting-javaconfig endpoint in the application. You can narrow the access by using the allowedOrigins, allowedMethods, allowedHeaders, exposedHeaders, maxAge or allowCredentials methods. I hope it should help. A: As per documentation try adding @Bean public WebMvcConfigurer configurer(){ return new WebMvcConfigurer(){ @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/*") .allowedOrigins("http://localhost:8080"); } }; } This makes the entire application request mappings accessible for all origins A: One potential fix is to use the @CrossOrigin annotation on the Spring Cloud function that you want to expose as an end point. adding the @CrossOrigin annotation to enable CORS for the reverseString function in your Spring Boot application might work: @CrossOrigin("*") @Bean public Function<String, String> reverseString() { return value -> new StringBuilder(value).reverse().toString(); }
Enable CORS for Spring Cloud Function with Angular
I have a Spring Boot application which is using Spring Cloud function to expose the functions as an end points. Currently we are using angular application as a consumer of the functions from the spring boot application. When we call the end point using httpClient module in angular, Its showing CORS error. I have tried different Bean configuration to enable the cors. Spring Boot App: @CrossOrigin("*") -> This did not work @SpringBootApplication public class CloudFunctionApplication { public static void main(String[] args) { SpringApplication.run(CloudFunctionApplication.class, args); } @Bean public Function<String, String> reverseString() { return value -> new StringBuilder(value).reverse().toString(); } @Bean --> This did not work public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/greeting-javaconfig").allowedOrigins("*"); } }; } } Angular Application. @Injectable() export class HttpService { constructor(private http: Http) { } getReverseStr(): Observable<Response> { const body = {"code": 123} return this.http.post("http://localhost:8080/reverseString", body); --> Giving cors error } } It would be great If some one could help to resolve CORS issue
[ "Remove @CrossOrigin(\"*\") and try using this:\npublic class DevCorsConfiguration implements WebMvcConfigurer {\n \n @Override\n public void addCorsMappings(CorsRegistry registry) {\n registry.addMapping(\"/greeting-javaconfig\").allowedMethods(\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"OPTIONS\");\n }\n }\n\ninstead of this:\npublic WebMvcConfigurer corsConfigurer() {\n return new WebMvcConfigurer() {\n @Override\n public void addCorsMappings(CorsRegistry registry) {\n registry.addMapping(\"/greeting-javaconfig\").allowedOrigins(\"*\");\n }\n };\n }\n\nThis configuration enables CORS requests from any origin to the /greeting-javaconfig endpoint in the application. You can narrow the access by using the allowedOrigins, allowedMethods, allowedHeaders, exposedHeaders, maxAge or allowCredentials methods.\nI hope it should help.\n", "As per documentation try adding\n@Bean\n public WebMvcConfigurer configurer(){\n return new WebMvcConfigurer(){\n @Override\n public void addCorsMappings(CorsRegistry registry) {\n registry.addMapping(\"/*\")\n .allowedOrigins(\"http://localhost:8080\");\n }\n };\n}\n\nThis makes the entire application request mappings accessible for all origins\n", "One potential fix is to use the @CrossOrigin annotation on the Spring Cloud function that you want to expose as an end point.\nadding the @CrossOrigin annotation to enable CORS for the reverseString function in your Spring Boot application might work:\n@CrossOrigin(\"*\")\n@Bean\npublic Function<String, String> reverseString() {\n return value -> new StringBuilder(value).reverse().toString();\n}\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "angular", "spring_boot", "spring_cloud_function" ]
stackoverflow_0074537101_angular_spring_boot_spring_cloud_function.txt
Q: problem password_reset_key_message.txt` - dj-rest-auth I'm creating a project (an api), but I'm stuck on the next part. When sending the password reset mail, specifically password_reset_key_message.txt, I can't capture the user's 'key' and 'uid', I want to change the address. Email delivery work fine, my problem is with password_reset_key_message.txt. Packages django==4.0.7 dj-rest-auth==2.2.5 django-allauth==0.51.0 I'm looking for something like this: {% extends "account/email/base_message.txt" %} {% load i18n %} {% block content %}{% autoescape off %}{% blocktrans %}You're receiving this e-mail because you or someone else has requested a password for your user account. It can be safely ignored if you did not request a password reset. Click the link below to reset your password.{% endblocktrans %} --- https://fontend-project.com/password-reset?id={{ uid }}&key={{ key }} --- {% if username %} {% blocktrans %}In case you forgot, your username is {{ username }}.{% endblocktrans %}{% endif %}{% endautoescape %}{% endblock %} But i can't capture 'uid and key. By default it uses '{{ password_reset_url }}', but I want to change the address, I need 'uid' and 'key' which are provided in '{{ password_reset_url }}' and I can't capture them, which I can do in the template o message file 'email_confirmation_message.txt'. Help please, I have tried and could not find the solution. A: To resolve this issue, I did the following: In the settings.py of the main project, add a custom_password_serializer: config/settings.py REST_AUTH_SERIALIZERS = { 'PASSWORD_RESET_SERIALIZER': 'myapp.serializers.CustomPasswordResetSerializer' } Create the custom_password_serializer: config/serializers.py from dj_rest_auth.serializers import PasswordResetSerializer from myapp.forms import CustomResetForm class CustomPasswordResetSerializer(PasswordResetSerializer): """ Serializer for requesting a password reset e-mail. """ @property def password_reset_form_class(self): return CustomResetForm Add new forms.py config/forms.py from dj_rest_auth.forms import AllAuthPasswordResetForm from django.contrib.sites.shortcuts import get_current_site from allauth.account.forms import default_token_generator from allauth.account.adapter import get_adapter from allauth.account.utils import user_pk_to_url_str class CustomResetForm(AllAuthPasswordResetForm): def save(self, request, **kwargs): current_site = get_current_site(request) email = self.cleaned_data['email'] token_generator = kwargs.get('token_generator', default_token_generator) for user in self.users: temp_key = token_generator.make_token(user) uid = user_pk_to_url_str(user) context = { 'current_site': current_site, 'user': user, 'key': temp_key, 'uid': uid, } get_adapter(request).send_mail( 'account/email/password_reset_key', email, context ) return self.cleaned_data['email'] Now you can capture user, key, uid in the password_reset_key_message.txt file Remember that password_reset_key_message.txt must go in the following path backend_directory/api/templates/account/email/ Thanks to StephenSorriaux for this solution, Source. I hope this solution helps.
problem password_reset_key_message.txt` - dj-rest-auth
I'm creating a project (an api), but I'm stuck on the next part. When sending the password reset mail, specifically password_reset_key_message.txt, I can't capture the user's 'key' and 'uid', I want to change the address. Email delivery work fine, my problem is with password_reset_key_message.txt. Packages django==4.0.7 dj-rest-auth==2.2.5 django-allauth==0.51.0 I'm looking for something like this: {% extends "account/email/base_message.txt" %} {% load i18n %} {% block content %}{% autoescape off %}{% blocktrans %}You're receiving this e-mail because you or someone else has requested a password for your user account. It can be safely ignored if you did not request a password reset. Click the link below to reset your password.{% endblocktrans %} --- https://fontend-project.com/password-reset?id={{ uid }}&key={{ key }} --- {% if username %} {% blocktrans %}In case you forgot, your username is {{ username }}.{% endblocktrans %}{% endif %}{% endautoescape %}{% endblock %} But i can't capture 'uid and key. By default it uses '{{ password_reset_url }}', but I want to change the address, I need 'uid' and 'key' which are provided in '{{ password_reset_url }}' and I can't capture them, which I can do in the template o message file 'email_confirmation_message.txt'. Help please, I have tried and could not find the solution.
[ "To resolve this issue, I did the following:\n\nIn the settings.py of the main project, add a custom_password_serializer:\n\nconfig/settings.py\n\nREST_AUTH_SERIALIZERS = {\n 'PASSWORD_RESET_SERIALIZER': 'myapp.serializers.CustomPasswordResetSerializer'\n}\n\n\n\nCreate the custom_password_serializer:\n\nconfig/serializers.py\nfrom dj_rest_auth.serializers import PasswordResetSerializer\nfrom myapp.forms import CustomResetForm\n\nclass CustomPasswordResetSerializer(PasswordResetSerializer):\n \"\"\"\n Serializer for requesting a password reset e-mail.\n \"\"\"\n @property\n def password_reset_form_class(self):\n return CustomResetForm\n\n\n\nAdd new forms.py\n\nconfig/forms.py\nfrom dj_rest_auth.forms import AllAuthPasswordResetForm\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom allauth.account.forms import default_token_generator\nfrom allauth.account.adapter import get_adapter\nfrom allauth.account.utils import user_pk_to_url_str\n\nclass CustomResetForm(AllAuthPasswordResetForm):\n\n def save(self, request, **kwargs):\n current_site = get_current_site(request)\n email = self.cleaned_data['email']\n token_generator = kwargs.get('token_generator', default_token_generator)\n\n for user in self.users:\n\n temp_key = token_generator.make_token(user)\n uid = user_pk_to_url_str(user)\n\n context = {\n 'current_site': current_site,\n 'user': user,\n 'key': temp_key,\n 'uid': uid,\n }\n get_adapter(request).send_mail(\n 'account/email/password_reset_key', email, context\n )\n return self.cleaned_data['email']\n\n\nNow you can capture user, key, uid in the password_reset_key_message.txt file\n\nRemember that password_reset_key_message.txt must go in the following path backend_directory/api/templates/account/email/\nThanks to StephenSorriaux for this solution, Source.\nI hope this solution helps.\n" ]
[ 0 ]
[]
[]
[ "api", "dj_rest_auth", "django_allauth", "python" ]
stackoverflow_0073476094_api_dj_rest_auth_django_allauth_python.txt
Q: How can I sort a list alphabetically based on the Hebrew language in Dart? Context In Dart, if I have a list: final myList = ['b', 'a']; and I wanted to sort it alphabetically, I would use: myList.sort( (String a, String b) => a.compareTo(b), ); The output of myList is now: ['a', 'b'] Now, this works on letters that are in the English alphabet. Question But if I have a list that's in Hebrew: final unorderedHebAlphabet = ['ื', 'ื‘']; I can't sort it as above using with: unorderedHebAlphabet.sort((String a, String b) => a.compareTo(b)) It doesn't sort. Expected output, instead of: ['ื', 'ื‘'] Should be: ['ื‘', 'ื'] How can I sort a list Alphabetically in the Hebrew language? Notes As a reference, the Hebrew alphabet sorted would be in this order: final sortedHebrewAlphabet = [ 'ื', 'ื‘', 'ื’', 'ื“', 'ื”', 'ื•', 'ื–', 'ื—', 'ื˜', 'ื™', 'ื›', 'ืœ', 'ืž', 'ื ', 'ืก', 'ืข', 'ืค', 'ืฆ', 'ืง', 'ืจ', 'ืฉ', 'ืช', ]; A: It does sort (by UTF-16 code units), but it's being shown in an unintuitive way. final unorderedHebAlphabet = ['ื', 'ื‘']; seems to be parsed RTL, so in the constructed list, element 0 is ื and element 1 is ื‘. That's already the desired order, so sorting it does not change it. (Mixing LTR and RTL text is confusing.) For example: import 'package:collection/collection.dart'; void main() { var literal = ['ื', 'ื‘']; print(literal[0]); // Prints: ื print(literal[1]); // Prints: ื‘ const alef = 'ื'; const bet = 'ื‘'; const expectedOrder = [alef, bet]; const listEquals = ListEquality(); print(listEquals.equals(literal..sort(), expectedOrder)); // Prints: true print(listEquals.equals([bet, alef]..sort(), expectedOrder)); // Prints: true } You also can observe that the elements are printed in the correct order if you prefix output with the Unicode LTR override (U+202D) to force rendering the text as LTR. Compare: const ltr = '\u202D'; print('$expectedOrder'); print('$ltr$expectedOrder'); Or you could simply print the elements separately: expectedOrder.forEach(print); which prints: ื ื‘ I'm not experienced with dealing with RTL text, but I'd probably avoid mixing LTR and RTL text in code and instead express them as hexadecimal Unicode code points to avoid confusion. A: To sort a list of strings in the Hebrew language alphabetically, you can use the compareTo method on the String class, passing in the String.localeCompare function as the argument. The String.localeCompare function will sort the strings based on the specified locale, which in this case is Hebrew: final unorderedHebAlphabet = ['ื', 'ื‘']; unorderedHebAlphabet.sort((String a, String b) => a.compareTo(b, String.localeCompare)); // Output: ['ื‘', 'ื'] You can also specify the locale directly in the compareTo method: unorderedHebAlphabet.sort((String a, String b) => a.compareTo(b, locale: 'he')); // Output: ['ื‘', 'ื'] A: It is being printed out in correct order. It's the Console which is printing it in the way it is. When you save the sorted list into a file and read it again, you get the ืื‘ characters as first two characters. So they are being written/iterated in right order. If you print the values one letter per line, you would get desired result. I am not 100% sure how console is handling it, but dart is simply passing it to the STDOUT (default console), and console is detecting that the string is actually RTL and printing (or writing to STDOUT) in that way. I did little fiddling which you can see: import 'dart:io'; void main(List<String> arguments) { final myList = [ 'ื', 'ื‘', 'ื’', 'ื“', 'ื”', 'ื•', 'ื–', 'ื—', 'ื˜', 'ื™', 'ื›', 'ืœ', 'ืž', 'ื ', 'ืก', 'ืข', 'ืค', 'ืฆ', 'ืง', 'ืจ', 'ืฉ', 'ืช' ]; // for (var i in myList) { // print("$i => ${i.runes.toList()}"); // } myList.sort(); String s = ""; for (var i in myList) { s += i; } print('$s'); print(myList.first); final file = new File('/Users/rahul/Desktop/string_l/test.txt'); file.writeAsStringSync(s, flush: true); final read = file.readAsStringSync().substring(0, 2); print(read); // You can also verify by calling print with every element for (var i in myList) { print(i); } } output ืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืœืžื ืกืขืคืฆืงืจืฉืช ื ืื‘ ื ื‘ ื’ ื“ ื” ื• ื– ื— ื˜ ื™ ื› ืœ ืž ื  ืก ืข ืค ืฆ ืง ืจ ืฉ ืช A: To sort a list of strings alphabetically in Hebrew, you can use the dart:intl package's Collator class, which provides support for sorting strings in different languages and locales. To use the Collator class, you will first need to add the dart:intl package to your pubspec.yaml file and run flutter pub get to install it. Then, you can use the Collator class's compare method to compare two strings and determine their relative order in the Hebrew alphabet. Here's an example of how you could use the Collator class to sort a list of strings alphabetically in Hebrew: import 'package:intl/intl.dart'; // Define the unordered list of Hebrew strings final unorderedHebAlphabet = ['ื', 'ื‘']; // Create a Collator instance for the Hebrew language final collator = Collator('he'); // Use the Collator instance's compare method to sort the list of Hebrew strings alphabetically unorderedHebAlphabet.sort((String a, String b) => collator.compare(a, b)); // The unorderedHebAlphabet list is now sorted
How can I sort a list alphabetically based on the Hebrew language in Dart?
Context In Dart, if I have a list: final myList = ['b', 'a']; and I wanted to sort it alphabetically, I would use: myList.sort( (String a, String b) => a.compareTo(b), ); The output of myList is now: ['a', 'b'] Now, this works on letters that are in the English alphabet. Question But if I have a list that's in Hebrew: final unorderedHebAlphabet = ['ื', 'ื‘']; I can't sort it as above using with: unorderedHebAlphabet.sort((String a, String b) => a.compareTo(b)) It doesn't sort. Expected output, instead of: ['ื', 'ื‘'] Should be: ['ื‘', 'ื'] How can I sort a list Alphabetically in the Hebrew language? Notes As a reference, the Hebrew alphabet sorted would be in this order: final sortedHebrewAlphabet = [ 'ื', 'ื‘', 'ื’', 'ื“', 'ื”', 'ื•', 'ื–', 'ื—', 'ื˜', 'ื™', 'ื›', 'ืœ', 'ืž', 'ื ', 'ืก', 'ืข', 'ืค', 'ืฆ', 'ืง', 'ืจ', 'ืฉ', 'ืช', ];
[ "It does sort (by UTF-16 code units), but it's being shown in an unintuitive way. final unorderedHebAlphabet = ['ื', 'ื‘']; seems to be parsed RTL, so in the constructed list, element 0 is ื and element 1 is ื‘. That's already the desired order, so sorting it does not change it. (Mixing LTR and RTL text is confusing.)\nFor example:\nimport 'package:collection/collection.dart';\n\nvoid main() {\n var literal = ['ื', 'ื‘'];\n print(literal[0]); // Prints: ื\n print(literal[1]); // Prints: ื‘\n\n const alef = 'ื';\n const bet = 'ื‘';\n const expectedOrder = [alef, bet];\n\n const listEquals = ListEquality();\n \n print(listEquals.equals(literal..sort(), expectedOrder)); // Prints: true\n print(listEquals.equals([bet, alef]..sort(), expectedOrder)); // Prints: true\n}\n\nYou also can observe that the elements are printed in the correct order if you prefix output with the Unicode LTR override (U+202D) to force rendering the text as LTR. Compare:\nconst ltr = '\\u202D';\nprint('$expectedOrder');\nprint('$ltr$expectedOrder');\n\nOr you could simply print the elements separately:\nexpectedOrder.forEach(print);\n\nwhich prints:\nื\nื‘\n\nI'm not experienced with dealing with RTL text, but I'd probably avoid mixing LTR and RTL text in code and instead express them as hexadecimal Unicode code points to avoid confusion.\n", "To sort a list of strings in the Hebrew language alphabetically, you can use the compareTo method on the String class, passing in the String.localeCompare function as the argument. The String.localeCompare function will sort the strings based on the specified locale, which in this case is Hebrew:\nfinal unorderedHebAlphabet = ['ื', 'ื‘'];\n\nunorderedHebAlphabet.sort((String a, String b) =>\na.compareTo(b, String.localeCompare));\n\n// Output: ['ื‘', 'ื']\n\nYou can also specify the locale directly in the compareTo method:\nunorderedHebAlphabet.sort((String a, String b) =>\na.compareTo(b, locale: 'he'));\n\n// Output: ['ื‘', 'ื']\n\n", "It is being printed out in correct order. It's the Console which is printing it in the way it is.\nWhen you save the sorted list into a file and read it again, you get the ืื‘ characters as first two characters. So they are being written/iterated in right order.\nIf you print the values one letter per line, you would get desired result. I am not 100% sure how console is handling it, but dart is simply passing it to the STDOUT (default console), and console is detecting that the string is actually RTL and printing (or writing to STDOUT) in that way.\nI did little fiddling which you can see:\nimport 'dart:io';\n\nvoid main(List<String> arguments) {\n final myList = [\n 'ื',\n 'ื‘',\n 'ื’',\n 'ื“',\n 'ื”',\n 'ื•',\n 'ื–',\n 'ื—',\n 'ื˜',\n 'ื™',\n 'ื›',\n 'ืœ',\n 'ืž',\n 'ื ',\n 'ืก',\n 'ืข',\n 'ืค',\n 'ืฆ',\n 'ืง',\n 'ืจ',\n 'ืฉ',\n 'ืช'\n ];\n\n // for (var i in myList) {\n // print(\"$i => ${i.runes.toList()}\");\n // }\n\n myList.sort();\n\n String s = \"\";\n\n for (var i in myList) {\n s += i;\n }\n\n print('$s');\n\n print(myList.first);\n\n final file = new File('/Users/rahul/Desktop/string_l/test.txt');\n file.writeAsStringSync(s, flush: true);\n\n final read = file.readAsStringSync().substring(0, 2);\n print(read);\n\n // You can also verify by calling print with every element\n for (var i in myList) {\n print(i);\n }\n}\n\n\noutput\nืื‘ื’ื“ื”ื•ื–ื—ื˜ื™ื›ืœืžื ืกืขืคืฆืงืจืฉืช\nื\nืื‘\nื\nื‘\nื’\nื“\nื”\nื•\nื–\nื—\nื˜\nื™\nื›\nืœ\nืž\nื \nืก\nืข\nืค\nืฆ\nืง\nืจ\nืฉ\nืช\n\n", "To sort a list of strings alphabetically in Hebrew, you can use the dart:intl package's Collator class, which provides support for sorting strings in different languages and locales.\nTo use the Collator class, you will first need to add the dart:intl package to your pubspec.yaml file and run flutter pub get to install it. Then, you can use the Collator class's compare method to compare two strings and determine their relative order in the Hebrew alphabet.\nHere's an example of how you could use the Collator class to sort a list of strings alphabetically in Hebrew:\nimport 'package:intl/intl.dart';\n\n// Define the unordered list of Hebrew strings\nfinal unorderedHebAlphabet = ['ื', 'ื‘'];\n\n// Create a Collator instance for the Hebrew language\nfinal collator = Collator('he');\n\n// Use the Collator instance's compare method to sort the list of Hebrew strings alphabetically\nunorderedHebAlphabet.sort((String a, String b) => collator.compare(a, b));\n\n// The unorderedHebAlphabet list is now sorted\n\n" ]
[ 5, 2, 1, 0 ]
[ "import 'dart:io';\n\nfinal unorderedHebAlphabet = [\n 'ื‘',\n 'ื’',\n 'ื“',\n 'ื”',\n 'ื•',\n 'ื–',\n 'ื—',\n 'ื˜',\n 'ื™',\n 'ื›',\n 'ืœ',\n 'ืž',\n 'ื ',\n 'ืก',\n 'ืข',\n 'ืค',\n 'ืฆ',\n 'ืง',\n 'ืจ',\n 'ืฉ',\n 'ืช',\n 'ื'\n];\n\n\nvoid main() {\n print(unorderedHebAlphabet);\n unorderedHebAlphabet\n .sort((a, b) => a.codeUnitAt(0).compareTo(b.codeUnitAt(0)));\n print(unorderedHebAlphabet);\n}\n\n" ]
[ -1 ]
[ "dart", "flutter", "hebrew", "list", "sorting" ]
stackoverflow_0074539877_dart_flutter_hebrew_list_sorting.txt
Q: How ASP.NET MVC 5 can do fast processing in C# Async How can I run the above code in the fastest way. What is the best practice? public ActionResult ExampleAction() { // 200K items var results = dbContext.Results.ToList(); foreach (var result in results) { // 10 - 40 items result.Kazanim = JsonConvert.SerializeObject( dbContext.SubTables // 2,5M items .Where(x => x.FooId == result.FooId) .Select(select => new { BarId = select.BarId, State = select.State, }).ToList()); dbContext.Entry(result).State = EntityState.Modified; dbContext.SaveChanges(); } return Json(true, JsonRequestBehavior.AllowGet); } This process takes an average of 500 ms as sync. I have about 2M records. The process is done 200K times. How should I code asynchronously? How can I do it faster and easier with an async method. A: Here are two suggestions that can improve the performance multiple orders of magnitude: Do work in batches: Make the client send a page of data to process; and/or In the web server code add items to a queue and process them separately. Use SQL instead of EF: Write an efficient SQL; and/or Use the stored proc to do the work inside the db rather than move data between the db and the code. A: There's nothing you can do with that code asynchronously for improving its performance. But there's something that can certainly make it faster. If you call dbContext.SaveChanges() inside the loop, EF will write back the changes to the database for every single entity as a separate transaction. Move your dbContext.SaveChanges() after the loop. This way EF will write back all your changes at once after in one single transaction. Always try to have as few calls to .SaveChanges() as possible. One call with 50 changes is much better, faster and more efficient than 50 calls for 1 change each. A: and welcome. There's quite a lot I see incorrect in terms of asynchronicity, but I guess it only matters if there are concurrent users calling your server. This has to do with scalability and the thread pool in charge of spinning up threads to take care of your incoming HTTP requests. You see, if you occupy a thread pool thread for a long time, that thread will not contribute to dequeueing incoming HTTP requests. This pretty much puts you in a position where you can spin up a maximum of around 2 new thread pool threads per second. If your incoming HTTP request rate is faster than the pool's ability to produce threads, all of your HTTP requests will start seeing increased response times (slowness). So as a general rule, when doing I/O intensive work, always go async. There are asynchronous versions of most (or all) of the materializing methods like .ToList(): ToListAsync(), CountAsync(), AnyAsync(), etc. There is also a SaveChangesAsync(). First thing I would do is use these under normal circumstances. Yours don't seem to be, so I mentioned this for completeness only. I think that you must, at the very least, run this heavy process outside the thread pool. Use Task.Factory.StartNew() with the TaskCreationOptions.LongRunning but run synchronous code so you don't fall in the trap of awaiting the returned task in vain. Now, all that just to have a "proper" skeleton. We haven't really talked about how to make this run faster. Let's do that. Personally, I think you need some benchmarking between different methods. It looks like you have benchmarked this code. Now listen to @tymtam and see if a stored procedure version runs faster. My hunch, just like @tymtam's, is that it will be definitely faster. If for whatever reason you insist in running this with C#, I would parallelize the work. The problem with this is Entity Framework. As per usual, my very popular, yet unfriendly ORM, is giving us a big but. EF's DB context works with a single connection and disallows multiple simultaneous queries. So you cannot parallelize this with EF. I would then move to my good, amazing friend, Dapper. Using Dapper, you could divide the workload in threads, and each thread would do an independent DB connection, and through that connection, take care of a portion of the 200K result set you obtain at the beginning.
How ASP.NET MVC 5 can do fast processing in C# Async
How can I run the above code in the fastest way. What is the best practice? public ActionResult ExampleAction() { // 200K items var results = dbContext.Results.ToList(); foreach (var result in results) { // 10 - 40 items result.Kazanim = JsonConvert.SerializeObject( dbContext.SubTables // 2,5M items .Where(x => x.FooId == result.FooId) .Select(select => new { BarId = select.BarId, State = select.State, }).ToList()); dbContext.Entry(result).State = EntityState.Modified; dbContext.SaveChanges(); } return Json(true, JsonRequestBehavior.AllowGet); } This process takes an average of 500 ms as sync. I have about 2M records. The process is done 200K times. How should I code asynchronously? How can I do it faster and easier with an async method.
[ "Here are two suggestions that can improve the performance multiple orders of magnitude:\n\nDo work in batches:\n\nMake the client send a page of data to process; and/or\nIn the web server code add items to a queue and process them separately.\n\n\nUse SQL instead of EF:\n\nWrite an efficient SQL; and/or\nUse the stored proc to do the work inside the db rather than move data between the db and the code.\n\n\n\n", "There's nothing you can do with that code asynchronously for improving its performance. But there's something that can certainly make it faster.\nIf you call dbContext.SaveChanges() inside the loop, EF will write back the changes to the database for every single entity as a separate transaction.\nMove your dbContext.SaveChanges() after the loop. This way EF will write back all your changes at once after in one single transaction.\nAlways try to have as few calls to .SaveChanges() as possible. One call with 50 changes is much better, faster and more efficient than 50 calls for 1 change each.\n", "and welcome.\nThere's quite a lot I see incorrect in terms of asynchronicity, but I guess it only matters if there are concurrent users calling your server. This has to do with scalability and the thread pool in charge of spinning up threads to take care of your incoming HTTP requests.\nYou see, if you occupy a thread pool thread for a long time, that thread will not contribute to dequeueing incoming HTTP requests. This pretty much puts you in a position where you can spin up a maximum of around 2 new thread pool threads per second. If your incoming HTTP request rate is faster than the pool's ability to produce threads, all of your HTTP requests will start seeing increased response times (slowness).\nSo as a general rule, when doing I/O intensive work, always go async. There are asynchronous versions of most (or all) of the materializing methods like .ToList(): ToListAsync(), CountAsync(), AnyAsync(), etc. There is also a SaveChangesAsync(). First thing I would do is use these under normal circumstances. Yours don't seem to be, so I mentioned this for completeness only.\nI think that you must, at the very least, run this heavy process outside the thread pool. Use Task.Factory.StartNew() with the TaskCreationOptions.LongRunning but run synchronous code so you don't fall in the trap of awaiting the returned task in vain.\nNow, all that just to have a \"proper\" skeleton. We haven't really talked about how to make this run faster. Let's do that.\nPersonally, I think you need some benchmarking between different methods. It looks like you have benchmarked this code. Now listen to @tymtam and see if a stored procedure version runs faster. My hunch, just like @tymtam's, is that it will be definitely faster.\nIf for whatever reason you insist in running this with C#, I would parallelize the work. The problem with this is Entity Framework. As per usual, my very popular, yet unfriendly ORM, is giving us a big but. EF's DB context works with a single connection and disallows multiple simultaneous queries. So you cannot parallelize this with EF. I would then move to my good, amazing friend, Dapper. Using Dapper, you could divide the workload in threads, and each thread would do an independent DB connection, and through that connection, take care of a portion of the 200K result set you obtain at the beginning.\n" ]
[ 2, 1, 0 ]
[]
[]
[ ".net", "async_await", "c#" ]
stackoverflow_0074642331_.net_async_await_c#.txt
Q: Updating/mutating a session with next-auth and tRPC I am building a multi-tenant NextJS app that uses next-auth for account authentication, tRPC for API's, and postgresql for a data store. I am trying to find a way to dynamically update/set/mutate a session value based on some client-side interaction The approach I am taking is similar to the one described in this article: a User is granted access to an Organization through a Membership a User may have a Membership to >1 Organization a User can change which Organization they are "logged in" to through some client-side UI. When the user authenticates, I want to: set session.user.orgId to some orgId (if they belong to an org) When the user changes the org they are accessing through some client-side UI, I want to: update session.user.orgId = newOrgId (validating they have proper permissions before doing so, of course). I have searched the net for ways to update/mutate session values, and as far as I can tell, it's only possible using next-auth's callbacks: ... callbacks: { async session({ session, user, token }) { // we can modify session here, i.e `session.orgId = 'blah'` // or look up a value in the db and attach it here. return session }, ... } However, there is no clear way to trigger this update from the client, outside of the authentication flow. I.E, if the user clicks to change their org in some UI, how do I validate the change + update the session value, without requiring the user to re-authenticate? A: Hack into NextAuth's PrismaAdapter. Mine looks like this: File: [...nextauth].ts import NextAuth, { Awaitable, type NextAuthOptions } from "next-auth"; import { PrismaAdapter } from "@next-auth/prisma-adapter"; import type { AdapterSession, AdapterUser } from "next-auth/adapters"; import { prisma } from "../../../server/db/client"; import { MembershipRole } from "@prisma/client"; ... const adapter = PrismaAdapter(prisma); adapter.createSession = (session: { sessionToken: string; userId: string; expires: Date; }): Awaitable<AdapterSession> => { return prisma.user .findUniqueOrThrow({ where: { id: session.userId, }, select: { memberships: { where: { isActiveOrg: true, }, select: { role: true, organization: true, }, }, }, }) .then((userWithOrg) => { const membership = userWithOrg.memberships[0]; const orgId = membership?.organization.id; return prisma.session.create({ data: { expires: session.expires, sessionToken: session.sessionToken, user: { connect: { id: session.userId }, }, organization: { connect: { id: orgId, }, }, role: membership?.role as MembershipRole, }, }); }); }; // the authOptions to user with NextAuth export const authOptions: NextAuthOptions = { // Include user.id on session callbacks: { session({ session, user }) { if (session.user) { session.user.id = user.id; } return session; }, }, adapter: adapter, // Configure one or more authentication providers providers: [ ... ], }; export default NextAuth(authOptions);
Updating/mutating a session with next-auth and tRPC
I am building a multi-tenant NextJS app that uses next-auth for account authentication, tRPC for API's, and postgresql for a data store. I am trying to find a way to dynamically update/set/mutate a session value based on some client-side interaction The approach I am taking is similar to the one described in this article: a User is granted access to an Organization through a Membership a User may have a Membership to >1 Organization a User can change which Organization they are "logged in" to through some client-side UI. When the user authenticates, I want to: set session.user.orgId to some orgId (if they belong to an org) When the user changes the org they are accessing through some client-side UI, I want to: update session.user.orgId = newOrgId (validating they have proper permissions before doing so, of course). I have searched the net for ways to update/mutate session values, and as far as I can tell, it's only possible using next-auth's callbacks: ... callbacks: { async session({ session, user, token }) { // we can modify session here, i.e `session.orgId = 'blah'` // or look up a value in the db and attach it here. return session }, ... } However, there is no clear way to trigger this update from the client, outside of the authentication flow. I.E, if the user clicks to change their org in some UI, how do I validate the change + update the session value, without requiring the user to re-authenticate?
[ "Hack into NextAuth's PrismaAdapter. Mine looks like this:\nFile: [...nextauth].ts\n\n\nimport NextAuth, { Awaitable, type NextAuthOptions } from \"next-auth\";\nimport { PrismaAdapter } from \"@next-auth/prisma-adapter\";\nimport type { AdapterSession, AdapterUser } from \"next-auth/adapters\";\nimport { prisma } from \"../../../server/db/client\";\nimport { MembershipRole } from \"@prisma/client\";\n\n...\n\nconst adapter = PrismaAdapter(prisma);\nadapter.createSession = (session: {\n sessionToken: string;\n userId: string;\n expires: Date;\n}): Awaitable<AdapterSession> => {\n return prisma.user\n .findUniqueOrThrow({\n where: {\n id: session.userId,\n },\n select: {\n memberships: {\n where: {\n isActiveOrg: true,\n },\n select: {\n role: true,\n organization: true,\n },\n },\n },\n })\n .then((userWithOrg) => {\n const membership = userWithOrg.memberships[0];\n const orgId = membership?.organization.id;\n\n return prisma.session.create({\n data: {\n expires: session.expires,\n sessionToken: session.sessionToken,\n user: {\n connect: { id: session.userId },\n },\n organization: {\n connect: {\n id: orgId,\n },\n },\n role: membership?.role as MembershipRole,\n },\n });\n });\n};\n\n\n// the authOptions to user with NextAuth\nexport const authOptions: NextAuthOptions = {\n // Include user.id on session\n callbacks: {\n session({ session, user }) {\n if (session.user) {\n session.user.id = user.id;\n }\n return session;\n },\n },\n\n adapter: adapter,\n\n // Configure one or more authentication providers\n providers: [\n ...\n ],\n};\n\nexport default NextAuth(authOptions);\n\n\n\n" ]
[ 0 ]
[]
[]
[ "next.js", "next_auth", "trpc.io" ]
stackoverflow_0073536282_next.js_next_auth_trpc.io.txt
Q: CDK Reading From Vault In Terraform can read the values from Vault (stored in AWS SSM as secure strings). However, with CDK we have to put it in SSM or secrets manager and read the value in CDK. Is there a way CDK can read from the Vault? A: It should be possible using AWS Custom Resources. AWS CDK provides a way to create custom resources that respond to CloudFormation's CRUD events (https://docs.aws.amazon.com/cdk/api/v1/docs/custom-resources-readme.html). According to the AWS Custom Resource docs, "return values are defined by the custom resource provider, and are retrieved by calling Fn::GetAtt on the provider-defined attributes". So after creating a custom resource that returns your Hashicorp Vault key as an attribute, you can have another resource reference that value using Fn::GetAtt in CDK, and the value should not get publicly exposed in the CloudFormation template. Another alternative could be to sync secret values between Hashicorp Vault and AWS SSM/SecretsManager.
CDK Reading From Vault
In Terraform can read the values from Vault (stored in AWS SSM as secure strings). However, with CDK we have to put it in SSM or secrets manager and read the value in CDK. Is there a way CDK can read from the Vault?
[ "It should be possible using AWS Custom Resources. AWS CDK provides a way to create custom resources that respond to CloudFormation's CRUD events (https://docs.aws.amazon.com/cdk/api/v1/docs/custom-resources-readme.html).\nAccording to the AWS Custom Resource docs, \"return values are defined by the custom resource provider, and are retrieved by calling Fn::GetAtt on the provider-defined attributes\". So after creating a custom resource that returns your Hashicorp Vault key as an attribute, you can have another resource reference that value using Fn::GetAtt in CDK, and the value should not get publicly exposed in the CloudFormation template.\nAnother alternative could be to sync secret values between Hashicorp Vault and AWS SSM/SecretsManager.\n" ]
[ 0 ]
[]
[]
[ "amazon_web_services", "aws_ssm", "ncurses_cdk", "vault" ]
stackoverflow_0074607981_amazon_web_services_aws_ssm_ncurses_cdk_vault.txt
Q: "Required request part 'image' is not present in" error in springboot with reactjs When i try to upload a image in react, and send it to a spring boot api to save the file in a database, I get the following errors in spring boot: 2022-12-04 03:25:28.610 WARN 15080 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'image' is not present] 2022-12-04 03:25:28.631 WARN 15080 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.LinkedHashMap<java.lang.String,java.util.List<java.lang.String>>` from Array value (token `JsonToken.START_ARRAY`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.LinkedHashMap<java.lang.String,java.util.List<java.lang.String>>` from Array value (token `JsonToken.START_ARRAY`)<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]] Idk how to solve this. I've tried searching around, but havent found any answer. Im also unsure if the problem is in my react code or in my springboot code. I think my error is in reactjs, because ive seen in other posts for people have somewhat the same problem, that their problem has been their react code. But I havent figured out what exactly might be wrong with my react code. Im also posting my spring boot code in case you may want to look at it, My react code: const FileUpload = () => { const link = "http://localhost:8080/uploadimage?key" var formData = new FormData() const [fileName, setFilename] = useState("") const [tags, setTags] = useState([]) {/* THIS IS CODE FOR SELECTING A FILE TO UPLOAD*/} {/* IM TRYING TO DEFINE IMAGE BY PUTTING IT IN QUOTES IN FROMDATA.APPEND */} const handleFile = (e) => { setFilename(e.target.files[0].name) console.log("handle file") console.log(e.target.files[0]) formData.append("image", e.target.files[0]) } const uploadFile = (e) => { {/* THIS IS CODE FOR FILE UPLOADING*/} console.log("sending...") console.log(formData) axios.post( link, formData, { header: { 'Content-Type': 'multipart/form-data' } }) .then(res => { console.log(res.data) }) .catch(error => { console.log(error) }) {/* THIS IS CODE FOR SOMETHING ELSE; SOME TAGHANDLING */} setTimeout(3000) const taglink = "http://localhost:8080/givetags/" + fileName; axios.post(taglink, tags) .then(res => ( console.log(res.data) )) } {/* THIS IS CODE IS ALSO FOR SOMETHING ELSE*/} function updateTags(e) { const log = {...tags} log[e.target.id] = e.target.value.split(" ") setTags(log) } return ( <div> <Container> <Card.Title className='text-center mb-3'>Upload File</Card.Title> <Form.Group controlId='file' className='mb-3'> <Form.Control type='file' onChange={(e) => handleFile(e)}></Form.Control> </Form.Group> <Form.Group controlId='tags' className='mb-3'> <Form.Control onChange={(e) => updateTags(e)} type="text" placeholder='Write tags'></Form.Control> </Form.Group> <Button onClick={(e) => uploadFile(e)}>Upload File</Button> </Container> <TagsConvention></TagsConvention> </div> ) } export default FileUpload This is my springboot code: Controller: @RestController public class FileController { @Autowired private ImageServiceImpl service; //==========================For uploading a file====================================== @CrossOrigin(origins = "http://localhost:3000") @PostMapping("/uploadimage") public ResponseEntity<?> uploadImage(@RequestParam("image") MultipartFile file) throws IOException { String uploadImage = service.uploadImage(file); return ResponseEntity.status(HttpStatus.OK) .body(uploadImage); } @CrossOrigin(origins = "http://localhost:3000") @GetMapping("/getimage/{fileName}") public ResponseEntity<?> downloadImage(@PathVariable String fileName){ byte[] file=service.downloadImage(fileName); System.out.println(file); return ResponseEntity.status(HttpStatus.OK) .contentType(MediaType.valueOf(service.getType(fileName))) .body(file); } @CrossOrigin(origins = "http://localhost:3000") @PostMapping("/givetags/{fileName}") public ImageData giveImagetags(@PathVariable String fileName, @RequestBody Map<String, List<String>> tags) { //return service.giveImageTags(fileName, tags); //return service.giveImageTags(fileName, tags); System.out.println(tags); List<String> tagList = tags.get("tags"); return service.giveImageTags(fileName, tagList); } @CrossOrigin(origins = "http://localhost:3000") @GetMapping("/getallimages") public List<String> getAllImages() { return service.getAllImages(); } } My model for the image: @Entity @Table(name = "ImageData") @Data @AllArgsConstructor @NoArgsConstructor @Builder public class ImageData implements Image{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long imageDataId; private String name; private String type; @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinTable(name="file_has_tag", joinColumns = {@JoinColumn(name="image_data_id")}, inverseJoinColumns = {@JoinColumn(name = "tag_id")}) @JsonIgnoreProperties("image_data") private Set<Tag> tags; @Lob @Column(name = "image_data",length = 1000) private byte[] data; @Override public String toString() { return "ImageData{" + "imageDataId=" + imageDataId + ", name='" + name + '\'' + ", type='" + type + '\'' + ", tags=" + tags + '}'; } } Service function for uploading a file: public String uploadImage(MultipartFile file) throws IOException { ImageData imageData = imageDataRepository.save(ImageData.builder() .name(file.getOriginalFilename()) .type(file.getContentType()) .data(ImageUtils.compressImage(file.getBytes())).build()); //"data" is from the model class System.out.println(imageData.toString()); if (imageData != null) { return "file uploaded successfully : " + file.getOriginalFilename(); } return null; } functions in utils class for compressing image public static byte[] compressImage(byte[] data) { Deflater deflater = new Deflater(); deflater.setLevel(Deflater.BEST_COMPRESSION); deflater.setInput(data); deflater.finish(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); byte[] tmp = new byte[4*1024]; while (!deflater.finished()) { int size = deflater.deflate(tmp); outputStream.write(tmp, 0, size); } try { outputStream.close(); } catch (Exception ignored) { } return outputStream.toByteArray(); } Ive tried to change the value of formdata, and the key in "image" in fromdata.append, but I havent figured it out. Ive also tried to search up the problem, but people have had different syntax problems from me, so idk what might be the problem. A: There are two questions: (1)Required request part 'image' is not present, the problem should be the parameter name problem, The @RequestParam("image") prefix must be "image". You can check if some parameter names are image. (2)JSON parse error: In my opinion, the main cause of the problem is the API: givetags, @RequestBody Map<String, List> tags, which is not translated properly when receiving the react parameter. You can try using List to receive arguments.
"Required request part 'image' is not present in" error in springboot with reactjs
When i try to upload a image in react, and send it to a spring boot api to save the file in a database, I get the following errors in spring boot: 2022-12-04 03:25:28.610 WARN 15080 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'image' is not present] 2022-12-04 03:25:28.631 WARN 15080 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.LinkedHashMap<java.lang.String,java.util.List<java.lang.String>>` from Array value (token `JsonToken.START_ARRAY`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.LinkedHashMap<java.lang.String,java.util.List<java.lang.String>>` from Array value (token `JsonToken.START_ARRAY`)<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]] Idk how to solve this. I've tried searching around, but havent found any answer. Im also unsure if the problem is in my react code or in my springboot code. I think my error is in reactjs, because ive seen in other posts for people have somewhat the same problem, that their problem has been their react code. But I havent figured out what exactly might be wrong with my react code. Im also posting my spring boot code in case you may want to look at it, My react code: const FileUpload = () => { const link = "http://localhost:8080/uploadimage?key" var formData = new FormData() const [fileName, setFilename] = useState("") const [tags, setTags] = useState([]) {/* THIS IS CODE FOR SELECTING A FILE TO UPLOAD*/} {/* IM TRYING TO DEFINE IMAGE BY PUTTING IT IN QUOTES IN FROMDATA.APPEND */} const handleFile = (e) => { setFilename(e.target.files[0].name) console.log("handle file") console.log(e.target.files[0]) formData.append("image", e.target.files[0]) } const uploadFile = (e) => { {/* THIS IS CODE FOR FILE UPLOADING*/} console.log("sending...") console.log(formData) axios.post( link, formData, { header: { 'Content-Type': 'multipart/form-data' } }) .then(res => { console.log(res.data) }) .catch(error => { console.log(error) }) {/* THIS IS CODE FOR SOMETHING ELSE; SOME TAGHANDLING */} setTimeout(3000) const taglink = "http://localhost:8080/givetags/" + fileName; axios.post(taglink, tags) .then(res => ( console.log(res.data) )) } {/* THIS IS CODE IS ALSO FOR SOMETHING ELSE*/} function updateTags(e) { const log = {...tags} log[e.target.id] = e.target.value.split(" ") setTags(log) } return ( <div> <Container> <Card.Title className='text-center mb-3'>Upload File</Card.Title> <Form.Group controlId='file' className='mb-3'> <Form.Control type='file' onChange={(e) => handleFile(e)}></Form.Control> </Form.Group> <Form.Group controlId='tags' className='mb-3'> <Form.Control onChange={(e) => updateTags(e)} type="text" placeholder='Write tags'></Form.Control> </Form.Group> <Button onClick={(e) => uploadFile(e)}>Upload File</Button> </Container> <TagsConvention></TagsConvention> </div> ) } export default FileUpload This is my springboot code: Controller: @RestController public class FileController { @Autowired private ImageServiceImpl service; //==========================For uploading a file====================================== @CrossOrigin(origins = "http://localhost:3000") @PostMapping("/uploadimage") public ResponseEntity<?> uploadImage(@RequestParam("image") MultipartFile file) throws IOException { String uploadImage = service.uploadImage(file); return ResponseEntity.status(HttpStatus.OK) .body(uploadImage); } @CrossOrigin(origins = "http://localhost:3000") @GetMapping("/getimage/{fileName}") public ResponseEntity<?> downloadImage(@PathVariable String fileName){ byte[] file=service.downloadImage(fileName); System.out.println(file); return ResponseEntity.status(HttpStatus.OK) .contentType(MediaType.valueOf(service.getType(fileName))) .body(file); } @CrossOrigin(origins = "http://localhost:3000") @PostMapping("/givetags/{fileName}") public ImageData giveImagetags(@PathVariable String fileName, @RequestBody Map<String, List<String>> tags) { //return service.giveImageTags(fileName, tags); //return service.giveImageTags(fileName, tags); System.out.println(tags); List<String> tagList = tags.get("tags"); return service.giveImageTags(fileName, tagList); } @CrossOrigin(origins = "http://localhost:3000") @GetMapping("/getallimages") public List<String> getAllImages() { return service.getAllImages(); } } My model for the image: @Entity @Table(name = "ImageData") @Data @AllArgsConstructor @NoArgsConstructor @Builder public class ImageData implements Image{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long imageDataId; private String name; private String type; @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinTable(name="file_has_tag", joinColumns = {@JoinColumn(name="image_data_id")}, inverseJoinColumns = {@JoinColumn(name = "tag_id")}) @JsonIgnoreProperties("image_data") private Set<Tag> tags; @Lob @Column(name = "image_data",length = 1000) private byte[] data; @Override public String toString() { return "ImageData{" + "imageDataId=" + imageDataId + ", name='" + name + '\'' + ", type='" + type + '\'' + ", tags=" + tags + '}'; } } Service function for uploading a file: public String uploadImage(MultipartFile file) throws IOException { ImageData imageData = imageDataRepository.save(ImageData.builder() .name(file.getOriginalFilename()) .type(file.getContentType()) .data(ImageUtils.compressImage(file.getBytes())).build()); //"data" is from the model class System.out.println(imageData.toString()); if (imageData != null) { return "file uploaded successfully : " + file.getOriginalFilename(); } return null; } functions in utils class for compressing image public static byte[] compressImage(byte[] data) { Deflater deflater = new Deflater(); deflater.setLevel(Deflater.BEST_COMPRESSION); deflater.setInput(data); deflater.finish(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); byte[] tmp = new byte[4*1024]; while (!deflater.finished()) { int size = deflater.deflate(tmp); outputStream.write(tmp, 0, size); } try { outputStream.close(); } catch (Exception ignored) { } return outputStream.toByteArray(); } Ive tried to change the value of formdata, and the key in "image" in fromdata.append, but I havent figured it out. Ive also tried to search up the problem, but people have had different syntax problems from me, so idk what might be the problem.
[ "There are two questions:\n(1)Required request part 'image' is not present, the problem should be the parameter name problem, The @RequestParam(\"image\") prefix must be \"image\". You can check if some parameter names are image.\n(2)JSON parse error: In my opinion, the main cause of the problem is the API: givetags, @RequestBody Map<String, List> tags, which is not translated properly when receiving the react parameter. You can try using List to receive arguments.\n" ]
[ 0 ]
[]
[]
[ "reactjs", "spring_boot" ]
stackoverflow_0074672504_reactjs_spring_boot.txt
Q: Mongoose populate with array of objects not working I have a exam mongoose schema and question schema exam schema is shown as followed const fields = { name : { type : String, required : true }, pages: [{ name: String, description: String, questions: [{ type: Schema.Types.ObjectId, ref: "question",required: true, } ], }, ], createdBy: { type: String, required: true, }, }; question schema is shown as followed const fields = { name : { type : String, required : true }, answer: { type : String, required : true } }; then I want to get the full example of the exam instance with the code await collection.findById(id).populate("pages.questions") but the result doesn't show me the question in detail, anything wrong with it? A: To use populate with an array of objects, you need to specify the path to the array field and the local field in the referenced schema that you want to populate. For example, the following populate call should work to populate the questions in your exam schema: await collection.findById(id).populate("pages.questions", "name answer") This will populate the questions array in each page with the name and answer fields from the question schema. Here is the updated exam schema with the populate call included: const fields = { name : { type : String, required : true }, pages: [{ name: String, description: String, questions: [{ type: Schema.Types.ObjectId, ref: "question",required: true, } ], }, ], createdBy: { type: String, required: true, }, }; const exam = mongoose.model("exam", new mongoose.Schema(fields)); // Get an exam instance by ID and populate the questions const exam = await exam.findById(id).populate("pages.questions", "name answer"); A: It looks like there might be an issue with the way you are defining the pages field in your exam schema. Specifically, the questions field in the pages array should reference the question schema using the type property and the ref property, rather than using the ref property alone. Here's an example of how you could define the pages field in your exam schema to properly reference the question schema: const examSchema = new Schema({ name: { type: String, required: true }, pages: [ { name: String, description: String, questions: [ { type: Schema.Types.ObjectId, ref: "question", required: true, } ], }, ], createdBy: { type: String, required: true }, }); With this change, you should be able to use the .populate() method to populate the questions field in the pages array with the corresponding question documents, and you should be able to see the detailed information for each question when you query for an exam instance. Here's an example of how you could use the .populate() method to query for an exam instance and include the detailed information for each question in the pages array: await collection.findById(id).populate("pages.questions"); With this query, you should be able to get the full exam instance, including the detailed information for each question in the pages array. A: It looks like there may be an issue with the way the populate method is being used in the code. In order to properly populate the questions field in the exam instance, the populate method should be used like this: await collection.findById(id).populate("pages.questions", "name answer") The second argument to the populate method specifies the fields to be populated in the questions array. In this case, the name and answer fields from the question schema are being populated. Additionally, it may be necessary to use the select method before the populate method in order to specify which fields from the exam instance should be returned. For example: await collection.findById(id).select("name pages").populate("pages.questions", "name answer") This will return only the name and pages fields from the exam instance, and will populate the questions array in each page object with the name and answer fields from the question schema.
Mongoose populate with array of objects not working
I have a exam mongoose schema and question schema exam schema is shown as followed const fields = { name : { type : String, required : true }, pages: [{ name: String, description: String, questions: [{ type: Schema.Types.ObjectId, ref: "question",required: true, } ], }, ], createdBy: { type: String, required: true, }, }; question schema is shown as followed const fields = { name : { type : String, required : true }, answer: { type : String, required : true } }; then I want to get the full example of the exam instance with the code await collection.findById(id).populate("pages.questions") but the result doesn't show me the question in detail, anything wrong with it?
[ "To use populate with an array of objects, you need to specify the path to the array field and the local field in the referenced schema that you want to populate.\nFor example, the following populate call should work to populate the questions in your exam schema:\nawait collection.findById(id).populate(\"pages.questions\", \"name answer\")\n\nThis will populate the questions array in each page with the name and answer fields from the question schema.\nHere is the updated exam schema with the populate call included:\nconst fields = {\n name : { type : String, required : true },\n pages: [{\n name: String,\n description: String,\n questions: [{\n type: Schema.Types.ObjectId, ref: \"question\",required: true, \n }\n ],\n },\n ],\n createdBy: { type: String, required: true, },\n};\n\nconst exam = mongoose.model(\"exam\", new mongoose.Schema(fields));\n\n// Get an exam instance by ID and populate the questions\nconst exam = await exam.findById(id).populate(\"pages.questions\", \"name answer\");\n\n", "It looks like there might be an issue with the way you are defining the pages field in your exam schema. Specifically, the questions field in the pages array should reference the question schema using the type property and the ref property, rather than using the ref property alone.\nHere's an example of how you could define the pages field in your exam schema to properly reference the question schema:\nconst examSchema = new Schema({\n name: { type: String, required: true },\n pages: [\n {\n name: String,\n description: String,\n questions: [\n {\n type: Schema.Types.ObjectId,\n ref: \"question\",\n required: true,\n }\n ],\n },\n ],\n createdBy: { type: String, required: true },\n});\n\nWith this change, you should be able to use the .populate() method to populate the questions field in the pages array with the corresponding question documents, and you should be able to see the detailed information for each question when you query for an exam instance.\nHere's an example of how you could use the .populate() method to query for an exam instance and include the detailed information for each question in the pages array:\nawait collection.findById(id).populate(\"pages.questions\");\n\nWith this query, you should be able to get the full exam instance, including the detailed information for each question in the pages array.\n", "It looks like there may be an issue with the way the populate method is being used in the code. In order to properly populate the questions field in the exam instance, the populate method should be used like this:\nawait collection.findById(id).populate(\"pages.questions\", \"name answer\")\n\nThe second argument to the populate method specifies the fields to be populated in the questions array. In this case, the name and answer fields from the question schema are being populated.\nAdditionally, it may be necessary to use the select method before the populate method in order to specify which fields from the exam instance should be returned. For example:\nawait collection.findById(id).select(\"name pages\").populate(\"pages.questions\", \"name answer\")\n\nThis will return only the name and pages fields from the exam instance, and will populate the questions array in each page object with the name and answer fields from the question schema.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "mongoose", "mongoose_populate" ]
stackoverflow_0074078300_mongoose_mongoose_populate.txt
Q: How do I use Random properly to generate number for text-based combat simulator game? I'm trying to use Random to generate random number for a text-based combat simulator but it keeps generating a very large and unusual number. Here is the code: (Mind you, I am not a very experienced programmer. I worked with Visual Basic back in 2001 and I haven't really used anything else since then (other than a few webpages I made within last 10 years). Here's my Visual studio screen: internal class Program { static void Main(string[] args) { System.Console.WriteLine("Starting Simulator"); Actor FoxTail = new Actor(); FoxTail.HealthPoints = 15; FoxTail.Strength = 2; FoxTail.Defense = 12; FoxTail.Spirit = 12; FoxTail.Dexterity = 2; FoxTail.Agility = 3; FoxTail.Intelligence = 2; FoxTail.Level = 0; FoxTail.ExperiencePoints = 0; Actor GreyWolf = new Actor(); GreyWolf.HealthPoints = 25; GreyWolf.Strength = 2; GreyWolf.Defense = 10; GreyWolf.Spirit = 8; GreyWolf.Dexterity = 5; GreyWolf.Agility = 7; GreyWolf.Intelligence = 2; GreyWolf.Level = 1; GreyWolf.ExperiencePoints = 5; int FoxTailAttack = new Randomizer.RandomIntegerGenerator(1).GeneratePositiveValue(); if(FoxTailAttack >= GreyWolf.Defense) { int damage = new Randomizer.RandomIntegerGenerator(1).GeneratePositiveValue() + FoxTail.Strength; GreyWolf.HealthPoints = GreyWolf.HealthPoints - damage; Console.WriteLine("Grey Wolf is at " + GreyWolf.HealthPoints + " health!"); } else { Console.WriteLine("Foxtail missed!"); } Console.WriteLine("Press any key to continue..."); System.Console.ReadLine(); I'm assuming the '1' in the parathesis after RandomIntegerGenerator is where my problem lies, but I just don't know how to define a range for the random number to generate. I get a weird -534011695 number that gets outputted in my runtime window. I'd like to get it to generate a number beween 1-25 if possible. Any help is appreciated. I'm very new to all of this and i'm starting small. I did my first 'Hello world!' program only 2 days ago. lol Thanks in advanced. A: You seem to be using some Randomizer class from somewhere else. You don't need that. C# comes with the Random class, that has everything you need. Only create one instance of the Random class and use it throughout the whole application. This is important because the instance is initialized with the current time as a random seed value when the instance is created. If you created a new instance each time, you would often get sequences of the same random number. internal class Program { public static Random Randomizer { get; private set; } = new Random(); You can then use the Next method to retrieve a random integer number in a given range: static void Main(string[] args) { for(int i=0; i <= 10; i++) { // Create integers >= 1 and < 26. // The result can be 1 and 25, but not 26 int number = Randomizer.Next(1, 26); Console.WriteLine(number.ToString()); } } The call Randomizer.Next(1, 26); will return values from 1 to 25.
How do I use Random properly to generate number for text-based combat simulator game?
I'm trying to use Random to generate random number for a text-based combat simulator but it keeps generating a very large and unusual number. Here is the code: (Mind you, I am not a very experienced programmer. I worked with Visual Basic back in 2001 and I haven't really used anything else since then (other than a few webpages I made within last 10 years). Here's my Visual studio screen: internal class Program { static void Main(string[] args) { System.Console.WriteLine("Starting Simulator"); Actor FoxTail = new Actor(); FoxTail.HealthPoints = 15; FoxTail.Strength = 2; FoxTail.Defense = 12; FoxTail.Spirit = 12; FoxTail.Dexterity = 2; FoxTail.Agility = 3; FoxTail.Intelligence = 2; FoxTail.Level = 0; FoxTail.ExperiencePoints = 0; Actor GreyWolf = new Actor(); GreyWolf.HealthPoints = 25; GreyWolf.Strength = 2; GreyWolf.Defense = 10; GreyWolf.Spirit = 8; GreyWolf.Dexterity = 5; GreyWolf.Agility = 7; GreyWolf.Intelligence = 2; GreyWolf.Level = 1; GreyWolf.ExperiencePoints = 5; int FoxTailAttack = new Randomizer.RandomIntegerGenerator(1).GeneratePositiveValue(); if(FoxTailAttack >= GreyWolf.Defense) { int damage = new Randomizer.RandomIntegerGenerator(1).GeneratePositiveValue() + FoxTail.Strength; GreyWolf.HealthPoints = GreyWolf.HealthPoints - damage; Console.WriteLine("Grey Wolf is at " + GreyWolf.HealthPoints + " health!"); } else { Console.WriteLine("Foxtail missed!"); } Console.WriteLine("Press any key to continue..."); System.Console.ReadLine(); I'm assuming the '1' in the parathesis after RandomIntegerGenerator is where my problem lies, but I just don't know how to define a range for the random number to generate. I get a weird -534011695 number that gets outputted in my runtime window. I'd like to get it to generate a number beween 1-25 if possible. Any help is appreciated. I'm very new to all of this and i'm starting small. I did my first 'Hello world!' program only 2 days ago. lol Thanks in advanced.
[ "You seem to be using some Randomizer class from somewhere else. You don't need that. C# comes with the Random class, that has everything you need.\nOnly create one instance of the Random class and use it throughout the whole application. This is important because the instance is initialized with the current time as a random seed value when the instance is created. If you created a new instance each time, you would often get sequences of the same random number.\ninternal class Program\n{\n public static Random Randomizer { get; private set; } = new Random();\n\nYou can then use the Next method to retrieve a random integer number in a given range:\nstatic void Main(string[] args)\n{\n for(int i=0; i <= 10; i++)\n {\n // Create integers >= 1 and < 26. \n // The result can be 1 and 25, but not 26\n int number = Randomizer.Next(1, 26);\n\n Console.WriteLine(number.ToString());\n }\n}\n\nThe call Randomizer.Next(1, 26); will return values from 1 to 25.\n" ]
[ 1 ]
[]
[]
[ "c#", "random" ]
stackoverflow_0074672446_c#_random.txt
Q: python parallel and join threading not working? I need to run parallel and join threads in the following code: ` from threading import Thread import time def do_stuff(i): if i == 1: time.sleep(1) if i ==2: time.sleep(2) if i ==3: time.sleep(3) print(i) time.sleep(1) def thread1(i): worker1 = Thread(target = do_stuff, args=(i,), daemon= True) worker1.start() def thread2(i): worker2 = Thread(target = do_stuff, args=(i,), daemon= True) worker2.start() def thread3(i): worker3 = Thread(target = do_stuff, args=(i,), daemon= True) worker3.start() num_threads = 1000 for i in range(num_threads): worker11 = Thread(target = thread1, args=(1, ), daemon= True) worker11.start() worker22 = Thread(target = thread2, args=(2, ), daemon= True) worker22.start() worker33 = Thread(target = thread3, args=(3, ), daemon= True) worker33.start() while True: # Keep running Code L = 1 ` Image explaine the process results shows that join method not working and the parallel threads join with themselfs. reults: 312233 1 3 11 31 2311 32 I appreciate your help. run parllel and join multi_threads properly. add Queue to to the code. A: To run threads in parallel, you can use the Thread.start() method, which starts the execution of the thread's target function. The join() method, on the other hand, is used to wait for a thread to complete its execution. In your code, you are starting three threads in the main thread, and then calling join() on each of those threads. This causes the main thread to wait for each of those threads to complete their execution before starting the next thread. This is why your threads are not running in parallel. To fix this, you can move the calls to start() and join() to the main thread, after starting all three threads. This will allow all three threads to run in parallel. Here is how your code could look like with these changes: from threading import Thread import time def do_stuff(i): time.sleep(1) print(i) time.sleep(1) def thread1(i): worker = Thread(target = do_stuff, args=(i,), daemon= True) worker.start() def thread2(i): worker = Thread(target = do_stuff, args=(i,), daemon= True) worker.start() def thread3(i): worker = Thread(target = do_stuff, args=(i,), daemon= True) worker.start() num_threads = 10 for i in range(num_threads): worker1 = Thread(target = thread1, args=(1, ), daemon= True) worker1.start() worker2 = Thread(target = thread2, args=(2, ), daemon= True) worker2.start() worker3 = Thread(target = thread3, args=(3, ), daemon= True) worker3.start() # wait for all threads to complete their execution worker1.join() worker2.join() worker3.join() while True: # Keep running Code L = 1 As for adding a queue to your code, you can use the Queue class from the queue module to create a queue. You can then add items to the queue using the put() method, and retrieve items from the queue using the get() method. Here is an example of how you could use a queue in your code: from queue import Queue from threading import Thread import time def do_stuff(i, queue): time.sleep(1) queue.put(i) def thread1(i, queue): worker = Thread(target = do_stuff, args=(i, queue), daemon= True) worker.start() def thread2(i, queue): worker = Thread(target = do_stuff, args=(i, queue), daemon= True) worker.start() def thread3(i, queue): worker = Thread(target = do_stuff, args=(i, queue), daemon= True) worker.start() num_threads = 10 queue = Queue() for i in range(num_threads): worker1 = Thread(target = thread1, args=(1, queue), daemon= True) worker1
python parallel and join threading not working?
I need to run parallel and join threads in the following code: ` from threading import Thread import time def do_stuff(i): if i == 1: time.sleep(1) if i ==2: time.sleep(2) if i ==3: time.sleep(3) print(i) time.sleep(1) def thread1(i): worker1 = Thread(target = do_stuff, args=(i,), daemon= True) worker1.start() def thread2(i): worker2 = Thread(target = do_stuff, args=(i,), daemon= True) worker2.start() def thread3(i): worker3 = Thread(target = do_stuff, args=(i,), daemon= True) worker3.start() num_threads = 1000 for i in range(num_threads): worker11 = Thread(target = thread1, args=(1, ), daemon= True) worker11.start() worker22 = Thread(target = thread2, args=(2, ), daemon= True) worker22.start() worker33 = Thread(target = thread3, args=(3, ), daemon= True) worker33.start() while True: # Keep running Code L = 1 ` Image explaine the process results shows that join method not working and the parallel threads join with themselfs. reults: 312233 1 3 11 31 2311 32 I appreciate your help. run parllel and join multi_threads properly. add Queue to to the code.
[ "To run threads in parallel, you can use the Thread.start() method, which starts the execution of the thread's target function. The join() method, on the other hand, is used to wait for a thread to complete its execution.\nIn your code, you are starting three threads in the main thread, and then calling join() on each of those threads. This causes the main thread to wait for each of those threads to complete their execution before starting the next thread. This is why your threads are not running in parallel.\nTo fix this, you can move the calls to start() and join() to the main thread, after starting all three threads. This will allow all three threads to run in parallel. Here is how your code could look like with these changes:\nfrom threading import Thread\nimport time\n\ndef do_stuff(i):\n time.sleep(1)\n print(i)\n time.sleep(1)\n\ndef thread1(i):\n worker = Thread(target = do_stuff, args=(i,), daemon= True)\n worker.start()\n\ndef thread2(i):\n worker = Thread(target = do_stuff, args=(i,), daemon= True)\n worker.start()\n \ndef thread3(i):\n worker = Thread(target = do_stuff, args=(i,), daemon= True)\n worker.start()\n\nnum_threads = 10\nfor i in range(num_threads):\n worker1 = Thread(target = thread1, args=(1, ), daemon= True)\n worker1.start()\n worker2 = Thread(target = thread2, args=(2, ), daemon= True)\n worker2.start()\n worker3 = Thread(target = thread3, args=(3, ), daemon= True)\n worker3.start()\n \n # wait for all threads to complete their execution\n worker1.join()\n worker2.join()\n worker3.join()\n\nwhile True:\n # Keep running Code\n L = 1\n\nAs for adding a queue to your code, you can use the Queue class from the queue module to create a queue. You can then add items to the queue using the put() method, and retrieve items from the queue using the get() method. Here is an example of how you could use a queue in your code:\nfrom queue import Queue\nfrom threading import Thread\nimport time\n\ndef do_stuff(i, queue):\n time.sleep(1)\n queue.put(i)\n\ndef thread1(i, queue):\n worker = Thread(target = do_stuff, args=(i, queue), daemon= True)\n worker.start()\n\ndef thread2(i, queue):\n worker = Thread(target = do_stuff, args=(i, queue), daemon= True)\n worker.start()\n \ndef thread3(i, queue):\n worker = Thread(target = do_stuff, args=(i, queue), daemon= True)\n worker.start()\n\nnum_threads = 10\nqueue = Queue()\n\nfor i in range(num_threads):\n worker1 = Thread(target = thread1, args=(1, queue), daemon= True)\n worker1\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_multithreading" ]
stackoverflow_0074672671_python_python_multithreading.txt
Q: Gorilla Mux router from inside handler only works once then gives 404 page not found I'm using Gorilla mux as my router and I'm having a very strange behaviour. On the first request to the server, I get a valid response. But on subsequent requests, I receive a 404 page not found. There are no errors in the console. My code is pretty straightforward (it can be copy-pasted to test it right out): package main import ( "fmt" "github.com/gorilla/mux" "log" "net/http" ) func main() { router := mux.NewRouter() router.HandleFunc("/", RootHandler).Name("root") http.Handle("/", router) log.Println("Listening on port 1337...") if err := http.ListenAndServe(":1337", nil); err != nil { log.Fatal("http.ListenAndServe: ", err) } } func RootHandler(w http.ResponseWriter, r *http.Request) { content := "Welcome to " rootUrl, err := mux.CurrentRoute(r).Subrouter().Get("root").URL() if err != nil { log.Printf("mux.CurrentRoute(r).Subrouter().Get(\"root\").URL(): ", err) } response := content + rootUrl.String() fmt.Fprintf(w, response) } After some code commenting and tests, it seems the following line is the culprit: rootUrl, err := mux.CurrentRoute(r).Subrouter().Get("root").URL() This method of getting the router inside the handler using the current request comes from another StackOverflow post: How to call a route by its name from inside a handler? But for a strange reason, it only works once: shell-1$ go run servertest.go 2014/10/30 13:31:34 Listening on port 1337... shell-2$ curl http://127.0.0.1:1337 Welcome to / shell-2$ curl http://127.0.0.1:1337 404 page not found As you can see, there are no errors in the console. Does someone have an idea of why it only works once ? A: The problem is Subrouter() isn't made to return the router, but to create one, thus it changes the matcher of the router it is called on, making you lose the handler. You could try passing the router to the handler using closures instead. func RootHandler(router *mux.Router) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { ... } } A: i run to this problem and fixe it by re initiating the methods //create a subrouter separately \ subRoute := mux.CurrentRoute(req).Subrouter() \ //Call the Route u want and store the URL url, err := subRoute.Get("check_authorization").URL("id", key, "password", token) // re-initiate the method to GET or whatever u had before subRoute.Methods(http.MethodGet)
Gorilla Mux router from inside handler only works once then gives 404 page not found
I'm using Gorilla mux as my router and I'm having a very strange behaviour. On the first request to the server, I get a valid response. But on subsequent requests, I receive a 404 page not found. There are no errors in the console. My code is pretty straightforward (it can be copy-pasted to test it right out): package main import ( "fmt" "github.com/gorilla/mux" "log" "net/http" ) func main() { router := mux.NewRouter() router.HandleFunc("/", RootHandler).Name("root") http.Handle("/", router) log.Println("Listening on port 1337...") if err := http.ListenAndServe(":1337", nil); err != nil { log.Fatal("http.ListenAndServe: ", err) } } func RootHandler(w http.ResponseWriter, r *http.Request) { content := "Welcome to " rootUrl, err := mux.CurrentRoute(r).Subrouter().Get("root").URL() if err != nil { log.Printf("mux.CurrentRoute(r).Subrouter().Get(\"root\").URL(): ", err) } response := content + rootUrl.String() fmt.Fprintf(w, response) } After some code commenting and tests, it seems the following line is the culprit: rootUrl, err := mux.CurrentRoute(r).Subrouter().Get("root").URL() This method of getting the router inside the handler using the current request comes from another StackOverflow post: How to call a route by its name from inside a handler? But for a strange reason, it only works once: shell-1$ go run servertest.go 2014/10/30 13:31:34 Listening on port 1337... shell-2$ curl http://127.0.0.1:1337 Welcome to / shell-2$ curl http://127.0.0.1:1337 404 page not found As you can see, there are no errors in the console. Does someone have an idea of why it only works once ?
[ "The problem is Subrouter() isn't made to return the router, but to create one, thus it changes the matcher of the router it is called on, making you lose the handler.\nYou could try passing the router to the handler using closures instead.\nfunc RootHandler(router *mux.Router) func(http.ResponseWriter, *http.Request) {\n return func(w http.ResponseWriter, r *http.Request) {\n ...\n }\n}\n\n", "i run to this problem and fixe it by re initiating the methods\n//create a subrouter separately \\\nsubRoute := mux.CurrentRoute(req).Subrouter() \\\n//Call the Route u want and store the URL \nurl, err := subRoute.Get(\"check_authorization\").URL(\"id\", key, \"password\", token) \n// re-initiate the method to GET or whatever u had before \nsubRoute.Methods(http.MethodGet) \n\n" ]
[ 2, 0 ]
[]
[]
[ "go", "gorilla" ]
stackoverflow_0026653152_go_gorilla.txt
Q: Binding without using "Get.to()" for GetX in Flutter I want to bind a controller to view 1 but I don't want to go to that view 1 via using Get.to(Page());. Instead I want to use view 1 directly inside view 2 by creating an object. Simplified code (BTW I'm using Veiw1Controller variables inside View1 itself) class Veiw2 extends GetView<Veiw2Controller>{ return View1(); } When I'm doing the above code, it throws an error saying "View1Controller" not found. You need to call "Get.put(View1Controller())" or "Get.lazyPut(()=>View1Controller())" I did call Get.put(...) in the binding but I think since we are not calling Get.to()therefore GetX does not realize when we are using that view and it does not bind the dependencies Here is what I've done class View1 extends Bindings { @override void dependencies() { Get.put<View1Controller>( View1Controller(), ); } } What is the best way to do that? A: well, the Bindings API was made to work together with the Getx navigation features, without actually Get.to(), Get.toNamed()..., you should not expect the automatic dependency injection of Getx. However, you still could inject those dependencies manually: like this: class BindingsOne extends Bindings { @override void dependencies() { Get.put<View1Controller>( View1Controller(), ); } } Now when you want to get a Widget: Widget getViewWidget() { BindingsOne().dependencies(); // this will inject all your dependencies from the bindings. return YourWidget(); } you could also inject them before you use Navigator routing features. // ... BindingsOne().dependencies(); // this will inject all your dependencies from the bindings. Navigator.of(context).push(MaterialPageRoute(builder: (context) => YourWidget())); }
Binding without using "Get.to()" for GetX in Flutter
I want to bind a controller to view 1 but I don't want to go to that view 1 via using Get.to(Page());. Instead I want to use view 1 directly inside view 2 by creating an object. Simplified code (BTW I'm using Veiw1Controller variables inside View1 itself) class Veiw2 extends GetView<Veiw2Controller>{ return View1(); } When I'm doing the above code, it throws an error saying "View1Controller" not found. You need to call "Get.put(View1Controller())" or "Get.lazyPut(()=>View1Controller())" I did call Get.put(...) in the binding but I think since we are not calling Get.to()therefore GetX does not realize when we are using that view and it does not bind the dependencies Here is what I've done class View1 extends Bindings { @override void dependencies() { Get.put<View1Controller>( View1Controller(), ); } } What is the best way to do that?
[ "well, the Bindings API was made to work together with the Getx navigation features, without actually Get.to(), Get.toNamed()..., you should not expect the automatic dependency injection of Getx.\nHowever, you still could inject those dependencies manually: like this:\nclass BindingsOne extends Bindings {\n @override\n void dependencies() {\n Get.put<View1Controller>(\n View1Controller(),\n );\n }\n}\n\nNow when you want to get a Widget:\nWidget getViewWidget() {\n BindingsOne().dependencies(); // this will inject all your dependencies from the bindings.\n return YourWidget();\n}\n\nyou could also inject them before you use Navigator routing features.\n // ...\n BindingsOne().dependencies(); // this will inject all your dependencies from the bindings.\n Navigator.of(context).push(MaterialPageRoute(builder: (context) => YourWidget()));\n}\n\n" ]
[ 0 ]
[]
[]
[ "dart", "flutter", "flutter_getx" ]
stackoverflow_0071336147_dart_flutter_flutter_getx.txt
Q: WHILE conditions are not working properly in MYSQL query? I am learning MySQL through self-practice. In a project, I want to create a transfer module using MySQL (phpMyAdmin). Unfortunately, the WHERE conditions are not working well. I execute the query using the XAMPP application. A part of the query is - SELECT * FROM (SELECT `emp_id`, `emp_name`, `present_posting`, `curr_zone`, `office_ID1` AS `new_office`, `Zone1` AS `new_zone`, `office_ID1` AS `C1`, `post`, `preference`, `curr_zone_id` FROM `transfer_applications` WHERE `Mutual Accepted` != 'Mutual Accepted' ORDER BY `apID` ASC) `aa` LEFT JOIN (SELECT `zone_ID`, `ZONE`, `office_ID`, `office_Vacancy` FROM `vacancy`) `ab` ON `aa`.`C1` = `ab`.`office_ID` LEFT JOIN (SELECT `zid`, `max_min_vacancy` FROM `capping_vacancy`) `ac` ON `aa`.`new_zone` = `ac`.`zid` WHERE ((`curr_zone_id` != `new_zone` AND (`max_min_vacancy` < 150 AND `max_min_vacancy` > 1) AND `station_Vacancy` > 0 AND `post` = 4 AND `apID` = x + 1) OR (`curr_zone_id` = `new_zone` AND `station_Vacancy` > 0)) The problem is that it allows transfer even if there is no vacancy available that is the minimum capping in WHERE ( max_min_vacancy > 1 ) is not working. I am unable to find out the reason why it skips this condition while all other conditions in the WHERE are working fine. Kindly help me to find out the mistake. Thanks. A: The WHERE clause is connected by an OR, so if the first Boolean expression is FALSE (ie. max_min_vacancy <=1), it is still TRUE as long as the second boolean expression returns TRUE. ... WHERE ( ( `curr_zone_id` != `new_zone` AND ( `max_min_vacancy` < 150 AND `max_min_vacancy` > 1 -- if max_min_vacancy <= 1 --> FALSE ) AND `station_Vacancy` > 0 AND `post` = 4 AND `apID` = x + 1 ) OR ( -- But this condition is TRUE `curr_zone_id` = `new_zone` AND `station_Vacancy` > 0 ) )
WHILE conditions are not working properly in MYSQL query?
I am learning MySQL through self-practice. In a project, I want to create a transfer module using MySQL (phpMyAdmin). Unfortunately, the WHERE conditions are not working well. I execute the query using the XAMPP application. A part of the query is - SELECT * FROM (SELECT `emp_id`, `emp_name`, `present_posting`, `curr_zone`, `office_ID1` AS `new_office`, `Zone1` AS `new_zone`, `office_ID1` AS `C1`, `post`, `preference`, `curr_zone_id` FROM `transfer_applications` WHERE `Mutual Accepted` != 'Mutual Accepted' ORDER BY `apID` ASC) `aa` LEFT JOIN (SELECT `zone_ID`, `ZONE`, `office_ID`, `office_Vacancy` FROM `vacancy`) `ab` ON `aa`.`C1` = `ab`.`office_ID` LEFT JOIN (SELECT `zid`, `max_min_vacancy` FROM `capping_vacancy`) `ac` ON `aa`.`new_zone` = `ac`.`zid` WHERE ((`curr_zone_id` != `new_zone` AND (`max_min_vacancy` < 150 AND `max_min_vacancy` > 1) AND `station_Vacancy` > 0 AND `post` = 4 AND `apID` = x + 1) OR (`curr_zone_id` = `new_zone` AND `station_Vacancy` > 0)) The problem is that it allows transfer even if there is no vacancy available that is the minimum capping in WHERE ( max_min_vacancy > 1 ) is not working. I am unable to find out the reason why it skips this condition while all other conditions in the WHERE are working fine. Kindly help me to find out the mistake. Thanks.
[ "The WHERE clause is connected by an OR, so if the first Boolean expression is FALSE (ie. max_min_vacancy <=1), it is still TRUE as long as the second boolean expression returns TRUE.\n...\nWHERE\n (\n (\n `curr_zone_id` != `new_zone` AND \n (\n `max_min_vacancy` < 150 AND \n `max_min_vacancy` > 1 -- if max_min_vacancy <= 1 --> FALSE\n ) AND \n `station_Vacancy` > 0 AND \n `post` = 4 AND \n `apID` = x + 1\n )\n OR ( -- But this condition is TRUE\n `curr_zone_id` = `new_zone` AND \n `station_Vacancy` > 0\n )\n )\n\n" ]
[ 0 ]
[]
[]
[ "mysql", "sql", "while_loop", "xampp" ]
stackoverflow_0074671729_mysql_sql_while_loop_xampp.txt
Q: Click a form button element on page load I am attempting to: Click a button element on page load, and; Make the form invisible Currently the JS / HTML is: <iframe src="https://api.leadconnectorhq.com/widget/form/FORMHERE" style="border:none;width:100%;" scrolling="no" id="FORMHERE"></iframe> <script src="https://api.leadconnectorhq.com/js/form_embed.js"></script> I have tried document.getElementById('watchButton').click but I have no knowledge on where to put it Or if I should be creatinga whole other JS / HTML element to perform the click A: To click a button element on page load, you can use the click() method in JavaScript. You can add this method to the onload event handler of the window object, which is called when the page has finished loading. Here is an example of how you could do this: <iframe src="https://api.leadconnectorhq.com/widget/form/FORMHERE" style="border:none;width:100%;" scrolling="no" id="FORMHERE"></iframe> <script src="https://api.leadconnectorhq.com/js/form_embed.js"></script> <script> window.onload = function() { // get the button element var button = document.getElementById('watchButton'); // click the button button.click(); }; </script> To make the form invisible, you can add a style attribute to the iframe element and set the display property to none. This will hide the form when the page loads. Here is an example of how you could do this: <iframe src="https://api.leadconnectorhq.com/widget/form/FORMHERE" style="border:none;width:100%;display:none;" scrolling="no" id="FORMHERE"></iframe> <script src="https://api.leadconnectorhq.com/js/form_embed.js"></script> <script> window.onload = function() { // get the button element var button = document.getElementById('watchButton'); // click the button button.click(); }; </script> You can also combine these two steps into a single function, and add the function to the onload event handler. Here is an example of how you could do this: <iframe src="https://api.leadconnectorhq.com/widget/form/FORMHERE" style="border:none;width:100%;display:none;" scrolling="no" id="FORMHERE"></iframe> <script src="https://api.leadconnectorhq.com/js/form_embed.js"></script> <script> window.onload = function() { // get the button and form elements var button = document.getElementById('watchButton'); var form = document.getElementById('FORMHERE'); // click the button and hide the form button.click(); form.style.display = 'none'; }; </script> This code will click the button and hide the form when the page loads.
Click a form button element on page load
I am attempting to: Click a button element on page load, and; Make the form invisible Currently the JS / HTML is: <iframe src="https://api.leadconnectorhq.com/widget/form/FORMHERE" style="border:none;width:100%;" scrolling="no" id="FORMHERE"></iframe> <script src="https://api.leadconnectorhq.com/js/form_embed.js"></script> I have tried document.getElementById('watchButton').click but I have no knowledge on where to put it Or if I should be creatinga whole other JS / HTML element to perform the click
[ "To click a button element on page load, you can use the click() method in JavaScript. You can add this method to the onload event handler of the window object, which is called when the page has finished loading. Here is an example of how you could do this:\n<iframe src=\"https://api.leadconnectorhq.com/widget/form/FORMHERE\" style=\"border:none;width:100%;\" scrolling=\"no\" id=\"FORMHERE\"></iframe>\n<script src=\"https://api.leadconnectorhq.com/js/form_embed.js\"></script>\n<script>\n window.onload = function() {\n // get the button element\n var button = document.getElementById('watchButton');\n\n // click the button\n button.click();\n };\n</script>\n\nTo make the form invisible, you can add a style attribute to the iframe element and set the display property to none. This will hide the form when the page loads. Here is an example of how you could do this:\n<iframe src=\"https://api.leadconnectorhq.com/widget/form/FORMHERE\" style=\"border:none;width:100%;display:none;\" scrolling=\"no\" id=\"FORMHERE\"></iframe>\n<script src=\"https://api.leadconnectorhq.com/js/form_embed.js\"></script>\n<script>\n window.onload = function() {\n // get the button element\n var button = document.getElementById('watchButton');\n\n // click the button\n button.click();\n };\n</script>\n\nYou can also combine these two steps into a single function, and add the function to the onload event handler. Here is an example of how you could do this:\n<iframe src=\"https://api.leadconnectorhq.com/widget/form/FORMHERE\" style=\"border:none;width:100%;display:none;\" scrolling=\"no\" id=\"FORMHERE\"></iframe>\n<script src=\"https://api.leadconnectorhq.com/js/form_embed.js\"></script>\n<script>\n window.onload = function() {\n // get the button and form elements\n var button = document.getElementById('watchButton');\n var form = document.getElementById('FORMHERE');\n\n // click the button and hide the form\n button.click();\n form.style.display = 'none';\n };\n</script>\n\nThis code will click the button and hide the form when the page loads.\n" ]
[ 1 ]
[]
[]
[ "forms", "html", "javascript", "web" ]
stackoverflow_0074672663_forms_html_javascript_web.txt
Q: What things should be saved in SESSION and what should not be? I give one example why this question appears in my head: Lets say i create class 'PDOstart' which extends PDO class. On class 'PDOstart' all variables needed for PDO is defined on private section (like host, user, password and ect). So it makes very easy to use PDO class like: $con = new PDOstart(); $con->query("SELECT ... "); Because on my webpage I use only one DB I begin thinking why not add PDOstart object into SESSION? like: $_SESSION['db'] = $con; ? So i don't need on every page do "new PODstart". But I'm not sure that will be good idea... Is there anything what i should avoid add to $_SESSION (for security or performance reason)? A: user id so that every time the page loads you know what use is browsing, meta data such as timespan from page changes (Bot Detect), Local information, User template selection. anything that's required for that session really. As you stated $con let me explain something. There are several variable types in php and the main ones are: strings boolean's integer's objects arrays resources Now you can store all of them into the sessions apart from resources, as there such things as file handles, connections to external entities there only open for the time it takes the page to be processed by PHP, then there closed. the others are ok as there stored in the memory and are static as such, they will not change unless you programmatically change them. The main entites you should store in the session are GUID: So that you can track what user is logged in. Flash Data: So if your doing a redirect you will be able to show a error message on the other page. Browser Data, so that you can compare that the browser that is currently browsing is the same as the last, this way you can kill the session fro security. Things like Database Data such as User Rows should not be stored in the session and you should create a separate cache mechanism to do this for you. A: You can store your PDOstart class in the session, as long as you keep this in mind: When you do $_SESSION['key'] = $obj, you actually serialize the object (assuming default php session handler, that happens when the data is flushed). When you do this to a 'resource', such as a database connection, there is every likelihood the connection will not persist. To workaround such cases, php has the __sleep and __wakeup magic methods I would assume your PDOstart class will ensure connection to PDO on both __construct and __wakeup, doubling the complexity. However, there's another reason for not doing it that way: the session might go away at any moment, so you shouldn't really rely on any information being there. Surely you can place safeguards, which would re-initialize everything, but that again is adding unneeded complexity. There's no golden rule (at least that I'm aware of) that explicitly states you should keep as little info as possible in your sessions, but it seems to be a fairly common approach. I'd keep a user id and probably an access token. There's not much stopping you to do it otherwise tho. As for security, this kind of use shouldn't really matter, as long as the session as a whole is secure. They never truly are, but it's a whole different topic. Short answer: good things to store - user id, bad things to store - everything else. A: Some complement to the good response of RobertPitt you should really add an autoloader if you start storing objects in the session.If the class of your object is not available you'll get a standard broken objet if you do not have an autoload mecanism for class loading. Then, depending on how your session are stored you should be careful of the size they take. let's say you store it on a very fast drive or on a memcached service, you do not need to worry too much about the fact that this file will be read for every request of your user. If you have slow IO on your drive be careful. Now if you store your session in a database you may care about the insert/update/delete rythm on the session table, some databases (think about MySQL) are not very god at handling an high write load on one table. In term of security you do not have to worry too much about session storage as it is on the server. At least if you (the admin) use disk storage you should ensure that all handled application are not using the same directory for session storage, if not the weaker application will define you security level for sessions. A: It depends what size have your column for store session variable. There should be stored only necessary information. If size of column for session have 255 chars then if you store 5 char or 120 or what else have no difference. Database see session data as size of column as 255 chars. If there will be attemption to save session as data bigger than 255 chars, data will be truncated to 255 size.
What things should be saved in SESSION and what should not be?
I give one example why this question appears in my head: Lets say i create class 'PDOstart' which extends PDO class. On class 'PDOstart' all variables needed for PDO is defined on private section (like host, user, password and ect). So it makes very easy to use PDO class like: $con = new PDOstart(); $con->query("SELECT ... "); Because on my webpage I use only one DB I begin thinking why not add PDOstart object into SESSION? like: $_SESSION['db'] = $con; ? So i don't need on every page do "new PODstart". But I'm not sure that will be good idea... Is there anything what i should avoid add to $_SESSION (for security or performance reason)?
[ "user id so that every time the page loads you know what use is browsing, meta data such as timespan from page changes (Bot Detect), Local information, User template selection. anything that's required for that session really.\nAs you stated $con let me explain something.\nThere are several variable types in php and the main ones are:\n\nstrings\nboolean's\ninteger's\nobjects\narrays\nresources\n\nNow you can store all of them into the sessions apart from resources, as there such things as file handles, connections to external entities there only open for the time it takes the page to be processed by PHP, then there closed.\nthe others are ok as there stored in the memory and are static as such, they will not change unless you programmatically change them.\nThe main entites you should store in the session are\n\nGUID: So that you can track what user is logged in.\nFlash Data: So if your doing a redirect you will be able to show a error message on the other page.\nBrowser Data, so that you can compare that the browser that is currently browsing is the same as the last, this way you can kill the session fro security.\n\nThings like Database Data such as User Rows should not be stored in the session and you should create a separate cache mechanism to do this for you.\n", "You can store your PDOstart class in the session, as long as you keep this in mind:\n\nWhen you do $_SESSION['key'] = $obj, you actually serialize the object (assuming default php session handler, that happens when the data is flushed).\nWhen you do this to a 'resource', such as a database connection, there is every likelihood the connection will not persist.\nTo workaround such cases, php has the __sleep and __wakeup magic methods\n\nI would assume your PDOstart class will ensure connection to PDO on both __construct and __wakeup, doubling the complexity.\nHowever, there's another reason for not doing it that way: the session might go away at any moment, so you shouldn't really rely on any information being there. Surely you can place safeguards, which would re-initialize everything, but that again is adding unneeded complexity.\nThere's no golden rule (at least that I'm aware of) that explicitly states you should keep as little info as possible in your sessions, but it seems to be a fairly common approach. I'd keep a user id and probably an access token. There's not much stopping you to do it otherwise tho.\nAs for security, this kind of use shouldn't really matter, as long as the session as a whole is secure. They never truly are, but it's a whole different topic.\nShort answer: good things to store - user id, bad things to store - everything else. \n", "Some complement to the good response of RobertPitt you should really add an autoloader if you start storing objects in the session.If the class of your object is not available you'll get a standard broken objet if you do not have an autoload mecanism for class loading.\nThen, depending on how your session are stored you should be careful of the size they take. let's say you store it on a very fast drive or on a memcached service, you do not need to worry too much about the fact that this file will be read for every request of your user. If you have slow IO on your drive be careful. Now if you store your session in a database you may care about the insert/update/delete rythm on the session table, some databases (think about MySQL) are not very god at handling an high write load on one table.\nIn term of security you do not have to worry too much about session storage as it is on the server. At least if you (the admin) use disk storage you should ensure that all handled application are not using the same directory for session storage, if not the weaker application will define you security level for sessions.\n", "It depends what size have your column for store session variable. There should be stored only necessary information. If size of column for session have 255 chars then if you store 5 char or 120 or what else have no difference. Database see session data as size of column as 255 chars. If there will be attemption to save session as data bigger than 255 chars, data will be truncated to 255 size.\n" ]
[ 7, 1, 0, 0 ]
[]
[]
[ "php", "session" ]
stackoverflow_0004656812_php_session.txt
Q: How to deny all GET requests made to the index, but allow other routes I want to deny GET request when they are made to the root of the website (www.mywebsite.com), without preventing GET request to other routes (www.mywebsite.com/thisroute), how is it possible? I could not find the answer to this specific question. (part of) My config file: location / { #ALLOW CORS# if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; # # Custom headers and headers various browsers *should* be OK with but aren't # add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; # # Tell client that this pre-flight info is valid for 20 days # add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } if ($request_method = 'POST') { add_header 'Access-Control-Allow-Origin' '*' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always; } if ($request_method = 'GET') { add_header 'Access-Control-Allow-Origin' '*' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always; } #END OF ALLOW CORS# try_files $uri $uri/ =404; autoindex on; client_max_body_size 20M; } A: To deny GET requests to the root of the website, you can use the deny directive in the Nginx configuration file. You can add the following code block to your Nginx config file, within the location / block: if ($request_method = 'GET') { deny all; } This will block any GET requests made to the root of the website, while allowing GET requests to other routes. Note: You may need to adjust the code block to match your specific configuration and requirements. Check out this article for further info
How to deny all GET requests made to the index, but allow other routes
I want to deny GET request when they are made to the root of the website (www.mywebsite.com), without preventing GET request to other routes (www.mywebsite.com/thisroute), how is it possible? I could not find the answer to this specific question. (part of) My config file: location / { #ALLOW CORS# if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; # # Custom headers and headers various browsers *should* be OK with but aren't # add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; # # Tell client that this pre-flight info is valid for 20 days # add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } if ($request_method = 'POST') { add_header 'Access-Control-Allow-Origin' '*' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always; } if ($request_method = 'GET') { add_header 'Access-Control-Allow-Origin' '*' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always; } #END OF ALLOW CORS# try_files $uri $uri/ =404; autoindex on; client_max_body_size 20M; }
[ "To deny GET requests to the root of the website, you can use the deny directive in the Nginx configuration file.\nYou can add the following code block to your Nginx config file, within the location / block:\nif ($request_method = 'GET') {\n deny all;\n}\n\nThis will block any GET requests made to the root of the website, while allowing GET requests to other routes.\nNote: You may need to adjust the code block to match your specific configuration and requirements.\nCheck out this article for further info\n" ]
[ 0 ]
[]
[]
[ "get", "nginx", "rest", "server" ]
stackoverflow_0074672721_get_nginx_rest_server.txt
Q: How to get a list of all referenced assemblies (loaded or not) I am trying to get a list of referenced assemblies for a an assembly I load into a main app in MEF. I want to make sure that all the referenced assemblies are present in the folder before running the plugin. I tried using List<AssemblyName> a = Assembly.GetEntryAssembly().GetReferencedAssemblies().ToList(); But when I do this, it only shows me assemblies used/loaded at that stage. I want a complete list (at runtime) of assemblies referenced (a replica of the References Folder in VS) regardless of whether they are used at that moment or at all. A: Before loading the plugin, you can load it for reflection only that will load only the metadata of the file. For example: var assm = Assembly.ReflectionOnlyLoadFrom(@"Same.dll"); var reff = assm.GetReferencedAssemblies(); Keep in mind that the associated library can have their references. A: You can extract that information from the file metadata. Quickest way is probably to use one of the libraries out there to do so. For example you can use Mono.Cecil Like this: var md = ModuleDefinition.ReadModule(assemblyPath); foreach (var reference in md.AssemblyReferences) { } A: I was struggling with this too and came up with Assembly.GetReferencedAssemblies(). This will give you all the referenced assemblies in an assembly. However, to get them all in the whole application you need to do a transitive closure to get the assemblies referenced by the references and so on. Here is a function that worked for me. private static List<Assembly> GetAllReferencedAssemblies(Assembly asm) { var nameQueue = new Queue<AssemblyName>(asm.GetReferencedAssemblies()); var alreadyProcessed = new HashSet<string>() { asm.FullName }; var result = new List<Assembly>(); result.Add(asm); while (nameQueue.Any()) { var name = nameQueue.Dequeue(); var fullName = name.FullName; if (alreadyProcessed.Contains(fullName) || fullName.StartsWith("Microsoft.") || fullName.StartsWith("System.")) continue; alreadyProcessed.Add(fullName); try { var newAssembly = Assembly.Load(name); result.Add(newAssembly); foreach (var innerAsmName in newAssembly.GetReferencedAssemblies()) nameQueue.Enqueue(innerAsmName); Debug.WriteLine(name); } catch (Exception e) { Debug.WriteLine(e); } } return result; } A couple of practical points: you will see that I added a line to exclude Microsoft and System assemblies -- if you go down that rabbit whole you get a crazy number of assemblies. However, you can adjust as you see fit. Also, I wrapped the Assembly.Load in an try/catch block since my experience is sometimes you get some dlls you can't load, or that aren't used any more. Again, feel free to do as you will with this. Obviously to you it you pass in the top level assembly you are using, the main program or whatever. You can call it easily with something like: var asmList = GetAllReferencedAssemblies(typeof(Main).Assembly); Where main is a type in your top level assembly.
How to get a list of all referenced assemblies (loaded or not)
I am trying to get a list of referenced assemblies for a an assembly I load into a main app in MEF. I want to make sure that all the referenced assemblies are present in the folder before running the plugin. I tried using List<AssemblyName> a = Assembly.GetEntryAssembly().GetReferencedAssemblies().ToList(); But when I do this, it only shows me assemblies used/loaded at that stage. I want a complete list (at runtime) of assemblies referenced (a replica of the References Folder in VS) regardless of whether they are used at that moment or at all.
[ "Before loading the plugin, you can load it for reflection only that will load only the metadata of the file. For example:\n var assm = Assembly.ReflectionOnlyLoadFrom(@\"Same.dll\");\n var reff = assm.GetReferencedAssemblies();\n\nKeep in mind that the associated library can have their references.\n", "You can extract that information from the file metadata. Quickest way is probably to use one of the libraries out there to do so.\nFor example you can use Mono.Cecil\nLike this:\nvar md = ModuleDefinition.ReadModule(assemblyPath);\nforeach (var reference in md.AssemblyReferences)\n{\n\n}\n\n", "I was struggling with this too and came up with Assembly.GetReferencedAssemblies(). This will give you all the referenced assemblies in an assembly. However, to get them all in the whole application you need to do a transitive closure to get the assemblies referenced by the references and so on.\nHere is a function that worked for me.\n private static List<Assembly> GetAllReferencedAssemblies(Assembly asm)\n {\n var nameQueue = new Queue<AssemblyName>(asm.GetReferencedAssemblies());\n var alreadyProcessed = new HashSet<string>() { asm.FullName };\n var result = new List<Assembly>();\n result.Add(asm);\n while (nameQueue.Any())\n {\n var name = nameQueue.Dequeue();\n var fullName = name.FullName;\n if (alreadyProcessed.Contains(fullName) || fullName.StartsWith(\"Microsoft.\") || fullName.StartsWith(\"System.\"))\n continue;\n alreadyProcessed.Add(fullName);\n try\n {\n var newAssembly = Assembly.Load(name);\n result.Add(newAssembly);\n foreach (var innerAsmName in newAssembly.GetReferencedAssemblies())\n nameQueue.Enqueue(innerAsmName);\n Debug.WriteLine(name);\n }\n catch (Exception e)\n {\n Debug.WriteLine(e);\n }\n }\n\n return result;\n }\n\nA couple of practical points: you will see that I added a line to exclude Microsoft and System assemblies -- if you go down that rabbit whole you get a crazy number of assemblies. However, you can adjust as you see fit. Also, I wrapped the Assembly.Load in an try/catch block since my experience is sometimes you get some dlls you can't load, or that aren't used any more. Again, feel free to do as you will with this.\nObviously to you it you pass in the top level assembly you are using, the main program or whatever. You can call it easily with something like:\nvar asmList = GetAllReferencedAssemblies(typeof(Main).Assembly);\n\nWhere main is a type in your top level assembly.\n" ]
[ 2, 1, 0 ]
[]
[]
[ ".net", ".net_assembly", "c#" ]
stackoverflow_0032051301_.net_.net_assembly_c#.txt
Q: How to refer to a specific struct in an array, while the array is in a struct in a function in C? #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> // sqrtf #include <limits.h> // INT_MAX #include <string.h> // strcmp, strlen, strcat #include <time.h> // time.NULL int logger = 0; struct obj_t { int id; float x; float y; }; struct cluster_t { int size; int capacity; struct obj_t *obj; }; void point_ctor(struct obj_t *p,int id, float x, float y){ p->id = id; p->x = x; p->y = y; } void init_cluster(struct cluster_t *c, int cap) { assert(c != NULL); assert(cap >= 0); // TODO c->capacity = cap; c->size = 0; c->obj = NULL; } /// Chunk of cluster objects. Value recommended for reallocation. const int CLUSTER_CHUNK = 10; struct cluster_t *resize_cluster(struct cluster_t *c, int new_cap) { // TUTO FUNKCI NEMENTE assert(c); assert(c->capacity >= 0); assert(new_cap >= 0); if (c->capacity >= new_cap) return c; size_t size = sizeof(struct obj_t) * new_cap; void *arr = realloc(c->obj, size); if (arr == NULL) return NULL; c->obj = (struct obj_t*)arr; c->capacity = new_cap; return c; } void append_cluster(struct cluster_t *c, struct obj_t obj) { // TODO if(c->size == c->capacity){ resize_cluster(c,(c->capacity)+1); } c->size += 1; //point musim pridat c->obj[(c->size)-1] strukt arg 2 c->obj[((c->size)-1)].id = obj.id; printf("TUSOM"); c->obj[(c->size)-1].x = obj.x; printf("TUSOM"); c->obj[(c->size)-1].y = obj.y; printf("TUSOM"); } void print_cluster(struct cluster_t *c) { // TUTO FUNKCI NEMENTE for (int i = 0; i < c->size; i++) { if (i) putchar(' '); printf("%d[%g,%g]", c->obj[i].id, c->obj[i].x, c->obj[i].y); } putchar('\n'); } void print_clusters(struct cluster_t *carr, int narr) { printf("Clusters:\n"); for (int i = 0; i < narr; i++) { printf("cluster %d: ", i); print_cluster(&carr[i]); } } int load_clusters(char *filename, struct cluster_t **arr){ assert(arr != NULL); FILE * obj; assert(obj = fopen(filename, "r")); //count init for number of objects char tempcount[100]; char countnumbers[100]; int count; int numberstart; int counter = 0; fscanf(obj, "%s", tempcount); for(int i = 0; i<strlen(tempcount); i++){ if(tempcount[i] == '='){ numberstart = i; break; } } for(int i = numberstart; i < strlen(tempcount); i++){ if(tempcount[i] >= 48 && tempcount[i] <= 57){ countnumbers[counter] = tempcount[i]; counter++; } } assert(strlen(countnumbers) > 0); count = atoi(countnumbers); // Get ID, X, Y int id, x, y, pos = 0; struct obj_t point[count]; while(fscanf(obj, "%d %d %d", &id, &x, &y) == 3) { // Build array point_ctor(&point[pos],id,x,y); arr[pos] = malloc(sizeof(struct obj_t)); init_cluster(arr[pos],count); append_cluster(arr[pos], point[pos]); printf("Object %d at X%f Y%f\n", arr[pos]->obj[pos].id,arr[pos]->obj[pos].x, arr[pos]->obj[pos].y); pos++; } fclose(obj); return 0; } int main(int argc, char *argv[]) { struct cluster_t *cluster; char extension[4]; strcpy(extension,".txt"); char subor[100]; strcpy(subor,argv[1]); strcat(subor,extension); load_clusters(subor, &cluster); //print_clusters(&cluster[3],20); // Lloydov algoritmus return 0; } the program is run: ./program objekty objekty - name of file without .txt An example of an input file: "objekty.txt": count=20 40 86 663 43 747 938 47 285 973 49 548 422 52 741 541 56 44 854 57 795 59 61 267 375 62 85 874 66 125 211 68 80 770 72 277 272 74 222 444 75 28 603 79 926 463 83 603 68 86 238 650 87 149 304 89 749 190 93 944 835 The problem seems to be at around in function append_cluster in line: c->obj[((c->size)-1)].id = obj.id; (line 150) A brief explanation before going through the code: Here are my structs: ``` struct obj_t { int id; float x; float y; }; struct cluster_t { int size; int capacity; struct obj_t *obj; }; ``` Full code pastebin: https://pastebin.com/cffiDYBm I make an array of cluster_t structs in main(); (struct cluster_t *cluster;) I pass this array to a function load_clusters(filename, &cluster); Function def: int load_clusters(char *filename, struct cluster_t **arr) I do some code and pass an index of the cluster array to an append function append_cluster(arr[pos], point[pos]); this function effectively adds a point at the end of the array. (resizes if needed) Function def: void append_cluster(struct cluster_t *c, struct obj_t obj); The problem: I need to be able to change data of a specific obj_t in a cluster_t array (cluster_t->obj[n]). The results being that my code stopped running and the line was not processed. Is there any other way to do this? Is it a small change in syntax? I'm out of ideas. I tried: c->obj[(c->size)-1].id = obj.id; Also I made a function which did this for me but I got the same results: void obj_ctor(struct obj_t *p, struct obj_t obj){ p->id = obj.id; p->x = obj.x; p->y = obj.y; } Here is the problem which should be as minimal as possible: (I'm trying to get both printfs on stdout) #include <stdio.h> #include <stdlib.h> struct obj_t { int id; float x; float y; }; struct cluster_t { int size; int capacity; struct obj_t *obj; }; void obj_ctor(struct obj_t *p, struct obj_t obj){ p->id = obj.id; p->x = obj.x; p->y = obj.y; } void pass(struct cluster_t *p, struct obj_t add){ obj_ctor(&p->obj[0],add); p->size += 1; } void pass1(struct cluster_t **arr){ struct obj_t o3; o3.id = 1; o3.x = 2; o3.y = 3; int count = 20; int pos = 0; while(pos < 3){ arr[pos]->capacity = 3; arr[pos]->size = 0; arr[pos]->obj = malloc(count*sizeof(struct obj_t)); pass(arr[pos], o3); pos++; } } int main(int argc, char *argv[]) { printf("Testing"); struct cluster_t *test; pass1(&test); printf("GOT HERE"); } A: The final minimal example is nicely manageable โ€” thank you. Here is a fairly straight-forward extension of that code. It is lazy in that it uses assert() to enforce necessary properties. It includes a function to dump the data in a struct cluster_t structure. I regard such functions as a necessity โ€” at the very least, they're extremely helpful. Quite often, I write them to take a FILE *fp argument so that messages can be written to standard output, standard error or to a log file, or, indeed, anywhere you can point a file stream. Often, I'd have a separate dump_obj() function that would be invoked from dump_cluster(), but it doesn't seem necessary here. The key point is that it ensures that test.obj in main() points to an array of 3 struct obj_t. If you want dynamic memory allocation, changes are needed. /* SO 7467-2430 */ #include <assert.h> #include <stdio.h> #include <stdlib.h> struct obj_t { int id; float x; float y; }; struct cluster_t { int size; int capacity; struct obj_t *obj; }; static void obj_ctor(struct obj_t *p, struct obj_t obj) { p->id = obj.id; p->x = obj.x; p->y = obj.y; } static void pass(struct cluster_t *p, struct obj_t add) { assert(p != NULL && p->obj != NULL); assert(p->size < p->capacity); obj_ctor(&p->obj[p->size], add); p->size += 1; } static void dump_cluster(const char *tag, struct cluster_t *p) { printf("%s (%p):\n", tag, p); if (p != NULL) { printf("size = %d, capacity = %d, objects = %p\n", p->size, p->capacity, p->obj); for (int i = 0; i < p->size; i++) printf(" [%d] id = %d, pos = (%g, %g)\n", i, p->obj[i].id, p->obj[i].x, p->obj[i].y); } } int main(void) { printf("Testing\n"); struct cluster_t test; struct obj_t o1, o2, o3; o1.id = 1; o2.id = 2; o3.id = 3; o1.x = 1; o2.x = 2; o3.x = 3; o1.y = 1; o2.y = 2; o3.y = 3; test.capacity = 3; test.size = 0; struct obj_t arr[3]; test.obj = arr; pass(&test, o3); printf("GOT HERE\n"); dump_cluster("After adding 1", &test); pass(&test, o2); pass(&test, o1); dump_cluster("After adding 3", &test); return 0; } Example output (the addresses will probably differ for you): Testing GOT HERE After adding 1 (0x7ffeed15b3b0): size = 1, capacity = 3, objects = 0x7ffeed15b3c0 [0] id = 3, pos = (3, 3) After adding 3 (0x7ffeed15b3b0): size = 3, capacity = 3, objects = 0x7ffeed15b3c0 [0] id = 3, pos = (3, 3) [1] id = 2, pos = (2, 2) [2] id = 1, pos = (1, 1)
How to refer to a specific struct in an array, while the array is in a struct in a function in C?
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> // sqrtf #include <limits.h> // INT_MAX #include <string.h> // strcmp, strlen, strcat #include <time.h> // time.NULL int logger = 0; struct obj_t { int id; float x; float y; }; struct cluster_t { int size; int capacity; struct obj_t *obj; }; void point_ctor(struct obj_t *p,int id, float x, float y){ p->id = id; p->x = x; p->y = y; } void init_cluster(struct cluster_t *c, int cap) { assert(c != NULL); assert(cap >= 0); // TODO c->capacity = cap; c->size = 0; c->obj = NULL; } /// Chunk of cluster objects. Value recommended for reallocation. const int CLUSTER_CHUNK = 10; struct cluster_t *resize_cluster(struct cluster_t *c, int new_cap) { // TUTO FUNKCI NEMENTE assert(c); assert(c->capacity >= 0); assert(new_cap >= 0); if (c->capacity >= new_cap) return c; size_t size = sizeof(struct obj_t) * new_cap; void *arr = realloc(c->obj, size); if (arr == NULL) return NULL; c->obj = (struct obj_t*)arr; c->capacity = new_cap; return c; } void append_cluster(struct cluster_t *c, struct obj_t obj) { // TODO if(c->size == c->capacity){ resize_cluster(c,(c->capacity)+1); } c->size += 1; //point musim pridat c->obj[(c->size)-1] strukt arg 2 c->obj[((c->size)-1)].id = obj.id; printf("TUSOM"); c->obj[(c->size)-1].x = obj.x; printf("TUSOM"); c->obj[(c->size)-1].y = obj.y; printf("TUSOM"); } void print_cluster(struct cluster_t *c) { // TUTO FUNKCI NEMENTE for (int i = 0; i < c->size; i++) { if (i) putchar(' '); printf("%d[%g,%g]", c->obj[i].id, c->obj[i].x, c->obj[i].y); } putchar('\n'); } void print_clusters(struct cluster_t *carr, int narr) { printf("Clusters:\n"); for (int i = 0; i < narr; i++) { printf("cluster %d: ", i); print_cluster(&carr[i]); } } int load_clusters(char *filename, struct cluster_t **arr){ assert(arr != NULL); FILE * obj; assert(obj = fopen(filename, "r")); //count init for number of objects char tempcount[100]; char countnumbers[100]; int count; int numberstart; int counter = 0; fscanf(obj, "%s", tempcount); for(int i = 0; i<strlen(tempcount); i++){ if(tempcount[i] == '='){ numberstart = i; break; } } for(int i = numberstart; i < strlen(tempcount); i++){ if(tempcount[i] >= 48 && tempcount[i] <= 57){ countnumbers[counter] = tempcount[i]; counter++; } } assert(strlen(countnumbers) > 0); count = atoi(countnumbers); // Get ID, X, Y int id, x, y, pos = 0; struct obj_t point[count]; while(fscanf(obj, "%d %d %d", &id, &x, &y) == 3) { // Build array point_ctor(&point[pos],id,x,y); arr[pos] = malloc(sizeof(struct obj_t)); init_cluster(arr[pos],count); append_cluster(arr[pos], point[pos]); printf("Object %d at X%f Y%f\n", arr[pos]->obj[pos].id,arr[pos]->obj[pos].x, arr[pos]->obj[pos].y); pos++; } fclose(obj); return 0; } int main(int argc, char *argv[]) { struct cluster_t *cluster; char extension[4]; strcpy(extension,".txt"); char subor[100]; strcpy(subor,argv[1]); strcat(subor,extension); load_clusters(subor, &cluster); //print_clusters(&cluster[3],20); // Lloydov algoritmus return 0; } the program is run: ./program objekty objekty - name of file without .txt An example of an input file: "objekty.txt": count=20 40 86 663 43 747 938 47 285 973 49 548 422 52 741 541 56 44 854 57 795 59 61 267 375 62 85 874 66 125 211 68 80 770 72 277 272 74 222 444 75 28 603 79 926 463 83 603 68 86 238 650 87 149 304 89 749 190 93 944 835 The problem seems to be at around in function append_cluster in line: c->obj[((c->size)-1)].id = obj.id; (line 150) A brief explanation before going through the code: Here are my structs: ``` struct obj_t { int id; float x; float y; }; struct cluster_t { int size; int capacity; struct obj_t *obj; }; ``` Full code pastebin: https://pastebin.com/cffiDYBm I make an array of cluster_t structs in main(); (struct cluster_t *cluster;) I pass this array to a function load_clusters(filename, &cluster); Function def: int load_clusters(char *filename, struct cluster_t **arr) I do some code and pass an index of the cluster array to an append function append_cluster(arr[pos], point[pos]); this function effectively adds a point at the end of the array. (resizes if needed) Function def: void append_cluster(struct cluster_t *c, struct obj_t obj); The problem: I need to be able to change data of a specific obj_t in a cluster_t array (cluster_t->obj[n]). The results being that my code stopped running and the line was not processed. Is there any other way to do this? Is it a small change in syntax? I'm out of ideas. I tried: c->obj[(c->size)-1].id = obj.id; Also I made a function which did this for me but I got the same results: void obj_ctor(struct obj_t *p, struct obj_t obj){ p->id = obj.id; p->x = obj.x; p->y = obj.y; } Here is the problem which should be as minimal as possible: (I'm trying to get both printfs on stdout) #include <stdio.h> #include <stdlib.h> struct obj_t { int id; float x; float y; }; struct cluster_t { int size; int capacity; struct obj_t *obj; }; void obj_ctor(struct obj_t *p, struct obj_t obj){ p->id = obj.id; p->x = obj.x; p->y = obj.y; } void pass(struct cluster_t *p, struct obj_t add){ obj_ctor(&p->obj[0],add); p->size += 1; } void pass1(struct cluster_t **arr){ struct obj_t o3; o3.id = 1; o3.x = 2; o3.y = 3; int count = 20; int pos = 0; while(pos < 3){ arr[pos]->capacity = 3; arr[pos]->size = 0; arr[pos]->obj = malloc(count*sizeof(struct obj_t)); pass(arr[pos], o3); pos++; } } int main(int argc, char *argv[]) { printf("Testing"); struct cluster_t *test; pass1(&test); printf("GOT HERE"); }
[ "The final minimal example is nicely manageable โ€” thank you. Here is a fairly straight-forward extension of that code. It is lazy in that it uses assert() to enforce necessary properties.\nIt includes a function to dump the data in a struct cluster_t structure. I regard such functions as a necessity โ€” at the very least, they're extremely helpful. Quite often, I write them to take a FILE *fp argument so that messages can be written to standard output, standard error or to a log file, or, indeed, anywhere you can point a file stream. Often, I'd have a separate dump_obj() function that would be invoked from dump_cluster(), but it doesn't seem necessary here.\nThe key point is that it ensures that test.obj in main() points to an array of 3 struct obj_t. If you want dynamic memory allocation, changes are needed.\n/* SO 7467-2430 */\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct obj_t\n{\n int id;\n float x;\n float y;\n};\n\nstruct cluster_t\n{\n int size;\n int capacity;\n struct obj_t *obj;\n};\n\nstatic void obj_ctor(struct obj_t *p, struct obj_t obj)\n{\n p->id = obj.id;\n p->x = obj.x;\n p->y = obj.y;\n}\n\nstatic void pass(struct cluster_t *p, struct obj_t add)\n{\n assert(p != NULL && p->obj != NULL);\n assert(p->size < p->capacity);\n obj_ctor(&p->obj[p->size], add);\n p->size += 1;\n}\n\nstatic void dump_cluster(const char *tag, struct cluster_t *p)\n{\n printf(\"%s (%p):\\n\", tag, p);\n if (p != NULL)\n {\n printf(\"size = %d, capacity = %d, objects = %p\\n\", p->size, p->capacity, p->obj);\n for (int i = 0; i < p->size; i++)\n printf(\" [%d] id = %d, pos = (%g, %g)\\n\", i, p->obj[i].id, p->obj[i].x, p->obj[i].y);\n }\n}\n\nint main(void)\n{\n printf(\"Testing\\n\");\n struct cluster_t test;\n struct obj_t o1, o2, o3;\n o1.id = 1;\n o2.id = 2;\n o3.id = 3;\n o1.x = 1;\n o2.x = 2;\n o3.x = 3;\n o1.y = 1;\n o2.y = 2;\n o3.y = 3;\n test.capacity = 3;\n test.size = 0;\n struct obj_t arr[3]; \n test.obj = arr;\n\n pass(&test, o3);\n printf(\"GOT HERE\\n\");\n dump_cluster(\"After adding 1\", &test);\n pass(&test, o2);\n pass(&test, o1);\n dump_cluster(\"After adding 3\", &test);\n\n return 0;\n}\n\nExample output (the addresses will probably differ for you):\nTesting\nGOT HERE\nAfter adding 1 (0x7ffeed15b3b0):\nsize = 1, capacity = 3, objects = 0x7ffeed15b3c0\n [0] id = 3, pos = (3, 3)\nAfter adding 3 (0x7ffeed15b3b0):\nsize = 3, capacity = 3, objects = 0x7ffeed15b3c0\n [0] id = 3, pos = (3, 3)\n [1] id = 2, pos = (2, 2)\n [2] id = 1, pos = (1, 1)\n\n" ]
[ 0 ]
[]
[]
[ "c" ]
stackoverflow_0074672430_c.txt
Q: How to test for a reference cycle caused by saved exception? I'm talking about this problem: https://bugs.python.org/issue36820. Small summary: Saving an exception causes a cyclic reference, because the exception's data include a traceback containing the stack frame with the variable where the exception was saved. try: 1/0 except Exception as e: ee = e The code is not broken, beacuse Python will eventually free the memory with its garbage collector. But the whole sitation can be avoided: try: 1/0 except Exception as e: ee = e ... ... finally: ee = None In the linked bpo-36820 there is a demonstration with a weak reference kept alive. My question is if there exist a test that does not need to edit the function itself. Something like run the tested function check if a new cycle was created Can the gc module do that? A: Yes, using the gc module, we can check whether there are (new) exceptions that are only referred to by a traceback frame. In practice, iterating gc objects creates an additional referrer (can't use WeakSet as built-in exceptions don't support weakref), so we check that there are two referrers โ€” the frame and the additional referrer. def get_exception_ids_with_reference_cycle(exclude_ids=None): import gc import types exclude_ids = () if exclude_ids is None else exclude_ids exceptions = [ o for o in gc.get_objects(generation=0) if isinstance(o, Exception) and id(o) not in exclude_ids ] exception_ids = [ id(e) for e in exceptions if len(gc.get_referrers(e)) == 2 and all( isinstance(r, types.FrameType) or r is exceptions for r in gc.get_referrers(e) ) ] return exception_ids Usage: exception_ids = get_exception_ids_with_reference_cycle() x() print(bool(get_exception_ids_with_reference_cycle(exclude_ids=exception_ids))) Alternative usage: @contextlib.contextmanager def make_helper(): exception_ids = get_exception_ids_with_reference_cycle() yield lambda: bool(get_exception_ids_with_reference_cycle(exclude_ids=exception_ids)) with make_helper() as get_true_if_reference_cycle_was_created: x() print(get_true_if_reference_cycle_was_created())
How to test for a reference cycle caused by saved exception?
I'm talking about this problem: https://bugs.python.org/issue36820. Small summary: Saving an exception causes a cyclic reference, because the exception's data include a traceback containing the stack frame with the variable where the exception was saved. try: 1/0 except Exception as e: ee = e The code is not broken, beacuse Python will eventually free the memory with its garbage collector. But the whole sitation can be avoided: try: 1/0 except Exception as e: ee = e ... ... finally: ee = None In the linked bpo-36820 there is a demonstration with a weak reference kept alive. My question is if there exist a test that does not need to edit the function itself. Something like run the tested function check if a new cycle was created Can the gc module do that?
[ "Yes, using the gc module, we can check whether there are (new) exceptions that are only referred to by a traceback frame.\nIn practice, iterating gc objects creates an additional referrer (can't use WeakSet as built-in exceptions don't support weakref), so we check that there are two referrers โ€” the frame and the additional referrer.\ndef get_exception_ids_with_reference_cycle(exclude_ids=None):\n import gc\n import types\n exclude_ids = () if exclude_ids is None else exclude_ids\n exceptions = [\n o for o in gc.get_objects(generation=0)\n if isinstance(o, Exception) and id(o) not in exclude_ids\n ]\n exception_ids = [\n id(e) for e in exceptions\n if len(gc.get_referrers(e)) == 2 and all(\n isinstance(r, types.FrameType) or r is exceptions\n for r in gc.get_referrers(e)\n )\n ]\n return exception_ids\n\nUsage:\nexception_ids = get_exception_ids_with_reference_cycle()\nx()\nprint(bool(get_exception_ids_with_reference_cycle(exclude_ids=exception_ids)))\n\nAlternative usage:\[email protected]\ndef make_helper():\n exception_ids = get_exception_ids_with_reference_cycle()\n yield lambda: bool(get_exception_ids_with_reference_cycle(exclude_ids=exception_ids))\n\n\nwith make_helper() as get_true_if_reference_cycle_was_created:\n x()\n print(get_true_if_reference_cycle_was_created())\n\n" ]
[ 2 ]
[ "I believe you can use the gc module to do something like this.\nimport gc\n\n# First, enable garbage collection\ngc.enable()\n\n# Save an exception to a variable\nexception = Exception('test exception')\n\n# Check for objects that are no longer being referenced by the program\nif gc.garbage:\n # Print the objects that are causing the cycle\n print(gc.garbage)\n\n # Use the gc.get_referrers method to find out what objects\n # are causing the cycle\n for obj in gc.garbage:\n print(gc.get_referrers(obj))\n\n # Modify your code to break the cycle\n # (This will depend on your specific code and the objects\n # involved in the cycle)\n\n" ]
[ -1 ]
[ "garbage_collection", "python" ]
stackoverflow_0067157372_garbage_collection_python.txt
Q: How to use KBinsDiscretizer with defined bin edges I need to discretize one column in my dataframe according to the following bin edges [ -1.4968, 2.546612, 3.612398, 6.18902] I see how to create the KBinsDiscretizer object but how to ask it to use my predefined bins? A: KBinsDiscretizer determines the cut-points according to the strategy selected. If you have predefined bin edges you can use pandas.cut() or numpy.digitize().
How to use KBinsDiscretizer with defined bin edges
I need to discretize one column in my dataframe according to the following bin edges [ -1.4968, 2.546612, 3.612398, 6.18902] I see how to create the KBinsDiscretizer object but how to ask it to use my predefined bins?
[ "KBinsDiscretizer determines the cut-points according to the strategy selected. If you have predefined bin edges you can use pandas.cut() or numpy.digitize().\n" ]
[ 0 ]
[]
[]
[ "python_3.x", "scikit_learn" ]
stackoverflow_0060417402_python_3.x_scikit_learn.txt
Q: How can I get the source of chat without using selenium? So my issue is that, I want to get user's id info from the chat. The chat area what I'm looking for, looks like this... <div id="chat_area" class="chat_area" style="will-change: scroll-position;"> <dl class="" user_id="asdf1234"><dt class="user_m"><em class="pc"></em> :</dt><dd id="1">blah blah</dd></dl> <a href="javascript:;" user_id="asdf1234" user_nick="asdf1234" userflag="65536" is_mobile="false" grade="user">asdf1234</a> ... What I want do is to, Get the part starting with <a href='javascript:'' user_id='asdf1234' ... so that I can parse this and do some other stuffs. But this webpage is the one I'm currently using, and it can not be proxy(webdriver by selenium). How can I extract that data from the chat? A: It looks like you've got two separate problems here. I'd use both the requests and BeautifulSoup libraries to accomplish this. Use your browser's developer tools, the network tab, to refresh the page and look for the request which responds with the HTML you want. Use the requests library to emulate this request exactly. import requests headers = {"name": "value"} # Get case example. response = requests.get("some_url", headers=headers) # Post case example. data = {"key": "value"} response = requests.post("some_url", headers=headers, data=data) Web-scraping is always finicky, if this doesn't work you're most likely going to need to use a requests session. Or a one-time hacky solution is just to set your cookies from the browser. Once you have made the request you can use BeautifulSoup to scrape your user id very easily. from bs4 import BeautifulSoup # Create BS parser. soup = BeautifulSoup(response.text, 'lxml') # Find all elements with the attribute "user_id". find_results = soup.findAll("a", {"user_id" : True}) # Iterate results. Could also just index if you want the single user_id. for result in find_results: user_id = result["user_id"] A: In order to extract data from the chat area you would need to use a web scraping tool or library. Since you mentioned that you cannot use a proxy such as Selenium, you may want to consider using a library in a programming language like Python or JavaScript to scrape the data from the chat area. For example, in Python you could use BeautifulSoup to parse the HTML of the page and extract the desired information. You could then use the user_id value to do any further processing that you need to do. Alternatively, if you have access to the server-side code for the page, you could modify it to include the user_id information in a more easily accessible way, such as in a data attribute on the chat area element itself. This would allow you to easily retrieve the user_id value using JavaScript without having to scrape the page.
How can I get the source of chat without using selenium?
So my issue is that, I want to get user's id info from the chat. The chat area what I'm looking for, looks like this... <div id="chat_area" class="chat_area" style="will-change: scroll-position;"> <dl class="" user_id="asdf1234"><dt class="user_m"><em class="pc"></em> :</dt><dd id="1">blah blah</dd></dl> <a href="javascript:;" user_id="asdf1234" user_nick="asdf1234" userflag="65536" is_mobile="false" grade="user">asdf1234</a> ... What I want do is to, Get the part starting with <a href='javascript:'' user_id='asdf1234' ... so that I can parse this and do some other stuffs. But this webpage is the one I'm currently using, and it can not be proxy(webdriver by selenium). How can I extract that data from the chat?
[ "It looks like you've got two separate problems here. I'd use both the requests and BeautifulSoup libraries to accomplish this.\nUse your browser's developer tools, the network tab, to refresh the page and look for the request which responds with the HTML you want. Use the requests library to emulate this request exactly.\nimport requests\n\nheaders = {\"name\": \"value\"}\n\n# Get case example.\nresponse = requests.get(\"some_url\", headers=headers)\n\n# Post case example.\ndata = {\"key\": \"value\"}\nresponse = requests.post(\"some_url\", headers=headers, data=data)\n\nWeb-scraping is always finicky, if this doesn't work you're most likely going to need to use a requests session. Or a one-time hacky solution is just to set your cookies from the browser.\nOnce you have made the request you can use BeautifulSoup to scrape your user id very easily.\nfrom bs4 import BeautifulSoup\n\n# Create BS parser.\nsoup = BeautifulSoup(response.text, 'lxml')\n\n# Find all elements with the attribute \"user_id\".\nfind_results = soup.findAll(\"a\", {\"user_id\" : True})\n\n# Iterate results. Could also just index if you want the single user_id.\nfor result in find_results:\n user_id = result[\"user_id\"]\n\n", "In order to extract data from the chat area you would need to use a web scraping tool or library. Since you mentioned that you cannot use a proxy such as Selenium, you may want to consider using a library in a programming language like Python or JavaScript to scrape the data from the chat area.\nFor example, in Python you could use BeautifulSoup to parse the HTML of the page and extract the desired information. You could then use the user_id value to do any further processing that you need to do.\nAlternatively, if you have access to the server-side code for the page, you could modify it to include the user_id information in a more easily accessible way, such as in a data attribute on the chat area element itself. This would allow you to easily retrieve the user_id value using JavaScript without having to scrape the page.\n" ]
[ 0, 0 ]
[]
[]
[ "html", "python", "python_requests", "selenium" ]
stackoverflow_0074672630_html_python_python_requests_selenium.txt
Q: Flutter GetX Snackbar Actions I was wondering how to implement GetX's Snackbar but with actions. I know how to write SnackbarActions on the usual ScaffoldSnackbar provided with Flutter. I was wondering if there was a way to get this same functionality in GetX's Snackbar. As you may be able to guess, I am trying to implement an undo functionality, and I wrote the rest of my app with GetX Snackbars. This is how I know how to show a Snackbar with Actions ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text("Deleted ${item.matchNumber.value}"), action: SnackBarAction( label: "Undo", onPressed: () => controller.documentsHelper .saveMatchData(item), ), duration: const Duration(seconds: 3), ), ); How would get this functionality through GetX? Thanks! A: Try this Get.snackbar( 'Snackber', 'Deleted ${item.matchNumber.value}', duration: const Duration(seconds: 3), colorText: Colors.black, backgroundColor: Colors.white, snackPosition: SnackPosition.BOTTOM, maxWidth: Get.width, mainButton: TextButton( child: Text('Undo'), onPressed: () { controller.documentsHelper .saveMatchData(item); }, ), );
Flutter GetX Snackbar Actions
I was wondering how to implement GetX's Snackbar but with actions. I know how to write SnackbarActions on the usual ScaffoldSnackbar provided with Flutter. I was wondering if there was a way to get this same functionality in GetX's Snackbar. As you may be able to guess, I am trying to implement an undo functionality, and I wrote the rest of my app with GetX Snackbars. This is how I know how to show a Snackbar with Actions ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text("Deleted ${item.matchNumber.value}"), action: SnackBarAction( label: "Undo", onPressed: () => controller.documentsHelper .saveMatchData(item), ), duration: const Duration(seconds: 3), ), ); How would get this functionality through GetX? Thanks!
[ "Try this\n Get.snackbar(\n 'Snackber',\n 'Deleted ${item.matchNumber.value}',\n duration: const Duration(seconds: 3),\n colorText: Colors.black,\n backgroundColor: Colors.white,\n snackPosition: SnackPosition.BOTTOM,\n maxWidth: Get.width,\n mainButton: TextButton(\n child: Text('Undo'),\n onPressed: () {\n controller.documentsHelper\n .saveMatchData(item);\n },\n ),\n );\n \n\n" ]
[ 2 ]
[]
[]
[ "dart", "flutter", "flutter_dependencies", "flutter_getx", "snackbar" ]
stackoverflow_0074580691_dart_flutter_flutter_dependencies_flutter_getx_snackbar.txt
Q: Get the integer value from an enum I am doing Advent of Code 2022 Day 2, and I have the following enums: type GameMove {.pure.} = enum rock = 1, paper = 2, scissors = 3 and I'd like to be able to perform the following calculation: ours = rock theirs = scissors echo ours - theirs However, I get the error that there is no proc - defined for <GameMove, GameMove>. Indeed there isn't! But how can I define it, and/or how can I get the integer values from this enum in order to perform my calculation? A: Converting to int does work, but apparently the correct answer (which is weirdly missing from the language manual) is the ord function, in the system module: ours = rock theirs = scissors echo ours.ord - theirs.ord Edit: ord is mentioned in the official tutorial, but only in passing, and it's easy to miss or forget!
Get the integer value from an enum
I am doing Advent of Code 2022 Day 2, and I have the following enums: type GameMove {.pure.} = enum rock = 1, paper = 2, scissors = 3 and I'd like to be able to perform the following calculation: ours = rock theirs = scissors echo ours - theirs However, I get the error that there is no proc - defined for <GameMove, GameMove>. Indeed there isn't! But how can I define it, and/or how can I get the integer values from this enum in order to perform my calculation?
[ "Converting to int does work, but apparently the correct answer (which is weirdly missing from the language manual) is the ord function, in the system module:\nours = rock\ntheirs = scissors\necho ours.ord - theirs.ord\n\nEdit: ord is mentioned in the official tutorial, but only in passing, and it's easy to miss or forget!\n" ]
[ 1 ]
[]
[]
[ "enums", "nim" ]
stackoverflow_0074672660_enums_nim.txt
Q: Grep for a character in one element of a vector Unless I am overlooking something, I cannot find the solution to the following. If I have the following single element vector: c("133 45123; 4514;25") How can I find the position within this element that has the ";" and " ", such that I can then use substr to obtain: 45123; Have tried grep, but that seems to work over a vector of multiple elements. A: x <- c("133 45123; 4514;25") stringr::str_extract(x, "\\w+(?=; )") [1] "45123" In Base R: sub(".*?(\\w+); .*", "\\1", x) [1] "45123" or even: regmatches(x, regexpr("\\w+(?=; )", x, perl = TRUE)) [1] "45123" A: Strsplit() will do it. Knew I was overlooking something.
Grep for a character in one element of a vector
Unless I am overlooking something, I cannot find the solution to the following. If I have the following single element vector: c("133 45123; 4514;25") How can I find the position within this element that has the ";" and " ", such that I can then use substr to obtain: 45123; Have tried grep, but that seems to work over a vector of multiple elements.
[ "x <- c(\"133 45123; 4514;25\")\n\nstringr::str_extract(x, \"\\\\w+(?=; )\")\n[1] \"45123\"\n\nIn Base R:\nsub(\".*?(\\\\w+); .*\", \"\\\\1\", x)\n[1] \"45123\"\n\nor even:\nregmatches(x, regexpr(\"\\\\w+(?=; )\", x, perl = TRUE))\n[1] \"45123\"\n\n", "Strsplit() will do it. Knew I was overlooking something.\n" ]
[ 2, 0 ]
[]
[]
[ "grep", "r" ]
stackoverflow_0074672691_grep_r.txt
Q: BuildContext when using GetX I try refactor my flutter app and start using GetX library. I using library "flutter_form_builder", and some methods here need BuildContext argument. For example: String? Function(T?) FormBuilderValidators.equal<T>( BuildContext context, Object value, { String? errorText, }) I try add as argument Get.context, but Get.context type is BuildContext? not BuildContext Any idea how to solve it? A: you can use Get.context which comes from the Getx package when you need it outside your UI, and mark it with ! so it will be a BuildContext type: Get.context // this is BuildContext? Get.context! // this is BuildContext you can also cast it directly like this: Get.context as BuildContext // this is BuildContext Note: using Get.context requires that you need to change MaterialApp with GetMaterialApp so it will never be null, otherwise it will throws a null error A: To use the Get.context property, you will need to make sure that it is not null before passing it to a method that expects a BuildContext object. You can do this by using the ?? null-coalescing operator to provide a default value for the Get.context property, like this: String? Function(T?) FormBuilderValidators.equal<T>( BuildContext context, Object value, { String? errorText, }) => FormBuilderValidators.equal(Get.context ?? context, value, errorText: errorText); This will check if Get.context is null, and if it is, it will use the context argument that was passed to the method as the BuildContext object. Otherwise, it will use the Get.context property as the BuildContext object.
BuildContext when using GetX
I try refactor my flutter app and start using GetX library. I using library "flutter_form_builder", and some methods here need BuildContext argument. For example: String? Function(T?) FormBuilderValidators.equal<T>( BuildContext context, Object value, { String? errorText, }) I try add as argument Get.context, but Get.context type is BuildContext? not BuildContext Any idea how to solve it?
[ "you can use Get.context which comes from the Getx package when you need it outside your UI, and mark it with ! so it will be a BuildContext type:\nGet.context // this is BuildContext?\nGet.context! // this is BuildContext\n\nyou can also cast it directly like this:\nGet.context as BuildContext // this is BuildContext\n\nNote: using Get.context requires that you need to change MaterialApp with GetMaterialApp so it will never be null, otherwise it will throws a null error\n", "To use the Get.context property, you will need to make sure that it is not null before passing it to a method that expects a BuildContext object. You can do this by using the ?? null-coalescing operator to provide a default value for the Get.context property, like this:\nString? Function(T?) FormBuilderValidators.equal<T>(\n BuildContext context,\n Object value, {\n String? errorText,\n}) => FormBuilderValidators.equal(Get.context ?? context, value, errorText: errorText);\n\nThis will check if Get.context is null, and if it is, it will use the context argument that was passed to the method as the BuildContext object. Otherwise, it will use the Get.context property as the BuildContext object.\n" ]
[ 0, 0 ]
[]
[]
[ "flutter", "flutter_getx" ]
stackoverflow_0070779462_flutter_flutter_getx.txt
Q: SuiteScript 2.0 - Load Custom Record Table Data Within Customization -> List, Records & Fields -> Custom Records I have a table with id: customrecord_{name} with the type "customrecordtype". I have multiple fields in that record How can I use the load function to get all the data for this table/record? (For all the fields) const data= record.load({ type: 'customrecord_{name}', isDynamic: false ... //get all fields }); I tried to look at the help center but am a bit lost on how to accomplish this. A: As far as I know load won't do it. After loading a custom record with load, you can check all the fields of this custom record by calling data.getFields() method. This will return a list of field ids (including custom ones) that you can fetch by calling data.getValue such as data.getValue({'fieldId':'isinactive'}) // a regular field or data.getValue({'fieldId':'custrecord_routeproduce_highpriority'}) // a custom field loading a custom record, checking its fields, fetching value of a custom field
SuiteScript 2.0 - Load Custom Record Table Data
Within Customization -> List, Records & Fields -> Custom Records I have a table with id: customrecord_{name} with the type "customrecordtype". I have multiple fields in that record How can I use the load function to get all the data for this table/record? (For all the fields) const data= record.load({ type: 'customrecord_{name}', isDynamic: false ... //get all fields }); I tried to look at the help center but am a bit lost on how to accomplish this.
[ "As far as I know load won't do it. After loading a custom record with load, you can check all the fields of this custom record by calling data.getFields() method. This will return a list of field ids (including custom ones) that you can fetch by calling data.getValue such as data.getValue({'fieldId':'isinactive'}) // a regular field or data.getValue({'fieldId':'custrecord_routeproduce_highpriority'}) // a custom field\nloading a custom record, checking its fields, fetching value of a custom field\n" ]
[ 0 ]
[]
[]
[ "netsuite", "suitescript", "suitescript2.0" ]
stackoverflow_0074662200_netsuite_suitescript_suitescript2.0.txt
Q: Counting a specific character inside an array, How to make a loop function in C? I am working on a board game, which has a game piece counter. However, I cannot figure out how can I make one with for loop, decrementing every time a piece will be eaten by another piece(character). Initially red pieces and blue pieces are 12 and as the game progresses, they will be eaten and so the game piece should be updated. I am also not recommended to use global variables unless user-defined function. What can I do? #include<stdio.h> char board[8][8] = { {'-', 'B', '-', 'B', '-', 'B', '-', 'B'}, {'B', '-', 'B', '-', 'B', '-', 'B', '-'}, {'-', 'B', '-', 'B', '-', 'B', '-', 'B'}, {' ', '-', ' ', '-', ' ', '-', ' ', '-'}, {'-', ' ', '-', ' ', '-', ' ', '-', ' '}, {'R', '-', 'R', '-', 'R', '-', 'R', '-'}, {'-', 'R', '-', 'R', '-', 'R', '-', 'R'}, {'R', '-', 'R', '-', 'R', '-', 'R', '-'}}; void printBoard() { int i , j , k ; printf("\n "); for(i=0;i<8;i++) printf(" %d", i); printf(" \n"); for(k=0;k<8;k++) { printf(" "); for(i=0;i<42;i++) { printf("-"); } printf(" \n"); printf(" %d ", k); for(j=0;j<8;j++) { printf("|| %c ", board[k][j]); } printf("|| \n"); } printf(" "); for(i=0;i<42;i++) { printf("-"); } printf(" \n"); } int gamePiece(int Player1, int BluePiece, int Player2, int RedPiece) { int i, j; printf("\n\Game piece counter:"); //for loop printf("\nPlayer %d = %d",Player1,BluePiece); printf("\nPlayer %d = %d",Player2,RedPiece); return 0; } int main(){ int Player1, BluePiece=12, Player2, RedPiece=12; gamePiece(Player1, BluePiece, Player2, RedPiece); return 0; } ` A: In your question, you state that you don't want to use global variables, but you are already using the global variable board. I recommend that you define a single struct that contains the entire game state, which includes the 2D array of the board as well as the number of blue and red pieces. You can then create an instance of this struct in the function main and pass a pointer to this struct to all functions that need to read or change the game state. That way, you are using no global variables. It is generally recommended not to use them. Here is an example: #include <stdio.h> struct game_state { char board[8][8]; int blue_pieces; int red_pieces; }; void eat_piece( struct game_state *p_gs, int predator_x, int predator_y, int prey_x, int prey_y ) { char (*board)[8] = p_gs->board; char predator = board[predator_y][predator_x]; char prey = board[prey_y][prey_x]; //remove the prey from the game and replace with predator if ( prey == 'R' ) p_gs->red_pieces--; else if ( prey == 'B' ) p_gs->blue_pieces--; board[prey_y][prey_x] = predator; //make the old board position of the predator empty board[predator_y][predator_x] = '-'; } void print_board( struct game_state *p_gs ) { char (*board)[8] = p_gs->board; printf( "\nBoard Content:\n" ); for ( int i = 0; i < 8; i++ ) { for ( int j = 0; j < 8; j++ ) { printf( " %c", board[i][j] ); } printf( "\n" ); } } void print_pieces( struct game_state *p_gs ) { printf( "Blue has %d pieces.\n", p_gs->blue_pieces ); printf( "Red has %d pieces.\n", p_gs->red_pieces ); } int main( void ) { //define and initialize the initial game state struct game_state gs = { { { '-', 'B', '-', 'B', '-', 'B', '-', 'B' }, { 'B', '-', 'B', '-', 'B', '-', 'B', '-' }, { '-', 'B', '-', 'B', '-', 'B', '-', 'B' }, { ' ', '-', ' ', '-', ' ', '-', ' ', '-' }, { '-', ' ', '-', ' ', '-', ' ', '-', ' ' }, { 'R', '-', 'R', '-', 'R', '-', 'R', '-' }, { '-', 'R', '-', 'R', '-', 'R', '-', 'R' }, { 'R', '-', 'R', '-', 'R', '-', 'R', '-' } }, 12, 12 }; //make the blue piece at board[2][1] eat the red piece at //board[5][2] eat_piece( &gs, 1, 2, 2, 5 ); //print the number of pieces print_pieces( &gs ); //print the board content print_board( &gs ); } This program has the following output: Blue has 12 pieces. Red has 11 pieces. Board Content: - B - B - B - B B - B - B - B - - - - B - B - B - - - - - - - - R - B - R - R - - R - R - R - R R - R - R - R - As you can see, the statement eat_piece( &gs, 1, 2, 2, 5 ); in the function main successfully caused the blue piece at board[2][1] to eat the red piece at board[5][2], which caused the number of red pieces to be reduced from 12 to 11.
Counting a specific character inside an array, How to make a loop function in C?
I am working on a board game, which has a game piece counter. However, I cannot figure out how can I make one with for loop, decrementing every time a piece will be eaten by another piece(character). Initially red pieces and blue pieces are 12 and as the game progresses, they will be eaten and so the game piece should be updated. I am also not recommended to use global variables unless user-defined function. What can I do? #include<stdio.h> char board[8][8] = { {'-', 'B', '-', 'B', '-', 'B', '-', 'B'}, {'B', '-', 'B', '-', 'B', '-', 'B', '-'}, {'-', 'B', '-', 'B', '-', 'B', '-', 'B'}, {' ', '-', ' ', '-', ' ', '-', ' ', '-'}, {'-', ' ', '-', ' ', '-', ' ', '-', ' '}, {'R', '-', 'R', '-', 'R', '-', 'R', '-'}, {'-', 'R', '-', 'R', '-', 'R', '-', 'R'}, {'R', '-', 'R', '-', 'R', '-', 'R', '-'}}; void printBoard() { int i , j , k ; printf("\n "); for(i=0;i<8;i++) printf(" %d", i); printf(" \n"); for(k=0;k<8;k++) { printf(" "); for(i=0;i<42;i++) { printf("-"); } printf(" \n"); printf(" %d ", k); for(j=0;j<8;j++) { printf("|| %c ", board[k][j]); } printf("|| \n"); } printf(" "); for(i=0;i<42;i++) { printf("-"); } printf(" \n"); } int gamePiece(int Player1, int BluePiece, int Player2, int RedPiece) { int i, j; printf("\n\Game piece counter:"); //for loop printf("\nPlayer %d = %d",Player1,BluePiece); printf("\nPlayer %d = %d",Player2,RedPiece); return 0; } int main(){ int Player1, BluePiece=12, Player2, RedPiece=12; gamePiece(Player1, BluePiece, Player2, RedPiece); return 0; } `
[ "In your question, you state that you don't want to use global variables, but you are already using the global variable board.\nI recommend that you define a single struct that contains the entire game state, which includes the 2D array of the board as well as the number of blue and red pieces. You can then create an instance of this struct in the function main and pass a pointer to this struct to all functions that need to read or change the game state. That way, you are using no global variables. It is generally recommended not to use them.\nHere is an example:\n#include <stdio.h>\n\nstruct game_state\n{\n char board[8][8];\n int blue_pieces;\n int red_pieces;\n};\n\nvoid eat_piece(\n struct game_state *p_gs,\n int predator_x,\n int predator_y,\n int prey_x,\n int prey_y\n)\n{\n char (*board)[8] = p_gs->board;\n char predator = board[predator_y][predator_x];\n char prey = board[prey_y][prey_x];\n\n //remove the prey from the game and replace with predator\n if ( prey == 'R' )\n p_gs->red_pieces--;\n else if ( prey == 'B' )\n p_gs->blue_pieces--;\n board[prey_y][prey_x] = predator;\n\n //make the old board position of the predator empty\n board[predator_y][predator_x] = '-';\n}\n\nvoid print_board( struct game_state *p_gs )\n{\n char (*board)[8] = p_gs->board;\n \n printf( \"\\nBoard Content:\\n\" );\n \n for ( int i = 0; i < 8; i++ )\n {\n for ( int j = 0; j < 8; j++ )\n {\n printf( \" %c\", board[i][j] );\n }\n\n printf( \"\\n\" );\n }\n}\n\nvoid print_pieces( struct game_state *p_gs )\n{\n printf( \"Blue has %d pieces.\\n\", p_gs->blue_pieces );\n printf( \"Red has %d pieces.\\n\", p_gs->red_pieces );\n}\n\nint main( void )\n{\n //define and initialize the initial game state\n struct game_state gs = {\n {\n { '-', 'B', '-', 'B', '-', 'B', '-', 'B' },\n { 'B', '-', 'B', '-', 'B', '-', 'B', '-' },\n { '-', 'B', '-', 'B', '-', 'B', '-', 'B' },\n { ' ', '-', ' ', '-', ' ', '-', ' ', '-' },\n { '-', ' ', '-', ' ', '-', ' ', '-', ' ' },\n { 'R', '-', 'R', '-', 'R', '-', 'R', '-' },\n { '-', 'R', '-', 'R', '-', 'R', '-', 'R' },\n { 'R', '-', 'R', '-', 'R', '-', 'R', '-' }\n },\n 12,\n 12\n };\n \n //make the blue piece at board[2][1] eat the red piece at\n //board[5][2]\n eat_piece( &gs, 1, 2, 2, 5 );\n\n //print the number of pieces\n print_pieces( &gs );\n\n //print the board content\n print_board( &gs );\n}\n\nThis program has the following output:\nBlue has 12 pieces.\nRed has 11 pieces.\n\nBoard Content:\n - B - B - B - B\n B - B - B - B -\n - - - B - B - B\n - - - -\n - - - - \n R - B - R - R -\n - R - R - R - R\n R - R - R - R -\n\nAs you can see, the statement\neat_piece( &gs, 1, 2, 2, 5 );\n\nin the function main successfully caused the blue piece at board[2][1] to eat the red piece at board[5][2], which caused the number of red pieces to be reduced from 12 to 11.\n" ]
[ 0 ]
[]
[]
[ "arrays", "c", "character" ]
stackoverflow_0074672279_arrays_c_character.txt
Q: How to use the first row as keys in excel for python selenium I am making auto login tool on selenium, i want it to use row by row to get login information. I used this code to do it but it only uses the 28th row. Is there a way for it to automatically get the data from the first row to the next to the next? Thank u all! from selenium import webdriver from selenium.webdriver.common.proxy import * from selenium.webdriver.common.by import By from time import sleep import time import openpyxl import requests def get_value_excel(filename, cellname): wb = openpyxl.load_workbook(filename) Sheet1 = wb['Sheet1'] wb.close() return Sheet1[cellname].value def update_value_excel(filename, cellname, value): wb = openpyxl.load_workbook(filename) Sheet1 = wb['Sheet1'] Sheet1[cellname].value = value wb.close() wb.save(filename) col_name_acc="A" col_name_pass="B" filename='file.xlsx' for i in range(2,29): cell_name_acc="%s%s"%(col_name_acc, i) cell_name_pass="%s%s"%(col_name_pass, i) account = get_value_excel(filename, cell_name_acc) password = get_value_excel(filename, cell_name_pass) print(i) A: Do you mean for i in range(2,29): doesn't cover the range of rows in the sheet. So you could increase 29 to max that is needed. Or you can use Sheet1.max_row to get the max row number (last row in sheet with data) except you need to create the worksheet (ws) object to get that value. From your code it looks like you are opening the excel workbook (wb) each time you call the function 'get_value_excel' or 'update_value_excel'. If these are called more than once it is inefficient, you should only open the wb/ws one time for reading and updating data. Therefore you could remove the wb and ws object creation from these functions and do that at the start. The ws object is then available to use in the range. Also you mention "first row to the next to the next" so if starting row 1 the range start param should be 1. Rough example of code change ... def get_value_excel(sheet, cellname): return sheet[cellname].value def update_value_excel(sheet, cellname, value): sheet[cellname].value = value col_name_acc = "A" col_name_pass = "B" filename = 'file.xlsx' wb = openpyxl.load_workbook(filename) Sheet1 = wb['Sheet1'] for i in range(1, Sheet1.max_row): cell_name_acc = "%s%s" % (col_name_acc, i) cell_name_pass = "%s%s" % (col_name_pass, i) account = get_value_excel(Sheet1, cell_name_acc) password = get_value_excel(Sheet1, cell_name_pass) print(i) wb.save(filename)
How to use the first row as keys in excel for python selenium
I am making auto login tool on selenium, i want it to use row by row to get login information. I used this code to do it but it only uses the 28th row. Is there a way for it to automatically get the data from the first row to the next to the next? Thank u all! from selenium import webdriver from selenium.webdriver.common.proxy import * from selenium.webdriver.common.by import By from time import sleep import time import openpyxl import requests def get_value_excel(filename, cellname): wb = openpyxl.load_workbook(filename) Sheet1 = wb['Sheet1'] wb.close() return Sheet1[cellname].value def update_value_excel(filename, cellname, value): wb = openpyxl.load_workbook(filename) Sheet1 = wb['Sheet1'] Sheet1[cellname].value = value wb.close() wb.save(filename) col_name_acc="A" col_name_pass="B" filename='file.xlsx' for i in range(2,29): cell_name_acc="%s%s"%(col_name_acc, i) cell_name_pass="%s%s"%(col_name_pass, i) account = get_value_excel(filename, cell_name_acc) password = get_value_excel(filename, cell_name_pass) print(i)
[ "Do you mean\nfor i in range(2,29): \n\ndoesn't cover the range of rows in the sheet. So you could increase 29 to max that is needed. Or you can use\nSheet1.max_row\n\nto get the max row number (last row in sheet with data) except you need to create the worksheet (ws) object to get that value.\nFrom your code it looks like you are opening the excel workbook (wb) each time you call the function 'get_value_excel' or 'update_value_excel'. If these are called more than once it is inefficient, you should only open the wb/ws one time for reading and updating data.\nTherefore you could remove the wb and ws object creation from these functions and do that at the start. The ws object is then available to use in the range.\nAlso you mention \"first row to the next to the next\" so if starting row 1 the range start param should be 1.\nRough example of code change\n...\ndef get_value_excel(sheet, cellname):\n return sheet[cellname].value\n\ndef update_value_excel(sheet, cellname, value):\n sheet[cellname].value = value\n\ncol_name_acc = \"A\"\ncol_name_pass = \"B\"\nfilename = 'file.xlsx'\n\nwb = openpyxl.load_workbook(filename)\nSheet1 = wb['Sheet1']\n\nfor i in range(1, Sheet1.max_row):\n cell_name_acc = \"%s%s\" % (col_name_acc, i)\n cell_name_pass = \"%s%s\" % (col_name_pass, i)\n\n account = get_value_excel(Sheet1, cell_name_acc)\n password = get_value_excel(Sheet1, cell_name_pass)\nprint(i)\n\nwb.save(filename)\n\n" ]
[ 0 ]
[]
[]
[ "excel", "openpyxl", "python", "python_3.x", "selenium_chromedriver" ]
stackoverflow_0074668602_excel_openpyxl_python_python_3.x_selenium_chromedriver.txt
Q: I would like to hide my outer div if inner div is empty I have two div a child and a parent. the child contains a contact number. If there is no contact number I want the parent div to display none. I am trying to use the :empty CSS statement but I think I am using the wrong logic. #inter #inter-content:empty { display:none; } <div id="inter" class="telephone">Intl: <div id="inter-content">{{contact_number_international}}</div></div> I'm not sure if CSS is the right route either. I have tried using the bottom as well: #inter + #inter-content:empty { display:none; } A: You cant do this in the way you are approaching it due to how CSS works, and that you can only write selectors to isolate child/subsequent DOM nodes. :empty also works on selecting elements with no child nodes (elements or text). The :empty pseudo-class represents any element that has no children at all. Only element nodes and text (including whitespace) are considered. As such, you cannot select a parent element using CSS- and you cannot determine a node to be empty, if it contains another node (whether that node is empty or not). One way to potentially get around this, is to apply the label in your code as a pseudo element, with its content conditionally sourced from a (data) attribute if the element is not empty. This will give the impression of the parent not displaying content if no number is present. That said, if you actually dont want to display the parent at all- you will run into trouble using CSS alone. It looks like you are using angular (or similar), in which case you may want to use a logical check to toggle the parent's visibility. .inter div:not(:empty):before { display: block; content: attr(data-label); } <div class="inter" class="telephone"> <div data-label="Intl: ">21342213</div> </div> <div class="inter" class="telephone"> <div data-label="Intl: "></div> </div> A: If you are using for example angular you could write <div id="inter" class="telephone" ng-if="contact_number_international != null"> <div id="inter-content">Intl: {{contact_number_international}}</div> </div> Other frameworks should have such functions too. (I assume u use something because of "{{}}") A: Fast forward a few years and CSS has a solution for this: .outer-content:has(.inner-content:empty) { display: none; } I was searching myself and none of the relevant answers were recently updated so I thought I'd write it down here. The browser support :has to be considered of course A: "Hide an empty container" questions are redirected here. So here's the simplest solution: .hide-if-empty:empty { display: none !important; } <div class="hide-if-empty"> <!-- if empty then hidden --> </div>
I would like to hide my outer div if inner div is empty
I have two div a child and a parent. the child contains a contact number. If there is no contact number I want the parent div to display none. I am trying to use the :empty CSS statement but I think I am using the wrong logic. #inter #inter-content:empty { display:none; } <div id="inter" class="telephone">Intl: <div id="inter-content">{{contact_number_international}}</div></div> I'm not sure if CSS is the right route either. I have tried using the bottom as well: #inter + #inter-content:empty { display:none; }
[ "You cant do this in the way you are approaching it due to how CSS works, and that you can only write selectors to isolate child/subsequent DOM nodes. :empty also works on selecting elements with no child nodes (elements or text).\n\nThe :empty pseudo-class represents any element that has no children at\n all. Only element nodes and text (including whitespace) are\n considered.\n\nAs such, you cannot select a parent element using CSS- and you cannot determine a node to be empty, if it contains another node (whether that node is empty or not).\nOne way to potentially get around this, is to apply the label in your code as a pseudo element, with its content conditionally sourced from a (data) attribute if the element is not empty. This will give the impression of the parent not displaying content if no number is present.\nThat said, if you actually dont want to display the parent at all- you will run into trouble using CSS alone. It looks like you are using angular (or similar), in which case you may want to use a logical check to toggle the parent's visibility.\n\n\n.inter div:not(:empty):before {\r\n display: block;\r\n content: attr(data-label);\r\n}\n<div class=\"inter\" class=\"telephone\">\r\n <div data-label=\"Intl: \">21342213</div>\r\n</div>\r\n\r\n<div class=\"inter\" class=\"telephone\">\r\n <div data-label=\"Intl: \"></div>\r\n</div>\n\n\n\n", "If you are using for example angular you could write\n<div id=\"inter\" class=\"telephone\" ng-if=\"contact_number_international != null\">\n <div id=\"inter-content\">Intl: {{contact_number_international}}</div>\n</div>\n\nOther frameworks should have such functions too. (I assume u use something because of \"{{}}\")\n", "Fast forward a few years and CSS has a solution for this:\n.outer-content:has(.inner-content:empty) { display: none; }\n\nI was searching myself and none of the relevant answers were recently updated so I thought I'd write it down here.\nThe browser support :has to be considered of course\n", "\"Hide an empty container\" questions are redirected here. So here's the simplest solution:\n.hide-if-empty:empty { display: none !important; }\n\n<div class=\"hide-if-empty\">\n <!-- if empty then hidden -->\n</div>\n\n" ]
[ 8, 1, 0, 0 ]
[]
[]
[ "css", "css_selectors", "html" ]
stackoverflow_0027938365_css_css_selectors_html.txt
Q: Create roll-on script using Database Project that does not require SqlCmd When using database projects, compare, and then Generate Script then the generated scripts is default for SqlCmd. E.g. it generates a row like: /* Detect SQLCMD mode and disable script execution if SQLCMD mode is not supported. To re-enable the script after enabling SQLCMD mode, execute the following: SET NOEXEC OFF; */ :setvar __IsSqlCmdEnabled "True" Is it possible to generate scripts in the Database Project that just generates the stuff that can be executed via SQL Server Management Studio? (I use Visual Studio 2022)
Create roll-on script using Database Project that does not require SqlCmd
When using database projects, compare, and then Generate Script then the generated scripts is default for SqlCmd. E.g. it generates a row like: /* Detect SQLCMD mode and disable script execution if SQLCMD mode is not supported. To re-enable the script after enabling SQLCMD mode, execute the following: SET NOEXEC OFF; */ :setvar __IsSqlCmdEnabled "True" Is it possible to generate scripts in the Database Project that just generates the stuff that can be executed via SQL Server Management Studio? (I use Visual Studio 2022)
[]
[]
[ "Yes, it is possible to generate scripts in a database project that can be executed via SQL Server Management Studio. To do this, you can use the Generate Scripts wizard in SQL Server Management Studio.\nTo access the wizard, right-click on the database project in Solution Explorer, then select \"Generate Scripts\" from the context menu. In the wizard, you can select the specific objects you want to generate scripts for, as well as configure options such as whether to include dependencies and whether to include data in the scripts.\nOnce you have selected the objects and configured the options, you can click \"Next\" to proceed to the summary page, where you can review the settings you have selected. If everything looks correct, you can click \"Finish\" to generate the scripts.\nThe generated scripts will be saved to the specified location and can be executed directly in SQL Server Management Studio without requiring SqlCmd.\n", "Yes, it is possible to generate scripts in a database project that can be executed directly in SQL Server Management Studio. By default, the scripts generated by a database project are designed to be run using the SQLCMD utility, which allows you to execute the scripts from the command line or from within a batch file.\nHowever, you can change the settings of the database project to generate scripts that can be run directly in SQL Server Management Studio. To do this, open the database project in Visual Studio and go to the project properties. In the \"Build\" tab, you will see a drop-down menu labeled \"Script Output Type\". Select \"Single file\" from this menu, which will generate a single script file that can be run directly in SQL Server Management Studio.\nAlternatively, you can also generate multiple script files by selecting the \"Multiple files\" option from the \"Script Output Type\" drop-down menu. This will generate a separate script file for each object in the database project, which you can then run individually in SQL Server Management Studio.\nIt's important to note that the scripts generated by a database project are not designed to be run directly in SQL Server Management Studio, and may not work as expected if you try to run them directly in this way. Instead, it is recommended to use the SQLCMD utility to run the scripts, or to modify the settings of the database project as described above to generate scripts that can be run directly in SQL Server Management Studio.\n" ]
[ -1, -1 ]
[ "database_project" ]
stackoverflow_0074544977_database_project.txt
Q: How to generate billing portal link for Stripe NextJS with Firebase extension? I'm using the Stripe extension in Firebase to create subscriptions in a NextJS web app. My goal is to create a link for a returning user to edit their payments in Stripe without authenticating again (they are already auth in my web app and Firebase recognizes the auth). I'm using the test mode of Stripe and I have a test customer and test products. I've tried The Firebase Stripe extension library does not have any function which can just return a billing portal link: https://github.com/stripe/stripe-firebase-extensions/blob/next/firestore-stripe-web-sdk/markdown/firestore-stripe-payments.md Use the NextJS recommended import of Stripe foudn in this Vercel blog First I setup the import for Stripe-JS: https://github.com/vercel/next.js/blob/758990dc06da4c2913f42fdfdacfe53e29e56593/examples/with-stripe-typescript/utils/get-stripejs.ts export default function Settings() { import stripe from "../../stripe_utils/get_stripejs" async function editDashboard() { const dashboardLink = await stripe.billingPortal.sessions.create({ customer: "cus_XXX", }) } console.log(dashboardLink.url) return ( <Button onClick={() => editDashboard()}> DEBUG: See payments </Button> ) } This would result in an error: TypeError: Cannot read properties of undefined (reading 'sessions') Use the stripe library. This seemed like the most promising solution but from what I read this is a backend library though I tried to use on the front end. There were no errors with this approach but I figure it hangs on the await import Stripe from "stripe" const stripe = new Stripe(process.env.STRIPE_SECRET) ... const session = await stripe.billingPortal.sessions.create({ customer: 'cus_XXX', return_url: 'https://example.com/account', }) console.log(session.url) // Does not reach here Use a pre-made Stripe link to redirect but the user will have to authenticate on Stripe using their email (this works but I would rather have a short-lived link from Stripe) <Button component={Link} to={"https://billing.stripe.com/p/login/XXX"}> Edit payment info on Stripe </Button> Using POST HTTPS API call found at https://stripe.com/docs/api/authentication. Unlike the previous options, this optional will register a Stripe Dashboard Log event. const response = await fetch("https://api.stripe.com/v1/billing_portal/sessions", { method: 'POST', // *GET, POST, PUT, DELETE, etc. mode: 'cors', // no-cors, *cors, same-origin cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', // include, *same-origin, omit headers: { 'Content-Type': 'application/json', 'Authorization': 'bearer sk_test_XXX', 'Content-Type': 'application/x-www-form-urlencoded', }, redirect: 'follow', // manual, *follow, error referrerPolicy: 'no-referrer', // no-referrer, *client body: JSON.stringify(data), // body data type must match "Content-Type" header }) The error is I'm missing some parameter parameter_missing -customer. So I'm closer to a resolution but I feel as if I should still be able to make the solution above work. A: You should use Stripe library to create a billing portal session (your 2nd approach), and you might want to check your Dashboard logs and set the endpoint to /v1/billing_portal/sessions so that you can see if there are any errors during portal session creation. A: Given my case, I chose to call the API itself instead of the libraries provided: export default async function Stripe(payload, stripeEndpoint) { const _ENDPOINTS = [ "/v1/billing_portal/sessions", "/v1/customers", ] let contentTypeHeader = "application/json" let body = JSON.stringify(payload) if _ENDPOINTS.includes(stripeEndpoint)) { contentTypeHeader = "application/x-www-form-urlencoded" body = Object.keys(payload).map( entry => entry + "=" + payload[entry]).join("&") } try { // Default options are marked with * const stripeResponse = await fetch("https://api.stripe.com" + stripeEndpoint, { method: "POST", // *GET, POST, PUT, DELETE, etc. headers: { "Authorization": "bearer " + STRIPE_PRIVATE_KEY, "Content-Type": contentTypeHeader, }, redirect: "follow", // manual, *follow, error referrerPolicy: "no-referrer", // no-referrer, *client body: body, // body data type must match "Content-Type" header }) return await stripeResponse.json() } catch (err) { console.error(err) } }
How to generate billing portal link for Stripe NextJS with Firebase extension?
I'm using the Stripe extension in Firebase to create subscriptions in a NextJS web app. My goal is to create a link for a returning user to edit their payments in Stripe without authenticating again (they are already auth in my web app and Firebase recognizes the auth). I'm using the test mode of Stripe and I have a test customer and test products. I've tried The Firebase Stripe extension library does not have any function which can just return a billing portal link: https://github.com/stripe/stripe-firebase-extensions/blob/next/firestore-stripe-web-sdk/markdown/firestore-stripe-payments.md Use the NextJS recommended import of Stripe foudn in this Vercel blog First I setup the import for Stripe-JS: https://github.com/vercel/next.js/blob/758990dc06da4c2913f42fdfdacfe53e29e56593/examples/with-stripe-typescript/utils/get-stripejs.ts export default function Settings() { import stripe from "../../stripe_utils/get_stripejs" async function editDashboard() { const dashboardLink = await stripe.billingPortal.sessions.create({ customer: "cus_XXX", }) } console.log(dashboardLink.url) return ( <Button onClick={() => editDashboard()}> DEBUG: See payments </Button> ) } This would result in an error: TypeError: Cannot read properties of undefined (reading 'sessions') Use the stripe library. This seemed like the most promising solution but from what I read this is a backend library though I tried to use on the front end. There were no errors with this approach but I figure it hangs on the await import Stripe from "stripe" const stripe = new Stripe(process.env.STRIPE_SECRET) ... const session = await stripe.billingPortal.sessions.create({ customer: 'cus_XXX', return_url: 'https://example.com/account', }) console.log(session.url) // Does not reach here Use a pre-made Stripe link to redirect but the user will have to authenticate on Stripe using their email (this works but I would rather have a short-lived link from Stripe) <Button component={Link} to={"https://billing.stripe.com/p/login/XXX"}> Edit payment info on Stripe </Button> Using POST HTTPS API call found at https://stripe.com/docs/api/authentication. Unlike the previous options, this optional will register a Stripe Dashboard Log event. const response = await fetch("https://api.stripe.com/v1/billing_portal/sessions", { method: 'POST', // *GET, POST, PUT, DELETE, etc. mode: 'cors', // no-cors, *cors, same-origin cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', // include, *same-origin, omit headers: { 'Content-Type': 'application/json', 'Authorization': 'bearer sk_test_XXX', 'Content-Type': 'application/x-www-form-urlencoded', }, redirect: 'follow', // manual, *follow, error referrerPolicy: 'no-referrer', // no-referrer, *client body: JSON.stringify(data), // body data type must match "Content-Type" header }) The error is I'm missing some parameter parameter_missing -customer. So I'm closer to a resolution but I feel as if I should still be able to make the solution above work.
[ "You should use Stripe library to create a billing portal session (your 2nd approach), and you might want to check your Dashboard logs and set the endpoint to /v1/billing_portal/sessions so that you can see if there are any errors during portal session creation.\n", "Given my case, I chose to call the API itself instead of the libraries provided:\nexport default async function Stripe(payload, stripeEndpoint) {\n const _ENDPOINTS = [\n \"/v1/billing_portal/sessions\",\n \"/v1/customers\",\n ]\nlet contentTypeHeader = \"application/json\"\n let body = JSON.stringify(payload)\n\n if _ENDPOINTS.includes(stripeEndpoint)) {\n contentTypeHeader = \"application/x-www-form-urlencoded\"\n body = Object.keys(payload).map(\n entry => entry + \"=\" + payload[entry]).join(\"&\")\n }\n\n try {\n // Default options are marked with *\n const stripeResponse = await fetch(\"https://api.stripe.com\" + stripeEndpoint, {\n method: \"POST\", // *GET, POST, PUT, DELETE, etc.\n headers: {\n \"Authorization\": \"bearer \" + STRIPE_PRIVATE_KEY,\n \"Content-Type\": contentTypeHeader,\n },\n redirect: \"follow\", // manual, *follow, error\n referrerPolicy: \"no-referrer\", // no-referrer, *client\n body: body, // body data type must match \"Content-Type\" header\n })\n return await stripeResponse.json()\n\n } catch (err) {\n console.error(err)\n }\n}\n\n" ]
[ 0, 0 ]
[]
[]
[ "firebase", "firebase_extensions", "next.js", "stripe_payments" ]
stackoverflow_0074579786_firebase_firebase_extensions_next.js_stripe_payments.txt
Q: How to add ServerCertificateCustomValidationCallback in a HttpClient Injection on NET6? How to add ServerCertificateCustomValidationCallback in a HttpClient Injection on NET6? I'm stuck on below program.cs: builder.Services.AddHttpClient<ITest, Test>(c => { c.BaseAddress = new Uri("https://iot.test.com/api"); c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); c.Timeout = TimeSpan.FromMinutes(20); }).ConfigureHttpClient((c) => { new HttpClientHandler() { ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => { return sslPolicyErrors == SslPolicyErrors.None; }; }; }); the VS2022 Community IDE keeps saying ServerCertificateCustomValidationCallback doesn't exist in the current context A: In order to initialize the ServerCertificateCustomValidationCallback callback like that you need to do some changes: Remove the round brackets after HttpClientHandler, so that you use an object initializer instead of a constructor call. Use = instead of += for assigning the callback handler. Remove the curly brackets around the construction of HttpClientHandler to directly return the newly created object instance without having a method body. (Or add the return keyword to return the object from the method body) Remove some of semicolons Code: builder.Services.AddHttpClient<ITest, Test>(c => { c.BaseAddress = new Uri("https://iot.test.com/api"); c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); c.Timeout = TimeSpan.FromMinutes(20); }).ConfigureHttpClient((c) => new HttpClientHandler { ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return sslPolicyErrors == SslPolicyErrors.None; } } );
How to add ServerCertificateCustomValidationCallback in a HttpClient Injection on NET6?
How to add ServerCertificateCustomValidationCallback in a HttpClient Injection on NET6? I'm stuck on below program.cs: builder.Services.AddHttpClient<ITest, Test>(c => { c.BaseAddress = new Uri("https://iot.test.com/api"); c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); c.Timeout = TimeSpan.FromMinutes(20); }).ConfigureHttpClient((c) => { new HttpClientHandler() { ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => { return sslPolicyErrors == SslPolicyErrors.None; }; }; }); the VS2022 Community IDE keeps saying ServerCertificateCustomValidationCallback doesn't exist in the current context
[ "In order to initialize the ServerCertificateCustomValidationCallback callback like that you need to do some changes:\n\nRemove the round brackets after HttpClientHandler, so that you use an object initializer instead of a constructor call.\nUse = instead of += for assigning the callback handler.\nRemove the curly brackets around the construction of HttpClientHandler to directly return the newly created object instance without having a method body. (Or add the return keyword to return the object from the method body)\nRemove some of semicolons\n\nCode:\nbuilder.Services.AddHttpClient<ITest, Test>(c =>\n {\n c.BaseAddress = new Uri(\"https://iot.test.com/api\");\n c.DefaultRequestHeaders.Accept.Add(new \n MediaTypeWithQualityHeaderValue(\"application/json\"));\n c.Timeout = TimeSpan.FromMinutes(20);\n }).ConfigureHttpClient((c) =>\n new HttpClientHandler\n {\n ServerCertificateCustomValidationCallback = (sender, cert, chain, \n sslPolicyErrors) =>\n {\n return sslPolicyErrors == SslPolicyErrors.None;\n }\n }\n );\n\n" ]
[ 0 ]
[]
[]
[ ".net_6.0", "asp.net_mvc" ]
stackoverflow_0074672714_.net_6.0_asp.net_mvc.txt
Q: How to set "Total" in footer at Yajra dataTable to get "total" of one or multiple columns in every page or at lest at the end There is a problem at Yajra DataTable to showing sum of some column data. How can I resolve this for Yajra? (I want actual view of total- like marked position) A: the process is bit long, first you need to add footer to your table, then after the column array objects add "footerCallback" key with callback function, then convert the column you want to sum into integer. see example enter link description here
How to set "Total" in footer at Yajra dataTable to get "total" of one or multiple columns in every page or at lest at the end
There is a problem at Yajra DataTable to showing sum of some column data. How can I resolve this for Yajra? (I want actual view of total- like marked position)
[ "the process is bit long, first you need to add footer to your table, then after the column array objects add \"footerCallback\" key with callback function, then convert the column you want to sum into integer. see example \nenter link description here\n" ]
[ 0 ]
[ "You are looking for Datatables' drawCallback() function - this will run after each time the table is drawn (on page load, and after it is filtered down) and will perform a specific action.\nIn this instance you would want to sum the relevant column using something along these lines :\nvar sum = $('#yourTable').DataTable().column(4).data().sum();\n\nand then just use jQuery to write the value to the relevant span or div as you would normally :\n$('#yourTotalBox').html(sum);\n\n" ]
[ -1 ]
[ "laravel", "yajra_datatable" ]
stackoverflow_0070180177_laravel_yajra_datatable.txt
Q: How to load a JS library in Blazor server razor file? I'm trying to follow the document HERE to load THIS bootstrap-datepicker within a blazor server app. Note: I want to load it for a single page only without having to load it for all pages. Within the .razor file I'm trying to do this: HTML <input @ref=ReferenceToInputControl class="form-control" id="obdInput"> Code @code { ElementReference ReferenceToInputControl; private IJSObjectReference? jsModule; protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { jsModule = await JS.InvokeAsync<IJSObjectReference>("import", "./js/bootstrap-datepicker.js"); await jsModule.InvokeVoidAsync("Datepicker", ReferenceToInputControl); } } } I get an error that "Could not find Datepicker. Datepicker was undefined". I've read so much information about IIFE and scope and closure and modules but I can't for the life of me figure out what I need to do with that function so it will load and I can use it to change the input into a calendar. A: That library isn't using ES Modules, so import won't work. The way it's distributed, it's designed to be loaded in a script tag: <script type="text/javascript" src="js/bootstrap-datepicker.min.js"></script> You'll also need the CSS from the same repo, as well as jQuery and Bootstrap. However it's worth noting that that library is fairly old, does not have Bootstrap 5 support, and will need some adjustments to use with Bootstrap 3 or 4 see here.
How to load a JS library in Blazor server razor file?
I'm trying to follow the document HERE to load THIS bootstrap-datepicker within a blazor server app. Note: I want to load it for a single page only without having to load it for all pages. Within the .razor file I'm trying to do this: HTML <input @ref=ReferenceToInputControl class="form-control" id="obdInput"> Code @code { ElementReference ReferenceToInputControl; private IJSObjectReference? jsModule; protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { jsModule = await JS.InvokeAsync<IJSObjectReference>("import", "./js/bootstrap-datepicker.js"); await jsModule.InvokeVoidAsync("Datepicker", ReferenceToInputControl); } } } I get an error that "Could not find Datepicker. Datepicker was undefined". I've read so much information about IIFE and scope and closure and modules but I can't for the life of me figure out what I need to do with that function so it will load and I can use it to change the input into a calendar.
[ "That library isn't using ES Modules, so import won't work. The way it's distributed, it's designed to be loaded in a script tag:\n<script type=\"text/javascript\" src=\"js/bootstrap-datepicker.min.js\"></script>\n\nYou'll also need the CSS from the same repo, as well as jQuery and Bootstrap.\nHowever it's worth noting that that library is fairly old, does not have Bootstrap 5 support, and will need some adjustments to use with Bootstrap 3 or 4 see here.\n" ]
[ 1 ]
[]
[]
[ "blazor", "blazor_server_side", "c#", "iife", "javascript" ]
stackoverflow_0074672696_blazor_blazor_server_side_c#_iife_javascript.txt
Q: NextRouter was not mounted Next.JS Using import { useRouter } from "next/router"; as import { useRouter } from "next/navigation"; throws "Argument of type '{ pathname: string; query: { search: string; }; }' is not assignable to parameter of type 'string'." const router = useRouter(); const [searchInput, setSearchInput] = useState(""); const search = (e) => { router.push({ pathname: '/search', query: { search: searchInput, }, }) } NextJS documentation Froms docs: "A component used useRouter outside a Next.js application, or was rendered outside a Next.js application. This can happen when doing unit testing on components that use the useRouter hook as they are not configured with Next.js' contexts." A: Migrating from the pages directory: The new useRouter hook should be imported from next/navigation and not next/router The pathname string has been removed and is replaced by usePathname() The query object has been removed and is replaced by useSearchParams() router.events is not currently supported. Here is the solution: https://beta.nextjs.org/docs/api-reference/use-router A: const router = useRouter(); const search = (e) => { const searchParams = { pathname: '/search', query: { search: e.target.value, }, } as any router.push(searchParams) } A: Now Nextjs CLI install by default Next@13. If you started with Nextjs@12 and recently reinstalled the packages after, you must remove Next to install a version lower than 13. I don't know why but for me it's what worked. npm uninstall next npm install [email protected] Note: Just be sure next version is under 13 A: import { useRouter } from "next/router"; This Router class push method push(url: Url, as?: Url, options?: TransitionOptions): Promise<boolean>; where type Url = string | UrlObject and interface UrlObject { auth?: string | null | undefined; hash?: string | null | undefined; host?: string | null | undefined; hostname?: string | null | undefined; href?: string | null | undefined; pathname?: string | null | undefined; protocol?: string | null | undefined; search?: string | null | undefined; slashes?: boolean | null | undefined; port?: string | number | null | undefined; query?: string | null | ParsedUrlQueryInput | undefined; } this is TransitionOptions: interface TransitionOptions { shallow?: boolean; locale?: string | false; scroll?: boolean; unstable_skipClientCache?: boolean; } You can use it like this: const router = useRouter(); const click = () => { router.push({ pathname: "/test", search: "?name=something", }); }; <button onClick={click}>click me</button> 'use client'; import { useRouter } from 'next/navigation'; this is its push type push(href: string, options?: NavigateOptions): void; interface NavigateOptions { forceOptimisticNavigation?: boolean; } from docs The new router has an in-memory client-side cache that stores the rendered result of Server Components (payload). The cache is split by route segments which allows invalidation at any level and ensures consistency across concurrent renders. As users navigate around the app, the router will store the payload of previously fetched segments and prefetched segments in the cache. This means, for certain cases, the router can re-use the cache instead of making a new request to the server. This improves performance by avoiding re-fetching data and re-rendering components unnecessarily.
NextRouter was not mounted Next.JS
Using import { useRouter } from "next/router"; as import { useRouter } from "next/navigation"; throws "Argument of type '{ pathname: string; query: { search: string; }; }' is not assignable to parameter of type 'string'." const router = useRouter(); const [searchInput, setSearchInput] = useState(""); const search = (e) => { router.push({ pathname: '/search', query: { search: searchInput, }, }) } NextJS documentation Froms docs: "A component used useRouter outside a Next.js application, or was rendered outside a Next.js application. This can happen when doing unit testing on components that use the useRouter hook as they are not configured with Next.js' contexts."
[ "Migrating from the pages directory:\n\nThe new useRouter hook should be imported from next/navigation and not next/router\nThe pathname string has been removed and is replaced by usePathname()\nThe query object has been removed and is replaced by useSearchParams()\nrouter.events is not currently supported.\n\nHere is the solution: https://beta.nextjs.org/docs/api-reference/use-router\n", "const router = useRouter();\n\nconst search = (e) => {\n const searchParams = {\n pathname: '/search',\n query: {\n search: e.target.value,\n },\n } as any\n router.push(searchParams)\n}\n\n", "Now Nextjs CLI install by default Next@13. If you started with Nextjs@12 and recently reinstalled the packages after, you must remove Next to install a version lower than 13. I don't know why but for me it's what worked.\nnpm uninstall next\n\nnpm install [email protected]\n\nNote: Just be sure next version is under 13\n", "import { useRouter } from \"next/router\";\n\nThis Router class push method\npush(url: Url, as?: Url, options?: TransitionOptions): Promise<boolean>;\n\nwhere\n type Url = string | UrlObject\n\nand\ninterface UrlObject {\n auth?: string | null | undefined;\n hash?: string | null | undefined;\n host?: string | null | undefined;\n hostname?: string | null | undefined;\n href?: string | null | undefined;\n pathname?: string | null | undefined;\n protocol?: string | null | undefined;\n search?: string | null | undefined;\n slashes?: boolean | null | undefined;\n port?: string | number | null | undefined;\n query?: string | null | ParsedUrlQueryInput | undefined;\n }\n\nthis is TransitionOptions:\ninterface TransitionOptions {\n shallow?: boolean;\n locale?: string | false;\n scroll?: boolean;\n unstable_skipClientCache?: boolean;\n}\n\nYou can use it like this:\n const router = useRouter();\n const click = () => {\n router.push({\n pathname: \"/test\",\n search: \"?name=something\",\n });\n };\n\n <button onClick={click}>click me</button>\n\n\n'use client';\nimport { useRouter } from 'next/navigation';\n\n\nthis is its push type\npush(href: string, options?: NavigateOptions): void;\n\ninterface NavigateOptions {\n forceOptimisticNavigation?: boolean;\n}\n\nfrom docs\n\nThe new router has an in-memory client-side cache that stores the\nrendered result of Server Components (payload). The cache is split by\nroute segments which allows invalidation at any level and ensures\nconsistency across concurrent renders.\nAs users navigate around the app, the router will store the payload of\npreviously fetched segments and prefetched segments in the cache.\nThis means, for certain cases, the router can re-use the cache instead\nof making a new request to the server. This improves performance by\navoiding re-fetching data and re-rendering components unnecessarily.\n\n" ]
[ 15, 0, 0, 0 ]
[]
[]
[ "next.js", "next_router", "typescript" ]
stackoverflow_0074421327_next.js_next_router_typescript.txt
Q: GraphQL Union and Input Type? Is it possible in GraphQL to have an input type that is also a union? Something like: const DynamicInputValueType = new GraphQLUnionType({ name: 'DynamicInputType', types: [GraphQLString, GraphQLFloat, GraphQLInt] }) but also able to be used as a input for a mutation? A: As of September 2017, this is not possible. There is an ongoing discussion around this functionality. A: There is a npm module. I haven't tested. https://www.npmjs.com/package/graphql-union-input-type A: As Artur mentioned, support for union input types is ongoing. Since his post, Tagged Types were proposed as a replacement, which in turn was superseded by the @oneOf directive proposal. If you need to do this today, an alternative could be to have an input like this: input AInput { a: String! } input BInput { b: String! } input DynamicInputType { # 'a' or 'b' โ€”ย you could make a scalar instead if you'd like type: String! # Exactly one of these should be set a: AInput b: BInput } The idea here is that you define one field on this input, and then set type to indicate which field is set. Your resolver would probably need to validate that only the property specified by type is defined. A: The solution Salem suggested does work and I do use it though its not ideal because in a bunch of situations it means you need to transform the type from the query to the input type (which I think is fine to do, just annoying). This is usually the case with nested types. If you find that is the case I would recommend restructuring your type so that List { ListItem: ListItemVariants[] } Becomes ListItem { ListItemVariant1: ListItemVariant1[], ListItemVariant2: ListItemVariant2[] } You will likely need to stick an order property on the variants where it is an array but it means you can mutate the item without transforming the type returned by the query so much as
GraphQL Union and Input Type?
Is it possible in GraphQL to have an input type that is also a union? Something like: const DynamicInputValueType = new GraphQLUnionType({ name: 'DynamicInputType', types: [GraphQLString, GraphQLFloat, GraphQLInt] }) but also able to be used as a input for a mutation?
[ "As of September 2017, this is not possible. There is an ongoing discussion around this functionality.\n", "There is a npm module. I haven't tested. https://www.npmjs.com/package/graphql-union-input-type\n", "As Artur mentioned, support for union input types is ongoing. Since his post, Tagged Types were proposed as a replacement, which in turn was superseded by the @oneOf directive proposal.\nIf you need to do this today, an alternative could be to have an input like this:\ninput AInput {\n a: String!\n}\n\ninput BInput {\n b: String!\n}\n\ninput DynamicInputType {\n # 'a' or 'b' โ€”ย you could make a scalar instead if you'd like \n type: String! \n \n # Exactly one of these should be set\n a: AInput\n b: BInput\n}\n\nThe idea here is that you define one field on this input, and then set type to indicate which field is set. Your resolver would probably need to validate that only the property specified by type is defined.\n", "The solution Salem suggested does work and I do use it though its not ideal because in a bunch of situations it means you need to transform the type from the query to the input type (which I think is fine to do, just annoying). This is usually the case with nested types.\nIf you find that is the case I would recommend restructuring your type so that\nList {\n ListItem: ListItemVariants[]\n}\n\n\nBecomes\nListItem {\n ListItemVariant1: ListItemVariant1[],\n ListItemVariant2: ListItemVariant2[]\n}\n\nYou will likely need to stick an order property on the variants where it is an array but it means you can mutate the item without transforming the type returned by the query so much as\n" ]
[ 20, 0, 0, 0 ]
[]
[]
[ "graphql", "graphql_js" ]
stackoverflow_0045288955_graphql_graphql_js.txt
Q: How to take max value from one column for each value in second column in table with many other columns in SAS Enterprise Guide? I have table in SAS Enterprise Guide like below: COL1 - date COL2 - numeric COL1 | COL2 | COL3 | COL4 | COL5 --------- |-------|-------|------|------- 01APR2021 | 11 | XXX | XXX | XXX 01MAY2021 | 5 | XXX | XXX | XXX 01MAY2021 | 25 | XXX | XXX | XXX 01JUN2021 | 10 | XXX | XXX | XXX ... | ... | ... | ... | ... And I need to for each dates in COL1 select max value in COL2. Moroever, in output I need to have also rest of my columns: COL3, COL4, COL5 So as a result I need somethin like below, because for date 01MAY2021 in COL1, in COL2 are two values and 25>5. COL1 | COL2 | COL3 | COL4 | COL5 --------- |-------|-------|------|------- 01APR2021 | 11 | XXX | XXX | XXX 01MAY2021 | 25 | XXX | XXX | XXX 01JUN2021 | 10 | XXX | XXX | XXX ... | ... | ... | ... | ... How can I do that in SAS Enterprise Guide ? A: You will need a GROUP BY COL1 clause in order to compute MAX(COL2) within the group, and also a HAVING clause to select the rows with the aggregate computation. Note, there might be two rows with the same max, and thus you will get both in your result set. Example: create table want_table as select * from have_table group by COL1 having COL2 = max(COL2) ;
How to take max value from one column for each value in second column in table with many other columns in SAS Enterprise Guide?
I have table in SAS Enterprise Guide like below: COL1 - date COL2 - numeric COL1 | COL2 | COL3 | COL4 | COL5 --------- |-------|-------|------|------- 01APR2021 | 11 | XXX | XXX | XXX 01MAY2021 | 5 | XXX | XXX | XXX 01MAY2021 | 25 | XXX | XXX | XXX 01JUN2021 | 10 | XXX | XXX | XXX ... | ... | ... | ... | ... And I need to for each dates in COL1 select max value in COL2. Moroever, in output I need to have also rest of my columns: COL3, COL4, COL5 So as a result I need somethin like below, because for date 01MAY2021 in COL1, in COL2 are two values and 25>5. COL1 | COL2 | COL3 | COL4 | COL5 --------- |-------|-------|------|------- 01APR2021 | 11 | XXX | XXX | XXX 01MAY2021 | 25 | XXX | XXX | XXX 01JUN2021 | 10 | XXX | XXX | XXX ... | ... | ... | ... | ... How can I do that in SAS Enterprise Guide ?
[ "You will need a GROUP BY COL1 clause in order to compute MAX(COL2) within the group, and also a HAVING clause to select the rows with the aggregate computation. Note, there might be two rows with the same max, and thus you will get both in your result set.\nExample:\n create table want_table as\n select * from have_table\n group by COL1\n having COL2 = max(COL2)\n ;\n\n" ]
[ 0 ]
[]
[]
[ "4gl", "enterprise_guide", "group_by", "max", "sas" ]
stackoverflow_0074672559_4gl_enterprise_guide_group_by_max_sas.txt
Q: How to apply multiple filters to an image using different range inputs with jquery? I am making sort of a photo editor where you can change basic filters (opacity, saturation, brightness, hue, grayscale, and blur) of the picture using range input sliders. I got it to work where moving the input slider accurately changes the intended filter, but when I try moving more than one slider it resets the previous selection and only one filter can be active at a time. How can I rebuild this so that each filter can be active at the same time? Here is the JS for the listeners for the input sliders: $('#sliderOpacity').on('input', function() { $('#imgManipulated img').css({filter: 'opacity('+$(this).val()+'%)'}); $('#numOpacity').text($(this).val()); }); $('#sliderSaturation').on('input', function() { $('#imgManipulated img').css({filter: 'saturate('+$(this).val()+'%)'}); $('#numSaturation').text($(this).val()); }); $('#sliderBrightness').on('input', function() { $('#imgManipulated img').css({filter: 'brightness('+$(this).val() + '%)'}); $('#numBrightness').text($(this).val()); }); $('#sliderHue').on('input', function() { $('#imgManipulated img').css({filter: 'hue-rotate('+$(this).val() + 'deg)'}); $('#numHue').text($(this).val()); }); $('#sliderGray').on('input', function() { $('#imgManipulated img').css({filter: 'grayscale('+$(this).val() + '%)'}); $('#numGray').text($(this).val()); }); $('#sliderBlur').on('input', function() { $('#imgManipulated img').css({filter: 'blur('+$(this).val() + 'px)'}); $('#numBlur').text($(this).val()); }); Here is the html for the form and image if needed: <div id="sliderBox"> <form> <label>Opacity: </label><p><input type="range" id="sliderOpacity" min="0" max="100" value="100" class="sliders" /> <span id="numOpacity">100</span>%</p> <p><label>Saturation: </label><input type="range" id="sliderSaturation" min="1" max="300" value="100" class="sliders"/> <span id="numSaturation">100</span>%</p> <p><label>Brightness: </label><input type="range" id="sliderBrightness" min="0" max="300" value="100" class="sliders" /> <span id="numBrightness">100</span>%</p> <p><label>Hue Rotate: </label><input type="range" id="sliderHue" min="0" max="360" value="0" class="sliders" /> <span id="numHue">0</span>deg</p> <p><label>Grayscale: </label><input type="range" id="sliderGray" min="0" max="100" value="0" class="sliders"/> <span id="numGray">0</span>%</p> <p><label>Blur: </label><input type="range" id="sliderBlur" min="0" max="10" value="0" class="sliders" /> <span id="numBlur">0</span>px</p> <p><button id="resetFilters">Reset</button> </p> </form> </div> <figure id="imgManipulated"> <img src="images/medium/painting1.jpg" > <figcaption> <em>Still Life with Flowers in a Glass Vase</em> <br> Jan Davidsz. de Heem, 1650 - 1683 </figcaption> </figure> Basically I just need to know how to get the JS to work so it applies as many of those filters I change at the same time. A: Here is a possible solution to your problem: Instead of applying the filter styles directly to the image using the css() method, you can keep track of the current value of each filter and then combine them into a single filter string when you update the image. This way, all the filters will be applied to the image at the same time. Here is an example of how you can implement this: // Create an object to store the current filter values const filterValues = { opacity: 100, saturation: 100, brightness: 100, hue: 0, grayscale: 0, blur: 0 }; // Function to update the image with the current filter values function updateImage() { // Create the filter string by combining the filter values const filterString = `opacity(${filterValues.opacity}%) saturate(${filterValues.saturation}%) brightness(${filterValues.brightness}%) hue-rotate(${filterValues.hue}deg) grayscale(${filterValues.grayscale}%) blur(${filterValues.blur}px)`; // Apply the filter string to the image $('#imgManipulated img').css({ filter: filterString }); } // Listeners for the input sliders $('#sliderOpacity').on('input', function() { // Update the filter value and the text next to the slider filterValues.opacity = $(this).val(); $('#numOpacity').text($(this).val()); // Update the image updateImage(); }); $('#sliderSaturation').on('input', function() { // Update the filter value and the text next to the slider filterValues.saturation = $(this).val(); $('#numSaturation').text($(this).val()); // Update the image updateImage(); }); $('#sliderBrightness').on('input', function() { // Update the filter value and the text next to the slider filterValues.brightness = $(this).val(); $('#numBrightness').text($(this).val()); // Update the image updateImage(); }); $('#sliderHue').on('input', function() { // Update the filter value and the text next to the slider filterValues.hue = $(this).val(); $('#numHue').text($(this).val()); // Update the image updateImage(); }); $('#sliderGray').on('input', function() { // Update the filter value and the text next to the slider filterValues.grayscale = $(this).val(); $('#numGray').text($(this).val()); // Update the image updateImage(); }); $('#sliderBlur').on('input', function() { // Update the filter value and the text next to the slider filterValues.blur = $(this).val(); $('#numBlur').text($(this).val()); // Update the image updateImage(); }); In this example, the filterValues object is used to store the current value of each filter. The updateImage() function is called whenever the value of a filter changes, and it combines the current filter values into a single filter string and applies it to the image using the css() method. In the event listeners for the input sliders, you can see that the current value of the filter is updated in the filterValues object and the text next to the slider is updated using the val() method. Then, the updateImage() function is called to apply the new filter values to the image. I hope this helps! Let me know if you have any other questions.
How to apply multiple filters to an image using different range inputs with jquery?
I am making sort of a photo editor where you can change basic filters (opacity, saturation, brightness, hue, grayscale, and blur) of the picture using range input sliders. I got it to work where moving the input slider accurately changes the intended filter, but when I try moving more than one slider it resets the previous selection and only one filter can be active at a time. How can I rebuild this so that each filter can be active at the same time? Here is the JS for the listeners for the input sliders: $('#sliderOpacity').on('input', function() { $('#imgManipulated img').css({filter: 'opacity('+$(this).val()+'%)'}); $('#numOpacity').text($(this).val()); }); $('#sliderSaturation').on('input', function() { $('#imgManipulated img').css({filter: 'saturate('+$(this).val()+'%)'}); $('#numSaturation').text($(this).val()); }); $('#sliderBrightness').on('input', function() { $('#imgManipulated img').css({filter: 'brightness('+$(this).val() + '%)'}); $('#numBrightness').text($(this).val()); }); $('#sliderHue').on('input', function() { $('#imgManipulated img').css({filter: 'hue-rotate('+$(this).val() + 'deg)'}); $('#numHue').text($(this).val()); }); $('#sliderGray').on('input', function() { $('#imgManipulated img').css({filter: 'grayscale('+$(this).val() + '%)'}); $('#numGray').text($(this).val()); }); $('#sliderBlur').on('input', function() { $('#imgManipulated img').css({filter: 'blur('+$(this).val() + 'px)'}); $('#numBlur').text($(this).val()); }); Here is the html for the form and image if needed: <div id="sliderBox"> <form> <label>Opacity: </label><p><input type="range" id="sliderOpacity" min="0" max="100" value="100" class="sliders" /> <span id="numOpacity">100</span>%</p> <p><label>Saturation: </label><input type="range" id="sliderSaturation" min="1" max="300" value="100" class="sliders"/> <span id="numSaturation">100</span>%</p> <p><label>Brightness: </label><input type="range" id="sliderBrightness" min="0" max="300" value="100" class="sliders" /> <span id="numBrightness">100</span>%</p> <p><label>Hue Rotate: </label><input type="range" id="sliderHue" min="0" max="360" value="0" class="sliders" /> <span id="numHue">0</span>deg</p> <p><label>Grayscale: </label><input type="range" id="sliderGray" min="0" max="100" value="0" class="sliders"/> <span id="numGray">0</span>%</p> <p><label>Blur: </label><input type="range" id="sliderBlur" min="0" max="10" value="0" class="sliders" /> <span id="numBlur">0</span>px</p> <p><button id="resetFilters">Reset</button> </p> </form> </div> <figure id="imgManipulated"> <img src="images/medium/painting1.jpg" > <figcaption> <em>Still Life with Flowers in a Glass Vase</em> <br> Jan Davidsz. de Heem, 1650 - 1683 </figcaption> </figure> Basically I just need to know how to get the JS to work so it applies as many of those filters I change at the same time.
[ "Here is a possible solution to your problem:\nInstead of applying the filter styles directly to the image using the css() method, you can keep track of the current value of each filter and then combine them into a single filter string when you update the image. This way, all the filters will be applied to the image at the same time.\nHere is an example of how you can implement this:\n// Create an object to store the current filter values\nconst filterValues = {\n opacity: 100,\n saturation: 100,\n brightness: 100,\n hue: 0,\n grayscale: 0,\n blur: 0\n};\n\n// Function to update the image with the current filter values\nfunction updateImage() {\n // Create the filter string by combining the filter values\n const filterString = `opacity(${filterValues.opacity}%) saturate(${filterValues.saturation}%) brightness(${filterValues.brightness}%) hue-rotate(${filterValues.hue}deg) grayscale(${filterValues.grayscale}%) blur(${filterValues.blur}px)`;\n\n // Apply the filter string to the image\n $('#imgManipulated img').css({ filter: filterString });\n}\n\n// Listeners for the input sliders\n$('#sliderOpacity').on('input', function() {\n // Update the filter value and the text next to the slider\n filterValues.opacity = $(this).val();\n $('#numOpacity').text($(this).val());\n\n // Update the image\n updateImage();\n});\n\n$('#sliderSaturation').on('input', function() {\n // Update the filter value and the text next to the slider\n filterValues.saturation = $(this).val();\n $('#numSaturation').text($(this).val());\n\n // Update the image\n updateImage();\n});\n\n$('#sliderBrightness').on('input', function() {\n // Update the filter value and the text next to the slider\n filterValues.brightness = $(this).val();\n $('#numBrightness').text($(this).val());\n\n // Update the image\n updateImage();\n});\n\n$('#sliderHue').on('input', function() {\n // Update the filter value and the text next to the slider\n filterValues.hue = $(this).val();\n $('#numHue').text($(this).val());\n\n // Update the image\n updateImage();\n});\n\n$('#sliderGray').on('input', function() {\n // Update the filter value and the text next to the slider\n filterValues.grayscale = $(this).val();\n $('#numGray').text($(this).val());\n\n // Update the image\n updateImage();\n});\n\n$('#sliderBlur').on('input', function() {\n // Update the filter value and the text next to the slider\n filterValues.blur = $(this).val();\n $('#numBlur').text($(this).val());\n\n // Update the image\n updateImage();\n});\n\nIn this example, the filterValues object is used to store the current value of each filter. The updateImage() function is called whenever the value of a filter changes, and it combines the current filter values into a single filter string and applies it to the image using the css() method.\nIn the event listeners for the input sliders, you can see that the current value of the filter is updated in the filterValues object and the text next to the slider is updated using the val() method. Then, the updateImage() function is called to apply the new filter values to the image.\nI hope this helps! Let me know if you have any other questions.\n" ]
[ 0 ]
[]
[]
[ "css", "forms", "input", "jquery", "webkit" ]
stackoverflow_0074672742_css_forms_input_jquery_webkit.txt
Q: Text hyperlink hashtags(#) and mentions(@) in Jetpack Compose? Text hyperlink hashtags(#) and mentions(@) in Jetpack Compose? @Composable fun HashtagsAndMentions() { val colorScheme = MaterialTheme.colorScheme val primaryStyle = SpanStyle(color = colorScheme.primary) val textStyle = SpanStyle(color = colorScheme.onBackground) val annotatedString = buildAnnotatedString { withStyle(style = textStyle) { append("I am ") } pushStringAnnotation(tag = "hashtags", annotation = "hashtags") withStyle(style = primaryStyle) { append(text = "#hashtags") } pop() withStyle(style = textStyle) { append(" and ") } pushStringAnnotation(tag = "mentions", annotation = "mentions") withStyle(style = primaryStyle) { append(text = "@mentions") } pop() withStyle(style = textStyle) { append(" in Jetpack Compose.") } } ClickableText( onClick = { annotatedString.getStringAnnotations("hashtags", it, it).firstOrNull()?.let { } annotatedString.getStringAnnotations("mentions", it, it).firstOrNull()?.let { } }, text = annotatedString, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(16.dp)) } @Preview @Composable fun PreviewTest() { HashtagsAndMentions() } The above are fixed tags, how to dynamically identify and link? ideas String to array val string = "I am #hashtags and @mentions in Jetpack Compose." val array = arrayOf("I am ", "#hashtags", " and ", "@mentions", "in Jetpack Compose.") A: To dynamically identify and link hashtags and mentions in a string using Jetpack Compose, you can use the Regex class to match the hashtags and mentions in the string, and then use the buildAnnotatedString function to apply styles and click handlers to the matched text. Here is an example of how you can do this: @Composable fun HashtagsAndMentions(text: String) { val colorScheme = MaterialTheme.colorScheme val primaryStyle = SpanStyle(color = colorScheme.primary) val textStyle = SpanStyle(color = colorScheme.onBackground) val hashtags = Regex("(#[a-zA-Z0-9]+)") val mentions = Regex("(@[a-zA-Z0-9]+)") // Create a list of text spans with styles and click handlers val spans = mutableListOf<AnnotatedString.Range<SpanStyle>>() var lastIndex = 0 // Add text spans for hashtags for (match in hashtags.findAll(text)) { val start = match.range.first val end = match.range.last + 1 val text = text.substring(start, end) if (start > lastIndex) { spans += AnnotatedString.Range( text = text.substring(lastIndex, start), style = textStyle ) } spans += AnnotatedString.Range( text = text, style = primaryStyle, onClick = { // Handle hashtag click } ) lastIndex = end } // Add text spans for mentions for (match in mentions.findAll(text)) { val start = match.range.first val end = match.range.last + 1 val text = text.substring(start, end) if (start > lastIndex) { spans += AnnotatedString.Range( text = text.substring(lastIndex, start), style = textStyle ) } spans += AnnotatedString.Range( text = text, style = primaryStyle, onClick = { // Handle mention click } ) lastIndex = end } // Add remaining text if (lastIndex < text.length) { spans += AnnotatedString.Range( text = text.substring(lastIndex, text.length), style = textStyle ) } // Build the annotated string val annotatedString = buildAnnotatedString { for (span in spans) { pushStyle(span.style) append(span.text) pop() } } // Use the annotated string in a ClickableText component ClickableText( onClick = { // Handle text click }, text = annotatedString, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(16.dp) ) } In this example, the `HashtagsAndMentions A: To dynamically identify hashtags and mentions in a string, you can use regular expressions to match hashtags and mentions in the string. Regular expressions are a powerful way to search for patterns in text. Here is an example of how you could use regular expressions to identify hashtags and mentions in a string: val string = "I am #hashtags and @mentions in Jetpack Compose." val hashtagsRegex = Regex("#\\w+") val mentionsRegex = Regex("@\\w+") val hashtags = hashtagsRegex.findAll(string).map { it.value } val mentions = mentionsRegex.findAll(string).map { it.value } println("Hashtags: $hashtags") println("Mentions: $mentions") The hashtagsRegex variable uses the # character followed by one or more word characters (letters, digits, and underscores) to match hashtags in the string. The mentionsRegex variable uses the @ character followed by one or more word characters to match mentions in the string. The findAll() method is used to search the string for all occurrences of the regular expression and return a sequence of MatchResult objects. The map() method is used to transform the sequence of MatchResult objects into a sequence of strings, which are the actual hashtags and mentions found in the string. Finally, the println() statements print the hashtags and mentions that were found in the string. You can then use the hashtags and mentions variables to link to the corresponding content in your Jetpack Compose UI. Hope this helps! Let me know if you have any other questions. A: Here is an available hashtag and mention link. Many thanks to @cyberpunk_unicorn for the idea, unfortunately his answer is not available, but I marked it anyway. I refactored his code to ensure that it is runnable, concise enough, and very helpful to those who need it later. @Composable fun HashtagsMentionsTextView(text: String) { val colorScheme = MaterialTheme.colorScheme val textStyle = SpanStyle(color = colorScheme.onBackground) val primaryStyle = SpanStyle(color = colorScheme.primary) val hashtags = Regex("(#[a-zA-Z0-9]+)") val mentions = Regex("(@[a-zA-Z0-9]+)") val annotatedStringList = remember { val annotatedStringList = mutableStateListOf<AnnotatedString>() var lastIndex = 0 // Add a text range for hashtags for (match in hashtags.findAll(text)) { val start = match.range.first val end = match.range.last + 1 val string = text.substring(start, end) if (start > lastIndex) { annotatedStringList.add( AnnotatedString( text = text.substring(lastIndex, start), spanStyle = textStyle ) ) } annotatedStringList.add(AnnotatedString(text = string, spanStyle = primaryStyle)) lastIndex = end } // Add text spans for mentions for (match in mentions.findAll(text)) { val start = match.range.first val end = match.range.last + 1 val string = text.substring(start, end) if (start > lastIndex) { annotatedStringList.add( AnnotatedString( text = text.substring(lastIndex, start), spanStyle = textStyle ) ) } annotatedStringList.add(AnnotatedString(text = string, spanStyle = primaryStyle)) lastIndex = end } // Add remaining text if (lastIndex < text.length) { annotatedStringList.add( AnnotatedString( text = text.substring(lastIndex, text.length), spanStyle = textStyle ) ) } annotatedStringList } // Build an annotated string val annotatedString = buildAnnotatedString { annotatedStringList.forEach { val spanStyle = it.spanStyles.first().item if (spanStyle == textStyle) { withStyle(it.spanStyles.first().item) { append(it.text) } } else { pushStringAnnotation(tag = it.text, annotation = it.text) withStyle(style = spanStyle) { append(it.text) } pop() } } } val onClick: (Int) -> Unit = { position -> annotatedStringList.forEach { annotatedString.getStringAnnotations(it.text, position, position).firstOrNull()?.let { println(it.item) } } } ClickableText( text = annotatedString, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(16.dp), onClick = onClick ) } @Preview @Composable fun PreviewTest() { val string = "I am #hashtags or #hashtags# and @mentions in Jetpack Compose." HashtagsMentionsTextView(string) }
Text hyperlink hashtags(#) and mentions(@) in Jetpack Compose?
Text hyperlink hashtags(#) and mentions(@) in Jetpack Compose? @Composable fun HashtagsAndMentions() { val colorScheme = MaterialTheme.colorScheme val primaryStyle = SpanStyle(color = colorScheme.primary) val textStyle = SpanStyle(color = colorScheme.onBackground) val annotatedString = buildAnnotatedString { withStyle(style = textStyle) { append("I am ") } pushStringAnnotation(tag = "hashtags", annotation = "hashtags") withStyle(style = primaryStyle) { append(text = "#hashtags") } pop() withStyle(style = textStyle) { append(" and ") } pushStringAnnotation(tag = "mentions", annotation = "mentions") withStyle(style = primaryStyle) { append(text = "@mentions") } pop() withStyle(style = textStyle) { append(" in Jetpack Compose.") } } ClickableText( onClick = { annotatedString.getStringAnnotations("hashtags", it, it).firstOrNull()?.let { } annotatedString.getStringAnnotations("mentions", it, it).firstOrNull()?.let { } }, text = annotatedString, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(16.dp)) } @Preview @Composable fun PreviewTest() { HashtagsAndMentions() } The above are fixed tags, how to dynamically identify and link? ideas String to array val string = "I am #hashtags and @mentions in Jetpack Compose." val array = arrayOf("I am ", "#hashtags", " and ", "@mentions", "in Jetpack Compose.")
[ "To dynamically identify and link hashtags and mentions in a string using Jetpack Compose, you can use the Regex class to match the hashtags and mentions in the string, and then use the buildAnnotatedString function to apply styles and click handlers to the matched text.\nHere is an example of how you can do this:\n @Composable\nfun HashtagsAndMentions(text: String) {\n val colorScheme = MaterialTheme.colorScheme\n val primaryStyle = SpanStyle(color = colorScheme.primary)\n val textStyle = SpanStyle(color = colorScheme.onBackground)\nval hashtags = Regex(\"(#[a-zA-Z0-9]+)\")\nval mentions = Regex(\"(@[a-zA-Z0-9]+)\")\n\n// Create a list of text spans with styles and click handlers\nval spans = mutableListOf<AnnotatedString.Range<SpanStyle>>()\nvar lastIndex = 0\n\n// Add text spans for hashtags\nfor (match in hashtags.findAll(text)) {\n val start = match.range.first\n val end = match.range.last + 1\n val text = text.substring(start, end)\n if (start > lastIndex) {\n spans += AnnotatedString.Range(\n text = text.substring(lastIndex, start),\n style = textStyle\n )\n }\n spans += AnnotatedString.Range(\n text = text,\n style = primaryStyle,\n onClick = {\n // Handle hashtag click\n }\n )\n lastIndex = end\n}\n\n// Add text spans for mentions\nfor (match in mentions.findAll(text)) {\n val start = match.range.first\n val end = match.range.last + 1\n val text = text.substring(start, end)\n if (start > lastIndex) {\n spans += AnnotatedString.Range(\n text = text.substring(lastIndex, start),\n style = textStyle\n )\n }\n spans += AnnotatedString.Range(\n text = text,\n style = primaryStyle,\n onClick = {\n // Handle mention click\n }\n )\n lastIndex = end\n}\n\n// Add remaining text\nif (lastIndex < text.length) {\n spans += AnnotatedString.Range(\n text = text.substring(lastIndex, text.length),\n style = textStyle\n )\n}\n\n// Build the annotated string\nval annotatedString = buildAnnotatedString {\n for (span in spans) {\n pushStyle(span.style)\n append(span.text)\n pop()\n }\n}\n\n// Use the annotated string in a ClickableText component\nClickableText(\n onClick = {\n // Handle text click\n },\n text = annotatedString,\n style = MaterialTheme.typography.bodyLarge,\n modifier = Modifier.padding(16.dp)\n)\n\n}\nIn this example, the `HashtagsAndMentions\n", "To dynamically identify hashtags and mentions in a string, you can use regular expressions to match hashtags and mentions in the string. Regular expressions are a powerful way to search for patterns in text.\nHere is an example of how you could use regular expressions to identify hashtags and mentions in a string:\nval string = \"I am #hashtags and @mentions in Jetpack Compose.\"\n\nval hashtagsRegex = Regex(\"#\\\\w+\")\nval mentionsRegex = Regex(\"@\\\\w+\")\n\nval hashtags = hashtagsRegex.findAll(string).map { it.value }\nval mentions = mentionsRegex.findAll(string).map { it.value }\n\nprintln(\"Hashtags: $hashtags\")\nprintln(\"Mentions: $mentions\")\n\nThe hashtagsRegex variable uses the # character followed by one or more word characters (letters, digits, and underscores) to match hashtags in the string. The mentionsRegex variable uses the @ character followed by one or more word characters to match mentions in the string.\nThe findAll() method is used to search the string for all occurrences of the regular expression and return a sequence of MatchResult objects. The map() method is used to transform the sequence of MatchResult objects into a sequence of strings, which are the actual hashtags and mentions found in the string.\nFinally, the println() statements print the hashtags and mentions that were found in the string.\nYou can then use the hashtags and mentions variables to link to the corresponding content in your Jetpack Compose UI.\nHope this helps! Let me know if you have any other questions.\n", "Here is an available hashtag and mention link.\nMany thanks to @cyberpunk_unicorn for the idea, unfortunately his answer is not available, but I marked it anyway.\nI refactored his code to ensure that it is runnable, concise enough, and very helpful to those who need it later.\n\n@Composable\nfun HashtagsMentionsTextView(text: String) {\n\n val colorScheme = MaterialTheme.colorScheme\n val textStyle = SpanStyle(color = colorScheme.onBackground)\n val primaryStyle = SpanStyle(color = colorScheme.primary)\n\n val hashtags = Regex(\"(#[a-zA-Z0-9]+)\")\n val mentions = Regex(\"(@[a-zA-Z0-9]+)\")\n\n val annotatedStringList = remember {\n\n val annotatedStringList = mutableStateListOf<AnnotatedString>()\n var lastIndex = 0\n\n // Add a text range for hashtags\n for (match in hashtags.findAll(text)) {\n\n val start = match.range.first\n val end = match.range.last + 1\n val string = text.substring(start, end)\n\n if (start > lastIndex) {\n annotatedStringList.add(\n AnnotatedString(\n text = text.substring(lastIndex, start),\n spanStyle = textStyle\n )\n )\n }\n annotatedStringList.add(AnnotatedString(text = string, spanStyle = primaryStyle))\n lastIndex = end\n }\n\n // Add text spans for mentions\n for (match in mentions.findAll(text)) {\n\n val start = match.range.first\n val end = match.range.last + 1\n val string = text.substring(start, end)\n\n if (start > lastIndex) {\n annotatedStringList.add(\n AnnotatedString(\n text = text.substring(lastIndex, start),\n spanStyle = textStyle\n )\n )\n }\n annotatedStringList.add(AnnotatedString(text = string, spanStyle = primaryStyle))\n lastIndex = end\n }\n\n // Add remaining text\n if (lastIndex < text.length) {\n annotatedStringList.add(\n AnnotatedString(\n text = text.substring(lastIndex, text.length),\n spanStyle = textStyle\n )\n )\n }\n annotatedStringList\n }\n\n // Build an annotated string\n val annotatedString = buildAnnotatedString {\n annotatedStringList.forEach {\n val spanStyle = it.spanStyles.first().item\n if (spanStyle == textStyle) {\n withStyle(it.spanStyles.first().item) {\n append(it.text)\n }\n } else {\n pushStringAnnotation(tag = it.text, annotation = it.text)\n withStyle(style = spanStyle) {\n append(it.text)\n }\n pop()\n }\n }\n }\n\n val onClick: (Int) -> Unit = { position ->\n annotatedStringList.forEach {\n annotatedString.getStringAnnotations(it.text, position, position).firstOrNull()?.let {\n println(it.item)\n }\n }\n }\n\n ClickableText(\n text = annotatedString,\n style = MaterialTheme.typography.bodyLarge,\n modifier = Modifier.padding(16.dp),\n onClick = onClick\n )\n}\n\n\n\n@Preview\n@Composable\nfun PreviewTest() {\n val string = \"I am #hashtags or #hashtags# and @mentions in Jetpack Compose.\"\n HashtagsMentionsTextView(string)\n}\n\n\n" ]
[ 2, 1, 0 ]
[]
[]
[ "android_jetpack_compose" ]
stackoverflow_0074051925_android_jetpack_compose.txt
Q: BitmapShader as a source for a Paint path Is it possible using non-openGL to achieve the effect shown in the graphic. Basically the stroke width is the same throughout the path as is the source bitmap. Before you're wondering why, Paint.setMaskFilter is quite slow. I'd rather prerender a blur in a bitmap and just paint with that. Code for what it's worth: paint = new Paint(); paint.setAntiAlias(true); paint.setDither(true); paint.setStrokeWidth(40f); paint.setStyle(Paint.Style.STROKE); paint.setPathEffect(new CornerPathEffect(8f)); Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.shader_source); BitmapShader shader = new BitmapShader(bm, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP); paint.setShader(shader); A: Yes, it is possible to achieve the effect shown in the graphic using non-openGL techniques. One way to do this is to prerender the blur effect in a bitmap and then paint the path using that bitmap as the source. This can be done by creating a blur effect on the bitmap using a blur filter, such as the BoxBlur or StackBlur filter, and then applying the bitmap to the paint object using a BitmapShader. Here is an example code snippet: // Create a blur effect on the bitmap Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.shader_source); bm = bm.copy(bm.getConfig(), true); BoxBlurFilter blurFilter = new BoxBlurFilter(radius, radius, iterations); blurFilter.filter(bm, bm); // Apply the bitmap to the paint object using a BitmapShader BitmapShader shader = new BitmapShader(bm, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP); Paint paint = new Paint(); paint.setShader(shader); // Use the paint object to draw the path on the canvas canvas.drawPath(path, paint); By using this approach, you can achieve the same effect as using OpenGL without incurring the performance overhead of using the Paint.setMaskFilter method. A: Yes, it is possible to achieve the effect shown in the graphic using non-OpenGL methods. One way to do this would be to pre-render the blur effect in a bitmap and then use that bitmap as the source for the paint. This can be done by applying a blur filter to the bitmap using a method such as Bitmap.createScaledBitmap() and then setting the paint's Shader property to use the blurred bitmap as the source. This will allow you to paint the path with the desired blur effect without the need for OpenGL. Here is an example of how you can use a Bitmap and BitmapShader to pre-render a blur effect and then apply it to a path in your canvas: // Create a new Paint object Paint paint = new Paint(); paint.setAntiAlias(true); paint.setDither(true); // Set the stroke width and style paint.setStrokeWidth(40f); paint.setStyle(Paint.Style.STROKE); // Set the path effect to add rounded corners to the path paint.setPathEffect(new CornerPathEffect(8f)); // Load the bitmap that will be used as the source for the blur effect Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.shader_source); // Create a BitmapShader using the bitmap as the source and set it as the shader for the paint BitmapShader shader = new BitmapShader(bm, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP); paint.setShader(shader); // Create a new path and add points to it Path path = new Path(); path.moveTo(100, 100); path.lineTo(200, 150); path.lineTo(300, 100); // Draw the path on the canvas using the paint with the pre-rendered blur effect canvas.drawPath(path, paint); You can also use the setMaskFilter method on the paint object to apply a blur effect directly, but this can be slower than pre-rendering the effect. Here is an example of how you can use setMaskFilter to apply a blur to a path: // Create a new Paint object Paint paint = new Paint(); paint.setAntiAlias(true); paint.setDither(true); // Set the stroke width and style paint.setStrokeWidth(40f); paint.setStyle(Paint.Style.STROKE); // Set the path effect to add rounded corners to the path paint.setPathEffect(new CornerPathEffect(8f)); // Set the mask filter to apply a blur effect to the path paint.setMaskFilter(new BlurMaskFilter(10, BlurMaskFilter.Blur.NORMAL)); // Create a new path and add points to it Path path = new Path(); path.moveTo(100, 100); path.lineTo(200, 150); path.lineTo(300, 100); // Draw the path on the canvas using the paint with the blur effect applied canvas.drawPath(path, paint); Note that in both examples, the blur effect will be applied to the entire path, including the stroke width and corners. You can adjust the parameters of the blur effect and path effect to achieve the desired result.
BitmapShader as a source for a Paint path
Is it possible using non-openGL to achieve the effect shown in the graphic. Basically the stroke width is the same throughout the path as is the source bitmap. Before you're wondering why, Paint.setMaskFilter is quite slow. I'd rather prerender a blur in a bitmap and just paint with that. Code for what it's worth: paint = new Paint(); paint.setAntiAlias(true); paint.setDither(true); paint.setStrokeWidth(40f); paint.setStyle(Paint.Style.STROKE); paint.setPathEffect(new CornerPathEffect(8f)); Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.shader_source); BitmapShader shader = new BitmapShader(bm, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP); paint.setShader(shader);
[ "Yes, it is possible to achieve the effect shown in the graphic using non-openGL techniques. One way to do this is to prerender the blur effect in a bitmap and then paint the path using that bitmap as the source. This can be done by creating a blur effect on the bitmap using a blur filter, such as the BoxBlur or StackBlur filter, and then applying the bitmap to the paint object using a BitmapShader.\nHere is an example code snippet:\n// Create a blur effect on the bitmap\nBitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.shader_source);\nbm = bm.copy(bm.getConfig(), true);\nBoxBlurFilter blurFilter = new BoxBlurFilter(radius, radius, iterations);\nblurFilter.filter(bm, bm);\n\n// Apply the bitmap to the paint object using a BitmapShader\nBitmapShader shader = new BitmapShader(bm, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);\nPaint paint = new Paint();\npaint.setShader(shader);\n\n// Use the paint object to draw the path on the canvas\ncanvas.drawPath(path, paint);\n\nBy using this approach, you can achieve the same effect as using OpenGL without incurring the performance overhead of using the Paint.setMaskFilter method.\n", "Yes, it is possible to achieve the effect shown in the graphic using non-OpenGL methods. One way to do this would be to pre-render the blur effect in a bitmap and then use that bitmap as the source for the paint. This can be done by applying a blur filter to the bitmap using a method such as Bitmap.createScaledBitmap() and then setting the paint's Shader property to use the blurred bitmap as the source. This will allow you to paint the path with the desired blur effect without the need for OpenGL.\nHere is an example of how you can use a Bitmap and BitmapShader to pre-render a blur effect and then apply it to a path in your canvas:\n// Create a new Paint object\nPaint paint = new Paint();\npaint.setAntiAlias(true);\npaint.setDither(true);\n\n// Set the stroke width and style\npaint.setStrokeWidth(40f);\npaint.setStyle(Paint.Style.STROKE);\n\n// Set the path effect to add rounded corners to the path\npaint.setPathEffect(new CornerPathEffect(8f));\n\n// Load the bitmap that will be used as the source for the blur effect\nBitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.shader_source);\n\n// Create a BitmapShader using the bitmap as the source and set it as the shader for the paint\nBitmapShader shader = new BitmapShader(bm, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);\npaint.setShader(shader);\n\n// Create a new path and add points to it\nPath path = new Path();\npath.moveTo(100, 100);\npath.lineTo(200, 150);\npath.lineTo(300, 100);\n\n// Draw the path on the canvas using the paint with the pre-rendered blur effect\ncanvas.drawPath(path, paint);\n\nYou can also use the setMaskFilter method on the paint object to apply a blur effect directly, but this can be slower than pre-rendering the effect. Here is an example of how you can use setMaskFilter to apply a blur to a path:\n// Create a new Paint object\nPaint paint = new Paint();\npaint.setAntiAlias(true);\npaint.setDither(true);\n\n// Set the stroke width and style\npaint.setStrokeWidth(40f);\npaint.setStyle(Paint.Style.STROKE);\n\n// Set the path effect to add rounded corners to the path\npaint.setPathEffect(new CornerPathEffect(8f));\n\n// Set the mask filter to apply a blur effect to the path\npaint.setMaskFilter(new BlurMaskFilter(10, BlurMaskFilter.Blur.NORMAL));\n\n// Create a new path and add points to it\nPath path = new Path();\npath.moveTo(100, 100);\npath.lineTo(200, 150);\npath.lineTo(300, 100);\n\n// Draw the path on the canvas using the paint with the blur effect applied\ncanvas.drawPath(path, paint);\n\nNote that in both examples, the blur effect will be applied to the entire path, including the stroke width and corners. You can adjust the parameters of the blur effect and path effect to achieve the desired result.\n" ]
[ 0, 0 ]
[]
[]
[ "android", "android_canvas", "bitmap" ]
stackoverflow_0021943340_android_android_canvas_bitmap.txt
Q: 'int' and 'str' mistake enter image description here bank_account = None highest = 0 for account, amount in accounts.items(): if amount > highest: -------------< bank_account = account highest = account print(bank_acount, highest) TypeError: '>' not supported between instances of 'int' and 'str' how can I alter my code to make it works A: Either 'account' or 'highest' is a string, you need to determine which one and adjust your code. If the string is the string form of a number, i.e. "1", you can use int("1") to get the int form. A: I believe you have a typo in the line that says: highest = account Looks like you wanted that line to say highest = amount
'int' and 'str' mistake
enter image description here bank_account = None highest = 0 for account, amount in accounts.items(): if amount > highest: -------------< bank_account = account highest = account print(bank_acount, highest) TypeError: '>' not supported between instances of 'int' and 'str' how can I alter my code to make it works
[ "Either 'account' or 'highest' is a string, you need to determine which one and adjust your code.\nIf the string is the string form of a number, i.e. \"1\", you can use int(\"1\") to get the int form.\n", "I believe you have a typo in the line that says:\n\nhighest = account\n\nLooks like you wanted that line to say\n\nhighest = amount\n\n" ]
[ 1, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074672798_python_python_3.x.txt
Q: How to implement a "read more" style button at the end of a text in SwiftUI I have a very long text and I want to show just 3 lines with more button just like the picture and also a less button when the text is expand. Any idea of how to do it with SwiftUI? var body: some View{ VStack{ Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") } } A: This answer is a bit of a hack, because it does not truncate the actual string and apply the "..." suffix, which in my humble opinion would be the better engineered solution. That would require the programmer to determine the length of the string that fits within three lines, remove the last two words (to allow for the More/Less button) and apply the "..." suffix. This solution limits the number of lines shown and literally covers the trailing end of the third line with a white background and the button. But it may be suitable for your case... @State private var isExpanded: Bool = false var body: some View{ VStack{ Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") .lineLimit(isExpanded ? nil : 3) .overlay( GeometryReader { proxy in Button(action: { isExpanded.toggle() }) { Text(isExpanded ? "Less" : "More") .font(.caption).bold() .padding(.leading, 8.0) .padding(.top, 4.0) .background(Color.white) } .frame(width: proxy.size.width, height: proxy.size.height, alignment: .bottomTrailing) } ) } } You can learn how to do this by following Apple's "Introducing SwiftUI" tutorials. Specifically the "Creating a macOS app" tutorial, "Section 9 Build the Detail View". A: I was also trying to achieve the similar Results as you. Also spent hours finding the solution when it was in front of me all along...! The solution is to use ZStack along with ScrollView and GeometaryReader all at once... struct CollapsableTextView: View { let lineLimit: Int @State private var expanded: Bool = false @State private var showViewButton: Bool = false private var text: String init(_ text: String, lineLimit: Int) { self.text = text self.lineLimit = lineLimit } private var moreLessText: String { if showViewButton { return expanded ? "View Less" : "View More" } else { return "" } } var body: some View { VStack(alignment: .leading) { ZStack { Text(text) .font(.body) .lineLimit(expanded ? nil : lineLimit) ScrollView(.vertical) { Text(text) .font(.body) .background( GeometryReader { proxy in Color.clear .onAppear { showViewButton = proxy.size.height > CGFloat(22 * lineLimit) } .onChange(of: text) { _ in showViewButton = proxy.size.height > CGFloat(22 * lineLimit) } } ) } .opacity(0.0) .disabled(true) .frame(height: 0.0) } Button(action: { withAnimation { expanded.toggle() } }, label: { Text(moreLessText) .font(.body) .foregroundColor(.orange) }) .opacity(showViewButton ? 1.0 : 0.0) .disabled(!showViewButton) .frame(height: showViewButton ? nil : 0.0) } } } struct CollapsableTextView_Previews: PreviewProvider { static var previews: some View { CollapsableTextView("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.", lineLimit: 3) } } The Most important part of this code is CGFloat(22 * lineLimit) here 22 is the height of single Line with the specified font used. You might have to change the height (i.e. 22 in this case) based upon your font... Other than that every thing is pretty straight forward. I hope it might help...! A: You can read this Medium article struct ExpandableText: View { @State private var expanded: Bool = false @State private var truncated: Bool = false @State private var shrinkText: String private var text: String let font: UIFont let lineLimit: Int init(_ text: String, lineLimit: Int, font: UIFont = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)) { self.text = text _shrinkText = State(wrappedValue: text) self.lineLimit = lineLimit self.font = font } var body: some View { ZStack(alignment: .bottomLeading) { Group { Text(self.expanded ? text : shrinkText) + Text(moreLessText) .bold() .foregroundColor(.black) } .animation(.easeInOut(duration: 1.0), value: false) .lineLimit(expanded ? nil : lineLimit) .background( // Render the limited text and measure its size Text(text) .lineLimit(lineLimit) .background(GeometryReader { visibleTextGeometry in Color.clear.onAppear() { let size = CGSize(width: visibleTextGeometry.size.width, height: .greatestFiniteMagnitude) let attributes:[NSAttributedString.Key:Any] = [NSAttributedString.Key.font: font] ///Binary search until mid == low && mid == high var low = 0 var heigh = shrinkText.count var mid = heigh ///start from top so that if text contain we does not need to loop /// while ((heigh - low) > 1) { let attributedText = NSAttributedString(string: shrinkText + moreLessText, attributes: attributes) let boundingRect = attributedText.boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil) if boundingRect.size.height > visibleTextGeometry.size.height { truncated = true heigh = mid mid = (heigh + low)/2 } else { if mid == text.count { break } else { low = mid mid = (low + heigh)/2 } } shrinkText = String(text.prefix(mid)) } if truncated { shrinkText = String(shrinkText.prefix(shrinkText.count - 2)) //-2 extra as highlighted text is bold } } }) .hidden() // Hide the background ) .font(Font(font)) ///set default font /// if truncated { Button(action: { expanded.toggle() }, label: { HStack { //taking tap on only last line, As it is not possible to get 'see more' location Spacer() Text("") }.opacity(0) }) } } } private var moreLessText: String { if !truncated { return "" } else { return self.expanded ? " read less" : " ... read more" } } } And use this ExpandableText in your view like bellow ExpandableText("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut laborum", lineLimit: 6)
How to implement a "read more" style button at the end of a text in SwiftUI
I have a very long text and I want to show just 3 lines with more button just like the picture and also a less button when the text is expand. Any idea of how to do it with SwiftUI? var body: some View{ VStack{ Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") } }
[ "This answer is a bit of a hack, because it does not truncate the actual string and apply the \"...\" suffix, which in my humble opinion would be the better engineered solution. That would require the programmer to determine the length of the string that fits within three lines, remove the last two words (to allow for the More/Less button) and apply the \"...\" suffix.\nThis solution limits the number of lines shown and literally covers the trailing end of the third line with a white background and the button. But it may be suitable for your case...\n@State private var isExpanded: Bool = false\n\nvar body: some View{\n \n VStack{\n\n Text(\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\")\n .lineLimit(isExpanded ? nil : 3)\n .overlay(\n GeometryReader { proxy in\n Button(action: {\n isExpanded.toggle()\n }) {\n Text(isExpanded ? \"Less\" : \"More\")\n .font(.caption).bold()\n .padding(.leading, 8.0)\n .padding(.top, 4.0)\n .background(Color.white)\n }\n .frame(width: proxy.size.width, height: proxy.size.height, alignment: .bottomTrailing)\n }\n )\n }\n}\n\nYou can learn how to do this by following Apple's \"Introducing SwiftUI\" tutorials. Specifically the \"Creating a macOS app\" tutorial, \"Section 9 Build the Detail View\".\n", "I was also trying to achieve the similar Results as you. Also spent hours finding the solution when it was in front of me all along...!\nThe solution is to use ZStack along with ScrollView and GeometaryReader all at once...\nstruct CollapsableTextView: View {\n let lineLimit: Int\n \n @State private var expanded: Bool = false\n @State private var showViewButton: Bool = false\n private var text: String\n \n init(_ text: String, lineLimit: Int) {\n self.text = text\n self.lineLimit = lineLimit\n \n }\n \n private var moreLessText: String {\n if showViewButton {\n return expanded ? \"View Less\" : \"View More\"\n \n } else {\n return \"\"\n \n }\n }\n \n var body: some View {\n VStack(alignment: .leading) {\n ZStack {\n Text(text)\n .font(.body)\n .lineLimit(expanded ? nil : lineLimit)\n \n ScrollView(.vertical) {\n Text(text)\n .font(.body)\n .background(\n GeometryReader { proxy in\n Color.clear\n .onAppear {\n showViewButton = proxy.size.height > CGFloat(22 * lineLimit)\n }\n .onChange(of: text) { _ in\n showViewButton = proxy.size.height > CGFloat(22 * lineLimit)\n }\n }\n )\n \n }\n .opacity(0.0)\n .disabled(true)\n .frame(height: 0.0)\n }\n \n Button(action: {\n withAnimation {\n expanded.toggle()\n }\n }, label: {\n Text(moreLessText)\n .font(.body)\n .foregroundColor(.orange)\n })\n .opacity(showViewButton ? 1.0 : 0.0)\n .disabled(!showViewButton)\n .frame(height: showViewButton ? nil : 0.0)\n \n }\n }\n}\n\nstruct CollapsableTextView_Previews: PreviewProvider {\n static var previews: some View {\n CollapsableTextView(\"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\", lineLimit: 3)\n }\n \n}\n\nThe Most important part of this code is CGFloat(22 * lineLimit) here 22 is the height of single Line with the specified font used. You might have to change the height (i.e. 22 in this case) based upon your font...\nOther than that every thing is pretty straight forward. I hope it might help...!\n", "You can read this Medium article\nstruct ExpandableText: View {\n \n @State private var expanded: Bool = false\n @State private var truncated: Bool = false\n @State private var shrinkText: String\n \n private var text: String\n let font: UIFont\n let lineLimit: Int\n \n init(_ text: String, lineLimit: Int, font: UIFont = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)) {\n self.text = text\n _shrinkText = State(wrappedValue: text)\n self.lineLimit = lineLimit\n self.font = font\n }\n \n var body: some View {\n ZStack(alignment: .bottomLeading) {\n Group {\n Text(self.expanded ? text : shrinkText) + Text(moreLessText)\n .bold()\n .foregroundColor(.black)\n }\n .animation(.easeInOut(duration: 1.0), value: false)\n .lineLimit(expanded ? nil : lineLimit)\n .background(\n // Render the limited text and measure its size\n Text(text)\n .lineLimit(lineLimit)\n .background(GeometryReader { visibleTextGeometry in\n Color.clear.onAppear() {\n let size = CGSize(width: visibleTextGeometry.size.width, height: .greatestFiniteMagnitude)\n let attributes:[NSAttributedString.Key:Any] = [NSAttributedString.Key.font: font]\n\n ///Binary search until mid == low && mid == high\n var low = 0\n var heigh = shrinkText.count\n var mid = heigh ///start from top so that if text contain we does not need to loop\n ///\n while ((heigh - low) > 1) {\n let attributedText = NSAttributedString(string: shrinkText + moreLessText, attributes: attributes)\n let boundingRect = attributedText.boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)\n if boundingRect.size.height > visibleTextGeometry.size.height {\n truncated = true\n heigh = mid\n mid = (heigh + low)/2\n \n } else {\n if mid == text.count {\n break\n } else {\n low = mid\n mid = (low + heigh)/2\n }\n }\n shrinkText = String(text.prefix(mid))\n }\n \n if truncated {\n shrinkText = String(shrinkText.prefix(shrinkText.count - 2)) //-2 extra as highlighted text is bold\n }\n }\n })\n .hidden() // Hide the background\n )\n .font(Font(font)) ///set default font\n ///\n if truncated {\n Button(action: {\n expanded.toggle()\n }, label: {\n HStack { //taking tap on only last line, As it is not possible to get 'see more' location\n Spacer()\n Text(\"\")\n }.opacity(0)\n })\n }\n }\n }\n \n private var moreLessText: String {\n if !truncated {\n return \"\"\n } else {\n return self.expanded ? \" read less\" : \" ... read more\"\n }\n }\n \n}\n\nAnd use this ExpandableText in your view like bellow\nExpandableText(\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut laborum\", lineLimit: 6)\n\n" ]
[ 2, 0, 0 ]
[]
[]
[ "swiftui" ]
stackoverflow_0063741474_swiftui.txt
Q: TCP or UDP for a client/server cyber cafe software? My program is a cyber cafe program and Server will control clients(opening-closing account,sending files, taking screenshot, closing running applications etc.) and clients will be able to: order drinks,send message etc. So, for best performance, Should I use TCP or UDP? Thanks in advance A: For a massive reduction in coding effort, pain, debugging, user-complaints and more, use TCP. A: I'd rather go for reliability instead and use TCP. Besides, for transferring files (the screenshots you mentioned) UDP is not so suitable since the packets can reach you out-of-order and you'll have to reorder them => you'll need some packet numbering on top of UDP, etc. etc. (TL;DR use TCP). A: Given that you're likely to only have a couple dozen client computers connected to the server, and they're all going to be running on a LAN, then performance is not your biggest concern. Given that, TCP is definitely the way to go. You don't want the headaches of out-of-order packets, dropped packets and duplicated packets that can happen with UDP (though over a LAN, a lot of those problems are minimised - though not eliminated). A: I can't think of any reason whatsoever why you should choose UDP in this situation. A: UDP will for sure give you the best performance because it is connection-less (you save the expensive connect call from TCP and the TCP flag management during transmissions). However develop some safe acknowledgement in your communication because the transmission is not guaranteed. However in a local network it should rarely be a problem, excepting if your customers pull or twist the cables :-). If your protocol becomes more complicated and want more than command/response pairs before reinventing the wheel rather consider taking TCP. A: IMHO the main difference between TCP and UDP is, TCP makes sure that packages arrives the destination and UDP does not. Because of that UDP is a bit faster than TCP. As I understand your program I would use TCP, because your task, seems like they have to work and the network connection have to be reliable. I would use UDP only for tasks, where some packages can be lost, e.g. broadcasting the temperature from a sensor. A: The U in UDP is often believed to stand for Unreliable (*). If you use UDP, then any time (and there will be some!) you need reliability in your server's networking you will need to program your own higher level protocols to detect packet loss, perform retry and so on. This is not simple, and it is particularly hard to do in a "user space" application. TCP deals with packet loss detection, out of order packet detection, retries, and so on ... without you having to worry about it at the application level. Another issue is that a lot of firewalls, routers, gateways etc will block all UDP traffic by default. IMO, you should only consider using UDP in situations where: loss of data is acceptable, and maximum network performance is an absolute, overriding requirement. [* - Actually, UDP stands for User Datagram Protocol.] A: You have to use TCP as it is reliable protocol while UPD is connectionless.
TCP or UDP for a client/server cyber cafe software?
My program is a cyber cafe program and Server will control clients(opening-closing account,sending files, taking screenshot, closing running applications etc.) and clients will be able to: order drinks,send message etc. So, for best performance, Should I use TCP or UDP? Thanks in advance
[ "For a massive reduction in coding effort, pain, debugging, user-complaints and more, use TCP.\n", "I'd rather go for reliability instead and use TCP. Besides, for transferring files (the screenshots you mentioned) UDP is not so suitable since the packets can reach you out-of-order and you'll have to reorder them => you'll need some packet numbering on top of UDP, etc. etc. (TL;DR use TCP).\n", "Given that you're likely to only have a couple dozen client computers connected to the server, and they're all going to be running on a LAN, then performance is not your biggest concern.\nGiven that, TCP is definitely the way to go. You don't want the headaches of out-of-order packets, dropped packets and duplicated packets that can happen with UDP (though over a LAN, a lot of those problems are minimised - though not eliminated).\n", "I can't think of any reason whatsoever why you should choose UDP in this situation.\n", "UDP will for sure give you the best performance because it is connection-less (you save the expensive connect call from TCP and the TCP flag management during transmissions). However develop some safe acknowledgement in your communication because the transmission is not guaranteed. However in a local network it should rarely be a problem, excepting if your customers pull or twist the cables :-). If your protocol becomes more complicated and want more than command/response pairs before reinventing the wheel rather consider taking TCP.\n", "IMHO the main difference between TCP and UDP is, TCP makes sure that packages arrives the destination and UDP does not. Because of that UDP is a bit faster than TCP.\nAs I understand your program I would use TCP, because your task, seems like they have to work and the network connection have to be reliable.\nI would use UDP only for tasks, where some packages can be lost, e.g. broadcasting the temperature from a sensor.\n", "The U in UDP is often believed to stand for Unreliable (*). If you use UDP, then any time (and there will be some!) you need reliability in your server's networking you will need to program your own higher level protocols to detect packet loss, perform retry and so on. This is not simple, and it is particularly hard to do in a \"user space\" application. TCP deals with packet loss detection, out of order packet detection, retries, and so on ... without you having to worry about it at the application level.\nAnother issue is that a lot of firewalls, routers, gateways etc will block all UDP traffic by default.\nIMO, you should only consider using UDP in situations where:\n\nloss of data is acceptable, and\nmaximum network performance is an absolute, overriding requirement.\n\n[* - Actually, UDP stands for User Datagram Protocol.]\n", "You have to use TCP as it is reliable protocol while UPD is connectionless.\n" ]
[ 7, 3, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "c#" ]
stackoverflow_0003127113_c#.txt
Q: How to tail a log file with timestamps and count occurrences in the last X seconds I have a log files that I read/stream into Python (it contains timestamp and data) using tail. I need a way to see if, in the last 10 seconds, how many lines were seen/observed based on a filter (e.g. line contains "error") I'll be checking every X seconds to see how many lines were present for "error" or "debug" etc... The count should only look at the last X seconds. Example: A log file which Python tails is 2022-11-15 14:00:00,000 : Error 1923 2022-11-15 14:00:01,000 : Error 1456 2022-11-15 14:00:01,400 : Error 1001 2022-11-15 14:00:03,400 : Error 1124 2022-11-15 14:00:05,400 : Normal 0011 2022-11-15 14:00:06,400 : Error 1123 When I read the file, in Python; I want to answer the question In the last X seconds, how many times have I seen Error or How many times have I seen Normal? How would I accomplish this whilst I tail a file to check the last 10 seconds or 20 seconds etc.? A: This is a quite simple solution that looks at the current timestamp (I hardcoded the timestamp to follow the timestamps from your example but you can use datetime.datetime.now() instead). Simply put, the following was done: I made a file called test.log with the exact contents of that python tails piece of text you made above, which I read in using Python Then you should be able to simply run and tweak the following code: import datetime import re with open('test.log') as f: lines = f.readlines() # Defining the interesting interval of time seconds_interval = 4 interval = datetime.timedelta(seconds=seconds_interval) # You could use now = datetime.datetime.now() but this is for this test now = datetime.datetime(2022, 11, 15, hour=14, minute=00, second=6) # This is the function that grabs the interesting lines, and is used in the # filter operator def grab_interesting_lines(line): strDate = re.search('\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', line).group(0) date_time_obj = datetime.datetime.strptime(strDate, '%Y-%m-%d %H:%M:%S') return date_time_obj >= now - interval # Now we're actually filtering. The interesting_lines object is an iterator over # which we can loop later on interesting_lines = filter(grab_interesting_lines, lines) # Now we simply loop over the interesting lines, and count whether an error # occurred, a "normal" occured or something else happened error_counter = 0 normal_counter = 0 else_counter = 0 for line in interesting_lines: if 'Error' in line: error_counter+=1 elif 'Normal' in line: normal_counter+=1 else: else_counter+=1 # Here we print out the output. Of course you can use these counter variables # somewhere else if you want print(f"The last {seconds_interval} seconds had {error_counter} errors, {normal_counter} normals and {else_counter} elses in there") The output for seconds_interval = 4 and your data example is: The last 4 seconds had 2 errors, 1 normals and 0 elses in there Of course, this is a pretty crude approach. Everything depends on how variable your input is. For example, what if you have an Error and a Normal on the same line? I didn't add any error handling in there because the edge cases are not known. Hope this helps you! :) A: To accomplish this, you can use a combination of the time and tail modules in Python. The time module allows you to get the current time and compare it to previous times, while the tail module allows you to read and stream the log file. Here is an example of how you could implement this in Python: # Import the necessary modules import time from tail import tail # Set the number of seconds to look back num_seconds = 10 # Open the log file and stream the lines with open('logfile.txt') as logfile: for line in tail(logfile): # Get the current time current_time = time.time() # Check if the line contains the desired string if "error" in line: # Check if the line was seen within the last X seconds if current_time - line_time <= num_seconds: # Increment the count count += 1 This code will stream the lines from the log file, and for each line, it will check if the line contains the string "error" and if the line was seen within the last num_seconds seconds. If both of these conditions are true, it will increment the count. You can adjust the num_seconds variable to change the number of seconds to look back, and you can also change the string that is being searched for in the log file. A: Here's one way to accomplish this in Python: Store the timestamps and lines of the log file in a list. Use the time module to get the current time and subtract X seconds from it to get the time X seconds ago. Iterate over the list of timestamps and lines and count the number of lines that occurred within the last X seconds. Here's an example: import time log_lines = [ ("2022-11-15 14:00:00,000", "Error 1923"), ("2022-11-15 14:00:01,000", "Error 1456"), ("2022-11-15 14:00:01,400", "Error 1001"), ("2022-11-15 14:00:03,400", "Error 1124"), ("2022-11-15 14:00:05,400", "Normal 0011"), ("2022-11-15 14:00:06,400", "Error 1123"), ] # Get the current time and subtract 10 seconds from it time_x_seconds_ago = time.time() - 10 # Count the number of lines that occurred within the last X seconds count = 0 for timestamp, line in log_lines: if time.strptime(timestamp, "%Y-%m-%d %H:%M:%S,%f") >= time_x_seconds_ago: count += 1 print(f"Number of lines in the last 10 seconds: {count}") You can adapt this approach to work with a log file that you're tailing in Python by storing the timestamps and lines in a list and continuously updating the list as you read new lines from the file. You can then use the same approach as above to count the number of lines that occurred within the last X seconds. Here's an example of how you could write unit tests for the code above using the unittest module in Python: import unittest import time log_lines = [ ("2022-11-15 14:00:00,000", "Error 1923"), ("2022-11-15 14:00:01,000", "Error 1456"), ("2022-11-15 14:00:01,400", "Error 1001"), ("2022-11-15 14:00:03,400", "Error 1124"), ("2022-11-15 14:00:05,400", "Normal 0011"), ("2022-11-15 14:00:06,400", "Error 1123"), ] class TestCountLines(unittest.TestCase): def test_count_lines(self): # Test counting the number of lines in the last 10 seconds time_x_seconds_ago = time.time() - 10 count = 0 for timestamp, line in log_lines: if time.strptime(timestamp, "%Y-%m-%d %H:%M:%S,%f") >= time_x_seconds_ago: count += 1 self.assertEqual(count, 4) # Test counting the number of lines in the last 5 seconds time_x_seconds_ago = time.time() - 5 count = 0 for timestamp, line in log_lines: if time.strptime(timestamp, "%Y-%m-%d %H:%M:%S,%f") >= time_x_seconds_ago: count += 1 self.assertEqual(count, 3) # Test counting the number of lines in the last 1 second time_x_seconds_ago = time.time() - 1 count = 0 for timestamp, line in log_lines: if time.strptime(timestamp, "%Y-%m-%d %H:%M:%S,%f") >= time_x_seconds_ago: count += 1 self.assertEqual(count, 0) if __name__ == "__main__": unittest.main() In this example, the TestCountLines class contains three test cases: test_count_lines: Tests counting the number of lines in the last 10 seconds. test_count_lines: Tests counting the number of lines in the last 5 seconds. test_count_lines: Tests counting the number of lines in the last 1 second. Each test case uses the assertEqual method to compare the expected output with the actual output of the code. If the expected and actual outputs match, the test passes. If the outputs don't match, the test fails.
How to tail a log file with timestamps and count occurrences in the last X seconds
I have a log files that I read/stream into Python (it contains timestamp and data) using tail. I need a way to see if, in the last 10 seconds, how many lines were seen/observed based on a filter (e.g. line contains "error") I'll be checking every X seconds to see how many lines were present for "error" or "debug" etc... The count should only look at the last X seconds. Example: A log file which Python tails is 2022-11-15 14:00:00,000 : Error 1923 2022-11-15 14:00:01,000 : Error 1456 2022-11-15 14:00:01,400 : Error 1001 2022-11-15 14:00:03,400 : Error 1124 2022-11-15 14:00:05,400 : Normal 0011 2022-11-15 14:00:06,400 : Error 1123 When I read the file, in Python; I want to answer the question In the last X seconds, how many times have I seen Error or How many times have I seen Normal? How would I accomplish this whilst I tail a file to check the last 10 seconds or 20 seconds etc.?
[ "This is a quite simple solution that looks at the current timestamp (I hardcoded the timestamp to follow the timestamps from your example but you can use datetime.datetime.now() instead).\nSimply put, the following was done:\n\nI made a file called test.log with the exact contents of that python tails piece of text you made above, which I read in using Python\nThen you should be able to simply run and tweak the following code:\n\nimport datetime\nimport re\n\nwith open('test.log') as f:\n lines = f.readlines()\n\n# Defining the interesting interval of time\nseconds_interval = 4\ninterval = datetime.timedelta(seconds=seconds_interval)\n# You could use now = datetime.datetime.now() but this is for this test\nnow = datetime.datetime(2022, 11, 15, hour=14, minute=00, second=6)\n\n# This is the function that grabs the interesting lines, and is used in the\n# filter operator\ndef grab_interesting_lines(line):\n strDate = re.search('\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}', line).group(0)\n date_time_obj = datetime.datetime.strptime(strDate, '%Y-%m-%d %H:%M:%S')\n return date_time_obj >= now - interval\n\n# Now we're actually filtering. The interesting_lines object is an iterator over\n# which we can loop later on\ninteresting_lines = filter(grab_interesting_lines, lines)\n\n# Now we simply loop over the interesting lines, and count whether an error\n# occurred, a \"normal\" occured or something else happened\nerror_counter = 0\nnormal_counter = 0\nelse_counter = 0\nfor line in interesting_lines:\n if 'Error' in line:\n error_counter+=1\n elif 'Normal' in line:\n normal_counter+=1\n else:\n else_counter+=1\n\n# Here we print out the output. Of course you can use these counter variables\n# somewhere else if you want\nprint(f\"The last {seconds_interval} seconds had {error_counter} errors, {normal_counter} normals and {else_counter} elses in there\")\n\nThe output for seconds_interval = 4 and your data example is:\nThe last 4 seconds had 2 errors, 1 normals and 0 elses in there\n\nOf course, this is a pretty crude approach. Everything depends on how variable your input is. For example, what if you have an Error and a Normal on the same line? I didn't add any error handling in there because the edge cases are not known.\nHope this helps you! :)\n", "To accomplish this, you can use a combination of the time and tail modules in Python. The time module allows you to get the current time and compare it to previous times, while the tail module allows you to read and stream the log file.\nHere is an example of how you could implement this in Python:\n# Import the necessary modules\nimport time\nfrom tail import tail\n\n# Set the number of seconds to look back\nnum_seconds = 10\n\n# Open the log file and stream the lines\nwith open('logfile.txt') as logfile:\n for line in tail(logfile):\n # Get the current time\n current_time = time.time()\n\n # Check if the line contains the desired string\n if \"error\" in line:\n # Check if the line was seen within the last X seconds\n if current_time - line_time <= num_seconds:\n # Increment the count\n count += 1\n\nThis code will stream the lines from the log file, and for each line, it will check if the line contains the string \"error\" and if the line was seen within the last num_seconds seconds. If both of these conditions are true, it will increment the count. You can adjust the num_seconds variable to change the number of seconds to look back, and you can also change the string that is being searched for in the log file.\n", "Here's one way to accomplish this in Python:\nStore the timestamps and lines of the log file in a list.\nUse the time module to get the current time and subtract X seconds from it to get the time X seconds ago.\nIterate over the list of timestamps and lines and count the number of lines that occurred within the last X seconds.\nHere's an example:\nimport time\n\nlog_lines = [\n (\"2022-11-15 14:00:00,000\", \"Error 1923\"),\n (\"2022-11-15 14:00:01,000\", \"Error 1456\"),\n (\"2022-11-15 14:00:01,400\", \"Error 1001\"),\n (\"2022-11-15 14:00:03,400\", \"Error 1124\"),\n (\"2022-11-15 14:00:05,400\", \"Normal 0011\"),\n (\"2022-11-15 14:00:06,400\", \"Error 1123\"),\n]\n\n# Get the current time and subtract 10 seconds from it\ntime_x_seconds_ago = time.time() - 10\n\n# Count the number of lines that occurred within the last X seconds\ncount = 0\nfor timestamp, line in log_lines:\n if time.strptime(timestamp, \"%Y-%m-%d %H:%M:%S,%f\") >= time_x_seconds_ago:\n count += 1\n\nprint(f\"Number of lines in the last 10 seconds: {count}\")\n\nYou can adapt this approach to work with a log file that you're tailing in Python by storing the timestamps and lines in a list and continuously updating the list as you read new lines from the file. You can then use the same approach as above to count the number of lines that occurred within the last X seconds.\nHere's an example of how you could write unit tests for the code above using the unittest module in Python:\nimport unittest\nimport time\n\nlog_lines = [\n (\"2022-11-15 14:00:00,000\", \"Error 1923\"),\n (\"2022-11-15 14:00:01,000\", \"Error 1456\"),\n (\"2022-11-15 14:00:01,400\", \"Error 1001\"),\n (\"2022-11-15 14:00:03,400\", \"Error 1124\"),\n (\"2022-11-15 14:00:05,400\", \"Normal 0011\"),\n (\"2022-11-15 14:00:06,400\", \"Error 1123\"),\n]\n\nclass TestCountLines(unittest.TestCase):\n def test_count_lines(self):\n # Test counting the number of lines in the last 10 seconds\n time_x_seconds_ago = time.time() - 10\n count = 0\n for timestamp, line in log_lines:\n if time.strptime(timestamp, \"%Y-%m-%d %H:%M:%S,%f\") >= time_x_seconds_ago:\n count += 1\n self.assertEqual(count, 4)\n\n # Test counting the number of lines in the last 5 seconds\n time_x_seconds_ago = time.time() - 5\n count = 0\n for timestamp, line in log_lines:\n if time.strptime(timestamp, \"%Y-%m-%d %H:%M:%S,%f\") >= time_x_seconds_ago:\n count += 1\n self.assertEqual(count, 3)\n\n # Test counting the number of lines in the last 1 second\n time_x_seconds_ago = time.time() - 1\n count = 0\n for timestamp, line in log_lines:\n if time.strptime(timestamp, \"%Y-%m-%d %H:%M:%S,%f\") >= time_x_seconds_ago:\n count += 1\n self.assertEqual(count, 0)\n\nif __name__ == \"__main__\":\n unittest.main()\n\nIn this example, the TestCountLines class contains three test cases:\ntest_count_lines: Tests counting the number of lines in the last 10 seconds.\ntest_count_lines: Tests counting the number of lines in the last 5 seconds.\ntest_count_lines: Tests counting the number of lines in the last 1 second.\nEach test case uses the assertEqual method to compare the expected output with the actual output of the code. If the expected and actual outputs match, the test passes. If the outputs don't match, the test fails.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074444395_python.txt
Q: Why does AndroidId have a different result between Android and Xamarin I have the need to detect a common factor between two apps, one written in Xamarin and one written in Java (Android Studio), running on a users phone. In the good old days the IMEI did the job nicely. However now I am having to use the Device ID, which is fine for the current purpose, but not perfect. Anyway, using the following statement in Xamarin gives one result, while using the statement that follows this in Android, gives a different result, both on the same phone. Why would this be, why is the Device ID not reported as the same value, and is there a way to identify the DeviceID via both platforms that result in the same output ? Thanks Xamarin code - Result is "a70c996e74002942" var Device_ID = Android.Provider.Settings.Secure.GetString(ContentResolver, Android.Provider.Settings.Secure.AndroidId); Android Studio code - Result is "702669b2e9a6f7d1" String Device_ID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); A: From the docs unique to each combination of app-signing key, user, and device For privacy reasons, two different apps on the same device will have different ids
Why does AndroidId have a different result between Android and Xamarin
I have the need to detect a common factor between two apps, one written in Xamarin and one written in Java (Android Studio), running on a users phone. In the good old days the IMEI did the job nicely. However now I am having to use the Device ID, which is fine for the current purpose, but not perfect. Anyway, using the following statement in Xamarin gives one result, while using the statement that follows this in Android, gives a different result, both on the same phone. Why would this be, why is the Device ID not reported as the same value, and is there a way to identify the DeviceID via both platforms that result in the same output ? Thanks Xamarin code - Result is "a70c996e74002942" var Device_ID = Android.Provider.Settings.Secure.GetString(ContentResolver, Android.Provider.Settings.Secure.AndroidId); Android Studio code - Result is "702669b2e9a6f7d1" String Device_ID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
[ "From the docs\n\nunique to each combination of app-signing key, user, and device\n\nFor privacy reasons, two different apps on the same device will have different ids\n" ]
[ 0 ]
[]
[]
[ "android", "xamarin.forms" ]
stackoverflow_0074672726_android_xamarin.forms.txt
Q: Why even i am instantiating template parameter at runtime but i am getting expected output instead of error ie. we cannot expand template at runtime? As I know that templates are expanded at compile time but in below example i am deciding or doing template instantiation at runtime depending on user input but still i am getting expected output.how this running? can someone explain me #include <iostream> using namespace std; template<typename T> class Demo { T Value = 20.67; public: void print(T val) { std::cout << "value :" << val << std::endl; } T getValue() { return Value; } }; int main() { int a; std::cout << "Enter value for a :"; std::cin >> a; if(a == 10) { Demo<int> demoObj1; demoObj1.print(demoObj1.getValue()); } else { Demo<float> demoObj2; demoObj2.print(demoObj2.getValue()); } } //output: Enter value for a :10 value :20 and Enter value for a :7 value :20.67 A: At compile time, both templates are created. There exists code in your compiled program for both branches. At runtime you are simply selecting which branch to execute. The compiler sees the two branches of code and realizes that it cannot determine which branch will be taken at compile time, so it will generate code for both branches. If the compiler can determine at compile time that a branch cannot possibly be taken, a compiler may optimize it away. A simple situation is with the following: if (4 < 5) { Demo<int> demoObj1; demoObj1.print(demoObj1.getValue()); } else { Demo<float> demoObj2; demoObj2.print(demoObj2.getValue()); } In this case, the compiler can see that the second branch will never get executed. The compiler will initially compile both branches, but then it may discard the second branch from the final executable. Whether or not the compiler does this depends on the compiler implementation and compilation flags. You can force the compiler to reject unused branches with if constexpr. Consider the following example: if constexpr (4 < 5) { Demo<int> demoObj1; demoObj1.print(demoObj1.getValue()); } else { Demo<float> demoObj2; demoObj2.print(demoObj2.getValue()); } All that was changed is that this example uses if constexpr. In this example, the second branch will NOT be fully compiled (it is still checked for correct syntax, but assembly generation is not done). Code for the second branch will not exist in the executable. A: Both Demo<int> and Demo<float> will be instantiated compile time as you're using a normal(non-constexpr) if, else instead of constexpr if. On the other hand, if you were to use constexpr if then only one of Demo<int> or Demo<float> would've been instantiated. Note that in this example we can't use constexpr if since the input is taken from user.
Why even i am instantiating template parameter at runtime but i am getting expected output instead of error ie. we cannot expand template at runtime?
As I know that templates are expanded at compile time but in below example i am deciding or doing template instantiation at runtime depending on user input but still i am getting expected output.how this running? can someone explain me #include <iostream> using namespace std; template<typename T> class Demo { T Value = 20.67; public: void print(T val) { std::cout << "value :" << val << std::endl; } T getValue() { return Value; } }; int main() { int a; std::cout << "Enter value for a :"; std::cin >> a; if(a == 10) { Demo<int> demoObj1; demoObj1.print(demoObj1.getValue()); } else { Demo<float> demoObj2; demoObj2.print(demoObj2.getValue()); } } //output: Enter value for a :10 value :20 and Enter value for a :7 value :20.67
[ "At compile time, both templates are created. There exists code in your compiled program for both branches. At runtime you are simply selecting which branch to execute.\nThe compiler sees the two branches of code and realizes that it cannot determine which branch will be taken at compile time, so it will generate code for both branches. If the compiler can determine at compile time that a branch cannot possibly be taken, a compiler may optimize it away. A simple situation is with the following:\nif (4 < 5) {\n Demo<int> demoObj1;\n demoObj1.print(demoObj1.getValue());\n} else {\n Demo<float> demoObj2;\n demoObj2.print(demoObj2.getValue());\n}\n\nIn this case, the compiler can see that the second branch will never get executed. The compiler will initially compile both branches, but then it may discard the second branch from the final executable. Whether or not the compiler does this depends on the compiler implementation and compilation flags.\nYou can force the compiler to reject unused branches with if constexpr. Consider the following example:\nif constexpr (4 < 5) {\n Demo<int> demoObj1;\n demoObj1.print(demoObj1.getValue());\n} else {\n Demo<float> demoObj2;\n demoObj2.print(demoObj2.getValue());\n}\n\nAll that was changed is that this example uses if constexpr. In this example, the second branch will NOT be fully compiled (it is still checked for correct syntax, but assembly generation is not done). Code for the second branch will not exist in the executable.\n", "Both Demo<int> and Demo<float> will be instantiated compile time as you're using a normal(non-constexpr) if, else instead of constexpr if.\nOn the other hand, if you were to use constexpr if then only one of Demo<int> or Demo<float> would've been instantiated. Note that in this example we can't use constexpr if since the input is taken from user.\n" ]
[ 1, 1 ]
[]
[]
[ "c++", "templates" ]
stackoverflow_0074672781_c++_templates.txt
Q: How to graph a mathematical function for "Distance and Speed over Time" in Python? I'm struggling with some Python homework. I'm really new to Python, and coding in general. I have really basic knowledge in Python, and somewhat acceptable level in JavaScript. My issue: I have to make a graph to represent these two functions: distance = (x**2/2 - np.cos(5*x) - 7) speed = (x + 5*np.sin(5*x)) Between the timestamps 3 and 6 (inclusive) I know I have to use Pandas to make a DataFrame, I know I have to use MatPlotLib to make the actual plot, and I have to use Numpy for the math to work, but I can't get the math to be recognised as mathematical functions because I simply don't know how. This is what the graph should look like: Graph for Distance and Speed over Time This is what my code looks for now: import pandas as pd import matplotlib.pyplot as plt import numpy as np x = 10 time = [3, 6] distance = (x**2/2 - np.cos(5*x) - 7) speed = (x + 5*np.sin(5*x)) values = {'Distance': distance, 'Speed': speed, 'Time': time} df = pd.DataFrame(data= values) df.plot(title='Distance and speed', xlabel='Time (hours)', ylabel='Distance (km) / Speed (km/h)', x='Time') plt.show() x = 10 I know shouldn't be included, but since I'm missing the part that makes the math work, I have to include it to make it "work" and not get an error. I have a vague idea that using Numpy is the answer to my problem, but I don't know how (for now, hopefully). How wrong am I? Can anyone help me? A: It looks like your code is almost there! You have imported all of the necessary libraries, and you have defined your distance and speed functions correctly. To make your code work, you need to specify the range of values that you want to use for the x-axis of your graph. In this case, you want to use the values between 3 and 6, inclusive. To do this, you can use the range function in Python, which will generate a sequence of numbers within a given range. Here is an example of how you can use the range function to specify the range of x-values that you want to use: x_values = np.arange(0.0, 20.0, 0.01) Once you have generated the list of x-values, you can use a for loop to iterate over each value and calculate the corresponding distance and speed values. You can then store these values in separate lists, which you can use to create your DataFrame. Here is an example of how you can use a for loop to calculate the distance and speed values for each x-value: # Initialize empty lists to store the distance and speed values distance_values = [] speed_values = [] # Iterate over each x-value for x in x_values: # Calculate the distance and speed values for the current x-value distance = (x**2/2 - np.cos(5*x) - 7) speed = (x + 5*np.sin(5*x)) # Append the calculated values to their respective lists distance_values.append(distance) speed_values.append(speed) Once you have calculated the distance and speed values for each x-value, you can use these lists to create your DataFrame. You can then use the plot method of your DataFrame to create the graph. Here is an example of how you can create your DataFrame and plot the graph: # Create the DataFrame using the x-values, distance values, and speed values df = pd.DataFrame({'Time': x_values, 'Distance': distance_values, 'Speed': speed_values}) # Use the plot method of the DataFrame to create the graph df.plot(title='Distance and speed', xlabel='Time (hours)', ylabel='Distance (km) / Speed (km/h)', x='Time') # Show the graph plt.show() A: Corrections to posted version Use variable t for time (rather than x) np.arange(3, 6.01, 0.01) to get time from 3 to 6 inclusive Code # time values from 3 to 6 inclusive in steps of 0.01 (use 6.01 to include 6) t = np.arange(3, 6.01, 0.01) # t for time # Use NumPy array operations to compute distance and speed at all time values (i.e. x axis) distance = (t**2/2 - np.cos(5*t) - 7) speed = (t + 5*np.sin(5*t)) values = {'Distance': distance, 'Speed': speed, 'Time': t} # x is time t df = pd.DataFrame(data= values) df.plot(title='Distance and speed', xlabel='Time (hours)', ylabel='Distance (km) / Speed (km/h)', x='Time') plt.show()
How to graph a mathematical function for "Distance and Speed over Time" in Python?
I'm struggling with some Python homework. I'm really new to Python, and coding in general. I have really basic knowledge in Python, and somewhat acceptable level in JavaScript. My issue: I have to make a graph to represent these two functions: distance = (x**2/2 - np.cos(5*x) - 7) speed = (x + 5*np.sin(5*x)) Between the timestamps 3 and 6 (inclusive) I know I have to use Pandas to make a DataFrame, I know I have to use MatPlotLib to make the actual plot, and I have to use Numpy for the math to work, but I can't get the math to be recognised as mathematical functions because I simply don't know how. This is what the graph should look like: Graph for Distance and Speed over Time This is what my code looks for now: import pandas as pd import matplotlib.pyplot as plt import numpy as np x = 10 time = [3, 6] distance = (x**2/2 - np.cos(5*x) - 7) speed = (x + 5*np.sin(5*x)) values = {'Distance': distance, 'Speed': speed, 'Time': time} df = pd.DataFrame(data= values) df.plot(title='Distance and speed', xlabel='Time (hours)', ylabel='Distance (km) / Speed (km/h)', x='Time') plt.show() x = 10 I know shouldn't be included, but since I'm missing the part that makes the math work, I have to include it to make it "work" and not get an error. I have a vague idea that using Numpy is the answer to my problem, but I don't know how (for now, hopefully). How wrong am I? Can anyone help me?
[ "It looks like your code is almost there! You have imported all of the necessary libraries, and you have defined your distance and speed functions correctly.\nTo make your code work, you need to specify the range of values that you want to use for the x-axis of your graph. In this case, you want to use the values between 3 and 6, inclusive. To do this, you can use the range function in Python, which will generate a sequence of numbers within a given range.\nHere is an example of how you can use the range function to specify the range of x-values that you want to use:\nx_values = np.arange(0.0, 20.0, 0.01) \n\nOnce you have generated the list of x-values, you can use a for loop to iterate over each value and calculate the corresponding distance and speed values. You can then store these values in separate lists, which you can use to create your DataFrame.\nHere is an example of how you can use a for loop to calculate the distance and speed values for each x-value:\n# Initialize empty lists to store the distance and speed values\ndistance_values = []\nspeed_values = []\n\n# Iterate over each x-value\nfor x in x_values:\n # Calculate the distance and speed values for the current x-value\n distance = (x**2/2 - np.cos(5*x) - 7)\n speed = (x + 5*np.sin(5*x))\n\n # Append the calculated values to their respective lists\n distance_values.append(distance)\n speed_values.append(speed)\n\nOnce you have calculated the distance and speed values for each x-value, you can use these lists to create your DataFrame. You can then use the plot method of your DataFrame to create the graph.\nHere is an example of how you can create your DataFrame and plot the graph:\n# Create the DataFrame using the x-values, distance values, and speed values\ndf = pd.DataFrame({'Time': x_values, 'Distance': distance_values, 'Speed': speed_values})\n\n# Use the plot method of the DataFrame to create the graph\ndf.plot(title='Distance and speed', xlabel='Time (hours)', ylabel='Distance (km) / Speed (km/h)', x='Time')\n\n# Show the graph\nplt.show()\n\n\n", "Corrections to posted version\n\nUse variable t for time (rather than x)\nnp.arange(3, 6.01, 0.01) to get time from 3 to 6 inclusive\n\nCode\n# time values from 3 to 6 inclusive in steps of 0.01 (use 6.01 to include 6)\nt = np.arange(3, 6.01, 0.01) # t for time\n\n# Use NumPy array operations to compute distance and speed at all time values (i.e. x axis)\ndistance = (t**2/2 - np.cos(5*t) - 7)\nspeed = (t + 5*np.sin(5*t))\nvalues = {'Distance': distance, 'Speed': speed, 'Time': t} # x is time t\n\ndf = pd.DataFrame(data= values)\ndf.plot(title='Distance and speed', xlabel='Time (hours)', ylabel='Distance (km) / Speed (km/h)', x='Time')\n\nplt.show()\n\n\n" ]
[ 0, 0 ]
[]
[]
[ "graph", "matplotlib", "numpy", "pandas", "python" ]
stackoverflow_0074671475_graph_matplotlib_numpy_pandas_python.txt
Q: Can I create a decorated object based on a list? I have a program that can print a pizza with decorators. I have an interface: public interface PizzaPie{ String top(); } And an implementation of the interface public class PizzaPieImplementation implements PizzaPie{ @Override public String top() { return "Pie of pizza"; } } And an abstract class that implements it with the same object. public abstract class PizzaTopper implements PizzaPie{ private PizzaPie pizza; @Override public String top() { return pizza.top(); } } And I have several decorator classes, such as public class Onions extends PizzaTopper{ public Onions(PizzaPie pizza) { super(pizza); } public String top() { return super.top() + topWithOnions(); } private String topWithOnions() { return " with onions"; } And similar classes for peppers, pepperoni, anchovies, pineapple, etc. I have a list as follows: List<String> toppings = {onions, pineapple}; Is there a way to take each topping from the toppings list, and use that to create a new pizza with those toppings, to return something like: Pie of pizza with onions with pineapple The method would look something like this: public PizzaPie CreatePizzaWithUserInput(List<String> toppings) { //code } And ultimately it would create code that looks like this: PizzaPie pizza1 = new Onion(new Pineapple(new PizzaPieImplementation())); In theory this can be done with a lot of ugly if statements but I'm wondering if there's a quicker way of doing it. A: You could just make the member variable stored in PizzaTopper an array, and its constructor accept (PizzaPie... pizzas). Then, you could pass in an array of pizzas/toppings (anything implementing PizzaPie) and PizzaTopper.top() could return a runtime-generated concatenation of all of the PizzaPies' top() results.
Can I create a decorated object based on a list?
I have a program that can print a pizza with decorators. I have an interface: public interface PizzaPie{ String top(); } And an implementation of the interface public class PizzaPieImplementation implements PizzaPie{ @Override public String top() { return "Pie of pizza"; } } And an abstract class that implements it with the same object. public abstract class PizzaTopper implements PizzaPie{ private PizzaPie pizza; @Override public String top() { return pizza.top(); } } And I have several decorator classes, such as public class Onions extends PizzaTopper{ public Onions(PizzaPie pizza) { super(pizza); } public String top() { return super.top() + topWithOnions(); } private String topWithOnions() { return " with onions"; } And similar classes for peppers, pepperoni, anchovies, pineapple, etc. I have a list as follows: List<String> toppings = {onions, pineapple}; Is there a way to take each topping from the toppings list, and use that to create a new pizza with those toppings, to return something like: Pie of pizza with onions with pineapple The method would look something like this: public PizzaPie CreatePizzaWithUserInput(List<String> toppings) { //code } And ultimately it would create code that looks like this: PizzaPie pizza1 = new Onion(new Pineapple(new PizzaPieImplementation())); In theory this can be done with a lot of ugly if statements but I'm wondering if there's a quicker way of doing it.
[ "You could just make the member variable stored in PizzaTopper an array, and its constructor accept (PizzaPie... pizzas). Then, you could pass in an array of pizzas/toppings (anything implementing PizzaPie) and PizzaTopper.top() could return a runtime-generated concatenation of all of the PizzaPies' top() results.\n" ]
[ 0 ]
[]
[]
[ "decorator", "java" ]
stackoverflow_0074672631_decorator_java.txt
Q: How would you print a list (not java lingo, a literal list) more easily? I was working on a project, and thought, Couldn't there be an easier way to write a list without having to waste 3 minutes and one line of code? I'm probably wasting even more time here, but suppose I want to spell out "Hello, world!": class Main { public static void main(String[] args) { String[] array = {"H", "E", "L", "L", "O", ", ", "W", "O", "R", "L", "D", "!"}; for (int i = 0; i < array.length; i++) { System.out.print(array[i] + "-"); // prints "H-E-L-L-O-, -W-O-R-L-D-!-" } } } As you can see there's a nagging dash hanging over the edge at the end of the line. One idea I had was doing this: class Main { public static void main(String[] args) { String[] array = {"H", "E", "L", "L", "O", ", ", "W", "O", "R", "L", "D", "!"}; System.out.print(array[0]); // enter "H" early for (int i = 1; i < array.length; i++) { // int i = 0 -> int i = 1 System.out.print("-" + array[i]); // switched order, prints "H-E-L-L-O-, -W-O-R-L-D-!" } } } Yes, this does complete the job, but I feel like the extra line is clunky and awkward in my code. Also, I don't feel it's exactly flexible? If there's something inside the documentary junk or a trick I need, please let me know. :) A: You can print the dash before the list element and if the list element is the first one, you don't print anything. class Main { public static void main(String[] args) { String[] array = {"H", "E", "L", "L", "O", ", ", "W", "O", "R", "L", "D", "!"}; for (int i = 0; i < array.length; i++) { System.out.print((i == 0 ? "" : "-") + array[i]); // prints "H-E-L-L-O-, -W-O-R-L-D-!" } } } A: You can use the iterator i in a ternary expression (i == array.length - 1 ? "" : "-") as a substitute for the constant "-". This way, whether or not there is a dash is dynamic, based on whatever you want. This is adaptable to lots of different scenarios.
How would you print a list (not java lingo, a literal list) more easily?
I was working on a project, and thought, Couldn't there be an easier way to write a list without having to waste 3 minutes and one line of code? I'm probably wasting even more time here, but suppose I want to spell out "Hello, world!": class Main { public static void main(String[] args) { String[] array = {"H", "E", "L", "L", "O", ", ", "W", "O", "R", "L", "D", "!"}; for (int i = 0; i < array.length; i++) { System.out.print(array[i] + "-"); // prints "H-E-L-L-O-, -W-O-R-L-D-!-" } } } As you can see there's a nagging dash hanging over the edge at the end of the line. One idea I had was doing this: class Main { public static void main(String[] args) { String[] array = {"H", "E", "L", "L", "O", ", ", "W", "O", "R", "L", "D", "!"}; System.out.print(array[0]); // enter "H" early for (int i = 1; i < array.length; i++) { // int i = 0 -> int i = 1 System.out.print("-" + array[i]); // switched order, prints "H-E-L-L-O-, -W-O-R-L-D-!" } } } Yes, this does complete the job, but I feel like the extra line is clunky and awkward in my code. Also, I don't feel it's exactly flexible? If there's something inside the documentary junk or a trick I need, please let me know. :)
[ "You can print the dash before the list element and if the list element is the first one, you don't print anything.\nclass Main {\n public static void main(String[] args) {\n String[] array = {\"H\", \"E\", \"L\", \"L\", \"O\", \", \", \"W\", \"O\", \"R\", \"L\", \"D\", \"!\"};\n\n for (int i = 0; i < array.length; i++) { \n System.out.print((i == 0 ? \"\" : \"-\") + array[i]); // prints \"H-E-L-L-O-, -W-O-R-L-D-!\"\n }\n }\n}\n\n", "You can use the iterator i in a ternary expression (i == array.length - 1 ? \"\" : \"-\") as a substitute for the constant \"-\". This way, whether or not there is a dash is dynamic, based on whatever you want. This is adaptable to lots of different scenarios.\n" ]
[ 1, 0 ]
[]
[]
[ "arrays", "for_loop", "java" ]
stackoverflow_0074672444_arrays_for_loop_java.txt
Q: Rails 7 Jquery Not Working (Uncaught ReferenceError: $ is not defined) I have a Rails 7 app setup (without Turbo) but with Bootstrap and Jquery. The jquery is showing up in my sources tab under assets, but I'm still getting an error saying "Uncaught ReferenceError: $ is not defined" whenever I try to use jquery. A sample instance where this error appears is this code, on the $ before document: <script> $( document ).ready(function() { $('.sortable').railsSortable(); }); </script> This error goes away if I add jquery via a CDN on my application.html.erb like this: <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script> ....however that then starts producing all the weird errors you get when JQuery is present twice. I have the following in my application.js: import "controllers" import "jquery" import "jquery_ujs" import "popper" import "bootstrap" import "trix" import "@rails/actiontext" //= require jquery-ui //= require rails_sortable //= require activestorage //= require font_awesome5 window.jQuery = $; window.$ = $; Here's my config/importmap.rb: pin "application", preload: true pin_all_from "app/javascript/controllers", under: "controllers" pin "jquery", to: "jquery.min.js", preload: true pin "jquery_ujs", to: "jquery_ujs.js", preload: true pin "popper", to: "popper.js", preload: true pin "bootstrap", to: "bootstrap.min.js", preload: true pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true pin "trix" pin "@rails/actiontext", to: "actiontext.js" And here is my application.html.erb head section: <head> ... <%= if content_for?(:head) then yield(:head) end %> <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= stylesheet_link_tag "application" %> <%= javascript_importmap_tags %> <%= include_gon %> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> Can anyone see why this isn't working? I know there's no error in the JQuery script itself (because the error is called on any $), but I can't see why the JQuery that shows in the sources tab isn't being recognized. A: If you only need to use jQuery, change like this import jquery from "jquery" window.$ = jquery window.jQuery = jquery However, if you want to use jQuery-UI, too You need a workaround by creating a file to include the 3 lines above. // ./src/jquery.js import jquery from "jquery" window.$ = jquery window.jQuery = jquery And then in application.js import "./src/jquery" import "jquery-ui" This solution is actually from GoRails :D https://gorails.com/episodes/how-to-use-jquery-with-esbuild
Rails 7 Jquery Not Working (Uncaught ReferenceError: $ is not defined)
I have a Rails 7 app setup (without Turbo) but with Bootstrap and Jquery. The jquery is showing up in my sources tab under assets, but I'm still getting an error saying "Uncaught ReferenceError: $ is not defined" whenever I try to use jquery. A sample instance where this error appears is this code, on the $ before document: <script> $( document ).ready(function() { $('.sortable').railsSortable(); }); </script> This error goes away if I add jquery via a CDN on my application.html.erb like this: <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script> ....however that then starts producing all the weird errors you get when JQuery is present twice. I have the following in my application.js: import "controllers" import "jquery" import "jquery_ujs" import "popper" import "bootstrap" import "trix" import "@rails/actiontext" //= require jquery-ui //= require rails_sortable //= require activestorage //= require font_awesome5 window.jQuery = $; window.$ = $; Here's my config/importmap.rb: pin "application", preload: true pin_all_from "app/javascript/controllers", under: "controllers" pin "jquery", to: "jquery.min.js", preload: true pin "jquery_ujs", to: "jquery_ujs.js", preload: true pin "popper", to: "popper.js", preload: true pin "bootstrap", to: "bootstrap.min.js", preload: true pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true pin "trix" pin "@rails/actiontext", to: "actiontext.js" And here is my application.html.erb head section: <head> ... <%= if content_for?(:head) then yield(:head) end %> <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= stylesheet_link_tag "application" %> <%= javascript_importmap_tags %> <%= include_gon %> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> Can anyone see why this isn't working? I know there's no error in the JQuery script itself (because the error is called on any $), but I can't see why the JQuery that shows in the sources tab isn't being recognized.
[ "If you only need to use jQuery, change like this\nimport jquery from \"jquery\"\nwindow.$ = jquery\nwindow.jQuery = jquery\n\nHowever, if you want to use jQuery-UI, too\nYou need a workaround by creating a file to include the 3 lines above.\n// ./src/jquery.js\nimport jquery from \"jquery\"\nwindow.$ = jquery\nwindow.jQuery = jquery\n\nAnd then in application.js\nimport \"./src/jquery\"\nimport \"jquery-ui\"\n\nThis solution is actually from GoRails :D\nhttps://gorails.com/episodes/how-to-use-jquery-with-esbuild\n" ]
[ 0 ]
[]
[]
[ "jquery", "ruby_on_rails" ]
stackoverflow_0074594258_jquery_ruby_on_rails.txt
Q: SwiftUI DragGesture swallowed by ScrollView I want to register a certain drag gesture on any SwiftUI view, including ScrollViews simultaneously with any other gestures (i.e. without influencing existing gestures). However, when adding a DragGesture on a ScrollView as follows, it seems like the gesture is immediately swallowed by the ScrollView. ScrollView { Rectangle() .frame(width: 500, height: 500) } .simultaneousGesture( DragGesture() .onChanged { value in print("changed:", value.translation) } .onEnded { value in print("ended:", value.translation) } ) When I drag the Rectangle, this code prints: changed: (3.0, 16.666671752929688) for example. So onChanged is only called once, onEnded is never called. Is there a way to make DragGestures work with ScrollViews as well? Note: I tried to find a workaround with GestureState and the updating(_:) modifier as well, but it didn't work either. A: Yes, it is possible to use a DragGesture on a ScrollView in SwiftUI. You can do this by adding the DragGesture to the ScrollView's content, rather than the ScrollView itself. This allows the DragGesture to be recognized by the content of the ScrollView, while still allowing the ScrollView to handle its own gestures. Here is an example: ScrollView { Rectangle() .frame(width: 500, height: 500) .gesture( DragGesture() .onChanged { value in print("changed:", value.translation) } .onEnded { value in print("ended:", value.translation) } ) } When you drag the Rectangle in this example, the DragGesture will be recognized and you will see the "changed" and "ended" messages in the console output. It is important to note that using the simultaneousGesture modifier on a ScrollView will not work, as this modifier only allows multiple gestures to be recognized simultaneously on the same view. In this case, the DragGesture and the ScrollView's gesture are not on the same view, so the simultaneousGesture modifier will not have the desired effect.
SwiftUI DragGesture swallowed by ScrollView
I want to register a certain drag gesture on any SwiftUI view, including ScrollViews simultaneously with any other gestures (i.e. without influencing existing gestures). However, when adding a DragGesture on a ScrollView as follows, it seems like the gesture is immediately swallowed by the ScrollView. ScrollView { Rectangle() .frame(width: 500, height: 500) } .simultaneousGesture( DragGesture() .onChanged { value in print("changed:", value.translation) } .onEnded { value in print("ended:", value.translation) } ) When I drag the Rectangle, this code prints: changed: (3.0, 16.666671752929688) for example. So onChanged is only called once, onEnded is never called. Is there a way to make DragGestures work with ScrollViews as well? Note: I tried to find a workaround with GestureState and the updating(_:) modifier as well, but it didn't work either.
[ "Yes, it is possible to use a DragGesture on a ScrollView in SwiftUI. You can do this by adding the DragGesture to the ScrollView's content, rather than the ScrollView itself. This allows the DragGesture to be recognized by the content of the ScrollView, while still allowing the ScrollView to handle its own gestures. Here is an example:\n ScrollView {\n Rectangle()\n .frame(width: 500, height: 500)\n .gesture(\n DragGesture()\n .onChanged { value in\n print(\"changed:\", value.translation)\n }\n .onEnded { value in\n print(\"ended:\", value.translation)\n }\n )\n}\n\nWhen you drag the Rectangle in this example, the DragGesture will be recognized and you will see the \"changed\" and \"ended\" messages in the console output.\nIt is important to note that using the simultaneousGesture modifier on a ScrollView will not work, as this modifier only allows multiple gestures to be recognized simultaneously on the same view. In this case, the DragGesture and the ScrollView's gesture are not on the same view, so the simultaneousGesture modifier will not have the desired effect.\n" ]
[ 0 ]
[]
[]
[ "draggesture", "gesture", "scrollview", "swiftui" ]
stackoverflow_0071997556_draggesture_gesture_scrollview_swiftui.txt
Q: Swift UI: Apple Music API artwork quality is poor So I implemented this code to get the song artwork from Apple Music based on what song the user searched for. However, the album cover is extremely blurry even when it is merely 50x50 in size. I can't figure out what is causing this issue. import Foundation import SwiftUI class ArtworkLoader { private var dataTasks: [URLSessionDataTask] = [] func loadArtwork(forSong song: Song, completion: @escaping((Image?) -> Void)) { guard let imageUrl = URL(string: song.artworkUrl) else { completion(nil) return } let dataTask = URLSession.shared.dataTask(with: imageUrl) { data, _, _ in guard let data = data, let artwork = UIImage(data: data) else { completion(nil) return } let image = Image(uiImage: artwork) completion(image) } dataTasks.append(dataTask) dataTask.resume() } func reset() { dataTasks.forEach { $0.cancel() } dataTasks.removeAll() } } Album cover sample after using code above: A: Based on the apple music API documentation available here (https://developer.apple.com/documentation/applemusicapi/artwork), you must specify the width and height that you want the API to return. (Required) The URL to request the image asset. {w}x{h}must precede image filename, as placeholders for the width and height values as described above. For example, {w}x{h}bb.jpeg). The artwork object will also tell you what the maximum width and height values available for the given artwork are, via the height and width object properties.
Swift UI: Apple Music API artwork quality is poor
So I implemented this code to get the song artwork from Apple Music based on what song the user searched for. However, the album cover is extremely blurry even when it is merely 50x50 in size. I can't figure out what is causing this issue. import Foundation import SwiftUI class ArtworkLoader { private var dataTasks: [URLSessionDataTask] = [] func loadArtwork(forSong song: Song, completion: @escaping((Image?) -> Void)) { guard let imageUrl = URL(string: song.artworkUrl) else { completion(nil) return } let dataTask = URLSession.shared.dataTask(with: imageUrl) { data, _, _ in guard let data = data, let artwork = UIImage(data: data) else { completion(nil) return } let image = Image(uiImage: artwork) completion(image) } dataTasks.append(dataTask) dataTask.resume() } func reset() { dataTasks.forEach { $0.cancel() } dataTasks.removeAll() } } Album cover sample after using code above:
[ "Based on the apple music API documentation available here (https://developer.apple.com/documentation/applemusicapi/artwork), you must specify the width and height that you want the API to return.\n(Required) The URL to request the image asset. {w}x{h}must precede image filename, as placeholders for the width and height values as described above. For example, {w}x{h}bb.jpeg).\nThe artwork object will also tell you what the maximum width and height values available for the given artwork are, via the height and width object properties.\n" ]
[ 1 ]
[]
[]
[ "api", "apple_music", "swift", "swift3", "swiftui" ]
stackoverflow_0074672614_api_apple_music_swift_swift3_swiftui.txt
Q: Can't load Kernel binary: Invalid SDK hash in Flutter Whenever I try to run a dart tool like Dart Migrate I get the following error and I am unable to run that tool. Is there a way to solve this problem or I have to reinstall Flutter? Btw every thing is okay with Flutter Doctor A: After a lot of effort and wasting a lot of time on this issue I have been able to solve this problem. I have installed dart-sdk separately in the past and place the path of that dart-sdk at the top (before flutter one) in environment variables PATH. So I deleted that old dart-sdk path and deleted the respective folder this solved my problem. A: In VS Code, if you get "Can't Load Kernel binary: Invalid SDK Hash" in Flutter or Dart, update dart.sdkPath setting If you get this in VS Code, in addition to re-downloading the dart-sdk, make sure the "dart.sdkPath" setting in user/workspace settings is pointing to the new SDK. In my case, even though I had it in my path as in Junaid's answer, VS Code was still looking to the old dart-sdk folder and giving me the kernel hash error. I updated the dart.sdkPath to the correct path and restarted VS Code: For example, in Windows: Download dart sdk Unzip it to c:\tools\dart-sdk or any other folder (make sure you rename or delete the existing dart-sdk folder) ctrl-shift-p, type 'user settings (JSON)', open the json settings, and add: "dart.sdkPath": "C:\\tools\\dart-sdk", Update your system PATH environmental variable to point to the new dart-sdk and delete the reference to the old location. Restart VS Code. A: Note that Instead of This "dart.sdkPath": "D:\Dart\dart-sdk\bin" work well for me. path should be included '\bin' also. It work for me
Can't load Kernel binary: Invalid SDK hash in Flutter
Whenever I try to run a dart tool like Dart Migrate I get the following error and I am unable to run that tool. Is there a way to solve this problem or I have to reinstall Flutter? Btw every thing is okay with Flutter Doctor
[ "After a lot of effort and wasting a lot of time on this issue I have been able to solve this problem. I have installed dart-sdk separately in the past and place the path of that dart-sdk at the top (before flutter one) in environment variables PATH. So I deleted that old dart-sdk path and deleted the respective folder this solved my problem.\n", "In VS Code, if you get \"Can't Load Kernel binary: Invalid SDK Hash\" in Flutter or Dart, update dart.sdkPath setting\nIf you get this in VS Code, in addition to re-downloading the dart-sdk, make sure the \"dart.sdkPath\" setting in user/workspace settings is pointing to the new SDK. In my case, even though I had it in my path as in Junaid's answer, VS Code was still looking to the old dart-sdk folder and giving me the kernel hash error. I updated the dart.sdkPath to the correct path and restarted VS Code:\nFor example, in Windows:\n\nDownload dart sdk\n\nUnzip it to c:\\tools\\dart-sdk or any other folder (make sure you rename or delete the existing dart-sdk folder)\n\nctrl-shift-p, type 'user settings (JSON)', open the json settings, and add:\n\n\n \"dart.sdkPath\": \"C:\\\\tools\\\\dart-sdk\",\n\n\n\nUpdate your system PATH environmental variable to point to the new dart-sdk and delete the reference to the old location.\n\nRestart VS Code.\n\n\n", "Note that Instead of This \"dart.sdkPath\": \"D:\\Dart\\dart-sdk\\bin\" work well for me.\npath should be included '\\bin' also. It work for me\n" ]
[ 8, 1, 0 ]
[]
[]
[ "dart", "dart_null_safety", "flutter" ]
stackoverflow_0067074432_dart_dart_null_safety_flutter.txt
Q: Find names in string and combinations & lookup for value - Google Sheets I've a data set with list of names & combinations and need to map with the team. For ex, if the list of name is unique, then it should give me team name.. If the name of combination from team, it should give same team name.. Combination between two teams, then it should say team C. Here is the trix for ref: https://docs.google.com/spreadsheets/d/1leb0hQ5gb6RclcMb__JYJLqvIFBQD_B3v7c2o4PbICg/edit#gid=0 I tried lookup, but it is fulling first case but not the people combination. Is there any way I can achieve this. Also, I assume these names are separated by ascii CHAR(10). Let me know any inputs or suggestions so I can fulfil this. A: You can try with this formula. It's a little long but splits the value of each cell, joins them to see if they're unique or not, and then applies C if they aren't: =BYROW(A2:A,lambda(val,IF(val="","",lambda(results,SI(COUNTA(results)=1,results,"C"))(UNIQUE(transpose(ARRAYFORMULA(VLOOKUP (SPLIT(val,CHAR(10)),E$2:F,2,0)))))))) A: You may use below formula- =IFERROR(BYROW(A2:INDEX(A2:A,COUNTA(A2:A)),LAMBDA(x,UNIQUE(INDEX(XLOOKUP(FLATTEN(SPLIT(x,CHAR(10))),E2:E7,F2:F7,,0))))),"C") Here A2:INDEX(A2:A,COUNTA(A2:A)) will return a array of values as well cell reference from A2 to last non empty cell in column A (Assume you do not have any blank rows inside data). If you have blank row, then you have to use different approach. See this post by @TheMaster Then LAMBDA() will apply XLOOKUP() function for each cell of A column. SPLIT() will separate all values from cell using line break CHAR(10) delimiter. XLOOKUP() will search for name and return team. For multiple names, UNIQUE() function will return only unique teams. Finaly BYROW() will return that unique team. If there are more than 1 teams, then BYROW() will through error. IFERROR() will catch that error and return C as result/exception.
Find names in string and combinations & lookup for value - Google Sheets
I've a data set with list of names & combinations and need to map with the team. For ex, if the list of name is unique, then it should give me team name.. If the name of combination from team, it should give same team name.. Combination between two teams, then it should say team C. Here is the trix for ref: https://docs.google.com/spreadsheets/d/1leb0hQ5gb6RclcMb__JYJLqvIFBQD_B3v7c2o4PbICg/edit#gid=0 I tried lookup, but it is fulling first case but not the people combination. Is there any way I can achieve this. Also, I assume these names are separated by ascii CHAR(10). Let me know any inputs or suggestions so I can fulfil this.
[ "You can try with this formula. It's a little long but splits the value of each cell, joins them to see if they're unique or not, and then applies C if they aren't:\n=BYROW(A2:A,lambda(val,IF(val=\"\",\"\",lambda(results,SI(COUNTA(results)=1,results,\"C\"))(UNIQUE(transpose(ARRAYFORMULA(VLOOKUP (SPLIT(val,CHAR(10)),E$2:F,2,0))))))))\n\n", "You may use below formula-\n=IFERROR(BYROW(A2:INDEX(A2:A,COUNTA(A2:A)),LAMBDA(x,UNIQUE(INDEX(XLOOKUP(FLATTEN(SPLIT(x,CHAR(10))),E2:E7,F2:F7,,0))))),\"C\")\n\n\nHere A2:INDEX(A2:A,COUNTA(A2:A)) will return a array of values as well cell reference from A2 to last non empty cell in column A (Assume you do not have any blank rows inside data). If you have blank row, then you have to use different approach. See this post by @TheMaster\n\nThen LAMBDA() will apply XLOOKUP() function for each cell of A column.\n\nSPLIT() will separate all values from cell using line break CHAR(10) delimiter.\n\nXLOOKUP() will search for name and return team.\n\nFor multiple names, UNIQUE() function will return only unique teams.\n\nFinaly BYROW() will return that unique team. If there are more than 1 teams, then BYROW() will through error.\n\nIFERROR() will catch that error and return C as result/exception.\n\n\n\n" ]
[ 1, 1 ]
[]
[]
[ "google_sheets" ]
stackoverflow_0074672508_google_sheets.txt
Q: Flutter [webview_flutter] How do javascriptChannels work with ports? Working with the flutter plugin: webview_flutter All the examples for sending data from JS to webview_flutter have similar syntax: Webpage: <script> toFlutter.postMessage('{"name":"Hello World"}'); </script> Flutter: javascriptChannels: { JavascriptChannel( name: 'toFlutter', onMessageReceived: (message) async { print('Javascript: "${message.message}"'); }, ), }, That works, except... Now that webpage gives me a JS error if viewed in a webbrowser. (preventing other JS from running) The correct (javascript) syntax for a javascriptChannel seems to be something like: <script> var toFlutter = new MessageChannel(); toFlutter.port1.postMessage('{"name":"Hello World"}'); </script> That works inside a webbrowser, but now webview_flutter is of course not happy. Obviously there are ways to work around this, I'm just asking: Did I miss something in the documentation? Is there a way to specify both a channel name and a port in webview_flutter? A: This article should be helpful: https://medium.com/flutter-community/flutter-webview-javascript-communication-inappwebview-5-403088610949 in Short: It shows 3 method to communicate with the JS code. One of which uses the message channel just like iFrames. That way you can reuse almost the same structure form your html-targeted dart code.
Flutter [webview_flutter] How do javascriptChannels work with ports?
Working with the flutter plugin: webview_flutter All the examples for sending data from JS to webview_flutter have similar syntax: Webpage: <script> toFlutter.postMessage('{"name":"Hello World"}'); </script> Flutter: javascriptChannels: { JavascriptChannel( name: 'toFlutter', onMessageReceived: (message) async { print('Javascript: "${message.message}"'); }, ), }, That works, except... Now that webpage gives me a JS error if viewed in a webbrowser. (preventing other JS from running) The correct (javascript) syntax for a javascriptChannel seems to be something like: <script> var toFlutter = new MessageChannel(); toFlutter.port1.postMessage('{"name":"Hello World"}'); </script> That works inside a webbrowser, but now webview_flutter is of course not happy. Obviously there are ways to work around this, I'm just asking: Did I miss something in the documentation? Is there a way to specify both a channel name and a port in webview_flutter?
[ "This article should be helpful:\nhttps://medium.com/flutter-community/flutter-webview-javascript-communication-inappwebview-5-403088610949\nin Short: It shows 3 method to communicate with the JS code. One of which uses the message channel just like iFrames.\nThat way you can reuse almost the same structure form your html-targeted dart code.\n" ]
[ 0 ]
[]
[]
[ "dart", "flutter", "webview_flutter" ]
stackoverflow_0070288778_dart_flutter_webview_flutter.txt
Q: Stack-Fields not displaying in create/edit page in Laravel Nova I have this field function inside my Resource: public function fields(Request $request) { return [ ID::make(__('ID'), 'id')->sortable(), Stack::make('Headings', [ Text::make('Heading (en)'), Text::make('Heading (de)'), Text::make('Heading (ar)'), ]), Stack::make('Content', [ Text::make('Content (en)'), Text::make('Content (de)'), Text::make('Content (ar)'), ]), Image::make('Image')->disk('public')->prunable(), ]; } which produces this view: but as soon as I want to create/edit an entry, it only shows the image field and not the heading/content text fields: This problem occurs since I implemented the Stack Fields. A: By default, the Stack field is not shown on forms and showOnUpdating() method doesn't work. The only solution I found by now is to insert the field I need in the Stack one and then recall them later with a hideFromIndex() method. Per your code: Stack::make('Titoli', [ Text::make('Titolo', 'title'), Slug::make('Slug', 'slug')->from('title'), ]) ->sortable(), Text::make('Titolo', 'title') ->rules('required', 'max:255') ->hideFromIndex(), Slug::make('Slug', 'slug')->from('title') ->hideFromIndex(), Not much elegant, but it works. A: reference @rx4storm solution, write a helper to keep thing easy :) <?php trait HasStackFieldPatcher { public function stackFieldPatch($fields): array { $patchFields = []; foreach ($fields as $field) { if (get_class($field) == 'Laravel\Nova\Fields\Stack') { $patchFields[] = $field->hideFromDetail(); foreach ($field->lines as $lineField) { if ($lineField->showOnCreation !== false || $lineField->showOnUpdate !== false) { $cloneField = clone $lineField; $cloneField ->hideFromIndex() ->hideFromDetail(); $patchFields[] = $cloneField; } } } else { $patchFields[] = $field; } } return $patchFields; } } and then use HasStackFieldPatcher via stackFieldPatch() to patch fields in your resource. use App\Nova\HasStackFieldPatcher; /** * call `stackFieldPatch` to patch stack fields */ public function fields(Request $request) { return $this->stackFieldPatch([ ID::make(__('ID'), 'id')->sortable(), Stack::make('Headings', [ Text::make('Heading (en)'), Text::make('Heading (de)'), Text::make('Heading (ar)'), ]), Stack::make('Content', [ Text::make('Content (en)'), Text::make('Content (de)'), Text::make('Content (ar)'), ]), Image::make('Image')->disk('public')->prunable(), ]); } But it might be better to use the official solution: Dynamic Field Methods fieldsForIndex fieldsForDetail fieldsForInlineCreate fieldsForCreate fieldsForUpdate fieldsForPreview
Stack-Fields not displaying in create/edit page in Laravel Nova
I have this field function inside my Resource: public function fields(Request $request) { return [ ID::make(__('ID'), 'id')->sortable(), Stack::make('Headings', [ Text::make('Heading (en)'), Text::make('Heading (de)'), Text::make('Heading (ar)'), ]), Stack::make('Content', [ Text::make('Content (en)'), Text::make('Content (de)'), Text::make('Content (ar)'), ]), Image::make('Image')->disk('public')->prunable(), ]; } which produces this view: but as soon as I want to create/edit an entry, it only shows the image field and not the heading/content text fields: This problem occurs since I implemented the Stack Fields.
[ "By default, the Stack field is not shown on forms and showOnUpdating() method doesn't work.\nThe only solution I found by now is to insert the field I need in the Stack one and then recall them later with a hideFromIndex() method.\nPer your code:\n Stack::make('Titoli', [\n Text::make('Titolo', 'title'),\n\n Slug::make('Slug', 'slug')->from('title'),\n ])\n ->sortable(),\n\n Text::make('Titolo', 'title')\n ->rules('required', 'max:255')\n ->hideFromIndex(),\n\n Slug::make('Slug', 'slug')->from('title')\n ->hideFromIndex(),\n\nNot much elegant, but it works.\n", "reference @rx4storm solution, write a helper to keep thing easy :)\n<?php\ntrait HasStackFieldPatcher\n{\n public function stackFieldPatch($fields): array\n {\n $patchFields = [];\n foreach ($fields as $field) {\n if (get_class($field) == 'Laravel\\Nova\\Fields\\Stack') {\n $patchFields[] = $field->hideFromDetail();\n foreach ($field->lines as $lineField) {\n if ($lineField->showOnCreation !== false ||\n $lineField->showOnUpdate !== false) {\n \n $cloneField = clone $lineField;\n $cloneField\n ->hideFromIndex()\n ->hideFromDetail();\n $patchFields[] = $cloneField;\n }\n }\n } else {\n $patchFields[] = $field;\n }\n }\n return $patchFields;\n }\n}\n\nand then use HasStackFieldPatcher via stackFieldPatch() to patch fields in your resource.\n\nuse App\\Nova\\HasStackFieldPatcher;\n\n/**\n * call `stackFieldPatch` to patch stack fields\n */\npublic function fields(Request $request)\n{\n return $this->stackFieldPatch([\n ID::make(__('ID'), 'id')->sortable(),\n Stack::make('Headings', [\n Text::make('Heading (en)'),\n Text::make('Heading (de)'),\n Text::make('Heading (ar)'),\n ]),\n Stack::make('Content', [\n Text::make('Content (en)'),\n Text::make('Content (de)'),\n Text::make('Content (ar)'),\n ]),\n Image::make('Image')->disk('public')->prunable(),\n ]);\n}\n\nBut it might be better to use the official solution: Dynamic Field Methods\nfieldsForIndex\nfieldsForDetail\nfieldsForInlineCreate\nfieldsForCreate\nfieldsForUpdate\nfieldsForPreview\n\n" ]
[ 0, 0 ]
[]
[]
[ "laravel", "laravel_nova", "vue.js", "vuejs3" ]
stackoverflow_0069698569_laravel_laravel_nova_vue.js_vuejs3.txt
Q: Is there any issue with learning .Net framework 4.0 now? I have been watching videos of C#.net, Asp.net, and MVC from the kudvenkat youtube channel this man is so brilliant at teaching dot net technology but kudvenkat`s dot net videos are from 2012 and I think there will be dot net version 4.0 but still, currently so many peoples are learning dot net from him so here I want to know if there any issues with dot net version and can I still learn from him? A: Yes, .NET 4 is very outdated and the company no longer supports this. Going forward, ".NET" is now .NET 6 with LTS support and .NET 7. I think in general, the problem with the old classic framework was the fact that it only ran on Windows. This was a big blocker for tech that wanted to scale apps using Linux, for example. Cloud tech is another example where net6 and net7 do much better as well.
Is there any issue with learning .Net framework 4.0 now?
I have been watching videos of C#.net, Asp.net, and MVC from the kudvenkat youtube channel this man is so brilliant at teaching dot net technology but kudvenkat`s dot net videos are from 2012 and I think there will be dot net version 4.0 but still, currently so many peoples are learning dot net from him so here I want to know if there any issues with dot net version and can I still learn from him?
[ "Yes, .NET 4 is very outdated and the company no longer supports this. Going forward, \".NET\" is now .NET 6 with LTS support and .NET 7. I think in general, the problem with the old classic framework was the fact that it only ran on Windows. This was a big blocker for tech that wanted to scale apps using Linux, for example. Cloud tech is another example where net6 and net7 do much better as well.\n" ]
[ 1 ]
[]
[]
[ ".net", "asp.net", "asp.net_mvc", "c#" ]
stackoverflow_0074672788_.net_asp.net_asp.net_mvc_c#.txt
Q: Filtering a dataframe using a list of values as parameter I have this dataframe: id check_id 1 10 1 100 2 10 3 34 4 12 1 101 and a list: list=[10,101] I am trying to filter this df like this: df[(df['id']==1) and (df['check_id'].isin(list))] To get this output: id check_id 1 10 1 101 but I get this error msg: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I've been trying to solve it but no sucess so far. How can I fix it? A: If you had searched instead of asking the question, you would have easily got the answer df[(df['id']==1) & (df['check_id'].isin(list))] A: With reference to this article , the query should be: df[(df['id']==1) & (df['check_id'].isin(list))]
Filtering a dataframe using a list of values as parameter
I have this dataframe: id check_id 1 10 1 100 2 10 3 34 4 12 1 101 and a list: list=[10,101] I am trying to filter this df like this: df[(df['id']==1) and (df['check_id'].isin(list))] To get this output: id check_id 1 10 1 101 but I get this error msg: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I've been trying to solve it but no sucess so far. How can I fix it?
[ "If you had searched instead of asking the question, you would have easily got the answer\ndf[(df['id']==1) & (df['check_id'].isin(list))]\n\n", "With reference to this article\n, the query should be:\ndf[(df['id']==1) & (df['check_id'].isin(list))]\n\n" ]
[ 0, 0 ]
[]
[]
[ "jupyter_notebook", "pandas", "python_3.x" ]
stackoverflow_0074672648_jupyter_notebook_pandas_python_3.x.txt
Q: RN None of these files exist: * aws-exports I initialized a new react native project with Amplify. npm install -g @aws-amplify/cli amplify configure npm install -g expo-cli expo init RNAmplify cd RNAmplify amplify init npm install aws-amplify aws-amplify-react-native @react-native-community/netinfo @react-native-async-storage/async-storage import Amplify from 'aws-amplify' import config from './aws-exports' Amplify.configure(config) And I keep getting this response when I reload the app. The aws-amplify, aws-amplify-react-native are present in the node_modules directory. Unable to resolve module ./aws-exports from C:\Users\Masi\IdeaProjects\RNAmplify\App.js: None of these files exist: * aws-exports(.native|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json) * aws-exports\index(.native|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json) A: Look in folder "src" A: What helped me was that I actually needed to run amplify init which creates an amplify folder for you after you answer a few questions.
RN None of these files exist: * aws-exports
I initialized a new react native project with Amplify. npm install -g @aws-amplify/cli amplify configure npm install -g expo-cli expo init RNAmplify cd RNAmplify amplify init npm install aws-amplify aws-amplify-react-native @react-native-community/netinfo @react-native-async-storage/async-storage import Amplify from 'aws-amplify' import config from './aws-exports' Amplify.configure(config) And I keep getting this response when I reload the app. The aws-amplify, aws-amplify-react-native are present in the node_modules directory. Unable to resolve module ./aws-exports from C:\Users\Masi\IdeaProjects\RNAmplify\App.js: None of these files exist: * aws-exports(.native|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json) * aws-exports\index(.native|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json)
[ "Look in folder \"src\"\n", "What helped me was that I actually needed to run amplify init which creates an amplify folder for you after you answer a few questions.\n" ]
[ 1, 0 ]
[]
[]
[ "aws_amplify", "aws_amplify_cli", "aws_amplify_sdk_android", "react_native" ]
stackoverflow_0068302950_aws_amplify_aws_amplify_cli_aws_amplify_sdk_android_react_native.txt
Q: Minimum cost path on a undirected weighted graph using an adjacency list I have implemented a minimum cost path function to my undirected weighted graph using an adjacency list. My approach of the minimum cost path function does not use a priority queue. My goal is to calculate and display the shortest path from a starting node. I'm able to calculate the shortest path starting at node A, however, the order of the nodes does not match the order of the nodes. Would it be better if I implemented a priority queue? Any help would be appreciated! The minimum cost paths starting at A Expected B(4) C(12) D(19) E(21) F(11) G(9) H(8) I(14) J(inf) Actually B(4) H(8) C(12) G(9) I(14) D(19) F(11) E(21) The adjacency list: A- {'B': 4, 'H': 8} B- {'A': 4, 'C': 8, 'H': 11} C- {'B': 8, 'D': 7, 'F': 4, 'I': 2} D- {'C': 7, 'E': 9, 'F': 14} E- {'D': 9, 'F': 10} F- {'C': 4, 'D': 14, 'E': 10, 'G': 2} G- {'F': 2, 'H': 1, 'I': 6} H- {'A': 8, 'B': 11, 'G': 1, 'I': 7} I- {'C': 2, 'G': 6, 'H': 7} J- {} My code class WGraph: def __init__(self, size=10): self.size = 10 self.nodeList = {} self.adjacencyMatrix = [[0] * size for i in range(size)] # initialize matrix def addNode(self, name): """Adds node to adjacency list""" self.nodeList[name] = {} def addEdge(self, startIndex, endIndex, weight): """Add edges for adjacency list and matrix""" self.nodeList[startIndex][endIndex] = weight self.nodeList[endIndex][startIndex] = weight index1 = list(self.nodeList.keys()).index(startIndex) index2 = list(self.nodeList.keys()).index(endIndex) self.adjacencyMatrix[index1][index2] = weight def displayAdjacency(self): """Displays adjacency list with edges and weight""" for node in self.nodeList: print(node + "- " + str(self.nodeList[node])) def minCostPaths(self, vertex): visited = {vertex: 0} queue = [(vertex, 0)] while queue: node, cost = queue.pop(0) for neighbor in self.nodeList[node]: if neighbor not in visited or cost + self.nodeList[node][neighbor] < visited[neighbor]: visited[neighbor] = cost + self.nodeList[node][neighbor] queue.append((neighbor, cost + self.nodeList[node][neighbor])) output = "" for node in visited: if node != vertex: output += f"{node}({visited[node]}) " return output[:-2] + ")" # Driver Code graph = WGraph() graph.addNode('A') graph.addNode('B') graph.addNode('C') graph.addNode('D') graph.addNode('E') graph.addNode('F') graph.addNode('G') graph.addNode('H') graph.addNode('I') graph.addNode('J') graph.addEdge('A', 'B', 4) graph.addEdge('A', 'H', 8) graph.addEdge('B', 'C', 8) graph.addEdge('B', 'H', 11) graph.addEdge('C', 'D', 7) graph.addEdge('C', 'F', 4) graph.addEdge('C', 'I', 2) graph.addEdge('D', 'E', 9) graph.addEdge('D', 'F', 14) graph.addEdge('E', 'F', 10) graph.addEdge('F', 'G', 2) graph.addEdge('G', 'H', 1) graph.addEdge('G', 'I', 6) graph.addEdge('H', 'I', 7) graph.displayAdjacency() print("The minimum cost paths starting at A ") print(" Expected B(4) C(12) D(19) E(21) F(11) G(9) H(8) I(14) J(inf) ") print(" Actually " + graph.minCostPaths('A'), end="\n") A: In your minCostPaths() function, you need to get the list of vertices from self.nodeList, not from visited. The order of BFS traversal is stored in visited, which isn't the ordering you need. output = "" for node in self.nodeList: if node != vertex: output += f"{node}({visited.get(node, 'inf')}) " return output[:-2] + ")" Output: The minimum cost paths starting at A Expected B(4) C(12) D(19) E(21) F(11) G(9) H(8) I(14) J(inf) Actually B(4) C(12) D(19) E(21) F(11) G(9) H(8) I(14) J(inf)
Minimum cost path on a undirected weighted graph using an adjacency list
I have implemented a minimum cost path function to my undirected weighted graph using an adjacency list. My approach of the minimum cost path function does not use a priority queue. My goal is to calculate and display the shortest path from a starting node. I'm able to calculate the shortest path starting at node A, however, the order of the nodes does not match the order of the nodes. Would it be better if I implemented a priority queue? Any help would be appreciated! The minimum cost paths starting at A Expected B(4) C(12) D(19) E(21) F(11) G(9) H(8) I(14) J(inf) Actually B(4) H(8) C(12) G(9) I(14) D(19) F(11) E(21) The adjacency list: A- {'B': 4, 'H': 8} B- {'A': 4, 'C': 8, 'H': 11} C- {'B': 8, 'D': 7, 'F': 4, 'I': 2} D- {'C': 7, 'E': 9, 'F': 14} E- {'D': 9, 'F': 10} F- {'C': 4, 'D': 14, 'E': 10, 'G': 2} G- {'F': 2, 'H': 1, 'I': 6} H- {'A': 8, 'B': 11, 'G': 1, 'I': 7} I- {'C': 2, 'G': 6, 'H': 7} J- {} My code class WGraph: def __init__(self, size=10): self.size = 10 self.nodeList = {} self.adjacencyMatrix = [[0] * size for i in range(size)] # initialize matrix def addNode(self, name): """Adds node to adjacency list""" self.nodeList[name] = {} def addEdge(self, startIndex, endIndex, weight): """Add edges for adjacency list and matrix""" self.nodeList[startIndex][endIndex] = weight self.nodeList[endIndex][startIndex] = weight index1 = list(self.nodeList.keys()).index(startIndex) index2 = list(self.nodeList.keys()).index(endIndex) self.adjacencyMatrix[index1][index2] = weight def displayAdjacency(self): """Displays adjacency list with edges and weight""" for node in self.nodeList: print(node + "- " + str(self.nodeList[node])) def minCostPaths(self, vertex): visited = {vertex: 0} queue = [(vertex, 0)] while queue: node, cost = queue.pop(0) for neighbor in self.nodeList[node]: if neighbor not in visited or cost + self.nodeList[node][neighbor] < visited[neighbor]: visited[neighbor] = cost + self.nodeList[node][neighbor] queue.append((neighbor, cost + self.nodeList[node][neighbor])) output = "" for node in visited: if node != vertex: output += f"{node}({visited[node]}) " return output[:-2] + ")" # Driver Code graph = WGraph() graph.addNode('A') graph.addNode('B') graph.addNode('C') graph.addNode('D') graph.addNode('E') graph.addNode('F') graph.addNode('G') graph.addNode('H') graph.addNode('I') graph.addNode('J') graph.addEdge('A', 'B', 4) graph.addEdge('A', 'H', 8) graph.addEdge('B', 'C', 8) graph.addEdge('B', 'H', 11) graph.addEdge('C', 'D', 7) graph.addEdge('C', 'F', 4) graph.addEdge('C', 'I', 2) graph.addEdge('D', 'E', 9) graph.addEdge('D', 'F', 14) graph.addEdge('E', 'F', 10) graph.addEdge('F', 'G', 2) graph.addEdge('G', 'H', 1) graph.addEdge('G', 'I', 6) graph.addEdge('H', 'I', 7) graph.displayAdjacency() print("The minimum cost paths starting at A ") print(" Expected B(4) C(12) D(19) E(21) F(11) G(9) H(8) I(14) J(inf) ") print(" Actually " + graph.minCostPaths('A'), end="\n")
[ "In your minCostPaths() function, you need to get the list of vertices from self.nodeList, not from visited. The order of BFS traversal is stored in visited, which isn't the ordering you need.\n output = \"\"\n for node in self.nodeList:\n if node != vertex:\n output += f\"{node}({visited.get(node, 'inf')}) \"\n return output[:-2] + \")\"\n\nOutput:\nThe minimum cost paths starting at A \n Expected B(4) C(12) D(19) E(21) F(11) G(9) H(8) I(14) J(inf) \n Actually B(4) C(12) D(19) E(21) F(11) G(9) H(8) I(14) J(inf)\n\n" ]
[ 1 ]
[]
[]
[ "adjacency_list", "algorithm", "graph", "python_3.x", "weighted_graph" ]
stackoverflow_0074672686_adjacency_list_algorithm_graph_python_3.x_weighted_graph.txt
Q: Removing duplicate blank lines with awk For one of my problems for class, I have a file where I am to delete duplicate blank lines in a file. so for example, I have an input file that looks like this: Sample Line 1 Sample line 2 Sample line 3 and the output would then turn all multiple blank lines into a singular one, so the output file would look like this: Sample Line 1 Sample line 2 Sample line 3 I've been able to complete this with a sed command, but the problem insists that I use awk in order to obtain this output. The closest I've gotten has been with awk '!x[$0]++', but that simply deletes pretty much every blank line. I feel like I'm missing something basic. Thanks for any help! A: $ awk 'NF{c=1} (c++)<3' file Sample Line 1 Sample line 2 Sample line 3 or if you don't mind an extra blank line at the end: $ awk -v RS= -v ORS='\n\n' '1' file Sample Line 1 Sample line 2 Sample line 3 A: Could you please try following. awk '!NF{found++} found>1 && !NF{next} NF{found=""} 1' Input_file Output will be as follows. Sample Line 1 Sample line 2 Sample line 3 A: This also works if the file has duplicate lines at beginning or end. awk ' NF==0{ if (! blank) {print;blank=1} next } {blank=0;print} ' file The base for its operation is that NF is zero for every blank/empty line with the default awk separator. For example, if file is: Sample Line 1 Sample line 2 Sample line 3 Sample line 4 it becomes Sample Line 1 Sample line 2 Sample line 3 Sample line 4 A: awk 'NF || p; { p = NF }' p=1 file For modifying multiple files at once: gawk -i inplace 'BEGINFILE { p = 1 } NF || p; { p = NF }' file ... Exclude p=1 or set initial value of p to 0 to also remove starting blank lines. A: 1 2 3 Sample Line 1 4 5 6 7 Sample line 2 8 9 10 11 12 Sample line 3 13 Sample Line 4 14 15 mawk 'ORS = "\n\n"' RS= 1 Sample Line 1 2 3 Sample line 2 4 5 Sample line 3 6 Sample Line 4 7
Removing duplicate blank lines with awk
For one of my problems for class, I have a file where I am to delete duplicate blank lines in a file. so for example, I have an input file that looks like this: Sample Line 1 Sample line 2 Sample line 3 and the output would then turn all multiple blank lines into a singular one, so the output file would look like this: Sample Line 1 Sample line 2 Sample line 3 I've been able to complete this with a sed command, but the problem insists that I use awk in order to obtain this output. The closest I've gotten has been with awk '!x[$0]++', but that simply deletes pretty much every blank line. I feel like I'm missing something basic. Thanks for any help!
[ "$ awk 'NF{c=1} (c++)<3' file\nSample Line 1\n\nSample line 2\n\nSample line 3\n\nor if you don't mind an extra blank line at the end:\n$ awk -v RS= -v ORS='\\n\\n' '1' file\nSample Line 1\n\nSample line 2\n\nSample line 3\n\n", "Could you please try following.\nawk '!NF{found++} found>1 && !NF{next} NF{found=\"\"} 1' Input_file\n\nOutput will be as follows.\nSample Line 1\n\nSample line 2\n\nSample line 3\n\n", "This also works if the file has duplicate lines at beginning or end.\nawk '\nNF==0{\n if (! blank) {print;blank=1}\n next\n}\n{blank=0;print}\n' file\n\nThe base for its operation is that NF is zero for every blank/empty line with the default awk separator.\n\nFor example, if file is:\n\n\nSample Line 1\n\n\n\nSample line 2\n\nSample line 3\nSample line 4\n\n\n\nit becomes\n\nSample Line 1\n\nSample line 2\n\nSample line 3\nSample line 4\n\n\n", "awk 'NF || p; { p = NF }' p=1 file\n\nFor modifying multiple files at once:\ngawk -i inplace 'BEGINFILE { p = 1 } NF || p; { p = NF }' file ...\n\nExclude p=1 or set initial value of p to 0 to also remove starting blank lines.\n", " 1 \n 2 \n 3 Sample Line 1\n 4 \n 5 \n 6 \n 7 Sample line 2\n 8 \n 9 \n10 \n11 \n12 Sample line 3\n13 Sample Line 4\n14 \n15\n\n\nmawk 'ORS = \"\\n\\n\"' RS=\n\n\n 1 Sample Line 1\n 2 \n 3 Sample line 2\n 4 \n 5 Sample line 3\n 6 Sample Line 4\n 7\n\n" ]
[ 5, 3, 1, 1, 0 ]
[]
[]
[ "awk" ]
stackoverflow_0061048751_awk.txt
Q: Does anyone know how to fix Error 1103 in MySQL? I am quite new to MySQL, I downloaded the file and then opened it in SQL I ran it, but it didn't work and stated the following Error Code: 1103. Incorrect table name 'campaign';/!40101 SET @saved_cs_client = @@character_set_client /;/!40101 SET character_set' This is where I believe the problem is DROP TABLE IF EXISTS `campaign'; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `campaign` ( `id` bigint(20) NOT NULL, `name` text, `sub_category_id` bigint(20) DEFAULT NULL, `country_id` bigint(20) DEFAULT NULL, `currency_id` bigint(20) DEFAULT NULL, `launched` datetime DEFAULT NULL, `deadline` datetime DEFAULT NULL, `goal` double DEFAULT NULL, `pledged` double DEFAULT NULL, `backers` bigint(20) DEFAULT NULL, `outcome` text, PRIMARY KEY (`id`), KEY `country_id` (`country_id`), KEY `sub_category_id` (`sub_category_id`), KEY `currency_id` (`currency_id`), CONSTRAINT `campaign_ibfk_1` FOREIGN KEY (`country_id`) REFERENCES `country` (`id`), CONSTRAINT `campaign_ibfk_2` FOREIGN KEY (`sub_category_id`) REFERENCES `sub_category` (`id`), CONSTRAINT `campaign_ibfk_3` FOREIGN KEY (`currency_id`) REFERENCES `currency` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; Dumping data for table `campaign` -- LOCK TABLES `campaign` WRITE; /*!40000 ALTER TABLE `campaign` DISABLE KEYS */; INSERT INTO `campaign` VALUES (1,'Ragdolls',23,2,2) INSERT INTO `campaign` VALUES (8667,'Blank Screen Films Summer Project 2013') /*!40000 ALTER TABLE `campaign` ENABLE KEYS */; UNLOCK TABLES; Feel free to ask any question to attain more insight. A: Where you have: DROP TABLE IF EXISTS `campaign'; this is supposed to be: DROP TABLE IF EXISTS `campaign`; Either you accidentally changed the backtick to a single quote, or something in your "downloaded the file and then opened it in SQL" changed it on you.
Does anyone know how to fix Error 1103 in MySQL?
I am quite new to MySQL, I downloaded the file and then opened it in SQL I ran it, but it didn't work and stated the following Error Code: 1103. Incorrect table name 'campaign';/!40101 SET @saved_cs_client = @@character_set_client /;/!40101 SET character_set' This is where I believe the problem is DROP TABLE IF EXISTS `campaign'; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `campaign` ( `id` bigint(20) NOT NULL, `name` text, `sub_category_id` bigint(20) DEFAULT NULL, `country_id` bigint(20) DEFAULT NULL, `currency_id` bigint(20) DEFAULT NULL, `launched` datetime DEFAULT NULL, `deadline` datetime DEFAULT NULL, `goal` double DEFAULT NULL, `pledged` double DEFAULT NULL, `backers` bigint(20) DEFAULT NULL, `outcome` text, PRIMARY KEY (`id`), KEY `country_id` (`country_id`), KEY `sub_category_id` (`sub_category_id`), KEY `currency_id` (`currency_id`), CONSTRAINT `campaign_ibfk_1` FOREIGN KEY (`country_id`) REFERENCES `country` (`id`), CONSTRAINT `campaign_ibfk_2` FOREIGN KEY (`sub_category_id`) REFERENCES `sub_category` (`id`), CONSTRAINT `campaign_ibfk_3` FOREIGN KEY (`currency_id`) REFERENCES `currency` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; Dumping data for table `campaign` -- LOCK TABLES `campaign` WRITE; /*!40000 ALTER TABLE `campaign` DISABLE KEYS */; INSERT INTO `campaign` VALUES (1,'Ragdolls',23,2,2) INSERT INTO `campaign` VALUES (8667,'Blank Screen Films Summer Project 2013') /*!40000 ALTER TABLE `campaign` ENABLE KEYS */; UNLOCK TABLES; Feel free to ask any question to attain more insight.
[ "Where you have:\nDROP TABLE IF EXISTS `campaign';\n\nthis is supposed to be:\nDROP TABLE IF EXISTS `campaign`;\n\nEither you accidentally changed the backtick to a single quote, or something in your \"downloaded the file and then opened it in SQL\" changed it on you.\n" ]
[ 0 ]
[]
[]
[ "mysql" ]
stackoverflow_0074672836_mysql.txt
Q: Why is PHP Session for my E-commerce website is not working? I'm building an ecommerce website project and right at the start, I kept on having the same problem. For some reason that I don't know, it feels like session_star() is not working or not displaying. I already done so many approach the last thing I have done is copy a source code online made by packetcode on youtube. but no results is showing in my browsers I was expecting that the results will show but even though I referenced alot of sourece code it's still doesn't work and I have no any idea. heres the index.php file: <?php session_start(); include "db.php"; include "retrieve.php"; include "function.php"; include "logic.php"; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Exquisite</title> </head> <body> <div class="container" id="main_cntr"> <div id="intro_cntr"> <div id="title_cntr"> <h2>Welcome to </h1> <h1>Exquisite</h1> </div> <div id="paragraph_cntr"> <p>Here to provide an excellent support for your style!</p> </div> </div> <?php if(empty($_SESSION['username'])){?> <div class="container" id="form"> <div id="login_cntr"> <form method="POST"> <h2>Login</h2> <label for="username">Username</label><br> <input type="text" name="username" placeholder="Enter your Username"><br> <label for="password">Password</label><br> <input type="password" name="pass" placeholder="Enter your Password"><br> <input type="submit" name="login" value="Login"> </form> </div> <?php }?> <div id="signupOption_cntr"> <a href="signup(user).php">Create an Account</a> <h4>or</h4> <a href="login(admin).php">Login as Admin</a> </div> </div> <?php if(!empty($_SESSION['username'])){?> <div class="container"> <h1>Hello again<?php echo $_SESSION['username'];?></h1> <form method="POST"> <button name="logout">Logout</button> </form> </div> <?php }?> </div> </body> </html> I also devided the codes as seen in packetcode's video. here the database code: <?php $conn = mysqli_connect('localhost', 'root', '', 'exquisite') or die ("Cannot connect to the Database"); ?> heres the account retrieval code: <?php if(isset($_REQUEST['login'])){ $uname = $_REQUEST['username']; $pword = $_REQUEST['pass']; } ?> here's the function to take data from the server: <?php function login($conn, $uname, $pword){ $sql = "SELECT * FROM `user_acc` WHERE `username` = '$uname'"; $query = mysqli_query($conn, $sql); return $query; } ?> and here's the code for validation: <?php if(isset($_REQUEST['login'])){ $result = login($conn, $uname, $pword); foreach($result as $r){ $passw_check = password_verify($pword, $r['password']); if($passw_check){ $_SESSION['username'] = $r['username']; header("location: home.php"); } } } if(isset($_REQUEST['logout'])){ session_destroy(); header("location: index.php"); exit(); } ?>
Why is PHP Session for my E-commerce website is not working?
I'm building an ecommerce website project and right at the start, I kept on having the same problem. For some reason that I don't know, it feels like session_star() is not working or not displaying. I already done so many approach the last thing I have done is copy a source code online made by packetcode on youtube. but no results is showing in my browsers I was expecting that the results will show but even though I referenced alot of sourece code it's still doesn't work and I have no any idea. heres the index.php file: <?php session_start(); include "db.php"; include "retrieve.php"; include "function.php"; include "logic.php"; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Exquisite</title> </head> <body> <div class="container" id="main_cntr"> <div id="intro_cntr"> <div id="title_cntr"> <h2>Welcome to </h1> <h1>Exquisite</h1> </div> <div id="paragraph_cntr"> <p>Here to provide an excellent support for your style!</p> </div> </div> <?php if(empty($_SESSION['username'])){?> <div class="container" id="form"> <div id="login_cntr"> <form method="POST"> <h2>Login</h2> <label for="username">Username</label><br> <input type="text" name="username" placeholder="Enter your Username"><br> <label for="password">Password</label><br> <input type="password" name="pass" placeholder="Enter your Password"><br> <input type="submit" name="login" value="Login"> </form> </div> <?php }?> <div id="signupOption_cntr"> <a href="signup(user).php">Create an Account</a> <h4>or</h4> <a href="login(admin).php">Login as Admin</a> </div> </div> <?php if(!empty($_SESSION['username'])){?> <div class="container"> <h1>Hello again<?php echo $_SESSION['username'];?></h1> <form method="POST"> <button name="logout">Logout</button> </form> </div> <?php }?> </div> </body> </html> I also devided the codes as seen in packetcode's video. here the database code: <?php $conn = mysqli_connect('localhost', 'root', '', 'exquisite') or die ("Cannot connect to the Database"); ?> heres the account retrieval code: <?php if(isset($_REQUEST['login'])){ $uname = $_REQUEST['username']; $pword = $_REQUEST['pass']; } ?> here's the function to take data from the server: <?php function login($conn, $uname, $pword){ $sql = "SELECT * FROM `user_acc` WHERE `username` = '$uname'"; $query = mysqli_query($conn, $sql); return $query; } ?> and here's the code for validation: <?php if(isset($_REQUEST['login'])){ $result = login($conn, $uname, $pword); foreach($result as $r){ $passw_check = password_verify($pword, $r['password']); if($passw_check){ $_SESSION['username'] = $r['username']; header("location: home.php"); } } } if(isset($_REQUEST['logout'])){ session_destroy(); header("location: index.php"); exit(); } ?>
[]
[]
[ "Need more information.\nif you are using separate file to validation make sure you are include sessio_start(); on that file too.\nwithout session_start(); session_destroy(); will not work.\n<?php\nsession_start();\n if(isset($_REQUEST['login'])){\n $result = login($conn, $uname, $pword);\n\n foreach($result as $r){\n $passw_check = password_verify($pword, $r['password']);\n\n if($passw_check){\n $_SESSION['username'] = $r['username'];\n\n header(\"location: home.php\");\n }\n }\n }\n\n if(isset($_REQUEST['logout'])){\n session_destroy();\n header(\"location: index.php\");\n exit();\n }\n\n?>\n\n" ]
[ -1 ]
[ "authentication", "forms", "html", "php", "session_variables" ]
stackoverflow_0074672535_authentication_forms_html_php_session_variables.txt
Q: How can I stop the camera after getting result in react-qr-reader I'm using react-qr-reader for scanning QR code, scanning works fine but I can't close the camera that was opened. Led indicator of the camera is still on. Also I tried with the getMedia functions but it creates new instance so I't doesn't work. Is there a another way to stop the camera. state doesn't helps. import { useState, useEffect, useRef } from "react"; import { QrReader } from "react-qr-reader"; const ScanQrPopUp = ({ handlePopUp, walletAddress }: ScanPopUpInterface) => { const [address, setAddress] = useState<string>(""); const [isRecording, setIsRecording] = useState<boolean>(true); useEffect(() => { walletAddress(address); setIsRecording(false) closeCam(); }, [address]); const closeCam = async () => { const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: true, }); stream.getTracks().forEach(function (track) { track.stop(); track.enabled = false; }); }; return ( <div> <h1> Buy </h1> {isRecording && ( <div> <QrReader onResult={(result, error) => { if (result) { setAddress(result?.text); } if (!!error) { console.log(error); } }} style={{ width: "100%" }} /> </div> )} <p>{address}</p> </div> ); }; export default ScanQrPopUp; A: Try to stop camera by doing ref import { useState, useEffect, useRef } from "react"; import { QrReader } from "react-qr-reader"; const ScanQrPopUp = ({ handlePopUp, walletAddress }: ScanPopUpInterface) => { const [address, setAddress] = useState<string>(""); const [isRecording, setIsRecording] = useState<boolean>(true); const ref = useRef(null); useEffect(() => { walletAddress(address); setIsRecording(false) closeCam(); }, [address]); const closeCam = async () => { const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: true, }); stream.getTracks().forEach(function (track) { track.stop(); track.enabled = false; }); ref.current.stopCamera() }; return ( <div> <h1> Buy </h1> {isRecording && ( <div> <QrReader onResult={(result, error) => { if (result) { setAddress(result?.text); } if (!!error) { console.log(error); } }} style={{ width: "100%" }} ref={ref} /> </div> )} <p>{address}</p> </div> ); }; A: Simply add window.location.reload() const closeCam = async () => { const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: true, }); // the rest of the cleanup code window.location.reload() };
How can I stop the camera after getting result in react-qr-reader
I'm using react-qr-reader for scanning QR code, scanning works fine but I can't close the camera that was opened. Led indicator of the camera is still on. Also I tried with the getMedia functions but it creates new instance so I't doesn't work. Is there a another way to stop the camera. state doesn't helps. import { useState, useEffect, useRef } from "react"; import { QrReader } from "react-qr-reader"; const ScanQrPopUp = ({ handlePopUp, walletAddress }: ScanPopUpInterface) => { const [address, setAddress] = useState<string>(""); const [isRecording, setIsRecording] = useState<boolean>(true); useEffect(() => { walletAddress(address); setIsRecording(false) closeCam(); }, [address]); const closeCam = async () => { const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: true, }); stream.getTracks().forEach(function (track) { track.stop(); track.enabled = false; }); }; return ( <div> <h1> Buy </h1> {isRecording && ( <div> <QrReader onResult={(result, error) => { if (result) { setAddress(result?.text); } if (!!error) { console.log(error); } }} style={{ width: "100%" }} /> </div> )} <p>{address}</p> </div> ); }; export default ScanQrPopUp;
[ "Try to stop camera by doing ref\nimport { useState, useEffect, useRef } from \"react\";\nimport { QrReader } from \"react-qr-reader\";\n\nconst ScanQrPopUp = ({ handlePopUp, walletAddress }: ScanPopUpInterface) => {\n const [address, setAddress] = useState<string>(\"\");\n const [isRecording, setIsRecording] = useState<boolean>(true);\n const ref = useRef(null);\n\n useEffect(() => {\n walletAddress(address);\n setIsRecording(false)\n closeCam();\n }, [address]);\n\n const closeCam = async () => {\n const stream = await navigator.mediaDevices.getUserMedia({\n audio: false,\n video: true,\n });\n stream.getTracks().forEach(function (track) {\n track.stop();\n track.enabled = false;\n });\n ref.current.stopCamera()\n };\n\n\n return (\n <div>\n <h1>\n Buy\n </h1>\n\n {isRecording && (\n <div>\n <QrReader\n onResult={(result, error) => {\n if (result) {\n setAddress(result?.text);\n }\n if (!!error) {\n console.log(error);\n }\n }}\n style={{ width: \"100%\" }}\n ref={ref}\n />\n </div>\n )}\n\n <p>{address}</p>\n </div>\n );\n};\n\n", "Simply add window.location.reload()\nconst closeCam = async () => {\n const stream = await navigator.mediaDevices.getUserMedia({\n audio: false,\n video: true,\n });\n // the rest of the cleanup code\n window.location.reload()\n};\n\n" ]
[ 0, 0 ]
[]
[]
[ "next.js", "qr_code", "typescript" ]
stackoverflow_0072951529_next.js_qr_code_typescript.txt
Q: Pause VBA until #GETTING DATA Power Pivot is complete I've found a lot of questions and answers about issues that feel very close to what I'm working on, but not quite. I have an Excel workbook with a large Data Model connected to two slicers. I need to cycle through every entry in the slicer, allow the workbook to catch up on loading a large number of cube formulas, then copy one particular worksheet over into another. I've written VBA which does all of this, but I can't for the life of me get the VBA to wait for the workbook to finish uploading before it continues with the rest of the script. I can rule out background refresh-based solutions, which don't apply to OLAP. Various solutions I've found online which recommend waiting for calculations to be complete don't seem to work, the script just barrels right through those lines. The only solution I've seen which seems to apply here involved identifying every cell which would be updated as a result of the slicer change and looping through them until they no longer say #GETTING DATA. For my workbook, this would be hundreds of cells to identify and check and feels very unsustainable. Even telling the script to Applcation.Wait seems to wait for the selected amount of time during which the workbook pauses getting data. Setting different values of a slicer connected to a Data Model and automating some output feels like it should be such a common task that we have a solution for it. Any help would be much appreciated. Running Office 365 Sub generate_all_forecasts() 'Cycle through all products and push forecast values to fcst_output' Application.ScreenUpdating = True Dim SC_products As SlicerCache Dim selection, product_array As Variant Dim push As Boolean Set SC_products = ThisWorkbook.SlicerCaches("Slicer_PRODUCT_GROUPING_WRITTEN") 'The product slicer on the Inputs worksheet' product_array = Range("product_array") 'Named range product_array on Tbl_Codes worksheet' For Each p In product_array 'For each product' push = WorksheetFunction.Index(Range("fcst_push_array"), WorksheetFunction.Match(p, product_array, 0)) 'Check if the product has been selected for this run' If push = True Then If p = "Major Medical Plan" Then 'If "Major Medical" ' selection = Array("[Query1 1].[PRODUCT_GROUPING_WRITTEN].&[Major Medical Plan - CMM]", _ "[Query1 1].[PRODUCT_GROUPING_WRITTEN].&[Major Medical Plan - GMM]") 'selection will be both CMM and GMM' Else selection = Array("[Query1 1].[PRODUCT_GROUPING_WRITTEN].&[" & p & "]") 'Otherwse selection is the single product' End If SC_products.VisibleSlicerItemsList = selection 'Change slicer to current selection' 'This is where the script needs to pause until #GETTING DATA is complete' Application.Run "push_to_output" 'Run the forecast update macro' End If Next p Worksheets("Fcst_Output").Range("B2:B1381").Value = "" 'Clear prior month's comments' Application.ScreenUpdating = True End Sub Solutions which have not worked: Wait time after change slicer in power pivot, Getting vba to wait before proceeding, Wait until Application.Calculate has finished The "solution" I really don't want to use: Force VBA to wait until power pivot finishes refreshing A: You can use the CalculationState property of the Application object to check if all calculations in the workbook are complete before proceeding with the rest of the script. You can add a Do Until loop that waits until the CalculationState is xlDone before proceeding. Here is an example of how this can be implemented: Do Until Application.CalculationState = xlDone DoEvents ' pause execution until calculation is complete Loop You can insert this loop at the point in your code where you want to wait for the workbook to finish updating before continuing. Note that using DoEvents in a loop like this can potentially cause performance issues, so it's recommended to use this approach only if necessary. Here is an example of how this can be implemented in your code: Sub generate_all_forecasts() 'Cycle through all products and push forecast values to fcst_output' Application.ScreenUpdating = True Dim SC_products As SlicerCache Dim selection, product_array As Variant Dim push As Boolean Set SC_products = ThisWorkbook.SlicerCaches("Slicer_PRODUCT_GROUPING_WRITTEN") 'The product slicer on the Inputs worksheet' product_array = Range("product_array") 'Named range product_array on Tbl_Codes worksheet' For Each p In product_array 'For each product' push = WorksheetFunction.Index(Range("fcst_push_array"), WorksheetFunction.Match(p, product_array, 0)) 'Check if the product has been selected for this run' If push = True Then If p = "Major Medical Plan" Then 'If "Major Medical" ' selection = Array("[Query1 1].[PRODUCT_GROUPING_WRITTEN].&[Major Medical Plan - CMM]", "[Query1 1].[PRODUCT_GROUPING_WRITTEN].&[Major Medical Plan - GMM]") 'selection will be both CMM and GMM' Else selection = Array("[Query1 1].[PRODUCT_GROUPING_WRITTEN].&[" & p & "]") 'Otherwse selection is the single product' End If SC_products.VisibleSlicerItemsList = selection 'Change slicer to current selection' 'This is where the script needs to pause until #GETTING DATA is complete' Do = Do Until Not Application.CalculationState = xlCalculating DoEvents Loop Application.Run "push_to_output" 'Run the forecast update macro' End If Next p Worksheets("Fcst_Output").Range("B2:B1381").Value = "" 'Clear prior month's comments' Application.ScreenUpdating = True End Sub
Pause VBA until #GETTING DATA Power Pivot is complete
I've found a lot of questions and answers about issues that feel very close to what I'm working on, but not quite. I have an Excel workbook with a large Data Model connected to two slicers. I need to cycle through every entry in the slicer, allow the workbook to catch up on loading a large number of cube formulas, then copy one particular worksheet over into another. I've written VBA which does all of this, but I can't for the life of me get the VBA to wait for the workbook to finish uploading before it continues with the rest of the script. I can rule out background refresh-based solutions, which don't apply to OLAP. Various solutions I've found online which recommend waiting for calculations to be complete don't seem to work, the script just barrels right through those lines. The only solution I've seen which seems to apply here involved identifying every cell which would be updated as a result of the slicer change and looping through them until they no longer say #GETTING DATA. For my workbook, this would be hundreds of cells to identify and check and feels very unsustainable. Even telling the script to Applcation.Wait seems to wait for the selected amount of time during which the workbook pauses getting data. Setting different values of a slicer connected to a Data Model and automating some output feels like it should be such a common task that we have a solution for it. Any help would be much appreciated. Running Office 365 Sub generate_all_forecasts() 'Cycle through all products and push forecast values to fcst_output' Application.ScreenUpdating = True Dim SC_products As SlicerCache Dim selection, product_array As Variant Dim push As Boolean Set SC_products = ThisWorkbook.SlicerCaches("Slicer_PRODUCT_GROUPING_WRITTEN") 'The product slicer on the Inputs worksheet' product_array = Range("product_array") 'Named range product_array on Tbl_Codes worksheet' For Each p In product_array 'For each product' push = WorksheetFunction.Index(Range("fcst_push_array"), WorksheetFunction.Match(p, product_array, 0)) 'Check if the product has been selected for this run' If push = True Then If p = "Major Medical Plan" Then 'If "Major Medical" ' selection = Array("[Query1 1].[PRODUCT_GROUPING_WRITTEN].&[Major Medical Plan - CMM]", _ "[Query1 1].[PRODUCT_GROUPING_WRITTEN].&[Major Medical Plan - GMM]") 'selection will be both CMM and GMM' Else selection = Array("[Query1 1].[PRODUCT_GROUPING_WRITTEN].&[" & p & "]") 'Otherwse selection is the single product' End If SC_products.VisibleSlicerItemsList = selection 'Change slicer to current selection' 'This is where the script needs to pause until #GETTING DATA is complete' Application.Run "push_to_output" 'Run the forecast update macro' End If Next p Worksheets("Fcst_Output").Range("B2:B1381").Value = "" 'Clear prior month's comments' Application.ScreenUpdating = True End Sub Solutions which have not worked: Wait time after change slicer in power pivot, Getting vba to wait before proceeding, Wait until Application.Calculate has finished The "solution" I really don't want to use: Force VBA to wait until power pivot finishes refreshing
[ "You can use the CalculationState property of the Application object to check if all calculations in the workbook are complete before proceeding with the rest of the script. You can add a Do Until loop that waits until the CalculationState is xlDone before proceeding.\nHere is an example of how this can be implemented:\nDo Until Application.CalculationState = xlDone\n DoEvents ' pause execution until calculation is complete\nLoop\n\nYou can insert this loop at the point in your code where you want to wait for the workbook to finish updating before continuing. Note that using DoEvents in a loop like this can potentially cause performance issues, so it's recommended to use this approach only if necessary.\nHere is an example of how this can be implemented in your code:\nSub generate_all_forecasts()\n 'Cycle through all products and push forecast values to fcst_output'\n Application.ScreenUpdating = True\n\n Dim SC_products As SlicerCache\n Dim selection, product_array As Variant\n Dim push As Boolean\n \nSet SC_products = ThisWorkbook.SlicerCaches(\"Slicer_PRODUCT_GROUPING_WRITTEN\") 'The product slicer on the Inputs worksheet'\n\nproduct_array = Range(\"product_array\") 'Named range product_array on Tbl_Codes worksheet'\n\nFor Each p In product_array 'For each product'\n push = WorksheetFunction.Index(Range(\"fcst_push_array\"), WorksheetFunction.Match(p, product_array, 0)) 'Check if the product has been selected for this run'\n\n If push = True Then\n If p = \"Major Medical Plan\" Then 'If \"Major Medical\" '\n selection = Array(\"[Query1 1].[PRODUCT_GROUPING_WRITTEN].&[Major Medical Plan - CMM]\", \"[Query1 1].[PRODUCT_GROUPING_WRITTEN].&[Major Medical Plan - GMM]\") 'selection will be both CMM and GMM'\n Else\n selection = Array(\"[Query1 1].[PRODUCT_GROUPING_WRITTEN].&[\" & p & \"]\") 'Otherwse selection is the single product'\n End If\n\n SC_products.VisibleSlicerItemsList = selection 'Change slicer to current selection'\n\n 'This is where the script needs to pause until #GETTING DATA is complete'\n Do =\n Do Until Not Application.CalculationState = xlCalculating\n DoEvents\n Loop\n\n Application.Run \"push_to_output\" 'Run the forecast update macro'\n End If\nNext p\n\nWorksheets(\"Fcst_Output\").Range(\"B2:B1381\").Value = \"\" 'Clear prior month's comments'\n\nApplication.ScreenUpdating = True\nEnd Sub\n\n" ]
[ 0 ]
[]
[]
[ "excel", "powerquery", "slicers", "vba" ]
stackoverflow_0074548591_excel_powerquery_slicers_vba.txt
Q: How to use mongocompact package in mongoclient connect options Currently I already use NewRegistryBuilder() in the mongo client options , Somehow i want to make use of NewRespectNilValuesRegistryBuilder() from mongocompact so that I can set the nilvalues in the []models as empty array . Currently I have something like below , To map the old mgo behavior tM := reflect.TypeOf(bson.M{}) registry := bson.NewRegistryBuilder().RegisterTypeMapEntry(bsontype.EmbeddedDocument, tM).Build() clientOpts := options.Client().ApplyURI(URI).SetAuth(info).SetRegistry(registry) client, err := mongo.Connect(ctx, clientOpts) Now somehow I want to incorporate and set the NewRespectNilValuesRegistryBuilder().Build() to true in the same connect options , Not sure how to do that . Also the other problem that i see is i'm not able to see the mongocompat registry file in my vendor directory can i do something like this , SetRegistry() two times ? like below ? tM := reflect.TypeOf(bson.M{}) registry := bson.NewRegistryBuilder().RegisterTypeMapEntry(bsontype.EmbeddedDocument, tM).Build() clientOpts := options.Client().ApplyURI(SOMEURI).SetAuth(info).SetRegistry(registry) //not sure if the below line is of right usage ?? clientOpts.SetRegistry(NewRespectNilValuesRegistryBuilder().Build()) client, err := mongo.Connect(ctx, clientOpts) can anyone help me with this ? related issue here A: I found a solution to this one , All we need to do is registry := mgocompat.NewRegistryBuilder().Build() connectOpts := options.Client().ApplyURI(SOMEURI).SetAuth(info).SetRegistry(registry) This will take care of both requirements , no need to say tM := reflect.TypeOf(bson.M{}) Since that's a default behavior that's included in mgocompat
How to use mongocompact package in mongoclient connect options
Currently I already use NewRegistryBuilder() in the mongo client options , Somehow i want to make use of NewRespectNilValuesRegistryBuilder() from mongocompact so that I can set the nilvalues in the []models as empty array . Currently I have something like below , To map the old mgo behavior tM := reflect.TypeOf(bson.M{}) registry := bson.NewRegistryBuilder().RegisterTypeMapEntry(bsontype.EmbeddedDocument, tM).Build() clientOpts := options.Client().ApplyURI(URI).SetAuth(info).SetRegistry(registry) client, err := mongo.Connect(ctx, clientOpts) Now somehow I want to incorporate and set the NewRespectNilValuesRegistryBuilder().Build() to true in the same connect options , Not sure how to do that . Also the other problem that i see is i'm not able to see the mongocompat registry file in my vendor directory can i do something like this , SetRegistry() two times ? like below ? tM := reflect.TypeOf(bson.M{}) registry := bson.NewRegistryBuilder().RegisterTypeMapEntry(bsontype.EmbeddedDocument, tM).Build() clientOpts := options.Client().ApplyURI(SOMEURI).SetAuth(info).SetRegistry(registry) //not sure if the below line is of right usage ?? clientOpts.SetRegistry(NewRespectNilValuesRegistryBuilder().Build()) client, err := mongo.Connect(ctx, clientOpts) can anyone help me with this ? related issue here
[ "I found a solution to this one , All we need to do is\nregistry := mgocompat.NewRegistryBuilder().Build()\nconnectOpts := options.Client().ApplyURI(SOMEURI).SetAuth(info).SetRegistry(registry)\n\nThis will take care of both requirements , no need to say\ntM := reflect.TypeOf(bson.M{})\n\n\nSince that's a default behavior that's included in mgocompat\n" ]
[ 0 ]
[]
[]
[ "driver", "go", "golang_migrate", "mongodb", "mongodb_query" ]
stackoverflow_0074653260_driver_go_golang_migrate_mongodb_mongodb_query.txt
Q: I have a line chart that I want to use to show temperature, but I want to show icons and time in x axis what I want to achieve what I have I want to show icons on the xAxis above time but line chart takes icon and places them on the value where temperature is shown. I have searched a lot but could not find the answer. Any help would be appreciated. I have tried a lot of things but all in vein. private fun setTempChart(hour: ArrayList<Hour>, id: String) { val entries: MutableList<Entry> = ArrayList() for (i in hour.indices) { val code = hour[i].condition.code val icon = if (hour[i].is_day == 1) requireActivity().setIconDay(code) else requireActivity().setIconNight( code ) entries.add(Entry(i.toFloat(), sharedPreference.temp?.let { hour[i].temp_c.setCurrentTemperature( it ).toFloat() }!!)) } val dataSet = LineDataSet(entries, "") dataSet.apply { lineWidth = 0f setDrawCircles(false) setDrawCircleHole(false) isHighlightEnabled = false valueTextColor = Color.WHITE setColors(Color.WHITE) valueTextSize = 12f mode = LineDataSet.Mode.CUBIC_BEZIER setDrawFilled(true) fillColor = Color.WHITE valueTypeface = typeface isDrawIconsEnabled setDrawIcons(true) valueFormatter = object : ValueFormatter() { override fun getFormattedValue(value: Float): String { return String.format(Locale.getDefault(), "%.0f", value) } } } val lineData = LineData(dataSet) chart.apply { description.isEnabled = false axisLeft.setDrawLabels(false) axisRight.setDrawLabels(false) legend.isEnabled = false axisLeft.setDrawGridLines(false) axisRight.setDrawGridLines(false) axisLeft.setDrawAxisLine(false) axisRight.setDrawAxisLine(false) setScaleEnabled(false) data = lineData setVisibleXRange(8f, 8f) animateY(1000) xAxis.apply { setDrawAxisLine(false) textColor = Color.WHITE setDrawGridLines(false) setDrawLabels(true) position = XAxis.XAxisPosition.BOTTOM textSize = 12f valueFormatter = MyAxisFormatter(hour, id) isGranularityEnabled = true granularity = 1f labelCount = entries.size } } } I am using MPAndroidChart library A: There isn't a nice built-in way to draw icons like that, but you can do it by making a custom extension of the LineChartRenderer and overriding drawExtras. Then you can get your icons from R.drawable.X and draw them on the canvas wherever you want. There is some work to figure out where to put them to line up with the data points, but you can copy the logic from drawCircles to find that. Example Custom Renderer inner class MyRenderer(private val context: Context, chart: LineDataProvider, animator: ChartAnimator, viewPortHandler: ViewPortHandler) : LineChartRenderer(chart, animator, viewPortHandler) { private var buffer: FloatArray = listOf(0f,0f).toFloatArray() override fun drawExtras(c: Canvas) { super.drawExtras(c) // get the icons you want to draw val cloudy = ContextCompat.getDrawable(context, R.drawable.cloudy) ?: return val sunny = ContextCompat.getDrawable(context, R.drawable.sunny) ?: return // Determine icon width in pixels val w = 100f // don't hard-code these in pixels val h = 100f val dataSets = mChart.lineData.dataSets val phaseY = mAnimator.phaseY for(dataSet in dataSets) { mXBounds.set(mChart, dataSet) val boundsRange = mXBounds.range + mXBounds.min val transformer = mChart.getTransformer(dataSet.axisDependency) for(j in mXBounds.min .. boundsRange) { val e = dataSet.getEntryForIndex(j) ?: break buffer[0] = e.x buffer[1] = e.y * phaseY transformer.pointValuesToPixel(buffer) if( !mViewPortHandler.isInBoundsRight(buffer[0])) { break } if( !mViewPortHandler.isInBoundsLeft(buffer[0]) || !mViewPortHandler.isInBoundsY(buffer[1])) { continue } // Draw the icon centered under the data point, but at a fixed // vertical position (arbitrary 650 here). val left = (buffer[0]-w/2).roundToInt() val right = (buffer[0]+w/2).roundToInt() val top = 650 val bottom = (top+h).roundToInt() // Use whatever logic you want to select which icon // to use at each position val icon = if( e.y > 68f ) { sunny } else { cloudy } icon.setBounds(left, top, right, bottom) icon.draw(c) } } } } Using the Custom Renderer val chart = findViewById<LineChart>(R.id.chart) chart.axisRight.isEnabled = false val yAx = chart.axisLeft yAx.setDrawLabels(false) yAx.setDrawGridLines(false) yAx.setDrawAxisLine(false) yAx.axisMinimum = 40f yAx.axisMaximum = 80f val xAx = chart.xAxis xAx.setDrawLabels(false) xAx.position = XAxis.XAxisPosition.BOTTOM xAx.setDrawGridLines(false) xAx.setDrawAxisLine(false) xAx.axisMinimum = 0.5f xAx.axisMaximum = 5.5f xAx.granularity = 0.5f val x = listOf(0,1,2,3,4,5,6) val y = listOf(60,65,66,70,65,50,55) val e = x.zip(y).map { Entry(it.first.toFloat(), it.second.toFloat())} val line = LineDataSet(e, "temp") line.setDrawValues(true) line.setDrawCircles(false) line.circleRadius = 20f // makes the text offset up line.valueTextSize = 20f line.color = Color.BLACK line.lineWidth = 2f line.setDrawFilled(true) line.fillColor = Color.BLACK line.fillAlpha = 50 line.mode = LineDataSet.Mode.CUBIC_BEZIER line.valueFormatter = object : ValueFormatter() { override fun getFormattedValue(value: Float): String { return "%.0f F".format(value) } } chart.renderer = MyRenderer(this, chart, chart.animator, chart.viewPortHandler) chart.data = LineData(line) chart.description.isEnabled = false chart.legend.isEnabled = false Gives the desired effect
I have a line chart that I want to use to show temperature, but I want to show icons and time in x axis
what I want to achieve what I have I want to show icons on the xAxis above time but line chart takes icon and places them on the value where temperature is shown. I have searched a lot but could not find the answer. Any help would be appreciated. I have tried a lot of things but all in vein. private fun setTempChart(hour: ArrayList<Hour>, id: String) { val entries: MutableList<Entry> = ArrayList() for (i in hour.indices) { val code = hour[i].condition.code val icon = if (hour[i].is_day == 1) requireActivity().setIconDay(code) else requireActivity().setIconNight( code ) entries.add(Entry(i.toFloat(), sharedPreference.temp?.let { hour[i].temp_c.setCurrentTemperature( it ).toFloat() }!!)) } val dataSet = LineDataSet(entries, "") dataSet.apply { lineWidth = 0f setDrawCircles(false) setDrawCircleHole(false) isHighlightEnabled = false valueTextColor = Color.WHITE setColors(Color.WHITE) valueTextSize = 12f mode = LineDataSet.Mode.CUBIC_BEZIER setDrawFilled(true) fillColor = Color.WHITE valueTypeface = typeface isDrawIconsEnabled setDrawIcons(true) valueFormatter = object : ValueFormatter() { override fun getFormattedValue(value: Float): String { return String.format(Locale.getDefault(), "%.0f", value) } } } val lineData = LineData(dataSet) chart.apply { description.isEnabled = false axisLeft.setDrawLabels(false) axisRight.setDrawLabels(false) legend.isEnabled = false axisLeft.setDrawGridLines(false) axisRight.setDrawGridLines(false) axisLeft.setDrawAxisLine(false) axisRight.setDrawAxisLine(false) setScaleEnabled(false) data = lineData setVisibleXRange(8f, 8f) animateY(1000) xAxis.apply { setDrawAxisLine(false) textColor = Color.WHITE setDrawGridLines(false) setDrawLabels(true) position = XAxis.XAxisPosition.BOTTOM textSize = 12f valueFormatter = MyAxisFormatter(hour, id) isGranularityEnabled = true granularity = 1f labelCount = entries.size } } } I am using MPAndroidChart library
[ "There isn't a nice built-in way to draw icons like that, but you can do it by making a custom extension of the LineChartRenderer and overriding drawExtras. Then you can get your icons from R.drawable.X and draw them on the canvas wherever you want. There is some work to figure out where to put them to line up with the data points, but you can copy the logic from drawCircles to find that.\nExample Custom Renderer\n\ninner class MyRenderer(private val context: Context, chart: LineDataProvider, animator: ChartAnimator, viewPortHandler: ViewPortHandler)\n : LineChartRenderer(chart, animator, viewPortHandler) {\n\n private var buffer: FloatArray = listOf(0f,0f).toFloatArray()\n\n override fun drawExtras(c: Canvas) {\n super.drawExtras(c)\n\n // get the icons you want to draw\n val cloudy = ContextCompat.getDrawable(context, R.drawable.cloudy) ?: return\n val sunny = ContextCompat.getDrawable(context, R.drawable.sunny) ?: return\n \n // Determine icon width in pixels\n val w = 100f // don't hard-code these in pixels\n val h = 100f\n\n val dataSets = mChart.lineData.dataSets\n val phaseY = mAnimator.phaseY\n\n for(dataSet in dataSets) {\n mXBounds.set(mChart, dataSet)\n val boundsRange = mXBounds.range + mXBounds.min\n val transformer = mChart.getTransformer(dataSet.axisDependency)\n\n for(j in mXBounds.min .. boundsRange) {\n val e = dataSet.getEntryForIndex(j) ?: break\n\n buffer[0] = e.x\n buffer[1] = e.y * phaseY\n\n transformer.pointValuesToPixel(buffer)\n\n if( !mViewPortHandler.isInBoundsRight(buffer[0])) {\n break\n }\n\n if( !mViewPortHandler.isInBoundsLeft(buffer[0]) || !mViewPortHandler.isInBoundsY(buffer[1])) {\n continue\n }\n\n // Draw the icon centered under the data point, but at a fixed\n // vertical position (arbitrary 650 here).\n val left = (buffer[0]-w/2).roundToInt()\n val right = (buffer[0]+w/2).roundToInt()\n val top = 650\n val bottom = (top+h).roundToInt()\n\n // Use whatever logic you want to select which icon\n // to use at each position\n val icon = if( e.y > 68f ) {\n sunny\n }\n else {\n cloudy\n }\n\n icon.setBounds(left, top, right, bottom)\n icon.draw(c)\n }\n }\n\n }\n}\n\nUsing the Custom Renderer\nval chart = findViewById<LineChart>(R.id.chart)\n\nchart.axisRight.isEnabled = false\nval yAx = chart.axisLeft\nyAx.setDrawLabels(false)\nyAx.setDrawGridLines(false)\nyAx.setDrawAxisLine(false)\nyAx.axisMinimum = 40f\nyAx.axisMaximum = 80f\n\nval xAx = chart.xAxis\nxAx.setDrawLabels(false)\nxAx.position = XAxis.XAxisPosition.BOTTOM\nxAx.setDrawGridLines(false)\nxAx.setDrawAxisLine(false)\nxAx.axisMinimum = 0.5f\nxAx.axisMaximum = 5.5f\nxAx.granularity = 0.5f\n\nval x = listOf(0,1,2,3,4,5,6)\nval y = listOf(60,65,66,70,65,50,55)\nval e = x.zip(y).map { Entry(it.first.toFloat(), it.second.toFloat())}\nval line = LineDataSet(e, \"temp\")\nline.setDrawValues(true)\nline.setDrawCircles(false)\nline.circleRadius = 20f // makes the text offset up\nline.valueTextSize = 20f\nline.color = Color.BLACK\nline.lineWidth = 2f\nline.setDrawFilled(true)\nline.fillColor = Color.BLACK\nline.fillAlpha = 50\nline.mode = LineDataSet.Mode.CUBIC_BEZIER\nline.valueFormatter = object : ValueFormatter() {\n override fun getFormattedValue(value: Float): String {\n return \"%.0f F\".format(value)\n }\n}\n\nchart.renderer = MyRenderer(this, chart, chart.animator, chart.viewPortHandler)\n\nchart.data = LineData(line)\nchart.description.isEnabled = false\nchart.legend.isEnabled = false\n\n\nGives the desired effect\n\n" ]
[ 0 ]
[]
[]
[ "android", "kotlin", "linechart", "mpandroidchart" ]
stackoverflow_0074655582_android_kotlin_linechart_mpandroidchart.txt
Q: Loop over an array and separate out the elements in different arrays in apps script I Have an array from a two columns concatenated in column Here is the link to spreadsheet - https://docs.google.com/spreadsheets/d/180iMihBq9-Gep9Em6v570pshPRNgsruaboFv5e4XHes/edit#gid=1082081384 var a1_range = To_check.getRange("A2:A"); var a1_val = a1_range.getValues(); I am trying to read the values of whole column and take out first and second elements into two different arrays correspondingly. If in the concatenated elements there is "Included" then it should skip it If in the concatenated elements there is "Flat Mon" then it should skip it the loop should break after encountering concatenation length as 0 I have tried this code below a1_arr= []; for (var j in a1_val){ if(a1_val[j][0].split("-").length==2){ a1_arr.push(BillFUOM_val[j][0]); } else{ break;} } for (var j in a1_arr){ var check_inluded = a1_arr[j].includes("Included"); if(check_inluded==true){ a1_arr.splice(j); } } for (var j in a1_arr){ var check_flat = a1_arr[j].includes("Flat Mon"); if(check_flat==true){ a1_arr.splice(j); } } var a1_arr_split = a1_arr.toString().split("-"); var a1 = []; a1_arr_split.forEach(function(q){a1.push([q]);}); Logger.log(a1); I want array a1 to be [GGG,Comms+ Excess] and an array a2 to have the above arrays corresponding second item [Yearly,Monthly] Please help! @Tanaike - san A: Fill in the conditions and it should be good to go. const ssid = '180iMihBq9-Gep9Em6v570pshPRNgsruaboFv5e4XHes'; const sss = SpreadsheetApp.openById(ssid); const range = sss.getRange('A1:A'); function results() { const values = range.getValues(); const output = {arr1: [],arr2: []}; for (const row of values) { // if you want to break the loop where the concatenation length is 0, you should not use 'A1:A' as range at the very begining, // and since you use 'A1:A' as you range, as long as your data do not have infinity length, // there is not much point to iterate the array just to find out the length so as to let you break it at the right place, // instead, you can just skip a loop with continue if it is empty. if (row[0] = '') continue; // If there is no value, skip it. const str = row[0]; if (str.includes('Included')) continue; // If in the concatenated elements there is "Included" then it should skip it if (str.includes('Flat Mon')) continue; // If in the concatenated elements there is "Flat Mon" then it should skip it if (str = '-') continue; // If the value is a single "-", skip it // I can't understand what is the result structure you want, but you can do this to push the result into the output object: const condition_1 = '1st condition you want to check'; const condition_2 = '2nd condition you want to check'; if (condition_1) output.arr1.push(str); if (condition_2) output.arr2.push(str); } console.log(output); }
Loop over an array and separate out the elements in different arrays in apps script
I Have an array from a two columns concatenated in column Here is the link to spreadsheet - https://docs.google.com/spreadsheets/d/180iMihBq9-Gep9Em6v570pshPRNgsruaboFv5e4XHes/edit#gid=1082081384 var a1_range = To_check.getRange("A2:A"); var a1_val = a1_range.getValues(); I am trying to read the values of whole column and take out first and second elements into two different arrays correspondingly. If in the concatenated elements there is "Included" then it should skip it If in the concatenated elements there is "Flat Mon" then it should skip it the loop should break after encountering concatenation length as 0 I have tried this code below a1_arr= []; for (var j in a1_val){ if(a1_val[j][0].split("-").length==2){ a1_arr.push(BillFUOM_val[j][0]); } else{ break;} } for (var j in a1_arr){ var check_inluded = a1_arr[j].includes("Included"); if(check_inluded==true){ a1_arr.splice(j); } } for (var j in a1_arr){ var check_flat = a1_arr[j].includes("Flat Mon"); if(check_flat==true){ a1_arr.splice(j); } } var a1_arr_split = a1_arr.toString().split("-"); var a1 = []; a1_arr_split.forEach(function(q){a1.push([q]);}); Logger.log(a1); I want array a1 to be [GGG,Comms+ Excess] and an array a2 to have the above arrays corresponding second item [Yearly,Monthly] Please help! @Tanaike - san
[ "Fill in the conditions and it should be good to go.\n\n\nconst ssid = '180iMihBq9-Gep9Em6v570pshPRNgsruaboFv5e4XHes';\nconst sss = SpreadsheetApp.openById(ssid);\nconst range = sss.getRange('A1:A');\n\nfunction results() {\n const values = range.getValues();\n\n const output = {arr1: [],arr2: []};\n for (const row of values) {\n // if you want to break the loop where the concatenation length is 0, you should not use 'A1:A' as range at the very begining,\n // and since you use 'A1:A' as you range, as long as your data do not have infinity length,\n // there is not much point to iterate the array just to find out the length so as to let you break it at the right place,\n // instead, you can just skip a loop with continue if it is empty.\n if (row[0] = '') continue; // If there is no value, skip it.\n \n const str = row[0];\n if (str.includes('Included')) continue; // If in the concatenated elements there is \"Included\" then it should skip it\n if (str.includes('Flat Mon')) continue; // If in the concatenated elements there is \"Flat Mon\" then it should skip it\n if (str = '-') continue; // If the value is a single \"-\", skip it\n\n // I can't understand what is the result structure you want, but you can do this to push the result into the output object:\n const condition_1 = '1st condition you want to check';\n const condition_2 = '2nd condition you want to check';\n if (condition_1) output.arr1.push(str);\n if (condition_2) output.arr2.push(str);\n }\n\n console.log(output);\n}\n\n\n\n" ]
[ 1 ]
[]
[]
[ "google_apps_script" ]
stackoverflow_0074672672_google_apps_script.txt
Q: Why does GO compiler add a pointer value receiver method to the method set of non-pointer type when using the pointer Type Embedding? First of all, I want to say that my question is not based on a specific problem, but is based on a potential discussion of why the GO compiler behaves in a certain way. I expect that potential experts in the given language (or at least people with serious experience) could explain this potentially strange behavior. Also, the title might be a little confusing because I'm not sure how to explain in one sentence (one question) without an example and a more detailed story. To clearly explain what the question in the title means, let me start from a situation that behaves as I expect. package main import ( "fmt" "reflect" ) type MyType1 struct { MyType2 } type MyType2 struct { } func (MyType2) Function1() { } func (*MyType2) Function2() { } func main() { t1 := reflect.TypeOf(MyType1{}) t2 := reflect.TypeOf(&MyType1{}) fmt.Println(t1, "has", t1.NumMethod(), "methods:") for i := 0; i < t1.NumMethod(); i++ { fmt.Print(" method#", i, ": ", t1.Method(i).Name, "\n") } fmt.Println(t2, "has", t2.NumMethod(), "methods:") for i := 0; i < t2.NumMethod(); i++ { fmt.Print(" method#", i, ": ", t2.Method(i).Name, "\n") } } When the type embedding is based on "type" (not correct name, but let's call it like that) everything behaves as I expect. The structure MyType1 has a MyType2 embedded field ("type" embedded field) so the type MyType1 will have the method (MyType1)Function1() in its method set and the type *MyType1 will have the methods (*MyType1)Function1() and (*MyType1)Function2() in its method set. So, each type (MyType1 and *MyType1) will get their corresponding methods. *MyType1 will get the method (*MyType1)Function1() because it's implicitly arises from (MyType1)Function1(). So, as I said before, everything is expected. To prove this, I also used the standard "reflect" package and got the following printout: main.MyType1 has 1 methods: method#0: Function1 *main.MyType1 has 2 methods: method#0: Function1 method#1: Function2 A strange behavior occurs when I replace the "type" embedded field with a "pointer type" embedded field (MyType1 now has *MyType2 instead of MyType2). So the code looks like this: package main import ( "fmt" "reflect" ) type MyType1 struct { *MyType2 } type MyType2 struct { } func (MyType2) Function1() { } func (*MyType2) Function2() { } func main() { t1 := reflect.TypeOf(MyType1{}) t2 := reflect.TypeOf(&MyType1{}) fmt.Println(t1, "has", t1.NumMethod(), "methods:") for i := 0; i < t1.NumMethod(); i++ { fmt.Print(" method#", i, ": ", t1.Method(i).Name, "\n") } fmt.Println(t2, "has", t2.NumMethod(), "methods:") for i := 0; i < t2.NumMethod(); i++ { fmt.Print(" method#", i, ": ", t2.Method(i).Name, "\n") } } Now what is actually the crux of the problem. The prints is: main.MyType1 has 2 methods: method#0: Function1 method#1: Function2 *main.MyType1 has 2 methods: method#0: Function1 method#1: Function2 So, somehow MyType1 also has method (MyType1)Function2() even though it is not declared as value receiver method for type MyType2. Does anyone have any logical explanation as to why this is happening? A: The simple explanation is: If type A embeds type B, type A gets all methods of type B. In your first example, MyType2 is embedded into MyType1, and MyType2 has one function, Function1, so MyType1 also gets Function1. In your second example, *MyType2 has two functions, Function1 and Function2, so MyType1 has both of those functions. The important point here is that methods defined with a pointer receiver of type A are only defined for *A, and not for A. The reason for that is to provide proper semantics for interfaces. Let's say you have an interface: type MyIntf interface { Function2() } If there is a function: func f(m MyIntf) { m.Function2() } then this property prevents you from passing MyType1 to f, because if it were allowed, the modifications f made on that object by calling Function2 would be lost. You can only pass MyType2, or the second MyType1 implementation, in which case any modifications made on m will be reflected on the passed instance of the value.
Why does GO compiler add a pointer value receiver method to the method set of non-pointer type when using the pointer Type Embedding?
First of all, I want to say that my question is not based on a specific problem, but is based on a potential discussion of why the GO compiler behaves in a certain way. I expect that potential experts in the given language (or at least people with serious experience) could explain this potentially strange behavior. Also, the title might be a little confusing because I'm not sure how to explain in one sentence (one question) without an example and a more detailed story. To clearly explain what the question in the title means, let me start from a situation that behaves as I expect. package main import ( "fmt" "reflect" ) type MyType1 struct { MyType2 } type MyType2 struct { } func (MyType2) Function1() { } func (*MyType2) Function2() { } func main() { t1 := reflect.TypeOf(MyType1{}) t2 := reflect.TypeOf(&MyType1{}) fmt.Println(t1, "has", t1.NumMethod(), "methods:") for i := 0; i < t1.NumMethod(); i++ { fmt.Print(" method#", i, ": ", t1.Method(i).Name, "\n") } fmt.Println(t2, "has", t2.NumMethod(), "methods:") for i := 0; i < t2.NumMethod(); i++ { fmt.Print(" method#", i, ": ", t2.Method(i).Name, "\n") } } When the type embedding is based on "type" (not correct name, but let's call it like that) everything behaves as I expect. The structure MyType1 has a MyType2 embedded field ("type" embedded field) so the type MyType1 will have the method (MyType1)Function1() in its method set and the type *MyType1 will have the methods (*MyType1)Function1() and (*MyType1)Function2() in its method set. So, each type (MyType1 and *MyType1) will get their corresponding methods. *MyType1 will get the method (*MyType1)Function1() because it's implicitly arises from (MyType1)Function1(). So, as I said before, everything is expected. To prove this, I also used the standard "reflect" package and got the following printout: main.MyType1 has 1 methods: method#0: Function1 *main.MyType1 has 2 methods: method#0: Function1 method#1: Function2 A strange behavior occurs when I replace the "type" embedded field with a "pointer type" embedded field (MyType1 now has *MyType2 instead of MyType2). So the code looks like this: package main import ( "fmt" "reflect" ) type MyType1 struct { *MyType2 } type MyType2 struct { } func (MyType2) Function1() { } func (*MyType2) Function2() { } func main() { t1 := reflect.TypeOf(MyType1{}) t2 := reflect.TypeOf(&MyType1{}) fmt.Println(t1, "has", t1.NumMethod(), "methods:") for i := 0; i < t1.NumMethod(); i++ { fmt.Print(" method#", i, ": ", t1.Method(i).Name, "\n") } fmt.Println(t2, "has", t2.NumMethod(), "methods:") for i := 0; i < t2.NumMethod(); i++ { fmt.Print(" method#", i, ": ", t2.Method(i).Name, "\n") } } Now what is actually the crux of the problem. The prints is: main.MyType1 has 2 methods: method#0: Function1 method#1: Function2 *main.MyType1 has 2 methods: method#0: Function1 method#1: Function2 So, somehow MyType1 also has method (MyType1)Function2() even though it is not declared as value receiver method for type MyType2. Does anyone have any logical explanation as to why this is happening?
[ "The simple explanation is: If type A embeds type B, type A gets all methods of type B.\nIn your first example, MyType2 is embedded into MyType1, and MyType2 has one function, Function1, so MyType1 also gets Function1.\nIn your second example, *MyType2 has two functions, Function1 and Function2, so MyType1 has both of those functions.\nThe important point here is that methods defined with a pointer receiver of type A are only defined for *A, and not for A. The reason for that is to provide proper semantics for interfaces.\nLet's say you have an interface:\ntype MyIntf interface {\n Function2()\n}\n\nIf there is a function:\nfunc f(m MyIntf) {\n m.Function2()\n}\n\nthen this property prevents you from passing MyType1 to f, because if it were allowed, the modifications f made on that object by calling Function2 would be lost. You can only pass MyType2, or the second MyType1 implementation, in which case any modifications made on m will be reflected on the passed instance of the value.\n" ]
[ 2 ]
[]
[]
[ "go" ]
stackoverflow_0074672810_go.txt
Q: How to populate camunda html form Select from Json I am trying to populate camunda html form select from json sent from my external service client. Here is my sent json - {myData=[{"id":1,"name":"This is one","value":"value11","localName":"this is local name 11"},{"id":2,"name":"This is Two","value":"value22","localName":"this is local name 22"}]} Here is my html form - <form> <div> <select cam-variable-type="String" cam-variable-name="selected_option" ng-options="item as item.name for item in myData track by item.id" ng-model="selected" class="form-control"> </select> </div> <script cam-script type="text/form-script"> camForm.on('form-loaded', function() { // tell the form SDK to fetch the variable named 'myData' camForm.variableManager.fetchVariable('myData'); }); camForm.on('variables-fetched', function() { // work with the variable (bind it to the current AngularJS $scope) $scope.myData = camForm.variableManager.variableValue('myData'); }); </script> </form> But it is coming up like below as undefined - And i can see my json myData in next step and it's values - Any help on how to populate my html form select from my json myData Thanks A: You should parse your process variable, because it has String type $scope.myData = JSON.parse(camForm.variableManager.variableValue('myData')); Without parsing your select ng-options ran through every letter in your string, that's why you had so many options in select instead of two. Also you didn't set correct id for ng-options. It must be like this: ng-options="item.id as item.name for item in myData track by item.id"
How to populate camunda html form Select from Json
I am trying to populate camunda html form select from json sent from my external service client. Here is my sent json - {myData=[{"id":1,"name":"This is one","value":"value11","localName":"this is local name 11"},{"id":2,"name":"This is Two","value":"value22","localName":"this is local name 22"}]} Here is my html form - <form> <div> <select cam-variable-type="String" cam-variable-name="selected_option" ng-options="item as item.name for item in myData track by item.id" ng-model="selected" class="form-control"> </select> </div> <script cam-script type="text/form-script"> camForm.on('form-loaded', function() { // tell the form SDK to fetch the variable named 'myData' camForm.variableManager.fetchVariable('myData'); }); camForm.on('variables-fetched', function() { // work with the variable (bind it to the current AngularJS $scope) $scope.myData = camForm.variableManager.variableValue('myData'); }); </script> </form> But it is coming up like below as undefined - And i can see my json myData in next step and it's values - Any help on how to populate my html form select from my json myData Thanks
[ "You should parse your process variable, because it has String type\n$scope.myData = JSON.parse(camForm.variableManager.variableValue('myData'));\n\nWithout parsing your select ng-options ran through every letter in your string, that's why you had so many options in select instead of two. Also you didn't set correct id for ng-options. It must be like this:\nng-options=\"item.id as item.name for item in myData track by item.id\"\n\n" ]
[ 0 ]
[]
[]
[ "camunda" ]
stackoverflow_0071750807_camunda.txt
Q: Seeking Proper Syntax for Calling a Function within a Function using Struct Datatypes My class assignment is to take a previous program where arrays were used, and replace them with structs instead. My struct program is not working. It is an issue with the struct syntax which is different than the array syntax. I get this error: invalid conversion from 'int' to 'candidateType*' from this line: int totalVotes = sumVotes(electionResults[i].votes, size); Here is my code: // STRUCT DEFINITIONS struct candidateType { string lastNames; int votes; int percentages; }; // FUNCTION PROTOTYPES int sumVotes(candidateType[], int); void display(const candidateType[], int); // FUNCTION TO CALCULATE SUM OF VOTES WITH STRUCT int sumVotes(candidateType electionResults[], int size) { int sum = 0.0; for (int i = 0; i < size; i++) { sum = sum + electionResults[i].votes; } return sum; } // FUNCTION TO CALL SUM OF VOTES FUNCTION AND DISPLAY // void display(const candidateType electionResults[], int size) { int i=0; int totalVotes = sumVotes(electionResults[i].votes, size); // ERROR OCCURS HERE!! cout <<endl << "Total " << fixed << setprecision(0) << totalVotes << endl; } A: Solved proper syntax was: int totalVotes = sumVotes(electionResults, size); reference to the parameter votes was unncessary with structs.
Seeking Proper Syntax for Calling a Function within a Function using Struct Datatypes
My class assignment is to take a previous program where arrays were used, and replace them with structs instead. My struct program is not working. It is an issue with the struct syntax which is different than the array syntax. I get this error: invalid conversion from 'int' to 'candidateType*' from this line: int totalVotes = sumVotes(electionResults[i].votes, size); Here is my code: // STRUCT DEFINITIONS struct candidateType { string lastNames; int votes; int percentages; }; // FUNCTION PROTOTYPES int sumVotes(candidateType[], int); void display(const candidateType[], int); // FUNCTION TO CALCULATE SUM OF VOTES WITH STRUCT int sumVotes(candidateType electionResults[], int size) { int sum = 0.0; for (int i = 0; i < size; i++) { sum = sum + electionResults[i].votes; } return sum; } // FUNCTION TO CALL SUM OF VOTES FUNCTION AND DISPLAY // void display(const candidateType electionResults[], int size) { int i=0; int totalVotes = sumVotes(electionResults[i].votes, size); // ERROR OCCURS HERE!! cout <<endl << "Total " << fixed << setprecision(0) << totalVotes << endl; }
[ "Solved proper syntax was:\nint totalVotes = sumVotes(electionResults, size);\nreference to the parameter votes was unncessary with structs.\n" ]
[ 0 ]
[]
[]
[ "c++", "struct" ]
stackoverflow_0074672733_c++_struct.txt
Q: check mariadb connection with c++ (without dependencies) I got myself a programm where a user types in their mariadb credentials (username/password/port). I now want the programm to check if this connection is working or if something is wrong. Right now I am running processes with CreateProcess but since statements like mysql -u root -pwrongpassword will still run through without any errors, this doesn't work. I want such a statement, or just a generic connection check, to return false when those credentials turn out as wrong. Important here is that it has to work without any existing software on the target system (except mariadb if necessary for your solution). What would be a solid practice for that task? A: Reinventing the wheel (as suggested by Sam Varshavchik) is not a good idea: It's not just opening a socket, writing and reading data. Depending on the authentication options you have to support SSL/TLS and the various authentication methods (native password, ed25519, sha256_caching_password, sha256_password, gssapi/kerberos) which is quite complex. Since you mentioned that MariaDB is installed on your target system, you can use the mariadb client library (MariaDB Connector/C), which is also used by mysql command line client. It is installed together with the server package. #include <mysql.h> int check_connection(const char *user, const char *password, int port) { int rc= 0; MYSQL *mysql= mysql_init(NULL); if (mysql_real_connect(mysql, "localhost", user, password, NULL, port, NULL, 0)) rc= 1; mysql_close(mysql); return rc; } Now you have to link your application against libmariadb.lib (dynamic linking) or mariadbclient.lib (static linking).
check mariadb connection with c++ (without dependencies)
I got myself a programm where a user types in their mariadb credentials (username/password/port). I now want the programm to check if this connection is working or if something is wrong. Right now I am running processes with CreateProcess but since statements like mysql -u root -pwrongpassword will still run through without any errors, this doesn't work. I want such a statement, or just a generic connection check, to return false when those credentials turn out as wrong. Important here is that it has to work without any existing software on the target system (except mariadb if necessary for your solution). What would be a solid practice for that task?
[ "Reinventing the wheel (as suggested by Sam Varshavchik) is not a good idea: It's not just opening a socket, writing and reading data. Depending on the authentication options you have to support SSL/TLS and the various authentication methods (native password, ed25519, sha256_caching_password, sha256_password, gssapi/kerberos) which is quite complex.\nSince you mentioned that MariaDB is installed on your target system, you can use the mariadb client library (MariaDB Connector/C), which is also used by mysql command line client. It is installed together with the server package.\n#include <mysql.h>\n\nint check_connection(const char *user, const char *password, int port)\n{\n int rc= 0;\n MYSQL *mysql= mysql_init(NULL);\n\n if (mysql_real_connect(mysql, \"localhost\", user, password, NULL, port, NULL, 0))\n rc= 1;\n\n mysql_close(mysql);\n return rc;\n}\n\nNow you have to link your application against libmariadb.lib (dynamic linking) or mariadbclient.lib (static linking).\n" ]
[ 1 ]
[]
[]
[ "c++", "createprocess", "database_connection", "mariadb", "sql" ]
stackoverflow_0074672571_c++_createprocess_database_connection_mariadb_sql.txt
Q: creating a crop-image effect for container with scss I have a modal where I want to display a certain amount of picture in a window, but show the full picture (the overlay) in the background. Basically if the amount of picture to be shown (the window) is 100px wide, but the picture itself is 150px wide, you'd see the picture as is in the window (opacity: 1;) but the overflow of the picture would be faded slightly, to give the effect that it would not be seen if the photo was cropped as is. Right now my modal looks like this: Its code: <div> <div className="d-grid"> <h4>Crop</h4> <Button variant="primary" onClick={() => setModalShow(true)}> Thumbnail </Button> <Modal show={modalShow} onHide={() => setModalShow(false)} size="lg" aria-labelledby="contained-modal-title-vcenter" centered animation={false} > <Modal.Header closeButton> <Modal.Title id="contained-modal-title-vcenter">Crop</Modal.Title> </Modal.Header> {selectedThumb ? ( <div> <Modal.Body className="crop-container"> <div className="visible"> {" "} <img className="pic" src={previewThumb} alt="" /> </div> </Modal.Body> <Modal.Footer> <Button>Crop</Button> </Modal.Footer> </div> ) : ( <Modal.Body> <div> You cannot crop or adjust an image that does not exist. Go back and upload a file, dummy. </div> </Modal.Body> )} </Modal> </div> </div> $width: 254.98px; $height: 143.42px; $channel-pic-width: 38px; $channel-pic-height: 38px; $title-font: 14px; $desc-font: 12.5px; .crop-container { min-height: 400px; // overflow: hidden; .visible { border: 5px solid red; aspect-ratio: $width / $height; width: 200px; height: 200px; } .pic { width: 100%; } } The functionality behind actually cropping the photo is not what I'm worried about right now, although I probably should. What I need now are three things: A modal that will fit all content (including the overflowing picture) inside it. A window (width: 200px; height: 100px; -- the actual size doesn't matter as long as it's smaller than the picture) Some kind of overlay to make the part of the picture that's overflowing (outside of the window dimensions) have a lower opacity than the window. A: Here is a possible solution that uses ::before and ::after pseudo elements on the crop window to create the crop border and the overlay. ::before works as the overlay for the overflowing part of image: .window::before { content: ""; position: absolute; inset: 0; opacity: 0.8; outline: 250px solid white; z-index: 50; } ::after works as the crop border on top of image: .window::after { content: ""; position: absolute; inset: 0; outline: 5px solid tomato; z-index: 75; } There are some buttons in below example to move the picture around, which are for testing only. These can be safely removed should this project choose a different approach for functionality. The example runs in snippet for convenience: function Crop({ image, boxSizeX, boxSizeY, step }) { const [imgX, setImgX] = React.useState(0); const [imgY, setImgY] = React.useState(0); const imgRef = React.useRef(null); const [imgNatural, setImgNatural] = React.useState({ width: 0, height: 0 }); const handleImageLoad = () => setImgNatural({ width: imgRef.current.naturalWidth, height: imgRef.current.naturalHeight, }); const rangeX = imgNatural.width ? Math.abs((boxSizeX - imgNatural.width) / 2) : 100; const rangeY = imgNatural.height ? Math.abs((boxSizeY - imgNatural.height) / 2) : 100; return ( <div className="modal"> <div className="window" style={{ width: `${boxSizeX}px`, height: `${boxSizeY}px` }} > <img src={image} alt="" ref={imgRef} onLoad={handleImageLoad} style={{ transform: `translate(${imgX}px, ${imgY}px)`, }} /> </div> <button onClick={() => { setImgY((prev) => (prev -= step)); }} disabled={imgY <= -rangeY ? true : false} > </button> <button onClick={() => { setImgY((prev) => (prev += step)); }} disabled={imgY >= rangeY ? true : false} > </button> <button onClick={() => { setImgX((prev) => (prev -= step)); }} disabled={imgX <= -rangeX ? true : false} > </button> <button onClick={() => { setImgX((prev) => (prev += step)); }} disabled={imgX >= rangeX ? true : false} > </button> </div> ); } const App = () => { return ( <div className="app"> <Crop image={"https://picsum.photos/400/300"} boxSizeX={200} boxSizeY={200} step={10} /> </div> ); }; ReactDOM.render(<App />, document.querySelector("#root")); body { display: flex; justify-content: center; align-items: center; min-height: 100vh; } .modal { width: 450px; height: 350px; border-radius: 10px; overflow: hidden; display: flex; justify-content: center; align-items: center; position: relative; outline: 5px solid darkseagreen; } .window { background-color: pink; display: flex; justify-content: center; align-items: center; position: relative; } .window > img { z-index: 25; } .window::before { content: ""; position: absolute; inset: 0; opacity: 0.8; outline: 250px solid white; z-index: 50; } .window::after { content: ""; position: absolute; inset: 0; outline: 5px solid tomato; z-index: 75; } button { position: absolute; padding: 6px; z-index: 100; } button:disabled { opacity: 0.3; } button:nth-of-type(1) { top: 25px; } button:nth-of-type(2) { bottom: 25px; } button:nth-of-type(3) { left: 70px; } button:nth-of-type(4) { right: 70px; } <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.production.min.js"></script> A: You could use background-blend-mode. let imageContainer = document.getElementById("image-container"); imageContainer.onmousemove = function(e) { let overlay = document.getElementById("overlay"); overlay.style.left = e.offsetX + "px"; overlay.style.top = e.offsetY + "px"; }; div { position: relative; width: 500px; height: 300px; background-image: url("https://images.pexels.com/photos/533769/pexels-photo-533769.jpeg"); background-color: rgba(0, 0, 0, 0.5); background-blend-mode: multiply; background-attachment: fixed; overflow: hidden; } #overlay { position:absolute; width: 200px; height: 100px; background-blend-mode: normal; pointer-events: none; } <div id="image-container"> <div id="overlay"></div> </div> A: One way to accomplish this would be to set the overflow property on the .visible class to hidden, and then add a ::before pseudo-element to the .visible class with the same dimensions as the window and a lower opacity. Here is an example of how you could achieve this: <div> <div className="d-grid"> <h4>Crop</h4> <Button variant="primary" onClick={() => setModalShow(true)}> Thumbnail </Button> <Modal show={modalShow} onHide={() => setModalShow(false)} size="lg" aria-labelledby="contained-modal-title-vcenter" centered animation={false} > <Modal.Header closeButton> <Modal.Title id="contained-modal-title-vcenter">Crop</Modal.Title> </Modal.Header> {selectedThumb ? ( <div> <Modal.Body className="crop-container"> <div className="visible"> <div class="window"> <img className="pic" src={previewThumb} alt="" /> </div> </div> </Modal.Body> <Modal.Footer> <Button>Crop</Button> </Modal.Footer> </div> ) : ( <Modal.Body> <div> You cannot crop or adjust an image that does not exist. Go back and upload a file, dummy. </div> </Modal.Body> )} </Modal> </div> </div> The ::before pseudo-element will create an overlay with a white background and a 50% opacity (rgba(255, 255, 255, 0.5)) on top of the part of the image that overflows the window. You can adjust the dimensions of the window and the opacity of the overlay as needed. A: background: linear-gradient(to bottom, rgba(url(' yourimg '), 0.0), rgba(url('yourimg'), 1.0));
creating a crop-image effect for container with scss
I have a modal where I want to display a certain amount of picture in a window, but show the full picture (the overlay) in the background. Basically if the amount of picture to be shown (the window) is 100px wide, but the picture itself is 150px wide, you'd see the picture as is in the window (opacity: 1;) but the overflow of the picture would be faded slightly, to give the effect that it would not be seen if the photo was cropped as is. Right now my modal looks like this: Its code: <div> <div className="d-grid"> <h4>Crop</h4> <Button variant="primary" onClick={() => setModalShow(true)}> Thumbnail </Button> <Modal show={modalShow} onHide={() => setModalShow(false)} size="lg" aria-labelledby="contained-modal-title-vcenter" centered animation={false} > <Modal.Header closeButton> <Modal.Title id="contained-modal-title-vcenter">Crop</Modal.Title> </Modal.Header> {selectedThumb ? ( <div> <Modal.Body className="crop-container"> <div className="visible"> {" "} <img className="pic" src={previewThumb} alt="" /> </div> </Modal.Body> <Modal.Footer> <Button>Crop</Button> </Modal.Footer> </div> ) : ( <Modal.Body> <div> You cannot crop or adjust an image that does not exist. Go back and upload a file, dummy. </div> </Modal.Body> )} </Modal> </div> </div> $width: 254.98px; $height: 143.42px; $channel-pic-width: 38px; $channel-pic-height: 38px; $title-font: 14px; $desc-font: 12.5px; .crop-container { min-height: 400px; // overflow: hidden; .visible { border: 5px solid red; aspect-ratio: $width / $height; width: 200px; height: 200px; } .pic { width: 100%; } } The functionality behind actually cropping the photo is not what I'm worried about right now, although I probably should. What I need now are three things: A modal that will fit all content (including the overflowing picture) inside it. A window (width: 200px; height: 100px; -- the actual size doesn't matter as long as it's smaller than the picture) Some kind of overlay to make the part of the picture that's overflowing (outside of the window dimensions) have a lower opacity than the window.
[ "Here is a possible solution that uses ::before and ::after pseudo elements on the crop window to create the crop border and the overlay.\n::before works as the overlay for the overflowing part of image:\n.window::before {\n content: \"\";\n position: absolute;\n inset: 0;\n opacity: 0.8;\n outline: 250px solid white;\n z-index: 50;\n}\n\n::after works as the crop border on top of image:\n.window::after {\n content: \"\";\n position: absolute;\n inset: 0;\n outline: 5px solid tomato;\n z-index: 75;\n}\n\nThere are some buttons in below example to move the picture around, which are for testing only. These can be safely removed should this project choose a different approach for functionality.\nThe example runs in snippet for convenience:\n\n\nfunction Crop({ image, boxSizeX, boxSizeY, step }) {\n const [imgX, setImgX] = React.useState(0);\n const [imgY, setImgY] = React.useState(0);\n\n const imgRef = React.useRef(null);\n const [imgNatural, setImgNatural] = React.useState({ width: 0, height: 0 });\n\n const handleImageLoad = () =>\n setImgNatural({\n width: imgRef.current.naturalWidth,\n height: imgRef.current.naturalHeight,\n });\n\n const rangeX = imgNatural.width\n ? Math.abs((boxSizeX - imgNatural.width) / 2)\n : 100;\n\n const rangeY = imgNatural.height\n ? Math.abs((boxSizeY - imgNatural.height) / 2)\n : 100;\n\n return (\n <div className=\"modal\">\n <div\n className=\"window\"\n style={{ width: `${boxSizeX}px`, height: `${boxSizeY}px` }}\n >\n <img\n src={image}\n alt=\"\"\n ref={imgRef}\n onLoad={handleImageLoad}\n style={{\n transform: `translate(${imgX}px, ${imgY}px)`,\n }}\n />\n </div>\n <button\n onClick={() => {\n setImgY((prev) => (prev -= step));\n }}\n disabled={imgY <= -rangeY ? true : false}\n >\n \n </button>\n <button\n onClick={() => {\n setImgY((prev) => (prev += step));\n }}\n disabled={imgY >= rangeY ? true : false}\n >\n \n </button>\n <button\n onClick={() => {\n setImgX((prev) => (prev -= step));\n }}\n disabled={imgX <= -rangeX ? true : false}\n >\n \n </button>\n <button\n onClick={() => {\n setImgX((prev) => (prev += step));\n }}\n disabled={imgX >= rangeX ? true : false}\n >\n \n </button>\n </div>\n );\n}\n\nconst App = () => {\n return (\n <div className=\"app\">\n <Crop\n image={\"https://picsum.photos/400/300\"}\n boxSizeX={200}\n boxSizeY={200}\n step={10}\n />\n </div>\n );\n};\n\nReactDOM.render(<App />, document.querySelector(\"#root\"));\nbody {\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 100vh;\n}\n\n.modal {\n width: 450px;\n height: 350px;\n border-radius: 10px;\n overflow: hidden;\n display: flex;\n justify-content: center;\n align-items: center;\n position: relative;\n outline: 5px solid darkseagreen;\n}\n\n.window {\n background-color: pink;\n display: flex;\n justify-content: center;\n align-items: center;\n position: relative;\n}\n\n.window > img {\n z-index: 25;\n}\n\n.window::before {\n content: \"\";\n position: absolute;\n inset: 0;\n opacity: 0.8;\n outline: 250px solid white;\n z-index: 50;\n}\n\n.window::after {\n content: \"\";\n position: absolute;\n inset: 0;\n outline: 5px solid tomato;\n z-index: 75;\n}\n\nbutton {\n position: absolute;\n padding: 6px;\n z-index: 100;\n}\n\nbutton:disabled {\n opacity: 0.3;\n}\n\nbutton:nth-of-type(1) {\n top: 25px;\n}\n\nbutton:nth-of-type(2) {\n bottom: 25px;\n}\n\nbutton:nth-of-type(3) {\n left: 70px;\n}\n\nbutton:nth-of-type(4) {\n right: 70px;\n}\n<div id=\"root\"></div>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.production.min.js\"></script>\n\n\n\n", "You could use background-blend-mode.\n\n\nlet imageContainer = document.getElementById(\"image-container\");\nimageContainer.onmousemove = function(e) {\n let overlay = document.getElementById(\"overlay\");\n overlay.style.left = e.offsetX + \"px\";\n overlay.style.top = e.offsetY + \"px\";\n};\ndiv {\n position: relative;\n width: 500px;\n height: 300px;\n background-image: url(\"https://images.pexels.com/photos/533769/pexels-photo-533769.jpeg\");\n background-color: rgba(0, 0, 0, 0.5);\n background-blend-mode: multiply;\n background-attachment: fixed;\n overflow: hidden;\n}\n\n#overlay {\n position:absolute;\n width: 200px;\n height: 100px;\n background-blend-mode: normal;\n pointer-events: none;\n}\n<div id=\"image-container\">\n <div id=\"overlay\"></div>\n</div>\n\n\n\n", "One way to accomplish this would be to set the overflow property on the .visible class to hidden, and then add a ::before pseudo-element to the .visible class with the same dimensions as the window and a lower opacity.\nHere is an example of how you could achieve this:\n<div>\n <div className=\"d-grid\">\n <h4>Crop</h4>\n <Button variant=\"primary\" onClick={() => setModalShow(true)}>\n Thumbnail\n </Button>\n <Modal\n show={modalShow}\n onHide={() => setModalShow(false)}\n size=\"lg\"\n aria-labelledby=\"contained-modal-title-vcenter\"\n centered\n animation={false}\n >\n <Modal.Header closeButton>\n <Modal.Title id=\"contained-modal-title-vcenter\">Crop</Modal.Title>\n </Modal.Header>\n {selectedThumb ? (\n <div>\n <Modal.Body className=\"crop-container\">\n <div className=\"visible\">\n <div class=\"window\">\n <img className=\"pic\" src={previewThumb} alt=\"\" />\n </div>\n </div>\n </Modal.Body>\n <Modal.Footer>\n <Button>Crop</Button>\n </Modal.Footer>\n </div>\n ) : (\n <Modal.Body>\n <div>\n You cannot crop or adjust an image that does not exist. Go back\n and upload a file, dummy.\n </div>\n </Modal.Body>\n )}\n </Modal>\n </div>\n</div>\n\nThe ::before pseudo-element will create an overlay with a white background and a 50% opacity (rgba(255, 255, 255, 0.5)) on top of the part of the image that overflows the window. You can adjust the dimensions of the window and the opacity of the overlay as needed.\n", "background: linear-gradient(to bottom, rgba(url(' yourimg '), 0.0), rgba(url('yourimg'), 1.0));\n" ]
[ 2, 0, 0, 0 ]
[]
[]
[ "css", "html", "reactjs", "sass" ]
stackoverflow_0074564802_css_html_reactjs_sass.txt
Q: Can't connect to mysql docker container from springboot docker container I want to connect from the sprinboot container to the mysql container but i get this error: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure I am using docker-compose. This is my docker-compose file: version: '3' services: trips-db: image: "mysql" container_name: "trips-db" volumes: - newDatabase:/home/sharedData ports: - 49152:3306 environment: - MYSQL_USER=adham - MYSQL_PASSWORD=123 - MYSQL_ROOT_PASSWORD=admin trips-app: build: ./Wasalny_BE container_name: trips-app ports: - 8080:8080 links: - trips-db volumes: newDatabase: This is my spring boot docker file: FROM openjdk:8-jdk-alpine COPY target/wasalny-0.0.1-SNAPSHOT.jar app.jar EXPOSE 8080 ENTRYPOINT ["java","-jar","/app.jar"] This is my application.properties file: spring.datasource.url= jdbc:mysql://trips-db:49152/wslny?allowPublicKeyRetrieval=true&useSSL=false&createDatabaseIfNotExist=true spring.datasource.username= root spring.datasource.password= admin spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.hibernate.ddl-auto= update I run using the following command form the terminal: docker-compose up -d --force-recreate A: Please create a docker network and attach it into the compose file. Create a docker Network first like below. docker network create ext-network Add network settings into your yaml file as below and give a try version: '3' services: trips-db: image: "mysql" container_name: "trips-db" volumes: - newDatabase:/home/sharedData ports: - 49152:3306 networks: - ext-network environment: - MYSQL_USER=adham - MYSQL_PASSWORD=123 - MYSQL_ROOT_PASSWORD=admin trips-app: build: ./Wasalny_BE container_name: trips-app ports: - 8080:8080 networks: - ext-network links: - trips-db networks: ext-network: external: true volumes: newDatabase:
Can't connect to mysql docker container from springboot docker container
I want to connect from the sprinboot container to the mysql container but i get this error: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure I am using docker-compose. This is my docker-compose file: version: '3' services: trips-db: image: "mysql" container_name: "trips-db" volumes: - newDatabase:/home/sharedData ports: - 49152:3306 environment: - MYSQL_USER=adham - MYSQL_PASSWORD=123 - MYSQL_ROOT_PASSWORD=admin trips-app: build: ./Wasalny_BE container_name: trips-app ports: - 8080:8080 links: - trips-db volumes: newDatabase: This is my spring boot docker file: FROM openjdk:8-jdk-alpine COPY target/wasalny-0.0.1-SNAPSHOT.jar app.jar EXPOSE 8080 ENTRYPOINT ["java","-jar","/app.jar"] This is my application.properties file: spring.datasource.url= jdbc:mysql://trips-db:49152/wslny?allowPublicKeyRetrieval=true&useSSL=false&createDatabaseIfNotExist=true spring.datasource.username= root spring.datasource.password= admin spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.hibernate.ddl-auto= update I run using the following command form the terminal: docker-compose up -d --force-recreate
[ "Please create a docker network and attach it into the compose file.\nCreate a docker Network first like below.\ndocker network create ext-network\nAdd network settings into your yaml file as below and give a try\nversion: '3'\nservices:\n\n trips-db:\n image: \"mysql\"\n container_name: \"trips-db\"\n volumes:\n - newDatabase:/home/sharedData\n ports:\n - 49152:3306\n networks:\n - ext-network\n environment:\n - MYSQL_USER=adham\n - MYSQL_PASSWORD=123 \n - MYSQL_ROOT_PASSWORD=admin\n\n trips-app:\n build: ./Wasalny_BE\n container_name: trips-app\n ports:\n - 8080:8080\n networks:\n - ext-network\n links:\n - trips-db\n \nnetworks:\n ext-network:\n external: true\n\nvolumes: \n newDatabase:\n\n" ]
[ 0 ]
[]
[]
[ "containers", "devops", "docker", "mysql", "spring_boot" ]
stackoverflow_0074646681_containers_devops_docker_mysql_spring_boot.txt
Q: How to merge a ZodEffect with a ZodObject I have two schemas, I would like to re-use the first schema in the second schema, this works fine when the first schema does not use the refine nor super-fine methods. According to the documentation, this should be possible by simply passing the second schema as an argument for the merge method in the first schema. I receive a type error saying that the first schema is of type ZodEffects, is there a way to infer the underlying object? import { z } from 'zod'; const FirstSchema = z.object({ name: z.string().min(1), }); const SeccondSchema = z .object({ lastname: z.string().min(1), }) .refine((data) => data.lastname.includes('foo')); const MergedSchema = FirstSchema.merge(SeccondSchema); // <-- How to convert ZodEffect to ZodObject? Here's an example in Stack Blitz with my error: https://stackblitz.com/edit/typescript-r9on2v?file=index.ts A: Solved by using the innerType method const MergedSchema = FirstSchema.merge(SeccondSchema.innerType());
How to merge a ZodEffect with a ZodObject
I have two schemas, I would like to re-use the first schema in the second schema, this works fine when the first schema does not use the refine nor super-fine methods. According to the documentation, this should be possible by simply passing the second schema as an argument for the merge method in the first schema. I receive a type error saying that the first schema is of type ZodEffects, is there a way to infer the underlying object? import { z } from 'zod'; const FirstSchema = z.object({ name: z.string().min(1), }); const SeccondSchema = z .object({ lastname: z.string().min(1), }) .refine((data) => data.lastname.includes('foo')); const MergedSchema = FirstSchema.merge(SeccondSchema); // <-- How to convert ZodEffect to ZodObject? Here's an example in Stack Blitz with my error: https://stackblitz.com/edit/typescript-r9on2v?file=index.ts
[ "Solved by using the innerType method\n\nconst MergedSchema = FirstSchema.merge(SeccondSchema.innerType());\n\n" ]
[ 0 ]
[]
[]
[ "typescript", "zod" ]
stackoverflow_0074672399_typescript_zod.txt
Q: Linking to a specific part of a web page How do I create a link to a part of long webpage on another website that I don't control? I thought you could use a variant of the #partofpage at the end of my link. Any suggestions? A: Just append a # followed by the ID of the <a> tag (or other HTML tag, like a <section>) that you're trying to get to. For example, if you are trying to link to the header in this HTML: <p>This is some content.</p> <h2><a id="target">Some Header</a></h2> <p>This is some more content.</p> You could use the link <a href="http://url.to.site/index.html#target">Link</a>. A: Create a "jump link" using the following format: http://www.example.com/somepage#anchor Where anchor is the id of the element you wish to link to on that page. Use browser development tools / view source to find the id of the element you wish to link to. If the element doesn't have an id and you don't control that site then you can't do it. A: That is only possible if that site has declared anchors in the page. It is done by giving a tag a name or id attribute, so look for any of those close to where you want to link to. And then the syntax would be <a href="page.html#anchor">text</a> A: In case the target page is on the same domain (i.e. shares the same origin with your page) and you don't mind creation of new tabs (1), you can (ab)use some JavaScript: <a href="javascript:void(window.open('./target.html').onload=function(){this.document.querySelector('p:nth-child(10)').scrollIntoView()})">see tenth paragraph on another page</a> Trivia: var w = window.open('some URL of the same origin'); w.onload = function(){ // do whatever you want with `this.document`, like this.document.querySelecotor('footer').scrollIntoView() } Working example of such 'exploit' you can try right now could be: javascript:(function(url,sel,w,el){w=window.open(url);w.addEventListener('load',function(){w.setTimeout(function(){el=w.document.querySelector(sel);el.scrollIntoView();el.style.backgroundColor='red'},1000)})})('https://stackoverflow.com/questions/45014240/link-to-a-specific-spot-on-a-page-i-cant-edit','footer') If you enter this into location bar (mind that Chrome removes javascript: prefix when pasted from clipboard) or make it a href value of any link on this page (using Developer Tools) and click it, you will get another (duplicate) SO question page scrolled to the footer and footer painted red. (Delay added as a workaround for ajax-loaded content pushing footer down after load.) Notes Tested in current Chrome and Firefox, generally should work since it is based on defined standard behaviour. Cannot be illustrated in interactive snippet here at SO, because they are isolated from the page origin-wise. MDN: Window.open() (1) window.open(url,'_self') seems to be breaking the load event; basically makes the window.open behave like a normal a href="" click navigation; haven't researched more yet. A: The upcoming Chrome "Scroll to text" feature is exactly what you are looking for.... https://github.com/bokand/ScrollToTextFragment You basically add #targetText= at the end of the URL and the browser will scroll to the target text and highlight it after the page is loaded. It is in the version of Chrome that is running on my desk, but currently it must be manually enabled. Presumably it will soon be enabled by default in the production Chrome builds and other browsers will follow, so OK to start adding to your links now and it will start working then. Edit: It's been implemented in Chrome. See https://chromestatus.com/feature/4733392803332096 A: First off target refers to the BlockID found in either HTML code or chromes developer tools that you are trying to link to. Each code is different and you will need to do some digging to find the ID you are trying to reference. It should look something like div class="page-container drawer-page-content" id"PageContainer"Note that this is the format for the whole referenced section, not an individual text or image. To do that you would need to find the same piece of code but relating to your target block. For example dv id="your-block-id" Anyways I was just reading over this thread and an idea came to my mind, if you are a Shopify user and want to do this it is pretty much the same thing as stated. But instead of > http://url.to.site.example/index.html#target You would put > http://example.com/target For example, I am setting up a disclaimer page with links leading to a newsletter signup and shopping blocks on my home page so I insert https://mystore-classifier.com/#shopify-section-1528945200235 for my hyperlink. Please note that the -classifier is for my internal use and doesn't apply to you. This is just so I can keep track of my stores. If you want to link to something other than your homepage you would put > http://mystore-classifier.example/pagename/#BlockID I hope someone found this useful, if there is something wrong with my explanation please let me know as I am not an HTML programmer my language is C#! A: You can NOW... As of Chrome release 81 (Feb 2020), there is a new feature called Text Fragments. It allows you to provide a link that opens at the precise text specified (with that text highlighted). At the moment, it works in Edge, Chrome and Opera but not in Firefox, Safari or Brave. (See note 6 at bottom for more) For security reasons, the feature requires links to be opened in a noopener context. Therefore, make sure to include rel="noopener" in your anchor markup or add noopener to your Window.open() list of window functionality features. You create the link to your desired text by appending this string to the end of the URL: /#:~:text= and providing the percent-encoded search string thus: /#:~:text=String%20to%20focus%20on Here is a working example: https://newz.icu/#:~:text=Google%20surveillance%20increases Notes: Test the above link in Chrome or Opera only In the above example, note that the text string is in a div that is normally hidden on page load - so in this example it is being displayed despite what would normally happen. Useful. Recent versions of Chrome also include a new option when you Right-Click on selected text: Copy link to highlight. This will auto-create the direct-to-text link for you (i.e. it automatically appends the /#:~:text= to the text you highlighted) and place it in the clipboard - just paste it where desired. Suppose you want to highlight an entire block of text? The Text Fragments feature allows specifying a starting%20phrase and an ending%20phrase (separated by a comma), and it will highlight all text in between: https://newz.icu/#:~:text=Dr.%20Mullis,before%20now Note the comma between Mullis and before web.dev article about Text Fragments CanIUse status of Text Fragments PS - Please forgive choice of example website. It simply had the desired elements required for the demonstration. Hoping we can focus on function rather than content. A: Basically, html tag can have id="abc" as shown below: <div id="abc">test</div> <p id="abc">test</p> <span id="abc">test</span> <a id="abc">test</a> And, "<a>" tag can also have name="abc" as shown below: <a name="abc">test</a> Then, you can use the id and name values "abc" with "#" in urls as shown below to go to the specific part of a page: https://www.example.com/#abc https://www.example.com/index.html#abc Then, you can put the urls above in "<a>" tag to create the links to id="abc" and name="abc" as shown below: <a href="https://www.example.com/#abc">test</a> <a href="https://www.example.com/index.html#abc">test</a> And, if you want to go to the specific part of the same page, you can only put the id and name values "abc" with "#" in "<a>" tag to create the links to id="abc" and name="abc" as shown below: <!-- Go to the specific part of the same page --> <a href="#abc">test</a> <div id="abc">test</div> <!-- Go to the specific part of the same page --> <a href="#abc">test</a> <a name="abc">test</a> A: It's now possible to create an "anchor" link that goes to a specific part of any webpage in most browsers in a few different ways. All of them will create a link with an #anchor at the end, where "anchor" is the thing that you want to navigate to. The browser will interpret the part of the URL after the # to scroll to a specific part of the page. Here are 3 ways to create a url like this: Using an existing anchor. Perhaps there will be one in the URL as you scroll down the page. If not, look around the page for a header that has a little link icon to the left of it and click it to update the browsers navigation url. Using any html element's id property or the name or id on an ("anchor") element. The other answers explain this quite well. You will have to open the developer console and inspect the part of the page to find an id (and you may not find one). It's a little different on each browser, but here's how to inspect an element in Chrome. Using a text snippet to highlight part of the page.
Linking to a specific part of a web page
How do I create a link to a part of long webpage on another website that I don't control? I thought you could use a variant of the #partofpage at the end of my link. Any suggestions?
[ "Just append a # followed by the ID of the <a> tag (or other HTML tag, like a <section>) that you're trying to get to. For example, if you are trying to link to the header in this HTML:\n<p>This is some content.</p>\n<h2><a id=\"target\">Some Header</a></h2>\n<p>This is some more content.</p>\n\nYou could use the link <a href=\"http://url.to.site/index.html#target\">Link</a>.\n", "Create a \"jump link\" using the following format:\nhttp://www.example.com/somepage#anchor\n\nWhere anchor is the id of the element you wish to link to on that page. Use browser development tools / view source to find the id of the element you wish to link to.\nIf the element doesn't have an id and you don't control that site then you can't do it.\n", "That is only possible if that site has declared anchors in the page.\nIt is done by giving a tag a name or id attribute, so look for any of those close to where you want to link to.\nAnd then the syntax would be\n<a href=\"page.html#anchor\">text</a>\n\n", "In case the target page is on the same domain (i.e. shares the same origin with your page) and you don't mind creation of new tabs (1), you can (ab)use some JavaScript:\n<a href=\"javascript:void(window.open('./target.html').onload=function(){this.document.querySelector('p:nth-child(10)').scrollIntoView()})\">see tenth paragraph on another page</a>\nTrivia:\nvar w = window.open('some URL of the same origin');\nw.onload = function(){\n // do whatever you want with `this.document`, like\n this.document.querySelecotor('footer').scrollIntoView()\n}\n\nWorking example of such 'exploit' you can try right now could be:\njavascript:(function(url,sel,w,el){w=window.open(url);w.addEventListener('load',function(){w.setTimeout(function(){el=w.document.querySelector(sel);el.scrollIntoView();el.style.backgroundColor='red'},1000)})})('https://stackoverflow.com/questions/45014240/link-to-a-specific-spot-on-a-page-i-cant-edit','footer')\nIf you enter this into location bar (mind that Chrome removes javascript: prefix when pasted from clipboard) or make it a href value of any link on this page (using Developer Tools) and click it, you will get another (duplicate) SO question page scrolled to the footer and footer painted red. (Delay added as a workaround for ajax-loaded content pushing footer down after load.)\nNotes\n\nTested in current Chrome and Firefox, generally should work since it is based on defined standard behaviour.\nCannot be illustrated in interactive snippet here at SO, because they are isolated from the page origin-wise.\nMDN: Window.open()\n(1) window.open(url,'_self') seems to be breaking the load event; basically makes the window.open behave like a normal a href=\"\" click navigation; haven't researched more yet.\n\n", "The upcoming Chrome \"Scroll to text\" feature is exactly what you are looking for....\nhttps://github.com/bokand/ScrollToTextFragment\nYou basically add #targetText= at the end of the URL and the browser will scroll to the target text and highlight it after the page is loaded.\nIt is in the version of Chrome that is running on my desk, but currently it must be manually enabled. Presumably it will soon be enabled by default in the production Chrome builds and other browsers will follow, so OK to start adding to your links now and it will start working then.\nEdit: It's been implemented in Chrome. See https://chromestatus.com/feature/4733392803332096\n", "First off target refers to the BlockID found in either HTML code or chromes developer tools that you are trying to link to. Each code is different and you will need to do some digging to find the ID you are trying to reference. It should look something like div class=\"page-container drawer-page-content\" id\"PageContainer\"Note that this is the format for the whole referenced section, not an individual text or image. To do that you would need to find the same piece of code but relating to your target block. For example dv id=\"your-block-id\" Anyways I was just reading over this thread and an idea came to my mind, if you are a Shopify user and want to do this it is pretty much the same thing as stated.\nBut instead of\n> http://url.to.site.example/index.html#target\n\nYou would put\n> http://example.com/target\n\nFor example, I am setting up a disclaimer page with links leading to a newsletter signup and shopping blocks on my home page so I insert https://mystore-classifier.com/#shopify-section-1528945200235 for my hyperlink.\nPlease note that the -classifier is for my internal use and doesn't apply to you. This is just so I can keep track of my stores.\nIf you want to link to something other than your homepage you would put\n> http://mystore-classifier.example/pagename/#BlockID\n\nI hope someone found this useful, if there is something wrong with my explanation please let me know as I am not an HTML programmer my language is C#!\n", "You can NOW...\nAs of Chrome release 81 (Feb 2020), there is a new feature called Text Fragments. It allows you to provide a link that opens at the precise text specified (with that text highlighted).\nAt the moment, it works in Edge, Chrome and Opera but not in Firefox, Safari or Brave. (See note 6 at bottom for more)\n\nFor security reasons, the feature requires links to be opened in a noopener context. Therefore, make sure to include rel=\"noopener\" in your anchor markup or add noopener to your Window.open() list of window functionality features.\n\nYou create the link to your desired text by appending this string to the end of the URL:\n/#:~:text=\n\nand providing the percent-encoded search string thus:\n /#:~:text=String%20to%20focus%20on\n\nHere is a working example:\nhttps://newz.icu/#:~:text=Google%20surveillance%20increases\nNotes:\n\nTest the above link in Chrome or Opera only\n\nIn the above example, note that the text string is in a div that is normally hidden on page load - so in this example it is being displayed despite what would normally happen. Useful.\n\nRecent versions of Chrome also include a new option when you Right-Click on selected text: Copy link to highlight. This will auto-create the direct-to-text link for you (i.e. it automatically appends the /#:~:text= to the text you highlighted) and place it in the clipboard - just paste it where desired.\n\nSuppose you want to highlight an entire block of text? The Text Fragments feature allows specifying a starting%20phrase and an ending%20phrase (separated by a comma), and it will highlight all text in between:\n\nhttps://newz.icu/#:~:text=Dr.%20Mullis,before%20now\n\nNote the comma between Mullis and before\n\nweb.dev article about Text Fragments\n\nCanIUse status of Text Fragments\n\n\n\n\nPS - Please forgive choice of example website. It simply had the desired \nelements required for the demonstration. Hoping we can focus on function \nrather than content.\n\n\n\n", "Basically, html tag can have id=\"abc\" as shown below:\n<div id=\"abc\">test</div>\n<p id=\"abc\">test</p>\n<span id=\"abc\">test</span>\n<a id=\"abc\">test</a>\n\nAnd, \"<a>\" tag can also have name=\"abc\" as shown below:\n<a name=\"abc\">test</a>\n\nThen, you can use the id and name values \"abc\" with \"#\" in urls as shown below to go to the specific part of a page:\nhttps://www.example.com/#abc\nhttps://www.example.com/index.html#abc\n\nThen, you can put the urls above in \"<a>\" tag to create the links to id=\"abc\" and name=\"abc\" as shown below:\n<a href=\"https://www.example.com/#abc\">test</a>\n<a href=\"https://www.example.com/index.html#abc\">test</a>\n\nAnd, if you want to go to the specific part of the same page, you can only put the id and name values \"abc\" with \"#\" in \"<a>\" tag to create the links to id=\"abc\" and name=\"abc\" as shown below:\n<!-- Go to the specific part of the same page -->\n\n<a href=\"#abc\">test</a>\n\n<div id=\"abc\">test</div>\n\n<!-- Go to the specific part of the same page -->\n\n<a href=\"#abc\">test</a>\n\n<a name=\"abc\">test</a>\n\n", "It's now possible to create an \"anchor\" link that goes to a specific part of any webpage in most browsers in a few different ways.\nAll of them will create a link with an #anchor at the end, where \"anchor\" is the thing that you want to navigate to. The browser will interpret the part of the URL after the # to scroll to a specific part of the page.\nHere are 3 ways to create a url like this:\n\nUsing an existing anchor. Perhaps there will be one in the URL as you scroll down the page. If not, look around the page for a header that has a little link icon to the left of it and click it to update the browsers navigation url.\nUsing any html element's id property or the name or id on an (\"anchor\") element. The other answers explain this quite well. You will have to open the developer console and inspect the part of the page to find an id (and you may not find one). It's a little different on each browser, but here's how to inspect an element in Chrome.\nUsing a text snippet to highlight part of the page.\n\n" ]
[ 112, 38, 11, 9, 7, 3, 3, 1, 0 ]
[]
[]
[ "anchor", "html", "hyperlink", "tags", "url" ]
stackoverflow_0015481911_anchor_html_hyperlink_tags_url.txt
Q: Differentiate between Simple and Symmetric Digital Differential Analyzer algorithm Differentiate between Simple and Symmetric Digital Differential Analyzer algorithm Differentiate between Simple and Symmetric Digital Differential Analyzer algorithm A: A Simple Digital Differential Analyzer (DDA) algorithm is a way of approximating the path of a line on a two-dimensional grid. It works by calculating the slope of the line and stepping along the line in equal intervals, incrementing the x and y values by the slope at each step. This method is relatively simple to implement, but it can produce results that are less accurate than other methods. In contrast, a Symmetric Digital Differential Analyzer (DDA) algorithm is a more advanced method for approximating the path of a line on a two-dimensional grid. It works by dividing the line into small segments and calculating the x and y values of each segment using a weighted average of the endpoint values. This method is more accurate than the Simple DDA algorithm, but it is also more complex to implement. In general, the Simple DDA algorithm is a good choice when speed is more important than accuracy, while the Symmetric DDA algorithm is a better choice when accuracy is more important. Both algorithms are commonly used in computer graphics applications, such as rendering images and animations on a screen.
Differentiate between Simple and Symmetric Digital Differential Analyzer algorithm
Differentiate between Simple and Symmetric Digital Differential Analyzer algorithm Differentiate between Simple and Symmetric Digital Differential Analyzer algorithm
[ "A Simple Digital Differential Analyzer (DDA) algorithm is a way of approximating the path of a line on a two-dimensional grid. It works by calculating the slope of the line and stepping along the line in equal intervals, incrementing the x and y values by the slope at each step. This method is relatively simple to implement, but it can produce results that are less accurate than other methods.\nIn contrast, a Symmetric Digital Differential Analyzer (DDA) algorithm is a more advanced method for approximating the path of a line on a two-dimensional grid. It works by dividing the line into small segments and calculating the x and y values of each segment using a weighted average of the endpoint values. This method is more accurate than the Simple DDA algorithm, but it is also more complex to implement.\nIn general, the Simple DDA algorithm is a good choice when speed is more important than accuracy, while the Symmetric DDA algorithm is a better choice when accuracy is more important. Both algorithms are commonly used in computer graphics applications, such as rendering images and animations on a screen.\n" ]
[ 0 ]
[]
[]
[ "java" ]
stackoverflow_0074672882_java.txt
Q: Select list items with a certain class but only if they are the last in the group Let's say there is a list that looks like this: <ul class="list"> <li class="item">Text</li> <li class="item unique">Text</li> <li class="item unique">Text</li> // <-- Should be selected <li class="item">Text</li> <li class="item unique">Text</li> <li class="item unique">Text</li> <li class="item unique">Text</li> // <-- Should be selected <li class="item">Text</li> <li class="item unique">Text</li> // <-- Should be selected <li class="item">Text</li> <ul> I'm trying to find a way to select all the list items with the class unique, but only if this item is the last one in the group, meaning that all list items with the class unique that come before this item should not be selected. Is there any way to achieve the desired behavior if the HTML structure cannot be changed? A: If :has can be used (not currently supported by Firefox), it could be: .unique:has(+ :not(.unique)) { color: crimson; } More about :has() Example: (not compatible with Firefox, IE, and older browsers) @supports (selector(html:has(body))) { .unique:has(+ :not(.unique)) { color: crimson; } } <ul class="list"> <li class="item">Text</li> <li class="item unique">Text</li> <li class="item unique">Text</li> // <-- Should be selected <li class="item">Text</li> <li class="item unique">Text</li> <li class="item unique">Text</li> <li class="item unique">Text</li> // <-- Should be selected <li class="item">Text</li> <li class="item unique">Text</li> // <-- Should be selected <li class="item">Text</li> <ul> If :has is not an option, perhaps use some Javascript code for this as a fallback solution. Example: (fallback solution with Javascript) const items = document.querySelectorAll("li"); items.forEach((item, index, arr) => { if (!item.classList.contains("unique")) return; if (index < arr.length - 1 && arr[index + 1].classList.contains("unique")) return; item.classList.add("last"); }); .last { color: crimson; } <ul class="list"> <li class="item">Text</li> <li class="item unique">Text</li> <li class="item unique">Text</li> // <-- Should be selected <li class="item">Text</li> <li class="item unique">Text</li> <li class="item unique">Text</li> <li class="item unique">Text</li> // <-- Should be selected <li class="item">Text</li> <li class="item unique">Text</li> // <-- Should be selected <li class="item">Text</li> <ul>
Select list items with a certain class but only if they are the last in the group
Let's say there is a list that looks like this: <ul class="list"> <li class="item">Text</li> <li class="item unique">Text</li> <li class="item unique">Text</li> // <-- Should be selected <li class="item">Text</li> <li class="item unique">Text</li> <li class="item unique">Text</li> <li class="item unique">Text</li> // <-- Should be selected <li class="item">Text</li> <li class="item unique">Text</li> // <-- Should be selected <li class="item">Text</li> <ul> I'm trying to find a way to select all the list items with the class unique, but only if this item is the last one in the group, meaning that all list items with the class unique that come before this item should not be selected. Is there any way to achieve the desired behavior if the HTML structure cannot be changed?
[ "If :has can be used (not currently supported by Firefox), it could be:\n.unique:has(+ :not(.unique)) {\n color: crimson;\n}\n\nMore about :has()\nExample: (not compatible with Firefox, IE, and older browsers)\n\n\n@supports (selector(html:has(body))) {\n .unique:has(+ :not(.unique)) {\n color: crimson;\n }\n}\n<ul class=\"list\">\n <li class=\"item\">Text</li>\n <li class=\"item unique\">Text</li>\n <li class=\"item unique\">Text</li> // <-- Should be selected\n <li class=\"item\">Text</li>\n <li class=\"item unique\">Text</li>\n <li class=\"item unique\">Text</li>\n <li class=\"item unique\">Text</li> // <-- Should be selected\n <li class=\"item\">Text</li>\n <li class=\"item unique\">Text</li> // <-- Should be selected\n <li class=\"item\">Text</li> \n<ul>\n\n\n\nIf :has is not an option, perhaps use some Javascript code for this as a fallback solution.\nExample: (fallback solution with Javascript)\n\n\nconst items = document.querySelectorAll(\"li\");\n\nitems.forEach((item, index, arr) => {\n if (!item.classList.contains(\"unique\")) return;\n if (index < arr.length - 1 && arr[index + 1].classList.contains(\"unique\"))\n return;\n item.classList.add(\"last\");\n});\n.last {\n color: crimson;\n}\n<ul class=\"list\">\n <li class=\"item\">Text</li>\n <li class=\"item unique\">Text</li>\n <li class=\"item unique\">Text</li> // <-- Should be selected\n <li class=\"item\">Text</li>\n <li class=\"item unique\">Text</li>\n <li class=\"item unique\">Text</li>\n <li class=\"item unique\">Text</li> // <-- Should be selected\n <li class=\"item\">Text</li>\n <li class=\"item unique\">Text</li> // <-- Should be selected\n <li class=\"item\">Text</li>\n<ul>\n\n\n\n" ]
[ 1 ]
[]
[]
[ "css", "css_selectors", "html" ]
stackoverflow_0074672811_css_css_selectors_html.txt
Q: NASM label or instruction expected at start of line I had trying assembly a file. But it has some error. How can I fix it? Why it failed? I had assembly the following code using nasm ipl.asm -o ipl.bin -l ipl.asm.lst: ; Omitted because it is not important. error: mov si, failmsg call putstr bl: hlt jmp bl ; Omitted because it is not important, too. (above ipl.asm) but it failed with: ipl.asm:80: error: label or instruction expected at start of line How can I fix it? Why it fail? A: (Copied from the comment of @ecm. Thank her.) bl is a register name, so we can't name a label using bl.
NASM label or instruction expected at start of line
I had trying assembly a file. But it has some error. How can I fix it? Why it failed? I had assembly the following code using nasm ipl.asm -o ipl.bin -l ipl.asm.lst: ; Omitted because it is not important. error: mov si, failmsg call putstr bl: hlt jmp bl ; Omitted because it is not important, too. (above ipl.asm) but it failed with: ipl.asm:80: error: label or instruction expected at start of line How can I fix it? Why it fail?
[ "(Copied from the comment of @ecm. Thank her.)\nbl is a register name, so we can't name a label using bl.\n" ]
[ 0 ]
[]
[]
[ "nasm" ]
stackoverflow_0074666263_nasm.txt
Q: Kubectl how to wait for operator package manifest to be created How do I wait in using oc command for an operator package manifest to be available? I am trying this โฏ oc wait --for=condition=ready packagemanifest/example-manifest -n openshift-marketplace Error from server (MethodNotAllowed): the server does not allow this method on the requested resource This is failing because there is no ready state under spec field of package manifest A: It looks like the --for flag is not supported for the packagemanifest resource. Instead, you can use the -w flag to wait for a specific condition. For example, you could wait for the Packagemanifest resource to be available using the following command: oc wait -w packagemanifest/example-manifest -n openshift-marketplace This will wait until the Packagemanifest resource with the name example-manifest is available in the openshift-marketplace namespace. Once the resource is available, the command will return and the rest of your script can continue to run. A: This error may occur when the server is configured in a way that does not allow you to perform a specific action for a particular URL. Check below possible solutions : 1)Kubectl resolves are driven by discovery. Please check you may have created two resources with conflicting names one of which is not listable. 2)Check that your Application Default Credentials are configured for a different user than your credentials. 3)Also make sure that your Application Credentials environment variable isn't pointing somewhere unexpected.
Kubectl how to wait for operator package manifest to be created
How do I wait in using oc command for an operator package manifest to be available? I am trying this โฏ oc wait --for=condition=ready packagemanifest/example-manifest -n openshift-marketplace Error from server (MethodNotAllowed): the server does not allow this method on the requested resource This is failing because there is no ready state under spec field of package manifest
[ "It looks like the --for flag is not supported for the packagemanifest resource. Instead, you can use the -w flag to wait for a specific condition. For example, you could wait for the Packagemanifest resource to be available using the following command:\noc wait -w packagemanifest/example-manifest -n openshift-marketplace\n\nThis will wait until the Packagemanifest resource with the name example-manifest is available in the openshift-marketplace namespace. Once the resource is available, the command will return and the rest of your script can continue to run.\n", "This error may occur when the server is configured in a way that does not allow you to perform a specific action for a particular URL.\nCheck below possible solutions :\n1)Kubectl resolves are driven by discovery. Please check you may have created two resources with conflicting names one of which is not listable.\n2)Check that your Application Default Credentials are configured for a different user than your credentials.\n3)Also make sure that your Application Credentials environment variable isn't pointing somewhere unexpected.\n" ]
[ 0, 0 ]
[]
[]
[ "kubectl", "openshift" ]
stackoverflow_0074666362_kubectl_openshift.txt
Q: Convert Columns to Row keeping First Column Data Intact I was able to use 'Text to Columns' and separate a comma delimited text to Columns. Is there a way to now transpose columns to rows keeping Column A on each row. Here's what I have: Tue Nov 29 2022, 9:20 am CABLE KECL SCOOTER SELLIND TI UCO Mon Nov 28 2022, 9:50 am KECL CABLE SCOOTER SELLIND TI UCO Mon Nov 28 2022, 9:20 am CABLE SCOOTER SELLIND TI UCO Fri Nov 25 2022, 9:25 am CABLE HMT SCOOTER TI UCO Here's what I am trying to achieve Tue Nov 29 2022, 9:20 am CABLE Tue Nov 29 2022, 9:20 am KECL Tue Nov 29 2022, 9:20 am SCOOTER Tue Nov 29 2022, 9:20 am SELLIND Tue Nov 29 2022, 9:20 am TI Tue Nov 29 2022, 9:20 am UCO Mon Nov 28 2022, 9:50 am KECL Mon Nov 28 2022, 9:50 am CABLE Mon Nov 28 2022, 9:50 am SCOOTER Mon Nov 28 2022, 9:50 am SELLIND Mon Nov 28 2022, 9:50 am TI Mon Nov 28 2022, 9:50 am UCO ..and so on A: Sub test1() Dim rng As Range, a As Variant, cnt As Long, r As Long, c As Long With ActiveSheet Set rng = .Range("A1").CurrentRegion a = rng cnt = 0 ReDim out(1 To UBound(a, 1) * UBound(a, 2), 1 To 2) For r = 1 To UBound(a, 1) For c = 2 To UBound(a, 2) If Not IsEmpty(a(r, c)) Then cnt = cnt + 1 out(cnt, 1) = a(r, 1) out(cnt, 2) = a(r, c) End If Next Next rng.ClearContents rng(1).Resize(cnt, 2) = out End With End Sub
Convert Columns to Row keeping First Column Data Intact
I was able to use 'Text to Columns' and separate a comma delimited text to Columns. Is there a way to now transpose columns to rows keeping Column A on each row. Here's what I have: Tue Nov 29 2022, 9:20 am CABLE KECL SCOOTER SELLIND TI UCO Mon Nov 28 2022, 9:50 am KECL CABLE SCOOTER SELLIND TI UCO Mon Nov 28 2022, 9:20 am CABLE SCOOTER SELLIND TI UCO Fri Nov 25 2022, 9:25 am CABLE HMT SCOOTER TI UCO Here's what I am trying to achieve Tue Nov 29 2022, 9:20 am CABLE Tue Nov 29 2022, 9:20 am KECL Tue Nov 29 2022, 9:20 am SCOOTER Tue Nov 29 2022, 9:20 am SELLIND Tue Nov 29 2022, 9:20 am TI Tue Nov 29 2022, 9:20 am UCO Mon Nov 28 2022, 9:50 am KECL Mon Nov 28 2022, 9:50 am CABLE Mon Nov 28 2022, 9:50 am SCOOTER Mon Nov 28 2022, 9:50 am SELLIND Mon Nov 28 2022, 9:50 am TI Mon Nov 28 2022, 9:50 am UCO ..and so on
[ "Sub test1()\n Dim rng As Range, a As Variant, cnt As Long, r As Long, c As Long\n With ActiveSheet\n Set rng = .Range(\"A1\").CurrentRegion\n a = rng\n cnt = 0\n ReDim out(1 To UBound(a, 1) * UBound(a, 2), 1 To 2)\n For r = 1 To UBound(a, 1)\n For c = 2 To UBound(a, 2)\n If Not IsEmpty(a(r, c)) Then\n cnt = cnt + 1\n out(cnt, 1) = a(r, 1)\n out(cnt, 2) = a(r, c)\n End If\n Next\n Next\n rng.ClearContents\n rng(1).Resize(cnt, 2) = out\n End With\nEnd Sub\n\n\n\n" ]
[ 0 ]
[]
[]
[ "excel", "excel_formula", "vba" ]
stackoverflow_0074672230_excel_excel_formula_vba.txt
Q: Uno Platform C# Create Material Card I am using the Uno Platform and trying to create a Material Card through C#. I have been able to find a number of examples of a Card created in XAML but nothing in C#. My current code is below to create a Card and add it to a Grid. I know I need to do something with adding a HeaderContentTemplate and SubHeaderContentTemplate but I am sure exactly what needs to be done. Card myCard = new Card(); myCard.HeaderContent = "test"; myCard.SubHeaderContent = "test"; Grid.SetRow(myCard, k); Grid.SetColumn(myCard, l); myGrid.Children.Add(myCard); Any help would be greatly appreciated. Thank you. A: To add a HeaderContentTemplate and SubHeaderContentTemplate to your card, you can try using the Card.HeaderContentTemplate and Card.SubHeaderContentTemplate properties. These properties allow you to specify a DataTemplate that defines the appearance of the header and subheader content of your card. Here's an example of how you might use these properties to create a DataTemplate for your card's header and subheader: Card myCard = new Card(); myCard.HeaderContent = "test"; myCard.SubHeaderContent = "test"; // Create a DataTemplate for the header content of the card DataTemplate headerTemplate = new DataTemplate(); FrameworkElementFactory headerFactory = new FrameworkElementFactory(typeof(TextBlock)); headerFactory.SetValue(TextBlock.TextProperty, "Header: "); headerFactory.SetValue(TextBlock.FontSizeProperty, 14.0); headerFactory.SetValue(TextBlock.FontWeightProperty, FontWeights.Bold); headerTemplate.VisualTree = headerFactory; myCard.HeaderContentTemplate = headerTemplate; // Create a DataTemplate for the subheader content of the card DataTemplate subheaderTemplate = new DataTemplate(); FrameworkElementFactory subheaderFactory = new FrameworkElementFactory(typeof(TextBlock)); subheaderFactory.SetValue(TextBlock.TextProperty, "Subheader: "); subheaderFactory.SetValue(TextBlock.FontSizeProperty, 12.0); subheaderFactory.SetValue(TextBlock.FontWeightProperty, FontWeights.Normal); subheaderTemplate.VisualTree = subheaderFactory; myCard.SubHeaderContentTemplate = subheaderTemplate; Grid.SetRow(myCard, k); Grid.SetColumn(myCard, l); myGrid.Children.Add(myCard); In this example, we create a DataTemplate for each of the card's header and subheader content. The DataTemplate specifies the appearance of the content by using a TextBlock element. We then set the Card.HeaderContentTemplate and Card.SubHeaderContentTemplate properties to the DataTemplate objects we created. A: I was not able to get the Material Cards working through C# so I ended up making a template xaml and C# file which I build the structure of my card. Then I created that through C#.
Uno Platform C# Create Material Card
I am using the Uno Platform and trying to create a Material Card through C#. I have been able to find a number of examples of a Card created in XAML but nothing in C#. My current code is below to create a Card and add it to a Grid. I know I need to do something with adding a HeaderContentTemplate and SubHeaderContentTemplate but I am sure exactly what needs to be done. Card myCard = new Card(); myCard.HeaderContent = "test"; myCard.SubHeaderContent = "test"; Grid.SetRow(myCard, k); Grid.SetColumn(myCard, l); myGrid.Children.Add(myCard); Any help would be greatly appreciated. Thank you.
[ "To add a HeaderContentTemplate and SubHeaderContentTemplate to your card, you can try using the Card.HeaderContentTemplate and Card.SubHeaderContentTemplate properties. These properties allow you to specify a DataTemplate that defines the appearance of the header and subheader content of your card.\nHere's an example of how you might use these properties to create a DataTemplate for your card's header and subheader:\nCard myCard = new Card();\n\nmyCard.HeaderContent = \"test\";\nmyCard.SubHeaderContent = \"test\";\n\n// Create a DataTemplate for the header content of the card\nDataTemplate headerTemplate = new DataTemplate();\nFrameworkElementFactory headerFactory = new FrameworkElementFactory(typeof(TextBlock));\nheaderFactory.SetValue(TextBlock.TextProperty, \"Header: \");\nheaderFactory.SetValue(TextBlock.FontSizeProperty, 14.0);\nheaderFactory.SetValue(TextBlock.FontWeightProperty, FontWeights.Bold);\nheaderTemplate.VisualTree = headerFactory;\nmyCard.HeaderContentTemplate = headerTemplate;\n\n// Create a DataTemplate for the subheader content of the card\nDataTemplate subheaderTemplate = new DataTemplate();\nFrameworkElementFactory subheaderFactory = new FrameworkElementFactory(typeof(TextBlock));\nsubheaderFactory.SetValue(TextBlock.TextProperty, \"Subheader: \");\nsubheaderFactory.SetValue(TextBlock.FontSizeProperty, 12.0);\nsubheaderFactory.SetValue(TextBlock.FontWeightProperty, FontWeights.Normal);\nsubheaderTemplate.VisualTree = subheaderFactory;\nmyCard.SubHeaderContentTemplate = subheaderTemplate;\n\nGrid.SetRow(myCard, k);\nGrid.SetColumn(myCard, l);\nmyGrid.Children.Add(myCard);\n\nIn this example, we create a DataTemplate for each of the card's header and subheader content. The DataTemplate specifies the appearance of the content by using a TextBlock element. We then set the Card.HeaderContentTemplate and Card.SubHeaderContentTemplate properties to the DataTemplate objects we created.\n", "I was not able to get the Material Cards working through C# so I ended up making a template xaml and C# file which I build the structure of my card. Then I created that through C#.\n" ]
[ 0, 0 ]
[]
[]
[ "c#", "material_ui", "uno_platform", "wpf", "xaml" ]
stackoverflow_0074671257_c#_material_ui_uno_platform_wpf_xaml.txt
Q: What does builder do that python code doesn't? When I use builder, the program outputs information from qr codes to the lower half of the application, but it is necessary to replace the built code with an equivalent python code, immediately information about qr codes ceases to be output With builder: ` from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.lang import Builder from kivy_garden.zbarcam import ZBarCam DEMO_APP_KV_LANG = """ BoxLayout: orientation: 'vertical' ZBarCam: id: zbarcam Label: text: ', '.join([str(symbol.data) for symbol in zbarcam.symbols]) """ class DemoApp(App): def build(self): return Builder.load_string(DEMO_APP_KV_LANG) if __name__ == '__main__': DemoApp().run() With python code: from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.lang import Builder from kivy_garden.zbarcam import ZBarCam class Demo(BoxLayout): def __init__(self, **kwargs): super().__init__(**kwargs) self.orientation = 'vertical' self.zbarcam= ZBarCam() self.add_widget(self.zbarcam) self.add_widget(Label(text=', '.join([str(symbol.data) for symbol in self.zbarcam.symbols]))) class DemoApp(App): def build(self): return Demo() if __name__ == '__main__': DemoApp().run() ` A: The kivy language sets up bindings for you that the pure python does not. So your line in the kv: text: ', '.join([str(symbol.data) for symbol in zbarcam.symbols]) sets up binding to zbarcam.symbols so that the text is updated whenever zbarcam.symbols changes. And in the python code: text=', '.join([str(symbol.data) for symbol in self.zbarcam.symbols] sets the text once when that line is executed, and it is never updated. Why must you replace the the kivy language code?
What does builder do that python code doesn't?
When I use builder, the program outputs information from qr codes to the lower half of the application, but it is necessary to replace the built code with an equivalent python code, immediately information about qr codes ceases to be output With builder: ` from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.lang import Builder from kivy_garden.zbarcam import ZBarCam DEMO_APP_KV_LANG = """ BoxLayout: orientation: 'vertical' ZBarCam: id: zbarcam Label: text: ', '.join([str(symbol.data) for symbol in zbarcam.symbols]) """ class DemoApp(App): def build(self): return Builder.load_string(DEMO_APP_KV_LANG) if __name__ == '__main__': DemoApp().run() With python code: from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.lang import Builder from kivy_garden.zbarcam import ZBarCam class Demo(BoxLayout): def __init__(self, **kwargs): super().__init__(**kwargs) self.orientation = 'vertical' self.zbarcam= ZBarCam() self.add_widget(self.zbarcam) self.add_widget(Label(text=', '.join([str(symbol.data) for symbol in self.zbarcam.symbols]))) class DemoApp(App): def build(self): return Demo() if __name__ == '__main__': DemoApp().run() `
[ "The kivy language sets up bindings for you that the pure python does not. So your line in the kv:\ntext: ', '.join([str(symbol.data) for symbol in zbarcam.symbols])\n\nsets up binding to zbarcam.symbols so that the text is updated whenever zbarcam.symbols changes.\nAnd in the python code:\ntext=', '.join([str(symbol.data) for symbol in self.zbarcam.symbols]\n\nsets the text once when that line is executed, and it is never updated.\nWhy must you replace the the kivy language code?\n" ]
[ 0 ]
[]
[]
[ "barcode", "kivy", "kivy_language", "python", "qr_code" ]
stackoverflow_0074669847_barcode_kivy_kivy_language_python_qr_code.txt
Q: Create ed25519 jwt and verify with joken I'm trying to create a JWT with joken privKey = """ -----BEGIN PRIVATE KEY----- MC4CAQAwBQYDK2VwBCIEIPaIrqi+I+znfdsteEXELr2J1e+qC72KNam6fx40pYvi -----END PRIVATE KEY----- """ signer = Joken.Signer.create("Ed25519", %{"pem" => privKey}) Joken.generate_and_sign!(%{}, %{"name" => "John Doe"}, signer) I receive the error ** (FunctionClauseError) no function clause matching in :jose_jwk_kty_ec.parameters_to_crv/1 The following arguments were given to :jose_jwk_kty_ec.parameters_to_crv/1: # 1 :ed25519 (jose 1.11.2) src/jwk/jose_jwk_kty_ec.erl:410: :jose_jwk_kty_ec.parameters_to_crv/1 (jose 1.11.2) src/jwk/jose_jwk_kty_ec.erl:389: :jose_jwk_kty_ec.jws_alg_to_digest_type/2 (jose 1.11.2) src/jwk/jose_jwk_kty_ec.erl:199: :jose_jwk_kty_ec.sign/3 (jose 1.11.2) src/jws/jose_jws.erl:311: :jose_jws.sign/4 (jose 1.11.2) src/jwt/jose_jwt.erl:173: :jose_jwt.sign/3 (joken 2.5.0) lib/joken/signer.ex:128: Joken.Signer.sign/2 (joken 2.5.0) lib/joken.ex:361: Joken.encode_and_sign/3 iex:6: (file) What is causing the error, I had a look at the code on https://github.com/joken-elixir/joken/issues/214 to try and fix it but couldn't. A: To create and verify a JWT with the ed25519 algorithm using the joken library, you will need to use a private key in the correct format. The error you're receiving suggests that the private key you're using is not in the correct format. To generate a new ed25519 private key, you can use the :crypto.strong_rand_bytes/1 function to generate 32 random bytes, which will be the private key. You can then encode the private key in base64 using the :base64.encode/1 function, and prepend and append the appropriate headers and footers to get the private key in the correct format. Here is an example of how you can generate a new ed25519 private key and use it to create and verify a JWT with joken: priv_key_bytes = :crypto.strong_rand_bytes(32) priv_key_b64 = :base64.encode(priv_key_bytes) priv_key = """ -----BEGIN PRIVATE KEY----- #{priv_key_b64} -----END PRIVATE KEY----- """ signer = Joken.Signer.create("Ed25519", %{"pem" => priv_key}) jwt = Joken.generate_and_sign!(%{}, %{"name" => "John Doe"}, signer) # verify the JWT Joken.verify!(jwt, signer) You can then use the Joken.verify!/2 function to verify the JWT using the same private key and signer. It's important to note that the ed25519 algorithm is not currently supported by the jose library, which joken uses under the hood. You will need to use the jose_jwt_verify library directly if you want to use the ed25519 algorithm with jose. A: It looks like there's an issue with the jose library that joken is using to generate the JWT. The error message indicates that jose is trying to convert the :ed25519 key type to a curve, but it doesn't know how to do that because Ed25519 is not an elliptic curve. It's possible that joken doesn't support the Ed25519 key type. To fix this error, you could try using a different key type that joken does support, such as :RS256, :HS256, or :ES256. Alternatively, you could try using a different library to generate your JWT. Alternatively, The error message mentions that the function :jose_jwk_kty_ec.parameters_to_crv/1 has no clause matching for the given argument :ed25519. To fix this, you can try using a different key type that is supported by the Joken library. You can find the supported key types and their corresponding values in the Joken documentation (https://hexdocs.pm/joken/Joken.Signer.html#create/3). For example, you can try using the key type :ecdsa with the curve :P-256, like this: privKey = """ -----BEGIN PRIVATE KEY----- MC4CAQAwBQYDK2VwBCIEIPaIrqi+I+znfdsteEXELr2J1e+qC72KNam6fx40pYvi -----END PRIVATE KEY----- """ signer = Joken.Signer.create("ecdsa", %{"pem" => privKey, "curve" => "P-256"}) Joken.generate_and_sign!(%{}, %{"name" => "John Doe"}, signer) A: There are 2 possibilities here; 1. It looks like the error is being caused by trying to use the "Ed25519" algorithm with the EC (Elliptic Curve) key type. The "Ed25519" algorithm is not supported by the EC key type. To fix the error, you can try using a different key type that does support the "Ed25519" algorithm, such as the "OKP" (Octet Key Pair) key type. Here is an example of how you could do that: privKey = """ -----BEGIN PRIVATE KEY----- MC4CAQAwBQYDK2VwBCIEIPaIrqi+I+znfdsteEXELr2J1e+qC72KNam6fx40pYvi -----END PRIVATE KEY----- """ signer = Joken.Signer.create("Ed25519", %{"pem" => privKey, "kty" => "OKP"}) Joken.generate_and_sign!(%{}, %{"name" => "John Doe"}, signer) This should fix the error and allow you to generate a JWT using the "Ed25519" algorithm. 2. It looks like the error is caused by a missing crv parameter when creating the signer. The crv parameter is used to specify the type of elliptic curve used with an Elliptic Curve key. Here is an example of creating the signer with the crv parameter included: privKey = """ -----BEGIN PRIVATE KEY----- MC4CAQAwBQYDK2VwBCIEIPaIrqi+I+znfdsteEXELr2J1e+qC72KNam6fx40pYvi -----END PRIVATE KEY----- """ signer = Joken.Signer.create("Ed25519", %{"pem" => privKey, "crv" => "Ed25519"}) Joken.generate_and_sign!(%{}, %{"name" => "John Doe"}, signer) Hope this helps.
Create ed25519 jwt and verify with joken
I'm trying to create a JWT with joken privKey = """ -----BEGIN PRIVATE KEY----- MC4CAQAwBQYDK2VwBCIEIPaIrqi+I+znfdsteEXELr2J1e+qC72KNam6fx40pYvi -----END PRIVATE KEY----- """ signer = Joken.Signer.create("Ed25519", %{"pem" => privKey}) Joken.generate_and_sign!(%{}, %{"name" => "John Doe"}, signer) I receive the error ** (FunctionClauseError) no function clause matching in :jose_jwk_kty_ec.parameters_to_crv/1 The following arguments were given to :jose_jwk_kty_ec.parameters_to_crv/1: # 1 :ed25519 (jose 1.11.2) src/jwk/jose_jwk_kty_ec.erl:410: :jose_jwk_kty_ec.parameters_to_crv/1 (jose 1.11.2) src/jwk/jose_jwk_kty_ec.erl:389: :jose_jwk_kty_ec.jws_alg_to_digest_type/2 (jose 1.11.2) src/jwk/jose_jwk_kty_ec.erl:199: :jose_jwk_kty_ec.sign/3 (jose 1.11.2) src/jws/jose_jws.erl:311: :jose_jws.sign/4 (jose 1.11.2) src/jwt/jose_jwt.erl:173: :jose_jwt.sign/3 (joken 2.5.0) lib/joken/signer.ex:128: Joken.Signer.sign/2 (joken 2.5.0) lib/joken.ex:361: Joken.encode_and_sign/3 iex:6: (file) What is causing the error, I had a look at the code on https://github.com/joken-elixir/joken/issues/214 to try and fix it but couldn't.
[ "To create and verify a JWT with the ed25519 algorithm using the joken library, you will need to use a private key in the correct format. The error you're receiving suggests that the private key you're using is not in the correct format.\nTo generate a new ed25519 private key, you can use the :crypto.strong_rand_bytes/1 function to generate 32 random bytes, which will be the private key. You can then encode the private key in base64 using the :base64.encode/1 function, and prepend and append the appropriate headers and footers to get the private key in the correct format.\nHere is an example of how you can generate a new ed25519 private key and use it to create and verify a JWT with joken:\npriv_key_bytes = :crypto.strong_rand_bytes(32)\npriv_key_b64 = :base64.encode(priv_key_bytes)\npriv_key = \"\"\"\n-----BEGIN PRIVATE KEY-----\n#{priv_key_b64}\n-----END PRIVATE KEY-----\n\"\"\"\n\nsigner = Joken.Signer.create(\"Ed25519\", %{\"pem\" => priv_key})\njwt = Joken.generate_and_sign!(%{}, %{\"name\" => \"John Doe\"}, signer)\n\n# verify the JWT\nJoken.verify!(jwt, signer)\n\n\nYou can then use the Joken.verify!/2 function to verify the JWT using the same private key and signer.\nIt's important to note that the ed25519 algorithm is not currently supported by the jose library, which joken uses under the hood. You will need to use the jose_jwt_verify library directly if you want to use the ed25519 algorithm with jose.\n", "It looks like there's an issue with the jose library that joken is using to generate the JWT. The error message indicates that jose is trying to convert the :ed25519 key type to a curve, but it doesn't know how to do that because Ed25519 is not an elliptic curve.\nIt's possible that joken doesn't support the Ed25519 key type. To fix this error, you could try using a different key type that joken does support, such as :RS256, :HS256, or :ES256. Alternatively, you could try using a different library to generate your JWT.\nAlternatively, The error message mentions that the function :jose_jwk_kty_ec.parameters_to_crv/1 has no clause matching for the given argument :ed25519.\nTo fix this, you can try using a different key type that is supported by the Joken library. You can find the supported key types and their corresponding values in the Joken documentation (https://hexdocs.pm/joken/Joken.Signer.html#create/3).\nFor example, you can try using the key type :ecdsa with the curve :P-256, like this:\nprivKey = \"\"\"\n-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIPaIrqi+I+znfdsteEXELr2J1e+qC72KNam6fx40pYvi\n-----END PRIVATE KEY-----\n\"\"\"\n\nsigner = Joken.Signer.create(\"ecdsa\", %{\"pem\" => privKey, \"curve\" => \"P-256\"})\n\nJoken.generate_and_sign!(%{}, %{\"name\" => \"John Doe\"}, signer)\n\n", "There are 2 possibilities here;\n1.\nIt looks like the error is being caused by trying to use the \"Ed25519\" algorithm with the EC (Elliptic Curve) key type. The \"Ed25519\" algorithm is not supported by the EC key type. To fix the error, you can try using a different key type that does support the \"Ed25519\" algorithm, such as the \"OKP\" (Octet Key Pair) key type. Here is an example of how you could do that:\nprivKey = \"\"\"\n-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIPaIrqi+I+znfdsteEXELr2J1e+qC72KNam6fx40pYvi\n-----END PRIVATE KEY-----\n\"\"\"\n\nsigner = Joken.Signer.create(\"Ed25519\", %{\"pem\" => privKey, \"kty\" => \"OKP\"})\n\nJoken.generate_and_sign!(%{}, %{\"name\" => \"John Doe\"}, signer)\n\nThis should fix the error and allow you to generate a JWT using the \"Ed25519\" algorithm.\n2.\nIt looks like the error is caused by a missing crv parameter when creating the signer. The crv parameter is used to specify the type of elliptic curve used with an Elliptic Curve key.\nHere is an example of creating the signer with the crv parameter included:\nprivKey = \"\"\"\n-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIPaIrqi+I+znfdsteEXELr2J1e+qC72KNam6fx40pYvi\n-----END PRIVATE KEY-----\n\"\"\"\n\nsigner = Joken.Signer.create(\"Ed25519\", %{\"pem\" => privKey, \"crv\" => \"Ed25519\"})\n\nJoken.generate_and_sign!(%{}, %{\"name\" => \"John Doe\"}, signer)\n\nHope this helps.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "cryptography", "ed25519", "elixir", "jwt" ]
stackoverflow_0074368181_cryptography_ed25519_elixir_jwt.txt
Q: Can not find PsiClass in my Intellij plugin project Many tutorials mention a class - PsiClass, but I can't find this class in my project. My build.gradle as below: plugins { id 'java' id 'org.jetbrains.intellij' version '0.4.16' id 'org.jetbrains.kotlin.jvm' version '1.3.61' id 'idea' } apply plugin: "org.jetbrains.intellij" apply plugin: 'java' apply plugin: 'idea' group 'com.github.boybeak.adapter' version '0.1' sourceCompatibility = 1.8 repositories { /*google() jcenter()*/ mavenCentral() } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8" // implementation group: 'com.github.boybeak', name: 'any-adapter', version: '1.1.2' testCompile group: 'junit', name: 'junit', version: '4.12' } intellij { /*version '192.7142.36'*/ type 'AI' plugins 'android' localPath '/Applications/Android Studio.app' } My IDEA version: IntelliJ IDEA 2019.3.1 (Community Edition) Build #IC-193.5662.53, built on December 18, 2019 Runtime version: 11.0.5+10-b520.17 x86_64 VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o macOS 10.15.3 GC: ParNew, ConcurrentMarkSweep Memory: 990M Cores: 4 Registry: Non-Bundled Plugins: DBN, OdpsStudio, no.tornado.tornadofx.idea Should I add some more libraries in my project? A: After a little more searching, I find a solution. https://intellij-support.jetbrains.com/hc/en-us/community/posts/360005055559-Missing-classes-after-upgrade-to-2019-2-2 Change my Gradle like this: intellij { /*version '192.7142.36'*/ type 'AI' plugins 'android', 'java' localPath '/Applications/Android Studio.app' } Add Java plugin after android A: Adding a Kotlin Script solution if you're using build.gradle.kts intellij { ... setPlugins("java") } The newest Idea Plugin template suggests gradle.properties as a source of plugin dependencies // gradle.properties platformPlugins = ... // build.gradle.kts val platformPlugins: String by project intellij { setPlugins(*platformPlugins.split(',').map(String::trim).filter(String::isNotEmpty).toTypedArray()) } A: I was able to fix this by adding this to the build.gradle.kts file: intellij { version.set("2021.3.3") type.set("IC") // Target IDE Platform plugins.set(listOf("com.intellij.java")) // Add this } When I did that, this little guy popped up: I clicked on that and then I was able to import the PsiClass.
Can not find PsiClass in my Intellij plugin project
Many tutorials mention a class - PsiClass, but I can't find this class in my project. My build.gradle as below: plugins { id 'java' id 'org.jetbrains.intellij' version '0.4.16' id 'org.jetbrains.kotlin.jvm' version '1.3.61' id 'idea' } apply plugin: "org.jetbrains.intellij" apply plugin: 'java' apply plugin: 'idea' group 'com.github.boybeak.adapter' version '0.1' sourceCompatibility = 1.8 repositories { /*google() jcenter()*/ mavenCentral() } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8" // implementation group: 'com.github.boybeak', name: 'any-adapter', version: '1.1.2' testCompile group: 'junit', name: 'junit', version: '4.12' } intellij { /*version '192.7142.36'*/ type 'AI' plugins 'android' localPath '/Applications/Android Studio.app' } My IDEA version: IntelliJ IDEA 2019.3.1 (Community Edition) Build #IC-193.5662.53, built on December 18, 2019 Runtime version: 11.0.5+10-b520.17 x86_64 VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o macOS 10.15.3 GC: ParNew, ConcurrentMarkSweep Memory: 990M Cores: 4 Registry: Non-Bundled Plugins: DBN, OdpsStudio, no.tornado.tornadofx.idea Should I add some more libraries in my project?
[ "After a little more searching, I find a solution.\nhttps://intellij-support.jetbrains.com/hc/en-us/community/posts/360005055559-Missing-classes-after-upgrade-to-2019-2-2\nChange my Gradle like this:\nintellij {\n /*version '192.7142.36'*/\n type 'AI'\n plugins 'android', 'java'\n localPath '/Applications/Android Studio.app'\n}\n\nAdd Java plugin after android\n", "Adding a Kotlin Script solution if you're using build.gradle.kts\nintellij {\n ...\n setPlugins(\"java\")\n}\n\nThe newest Idea Plugin template suggests gradle.properties as a source of plugin dependencies\n// gradle.properties\nplatformPlugins = ...\n\n// build.gradle.kts\nval platformPlugins: String by project\n\nintellij {\n setPlugins(*platformPlugins.split(',').map(String::trim).filter(String::isNotEmpty).toTypedArray())\n}\n\n", "I was able to fix this by adding this to the build.gradle.kts file:\nintellij {\n version.set(\"2021.3.3\")\n type.set(\"IC\") // Target IDE Platform\n\n plugins.set(listOf(\"com.intellij.java\")) // Add this\n}\n\nWhen I did that, this little guy popped up:\n\nI clicked on that and then I was able to import the PsiClass.\n" ]
[ 4, 1, 0 ]
[]
[]
[ "intellij_plugin" ]
stackoverflow_0060518688_intellij_plugin.txt
Q: input a string and an integer o the same line separated by a space in C I am trying to make a mini game where you input a command about what to do, and you need to input your since most of my inputs will look like this:atk 1 or:health 1 The input must in one line, but there are commands that don't have a number after them. I need to input them in one line, so I use scanf("%s %d") to do this, but I also have some commands that don't have a number after the string, but if I don't use scanf I don't have ways to input them in a same line. Is there solutions for situation like this? Sometimes the input is a string with a number, and sometimes a string only. #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXSIZE 100 struct status { int hp; char name[MAXSIZE]; }; int main() { struct status you; struct status enemy; //your name and hp scanf("%s %d", you.name, &you.hp); //enemy's name and hp scanf("%s %d", enemy.name, &enemy.hp); char move[MAXSIZE]; int damage = 0; int poison = 0; int round = 0; //game start //you start first, than you input what enemy do in next round //atk means attack, poison means you got poison by enemy on every end of rounds, health means you heal yourself, none means you skip this round //show means to show your and enemy's curreny status //end means end the game the process stop, it also stops when someone's hp is zero while((you.hp > 0)&&(enemy.hp > 0) ) { scanf("%s %d", move, &damage); if( strcmp(move,"atk") == 0 ) { if((round%2) == 0) enemy.hp = enemy.hp - damage; else you.hp = you.hp = damage; round++; } else if( strcmp(move,"health") == 0 ) { you.hp = you.hp + damage; round++; } else if( strcmp(move,"poison") == 0 ) { poison = poison + damage; round++; } else if( strcmp(move,"none") == 0 ) { round++; } else if( strcmp(move,"show") == 0) { printf("%s %d %s %d\n", you.name, you.hp, enemy.name, enemy.hp); continue; } else break; } if( strcmp(move, "atk") == 0) { if((round%2) == 0) printf("%s were defeated by attack", you.name); else printf("%s were defeated by your attack", enemy.name); } else if( strcmp(move, "end") == 0) { return 0; } else printf("%s were defeated by poison", you.name); return 0; } A: The general advice is to avoid scanf. Instead, fgets can be used to read an entire line of input from a stream into a buffer. Then the buffer can be freely manipulated, or parsed multiple times, without having to worry about the state of the stream. The program below has examples of using both strtok (+ strtol) and sscanf to extract data from a string. Each of these tools has advantages and disadvantages; reading their documentation is recommended. Some additional suggestions: The use of an enum reduces the need to repeatedly compare strings, and its integral nature allows the use of a switch. An array kept in parallel (actions) to the enumeration type acts as a lookup table for string<->enum conversions. At the same time, this array can be used to indicate if a command requires an argument. Placing your players in an array allows the use of modular arithmetic to determine the current player and next player without repeatedly checking the turn count. Alternatively, having a pointer to each player and swapping the values of the pointers each turn might prove easier to read. poison should probably be an attribute of a player (struct status). Here is an example program with a few of these concepts to play around with: #include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXSIZE 100 #define SEP " \r\n" struct status { char name[MAXSIZE]; int hp; int poison; }; static const struct { const char *method; bool needs_value; } actions[] = { { NULL }, { "atk", true }, { "health", true }, { "poison", true }, { "show", false }, { "end", false }, { "none", false } }; enum ACTION { ACTION_INVALID, ACTION_ATK, ACTION_HEALTH, ACTION_POISON, ACTION_SHOW, ACTION_END, ACTION_NONE, ACTION_ACTIONS }; enum ACTION get_action(int *value) { char buf[256]; if (!fgets(buf, sizeof buf, stdin)) exit(EXIT_FAILURE); char *method = strtok(buf, SEP); if (!method) return ACTION_INVALID; for (enum ACTION e = ACTION_ATK; e < ACTION_ACTIONS; e++) { if (0 == strcmp(method, actions[e].method)) { if (actions[e].needs_value) { char *value_token = strtok(NULL, SEP); if (!value_token || !*value_token) break; char *end; errno = 0; *value = strtol(value_token, &end, 10); /* integer overflow or string was not completely parsed */ if (ERANGE == errno || *end) break; } return e; } } return ACTION_INVALID; } bool get_player(struct status *p) { char buf[256]; printf("Enter a name and hp: "); if (!fgets(buf, sizeof buf, stdin)) exit(EXIT_FAILURE); p->poison = 0; return 2 == sscanf(buf, "%99s%d", p->name, &p->hp); } void print_status(struct status *s) { printf("%s has %d HP and %d poison.\n", s->name, s->hp, s->poison); } int main(void) { struct status players[2] = { { "Alice", 123, 0 }, { "Bob", 42, 0 } }; /* uncomment for user input if (!get_player(players) || !get_player(players + 1)) exit(EXIT_FAILURE); */ int current = 0; while (1) { int next = (current + 1) % 2; int value; printf("%s's turn. Enter an action: ", players[current].name); switch (get_action(&value)) { case ACTION_INVALID: fprintf(stderr, "Invalid action.\n"); continue; case ACTION_ATK: printf("%s deals %d damage to %s\n", players[current].name, value, players[next].name); players[next].hp -= value; break; case ACTION_POISON: printf("%s applies %d poison to %s\n", players[current].name, value, players[next].name); players[next].poison += value; break; case ACTION_HEALTH: printf("%s heals %d health.\n", players[current].name, value); players[current].hp += value; break; case ACTION_SHOW: print_status(players + current); print_status(players + next); continue; case ACTION_END: return EXIT_SUCCESS; case ACTION_NONE: break; default: continue; } if (players[next].hp < 1) { printf("%s has slain %s!\n", players[current].name, players[next].name); break; } /* apply poison, and reduce poison by one */ if (players[current].poison) players[current].hp -= players[current].poison--; if (players[current].hp < 1) { printf("%s has died to poison!\n", players[current].name); break; } current = next; } } Example usage: Alice's turn. Enter an action: show Alice has 123 HP and 0 poison. Bob has 42 HP and 0 poison. Alice's turn. Enter an action: poison 22 Alice applies 22 poison to Bob Bob's turn. Enter an action: atk 50 Bob deals 50 damage to Alice Alice's turn. Enter an action: none Bob's turn. Enter an action: atk 50 Bob deals 50 damage to Alice Bob has died to poison!
input a string and an integer o the same line separated by a space in C
I am trying to make a mini game where you input a command about what to do, and you need to input your since most of my inputs will look like this:atk 1 or:health 1 The input must in one line, but there are commands that don't have a number after them. I need to input them in one line, so I use scanf("%s %d") to do this, but I also have some commands that don't have a number after the string, but if I don't use scanf I don't have ways to input them in a same line. Is there solutions for situation like this? Sometimes the input is a string with a number, and sometimes a string only. #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXSIZE 100 struct status { int hp; char name[MAXSIZE]; }; int main() { struct status you; struct status enemy; //your name and hp scanf("%s %d", you.name, &you.hp); //enemy's name and hp scanf("%s %d", enemy.name, &enemy.hp); char move[MAXSIZE]; int damage = 0; int poison = 0; int round = 0; //game start //you start first, than you input what enemy do in next round //atk means attack, poison means you got poison by enemy on every end of rounds, health means you heal yourself, none means you skip this round //show means to show your and enemy's curreny status //end means end the game the process stop, it also stops when someone's hp is zero while((you.hp > 0)&&(enemy.hp > 0) ) { scanf("%s %d", move, &damage); if( strcmp(move,"atk") == 0 ) { if((round%2) == 0) enemy.hp = enemy.hp - damage; else you.hp = you.hp = damage; round++; } else if( strcmp(move,"health") == 0 ) { you.hp = you.hp + damage; round++; } else if( strcmp(move,"poison") == 0 ) { poison = poison + damage; round++; } else if( strcmp(move,"none") == 0 ) { round++; } else if( strcmp(move,"show") == 0) { printf("%s %d %s %d\n", you.name, you.hp, enemy.name, enemy.hp); continue; } else break; } if( strcmp(move, "atk") == 0) { if((round%2) == 0) printf("%s were defeated by attack", you.name); else printf("%s were defeated by your attack", enemy.name); } else if( strcmp(move, "end") == 0) { return 0; } else printf("%s were defeated by poison", you.name); return 0; }
[ "The general advice is to avoid scanf.\nInstead, fgets can be used to read an entire line of input from a stream into a buffer. Then the buffer can be freely manipulated, or parsed multiple times, without having to worry about the state of the stream.\nThe program below has examples of using both strtok (+ strtol) and sscanf to extract data from a string. Each of these tools has advantages and disadvantages; reading their documentation is recommended.\nSome additional suggestions:\nThe use of an enum reduces the need to repeatedly compare strings, and its integral nature allows the use of a switch. An array kept in parallel (actions) to the enumeration type acts as a lookup table for string<->enum conversions. At the same time, this array can be used to indicate if a command requires an argument.\nPlacing your players in an array allows the use of modular arithmetic to determine the current player and next player without repeatedly checking the turn count. Alternatively, having a pointer to each player and swapping the values of the pointers each turn might prove easier to read.\npoison should probably be an attribute of a player (struct status).\nHere is an example program with a few of these concepts to play around with:\n#include <errno.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define MAXSIZE 100\n#define SEP \" \\r\\n\"\n\nstruct status {\n char name[MAXSIZE];\n int hp;\n int poison;\n};\n\nstatic const struct {\n const char *method;\n bool needs_value;\n} actions[] = {\n { NULL },\n { \"atk\", true },\n { \"health\", true },\n { \"poison\", true },\n { \"show\", false },\n { \"end\", false },\n { \"none\", false }\n};\n\nenum ACTION {\n ACTION_INVALID,\n ACTION_ATK,\n ACTION_HEALTH,\n ACTION_POISON,\n ACTION_SHOW,\n ACTION_END,\n ACTION_NONE,\n ACTION_ACTIONS\n};\n\nenum ACTION get_action(int *value)\n{\n char buf[256];\n\n if (!fgets(buf, sizeof buf, stdin))\n exit(EXIT_FAILURE);\n\n char *method = strtok(buf, SEP);\n\n if (!method)\n return ACTION_INVALID;\n\n for (enum ACTION e = ACTION_ATK; e < ACTION_ACTIONS; e++) {\n if (0 == strcmp(method, actions[e].method)) {\n if (actions[e].needs_value) {\n char *value_token = strtok(NULL, SEP);\n\n if (!value_token || !*value_token)\n break;\n\n char *end;\n errno = 0;\n *value = strtol(value_token, &end, 10);\n\n /* integer overflow or string was not completely parsed */\n if (ERANGE == errno || *end)\n break;\n }\n\n return e;\n }\n }\n\n return ACTION_INVALID;\n}\n\nbool get_player(struct status *p)\n{\n char buf[256];\n\n printf(\"Enter a name and hp: \");\n if (!fgets(buf, sizeof buf, stdin))\n exit(EXIT_FAILURE);\n\n p->poison = 0;\n\n return 2 == sscanf(buf, \"%99s%d\", p->name, &p->hp);\n}\n\nvoid print_status(struct status *s)\n{\n printf(\"%s has %d HP and %d poison.\\n\",\n s->name, s->hp, s->poison);\n}\n\nint main(void)\n{\n struct status players[2] = { { \"Alice\", 123, 0 }, { \"Bob\", 42, 0 } };\n\n /* uncomment for user input\n if (!get_player(players) || !get_player(players + 1))\n exit(EXIT_FAILURE);\n */\n\n int current = 0;\n\n while (1) {\n int next = (current + 1) % 2;\n int value;\n\n printf(\"%s's turn. Enter an action: \", players[current].name);\n\n switch (get_action(&value)) {\n case ACTION_INVALID:\n fprintf(stderr, \"Invalid action.\\n\");\n continue;\n\n case ACTION_ATK:\n printf(\"%s deals %d damage to %s\\n\",\n players[current].name, value, players[next].name);\n players[next].hp -= value;\n break;\n case ACTION_POISON:\n printf(\"%s applies %d poison to %s\\n\",\n players[current].name, value, players[next].name);\n players[next].poison += value;\n break;\n case ACTION_HEALTH:\n printf(\"%s heals %d health.\\n\",\n players[current].name, value);\n players[current].hp += value;\n break;\n\n case ACTION_SHOW:\n print_status(players + current);\n print_status(players + next);\n continue;\n case ACTION_END:\n return EXIT_SUCCESS;\n\n case ACTION_NONE:\n break;\n\n default:\n continue;\n }\n\n if (players[next].hp < 1) {\n printf(\"%s has slain %s!\\n\",\n players[current].name, players[next].name);\n break;\n }\n\n /* apply poison, and reduce poison by one */\n if (players[current].poison)\n players[current].hp -= players[current].poison--;\n\n if (players[current].hp < 1) {\n printf(\"%s has died to poison!\\n\", players[current].name);\n break;\n }\n\n current = next;\n }\n}\n\nExample usage:\nAlice's turn. Enter an action: show\nAlice has 123 HP and 0 poison.\nBob has 42 HP and 0 poison.\nAlice's turn. Enter an action: poison 22\nAlice applies 22 poison to Bob\nBob's turn. Enter an action: atk 50\nBob deals 50 damage to Alice\nAlice's turn. Enter an action: none\nBob's turn. Enter an action: atk 50\nBob deals 50 damage to Alice\nBob has died to poison!\n\n" ]
[ 0 ]
[]
[]
[ "c", "input", "multiple_input", "string" ]
stackoverflow_0074668097_c_input_multiple_input_string.txt
Q: Getting Element Not Interactable Exception after attempting to insert search query into YouTube input field I'm just beginning to explore Python and automation testing Wanted to create a quick script that will: Open a YouTube page Find the search input field where I will insert my search query Insert a search query into the field Press on the button to receive search results Unfortunately Ive bumped into an error: "selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable" Please assist from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys link = "https://www.youtube.com/" browser = webdriver.Chrome() browser.get(link) search_string = browser.find_element(By.XPATH, "/html/body/ytd-app/div[1]/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/div[1]/div[1]/div/div[2]/input") search_string.send_keys("Test search input") button = browser.find_element(By.XPATH, '/html/body/ytd-app/div[1]/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/button') button.click() A: Instead of searching the Input field using the absolute xpath you can use the id properties of the element i.e search and similarly to click on the search icon to resolve the error. Note:- We will have to specify the input tag along with the id since the page contains couple of element with id as as search Your solution would look like link = "https://www.youtube.com/" browser.get(link) browser.maximize_window() browser.find_element(By.CSS_SELECTOR, "input#search").send_keys("Test search input") button = browser.find_element(By.ID, 'search-icon-legacy') button.click()
Getting Element Not Interactable Exception after attempting to insert search query into YouTube input field
I'm just beginning to explore Python and automation testing Wanted to create a quick script that will: Open a YouTube page Find the search input field where I will insert my search query Insert a search query into the field Press on the button to receive search results Unfortunately Ive bumped into an error: "selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable" Please assist from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys link = "https://www.youtube.com/" browser = webdriver.Chrome() browser.get(link) search_string = browser.find_element(By.XPATH, "/html/body/ytd-app/div[1]/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form/div[1]/div[1]/div/div[2]/input") search_string.send_keys("Test search input") button = browser.find_element(By.XPATH, '/html/body/ytd-app/div[1]/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/button') button.click()
[ "Instead of searching the Input field using the absolute xpath you can use the id properties of the element i.e search and similarly to click on the search icon to resolve the error.\nNote:- We will have to specify the input tag along with the id since the page contains couple of element with id as as search\nYour solution would look like\nlink = \"https://www.youtube.com/\"\nbrowser.get(link)\nbrowser.maximize_window()\nbrowser.find_element(By.CSS_SELECTOR, \"input#search\").send_keys(\"Test \nsearch input\")\nbutton = browser.find_element(By.ID, 'search-icon-legacy')\nbutton.click()\n\n" ]
[ 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074662142_python_selenium.txt
Q: How can I remove all vowels from an inputted string This doesn't really work To explain what I did: I set a vowel variable with a list Then I used a for loop to iterate through the list and print the letters not in the list A: as user @user56700 noted: You did, probably by mistake: if not letter.lower in vowels: instead: if not letter.lower() in vowels: first is method "itself", second is call of method. P.S. also, as user @user56700 noted, do not screenshot and paste code as image. Just paste and format as code, it is really simple, and shows that min of respect for others :) A: ` st=input("Enter Any String ") vowel=['a','e','i','o','u'] #Create a List of Vowel st=st.lower() #Convert Vowel in Lower case output="" for i in st: if i not in vowel: #Check Vowel if not then add to output output+=i print(output)`
How can I remove all vowels from an inputted string
This doesn't really work To explain what I did: I set a vowel variable with a list Then I used a for loop to iterate through the list and print the letters not in the list
[ "as user @user56700 noted: You did, probably by mistake:\nif not letter.lower in vowels:\n\ninstead:\nif not letter.lower() in vowels:\n\nfirst is method \"itself\", second is call of method.\nP.S.\nalso, as user @user56700 noted, do not screenshot and paste code as image. Just paste and format as code, it is really simple, and shows that min of respect for others :)\n", "`\nst=input(\"Enter Any String \")\nvowel=['a','e','i','o','u']\n#Create a List of Vowel\nst=st.lower()\n#Convert Vowel in Lower case\noutput=\"\"\nfor i in st:\nif i not in vowel:\n\n#Check Vowel if not then add to output\n\n output+=i\n\nprint(output)`\n" ]
[ 0, 0 ]
[ "import re\nvowel = input()\nlst = re.sub(\"[aeiouAEIOU]\",\"\",vowel)\nprint(lst)\n" ]
[ -1 ]
[ "list", "python", "string" ]
stackoverflow_0074670665_list_python_string.txt
Q: How Do I Add Subtitles to a Video in Python If I have a script.txt which contains all the things said in the video and the video itself then how do I dynamically add subtitles to the video using python. A: To add subtitles to a video using python, you can use the moviepy library. Here is an example of how you can do this: from moviepy.editor import * # Open the video video = VideoFileClip('video.mp4') # Read the script from the text file with open('script.txt', 'r') as f: script = f.read() # Add the subtitles to the video using the script video_with_subtitles = video.subclip(t_start=0, t_end=None).text_imprint(txt=script, fontsize=20, font='Arial', color='white') # Save the video with subtitles video_with_subtitles.write_videofile('video_with_subtitles.mp4') This code will open the video file, read the script from the text file, add the subtitles to the video using the script, and save the video with subtitles. You can adjust the font size, font, and color of the subtitles by modifying the fontsize, font, and color parameters in the text_imprint method.
How Do I Add Subtitles to a Video in Python
If I have a script.txt which contains all the things said in the video and the video itself then how do I dynamically add subtitles to the video using python.
[ "To add subtitles to a video using python, you can use the moviepy library. Here is an example of how you can do this:\nfrom moviepy.editor import *\n\n# Open the video\nvideo = VideoFileClip('video.mp4')\n\n# Read the script from the text file\nwith open('script.txt', 'r') as f:\n script = f.read()\n\n# Add the subtitles to the video using the script\nvideo_with_subtitles = video.subclip(t_start=0, \nt_end=None).text_imprint(txt=script, fontsize=20, font='Arial', \ncolor='white')\n\n# Save the video with subtitles\nvideo_with_subtitles.write_videofile('video_with_subtitles.mp4')\n\nThis code will open the video file, read the script from the text file, add the subtitles to the video using the script, and save the video with subtitles. You can adjust the font size, font, and color of the subtitles by modifying the fontsize, font, and color parameters in the text_imprint method.\n" ]
[ 2 ]
[]
[]
[ "python", "video_subtitles" ]
stackoverflow_0074672952_python_video_subtitles.txt
Q: How can we print a list of numbers taken as [1,2,3,4,5] in a column one by one such that the output should be as 1 2 3 4 5 i had written a piece of code expecting the output as 1 2 3 4 5 but i am unable to get that with my code for num in numlist: print(num) print(num,end=' ') 1 1 2 2 3 3 4 4 5 5 for num in numlist: print(num) print(num,end=' ') 1 2 3 4 5 5 can i know when i am executing it separately without indentation i am getting 5 5 two time line by line And also what if i wanted to get the output as 1 2 3 4 5
How can we print a list of numbers taken as [1,2,3,4,5] in a column one by one such that the output should be as 1 2 3 4 5
i had written a piece of code expecting the output as 1 2 3 4 5 but i am unable to get that with my code for num in numlist: print(num) print(num,end=' ') 1 1 2 2 3 3 4 4 5 5 for num in numlist: print(num) print(num,end=' ') 1 2 3 4 5 5 can i know when i am executing it separately without indentation i am getting 5 5 two time line by line And also what if i wanted to get the output as 1 2 3 4 5
[]
[]
[ "You can use list comprehension to get a list of strings, and then use join to get a string and print it.\nstrlist = [str(x) for x in numlist] \noutstr = \"\\n\".join(strlist) \nprint(outstr) \n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074672938_python.txt
Q: How can i display more than one row in my table USING PHP & MYSQL database I'm having issues to display all the rows inside my database table. But only one rows display instead of all data. $query= mysqli_query($conn,"select* from food_table"); if (mysqli_num_rows($query)>0){ echo "<p style='color: green;'>See Below the Available Foods<br></p>"; while($row=mysqli_fetch_assoc($query)){ $food_name= $row['food_name']; $food_info = $row['food_info']; $food_price = $row['food_price']; $vendor_id = $row['vendor_id']; $default_miles = $row['default_miles']; $food_date= $row['date']; } $foods= array($food_name,$food_info,$food_price,$vendor_id,$default_miles, $food_date ); foreach($foods as $foodss){ echo "$foodss.<br/>"; } please see result below;enter image description here A: You've got your loops wrong. You first loop through all rows in the database and assign them to the variables $food_name etc, however, only after you exit the while loop you create an array with those variables. This doesn't work, as now the $food_name etc just has the value of the last row. What you'd want is something like this: while($row = mysqli_fetch_assoc($query)) { $food_name= $row['food_name']; $food_info = $row['food_info']; $food_price = $row['food_price']; $vendor_id = $row['vendor_id']; $default_miles = $row['default_miles']; $food_date= $row['date']; echo $food_name . "<br/>; } Now you put the food name for every row on the page. Always keep in mind what your loop is actually doing. Every iteration of the while loop you set the variables $food_name to a certain value. Print the value in the current iteration to get all values on the page. If you want to store those values in an array, you would have to do something like $food_names[] = $row['food_name']. A: You have to store all data inside a array before display or you can print it inside while loop. best practice is store data inside array first. $query= mysqli_query($conn,"select* from food_table"); if (mysqli_num_rows($query)>0){ echo "<p style='color: green;'>See Below the Available Foods<br></p>"; $foods = array() //initialize an empty array while($row=mysqli_fetch_assoc($query)){ $food_name= $row['food_name']; $food_info = $row['food_info']; $food_price = $row['food_price']; $vendor_id = $row['vendor_id']; $default_miles = $row['default_miles']; $food_date= $row['date']; array_push($foods,$food_name,$food_info,$food_price,$vendor_id,$default_miles,$food_date); } foreach($foods as $foodss){ echo "$foodss.<br/>"; }
How can i display more than one row in my table USING PHP & MYSQL database
I'm having issues to display all the rows inside my database table. But only one rows display instead of all data. $query= mysqli_query($conn,"select* from food_table"); if (mysqli_num_rows($query)>0){ echo "<p style='color: green;'>See Below the Available Foods<br></p>"; while($row=mysqli_fetch_assoc($query)){ $food_name= $row['food_name']; $food_info = $row['food_info']; $food_price = $row['food_price']; $vendor_id = $row['vendor_id']; $default_miles = $row['default_miles']; $food_date= $row['date']; } $foods= array($food_name,$food_info,$food_price,$vendor_id,$default_miles, $food_date ); foreach($foods as $foodss){ echo "$foodss.<br/>"; } please see result below;enter image description here
[ "You've got your loops wrong. You first loop through all rows in the database and assign them to the variables $food_name etc, however, only after you exit the while loop you create an array with those variables. This doesn't work, as now the $food_name etc just has the value of the last row.\nWhat you'd want is something like this:\nwhile($row = mysqli_fetch_assoc($query)) {\n\n $food_name= $row['food_name'];\n $food_info = $row['food_info'];\n $food_price = $row['food_price'];\n $vendor_id = $row['vendor_id'];\n $default_miles = $row['default_miles'];\n $food_date= $row['date'];\n\n echo $food_name . \"<br/>;\n \n}\n\nNow you put the food name for every row on the page.\nAlways keep in mind what your loop is actually doing. Every iteration of the while loop you set the variables $food_name to a certain value. Print the value in the current iteration to get all values on the page. If you want to store those values in an array, you would have to do something like $food_names[] = $row['food_name'].\n", "You have to store all data inside a array before display or you can print it inside while loop. best practice is store data inside array first.\n$query= mysqli_query($conn,\"select* from food_table\");\n if (mysqli_num_rows($query)>0){\n\n echo \"<p style='color: green;'>See Below the Available Foods<br></p>\";\n $foods = array() //initialize an empty array\n while($row=mysqli_fetch_assoc($query)){\n\n $food_name= $row['food_name'];\n $food_info = $row['food_info'];\n $food_price = $row['food_price'];\n $vendor_id = $row['vendor_id'];\n $default_miles = $row['default_miles'];\n $food_date= $row['date'];\n\n array_push($foods,$food_name,$food_info,$food_price,$vendor_id,$default_miles,$food_date);\n \n }\n\n\n foreach($foods as $foodss){\n\n echo \"$foodss.<br/>\";\n }\n\n" ]
[ 0, 0 ]
[]
[]
[ "html", "php" ]
stackoverflow_0074670698_html_php.txt
Q: "NotSupportedException" when WebRequest is unable to find a creator for that prefix I have a really strange problem with WebRequest in a ServiceStack web application (hosted by XSP on Mono). It seems that the registration of request modules works in a very strange way; I am using WebRequest to create an HTTP request, and it is failing because it was not able to find a creator for that "prefix" (HTTP). The exception I am seeing is NotSupportedException, and I was able to track it to the fact that no creator is registered for the HTTP prefix (I am hitting https://github.com/mono/mono/blob/master/mcs/class/System/System.Net/WebRequest.cs, around line 479) EDIT: more details: NotSupportedException is thrown by WebRequest.GetCreator, which uses the URL prefix as a key to choose which creator to return; in my case, a HttpRequestCreator. The exception is thrown because there is no creator registered for the "HTTP" prefix (actually, there are no creators at all). So I searched around a little bit, dug into Mono sources, and found that modules are (or should be) added to the webRequestModules section of system.web in one of the various *.config files. I looked at my machine.config file, and there it is: System.Net.HttpRequestCreator, System, Version=4.0.0.0 Looking at WebRequest Mono sources it seems that prefixes are added from configuration(s) inside the class static constructor (not a good choice, IMHO, but still.. it should work). To test it, I tried to add an HttpRequestCreator to system.net/webRequestModules in my web.config; this is loaded by XSP/Mono and results in a duplicate key exception (which is expected since HttpRequestCreator should be already loaded, as it is already present in machine.config). Even stranger: if I add a mock handler for Http, like this: bool res = System.Net.WebRequest.RegisterPrefix ("http", new MyHttpRequestCreator ()); Debug.Assert (res == false); The assertion sometimes pass... sometimes not! (RegisterPrefix returns "false" if a creator for the same prefix is already registered; I expect it always to return false, but this is not the case! Again, it is completely random) When the registration "fails" (i.e., returns false because an "HTTP" prefix is already registered), then the WebRequest can create requests for HTTP. It is as if calling RegisterPrefix "wakes up" the static constructor and let it run. I am perplexed: it seems like a race condition in the execution of the static constructor of WebRequest, but this does not make sense (the runtime protects static constructors with a lock, IIRC) What am I missing? How could I solve or work around this problem? Is it my fault (misunderstanding or missing something), or does it look like a Mono bug, so should I submit it? Details: mono --version Mono JIT compiler version 3.0.6 (Debian 3.0.6+dfsg-1~exp1~pre1) Possibly related, unanswered question: HTTP protocol not supported in WebRequest under mono A: It looks like there might be a race condition occurring in the static constructor of the WebRequest class when it is initializing the webRequestModules dictionary. The webRequestModules dictionary is not thread-safe, so if multiple threads are accessing it simultaneously when it is being initialized, it can cause issues like the ones you are experiencing. To avoid this problem, you could try initializing the webRequestModules dictionary manually in your code before calling any methods that use it, like this: static WebRequest() { webRequestModules = new Dictionary<string, IWebRequestCreate>(); // Add the standard prefixes and creators webRequestModules.Add("http", new HttpRequestCreator()); webRequestModules.Add("https", new HttpRequestCreator()); webRequestModules.Add("file", new FileWebRequestCreator()); webRequestModules.Add("ftp", new FtpWebRequestCreator()); // Add the prefixes and creators specified in config // ... } Alternatively, you could synchronize access to the webRequestModules dictionary using a lock statement, like this: static WebRequest() { webRequestModules = new Dictionary<string, IWebRequestCreate>(); // Add the standard prefixes and creators lock (webRequestModules) { webRequestModules.Add("http", new HttpRequestCreator()); webRequestModules.Add("https", new HttpRequestCreator()); webRequestModules.Add("file", new FileWebRequestCreator()); webRequestModules.Add("ftp", new FtpWebRequestCreator()); } // Add the prefixes and creators specified in config // ... } A: It looks like you're encountering a known issue with Mono where the webRequestModules section of the system.web configuration is not being loaded properly. The issue has been reported on the Mono project's GitHub page, and it appears that a fix has been implemented. You may be able to resolve this issue by upgrading to a newer version of Mono that includes the fix. Alternatively, you could try manually registering the HttpRequestCreator with the WebRequest class in your code, like this: System.Net.WebRequest.RegisterPrefix("http", new System.Net.HttpRequestCreator()); This should allow you to create WebRequest objects for HTTP URLs without encountering the NotSupportedException error. I would also recommend submitting the issue to the Mono project's GitHub page, as it may help the developers identify and address the underlying issue in a future release. Further, it looks like the issue may be related to the fact that the WebRequest.RegisterPrefix method is not thread-safe. This means that if multiple threads are trying to register prefixes at the same time, it can cause errors such as the ones you're seeing. To fix this, you could try using a lock around any calls to RegisterPrefix to ensure that only one thread is able to register a prefix at a time. Here's an example of how you could do this: private static readonly object _lock = new object(); public static void RegisterHttpPrefix() { lock (_lock) { bool res = System.Net.WebRequest.RegisterPrefix("http", new MyHttpRequestCreator()); Debug.Assert(res == false); } } This should prevent any errors related to multiple threads trying to register the same prefix at the same time. Further, you could be encountering a race condition with the static constructor for the WebRequest class. This is a known issue with the mono implementation of WebRequest. One possible workaround is to use the WebClient class instead of WebRequest. The WebClient class does not have the same issues with its static constructor, and should be able to create HTTP requests without any problems. Here is an example of how you could use WebClient to make an HTTP request: using System.Net; WebClient client = new WebClient(); string response = client.DownloadString("http://www.example.com/"); Alternatively, you could try using the HttpWebRequest class instead of WebRequest, as it does not have the same issues with its static constructor. Here is an example of how you could use HttpWebRequest to make an HTTP request: using System.Net; HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com/"); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Hope this helps!
"NotSupportedException" when WebRequest is unable to find a creator for that prefix
I have a really strange problem with WebRequest in a ServiceStack web application (hosted by XSP on Mono). It seems that the registration of request modules works in a very strange way; I am using WebRequest to create an HTTP request, and it is failing because it was not able to find a creator for that "prefix" (HTTP). The exception I am seeing is NotSupportedException, and I was able to track it to the fact that no creator is registered for the HTTP prefix (I am hitting https://github.com/mono/mono/blob/master/mcs/class/System/System.Net/WebRequest.cs, around line 479) EDIT: more details: NotSupportedException is thrown by WebRequest.GetCreator, which uses the URL prefix as a key to choose which creator to return; in my case, a HttpRequestCreator. The exception is thrown because there is no creator registered for the "HTTP" prefix (actually, there are no creators at all). So I searched around a little bit, dug into Mono sources, and found that modules are (or should be) added to the webRequestModules section of system.web in one of the various *.config files. I looked at my machine.config file, and there it is: System.Net.HttpRequestCreator, System, Version=4.0.0.0 Looking at WebRequest Mono sources it seems that prefixes are added from configuration(s) inside the class static constructor (not a good choice, IMHO, but still.. it should work). To test it, I tried to add an HttpRequestCreator to system.net/webRequestModules in my web.config; this is loaded by XSP/Mono and results in a duplicate key exception (which is expected since HttpRequestCreator should be already loaded, as it is already present in machine.config). Even stranger: if I add a mock handler for Http, like this: bool res = System.Net.WebRequest.RegisterPrefix ("http", new MyHttpRequestCreator ()); Debug.Assert (res == false); The assertion sometimes pass... sometimes not! (RegisterPrefix returns "false" if a creator for the same prefix is already registered; I expect it always to return false, but this is not the case! Again, it is completely random) When the registration "fails" (i.e., returns false because an "HTTP" prefix is already registered), then the WebRequest can create requests for HTTP. It is as if calling RegisterPrefix "wakes up" the static constructor and let it run. I am perplexed: it seems like a race condition in the execution of the static constructor of WebRequest, but this does not make sense (the runtime protects static constructors with a lock, IIRC) What am I missing? How could I solve or work around this problem? Is it my fault (misunderstanding or missing something), or does it look like a Mono bug, so should I submit it? Details: mono --version Mono JIT compiler version 3.0.6 (Debian 3.0.6+dfsg-1~exp1~pre1) Possibly related, unanswered question: HTTP protocol not supported in WebRequest under mono
[ "It looks like there might be a race condition occurring in the static constructor of the WebRequest class when it is initializing the webRequestModules dictionary. The webRequestModules dictionary is not thread-safe, so if multiple threads are accessing it simultaneously when it is being initialized, it can cause issues like the ones you are experiencing.\nTo avoid this problem, you could try initializing the webRequestModules dictionary manually in your code before calling any methods that use it, like this:\nstatic WebRequest()\n{\n webRequestModules = new Dictionary<string, IWebRequestCreate>();\n // Add the standard prefixes and creators\n webRequestModules.Add(\"http\", new HttpRequestCreator());\n webRequestModules.Add(\"https\", new HttpRequestCreator());\n webRequestModules.Add(\"file\", new FileWebRequestCreator());\n webRequestModules.Add(\"ftp\", new FtpWebRequestCreator());\n // Add the prefixes and creators specified in config\n // ...\n}\n\nAlternatively, you could synchronize access to the webRequestModules dictionary using a lock statement, like this:\nstatic WebRequest()\n{\n webRequestModules = new Dictionary<string, IWebRequestCreate>();\n // Add the standard prefixes and creators\n lock (webRequestModules)\n {\n webRequestModules.Add(\"http\", new HttpRequestCreator());\n webRequestModules.Add(\"https\", new HttpRequestCreator());\n webRequestModules.Add(\"file\", new FileWebRequestCreator());\n webRequestModules.Add(\"ftp\", new FtpWebRequestCreator());\n }\n // Add the prefixes and creators specified in config\n // ...\n}\n\n", "It looks like you're encountering a known issue with Mono where the webRequestModules section of the system.web configuration is not being loaded properly.\nThe issue has been reported on the Mono project's GitHub page, and it appears that a fix has been implemented. You may be able to resolve this issue by upgrading to a newer version of Mono that includes the fix.\nAlternatively, you could try manually registering the HttpRequestCreator with the WebRequest class in your code, like this:\nSystem.Net.WebRequest.RegisterPrefix(\"http\", new \nSystem.Net.HttpRequestCreator());\n\nThis should allow you to create WebRequest objects for HTTP URLs without encountering the NotSupportedException error.\nI would also recommend submitting the issue to the Mono project's GitHub page, as it may help the developers identify and address the underlying issue in a future release.\nFurther, it looks like the issue may be related to the fact that the WebRequest.RegisterPrefix method is not thread-safe. This means that if multiple threads are trying to register prefixes at the same time, it can cause errors such as the ones you're seeing.\nTo fix this, you could try using a lock around any calls to RegisterPrefix to ensure that only one thread is able to register a prefix at a time. Here's an example of how you could do this:\nprivate static readonly object _lock = new object();\n\npublic static void RegisterHttpPrefix()\n{\n lock (_lock)\n {\n bool res = System.Net.WebRequest.RegisterPrefix(\"http\", new MyHttpRequestCreator());\n Debug.Assert(res == false);\n }\n}\n\nThis should prevent any errors related to multiple threads trying to register the same prefix at the same time.\nFurther, you could be encountering a race condition with the static constructor for the WebRequest class. This is a known issue with the mono implementation of WebRequest.\nOne possible workaround is to use the WebClient class instead of WebRequest. The WebClient class does not have the same issues with its static constructor, and should be able to create HTTP requests without any problems.\nHere is an example of how you could use WebClient to make an HTTP request:\nusing System.Net;\n\nWebClient client = new WebClient();\nstring response = client.DownloadString(\"http://www.example.com/\");\n\nAlternatively, you could try using the HttpWebRequest class instead of WebRequest, as it does not have the same issues with its static constructor. Here is an example of how you could use HttpWebRequest to make an HTTP request:\nusing System.Net;\n\nHttpWebRequest request = (HttpWebRequest)WebRequest.Create(\"http://www.example.com/\");\nHttpWebResponse response = (HttpWebResponse)request.GetResponse();\n\nHope this helps!\n" ]
[ 0, 0 ]
[ "It looks like you are encountering a known issue with the Mono implementation of the WebRequest class. The problem is that the WebRequest static constructor is not thread-safe, which can cause race conditions when multiple threads try to access it at the same time.\nThe suggested workaround is to use the Lazy class to initialize the WebRequest class in a thread-safe way. You can do this by changing your code to something like this:\nstatic Lazy<WebRequest> _webRequest = new Lazy<WebRequest>(() => {\n bool res = System.Net.WebRequest.RegisterPrefix(\"http\", new MyHttpRequestCreator());\n Debug.Assert(res == false);\n return new WebRequest();\n});\n\nThis creates a lazy initialization of the WebRequest class, which ensures that it is only initialized once and in a thread-safe manner. You can then use the _webRequest variable to access the WebRequest instance in your code.\nI hope this helps! Let me know if you have any other questions.\n" ]
[ -1 ]
[ "httpwebrequest", "mono", "servicestack", "xsp" ]
stackoverflow_0017657145_httpwebrequest_mono_servicestack_xsp.txt
Q: jinja2 basename or dirname from builtin filters? Is there any way of doing a basename or dirname in jinja2 using only builtin filters? E.g. something like: #!/usr/bin/python import jinja2 mybin = '/my/favorite/full/path/foo' t = jinja2.Template("my binary is {{ mybin }}") print t.render() t = jinja2.Template("my basename is {{ mybin|basename() }}") print t.render() t = jinja2.Template("my dirname is {{ mybin|dirname() }}") print t.render() 1 Any ideas? A: If you found this question & are using Ansible, then these filters do exist in Ansible. To get the last name of a file path, like โ€˜foo.txtโ€™ out of โ€˜/etc/asdf/foo.txtโ€™: {{ path | basename }} To get the directory from a path: {{ path | dirname }} Without Ansible, it's easy to add custom filters to Jinja2: def basename(path): return os.path.basename(path) def dirname(path): return os.path.dirname(path) You register these in the template environment by updating the filters dictionary in the environment, prior to rendering the template: environment.filters['basename'] = basename environment.filters['dirname'] = dirname A: There doesn't appear to be a built in filter to get the physical base path. http://jinja.pocoo.org/docs/templates/#list-of-builtin-filters Here's how you could pass the current physical path. import os tmpl = env.get_template('index.html') return tmpl.render(folder=os.path.dirname(__file__)) Hope this helps! A: It's pretty simple, if you think about it, it's just tokenization using /, so for basename you split your string by slashes into a list, then get the last element from that list: {{ mybin.split('/') | last }} dirname is a bit more tricky: {{ mybin.split('/')[:-1] | join('/') }} Again, you explode the string by slashes, then take that list from the first item (:) until the penultimate item (-1), then join them back together. Easy as pie, right? Jinja2 often drives me crazy, but at the same time it's an incredibly powerful and often really efficient language :)
jinja2 basename or dirname from builtin filters?
Is there any way of doing a basename or dirname in jinja2 using only builtin filters? E.g. something like: #!/usr/bin/python import jinja2 mybin = '/my/favorite/full/path/foo' t = jinja2.Template("my binary is {{ mybin }}") print t.render() t = jinja2.Template("my basename is {{ mybin|basename() }}") print t.render() t = jinja2.Template("my dirname is {{ mybin|dirname() }}") print t.render() 1 Any ideas?
[ "If you found this question & are using Ansible, then these filters do exist in Ansible.\nTo get the last name of a file path, like โ€˜foo.txtโ€™ out of โ€˜/etc/asdf/foo.txtโ€™:\n{{ path | basename }}\n\nTo get the directory from a path:\n{{ path | dirname }}\n\nWithout Ansible, it's easy to add custom filters to Jinja2:\ndef basename(path):\n return os.path.basename(path)\n\ndef dirname(path):\n return os.path.dirname(path)\n\nYou register these in the template environment by updating the filters dictionary in the environment, prior to rendering the template:\nenvironment.filters['basename'] = basename\nenvironment.filters['dirname'] = dirname\n\n", "There doesn't appear to be a built in filter to get the physical base path.\nhttp://jinja.pocoo.org/docs/templates/#list-of-builtin-filters\nHere's how you could pass the current physical path.\nimport os\n\n\ntmpl = env.get_template('index.html')\nreturn tmpl.render(folder=os.path.dirname(__file__))\n\nHope this helps!\n", "It's pretty simple, if you think about it, it's just tokenization using /, so for basename you split your string by slashes into a list, then get the last element from that list:\n{{ mybin.split('/') | last }}\n\n\ndirname is a bit more tricky:\n{{ mybin.split('/')[:-1] | join('/') }}\n\nAgain, you explode the string by slashes, then take that list from the first item (:) until the penultimate item (-1), then join them back together.\n\nEasy as pie, right? Jinja2 often drives me crazy, but at the same time it's an incredibly powerful and often really efficient language :)\n" ]
[ 51, 0, 0 ]
[]
[]
[ "jinja2", "python_2.7" ]
stackoverflow_0022562969_jinja2_python_2.7.txt
Q: Converting hex to decimal in awk or sed I have a list of numbers, comma-separated: 123711184642,02,3583090366663629,639f02012437d4 123715942138,01,3538710295145500,639f02afd6c643 123711616258,02,3548370476972758,639f0200485732 I need to split the 3rd column into three as below: 123711184642,02,3583090366663629,639f02,0124,37d4 123715942138,01,3538710295145500,639f02,afd6,c643 123711616258,02,3548370476972758,639f02,0048,5732 And convert the digits in the last two columns into decimal: 123711184642,02,3583090366663629,639f02,292,14292 123715942138,01,3538710295145500,639f02,45014,50755 123711616258,02,3548370476972758,639f02,72,22322 A: Here's a variation on Jonathan's answer: awk $([[ $(awk --version) = GNU* ]] && echo --non-decimal-data) -F, ' BEGIN {OFS = FS} { $6 = sprintf("%d", "0x" substr($4, 11, 4)) $5 = sprintf("%d", "0x" substr($4, 7, 4)) $4 = substr($4, 1, 6) print }' I included a rather contorted way of adding the --non-decimal-data option if it's needed. Edit Just for the heck of it, here's the pure-Bash equivalent: saveIFS=$IFS IFS=, while read -r -a line do printf '%s,%s,%d,%d\n' "${line[*]:0:3}" "${line[3]:0:6}" "0x${line[3]:6:4}" "0x${line[3]:10:4}" done IFS=$saveIFS The "${line[*]:0:3}" (quoted *) works similarly to AWK's OFS in that it causes Bash's IFS (here a comma) to be inserted between array elements on output. We can take further advantage of that feature by inserting array elements as follows which more closely parallels my AWK version above. saveIFS=$IFS IFS=, while read -r -a line do line[6]=$(printf '%d' "0x${line[3]:10:4}") line[5]=$(printf '%d' "0x${line[3]:6:4}") line[4]=$(printf '%s' "${line[3]:0:6}") printf '%s\n' "${line[*]}" done IFS=$saveIFS Unfortunately, Bash doesn't allow printf -v (which is similar to sprintf()) to make assignments to array elements, so printf -v "line[6]" ... doesn't work. Edit: As of Bash 4.1, printf -v can now make assignments to array elements. Example: printf -v 'line[6]' '%d' "0x${line[3]:10:4}" The quotes around the array reference are needed to prevent possible filename matching. If a file named "line6" existed in the current directory and the reference wasn't quoted, then a variable named line6 would be created (or updated) containing the printf output. Nothing else about the file, such as its contents, would come into play. Only the name - and only tangentially. A: By AWK This answer concentrates on showing how to do the conversion by awk portably. Using --non-decimal-data for gawk is not recommended according to GNU Awk User's Guide. And using strtonum() is not portable. In the following examples the first word of each record is converted. By user-defined function The most portable way of doing conversion is by a user-defined awk function [reference]: function parsehex(V,OUT) { if(V ~ /^0x/) V=substr(V,3); for(N=1; N<=length(V); N++) OUT=(OUT*16) + H[substr(V, N, 1)] return(OUT) } BEGIN { for(N=0; N<16; N++) { H[sprintf("%x",N)]=N; H[sprintf("%X",N)]=N } } { print parsehex($1) } By calling shell's printf You could use this awk '{cmd="printf %d 0x" $1; cmd | getline decimal; close(cmd); print decimal}' but it is relatively slow. The following one is faster, if you have many newline-separated hexadecimal numbers to convert: awk 'BEGIN{cmd="printf \"%d\n\""}{cmd=cmd " 0x" $1}END{while ((cmd | getline dec) > 0) { print dec }; close(cmd)}' There might be a problem if very many arguments are added for the single printf command. In Linux In my experience the following works in Linux: awk -Wposix '{printf("%d\n","0x" $1)}' I tested it by gawk, mawk and original-awk in Ubuntu Linux 14.04. By original-awk the command displays a warning message, but you can hide it by redirection directive 2>/dev/null in shell. If you don't want to do that, you can strip the -Wposix in case of original-awk like this: awk $(awk -Wversion >/dev/null 2>&1 && printf -- "-Wposix") '{printf("%d\n","0x" $1)}' (In Bash 4 you could replace >/dev/null 2>&1 by &>/dev/null) Note: The -Wposix trick probably doesn't work with nawk which is used in OS X and some BSD OS variants, though. A: This seems to work: awk -F, '{ p1 = substr($4, 1, 6); p2 = ("0x" substr($4, 7, 4)) + 0; p3 = ("0x" substr($4, 11, 4)) + 0; printf "%s,%s,%s,%s,%d,%d\n", $1, $2, $3, p1, p2, p3; }' For your sample input data, it produces: 123711184642,02,3583090366663629,639f02,292,14292 123715942138,01,3538710295145500,639f02,45014,50755 123711616258,02,3548370476972758,639f02,72,22322 The string concatenation of '0x' plus the 4-digit hex followed by adding 0 forces awk to treat the numbers as hexadecimals. You can simplify this to: awk -F, '{ p1 = substr($4, 1, 6); p2 = "0x" substr($4, 7, 4); p3 = "0x" substr($4, 11, 4); printf "%s,%s,%s,%s,%d,%d\n", $1, $2, $3, p1, p2, p3; }' The strings prefixed with 0x are forced to integer when presented to printf() and the %d format. The code above works beautifully with the native awk on MacOS X 10.6.5 (version 20070501); sadly, it does not work with GNU gawk 3.1.7. That, it seems, is permitted behaviour according to POSIX (see the comments below). However, gawk has a non-standard function strtonum that can be used to bludgeon it into performing correctly - pity that bludgeoning is necessary. gawk -F, '{ p1 = substr($4, 1, 6); p2 = "0x" substr($4, 7, 4); p3 = "0x" substr($4, 11, 4); printf "%s,%s,%s,%s,%d,%d\n", $1, $2, $3, p1, strtonum(p2), strtonum(p3); }' A: printf "%d\n", strtonum( "0x"$1 )" A: This might work for you (GNU sed & printf): sed -r 's/(....)(....)$/ 0x\1 0x\2/;s/.*/printf "%s,%d,%d" &/e' file Split the last eight characters and add spaces preceeding the fields by the hex identifier and then evaluate the whole line using printf. A: cat all_info_List.csv| awk 'BEGIN {FS="|"}{print $21}'| awk 'BEGIN {FS=":"}{p1=$1":"$2":"$3":"$4":"$5":"; p2 = strtonum("0x"$6); printf("%s%02X\n",p1,p2+1) }' The above command prints the contents of "all_info_List.csv", a file where the field separator is "|". Then takes field 21 (MAC address) and splits it using field separator ":". It assigns to variable "p1" the first 5 bytes of each mac address, so if we had this mac address:"11:22:33:44:55:66", p1 would be: "11:22:33:44:55:". p2 is assigned with the decimal value of the last byte: "0x66" would assign "102" decimal to p2. Finally, I'm using printf to join p1 and p2, while converting p2 back to hex, after adding one to it. A: --- My 5 Cents I just want to add my 5 Cents in case this topic is still of interest. From the comments in the thread I take it, there still is. Hope it helps: Challenge: Convert a hex number to decimal on a Apple M1 laptop running the latest MacOS (2022) With the following versions on MacOS % uname -a Darwin macbook 22.1.0 Darwin Kernel Version 22.1.0: Sun Oct 9 20:15:09 PDT 2022; root:xnu-8792.41.9~2/RELEASE_ARM64_T6000 arm64 arm Darwin % gawk --version GNU Awk 5.2.1, API 3.2, (GNU MPFR 4.1.0-p13, GNU MP 6.2.1) Copyright (C) 1989, 1991-2022 Free Software Foundation. --- gawk -Wposix needed % echo "116B" | gawk '{p = ("0x" substr($1, 1, 4)) +0; printf("%d\n", p )}' 0 % echo "116B" | gawk -Wposix '{p = ("0x" substr($1, 1, 4)) +0; printf("%d\n", p )}' 4459 --- Some simplifications also work % echo "116B" | gawk -Wposix '{p = "0x" substr($1, 1, 4); printf("%d\n", p )}' 4459 % echo "116B" | gawk -Wposix '{printf("%d\n", "0x" substr($1, 1, 4))}' 4459 --- Checking... % echo "4459" | gawk '{printf("%X\n", $1 )}' 116B --- This form is what I was looking for % echo "00:11:6BX" | gawk -Wposix '{printf("%d\n", "0x" substr($1, 1, 2) substr($1, 4, 2) substr($1, 7, 2))}' 4459 A: this should be a cleaner approach than perl python or printf : echo 0x7E07E30EAAC59DB8EB9FDAD2EE818EA7AEB70192DAE552AD06B9FE 593BE89BC258483EA07C972B0FE7BA0D7B6CAC6DF338571F49CABB DD195629411CDF0F88858EC39F01AE181E60A4F0DAF5F4F0E86991 82243BDF159AB588F11E3FF68E799509128EA7BA957B62DF103D0E B2C3195DA1CCDFDD0CAF0E9958C1AF3E2B6993AA74C255B711BE38 DB031B26A596EFE19051A864000FB99F161923F12C2F9F40F18B6E 064CCCAE4C0776D0EB815947A30AB68B1CF12CA6622CAECA530221 2C27FD1579178363FE2E87B1F02FC0FDFFF | gawk -nMbe '$++NF = +$!_' OFS='\n\n' 1 0x7E07E30EAAC59DB8EB9FDAD2EE818EA7AEB70192DAE552AD06B9FE 593BE89BC258483EA07C972B0FE7BA0D7B6CAC6DF338571F49CABB DD195629411CDF0F88858EC39F01AE181E60A4F0DAF5F4F0E86991 82243BDF159AB588F11E3FF68E799509128EA7BA957B62DF103D0E B2C3195DA1CCDFDD0CAF0E9958C1AF3E2B6993AA74C255B711BE38 DB031B26A596EFE19051A864000FB99F161923F12C2F9F40F18B6E 064CCCAE4C0776D0EB815947A30AB68B1CF12CA6622CAECA530221 2C27FD1579178363FE2E87B1F02FC0FDFFF 2 985801769662049290799836483751359680713382803597807741 342261221390727037343867491391068497002991150267570021 888625408701957708383236015057159917981445085171196540 056449671723413767151987807183076995694938175592905407 706727043644590485574826597324100590757487981303537403 481578192766548120367625144822345612103264180960846560 558546717739085751660018602037450619797709845938562717 870137791128285871274530893277287577788311030033741131 093413810677239057304751530532826551215693481438241043 55789791231 in case you're wondering, this number is a Mersenne prime to the power of another Mersenne prime : 8191 ^ 127 And the 2 primes closest to it should be 8191 ^ 127 - ( 16 + 512 ) 8191 ^ 127 + ( 1450 )
Converting hex to decimal in awk or sed
I have a list of numbers, comma-separated: 123711184642,02,3583090366663629,639f02012437d4 123715942138,01,3538710295145500,639f02afd6c643 123711616258,02,3548370476972758,639f0200485732 I need to split the 3rd column into three as below: 123711184642,02,3583090366663629,639f02,0124,37d4 123715942138,01,3538710295145500,639f02,afd6,c643 123711616258,02,3548370476972758,639f02,0048,5732 And convert the digits in the last two columns into decimal: 123711184642,02,3583090366663629,639f02,292,14292 123715942138,01,3538710295145500,639f02,45014,50755 123711616258,02,3548370476972758,639f02,72,22322
[ "Here's a variation on Jonathan's answer:\nawk $([[ $(awk --version) = GNU* ]] && echo --non-decimal-data) -F, '\n BEGIN {OFS = FS}\n {\n $6 = sprintf(\"%d\", \"0x\" substr($4, 11, 4))\n $5 = sprintf(\"%d\", \"0x\" substr($4, 7, 4))\n $4 = substr($4, 1, 6)\n print\n }'\n\nI included a rather contorted way of adding the --non-decimal-data option if it's needed.\nEdit\nJust for the heck of it, here's the pure-Bash equivalent:\nsaveIFS=$IFS\nIFS=,\nwhile read -r -a line\ndo\n printf '%s,%s,%d,%d\\n' \"${line[*]:0:3}\" \"${line[3]:0:6}\" \"0x${line[3]:6:4}\" \"0x${line[3]:10:4}\"\ndone\nIFS=$saveIFS\n\nThe \"${line[*]:0:3}\" (quoted *) works similarly to AWK's OFS in that it causes Bash's IFS (here a comma) to be inserted between array elements on output. We can take further advantage of that feature by inserting array elements as follows which more closely parallels my AWK version above.\nsaveIFS=$IFS\nIFS=,\nwhile read -r -a line\ndo\n line[6]=$(printf '%d' \"0x${line[3]:10:4}\")\n line[5]=$(printf '%d' \"0x${line[3]:6:4}\")\n line[4]=$(printf '%s' \"${line[3]:0:6}\")\n printf '%s\\n' \"${line[*]}\"\ndone\nIFS=$saveIFS\n\nUnfortunately, Bash doesn't allow printf -v (which is similar to sprintf()) to make assignments to array elements, so printf -v \"line[6]\" ... doesn't work.\nEdit: As of Bash 4.1, printf -v can now make assignments to array elements. Example:\nprintf -v 'line[6]' '%d' \"0x${line[3]:10:4}\"\n\nThe quotes around the array reference are needed to prevent possible filename matching. If a file named \"line6\" existed in the current directory and the reference wasn't quoted, then a variable named line6 would be created (or updated) containing the printf output. Nothing else about the file, such as its contents, would come into play. Only the name - and only tangentially.\n", "By AWK\nThis answer concentrates on showing how to do the conversion by awk portably.\nUsing --non-decimal-data for gawk is not recommended according to GNU Awk User's Guide. And using strtonum() is not portable.\nIn the following examples the first word of each record is converted.\nBy user-defined function\nThe most portable way of doing conversion is by a user-defined awk function [reference]:\nfunction parsehex(V,OUT)\n{\n if(V ~ /^0x/) V=substr(V,3);\n\n for(N=1; N<=length(V); N++)\n OUT=(OUT*16) + H[substr(V, N, 1)]\n\n return(OUT)\n}\n\nBEGIN { for(N=0; N<16; N++)\n { H[sprintf(\"%x\",N)]=N; H[sprintf(\"%X\",N)]=N } }\n\n{ print parsehex($1) }\n\nBy calling shell's printf\nYou could use this\nawk '{cmd=\"printf %d 0x\" $1; cmd | getline decimal; close(cmd); print decimal}'\n\nbut it is relatively slow. The following one is faster, if you have many newline-separated hexadecimal numbers to convert:\nawk 'BEGIN{cmd=\"printf \\\"%d\\n\\\"\"}{cmd=cmd \" 0x\" $1}END{while ((cmd | getline dec) > 0) { print dec }; close(cmd)}'\n\nThere might be a problem if very many arguments are added for the single printf command.\nIn Linux\nIn my experience the following works in Linux:\nawk -Wposix '{printf(\"%d\\n\",\"0x\" $1)}'\n\nI tested it by gawk, mawk and original-awk in Ubuntu Linux 14.04. By original-awk the command displays a warning message, but you can hide it by redirection directive 2>/dev/null in shell. If you don't want to do that, you can strip the -Wposix in case of original-awk like this:\nawk $(awk -Wversion >/dev/null 2>&1 && printf -- \"-Wposix\") '{printf(\"%d\\n\",\"0x\" $1)}'\n\n(In Bash 4 you could replace >/dev/null 2>&1 by &>/dev/null)\nNote: The -Wposix trick probably doesn't work with nawk which is used in OS X and some BSD OS variants, though.\n", "This seems to work:\nawk -F, '{ p1 = substr($4, 1, 6);\n p2 = (\"0x\" substr($4, 7, 4)) + 0;\n p3 = (\"0x\" substr($4, 11, 4)) + 0;\n printf \"%s,%s,%s,%s,%d,%d\\n\", $1, $2, $3, p1, p2, p3;\n }'\n\nFor your sample input data, it produces:\n123711184642,02,3583090366663629,639f02,292,14292\n123715942138,01,3538710295145500,639f02,45014,50755\n123711616258,02,3548370476972758,639f02,72,22322\n\nThe string concatenation of '0x' plus the 4-digit hex followed by adding 0 forces awk to treat the numbers as hexadecimals.\nYou can simplify this to:\nawk -F, '{ p1 = substr($4, 1, 6);\n p2 = \"0x\" substr($4, 7, 4);\n p3 = \"0x\" substr($4, 11, 4);\n printf \"%s,%s,%s,%s,%d,%d\\n\", $1, $2, $3, p1, p2, p3;\n }'\n\nThe strings prefixed with 0x are forced to integer when presented to printf() and the %d format.\n\nThe code above works beautifully with the native awk on MacOS X 10.6.5 (version 20070501); sadly, it does not work with GNU gawk 3.1.7. That, it seems, is permitted behaviour according to POSIX (see the comments below). However, gawk has a non-standard function strtonum that can be used to bludgeon it into performing correctly - pity that bludgeoning is necessary.\ngawk -F, '{ p1 = substr($4, 1, 6);\n p2 = \"0x\" substr($4, 7, 4);\n p3 = \"0x\" substr($4, 11, 4);\n printf \"%s,%s,%s,%s,%d,%d\\n\", $1, $2, $3, p1, strtonum(p2), strtonum(p3);\n }'\n\n", "printf \"%d\\n\", strtonum( \"0x\"$1 )\"\n\n", "This might work for you (GNU sed & printf):\nsed -r 's/(....)(....)$/ 0x\\1 0x\\2/;s/.*/printf \"%s,%d,%d\" &/e' file\n\nSplit the last eight characters and add spaces preceeding the fields by the hex identifier and then evaluate the whole line using printf.\n", "cat all_info_List.csv| awk 'BEGIN {FS=\"|\"}{print $21}'| awk 'BEGIN {FS=\":\"}{p1=$1\":\"$2\":\"$3\":\"$4\":\"$5\":\"; p2 = strtonum(\"0x\"$6); printf(\"%s%02X\\n\",p1,p2+1) }'\n\nThe above command prints the contents of \"all_info_List.csv\", a file where the field separator is \"|\".\nThen takes field 21 (MAC address) and splits it using field separator \":\".\nIt assigns to variable \"p1\" the first 5 bytes of each mac address, so if we had this mac address:\"11:22:33:44:55:66\", p1 would be: \"11:22:33:44:55:\".\np2 is assigned with the decimal value of the last byte: \"0x66\" would assign \"102\" decimal to p2.\nFinally, I'm using printf to join p1 and p2, while converting p2 back to hex, after adding one to it.\n", "--- My 5 Cents\nI just want to add my 5 Cents in case this topic is still of interest. From the comments in the thread\nI take it, there still is. Hope it helps:\nChallenge: Convert a hex number to decimal on a Apple M1 laptop running the latest MacOS (2022)\nWith the following versions on MacOS\n% uname -a\nDarwin macbook 22.1.0 Darwin Kernel Version 22.1.0: Sun Oct 9 20:15:09 PDT 2022; root:xnu-8792.41.9~2/RELEASE_ARM64_T6000 arm64 arm Darwin\n\n% gawk --version\nGNU Awk 5.2.1, API 3.2, (GNU MPFR 4.1.0-p13, GNU MP 6.2.1)\nCopyright (C) 1989, 1991-2022 Free Software Foundation.\n\n--- gawk -Wposix needed\n% echo \"116B\" | gawk '{p = (\"0x\" substr($1, 1, 4)) +0; printf(\"%d\\n\", p )}'\n0\n\n% echo \"116B\" | gawk -Wposix '{p = (\"0x\" substr($1, 1, 4)) +0; printf(\"%d\\n\", p )}'\n4459\n\n--- Some simplifications also work\n% echo \"116B\" | gawk -Wposix '{p = \"0x\" substr($1, 1, 4); printf(\"%d\\n\", p )}'\n4459\n\n% echo \"116B\" | gawk -Wposix '{printf(\"%d\\n\", \"0x\" substr($1, 1, 4))}'\n4459\n\n--- Checking...\n% echo \"4459\" | gawk '{printf(\"%X\\n\", $1 )}'\n116B\n\n--- This form is what I was looking for\n% echo \"00:11:6BX\" | gawk -Wposix '{printf(\"%d\\n\", \"0x\" substr($1, 1, 2) substr($1, 4, 2) substr($1, 7, 2))}'\n4459\n\n", "this should be a cleaner approach than perl python or printf :\necho 0x7E07E30EAAC59DB8EB9FDAD2EE818EA7AEB70192DAE552AD06B9FE\n 593BE89BC258483EA07C972B0FE7BA0D7B6CAC6DF338571F49CABB\n DD195629411CDF0F88858EC39F01AE181E60A4F0DAF5F4F0E86991\n 82243BDF159AB588F11E3FF68E799509128EA7BA957B62DF103D0E\n B2C3195DA1CCDFDD0CAF0E9958C1AF3E2B6993AA74C255B711BE38\n DB031B26A596EFE19051A864000FB99F161923F12C2F9F40F18B6E\n 064CCCAE4C0776D0EB815947A30AB68B1CF12CA6622CAECA530221\n 2C27FD1579178363FE2E87B1F02FC0FDFFF | \n\n\ngawk -nMbe '$++NF = +$!_' OFS='\\n\\n' \n\n\n 1 0x7E07E30EAAC59DB8EB9FDAD2EE818EA7AEB70192DAE552AD06B9FE\n 593BE89BC258483EA07C972B0FE7BA0D7B6CAC6DF338571F49CABB\n DD195629411CDF0F88858EC39F01AE181E60A4F0DAF5F4F0E86991\n 82243BDF159AB588F11E3FF68E799509128EA7BA957B62DF103D0E\n B2C3195DA1CCDFDD0CAF0E9958C1AF3E2B6993AA74C255B711BE38\n DB031B26A596EFE19051A864000FB99F161923F12C2F9F40F18B6E\n 064CCCAE4C0776D0EB815947A30AB68B1CF12CA6622CAECA530221\n 2C27FD1579178363FE2E87B1F02FC0FDFFF\n\n 2 985801769662049290799836483751359680713382803597807741\n 342261221390727037343867491391068497002991150267570021\n 888625408701957708383236015057159917981445085171196540\n 056449671723413767151987807183076995694938175592905407\n 706727043644590485574826597324100590757487981303537403\n 481578192766548120367625144822345612103264180960846560\n 558546717739085751660018602037450619797709845938562717\n 870137791128285871274530893277287577788311030033741131\n 093413810677239057304751530532826551215693481438241043\n 55789791231\n\nin case you're wondering, this number is a Mersenne prime to the power of another Mersenne prime :\n\n8191 ^ 127 \n\n\nAnd the 2 primes closest to it should be\n\n\n 8191 ^ 127 - ( 16 + 512 )\n\n\n\n 8191 ^ 127 + ( 1450 )\n\n\n\n" ]
[ 31, 12, 11, 3, 1, 0, 0, 0 ]
[ "Perl version, with a tip of the hat to @Jonathan:\nperl -F, -lane '$p1 = substr($F[3], 0, 6); $p2 = substr($F[3], 6, 4); $p3 = substr($F[3], 10, 4); printf \"%s,%s,%s,%s,%d,%d\\n\", @F[0..2], $p1, hex($p2), hex($p3)' file\n\n-a turn on autosplit mode, to populate the @F array\n-F, changes the autosplit separator to , (default is whitespace)\nThe substr() indices are 1 less than their awk equivalents, since Perl arrays start from 0.\nOutput:\n123711184642,02,3583090366663629,639f02,292,14292\n123715942138,01,3538710295145500,639f02,45014,50755\n123711616258,02,3548370476972758,639f02,72,22322\n\n" ]
[ -1 ]
[ "awk", "decimal", "hex", "sed" ]
stackoverflow_0004614775_awk_decimal_hex_sed.txt
Q: why after passing object to method for another object it becomes invisible in c++? my question is why the object becomes invisible or uncountable after passing another object to a method in my object? it's H page class test { public: test(); void setNumber(int number); test add_test (test t1); int GetCounter(); virtual ~test(); private: int number; int static counter; }; #endif it's class page int test::counter = 0; test::test() { counter++; } test::~test() { counter--; } void test::setNumber(int n) { number = n; } test test::add_test(test t1) { test result; result.number = number + t1.number; return result; } int test::GetCounter() { return counter; } it's the main page #include <iostream> using namespace std; int main() { test t1; test t2; test t3; t1.setNumber(5); cout<<t1.GetCounter()<<"\n"; t2.setNumber(5); cout<<t2.GetCounter()<<"\n"; t3 = t2.add_test(t1); cout<<t3.GetCounter()<<"\n"; } it all happens after I put "add_test" methode to object (t3) then became t3 like invisible which can't be counted as an object how does the output = (3 3 2) if there's 3 objects (t1 ,t2, t3) why didn't it return 3 3 3 A: t3 = t2.add_test(t1); This makes a new temporary class test object to pass to add_test (so there are actually four test objects in the program). Since you didn't define a copy constructor, the default copy constructor is used, and it doesn't increment your counter. But when this temporary is destructed, it calls your destructor (there is no other) which does decrement the counter.
why after passing object to method for another object it becomes invisible in c++?
my question is why the object becomes invisible or uncountable after passing another object to a method in my object? it's H page class test { public: test(); void setNumber(int number); test add_test (test t1); int GetCounter(); virtual ~test(); private: int number; int static counter; }; #endif it's class page int test::counter = 0; test::test() { counter++; } test::~test() { counter--; } void test::setNumber(int n) { number = n; } test test::add_test(test t1) { test result; result.number = number + t1.number; return result; } int test::GetCounter() { return counter; } it's the main page #include <iostream> using namespace std; int main() { test t1; test t2; test t3; t1.setNumber(5); cout<<t1.GetCounter()<<"\n"; t2.setNumber(5); cout<<t2.GetCounter()<<"\n"; t3 = t2.add_test(t1); cout<<t3.GetCounter()<<"\n"; } it all happens after I put "add_test" methode to object (t3) then became t3 like invisible which can't be counted as an object how does the output = (3 3 2) if there's 3 objects (t1 ,t2, t3) why didn't it return 3 3 3
[ "t3 = t2.add_test(t1);\n\nThis makes a new temporary class test object to pass to add_test (so there are actually four test objects in the program). Since you didn't define a copy constructor, the default copy constructor is used, and it doesn't increment your counter. But when this temporary is destructed, it calls your destructor (there is no other) which does decrement the counter.\n" ]
[ 1 ]
[]
[]
[ "c++", "oop" ]
stackoverflow_0074672960_c++_oop.txt
Q: An efficient way to search elements in a Json array (dictionary of arrays) I am writing a script that reads two Json files into dictionaries The dictionaries are more or less similar, like this { "elements":[ { "element_id":0, "thedata":{ "this": 5 } }, { "element_id":4, "thedata":{ "this": 5 } } { ... } ]} So far I had assumed that the element_id went from 0 and increased 1 by 1 Then the requirements changed and this time they went from 0 and increased 4 by 4 or something like this Anyway, I though so far that both dictionaries would have the same number of elements and the same increasing distance so when I got the elements in my script I wrote something like def process_elements(number): el1_id=thedictionary['elements'][number]['element_id'] el2_id=thedictionary2['elements'][number]['element_id'] assert(el1_id==el2_id) #here work with the data However the requirements have changed again Now the number of elements of one dictionary are not necessarily the same as the other Also it is not guaranteed that one of them start always at 0 So now I have to find the elements in both dictionaries with the same element id So my question is , in a dictionary like above (that came from a json) is there a quick way to find the element that has a particular element_id and get the element? Something like def process_elements(number): el1_id=thedictionary['elements'][number]['element_id'] n=find_i(thedictionary2,el1_id) #finds the index with the element that has id the same as el1_id el2_id=thedictionary2['elements'][n]['element_id'] assert(el1_id==el2_id) #Of course they are the same since we used find_i #here work with the data It has to be quick since I use it for an animation A: If you need to find multiple elements with a particular element_id in a dictionary, and you want to do it as efficiently as possible, you could use a dictionary to store the elements with a given element_id. Then, when you need to find an element with a particular element_id, you can just look it up in the dictionary using the element_id as the key, without having to iterate over the elements in the dictionary. Here's an example of how you could do this: # Create a dictionary to store the elements with a given element_id elements_by_id = {} # Iterate over the elements in the dictionary for element in thedictionary['elements']: # Get the element_id for the current element element_id = element['element_id'] # Check if the element_id is already a key in the elements_by_id dictionary if element_id not in elements_by_id: # If the element_id is not already a key in the dictionary, create a new key-value pair in the dictionary, # with the element_id as the key and an empty list as the value elements_by_id[element_id] = [] # Add the current element to the list of elements with the given element_id elements_by_id[element_id].append(element) # Now, when you need to find the elements with a particular element_id, you can just look it up in the dictionary # using the element_id as the key found_elements = elements_by_id[4] # Print the found elements to the console print(found_elements) This method is more efficient than iterating over the elements in the dictionary and checking each element's element_id value, because it only requires a single pass over the elements in the dictionary to create the elements_by_id dictionary, and then you can look up elements with a particular element_id in constant time. If you want to make the code even faster, you could use the dict.setdefault() method to create the elements_by_id dictionary in a single pass over the elements in the dictionary. This method allows you to specify a default value to use if the key you're looking for doesn't already exist in the dictionary, so you don't have to check if the key exists before adding it to the dictionary. Here's an example of how you could use the dict.setdefault() method to create the elements_by_id dictionary: # Create a dictionary to store the elements with a given element_id elements_by_id = {} # Iterate over the elements in the dictionary for element in thedictionary['elements']: # Get the element_id for the current element element_id = element['element_id'] # Use the setdefault() method to create a new key-value pair in the dictionary, # with the element_id as the key and an empty list as the value, if the element_id is not already a key in the dictionary elements_by_id.setdefault(element_id, []) # Add the current element to the list of elements with the given element_id elements_by_id[element_id].append(element) # Now, when you need to find the elements with a particular element_id, you can just look it up in the dictionary # using the element_id as the key found_elements = elements_by_id[4] # Print the found elements to the console print(found_elements) This method is faster than the previous method because it only requires a single pass over the elements in the dictionary, and it doesn't require you to check if the element_id is already a key in the dictionary before adding it. A: Using the get() method: # Create a dictionary to store the elements with a given element_id elements_by_id = {} # Iterate over the elements in the dictionary for element in thedictionary['elements']: # Get the element_id for the current element element_id = element['element_id'] # Check if the element_id is already a key in the elements_by_id dictionary if element_id not in elements_by_id: # If the element_id is not already a key in the dictionary, create a new key-value pair in the dictionary, # with the element_id as the key and an empty list as the value elements_by_id[element_id] = [] # Add the current element to the list of elements with the given element_id elements_by_id[element_id].append(element) # Now, when you need to find the elements with a particular element_id, you can use the dict.get() method # to get the list of elements with the given element_id, and specify a default value to return if the element_id # doesn't exist as a key in the dictionary found_elements = elements_by_id.get(34554, []) # Print the found elements to the console print(found_elements)
An efficient way to search elements in a Json array (dictionary of arrays)
I am writing a script that reads two Json files into dictionaries The dictionaries are more or less similar, like this { "elements":[ { "element_id":0, "thedata":{ "this": 5 } }, { "element_id":4, "thedata":{ "this": 5 } } { ... } ]} So far I had assumed that the element_id went from 0 and increased 1 by 1 Then the requirements changed and this time they went from 0 and increased 4 by 4 or something like this Anyway, I though so far that both dictionaries would have the same number of elements and the same increasing distance so when I got the elements in my script I wrote something like def process_elements(number): el1_id=thedictionary['elements'][number]['element_id'] el2_id=thedictionary2['elements'][number]['element_id'] assert(el1_id==el2_id) #here work with the data However the requirements have changed again Now the number of elements of one dictionary are not necessarily the same as the other Also it is not guaranteed that one of them start always at 0 So now I have to find the elements in both dictionaries with the same element id So my question is , in a dictionary like above (that came from a json) is there a quick way to find the element that has a particular element_id and get the element? Something like def process_elements(number): el1_id=thedictionary['elements'][number]['element_id'] n=find_i(thedictionary2,el1_id) #finds the index with the element that has id the same as el1_id el2_id=thedictionary2['elements'][n]['element_id'] assert(el1_id==el2_id) #Of course they are the same since we used find_i #here work with the data It has to be quick since I use it for an animation
[ "If you need to find multiple elements with a particular element_id in a dictionary, and you want to do it as efficiently as possible, you could use a dictionary to store the elements with a given element_id. Then, when you need to find an element with a particular element_id, you can just look it up in the dictionary using the element_id as the key, without having to iterate over the elements in the dictionary.\nHere's an example of how you could do this:\n# Create a dictionary to store the elements with a given element_id\nelements_by_id = {}\n\n# Iterate over the elements in the dictionary\nfor element in thedictionary['elements']:\n # Get the element_id for the current element\n element_id = element['element_id']\n\n # Check if the element_id is already a key in the elements_by_id dictionary\n if element_id not in elements_by_id:\n # If the element_id is not already a key in the dictionary, create a new key-value pair in the dictionary,\n # with the element_id as the key and an empty list as the value\n elements_by_id[element_id] = []\n\n # Add the current element to the list of elements with the given element_id\n elements_by_id[element_id].append(element)\n\n# Now, when you need to find the elements with a particular element_id, you can just look it up in the dictionary\n# using the element_id as the key\nfound_elements = elements_by_id[4]\n\n# Print the found elements to the console\nprint(found_elements)\n\nThis method is more efficient than iterating over the elements in the dictionary and checking each element's element_id value, because it only requires a single pass over the elements in the dictionary to create the elements_by_id dictionary, and then you can look up elements with a particular element_id in constant time.\nIf you want to make the code even faster, you could use the dict.setdefault() method to create the elements_by_id dictionary in a single pass over the elements in the dictionary. This method allows you to specify a default value to use if the key you're looking for doesn't already exist in the dictionary, so you don't have to check if the key exists before adding it to the dictionary.\nHere's an example of how you could use the dict.setdefault() method to create the elements_by_id dictionary:\n# Create a dictionary to store the elements with a given element_id\nelements_by_id = {}\n\n# Iterate over the elements in the dictionary\nfor element in thedictionary['elements']:\n # Get the element_id for the current element\n element_id = element['element_id']\n\n # Use the setdefault() method to create a new key-value pair in the dictionary,\n # with the element_id as the key and an empty list as the value, if the element_id is not already a key in the dictionary\n elements_by_id.setdefault(element_id, [])\n\n # Add the current element to the list of elements with the given element_id\n elements_by_id[element_id].append(element)\n\n# Now, when you need to find the elements with a particular element_id, you can just look it up in the dictionary\n# using the element_id as the key\nfound_elements = elements_by_id[4]\n\n# Print the found elements to the console\nprint(found_elements)\n\nThis method is faster than the previous method because it only requires a single pass over the elements in the dictionary, and it doesn't require you to check if the element_id is already a key in the dictionary before adding it.\n", "Using the get() method:\n# Create a dictionary to store the elements with a given element_id\nelements_by_id = {}\n\n# Iterate over the elements in the dictionary\nfor element in thedictionary['elements']:\n # Get the element_id for the current element\n element_id = element['element_id']\n\n # Check if the element_id is already a key in the elements_by_id dictionary\n if element_id not in elements_by_id:\n # If the element_id is not already a key in the dictionary, create a new key-value pair in the dictionary,\n # with the element_id as the key and an empty list as the value\n elements_by_id[element_id] = []\n\n # Add the current element to the list of elements with the given element_id\n elements_by_id[element_id].append(element)\n\n# Now, when you need to find the elements with a particular element_id, you can use the dict.get() method\n# to get the list of elements with the given element_id, and specify a default value to return if the element_id\n# doesn't exist as a key in the dictionary\nfound_elements = elements_by_id.get(34554, [])\n\n# Print the found elements to the console\nprint(found_elements)\n\n" ]
[ 1, 1 ]
[]
[]
[ "dictionary", "json", "python" ]
stackoverflow_0074672767_dictionary_json_python.txt
Q: How do I send cmd key mappings on macOS from kitty to neovim? I'd like to use the following mapping in my mappings.lua configuration: map('n', '<C-D-[>', ':BufferPrevious<cr>', options) map('n', '<C-D-]>', ':BufferNext<cr>', options) map('n', '<C-D-w>', ':BufferClose<cr>', options) I currently have this in my kitty.conf which is not working. map ctrl+cmd+[ send_text all ? A: To send key mappings from kitty to neovim, you will need to use the send_text command in kitty's configuration file (kitty.conf). This command can be used to send keystrokes to the terminal, which will be interpreted by neovim. For example, to send the <C-D-[> key mapping to neovim, you would use the following configuration in kitty: map ctrl+cmd+[ send_text all :BufferPrevious<cr> The send_text command will send the text :BufferPrevious to neovim, which will be interpreted as a command to switch to the previous buffer. You can use this same syntax to send the other key mappings you mentioned in your question. For example, the <C-D-]> mapping would be configured like this: map ctrl+cmd+] send_text all :BufferNext<cr> And the mapping would be configured like this: map ctrl+cmd+w send_text all :BufferClose<cr> Once you have added these mappings to your kitty.conf file, you should be able to use them to control neovim from within kitty. A: The kitty.conf configuration file uses a different syntax than the mappings.lua configuration file. In kitty.conf, you need to specify the key combination and the action that should be taken when that key combination is pressed. To use the key mappings you specified in your mappings.lua configuration file, you would need to use the following syntax in kitty.conf: map ctrl+cmd+[ send_text all :BufferPrevious<cr> map ctrl+cmd+] send_text all :BufferNext<cr> map ctrl+cmd+w send_text all :BufferClose<cr> This will map the ctrl+cmd+[ key combination to the :BufferPrevious<cr> action, the ctrl+cmd+] key combination to the :BufferNext<cr> action, and the ctrl+cmd+w key combination to the :BufferClose<cr> action. A: The latest commit of the current Neovide repository does not support macOS without Python2 installed Should fallback to db53e94 commit after git clone git reset --hard db53e94 And add the following environment variables in zshrc: export SKIA_BINARIES_URL=https://github.91chi.fun//https://github.com/rust-skia/skia-binaries/releases/download/{tag}/skia-binaries-{key}.tar.gz Restart the shell, re-use the cargo bundle --release command to build the App, and drag the built App to the /Applications folder. A: Here is a possible configuration for the mapping in mappings.lua: map('n', '<C-D-[>', ':BufferPrevious<cr>', {noremap = true}) map('n', '<C-D-]>', ':BufferNext<cr>', {noremap = true}) map('n', '<C-D-w>', ':BufferClose<cr>', {noremap = true}) The noremap option specifies that the mapping is not to be remapped by subsequent mappings. This can prevent conflicts with other mappings and ensure that the mapping behaves as expected. Note that the send_text option in kitty.conf is used to send a sequence of characters as keyboard input, rather than mapping a key sequence to a command. So it is not directly applicable to the mapping you are trying to create.
How do I send cmd key mappings on macOS from kitty to neovim?
I'd like to use the following mapping in my mappings.lua configuration: map('n', '<C-D-[>', ':BufferPrevious<cr>', options) map('n', '<C-D-]>', ':BufferNext<cr>', options) map('n', '<C-D-w>', ':BufferClose<cr>', options) I currently have this in my kitty.conf which is not working. map ctrl+cmd+[ send_text all ?
[ "To send key mappings from kitty to neovim, you will need to use the send_text command in kitty's configuration file (kitty.conf). This command can be used to send keystrokes to the terminal, which will be interpreted by neovim.\nFor example, to send the <C-D-[> key mapping to neovim, you would use the following configuration in kitty:\nmap ctrl+cmd+[ send_text all :BufferPrevious<cr>\n\nThe send_text command will send the text :BufferPrevious to neovim, which will be interpreted as a command to switch to the previous buffer.\nYou can use this same syntax to send the other key mappings you mentioned in your question. For example, the <C-D-]> mapping would be configured like this:\nmap ctrl+cmd+] send_text all :BufferNext<cr>\n\nAnd the mapping would be configured like this:\nmap ctrl+cmd+w send_text all :BufferClose<cr>\n\nOnce you have added these mappings to your kitty.conf file, you should be able to use them to control neovim from within kitty.\n", "The kitty.conf configuration file uses a different syntax than the mappings.lua configuration file. In kitty.conf, you need to specify the key combination and the action that should be taken when that key combination is pressed.\nTo use the key mappings you specified in your mappings.lua configuration file, you would need to use the following syntax in kitty.conf:\nmap ctrl+cmd+[ send_text all :BufferPrevious<cr>\nmap ctrl+cmd+] send_text all :BufferNext<cr>\nmap ctrl+cmd+w send_text all :BufferClose<cr>\n\nThis will map the ctrl+cmd+[ key combination to the :BufferPrevious<cr> action, the ctrl+cmd+] key combination to the :BufferNext<cr> action, and the ctrl+cmd+w key combination to the :BufferClose<cr> action.\n", "The latest commit of the current Neovide repository does not support macOS without Python2 installed\nShould fallback to db53e94 commit after git clone\ngit reset --hard db53e94\n\nAnd add the following environment variables in zshrc:\nexport SKIA_BINARIES_URL=https://github.91chi.fun//https://github.com/rust-skia/skia-binaries/releases/download/{tag}/skia-binaries-{key}.tar.gz\n\nRestart the shell, re-use the cargo bundle --release command to build the App, and drag the built App to the /Applications folder.\n", "Here is a possible configuration for the mapping in mappings.lua:\nmap('n', '<C-D-[>', ':BufferPrevious<cr>', {noremap = true})\nmap('n', '<C-D-]>', ':BufferNext<cr>', {noremap = true})\nmap('n', '<C-D-w>', ':BufferClose<cr>', {noremap = true})\n\nThe noremap option specifies that the mapping is not to be remapped by subsequent mappings. This can prevent conflicts with other mappings and ensure that the mapping behaves as expected.\nNote that the send_text option in kitty.conf is used to send a sequence of characters as keyboard input, rather than mapping a key sequence to a command. So it is not directly applicable to the mapping you are trying to create.\n" ]
[ 0, 0, 0, 0 ]
[]
[]
[ "kitty", "neovim" ]
stackoverflow_0072681219_kitty_neovim.txt
Q: how to display all elements in queue? #include<stdio.h> #include<string.h> #include<stdlib.h> #define max 100 char name[max][80], data[80]; int front = 0; int rear = 0; int enqueue(); int dequeue(); int peek(); void display(); int main() { int value; int ch; printf("------------------------------\n"); printf("\tMenu"); printf("\n------------------------------"); printf("\n [1] ENQUEUE"); printf("\n [2] DEQUEUE"); printf("\n [3] PEEK"); printf("\n [4] DISPLAY"); printf("\n------------------------------\n"); while(1) { printf("Choice : "); scanf("%d", &ch); switch(ch) { case 1 : // insert printf("\nEnter the Name : "); scanf("%s",data); value = enqueue(name, &rear, data); if(value == -1 ) printf("\n QUEUE is Full \n"); else printf("\n'%s' is inserted in QUEUE.\n\n",data); break; case 2 : // delete value = dequeue(name, &front, &rear, data); if( value == -1 ) printf("\n QUEUE is Empty \n"); else printf("\n Deleted Name from QUEUE is : %s\n", data); printf("\n"); break; case 3: value = peek(name, &front, &rear, data); if(value != -1) { printf("\n The front is: %s\n", data); } break; case 4: display(); break; case 5 : exit(0); default: printf("Invalid Choice \n"); } } return 0; } int enqueue(char name[max][80], int *rear, const char data[80]) { if(*rear + 1 == max) return -1; strcpy(name[*rear], data); (*rear)++; return 1; } int dequeue(char name[max][80], int *front, int *rear, char data[80]) { if(*front == *rear) return -1; strcpy(data, name[(*front)++]); return 1; } int peek(char name[max][80], int *front, int *rear, char data[80]) { if(*front == *rear) { printf(" QUEUE IS EMPTY\n"); return -1; } strcpy(data, name[*front]); return 1; } void display(char name[max][80], int *front, int *rear, char data[80]) { if(*front == -1 || *front > *rear) { printf("\n QUEUE IS EMPTY"); } else { for(int i = *front; i<= *rear; i++) { printf("\t %s",data[i]); } } } Student here. I need to display all elements inside the queue, but my program ends whenever I click option number 4, For example, the user inputs four names, "Jennie, Lisa, Jisoo, Rose", when the user selects option number 4, the program should print all 4 names. Even though I only input one name and need to print it, the program just ends. How to fix this? A: There seems to be a few issues with the implementation of the display() function. First, the function definition has 4 parameters, but the implementation only has one parameter (data). This means that the values of the name, front, and rear variables are not being passed to the function, which will cause unexpected behavior. To fix this, the function definition should match the implementation, so you should remove the extra 3 parameters from the function definition. Then, you can access the name, front, and rear variables directly within the function since they are already defined in the global scope. The next issue is that you are iterating through the data array and printing each element, but the data array only contains the value of the last element that was dequeued. Instead, you should be iterating through the name array and printing the values of each element in that array. Here is an updated implementation of the display() function that should fix these issues: void display() { if(front == -1 || front > rear) { printf("\n QUEUE IS EMPTY"); } else { for(int i = front; i<= rear; i++) { printf("\t %s", name[I]); } } } Note that I also removed the unused data parameter from the function definition. You can now call this function from the main() function to display all the elements in the queue.
how to display all elements in queue?
#include<stdio.h> #include<string.h> #include<stdlib.h> #define max 100 char name[max][80], data[80]; int front = 0; int rear = 0; int enqueue(); int dequeue(); int peek(); void display(); int main() { int value; int ch; printf("------------------------------\n"); printf("\tMenu"); printf("\n------------------------------"); printf("\n [1] ENQUEUE"); printf("\n [2] DEQUEUE"); printf("\n [3] PEEK"); printf("\n [4] DISPLAY"); printf("\n------------------------------\n"); while(1) { printf("Choice : "); scanf("%d", &ch); switch(ch) { case 1 : // insert printf("\nEnter the Name : "); scanf("%s",data); value = enqueue(name, &rear, data); if(value == -1 ) printf("\n QUEUE is Full \n"); else printf("\n'%s' is inserted in QUEUE.\n\n",data); break; case 2 : // delete value = dequeue(name, &front, &rear, data); if( value == -1 ) printf("\n QUEUE is Empty \n"); else printf("\n Deleted Name from QUEUE is : %s\n", data); printf("\n"); break; case 3: value = peek(name, &front, &rear, data); if(value != -1) { printf("\n The front is: %s\n", data); } break; case 4: display(); break; case 5 : exit(0); default: printf("Invalid Choice \n"); } } return 0; } int enqueue(char name[max][80], int *rear, const char data[80]) { if(*rear + 1 == max) return -1; strcpy(name[*rear], data); (*rear)++; return 1; } int dequeue(char name[max][80], int *front, int *rear, char data[80]) { if(*front == *rear) return -1; strcpy(data, name[(*front)++]); return 1; } int peek(char name[max][80], int *front, int *rear, char data[80]) { if(*front == *rear) { printf(" QUEUE IS EMPTY\n"); return -1; } strcpy(data, name[*front]); return 1; } void display(char name[max][80], int *front, int *rear, char data[80]) { if(*front == -1 || *front > *rear) { printf("\n QUEUE IS EMPTY"); } else { for(int i = *front; i<= *rear; i++) { printf("\t %s",data[i]); } } } Student here. I need to display all elements inside the queue, but my program ends whenever I click option number 4, For example, the user inputs four names, "Jennie, Lisa, Jisoo, Rose", when the user selects option number 4, the program should print all 4 names. Even though I only input one name and need to print it, the program just ends. How to fix this?
[ "There seems to be a few issues with the implementation of the display() function. First, the function definition has 4 parameters, but the implementation only has one parameter (data). This means that the values of the name, front, and rear variables are not being passed to the function, which will cause unexpected behavior.\nTo fix this, the function definition should match the implementation, so you should remove the extra 3 parameters from the function definition. Then, you can access the name, front, and rear variables directly within the function since they are already defined in the global scope.\nThe next issue is that you are iterating through the data array and printing each element, but the data array only contains the value of the last element that was dequeued. Instead, you should be iterating through the name array and printing the values of each element in that array.\nHere is an updated implementation of the display() function that should fix these issues:\nvoid display()\n{\n if(front == -1 || front > rear)\n {\n printf(\"\\n QUEUE IS EMPTY\");\n }\n else\n {\n for(int i = front; i<= rear; i++)\n {\n printf(\"\\t %s\", name[I]);\n }\n }\n}\n\nNote that I also removed the unused data parameter from the function definition. You can now call this function from the main() function to display all the elements in the queue.\n" ]
[ 0 ]
[]
[]
[ "c", "queue" ]
stackoverflow_0074672940_c_queue.txt
Q: Is there a way to change the colour palette for light and dark themes in Ant Design version 5? I created a hook which works well when I toggle between light and dark modes in Chrome's Rendering, panel. However, the values in the ConfigProvider do not change when the theme is toggled. Can someone explain how to hack the design token to achieve the desired result? "use client"; import '@/styles/global.scss'; import { Layout } from 'antd'; import { theme, ConfigProvider } from 'antd'; import palette from "@/styles/palette.module.scss"; import { lato, inter, futura } from '@/assets/fonts'; import { usePrefersColorScheme } from '@/hooks/index'; import { Navbar, Footer, Ribbon } from "@/components/index"; const themeConfig = { token: { components: { Button: { fontFamily: futura.style.fontFamily, }, Input: { fontFamily: lato.style.fontFamily } }, // typography fontFamily: `-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'`, } }; // palette const colours = { lucid: { colorInfo: palette['cyan'], colorError: palette['red'], colorPrimary: palette['blue'], colorWarning: palette['orange'], colorSuccess: palette['green'], colorBgLayout: palette['light'] }, muted: { colorInfo: palette['muted-cyan'], colorError: palette['muted-red'], colorPrimary: palette['muted-blue'], colorWarning: palette['muted-orange'], colorSuccess: palette['muted-green'], colorBgLayout: palette['dark'] } } const RootLayout = ({ children }) => { const { token } = theme.useToken(); const lightThemed = usePrefersColorScheme(); const preference = (colours[lightThemed ? 'lucid' : 'muted']); return <html lang="en"> <head> <meta charSet="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <ConfigProvider theme={{ ...themeConfig, ...preference }}> <body className={`${inter.className}`}> <Layout> <Layout.Header style={{ background: token.colorBgLayout, lineHeight: 'normal' }}> <Navbar /> </Layout.Header> {children} <Ribbon /> <Footer /> </Layout> </body> </ConfigProvider> </html>; }; export default RootLayout; Is there anything I'm missing with using the new design token in Ant Design version 5? A: Yes, it is possible to change the color palette for light and dark themes in Ant Design version 5. Ant Design is a popular React UI library that provides a suite of pre-built components and design resources, including a color system that allows you to define and customize your color palette. To change the color palette for light and dark themes in Ant Design version 5, you can use the component to define your color palette and apply it to the whole application. The component allows you to customize various aspects of the Ant Design design system, including the color palette. Here is an example of how you can use the component to change the color palette for light and dark themes in Ant Design version 5: import { ConfigProvider } from 'antd'; // Define your color palette const palette = { primary: '#1890ff', secondary: '#f5222d', success: '#52c41a', warning: '#faad14', error: '#f5222d', info: '#1890ff', }; // Use the <ConfigProvider /> component to apply the color palette // to the whole application function App() { return ( <ConfigProvider autoInsertSpaceInButton={false} palette={palette} > {/* Your application components here */} </ConfigProvider> ); } In this example, the palette object defines the color values for the different colors in the color palette. You can customize these values to match your desired color scheme. The component is then used to apply the color palette to the whole application. Once you have defined your color palette and applied it using the component, you can use the color values in your application components to apply the colors to various elements. For example, you can use the color prop on a Button component to apply the primary color from your palette to the button: import { Button } from 'antd'; // Use the color prop to apply the primary color from the palette function MyButton() { return <Button color="primary">Click me!</Button>; } This code would create a Button component with the primary color from your color palette applied to it. You can use the other color values from your palette in the same way to apply them to different elements in your application. In summary, to change the color palette for light and dark themes in Ant Design version 5, you can use the component to define your color palette and apply it to the whole application. You can then use the color values from your palette in your application components to apply the colors to various elements. A: I finally cracked it. I'm using NextJS v13. And configuring React's contexts in the layout.jsx file in the new app is not supported. Solution: Create a file in the app directory and name it providers.jsx ensure to mark it as a client component with use client; at the top of the file. Nest all your client-side providers i.e theme, auth, etc Use the provider in the layout of your choice. You can find more in the Next 13 docs here
Is there a way to change the colour palette for light and dark themes in Ant Design version 5?
I created a hook which works well when I toggle between light and dark modes in Chrome's Rendering, panel. However, the values in the ConfigProvider do not change when the theme is toggled. Can someone explain how to hack the design token to achieve the desired result? "use client"; import '@/styles/global.scss'; import { Layout } from 'antd'; import { theme, ConfigProvider } from 'antd'; import palette from "@/styles/palette.module.scss"; import { lato, inter, futura } from '@/assets/fonts'; import { usePrefersColorScheme } from '@/hooks/index'; import { Navbar, Footer, Ribbon } from "@/components/index"; const themeConfig = { token: { components: { Button: { fontFamily: futura.style.fontFamily, }, Input: { fontFamily: lato.style.fontFamily } }, // typography fontFamily: `-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'`, } }; // palette const colours = { lucid: { colorInfo: palette['cyan'], colorError: palette['red'], colorPrimary: palette['blue'], colorWarning: palette['orange'], colorSuccess: palette['green'], colorBgLayout: palette['light'] }, muted: { colorInfo: palette['muted-cyan'], colorError: palette['muted-red'], colorPrimary: palette['muted-blue'], colorWarning: palette['muted-orange'], colorSuccess: palette['muted-green'], colorBgLayout: palette['dark'] } } const RootLayout = ({ children }) => { const { token } = theme.useToken(); const lightThemed = usePrefersColorScheme(); const preference = (colours[lightThemed ? 'lucid' : 'muted']); return <html lang="en"> <head> <meta charSet="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <ConfigProvider theme={{ ...themeConfig, ...preference }}> <body className={`${inter.className}`}> <Layout> <Layout.Header style={{ background: token.colorBgLayout, lineHeight: 'normal' }}> <Navbar /> </Layout.Header> {children} <Ribbon /> <Footer /> </Layout> </body> </ConfigProvider> </html>; }; export default RootLayout; Is there anything I'm missing with using the new design token in Ant Design version 5?
[ "Yes, it is possible to change the color palette for light and dark themes in Ant Design version 5. Ant Design is a popular React UI library that provides a suite of pre-built components and design resources, including a color system that allows you to define and customize your color palette.\nTo change the color palette for light and dark themes in Ant Design version 5, you can use the component to define your color palette and apply it to the whole application. The component allows you to customize various aspects of the Ant Design design system, including the color palette.\nHere is an example of how you can use the component to change the color palette for light and dark themes in Ant Design version 5:\nimport { ConfigProvider } from 'antd';\n\n// Define your color palette\nconst palette = {\n primary: '#1890ff',\n secondary: '#f5222d',\n success: '#52c41a',\n warning: '#faad14',\n error: '#f5222d',\n info: '#1890ff',\n};\n\n// Use the <ConfigProvider /> component to apply the color palette\n// to the whole application\nfunction App() {\n return (\n <ConfigProvider\n autoInsertSpaceInButton={false}\n palette={palette}\n >\n {/* Your application components here */}\n </ConfigProvider>\n );\n}\n\n\nIn this example, the palette object defines the color values for the different colors in the color palette. You can customize these values to match your desired color scheme. The component is then used to apply the color palette to the whole application.\nOnce you have defined your color palette and applied it using the component, you can use the color values in your application components to apply the colors to various elements. For example, you can use the color prop on a Button component to apply the primary color from your palette to the button:\nimport { Button } from 'antd';\n\n// Use the color prop to apply the primary color from the palette\nfunction MyButton() {\n return <Button color=\"primary\">Click me!</Button>;\n}\n\n\nThis code would create a Button component with the primary color from your color palette applied to it. You can use the other color values from your palette in the same way to apply them to different elements in your application.\nIn summary, to change the color palette for light and dark themes in Ant Design version 5, you can use the component to define your color palette and apply it to the whole application. You can then use the color values from your palette in your application components to apply the colors to various elements.\n", "I finally cracked it. I'm using NextJS v13. And configuring React's contexts in the layout.jsx file in the new app is not supported. Solution:\n\nCreate a file in the app directory and name it providers.jsx ensure to mark it as a client component with use client; at the top of the file.\nNest all your client-side providers i.e theme, auth, etc\nUse the provider in the layout of your choice.\n\nYou can find more in the Next 13 docs here\n" ]
[ 0, 0 ]
[]
[]
[ "antd", "javascript", "next.js", "reactjs", "themes" ]
stackoverflow_0074653488_antd_javascript_next.js_reactjs_themes.txt