instruction
stringlengths
0
30k
βŒ€
null
I am writing a request handler in a telegram bot. I am having difficulty processing the waiting for pressing the inline button, can you tell me if this can be implemented? I have a ticket monitoring start handler, get them in json, then process each ticket in the list. ``` class MonitoringStatus(StatesGroup): monitoring_active = State() monitoring_pending = State() waiting_for_ticket_action = State() ``` ``` def get_ticket_keyboard(): builder = InlineKeyboardBuilder() builder.add( InlineKeyboardButton( text="assign", callback_data="assign"), InlineKeyboardButton( text="resolve", callback_data="resolve"), ) return builder.as_markup() ``` ``` @router.message(None or MonitoringStatus.monitoring_pending, F.text == 'Start Monitoring') async def start_monitoring(message: Message, state: FSMContext): await state.set_state(MonitoringStatus.monitoring_active) await state.update_data(is_monitoring_active=True) await asyncio.sleep(3) await message.answer('Monitoring started') while True: is_monitoring_active = data.get('is_monitoring_active', False) if not is_monitoring_active: break tickets = await fetch_tickets_from_file() for ticket in tickets: await message.answer(f'Ticket: {ticket["ticket_number"]}\n' f'Reporter: {ticket["reporter"]}\n' f'Description: {ticket["description"]}', reply_markup=get_ticket_keyboard()) await MonitoringStatus.waiting_for_ticket_action.set() await asyncio.sleep(10) ``` And I get an error AttributeError: 'State' object has no attribute 'set'. If I don't use the set() function, all requests from "tickets" in cycle instantly leave messages in telegram, but I need to process each ticket sequentially.
{"Voters":[{"Id":11638718,"DisplayName":"εΊ·ζ‘“η‘‹"}],"DeleteType":1}
I have a current project of put sentences embeddings into clusters. I already have my embeddings and some clusters associated to a part of my sentences dataset. My goal is to use sentence similarity to my embeddings in order to apply a cluster to each of my sentence. I have in mind to use K nearest neighbours algorithm to label each of my sentence with a cluster. But I am not sure if it would work efficiently. What do you think of this approach ? Should I consider another method ?
Project idea about clustering and sentences similarity
My application is not running on a virtual device after I press the Run button, I get the message [Execution finished](https://i.stack.imgur.com/EIdAo.jpg). The Project is correctly [building](https://i.stack.imgur.com/k9fqx.jpg) and I don't get any error message in logcat. I've deleted all the virtual devices and created a new one wich is working well because I can load it in the device manager. I've also checked the [Run configurations] tab (https://i.stack.imgur.com/AoW8h.jpg) and it seems to be ok. This is my Android [tree structure](https://i.stack.imgur.com/mAAbc.jpg) Here my Manifest and gradle files ``` <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <application android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.DeviworksApp" tools:targetApi="31"> <activity android:name=".MainActivity" android:exported="true" android:label="@string/app_name" android:screenOrientation="sensorLandscape"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> // Top-level build file where you can add configuration options common to all sub-projects/modules. plugins { id 'com.android.application' version '8.2.2' apply false id ("com.google.devtools.ksp") version "1.9.0-1.0.12" apply false } plugins { id 'com.android.application' id 'com.google.devtools.ksp' } android { namespace 'com.deviworksapp' compileSdk 34 defaultConfig { applicationId "com.deviworksapp" minSdk 21 targetSdk 34 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } dataBinding{ enabled=true } buildFeatures { viewBinding true } } dependencies { implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'com.google.android.material:material:1.11.0' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.5' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' def room_version = "2.6.1" implementation("androidx.room:room-runtime:$room_version") annotationProcessor("androidx.room:room-compiler:$room_version") // To use Kotlin annotation processing tool (kapt) ksp("androidx.room:room-compiler:$room_version") // optional - Kotlin Extensions and Coroutines support for Room implementation("androidx.room:room-ktx:$room_version") // optional - Test helpers testImplementation("androidx.room:room-testing:$room_version") // optional - Paging 3 Integration implementation("androidx.room:room-paging:$room_version") } ```
Terraform replaces `aws_api_gateway_deployment` in each deployment, despite triggers seem constant. Here, `local.rendered_openapi` is the result of `templatefile(var.template_path, local.openapi_vars)`, which is constant (`local.openapi_vars` never change). So, the issue seems to be caused by `jsonencode({ for k, v in data.aws_default_tags.default_tags: k => v if k != "DeploymentId" }`. Here `DeploymentId` changes on every deploy, but it's filtered out. May `jsonencode` on a dictionary result in a different JSON encoding, since Terraform provides no guarantees with regards to ordering of keys/values? resource "aws_api_gateway_deployment" "api_gateway" { rest_api_id = aws_api_gateway_rest_api.api_gateway.id triggers = { redeployment = sha1(join(",", [jsonencode(local.rendered_openapi), jsonencode({ for k, v in data.aws_default_tags.default_tags: k => v if k != "DeploymentId" } )])) } lifecycle { create_before_destroy = true } }
Terraform replaces aws_api_gateway_deployment in each deployment, despite triggers seem constant?
|amazon-web-services|terraform|
I asked this question on [GitHub](https://github.com/GoogleCloudPlatform/spring-cloud-gcp/issues/2512) as well, and we figured out that to solve this you need to follow these steps: 1. Move the `spring.cloud.gcp.secretmanager.enabled: false` from your test `bootstrap.yaml` to your test `application.yaml` 1. Don't add/use `spring.cloud.config.import: sm://` in your test `application.yaml` Then it'll work. For me, I still got this warning when starting: ``` 2024-01-13T14:54:13.166+01:00 WARN 47230 --- [my-service] [ main] c.g.c.s.core.DefaultCredentialsProvider : No core credentials are set. Service-specific credentials (e.g., spring.cloud.gcp.pubsub.credentials.*) should be used if your app uses services that require credentials. java.io.IOException: Your default credentials were not found. To set up Application Default Credentials for your environment, see https://cloud.google.com/docs/authentication/external/set-up-adc. at com.google.auth.oauth2.DefaultCredentialsProvider.getDefaultCredentials(DefaultCredentialsProvider.java:127) ~[google-auth-library-oauth2-http-1.20.0.jar:1.20.0] at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:129) ~[google-auth-library-oauth2-http-1.20.0.jar:1.20.0] at com.google.auth.oauth2.GoogleCredentials.getApplicationDefault(GoogleCredentials.java:101) ~[google-auth-library-oauth2-http-1.20.0.jar:1.20.0] at com.google.api.gax.core.GoogleCredentialsProvider.getCredentials(GoogleCredentialsProvider.java:70) ~[gax-2.38.0.jar:2.38.0] at com.google.cloud.spring.core.DefaultCredentialsProvider.<init>(DefaultCredentialsProvider.java:101) ~[spring-cloud-gcp-core-5.0.0.jar:5.0.0] at com.google.cloud.spring.autoconfigure.core.GcpContextAutoConfiguration.googleCredentials(GcpContextAutoConfiguration.java:56) ~[spring-cloud-gcp-autoconfigure-5.0.0.jar:5.0.0] at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:580) ~[na:na] at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:140) ~[spring-beans-6.1.2.jar:6.1.2] at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651) ~[spring-beans-6.1.2.jar:6.1.2] at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:489) ~[spring-beans-6.1.2.jar:6.1.2] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1334) ~[spring-beans-6.1.2.jar:6.1.2] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1164) ~[spring-beans-6.1.2.jar:6.1.2] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:561) ~[spring-beans-6.1.2.jar:6.1.2] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521) ~[spring-beans-6.1.2.jar:6.1.2] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325) ~[spring-beans-6.1.2.jar:6.1.2] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.1.2.jar:6.1.2] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323) ~[spring-beans-6.1.2.jar:6.1.2] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-6.1.2.jar:6.1.2] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:975) ~[spring-beans-6.1.2.jar:6.1.2] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:960) ~[spring-context-6.1.2.jar:6.1.2] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:625) ~[spring-context-6.1.2.jar:6.1.2] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762) ~[spring-boot-3.2.1.jar:3.2.1] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:464) ~[spring-boot-3.2.1.jar:3.2.1] at org.springframework.boot.SpringApplication.run(SpringApplication.java:334) ~[spring-boot-3.2.1.jar:3.2.1] at org.springframework.boot.test.context.SpringBootContextLoader.lambda$loadContext$3(SpringBootContextLoader.java:137) ~[spring-boot-test-3.2.1.jar:3.2.1] at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:58) ~[spring-core-6.1.2.jar:6.1.2] at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:46) ~[spring-core-6.1.2.jar:6.1.2] at org.springframework.boot.SpringApplication.withHook(SpringApplication.java:1458) ~[spring-boot-3.2.1.jar:3.2.1] at org.springframework.boot.test.context.SpringBootContextLoader$ContextLoaderHook.run(SpringBootContextLoader.java:552) ~[spring-boot-test-3.2.1.jar:3.2.1] at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:137) ~[spring-boot-test-3.2.1.jar:3.2.1] at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:108) ~[spring-boot-test-3.2.1.jar:3.2.1] at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:225) ~[spring-test-6.1.2.jar:6.1.2] at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:152) ~[spring-test-6.1.2.jar:6.1.2] at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:130) ~[spring-test-6.1.2.jar:6.1.2] at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:191) ~[spring-test-6.1.2.jar:6.1.2] at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:130) ~[spring-test-6.1.2.jar:6.1.2] at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:260) ~[spring-test-6.1.2.jar:6.1.2] at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:163) ~[spring-test-6.1.2.jar:6.1.2] at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$10(ClassBasedTestDescriptor.java:378) ~[junit-jupiter-engine-5.10.1.jar:5.10.1] at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:383) ~[junit-jupiter-engine-5.10.1.jar:5.10.1] at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$11(ClassBasedTestDescriptor.java:378) ~[junit-jupiter-engine-5.10.1.jar:5.10.1] at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na] at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) ~[na:na] at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1708) ~[na:na] at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509) ~[na:na] at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499) ~[na:na] at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310) ~[na:na] at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735) ~[na:na] at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734) ~[na:na] at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762) ~[na:na] at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:377) ~[junit-jupiter-engine-5.10.1.jar:5.10.1] at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$instantiateAndPostProcessTestInstance$6(ClassBasedTestDescriptor.java:290) ~[junit-jupiter-engine-5.10.1.jar:5.10.1] at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:289) ~[junit-jupiter-engine-5.10.1.jar:5.10.1] at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$4(ClassBasedTestDescriptor.java:279) ~[junit-jupiter-engine-5.10.1.jar:5.10.1] at java.base/java.util.Optional.orElseGet(Optional.java:364) ~[na:na] at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$5(ClassBasedTestDescriptor.java:278) ~[junit-jupiter-engine-5.10.1.jar:5.10.1] at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31) ~[junit-jupiter-engine-5.10.1.jar:5.10.1] at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:106) ~[junit-jupiter-engine-5.10.1.jar:5.10.1] at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:105) ~[junit-jupiter-engine-5.10.1.jar:5.10.1] at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:69) ~[junit-jupiter-engine-5.10.1.jar:5.10.1] at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$2(NodeTestTask.java:123) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:123) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:90) ~[junit-platform-engine-1.10.1.jar:1.10.1] at java.base/java.util.ArrayList.forEach(ArrayList.java:1596) ~[na:na] at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) ~[junit-platform-engine-1.10.1.jar:1.10.1] at java.base/java.util.ArrayList.forEach(ArrayList.java:1596) ~[na:na] at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54) ~[junit-platform-engine-1.10.1.jar:1.10.1] at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:198) ~[junit-platform-launcher-1.10.1.jar:1.10.1] at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:169) ~[junit-platform-launcher-1.10.1.jar:1.10.1] at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:93) ~[junit-platform-launcher-1.10.1.jar:1.10.1] at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:58) ~[junit-platform-launcher-1.10.1.jar:1.10.1] at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:141) ~[junit-platform-launcher-1.10.1.jar:1.10.1] at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:57) ~[junit-platform-launcher-1.10.1.jar:1.10.1] at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:103) ~[junit-platform-launcher-1.10.1.jar:1.10.1] at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:85) ~[junit-platform-launcher-1.10.1.jar:1.10.1] at org.junit.platform.launcher.core.DelegatingLauncher.execute(DelegatingLauncher.java:47) ~[junit-platform-launcher-1.10.1.jar:1.10.1] at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:63) ~[junit-platform-launcher-1.10.1.jar:1.10.1] at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57) ~[junit5-rt.jar:na] at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38) ~[junit-rt.jar:na] at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11) ~[idea_rt.jar:na] at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35) ~[junit-rt.jar:na] at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232) ~[junit-rt.jar:na] at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55) ~[junit-rt.jar:na] ``` But with this configuration, I got rid of that as well: ```yaml spring: cloud: gcp: secretmanager: enabled: false core: enabled: false ```
null
null
When I try to install postgis33_15 on Rocky Linux 8, I end up with the following error package postgis33_15-3.3.1-1.rhel8.x86_64 from pgdg15 requires gdal35-libs >= 3.5.2, but none of the providers can be installed package postgis33_15-3.3.1-1.rhel8.x86_64 from pgdg15 requires libgdal.so.31()(64bit), but none of the providers can be installed ... conflicting requests - nothing provides libarmadillo.so.10()(64bit) needed by gdal35-libs-3.5.3-4.rhel8.x86_64 from pgdg-common internet suggests to enable EPEL and crb, but it's already done (CRB is showing up under name powertools) sudo dnf repolist repo id repo name appstream Rocky Linux 8 - AppStream baseos Rocky Linux 8 - BaseOS epel Extra Packages for Enterprise Linux 8 - x86_64 extras Rocky Linux 8 - Extras pgdg-common PostgreSQL common RPMs for RHEL / Rocky / AlmaLinux 8 - x86_64 pgdg12 PostgreSQL 12 for RHEL / Rocky / AlmaLinux 8 - x86_64 pgdg13 PostgreSQL 13 for RHEL / Rocky / AlmaLinux 8 - x86_64 pgdg14 PostgreSQL 14 for RHEL / Rocky / AlmaLinux 8 - x86_64 pgdg15 PostgreSQL 15 for RHEL / Rocky / AlmaLinux 8 - x86_64 pgdg16 PostgreSQL 16 for RHEL / Rocky / AlmaLinux 8 - x86_64 powertools Rocky Linux 8 - PowerTools so now I wonder what am I missing :) Any suggestions are appreciated!
installation of postgis33_15 on Rocky Linux 8 fails
|postgresql|postgis|postgis-installation|
null
null
null
null
### Preamble Reading the title of your question, I think you have to read quietly the *`address chapter*`* in `info sed`! Understanding the difference between *addressing* and *commands*! `s`, like `p` are commands! So your request is about *addressing* for *executing a command*. ### Address range and address for commands Little sample: comment all lines that contain *badWord*: sed -e '/badWord/s/^/# /' -i file More complete sample: <!-- language: lang-bash --> info sed | sed -ne ' /^4.3/,/^5/{ /^\(\o47\|\o342\o200\o230\){ :a; N; /\n / ! ba; N; p } }' - From the line that ***begin by `4.3`*** to the line that ***begin by `5`***, - On lines that **begin by a *quote `'`*** (or a *UTF8 open quote: `β€˜`*), - Place a *label* *`a`*. - Append next line - If current buffer ***does not contain*** a *newline* followed by **one *space***, the branch to *label `a`*. - Append one more line - print current buffer. <!-- language: lang-none --> '/REGEXP/' This will select any line which matches the regular expression REGEXP. If REGEXP itself includes any '/' characters, each must be '\%REGEXP%' (The '%' may be replaced by any other single character.) '/REGEXP/I' '\%REGEXP%I' The 'I' modifier to regular-expression matching is a GNU extension which causes the REGEXP to be matched in a case-insensitive manner. '/REGEXP/M' '\%REGEXP%M' The 'M' modifier to regular-expression matching is a GNU 'sed' extension which directs GNU 'sed' to match the regular expression '/[0-9]/p' matches lines with digits and prints them. Because the second line is changed before the '/[0-9]/' regex, it will not match and will not be printed: $ seq 3 | sed -n 's/2/X/ ; /[0-9]/p' 1 '0,/REGEXP/' A line number of '0' can be used in an address specification like '0,/REGEXP/' so that 'sed' will try to match REGEXP in the first 'ADDR1,+N' Matches ADDR1 and the N lines following ADDR1. 'ADDR1,~N' Matches ADDR1 and the lines following ADDR1 until the next line whose input line number is a multiple of N. The following command ### Please, RTFM: Have a look at `info sed`, search for *`* sed addresses`*, then *`* Regexp Addresses`*: > β€˜/REGEXP/’ > This will select any line which matches the regular expression > REGEXP. If REGEXP itself includes any β€˜/’ characters, each must be > escaped by a backslash (β€˜\’). > ... > > β€˜\%REGEXP%’ > (The β€˜%’ may be replaced by any other single character.) > > This also matches the regular expression REGEXP, but allows one to > use a different delimiter than β€˜/’. This is particularly useful if > the REGEXP itself contains a lot of slashes, since it avoids the > tedious escaping of every β€˜/’. If REGEXP itself includes any > delimiter characters, each must be escaped by a backslash (β€˜\’). ### In fine, regarding your question: So you have to precede your 1st *delimiter* by a backslash `\`: $ echo A | sed -ne '\#A#p' A
When using the `semantic-release` plugin `@semantic-release/gitlab` on protected branch (master is protected with maintainers allowed to merge and no one allowed to push and merge) I have remote: GitLab: You are not allowed to push code to protected branches on this project I also tried with allowed to force push enabled but it changes nothing. What's the solution ?
@semantic-release/gitlab and protected branches
|gitlab-ci|semantic-release|
We have UI editor from which user can select any number of days.<br> If the user selects continuous days, those are represented by dashes or hyphens, but if non-continuous days are selected then those are represented by commas..<br> `eg - String - M,W,F` - Non Continuous days.<br> `eg - String - M-F` - User selected continuous 5 days.<br> From backend point of view, if we are getting some string like `M-Tu,Th,Sa-Su` or `M-W,F-Su` etc combination, how to find the valid days from this ?.<br> I have created a constant array to either loop or check the value<br> ```DAYS: ['M', 'Tu', 'W', 'Th', 'F', 'Sa', 'Su'] let userInput = 'M-Tu,Th,Sa-Su' or 'M-W,F-Su' let validDays = []; const commaSeperatedDays = userInput?.split(','); const ContinuousDays = userInput?.split('-'); let indivdualDays = validDays.push(commaSeperatedDays.map(x => findIndividualDays(x))); function findIndividualDays(daysString) { //getting confused here how to handle cases const daysOfWeek = daysString?.split('-'); const startIndex = constants.DAYS.indexOf(daysOfWeek[0]); const endIndex = daysOfWeek.length > 1 ? constants.DAYS.indexOf(daysOfWeek[1]) : null; } ```
Find all the valid week days from a given string separated by commas and dashes
|javascript|arrays|
How to allow a single script in Laravel app, blade page when CSP (Content Security Policy) is enabled?
I need a script to copy a set of filetypes (but just the most recent (Backup) file!) from a backup structure and delete older existing files in the destination. This is what I got, but I am stuck in the last 2 commands (del and the copy command) : # Define Source $Source = "D:\Fullbackups" $Destination = "X:" # Array to filter Types $Filetype = @("*.vbk", "*.vbm", "*.bco") # Loop through each Subfolder foreach ($Folder in Get-ChildItem $Source -Directory) { # Get latest File per Filetype foreach ($fType in $Filetype) { # del existing $fType in Destination, so older backups do not waste space del $Destination\$Folder\*.$fType get-childitem -path $Folder.FullName -Filter $fType | where-object { -not $_.PSIsContainer } | sort-object -Property $_.CreationTime | select-object -last 1 | copy-item -Destination (join-path $Destination\$Folder $_) } }
You need to catch the click event of the generated CommandButtons. For this create a class module named `Class1` with this code, where Sheets(1) is the same sheet as in yours. ```` Public WithEvents contbutts As MSForms.CommandButton Private Sub contbutts_click() clicked_no = Mid(contbutts.Caption, 8) Sheets(1).Cells(clicked_no + 1, 2).Hyperlinks(1).Follow End Sub ```` Insert the assignment into your code ```` Sub UserForm1_Initialize() With UserForm1 ' last for A find Dim lastRowA As Long lastRowA = ThisWorkbook.Sheets(1).Cells(ThisWorkbook.Sheets(1).Rows.Count, 1).End(xlUp).Row ReDim conts(1 To lastRowA - 1) As Class1 'array for the classes ' reverse Dim i As Long For i = .Controls.Count - 1 To 0 Step -1 If TypeName(.Controls(i)) = "CommandButton" Then If Left(.Controls(i).Name, 7) = "Button_" Then .Controls.Remove i End If End If Next i Dim topOffset As Integer topOffset = 10 ' Start position For i = 2 To lastRowA ' Creating button Dim newButton As MSForms.CommandButton Set newButton = .Controls.Add("Forms.CommandButton.1", "Button_" & i - 1, True) ' Creating Button With newButton .Caption = ThisWorkbook.Sheets(1).Cells(i, 1).Value .Left = 10 .Top = topOffset .Width = 120 .Height = 20 End With Set conts(i - 1) = New Class1 'create a class for the button Set conts(i - 1).contbutts = newButton 'assign the button to the class's button to catch the click event. ' Position topOffset = topOffset + 30 ' area Between buttons Next i End With UserForm1.Show End Sub
Save a JSON array into one text record per array element
|javascript|json|stringify|
I am trying to make some coins I spawn trough Instantiate, to float up and down. This is the code I currently have: ``` using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Coin : MonoBehaviour{ public bool isopen; [SerializeField] private float Speed = 1f; [Header("Sliding Configs")] [SerializeField] private Vector3 SlideDirection = Vector3.up; [SerializeField] private float SlideAmount = 1f; private Vector3 StartPosition; private Coroutine AnimationCoroutine; public bool diadromos = true; public float[] CoinR = { 0 , 0, 0 , 0 , 0 , 0 }; public GameObject coin; public GameObject spawned; public List<GameObject> allSpawns = new List<GameObject>(); public void Start(){ CoinR[5] = 4; } public void Update(){ CoinR[0] = -51; CoinR[1] = -32; CoinR[2] = 1; CoinR[3] = -24; CoinR[4] = -20; if (diadromos ==true){ for(float i=0; i<= CoinR[5]; i++){ Invoke("SpawnCoin",0.3f); } diadromos= false; } foreach (GameObject thisEnemy in allSpawns){ DoSlidingOpen(thisEnemy); DoSlidingClose(thisEnemy); } } public void SpawnCoin(){ Vector3 randCoinPos = new Vector3(Random.Range(CoinR[0], CoinR[1]), CoinR[2], Random.Range(CoinR[3], CoinR[4])); Quaternion CoinQ = new Quaternion(90,90,0,0); GameObject spawned = Instantiate(coin, randCoinPos, CoinQ); allSpawns.Add(spawned); } private IEnumerator DoSlidingOpen(GameObject eachcoin){ StartPosition = eachcoin.transform.position; Vector3 endPosition = StartPosition + SlideAmount * SlideDirection; Vector3 startPosition = eachcoin.transform.position; float time = 0; while (time < 1) { eachcoin.transform.position = Vector3.Lerp(startPosition, endPosition, time); yield return null; time += Time.deltaTime * Speed; } } private IEnumerator DoSlidingClose(GameObject eachcoins){ StartPosition = eachcoins.transform.position; Vector3 endPosition = StartPosition; Vector3 startPosition = eachcoins.transform.position; float time = 0; while (time < 1) { eachcoins.transform.position = Vector3.Lerp(startPosition, endPosition, time); yield return null; time += Time.deltaTime * Speed; } } } ``` It's kind of a mess at this point, but I have tried a lot of different things. I am trying to reuse functions (DoSlidingOpen & DoSlidingClos) from another script for opening and closing doors. Edit: What is not happening is that the coins, which do actually spawn and are added to the list, don't move at all, they don't even glitch around. I tried to use ``` Invoke("DoSlidingOpen(thisEnemy)",2); Invoke("DoSlidingOpen(thisEnemy)",2); ``` Which didn't work as well, not sure if invoke can take variables input or not. I also tried doing foreach() inside the functions instead of in Update, also didn't work.
Application not running in virtual device Execution finished Android Studio
|android|
null
Actually the task is still not clear but why don't you do like that? ```dart bool _wasCallbackThatNeedToBeFiredOnceCalled = false; @override void didChangeDependencies() { if(!_wasCallbackThatNeedToBeFiredOnceCalled) { _callbackThatNeedToBeFiredOnce(); _wasCallbackThatNeedToBeFiredOnceCalled = true; } } ```
I'm trying to fetch the data and display on browser but getting an error '**notes.map is not a function**'. ``` import { useEffect, useState } from 'react'; import { Note as NoteModel } from './models/note'; import NoteComponent from './component/NoteComponent'; function App() { const [notes, setNotes] = useState<NoteModel[]>([]); const [isLoading, setIsLoading] = useState(true); useEffect(() => { const loadNotes = async () => { try { setIsLoading(true); const response = await fetch("/api/notes", { method: "GET" }); const notes : [] = await response.json(); setNotes(notes); console.log(notes); } catch (error) { console.error(error); alert(error); } finally { setIsLoading(false); } }; loadNotes(); },[]); return ( <div className="App"> { notes.map(note => ( <NoteComponent note={note} key={note._id}/> )) } </div> ); } export default App; ``` I am able to display data through 'JSON.stringyfy(notes)' but i want display data in component.
Problem in fetching data from different port in react-
|reactjs|typescript|
null
Accompanist allows to ask for one permission at once is it possible to ask for these two location permission at once? ``` <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> ``` thats my code ``` PermissionUtils.requestForPermission( context = context, permission = if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) { Manifest.permission.ACCESS_FINE_LOCATION } else { Manifest.permission.ACCESS_COARSE_LOCATION },) ``` ``` @Composable fun rememberPermissionLauncher( onGranted: () -> Unit, onDenied: () -> Unit, ): PermissionLauncher { return PermissionLauncher( rememberLauncherForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { onGranted() } else { onDenied() } } ) } class PermissionLauncher( val launcher: ManagedActivityResultLauncher<String, Boolean> ) ``` Greetings, Chris
How to properly ask for COARSE and FINE location permission using accompanist?
|android|kotlin|jetpack-compose-accompanist|
I'm trying to use the [NVIDIA SDK][1] to encode HDR video with H265. Windows Media Foundation doesn't (yet) support 10-bit input with H265. I can't seem to feed the colors correctly to the encoder. I'm trying to render a video which has 3 images, one green with a value of 1.0, one with value of 2.0 and one with value of 3.0 (maximum) in the RGB, that is, in D2D1_COLOR_F it's {0,1,0,1}, {0,2,0,1} and {0,3,0,1}. Only the maximum 3 is seen correctly (The left one is the generated video, the right one is the correct color that should be shown in the video): [![enter image description here][2]][2] With green set to 2.0, this is the result: [![enter image description here][3]][3] And with green set to 1.0, even worse: [![enter image description here][4]][4] And this is the result of a real HDR image: [![enter image description here][5]][5] The Nvidia encoder accepts colors in AR30 format, that is, 10 bits for R,G,B and 2 for Alpha (which is ignored). My DirectX rendered has the colors in GUID_WICPixelFormat128bppPRGBAFloat so I'm doing this: struct fourx { float r, g, b, a; }; float*f = pointer_to_floats; for (int x = 0; x < wi; x++) { for (int y = 0; y < he; y++) { char* dx = (char*)f; dx += y * wi * 16; dx += x * 16; fourx* col = (fourx*)dx; DirectX::XMVECTOR v; DirectX::XMVECTORF32 floatingVector = { col->r,col->g,col->b,col->a }; v = floatingVector; // float is 0 to max_lim float max_number = 3.0f; // this is got from my monitor's white level as described [here][6]. DirectX::PackedVector::XMUDECN4 u4 = {}; col->r *= 1023.0f / max_number; col->g *= 1023.0f / max_number; col->b *= 1023.0f / max_number; u4.z = (int)col->r; u4.y = (int)col->g; u4.x = (int)col->b; u4.w = 0; DWORD* dy = output_pointer; dy += y * wi; dy += x; *dy = u4.operator unsigned int(); } } I suspect something's wrong with the gamma or what. I'm not sure how to proceed from now on. [1]: https://developer.nvidia.com/nvidia-video-codec-sdk/download [2]: https://i.stack.imgur.com/qdsoV.png [3]: https://i.stack.imgur.com/Qr8YD.png [4]: https://i.stack.imgur.com/5eTNV.png [5]: https://i.stack.imgur.com/27IoG.jpg [6]: https://learn.microsoft.com/en-us/windows/win32/direct3darticles/high-dynamic-range
[![enter image description here][1]][1] So i have this table shown above. K3 represents the date (manually entered) and L1 represents the lead time. **The conditions the result has to follow is shown below** 1) Days that should be included are Monday, Tuesday, Wednesday, Thursday, Saturday and Sunday. (Leaving out Friday as non working day) 2) The Holidays should not be included `=holidays!A2:A9` the formula in L3 is `=WORKDAY.INTL(K4, L2, "0111101", holidays!A2:A9)` The list of holidays are shown in the table below. [![enter image description here][2]][2] As you can see, the result in L3 is 2nd March instead of 29th February. As this date does not fall on the holiday list and is not a Friday. Could someone help me with this, it would be much appreciated. [1]: https://i.stack.imgur.com/bbWm4.png [2]: https://i.stack.imgur.com/yDIhS.png
WORKDAY.INTL formula not working as intended
|excel|formula|wps|
Try adding these dependencies in your pom.xml file: <!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api --> <dependency> <groupId>javax.mail</groupId> <artifactId>javax.mail-api</artifactId> <version>1.6.2</version> </dependency> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.2</version> </dependency>
so I used gridfs to store an image on mongodb and when I want to get the images value in b64 it returns its function too. Here is how it looks: `Binary.createFromBase64(base64ValueHere)` instead of just returning the value itself. I read the docs and when I try: `myCollection.binaryObjectsFromBase64.findOne( { _id: fileId } )` I get the following error: ``` await chunksCollection.binaryObjectsFromBase64.findOne({files_id: filesResult._id}) ^ TypeError: Cannot read properties of undefined (reading 'findOne') ``` And this is how I am trying to retreive the file: ``` const getCourseImage = async (req, res) => { const courseId = req.params.courseId; if (courseId.length !== 24) { throw new InvalidInputError("Invalid course Id."); } const course = await Course.findById(courseId); if (!course) { throw new NotFoundError("Course not found"); } const db = mongoose.connection.db; if(!db) { throw new Error("Could not connect to databas"); } const filesCollection = db.collection("uploads.files"); if(!filesCollection) { throw new NotFoundError("Could not find collection") } const filesResult = await filesCollection.findOne({filename: course.image}); if(!filesResult){ throw new NotFoundError("Image not found") } const chunksCollection = db.collection("uploads.chunks") const chunksResult = await chunksCollection.findOne({files_id: filesResult._id}) console.log(chunksResult) const binaryData = Buffer.from(imageData, 'base64'); res.contentType('image/jpeg'); res.send(binaryData); }; ``` This is also my gridfs storage settings: ``` const multer = require('multer'); const {GridFsStorage} = require('multer-gridfs-storage'); const { v4: uuidv4 } = require('uuid'); const storage = new GridFsStorage({ url: 'mongodb://moonstruck:moonstruck@localhost:27018/moonstruck', file: (req, file) => { const filename = `${uuidv4()}.${file.originalname.split('.').pop()}`; return { filename: filename, bucketName: 'uploads', }; }, }); const upload = multer({ storage }); module.exports = upload; ``` I need to fix this so I can turn the b64 to buffer so I can send an image as a response but the image now has errors because of the function in the base64 string. Thanks!
## Authenticate is not a use-case First of all, `authenticate` is not really a use-case: - From the use-case analysis point of view, it's not a goal for the user. No user would buy a system just to authenticate. It's just a constraint necessary for certain behaviours to complete. - From the strict UML point of view, a use-case > specifies a set of behaviors performed by that subject, which yields an **observable result** that is **of value** for Actors or other stakeholders But performing authentication may not necessarily be observable (for example if the authentication is performed via single sign on capability behind the scene) and the user may not value the result of the authentication, but only the value of the other use cases for which authentication is a constraint. * There is no order defined for use-cases. Use cases are not meant to describe workflow, whereas both of your diagrams expect an order. (By the way, I assume that in the second diagram, `User` should also be associated with `authenticate`) The authentication should either be a constraint, or some activity to be performed (perhaps conditionally, e.g. if user is already authenticated) as part of the activity diagram that describes the details behind a use-case. Last but not least, more and more, authentication is no longer performed in the system but by an external system that is identity provider. ## What diagram alternative is more suitable I strongly disagree with your professor: the first alternative is not the recommended one, because it's a functional decomposition of your use-cases. While this is not forbidden in UML, it is seen as bad practice by leading authors such as [Bittner & Spence][1]. The second one is more elegant in this regard, as your actor specialisation (which is fully legit) allows to see what an authenticated user can do and what a non-authenticated user can do. The only flaw is the `authenticate` use-case. But if you'd remove it, it would still be correct and express your design intention. How the authentication is managed, is then a technical or a user-interface detail. Some side-remarks: - if you'd insist on keeping `authenticate`, then add at least an association with `User` - you do not need the redundant association between `navigate products` and `Authenticated user`, because this association is inherited from `User` (all what a user can do, the authenticated user can do as well) - you should remove the arrows from the associations between actors and use-cases. This old notation is no longer valid (even if you'll find many examples of it on the internet and in books, refers to the UML 2.5.1 specifications in case of doubt). [1]: https://books.google.com/books/about/Use_Case_Modeling.html?id=zvxfXvEcQjUC&redir_esc=y
I have a class `String` and I've made a field `char* name`, default, parameterized, copy constructor, destructor and overwritten `operator =`. My question is how my default constructor should look like for a `char*`. Below is part of my code. I use `char*` because the array should be dynamic: ``` class String { public: char* name; String(){ name = new char[0]; } String(char* str){ name = new char[strlen(str) + 1]; strcpy(name, str); } ```
i want to write a code for a telegram bot, where i can connect and see a "dashboard" and "kpi" sheet on a google sheet, however i keep getting this error; ``` "PS C:\Users\ASUS> & C:/Users/ASUS/AppData/Local/Microsoft/WindowsApps/python3.12.exe c:/Users/ASUS/Downloads/philbot.py Traceback (most recent call last): File "c:\Users\ASUS\Downloads\philbot.py", line 51, in <module> main() File "c:\Users\ASUS\Downloads\philbot.py", line 41, in main updater = Updater(TOKEN) ^^^^^^^^^^^^^^" ``` Below is the code; ``` # CODE start import telegram from telegram import InlineKeyboardMarkup, InlineKeyboardButton from telegram.ext import Updater, CommandHandler, CallbackQueryHandler from google.oauth2 import service_account import gspread # Telegram bot token TOKEN = 'xxxxxyyyyyy' # Google Sheets credentials SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] SERVICE_ACCOUNT_FILE = 'C:/Users/ASUS/Downloads/credentials.json' # Specify the path to your credentials JSON file spreadsheet_id = 'yyyyxxxxxxx' # Authenticate with Google Sheets API creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES) # Function to fetch data from Google Sheets def get_sheet_data(sheet_name): gc = gspread.authorize(creds) sheet = gc.open_by_key(spreadsheet_id) worksheet = sheet.worksheet(sheet_name) return worksheet.get_all_values() # Command handler for starting the bot def start(bot, update): keyboard = [[InlineKeyboardButton("Dashboard", callback_data='dashboard')], [InlineKeyboardButton("KPI", callback_data='kpi')]] reply_markup = InlineKeyboardMarkup(keyboard) update.message.reply_text('Please choose:', reply_markup=reply_markup) # Callback handler for button presses def button(bot, update): query = update.callback_query sheet_name = query.data data = get_sheet_data(sheet_name) message = '\n'.join(['\t'.join(row) for row in data]) query.edit_message_text(text=message) def main(): updater = Updater(TOKEN) dp = updater.dispatcher dp.add_handler(CommandHandler("start", start)) dp.add_handler(CallbackQueryHandler(button)) updater.start_polling() updater.idle() if __name__ == '__main__': main() ``` i was trying to have 2 buttons in my telegram bot, where if pushed connects to the sheets with the same name and show me the table there, however getting an error
I am builing my accordion with ReactJS but cannot find a way to make it auto-collapse when another one is opened. It is working perfectly fine but I just want the item to callapse as soon as another is opened. ``` import React, {useState} from 'react' import { FaMinus, FaPlus } from "react-icons/fa6"; import './accordion.css' const Accordion = ({ title, answer }) => { const [accordionOpen, setAccordionOpen] = useState(false); return ( <div className='accordion-group'> <button onClick={() => setAccordionOpen(!accordionOpen)} className='accordion-toggle'> <h1 className='question' >{title}</h1> {accordionOpen ? <span className="accordion-icon"><FaMinus /> </span> : <span className="accordion-icon"><FaPlus /></span> } </button> <div className={ `accordion-text ${ accordionOpen ? "accordion-show" : "accordion-hidden" }` }> <h4 className="answer">{answer}</h4> </div> </div> ) } export default Accordion ```
@gog mentioned, For the same reason you wrote show() with parentheses and not just show. Thanks @gog
You can define the path of your file manually. ```ts beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [ ConfigModule.forRoot({ envFilePath: ['.env.test'], load: [yourConfig], }), ], }).compile() ``` While `yourConfig` is a typical config file ```ts export default registerAs('yourConfig', () => ({ host: process.env.HOST, })) ```
I have a django project, when I create a user from empty migration files, I can logged in perfectly. But when I create a user from POST method, I can't logged in and it throwing invalid credentials. This is my user model ``` class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField("Username", max_length=50, unique=True) password = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_password_reset = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) deleted_at = models.DateTimeField(null=True, blank=True) roles = models.ManyToManyField(Role, related_name='users') def delete(self, *args, **kwargs): self.deleted_at = timezone.now() self.save() def save(self, *args, **kwargs): # Hash the password before saving self.password = make_password(self.password) super(User, self).save(*args, **kwargs) def __str__(self): roles_str = "\n".join([str(role) for role in self.roles.all()]) return f"(username: {self.username}, id: {self.id}, is_active: {self.is_active}, is_password_reset: {self.is_password_reset}, roles:\n{roles_str})" ``` this is my login API view ``` @api_view(['POST']) @authentication_classes([]) @permission_classes([AllowAny]) def login(request): username = request.data.get('username') password = request.data.get('password') user = authenticate(request, username=username, password=password) if user: serializer = UserSerializer(user, context={'request': request}) refresh = RefreshToken.for_user(user) data = { 'user': serializer.data, 'refresh': str(refresh), 'access': str(refresh.access_token), } return Response(data) else: return Response({'error': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED) ``` I already tried to debug using raw password without hashing and print out the request from login. It prints out exactly the same as in the database. But it keeps throwing invalid credentials. I think the problem is in the authenticate. but don't know exactly how to fix it.
Django Auth Login
|django|django-models|django-rest-framework|django-views|backend|
null
Turns out `bpy.ops.import_scene.obj` was removed at `bpy==4` which is the latest blender-api for python, hence the error. In `bpy>4` you have to use `bpy.ops.wm.obj_import(filepath='')` I just downgraded to `bpy==3.60` to import object directly in the current scene. ``` pip install bpy=3.6.0 ``` I also modified my script to take input of `.obj` files in triangular-mesh and then convert the mesh to quadrilateral, then export as both `stl` and `obj`. Here's my working script: ``` def convert_tris_to_quads(obj_path, export_folder): try: filename = os.path.basename(obj_path).split('.')[0] logging.info(f"Importing {obj_path}") bpy.ops.object.select_all(action='DESELECT') bpy.ops.object.select_by_type(type='MESH') bpy.ops.object.delete() bpy.ops.import_scene.obj(filepath=obj_path) print("current objects in the scene: ", [obj for obj in bpy.context.scene.objects]) for obj in bpy.context.selected_objects: bpy.context.view_layer.objects.active = obj logging.info("Converting mesh") bpy.ops.object.mode_set(mode='EDIT') bpy.ops.mesh.select_all(action='SELECT') bpy.ops.mesh.tris_convert_to_quads() bpy.ops.object.mode_set(mode='OBJECT') # Export to OBJ obj_export_path = export_folder + filename + '_quad.obj' logging.info(f"Exporting OBJ to {obj_export_path}") bpy.ops.export_scene.obj(filepath=obj_export_path, use_selection=True) # Export to STL stl_export_path = export_folder + filename + '_quad.stl' logging.info(f"Exporting STL to {stl_export_path}") bpy.ops.export_mesh.stl(filepath=stl_export_path, use_selection=True) except Exception as e: logging.error(f"Error processing {obj_path}: {e}") return False ``` This still might not be the best approach to this, so do let me know if anyone know any better approach.
How can I make my accordion auto-collapsible
|reactjs|accordion|react-native-collapsible|
null
It's necessary that when searching, complete matches of words/phrases are found and replaced with new ones: - If the value is blank, then delete. - If the value is not blank, then replace it with a word/phrase while maintaining the separator. Original Text: ---- 1: Coconut 2: Coconut,Orange,Coconut,Pear,Coconut 3: Coconut,Coconut 4: Coconut,Coconut,Coconut 5: Coconut,Coconut,Orange 6: Coconut,Coconut,Coconut,Orange 7: Orange,Coconut,Coconut,Pear 8: Orange,Coconut,Coconut,Coconut,Pear 9: Pear,Coconut,Coconut 10: Pear,Coconut,Coconut,Coconut Expected Results: ---- **Nuances:** 1. If there are extra characters before and/or after a word/phrase, this is not a complete match (only commas are ignored). 2. If a word/phrase is repeated sequentially through a delimiter (in this case, a comma), then this sequence is replaced by one word/phrase. It doesn’t matter whether this sequence starts from the very beginning, in the middle or from the end of the text. - Replace with: ` ` - means blank, not space ---------- 1: 2: Orange,Pear 3: 4: 5: Orange 6: Orange 7: Orange,Pear 8: Orange,Pear 9: Pear 10: Pear - Replace with: `Tomato` ---------- 1: Tomato 2: Tomato,Orange,Tomato,Pear,Tomato 3: Tomato 4: Tomato 5: Tomato,Orange 6: Tomato,Orange 7: Orange,Tomato,Pear 8: Orange,Tomato,Pear 9: Pear,Tomato 10: Pear,Tomato My Try (with Results): ---- - **Find what:** `^(Coconut)$|^(Coconut)(,)|(,)(Coconut)(,)|(,)(Coconut)$` 1. **Replace with:** `$4$7$3$6` 1: 2: ,Orange,,Pear, 3: ,Coconut 4: ,Coconut, 5: ,Coconut,Orange 6: ,Coconut,,Orange 7: Orange,,Coconut,Pear 8: Orange,,Coconut,,Pear 9: Pear,,Coconut 10: Pear,,Coconut, 2. **Replace with:** `$4$7Tomato$3$6` 1: Tomato 2: Tomato,Orange,Tomato,Pear,Tomato 3: Tomato,Coconut 4: Tomato,Coconut,Tomato 5: Tomato,Coconut,Orange 6: Tomato,Coconut,Tomato,Orange 7: Orange,Tomato,Coconut,Pear 8: Orange,Tomato,Coconut,Tomato,Pear 9: Pear,Tomato,Coconut 10: Pear,Tomato,Coconut,Tomato
Regular expression to find and replace full matches (consecutive repeats, preserve delimiter)
|regex|
You could create a listener and initialize that in the CardsPage class. ``` # ui_theme.py class ThemeVariantListener: def __init__(self): self.on_change_variant_callback = None def set_variant_change_callback(self, callback): self.on_change_variant_callback = callback def on_change_variant_click(self, dbref, msg, to_ms): print("button clicked:", msg.value) if self.on_change_variant_callback: self.on_change_variant_callback(dbref, msg, to_ms) # cards_page.py import ui_theme class CardsPage: def __init__(self): self.theme_listener = ui_theme.ThemeVariantListener() def on_variant_select(self, dbref, msg, to_ms): # Your logic for variant selection pass def initialize(self): self.theme_listener.set_variant_change_callback(self.on_variant_select) # main.py from cards_page import CardsPage def main(): cards_page = CardsPage() cards_page.initialize() # Now, you can use ui_theme.py and set its variant change callback ui_theme_instance = cards_page.theme_listener # Here, you can pass ui_theme_instance to wherever needed in your application # For example: # some_module.setup_ui_theme(ui_theme_instance) if __name__ == "__main__": main() ```
Is there a way to execute command from array with "for do"?
|arrays|for-loop|lua|
null
$foo = new Foo(); $bar = new Bar(); $array_diff = array_keys( array_diff_key( get_object_vars($foo), get_object_vars($bar) )); `$array_diff` will be an array containing every property of `$foo` that is not found in `$bar`. I'm from my smartphone so I didn't tested it
Can someone assist how to solve this issue (if possible to be solved)? I am using **DevTools** for getting necessary token (in all automation tests). Tests are written in **Java (Selenium 4.16.1)** In order to have them run on pipeline, must be in headless mode and in incognito mode, too. But throws error: **java.awt.AWTException: headless environment** Tried a lot of options in Chrome, but without any success. Chrome browser class looks like this: ``` ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.addArguments("--disable-extensions"); chromeOptions.addArguments("--enable-application-cache"); chromeOptions.addArguments("--allow-running-insecure-content"); chromeOptions.addArguments("--no-sandbox"); chromeOptions.addArguments("--enable-automation"); chromeOptions.addArguments("--ignore-certificate-errors"); chromeOptions.addArguments("--remote-allow-origins=*"); chromeOptions.addArguments("--disable-dev-shm-usage"); chromeOptions.addArguments("--disable-gpu"); chromeOptions.addArguments("--remote-debugging-port=3222"); chromeOptions.addArguments("--disable-infobars"); String incognito = System.getProperty("incognito", "false"); if (incognito.equalsIgnoreCase("true")) { chromeOptions.addArguments("--incognito"); } String pathToDownl = System.getProperty("user.home") + "\\" + Constants. $string("download.location"); HashMap<String, Object> chromePre = new HashMap<String, Object>(); chromePre.put("profile.default_content_settings.popups", 0); chromePre.put("download.prompt_for_download", false); chromePre.put("download.default_directory", pathToDownl); chromePre.put("profile.content_settings.exceptions.automatic_downloads.*.setting", 1); chromePre.put("safebrowsing.enabled", false); chromeOptions.setExperimentalOption("prefs", chromePre); //System.out.println(pathToDownl); if ($boolean("enableProxy")==true){ chromeOptions.setCapability("proxy", setProxy()); } ```
|php|symfony|object|entity|difference|
null
With command: npx amplify generate config --app-id <id> --branch <branch> --format json --out-dir config It correctly generate amplifyconfiguration.json file in config folders with correct IDs in it that correspond to <branch> already deployed stack. But then with command: npx amplify sandbox --config-out-dir ./config --format json It don't care about whatever options I've tried and every time re-generate a complete fresh new stack with a new amplifyconfiguration.json file in project's root folder. This is not what I want. What I'd like is a sandbox that use backend stack from an already deployed branch (with seed data).
# Root cause You got errors during the anaconda installation because the machine does not have internet access, so, it means that you did not pack ALL the dependencies in the file. The dependencies are not limited to the packages you declared in the file environment. # Solution You need to package your project. That is, resolve all the dependencies and put them all together in the same file. I suggest you those steps: ## 1. Create Environment.yml File Create an environment.yml file that lists all the packages and their versions, as you did: ``` name: my_env channels: - conda-forge - defaults dependencies: - bzip2=1.0.8=hcfcfb64_5 # other packages - pip: - attrs==23.1.0 # other packages ``` ## 2. Export Packages to Tarballs On a machine with internet access, use the `conda pack` command to export the specified packages and their dependencies into tarballs: ``` bash conda pack -n my_environment -o my_environment.tar.gz ``` ## 3.Transfer the Tarball to the offline machine Upload the tar file with as you need. ## 4. Create the environment from Tarball ``` conda create --name my_environment --use-local --file my_environment.tar.gz ``` --use-local option tells conda to use locally available packages. In your case, it's used in conjunction with the --file option to indicate that the environment specification is provided in a local tarball file (my_environment.tar.gz). ## 5. Activate the env and test it ``` conda activate my_environment conda list && conda info ``` # Extra Ball I also recommend you the following official resource on conda doc for further deployments of conda environments: https://conda.github.io/conda-pack/
For me, it works by removing these folders and restarting the simulator. Run this command on your terminal: > rm -R ~/Library/Developer/CoreSimulator/Caches > rm -R ~/Library/Developer/Xcode/iOS\ DeviceSupport/ > rm -R ~/Library/Developer/Xcode/DerivedData/
I want to tune a model using a custom class probability metric "pg", which stands for partial gini coefficient. I use it on data that exists of numerical predictors and a binary factor as class label (after preprocessing with the recipe). This is the tuning code: ``` xgb_folds <- train %>% vfold_cv(v=5) xgb_model <- parsnip::boost_tree( mode = "classification", trees = tune(), tree_depth = tune(), learn_rate = tune(), loss_reduction = tune() ) %>% set_engine("xgboost") xgb_wf <- workflow() %>% add_recipe(TREE_recipe) %>% add_model(xgb_model) xgboost_tuned <- tune::tune_grid( object = xgb_wf, resamples = xgb_folds, grid = hyperparameters_XGB_tidy, metrics = metric_set(pg), control = tune::control_grid(verbose = TRUE) ``` The code above worked when I set the metric in tune_grid to roc_auc. When using pg however I get this warning: `Warning message: All models failed. Run `show_notes(.Last.tune.result)` for more information.` The .Last.tune.result contains this error: ``` unique notes: ──────────────────────────────────────────────────────────────────────────────────────────────────── Error in `metric_set()`: ! Failed to compute `pg()`. Caused by error in `UseMethod()`: ! no applicable method for 'pg' applied to an object of class "c('grouped_df', 'tbl_df', 'tbl', 'data.frame')" ``` This is the yardstick implementation for pg I tried: (running pg_vec on class probabilities and label vectors worked as expected) ``` # partialGini for tidymodels library(tidymodels, rlang) pg_impl <- function(truth, estimate, case_weights = NULL) { sorted_indices <- order(estimate, decreasing = TRUE) sorted_probs <- estimate[sorted_indices] sorted_actuals <- truth[sorted_indices] # Select subset with PD < 0.4 subset_indices <- which(sorted_probs < 0.4) subset_probs <- sorted_probs[subset_indices] subset_actuals <- sorted_actuals[subset_indices] # Check if there are both positive and negative cases in the subset if (length(unique(subset_actuals)) > 1) { # Calculate ROC curve for the subset roc_subset <- pROC::roc(subset_actuals, subset_probs, direction = "<", quiet = TRUE) # Calculate AUC for the subset partial_auc <- pROC::auc(roc_subset) # Calculate partial Gini coefficient (2 * partial_auc - 1) } else return(NA) } pg_vec <- function(truth, estimate, estimator = NULL, na_rm = TRUE, case_weights = NULL, ...) { abort_if_class_pred(truth) estimator <- finalize_estimator(truth, estimator) check_prob_metric(truth, estimate, case_weights, estimator) if (na_rm) { result <- yardstick_remove_missing(truth, estimate, case_weights) truth <- result$truth estimate <- result$estimate case_weights <- result$case_weights } else if (yardstick_any_missing(truth, estimate, case_weights)) { return(NA_real_) } pg_impl(truth, estimate, case_weights = case_weights) } pg <- function(data, ...) { UseMethod("pg") } pg <- new_prob_metric(pg, direction = "maximize") pg.data.frame <- function(data, truth, ..., na_rm = TRUE) { prob_metric_summarizer( name = "pg", fn = pg_vec, data = data, truth = !! enquo(truth), ..., na_rm = na_rm) } ```
[enter image description here](https://i.stack.imgur.com/s408v.png) "When I click on this item to enter the webpage, I can't execute the step into operation?" "I hope to be able to execute the step into operation in PyCharm when opening the webpage."
Breakpoint cannot be stepped into
|breakpoints|
null
Could you, please, explain me if I still need to do train_test split if I use cross validation technique? If I do, should I use cross-validation only on the train set? What is the best practice regarding cross validation and train_test_split? ```python from sklearn.linear_model import ElasticNet from sklearn.pipeline import make_pipeline from sklearn.compose import ColumnTransformer from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn.model_selection import cross_validate numeric_features = X.select_dtypes(include=['int', 'float']).columns categorical_features = X.select_dtypes(include=['object', 'category']).columns preprocessor = ColumnTransformer( transformers=[ ('num', StandardScaler(), numeric_features), ('cat', OneHotEncoder(handle_unknown='ignore'), categorical_features) ] ) en = ElasticNet(alpha=0.1, l1_ratio = 0.3, n_jobs = -1) model = make_pipeline(preprocessor, en) cv_results = cross_validate(model, X, y, cv=10, scoring='neg_mean_absolute_error', return_estimator=True) scores = - cv_results['test_score'] print(f'The mean mse of the model is {scores.mean(): .2f} +/- {scores.std(): .2f}') ``` Here I used cross_validate on the whole dataset and didn't test the model on the unseen data from the train_test_split. Can the result of scores.mean() be considered reliable in this case? Or the best practice would be to use train_test_split first, **do cross validation only on the train set**, and check the model on the test set? Thanks in advance and have a great day!
Cross validation and/or train_test_split in scikit-learn?
|scikit-learn|cross-validation|evaluation|train-test-split|
null
If changing port number doesn't solve your problem, follow steps and this solves problem: (** By these steps don't need to reinstall Xampp or loss your database**) 1) Stop all Xampp services and exit application. 2) Move to c:\xampp\mysql 3) Rename data folder to data_old 4) create new data folder and copy whole content of backup folder to the data folder except "ibdata1" [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/B7iMW.png 5) Select all files in data_old folder and paste into data folder (***Note*** Don't replace copied files and skip replace theme).
the problem is that you initialize the value inside the build method, which is called every time the widget is rendered, as with setState. Just change to this double currentSliderValue = 100.0; @override Widget build(BuildContext context) {
ERROR: Permission to gitTest.git denied to deploy key fatal: Could not read from remote repository
[Reference 1][1] **Problem :-** Look below. ```python application = ProtocolTypeRouter({ "websocket": URLRouter([ path("ws/notifications/", consumers.NotificationConsumer.as_asgi()), ]), }) ``` It's `notifications`. And ```javascript const ws = new WebSocket('ws://localhost:8000/ws/notification/'); ``` It's `notification`. ***Path should be same path.*** Use as below. **Answer :-** ```python application = ProtocolTypeRouter({ "websocket": URLRouter([ path("ws/notifications/", consumers.NotificationConsumer.as_asgi()), ]), }) ``` And ```javascript const ws = new WebSocket('ws://localhost:8000/ws/notifications/'); ``` ___ [Reference 2][2] **Info :-** 1) If you have configured django-channels your console output opon `python manage.py runserver` should be something like below. ``` Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. August 19, 2022 - 10:20:28 Django version 4.1, using settings 'mysite.settings' Starting ASGI/Daphne version 3.0.2 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. ``` Look for `Starting ASGI/Daphne version x.x.x`. 2) Daphne is required in development server. [Look here][2] [1]: https://channels.readthedocs.io/en/latest/index.html [2]: https://channels.readthedocs.io/en/latest/tutorial/part_1.html#integrate-the-channels-library 3) As I understand, you need to reconnect on error. App should be trying to connect always, if not connected already. Like this. ``` Function channels_connect(){ On_Connect{ Messages } On_error{ //reconnect here channels_connect(); } } ```
Not able to generate a user_Access_Token by using api server . Able to generate a app_token but not able to access user details with this token I need a request api to create a user_Access _Token for fb developers app. Help.....
FB Developer app , need to create a user_access_token by using server api
|javascript|node.js|nestjs|backend|react-fullstack|
null
{"Voters":[{"Id":11638718,"DisplayName":"εΊ·ζ‘“η‘‹"}]}
I am implementing application in flutter. Recently, i upgraded my flutter to 3.19.4 and i am facing lots of bug. like i am unable to open the keypad in my app. On other Android versions, it was working fine, but on Android 12, its not working. It is working only when I select the keypad icon on the bottom and change it to Google Voice Typing from Gboard. I tried to add hardwareaccelerated=true in my manifest, but still its not working. here is [![enter image description here][1]][1] what can i do please any one know about anything please help me. [1]: https://i.stack.imgur.com/trAW9.png
I have hundreds of different *.rego files, each with different rules. Every single rule needs to check for user-role and method from the input. So I decided to create a `functions.rego` with the following content package abc.functions method_and_role_valid(in, meth, role) { in.method == meth in.current_user_roles[_] == role } The other documents can then import this function without having to redefine it again and again, e.g. package opa.abc.institutions.view import data.abc.functions default allow = false allow { functions.method_and_role_valid(input, "view", "administrator") } This work. However, I need to write tests for each of the rules. After reading the opa guidelines on testing, especially mocking functions and data, I tried to do the follwing package opa.abc.institutions.view test_allow_1 { allow with input as {"method": "view", "current_user_roles": ["authenticated"]} with data.abc.functions.method_and_role_valid as true } test_deny_2 { not allow with input as {"method": "view", "current_user_roles": ["authenticated"]} with data.abc.functions.method_and_role_valid as false } This creates the error `rego_type_error: undefined function data.abc.functions.method_and_role_valid` The documentation shows mocking examples for built-in functions (also replacing a function with a single boolean value), is there really no way to mock "custom" functions defined in virtual documents as I did? **Update** Thanks to @[devoops][1] I forgot to load the functions.rego when testing. Didn't know this needs to be done explicitly. ./opa test -v test1_test.rego test1.rego functions.rego [1]: https://stackoverflow.com/users/11849243/devoops
Error when using a custom probability metric in tidymodels
|r|tidymodels|yardstick|
null