CitrusFramework CustomAction did not failed testcase in Test Results

Question: Actually all suggested code from @Christoph is not give answer
Somehow explanations from Christoph is valid in before test scenario but not in after test
<code>    @Configuration
    public class AppConfig {

    @Bean(name="correlationId")
    public String getCorrelationId() {
        return RandomNumberFunction.getRandomNumber(48, false);
    }

    @Bean
    @DependsOn("correlationId")
    public SequenceAfterTest afterTest() {
        return new KrampCitrusTestRunnerAfterTestSupport();
    }

    @Bean
    @DependsOn("correlationId")
    public SequenceBeforeTest  beforeTest() {
        return new KrampCitrusTestRunnerBeforeTestSupport();
     }
    }
</code>
after test class
<code>    public class KrampCitrusTestRunnerAfterTestSupport
        extends TestRunnerAfterTestSupport {

    @Override
    public void afterTest(TestRunner runner) {

         runner.echo("This action should be executed after each test");
         runner.fail("message");
      }
    }
</code>
So this configuration produce following - pls notice its report for TEST SUCESS?!?!
<code>14:19:50,900 INFO         citrus.Citrus|
14:19:50,901 INFO         citrus.Citrus|
14:19:50,903 WARN       citrus.TestCase| After test failed with errors
com.consol.citrus.exceptions.TestCaseFailedException: Test case failed
    at com.consol.citrus.TestCase.executeAction(TestCase.java:236)
    at com.consol.citrus.dsl.runner.DefaultTestRunner.run(DefaultTestRunner.java:198)
    at com.consol.citrus.dsl.runner.DefaultTestRunner.fail(DefaultTestRunner.java:265)
    at com.kramp.eai.test.common.iibexception.KrampCitrusTestRunnerAfterTestSupport.afterTest(KrampCitrusTestRunnerAfterTestSupport.java:45)
    at com.consol.citrus.dsl.runner.TestRunnerAfterTestSupport.doExecute(TestRunnerAfterTestSupport.java:48)
    at com.consol.citrus.actions.AbstractTestAction.execute(AbstractTestAction.java:42)
    at com.consol.citrus.TestCase.afterTest(TestCase.java:203)....
    Caused by: com.consol.citrus.exceptions.CitrusRuntimeException: message
at com.consol.citrus.actions.FailAction.doExecute(FailAction.java:40)
at com.consol.citrus.actions.AbstractTestAction.execute(AbstractTestAction.java:42)
at com.consol.citrus.TestCase.executeAction(TestCase.java:229)
... 31 more
14:19:50,917 INFO         citrus.Citrus|
14:19:50,917 INFO         citrus.Citrus| -----------------------------------
 -------------------------------------
14:19:50,917 INFO         citrus.Citrus|
14:19:50,918 INFO         citrus.Citrus|
14:19:50,918 INFO         citrus.Citrus| AFTER TEST SUITE: SUCCESS
14:19:50,918 INFO         citrus.Citrus| -----------------------------------
-------------------------------------
14:19:50,918 INFO         citrus.Citrus|
14:19:50,918 INFO         citrus.Citrus| -----------------------------------
-------------------------------------
14:19:50,918 INFO         citrus.Citrus|
14:19:50,918 INFO         citrus.Citrus| CITRUS TEST RESULTS
14:19:50,918 INFO         citrus.Citrus|
14:19:50,924 INFO         citrus.Citrus|  TC12: CDM............................... SUCCESS
14:19:50,924 INFO         citrus.Citrus|
14:19:50,924 INFO         citrus.Citrus| TOTAL: 1
14:19:50,924 INFO         citrus.Citrus| FAILED:    0 (0.0%)
</code>
Answer: This is because you are in the after test phase of JUnit or TestNG. This is technically no more part of the Citrus test. You should be using *AfterTestSupport classes in Citrus as described here: http://www.citrusframework.org/reference/html/test-suite.html#after-test. Only then you have access to test variables and test boundaries in Citrus.
Comment: Still no good `@Override
 public void afterTest(TestRunner runner) {    FailAction action = new FailAction();
         action.setMessage("ERROR");
         runner.run(action); } ` I get this in report INFO  nnerAfterTestSupport, event name: output
WARN       citrus.TestCase| After test failed with errors
com.consol.citrus.exceptions.TestCaseFailedException: Test case failed citrus.Citrus| AFTER TEST SUITE: SUCCESS
citrus.Citrus|
citrus.Citrus| CITRUS TEST RESULTS
FlowTestCase.flowTestItemUpdateMessage  SUCCESS
Comment: You must add the AfterTestSupport class to the Spring application context either using XML bean definition in citrus-context.xml

    ``

Or via Java Spring bean config

    `@Bean
    public SequenceAfterTest afterTest() {
        return new MyAfterTestSupport();
    }`


Displaying realm data in UIKit

Question: I work with realm in UIKit. I set up saving to the realm, everything is displayed in MongoDB Realm Studio, but when I want this data to be shown in UITableView, there is nothing.
I wrote an extension, there seem to be no errors, but I don't understand why the data is not displayed.
extension ViewController: UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return spendingDBArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewCell

        let spending = spendingDBArray[indexPath.row]

        cell.recordCategory.text = spending.category
        cell.recordMoney.text = "\(spending.cost)"

        print("work")

        switch spending.category {
        case "Home": cell.recordImage.image = #imageLiteral(resourceName: "Frame 4")
        case "Clothes": cell.recordImage.image = #imageLiteral(resourceName: "Frame 8")
        case "Connection": cell.recordImage.image = #imageLiteral(resourceName: "Frame 7")
        case "Auto": cell.recordImage.image = #imageLiteral(resourceName: "Frame 3")
        case "Pharmacy": cell.recordImage.image = #imageLiteral(resourceName: "Frame 2")
        case "Products": cell.recordImage.image = #imageLiteral(resourceName: "Frame 1")
        case "Cafe": cell.recordImage.image = #imageLiteral(resourceName: "Frame 6")
        case "Other": cell.recordImage.image = #imageLiteral(resourceName: "Frame 5")
        default:
            cell.recordImage.image = #imageLiteral(resourceName: "Rectangle 1")
        }
        return cell
    }

}

Answer: I get my Realm data by:
lazy var yourvarname: Results<yourObjectClass> = {
    self.realm.objects(yourObjectClass.self) }()

cell.textlabel.text = yourvarname[indexPath.row].varinyourObjectClass

No extension is needed.

Displaying realm data in UIKit


Getting below error on ActiveMQ "Classic" message broker log. I'm looking for some solution to find the root cause and fix for this issue

Question: Getting below error on ActiveMQ "Classic" message broker log. I'm looking for some solution to find the root cause and fix for this issue.
Sep  6 16:10:46 SERVER activemq_db8159[1168628]:  WARN | Error while closing connection: Deadlock found when trying to get lock; try restarting transaction
Sep  6 16:10:46 SERVER activemq_db8159[1168628]: java.sql.BatchUpdateException: Deadlock found when trying to get lock; try restarting transaction

Later the broker is being restarting due to restart of the service messages are getting stuck for continuous client messages.
2023-09-06 16:10:46,332 | INFO  | Stopping BrokerService[dbaas_broker] due to exception, java.io.IOException: Deadlock found when trying to get lock; try restarting transaction | org.apache.activemq.util.DefaultIOExceptionHandler | ActiveMQ Transport: ssl:///<IPadress>:54970

JDBC connection:
<jdbcPersistenceAdapter dataSource="#mysql-ds" lockKeepAlivePeriod="10000">
<bean class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close" id="mysql-ds">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://mysqldb.com:3307/8159_activemq?useSSL=true&requireSSL=true&socketTimeout=10000&connectTimeout=5000&autoReconnect=true&maxReconnects=60" />

Version details

ActiveMQ "Classic" 5.17.2
MySQL connector 8.0.31

INNODB status:

MariaDB [(none)]> SHOW ENGINE INNODB STATUS \G;
*************************** 1. row ***************************
  Type: InnoDB
  Name:
