instruction
stringlengths
0
30k
`rand()` generates a random integer. The range of this random integer depends on the implementation of the `rand()` function in your programming environment. Usually, it generates a random number between 0 and a large maximum value (such as `RAND_MAX` in C/C++). (a + 1) is added as the right operand of the modulus operator. This means that the random number generated by `rand()` will be divided by (a + 1). The modulus operation `%` returns the remainder of dividing the random number by (a + 1). I guess this part is most significant for answering your question. **Since the divisor is (a + 1), the possible remainders will be between 0 and a inclusive** since possible remainders when dividing some number N are all numbers between 0 and (N - 1) including both boundaries. For example, let's say a = 5. If the random number generated by `rand()` is 12, then (12 % 6) would be 0, because 12 is evenly divisible by 6. If the random number is 15, then (15 % 6) would be 3, because 15 divided by 6 gives a quotient of 2 with a remainder of 3. Thus, the result stored in num will always be a number between 0 and a.
Here is a way: ```r library(shiny) library(DT) library(htmltools) dat <- iris js <- c( "function(){", " var $th = $(this.api().table().header()).find('tr:eq(1)').find('td:first');", " var column = this.api().column(0);", " var select = $('<select multiple=\"multiple\"><option value=\"\"></option></select>')", " .appendTo( $th.empty() )", " .on('change', function(){", " var vals = $('option:selected', this).map(function(index,element){", " return $.fn.dataTable.util.escapeRegex($(element).val());", " }).toArray().join('|');", " column.search(vals.length > 0 ? '^('+vals+')$' : '', true, false).draw();", " });", " var data = column.data();", " data.each(function(d, j){", " select.append('<option value=\"'+d+'\">'+d+'</option>');", " });", " select.select2({width: '100px', closeOnSelect: false});", "}") ui <- fluidPage( tags$head( tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css"), tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js") ), br(), DTOutput("dtable") ) server <- function(input, output, session){ output[["dtable"]] <- renderDT({ datatable( dat, #container=sketch, filter = "top", options = list( orderCellsTop = TRUE, initComplete = JS(js), columnDefs = list( list(targets = "_all", className = "dt-center") ) ) ) }, server = FALSE) } shinyApp(ui, server) ```
null
Pytest runs all files of the form `test_*.py` or `*_test.py` in the current directory and its subdirectories. More generally, it follows standard test [discovery rules][1]. [1]: https://docs.pytest.org/en/7.1.x/explanation/goodpractices.html#test-discovery
{"OriginalQuestionIds":[6355787],"Voters":[{"Id":4108803,"DisplayName":"blackgreen"}]}
I would like to understand if it is possible to parallelize the following nested loop (using OpenMP in Fortran). To give some background information, I am doing this to initialize a sparse matrix. It turns out that the matrix-vector multiplication is very fast, thanks to the sparse BLAS library. The bottleneck in the code is however the loops that I do to create the COO representation of the matrix (row index, col index and nonzero values). So the question is whether it is possible to parallelize this (perhaps using a reduction clause): nnz = N*N allocate(row_ind(nnz),col_ind(nnz),values(nnz),stat=istat) if (istat/=0) then error stop "Allocation of row_ind,col_ind,values failed" endif counter = 1 do iz = 1,n_z do ia = 1,n_a ix = (iz-1)*n_a+ia opt_ind = pol_ap_ind(ia,iz) do izp = 1,n_z if (Pi(iz,izp)/=0.0d0) then ixp = (izp-1)*n_a+opt_ind values(counter) = Pi(iz,izp) row_ind(counter) = ix col_ind(counter) = ixp counter = counter+1 endif enddo enddo enddo nnz = counter -1 row_ind = row_ind(1:nnz) col_ind = col_ind(1:nnz) values = values(1:nnz)
I have a set of constraints: Lane(l0) == True, Lane(l1) == True, OnComingLane(l1) == True, LaneMarking(m1) == True, LaneMarking(m0) == True, SolidWhiteLine(m1) == True, SolidWhiteLine(m0) == True, leftConnectedTo(l0, m0) == True, Driver(v0) == True, Vehicle(v1) == True, block(v1, l0) == True, inFrontOf(v1, v0) == True, Inoperative(v1) == True, NotHasOncomingVehicle(l1, v1) == True, EgoLane(l0) == True and: ``` Implies( And(inFrontOf(X, D), Vehicle(X), OnComingLane(Z), SolidWhiteLine(Y), leftConnectedTo(G, Y), Driver(D), block(X, G), Inoperative(X), NotHasOncomingVehicle(D, Z), EgoLane(G)), And(Overtake(X), Cross(Y), LaneChangeTo(Z))) ``` and want to deduce which actions are satisfied: `{Overtake, Cross, LaneChangeTo}`. How can I utilize the z3 Theorem for finding the only solution, i.e. `Overtake(v1)`, `Cross(m0)` and `LaneChangeTo(l1)`?
This should probably be considered an implementation detail of the `json` package, and also it might be a Python version thing. In any case, it becomes crucial with your implementation: - The `dump()` function internally calls the `iterencode()` method on your encoder (see lines 169 and 176 [in the actual source code][1]. - Yet, the `dumps()` function internally calls `encode()` (see lines 231 and 238). You can verify this by adjusting `encode()` and overriding `iterencode()` in your `JSONSerializer` like so: ```python class JSONSerializer(json.JSONEncoder): def encode(self, obj): print("encode called") ... # Your previous code here return super().encode(obj) def iterencode(self, *args, **kwargs): print("iterencode called") return super().iterencode(*args, **kwargs) ``` … and you will see that only "iterencode called" will be printed with your test code, but not "encode called". The other Stack Overflow question that you linked in your question seems to have the same issue by the way, at least when using a rather recent version of Python (I am currently on 3.11 for writing this) – see my [comment][2] to the corresponding answer. I have two solutions: 1. *Either* use `dumps()` in your `Agent.memorize()` method, e.g. like so: ```python def memorize(self): with open("memory.json", "w") as w: w.write(json.dumps(self.G, cls=JSONSerializer)) ``` 2. *Or* move your own implementation from `encode()` to `iterencode()`, e.g. like so: ```python class JSONSerializer(json.JSONEncoder): def iterencode(self, obj, *args, **kwargs): if isinstance(obj, MutableMapping): for key in list(obj.keys()): if isinstance(key, tuple): strkey = "%d:%d" % key obj[strkey] = obj.pop(key) yield from super().iterencode(obj, *args, **kwargs) ``` This 2nd solution seems to have the benefit that it works with both `dump()` and `dumps()` (see note below). A note for completion: The `dumps()` function later seems to result in a call of `iterencode()`, as well (I did not track the source code so far as to see where exactly that happens, but from the printouts that I added it definitely happens). This has the following effects: (1) In the 1st proposed solution, as `encode()` is called first and we can make all adjustments for making our data JSON-serializable there, at this later point, calling `iterencode()` will not result in an error, any more. (2) In the 2nd proposed solution, as we reimplemented `iterencode()`, our data will be made JSON-serializable at this point. **Update**: There is actually a third solution, thanks to the comment of @AbdulAzizBarkat: we can override the [`default()`][3] method. However, we have to make sure that we hand over an object type for serialization that is not handled by the regular encoder, or otherwise we will never reach the `default()` method with it. In the given code, we can for example pass the `Agent` instance itself to `dump()` or `dumps()`, rather than its dictionary field `G`. So we have to make two adjustments: 1. Adjust `memorize()` to pass `self`, rather than `self.G`, e.g. like so: ```python def memorize(self): with open("memory.json", "w") as w: json.dump(self, w, cls=JSONSerializer) ``` 2. Adjust `JSONSerializer.default()` to handle the `Agent` instance, e.g. like so (we won't need `encode()` and `iterencode()`, any more): ```python class JSONSerializer(json.JSONEncoder): def default(self, obj): if isinstance(obj, Agent): obj = obj.G for key in list(obj.keys()): if isinstance(key, tuple): strkey = "%d:%d" % key obj[strkey] = obj.pop(key) return obj # Return the adjusted dictionary return super().default(obj) ``` Final side note: In all current solutions, the keys of the original dictionary are altered. You probably don't want to have this as actually your instance should not change just because you dump a copy of it. So you might rather want to create a new dictionary with the altered keys and original values. [1]: https://github.com/python/cpython/blob/6c8ac8a32fd6de1960526561c44bc5603fab0f3e/Lib/json/__init__.py#L169 [2]: https://stackoverflow.com/questions/72931719/json-serializer-class-why-json-dumps-works-while-json-dump-does-not/72932299#comment137929561_72932299 [3]: https://docs.python.org/3/library/json.html#json.JSONEncoder.default
When testing the composite function using Vitest, I get the error [enter image description here](https://i.stack.imgur.com/AQmKa.png) in the function I simply declare const redirectTo = useRouteQuery("redirectTo"); I would like to solve the problem with useRouteQuery
# When the project had one data source, native queries ran fine, now when there are two data sources, hibernation cannot determine the schema for receiving native queries, non-native queries work fine. **application.yaml** ``` spring: autoconfigure: exclude: org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration flyway: test: testLocations: classpath:/db_test/migration,classpath:/db_test/migration_test testSchemas: ems_core locations: classpath:/db_ems/migration baselineOnMigrate: true schemas: my_schema jpa: packages-to-scan: example.example1.example2.example3.example4 show-sql: false properties: hibernate.dialect: org.hibernate.dialect.PostgreSQL10Dialect hibernate.format_sql: false hibernate.jdbc.batch_size: 50 hibernate.order_inserts: true hibernate.order_updates: true hibernate.generate_statistics: false hibernate.prepare_connection: false hibernate.default_schema: my_schema org.hibernate.envers: audit_table_prefix: log_ audit_table_suffix: hibernate.javax.cache.uri: classpath:/ehcache.xml hibernate.cache: use_second_level_cache: true region.factory_class: org.hibernate.cache.ehcache.internal.SingletonEhcacheRegionFactory hibernate: connection: provider_disables_autocommit: true handling_mode: DELAYED_ACQUISITION_AND_RELEASE_AFTER_TRANSACTION hibernate.ddl-auto: validate # todo: open-in-view: false database-platform: org.hibernate.dialect.H2Dialect #database connections read-only: datasource: url: jdbc:postgresql://localhost:6432/ems username: postgres password: postgres configuration: pool-name: read-only-pool read-only: true auto-commit: false schema: my_schema read-write: datasource: url: jdbc:postgresql://localhost:6433/ems username: postgres password: postgres configuration: pool-name: read-write-pool auto-commit: false schema: my_schema ``` **Datasources config:** ``` @Configuration public class DataSourceConfig { @Bean @ConfigurationProperties("spring.read-write.datasource") public DataSourceProperties readWriteDataSourceProperties() { return new DataSourceProperties(); } @Bean @ConfigurationProperties("spring.read-only.datasource") public DataSourceProperties readOnlyDataSourceProperties() { return new DataSourceProperties(); } @Bean @ConfigurationProperties("spring.read-only.datasource.configuration") public DataSource readOnlyDataSource(DataSourceProperties readOnlyDataSourceProperties) { return readOnlyDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build(); } @Bean @ConfigurationProperties("spring.read-write.datasource.configuration") public DataSource readWriteDataSource(DataSourceProperties readWriteDataSourceProperties) { return readWriteDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build(); } @Bean @Primary public RoutingDataSource routingDataSource(DataSource readWriteDataSource, DataSource readOnlyDataSource) { RoutingDataSource routingDataSource = new RoutingDataSource(); Map<Object, Object> dataSourceMap = new HashMap<>(); dataSourceMap.put(DataSourceType.READ_WRITE, readWriteDataSource); dataSourceMap.put(DataSourceType.READ_ONLY, readOnlyDataSource); routingDataSource.setTargetDataSources(dataSourceMap); routingDataSource.setDefaultTargetDataSource(readWriteDataSource); return routingDataSource; } @Bean public BeanPostProcessor dialectProcessor() { return new BeanPostProcessor() { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof HibernateJpaVendorAdapter) { ((HibernateJpaVendorAdapter) bean).getJpaDialect().setPrepareConnection(false); } return bean; } }; } } ``` **Routing data sources** ``` public class RoutingDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceTypeContextHolder.getTransactionType(); } @Override public void setTargetDataSources(Map<Object, Object> targetDataSources) { super.setTargetDataSources(targetDataSources); afterPropertiesSet(); } } ``` **depending on the type of transaction readOnly or not, the datasource is selected** ``` public class DataSourceTypeContextHolder { private static final ThreadLocal<DataSourceType> contextHolder = new ThreadLocal<>(); public static void setTransactionType(DataSourceType dataSource) { contextHolder.set(dataSource); } public static DataSourceType getTransactionType() { return contextHolder.get(); } public static void clearTransactionType() { contextHolder.remove(); } } ``` ``` @Aspect @Component @Slf4j public class TransactionAspect { @Before("@annotation(transactional) && execution(* *(..))") public void setTransactionType(Transactional transactional) { if (transactional.readOnly()) { DataSourceTypeContextHolder.setTransactionType(DataSourceType.READ_ONLY); } else { DataSourceTypeContextHolder.setTransactionType(DataSourceType.READ_WRITE); } } @AfterReturning("@annotation(transactional) && execution(* *(..))") public void clearTransactionType(Transactional transactional) { DataSourceTypeContextHolder.clearTransactionType(); } } ``` **Error** ``` org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [UPDATE my_table SET lock_until = timezone('utc', CURRENT_TIMESTAMP) + cast(? as interval), locked_at = timezone('utc', CURRENT_TIMESTAMP), locked_by = ? WHERE my_table.name = ? AND my_table.lock_until <= timezone('utc', CURRENT_TIMESTAMP)]; nested exception is org.postgresql.util.PSQLException: ERROR: relation "shedlock" does not exist Позиция: 8 at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:235) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72) at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1443) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:862) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:883) at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.update(NamedParameterJdbcTemplate.java:321) at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.update(NamedParameterJdbcTemplate.java:326) at net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateStorageAccessor.lambda$execute$0(JdbcTemplateStorageAccessor.java:115) at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140) at net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateStorageAccessor.execute(JdbcTemplateStorageAccessor.java:115) at net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateStorageAccessor.updateRecord(JdbcTemplateStorageAccessor.java:81) at net.javacrumbs.shedlock.support.StorageBasedLockProvider.doLock(StorageBasedLockProvider.java:91) at net.javacrumbs.shedlock.support.StorageBasedLockProvider.lock(StorageBasedLockProvider.java:65) at jdk.internal.reflect.GeneratedMethodAccessor328.invoke(Unknown Source) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:205) at com.sun.proxy.$Proxy139.lock(Unknown Source) at net.javacrumbs.shedlock.core.DefaultLockingTaskExecutor.executeWithLock(DefaultLockingTaskExecutor.java:63) at net.javacrumbs.shedlock.spring.aop.MethodProxyScheduledLockAdvisor$LockingInterceptor.invoke(MethodProxyScheduledLockAdvisor.java:86) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689) at ru.russianpost.ems.core.assembly.service.impl.scheduler.RpoContentSheduler$$EnhancerBySpringCGLIB$$631d68e1.loadData(<generated>) at jdk.internal.reflect.GeneratedMethodAccessor320.invoke(Unknown Source) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:834) Caused by: org.postgresql.util.PSQLException: ERROR: relation "my_table" does not exist ``` when I change the native query and specify the schema before the table name, the query processes normally : UPDATE my_schema.my_table SET lock_until = timezone('utc', CURRENT_TIMESTAMP) + cast(? as interval), locked_at = timezone('utc', CURRENT_TIMESTAMP), locked_by = ? WHERE my_schema.my_table.name = ? AND my_schema.my_table.lock_until <= timezone('utc', CURRENT_TIMESTAMP);
Problem with native queries when there are two data sources in the project
|java|spring|postgresql|spring-boot|hibernate|
null
@Vaseltior's solution is good and worked for me. A slight change to not have to wrap the non-preview path, just put this at the top. ``` if [ $ENABLE_PREVIEWS == "YES" ] then echo "Skipping the script because of preview mode" exit 0 fi ```
Interesting, I tried the following snippet and Stata 17 behaviour is the same as expected: ```stata sysuse auto browse mpg turn make length price if length>10 & rep78 == 2 ``` This opens the editor with the varlist as specified in the command, not as ordered in the original dataset. It would be helpful if you can check that the same behaviour persists when using the small snippet above.
The solution for the code is provided below: import pandas as pd df1 = pd.DataFrame({'user_id':['A','A','A', 'B','B','B', 'D','D','D', 'E','E'], 'Category':['ABC','ABC','ABC','ABC','ABC','ABC','XYZ','XYZ','XYZ','XYZ','XYZ'], 'counts':[3,3,3,2,2,1,2,1,2,2,2]}) def g(df1): df1["Overall_average__Unique_Counts"] = df1.groupby('user_id')['counts'].transform('mean') df1["Categorywise_average_Unique_counts"] = df1.groupby(['user_id', 'Category'])['counts'].transform('mean') return df1 df2 = g(df1.copy()) print(df2) Output of the above code : [output][1] [1]: https://i.stack.imgur.com/H3A3p.png
# When the project had one data source, native queries ran fine, now when there are two data sources, hibernation cannot determine the schema for receiving native queries, non-native queries work fine. **application.yaml** ``` spring: autoconfigure: exclude: org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration flyway: test: testLocations: classpath:/db_test/migration,classpath:/db_test/migration_test testSchemas: ems_core locations: classpath:/db_ems/migration baselineOnMigrate: true schemas: my_schema jpa: packages-to-scan: example.example1.example2.example3.example4 show-sql: false properties: hibernate.dialect: org.hibernate.dialect.PostgreSQL10Dialect hibernate.format_sql: false hibernate.jdbc.batch_size: 50 hibernate.order_inserts: true hibernate.order_updates: true hibernate.generate_statistics: false hibernate.prepare_connection: false hibernate.default_schema: my_schema org.hibernate.envers: audit_table_prefix: log_ audit_table_suffix: hibernate.javax.cache.uri: classpath:/ehcache.xml hibernate.cache: use_second_level_cache: true region.factory_class: org.hibernate.cache.ehcache.internal.SingletonEhcacheRegionFactory hibernate: connection: provider_disables_autocommit: true handling_mode: DELAYED_ACQUISITION_AND_RELEASE_AFTER_TRANSACTION hibernate.ddl-auto: validate # todo: open-in-view: false database-platform: org.hibernate.dialect.H2Dialect #database connections read-only: datasource: url: jdbc:postgresql://localhost:6432/db username: postgres password: postgres configuration: pool-name: read-only-pool read-only: true auto-commit: false schema: my_schema read-write: datasource: url: jdbc:postgresql://localhost:6433/db username: postgres password: postgres configuration: pool-name: read-write-pool auto-commit: false schema: my_schema ``` **Datasources config:** ``` @Configuration public class DataSourceConfig { @Bean @ConfigurationProperties("spring.read-write.datasource") public DataSourceProperties readWriteDataSourceProperties() { return new DataSourceProperties(); } @Bean @ConfigurationProperties("spring.read-only.datasource") public DataSourceProperties readOnlyDataSourceProperties() { return new DataSourceProperties(); } @Bean @ConfigurationProperties("spring.read-only.datasource.configuration") public DataSource readOnlyDataSource(DataSourceProperties readOnlyDataSourceProperties) { return readOnlyDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build(); } @Bean @ConfigurationProperties("spring.read-write.datasource.configuration") public DataSource readWriteDataSource(DataSourceProperties readWriteDataSourceProperties) { return readWriteDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build(); } @Bean @Primary public RoutingDataSource routingDataSource(DataSource readWriteDataSource, DataSource readOnlyDataSource) { RoutingDataSource routingDataSource = new RoutingDataSource(); Map<Object, Object> dataSourceMap = new HashMap<>(); dataSourceMap.put(DataSourceType.READ_WRITE, readWriteDataSource); dataSourceMap.put(DataSourceType.READ_ONLY, readOnlyDataSource); routingDataSource.setTargetDataSources(dataSourceMap); routingDataSource.setDefaultTargetDataSource(readWriteDataSource); return routingDataSource; } @Bean public BeanPostProcessor dialectProcessor() { return new BeanPostProcessor() { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof HibernateJpaVendorAdapter) { ((HibernateJpaVendorAdapter) bean).getJpaDialect().setPrepareConnection(false); } return bean; } }; } } ``` **Routing data sources** ``` public class RoutingDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceTypeContextHolder.getTransactionType(); } @Override public void setTargetDataSources(Map<Object, Object> targetDataSources) { super.setTargetDataSources(targetDataSources); afterPropertiesSet(); } } ``` **depending on the type of transaction readOnly or not, the datasource is selected** ``` public class DataSourceTypeContextHolder { private static final ThreadLocal<DataSourceType> contextHolder = new ThreadLocal<>(); public static void setTransactionType(DataSourceType dataSource) { contextHolder.set(dataSource); } public static DataSourceType getTransactionType() { return contextHolder.get(); } public static void clearTransactionType() { contextHolder.remove(); } } ``` ``` @Aspect @Component @Slf4j public class TransactionAspect { @Before("@annotation(transactional) && execution(* *(..))") public void setTransactionType(Transactional transactional) { if (transactional.readOnly()) { DataSourceTypeContextHolder.setTransactionType(DataSourceType.READ_ONLY); } else { DataSourceTypeContextHolder.setTransactionType(DataSourceType.READ_WRITE); } } @AfterReturning("@annotation(transactional) && execution(* *(..))") public void clearTransactionType(Transactional transactional) { DataSourceTypeContextHolder.clearTransactionType(); } } ``` **Error** ``` org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [UPDATE my_table SET lock_until = timezone('utc', CURRENT_TIMESTAMP) + cast(? as interval), locked_at = timezone('utc', CURRENT_TIMESTAMP), locked_by = ? WHERE my_table.name = ? AND my_table.lock_until <= timezone('utc', CURRENT_TIMESTAMP)]; nested exception is org.postgresql.util.PSQLException: ERROR: relation "shedlock" does not exist Позиция: 8 at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:235) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72) at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1443) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:862) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:883) at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.update(NamedParameterJdbcTemplate.java:321) at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.update(NamedParameterJdbcTemplate.java:326) at net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateStorageAccessor.lambda$execute$0(JdbcTemplateStorageAccessor.java:115) at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140) at net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateStorageAccessor.execute(JdbcTemplateStorageAccessor.java:115) at net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateStorageAccessor.updateRecord(JdbcTemplateStorageAccessor.java:81) at net.javacrumbs.shedlock.support.StorageBasedLockProvider.doLock(StorageBasedLockProvider.java:91) at net.javacrumbs.shedlock.support.StorageBasedLockProvider.lock(StorageBasedLockProvider.java:65) at jdk.internal.reflect.GeneratedMethodAccessor328.invoke(Unknown Source) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:205) at com.sun.proxy.$Proxy139.lock(Unknown Source) at net.javacrumbs.shedlock.core.DefaultLockingTaskExecutor.executeWithLock(DefaultLockingTaskExecutor.java:63) at net.javacrumbs.shedlock.spring.aop.MethodProxyScheduledLockAdvisor$LockingInterceptor.invoke(MethodProxyScheduledLockAdvisor.java:86) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689) at ru.russianpost.ems.core.assembly.service.impl.scheduler.RpoContentSheduler$$EnhancerBySpringCGLIB$$631d68e1.loadData(<generated>) at jdk.internal.reflect.GeneratedMethodAccessor320.invoke(Unknown Source) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:834) Caused by: org.postgresql.util.PSQLException: ERROR: relation "my_table" does not exist ``` when I change the native query and specify the schema before the table name, the query processes normally : UPDATE my_schema.my_table SET lock_until = timezone('utc', CURRENT_TIMESTAMP) + cast(? as interval), locked_at = timezone('utc', CURRENT_TIMESTAMP), locked_by = ? WHERE my_schema.my_table.name = ? AND my_schema.my_table.lock_until <= timezone('utc', CURRENT_TIMESTAMP);
Running the following code: ``` #!/usr/bin/env perl use 5.038; use Test2::Mock; use Time::HiRes; my($mock) = Test2::Mock->new( class => 'Time::HiRes', override => [ gettimeofday => sub { return 1; }, ] ); my($foo) = Time::HiRes::gettimeofday; say $foo; ``` results in this output: ``` Prototype mismatch: sub Time::HiRes::gettimeofday () vs none at /opt/perl/lib/site_perl/5.38.0/Test2/Mock.pm line 434. 1 Prototype mismatch: sub Time::HiRes::gettimeofday: none vs () at /opt/perl/lib/site_perl/5.38.0/Test2/Mock.pm line 452. ``` I don't know how to get rid of the prototype mismatch warnings. I've tried a number of things with no effect (some of them out of desperation, not because I thought they would work): - adding a prototype to the anon sub ``` gettimeofday => sub () { return 1; }, ``` - defined a named sub with a prototype in a `BEGIN` block & used it instead ``` BEGIN { sub gtod () { return 1; } } my($mock) = Test2::Mock->new( class => 'Time::HiRes', override => [ gettimeofday => \&gtod, ] ); ``` - using `Time::Hires` before `Test2::Mock` - imported `gettimeofday` into `main` and overrode that, in combination with all of the above, e.g.: ``` use Test2::Mock; use Time::HiRes qw(gettimeofday); my($mock) = Test2::Mock->new( class => 'main', override => [ gettimeofday => sub () { return 1; }, ] ); my($foo) = gettimeofday; say $foo; ``` - wrapped it in a `no warnings 'prototype'` block ``` { no warnings 'prototype'; my($mock) = Test2::Mock->new( class => 'main', override => [ gettimeofday => sub () { return 1; }, ] ); } ``` Nothing made any difference. My code works, but there's a warning for a reason, and I'd really like to deal with it in the proper manner. The best I've come up with Googling for an answer is to suppress the message by modifying `$SIG{__WARN__}`, which just seems like a bad idea, if there are other options. Note: I am aware of [`Test::Mock::Time`][1], [`Test::MockTime`][2], and [`Test::MockTime::HiRes`][3] -- they don't do what I need them to do, so I thought I'd roll my own. Also, I've looked at [`Sub::Prototype`][4] but haven't tried it, yet, as it's not a core module and I'd rather not go there unless there's no other choice (at which point I may modify `$SIG{__WARN__}` instead. [1]: https://metacpan.org/pod/Test::Mock::Time [2]: https://metacpan.org/pod/Test::MockTime [3]: https://metacpan.org/pod/Test::MockTime::HiRes [4]: https://metacpan.org/pod/Sub::Prototype
I have a list of elements. Each of them has a button. When you click on it, the description assigned to each element expands. Each element has a separate description. Currently, when I click on the description, regardless of the element, it shows me the same description. ``` export class myComponent { elements: MyArray[] = []; isDisplay: boolean[] = []; showDesc(index: number) { this.isDisplay[index] = !this.isDisplay[index] } } ``` ``` <div *ngFor="let element of elements; let i = index"> <div> <span>{{ element.range }}</span> <button (click)="showDesc(i)">Show element description</button> <p *ngIf="isDisplay[i]">{{ description }}</p> </div> <div> <span *ngIf="elements.length > 1" <button (click)="loadElements()">load more elements</button> </span> </div> ``` When I console.log my showDesc method I got: In the first case when I opened the description: [true], when close [false] In the second case In the second case: when I opened the description: [false, true] or when the first case shows only true - true. It means that the second value is adds what was clicked in 1 option
Goto: 1. Tool->SDK Manager and Apply SDK command line toolkit. [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/8rhog.png
If it is the initial value, then referencing its historical value will return `NaN`. You can use `fixnan()` to replace `NaN` values with previous nearest non-NaN value, or `nz()` to replace `NaN` values with zeros (or given value) in a series. Here is a demonstration: //@version=5 indicator("My script", overlay=true) src_1 = close[1] src_2 = fixnan(close[1]) src_3 = nz(close[1]) plot(src_1, "src_1", color=color.green) plot(src_2, "src_2", color=color.yellow) plot(src_3, "src_3", color=color.red) [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/sZQbb.png
Hello I am trying to do the background action in react native. I already tested a lot of libreries and no one is not working. Now I am trying to do background task using the Headless JS. I am using React-Native-CLI ``` javascript import React from 'react'; import {AppRegistry, Button} from 'react-native'; import { View } from 'react-native'; const bgTask = () => { console.log('Working in background!') } const regBG = () => { console.log('Pressed') AppRegistry.registerHeadlessTask('Task', () => bgTask()); } function App(){ return ( <View> <Button title="Press" onPress={() => regBG()} /> </View> ); } export default App; ``` After the push on 'Press' button console showing the log message 'Pressed' and it's all. [console img](https://i.stack.imgur.com/NkSQc.png) Handless JS, React Native Background Task, React Native Background Action.
Headless JS is not working in React Native
|react-native|
null
I have version 1.7.8.11 and I cannot select carriers in the payment preferences, they appear with a double dash instead of the checkbox. [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/LT2ym.png I have uninstalled the carriers several times and reinstalled them but there is no way. I also don't see the difference between 31, which has the visible checkboxes, and the others. What is the reason why the checkboxes do not appear?
You can even crawl it. Chrome also get `410` error code: [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/L96ys.png Continue your stuff like if it was `200` code. -- Edit -- Look at this code it works well for your page : ``` $context = stream_context_create(array( 'http' => array('ignore_errors' => true), )); $result = file_get_contents('https://waset.org/conferences-in-february-2020-in-london', false, $context); var_dump($result); // output <!DOCTYPE html> <html lang="en" dir="ltr" id="desktop"> <head> <!--Google Tag Manager -->... ``` We only choose to ignore errors, like our browser do automatically.
I'm trying to create this program and only developed a partial of the code and need help with the rest. PROGRAM 6: Crazy 8s Game Write a program that reads a set of three different numbers. Then by subtracting off tens, determine if any of the values ends in an eight. Continue looping as long as one of the numbers in the set ends in eight. Three sets with a value ending in eight wins the game. This is what I have so far. Any suggestions or help? to complete the code? basic hla structure no only use cmp jmp for loops program CrazyGame; #include( "stdlib.hhf" ); [[enter image description here](https://i.stack.imgur.com/X0sA8.png)](https://i.stack.imgur.com/X03X5.png)
Program 6 Crazy 8 Game
|assembly|hla|
null
SwiftUI is smart enough to know which parts of the view need to be redrawn when observed data changes. So assigning an updated version of a `Post` object to the same index in the `posts` array, will only cause the views that depend on the changed data to be rerendered. ``` class PostManager: ObservableObject { @Published var posts = [Post]() // ... func update(with newPost: Post) { if let postIndex = posts.firstIndex(where: {$0.id == newPost.id}) { posts[postIndex] = newPost } } } ``` If the `newPost` contains only an updated message, views that display that message will rerender. If `newPost` is an exact copy of the original post, nothing will be updated (at least nothing that will noticeably impact performance). With this model, actually retrieving updated `Post` data can be done anywhere, as long as you pass the data back into the `update(with:)` method when it's received. It's hard to say how exactly without knowing too much about your project, but at least the api calls are now separated from your manager. For example, using an dependency injection pattern would look something like this: ``` public protocol API: Sendable { // ... func updatePost(withId: Post.ID, data: Post) -> Post } class PostManager: ObservableObject { func update(with newPost: Post, on api: some API) { let updatedPost = api.updatePost(withId: newPost.id, data: newPost) if let postIndex = posts.firstIndex(where: {$0.id == newPost.id}) { posts[postIndex] = updatedPost } } } ``` There is a bit of redundancy here because as it stands, the data to send over API for updates is of the same type as the data used in your views (both are just the `Post` struct). But as the scope of your project increases, you may want to separate those (by having, for example, a `Post.Model` struct that is `Codable`, freeing the `Post` struct of that restriction).
I make two OOT block in gnuradio for udp tx/rx, with the itemsize 188 for input/output, rx block recieve udp ts stream and do packetFragmentation, and tx block do defragmentation then transmit udp stream to VLC, it and work success as the flowgraph below (ffmpeg -\> gnuradio udprx -\> gnuradio -\> VLC) : ![](https://i.stack.imgur.com/sJsXw.png) Then I want to connect to the modulation system, but it can't work because of the itemsize mismatch ,bbheader only accept 1 itemsize instead 188 ![](https://i.stack.imgur.com/LZvVW.png) so I tried to make two blocks, let two sides can respectively accept 188 and 1 itemsize ![](https://i.stack.imgur.com/xLTjj.png) ``` #include "udppacket_impl.h" #include <gnuradio/io_signature.h> namespace gr { namespace udp0129 { udppacket::sptr udppacket::make() { return gnuradio::make_block_sptr<udppacket_impl>(); } /* * The private constructor */ udppacket_impl::udppacket_impl() : gr::sync_block("udppacket", gr::io_signature::make(1 , 1 , sizeof(unsigned char)*188), gr::io_signature::make(1 , 1 , sizeof(unsigned char))) { } /* * Our virtual destructor. */ udppacket_impl::~udppacket_impl() {} int udppacket_impl::work(int noutput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items) { const unsigned char *in = (const unsigned char *) input_items[0]; unsigned char *out = (unsigned char *) output_items[0]; for(int i = 0; i < noutput_items; i++) { out[i]=in[i]; } return noutput_items; } } } ``` ``` #include "packetudp_impl.h" #include <gnuradio/io_signature.h> namespace gr { namespace udp0129 { packetudp::sptr packetudp::make() { return gnuradio::make_block_sptr<packetudp_impl>(); } /* * The private constructor */ packetudp_impl::packetudp_impl() : gr::sync_block("packetudp", gr::io_signature::make( 1 , 1 , sizeof(unsigned char)), gr::io_signature::make( 1 , 1 , sizeof(unsigned char)*188)) { } /* * Our virtual destructor. */ packetudp_impl::~packetudp_impl() {} int packetudp_impl::work(int noutput_items, gr_vector_const_void_star& input_items, gr_vector_void_star& output_items) { const unsigned char *in = (const unsigned char *) input_items[0]; unsigned char *out = (unsigned char *) output_items[0]; for(int i = 0; i < noutput_items; i++) { out[i]=in[i]; } return noutput_items; } } /* namespace udp0129 */ } /* namespace gr */ ``` flowgraph can be run ,but it can't work properly ,when I push the udp stream flow from ffmpeg , VLC side jump out messeage said In gnuradio it automaticly stop the program with the message below: ![enter image description here](https://i.stack.imgur.com/eQmOr.png) I need some help with this
All the code from previous answers is not longer necessary, simply use `@ApplicationContext` where context is needed: @Provides fun provideFirebaseAnalytics(@ApplicationContext context: Context) = FirebaseAnalytics.getInstance(context)
|asp.net-core|visual-studio-2022|.net-8.0|
You need to find all installed app from HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall Here is the sample code: private string FindByDisplayName(RegistryKey parentKey, string name) { string[] nameList = parentKey.GetSubKeyNames(); for (int i = 0; i < nameList.Length; i++) { RegistryKey regKey = parentKey.OpenSubKey(nameList[i]); try { if (regKey.GetValue("DisplayName").ToString() == name) { return regKey.GetValue("InstallLocation").ToString(); } } catch { } } return ""; } RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall"); string location = FindByDisplayName(regKey, "MSN"); MessageBox.Show(location); This example will compare the `DisplayName` key value to your input name, if it finds the value, then return the `InstallLocation` key value.
"Prototype mismatch" warning with Test2::Mock
|unit-testing|perl|warnings|
Use the below function instead to generate new poses. You can change it from random if you like to. def random_camera_pose(radius=2.0): theta = np.random.uniform(0, 2* np.pi) # theta is the angle with the z-axis rot_z = np.array([ [np.cos(theta), -np.sin(theta), 0, 0], [np.sin(theta), np.cos(theta), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1] ]) pose = np.array([ [0.0, -np.sqrt(2)/2, np.sqrt(2)/2, 0.5], [1.0, 0.0, 0.0, 0.0], [0.0, np.sqrt(2)/2, np.sqrt(2)/2, 0.5], [0.0, 0.0, 0.0, 1.0] ]) cam_pose_rotated = np.dot(rot_z, pose) print(cam_pose_rotated) return cam_pose_rotated Use the camera pose obtained from the above in all the scene.add() for the camera node ren = pyrender.OffscreenRenderer(800, 800) # Render the scene from each random camera pose - 12 views for i in range(12): # Create a camera camera = pyrender.PerspectiveCamera(yfov=np.pi / 3.0) # Generate a random camera pose camera_pose = random_camera_pose() # Add the mesh obj to the scene mesh_node = scene.add(mesh, pose=drill_pose) # Add the camera to the scene with the specified pose camera_node = scene.add(camera, pose=camera_pose) # Render the scene color, depth = renderer.render(scene) im = Image.fromarray(color) im.save(os.path.join(out_path, 'renview' + '['+ str(inc) +'].png')) # Remove the camera from the scene scene.remove_node(camera_node)
`SecureRandom` initialises itself differently everytime you instantiate it. I.e., it will also create a different sequence of random values each time. Even if you initialise SALT with a fixed initial value, in the next step you overwrite it again by calling `random.nextBytes(SALT)`. Either don't do that or instantiate `SecureRandom` with a seed, so it creates the same sequence of random numbers every time. But this is kind of counter-productive. Similarly, you also randomise `IvParameterSpec`. You only need the `nextBytes()` result, if you want to generate new salt or IV values for multiple users or a sequence of distinct encryption/decryption actions. AES being a symmetric cypher, you need to make sure that when decrypting a message, you use the same salt and IV (if any) which were used for encryption. Try this in order to get identical encryption results: ```java static { random = new SecureRandom(); // not used in this example SALT = "I am so salty!".getBytes(StandardCharsets.UTF_8); byte[] bytesIV = "my super fancy IV".getBytes(StandardCharsets.UTF_8); ivspec = new IvParameterSpec(Arrays.copyOfRange(bytesIV, 0, 16)); } ``` Of course, in the example above I am assuming that actually salt and IV were initially created randomly, then securely saved or transmitted to the recipient, and then loaded/received and used to decrypt the message. In a real-world scenario, you would transmit or store salt and IV asymmetrically encrypted (using public-key cryptography), while the message itself (which usually is much bigger than secret key, salt and IV) is encrypted using the much faster and more efficient symmetric AES256 algorithm. P.S.: `Arrays.copyOfRange(bytesIV, 0, 16)` is necessary, because in contrast to the salt the IV must be exactly 16 bytes long. The salt is more flexible. --- **Update:** Actually, it is not necessary to encrypt salt and IV. They just make sure that the same input and secret key do not yield the same encrypted message in order to make attacks based on known cleartext more difficult. This is also why e.g. when storing salted hashes in a database, you store the salt values as cleartext along with the salted password hash (not the password itself!), because you need them every time you want to validate a user password.
|python|python-3.x|python-multiprocessing|pydantic|multiprocessing-manager|
I have figured it out, I used CardView inside of the ScrollView, which kept the images the same no matter the screen size. I also used a LinerLayout for my buttons so they would stay at the bottom of the image! `<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true" tools:ignore="SpeakableTextPresentCheck"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#FFC107" android:padding="40dp" tools:context=".ActivitiesActivity"> <androidx.cardview.widget.CardView android:id="@+id/alabama_music_hall_of_fame_card" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="8dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:cardCornerRadius="0dp" app:cardElevation="4dp"> <ImageView android:id="@+id/alabama_music_hall_of_fame" android:layout_width="match_parent" android:layout_height="200dp" android:src="@drawable/activity_alabama_music_hall_of_fame_card" android:scaleType="fitXY" android:contentDescription="@string/alabama_music_hall_of_fame_logo"/> <LinearLayout style="?android:attr/buttonBarStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_gravity="bottom" android:gravity="center_horizontal"> <Button android:id="@+id/alabama_music_hall_of_fame_FacebookButton" style="?android:attr/buttonBarButtonStyle" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:contentDescription="@string/amhfFB" android:background="@android:color/transparent" tools:ignore="VisualLintButtonSize" /> <Button android:id="@+id/alabama_music_hall_of_fame_InstagramButton" style="?android:attr/buttonBarButtonStyle" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:contentDescription="@string/amhfIG" android:background="@android:color/transparent" tools:ignore="VisualLintButtonSize" /> <Button android:id="@+id/alabama_music_hall_of_fame_WebsiteButton" style="?android:attr/buttonBarButtonStyle" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:contentDescription="@string/amhfWeb" android:background="@android:color/transparent" /> <Button android:id="@+id/alabama_music_hall_of_fame_DirectionsButton" style="?android:attr/buttonBarButtonStyle" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:contentDescription="@string/amhfDir" android:background="@android:color/transparent" tools:ignore="VisualLintButtonSize" /> </LinearLayout> </androidx.cardview.widget.CardView> <androidx.cardview.widget.CardView android:id="@+id/the_boiler_room_card" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@id/alabama_music_hall_of_fame_card" app:cardCornerRadius="0dp" app:cardElevation="4dp"> <ImageView android:id="@+id/the_boiler_room" android:layout_width="match_parent" android:layout_height="150dp" android:contentDescription="@string/the_boiler_room_logo" android:src="@drawable/activity_the_boiler_room" android:scaleType="fitXY"/> <LinearLayout style="?android:attr/buttonBarStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_gravity="bottom" android:gravity="center_horizontal"> <Button android:id="@+id/the_boiler_room_FacebookButton" style="?android:attr/buttonBarButtonStyle" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:contentDescription="@string/tbrFB" android:background="@android:color/transparent" /> <Button android:id="@+id/the_boiler_room_InstagramButton" style="?android:attr/buttonBarButtonStyle" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:contentDescription="@string/tbrIG" android:background="@android:color/transparent" /> <Button android:id="@+id/the_boiler_room_WebsiteButton" style="?android:attr/buttonBarButtonStyle" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:contentDescription="@string/tbrWeb" android:background="@android:color/transparent" /> <Button android:id="@+id/the_boiler_room_DirectionsButton" style="?android:attr/buttonBarButtonStyle" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:contentDescription="@string/tbrDir" android:background="@android:color/transparent"/> </LinearLayout> </androidx.cardview.widget.CardView> <androidx.cardview.widget.CardView android:id="@+id/the_escape_room_card" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@id/the_boiler_room_card" app:cardCornerRadius="0dp" app:cardElevation="4dp"> <ImageView android:id="@+id/activity_the_escape_room" android:layout_width="match_parent" android:layout_height="200dp" android:contentDescription="@string/the_escape_room_logo" android:src="@drawable/activity_the_escape_room" android:scaleType="fitXY"/> <LinearLayout style="?android:attr/buttonBarStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_gravity="bottom" android:gravity="center_horizontal"> <Button android:id="@+id/the_escape_room_FacebookButton" style="?android:attr/buttonBarButtonStyle" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:contentDescription="@string/terFB" android:background="@android:color/transparent" tools:ignore="VisualLintButtonSize" /> <Button android:id="@+id/the_escape_room_InstagramButton" style="?android:attr/buttonBarButtonStyle" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:contentDescription="@string/terIG" android:background="@android:color/transparent" /> <Button android:id="@+id/the_escape_room_WebsiteButton" style="?android:attr/buttonBarButtonStyle" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:contentDescription="@string/terWeb" android:background="@android:color/transparent" /> <Button android:id="@+id/the_escape_room_DirectionsButton" style="?android:attr/buttonBarButtonStyle" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:contentDescription="@string/terDir" android:background="@android:color/transparent"/> </LinearLayout> </androidx.cardview.widget.CardView> </androidx.constraintlayout.widget.ConstraintLayout> </ScrollView>`
{"Voters":[{"Id":14991864,"DisplayName":"Abdul Aziz Barkat"},{"Id":2530121,"DisplayName":"L Tyrone"},{"Id":16217248,"DisplayName":"CPlus"}],"SiteSpecificCloseReasonIds":[13]}
You may consider this solution that would with any version of `awk`: ```sh printf '%s\n' "${arr[@]}" | awk -F, ' { for(i=1; i<NF; ++i) { row[$i] = ($i in fq ? row[$i] ", " : "") $NF ++fq[$i] } } END { for (k in fq) print fq[k], k ":", row[k] }' | sort -rn -k1 3 test: meta, amazon, google 2 my: amazon, google 1 this: meta 1 hello: microsoft ``` Note that, I have used `sort` to get output as per your shown expected output. If you don't care about ordering that you can remove `sort` command.
You can always try compounding statements: cb.sum(functionListToAdd.get(0), cb.sum(functionListToAdd.get(1), functionListToAdd.get(2)))
I'm developing a MAUI app with .NET 8 targeting Android. Everything works well with the default theme @style/Maui.SplashTheme in my **MainActivity.cs**. But I need to edit the theme and add some configuration, because my **DatePicker's dialog** doesn't show well the dialog buttons (OK/Cancel): [![enter image description here][1]][1] Following [this][2] answer I created my own **style.xml** and set my color values, like this: <?xml version="1.0" encoding="UTF-8" ?> <resources> <style name="MyTheme" parent="MainTheme.Base"> <item name="android:datePickerDialogTheme">@style/CustomDatePickerDialog</item> </style> <style name="CustomDatePickerDialog" parent="ThemeOverlay.AppCompat.Dialog"> <!--header background--> <item name="colorAccent">#ff0000</item> <!--header textcolor--> <item name="android:textColorPrimaryInverse">#00ff00</item> <!--body background--> <item name="android:windowBackground">#0000ff</item> <!--selected day--> <item name="android:colorControlActivated">#ff1111</item> <!--days of the month--> <item name="android:textColorPrimary">#ffffff</item> <!--days of the week--> <item name="android:textColorSecondary">#33ff33</item> <!--cancel&ok--> <item name="android:textColor">#00ffff</item> </style> </resources> Now, in my MainActivity, If I replace... Theme = "@style/Maui.SplashTheme" With: Theme = "@style/MyTheme" ...I can solve my problem and change every color of the dialog. But now I have other issues in my app: I don't have the splash screen (and I want it) and also the Shell Flyout doesn't work as expected. I've also read [here][3] that I should keep the default theme in my MainActivity.cs. So, my question is: is it possibile to override in any way the @style/Maui.SplashTheme theme with a custom theme (possibly in my style.xml file)? In this way I could keep everything of my SplashTheme. I was expecting something like this (look at **parent="Maui.SplashTheme"**), but it is not working (I don't receive errors or warnings, but the theme simply doesn't work): <?xml version="1.0" encoding="utf-8"?> <resources> <style name="MyTheme" parent="Maui.SplashTheme"> <item name="android:windowIsTranslucent">true</item> <item name="android:datePickerDialogTheme">@style/CustomDatePickerDialog</item> </style> <style name="CustomDatePickerDialog" parent="ThemeOverlay.AppCompat.Dialog"> <!--header background--> <item name="colorAccent">#ff0000</item> <!--header textcolor--> <item name="android:textColorPrimaryInverse">#00ff00</item> <!--body background--> <item name="android:windowBackground">#0000ff</item> <!--selected day--> <item name="android:colorControlActivated">#ff1111</item> <!--days of the month--> <item name="android:textColorPrimary">#ffffff</item> <!--days of the week--> <item name="android:textColorSecondary">#33ff33</item> <!--cancel&ok--> <item name="android:textColor">#00ffff</item> </style> </resources> [1]: https://i.stack.imgur.com/DATwC.png [2]: https://stackoverflow.com/q/77259114/833644 [3]: https://learn.microsoft.com/en-us/dotnet/maui/user-interface/images/splashscreen?view=net-maui-8.0&tabs=android#platform-specific-configuration
Checkbox not visible in restrictions by carriers in Prestashop 1.7 payment preferences
|prestashop-1.7|
I have a web site that has a fairly wide main menu of five items. This works fine on a desktop display, and on a mobile device this changes to have the menu displayed as a hamburger menu. However, on an iPad landscape display the full menu is displayed, messing up the UI. In WordPress how and where do I set when a hamburger display should be used for a menu? Also I've just noticed that when using an iPad in portrait mode, when I click on the hamburger menu nothing is displayed. I'm using Elementor with the Astra theme.
(flutter doctor --android-licenses) when I write this code I get the following error [[enter image description here] (https://i.stack.imgur.com/euRv7.png)](https://i.stack.imgur.com/JO5KM.png) I downloaded sdk command line tools and it still gives the same error I also edited the system environment variables installed in my folder src and installed flutter and dart in visual studio code but the error is still the same. I found some stuff about it on the internet, but it didn't work.
I get a sdk error when trying to install flutter
|android|arp|nt|
null
merge function in kaggel
I am trying to use NextAuth (v5) with the MongoDB adapter following the documentation here: https://authjs.dev/reference/adapter/mongodb I am using Node v 20.11.0 But I am getting the following error: Server Error Error: The edge runtime does not support Node.js 'stream' module. Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime This is my auth.ts file: ``` import NextAuth from 'next-auth' import authConfig from '@/auth.config' import {MongoDBAdapter} from '@auth/mongodb-adapter' import clientPromise from './app/lib/auth.mongoClient' import type {Adapter} from '@auth/core/adapters' export const { handlers: { GET, POST }, auth, signIn, signOut, } = NextAuth({ adapter: <Adapter>MongoDBAdapter(clientPromise), session: {strategy : "jwt"}, ...authConfig, }) ``` And this is my auth.config.ts file: ``` import type { NextAuthConfig } from 'next-auth' import Credentials from 'next-auth/providers/credentials' import { LoginSchema } from './zodSchemas' import clientPromise from './app/lib/auth.mongoClient' export default { providers: [ Credentials({ async authorize(credentials) { const validatedFields = LoginSchema.safeParse(credentials) if(validatedFields.success){ const user = credentials.user const password = credentials.password const database = (await clientPromise).db() const users = database.collection('users') // TO DO --> find user in database and check password } }, }), ], } satisfies NextAuthConfig ``` However, as soon as I add the database constant, I get the error mentioned above. Just to be clear, my clientPromise variable imports the following (comes from the documentation): ``` // This approach is taken from https://github.com/vercel/next.js/tree/canary/examples/with-mongodb import { MongoClient } from "mongodb" if (!process.env.MONGODB_URI) { throw new Error('Invalid/Missing environment variable: "MONGODB_URI"') } declare global { var _mongoClientPromise: Promise<MongoClient>; } const uri = process.env.MONGODB_URI const options = { } let client let clientPromise: Promise<MongoClient> if (process.env.NODE_ENV === "development") { // In development mode, use a global variable so that the value // is preserved across module reloads caused by HMR (Hot Module Replacement). if (!global._mongoClientPromise) { client = new MongoClient(uri, options) global._mongoClientPromise = client.connect() } clientPromise = global._mongoClientPromise } else { // In production mode, it's best to not use a global variable. client = new MongoClient(uri, options) clientPromise = client.connect() } // Export a module-scoped MongoClient promise. By doing this in a // separate module, the client can be shared across functions. export default clientPromise ``` Any ideas on what I may be doing wrong? I tried following the official documentation, but it is not working.
Segmented picker in iOS - handle tap on already selected item
|ios|swift|swiftui|picker|
When I define a molecule with qiskit's PyscfDriver, it has a certain number of (spatial) orbitals. In this example, I define a NaH molecule and get an object with 10 spatial orbitals. I would like to reduce this number by reducing some orbitals from the active space. I intend to use the FreezeCoreTransformer as in `FreezeCoreTransformer(freeze_core=False, remove_orbitals=[0,1,2,3,4,5])`. But how do I know which physical orbital corresponds to which orbital number in this example? I know that all 12 electrons are within the first 6 spatial orbitals, as the num.particles becomes (0,0) after removing orbitals 0-5. Here is the minimal code example: ``` from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.transformers import FreezeCoreTransformer driver = PySCFDriver( atom=f"H 0 0 0; Na 0 0 {1.5}", basis="sto3g", charge=0, spin=0, ) problem = driver.run() print(f'{problem.num_particles = }') print(f'{problem.num_spatial_orbitals = }') as_transformer = FreezeCoreTransformer(freeze_core=False, remove_orbitals=[0,1,2,3,4,5]) as_transformer.prepare_active_space(problem.molecule, problem.num_spatial_orbitals) as_problem = as_transformer.transform(problem) print(f'{as_problem.num_particles = }') print(f'{as_problem.num_spatial_orbitals = }') ``` The printed outcome is: ``` problem.num_particles = (6, 6) problem.num_spatial_orbitals = 10 as_problem.num_particles = (0, 0) as_problem.num_spatial_orbitals = 4 ```
When you want to use the `isEqualTo` operation to match a timestamp, you'll have to match the exact timestamp that is stored in the database. To make that feasible, you'll need to ensure that you store the timestamp with 0 milliseconds **and 0 microseconds** too. For example: ``` DateTime now = DateTime.now(); DateTime today = DateTime(now.year, now.month, now.day); ``` The `today` variable will not have just the date part, with all time parts set to `0`.
null
I have a project in which i downloaded lidar 3D point cloud data from semantckitti. I want to perform Semantic Segmentation on the data using U-Net. I converted the 3d point cloud data into 2D using spherical conversion and saved the original point cloud data which was in (.bin format) into numpy arrays with dimensions as 64,1024,5 where: 64 = height , 1024 = width and 5 = xyz coordinates, Intensity and Distance from sensor of each point, in that order. I also projected the semantic information contained in the label files of point cloud(taken from yaml file of semantickitti), on 2D image plane and saved them in .png format with each pixel having depitcing the color of its respective class. **NOW MY QUESTION IS I have as input for U-net is numpy array with dimensions (64,1024,5) label image in .pn format with dimensions (64,1024) How can i input this data in U-Net? Can i input the numpy array with (64,1024,5) directly in U-Net? or some processing needs to take place? I have read somewhere that U-Net cannot take multichannel images as input. Also do i need to one-hot encode my ground truth label images as they donot contain any additional information at the moment.** Below is my code for conversion of point clouds into 2d along with label images ``` import os import numpy as np from tqdm import tqdm from PIL import Image import yaml # Function to read semantic labels from label files def read_semantic_labels(label_file): labels = np.fromfile(label_file, dtype=np.int32) semantic_labels = labels & 0xFFFF # Extract semantic labels return semantic_labels # Function to load color map from YAML file def load_color_map(yaml_file): with open(yaml_file, "r") as file: color_map = yaml.safe_load(file)["color_map"] # Convert color map to dictionary color_dict = {k: tuple(v) for k, v in color_map.items()} return color_dict # Function to project 3D point cloud data onto a 2D image using spherical projection def project_point_cloud(scan_file, label_file, color_dict, height=64, width=1024): # Read point cloud data from .bin file points = np.fromfile(scan_file, dtype=np.float32).reshape(-1, 4) # Parameters for spherical projection fov_up = 3.0 # Field of view up in degrees fov_down = -25.0 # Field of view down in degrees # Convert field of view to radians fov_up_rad = np.radians(fov_up) fov_down_rad = np.radians(fov_down) # Calculate spherical coordinates (yaw and pitch) of each point x, y, z = points[:, 0], points[:, 1], points[:, 2] range_values = np.linalg.norm(points, 2, axis=1) yaw = -np.arctan2(y, x) # Yaw angle pitch = np.arcsin(z / range_values) # Pitch angle # Convert spherical coordinates to image coordinates x_img = np.floor((yaw / np.pi + 1.0) * width / 2.0).astype(np.int32) y_img = np.floor((pitch + np.abs(fov_down_rad)) * height / (fov_up_rad + np.abs(fov_down_rad))).astype(np.int32) # Adjust image coordinates to ensure proper orientation y_img = height - 1 - y_img # Flip vertically # Clip coordinates to fit within image dimensions x_img = np.clip(x_img, 0, width - 1) y_img = np.clip(y_img, 0, height - 1) # Create empty image image = np.zeros((height, width, 5), dtype=np.uint8) # Assign values to image channels scaled_intensity = (points[:, 3] * 255).astype(np.uint8) image[y_img, x_img, 0] = x.astype(np.uint8) # X channel image[y_img, x_img, 1] = y.astype(np.uint8) # Y channel image[y_img, x_img, 2] = z.astype(np.uint8) # Z channel image[y_img, x_img, 3] = scaled_intensity # Intensity (I) channel image[y_img, x_img, 4] = range_values.astype(np.uint8) # Range (R) channel # Load semantic labels and assign colors labels = read_semantic_labels(label_file) label_image = np.zeros((height, width, 3), dtype=np.uint8) for i in range(len(labels)): label_image[y_img[i], x_img[i]] = color_dict[labels[i]] return image, label_image, labels # Main function to convert and save data def convert_and_save_data(input_folder, output_folder): # Load color map from YAML file color_dict = load_color_map("semantic-kitti.yaml") # Loop through sequences (folders named '00', '01', ..., '10') for sequence_folder in os.listdir(input_folder): sequence_folder_path = os.path.join(input_folder, sequence_folder) output_sequence_folder_path = os.path.join(output_folder, sequence_folder) # Create sequence folder in the output directory os.makedirs(output_sequence_folder_path, exist_ok=True) # Loop through files in the 'velodyne' folder velodyne_folder_path = os.path.join(sequence_folder_path, 'velodyne') label_folder_path = os.path.join(sequence_folder_path, 'labels') for file_name in tqdm(os.listdir(velodyne_folder_path), desc=f'Processing {sequence_folder}'): file_path = os.path.join(velodyne_folder_path, file_name) label_file_path = os.path.join(label_folder_path, file_name[:-4] + '.label') # Check if file is a .bin file (point cloud data) if file_name.endswith('.bin'): # Convert point cloud data to numpy array and save image, label_image, labels = project_point_cloud(file_path, label_file_path, color_dict) np.save(os.path.join(output_sequence_folder_path, file_name[:-4] + '.npy'), image) # Save the label image directly in the main folder Image.fromarray(label_image).save(os.path.join(output_sequence_folder_path, f'{file_name[:-4]}_label.png')) # Define input and output folder paths input_folder = ### output_folder = ### # Call the function to convert and save the data convert_and_save_data(input_folder, output_folder) ```
How to input multi-channel Numpy array to U-net for semantic segmentation
|deep-learning|point-clouds|semantic-segmentation|lidar|unet-neural-network|
null
I understand that your protocol interception handler recursively invokes itself because the `net.request` leads to another invocation of the same protocol. You could avoid this by inserting a special header that ends the recursion: ```js if (req.url.includes("special url here") && !req.headers["x-request-interception"]) { var request = net.request({ method: req.method, headers: {...req.headers, "x-request-interception": "true"}, url: req.url }); ... } else { // Is supposedly going to carry out the request without interception protocol.uninterceptProtocol("http"); } } ``` Instead of adding a special header, you could also use a special value for the `User-Agent` header.
I use a COUNTIF function to count and increment the number of instances of an ID in excel. Id_Treatment_Count ID 1 769334 1 769345 2 769345 1 769376 3 769345 In Excel, I would get the above using =COUNTIF($B$2:B2,B2) and then I would drag down (Id_treatment_count being column A and ID being column B). How can I get the Id_treatment_Count in Power BI using DAX?
My react app is running on **apache2** and is placed inside **cPanel's directory public_html**. My backend **nodejs server** is also inside the same public_html directory **but its running on linux**, My frontend works fine but its not fetching data from server. I have updated the virtualHost inside this direcotry **"/apache2/conf/httpd.conf"** <VirtualHost myDomain:8080> ServerName myDomain ServerAlias myDomian DocumentRoot /home/userDirectory/public_html ServerAdmin webmaster@myDomain UseCanonicalName Off # Reverse Proxy settings for Node.js server ProxyPass /api http://myServer's Address:port ProxyPassReverse /api http://myServer's Address:port I am running nodejs server through pm2 and its successfully running on 0.0.0.0.port and its responding to the curl command to show all products. but my frontend react app is not listening to it moreover i can type commands like curl on linux and they work fine, but i am unable to access my nodejs server on browser. Please provide any suggestions, thanks for your time.
Alma Linux 8 cant connect my react app with nodejs server
|reactjs|node.js|linux|apache|deployment|
null
null
null
null
null
null
im downloading a video and storing it using async storage and filesystem, i want to play that video by accessing it from async storage and using the path or the downloaded video, i want to play in expo av, it has an option of uri: videourl. I also tried require but even that doesn't work. What else can i do? trying to pass file path of file stored to the video av module to play video in expo ``` <Video ref={video} style={styles.video} source={{ uri: Path of the video here }} useNativeControls resizeMode={ResizeMode.CONTAIN} isLooping onPlaybackStatusUpdate={status => setStatus(() => status)} /> ```
I'm downloading a video from its url that is coming from the server. Im downloading it locally and storage it in file system. How to play in expo Av?
|expo|expo-av|
null
{"Voters":[{"Id":7177346,"DisplayName":"freeflow"},{"Id":6600940,"DisplayName":"Storax"},{"Id":8162520,"DisplayName":"Mayukh Bhattacharya"}],"SiteSpecificCloseReasonIds":[13]}
I want to write a function that returns several configuration settings from a settings store. Settings can be of several types, some have parameters, some hold strings, some hold arrays like so: ```typescript type StringSetting = 'outputPath' | 'fileName' type StringSettingWithParam = 'emailAddress' | 'homeDirectory' type ArrayOfStringsSetting = 'inputPaths' ``` I want to fetch several settings at once, the function implementation is not a problem, but I can't find a way to strongly type the function: Example parameter to the function: ```typescript { a: {setting: 'outputPath'}, b: {setting: 'emailAddress', param: 'userA'}, c: {setting: 'inputPaths'} } ``` Expected return value ```typescript { a: '/home/user', // string b: 'foo@bar.com', // string c: ['/usr/var/output', '/home/user/output' // string[] } ``` In other words, the output type should have the same keys as the input type, the output values should be dependent on the input values I thought, a good starting point would be to describe functions for each kind of input type ```typescript type StringSettingProcessor = (s: {setting: StringSetting}) => string type StringWithParamSettingProcessor = (s: { setting: StringSettingWithParam; param: string }) => string type ArrayOfStringsSettingProcessor = (s: { setting: ArrayOfStringsSetting }) => string[] ``` Now I can combine all of those into a single type ```typescript type Processors = StringSettingProcessor | StringWithParamSettingProcessor | ArrayOfStringsSettingProcessor ``` My function signature could be perhaps be something like this, but I have no idea how to correctly set the output type. ```typescript function getSettings<T extends Record<string, Parameters<Processors>[0]>(settings: { [K in keyof T]: T[K] }): any {} ```
How to solve OutOfMemoryError in Android Kotlin when reading large file?
null
I'm using nestjs with typeorm. For my audit log I have created typeorm subscriber but I cant able to inject my service in to it. When I call the function from the service im getting error `TypeError: Cannot read properties of undefined` also when I do console `console.log(this.activityLogService);` in subscriber hook it shows undefined. FYI: I have tried by adding `@Injectable()` aswell ``` @EventSubscriber() export class GlobalSubscriber implements EntitySubscriberInterface { constructor(private activityLogService: ActivityLogService) {} afterUpdate(event: UpdateEvent<any>) { console.log(this.activityLogService); // This is undefined } } ```
Nest JS TypeORM inject service
|mysql|typescript|nestjs|typeorm|
null
I'm using ups API for tracking packages for many years now. Works fine. Now I'm trying to get the Proof of Delivery image, but can't seem to find how to do this. In the UPS PDF document there seems to be something called "Signature Tracking", but not a word on how to implement/call this signature tracking. Up till now I called: $"https://onlinetools.ups.com/api/track/v1/details/{TrackCode}" What do I need to do to get the POD image? Thanks
How to get Proof of Delivery Image via UPS API?
|ups|
IN MbedTls with RSA in a C-programm encryption/decryption works when using separate buffers (for plainText, cipherText, and decryptedText, i.e. the content of plainText and decryptedText is the same), but not when using just one buffer to perform in-place encryption/decryption as i get gibberish/not correctly encrypted data. Is that just a general limitation or is my code wrong? Background: I'm trying to use in-place encryption and decryption with RSA in MbedTls in a C-programm. [Here](https://forums.mbed.com/t/in-place-encryption-decryption-with-aes/4531) it says that "In place cipher is allowed in Mbed TLS, unless specified otherwise.", although I'm not sure if they are also talking about AES. From my understanding i didn't see any specification saying otherwise for mbedtls_rsa_rsaes_oaep_decrypt (should work) in the Mbed TLS API documentation. Code: ``` size_t sizeDecrypted; unsigned char plainText[15000] = "yxcvbnm"; unsigned char cipherText[15000]; unsigned char decryptedText[15000]; rtn = mbedtls_rsa_rsaes_oaep_encrypt(&rsa, mbedtls_ctr_drbg_random, &ctr_drbg, NULL, 0, sizeof("yxcvbnm"), &plainText, &cipherText); rtn = mbedtls_rsa_rsaes_oaep_decrypt(&rsa, mbedtls_ctr_drbg_random, &ctr_drbg, NULL, 0, &sizeDecrypted, &cipherText, &decryptedText, 15000); //decryptedText afterwards contains the correctly decrypted text just like plainText unsigned char text[15000] = "yxcvbnm"; rtn = mbedtls_rsa_rsaes_oaep_encrypt(&rsa, mbedtls_ctr_drbg_random, &ctr_drbg, NULL, 0, sizeof("yxcvbnm"), &text, &text); rtn = mbedtls_rsa_rsaes_oaep_decrypt(&rsa, mbedtls_ctr_drbg_random, &ctr_drbg, NULL, 0, &sizeDecrypted, &text, &text, 15000); //someText afterwards doesn't contain the correctly decrypted text/has a different content than plainText //rtn is always 0, i.e. no error is returned ```
Strongly typed object output with same keys as input
|typescript|
The issue with your code is that you get the last message of the channel, which was sent by the bot. A simpler solution would be to store the message ID, and use that ID to delete the message ``` @Override public void onMessageReceived(MessageReceivedEvent event) { event.getChannel().sendMessage(event.getJumpUrl()).addActionRow(Button.danger("delete"+event.getMessageId(), "Delete Message")).queue(); } @Override public void onButtonInteraction(ButtonInteractionEvent event) { if(event.getComponentId().contains("delete")) { String id; id = event.getComponentId().replace("delete", ""); event.getJDA().getTextChannelById("1195039391563907082").deleteMessageById(id).queue(); } } ``` Make sure you change this based on your requirement.
Update: You can simply use `(name ='')` as order by clause which will return 1 if name is empty other wise 0. select * from comments order by (name ='') If you have `null` as well then you can use: select * from comments order by (NULLIF(name,'') is null) Here `NULLIF(name,'')` will convert empty string into null You can select rows without empty strings first without any order. Then you can select the rows with empty strings. You can combine both the results with `union all` Query: select * from comments where name <>'' union all select * from comments where name ='' Output: | name | |:-----| | Apple | | Orange | | Avocado | | Banana | | Cauliflower | | Broccoli | | Potato | | Cabbage | | | | | [fiddle](https://dbfiddle.uk/u75I0Nmw) Better approach would be to use conditional order clause like below: Query: select * from comments order by (case when name ='' then 1 else 0 end) Output: | name | |:-----| | Apple | | Orange | | Avocado | | Banana | | Cauliflower | | Broccoli | | Potato | | Cabbage | | | | | [fiddle](https://dbfiddle.uk/Be2Z1dQn)
I'm not a fan of using `@Param <> ColumnName` syntax for something like this; if either value is `NULL` then this expression will resolve the UNKNOWN, which *isn't* TRUE, and so the row *isn't* affected. The more complete version would be: ```sql WHERE (@Param <> ColumnName OR (@Param IS NULL AND ColumnName IS NOT NULL) OR (@Param IS NOT NULL AND ColumnName IS NULL)) ``` For *a lot* of `NULL`able columns that becomes *very* long. In newer versions of SQL Server you can use `IS DISTINCT FROM` instead, which will treat an expression like `NULL IS DISTINCT FROM 1` as TRUE and `NULL IS DISTINCT FROM NULL` as FALSE. This, much like the solution you have, involves a lot of `OR` clauses: ```sql ... FROM ... WHERE @Param1 IS DISTINCT FROM Col1 OR @Param2 IS DISTINCT FROM Col2 OR @Param3 IS DISTINCT FROM Col3 ... OR @Param15 IS DISTINCT FROM Col15 ``` An alternative method I quite like is to use an `EXCEPT` or `INTERSECT` in a `(NOT) EXISTS)`, and `SELECT` the parameters in one and the columns in the other. This would look something like this: ```sql ... FROM ... WHERE EXISTS (SELECT Col1, Col2, Col3, ..., Col15 EXCEPT SELECT @Param1, @Param2, @Param3, ..., @Param15); ``` If all the columns and parameters have the *same* value then a row won't be returned in the subquery, and so the `EXISTS` returns FALSE and the row isn't updated. Like `IS DISTINCT FROM`, this will handle `NULL` values, as `SELECT NULL EXCEPT SELECT NULL;` will result in no returned rows.
On Windows, follow the steps below: 1) Windows button + R 2) type "services" and press Enter, 3) Find "MongoDb", right click and select "Start" 4) Go back to MongoDBCompass, and try again to connect to localhost.
Sorry but I am new to Netlogo, here is my problem: I have created polar bears, who have better chances to survive on ice than on dirt. I am wondering which effect the ice dirt ratio has on the lifespan of the polar bears. For that I need a list of the polar bears age before they die and create a histogramm with it. I am greatful for any help. I got told to use the comand lput, but to be honest I dont quite know how that comand works.
I need the age of my agents before they die to create a list and histogram
|list|histogram|netlogo|