text:
Q: How to check efficiently if two characters are neighbours on the keyboard? I want to develop a soft keyboard for Android and already got a autocorrect algorithm which makes suggestions based on the fact if the input character and the character of a word from the dictionary are neighbours on the keyboard. This works in combination with the levenshtein-algorithm (if a character has to be replaced with a different character it is checked if they are neighbours). That's why this check is called very frequently. Currently, it consumes 50% of the time spent on autocorrection.
My current approach is a seperate trie with 3 layers. First layer: first character. Second layer: second character: Third layer: boolean holding the information if the characters are neighbours. But I'm afraid a trie is overkill? The intern hashmaps for every children may slow it down, as well? Should I build a hashmap with an own charToNumber-function?
How would you do this? Which bottlenecks can be avoided? Character.toLowerCase() seems to be inefficient as well when it's called everytime a check is performed.
I hope you can help me speeding up the task :)

A: You just want to determine whether two characters are next to each other on the keyboard? Why not use a map from a character to a set of adjacent characters? When using efficient data structures you will get O(1) time - use array for a map (continuous key space - ASCII codes of keys) and BitSet for a set of adjacent keys. Also very compact.
Here is a sample code:
BitSet[] adjacentKeys = new BitSet[127];

//initialize
adjacentKeys[(int) 'q'] = new BitSet(127);
adjacentKeys[(int) 'q'].set((int)'a');
adjacentKeys[(int) 'q'].set((int)'w');
adjacentKeys[(int) 'q'].set((int)'s');
//...

//usage
adjacentKeys[(int) 'q'].get((int) 'a');     //q close to a yields true
adjacentKeys[(int) 'q'].get((int) 'e');     //q close to e yields false

This should be very efficient, no loops and complicated computations like hashCodes. Of course you have to initialize the table manually, I would advice doing this once at application startup from som external configuration file.
BTW neat idea!

A: I really like the idea.
For raw speed, you would use a massive switch statement. The code would be large, but there would be nothing faster:
public static boolean isNeighbour(char key1, char key2) {
    switch (key1) {
    case 'a':
        return key2 == 'w' || key2 == 'e' || key2 == 'd' || key2 == 'x' || key2 == 'z';
    case 'd':
        return key2 == 's' || key2 == 'w' || key2 == 'f' || key2 == 'c' || key2 == 'x';
    // etc
    default:
        return false;
    }
}

Here's a "standard" way to do it that should still perform well:
private static final Map<Character, List<Character>> neighbours =
    new HashMap<Character, List<Character>>() {{
    put('s', Arrays.asList('a', 'w', 'e', 'd', 'x', 'z'));
    put('d', Arrays.asList('s', 'e', 'w', 'f', 'c', 'x'));
    // etc
}};

public static boolean isNeighbour(char key1, char key2) {
    List<Character> list = neighbours.get(key1);
    return list != null && list.contains(key2);
}

This algorithm does not make use of the fact that if a isneighbour b then b isneighbour a, but rather sacrifices data size for code simplicity.

A: What about assigning numbers to each key and use that to determine proximity.
    public static void main(String[] args) {
    double[] d = new double[26];
    d['q'-97] = 100d;
    d['w'-97] = 101d;
    d['e'-97] = 102d;
    d['r'-97] = 103d;
    d['t'-97] = 104d;
    //(optionally, put a space of 5 between right hand and left hand for each row)
    d['y'-97] = 105d;
    d['u'-97] = 106d;
    d['i'-97] = 107d;
    d['o'-97] = 108d;
    d['p'-97] = 109d;

    //my keyboard middle row is about 20% indented from first row
    d['a'-97] = 200.2;
    d['s'-97] = 201.2;
    d['d'-97] = 202.2;
    d['f'-97] = 203.2;
    d['g'-97] = 204.2;
    d['h'-97] = 205.2;
    d['j'-97] = 206.2;
    d['k'-97] = 207.2;
    d['l'-97] = 208.2;

    //third row is about 50% indented from middle row
    d['z'-97] = 300.5;
    d['x'-97] = 301.5;
    d['c'-97] = 302.5;
    d['v'-97] = 303.5;
    d['b'-97] = 304.5;
    d['n'-97] = 305.5;
    d['m'-97] = 306.5;

    for (char a = 'a'; a <= 'z'; a++) {
        for (char b = 'a'; b <= 'z'; b++)
            if (a != b && prox(a,b,d))
                System.out.println(a + " and " + b + " are prox");
    }

}

static boolean prox(char a, char b, double m) {
    double a1 = m[a-97];
    double a2 = m[b-97];

    double d = Math.abs(a1-a2);
    //TODO: add in d == 5 if there is a spacing for left and right hand gap (since it's more unlikely of a crossover)
    return d == 0 || d == 1 || (d >= 99 && d <= 101);
}

Partial Output:
a and q are prox
a and s are prox
a and w are prox
a and z are prox
....
g and b are prox
g and f are prox
g and h are prox
g and t are prox
g and v are prox
g and y are prox
....
y and g are prox
y and h are prox
y and t are prox
y and u are prox

A: Here is my hungarian version (if somebody needs it):
 public static boolean isHungarianNeighbour(int key1, int key2) {
    switch (key1) {
        case 'q':
            return key2 == 'w' || key2 == 's' || key2 == 'a' || key2 == '1' || key2 == '2';
        case 'w':
            return key2 == 'q' || key2 == '2' || key2 == '3' || key2 == 'e' || key2 == 's' || key2 == 'a';
        case 'e':
            return key2 == '3' || key2 == '4' || key2 == 'w' || key2 == 'r' || key2 == 's' || key2 == 'd';
        case 'r':
            return key2 == '4' || key2 == '5' || key2 == 'e' || key2 == 't' || key2 == 'd'|| key2 == 'f';
        case 't':
            return key2 == '5' || key2 == '6' || key2 == 'r' || key2 == 'z' || key2 == 'f' || key2 == 'g';
        case 'z':
            return key2 == '6' || key2 == '7' || key2 == 't' || key2 == 'u' || key2 == 'g' || key2 == 'h';
        case 'u':
            return key2 == '7' || key2 == '8' || key2 == 'z' || key2 == 'i' || key2 == 'h' || key2 == 'j';
        case 'i':
            return key2 == '8' || key2 == '9' || key2 == 'u' || key2 == 'o' || key2 == 'j' || key2 == 'k';
        case 'o':
            return key2 == '9' || key2 == 'ö' || key2 == 'i' || key2 == 'p' || key2 == 'k' || key2 == 'l';
        case 'p':
            return key2 == 'ö' || key2 == 'ü' || key2 == 'o' || key2 == 'ő' || key2 == 'l' || key2 == 'é';
        case 'ő':
            return key2 == 'ü' || key2 == 'ó' || key2 == 'p' || key2 == 'ú' || key2 == 'é' || key2 == 'á';
        case 'ú':
            return key2 == 'ó' || key2 == 'ő' || key2 == 'á' || key2 == 'ű';
        case 'a':
            return key2 == 'q' || key2 == 'w' || key2 == 's' || key2 == 'y' || key2 == 'í';
        case 's':
            return key2 == 'w' || key2 == 'e' || key2 == 'a' || key2 == 'd' || key2 == 'y' || key2 == 'x';
        case 'd':
            return key2 == 'e' || key2 == 'r' || key2 == 's' || key2 == 'f' || key2 == 'x' || key2 == 'c';
        case 'f':
            return key2 == 'r' || key2 == 't' || key2 == 'd' || key2 == 'g' || key2 == 'c' || key2 == 'v';
        case 'g':
            return key2 == 't' || key2 == 'z' || key2 == 'f' || key2 == 'h' || key2 == 'v' || key2 == 'b';
        case 'h':
            return key2 == 'z' || key2 == 'u' || key2 == 'g' || key2 == 'j' || key2 == 'b' || key2 == 'n';
        case 'j':
            return key2 == 'u' || key2 == 'i' || key2 == 'h' || key2 == 'k' || key2 == 'n' || key2 == 'm';
        case 'k':
            return key2 == 'i' || key2 == 'o' || key2 == 'j' || key2 == 'l' || key2 == 'm';
        case 'l':
            return key2 == 'o' || key2 == 'p' || key2 == 'k' || key2 == 'é';
        case 'é':
            return key2 == 'p' || key2 == 'ő' || key2 == 'l' || key2 == 'á';
        case 'á':
            return key2 == 'ő' || key2 == 'ú' || key2 == 'é' || key2 == 'ű';
        case 'ű':
            return key2 == 'á' || key2 == 'ú';
        case 'í':
            return key2 == 'a' || key2 == 'y';
        case 'y':
            return key2 == 'a' || key2 == 's' || key2 == 'í' || key2 == 'x';
        case 'x':
            return key2 == 's' || key2 == 'd' || key2 == 'y' || key2 == 'c';
        case 'c':
            return key2 == 'd' || key2 == 'f' || key2 == 'x' || key2 == 'v';
        case 'v':
            return key2 == 'f' || key2 == 'g' || key2 == 'c' || key2 == 'b';
        case 'b':
            return key2 == 'g' || key2 == 'h' || key2 == 'v' || key2 == 'n';
        case 'n':
            return key2 == 'h' || key2 == 'j' || key2 == 'b' || key2 == 'm';
        case 'm':
            return key2 == 'j' || key2 == 'k' || key2 == 'n' || key2 == '?';
        default:
            return false;
    }
}


text:
Q: Simple slopes test for merMod object with R package interactions (jtools) I'm trying to conduct a simple slopes analysis for a mixed effects model obtained with lmer.
The model is similar to the following:
data(Orthodont,package="nlme")
mod <- lme4::lmer(distance ~ age*Sex + (1|Subject), data=Orthodont)

When trying to conduct a simple slopes analysis with the function sim_slopes in the package interactions, I obtain the following error message.
interactions::sim_slopes(model=mod, pred=age, modx=Sex)

Error: One of the requested columns does not exist.
  Backtrace:
  1. interactions::sim_slopes(model = mod, pred = age, modx = Sex)
  5. jtools:::summ.merMod(...)
  6. jtools:::create_table(...)
  In addition: Warning message:
  Johnson-Neyman intervals are not available for factor moderators.

