heads-up | #Notification | new headsup notifications from Android Lollipop

 by   SimenCodes Java Updated: 9 months ago - v1.14 License: GPL-3.0

Download this library from

Build Applications

kandi X-RAY | heads-up REVIEW AND RATINGS

Heads-up notifications - Get the new heads-up notifications from Android Lollipop on any device, for free!

kandi-support
Support

  • heads-up has a low active ecosystem.
  • It has 181 star(s) with 62 fork(s).
  • It had no major release in the last 12 months.
  • On average issues are closed in 65 days.
  • It has a neutral sentiment in the developer community.

quality kandi
Quality

  • heads-up has 14 bugs (0 blocker, 0 critical, 2 major, 12 minor) and 339 code smells.

security
Security

  • heads-up has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • heads-up code analysis shows 0 unresolved vulnerabilities.
  • There are 28 security hotspots that need review.

license
License

  • heads-up is licensed under the GPL-3.0 License. This license is Strong Copyleft.
  • Strong Copyleft licenses enforce sharing, and you can use them when creating open source projects.

build
Reuse

  • heads-up releases are available to install and integrate.
  • Build file is available. You can build the component from source.
  • heads-up saves you 5484 person hours of effort in developing the same functionality from scratch.
  • It has 11492 lines of code, 279 functions and 133 files with 0 % test coverage
  • It has high code complexity. Code complexity directly impacts maintainability of the code.
Top functions reviewed by kandi - BETA

kandi has reviewed heads-up and discovered the below as its top functions. This is intended to give you an instant insight into heads-up implemented functionality, and help decide if they suit your requirements.

  • Start command .
  • Handles a touch event .
  • Handle an action .
  • Update the game .
  • Handle the intent .
  • Called when a received message is received .
  • Initializes the blacklist .
  • Handle accessibility event .
  • Step 2 .
  • This method is called when a status bar is selected .

heads-up Key Features

Displays notifications as a floating popup

Easily control which notifications to display

Quick actions: mark messages as read in one tap (Android 4.1+, doesn't work with all devices and apps)

Display the heads-up on lock screen as well

Battery friendly! (Email me if you notice significant battery consumption after installing)

Choose how long you want the notifications to display

Pocket detection / active display (causes a tiny increase in battery usage if you get a ton of notifications)

Display notifications on the lock screen until dismissed

Privacy on the lock screen

Multiple themes

Choose popup positioning and opacity

Don't display heads-up while using certain apps

Display a popup for the currently playing song

Compact/expandable mode

Full notification

heads-up examples and code snippets

  • How can I find out how many lines are between a number and the next occurrence of the same number in a file?
  • In Vue3, how to make Custom Component work with v-model for group of checkboxs?
  • NumPy: how to calculate variance along each row of a 2D array using np.var and by hand (i.e., not using np.var; calculating each term explicitly)?
  • How to get canvas onmousemove handler to see latest React state hook value?
  • How do I make this shape in HTML?
  • Can I detect a hanging JS function and abort?
  • React / Gatsby - render different component based on screen size
  • How to convert ByteArray[] to int16 in Python?
  • Use a specific part of code (img src) that I generated using a foreach loop in the page I open using asp-route-id and asp-page
  • Android heads-up notification not showing

How can I find out how many lines are between a number and the next occurrence of the same number in a file?

awk -v c=330 -v p=1 'function pr(n) {
    if( n - p == c)  printf "%s", buf; 
    buf = ""} 
    NF == 1 { pr(NR); p = NR; c = $1 } 
    {buf = sprintf("%s%s\n", buf, $0)} 
    END {pr(NR+1)}' input-file
-----------------------
awk 'BEGIN { RS="i =" } { split($0,bits,"\n");if (length(bits)-1==331) { print RS$0 } }' file > newfile
awk 'BEGIN { 
             RS="i =" 
           } 
           { 
             split($0,bits,"\n");
             if (length(bits)-1==331) { 
                print RS$0 
             } 
           }' file > newfile
-----------------------
awk 'BEGIN { RS="i =" } { split($0,bits,"\n");if (length(bits)-1==331) { print RS$0 } }' file > newfile
awk 'BEGIN { 
             RS="i =" 
           } 
           { 
             split($0,bits,"\n");
             if (length(bits)-1==331) { 
                print RS$0 
             } 
           }' file > newfile
-----------------------
csplit -k infile '/i = /' {*}
wc -l xx* | sed -n 's/^ *331 \(xx.*\)/\1/p'
wc -l xx* | sed -n 's/^ *331 \(xx.*\)/\1/p' | xargs cat > newfile
wc -l xx* | sed -e '$d' -e '/^ *331 \(xx.*\)/d' | xargs cat > failures
-----------------------
csplit -k infile '/i = /' {*}
wc -l xx* | sed -n 's/^ *331 \(xx.*\)/\1/p'
wc -l xx* | sed -n 's/^ *331 \(xx.*\)/\1/p' | xargs cat > newfile
wc -l xx* | sed -e '$d' -e '/^ *331 \(xx.*\)/d' | xargs cat > failures
-----------------------
csplit -k infile '/i = /' {*}
wc -l xx* | sed -n 's/^ *331 \(xx.*\)/\1/p'
wc -l xx* | sed -n 's/^ *331 \(xx.*\)/\1/p' | xargs cat > newfile
wc -l xx* | sed -e '$d' -e '/^ *331 \(xx.*\)/d' | xargs cat > failures
-----------------------
csplit -k infile '/i = /' {*}
wc -l xx* | sed -n 's/^ *331 \(xx.*\)/\1/p'
wc -l xx* | sed -n 's/^ *331 \(xx.*\)/\1/p' | xargs cat > newfile
wc -l xx* | sed -e '$d' -e '/^ *331 \(xx.*\)/d' | xargs cat > failures
-----------------------
$ cat tst.awk
/^ i =/  {
    prt()
    expNumLines = prev + 1
    actNumLines = 2
    rec = prev RS $0
    next
}
NF == 4 {
    rec = rec RS $0
    actNumLines++
}
{ prev = $0 }
END { prt() }

function prt() {
    if ( (actNumLines == expNumLines) && (rec != "") ) {
        print "-------------"
        print rec
    }
}
$ awk -f tst.awk file
-------------
     3
 i =        3, time =        2.000, E =     1234567
  Mg       22.9985897185        6.9311166109        0.7603733573
  O        23.0438129644        6.4358253659        1.5992513709
-------------
     3
 i =        5, time =        3.000, E =     1234567
  Mg       22.9985897185        6.9311166109        0.7603733573
  O        23.0438129644        6.4358253659        1.5992513709
-----------------------
$ cat tst.awk
/^ i =/  {
    prt()
    expNumLines = prev + 1
    actNumLines = 2
    rec = prev RS $0
    next
}
NF == 4 {
    rec = rec RS $0
    actNumLines++
}
{ prev = $0 }
END { prt() }

function prt() {
    if ( (actNumLines == expNumLines) && (rec != "") ) {
        print "-------------"
        print rec
    }
}
$ awk -f tst.awk file
-------------
     3
 i =        3, time =        2.000, E =     1234567
  Mg       22.9985897185        6.9311166109        0.7603733573
  O        23.0438129644        6.4358253659        1.5992513709
-------------
     3
 i =        5, time =        3.000, E =     1234567
  Mg       22.9985897185        6.9311166109        0.7603733573
  O        23.0438129644        6.4358253659        1.5992513709
-----------------------
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Constants are hardcoded to make the program more readable
// But they could be passed as program argument
const char separator[]="i =";
const unsigned int requiredlines=331;

int main(void) {
    char* buffer[331] = { NULL, };
    ssize_t buffersizes[331] = { 0, };
    size_t n = requiredlines+1; // Ignore lines until the separator is found
    char* line = NULL;
    size_t len = 0;
    ssize_t nbread;
    size_t i;

    // Iterate through all lines
    while ((nbread = getline(&line, &len, stdin)) != -1) {

        // If the separator is found:
        // - print the record (if valid)
        // - reset the record (always)
        if (strstr(line, separator)) {
            if (n == requiredlines) {
                for (i = 0 ; i < requiredlines ; ++i) printf("%s", buffer[i]);
            }
            n = 0;
        }

        // Add the line to the buffer, unless too many lines have been read
        // (in which case we may discard lines until the separator is found again)
        if (n < requiredlines) {
            if (buffersizes[n] > nbread) {
                strncpy(buffer[n], line, nbread);
                buffer[n][nbread] = '\0';
            } else {
                free(buffer[n]);
                buffer[n] = line;
                buffersizes[n] = nbread+1;
                line = NULL;
                len = 0;
            }
        }
        ++n;
    }

    // Don't forget about the last record, if valid
    if (n == requiredlines) {
        for (i = 0 ; i < requiredlines ; ++i) printf("%s", buffer[i]);
    }

    free(line);
    for (i = 0 ; i < requiredlines ; ++i) free(buffer[i]);

    return 0;
}
gcc -c prog.c && gcc -o prog prog.o
./prog < infile > outfile
(time awk 'BEGIN { RS="i =" } { split($0,bits,"\n");if (length(bits)-1==331) { printf "%s",RS$0 } }' infile) > outfile