Status:
=====================================
2023-09-08 05:44:03 0x7fc5ddd00700 INNODB MONITOR OUTPUT
=====================================
Per second averages calculated from the last 55 seconds
-----------------
BACKGROUND THREAD
-----------------
srv_master_thread loops: 658347 srv_active, 0 srv_shutdown, 3052597 srv_idle
srv_master_thread log flush and writes: 3710151
----------
SEMAPHORES
----------
OS WAIT ARRAY INFO: reservation count 13196031
OS WAIT ARRAY INFO: signal count 7507305
RW-shared spins 3175113, rounds 52954335, OS waits 1496241
RW-excl spins 1004776, rounds 5875228, OS waits 14950
RW-sx spins 3900, rounds 714889, OS waits 23471
Spin rounds per wait: 16.68 RW-shared, 5.85 RW-excl, 183.30 RW-sx
------------------------
LATEST DETECTED DEADLOCK
------------------------
2023-09-07 11:30:08 0x7fc5ec0f5700
*** (1) TRANSACTION:
TRANSACTION 59108994, ACTIVE 22 sec fetching rows
mysql tables in use 2, locked 2
LOCK WAIT 10 lock struct(s), heap size 1128, 2 row lock(s)
MySQL thread id 965528, OS thread handle 140488046327552, query id 18506205 10.4.28.55 8159_activemq_rw Sending data
DELETE FROM ACTIVEMQ_MSGS WHERE (PRIORITY=0 AND ID <=      ( SELECT min(ACTIVEMQ_ACKS.LAST_ACKED_ID)       FROM ACTIVEMQ_ACKS WHERE ACTIVEMQ_ACKS.CONTAINER=ACTIVEMQ_MSGS.CONTAINER        AND ACTIVEMQ_ACKS.PRIORITY=0)   )
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 62 page no 22720 n bits 96 index PRIMARY of table `8159_activemq`.`ACTIVEMQ_MSGS` trx id 59108994 lock_mode X locks rec but not gap waiting
Record lock, heap no 8 PHYSICAL RECORD: n_fields 10; compact format; info bits 32
0: len 8; hex 800000000000c2db; asc         ;;
1: len 6; hex 00000385ef32; asc      2;;
2: len 7; hex 77000039360733; asc w  96 3;;
3: len 20; hex 71756575653a2f2f544f504841545f494e565f46; asc queue://topic_INV_F;;
4: len 30; hex 49443a464d5341503331302d34393933362d313639343038303939383932; asc ID:FMSAP310-49936-169408099892; (total 41 bytes);
5: len 8; hex 8000000000000006; asc         ;;
6: len 8; hex 8000000000000000; asc         ;;
7: len 30; hex 000001c91c0000008e00017b01002549443a464d5341503331302d343939; asc            {  %ID:FMSAP310-499; (total 461 bytes);
8: len 8; hex 8000000000000000; asc         ;;
9: SQL NULL;

*** (2) TRANSACTION:
TRANSACTION 59109170, ACTIVE 1 sec updating or deleting
mysql tables in use 1, locked 1
3 lock struct(s), heap size 1128, 2 row lock(s), undo log entries 1
MySQL thread id 965524, OS thread handle 140488045713152, query id 18506329 <IP adress> 8159_activemq_rw Updating
DELETE FROM ACTIVEMQ_MSGS WHERE ID=49883
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 62 page no 22720 n bits 96 index PRIMARY of table `8159_activemq`.`ACTIVEMQ_MSGS` trx id 59109170 lock_mode X locks rec but not gap
Record lock, heap no 8 PHYSICAL RECORD: n_fields 10; compact format; info bits 32
0: len 8; hex 800000000000c2db; asc         ;;
1: len 6; hex 00000385ef32; asc      2;;
2: len 7; hex 77000039360733; asc w  96 3;;
3: len 20; hex 71756575653a2f2f544f504841545f494e565f46; asc queue://topic_INV_F;;
4: len 30; hex 49443a464d5341503331302d34393933362d313639343038303939383932; asc ID:FMSAP310-49936-169408099892; (total 41 bytes);
5: len 8; hex 8000000000000006; asc         ;;
6: len 8; hex 8000000000000000; asc         ;;
7: len 30; hex 000001c91c0000008e00017b01002549443a464d5341503331302d343939; asc            {  %ID:FMSAP310-499; (total 461 bytes);
8: len 8; hex 8000000000000000; asc         ;;
9: SQL NULL;

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 62 page no 7 n bits 792 index ACTIVEMQ_MSGS_PIDX of table `8159_activemq`.`ACTIVEMQ_MSGS` trx id 59109170 lock_mode X locks rec but not gap waiting
Record lock, heap no 558 PHYSICAL RECORD: n_fields 2; compact format; info bits 0
0: len 8; hex 8000000000000000; asc         ;;
1: len 8; hex 800000000000c2db; asc         ;;

*** WE ROLL BACK TRANSACTION (2)
------------
TRANSACTIONS
------------
Trx id counter 59338587
Purge done for trx's n:o < 59338587 undo n:o < 0 state: running but idle
History list length 0
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 421962821473120, not started
0 lock struct(s), heap size 1128, 0 row lock(s)
---TRANSACTION 421962821456256, not started
0 lock struct(s), heap size 1128, 0 row lock(s)
---TRANSACTION 421962821481552, not started
0 lock struct(s), heap size 1128, 0 row lock(s)
---TRANSACTION 421962821468904, not started
0 lock struct(s), heap size 1128, 0 row lock(s)
---TRANSACTION 421962821477336, not started
0 lock struct(s), heap size 1128, 0 row lock(s)
---TRANSACTION 421962821464688, not started
0 lock struct(s), heap size 1128, 0 row lock(s)
---TRANSACTION 421962821460472, not started
0 lock struct(s), heap size 1128, 0 row lock(s)
---TRANSACTION 421962821452040, not started
0 lock struct(s), heap size 1128, 0 row lock(s)
---TRANSACTION 421962821447824, not started
0 lock struct(s), heap size 1128, 0 row lock(s)
--------
FILE I/O
--------
I/O thread 0 state: waiting for i/o request (insert buffer thread)
I/O thread 1 state: waiting for i/o request (log thread)
I/O thread 2 state: waiting for i/o request (read thread)
I/O thread 3 state: waiting for i/o request (read thread)
I/O thread 4 state: waiting for i/o request (read thread)
I/O thread 5 state: waiting for i/o request (read thread)
I/O thread 6 state: waiting for i/o request (read thread)
I/O thread 7 state: waiting for i/o request (read thread)
I/O thread 8 state: waiting for i/o request (read thread)
I/O thread 9 state: waiting for i/o request (read thread)
I/O thread 10 state: waiting for i/o request (read thread)
I/O thread 11 state: waiting for i/o request (read thread)
I/O thread 12 state: waiting for i/o request (read thread)
I/O thread 13 state: waiting for i/o request (read thread)
I/O thread 14 state: waiting for i/o request (read thread)
I/O thread 15 state: waiting for i/o request (read thread)
I/O thread 16 state: waiting for i/o request (read thread)
I/O thread 17 state: waiting for i/o request (read thread)
I/O thread 18 state: waiting for i/o request (read thread)
I/O thread 19 state: waiting for i/o request (read thread)
I/O thread 20 state: waiting for i/o request (read thread)
I/O thread 21 state: waiting for i/o request (read thread)
I/O thread 22 state: waiting for i/o request (read thread)
I/O thread 23 state: waiting for i/o request (read thread)
I/O thread 24 state: waiting for i/o request (read thread)
I/O thread 25 state: waiting for i/o request (read thread)
I/O thread 26 state: waiting for i/o request (read thread)
I/O thread 27 state: waiting for i/o request (read thread)
I/O thread 28 state: waiting for i/o request (read thread)
I/O thread 29 state: waiting for i/o request (read thread)
I/O thread 30 state: waiting for i/o request (read thread)
I/O thread 31 state: waiting for i/o request (read thread)
I/O thread 32 state: waiting for i/o request (read thread)
I/O thread 33 state: waiting for i/o request (read thread)
I/O thread 34 state: waiting for i/o request (read thread)
I/O thread 35 state: waiting for i/o request (read thread)
I/O thread 36 state: waiting for i/o request (read thread)
I/O thread 37 state: waiting for i/o request (read thread)
I/O thread 38 state: waiting for i/o request (read thread)
I/O thread 39 state: waiting for i/o request (read thread)
I/O thread 40 state: waiting for i/o request (read thread)
I/O thread 41 state: waiting for i/o request (read thread)
I/O thread 42 state: waiting for i/o request (read thread)
I/O thread 43 state: waiting for i/o request (read thread)
I/O thread 44 state: waiting for i/o request (read thread)
I/O thread 45 state: waiting for i/o request (read thread)
I/O thread 46 state: waiting for i/o request (read thread)
I/O thread 47 state: waiting for i/o request (read thread)
I/O thread 48 state: waiting for i/o request (read thread)
I/O thread 49 state: waiting for i/o request (read thread)
I/O thread 50 state: waiting for i/o request (read thread)
I/O thread 51 state: waiting for i/o request (read thread)
I/O thread 52 state: waiting for i/o request (read thread)
I/O thread 53 state: waiting for i/o request (read thread)
I/O thread 54 state: waiting for i/o request (read thread)
I/O thread 55 state: waiting for i/o request (read thread)
I/O thread 56 state: waiting for i/o request (read thread)
I/O thread 57 state: waiting for i/o request (read thread)
I/O thread 58 state: waiting for i/o request (read thread)
I/O thread 59 state: waiting for i/o request (read thread)
I/O thread 60 state: waiting for i/o request (read thread)
I/O thread 61 state: waiting for i/o request (read thread)
I/O thread 62 state: waiting for i/o request (read thread)
I/O thread 63 state: waiting for i/o request (read thread)
I/O thread 64 state: waiting for i/o request (read thread)
I/O thread 65 state: waiting for i/o request (read thread)
I/O thread 66 state: waiting for i/o request (write thread)
I/O thread 67 state: waiting for i/o request (write thread)
I/O thread 68 state: waiting for i/o request (write thread)
I/O thread 69 state: waiting for i/o request (write thread)
I/O thread 70 state: waiting for i/o request (write thread)
I/O thread 71 state: waiting for i/o request (write thread)
I/O thread 72 state: waiting for i/o request (write thread)
I/O thread 73 state: waiting for i/o request (write thread)
I/O thread 74 state: waiting for i/o request (write thread)
I/O thread 75 state: waiting for i/o request (write thread)
I/O thread 76 state: waiting for i/o request (write thread)
I/O thread 77 state: waiting for i/o request (write thread)
I/O thread 78 state: waiting for i/o request (write thread)
I/O thread 79 state: waiting for i/o request (write thread)
I/O thread 80 state: waiting for i/o request (write thread)
I/O thread 81 state: waiting for i/o request (write thread)
I/O thread 82 state: waiting for i/o request (write thread)
I/O thread 83 state: waiting for i/o request (write thread)
I/O thread 84 state: waiting for i/o request (write thread)
I/O thread 85 state: waiting for i/o request (write thread)
I/O thread 86 state: waiting for i/o request (write thread)
I/O thread 87 state: waiting for i/o request (write thread)
I/O thread 88 state: waiting for i/o request (write thread)
I/O thread 89 state: waiting for i/o request (write thread)
I/O thread 90 state: waiting for i/o request (write thread)
I/O thread 91 state: waiting for i/o request (write thread)
I/O thread 92 state: waiting for i/o request (write thread)
I/O thread 93 state: waiting for i/o request (write thread)
I/O thread 94 state: waiting for i/o request (write thread)
I/O thread 95 state: waiting for i/o request (write thread)
I/O thread 96 state: waiting for i/o request (write thread)
I/O thread 97 state: waiting for i/o request (write thread)
Pending normal aio reads: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] , aio writes: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ,
ibuf aio reads:, log i/o's:, sync i/o's:
Pending flushes (fsync) log: 0; buffer pool: 0
84348099 OS file reads, 45353143 OS file writes, 7813858 OS fsyncs
0.00 reads/s, 0 avg bytes/read, 5.60 writes/s, 2.58 fsyncs/s
-------------------------------------
INSERT BUFFER AND ADAPTIVE HASH INDEX
-------------------------------------
Ibuf: size 1, free list len 0, seg size 2, 326 merges
merged operations:
insert 150, delete mark 267, delete 22
discarded operations:
insert 0, delete mark 0, delete 0
Hash table size 69257, node heap has 1 buffer(s)
Hash table size 69257, node heap has 1 buffer(s)
Hash table size 69257, node heap has 1 buffer(s)
Hash table size 69257, node heap has 1 buffer(s)
Hash table size 69257, node heap has 1 buffer(s)
Hash table size 69257, node heap has 1 buffer(s)
Hash table size 69257, node heap has 1 buffer(s)
Hash table size 69257, node heap has 1 buffer(s)
3.85 hash searches/s, 0.25 non-hash searches/s
---
LOG
---
Log sequence number 2500024278373
Log flushed up to   2500024276737
Pages flushed up to 2500024276737
Last checkpoint at  2500024276128
0 pending log flushes, 0 pending chkp writes
6087092 log i/o's done, 2.31 log i/o's/second
----------------------
BUFFER POOL AND MEMORY
----------------------
Total large memory allocated 301989888
Dictionary memory allocated 43920
Buffer pool size   16054
Free buffers       1024
Database pages     15022
Old database pages 5525
Modified db pages  50
Percent of dirty pages(LRU & free pages): 0.312
Max dirty pages percent: 75.000
Pending reads 0
Pending writes: LRU 0, flush list 0, single page 0
Pages made young 7648268, not young 94650352
0.00 youngs/s, 0.00 non-youngs/s
Pages read 84348078, created 11140151, written 37578055
0.00 reads/s, 0.00 creates/s, 2.96 writes/s
Buffer pool hit rate 1000 / 1000, young-making rate 0 / 1000 not 0 / 1000
Pages read ahead 0.00/s, evicted without access 0.00/s, Random read ahead 0.00/s
LRU len: 15022, unzip_LRU len: 0
I/O sum[157]:cur[0], unzip sum[0]:cur[0]
--------------
ROW OPERATIONS
--------------
0 queries inside InnoDB, 0 queries in queue
0 read views open inside InnoDB
Process ID=1, Main thread ID=140484596745984, state: sleeping
Number of rows inserted 55948, updated 665215, deleted 55946, read 8771119
0.00 inserts/s, 0.33 updates/s, 0.00 deletes/s, 2.35 reads/s
Number of system rows inserted 824726, updated 0, deleted 824703, read 824744
0.33 inserts/s, 0.00 updates/s, 0.00 deletes/s, 0.00 reads/s
----------------------------
END OF INNODB MONITOR OUTPUT
============================

1 row in set (0.001 sec)

ERROR: No query specified

MariaDB [(none)]>

I tried to collate all the information and logs and tried to research in internet and found no solutions to this problem ?
Adding InnoDB status:
MariaDB [8374_activemq]> SHOW TABLE STATUS LIKE 'ACTIVEMQ_LOCK' \G;
*************************** 1. row ***************************
            Name: ACTIVEMQ_LOCK
          Engine: InnoDB
         Version: 10
      Row_format: Dynamic
            Rows: 1
  Avg_row_length: 16384
     Data_length: 16384
 Max_data_length: 0
    Index_length: 0
       Data_free: 0
  Auto_increment: NULL
     Create_time: 2023-02-17 00:25:26
     Update_time: 2023-10-03 21:48:28
      Check_time: NULL
       Collation: utf8_general_ci
        Checksum: NULL
  Create_options:
         Comment:
Max_index_length: 0
       Temporary: N
1 row in set (0.000 sec)

ERROR: No query specified

MariaDB [8374_activemq]> SHOW TABLE STATUS LIKE 'ACTIVEMQ_MSGS' \G;
*************************** 1. row ***************************
            Name: ACTIVEMQ_MSGS
          Engine: InnoDB
         Version: 10
      Row_format: Dynamic
            Rows: 0
  Avg_row_length: 0
     Data_length: 16384
 Max_data_length: 0
    Index_length: 81920
       Data_free: 0
  Auto_increment: NULL
     Create_time: 2023-02-17 00:25:26
     Update_time: NULL
      Check_time: NULL
       Collation: utf8_general_ci
        Checksum: NULL
  Create_options:
         Comment:
Max_index_length: 0
       Temporary: N
1 row in set (0.000 sec)

ERROR: No query specified

MariaDB [8374_activemq]>

SHOW CREATE TABLE ACTIVEMQ_MSGS \G;
*************************** 1. row ***************************
       Table: ACTIVEMQ_MSGS
Create Table: CREATE TABLE `ACTIVEMQ_MSGS` (
  `ID` bigint(20) NOT NULL,
  `CONTAINER` varchar(250) DEFAULT NULL,
  `MSGID_PROD` varchar(250) DEFAULT NULL,
  `MSGID_SEQ` bigint(20) DEFAULT NULL,
  `EXPIRATION` bigint(20) DEFAULT NULL,
  `MSG` longblob DEFAULT NULL,
  `PRIORITY` bigint(20) DEFAULT NULL,
  `XID` varchar(250) DEFAULT NULL,
  PRIMARY KEY (`ID`),
  KEY `ACTIVEMQ_MSGS_MIDX` (`MSGID_PROD`,`MSGID_SEQ`),
  KEY `ACTIVEMQ_MSGS_CIDX` (`CONTAINER`),
  KEY `ACTIVEMQ_MSGS_EIDX` (`EXPIRATION`),
  KEY `ACTIVEMQ_MSGS_PIDX` (`PRIORITY`),
  KEY `ACTIVEMQ_MSGS_XIDX` (`XID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci
1 row in set (0.000 sec)

ERROR: No query specified

Comment: Additional DB information request, please.
RAM size, # cores, any SSD or NVME devices on MySQL Host server?
Post TEXT data on justpaste.it and share the links.
From your SSH login root, Text results of:
A) SELECT COUNT(*) FROM information_schema.tables;
B) SHOW GLOBAL STATUS;    after minimum 24 hours UPTIME - if possible.
C) SHOW GLOBAL VARIABLES;
D) SHOW FULL PROCESSLIST;
E) STATUS;  not SHOW STATUS, just STATUS;
G) SHOW ENGINE INNODB STATUS;
for server workload tuning analysis to provide suggestions.
Answer: Consider
OPTIMIZE table 8159_activemq.ACTIVEMQ_MSGS
to resolve the 'no gap' message in SHOW ENGINE INNODB STATUS deadlock reporting.
And provide additional for workload analysis when time permits.
Comment: please look at the table status and we are already using InnoDB. do you suggest any optimization other than using InnoDB for the table ?
Comment: @unknown Please post TEXT results of SHOW CREATE TABLE activemq_msgs;  after USE schema_name;  If you could post the additional data requested, a workload analysis could be completed for your instance to provide some suggestions to improve performance.
Comment: added the output of SHOW CREATE TABLE activemq_msgs;
Comment: With the currently available information, there are NO rows in ACTIVEMQ_MSGS.  Are you familar with GENERAL LOG content and turning the General Log on during your testing to get more details on what MySQL is trying to do for you?  Turn off the General Log as SOON as POSSIBLE to avoid filling your media and keep your General Logs for a reasonable length of time. Send to flash drive and free the space on your media, please.  Then you can study the General Log at your leisure.


How can I monitor VNC via Nagios?

Question: I have a number of remote sites which have VNC running on a few computers for support purposes.  They are (obviously) only available on our internal network.
I am using Nagios to keep track of all the systems in the network and I want to have it check to make sure the VNC server is running on the appropriate hosts.
There is a 'check_vnc' plugin available here but it relies on VNC Snapshot which I don't want to use.  Certainly I could use it, but it adds more complexity and dependency, which I want to avoid.
It seems simpler to just use check_tcp to make sure I get the proper response to a connection request for VNC, e.g. port 5900, send a connect string, get back framebuffer info.  My real question, I suppose, is this:  What is the 'proper' generic connect string for VNC (I use both UltraVNC and RealVNC) and what is the expected response?
If it's really easier to use the VNC Snapshot and check_vnc, let me know.  I just can't imagine that a string of text isn't easier, faster, and less bandwidth intensive to monitor.
Answer: This should work for vnc:
check_tcp -H $HOSTADDRESS$ -p 5900 -w 5 -c 8 -e "RFB"
Comment: It works!  Thanks a lot.  You've save me a lot of horsing around.

How can I monitor VNC via Nagios?


Python: Compare lists, perform operation, create new list

Question: I am currently studying python and have run into a problem I can't seem to find a solution for. I hope some of you may help me.
The problem is as follows:
I have three lists, each with 3000 elements. The first five elements of each list are as follows:
A = [100, 101, 100, 99, 100...]
B = [100, 102, 101, 98, 101...]
C = [100, 103, 100, 99, 100...]
I need to create a new list called D with the following rules:
For each element of list D, I need Python to first choose between lists A, B and C for the one with the lowest value for that same index. That is, to determine what will be the 0eth element of the list D, Python first needs to choose between lists A, B and C for the one with the smallest element for that index. Whenever there are more that one list with the same smallest value for the index in question, Python needs to choose randomly between those lists.
In the case of the 0eth element of List D, because all three reference lists have the same 0eth element (namely 100), Python needs to randomly pick between the three.
Let's say Python randomly picks list B. Then, to determine the 0eth element of list D, python will divide the last element of list B by its 0eth element. Lets say the last element of list B was 130. In this case, the 0eth element of list D will be 1.3.
Continuing, for list D's index=1 element, Python will immediately choose list A, because it has the lowest index=1 element. Then, python will divide the last element of list A by the list A's index=1 element. Let's say it was 145. In this case, list D's index=1 element will be 145 / 101 = 1.4356
In the end, list D will also have 3000 elements.
Does anyone know how to code to solve this?
Thank you.
Comment: Next time, please provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) of any attempts you've made to try to solve your problem. That aside, consider using python's inbuilt [`zip()`](https://docs.python.org/3.3/library/functions.html#zip) function
Answer: I think the downvotes are justified because you did not provide any code at all to show us what you tried so far, so that we know where you are stuck with your code. Also i think the way you wrote the requirements is a bit confusing (0eth probably means nth sometimes?). Anyways, this is not hard to do - All you need is zip, min, a list comprehension and random.choice and you can work with n lists:
from random import choice

a = [100, 101, 100, 99, 100, 110]
b = [100, 102, 101, 98, 101, 130]
c = [100, 103, 100, 99, 100, 120]

# In order to work properly with indexes
# we should rely on a list of lists
lists = [a, b, c]
# Collect the last value of each sublist in lists
last_values = [sublist[-1] for sublist in lists]
# Your d list
result = []

# zip combines each element from each given list on the same index
# splat the sublists with * (keeps the proper order of sublists)
for zipped in zip(*lists):
  # min selects the lowest value in the zipped values
  lowest = min(zipped)
  # find all occurences of the lowest value within zipped values
  indexes = [i for i, v in enumerate(zipped) if v == lowest]
  # pick a random index (len(indexes) doesn't matter)
  random_index = choice(indexes)
  # Divide the last value in the picked list with the lowest value
  value = last_values[random_index] / lowest
  # And add to result
  result.append(value)

print(result)


Why is regex being lazy instead of greedy in this case?

Question: This is a snippet of a complex regex:
/\x87([\xA6-\xBf]|\xA6\xF0\x9F)/x

Why is it stopping and returning  \x87\xA6 instead of \x87\xA6\xF0\x9F
when matching against a string containing \x87\xA6\xF0\x9F  ?
I thought regex was greedy by default and would try to consume the longest pattern?
Or is that only for the * and + operators?
Is there any way I can force it to look for the longest pattern? Using word boundaries is not an option in this case unfortunately.

eta: apparently it works as desired if I move the shorter pattern to the end
/\x87(\xA6\xF0\x9F|[\xA6-\xBf])/x

is it really that simple and regex is sensitive to order of the pattern?
Answer:
I thought regex was greedy by default and would try to consume the longest pattern?

"Greediness" refers to the preference of the quantifiers (?, *, +, etc.) for repeating more times rather than fewer. That's not exactly the same as consuming the longest substring, though of course it usually works out that way.
The alternation operator | also has a preference: it prefers to match what's before the |, instead of what's after it. You can fix your pattern by writing:
/\x87(\xa6\xF0\x9F|[\xa6-\xbf])/x

Comment: @ck_: Indeed, with an 80-line pattern, it is very easy to introduce a bug. Unfortunately, there's no relevant concept of "robustness"; if you tell the regex engine that you prefer A over B, there's no way that it can tell that you actually prefer B over A. (More generally, there's no way that a programming language can be "robust" against programmer error and automatically detect and fix your bugs.) I'd suggest eliminating this pattern, e.g. by breaking it into many smaller patterns.
Comment: Excellent answer!  The distinction between greedy *quantifiers* and greedy *regexes* is one that doesn't get mentioned often enough.  Like the meaning of singleline and multiline modes, regex users can go their whole careers without really understanding it.
Comment: Ah you posted just as I was tinkering and discovered that order matters. But it makes me worry as this particular regex pattern is 80 lines long and very easy to make a human mistake of putting a shorter pattern before the longer. I don't suppose there is a flag or other trick I can use to make it search more robustly?


Rationale of Rails 5 Join Table Generated Defaults

Question: The Rails 5 command rails g migration create_foo_bar_join_table generates the following migration:
class CreateFooBarJoinTable < ActiveRecord::Migration[5.0]
  def change
    create_join_table :foos, :bars do |t|
      # t.index [:foo_id, :bar_id]
      # t.index [:bar_id, :foo_id]
    end
  end
end

Why does the generator stub out two (bi-directional) indices with composite keys? Also why are they commented out? I'm confused by this and can't find any clear explanation for having these suggested defaults.
Are the above indices more lookup efficient than the ones below?
...
    create_join_table :foos, :bars do |t|
      t.index :foo_id
      t.index :bar_id
    end
...

Comment: I haven't had a chance to look into this deeper, maybe you have already taken a look at https://github.com/rails/rails/blob/master/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb#L25 for more on this?
Comment: Seems the composite indices are specifically for MySQL. Good to know.
Answer: Stumbled on the exact answer reading the docs on has_and_belongs_to_many:

It's also a good idea to add indexes to each of those columns to speed
  up the joins process. However, in MySQL it is advised to add a
  compound index for both of the columns as MySQL only uses one index
  per table during the lookup.

https://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many


Como converter uma string para um inteiro em um programa socket?

Question: Aqui está um trecho do código:
def CriarServer(self):
     Host = self.Txt1.get()
     Port = self.Txt2.get()

     sockobj = socket(AF_INET, SOCK_STREAM) #Erro

     sockobj.bind((Host, Port))
     sockobj.listen(5)

     while True:

        data = conexão.recv(1024)

        if not data: break

        conexão.close()

Como eu estou em um programa em Tkinter, pedi ao Python para que ele pegasse o texto de duas entradas, uma de porta e outra de host, porém quando se pega o texto de uma Form, ele vem como uma string e o socket bind só aceita números inteiros para fazer a atribuição. Como converto a string para int?
Erro:

sockobj.bind(int(Host, Port))TypeError: 'str' object cannot be interpreted as an integer.
Comment: Tinha vária pessoas dando negativo sem motivo algum.
Comment: Muito obrigado, quando der o tempo eu aceito a resposta.
Answer: Prsesumo que precises que o Port seja um inteiro, então faz:
Host = int(self.Txt1.get())

int()
Assim tens de ter a certeza que o input vai ser númerico, caso contrário isso vai gerar erro ValueError: invalid literal for int() with base 10:...
Podes certeficar-te que "há de ser inteiro" e adaptar ao teu código assim:
Host = None
while not isinstance(Host, int):
    try:
        Host = int(input('número'))
    except ValueError as err:
        print('numro incorreto')

O erro que colocaste num edição recente, já depois desta resposta que era acerca de outra questão, acontece porque estás a tentar tranformar em inteiro duas variáveis, int(Host, Port), não pode ser porque no metodo bind entra como argumento um tuple (host, port) em que o host é uma string e o port é um inteiro, ou seja, tens de fazer só:
sockobj.bind((Host, Port))

Em que port será um inteiro, com a maneira que coloquei acima, Host = int(self.Txt1.get())


Symmetric C* property

Question: What can be said about elements $a$ of a C*-algebra which fulfil the 'symmetric C* property'
$$\| a^\ast a+ aa^\ast\|=2\| a\|^2$$
I'd guess that this is not a general property, but I don't have a good idea which elements (except for self-adjoint and normal ones, of course) should satisfy this.
Answer: If you assume that $a^*a$, $a a^\ast$ are compact (this is just to avoid working with continuous spectrum), the equality above holds iff there is an eigenvalue $\lambda$ with maximal norm $| \lambda | = \|a\|^2$ such that the eigenspaces of $\lambda$ for $a^\ast a$ and $a a^\ast$ have nontrivial intersection. That already give you that the condition is pretty rare.
Indeed, two projections $p,q \in \mathcal{K}(\ell^2)$ satisfy that there is a partial isometry $a$ such that $p = a^\ast a$ and $q = a a^\ast$ iff $\dim(p\ell^2) = \dim(q \ell^2)$. But you can take $p \perp q$ and in that case:
$$
\| a^\ast a + a a^\ast \| = \max \{ \| a^\ast a \|, \| a a^\ast\| \} = 1.
$$
Comment: Highly related: https://math.stackexchange.com/questions/2700980/c-algebras-when-is-there-equality-in-the-triangle-inequality
Comment: Are you working with the GNS representation here? Or what do you mean by *compact elements* and *eigenspace*?
Comment: Yes, I was assuming that $A \subset B(\ell^2)$. I just use that $\| a^\ast a + a a^\ast \| = \sup \langle a^\ast a + a a^\ast \xi, \xi \rangle$, where $\xi$ the unit ball and and that the supremum is attained for compact positive operators. You can work intrinsically by changing $x \mapsto \langle x \xi, \xi \rangle$ by a state $\varphi$ that has to satisfy $$\varphi(a^\ast a) = \varphi(a a^\ast) = \| a\|^2$$.

Symmetric C* property


How to redirect a user to mobile site?

Question: I have created a Drupal 7 site with all required functions. As per the requirement I have to create a mobile theme for this site, which I did effectively. Now problem is I need to redirect the user to the mobile site if the request is made from a mobile. If the request is made from computer he should be redirected to the main site.
Thanks in advance.
Comment: you could see my [answer](http://drupal.stackexchange.com/questions/32464/the-question-of-enable-mobile-switch/32494#32494) for the same issue :-)
Answer: There are already existing modules to do it like mobile_tools. Where u can set what theme to use for mobiles. and redirection on mobile detection also.
Comment: @slassenger - check this link for 7 version of mobile tools http://drupal.org/node/416196/release
Comment: @slassenger - Welcome :)
Comment: can u say few modules that can work with D7 as well.
Answer: Mobile Tools is a good option, or you may use theme_key just as well.
Regards.
Comment: thanks for ur reply:):) Hacker's answer solved the problem. But still need to work with D7.

How to redirect a user to mobile site?


How do you resize a bar chart created using matplotlib?

Question: I've found other topics similar to this, but I'm finding anything that works specifically for me, so I'm wondering what I'm doing wrong.
I've got the following code:
# Plot weather vs. # of accidents on grouped-bar-chart for each year
data_chart = dataset2.plot.bar()
data_chart.set_xlabel('Weather Condition')
data_chart.set_ylabel('No. of Accidents')
data_chart.set_title('Annual Number of Accidents per Weather Condition')

I've tried using the two following bits of code to increase the size of my chart:
data_chart.plot(figsize=(10,5))

plt.figure(figsize=[10,5])

but neither of them have worked.
Thank you for your help!
Comment: `fig, ax = plt.subplots(figsize=(10,5))`, `dataset2.plot.bar(ax=ax)`.
Comment: Does this answer your question? [Inconsistency when setting figure size using pandas plot method](https://stackoverflow.com/questions/42215252/inconsistency-when-setting-figure-size-using-pandas-plot-method)
Comment: Calling `plt.figure(figsize=[10,5])` after you created the plot just creates a new plot.
Comment: Thanks, but I just get ```NameError: name 'ax' is not defined.```  Do I need to import something special to use ax?
Comment: Please see my answer and check if it works. If it doesn't let me know I will help.
Answer: Please try
import matplotlib .pyplot as plt
plt.rcParams["figure.figsize"] = (10,5)
data_chart = dataset2.plot.bar()
data_chart.set_xlabel('Weather Condition')
data_chart.set_ylabel('No. of Accidents')
data_chart.set_title('Annual Number of Accidents per Weather Condition')
plt.show()

Matplot lib defaults **to width, height in inches=[6.4, 4.8]**. set as rcParams["figure.figsize"] = [6.4, 4.8]. So Change them to (10,5)


Is there a difference between == true and != false in swift?

Question: I had this code in my Swift App
func parseJSON() {

    let urlString = "www.websitethatlinkstoJSONfile.com"

    if NSURL(string: urlString) == true {
        let url = NSURL(string: urlString)
        let data = try? NSData(contentsOfURL: url!, options: []) as NSData
        let json = NSData(data: data!)

// more code
However, even though the link actually worked and was true, the if statement was never met and it kept skipping it and moving to else. So I changed the code to
if NSURL(string: urlString) != false

and it worked perfectly. I'm not sure why though?
Comment: `NSURL(string:)` will return true for any string be it a valid url or just radom characters.
Comment: Using guard statements are encouraged in Swift during situations like this to check for nil.  Also you may want to research the Equatable protocol for future reference.
Answer: As already explained in the other answers, comparing the optional
NSURL? against true or false is not what you want, and you should
use optional binding instead.
But why does it compile at all? And how can the result be interpreted?
In NSURL(string: urlString) == true, the left-hand side has the type
NSURL?, and NSURL is a subclass of NSObject.
There is a == operator taking two optional operands:
public func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool

The compiler uses the implicit conversion of Bool to NSNumber
to make that compile.  So your code is equivalent to
if NSURL(string: urlString) == NSNumber(bool: true)

and that will always be false, and
if NSURL(string: urlString) != NSNumber(bool: false)

will always be true, simply because the left-hand side is not a
number.
Here is a demonstration of the effect:
func foo(x: NSObject?) {
    print(x == true, x == false)
}

foo(NSNumber(bool: true))  // true, false
foo(NSNumber(bool: false)) // false, true
foo(NSObject())            // false, false  !!!

The last case is what you observed: Both x == true and x == false
return false.
For classes not inheriting from NSObject it would not compile:
class A { }
let a: A? = A()
if a == true { } // cannot convert value of type 'A?' to expected argument type 'Bool'

Remark: This is another argument for not comparing boolean values
against true or false, i.e.
 if a == true && b == false { ... }

is better written as
 if a && !b { ... }

Applied to your case, you would get a compiler error indicating
the problem:
let urlString = "http://www.websitethatlinkstoJSONfile.com"
if NSURL(string: urlString) {  }
// error: optional type '_' cannot be used as a boolean; test for '!= nil' instead

Comment: Thanks for the awesome explanation! I am new to swift, and I appreciate you breaking this down.
Answer: You don't really want to check for a boolean value when creating a NSURL, but rather make sure the NSURL you create is non-nil. Try wrapping it it in an if let statement like so to make sure whatever URL's you create are non-nil before executing further code.
   let urlString = "www.websitethatlinkstoJSONfile.com"

    if let url = NSURL(string: urlString) {
       if let data = try? NSData(contentsOfURL: url, options: []) {
           let json = NSData(data: data)
       } else {
          //Handle case where data is nil
       }
    } else {
        //Handle case where url is nil
    }

Using if let statements in this way makes sure that the NSURL and NSData objects you are creating are non-nil and valid objects and then you can add an else statement to them to handle cases where your url or data objects are nil. This will save you from unwanted crashes due to force unwrapping with the ! operator.
Comment: When I use ```if let data = try? NSData(contentsOfURL: url, options: []) as? NSData {``` it says Conditional cast from 'NSData' to 'NSData' always succeeds.
Comment: I removed the `as? NSData` from my answer. It was unnecessary casting I had copied from your code.
Comment: This worked! Thank you!!! Now my if and my else is working. Appreciate the help!!
Answer: Yes there is a different take a look at some of the documentation. In this init method it is fallible.

public convenience init?(string URLString: String)

the question mark indicates it is fallible.
So  it will return a NSURL object or nil.
convenience init?(parameter: AnyObject) {
    if parameter == nil {
        return nil
    }
    self.init()
}

So in a specific example like your example. You can test it in playground
let urlString = "100"

if NSURL(string: urlString) == true {
    print("true")
    //Never prints in any circumstance//
}

if NSURL(string: urlString) != false {
    print("true")
    //always prints//
}

if NSURL(string: urlString) != nil {
    print("true")
   //object was created//
}

Comment: `NSURL.init(string:)` returns `NSURL` object or `nil`. It does not return `false`.
Comment: You should note that `NSURL(string: urlString) != false` is always true, even when `NSURL(string: urlString)` returns `nil`. In fact, it's equivalent to `NSURL(string: urlString) != NSNumber(bool: false)`. Test with giving `urlString` an invalid url.
Comment: Thats why said "in a way" to help them understand
Comment: "in a way" would not be suitable here. Because comparing `NSURL?` to `false` can never be considered to be "equal".
Comment: Thank you for explaining! I'm new to Swift so it can be pretty confusing.
Comment: @cheesydoritosandkale you may also be interested in looking at https://developer.apple.com/reference/uikit/uiapplication/1622952-canopenurl
Comment: I'm using Cocoa for OS X app development. I have been trying to use the API, but it can be pretty confusing hehe :)
Comment: @cheesydoritosandkale http://stackoverflow.com/questions/26704852/osx-swift-open-url-in-default-browser
Answer: The == operator checks whether both side value is equal or not.For example:
var data:Int = 6
if data == 5 {
   //if this block is executed that means `data` is exactly equal to 5
   //do something
}
else {
    //In this situation, this block of code will be executed.
   //if this block is executed that means data is anything other than 5.
   //do something
}

The != operator checks that two values are not equal to each other.For example:
var data:Int = 6
if data != 5 {
    //In this situation, this block of code will be executed.
   //If this block is executed that means `data` is anything other than 5.
   //do something
}
else {
   //if this block is executed that means data is exactly equal to 5.
   //do something
}

In your case code if NSURL(string: urlString) == true checks that if NSURL(string: urlString) return true then it should excute if block otherwise else block.
NSURL(string: urlString) is convenience initializer which creates NSURL object and returns. In case if it fails to do so then it returns nil
In any case, it does not return either true or false.So when you compare this with true it always fails and goes to else block.
And when you check that it is not equal to false (!= false) becomes true because NSURL(string: urlString) returning NSURL object and that is not equal to false.
So if you want to check that whether NSURL object is created or not you can check whether the return value is nil or not.
if NSURL(string: urlString) != nil {
   //Object is created successfully.Now you can do whatever you want this object.
}
else {
   //It failed to create an object.
}


Get percentage variation of numbers from two dataframes based on column positioning

Question: I have two dataframes:
df1=pd.DataFrame({'Product':("A","B","C"),"Data":(1,2,3)})
df2=pd.DataFrame({'Product':("A","B","C"),"Data":(2,4,6)})

I want to get the percentage variation numbers of the columns.
I have tried the below code:
data1_i=df1.set_index(["Product"])

data2_i=df2.set_index(["Product"])

data_diff=(data2_i-data1_i)/data1_i*100
data_diff.reset_index(inplace=True)

Output obtained:
    Product Data
0   A   100.0
1   B   100.0
2   C   100.0

I am able to do this since the column name are same. How to get the variation if I have different column names like below:
df1=pd.DataFrame({'Product':("A","B","C"),"Data":(1,2,3)})
df2=pd.DataFrame({'Product':("A","B","C"),"Data_new":(2,4,6)})

I wont be able to use rename functions as I have lot of columns. I want to get the variation on numbers based on column positioning. Any pointers so that I can get started
Comment: Some problem with solution?
Answer: You can select columns by position with iloc:
df1=pd.DataFrame({'Product':("A","B","C"),"Data":(1,2,3)})
df2=pd.DataFrame({'Product':("A","B","C"),"Data_new":(2,4,6)})
data1_i=df1.set_index(["Product"])
data2_i=df2.set_index(["Product"])

data_diff=(data2_i.iloc[:, 0]-data1_i.iloc[:, 0])/data1_i.iloc[:, 0]*100
data_diff = data_diff.reset_index(name='Data')
print (data_diff)
  Product   Data
0       A  100.0
1       B  100.0
2       C  100.0

Comment: @jezarel Thank you. But it works if you have variation of numbers for one column, in this scenario you are able to use reset_index.
It gives:TypeError: Cannot reset_index inplace on a Series to create a DataFrame, if I have multiple columns
Comment: Then use `data_diff = data_diff.reset_index()`, `data_diff = data_diff.reset_index(name='Data')` working only with one column


Proof that Integral is continuous in given metric space

Question: I am supposed to show that the following statement is true:

For $p \in [1, \infty]$ the projection of $I:(C([a,b]), \|\cdot\|_p)
> \rightarrow (\mathbb{R},|\cdot|)$ defined as
$$I(f) = \int_{a}^{b}f(x) dx,$$ is continous.

I tried proving this statement with the $\epsilon$-$\delta$-criteria, since this was a hint I was given, sadly I couldn't really find a way to define my $\epsilon$ and my $\delta$ so I tried it with another approach.
In my script I found a very handy Satz, though. Which says:

Satz 4.29: Let $(X, \|\cdot\|_X)$ and $(X', \|\cdot\|_{X'})$ be normed
  vector spaces over $\mathbb{K}$, where $A:X\rightarrow X'$ is linear,
  then the following statements are equivalent:

A is continous
A is continous at 0
There exists a $C > 0$ with $\|A(x)\|_{X'} \leq C\|x\|_X$ for every $x \in X$

So I tried proofing the upper statement with the Satz 4.29.
First of all I can say that $I(f)$ is linear since we already proved that Integrals are linear.
Then I claimed that $$\forall p \neq \infty:||f||_{p} \leq ||f||_{\infty}$$
Which is easy provable since the supremum-norm is just defined as the supremum of every function, thus being always greater or equal to any given $p$-norm.
With that I finally applied Satz 4.29:
$$|I(f)|\leq\int_{a}^{b}|f(x)|dx \leq (b-a)||f||_{\infty} \quad with \quad \forall p \neq \infty:||f||_{p} \leq ||f||_{\infty}$$
My questions:

Am I already done with the proof that way?
How is this solvable with the $\epsilon$-$\delta$-criteria? I think that this is a way smoother way to solve it, but I couldn't find a way

Thanks in advance.
Answer: You can show that for each $p$ there exists a constant $C_p>0$ such that $|I(f)|\le C_p\|f\|_p$ for all your $f$'s, as you state in Satz 4.29. You showed it for $p=\infty$. You still need to show it for $p\neq\infty$. You can apply Hölder's inequality to $\int_a^b1|f(x)|dx$. You can apply Hölder's inequality to a $\epsilon$-$\delta$ argument bypassing Satz 4.29 (if you know that $|\int f-\int g|\le \int|f-g|$).
Comment: Thank you very much. I forgot about the Hölder Inequality. Will try it that way.


Ftp relative path in php

Question: I have a problem that I don't know how to solve. Let me explain it...
Directory structure:
-/public_html/lab/
-/public_html/lab/upload.php
-/public_html/lab/plugins/

I am really newbie with php+ftp, but I have the idea that FTP does not use "absolute root path" (/home/user/public_html/), instead it use "absolute user path" according to the user in question (/public_html), right?
Well, in the upload.php I have the code where the FTP class take a file temporally stored at the same folder where upload.php reside (/public_html/lab/) and then try yo move it to /public_html/lab/plugins/ folder.
FTP class receive a path where you want to move the file. But, I don't want to pass the path like absolute, I want to avoid this:
ftp->move('the-file.zip', '/public_html/lab/plugins/');

I would like to do something like this:
ftp->move('the-file.zip', '../plugins/');

But the code above looks like is not valid. So, how can I reproduce that result?
Comment: what library are you using to make the FTP connection? PHP's native FTP commands do not have a "move" method, AFAIK. http://us2.php.net/manual/en/book.ftp.php
Comment: Well, I'm using Codeigniter. But is it relevant the class/method to manage the path?
Comment: I was thinking you could change your directory first ftp->changedir per http://apigen.juzna.cz/doc/EllisLab/CodeIgniter/class-CI_FTP.html but the more I look at it, is FTP really something you need? Why not just have upload.php move the file?
Comment: @zamnuts, PHP's native FTP could resolve it? 5 spended hours with no results. u.u
Answer: You can use php relative path Like for moving file to your FTP location
$_SERVER['DOCUMENT_ROOT'] ."/lab/plugins/" ;

Answer: Rather than FTP which is designed for communication between two different hosts, consider moving the file via move_uploaded_file in upload.php:
move_uploaded_file($_FILES['uploaded']['tmp_name'],'./plugins/'.$_FILES['uploaded']['name']);

Once the file is uploaded via the PHP script, the temp file will be available in the _FILES superglobal under $_FILES[$inputFieldName]['tmp_name']. If you're using the example I gave, make sure to clean the "name" attribute before, since it will allow for client-side injection and leave a huge security hole in the application.
Comment: in retrospect i don't think this answer is helpful, but it does offer another perspective on file management.

Ftp relative path in php


how to convert AVFrame to texture used by glTexImage2D?

Question: as you know that AVFrame has 2 property:pFrame->data, pFrame->linesize. After i read frame from video /sdcard/test.mp4 (android platform),  and convert to RGB AVFrame vice:
<code>img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height,
                   pCodecCtx->pix_fmt,
                   target_width, target_height, PIX_FMT_RGB24, SWS_BICUBIC,
                   NULL, NULL, NULL);
            if(img_convert_ctx == NULL) {
                LOGE("could not initialize conversion context\n");
                return;
            }
            sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameRGB->data, pFrameRGB->linesize);
</code>
I get pFrameRGB after converted. I need to texture it in opengl by using glTextImage2D:
<code>// Create The Texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 256, 256, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
</code>
// i don't know data in here is pFrameRGB->data or not,if not, how to convert it to approriate format for glTextImage  so i can display video in opengl, using AVFrame and gltextImage2D. All helps from u are very appreciated.
Answer: The actual pixel data for the pFrameRGB is in pFrameRGB->data[0]... In your glTexImage2D call use GL_RGBA instead of GL_RGB. Thats what I did to get it working anyway. Assuming you have your texture and vertex coordinates created correctly then that should get it working. I can post some code examples if that doesn't help.
Comment: Can you post some code example using pFrameRGB->data[0] in GL_RGBA to texture, i also do that as:     sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameRGB->data, pFrameRGB->linesize);
data=(char*)malloc(pFrameRGB->linesize[0]*target_height)
  memcpy(data,pFrameRGB->data,pFrameRGB->linesize[0]*target_height);
*w=320,*h=240;
my function return data, widht and height to glTextImage2D:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, *w, *h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
but i don;t get any appearing image, am i wrong
Comment: Hi, could you post some code examples Kieran? I'm just getting a blank screen, in my SwsContext I'm changing the 854x480 input to be converted to a RGB24 at 512x256 (for the power of 2 requirement) then in sws_scale() I convert and put in pFrameRGB and then my glTexImage2D looks like this: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 512, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, pFrameRGB->data[0]); but I'm getting nothing, completely blank screen. Any ideas?
Answer: Two things: (1) is target_width and target_height powers of 2? If not, you'll get a blank screen. You need to scale the picture to a power of 2. (2) where it says "data" in glTexImage, you need to use pFrameRGB->data[0] as Kieran pointed out.
One more thing, you don't need to use RGBA (unless it's faster. I haven't tested it out). If you do, you change the ffmpeg target format to PIX_FMT_RGBA and then change both instances of GL_RGB to GL_RGBA.
Other than that, I don't see anything wrong with your code. I have almost the same exact code and it runs just fine.


Is there a phenomenon like this?

Question: It's like the mean of every part increases, but the overall mean decrease; or the mean of a group is larger in every part but is smaller in all samples; or something like this.
I remember there is a name for this phenomenon like this (it may not be accurate) but my impression is very vague and I cannot remember it clearly.
Comment: [I think you mean Simpson's paradox.](https://en.m.wikipedia.org/wiki/Simpson%27s_paradox)
Comment: @Dave Thank you very much, I still have a simple question. If group A has a larger mean in every part than group B but has a smaller mean overall, then which group is better? Assuming the larger the better.
Comment: I suggest posting that as a separate question that includes either a drawing or a small data set (can be made up), because I do not totally follow what you mean.
Comment: It's like [everything's amazing now and nobody's happy](https://youtu.be/nUBtKNzoKZ4)
Answer: You are thinking of (one version of) Simpson's paradox.  You can find many threads about it on the site.
Comment: Thank you very much, I still have a simple question. If group A has a larger mean in every part than group B but has a smaller mean overall, then which group is better? Assuming the larger the better.
Comment: @user900476, you need to read through some of the threads we have on the topic. I have a related answer [here](https://stats.stackexchange.com/a/78264/7290).

Is there a phenomenon like this?


How to load field configurations in code

Question: I have defined fields using the UI, and some more fields using YAML files in my custom module, e.g.:
The field storage is defined in field.storage.node.my_heading:
langcode: en
status: true
dependencies:
  enforced:
    module:
      - my_module
id: node.my_heading
field_name: my_heading
entity_type: node
type: string
settings: {  }
module: core
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

The field instance (which attaches a field to an entity) is defined in field.field.node.my_content_type.my_heading:
langcode: en
status: true
dependencies:
  config:
    - field.storage.node.my_heading
    - node.type.my_content_type
id: node.my_content_type.my_heading
field_name: my_heading
entity_type: node
bundle: my_content_type
label: 'Heading'
description: 'An optional heading'
required: false
translatable: true
default_value: {  }
default_value_callback: ''
settings: {  }
field_type: string

After installing this custom module, how do I get the field configuration in code?
Answer: The terminology is a bit confusing (as usual with Drupal), but here goes:
Field storage configurations are defined by FieldStorageConfig. To load one, do this:
$field = Drupal::entityTypeManager()->getStorage('field_storage_config')->load('node.my_field');

Field instance configurations are defined by FieldConfig. To load one, do this:
$field_instance = Drupal::entityTypeManager()->getStorage('field_config')->load('node.my_content_type.my_field');

Comment: Helpful.
How to read the field default value?
Comment: @RajeshVishwakarma The default value is part of the field instance configuration. The code to load that is shown in my answer.
Answer: There is shorter version for @rudolfbyker's answer
For field storage:
use Drupal\field\Entity\FieldStorageConfig;

$field = FieldStorageConfig::loadByName('node', 'my_field');

For field instance:
use Drupal\field\Entity\FieldConfig;

$field_instance = FieldConfig::loadByName('node', 'my_content_type', 'my_field');

Those loadByName() static methods are actually wrappers to logic from @rudolfbyker's answer.


OpenVPN and one way pings

Question: Network configuration
I have set up a network:

Appropriate ports of computers in 192.168.87.0/24 are forwarded on TP-LINK router to be seen "all over the world".
IP forwarding in enabled on OpenVPN server.
I am able to connect from OfficeB from client1 to OpenVPN server in OfficeA. client1 and server see each other -- they reply for pings (both in 192.168.87.0/24 and 10.8.0.0/24 network), send data, create connections (i.e. ssh).
Routing table on TP-LINK router (a.b.c.d is a WAN IP):
DST             MASK                GATEWAY         IFACE
a.b.c.d         255.255.255.255     0.0.0.0         WAN
192.168.87.0    255.255.255.0       0.0.0.0         LAN & WLAN
10.8.0.0        255.255.255.0       192.168.87.2    LAN & WLAN (route added by hand)
220.127.116.11       255.0.0.0           0.0.0.0         LAN & WLAN
0.0.0.0         0.0.0.0             a.b.c.d         WAN

The problem
And now... From ANY computer in 192.168.87.0/24, I can ping 10.8.0.6. Unfortunately 10.8.0.6 can ping ONLY 87.1, 87.2.
But... 10.8.0.6 would start to ping a computer in 87.0/24 (for example 87.104) only if I pinged firstly from this computer to 10.8.0.6:

10.8.0.6: ping 192.168.87.104 -- failed, time exceeded.
192.168.87.104: ping 10.8.0.6 -- ok.
10.8.0.6: ping 192.168.87.104 -- ok.

What I've checked
I've checked with tcpdump, that 192.168.87.104 DOES always get requests send replies for pings from 10.8.0.6. But the replies seem not to pass thru gateway TP-LINK router back to 10.8.0.6 -- I cannot see them with tcpdump on OpenVPN server on both interfaces.
I've also checked, that if I added a route on 192.168.87.104:
(1) route add 10.8.0.0 netmask 255.255.255.0 gw 192.168.87.2

then 10.8.0.6 would always get a ping reply, even if I hadn't pinged it from 192.168.87.104 before.
Another thing I've found out: pinging from 192.168.87.104 to 10.8.0.6 adds to routing cache (route -C) an entry (1). And in the ,,first ping'' (before the entry is added) I get:
PING 10.8.0.6 (10.8.0.6) 56(84) bytes of data.
64 bytes from 10.8.0.6: icmp_req=1 ttl=127 time=37.0 ms
From 192.168.87.1: icmp_seq=2 Redirect Host(New nexthop: 192.168.87.2)
64 bytes from 10.8.0.6: icmp_req=2 ttl=127 time=93.0 ms

I read, that this was a normal behavior, because the gateway to 10.8.0.0 was in the same network segment. And after icmp redirect host a new entry was created in routing cache.
The TP-LINK router, in web configuration panel, has a check-box SPI Firewall - Stateful Packet Inspection. Disabling it does not solve the problem.
My question
I can't understand why a ping reply 192.168.87.104 > 10.8.0.6 does not pass thru TP-LINK router despite TP-LINK router knows a route to 10.8.0.0 and ping request from 192.168.87.104 to 10.8.0.6 does pass.
So my question is: what is the reason? Is there anything I can do to solve the situation (except for adding a route (1) on each computer in OfficeA...)? I, personally, think that a problem is in TP-LINK router.

OpenVPN server configuration file:
port 1194
proto udp
dev tun

ca keys/ca.crt
cert keys/server.crt
key keys/server.key
dh keys/dh1024.pem

server 10.8.0.0 255.255.255.0
push "route 192.168.87.0 255.255.255.0"

client-to-client

keepalive 10 120
comp-lzo

persist-key
persist-tun

Answer: My guess is that the TP-LINK is initially dropping the ping replies from .87.104 to .0.6 because of a stateful firewall rule. Notice that when .0.6 pings .87.104, the TP-LINK router never sees the ping request packets. From the point of view of a stateful firewall, it is perfectly reasonable to drop ping replies if it never saw the original ping requests going in the opposite direction. Later, after .87.104 has sent some ping requests to .0.6, the firewall can allow ping replies from .84.104 to .0.6, since it has seen .87.104 initiate communication with .0.6 recently.
It may be possible to modify the TP-LINK's firewall rules. But since it is a "budget" brand router, I suspect your options will be limited to something like a "Stateful Firewall on/off" check-box. Or you may not even get that.
One possible solution is to add a second NIC to the Debian OpenVPN server, and make it Office A's internet gateway router. That way, the default gateway route on Office A clients will also work for 10.8 traffic, and you won't have to add an extra entry to all clients' routing tables. And as an added bonus, you will have the opportunity to use iptables to tailor your firewall rules to your heart's desire.
Comment: Yes, this TP-LINK has checkbox `SPI Firewall - Stateful Packet Inspection`. I tried (I forgot to mention it in my Q.) to turn of that `SPI` -- but the problem still existed. And I also thought about second NIC :). Thank you very much: you've confirmed my ideas:) BTW. I've just setup the connection A-B with OpenVPN Ethernet Bridging (`dev tap`)-- it's working perfectly now.

OpenVPN and one way pings


Show that the conclusion may fail if the condition: $\lim \int f_n \, d\mu\lt +\infty$ is dropped.

Question: Suppose that  $(f_n)\in M^+(X, X)$ and $(f_n)$ converges to $f$, and that $$\int f \, d\mu=\lim \int f_n \, d\mu\lt +\infty,$$ we have the conclusion that $$\int_E f \, d\mu=\lim \int_E f_n \, d\mu$$ for each $E\in X$
Note that $M^+(X, X)$ denote the collection of all extended real-valued $X$-measuable functions on $X$
I already know how to prove the above claim, but could someone show that the conclusion may fail if the condition: $\lim \int f_n \, d\mu\lt +\infty$ is dropped. Thanks.
Answer: Define
$$ f_n = \chi_{[-n,0]} + \chi_{[n,n+1]},f = \chi_{]-\infty,0]}
$$
then $f_n \to f$ pointwise, and $\int f\,d\lambda = \lim \int f_n\,d\lambda$. (Here $\lambda$ is Lebesgue measure on $\mathbb{R}$).
But if you choose $E = [0,\infty[$...
Comment: Thanks, so if the functions are defined in this way, does it mean that $\lim \int f_n\,d\lambda = +\infty$? Also, could you explain further what happens when $E = [0,\infty)$?
Comment: @user3029 $\int_E f_n\,d\lambda = 1$ for all $n$, while $\int_E f\,d\lambda = 0$. To see this, try writing out the explicit expression for $\int_E f_n\,d\lambda$.


Add upload photo or file field to opencard 1.5.X

Question: How can I add a custom image or file upload field to opencart customer registration page?
I use opencart as mijoshop (a joomla component).
Answer: you can get idea from catalog/product.tpl & catalog/product.php


sorting a while function

Question: I have a purchase log in my webshop admin, one costumer buy many products, all products are marked with SKU and i want to sort and group my purchase log by sku.
Is there any way to sort this and group them?
It purchase log SKU could look like this:
27318
15277
14065
6236
vild-100
N/A
blomsterkasser-40g
16694
7147
24608

and the sorted version i am looking for:
6236
7147
14065
15277
16694
24608
27318
blomsterkasser-40g
vild-100
N/A

Here is the code:
private function purchase_log_cart_items() {
while( wpsc_have_purchaselog_details() ) :
wpsc_the_purchaselog_item(); ?>

<?php echo wpsc_purchaselog_details_quantity(); ?> x
<?php echo wpsc_purchaselog_details_name(); ?>
<?php echo wpsc_purchaselog_details_SKU(); ?>

<?php
echo wp.....

Comment: @kuh-chan That probably doesn't work since 'N/A' is the last entry in the list.
Comment: have you tried `sort`?
Answer: You can do it with usort and a custom sort function:
$array = [
    27318,
    15277,
    14065,
    6236,
    'vild-100',
    'N/A',
    'blomsterkasser-40g',
    16694,
    7147,
    24608
];

usort($array, function($left, $right) {
    // else 'blomsterkasser-40g' would be the first entry
    $left = (string) $left;
    $right = (string) $right;
    // always put 'N/A' on the last position
    if($left == 'N/A' && $right == 'N/A') {
        return 0;
    }else if($left == 'N/A') {
        return 1;
    } else if($right == 'N/A') {
        return -1;
    }

    return $left <=> $right;
});

var_dump($array);

Working code: https://3v4l.org/2K5sO

sorting a while function


Given the set of all polygons with m sides and perimeter 1, why is there an element with maximal area?

Question:
The set of all polygons with $m$ sides and perimeter $1$ has  an element with maximal area.

I read this fact in a book, and the reference was in German. Does anyone here know?
I know how to prove that the maximal area polygonal must be regular.
Comment: If the maximal area polygon must be regular, then the regular polygon in the set of all polygons with m sides and perimeter 1 is an element with maximal area.
Answer: By translation invariance, you can assume one of the vertices is $(0,0)$. Then the rest are in the closed unit disk $D$. Encoding the polygon as a finite sequence of vertices, you can identify it with a point in $D^m$. Clearly, $D^m$ is a compact set. It remains to show that the area of polygon is a continuous function of the sequence of vertices $P_i$. This can be done, for example, by writing the area in terms of 2D cross-products:
$$
A = \frac12 \sum_i ({P_{i+1}P_i} \times OP_i) \tag{1}
$$

By 2D cross product of two vectors $\langle x_1,y_1\rangle$ and $\langle x_2,y_2\rangle$ I mean the determinant
$$\begin{vmatrix} x_1& y_1 \\ x_2 & y_2 \end{vmatrix}$$
It gives the signed area of the parallelogram spanned by the vectors; division by $2$ makes it the area of triangle $OP_iP_{i+1}$ in the formula (1). The area being signed takes care of the possible wiggly shapes of the polygon. One way to prove (1) is to express the area using Green's formula, as in anorton's blog post.
Comment: This makes sense, but what is a 2D cross product?
Comment: I added an explanation.


Inclusion of open balls gives an inequality

Question: The proof I am reading contains the following statement:

... we obtain:
  $$\overline{B_Y} \subset r\cdot \overline{T(B_X)}$$
  (Here $B_X$ and $B_Y$ are unit balls centered at the origin in Banach spaces $X$ and $Y$, resp. Also $r > 0$ and $T$ is linear and continuous)
Therefore, since $\overline{B_Y}$ is the closed unit ball in $Y$, for each $y\in Y$ and $\epsilon > 0$, there is an $x \in X$ for which: $$\|y - T(x)\| < \epsilon \text{ and } \|x\| \leq r \cdot \|y\|$$

Certainly, by inclusion of the balls, the first inequality is true. I don't understand where the second inequality is coming from though -- where does it come from?
Comment: Is $T$ linear?$\hspace{0pt}$
Comment: In this terminology, should a unit ball contain the origin?
Comment: yes! sorry I'll add that
Comment: It does not say so explicitly, but let us assume so. i updated the prompt
Answer: Given the provided set inclusion, take $y \in Y \setminus \{0\}$. Then $\frac{y}{\|y\|} \in \overline{B_Y} \subseteq r \cdot\overline{T(B_X)}$. Therefore, there exists some $z \in \overline{T(B_X)}$ such that $\frac{y}{\|y\|} = rz$. Given $z \in \overline{T(B_X)}$, there must be some $v \in B_X$ such that $\|T(v) - z\| < \frac{\varepsilon}{r\|y\|}$. Putting this together,
$$\|T(v) - z\| < \frac{\varepsilon}{r\|y\|} \implies \Big\|\|y\|rT(v) - \|y\|rz\Big\| < \varepsilon \implies \|T(r\|y\|v) - y\| < \varepsilon.$$
Take $x = r\|y\|v \in X$ such that $\|x\| = \Big\|r\|y\|v\Big\| = r\|y\| \cdot \|v\| \le r\|y\|$ as required.
If $y = 0$, then take $x = 0$.
Comment: @yoshi The $x$ I have and the $x$ in the question are not the same. I've edited my answer to make it more clear, hopefully.
Comment: Why does $r\|y\| \cdot \|x\| \leq r\|y\|$ imply the inequality? It looks like this just means $x$ is in $B_X$ (by canceling)


Would this situation be a ratio of 1/5 or 1/10?

Question: Hypothetical situation that I'm trying to use for understanding some criminal statistics.
Let's say there is a city with 10 banks.
One criminal robs two banks before being arrested and placed in jail.
Would the probability of having a bank robbed be 1/5 (2 robberies / 10 banks) or 1/10 (1 criminal / 10 banks)?
Why I'm asking:
The data I'm looking at contains the identities for criminals and I'm trying to understand some way of measuring the impact of crime in the community.
I'm thinking that when counting the frequency of crimes, one person committing more than one crime wouldn't necessarily be indicative of a crime wave.
Comment: Suppose one really successful criminal gets around and not only robs every bank, but robs some of the them again.  Other criminals may commit robberies, too, over some (perhaps long) period of time, leading (say) to 50 robberies of 10 banks. What sense would you make of the assertion that "the probability of having a bank robbed is 5 = 50/10"?
Comment: @whuber lol - okay, given the scenario, my head is spinning. I don't can't think of a way to make sense of that. It sounds like the count of criminals outweighs the count of crimes.
Comment: Just the opposite: many criminals commit multiple crimes and--by definition--the count of crimes cannot be any less than the count of criminals! What's missing here is any sense of what you are trying to accomplish with your use of statistics. Also missing is any information about how numbers of criminals, banks, or robberies could be (quantitatively) related to "impact of crime in the community."
Comment: Since I have the hometown of criminals in the records, I thought it would be interesting to list the most frequent type of crime by town. But in doing that, I wasn't sure if I should start by counting the crimes or the criminals. I then wanted to see the ratio of the crime or the criminal compared to the population of the town.
Answer: I suggest that you start with a simple stochastic process, explore it thoroughly, and then expand it to cover the full set of cases.
For example, you could start with a stochastic process that assumes that each criminal can only rob one bank per day.  Each day, each of the criminals chooses to rob a bank or not (a Bernoulli trial). If they choose to rob a bank that day, they then choose a bank to rob (with uniform probability). Given a decision to rob and a choice of bank, the criminal has a probability of success (getting money and not getting arrested) vs. failure (not getting money or getting arrested).  But probability of success may not weigh into crime statistics.
The probability of any given bank being robbed on any given day is a function of the total number of criminals and the probability that they will, individually, choose to rob on any given day and that they will select a given bank on that day.
Related but somewhat separate is the probability of being arrested. Each day there is a probability that each criminal might be arrested, conditional on the number of robbery attempts (successful or not).  Presumably, the higher numbers of robbery attempts increases the probability of being arrested.
With this model, you need to estimate the total population of criminals (i.e. potential bank robbers), the daily probability that each criminal would choose to rob a bank, and the conditional probability of being arrested given a number of robbery attempts.
Answer: If the robber randomly selects two different banks, the probability for each bank to be robbed is 2/10=0.2 .
(Consider an extremal case: the robber robs all 10 banks.  The probability is 1.)
If he randomly selects a bank, then again randomly selects a bank (not neccessarily a different one), the probability for each bank to be robbed is $ 1-0.9^2=0.19 $


How to convert an HTML website to Drupal 7 nodes?

Question: I have a website that I want to move to Drupal 7. It is in HTML. I want the content to be in nodes. I don't know much about Drupal and so I need help doing this. I don't want to create a new theme because I want the design to change. I just want the content in nodes. How can I do this in Drupal? Is there a module that can help?
Answer: You don't necessarily need a module to add a content to drupal. Just simply create a content of type page and add your content. To help you with formatting, you may want to install the WYSIWYG module to help you with formatting.
Comment: For some reason I can't find the option to create a new page.
Comment: Can you see content on your menu?
Comment: I see content but when I click it there is nowhere to add a new page
Comment: At the top left you would see add content. Click on it and then choose basic page
Comment: It takes me to Add Project page when I do that and the option for basic page is not shown
Comment: go back to your homepage, and at the end of the url add node/add
Comment: It forwards to upload project. Is this right?
Comment: better you install a new drupal site and add the contents by using ths url node/add
Answer: The module I used (several years ago) was the Import HTML module. I imported a site into Drupal 5 and it worked well. There is a Drupal 7 dev version, but I have no experience with it.
If you use it, plan and prepare well, and you can expect a considerable amount of manual editing after the fact. You may have to try a few times before you get it right, but for a bulk import, it saved me a lot of work.


How to refactor a long method in ruby

Question: Below is an example of my coding style. Sometimes I end up with 50 line methods.
def make_juice
  wash_fruits()
  cut_fruits()

  while(true) do
    if electicity_available?
      turn_on_lights()
      break
    else
      pay_electricity_bill()
      sleep(60)
    end
  end

  mix_fruits_in_mixer()
  add_sugar()
end

# ---------- function definitions ----------

def wash_fruits
  # ...
end
def cut_fruits
  # ...
end
def electricity_avalable?
  # return true  if available
end
def turn_on_lights
  # turn on
end
def pay_electricity_bill
  # pay
end
def create_juice
  # steps for creating juice
end
def add_sugar
  # steps for adding sugar
end

It is not ruby convention to write long methods, and I would like to know the standard way of refactoring a ruby program. I tried to refactor the code and got the result below:
def wash_fruits
  # ...
  cut_fruits
end

def cut_fruits
  # ...
  turn_on_lights
end

def turn_on_lights
  while(true) do
    if electricity_avalable?
      turn_on_lights
      break
    else
      sleep 1.hour
    end
  end
  mix_fruits_in_mixer
end

def mix_fruits_in_mixer
  # ...
  add_sugar
end

def turn_on_lights
  # ...
end

def add_sugar
  # ...
  # ... program exits
end

The method names in the second style isn't very meaningful. Is this the right way to refactor a program?
Comment: Opinion questions, as you alluded to, are generally frowned upon here. You may want to check out https://codereview.stackexchange.com/
Comment: @Stefan is absolutely right, and that's the crux of the matter. Often, long methods are a sign that you're violating the [Single Responsibility Principle](https://en.wikipedia.org/wiki/Single_responsibility_principle). In this case, it's easy to spot. Nobody would expect paying bills to be part of a juice-making procedure. In real-world scenarios it can be tricky but if you recognize the refactoring pattern you can improve the code. Recommended books: Refactoring (Ruby Edition), and Sandi Metz's books.
Comment: @MarkThomas Thank you for the book recommendation
Comment: @Josh, I agree with your advice, but more because the OP has presented working code. SO is concerned with broken code and "how to" questions, whereas Code Review seeks to show how working code can be improved.
Comment: You tell the program (or robot?) to make juice and it may end up in a dark kitchen paying bills – that doesn't sound right to me. Wouldn't it make more sense to fail if something goes wrong?
Comment: It does not make sense to post the code before you refactor attempt. You think it is worse than the refactored code; why do you want to show that to us? You don't need to ask about refactoring. Just post you best attempt, and ask whether that is good code. Refactoring will follow from that.
Comment: @MarkThomas Absolutely not! This question would get closed at Code Review for being example code. It isn't doing anything. Please take a look at their [help center](https://codereview.stackexchange.com/help/on-topic) before making such recommendations again.
Comment: @JoshBrody Same goes for you ^^
Comment: @Mast, you are correct. I suppose it's like this: Broken code: http://stackoverflow.com; Working code: http://CodeReview.stackexchange.com; Hypothetical code: http://SoftwareEngineering.stackexchange.com.
Comment: @MarkThomas Roughly, yes. But take a look at each help center to notice not everything under those categories is automatically allowed.
Answer: I would be inclined to write the following1.
def make_juice
  wash_fruits
  cut_fruits
  turn_on_lights
  mix_fruits_in_mixer
  add_sugar
end

def turn_on_lights
  until electricity_available?
    pay_electricity_bill()
    sleep(60)
  end
  flip_switch_on
end

1 The logic suggests that washing and cutting might be done in the dark and one might have to pay the electricity bill multiple times to get power back. ¯\_(ツ)_/¯.

How to refactor a long method in ruby


To find limit of a sequence: $a_n=n\left(\sqrt[n]{ea}- \sqrt[n]{a}\right),\,a>0.$

Question: I have to find limit of the following sequence:
Suppose $a>0$, consider the sequence $a_n=n\left(\sqrt[n]{ea}- \sqrt[n]{a}\right),\,n\ge1 \,\text{then} \lim_{n \to \infty}a_n\,\text{is}\ldots$
I tried to solve this problem and considered $a$ to be a very small positive number and I got the result that sequence converges to $0$.
But actually the answer is that sequence converges to 1.
How shall I proceed to find limit of this sequence.
Comment: Have you already covered functions, their limits, derivatives ,etc.?
Comment: "I got the result that sequence converges to 0" You could explain precisely what you did to get this.
Answer: One may write, as $n \to \infty$,
$$
\begin{align}
a_n&=n\left(e^{\frac{\large\ln(ea)}n}-e^{\large\frac{\ln(a)}n} \right)
\\&=n\left(e^{\large\frac{1+\ln(a)}n}-e^{\large\frac{\ln(a)}n} \right)
\\&=n \cdot e^{\large\frac{\ln(a)}n}\left(e^{\large\frac{1}n}-1 \right)
\\&= e^{\large\frac{\ln(a)}n}\cdot\frac{e^{\frac{1}n}-1}{\frac{1}n}
\end{align}
$$ then one may conclude with
$$
\lim_{n \to \infty}\frac{e^{\frac{1}n}-1}{\frac{1}n}=1.
$$
Comment: @AbhishekChandra You are welcome. I have a lot of practice ;)
Answer: $$n\left(\sqrt[n]{ea}-\sqrt[n]a\right)=n\sqrt[n]a\left(\sqrt[n]e-1\right)=\sqrt[n]a\,\frac{\sqrt[n]e-1}{\frac1n}\xrightarrow[n\to\infty]{}1\cdot\left[\left(e^x\right)'\right]_{x=0}=1\cdot e^0=1$$
Answer: The function $$A:[1,+\infty)\to\Bbb R: x\mapsto xa^{\frac{1}{x}}(e^{\frac{1}{x}}-1)$$ is continuous as a product of composite functions of continuous functions.
Hence, if the limit when $x\to+\infty$ exists, it is the same along any sequence $(x_{n})_{n}$ such that $x_{n}\to+\infty$ as $n\to+\infty$. We shall prove that the limit exists and thus for the sequence $x_{n}=n$ as well.
We have:
\begin{align*}
&\lim_{x\to+\infty}A(x)\\
&=\lim_{x\to+\infty}xa^{\frac{1}{x}}(e^{\frac{1}{x}}-1)\\
&=\lim_{x\to+\infty}\frac{a^{\frac{1}{x}}(e^{\frac{1}{x}}-1)}{1/x}
\end{align*}
Here, we have a $\frac{0}{0}$ limit and we can thus use L'Hospital's rule. It yields:
\begin{align*}
&\lim_{x\to+\infty}A(x)\\
&=\lim_{x\to+\infty}\frac{a^{\frac{1}{x}}(e^{\frac{1}{x}}-1)}{1/x}\\
&=\lim_{x\to+\infty}\frac{\ln(a)a^{\frac{1}{x}}\left(-\frac{1}{x^{2}}\right)(e^{\frac{1}{x}}-1)+a^{\frac{1}{x}}\left(-\frac{1}{x^{2}}\right)e^{\frac{1}{x}}}{-\frac{1}{x^{2}}}\\
&=\lim_{x\to+\infty}\ln(a)a^{\frac{1}{x}}(e^{\frac{1}{x}}-1)+e^{\frac{1}{x}}a^{\frac{1}{x}}\\
&= 1
\end{align*}


Numerical sum problem.

Question: I just started the series chapter and I come across some series that I don't know how should I resolve them.
All of them have the same structure :
$$
\sum_{n=0}^{\infty} (-1)^n ...
$$
For example:
$$
\sum_{n=0}^{\infty} (-1)^n \frac{n+1}{2^n} or $$
$$
\sum_{n=0}^{\infty} (-1)^n \frac{n^2}{2^n}
$$
Some tips on how should i aproache this would be greatly appreciated.
Comment: I edited my post. Sorry it's n from 0 to infinity.
Comment: I suggest you change the upper value to $m$
Answer: First, absorb  $(-1)^n$ with $\displaystyle\frac1{2^n}$ to find
$$\sum_{n=0}^{\infty}(-1)^n\frac{n+1}{2^n}=\sum_{n=0}^{\infty}(n+1)\left(-\frac12\right)^n$$
$$=\sum_{n=0}^{\infty}(n-1)\left(-\frac12\right)^n+2\underbrace{\sum_{n=0}^{\infty}\left(-\frac12\right)^n}_{\text{ Geomtric Series}}$$
For $|r|<1,$
$$\sum_{n=0}^{\infty}(n-1)r^n=\sum_{n=0}^{\infty}(n-1)r^n=\frac{d \sum_{n=0}^{\infty}r^n}{dr}$$
See also: Elementary problems  and this
Can you manage the last problem from here?
Comment: It is funny ! Today, you wrote at least twice $Geomtric$ $Series$. Cheers.
Comment: Yes, i will manage the second problem. Thank you very much!
Comment: @ClaudeLeibovici, Sorry for the repetition
Comment: @user137209, We can utilize http://en.wikipedia.org/wiki/Arithmetico-geometric_sequence#Sum_to_infinite_terms for the problem I've answered
Comment: Don't be sorry, please ! I just found funny that, being almost blind, I noticed that. At least, it proves that I read what you write (so nicely) ! Cheers.

Numerical sum problem.


Drupal + MongoDB + ApacheSolr

Question: I'm developing a website which uses MongoDB drupal module, I also need ApacheSolr as search engine, I googled about the Compatibility of ApacheSolr and MondoDB but found nothing.
Can I use Mongo as database and ApacheSolr as search engine (with search api) together?
Comment: Did you try out the above said combination, was it successful?
Answer: Given that Search API/Search API Solr use Drupal core functions for retrieving entity data in order to be database agnostic, and the MongoDB module just adds another database backend for storing items like fields, there wouldn't be a conflict. As long as you stick with Drupal core functions in your custom integration, you should be fine.

Drupal + MongoDB + ApacheSolr


Connection issues with Behringer UM2 and Clavinova CLP-360 keyboard

Question: After deciding on getting a Behringer UM2 to record my Clavinova CLP-360, I'm having issues connecting it. Audio interface has two 1/4" inputs (One is line level and the other is high impedance), and the keyboard has a 1/4" headphone, AND stereo RCA output. I'm bumping into so many little problems along the way, so i'll go back to: how do you recommend I hook them up? For now, I don't care if the result is stereo or mono: just high-quality.
Thanks!
Comment: Sorry, i'm still trying to wrap my head around the balanced/unbalanced idea. It's definitely stereo (at least through the headphone jack). So, do you mean something like this (https://www.amazon.com/Kenable-6-35mm-Phono-Plugs-SCREENED/dp/B019ZUCL0C/ref=sr_1_8?keywords=dual+rca+to+1%2F4&qid=1562623223&s=gateway&sr=8-8)? Or does the 1/4" have to be stereo to imitate balanced? The problem is, I'm almost sure that the UM2's inputs are each mono, so if I want the final result to be mono, I'll have to (1) get a different interface, or (2) do it in post.
Answer: The Behringer UM2 has two inputs, but the second input is a dedicated high-impedance guitar input, so when recording your Yamaha digital piano, you will have to use the Mic/Line input and record in mono.
The Yamaha CLP-360 has quite a wide stereo image, with the keyboard range spread out over the stereo field, so only recording either the left or the right side of the stereo output is not an option; you will have to combine both channels.
There are both a stereo headphone output and stereo line-level outputs on unbalanced RCA plugs; the line-level outputs are the best match and will give the best audio quality when connecting to a line-level input on an audio interface.
The Mic/Line input is a balanced XLR/TRS combination input. So you are connecting a stereo unbalanced output to a mono balanced input. This will require specific pseudo-balanced cabling to get the optimal results.
I suggest making a pseudo-balanced Y-cable with screened 2-wire cable: connect the tips of both RCA outputs to the tip of the TRS input, the sleeve of both RCA outputs to the ring of the TRS input, and the screen of both cables to the sleeve of the TRS input but unconnected at the output side.

UNBALANCED OUT                   BALANCED IN
(2x RCA)                          (TRS JACK)

OUT L tip --------wire 1--------+---- tip
   sleeve --------wire 2--------|-+-- ring
          --------screen--------|-|-+ sleeve
                                | | |
OUT R tip --------wire 1--------+ | |
   sleeve --------wire 2----------+ |
          --------screen------------+

Note: If you have no use for the option of connecting a guitar or microphone to the audio interface, and you just want to record your digital piano, then the even simpler and cheaper Behringer UCA-202 may be a better choice. You'd be able to connect it with a simple RCA cable.
Note: The instrument input is presented as a high-impedance input for guitar in the manual, but the label "instrument" seems to suggests that it may also accept other types of signals; the manual and the Behringer website are quite vague about this. But it will be a mono connection, and a generic Y-cable will only connect one of the stereo channels instead of mixing them.
Answer: The OP already purchased his interface, so instead of getting another interface it would be cheaper to get a simple Y adapter.  The adapter will mix the right and the left channels from the Clavinova's RCA output to a regular stereo 1/4" jack (called TRS).
You can get them online, from higher quality like this one in Amazon, to cheap ones like this in eBay.  They also exist in RCA-to-XLR, like this one.

@Your Uncle Bob: if I'm not mistaken, the balanced output RCA on the clavinova would be happy to go into the Behringer UM2's instrument input, which should be a TRS, according to this page (unfortunately I don't have this model, and the specs sheet doesn't specify it).  Can you confirm?
Comment: Whether the instrument input is a high-impedance input for guitar only, or also accepts other instrument signals is indeed unclear, even in the manual. But it will be a mono connection, and a generic Y-cable will only connect one of the stereo channels instead of mixing them.
Comment: RCA has only two connections, it can never be balanced. Using the cable you suggest will result in one channel being inverted before they are added, and cancelling all the mid info in the signal.


Ola, no tkinter como pegar o valor da soma gerada por numeros eleatorios e comparar com a entrada do usuario?

Question: from tkinter import *
from random import randrange, uniform

window = Tk()
window.title("Welcome to LikeGeeks app")
window.geometry('800x600')

lbl1 = Label(window, text="00", font=("Arial Bold", 50))
lbl1.grid(column=0, row=0)
lbl2 = Label(window, text="00", font=("Arial Bold", 50))
lbl2.grid(column=0, row=1)
lbl3 = Label(window, text="+", font=("Arial Bold", 50))
lbl3.grid(column=3, row=0)
resposta = Entry(window,width=4, font=("Arial Bold", 50))
resposta.grid(column=0, row=2)

def proxima():
    a = randrange(10, 99) #faixa de inteiro
    b = randrange(10, 99) #faixa de inteiro
    lbl1.configure(text= str(a))
    lbl2.configure(text= str(b))
    soma = a+b
    print(soma)

def calculo():
    print(soma)
    if resposta.get() == soma:
        print("Acertou")
    else:
        print("Errou...")

btn = Button(window, text="Proxima", command=proxima)
btn.grid(column=0, row=3)
btn2 = Button(window, text="Calcular", command=calculo)
btn2.grid(column=0, row=4)
window.mainloop()

Relacionar o item
Answer: Sua pergunta não está muito clara. O Tkinter não tem nada a ver com soma de números, ele é somente uma interface gráfica visual para o usuário interagir. A parte de somar números aleatórios e comparar, você tem que fazer em python mesmo, e não em tkinter.
Além disso você esqueceu de colocar o erro completo que está recebendo quando executa o seu código. Fica muito mais fácil ver o problema quando tem o erro completo. Sugiro editar a pergunta e acrescentar informações para que ela fique mais clara.

Quanto à resposta, parece que você está usando duas variáveis chamadas soma; uma dentro da função proxima e outra dentro da função resposta.
Em python as variáveis ficam presas ao escopo em que elas foram criadas; se você quiser acessar uma variável que está em outro escopo, é preciso fazer isso manualmente, e cada função cria um escopo de variáveis.
Uma forma direta de resolver seria passar a variável soma para o escopo global.
def proxima():
    global soma
    # ... restante da função continua igual

Comment: Valeu amigo! Mesmo sem entender você me deu a resposta que precisava, "global soma", funcionou da forma que queria!