Would any one have any thoughts on what the problem might be?
Note that it works well with the package reghelper, but I need p values for these tests, which reghelper does not provide.
reghelper::simple_slopes(mod)

The output of sessionInfo() is:

R version 3.6.0 (2019-04-26)
  Platform: x86_64-pc-linux-gnu (64-bit) Running under: Ubuntu 18.04.2
  LTS
Matrix products: default BLAS:
  /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1 LAPACK:
  /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1
locale:  [1] LC_CTYPE=en_CA.UTF-8       LC_NUMERIC=C
  LC_TIME=en_CA.UTF-8         [4] LC_COLLATE=en_CA.UTF-8
  LC_MONETARY=en_CA.UTF-8    LC_MESSAGES=en_CA.UTF-8     [7]
  LC_PAPER=en_CA.UTF-8       LC_NAME=C                  LC_ADDRESS=C
  [10] LC_TELEPHONE=C             LC_MEASUREMENT=en_CA.UTF-8
  LC_IDENTIFICATION=C
attached base packages: [1] stats     graphics  grDevices utils
  datasets  methods   base
loaded via a namespace (and not attached):
  [1] Rcpp_1.0.1        magrittr_1.5       splines_3.6.0      MASS_7.3-51.1
  [5] munsell_0.5.0      colorspace_1.4-1   lattice_0.20-38    rlang_0.3.4
  [9] minqa_1.2.4        plyr_1.8.4         tools_3.6.0       grid_3.6.0
  [13] gtable_0.3.0       nlme_3.1-140       cli_1.1.0          assertthat_0.2.1
  [17] digest_0.6.19      lme4_1.1-21        lazyeval_0.2.2     tibble_2.1.2
  [21] crayon_1.3.4       Matrix_1.2-17      reghelper_0.3.4    nloptr_1.2.1
[25] ggplot2_3.1.1      interactions_1.1.0 jtools_2.0.1       pander_0.6.3
  [29] compiler_3.6.0     pillar_1.4.1       scales_1.0.0       boot_1.3-20
  [33] pkgconfig_2.0.2

A: (Not an answer but way too long for a comment.  Will delete later if appropriate.)
In a clean R session, this works for me:
data(Orthodont,package="nlme")
mod <- lme4::lmer(distance ~ age*Sex + (1|Subject), data=Orthodont)
interactions::sim_slopes(model=mod, pred=age, modx=Sex)
sessionInfo()

SIMPLE SLOPES ANALYSIS
  Slope of age when Sex = Female:
   Est.   S.E.    t val.      p
  ------ ------ -------- ------
   0.48   0.09     5.13   0.00
  Slope of age when Sex = Male:
   Est.   S.E.   t val.      p
  ------ ------ -------- ------
    0.78   0.08    10.12   0.00
  Warning message:
  Johnson-Neyman intervals are not available for factor moderators.

Here is my sessionInfo(): the important stuff looks the same as yours (lme4 1.1-21, interactions 1.1.0, jtools 2.0.1), but it's certainly not identical ... ??
R Under development (unstable) (2019-05-21 r76566)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.6 LTS

[matrix product and locale info deleted]

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.1         magrittr_1.5       splines_3.7.0      MASS_7.3-51.4
 [5] tidyselect_0.2.5   munsell_0.5.0      colorspace_1.4-1   lattice_0.20-38
 [9] R6_2.4.0           rlang_0.3.4        minqa_1.2.4        plyr_1.8.4
[13] dplyr_0.8.1        tools_3.7.0        grid_3.7.0         gtable_0.3.0
[17] nlme_3.1-140       cli_1.1.0          digest_0.6.19      assertthat_0.2.1
[21] lme4_1.1-21        lazyeval_0.2.2     tibble_2.1.2       numDeriv_2016.8-1
[25] crayon_1.3.4       Matrix_1.2-17      purrr_0.3.2        nloptr_1.2.1
[29] ggplot2_3.1.1      jtools_2.0.1       interactions_1.1.0 glue_1.3.1
[33] pander_0.6.3       compiler_3.7.0     pillar_1.4.1       scales_1.0.0
[37] lmerTest_3.1-0     boot_1.3-22        pkgconfig_2.0.2

A: I solved the problem by detaching lmerTest.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fetch latest start date, if there are two minimum start dates in a table I'm trying to build a query for the following scenario,

*

*Group records by license ID and get min and max dates

*For a given license ID, if there are two earliest start dates, then start date of the particular ID has to be updated as latest start date in that grouping.

Since I'm new to sql, I need help to satisfy condition 2. Any help is greatly appreciated. Thanks
Actual data

LicenseID
StartDate
EndDate

100
4/3/2000
3/1/2013

100
4/3/2000
2/2/2017

100
3/1/2013
1/23/2015

100
1/23/2015
2/2/2017

100
2/2/2017
2/9/2018

100
2/2/2017
12/18/2018

100
12/18/2018
2/16/2021

Expected output

LicenseID
StartDate
EndDate

100
12/18/2018
2/16/2021

A: Here's one option; read comments within code.
Sample data:
SQL> with test (id, start_date, end_date) as
  2    (select 100, date '2000-04-03', date '2013-03-01' from dual union all
  3     select 100, date '2000-04-03', date '2017-02-02' from dual union all
  4     select 100, date '2018-12-18', date '2021-02-16' from dual
  5    ),

Query begins here:
  6  -- rank start dates per each ID
  7  temp as
  8    (select id,
  9       min(start_date) over (partition by id) min_sd,
 10       max(start_date) over (partition by id) max_sd,
 11       rank() over (partition by id order by start_date) rnk_sd,
 12       --
 13       max(end_date) over (partition by id) max_ed
 14     from test
 15    ),
 16  -- count number of the 1st start dates
 17  temp2 as
 18    (select id,
 19       sum(case when rnk_sd = 1 then 1 else 0 end) cnt_sd
 20     from temp
 21     group by id
 22    )
 23  -- if number of the 1st start dates is 1, take MIN_SD. Otherwise, take MAX_SD
 24  select distinct
 25    b.id,
 26    case when b.cnt_sd = 1 then a.min_sd else a.max_sd end start_date,
 27    a.max_ed end_date
 28  from temp2 b join temp a on a.id = b.id;

Result:
        ID START_DATE END_DATE
---------- ---------- ----------
       100 12/18/2018 02/16/2021

SQL>

A: This can filter them:
WITH sample_data AS
(
  SELECT 100 AS LicenseID, TO_DATE('04/03/2000','MM/DD/YYYY') AS StartDate, TO_DATE('03/01/2013','MM/DD/YYYY') AS EndDate FROM DUAL UNION ALL
  SELECT 100, TO_DATE('04/03/2000','MM/DD/YYYY'), TO_DATE('02/02/2017','MM/DD/YYYY') FROM DUAL UNION ALL
  SELECT 100, TO_DATE('03/01/2013','MM/DD/YYYY'), TO_DATE('01/23/2015','MM/DD/YYYY') FROM DUAL UNION ALL
  SELECT 100, TO_DATE('01/23/2015','MM/DD/YYYY'), TO_DATE('02/02/2017','MM/DD/YYYY') FROM DUAL UNION ALL
  SELECT 100, TO_DATE('02/02/2017','MM/DD/YYYY'), TO_DATE('02/09/2018','MM/DD/YYYY') FROM DUAL UNION ALL
  SELECT 100, TO_DATE('02/02/2017','MM/DD/YYYY'), TO_DATE('12/18/2018','MM/DD/YYYY') FROM DUAL UNION ALL
  SELECT 100, TO_DATE('12/18/2018','MM/DD/YYYY'), TO_DATE('02/16/2021','MM/DD/YYYY') FROM DUAL
)
SELECT dat.licenseID, CASE WHEN dups.licenseID IS NOT NULL THEN MAX(StartDate)
                          ELSE MIN(StartDate)
                     END,
                     CASE WHEN dups.licenseID IS NOT NULL THEN MAX(EndDate)
                          ELSE MIN(EndDate)
                     END
  FROM sample_data dat
       LEFT OUTER JOIN (SELECT COUNT(1), sd.LicenseID
                          FROM sample_data sd
                               INNER JOIN (SELECT MIN(StartDate) AS StartDate, LicenseID
                                             FROM sample_data
                                            GROUP BY LicenseID) mins
                                  ON sd.LicenseID = mins.LicenseID AND sd.startDate = mins.StartDate
                         GROUP BY sd.LicenseID
                         HAVING COUNT(1) > 1) dups
                    ON dups.LicenseID = dat.licenseID
 GROUP BY dat.licenseID, dups.licenseID;

A: You can use:
SELECT licenseid,
       MAX(startdate) AS startdate,
       MAX(enddate) KEEP (DENSE_RANK LAST ORDER BY startdate) AS enddate
FROM   table_name
GROUP BY licenseid
HAVING COUNT(*) KEEP (DENSE_RANK FIRST ORDER BY startdate) > 1;

or:
SELECT licenseid,
       max_startdate AS startdate,
       max_enddate As enddate
FROM   (
  SELECT licenseid,
         RANK()
           OVER (PARTITION BY licenseid ORDER BY startdate) AS rnk,
         ROW_NUMBER()
           OVER (PARTITION BY licenseid, startdate ORDER BY enddate) AS rn,
         MAX(startdate)
           OVER (PARTITION BY licenseid) AS max_startdate,
         MAX(enddate)
           KEEP (DENSE_RANK LAST ORDER BY startdate)
           OVER (PARTITION BY licenseid) AS max_enddate
  FROM   table_name t
)
WHERE  rnk = 1
AND    rn  = 2;

Which, for the sample data:
CREATE TABLE table_name (licenseid, startdate, enddate) AS
  SELECT 100, DATE'2000-04-03', DATE'2013-03-01' FROM DUAL UNION ALL
  SELECT 100, DATE'2000-04-03', DATE'2017-02-02' FROM DUAL UNION ALL
  SELECT 100, DATE'2013-03-01', DATE'2015-01-23' FROM DUAL UNION ALL
  SELECT 100, DATE'2015-01-23', DATE'2017-02-02' FROM DUAL UNION ALL
  SELECT 100, DATE'2017-02-02', DATE'2018-02-09' FROM DUAL UNION ALL
  SELECT 100, DATE'2018-02-02', DATE'2018-12-18' FROM DUAL UNION ALL
  SELECT 100, DATE'2018-12-18', DATE'2021-02-16' FROM DUAL;