real    0m24.655s
user    0m24.357s
sys     0m0.279s

(time ./prog < infile) > outfile

real    0m1.414s
user    0m1.291s
sys     0m0.121s
-----------------------
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Constants are hardcoded to make the program more readable
// But they could be passed as program argument
const char separator[]="i =";
const unsigned int requiredlines=331;

int main(void) {
    char* buffer[331] = { NULL, };
    ssize_t buffersizes[331] = { 0, };
    size_t n = requiredlines+1; // Ignore lines until the separator is found
    char* line = NULL;
    size_t len = 0;
    ssize_t nbread;
    size_t i;

    // Iterate through all lines
    while ((nbread = getline(&line, &len, stdin)) != -1) {

        // If the separator is found:
        // - print the record (if valid)
        // - reset the record (always)
        if (strstr(line, separator)) {
            if (n == requiredlines) {
                for (i = 0 ; i < requiredlines ; ++i) printf("%s", buffer[i]);
            }
            n = 0;
        }

        // Add the line to the buffer, unless too many lines have been read
        // (in which case we may discard lines until the separator is found again)
        if (n < requiredlines) {
            if (buffersizes[n] > nbread) {
                strncpy(buffer[n], line, nbread);
                buffer[n][nbread] = '\0';
            } else {
                free(buffer[n]);
                buffer[n] = line;
                buffersizes[n] = nbread+1;
                line = NULL;
                len = 0;
            }
        }
        ++n;
    }

    // Don't forget about the last record, if valid
    if (n == requiredlines) {
        for (i = 0 ; i < requiredlines ; ++i) printf("%s", buffer[i]);
    }

    free(line);
    for (i = 0 ; i < requiredlines ; ++i) free(buffer[i]);

    return 0;
}
gcc -c prog.c && gcc -o prog prog.o
./prog < infile > outfile
(time awk 'BEGIN { RS="i =" } { split($0,bits,"\n");if (length(bits)-1==331) { printf "%s",RS$0 } }' infile) > outfile

real    0m24.655s
user    0m24.357s
sys     0m0.279s

(time ./prog < infile) > outfile

real    0m1.414s
user    0m1.291s
sys     0m0.121s
-----------------------
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Constants are hardcoded to make the program more readable
// But they could be passed as program argument
const char separator[]="i =";
const unsigned int requiredlines=331;

int main(void) {
    char* buffer[331] = { NULL, };
    ssize_t buffersizes[331] = { 0, };
    size_t n = requiredlines+1; // Ignore lines until the separator is found
    char* line = NULL;
    size_t len = 0;
    ssize_t nbread;
    size_t i;

    // Iterate through all lines
    while ((nbread = getline(&line, &len, stdin)) != -1) {

        // If the separator is found:
        // - print the record (if valid)
        // - reset the record (always)
        if (strstr(line, separator)) {
            if (n == requiredlines) {
                for (i = 0 ; i < requiredlines ; ++i) printf("%s", buffer[i]);
            }
            n = 0;
        }

        // Add the line to the buffer, unless too many lines have been read
        // (in which case we may discard lines until the separator is found again)
        if (n < requiredlines) {
            if (buffersizes[n] > nbread) {
                strncpy(buffer[n], line, nbread);
                buffer[n][nbread] = '\0';
            } else {
                free(buffer[n]);
                buffer[n] = line;
                buffersizes[n] = nbread+1;
                line = NULL;
                len = 0;
            }
        }
        ++n;
    }

    // Don't forget about the last record, if valid
    if (n == requiredlines) {
        for (i = 0 ; i < requiredlines ; ++i) printf("%s", buffer[i]);
    }

    free(line);
    for (i = 0 ; i < requiredlines ; ++i) free(buffer[i]);

    return 0;
}
gcc -c prog.c && gcc -o prog prog.o
./prog < infile > outfile
(time awk 'BEGIN { RS="i =" } { split($0,bits,"\n");if (length(bits)-1==331) { printf "%s",RS$0 } }' infile) > outfile

real    0m24.655s
user    0m24.357s
sys     0m0.279s

(time ./prog < infile) > outfile

real    0m1.414s
user    0m1.291s
sys     0m0.121s
-----------------------
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Constants are hardcoded to make the program more readable
// But they could be passed as program argument
const char separator[]="i =";
const unsigned int requiredlines=331;

int main(void) {
    char* buffer[331] = { NULL, };
    ssize_t buffersizes[331] = { 0, };
    size_t n = requiredlines+1; // Ignore lines until the separator is found
    char* line = NULL;
    size_t len = 0;
    ssize_t nbread;
    size_t i;

    // Iterate through all lines
    while ((nbread = getline(&line, &len, stdin)) != -1) {

        // If the separator is found:
        // - print the record (if valid)
        // - reset the record (always)
        if (strstr(line, separator)) {
            if (n == requiredlines) {
                for (i = 0 ; i < requiredlines ; ++i) printf("%s", buffer[i]);
            }
            n = 0;
        }

        // Add the line to the buffer, unless too many lines have been read
        // (in which case we may discard lines until the separator is found again)
        if (n < requiredlines) {
            if (buffersizes[n] > nbread) {
                strncpy(buffer[n], line, nbread);
                buffer[n][nbread] = '\0';
            } else {
                free(buffer[n]);
                buffer[n] = line;
                buffersizes[n] = nbread+1;
                line = NULL;
                len = 0;
            }
        }
        ++n;
    }

    // Don't forget about the last record, if valid
    if (n == requiredlines) {
        for (i = 0 ; i < requiredlines ; ++i) printf("%s", buffer[i]);
    }

    free(line);
    for (i = 0 ; i < requiredlines ; ++i) free(buffer[i]);

    return 0;
}
gcc -c prog.c && gcc -o prog prog.o
./prog < infile > outfile
(time awk 'BEGIN { RS="i =" } { split($0,bits,"\n");if (length(bits)-1==331) { printf "%s",RS$0 } }' infile) > outfile

real    0m24.655s
user    0m24.357s
sys     0m0.279s

(time ./prog < infile) > outfile

real    0m1.414s
user    0m1.291s
sys     0m0.121s

In Vue3, how to make Custom Component work with v-model for group of checkboxs?

const {
  ref,
  createApp
} = Vue;

const app = createApp({
  setup() {
    const itemsSelected = ref([]);
    const items = ref([{
        id: '1',
        name: 'Jack'
      },
      {
        id: '2',
        name: 'John'
      },
      {
        id: '3',
        name: 'Mike'
      },
    ]);

    return {
      items,
      itemsSelected,
    };
  },
});

app.component('custom-checkbox', {
  props: {
    item: {
      type: Object,
      default: () => ({})
    },
    modelValue: {
      type: Array,
      required: true
    }
  },
  emits: ['update:modelValue'],
  computed: {
    model: {
      get() {
        return this.modelValue
      },
      set(value) {
        this.$emit('update:modelValue', value)
      }
    }
  },
  template: `
    <div>
      <input
        type="checkbox" :value="item.id" v-model="model"
      > {{ item.name }}
    </div>
    `
})

app.mount("#app");
<script src="https://unpkg.com/vue@3.0.11/dist/vue.global.js"></script>

<div id="app">
  <div><code>itemsSelected: {{ itemsSelected }}</code></div>
  <hr />
  <custom-checkbox v-for="item in items" :key="item.id" :item="item" v-model="itemsSelected"></custom-checkbox>
</div>
-----------------------
const {
  ref,
  createApp
} = Vue;

const app = createApp({
  setup() {
    const itemsSelected = ref([]);
    const items = ref([{
        id: '1',
        name: 'Jack'
      },
      {
        id: '2',
        name: 'John'
      },
      {
        id: '3',
        name: 'Mike'
      },
    ]);

    return {
      items,
      itemsSelected,
    };
  },
});

app.component('custom-checkbox', {
  props: {
    item: {
      type: Object,
      default: () => ({})
    },
    modelValue: {
      type: Array,
      required: true
    }
  },
  emits: ['update:modelValue'],
  computed: {
    model: {
      get() {
        return this.modelValue
      },
      set(value) {
        this.$emit('update:modelValue', value)
      }
    }
  },
  template: `
    <div>
      <input
        type="checkbox" :value="item.id" v-model="model"
      > {{ item.name }}
    </div>
    `
})