Both output:

LICENSEID
STARTDATE
ENDDATE

100
2018-12-18 00:00:00
2021-02-16 00:00:00

If you do want to perform an UPDATE of that second row then:
MERGE INTO table_name dst
USING (
  SELECT ROWID AS rid,
         max_startdate,
         max_enddate
  FROM   (
    SELECT RANK()
             OVER (PARTITION BY licenseid ORDER BY startdate) AS rnk,
           ROW_NUMBER()
             OVER (PARTITION BY licenseid, startdate ORDER BY enddate) AS rn,
           MAX(startdate)
             OVER (PARTITION BY licenseid) AS max_startdate,
           MAX(enddate)
             KEEP (DENSE_RANK LAST ORDER BY startdate)
             OVER (PARTITION BY licenseid) AS max_enddate
    FROM   table_name t
  )
  WHERE  rnk = 1
  AND    rn  = 2
)src
ON (src.rid = dst.ROWID)
WHEN MATCHED THEN
  UPDATE
  SET startdate = src.max_startdate,
      enddate   = src.max_enddate;

db<>fiddle here


text:
Q: How to Get Last Id MySQL in Scrapy? This is the snippet of the code in my pipeline. And I want to get the last inserted ID
result = tx.execute("INSERT INTO articles(title, description, url) VALUES ('" + item['title'] + "', '" + it    em['description'] + "', '" + item['url'] + "')"
          )
print('#RESULT', result)

In here, the result printed 1L.
My Purpose: My article as many images, so I want to save them in a different table. By getting the last id of the article, I can use it as a foreign keys to the images table.
How do I do it? Or You have any other practical solutions?

A: Use tx.lastrowid to get the last row ID inserted


text:
Q: spring boot jaeger won't trace webClient request I have a Spring boot application and i want to trace the webClient request with jaeger:
implementation "io.micrometer:micrometer-registry-prometheus:1.10.3"
implementation "org.springframework.boot:spring-boot-starter-web:2.6.6"
implementation "org.springframework.boot:spring-boot-starter-webflux:2.6.6"
implementation 'io.opentracing.contrib:opentracing-spring-jaeger-web-starter:3.3.1'
implementation "io.opentracing.contrib:opentracing-jdbc:0.2.15"

My application.yml:
server:
  port: 4502
spring:
   application:
    name: myServiceName
  datasource:
    url: jdbc:tracing:sqlserver:xxxx
    username: sssr
    password: blabla
    driver-class-name: io.opentracing.contrib.jdbc.TracingDriver

opentracing:
  jaeger:
    enabled: true
    service-name: myServiceName
    log-spans: true
    udp-sender:
      port: 31683
      host: a.b.asd.wq
    http-sender:
      url: http://a.b.asd.wq:31268/api/traces

my webClient request:
String response = webClient.get()
                                    .uri(url)
                                    .retrieve()
                                    .bodyToMono(String.class)
                                    .block();

i send a request to http://127.0.0.1:4502/ and i got some spans reported
2023.02.22 10:02:54.350 [http-nio-4502-exec-1] INFO  i.j.i.reporters.LoggingReporter:43 - Span reported: 7d0aef60d1f97f02:7d0aef60d1f97f02:0:1 - GET

The Jaeger UI on the host can the webClient request not reported.


text:
Q: Update InnerHTML (Echo PHP) Value on Button Click I am still in beginner's level of WordPress and PHP. I already doing my research in stackoverflow but because of my low-level understanding, I can't find the solution for the problem I have.
I use WordPress as CMS for my website. I use PHP echo for showing the average rating value of a user review plugin. It shows fine. But after a visitor insert his/her own rating and click submit button, the average rating value didn't update until the page is refreshed. How to automatically update the average rating value after the submit button clicked without having to refresh the page?
<script type="text/javascript">
var userRating = <?php echo rmp_get_avg_rating( $postID ); ?> ;
document.getElementById("div-rating").innerHTML = userRating;
</script>

This is the submit button class created by the plugin to trigger User Submission.
rmp-rating-widget__submit-btn rmp-btn js-submit-rating-btn rmp-rating-widget__submit-btn--visible

This is the PHP function I need to echo.
public function load_results() {
    if ( wp_doing_ajax() ) {
        // array with vote count, ratings and errors
        $data = array(
            'voteCount' => false,
            'avgRating' => false,
            'errorMsg'  => '',
        );

    $post_id = intval( $_POST['postID'] );
        $nonce = isset( $_POST['nonce'] ) ? $_POST['nonce'] : false;

        // security check
        if( ! $post_id ) {
            $data['errorMsg'] = esc_html__( 'You cannot rate a web page without an id!', 'rate-my-post' );
            echo json_encode( $data );
            die();
        }

        $nonce_check = $this->has_valid_nonce( $nonce );
        if( ! $nonce_check['valid']  ) {
            $data['errorMsg'] = $nonce_check['error'];
            echo json_encode( $data );
            die();
        }

        $vote_count = rmp_get_vote_count( $post_id );
        $sum_of_ratings = rmp_get_sum_of_ratings( $post_id );
        $average_rating = rmp_calculate_average_rating( $sum_of_ratings, $vote_count );

        if ( $average_rating ) { // post has been rated
            $data['voteCount'] = $vote_count;
            $data['avgRating'] = $average_rating;
        } else { // no ratings so far
            $data['voteCount'] = 0;
            $data['avgRating'] = 0;
        }

        echo json_encode( $data );
    };
    die();
}

Thank you for your help.

A: Without refreshing the webpage, you can take the data on the server by using XMLHttpRequest object on client side. You can find a lot of implementations ( such as
XMLHttpRequest, Fetch API) which help you for communicating with the server from client side without refreshing page.
If you want to use a different technology ( Socket.io ), web sockets can meet your needs on this problem.


text:
Q: odoo 8 Button Logic i'm new with Odoo 8. I added a Button in my module (inherit sale order) to be able to execute the method calkulateEKNew. The function is calling how it should be, but it looks like that the button is doing more stuff in the background. After clicking the button it saves the sale order and calls the method calkulateEKNew.
Is it possible to trigger this button or to find the logic behind the button ?

Nice regards

A: Buttons are available to execute python methods on the Odoo server.
If you want to execute JavaScript code, you'll have to add a (client-side) widget, possibly a template and a JavaScript file to your module.
This URL points to further information about simple widgets:
https://www.odoo.com/documentation/8.0/howtos/web.html#widgets-basics


text:
Q: Prove that $\limsup_{n\to\infty}\int f_n\leq \int\limsup_{n\to\infty }f_n$ Les $f_n$ a sequence of measurable function such that $|f_n|\leq 1$ for all $n$.
1) Prove that $$\limsup_{n\to\infty}\int f_n\leq  \int\limsup_{n\to\infty }f_n$$
2) Does this inequality hold if supposed $f_n\geq 0$ but no necessarily bounded ?
My try
I set $f_n=f_n^++f_n^-$ where $f_n^+(x)=\max\{0,f_n(x)\}$ and $f_n^-=\min\{0, -f(x)\}$. Then
\begin{align*}
\limsup_{n\to\infty }\int f_n&=\limsup_{n\to\infty }\int f_n^+-f_n^-\\
&\leq\limsup_{n\to\infty }\int f_n^++\limsup_{n\to\infty }\int(-f_n^-)\\
&=\limsup_{n\to\infty }\int f_n^+-\liminf_{n\to\infty }\int f_n^-\\
&\underset{Fatou}{\leq} \limsup_{n\to\infty }\int f_n^+-\int\liminf_{n\to\infty }f_n^-\\
&= \limsup_{n\to\infty }\int f_n^++\int\limsup_{n\to\infty }(-f_n^-)
\end{align*}
but I can't conclude.
For 2) I'm sure it's wrong, but I can't find a counter example.

A: Question 1: First of all: If you consider the Lebesgue measure on $(\mathbb{R},\mathcal{B}(\mathbb{R}))$, then your claim is not correct. Just consider
$$f_n(x) := 1_{[n,n+1]}(x),$$
then
$$\limsup_{n \to \infty} \int f_n(x) \, dx= 1 > 0 = \int \limsup_{n \to \infty} f_n(x) \, dx.$$
Now if you restrict the Lebesgue measure to $[0,1]$, i.e.
$$\limsup_{n \to \infty} \int_{[0,1]} f_n(x) \, dx \leq \int_{[0,1]} \limsup_{n \to \infty} f_n(x) \, dx,$$
then this inequality follows from Fatou's lemma applied to the non-negative sequence $g_n(x) := 1-f_n(x)$.
Question 2: No, this inequality is, in general, not satisfied if $f_n$ is not bounded. Consider
$$f_n(x) := n 1_{[0,1/n]}(x).$$
Remark: More generally, one can show the following statement

Let $(X,\mathcal{A},\mu)$ be a measure space. If $(f_n)_{n \in \mathbb{N}}$ is a sequence of measurable functions such that $f_n \leq g$ for some $g \in L^1(\mu)$, then $$\limsup_{n \to \infty} \int f_n \, d\mu \leq \int \limsup_{n \to \infty} f_n \, d \mu.$$


text:
Q: How to pass one JS var to another JS page I have followed some tutorial on internet and created a little game that works in browsers. It is a canvas game, and with paddle you prevent the ball falling and reflecting it to destroy bricks(I hope you know what I am talking about). I did everything that instructor did in that course but in the end I made some changes and copied that JS code onto another JS page with some changes to it so it passes on "Level 2" when you finish first part of the game.
My problem is that the lives that are implemented in the game aren't passing onto "Level 2", if you know what I mean. You start with 3 lives, for example you lose 1 life, when you finish "Level 1" with 2 lives and continue to "Level 2" you will have 3 lives again, instead of 2. If anyone does understand me, please help. I have probably made this question so awkward and confusing but i had to tell the whole story so you would understand. Thanks in advance!

A: To pass data to another page, the simply solution is to pass them as query parameters:
https://gomakethings.com/how-to-get-the-value-of-a-querystring-with-native-javascript/
But in your case I suggest to use sessionstorage or localstorage.
SessionStorage conserve the data until you close the browser:
https://developer.mozilla.org/en/docs/Web/API/Window/sessionStorage
Whit Localstorage the data persist even if you close the browser:
https://developer.mozilla.org/en/docs/Web/API/Window/localStorage
If you have complex data to save you can store in a database, see indexeddb:
https://developer.mozilla.org/it/docs/Web/API/IndexedDB_API


text:
Q: Resistivity in terms of temperature coefficient of resistance $$R = R_0 * (1 + \alpha (T - T_0))$$
Where $R_0$ and $T_0$ are the reference resistance and temperature.
Is it then safe to say that: $$\rho = \rho _0 * (1 + \alpha (T - T_0))$$
(where $\rho _0$ is the reference resistivity)?

A: Yes; under the relationship $R=\rho L/A$, the two expressions are equivalent for a given geometry. Resistivity generally depends on temperature in a complex way, but for small temperature differences, this dependence is approximately linear, as captured by the coefficient $\alpha$. All resistivity values for materials (should) include a reference temperature because of this temperature sensitivity. In this Wikipedia list of material resistivities, for example, the reference temperature is 20°C.

A: Yes! But no
This expression will work for lower temperatures but gets complex for higher temperatures
Also you should know that it was by luck that you got the right answer since you forgot to consider thermal expansion of length and cross-sectional area
Now if you think about it you might think that expression is wrong it indeed is but certainly gives a good approximation of correct answer
And why is that ?
That's because coefficient of thermal expansion is of the order of 10^-6
Whereas coefficient (alpha) we are talking here is roughly of the order of 10^-3
Hope this helps !


text:
Q: My division function returns a zero. Should I declare x differently in main? #include <iostream>
using namespace std;

int division(int c, int d);

int x = 2;
int y = 2;

int division(int c, int d)
{
    return (c/d);
}

int main()
{
    cout << "Hello World!\n";
    int x = division(x,y);
    cout << x;
    return 0;
}

I expected the code to show 1 after Hello World!, but it prints 0.
I removed int from in front of x (in main()) and ran it again and it returned 1.
But I also passed x,x to the division function with the int in front of x (in main()) and it returned 1.
So I am not sure how the assignment statement is working.

A: This expression:
int x = division(x,y);

is equivalent to writing this:
// 'x' was defined globally somewhere here before
int x;
x = division(x, y);

This shadows the previous x variable defined globally and defines a local variable x which again is uninitialized so after passing it in the division() function, your code has Undefined Behavior. (When that happens, the output can be anything, it can be 0, it can even be 1 or something else entirely.)
What you want to do is to remove the declaration and turn it into an assignment instead:
x = division(x,y);

Then the above works properly and gives 1.

A: You should compile your code at least  with -Wall flag.
You would then see a helpful warning message:
foo.cpp: In function 'int main()':
foo.cpp:17:21: warning: 'x' is used uninitialized [-Wuninitialized]
   17 |     int x = division(x,y);
      |             ~~~~~~~~^~~~~

It means that to the division() isn't passed global x, but the local one from main().
It's undefinied behaviour, no different than int z = division(z,y);
After removing int from before x in main() you no longer declare local variable, thus there is only one x in your program (the global one) and from initialization the line turns into plain assignment.


text:
Q: SNS not able to hit HTTPS endpoint I have below annotation set on my controller but it is not able to receive AWS SNS messages,
@RequestMapping(method = RequestMethod.POST, headers = "Content-Type=text/plain; charset=UTF-8")

SNS message sample is here
I always get 415 Unsupported Media Type. Looks like I am missing some minor thing here.

A: This what worked for me:
The request body is actually a JSON string (text/plain) so you should accept it as a string and then parse it to a usable structure.
Here is an example.
@RequestMapping(method = RequestMethod.POST, consumes = "text/plain")
void subscribe(@RequestBody String paramsString) {
    Map<String, String> params = new Gson().fromJson(paramsString, new
HashMap<String, String>().getClass());
    // Use params..
}


text:
Q: Add Horizontal Scroll in Jquery Mobile Table? I have the following markup,

                SL

                Cat

                Brand

                Product

                Item
                Code

                Model
                Number

                Bundle Value

                Old RSP

                Promo
                RSP

                Reduced %age

                Start Date

                Vendor End
                Date

A115

SDA

Panasonic

Blender

11651099

MXAC400

GV 50

      399

                          399

0%

Feb 26th

Mar 8th

C073

SDA

Tefal

Fryer

11480473

FZ700072

PB

999

      749

25%

Mar 1st

Will Revert

Can I add a horizontal markup? So that users can easily scroll right and left

A: You can wrap your table with div like:

A: If table > window width scroll will be visible dy default.
Check CSS styles and js (jQuery Mobile can fixed the table to window width)
Also you can use div container, for example:

...

A: The answers above worked for me; however, I didn't want to specify explicit widths or heights, so the following solved the problem even better:

  <table [...]


text:
Q: I can't seem to get my code to display my calculation, am I missing an output tag? I am trying to create an MPG (Miles Per Gallon) calculator in Javascript. I can't seem to display my results after I hit the "Calculate" button.

 <title> Miles per Gallons Calculator</title>

Miles per Gallons Calculator

by

<form name="form1">
Miles <input type="text" size="21" name="txtMiles">

Gallons <input type="text" size="20" name="txtGallons">

<input type="button" name="btnCalc" value="Calculate MPG" onclick="calcMPG()">

<input type="reset" name="btnClear" value="Clear">

Miles Per Gallon
<input type="text" size="20"    name="txtMPG">

</form>

A: Hi Please Use this code I hope it's helpful
Thanks

 <title> Miles per Gallons Calculator</title>

Miles per Gallons Calculator

by

<form name="form1">
Miles <input type="text" size="21" name="txtMiles">

Gallons <input type="text" size="20" name="txtGallons">

<input type="button" name="btnCalc" value="Calculate MPG" onclick="calcMPG()">

<input type="reset" name="btnClear" value="Clear">

Miles Per Gallon
<input type="text" size="20"    name="txtMPG">

</form>

A: Try add your script tag bottom of the body tag.


text:
Q: Xamarin for android: unable to play mp3 from external folder I am unable to play an mp3 file that I placed in the files folder of my application's external storage.
I requested the permission in OnCreate()
    private const int EXTERNAL_READ_WRITE_REQUEST = 1337;

    protected override async void OnCreate(Bundle savedInstanceState)
    {
        ActivityCompat.RequestPermissions(this, new string[]
        {
            Manifest.Permission.ReadExternalStorage,
            Manifest.Permission.WriteExternalStorage
        },
        EXTERNAL_READ_WRITE_REQUEST);
    }

Then I verified the permission was granted:
    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        if (requestCode == EXTERNAL_READ_WRITE_REQUEST)
        {
            if (grantResults.ToArray().ToList().IndexOf(Permission.Denied) == -1)
            {
                ShowMessage("Permissions granted");
            }
            else
                ShowMessage("Permission request denied, unable to continue.");
        }

        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }

Then in the service (not activity) I check the permission, get the folder, get the file, and try to play the mp3 with the MediaPlayer class:
    MediaPlayer player;

    public string GetSongDirectory()
    {
        string result = "";

        List<Java.IO.File> files = GetExternalFilesDirs(null).ToList();

        files = files.OrderBy(x => x.AbsolutePath.IndexOf("emulated")).ToList();

        var f = files.DefaultIfEmpty(null).FirstOrDefault();

        if (f != null)
        {
            result = f.AbsolutePath + "/songs";

            if (Directory.Exists(result) == false)
                Directory.CreateDirectory(result);
        }

        return result;
    }

    [return: GeneratedEnum]
    public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
    {
        string songFolder = GetSongDirectory();

        var p = ContextCompat.CheckSelfPermission(this.ApplicationContext, Manifest.Permission.ReadExternalStorage);

        if (p == Android.Content.PM.Permission.Granted)
        {
            try
            {
                foreach (string fileName in System.IO.Directory.GetFiles(songFolder, "*.*", SearchOption.AllDirectories))
                {
                    player = new MediaPlayer();

                    JFile f = new JFile(fileName);

                    Java.IO.FileInputStream fs = new FileInputStream(f);

                    player.Reset();
                    //player.SetDataSource(fileName); this didn't work either
                    player.SetDataSource(fs.FD, 0L, f.Length());
                    player.Prepare();
                    player.Start();

                    break;
                }
            }
            catch (Exception x)
            {
                x.ToString();
            }
        }

        Toast.MakeText(this, "Greetings from serivce", ToastLength.Long).Show();

        return StartCommandResult.Sticky;
    }