app.mount("#app");
<script src="https://unpkg.com/vue@3.0.11/dist/vue.global.js"></script>

<div id="app">
  <div><code>itemsSelected: {{ itemsSelected }}</code></div>
  <hr />
  <custom-checkbox v-for="item in items" :key="item.id" :item="item" v-model="itemsSelected"></custom-checkbox>
</div>

NumPy: how to calculate variance along each row of a 2D array using np.var and by hand (i.e., not using np.var; calculating each term explicitly)?

import numpy as np 

importedData = np.arange(1,10).reshape(3,3)

# Get means for each row
means = [row.mean() for row in importedData]

# Calculate squared errors
squared_errors = [(row-mean)**2 for row, mean in zip(importedData, means)]

# Calculate "mean for each row of squared errors" (aka the variance)
variances = [row.mean() for row in squared_errors]

# Sanity check
print(variances)
print(importedData.var(1))

# [0.6666666666666666, 0.6666666666666666, 0.6666666666666666]
# [0.66666667 0.66666667 0.66666667]

How to get canvas onmousemove handler to see latest React state hook value?

<canvas ref={canvasRef} width="600" height="200" onMouseMove={handleMouseMove}></canvas>
const {x, y} = ev.nativeEvent;
React.useEffect(componentMountEffect, [isDragging]);
-----------------------
<canvas ref={canvasRef} width="600" height="200" onMouseMove={handleMouseMove}></canvas>
const {x, y} = ev.nativeEvent;
React.useEffect(componentMountEffect, [isDragging]);
-----------------------
<canvas ref={canvasRef} width="600" height="200" onMouseMove={handleMouseMove}></canvas>
const {x, y} = ev.nativeEvent;
React.useEffect(componentMountEffect, [isDragging]);

How do I make this shape in HTML?

#Shape {
  position: absolute;
  --Width: 60%;
  --Height: 80%;
  width: var(--Width);
  height: var(--Height);
  top: calc(50% - var(--Height)/2);
  left: calc(50% - var(--Width)/2);
}
<svg id="Shape" viewBox="0 0 374 381" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M248.434 46H334C356.092 46 374 63.9087 374 86V381H0V86C0 63.9087 17.9082 46 40 46H125.566C133.342 19.417 157.903 0 187 0C216.097 0 240.658 19.417 248.434 46Z" fill="rgba(30,28,33,1)"/>
</svg>
-----------------------
#Shape {
  position: absolute;
  --Width: 60%;
  --Height: 80%;
  width: var(--Width);
  height: var(--Height);
  top: calc(50% - var(--Height)/2);
  left: calc(50% - var(--Width)/2);
}
<svg id="Shape" viewBox="0 0 374 381" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M248.434 46H334C356.092 46 374 63.9087 374 86V381H0V86C0 63.9087 17.9082 46 40 46H125.566C133.342 19.417 157.903 0 187 0C216.097 0 240.658 19.417 248.434 46Z" fill="rgba(30,28,33,1)"/>
</svg>
-----------------------
/* some default css so other css in your project will not interfere */
#logo span {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  border: 0;
  display: inline-block;
  background-color: black;
}
/* below the css for the logo */
#logo .l, #logo .r {
  width: 160px;
  height: 420px;
}
#logo .l {
  border-top-left-radius: 45px;
}
#logo .r {
  border-top-right-radius: 45px;
}
#logo .m {
  width: 0;
  height: 475px;
  border: 55px solid black;
  border-top-left-radius: 55px;
  border-top-right-radius: 55px;
}
<div id="logo">
  <span class="l"></span><span class="m"></span><span class="r"></span>
</div>
-----------------------
/* some default css so other css in your project will not interfere */
#logo span {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  border: 0;
  display: inline-block;
  background-color: black;
}
/* below the css for the logo */
#logo .l, #logo .r {
  width: 160px;
  height: 420px;
}
#logo .l {
  border-top-left-radius: 45px;
}
#logo .r {
  border-top-right-radius: 45px;
}
#logo .m {
  width: 0;
  height: 475px;
  border: 55px solid black;
  border-top-left-radius: 55px;
  border-top-right-radius: 55px;
}
<div id="logo">
  <span class="l"></span><span class="m"></span><span class="r"></span>
</div>
-----------------------
* {
  margin: 0px;
  padding: 0px;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
}

div {
  position: relative;
  display: flex;
  justify-content: center;
  margin-top: 10%;
  padding-top: 40%;
  width: 40%;
  background: black;
  border-radius: 14% 14% 0 0;
}

p {
  display: block;
  content: "";
  position: absolute;
  width: 10%;
  padding-top: 10%;
  margin-top: -28%;
  background: black;
  border-radius: 50%;
}
<div></div>
<p></p>
-----------------------
* {
  margin: 0px;
  padding: 0px;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
}

div {
  position: relative;
  display: flex;
  justify-content: center;
  margin-top: 10%;
  padding-top: 40%;
  width: 40%;
  background: black;
  border-radius: 14% 14% 0 0;
}

p {
  display: block;
  content: "";
  position: absolute;
  width: 10%;
  padding-top: 10%;
  margin-top: -28%;
  background: black;
  border-radius: 50%;
}
<div></div>
<p></p>
-----------------------
.box {
  width: 200px;
  height: 200px;
  margin-top: 40px;
  border-radius: 20px 20px 0 0;
  background: black;
}

.box::before {
  content: "";
  display: block;
  width: 50px;
  height: 50px;
  background: inherit;
  border-radius: 50%;
  margin: auto;
  transform:translateY(-20px);
}
<div class="box"></div>
-----------------------
.box {
  width: 200px;
  height: 200px;
  margin-top: 40px;
  border-radius: 20px 20px 0 0;
  background: black;
}

.box::before {
  content: "";
  display: block;
  width: 50px;
  height: 50px;
  background: inherit;
  border-radius: 50%;
  margin: auto;
  transform:translateY(-20px);
}
<div class="box"></div>

Can I detect a hanging JS function and abort?

var worker = new Worker('/path/to/run-regex.js');
function regexMatch(str, regexStr, callback) {
  let regex = new RegExp(regexStr);
  let result = str.match(regex);
  callback(result, '');
}

onmessage = function(e) {
  let data = e.data;
  switch (data.cmd) {
    case 'match':
      regexMatch(data.str, data.regex, function(result, err) {
        postMessage({ cmd: data.cmd, result: result, err: err });
      });
      break;
    case 'replace':
      //regexMatch(data.str, data.regex, data.replace, function(result, err) {
      //  postMessage({ cmd: data.cmd, result: result, err: err });
      //});
      break;
    default:
      break;
      postMessage({ err: 'Unknown command: ' + data.cmd });
  }
}
if(window.Worker) {
  const myWorker = new Worker('/path/to/run-regex.js');

  myWorker.onmessage = function(e) {
    let data = e.data;
    if(data.err) {
      // handle error
    } else {
      // handle match result using data.result;
    }
  }

  function regexMatch(str, regex) {
    let data = { cmd: 'match', str: str, regex: regex.toString() };
    myWorker.postMessage(data);
  }

  regexMatch('xxxxxxxxxxxxxxxxxxxxxxxxx', /(x+x+)+y/);

} else {
  console.log('Your browser does not support web workers.');
}
-----------------------
var worker = new Worker('/path/to/run-regex.js');
function regexMatch(str, regexStr, callback) {
  let regex = new RegExp(regexStr);
  let result = str.match(regex);
  callback(result, '');
}

onmessage = function(e) {
  let data = e.data;
  switch (data.cmd) {
    case 'match':
      regexMatch(data.str, data.regex, function(result, err) {
        postMessage({ cmd: data.cmd, result: result, err: err });
      });
      break;
    case 'replace':
      //regexMatch(data.str, data.regex, data.replace, function(result, err) {
      //  postMessage({ cmd: data.cmd, result: result, err: err });
      //});
      break;
    default:
      break;
      postMessage({ err: 'Unknown command: ' + data.cmd });
  }
}
if(window.Worker) {
  const myWorker = new Worker('/path/to/run-regex.js');

  myWorker.onmessage = function(e) {
    let data = e.data;
    if(data.err) {
      // handle error
    } else {
      // handle match result using data.result;
    }
  }

  function regexMatch(str, regex) {
    let data = { cmd: 'match', str: str, regex: regex.toString() };
    myWorker.postMessage(data);
  }

  regexMatch('xxxxxxxxxxxxxxxxxxxxxxxxx', /(x+x+)+y/);

} else {
  console.log('Your browser does not support web workers.');
}
-----------------------
var worker = new Worker('/path/to/run-regex.js');
function regexMatch(str, regexStr, callback) {
  let regex = new RegExp(regexStr);
  let result = str.match(regex);
  callback(result, '');
}