However, on the call to Prepare, it throws the exception:
{Java.IO.IOException: Prepare failed.: status=0x1
  at Java.Interop.JniEnvironment+InstanceMethods.CallVoidMethod

The fileName contains "/storage/1606-3C08/Android/data/com.companyname.mypod/files/songs/IshDARR - Alpha.mp3"
How can I play this mp3 file from my service in xamarin when it belongs to the external SD card?
Edit: I am able to read the file's content using BinaryReader so its not a file access permissions issue.

A: I found an answer online, but lost the original author so is how to play an mp3 from an external sd card on xamarain:
    public class StreamMediaDataSource : MediaDataSource
    {
        System.IO.Stream data;

        public StreamMediaDataSource(System.IO.Stream Data)
        {
            data = Data;
        }

        public override long Size
        {
            get
            {
                return data.Length;
            }
        }

        public override int ReadAt(long position, byte[] buffer, int offset, int size)
        {
            data.Seek(position, System.IO.SeekOrigin.Begin);
            return data.Read(buffer, offset, size);
        }

        public override void Close()
        {
            if (data != null)
            {
                data.Dispose();
                data = null;
            }
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (data != null)
            {
                data.Dispose();
                data = null;
            }
        }
    }

Here is a snippet:
StreamReader sr = new StreamReader(fileName);
player.SetDataSource(new StreamMediaDataSource(sr.BaseStream));
player.Prepare();
player.Start();

I believe the reason why it was failing was because of the method it was using to read the file.
If I try to to read the file using FileStream. It throws a access denied exception even though it has had access granted through it through the user prompt.
This was the java log in case anyone needs to search it through google:
06-10 11:37:26.048 E/MediaPlayerNative(31944): error (1, -2147483648)
06-10 11:37:26.175 D/Mono    (31944): DllImport searching in: '__Internal' ('(null)').
06-10 11:37:26.175 D/Mono    (31944): Searching for 'java_interop_jnienv_call_object_method'.
06-10 11:37:26.175 D/Mono    (31944): Probing 'java_interop_jnienv_call_object_method'.
06-10 11:37:26.176 D/Mono    (31944): Found as 'java_interop_jnienv_call_object_method'.


text:
Q: Valores repetidos ao fazer um INNER JOIN Esse código abaixo está trazendo valores repetidos na tela.
Alguém poderia me ajudar ?
$id_credenciado = $_SESSION['id_credenciado'];

//$sql = mysqli_query($conn, "SELECT DISTINCT * FROM tb_protocolo INNER JOIN tb_certidao ON tb_protocolo.id_credenciado = tb_certidao.id_credenciado WHERE tb_protocolo.id_credenciado = $id_credenciado AND tb_certidao.id_credenciado = $id_credenciado");

$sql = mysqli_query($conn, "SELECT DISTINCT * FROM tb_protocolo INNER JOIN tb_certidao WHERE tb_protocolo.id_credenciado = $id_credenciado AND tb_certidao.id_credenciado = $id_credenciado");

A: Na verdade não está trazendo valores repetidos.
O que acontece é que o distinct compara todas as colunas.
Basta uma coluna no registro estar diferente que ele já vai separar em dois registros.
Para solucionar isso você precisa especificar somente as colunas da busca que você precisa, ao invés de trazer todas usando o asterisco (*).

A: Teste fazer assim:
$sql = mysqli_query($conn,
"SELECT DISTINCT p.* FROM tb_protocolo p INNER JOIN tb_certidao c ON c.id_credenciado = p.id_credenciado WHERE c.id_credenciado = $id_credenciado");

Estamos juntando a tabela de certidão na consulta ligando ao código principal da primeira tabela.


text:
Q: Integration of Paypal using Drupal - Which module do you recommend? I'm building a Drupal website. It's for a coming and important event(symposium) at yhe university. Every participant of the event must paid it. The organization wants to use Paypal.
I'm new in Drupal 7. I need a secure and nice module to works with Paypal. I found two interesting modules on the Internet but I don't know what could be the best ?

*

*Drupal Commerce.

*Ubercart.

Any idea?
Thanks a lot.

A: I would suggest drupal commerce. Integrating paypal will be easy. You can find the contrib module at https://www.drupal.org/project/commerce_paypal .
And moreover drupal commerce provides much more flexibility in dealing with ecommerce platform.


text:
Q: This code does not completely sort a linked list as expected I am new to programing and so I am trying out a program to sort a linked list by insertion sort algorithm. I want to swap the nodes and not just the elements. Although I have seen alternative implementations on the internet, but I'm curious to understand why my current implementation isn't giving the expected output.
My code returns immediately after one swap operation without going through the entire list. Here is my current implementation:
sort.h
/**
 * struct listint_s - Doubly linked list node
 *
 * @n: Integer stored in the node
 * @prev: Pointer to the previous element of the list
 * @next: Pointer to the next element of the list
 */

typedef struct listint_s
{
const int n;
    struct listint_s *prev;
    struct listint_s *next;
} listint_t;

void print_list(const listint_t *list);
void insertion_sort_list(listint_t **list);

sort.c
#include "sort.h"
/**
 * insertion_sort_list - Sorts a list of integers using insertion sort algorithm
 *
 * @list: list of integers to be sorted
 * Return: Nothing
 */

void insertion_sort_list(listint_t **list)
{
   listint_t *left, *right, *temp;

        if (list == NULL)
                return;
        left = *list;
        right = left->next;

        if (right == NULL)
                return;

        while (right)
        {
                while (1)
                {
                        if (right->n < left->n)
                        {
                                //swap operation

                                temp = left->prev;
                                left->next = right->next;
                                right->next = left;
                                left->prev = right;
                                right->prev = temp;

                                //incase of a list with only two elements
                                if (right->prev == NULL)
                                {
                                        *list = right;
                                        return;
                                }
                                  //update the swapped nodes with the rest of the list
                                else
                                {
                                        right->prev->next = right;
                                        left->next->prev = left;
                                }
                        }

                        //if no swap operation
                        else
                                break;

                        //if swap occurred, update the transversal positions
                        right = left;
                        left = right;

                        //prints list after each swap
                        print_list(*list);

                        //move a step backwards and reiterate the loop
                        if (left->prev != NULL)
                        {
                                right = right->prev;
                                left = left->prev;

                        }

                }

                //continue with the next iteration
                right = right->next;
                left = left->next;
        }
}

    #include <stdio.h>
#include <stdlib.h>
#include "sort.h"

/**
 * create_listint - Creates a doubly linked list from an array of integers
 *
 * @array: Array to convert to a doubly linked list
 * @size: Size of the array
 *
 * Return: Pointer to the first element of the created list. NULL on failure
 */
listint_t *create_listint(const int *array, size_t size)
{
    listint_t *list;
    listint_t *node;
    int *tmp;

    list = NULL;
    while (size--)
    {
        node = malloc(sizeof(*node));
        if (!node)
            return (NULL);
        tmp = (int *)&node->n;
        *tmp = array[size];
        node->next = list;
        node->prev = NULL;
        list = node;
        if (list->next)
            list->next->prev = list;
    }
    return (list);
}

/**
 * main - Entry point
 *
 * Return: Always 0
 */
int main(void)
{
    listint_t *list;
    int array[] = {19, 48, 99, 71, 13, 52, 96, 73, 86, 7};
    size_t n = sizeof(array) / sizeof(array[0]);

    list = create_listint(array, n);
    if (!list)
        return (1);
    print_list(list);
    printf("\n");
    insertion_sort_list(&list);
    printf("\n");
    print_list(list);
    return (0);
}

    #include <stdio.h>
#include "sort.h"

/**
 * print_list - Prints a list of integers
 *
 * @list: The list to be printed
 */
void print_list(const listint_t *list)
{
    int i;

    i = 0;
    while (list)
    {
        if (i > 0)
            printf(", ");
        printf("%d", list->n);
        ++i;
        list = list->next;
    }
    printf("\n");
}

I tried to sort a list with the following set of integers:
Input: 19, 48, 99, 71, 13, 52, 96, 73, 86, 7
Output: 19, 48, 71, 99, 13, 52, 96, 73, 86, 7 //swapped only 71
Expected output:
19, 48, 71, 99, 13, 52, 96, 73, 86, 7
19, 48, 71, 13, 99, 52, 96, 73, 86, 7
19, 48, 13, 71, 99, 52, 96, 73, 86, 7
19, 13, 48, 71, 99, 52, 96, 73, 86, 7
13, 19, 48, 71, 99, 52, 96, 73, 86, 7
13, 19, 48, 71, 52, 99, 96, 73, 86, 7
13, 19, 48, 52, 71, 99, 96, 73, 86, 7
13, 19, 48, 52, 71, 96, 99, 73, 86, 7
13, 19, 48, 52, 71, 96, 73, 99, 86, 7
13, 19, 48, 52, 71, 73, 96, 99, 86, 7
13, 19, 48, 52, 71, 73, 96, 86, 99, 7
13, 19, 48, 52, 71, 73, 86, 96, 99, 7
13, 19, 48, 52, 71, 73, 86, 96, 7, 99
13, 19, 48, 52, 71, 73, 86, 7, 96, 99
13, 19, 48, 52, 71, 73, 7, 86, 96, 99
13, 19, 48, 52, 71, 7, 73, 86, 96, 99
13, 19, 48, 52, 7, 71, 73, 86, 96, 99
13, 19, 48, 7, 52, 71, 73, 86, 96, 99
13, 19, 7, 48, 52, 71, 73, 86, 96, 99
13, 7, 19, 48, 52, 71, 73, 86, 96, 99

7, 13, 19, 48, 52, 71, 73, 86, 96, 99 //sorted list

Removing the break statement in the code threw it into an infinite loop. Please help.

A: What you have there is not an insertion sort. It's close, but there are a number of things breaking it, including the way you are thinking about it.
The main problem is that it is, as coded, too complicated to keep everything straight in your head, so you mixed things up. Part of that is also the names you are using.
Insertion Sort
Insertion sort divides a sequence up into two partitions: sorted and unsorted, in that order.
[1 2 3 4][7 8 0 6 9 5]
 ↑        ↑
 sorted   unsorted

You have already thought about this a little. The sort starts with a sorted partition of length 1.
[3][4 1 2 7 8 0 6 9 5]

Then, while there are unsorted elements (the unsorted partition is not empty), take the first unsorted and find its new position. Move it there, shifting all elements between the new position (inclusive) and old position (exclusive) rightward one.
[3 4][1 2 7 8 0 6 9 5]
[1 3 4][2 7 8 0 6 9 5]
[1 2 3 4][7 8 0 6 9 5]
...
[0 1 2 3 4 6 7 8 9][5]
[0 1 2 3 4 5 6 7 8 9][]

This is a pretty simple algorithm. Two loops: one to traverse the list, and one to scan backwards for the place to insert each time.
Doubly-Linked List Insertion Sort
Linked lists give us an interesting twist here. A normal insertion sort has to repeatedly swap the unsorted element leftward until it is in place. But with a linked list that is a lot of work.
Instead, we can simply unlink the node, and insert it in the correct position. There is no need to do repeated adjacent element swaps!
while (unsorted elements remain):
  found ⟵ scan back to find the node to insert after (this is your inner loop)
  node ⟵ extract first unsorted node
  if (found == NULL):
    insert node at front of list
  else:
    insert node after found

Graphically, that looks like this:
[1]→[3]→[4]→[2]→[7]→[8]→[0]→[6]→[9]→[5]
             ↑
             unsorted

Start searching backwards...
         found
         ↓
[1]→[3]→[4]→[2]→[7]→[8]→[0]→[6]→[9]→[5]
             ↑
             unsorted

...until we find a node where found->n ≤ unsorted->n
 found
 ↓
[1]→[3]→[4]→[2]→[7]→[8]→[0]→[6]→[9]→[5]
             ↑
             unsorted

Extract the unsorted node, making sure to update unsorted to point to the next available node (if any):
            extracted node
            ↓
 found     [2]
 ↓
[1]→[3]→[4]→[7]→[8]→[0]→[6]→[9]→[5]
             ↑
             (the new) unsorted

Insert the extracted node after the found found node:
 found
 ↓
[1]→[2]→[3]→[4]→[7]→[8]→[0]→[6]→[9]→[5]
     ↑           ↑
     node        unsorted

Done! Ready for the next loop.
[1]→[2]→[3]→[4]→[7]→[8]→[0]→[6]→[9]→[5]
                 ↑
                 unsorted

Extract and Insert Nodes
If you don't already, you will need some functions to unlink and insert nodes from/into a list. I recommend:
void unlink_node (listint_t **list, listint_t *node);

void append_node (listint_t **tail, listint_t *node);
void prepend_node(listint_t **head, listint_t *node);
// Unlike other list functions, `head` and `tail` need not point to the
// head of the list (though they could)! Their values are updated, however,
// to maintain the whole list and their head/tail position in the sublist.

You should not be doing this manually inside your sort function! All it does is add complexity that makes it harder to see what you are doing. Abstract those operations elsewhere and keep your sort function short and clean.
My version of your insertion sort function is about 12 lines long. You should be able to do something similar — twenty lines maximum with heavy commentary.
Apologies
I know this is a bit to think about, and not a fix-your-code kind of answer. Honestly, you got lost and your code is pretty badly broken. Toss the sorting code you wrote and start over. The hints I give above are far more direct than you may think.
Always think about your algorithm before you start hacking out code. In this case we can see that it benefits us to have the link and unlink helper functions. That abstracts the complexity of those operations away so that we don't overwhelm ourselves when trying to sort. By breaking your code up into smaller chunks, everything you do is significantly less complex, letting you focus on a simpler problem without stumbling into the weeds.
Main
Here is the main function I wrote to play with this:
#include <stdio.h>
#include <stdlib.h>
#include "listint.h"

int main(int argc, char **argv)
{
    listint_t *list = NULL;

    // Convert program arguments into linked list of integers
    listint_t *tail = list;
    for (int n = 1;  n < argc;  n++)
    {
        append_node(&tail, new_node(atoi(argv[n])));
        if (!list) list = tail;
    }

    // Sort the list and show the user
    insertion_sort_list(&list);
    print_list(&list);

    // Don't forget to clean up!
    free_list(&list);
    return 0;
}

And some example runs:
C:\Users\Dúthomhas\programming\cpp\foo> main 2 1 -7 34 5
-7 1 2 5 34

C:\Users\Dúthomhas\programming\cpp\foo> main 3 3 3
3 3 3

C:\Users\Dúthomhas\programming\cpp\foo> main 0
0

C:\Users\Dúthomhas\programming\cpp\foo> main 1 2 3
1 2 3

C:\Users\Dúthomhas\programming\cpp\foo> main 4 2
2 4

Consistency
Your linked list functions should be as consistent as possible. For example,
the print_list() function should take a listint_t **, just like all the other list functions. Even though it doesn't need a reference to the list, it makes using it work just like any other list function.
Your indentation and spacing is pretty good. I assume the inconsistencies were just where you were messing with it. Personally, eight spaces is a very wide indent. Switch to 2 or 4.
Names
Choose names that reflect what a thing is or does. You seem to be already aware of this to some degree. Choice of left and right in your algorithm suggests to me part of the logic you tried to implement (and why that logic failed — sorting a linked list is different than sorting an array).
As you think about the algorithm, before you even start writing code, you should be generating names for things that reflect what your algorithm is doing. My version of the sort uses the very same names I created when I thought through the algorithm above: unsorted, node, find.
Likewise, even the filenames you choose matter. The header file, for example, has as its primary purpose describing a doubly-linked list of integers and the operations that can be performed on them — one of which (the primary one for this homework, I assume) is sorting it. But sorting is still just an appendage to maintaining a list. Hence, the files I created to play with this are named:
listint.h
listint.c
main.c

Commentary and documentation
The header file is your primary source of documentation for any library. Put the primary doxygen markup there.
Remember, the purpose of documentation is for users of your library. Users should not care about anything except the interface presented to them.
Here we have a listint_t, and functions to work over a listint_t *.
#ifndef LISTINT_H
#define LISTINT_H

/**
 * listint_t - Doubly linked list node
 *
 * @n: Integer stored in the node
 * @prev: Pointer to the previous element of the list
 * @next: Pointer to the next element of the list
 */
typedef struct listint_s
{
    const int n;
    struct listint_s *prev;
    struct listint_s *next;
} listint_t;

/**
 * new_node() - Create a new node
 *
 * @n: Integer to store in the node
 *
 * Return: The new, unlinked node, or NULL on allocation failure.
 */
listint_t *new_node(int n);

/**
 * free_list() - Delete an entire list
 *
 * @list: Reference to the list to delete. May not be NULL.
 *        (The referenced list itself may be NULL, though.)
 */
void free_list(listint_t **list);

/**
 * append_node()
 * prepend_node()
 * unlink_node()  - Add or remove nodes in a list
 *
 * @tail: Reference to the last node in a sublist
 * @head: Reference to the first node in a sublist
 * @list: Reference to the list to modify.
 * @node: The node to add or remove. If adding,
 *        the node must not be part of any list.
 *        If removing, the node must be a member
 *        of the argument list.
 */
void append_node (listint_t **tail, listint_t *node);
void prepend_node(listint_t **head, listint_t *node);
void unlink_node (listint_t **list, listint_t *node);

/**
 * insertion_sort_list() - Sorts a list of integers using insertion sort algorithm
 *
 * @list: Reference to the list of integers to be sorted
 */
void insertion_sort_list(listint_t **list);

/**
 * print_list() - Print a list to stdout
 *
 * @list: Reference to the list
 */
void print_list(listint_t **list);

#endif

(Sorry for abusing the Doxygen markup a little, but my patience with it is thin for some fun question I found on the internet.)
This stuff is hard. But it will make sense eventually. Keep going!


text:
Q: Make single widget area top level in 4.0 Customize Panel So I have a widget area that, in v4.0, is burried in a dropdown within the secondary Widgets panel on the Customize panel page.
Because it's the only widget area it feels rather silly being burried so deeply, so I'm wondering if there's a way to override the nesting and make that widget area dropdown a top-level section like it was in v3.x?
It looks like this was brought up by the Core team here, but didn't gain any traction.
Does anyone know how I might be able to do this?

A: Got it.
Admittedly, this feels hacky but seems to do the job just fine.
In my existing customize_register hook I set the following:
// Retreive the widget section in the Theme Customizer
// We need to cast the return of get_section to an object
// "the_widgets_section" in get_section is the ID of the registered widget area
$widget_area = (object) $wp_customize->get_section( 'sidebar-widgets-the_widgets_section' )
// The value of panel will be 'widgets', so we set it back to '' (top level panel)
$widget_area->panel = '';
// If you're so inclined, we can change the title of it as well.
$widget_area->title = __( 'My Widgets', 'textdomain' );


text:
Q: Rails 5 error: No route matches [DELETE] "/comments" I am currently trying to delete a comment the exact same way I can delete a post in my application. However, for some reason the exact same code does not seem to work for my comments an returns the following error:
No route matches [DELETE] "/comments"
def destroy
   @post = @comment.post
   @comment.destroy
   respond_to do |format|
      format.html { redirect_to @post, notice: 'Comment was successfully destroyed.' }
      format.json { head :no_content }
   end
end

This is what my model looks like:
class Comment < ApplicationRecord
    belongs_to :post
    belongs_to :user
end

This is what my route looks like:
Rails.application.routes.draw do
   resources :posts
   resources :users
   resources :comments, only: [:create, :destroy]

   #signup and register workflow
   get '/signup' => 'users#new'
   get '/login' => 'sessions#new'
   post '/login' => 'sessions#create'
   delete '/logout' => 'sessions#destroy'
end

This is what my link in my view looks like (Slim):
   - @comments.each do |comment|
      .comment-container.level-0
        p
        a href="/users/#{comment.user_id}" = comment.user.first_name
        | :
        = comment.comment
        - if comment.user == current_user
          .icon-delete
            = link_to "Delete", comment, method: :delete, data: { confirm: 'Are you sure?' }
    end
    hr
    h3 Write a new comment
    = bootstrap_form_for(@comment) do |c|
      .field
        = c.text_field :comment
      .field
        = c.hidden_field :user_id, :value => current_user.id
        = c.hidden_field :post_id, :value => @post.id
      .actions
        = c.submit

A: I guess you just missed the format of the link_to method:
= link_to "Delete", comment, method: :delete, data: { confirm: 'Are you sure?' }

It should be like: link_to(body, url, html_options = {})
You missed the body part.
Check here
EDIT

I just realised that when I posted this comment: If I try this, then
  the error is: undefined method `post' for nil:NilClass

Ok, the problem is: When you click on the link it goes to the destroy method. Then it tries to query like @post = @comment.post. As you can see in the link you're sending comment. So in the destroy method you should fetch the post like:
def destroy
   @comment = Comment.find(params[:id])
   @post = @comment.post
   @comment.destroy
   respond_to do |format|
      format.html { redirect_to @post, notice: 'Comment was successfully destroyed.' }
      format.json { head :no_content }
   end
end

Then you'll be good to go. :)


text:
Q: Go - Custom unmarshaler - string to float I consume a 3th party API that gives me the price as a string, there are 3 flavours:
//Input
[
    {"id": "A", "price": "123"},
    {"id": "B", "price": "123.5"},
    {"id": "C", "price": ""}
]

//Expected output

[
    A 123,
    B 123.5,
    C 0
]

I know i can add the ,string part inside my struct but this will not handle order C. I have found this github issue where this question is asked about int's. In there there is a playground code that i altered a little bit to my needs.
If i change this to float64 instead of int i get an error with the log of order A that is now 0.
json: cannot unmarshal string into Go struct field Order.price of type float64
[{A 0}]

I thought that this if string(data) ==  '""' { part of the code will check for the empty string (case order C) if so: set to 0. But "123" is not "". The rest of the custom unmarshaler i understand apart from the part below. Can someone point me to the right direction?
p := (*float64)(foe)
*p = f

The full code Also here
package main

import (
    "encoding/json"
    "fmt"
    "strings"
)

type StringToFloat float64

type Order struct {
    Id    string        `json:"id"`
    Price StringToFloat `json:"price"`
}

func (foe *StringToFloat) UnmarshalJSON(data []byte) error {
    if string(data) == `""` {
        if foe != nil {
            *foe = 0
        }
        return nil
    }

    var f float64
    err := json.Unmarshal(data, &f)
    if err != nil {
        return err
    }
    p := (*float64)(foe)
    *p = f
    return nil
}

func main() {
    jsonString := `[
        {"id": "A", "price": "123"},
        {"id": "B", "price": "123.5"},
        {"id": "C", "price": ""}
    ]`
    var orders []Order
    if err := json.NewDecoder(strings.NewReader(jsonString)).Decode(&orders); err != nil {
        fmt.Println(err)
    }

    fmt.Println(orders)
}

EDIT: comment @mkopriva
I adjusted the unmarshaler:
func (foe *StringToFloat) UnmarshalJSON(data []byte) {
    fmt.Println(string(data))
    if string(data) == `""` {
        if foe != nil {
            *foe = 0
        }
    }

    n, err := strconv.ParseFloat(string(data), 64)
    if err != nil {
        fmt.Println(err)
    }

    *foe = StringToFloat(n)
}

What gives me this output:
json: cannot unmarshal string into Go struct field Order.price of type main.StringToFloat
[{A 0} {B 0} {C 0}]

A: Try this
package main

import (
    "encoding/json"
    "fmt"
    "strconv"
    "strings"
)

type StringToFloat float64

type Order struct {
    Id    string        `json:"id"`
    Price StringToFloat `json:"price"`
}

func (foe *StringToFloat) UnmarshalJSON(data []byte) error {
    if string(data) == "\"\"" {
        if foe != nil {
            *foe = 0
        }
        return nil
    }
    num := strings.ReplaceAll(string(data), "\"", "")
    n, err := strconv.ParseFloat(num, 64)
    if err != nil {
        return err
    }
    *foe = StringToFloat(n)
    return nil
}

func main() {
    jsonString := `[
        {"id": "A", "price": "123"},
        {"id": "B", "price": "123.5"},
        {"id": "C", "price": ""}
    ]`
    var orders []Order
    if err := json.NewDecoder(strings.NewReader(jsonString)).Decode(&orders); err != nil {
        fmt.Println(err)
    }

    fmt.Println(orders)
}

Go playground: https://go.dev/play/p/cHjNQ447eX9
Things to note:

*

*The function signature of UmarshalJSON func needs to be exactly the same as given to be picked up by Decode. In your updated code error return type was missing

*string(data) gives "123" so the quotes need to be removed before ParseFloat

*return nil is required after string = "" check so it dosent go further


text:
Q: Path not added to $PATH variable when executing a command First of all, the context of this question is: Cannot install psycopg2 on OSX 10.6.7 with XCode4
So I am trying to execute the following:
$PATH=$PATH:/Library/PostgreSQL/9.1/bin sudo env ARCHFLAGS="-arch i386 -arch x86_64" pip install psycopg2

however, I get the following:
/opt/local/bin:/opt/local/sbin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin:/usr/texbin:/usr/X11/bin=/opt/local/bin:/opt/local/sbin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin:/usr/texbin:/usr/X11/bin:/Library/PostgreSQL/9.1/bin: No such file or directory

Basically, I need to add '/Library/PostgreSQL/9.1/bin' to $PATH, so that the rest of the command can be executed as it needs something from that directory.
Any suggestion?

A: Variables being assigned to shouldn't have a $.
PATH=...

A: try:
export PATH=$PATH:/Library/PostgreSQL/9.1/bin sudo env ARCHFLAGS="-arch i386 -arch x86_64" pip install psycopg2

A: Issue this commnad:
export PATH=$PATH:/Library/PostgreSQL/9.1/bin sudo env ARCHFLAGS="-arch i386 -arch x86_64" pip install psycopg2

A: Yep, remove the $ as already mentioned.  You might also need the -E option to sudo, or to change the env_reset setting in sudoers.  You also can specify environment variables after sudo.
sudo -E PATH="..." ARCH="..." pip install whatever


text:
Q: C++ Text to Morse Code I was given a .txt file with the chars and the translation for them in morse code. I was told that I had to read the .txt file into two different arrays.
One array will contain the characters that are being mapped from and the second array will contain the equivalent Morse code.
this is what the .txt file contains.
39
,  --..--
. .-.-.-
?  ..--..
0 -----
1  .----
2  ..---
3  ...--
A  .-
and so on.
void readFile(string userMapping)
{

    fstream mappingFile;

    mappingFile.open(userMapping);

    if (mappingFile.is_open())
    {
        // call the next function
        cout << "Hello World!"; // ignore this, I was testing to see if the file was open.
    }
    else
    {

    }
}

How do I go about reading the file into two dynamically sized arrays from what they are asking here?
"One array will contain the characters that are being mapped from and the second array will contain the equivalent Morse code."

A: You might consider using the character as a subscript int into array where your code characters are.


text:
Q: How to avoid WebDriver getting stuck while waiting for Google Ads or Google Analytics to load? I'm using Selenium WebDriver (C# library) for UI automation. The web app uses google ads and google analytics on most of pages.
When I run the tests after a while (about 50 tests executed) all tests get stuck and eventualy fail while waiting for google ads and analytics to load.

*

*Has anyone had this problem?

*How would you work around this issue?

But before you answer 'create a build just for tests without google ad scripts' lets say its not an option.

A: You could

*

*use the hosts file trick to block the google ad servers (but this would block them for all users of that PC, not just the selenium tests)

*set up an http proxy such as squid, and configure it to return empty content from those sites.

*use a custom firefox profile that uses NoScript to block those sites


text:
Q: OpenVPN Server Port Forwarding I'm sorry if this question was asked already, but I didn't even know how to search for it, so if you already have a solution, please be kind enough to reply with a link.
So a friend of mine has a 4g connection as their internet connection without a public IP address and they wanted to access a samba share remotely. I have a vdsl connection with a public IP address and I run an OpenVPN server on a raspberry pi, so they asked me if they could use my VPN to use my private IP address to connect to their samba share. I can't figure out how to do this but I really want to help my friend out. Thanks in advance to anyone who can help.

A: you can do what you asked for, here is some instructions to achieve it.
it is a matter of port forwarding, so you first have to control what internal IP address you give to your 4G client, you can do this by using openssl key, and setup a special profile with a dedicated address attached to this special key using the ccd directory and making a file named after the key in that directory.
that is, in your openvpn server.conf just add
client-config-dir ccd

if your client key name is samba4Gshare then create a file /etc/openvpn/ccd/samba4Gshare
and put in it some dedicated IP address (for example if your openvpn internal lan is 192.168.2.0/24)
ifconfig-push 192.168.2.6 192.168.2.5

So 192.168.2.6 will be the dedicated IP for your samba4Gshare and 192.168.2.5 will be used internally by openvpn for connections with this client.(be aware that openvpn by default use some /30 internal subnets so you have to segment your internal LAN in some /30)
Then you setup an openvpn client on your samba share using this openssl key so your client connect to your openvpn server and got the dedicated IP address.
once the client connect with its dedicated key and it has this special fixed IP address, if you use iptables/netfilter you can just forward connections from your raspberryPI IP with DNAT in table nat/PREROUTING to the samba share openvpn dedicated IP address.
At this time, you may be able to see the share from your RaspberryPI IP address using a client in your local private LAN.
After that, last part is to forward a port from your VDSL to your raspberryPi so you can use this port to access your samba share from the public IP of your VDSL. As a matter of fact you need to ajust route on your samba share so the connections that came from your openvpn links get back to the same ways to the requester. it may require some MASQUERADE or dynamic route based on port if your samba share has different route to reach internet or your openvpn segment.
For instance if you MASQUERADE on your openvpn server it may works correctly directly out of the box, but your samba share may not see what real IP is requesting the share, because for this share every request seems to come from your openvpn server. It may not be very secure to not control the area that is allowed.
VDSL(Pub IP)-->RASPBERRY(Private IP)-->SAMBA(openvpn IP)

where --> mean port forward.
if you give detail on what are your internals IP and router I can give you samples commands.
regards and good luck.


text:
Q: R xts lag() function only lags 1 position I have some confusion about the xts lag() function.  No matter what value I assign for k, I get the identical 1 position lag.
Using the examples from https://www.rdocumentation.org/packages/xts/versions/0.12-0/topics/diff.xts:
(x <- xts(1:10, Sys.Date()+1:10))
(x1 = lag(x))
(x2 = lag(x, k=2))
(lag(x, k=-1, na.pad=FALSE))

           [,1]
2020-04-20    1
2020-04-21    2
2020-04-22    3
2020-04-23    4
2020-04-24    5
2020-04-25    6
2020-04-26    7
2020-04-27    8
2020-04-28    9
2020-04-29   10
           [,1]
2020-04-20   NA
2020-04-21    1
2020-04-22    2
2020-04-23    3
2020-04-24    4
2020-04-25    5
2020-04-26    6
2020-04-27    7
2020-04-28    8
2020-04-29    9
           [,1]
2020-04-20   NA
2020-04-21    1
2020-04-22    2
2020-04-23    3
2020-04-24    4
2020-04-25    5
2020-04-26    6
2020-04-27    7
2020-04-28    8
2020-04-29    9
           [,1]
2020-04-20   NA
2020-04-21    1
2020-04-22    2
2020-04-23    3
2020-04-24    4
2020-04-25    5
2020-04-26    6
2020-04-27    7
2020-04-28    8
2020-04-29    9

What might I be failing to understand here?

A: It's highly likely dplyr that's causing the mess.
library(dplyr)
# Attaching package: 'dplyr'
#
# The following objects are masked from 'package:xts':
#
#   first, last
#
# The following objects are masked from 'package:stats':
#
#   filter, lag  <-------------------------------------------   !!!
#
# The following objects are masked from 'package:base':
#
#   intersect, setdiff, setequal, union

You may carefully read those starting messages and add stats:: before the function in this case (look up ?lag and you'll see a list of alterntives).
Comparison:
cbind(stats::lag(x), stats::lag(x, k=2), stats::lag(x, k=-1, na.pad=F))
#            stats..lag.x. stats..lag.x..k...2. stats..lag.x..k....1..na.pad...F.
# 2020-04-21            NA                   NA                                 2
# 2020-04-22             1                   NA                                 3
# 2020-04-23             2                    1                                 4
# 2020-04-24             3                    2                                 5
# 2020-04-25             4                    3                                 6
# 2020-04-26             5                    4                                 7
# 2020-04-27             6                    5                                 8
# 2020-04-28             7                    6                                 9
# 2020-04-29             8                    7                                10
# 2020-04-30             9                    8                                NA

cbind(dplyr::lag(x), dplyr::lag(x, k=2), dplyr::lag(x, k=-1, na.pad=F))
#            dplyr..lag.x. dplyr..lag.x..k...2. dplyr..lag.x..k....1..na.pad...F.
# 2020-04-21            NA                   NA                                NA
# 2020-04-22             1                    1                                 1
# 2020-04-23             2                    2                                 2
# 2020-04-24             3                    3                                 3
# 2020-04-25             4                    4                                 4
# 2020-04-26             5                    5                                 5
# 2020-04-27             6                    6                                 6
# 2020-04-28             7                    7                                 7
# 2020-04-29             8                    8                                 8
# 2020-04-30             9                    9                                 9

xts::lag.xts is actually a method of the xts package that tells stats::lag how to deal with time series. However you may use it directly as you already discovered. Both results are identical.
cbind(lag.xts(x), lag.xts(x, k=2), lag.xts(x, k=-1, na.pad=F))
#            lag.xts.x. lag.xts.x..k...2. lag.xts.x..k....1..na.pad...F.
# 2020-04-21         NA                NA                              2
# 2020-04-22          1                NA                              3
# 2020-04-23          2                 1                              4
# 2020-04-24          3                 2                              5
# 2020-04-25          4                 3                              6
# 2020-04-26          5                 4                              7
# 2020-04-27          6                 5                              8
# 2020-04-28          7                 6                              9
# 2020-04-29          8                 7                             10
# 2020-04-30          9                 8                             NA

Note: Maybe you load some packages automatically with a manipulated .rprofile file. I'd recommend not to do such things and delete library/require calls there. Another possibility is that you load another package that uses dplyr as dependency (e.g. `tidyverse'). Anyway, in all cases the solution above works (but it is tedious to find out every time which base R function has been overwritten again by some sloppy package!).


text:
Q: Percentage of signed up users for beta is wrong on Area 51 The percentage of users that committed to the proposal and then joined the beta, displayed in the right sidebar on Area 51, shows 0% for all the older proposals.

The cutoff seems to be around 90 days, all older proposals show 0% signed up, the newer proposals show a proper value.

A: This is fixed now. Thanks.
A couple months ago, we changed the way that we store each site's "beta access whitelist", and the old way was accidentally made incompatible with our mechanism for fetching "% signed up for beta" stats.


text:
Q: Ratios of numbers of distinct prime factors in successive numbers: is every n:1 ratio realizable by a composite number? Let $\omega(n)$ refer to the number of distinct prime factors of $n$.
I'm curious about what values of $\frac{\omega(n-1)}{\omega(n)}$ (which I'll call $\alpha(n)$ for convenience) can be realized by composite numbers.
As it turns out, there are many composite $n$ such that $\alpha(n)$ is $2,3,4,5,6$ ...
$2$ is very easy to achieve with a prime power.
16
25
27
49

So is $3$.
121
169
256
343

And so on up to 6.
175561
212521
326041
434281

Seven has a few but they're harder to find.
2042041
7447441
9393931

I'm curious whether every possible for $\alpha(n)$ is realizable by some composite $n$.
The examples that have turned up so far are prime powers and mostly squares of primes at that.

Update #1:
Interestingly, if you remove the restriction that $n$ has to be composite, there are relatively small solutions for $\alpha^{-1}(8)$ and $\alpha^{-1}(9)$.
Here are the solutions for $\alpha^{-1}(9)$ that I've found so far, all are prime.
300690391
340510171
358888531
397687291
406816411

Another pattern that seems to hold is that the smallest solution to $\alpha^{-1}(n)$ is less than $10^n$.

Update #2
It's possible that $\omega(-1 + 2^{\mathbb{N}_{\ge 1}})$ is $\mathbb{N}_{\ge 1}$. Since powers of two have exactly one prime factor, this is useful for establishing the truth of the lemma.
This OEIS sequence has the number of distinct factors of $-1+2^n$ https://oeis.org/A046800.
Some cursory investigation using pari/gp also suggests that this hits every positive integer.
$$ \omega(-1 + 64 ^ {60}) = 29 \\
   \omega(-1 + 64 ^ {66}) = 27 \\
   \omega(-1 + 64 ^ {70}) = 34