onmessage = function(e) {
  let data = e.data;
  switch (data.cmd) {
    case 'match':
      regexMatch(data.str, data.regex, function(result, err) {
        postMessage({ cmd: data.cmd, result: result, err: err });
      });
      break;
    case 'replace':
      //regexMatch(data.str, data.regex, data.replace, function(result, err) {
      //  postMessage({ cmd: data.cmd, result: result, err: err });
      //});
      break;
    default:
      break;
      postMessage({ err: 'Unknown command: ' + data.cmd });
  }
}
if(window.Worker) {
  const myWorker = new Worker('/path/to/run-regex.js');

  myWorker.onmessage = function(e) {
    let data = e.data;
    if(data.err) {
      // handle error
    } else {
      // handle match result using data.result;
    }
  }

  function regexMatch(str, regex) {
    let data = { cmd: 'match', str: str, regex: regex.toString() };
    myWorker.postMessage(data);
  }

  regexMatch('xxxxxxxxxxxxxxxxxxxxxxxxx', /(x+x+)+y/);

} else {
  console.log('Your browser does not support web workers.');
}

React / Gatsby - render different component based on screen size

class SiteNav extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      changeLogo: false
    };
    this.handleResize = this.handleResize.bind(this);
  }

  handleResize() {
    this.setState({
      changeLogo: window.matchMedia("(max-width: 400px)").matches
    });
  }

  componentDidMount() {
    window.addEventListener("resize", this.handleResize);
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.handleResize);
  }

  render() {
    return (
      <div>
        {this.state.changeLogo && <SiteNavLogoMobile />}
        {!this.state.changeLogo && <SiteNavLogo/>}
      </div>
    );
  }
} 
-----------------------
return (
  <>
        ...
        { typeof window !== 'undefined' 
          ? window.innerWidth <= 400 ? <SiteNavLogoMobile /> : <SiteNavLogo/> 
          : null
        }
  </>
);
-----------------------
<div className="display-xs">
  <MobileVariant />
</div>

<div className="display-md">
  <DesktopVariant />
</div>

How to convert ByteArray[] to int16 in Python?

import numpy as np
# read file or stream in binary mode into a bin_array list
...
# convert binary input values to numpy array with container type int16
np.array([v for v in bin_array], dtype=np.int16)

Use a specific part of code (img src) that I generated using a foreach loop in the page I open using asp-route-id and asp-page

<div class="item">
    @{int randomImg = random.Next(1, Apron);}
    <img src="~/content/images/map/@jobTitleModel.ImageType.ImageTypeOption/img@(randomImg).svg" type="image/svg+xml" />

    <a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" asp-route-ImgId="@randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block">@jobTitleModel.JobTitle</a>
</div>
switch (jobTitleModel.ImageType.ImageTypeOption)
{
    case "Apron":
        <div class="item">
            @{int randomImg = random.Next(1, Apron);}
            <img src="~/content/images/map/@jobTitleModel.ImageType.ImageTypeOption/img@(randomImg).svg" type="image/svg+xml" />

            <form method="post" asp-page="/UIMain/Requirements/Index" asp-page-handler="ShowImg" asp-route-ID="@jobTitleModel.JobTitleId">
                <input type="hidden" name="ImgId" value="@randomImg" />
                <input type="submit" class="btnhidden" />
            </form>
            <a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" asp-route-ImgId="@randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block" onclick="return myfunc(this)">@jobTitleModel.JobTitle</a>
        </div>
        break;

    case "Casual":
        <div class="item">
            @{randomImg = random.Next(1, Casual);}
            <img src="~/content/images/map/@jobTitleModel.ImageType.ImageTypeOption/img@(randomImg).svg" type="image/svg+xml" />
            <form method="post" asp-page="/UIMain/Requirements/Index" asp-page-handler="ShowImg" asp-route-ID="@jobTitleModel.JobTitleId">
                <input type="hidden" name="ImgId" value="@randomImg" />
                <input type="submit" class="btnhidden" />
            </form>
            <a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" asp-route-ImgId="@randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block" onclick="return myfunc(this)">@jobTitleModel.JobTitle</a>
        </div>
        break;
}
public IActionResult OnPostShowImg()
{
    //code logic here

    return Page();
}
function myfunc(el) {
    $(el).prev().find("input[type='submit']").click();
    return false;
}
-----------------------
<div class="item">
    @{int randomImg = random.Next(1, Apron);}
    <img src="~/content/images/map/@jobTitleModel.ImageType.ImageTypeOption/img@(randomImg).svg" type="image/svg+xml" />

    <a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" asp-route-ImgId="@randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block">@jobTitleModel.JobTitle</a>
</div>
switch (jobTitleModel.ImageType.ImageTypeOption)
{
    case "Apron":
        <div class="item">
            @{int randomImg = random.Next(1, Apron);}
            <img src="~/content/images/map/@jobTitleModel.ImageType.ImageTypeOption/img@(randomImg).svg" type="image/svg+xml" />

            <form method="post" asp-page="/UIMain/Requirements/Index" asp-page-handler="ShowImg" asp-route-ID="@jobTitleModel.JobTitleId">
                <input type="hidden" name="ImgId" value="@randomImg" />
                <input type="submit" class="btnhidden" />
            </form>
            <a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" asp-route-ImgId="@randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block" onclick="return myfunc(this)">@jobTitleModel.JobTitle</a>
        </div>
        break;

    case "Casual":
        <div class="item">
            @{randomImg = random.Next(1, Casual);}
            <img src="~/content/images/map/@jobTitleModel.ImageType.ImageTypeOption/img@(randomImg).svg" type="image/svg+xml" />
            <form method="post" asp-page="/UIMain/Requirements/Index" asp-page-handler="ShowImg" asp-route-ID="@jobTitleModel.JobTitleId">
                <input type="hidden" name="ImgId" value="@randomImg" />
                <input type="submit" class="btnhidden" />
            </form>
            <a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" asp-route-ImgId="@randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block" onclick="return myfunc(this)">@jobTitleModel.JobTitle</a>
        </div>
        break;
}
public IActionResult OnPostShowImg()
{
    //code logic here

    return Page();
}
function myfunc(el) {
    $(el).prev().find("input[type='submit']").click();
    return false;
}
-----------------------
<div class="item">
    @{int randomImg = random.Next(1, Apron);}
    <img src="~/content/images/map/@jobTitleModel.ImageType.ImageTypeOption/img@(randomImg).svg" type="image/svg+xml" />

    <a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" asp-route-ImgId="@randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block">@jobTitleModel.JobTitle</a>
</div>
switch (jobTitleModel.ImageType.ImageTypeOption)
{
    case "Apron":
        <div class="item">
            @{int randomImg = random.Next(1, Apron);}
            <img src="~/content/images/map/@jobTitleModel.ImageType.ImageTypeOption/img@(randomImg).svg" type="image/svg+xml" />

            <form method="post" asp-page="/UIMain/Requirements/Index" asp-page-handler="ShowImg" asp-route-ID="@jobTitleModel.JobTitleId">
                <input type="hidden" name="ImgId" value="@randomImg" />
                <input type="submit" class="btnhidden" />
            </form>
            <a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" asp-route-ImgId="@randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block" onclick="return myfunc(this)">@jobTitleModel.JobTitle</a>
        </div>
        break;

    case "Casual":
        <div class="item">
            @{randomImg = random.Next(1, Casual);}
            <img src="~/content/images/map/@jobTitleModel.ImageType.ImageTypeOption/img@(randomImg).svg" type="image/svg+xml" />
            <form method="post" asp-page="/UIMain/Requirements/Index" asp-page-handler="ShowImg" asp-route-ID="@jobTitleModel.JobTitleId">
                <input type="hidden" name="ImgId" value="@randomImg" />
                <input type="submit" class="btnhidden" />
            </form>
            <a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" asp-route-ImgId="@randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block" onclick="return myfunc(this)">@jobTitleModel.JobTitle</a>
        </div>
        break;
}
public IActionResult OnPostShowImg()
{
    //code logic here

    return Page();
}
function myfunc(el) {
    $(el).prev().find("input[type='submit']").click();
    return false;
}
-----------------------
<div class="item">
    @{int randomImg = random.Next(1, Apron);}
    <img src="~/content/images/map/@jobTitleModel.ImageType.ImageTypeOption/img@(randomImg).svg" type="image/svg+xml" />

    <a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" asp-route-ImgId="@randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block">@jobTitleModel.JobTitle</a>
</div>
switch (jobTitleModel.ImageType.ImageTypeOption)
{
    case "Apron":
        <div class="item">
            @{int randomImg = random.Next(1, Apron);}
            <img src="~/content/images/map/@jobTitleModel.ImageType.ImageTypeOption/img@(randomImg).svg" type="image/svg+xml" />

            <form method="post" asp-page="/UIMain/Requirements/Index" asp-page-handler="ShowImg" asp-route-ID="@jobTitleModel.JobTitleId">
                <input type="hidden" name="ImgId" value="@randomImg" />
                <input type="submit" class="btnhidden" />
            </form>
            <a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" asp-route-ImgId="@randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block" onclick="return myfunc(this)">@jobTitleModel.JobTitle</a>
        </div>
        break;

    case "Casual":
        <div class="item">
            @{randomImg = random.Next(1, Casual);}
            <img src="~/content/images/map/@jobTitleModel.ImageType.ImageTypeOption/img@(randomImg).svg" type="image/svg+xml" />
            <form method="post" asp-page="/UIMain/Requirements/Index" asp-page-handler="ShowImg" asp-route-ID="@jobTitleModel.JobTitleId">
                <input type="hidden" name="ImgId" value="@randomImg" />
                <input type="submit" class="btnhidden" />
            </form>
            <a asp-page="/UIMain/Requirements/Index" asp-route-ID="@jobTitleModel.JobTitleId" asp-route-ImgId="@randomImg" class="btn btn-outline-primary mb-2 mt-1 btn-block" onclick="return myfunc(this)">@jobTitleModel.JobTitle</a>
        </div>
        break;
}
public IActionResult OnPostShowImg()
{
    //code logic here

    return Page();
}
function myfunc(el) {
    $(el).prev().find("input[type='submit']").click();
    return false;
}

Android heads-up notification not showing

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
                                .setSmallIcon(android.R.drawable.arrow_up_float)
                                .setContentTitle("Check running time - click!")
                                .setContentText(String.valueOf(elapsedTime))
                                .setContentIntent(pendingIntent)
                                .setDefaults(Notification.DEFAULT_ALL)
                                .setPriority(Notification.PRIORITY_HIGH)
                                .setVibrate(new long[0]);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
-----------------------
 NotificationManager mNotificationManager = (NotificationManager)
            this.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent myintent = new Intent(this, MainActivity.class);
    myintent.putExtra("message", msg);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            myintent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentTitle("ttile")
                    .setStyle(new NotificationCompat.BigTextStyle()
                            .bigText(msg))
                    .setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(1, mBuilder.build());
-----------------------
builder.setPriority(Notification.PRIORITY_HIGH);
if (Build.VERSION.SDK_INT >= 21) {
   mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
}
builder.fullScreenIntent(sameAsContentPendingtIntent);
channel = new NotificationChannel("uniqueId", "name", NotificationManager.IMPORTANCE_HIGH);
channel.enableVibration(true);
-----------------------
builder.setPriority(Notification.PRIORITY_HIGH);
if (Build.VERSION.SDK_INT >= 21) {
   mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
}
builder.fullScreenIntent(sameAsContentPendingtIntent);
channel = new NotificationChannel("uniqueId", "name", NotificationManager.IMPORTANCE_HIGH);
channel.enableVibration(true);
-----------------------
builder.setPriority(Notification.PRIORITY_HIGH);
if (Build.VERSION.SDK_INT >= 21) {
   mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
}
builder.fullScreenIntent(sameAsContentPendingtIntent);
channel = new NotificationChannel("uniqueId", "name", NotificationManager.IMPORTANCE_HIGH);
channel.enableVibration(true);
-----------------------
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_HIGH; //Important for heads-up notification
        NotificationChannel channel = new NotificationChannel("1", name, importance);
        channel.setDescription(description);
        channel.setShowBadge(true);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "1")
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle(textTitle)
        .setContentText(textContent)
        .setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE) //Important for heads-up notification
        .setPriority(Notification.PRIORITY_MAX); //Important for heads-up notification
Notification buildNotification = mBuilder.build();
NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(001, buildNotification);
-----------------------
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_HIGH; //Important for heads-up notification
        NotificationChannel channel = new NotificationChannel("1", name, importance);
        channel.setDescription(description);
        channel.setShowBadge(true);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "1")
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle(textTitle)
        .setContentText(textContent)
        .setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE) //Important for heads-up notification
        .setPriority(Notification.PRIORITY_MAX); //Important for heads-up notification
Notification buildNotification = mBuilder.build();
NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(001, buildNotification);
-----------------------
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_HIGH; //Important for heads-up notification
        NotificationChannel channel = new NotificationChannel("1", name, importance);
        channel.setDescription(description);
        channel.setShowBadge(true);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "1")
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle(textTitle)
        .setContentText(textContent)
        .setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE) //Important for heads-up notification
        .setPriority(Notification.PRIORITY_MAX); //Important for heads-up notification
Notification buildNotification = mBuilder.build();
NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(001, buildNotification);

COMMUNITY DISCUSSIONS

Top Trending Discussions on heads-up
  • How can I find out how many lines are between a number and the next occurrence of the same number in a file?
  • In Vue3, how to make Custom Component work with v-model for group of checkboxs?
  • NumPy: how to calculate variance along each row of a 2D array using np.var and by hand (i.e., not using np.var; calculating each term explicitly)?
  • How to get canvas onmousemove handler to see latest React state hook value?
  • Kotlin Android - Notification not appearing as heads up
  • How do I make this shape in HTML?
  • Can I detect a hanging JS function and abort?
  • React / Gatsby - render different component based on screen size
  • Google analytics API - how to create new account
  • Android heads-up notification not showing after disable and enable it on application settings
Top Trending Discussions on heads-up

QUESTION

How can I find out how many lines are between a number and the next occurrence of the same number in a file?

Asked 2021-Jun-02 at 18:35

I have large files that each store results from very long calculations. Here's an example of a file where there are results for five time steps; there are problems with the output at the third, fourth, and fifth time steps.

(Please note that I have been lazy and have used the same numbers to represent the results at each time step in my example. In reality, the numbers would be unique at each time step.)

     3
 i =        1, time =        1.000, E =     1234567
  Mg       22.9985897185        6.9311166109        0.7603733573
  O        23.0438129644        6.4358253659        1.5992513709
  O        23.8223149199        7.2029442290        0.4030956770
     3
 i =        2, time =        1.500, E =     1234567
  Mg       22.9985897185        6.9311166109        0.7603733573
  O        23.0438129644        6.4358253659        1.5992513709
  O        23.8223149199        7.2029442290        0.4030956770
     3
 i =        3, time =        2.000, E =     1234567
  Mg       22.9985897185        6.9311166109        0.7603733573
  O        23.0438129644        6.4358253659        1.5992513709
  O        23.8223149199                                       (<--Problem: calculation stopped and some numbers are missing)
     3
 i =        4, time =        2.500, E =     1234567
  Mg       22.9985897185        6.9311166109        0.7603733573
  O        23.0438129644        6.4358253659        1.5992513709 (Problem: calculation stopped and entire row is missing below)
     3
 i =        5, time =        3.000, E =     1234567
  Mg       22.9985897185        6.9311166109        0.7603733573
  O        23.0438129644        6.4358253659        1.5992513709
  O        23.8223149199        7.2029442290        0.4030956770 sdffs (<--Problem: rarely, additional characters can be printed but I figured out how to identify the longest lines in the file and don't have this problem this time)

The problem is that the calculations can fail (and then need to be restarted) as a result is printing to a file. That means that when I try to use the results, I have problems.

My question is, how can I find out when something has gone wrong and the results file has been messed up? The most common problem is that there are not "3" lines of results (plus the header, which is the line where there's i = ...)? If I could find a problem line, I could then delete that time step.

Here is an example of error output I get when trying to use a messed-up file:

Traceback (most recent call last):
  File "/mtn/storage/software/languages/anaconda/Anaconda3-2018.12/lib/python3.7/site-packages/aser/io/extxyz.py", line 593, in read_xyz
    nentss = int(line)
ValueError: invalid literal for int() with base 10: '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "pythonPostProcessingCode.py", line 25, in <module>
    path = read('%s%s' % (filename, fileext) , format='xyz', index=':')  # <--This line tells me that Python cannot read in a particular time step because the formatting is messed up.

I am not experienced with scripting/Awk, etc, so if anyone thinks I have not used appropriate question tags, a heads-up would be welcome. Thank you.

ANSWER

Answered 2021-Jun-02 at 12:08

It's a little bit more difficult to spread the match of a record across 2 lines to try and incorporate the i = ..., but I don't think you actually need to. It looks like a new record can be distinguished by the occurrence of a line with only one column. If that is the case, you could do something like:

awk -v c=330 -v p=1 'function pr(n) {
    if( n - p == c)  printf "%s", buf; 
    buf = ""} 
    NF == 1 { pr(NR); p = NR; c = $1 } 
    {buf = sprintf("%s%s\n", buf, $0)} 
    END {pr(NR+1)}' input-file

In the above, whenever a line is seen with a single record, the expectation is that many lines will be in the following record. If that number is not matched, the record is not printed. To avoid that logic, just remove the c = $1 near the end of line 4. The only reason you need the -v c=330 is to enable the removal of that assignment; if you want the single column line to be the line count of the record, you can omit -v c=330.

Source https://stackoverflow.com/questions/67803893

QUESTION

In Vue3, how to make Custom Component work with v-model for group of checkboxs?

Asked 2021-May-27 at 05:27

The below given code you can see the magic of v-model, after checking / unchecking the checkboxes the array checkedNames will add/remove names automatically. We don't have to write anything to push/slice/filter names from the array, right?

const { ref } = Vue;

const App = {
  setup () {
    const checkedNames = ref([])
    return { checkedNames }
  }
}

Vue.createApp(App).mount("#app");
<script src="https://unpkg.com/vue@3.0.11/dist/vue.global.js"></script>

<div id="app">
  <input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
  <label for="jack">Jack</label>
  <input type="checkbox" id="john" value="John" v-model="checkedNames">
  <label for="john">John</label>
  <input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
  <label for="mike">Mike</label>
  <br>
  <span>Checked names: {{ checkedNames }}</span>
</div>

My question is: How can I do the same feature but with custom components?

You can see, In below given code snippets I tried but I did not like it because we are missing that magic of v-model instead I am handeling this in my function addOrRemoveItem()

heads-up: It may seem to you that I am over explaining :) sorry for that.