$$

A: PARTIAL ANSWER
That every integer ratio $n$ can be achieved , is probably impossible to be proven. But in the range $[2,16]$ , there are solutions in form of $p^4$ , where $p$ is a prime number :
2     16     2
5     625     3
11     14641     4
13     28561     5
43     3418801     6
83     47458321     7
307     8882874001     8
463     45954068161     9
1597     6504586067281     10
4217     316238254381921     11
20747     185276879591884081     12
102829     111805314979382104081     13
328901     11702018374499428575601     14
1799797     10492865217042730623781681     15
6498419     1783326405035972793339192721     16

The smallest prime power solutions are
gp > for(k=1,10,n=1;gef=0;while(gef==0,n=n+1;if(ispower(n)>0,if(ispseudoprime(n)==0,if(omega(n)==1,if(omega(n-1)==k,gef=1;print(k,"   ",n)))))))
1   4
2   16
3   121
4   841
5   17161
6   175561
7   2042041
8   214007641

The smallest solutions with more than one prime factor (conjecture : all of them have $2$ prime factors) :
1   15    2
2   391    2
3   30031    2
4   9699691    2

Solutions for larger $\alpha$ :

*

*$\alpha(n)=17$ : $1109^{12}$

*$\alpha(n)=18$ : $1627^{12}$