I followed this tutorial for some idea but was not much helpful, then referred vue official doc here. below is the functional code but it's kinda overkill.

const { ref, createApp } = Vue;

const app = createApp({
  setup() {
    const itemsSelected = ref([]);
    const items = ref([
      { id: '1', name: 'Jack' }, 
      { id: '2', name: 'John' }, 
      { id: '3', name: 'Mike' }, 
    ]);

    const addOrRemoveItem = (itemId) => {
      const exists = itemsSelected.value.includes(itemId);

      if (exists) {
        itemsSelected.value = itemsSelected.value.filter((id) => id !== itemId);
      } else {
        itemsSelected.value.push(itemId);
      }
    };

    return { 
      items,
      itemsSelected,
      addOrRemoveItem,
    };
  },
});

app.component('custom-checkbox', {
   props: {
    item: { type: Object, default: () => ({}) },
    modelValue: { type: Array, default: () => [] },
  },
  template: `
    <div>
      <input
        type="checkbox" :value="item.id"
        @change="$emit('update:model-value', $event.target.checked)"
      > {{ item.name }}
    </div>
    `
})

app.mount("#app");
<script src="https://unpkg.com/vue@3.0.11/dist/vue.global.js"></script>

<div id="app">
  <div><code>itemsSelected: {{ itemsSelected }}</code></div>
 <hr />
  <custom-checkbox
    v-for="item in items"
    :key="item.id"
    :item="item"
    :model-value="itemsSelected"
    @update:model-value="addOrRemoveItem(item.id)"
  ></custom-checkbox>
</div>

As mentioned above, the code was bit overkill when I follow as mentioned in doc $emit('update:model-value', ...) which can be simply anything for eg: $emit('val-updated'), here is bit simplified version after removing unwanted prop and reducing the length of $emit.

const { ref, createApp } = Vue;

const app = createApp({
  setup() {
    const itemsSelected = ref([]);
    const items = ref([
      { id: '1', name: 'Jack' }, 
      { id: '2', name: 'John' }, 
      { id: '3', name: 'Mike' }, 
    ]);

    const addOrRemoveItem = (itemId) => {
      const exists = itemsSelected.value.includes(itemId);

      if (exists) {
        itemsSelected.value = itemsSelected.value.filter((id) => id !== itemId);
      } else {
        itemsSelected.value.push(itemId);
      }
    };

    return { 
      items,
      itemsSelected,
      addOrRemoveItem,
    };
  },
});

app.component('custom-checkbox', {
   props: {
    item: { type: Object, default: () => ({}) },
  },
  template: `
    <div>
      <input
        type="checkbox" :value="item.id"
        @change="$emit('val-updated')"
      > {{ item.name }}
    </div>
    `
})

app.mount("#app");
<script src="https://unpkg.com/vue@3.0.11/dist/vue.global.js"></script>

<div id="app">
  <div><code>itemsSelected: {{ itemsSelected }}</code></div>
 <hr />
  <custom-checkbox
    v-for="item in items"
    :key="item.id"
    :item="item"
    @val-updated="addOrRemoveItem(item.id)"
  ></custom-checkbox>
</div>

ANSWER

Answered 2021-May-26 at 11:48

The addOrRemoveItem() method is not needed at all. Just let the default Vue v-model logic for a checkbox do the heavy lifting. Only thing you need is to use computed prop for a v-model (because using prop directly is not possible as props can not be mutated from child component)

const {
  ref,
  createApp
} = Vue;

const app = createApp({
  setup() {
    const itemsSelected = ref([]);
    const items = ref([{
        id: '1',
        name: 'Jack'
      },
      {
        id: '2',
        name: 'John'
      },
      {
        id: '3',
        name: 'Mike'
      },
    ]);

    return {
      items,
      itemsSelected,
    };
  },
});

app.component('custom-checkbox', {
  props: {
    item: {
      type: Object,
      default: () => ({})
    },
    modelValue: {
      type: Array,
      required: true
    }
  },
  emits: ['update:modelValue'],
  computed: {
    model: {
      get() {
        return this.modelValue
      },
      set(value) {
        this.$emit('update:modelValue', value)
      }
    }
  },
  template: `
    <div>
      <input
        type="checkbox" :value="item.id" v-model="model"
      > {{ item.name }}
    </div>
    `
})

app.mount("#app");
<script src="https://unpkg.com/vue@3.0.11/dist/vue.global.js"></script>

<div id="app">
  <div><code>itemsSelected: {{ itemsSelected }}</code></div>
  <hr />
  <custom-checkbox v-for="item in items" :key="item.id" :item="item" v-model="itemsSelected"></custom-checkbox>
</div>

Source https://stackoverflow.com/questions/67703675

QUESTION

NumPy: how to calculate variance along each row of a 2D array using np.var and by hand (i.e., not using np.var; calculating each term explicitly)?

Asked 2021-Apr-26 at 22:58

I am using Python to import data from large files. There are three columns corresponding to x, y, z data. Each row represents a time at which the data were collected. For example:

importedData = [[1, 2, 3],  <--This row: x, y, and z data at time 0.
                [4, 5, 6],
                [7, 8, 9]];
  1. I want to calculate the variance for each time (row). As far as I know, one way to do this is as follows (if this is not correct, I would appreciate a heads-up):

    varPerTimestep = np.var(importedData,axis=1);

  2. Here's my problem. To convince a coworker it works, I would next like to do the same thing, but avoid using np.var. This means solving:

    Var(S)=(⟨S_bar⋅S_bar⟩−⟨S_bar⟩⟨S_bar⟩) # S_bar, x, y, z

I'm an intermittent Python user and just can't figure out how to do this for each row. I found a suggestion online but don't know how to adapt the code below so it applies to each row (apologies; can't provide the link because when I do, I get an error that my code is not formatted correctly and I can't post the question; also the reason that some of the code is formatted as quotes below):

def variance(data, ddof=0):
     n = len(data)
     mean = sum(data) / n
     return sum((x - mean) ** 2 for x in data) / (n - ddof)

I have tried various things. For example, putting the function in a loop where I first attempted just getting a row average:

for row in importedData:
    mean_test = np.mean(importedData,axis=1)
print(mean_test)

This gives me an error I can't figure out:

Traceback (most recent call last):
  File "<string>", line 13, in <module>
TypeError: list indices must be integers or slices, not tuple

I also tried this and get no output because I seem to be stuck in a loop:

 n = len(importedData[0,:])         # Trying to get the length of each row.
 mean = mean(importedData[0,:])     # Likewise trying to get the mean of each row.
 deviations = [(x - mean) ** 2 for x in importedData]
 variance = sum(deviations) / n

If anyone could please point me in the right direction, I would be grateful.

ANSWER

Answered 2021-Apr-26 at 22:58

Well you could do something like this to make things more explicit:

import numpy as np 

importedData = np.arange(1,10).reshape(3,3)

# Get means for each row
means = [row.mean() for row in importedData]

# Calculate squared errors
squared_errors = [(row-mean)**2 for row, mean in zip(importedData, means)]

# Calculate "mean for each row of squared errors" (aka the variance)
variances = [row.mean() for row in squared_errors]

# Sanity check
print(variances)
print(importedData.var(1))

# [0.6666666666666666, 0.6666666666666666, 0.6666666666666666]
# [0.66666667 0.66666667 0.66666667]

Source https://stackoverflow.com/questions/67269103

QUESTION

How to get canvas onmousemove handler to see latest React state hook value?

Asked 2021-Apr-22 at 00:23

I'm coding a super basic canvas-based image viewer. I'm trying to implement image panning. I want to be able to hold my mouse button down and move the mouse to pan the image around. I'm using the mouse up and down events to enter and leave a "panning mode". My mouse move handler never seems to see that the panning boolean changes from false to true, though.

I've tried writing my functions as arrow functions instead, thinking maybe it was something to do with the fact that these are DOM handlers (issues with this or something), but that didn't seem to make any difference.

I have a heads-up display that shows the panning state and it updates accordingly, but my console logs within the mouse move handler always show the variable as false.

How can I get this panning boolean value to update as you'd expect within my mouse move handler?

Here is my trimmed down code, which is testable in my codepen link further down ...

import * as React from "https://cdn.skypack.dev/react@17.0.1";
import * as ReactDOM from "https://cdn.skypack.dev/react-dom@17.0.1";

type PropsType = {
  url: string;
};

function ImageViewer(props: PropsType) {
  const imgRef = React.useRef(null);
  const canvasRef = React.useRef(null);
  
  const [isDragging, setIsDragging] = React.useState(false);
  
  function imageUrlChangeEffect() {
    imgRef.current.src = props.url;
  }
  
  function componentMountEffect() {
    imgRef.current.onload = handleImageLoad;
    canvasRef.current.onmouseup = handleMouseUp;
    canvasRef.current.onmousedown = handleMouseDown;
    canvasRef.current.onmousemove = handleMouseMove;
  }

  function handleMouseUp() {
    setIsDragging(false);
  }
  
  function handleMouseDown() {
    setIsDragging(true);
  }
  
  function handleMouseMove(ev) {
    const {x, y} = ev;
    console.log({x, y, isDragging});
  }
  
  function handleImageLoad() {
    clearCanvas();
    drawImage();
  }
  
  function clearCanvas() {
    const context = canvasRef.current.getContext("2d");
    context.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);
  }
    
  function drawImage() {
    const context = canvasRef.current.getContext("2d");
    context.drawImage(imgRef.current, 0, 0, imgRef.current.width, imgRef.current.height);
  }

  React.useEffect(componentMountEffect, []);
  React.useEffect(imageUrlChangeEffect, [props.url]);

  return (
    <div className="image-viewer">
      <p>is dragging: {isDragging.toString()}</p>
      <canvas ref={canvasRef} width="600" height="200"></canvas>
      <img ref={imgRef} />
    </div>
  );
}

ReactDOM.render(
  <ImageViewer url="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" />,
  document.getElementById("container"));

Here is a testable code sample. You have to bring up the console to see the console logs of the variable never changing to true as you move your mouse and hold down the mouse button. You see though that the text above the canvas changes to show that it's changing from false to true ...

https://codepen.io/betawarz/pen/poRQdpa

ANSWER

Answered 2021-Apr-22 at 00:23

you have at least two solutions here:

Solution 1:

declare listener on canvas:

<canvas ref={canvasRef} width="600" height="200" onMouseMove={handleMouseMove}></canvas>

and use native event in the handleMouseMove:

const {x, y} = ev.nativeEvent;

Solution 2:

instruct useEffect to update value of isDragging:

React.useEffect(componentMountEffect, [isDragging]);

Source https://stackoverflow.com/questions/67204106

QUESTION

Kotlin Android - Notification not appearing as heads up

Asked 2021-Apr-13 at 21:19

(My device is running Android 5.1.)

Hello,

For an app I've making, I've created a type of notification class, with methods, etc., which make it easy to create notifications.

I've tried to configure it to use a 'heads-up' notification, although it has not been working for me. It just appears as a regular notification: maybe I have gotten something wrong?

Notification helper class and interface:

interface NotificationHelper {
        fun startNotification(title: String, text: String, priority: Int, smallIcon: Int)
    }
    
    class DefaultNotificationHelper(private val context: Context) : NotificationHelper {
        private val channelID = "channel_01"

        private fun registerNotificationManagerWithSystem(channel: NotificationChannel) {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
                (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(channel)
            }
        }

        private fun createNotificationChannel() {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
                val notificationChannelInstance = NotificationChannel(channelID, "Channel 1", NotificationManager.IMPORTANCE_HIGH).let {
                    it.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
                    it.setShowBadge(true)

                    registerNotificationManagerWithSystem(it)
                }
            }
        }

        private fun createNotificationInstance(title: String, text: String, priority: Int, smallIcon: Int): NotificationCompat.Builder {
            return NotificationCompat.Builder(context, channelID)
                    .setContentTitle(title)
                    .setContentText(text)
                    .setPriority(priority)
                    .setDefaults(DEFAULT_VIBRATE)
                    .setDefaults(DEFAULT_SOUND)
                    .setSmallIcon(smallIcon)
        }

        private fun notify(notificationCompat: NotificationCompat.Builder) {
            (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).notify(1, notificationCompat.build())
        }

        override fun startNotification(title: String, text: String, priority: Int, smallIcon: Int) {
            createNotificationChannel()
            notify(createNotificationInstance(title, text, priority, smallIcon))
        }
    }

Implementation:

val notificationHelper = DefaultNotificationHelper(this)
        notificationHelper.startNotification("Hello", "Hello", NotificationCompat.PRIORITY_HIGH, R.drawable.fire_gradient)

Appreciate your help - it could be something related to my phone though.

Cheers,

Tom Joney

Edit: I've determined that it's just an issue with my phone, it doesn't matter how hard I try - it will never work. Don't get a Huawei Y6 Elite if you want to test heads-up notifications, it WON'T work no matter how hard you try.

ANSWER

Answered 2021-Apr-13 at 08:05

Here's the Github project link, it has a custom heads-up notification code. https://github.com/kavitamp/CustomHeadsUpNotification

I have tested it on Android 10 & it's working fine. Here's the screenshot. enter image description here

Source https://stackoverflow.com/questions/67030970

QUESTION

How do I make this shape in HTML?

Asked 2021-Feb-24 at 05:19

I'm trying to make this shape in HTML/CSS, and I can't do it for the life of me. If anyone can give a heads-up, it would be much appreciated. Including JS also doesn't matter. If you can give the smallest nudge in the right direction, I would be grateful. Thanks, here's the drawing.

Shape

ANSWER

Answered 2021-Feb-23 at 16:49

Create a couple of divs, one the width and height of the big bit, one a square with width that of the diameter of the semi circle.

Background of both black.

Big bit has border-radius something like 10%, play around to get what you want, on the top corners, 0 on the bottom corners.

Semi circle is a circle in fact, border radius 50%. Position absolute within the big bit.

Warning, sometimes border radius can give a not very smooth finish. If that’s a problem you could try an SVG, but your question stipulated HTML and CSS.

If you make the dimensions and positioning %s it will expand or contract to fit as required.

Source https://stackoverflow.com/questions/66336999

QUESTION

Can I detect a hanging JS function and abort?

Asked 2021-Feb-12 at 18:35

I am working on a tool that allows users to enter a regular expression for a find&replace, and then my tool will execute that find&replace and return the changed text. However, I recently ran into a situation where the find&replace simply froze, so I decided it would probably be best to somehow detect issues with regular expression matching, and abort after a certain amount of time has passed.

I've checked around, and what I was able to find using this answer was that the problem I'm experiencing was called 'catastrophic backtracking'. That's ideal to know, because that way I can make a minimal working example of where it goes wrong, however not ideal if the solution to change the regular expression isn't possible, because I have no control over the user's regex input (and there's no way I can write an advanced enough regex parser to limit the user's regex usage to exclude situations like this).

So in an attempt to solve this, I tried using promises, as suggested in this answer. I've made the 'catastrophic' match string in this example just long enough for the effect to hang my tab for a few seconds, without completely crashing the tab. Different computer specs may see different results though, I'm not sure.

Just one heads-up: Executing this code might freeze your current tab. PLEASE make sure you do not have a partial answer written when executing this code, as it might cause loss of work.

var PTest = function () {
    return new Promise(function (resolve, reject) {
    setTimeout(function() {
      reject();
    }, 100)
    "xxxxxxxxxxxxxxxxxxxxxxxxx".match(/(x+x+)+y/)
    resolve();
  });
}
var myfunc = PTest();
myfunc.then(function () {
     console.log("Promise Resolved");
}).catch(function () {
     console.log("Promise Rejected");
});

On my computer, this causes the tab to freeze for about 4 seconds before showing "Promise Resolved" in the console.

My question now is: is it at all possible to "abort" the execution of a script like this, if execution takes too long (in the example: over 0.2 seconds)? I'd rather kill the regex find&replace than completely crash the tool, causing loss of work for the user.

ANSWER