*$\alpha(n)=19$ : $137^{24}$

*$\alpha(n)=20$ : $211^{24}$
UPDATE : Dirichlet's theorem guarantees that for infinite many positive integers $\ n\ $ , a prime number $\ p\ $ with $\ \alpha(p^2)=n\ $ exists. And if the Schinzel hypothesis is true , such a prime exists for every positive integer $\ n\ $ , hence the above conjecture is true.
Proof :
Define $$t:=\prod_{j=2}^n p_j$$ where $\ n\ge 2\ $ and $\ p_j\ $ is the $j$-th prime number. Dirichlet's theorem guarantees that there is a positive integer $\ s\ $ such that $\ q:=st+1\ $ is prime. Then $$\omega(q^2-1)\ge \omega(q-1)=\omega(st)\ge \omega(t)=n-1$$ Hence $\ \omega(q^2-1)\ $ with prime $\ q\ $ is unbounded. Therefore infinite many $\ n\ $ must be realizable.
Assume that with the above $t$ , we can find a prime $\ p>p_n\ $ such that $\ 2tp+1\ $ and $\ 4tp+1\ $ are both prime. This is possible if the Schinzel hypothesis is true. Then with $\ q:=4tp+1\ $ we have $$\omega(q+1)=\omega(4tp+2)=\omega(2(2tp+1))=2$$ and $$\omega(q-1)=\omega(4tp)=n+1$$ Because of $\ \gcd(q-1,q+1)=2\ $ , we get $$\omega(q^2-1)=\omega(q-1)+\omega(q+1)-1=n+2$$
hence every positive integer $\ n'=n+2\ge 4\ $ is realizable.


text:
Q: Android - Views in Custom Compound Component are not inflated (findByView returns null) I have made a Custom Component in XML, consisting of a button with an imageview stacked on top of it:
<myapp.widget.ClearableCaptionedButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
    android:id="@+id/ccbutton_button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical|left"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:background="@android:drawable/edit_text"/>
<ImageView
    android:id="@+id/ccbutton_clear"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="5dip"
    android:layout_alignRight="@id/ccbutton_button"
    android:layout_alignTop="@id/ccbutton_button"
    android:layout_alignBottom="@id/ccbutton_button"/>
  </myapp.widget.ClearableCaptionedButton>

extract of java source code:
public class ClearableCaptionedButton extends RelativeLayout implements OnClickListener {
...
public ClearableCaptionedButton(Context context, AttributeSet attrs) {
    super(context, attrs);
// some stuff that works fine
}
..

protected void onFinishInflate() {
  super.onFinishInflate();

  mButton = (Button) findViewById(R.id.ccbutton_button);
  mClear = (ImageView) findViewById(R.id.ccbutton_clear);

  mButton.setText("");  // error here: mButton == null
}

My problem is similar to this one. When i try to find the views inside the custom compound, findViewById returns null. But, as you can see, i already added super(context, attrs); to the constructor.
i am using the custom component directly in xml layout, like this:
<LinearLayout>
<!-- some stuff -->
<myapp.widget.ClearableCaptionedButton
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    app:caption="to"/>
</LinearLayout>

can anybody spot something? thanks.

A: I am confused by your two XML layouts.
The second one is where you say you use the widget. Hence, I am assuming that the class named ClearableCaptionedButton is in the package de.pockettaxi.widget.
I am further assuming that the Button and ImageView shown in your first layout are things that are always supposed to be in ClearableCaptionButton, not something supplied by the reuser of ClearableCaptionButton.
If those assumptions are all correct, then you have two problems.

*

*First, you aren't using the first
layout anywhere that I can see.

*Second, the first
layout has reference to a myapp.widget.ClearableCaptionedButton that probably does not exist.

I would replace the myapp.widget.ClearableCaptionedButton element with a <merge> element, then inflate that layout in the constructor or onFinishInflate() of ClearableCaptionedButton.
Here is a sample project from one of my books that shows the use of a custom widget that works in this manner.
Also, given your package name, I hope that it is either a very large pocket or a very small taxi... :-)