Answered 2021-Feb-12 at 18:35

I recommend using a Web Worker since it will run in its own sandbox: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API

The Web Worker is its own script that you need to include in your JavaScript, such as:

var worker = new Worker('/path/to/run-regex.js');

The following is untested code, but should get you going.

Your run-regex.js does the (potentially long running) regex match:

function regexMatch(str, regexStr, callback) {
  let regex = new RegExp(regexStr);
  let result = str.match(regex);
  callback(result, '');
}

onmessage = function(e) {
  let data = e.data;
  switch (data.cmd) {
    case 'match':
      regexMatch(data.str, data.regex, function(result, err) {
        postMessage({ cmd: data.cmd, result: result, err: err });
      });
      break;
    case 'replace':
      //regexMatch(data.str, data.regex, data.replace, function(result, err) {
      //  postMessage({ cmd: data.cmd, result: result, err: err });
      //});
      break;
    default:
      break;
      postMessage({ err: 'Unknown command: ' + data.cmd });
  }
}

In your own script, load the Web Worker, and add an event listener:

if(window.Worker) {
  const myWorker = new Worker('/path/to/run-regex.js');

  myWorker.onmessage = function(e) {
    let data = e.data;
    if(data.err) {
      // handle error
    } else {
      // handle match result using data.result;
    }
  }

  function regexMatch(str, regex) {
    let data = { cmd: 'match', str: str, regex: regex.toString() };
    myWorker.postMessage(data);
  }

  regexMatch('xxxxxxxxxxxxxxxxxxxxxxxxx', /(x+x+)+y/);

} else {
  console.log('Your browser does not support web workers.');
}

With this, your main JavaScript thread is non blocking while the worker is working.

In case of a long running worker, you may add code to either:

Source https://stackoverflow.com/questions/66153487

QUESTION

React / Gatsby - render different component based on screen size

Asked 2020-Oct-30 at 19:34

(Heads-up warning: I am not extremely familiar with React/GraphQL, so please go easy on me).

I am building a blog using Gatsby and my navbar changes its appearance based on the screen-size. In the middle of my navbar is the logo of the blog. Now, when the reader is viewing the page on Desktop, I want the full logo (including text) to show. When they are viewing it on mobile, I only want the actual logo (excluding text) to be rendered (I have one image with the full logo and one image with the shortened logo).

So far, my approach has been to 1. create two separate SiteNavLogo-components and 2. check the current window size using the following block of code (I removed all of the code that is not relevant to this problem and replaced it with "...") and 3. render one of the two logo-components conditionally:

class SiteNav extends React.Component {
  ...
  };

  render(): JSX.Element {
    changeLogo = window.matchMedia('(max-width: 600px)').matches;
    return (
      <>
            ...
            {changeLogo && (
            <SiteNavLogoMobile />) || !changeLogo &&
            <SiteNavLogo/>}
      </>
    );
 }
}

This works fine with gatsby develop but fails with gatsby build because "window" is not available. In this article I found the recommendation to use componentDidMount, so I tried this:

class SiteNav extends React.Component {
   changeLogo = false;
   componentDidMount(): void {
    this.changeLogo = window.matchMedia('(max-width: 600px)').matches;
  }
  };

  render(): JSX.Element {
    return (
      <>
            ...
            {this.changeLogo && (
            <SiteNavLogoMobile />) || !this.changeLogo &&
            <SiteNavLogo/>}
      </>
    );
 }
}

The problem with this is that the first render cycle is executed before componentDidMount is executed, which means that the page will always be rendered with changeLogo=false.

How can I make it so that when a mobile user views the page, the shortened logo is rendered? (Do I even need two components for this or can I just change my GraphQL-query?) Any advice is highly appreciated.

ANSWER

Answered 2020-Oct-25 at 14:44

You should use the component's state to store the changeLogo variable. By using a state variable, changeLogo is correctly updated in componentDidMount() resulting in the correct nav bar being displayed.

To ensure that changeLogo updates depending on the viewport width, an addEventListener has also been included in the component.

class SiteNav extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      changeLogo: false
    };
    this.handleResize = this.handleResize.bind(this);
  }

  handleResize() {
    this.setState({
      changeLogo: window.matchMedia("(max-width: 400px)").matches
    });
  }

  componentDidMount() {
    window.addEventListener("resize", this.handleResize);
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.handleResize);
  }

  render() {
    return (
      <div>
        {this.state.changeLogo && <SiteNavLogoMobile />}
        {!this.state.changeLogo && <SiteNavLogo/>}
      </div>
    );
  }
} 

Here's a Codesandbox demo.

Source https://stackoverflow.com/questions/64523091

QUESTION

Google analytics API - how to create new account

Asked 2020-Sep-15 at 22:51

Okay, some heads-ups as I feel I'm an idiot and missing some simple stuff. As far as I understand Google Analytics works with a 3 tiers system: account -> property -> view. and I should be able to manage these 3 levels via the google analytics management api.

For some context as to why I encounter this issue. I am making a CMS in which I want to register a new google analytics account per user, and a property per website this user has. (implementation and usage of views out of scope for now, I will implement those on a later date). To achieve all of this I started following Google's documentation on the Google Analytics Management API (according to Google this is what manages accounts, properties and views). Therefor I have made a service-user-account which should have enough permissions to manage GA-accounts.

However I can't seem to be able to create a new account via the API. Am I missing something obvious? Is it not possible at all this way? If so, how then? Because my goal is to have GA on every website, without the user having to config anything.

ANSWER

Answered 2020-Sep-15 at 22:51

You can't do it. The management API only allows for the list operation on accounts: https://developers.google.com/analytics/devguides/config/mgmt/v3/account-management#account_summaries

The only solution would be to use the Provisioning API. It can be used to create new Google Analytics accounts and enable Google Analytics for your customers at scale: https://developers.google.com/analytics/devguides/config/provisioning/v3/

Anyway, the Provisioning API is currently available by invitation only.

Source https://stackoverflow.com/questions/63884816

QUESTION

Android heads-up notification not showing after disable and enable it on application settings

Asked 2020-Sep-01 at 10:08

I made heads up notification on my application and it's working well.
But when I disable -> enable it on my application notification settings, I can not see heads up notification anymore.
(It still shows on notification bar, makes sound and vibration, but not on heads-up)

-- The logcat message says.

  • before disable/enable it
    showForNotification : isInteractive=true, isHeadUp=true, color=0, sbn = StatusBarNotification...

  • after disable/enable it
    showForNotification : isInteractive=true, isHeadUp=false, color=0, sbn = StatusBarNotification...

This issue is not resolved when the app is killed and restarted.
Only works normally again when app is deleted and reinstalled.

Is there any way to solve it?

Thanks for your time.


Edited

I found same issue on sample code
https://github.com/googlearchive/android-Notifications

In this application, set notification style to BIG_PICTURE_STYLE and press launch button. then, you can see heads-up notification, but after set "Sample Social" notification settings off -> on from application notification settings, you can not see heads-up notification anymore.

ANSWER

Answered 2020-Sep-01 at 10:08

That is the expected behavior. When the user blocks notifications for a particular notification channel in the notification settings, the importance for that notification channel is reduced. Due to which the notification banner will not show across the top of the device. The user will have to manually set the appropriate settings for the notification channel.

That would be considered as the user's preference and should not be changed forcibly from the application.

If for whatever reason you absolutely need the notification for the proper functioning of the application, you can detect if the user has disabled notifications or if the importance of a notification channel has been changed and ask the user to change it. Check this

If for whatever reason you need to forcibly maintain notification settings, what you can do is to delete notification channels and recreate them with the appropriate importance.

Note: If you delete a notification channel and create a new channel with this same id, the deleted channel will be un-deleted with all of the same settings it had before it was deleted. Thus, you need to create a channel with a new id.

To check if notifications are blocked for the application, use NotificationManager.areNotificationsEnabled(). Documentation

To check if notifications are blocked for a notification channel group, use NotificationChannelGroup.isBlocked(). Documentation

To check if the importance of a notification channel has been changed:

  1. For API 26 to API 28, use NotificationChannel.getImportance() to see if the notification channel importance has been changed. Note that the importance of a channel cannot be changed programmatically once the channel has been created. Documentation
  2. For API 29 and above, use NotificationChannel.hasUserSetImportance(). Documentation

Source https://stackoverflow.com/questions/63593137

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

VULNERABILITIES

No vulnerabilities reported

INSTALL heads-up

You can use heads-up like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the heads-up component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

SUPPORT

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

Implement heads-up faster with kandi.

  • Use the support, quality, security, license, reuse scores and reviewed functions to confirm the fit for your project.
  • Use the, Q & A, Installation and Support guides to implement faster.

Discover Millions of Libraries and
Pre-built Use Cases on kandi