Adding/removing progress bar spinners leaves newlines

When displaying a progress bar at the bottom and spinner(s) above, the spinners leave newlines when they get cleared:

This is the source code for this test:
use std::{thread, time::Duration};
use indicatif::{MultiProgress, ProgressBar, ProgressDrawTarget};

fn main() {
	let pbs = MultiProgress::with_draw_target(ProgressDrawTarget::stderr());
	let pb = ProgressBar::new(20);
	pbs.add(pb.clone());

	for i in 0..20 {
		let msg = format!("running {i}");

		let run_pb = ProgressBar::new_spinner();
		run_pb.enable_steady_tick(Duration::from_millis(100));
		run_pb.set_message(msg);
		pbs.insert_from_back(1, run_pb.clone());

		thread::sleep(Duration::from_secs(1));

		run_pb.finish_and_clear();
		pb.inc(1);
	}

	pb.finish();
}

The issue is that you called some methods on the ProgressBar which caused draws, before adding them to the MultiProgress. MultiProgress assumes ProgressBars that have been added to it have not been drawn yet. (Perhaps we can enforce this in code...)
let run_pb = ProgressBar::new_spinner();
run_pb.enable_steady_tick(Duration::from_millis(100));
run_pb.set_message(msg);   // <- draw happened
pbs.insert_from_back(1, run_pb.clone());  // <- add to MultiProgress, but it's too late...

If you re-order those lines, everything works:
let run_pb = ProgressBar::new_spinner();
pbs.insert_from_back(1, run_pb.clone());
run_pb.enable_steady_tick(Duration::from_millis(100));
run_pb.set_message(msg);

Also, you can make the code simpler by avoiding the clones:
use std::{thread, time::Duration};
use indicatif::{MultiProgress, ProgressBar, ProgressDrawTarget};

fn main() {
	let pbs = MultiProgress::with_draw_target(ProgressDrawTarget::stderr());
	let pb = pbs.add(ProgressBar::new(20));

	for i in 0..20 {
		let msg = format!("running {i}");

		let run_pb = pbs.insert_from_back(1, ProgressBar::new_spinner());
		run_pb.enable_steady_tick(Duration::from_millis(100));
		run_pb.set_message(msg);

		thread::sleep(Duration::from_secs(1));

		run_pb.finish_and_clear();
		pb.inc(1);
	}

	pb.finish();
}

It also removes the temptation to call methods before adding them to the MultiProgress :).

Thanks, that indeed fixed my problem :)
Maybe you could at least store a flag (in debug mode) for progress bars whether they have been drawn already, and print a warning when you add one to a multi progress that had already been drawn?

Thanks, that indeed fixed my problem :)
Maybe you could at least store a flag (in debug mode) for progress bars whether they have been drawn already, and print a warning when you add one to a multi progress that had already been drawn?

I agree, that would be helpful. I will submit an issue for myself to consider adding this feature.


can we merge the happler and haptools format specs for haplotypes?

...and just have a single format spec for haplotypes instead of two different ones?
I know we did a lot of work on both specs already, so I know I'm kinda proposing a huge backtrack, but I felt like we didn't really consider it before and I figured it would be better to throw it out there as an idea now before we try to move to a beta version of both tools where it would be harder for us to consider a change.

From a haptools perspective, the main thing that the happler format spec doesn't have is a way of encoding local ancestry. But I think this could be added as another attribute of the haplotype metadata.

[ ] create a subcommand to check that a .hap file is formatted properly (ie matches the spec)

how to read the haplotype lines?
HAPLOTYPES

search for H lines w/ ID
get variants w/ tabix
REGION
get haplotypes w/ tabix
get variants w/ tabix
ALL
iterate through, line by line, while storing info

ok, I just thought of something!
In order to make it easier to parse through the files, we can require that lines of the same type are kept together!
This is easy to achieve if we sort the lines by their type, and then their contig, and then their start + end positions
To facilitate that, we might want to consider moving the ID field to be right after the end position field

how should the code be organized?

[ ] The Haplotypes class lives in the data module and reads and writes from the .haps files
[ ] We define a Haplotype abstract class (in the data module) with fields for each of the mandatory lines in the haps format spec and an abstract property for the extra fields
[ ] The Haplotype abstract class gets implemented for local ancestry and a beta effect size (and a transform function)
[ ] The Haplotypes class must be initialized with a Haplotype object
[ ] We also define a Variant abstract class (in the data module) with fields for each of the mandatory lines in the haps format spec and an abstract property for the extra fields
[ ] The Haplotypes class must be initialized with a Variant object
[ ] we create a new function in the Haplotypes class that checks that the requested extra fields are supported by the header lines

and we call this function automatically in Haplotypes.load

[ ] The Haplotype abstract class and Variant abstract class each require methods to convert a line from the .haps format spec into the object and vice versa. These get called from within the Haplotypes class
[ ] The Haplotype abstract class and Variant abstract class themselves inherit from a different abstract class that requires CHROM, START, END, and ID fields


MAAS-2470 | Trigger push feeder on startup

Coverage increased (+0.6%) to 83.492% when pulling a331dfcfc8bf28d8e66cfd8134d5ab5bec773070 on develop into 734308f8ece4ef8f321230bf6459dcdd6e6d5eee on master.


[Bug]: randen_detect.cc compilation failure with Intel compilers

Describe the issue
I decided to try compiling Tensorflow with the latest Intel compiler (/opt/intel/oneapi/compiler/2023.0.0). The compilation failed on abseil like so:
external/com_google_absl/absl/random/internal/randen_detect.cc:50:13: error: static declaration of '__cpuid' follows non-static declaration
static void __cpuid(int cpu_info[4], int info_type) {
            ^
external/com_google_absl/absl/random/internal/randen_detect.cc:50:13: note: '__cpuid' is a builtin

Apparently the Intel compilers define the __cpuid built-in similar to MSVC. (But the compiler itself is based on LLVM.)
Steps to reproduce the problem
Compile abseil using any recent Intel compiler
What version of Abseil are you using?
Just looking at the source code for randen-detect.cc this is present in the master branch.
What operating system and version are you using?
Alma Linux 9.1
What compiler and version are you using?
Intel compiler 2023.0.0 and 2022.2.1 both fail this way.
What build system are you using?
N/A
Additional context
Easiest fix is probably to detect the Intel compilers and do not define your own __cpuid() when using them.
The newer Intel compilers provide the preprocessor symbol __INTEL_LLVM_COMPILER (see here for details).

Alternatively, name this static function "cpuid" (since technically the double-underscore name is reserved) and have it call __cpuid() on MSVC.


FileNotFoundError: [Errno 2] No such file or directory: 'Simulation_data/buckSimulation_0.mat'

Hello Mr. Zhao
I run the file in PyCharm and get the below error, though I put the buck simulation files in directory:
FileNotFoundError: [Errno 2] No such file or directory: 'Simulation_data/buckSimulation_0.mat'
How can I solve that?

Hi Javadshamsicodes, you can find the datasets in the subfolder Simulation_data and then specify the path yourself.


Remove unused tuf code

Summary

Removed tuf policy.go

Release Note
None

While doing this I ran into this #736

I would be adding additional Fuzz tests and then integrating with oss-fuzz

@asraa FYI

Hi!
Note that this seems to be testing repository creation via policy.go: which is not used anywhere
It would be good to have a TUF client fuzzer, on the other hand, but that also interacts with a filesystem, not sure how easy that is to fuzz (the code in client.go)
Maybe this PR can actually remove the policy.go files entirely

I have removed the policy.go and its tests.

Hi!
Note that this seems to be testing repository creation via policy.go: which is not used anywhere
It would be good to have a TUF client fuzzer, on the other hand, but that also interacts with a filesystem, not sure how easy that is to fuzz (the code in client.go)
Maybe this PR can actually remove the policy.go files entirely

I have removed the policy.go and its tests.

@asraa   It is breaking the signer.go. Should that also be removed?

Hi!
Note that this seems to be testing repository creation via policy.go: which is not used anywhere
It would be good to have a TUF client fuzzer, on the other hand, but that also interacts with a filesystem, not sure how easy that is to fuzz (the code in client.go)
Maybe this PR can actually remove the policy.go files entirely

Testing with file system is going to be an issue. Unless there is some abstraction AFAIK.

@asraa It is breaking the signer.go. Should that also be removed?

Yes!

Unless there is some abstraction AFAIK.

Enabling a test env var SIGSTORE_NO_CACHE disables the filesystem, but the problem is that the filesystem cache has had bugs before (and is the only major component off of go-tuf client itself)
We can configure the test dir to be a tempdir, and golang might work with an abstract fs impl

Unless there is some abstraction AFAIK.

Enabling a test env var SIGSTORE_NO_CACHE disables the filesystem, but the problem is that the filesystem cache has had bugs before (and is the only major component off of go-tuf client itself) We can configure the test dir to be a tempdir, and golang might work with an abstract fs impl

OK. Thanks

@asraa Friendly ping

Hey, does that mean that the following cosign/cli/policy_init.go is unused and should be removed as well?

Hey, does that mean that the following cosign/cli/policy_init.go is unused and should be removed as well?

Yes, I believe so - the only relevant TUF code is under the tuf package in this repo (which cosign pulls from) and has the client code!

pkg/tuf should provide anything TUF-related (client side) to the rest of the sigstore projects.

Correct!

As a side note here, I se e some parts of TUF-related code that leaked out a bit into other projects/packages that should probably be moved to sigstore/pkg/tuf.

Hmm, I think there may be some accessors (like GetFulcio) that are leaked into other packages as intermediates. TBH, I think I agree that the tuf package should be all that's necessary.
That being said, those methods should be deprecated anyway and replaced with https://github.com/sigstore/sigstore/issues/1042

With the completion of https://github.com/sigstore/cosign/pull/2846, I think it should be safe to move forward with removing policy.go and signer.go too 👍

@rdimitrov did you want to take over removing those files? I’d say let’s just open a new pr

@rdimitrov did you want to take over removing those files? I’d say let’s just open a new pr

Sure 👍 I'll open a PR at the end of next week(due to PTO).


ValueError: Error when checking target: expected dense_8 to have 2 dimensions, but got array with shape (X, 172800, 3)

here is my model:
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
Y_train = np_utils.to_categorical(y_train, 3)
Y_test = np_utils.to_categorical(y_test, 3)
model = Sequential()
model.add(Convolution2D(32, (3, 3), activation='relu', input_shape=(360,480,3)))
model.add(Convolution2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Convolution2D(16, (3, 3), activation='relu'))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(172800, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary()
model.fit(X_train, Y_train,
batch_size=8, nb_epoch=10, validation_data=(X_test, Y_test), verbose=1)
score = model.evaluate(X_test, Y_test, batch_size=8,verbose=1)
model.save('car_road_weights1.mdl')

Layer (type)                 Output Shape              Param #
conv2d_10 (Conv2D)           (None, 358, 478, 32)      896

conv2d_11 (Conv2D)           (None, 356, 476, 32)      9248

max_pooling2d_4 (MaxPooling2 (None, 178, 238, 32)      0

conv2d_12 (Conv2D)           (None, 176, 236, 16)      4624

dropout_7 (Dropout)          (None, 176, 236, 16)      0

flatten_4 (Flatten)          (None, 664576)            0

dense_7 (Dense)              (None,<PHONE_NUMBER>6

dropout_8 (Dropout)          (None, 128)               0

dense_8 (Dense)              (None, 172800)            22291200
Total params: 107,371,824
Trainable params: 107,371,824
Non-trainable params: 0

Please check the shape of your Y_train, it should be [None, 172800] according your model definition, but Y_train = np_utils.to_categorical(y_train, 3) produce the shape of [None, 172800, 3], they are mismatched.


Questions about installing mxnet and gluoncv on nvidia jetson tx2

I tried the mxnet official website to use the source installation steps, failed after many attempts.
Use sudo pip install mxnet-jetson to install successfully, but the latest version is 1.2.1, and gluoncv requires mxnet version to be at least 1.3.0 (otherwise when importing gluoncv error)
How do I upgrade the mxnet version on jetson to 1.3.0 or higher?

@mxnet-label-bot add [question, build]
@Jessespace : Could you please share the errors you faced when trying to compile from source?
@KellenSunderland : Would you be able to provide a context on mxnet-jetson package and its upgrade time frames?

@mxnet-label-bot add [question, build]
@Jessespace : Could you please share the errors you faced when trying to compile from source?
@KellenSunderland : Would you be able to provide a context on mxnet-jetson package and its upgrade time frames?

My device is nvidia jetson tx2

I followed the steps of the official website, failed. ( Sorry, I didn't record the errors. )
I referenced here to recompile and succeeded. This is the follow steps:

sudo apt-get update
sudo apt-get -y install git build-essential libatlas-base-dev libopencv-dev graphviz python-pip
sudo pip install pip --upgrade
sudo pip install setuptools numpy --upgrade
sudo pip install graphviz jupyter

git clone https://github.com/apache/incubator-mxnet.git --recursive
cd incubator-mxnet

cp make/config.mk .
sed -i 's/USE_CUDA = 0/USE_CUDA = 1/' config.mk
sed -i 's/USE_CUDA_PATH = NONE/USE_CUDA_PATH = \/usr\/local\/cuda/' config.mk
sed -i 's/USE_CUDNN = 0/USE_CUDNN = 1/' config.mk
sed -i '/USE_CUDNN/a CUDA_ARCH := -gencode arch=compute_62,code=sm_62' config.mk

Editing 3rdparty/mshadow/make/mshadow.mk and adding the following after line 122:
MSHADOW_CFLAGS += -DMSHADOW_USE_PASCAL=1

make -j $(nproc)

cd ..     # (incubator-mxnet dir)
export MXNET_HOME=$(pwd)
echo "export PYTHONPATH=$MXNET_HOME/python:$PYTHONPATH" >> ~/.bashrc
source ~/.bashrc

The main difference between the above steps and the official website tutorial is that:
cp make/config.mk cp make/crosscompile.jetson.mk config.mk ,What is the difference between the two?
In addition, can you provide compiled mxnet1.4.0 ? The compilation process is too long, Thanks.

@Jessespace Can you try the instructions here: https://github.com/apache/incubator-mxnet/blame/master/docs/install/install-jetson.md

@Jessespace I've tried installation on Jetson TX2 before and I would definitely recommend using the cross-compilation method.

yiyiy


Allow parameters to mark be Advanced

If a group has advanced options then add a toggle to it's panel header. If the toggle is enabled then show the advanced parameters. See @spg-matt's designs for the layout of the new form page.
The goal here being that this doesn't impact validation at all. If a parameter is marked advanced then it should either:

not be required and thus no problem if the user doesn't fill it out
have an intelligent default

Sound doable?

Ref comit: https://github.com/samtecspg/conveyor/commit/b23a788e990279de2b245977a5574c1dbe1afd2a
Added isAdvance boolean attribute to the parameter object.
When the Advance toggle os off this parameters will be ignored even if they are marked as required.


Issue with  "Exclude certain URLs"

Hi Leon,
Hope you are doing well.
For example, I want to exclude all urls that begin with /news (a sub site in a network site) e.g /news/post-url
so I added these urls to the exclude certain URLs option
/news
/news/
https://www.dropbox.com/s/ozfgaongah6uay4/2020-06-18_08-33-47.png?dl=0
and then it will exclude all urls containing /news e.g /category/news or /blog/news
Thank you!

Thanks for reporting, @nhhau!
I'll be doing some work around exclusions/inclusions before next release, as those areas have changed in latest versions and not yet tested/fixed - I have some improvement plans:
https://github.com/WP2Static/static-html-output-plugin/issues/107
For the multisite - I highly recommend to run the multisites as subdomain sites, not subdirectory.
I'm probably going to officially say I don't support running the plugin on sites with WP hosted in a subdirectory, whether it be a multisite network or a single site at example.com/wp/
It may be working for you today, but I can't guarantee it will continue to work properly


"no tty present and no askpass program specified" exception with sudo in deploy:writable task

Hi,
I'm using username/password ssh
server(...)
    ->user('username', 'password')

and
set('writable_use_sudo', true); // Using sudo in writable commands?

And there was RuntimeException with sudo commands at deployment:
 [RuntimeException]
  sudo: no tty present and no askpass program specified

Is there a solution for this or passwordless sudo is a must?
Thank you.

Yes, now passwordless sudo is a must.

Thanks @elfet

I think it would be unsafe when deploy user can change permission of directory and files without sudo password.

@oanhnn You can configure sudo to allow explicit commands and arguments to be executed without asking for a password. See https://stackoverflow.com/a/24107529/1119601


Add Programiz Website for Frontend Tools Section

Related Issue
Closes #887

Description

Add Programiz website for Learning Programming for Free including Frontend Technologies Available in this Website

Screenshots

Checklist

[x] My code adheres to the established style guidelines of the project.
[x] I have included comments in areas that may be difficult to understand.
[x] My changes have not introduced any new warnings.
[x] I have conducted a self-review of my code.

I Deleted Previous PR  and Update this New PR in DB Json File Also

@NarendraKoya999, your issue suggests adding just 1 tool, so the PR should do the same. Please revert the changes back and only modify what is mentioned in the issue. Also, format the title of the PR to prevent it from entering the workflow.
For example : chore: your title


Upgrade machine-controller to v1.4.0

https://github.com/kubermatic/machine-controller/releases/tag/v1.4.0
P.S.
There are new fields in spec

I want to give this a try
/assign
/lifecycle active


continuous-integration

Relate to actions executed for its continous integration.
https://github.com/jgwill/pto_jubook_as_website2409/actions/new?category=continuous-integration

What does that implies ?  Each time a Push is made, actions execute in the cloud.

there was a notion of the pole request when you resolve an issue with some work want to trigger emerge that execute whatever testing to ensure that it doesn't break the main branch if it works well that work is done


Lifecycle events and HeadlessJS on Android

I'm interested in how exactly lifecycle events work with HeadlessJS and how they should be used by react-native modules.
Example: If I were to make a background task where I'm fetching messages only over WiFi, I'd need NetInfo to tell me the network type. I'd register a listener and stop fetching if network provider changed.
The problem is that onHostResume, onHostDestroy and onHostPause listeners are triggered when something happens with the main activity.
In the above case, NetInfo unregisters receiver and the background task that can still be running (despite activity being destroyed or on pause) will no longer receive events on network provider. There might be other ways to solve the task above but there can be plenty of similar tasks that are crippled by things done in native when actions on activity trigger lifecycle changes.
There seem to be other non-react-native modules doing similar things and completely crippling the background task.
Is this expected behavior?

What exactly happened here?

This is not a bug report and this is not a question or a problem I have with the library?
Should I frame the NetInfo implementation as a bug?

Hey @vjeranc, we have a bot that periodically closes issues that don't use the template provided. We're only using GitHub issues for bug reports at this time. If you can frame this within the requirements set forth by the template, go ahead and open a new issue. Otherwise it might be best to find another avenue to direct this sort of question.


wmt16_en_de.sh crashed with "Illegal byte sequence"

wmt16_en_de.sh runs partially then crashed:
Cloning into '/tmp/wmt16/subword-nmt'...
...
Learning BPE with merge_ops=32000. This may take a while...
Apply BPE with merge_ops=32000 to tokenized files...
... (many tok files here, skipped.)
/tmp/wmt16/newstest2016.tok.clean.bpe.32000.de
/tmp/wmt16/train.tok.clean.bpe.32000.de
cut: stdin: Illegal byte sequence
Traceback (most recent call last):
  File "/tmp/wmt16/subword-nmt/get_vocab.py", line 13, in <module>
    print(key+" "+ str(f))
IOError: [Errno 32] Broken pipe

Considering it took such a long time and almost done, how to fix the script and resume the whole procedure???
Thanks.

This only happens on Mac OS X. Everything is fine on Ubuntu 16.04 LTS.

Has there been any fix for this? I've been getting the same error. Running this on macOS Sierra.
/tmp/wmt16/train.tok.clean.bpe.32000.de
/tmp/wmt16/subword-nmt/get_vocab.py:60: DeprecationWarning: this script's location has moved to /tmp/wmt16/subword-nmt/subword_nmt. This symbolic link will be removed in a future version. Please point to the new location, or install the package and use the command 'subword-nmt'
  DeprecationWarning
cut: stdin: Illegal byte sequence
Traceback (most recent call last):
  File "/tmp/wmt16/subword-nmt/get_vocab.py", line 82, in <module>
    get_vocab(args.input, args.output)
  File "/tmp/wmt16/subword-nmt/get_vocab.py", line 50, in get_vocab
    vocab_file.write(key+" "+ str(f) + "\n")
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/codecs.py", line 370, in write
    self.stream.write(data)
IOError: [Errno 32] Broken pipe


#31: Restrict user to draw outside of image

#31

Nice job, but could you also make non-drawable area to be of other color?
At the moment, non-drawable area is white, the same as border markers.
It is a bit confusing for a user, easy to lose track of what is drawable and what is not.


Documentation: Broken links in IdentityProvider page

https://international-data-spaces-association.github.io/DataspaceConnector/CommunicationGuide/v6/IdsEcosystem/IdentityProvider
Links to documentation of DAPS and DAT are broken.

Link to documentation of Broker is affected too (https://international-data-spaces-association.github.io/DataspaceConnector/CommunicationGuide/v6/IdsEcosystem/Broker)

Documentation of ClearingHouse too: https://international-data-spaces-association.github.io/DataspaceConnector/CommunicationGuide/v6/IdsEcosystem/ClearingHouse

Thanks for the hint. Will be updated soon. Still not a bug just because I don't immediately notice when other repos change their structure ;)


Create Articles “how-to-check-your-garden-for-termites”

Automatically generated by Netlify CMS

👷 Deploy Preview for chic-shortbread-66a66b processing.

Name
Link

🔨 Latest commit
6ffbaf9e230c148589139d7211adf5de29a0fef8

🔍 Latest deploy log
https://app.netlify.com/sites/chic-shortbread-66a66b/deploys/672325db6beb3c000819c659


oct blog: add wge image

Signed-off-by: Daniel Holbach<EMAIL_ADDRESS>

→ https://deploy-preview-1248--fluxcd.netlify.app/blog/2022/11/october-2022-update/#weave-gitops-enterprise


start_row out of bounds error in function 'apply_highlights_fn'

Hi, I'm using inc-rename with dressing, following instructions in README.
Here's the error message when press  to confirm rename:

Thanks for reporting, I made a silly mistake in the previous commit. Fixed now!


Train on IAMDataset "Word" Crashes the code

Hello, I have a need to train the model with words. Can you please help me?
I tried by updating the code with max_seq_len =96 as "jonomon" mentioned but it crashes with error
DeferredInitializationError: Parameter 'cnnbilstm0_hybridsequential1_hybridsequential0_encoderlayer0_lstm0_l0_i2h_weight' has not been initialized yet because initialization was deferred. Actual initialization happens during the first forward pass. Please pass one batch of data through the network before accessing Parameters. You can also avoid deferred initialization by specifying in_units, num_features, etc., for network layers.
During handling of the above exception, another exception occurred:

Hey John, I was able to figure out. .size of features in CNNBiLSTM.hybrid_forward was a problem and it worked for me when i set max_seq_len =64


Default editor toolbar uses bad ids for buttons

This issue was imported from Closure Library's previous home at http://closure-library.googlecode.com
The link to the original issue is:
https://code.google.com/p/closure-library/issues/detail?id=273

This issue is being closed as a preparation step before archiving the repository.  See the README for more detail.


feaLib.builder_test.py contains non-unit tests

As it is right now, a few functions do this:
    def test_GPOS(self):
        for name in "1 2 2b 3 4 5 6 8".split():
            font = makeTTFont()
            addOpenTypeFeatures(self.getpath("GPOS_%s.fea" % name), font)
            self.expect_ttx(font, self.getpath("GPOS_%s.ttx" % name))

This is not good because we now only see one failure if any number of those tests fail.  Please rewrite these to add one function per test.  There are a couple of different ways to do that, for example, building the class dynamically.  I don't know what the best way is, but I'm sure there's a standard way to do that.
Thanks.

I recently used a class decorator for something similar: https://github.com/adrientetar/defcon/blob/python3-ufo3/Lib/defcon/objects/info.py#L49


program crash when run sparse model predict

I just run the linear_classification.py and save model.Then i need to predict data base on this model.
The predict code such as below:
if name == 'main':
args = parse_args()
prefix = './dnn'

devs = mx.cpu() if args.gpus is None else [
         mx.gpu(int(i)) for i in args.gpus.split(',')]

model_load = mx.model.FeedForward.load(prefix, args.iteration,ctx=devs)

test = mx.io.LibSVMIter(data_libsvm=args.test_dir, data_shape=(3864334,),
                              batch_size=args.batch_size, num_parts=1,
                              part_index=0,
                              num_epoch = 1)

[prob, data, label] = model_load.predict(test, return_data=True)
data_len = len(prob)

for i in range(0, data_len):
    print '%s\t%d\t%.6f' % ('1', label[i], prob[i])

shell command is as below:
python predict.py  --test-dir="./test41.xls" --iteration=1 --batch-size=2000
and then it will report
include/mxnet/././tensor_blob.h:275: Check failed: this->shape_.Size() == shape.Size() (77286
68000 vs.<PHONE_NUMBER>) TBlob.get_with_shape: new and old shape do not match total elements
how can i fixed it?
@eric-haibin-lin

How large is your weight matrix?  This is one of the mshadow-related legacy issues mentioned in https://github.com/apache/incubator-mxnet/issues/7319#issue-247538605
The problem is that 32 bit int is not sufficient to calculate the number of elements in a large matrix..

i have no idea how to caculate the weight matrix? batchsize*num_features?
batchsize is 2000,num_features is 3864334,
and in error log how<PHONE_NUMBER> is caculated?
In fact,during training ,the batchsize and num_features are setted the same as predict,and it can run during trainning.
@eric-haibin-lin

If you reduce batch_size to 1000 or 100, is the error still there?
I suspect there's some integer overflow problem

yes,there is no error report when batchsize reduce to 200.Maybe there is bug in code.
But why it is ok during trainning? Is the result right if the batchsize is setted to 2000 during trainning?
@eric-haibin-lin

The code only breaks when it calls this functions: https://github.com/apache/incubator-mxnet/blob/master/include/mxnet/tensor_blob.h#L270
It's just doing a sanity check to sure the shape matches.
It won't affect the quality of the model. You can either use small batch size for now as a walk-around, or remove that CHECK and build from source to predict with large batch size.

OK,
And one more question,
Now the train datasize is 98994453 ,bathsize is 200
it takes 2 hours to finish 1 epoch,seemed to slow.
Can it possible to speed up sparse trainning?
In other sparse lr training ,it should be much more faster
@eric-haibin-lin

batch size = 200 seems to be very small. You can increase the batch size to reduce the time for training per epoch (you have to increase learning rate according).
Module.load just loads the model symbols and model parameters. You can train with large data batch and predict with small batch.

is learning rate related to batchsize ?In code, grad has divided to batchsize.
In my data,if batchsize are  increased to 20000 or 200000,the model result will be bad.
@eric-haibin-lin

In fact,even the batchsize is increased to 200000,it take much to finish one epoch also
Time cost=2174.153
@eric-haibin-lin

Usually you want to increase the learning rate if batch size is increased.
What's the density of your model and how many classes are there?
If you have a GPU, you can change the ctx to mx.gpu(0) and run the same code without kvstore. The sparse.dot is implemented on GPU.
If you have multiple machines, you can do distributed training.

It cost 1868.217 in every epoch in one gpu,seemed so slowly.
There are only 2 classes ,0 and 1.Batchsizes are assigned to 80000,features num are 3864334.Train data sizes are 100 millions.
The same train data is run much fasted in my leagcy code in one machine
@eric-haibin-lin

What was your legacy code based on? Is it MXNet dense NDArray implementation?
For cpu training, did you train setting OMP_NUM_THREADS to different values and see if that affects training time? What version of MXNet are you using? Is it built from source?
If you run your programme in terminal, do you see any warning messages?
What optimizer are you using?
I wonder if you can post your training code and see if there's any obvious place for improvement.

The legacy code is implented by mpi for lr,used in my product,not mxnet.
The trainning code is modified a little by your sparse examples,change from weighted loss to LogsticRegressOutput
The mxnet version is 0.12.0,and it is build from source.
The log is as below:
auc is added by myself,and it won't affect the speed,wii it?
/search/ted/mxnet_new/example/../../python/mxnet/metric.py:1191: UserWarning: ^[[91mNew metric mxnet.metric.AUC registered with name auc isoverriding ex
isting metric mxnet.metric.AUC^[[0m
class AUC(EvalMetric):
2017-11-08 16:47:05,419 Namespace(batch_size=80000, gpus=0, kvstore=None, num_epoch=100, optimizer='sgd')
2017-11-08 16:47:09,010 Already bound, ignoring bind()
/search/ted/mxnet_new/example/../../python/mxnet/module/base_module.py:464: UserWarning: Parameters already initialized and force_init=False. init_param
s call ignored.
allow_missing=allow_missing, force_init=force_init)
2017-11-08 16:47:09,012 optimizer already initialized, ignoring...
/search/ted/mxnet_new/example../../python/mxnet/metric.py:1191: UserWarning: ^[[91mNew metric mxnet.metric.AUC registered with name auc isoverriding ex
isting metric mxnet.metric.AUC^[[0m
class AUC(EvalMetric):
2017-11-08 17:12:12,118 Namespace(batch_size=80000, gpus=0, kvstore=None, num_epoch=100, optimizer='sgd')
2017-11-08 17:12:15,516 Already bound, ignoring bind()
/search/ted/mxnet_new/example../../python/mxnet/module/base_module.py:464: UserWarning: Parameters already initialized and force_init=False. init_param
s call ignored.
allow_missing=allow_missing, force_init=force_init)
and line_model.py as below:
def linear_model(num_features, positive_cls_weight):
# data with csr storage type to enable feeding data with CSRNDArray
x = mx.symbol.Variable("data", stype='csr')
norm_init = mx.initializer.Normal(sigma=0.01)
# weight with row_sparse storage type to enable sparse gradient updates
#weight = mx.symbol.Variable("weight", shape=(num_features, 1),
#                            init=norm_init, stype='row_sparse')
weight = mx.symbol.Variable("weight", shape=(num_features, 1),stype='row_sparse',
)
bias = mx.symbol.Variable("bias", shape=(1,))
dot = mx.symbol.sparse.dot(x, weight)
pred = mx.symbol.broadcast_add(dot, bias)
y = mx.symbol.Variable("softmax_label")
#model = mx.sym.Custom(pred, y, op_type='weighted_softmax_ce_loss',
#                      positive_cls_weight=positive_cls_weight, name='out')
#return mx.sym.MakeLoss(model)
net = mx.symbol.LogisticRegressionOutput(data=dot, name="softmax")
return net
@eric-haibin-lin

I just set 2 environment values in mxnet.
export MXNET_GPU_COPY_NTHREADS=4
export MXNET_CPU_WORKER_NTHREADS=20
@eric-haibin-lin

Linear_classfication.py is also changed
model
# The positive class weight, says how much more we should upweight the importance of
# positive instances in the objective function.
# This is used to combat the extreme class imbalance.
positive_class_weight = 2
model = linear_model(num_features, positive_class_weight)

# module
mod = mx.mod.Module(symbol=model,data_names=['data'], label_names=['softmax_label'],context=devs)
mod.bind(data_shapes=train_data.provide_data, label_shapes=train_data.provide_label)
mod.init_params()
optim = mx.optimizer.create(optimizer, learning_rate=0.7,momentum = 0.8,rescale_grad=1.0/batch_size/num_worker)
mod.init_optimizer(optimizer=optim, kvstore=kv)
# use accuracy as the metric
metric = mx.metric.create(['ce','auc'])

# get the sparse weight parameter
weight_index = mod._exec_group.param_names.index('weight')
weight_param = mod._exec_group.param_arrays[weight_index]
speedometer = mx.callback.Speedometer(batch_size, 100)

mod.fit(train_data = train_data,
        eval_data = eval_data,
        eval_metric = metric,
        optimizer = optim,
        kvstore = kvstore,
        num_epoch = args.num_epoch,
        #batch_end_callback = mx.callback.Speedometer(batch_size, 10000),
        batch_end_callback = None,
        epoch_end_callback = save_model())

io: Are you using LibSVMIter for io?
metrics: it might affect speed depending on your implementation. Are you using numpy to implement it? (as a side-note, contribution back to MXNet is welcome!)
what commit id did you build MXNet from?
do you mind build it with USE_PROFILER=1 to enable profiler,  and set env_var MXNET_PROFILER_AUTOSTART to get the profiling result for your training of first 20 batches? That will be very helpful diagnose any performance bottleneck.
BTW, we observed some space for performance improvement for the backward of sparse.dot, and there's a PR for it: https://github.com/apache/incubator-mxnet/pull/8611 which will be potentially helpful in your case.

The cpu _backward_dot operator was improved by at least 3x in #8611
Do you want to sync with master and run it again?

Current LR example is broken due to the custom op. This is fixed in https://github.com/apache/incubator-mxnet/pull/8721.

@eric-haibin-lin ok,i will try later

1.After updating new codes,the trainning speed is still slowly.
Batchsize is 80000 also,train data size is 100 millions,the same as last testing.
It cost 1977.781s in gpus per epoch,and  cost 2038.416 cpus .
2.I don't t think metric affect the speed,because i have skip the metric during trainning.
3.how can i collect profile log?i'have build it with profile=1,and set export MXNET_PROFILER_AUTOSTART=0,but no profile log are printed on nohup logs.
@eric-haibin-lin

You can either inject these code into the training loop:
    mx.profiler.profiler_set_config(mode='all', filename='profile_output.json')
    mx.profiler.profiler_set_state('run')

    # Code to be profiled goes here...

    mx.profiler.profiler_set_state('stop')

or set MXNET_PROFILER_AUTOSTART=1 to enable auto start for profiling.
You can post the xxx_profile.json file here for us to take a look which part is the bottleneck.

I think the performance of _backward_dot operator needs to be improved further. I'll keep you posted.

Only touch profile_output.json first,and when run python linear_classification.py , the logs will be writed to
profile_output.json,But no more logs when the program started to training.

profile_output.txt

I see a lot of gaps between batches. It could be thread scheduling or IO overhead.
I don't think export MXNET_CPU_WORKER_NTHREADS=20 will help. This is useful when you have parallel path in the graph (for example, two operators can be executed at the same time). Maybe setting this to 1 or 2 is good enough. Setting this to a too high value will lead to some overhead.
MXNET_CPU_WORKER_NTHREADS controls how many operators executed in parallel, while OMP_NUM_THREADS controls how many threads run in parallel for any particular operator.
Could you also run with MXNET_CPU_WORKER_NTHREADS=1 and see if there's any IO bottleneck?

profile_output.txt
this is the updated profile ,when the 1 epoch is finished.

profile_output.txt
Here is the MXNET_CPU_WORKER_NTHREADS=1 ,it cost the same time as cpu_worker_nthreads=20

There's a 2-second gap between batches. What metric are you using? Did you verify how much time computing the metric takes? What data iterator are you using?

I used libsvm data iterator.And I set batch_end_callback=None,and re-run the new codes.It cost 1303.680s per epoch,the older codes cost  2038.416s.It did much more faster.
But it is still slower than my mpi lr code.For my code,the same datasize,it only cost 1.6 hours when run 100 epoches.
Do u think mxnet can be improved much for faster?
profile.txt

For this model you don't need to change the default value for MXNET_CPU_WORKER_NTHREADS . This env var is to enable running multiple operators in parallel when you have a computation graph that has divergent path. I recommend you setting it back to 1, which will make the profiler result much easier to read.
The time spent on forward and backward is only a small fraction of the total time. I don't see the profiler block for updater. What optimizer are you using? Is it any custom optimizer?

I think probably IO (libsvmIter) is the bottleneck.

profile (2).txt
This the latest profile,and i have set env value to 1.
SGD optimizer is used ,not any custom optimizer.
It did slowly ,though it is faster than last version

If I skip the forward/backward/update/update_metric,the cost time is reduced from 1303.680s  to 276.323s.It did cost much time when get batch data.
It may be a issue for every io iter,not only libsvmIter?
@eric-haibin-lin

@liumilan I don't know why your profiler doesn't show SGD optimizer at all. That's very strange. How did you compile MXNet? Did you set DEV=0, DEBUG=0, USE_PROFILER=1? Did you do a clean build when build config was changed?

@liumilan Just to follow up with this thread, are you still facing the issue?

@sandeep-krishnamurthy @nswamy @anirudh2290 Could you please close this issue due to lack of activity.
@liumilan Please feel free to re-open in case closed in error

@mxnet-label-bot add [suggest-closed]


Background mode not working on Android 8.0.0. Working on earlier versions

Test Environment:

Android 8.0.0
Phone: Galaxy S9+
Samsung experience version  9.0
Background Mode Version: cordova-plugin-background-mode 0.7.2 "BackgroundMode"
Cordova Android Version: 6.4.0
npm install output:

npm WARN optional SKIPPING OPTIONAL DEPENDENCY<EMAIL_ADDRESS>(node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for<EMAIL_ADDRESS>wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

Battery optimization disabled.

Symptoms:

Phone sleeps, fails several minutes after working in background
Notification is not showing up for backgroundmode
Logging the output of isEnabled(), I get an empty result (at least console.log doesn't show anything).

I'm happy to do any debugging or additional information that might help.

same here
Dont works in android 8

after 5 minutes of running the app in the background in android the app stops

Just worked around this. (I'm finding the issue is also happening on Android 7.)
I'm subscribing to pause and resume events from the platform. If I get paused, I set a timer for 2 minutes. When that times out, if the screen is locked I force the app to the foreground using bringtofront from https://github.com/markeeftb/cordova-bring-to-front.git. I'm sure I must be doing something wrong with this plugin, but I can't figure it out.

after 5 minutes of running the app in the background in android the app stops

That's what I'm seeing as well. I'm also noticing that the notification isn't showing up as described in the plugin. I've tried a few of the forks that fix the notification issue for 8.0... they fix the notification issue, but I was still seeing what you are seeing.

Same problem with me too. It works for few mins after going to background and then stops until I go back to foreground. And I guess this issue is coming with Samsung devices more often. Working slightly better on Nexus and other devices.

what I found in my testing was that after disabling webview optimizations, the code worked correctly:
this.backgroundMode.on('activate', () => this.backgroundMode.disableWebviewOptimizations());

what I found in my testing was that after disabling webview optimizations, the code worked correctly:
this.backgroundMode.on('activate', () => this.backgroundMode.disableWebviewOptimizations());

What device and OS are you working with? I'm testing on a Galaxy S9+, 8.0. I'll give this a try tonight.

not working after +- 5 minutes
Android 8.0

Same here I tried several times by Disabling Web View Optimisation.Its working better in Nexus but have a problem with Samsung. I guess Its because Samsung has custom OS which is customised Android OS.

what I found in my testing was that after disabling webview optimizations, the code worked correctly:
this.backgroundMode.on('activate', () => this.backgroundMode.disableWebviewOptimizations());

I tried this with my Samsung s9+, still fails to stay running. I send a ping every 30 seconds to the phone. At just under 4 minutes, the phone fails to reply to the ping. The ping timeout is set to about 40 seconds, so that means the phone app is stalling about 3 min 30 sec.

Does anyone managing this plugin anymore? This issue is really critical :(

Same problem with 8.0
Moto G5 7.0 Works well. Ancerra only stresses the system and call the camera, for example. It is still possible to circumvent predicting the user, and optimizing the maximum memory and CPU resource during persistent use, because it counts more in the decision of the system to encessr or not the application.
Moto X 8.0 With promises reported. In fact the service apparently is not really started, because neither the notification in my case works.
I've been through this problem for a long time. In fact every application, even the native ones like Google Maps in browsing mode, can be closed in more extreme ways (but close to my case). It will not be with a webviw cordon that will be different. I think the only way to actually create a persistent application is actually through direct services on the system, and this will not be possible with Cordova or the like.

I came across this solution mixing power management, partial wake-locks, and background mode: https://forum.ionicframework.com/t/i-found-a-solution-for-some-regular-background-activity/27012
Seems to do the trick for the samsung s9...

@mpfurnari  Do this trick works on all android?

i need keep open a websocket connect on background

i need keep open a websocket connection on background

That's exactly what's I'm doing...

I came across this solution mixing power management, partial wake-locks, and background mode: https://forum.ionicframework.com/t/i-found-a-solution-for-some-regular-background-activity/27012
Seems to do the trick for the samsung s9...

I've been running for hours with this solution... tested through phone calls, idle times, on a charger and off a charger. It seems to work. I'll be shipping with this solution. As I mentioned in my last comment, I'm setting up a WebSocket and need this to keep the other end informed that I'm still alive...

The mpfurnari solution has momentarily answered, even if it is not yet the ideal form, as I'm afraid the nescessity of it keeps the screen on and the application in the foreground: /. The truth is that there is only one really correct and stable way to do this: with java through service. I'm trying to integrate a real service into android (outside the webview environment) natively developed in java via plugin. However all behavior and methods must be done directly in the plugin, in java. It is not possible in this case to create a universal method because there is no java / javascript interaction for this case. What seems to be a possible solution (still in testing) is to have the application call the service and receive data from it and vice versa. If the application is paused or closed, the service will continue. If the application reopens, it collects the updated data gutted by the service.
I'm working together with a java developer for this. If you succeed, step here.
Hugs!

The mpfurnari solution has momentarily answered, even if it is not yet the ideal form, as I'm afraid the nescessity of it keeps the screen on and the application in the foreground :/ . The truth is that there is only one really correct and stable way to do this: with java through service. I'm trying to integrate a real service into android (outside the webview environment) natively developed in java via plugin. However all behavior and methods must be done directly in the plugin, in java. It is not possible in this case to create a universal method because there is no java / javascript interaction for this case. What seems to be a possible solution (still in testing) is to have the application call the service and receive data from it and vice versa. If the application is paused or closed, the service will continue. If the application reopens, it collects the updated data gutted by the service.
I'm working together with a java developer for this. If you succeed, step here.
Hugs!

Agreed this solution is not ideal in that it requires 2 plugins to make it work. However, you might want to try the solution before making comments. This does not keep the screen on... it stays off as it should. It also does not keep the application in the "foreground"; In fact, the application doesn't come to the top unless called upon. The cost of this (in my solution and measured in battery consumption) appears to be close to the solution without the partial wake-lock.  That said, I welcome a solution which provides an equivalent service layer that can easily be customized for a cordova app. Until then, I'm good with the partial wake-lock and the backgroundmode solution.

In my case, even with the two plugins, activating the window.powerManagement.dim mode, but putting the app in the background and stressing the system, the android paused the application (moto g5). If the app stays in the foreground, keeping the "dim" state on, it really does not stop. But I did not find a relation of the "dim" state with a supposed response of the system in killing or not the application when in the background. If the system needs resources, it will kill! Even because, from what I noticed, when you put the application in the background, this state is paused, only resuming if it is to the foreground again. But I pray that my ignorance is wrong.
I launched the solution for beta testers and I will monitor whether the report of problems with "normal" use decreases. I'm very fond of it, believe me!
I've been trying to get around this for over a year. As much as Cordova's own documentation does not recommend this and imposes this limitation, we try to stubbornly. I have combined all kinds of plugin and behavior. But I am more and more convinced that there really is nothing that can be done other than trying to develop a service through Plugin and with the methods directly in Java. Google Maps itself, for example, google native app, by not using a service, if put in background mode and stressing Android with the use of links and camera, it is dead, only maintain the state of form really stable in " acquire "(foreground and with the screen attached). Why would mine be any different?
Unfortunately, because of the limitations of the platform and the way it works, I do not see today how this so-called background services plugin can be developed and integrated with the webview JS, where it installs and submits to the javascript methods as a plugin any . It would be a kind of plugin itself, where your service is really built within the JAVA environment.
Maybe in a future version of Cordova? Do not know!
I am guided by this content:
https://www.red-folder.com/blog/phonegap-android-background-service

Agreed, if the app is kept in the foreground with this solution, it doesn't behave as desired when the phone is locked etc. My workaround for this will be to force the app into the background. It works for my application, but maybe not for everyone.
I haven't tried stressing the system, but I could see this causing issues with even just basic performance. Again, for my application, I'm not so concerned about excessive stress scenario. (My typical use case is with the phone otherwise idled.)
I'm very open to move the necessary functions to a service layer. Specifically, I'm trying to run an MQTT connection (over websockets for now, but not required.) Ultimately, though, my service layer needs to interrupt the user with notifications and vibrations.... I imagine my needs are not so different than many others developing system solutions that are not just basic phone apps.
I'd be very interested in what you uncover!
For now, though, this will have to do....

Is this about using API 26 as target sdk in android code or running any targeted sdk code on android 8.0 or above devices?

Is this about using API 26 as target sdk in android code or running any targeted sdk code on android 8.0 or above devices?

As far as I know, the issue is specific to Android 8.0 running on Samsung. @luisvt reported a similar problem but different solution (above) running on a Nexus 6p 8.1.

Following up on the undesired lock-screen behavior, I've added the following to my initialization:
this.onPauseSubscription = this.platform.pause.subscribe(() => {    this.backgroundmode.moveToBackground(); });
and added this to my cleanup:
this.onPauseSubscription.unsubscribe();

@mpfurnari , thanks so much for posting your fix. I have just implemented it in our test env and it appears to be working! This if the first time we've been able to get our app to last past 5 min since this error started happening with Android devices. I am going to test overnight and let you all know how it goes. I'm encouraged so far.

@aminholmes Hey Amin, Glad to hear that it's working for you! Matt

I was running on android P on oneplus 6. I have enabled the notification and it is being displayed on android 6.0 devices but not on P.

Hey Everyone,
I think this fork is working better.
https://github.com/tushe/cordova-plugin-background-mode
Finally I was able to make it work for longer time.

I was running on android P on oneplus 6. I have enabled the notification and it is being displayed on android 6.0 devices but not on P.

I believe the tushe fork provided by @iverveinc  corrects the notification issue. Still, with this fork, I was unable to run for long on a Samsung S9+ Android 8.0 with only the backgroundmode plugin. Failing that on tushe's fork, I tried the wake-lock solution with katzer's version of backgroundmode and I was able to run.
If someone can confirm that they are getting tushe's fork to work on a Samsung S9, I'll dig deeper...

@mpfurnari Hey, Would like to hear more about wake-lock solution in  bit detail. I read above thread but not sure how to implement it. Can you help me with it.

@mpfurnari Noticing similar behaviour with Android 8.* on OnePlus 5T, Huawei and Sony models. I have implemented the wake-lock workaround, but still seeing the same type of behaviour (5 mins of background work). Going to spend some time today ensuring I have implemented the fix correctly, will update if I get anywhere.

Using tushe's backgroundmode to fix notifications, combined with the partial wake-lock solution with the powermanagement plugin, and setting cordova.plugins.backgroundMode.disableWebViewOptimizations(); seems to really work great for my scenario, where networking needs to keep working.
@mpfurnari  I was wondering what problems you were having regarding the when the phone is locked, as I have not seen any problems with a Samsung Galaxy s8. I am also using a websocket that must stay open.

@mpfurnari I was wondering what problems you were having regarding when the phone is locked, which prompted you to force the application to the background, as I have not seen any problems with a Samsung Galaxy s8. I am also using a websocket that must stay open.

@Danthemanwenttojapan The phone screen would stay on, and the app would be in focus even though the screen was "locked". Forcing the app to the background eliminated this problem.

@Danthemanwenttojapan I spent 3-4 days trying different solutions including the disableWebViewOptimizations() and still couldn't get it working correctly. Android 8 seems to be very aggressive towards background processes even when writing natively. I have moved on to writing a native app that will run the "always on" background tasks I need and use my angular 6 as a front end embedded in a webview using cordova. Like I said, Android 8 is very agressive and I think this is the best solution in my case. Moving forward using another cross-platform angular to mobile framework might be better, one which allows easier access to native APIs and doesn't use webviews.

@mpfurnari That's interesting, I'm not getting the same phenomena with with a Cordova implementation (Not ionic), with Android 8, galaxy s8. I used all the solutions including backgroundMode.disableWebViewOptimizations();

@gerard-d-kelly It's working for me with all the solutions here together on a Android 8 with galaxy s8 (I must maintain a websocket). The plugin (I didn't look too carefully at the code), creates a foreground (or background) service, which should work.

i need keep open a websocket connection on background

Is this work-around to keep the App alive in background?

@gerard-d-kelly It's working for me with all the solutions here together on a Android 8 with galaxy s8 (I must maintain a websocket). The plugin (I didn't look too carefully at the code), creates a foreground (or background) service, which should work. I don't have access to all the phones you mentioned, so was wondering if some Android implementation pauses foreground services. Try disabling doze mode for your app (Under battery management), and let me know what happened (If that is ok). I don't think this should be necessary for a foreground service.

I have done this still App got close.

Did anyone tried this solution https://github.com/Red-Folder/bgs-core/wiki/Build-your-own-Background-Service

In silent mode the plugin will not display a notification - which is not the default. Be aware that Android recommends adding a notification otherwise the OS may pause the app.
cordova.plugins.backgroundMode.setDefaults({ silent: true });

decided to develop the service in native code as I have come to the conclusion the plugins for such type of requirement will not work.  The App will close period, background service is something need, s to be out proc and not in-proc, the plugins here I guess works as in-proc and when the App closes the service will close bhoom over :( more here

Try below, solved the crashing issue for me on Android 8+
https://github.com/katzer/cordova-plugin-background-mode/issues/393#issuecomment-449635095
Tested working on 8.0 on device, while 8.1 & 9.0 on emulator.

Hey Everyone,
I think this fork is working better.
https://github.com/tushe/cordova-plugin-background-mode
Finally I was able to make it work for longer time.

Work on<EMAIL_ADDRESS>thx...

@devi255
It doesn't work for me. still stop in 5 minutes.
thx

@n1705771 are you sure that you are using the latest git version of the plugin?

Working for Oreo & Pie.
Little tips for OnePlus users, you have to "lock" the app (the padlock in top right on app switcher)

Use this to keep app running when phone goes into (Android 6+) doze/standby mode.
https://github.com/thomas550i/cordova-plugin-doze-Optimize/

@ziyaddin Thanks. Do you mean latest "katzer" version or "tushe" version?

Working for Oreo & Pie.
Little tips for OnePlus users, you have to "lock" the app (the padlock in top right on app switcher)

Locking the app isn't a good solution for most users...

Hey Everyone,
I think this fork is working better.
https://github.com/tushe/cordova-plugin-background-mode
Finally I was able to make it work for longer time.

Work on<EMAIL_ADDRESS>thx...

What version of Android did you test with? I ran a test with tushe's merged in changes and still had issues with the communications stopping after a few minutes. The app still runs in the background, but comms are stopped. I had to go back to using the wakelock to keep comms up. I guess I should update the original issue with this bit of information...

@mpfurnari Hey, Would like to hear more about wake-lock solution in bit detail. I read above thread but not sure how to implement it. Can you help me with it.

I implemented this as an ionic provider. I've attempted to clean up my code for general use below, but I haven't verified this version. My version is very similar...
`
import { Injectable } from '@angular/core';
import { BackgroundMode } from '@ionic-native/background-mode';
import { Platform } from 'ionic-angular';
import { PowerManagement } from '@ionic-native/power-management';
@Injectable()
export class backgroundProvider {
static backgroundMode;
static isAndroid;
static powerManagement;
static platform;
static onPauseSubscription;

constructor(public _backgroundMode: BackgroundMode,
    public _platform: Platform,
    public _powerManagement: PowerManagement) {
    backgroundProvider.backgroundMode = _backgroundMode;
    backgroundProvider.platform = _platform
    backgroundProvider.isAndroid = (backgroundProvider.platform.is('android'));
    backgroundProvider.powerManagement = _powerManagement;
    backgroundProvider.onPauseSubscription = undefined;
}

static paused() {
    // push us to the background in this case so that we're not driving the screen...
    backgroundProvider.backgroundMode.moveToBackground();
}

static enableBackground(forceBackgroundOnPause) {

    console.log("Enabling Background Mode");
    // https://forum.ionicframework.com/t/i-found-a-solution-for-some-regular-background-activity/27012

    backgroundProvider.backgroundMode.setDefaults({
        title: "My App Name",
        text: "Working for you in the background",
        icon: 'res://bgicon.png',
        hidden: true
    });
    if (backgroundProvider.isAndroid) {
        backgroundProvider.backgroundMode.enable();
        if (forceBackgroundOnPause) {
            backgroundProvider.onPauseSubscription = this.backgroundMode.platform.pause.subscribe(() => {
                console.log('paused')
                backgroundProvider.paused(); // when we pause, some apps are better left in the background so as to not keep the screen lit..
            });
        } else {
            backgroundProvider.onPauseSubscription = undefined;
        }

        backgroundProvider.powerManagement.dim(function () {
            console.log('enablebackground: Wakelock acquired');
            backgroundProvider.powerManagement.setReleaseOnPause(false, function () {
                console.log('enablebackground: setReleaseOnPause success');
            }, function () {
                console.log('enablebackground: setReleaseOnPause Failed to set');
            });
        }, function () {
            console.log('enablebackground: Failed to acquire wakelock');
        });
    } else {
        backgroundProvider.backgroundMode.enable();
    }
}

static disableBackground() {
    console.log("Disabling Background Mode");
    if (backgroundProvider.isAndroid) {
        if (backgroundProvider.onPauseSubscription != undefined) {
            this.backgroundMode.onPauseSubscription.unsubscribe();
        }
        this.backgroundMode.bgmode.disable();
        this.backgroundMode.powerManagement.release(function () {
            console.log('disableBackground: Wakelock released');
        }, function () {
            console.log('disableBackground: Failed to release wakelock');
        });
    } else {
        backgroundProvider.backgroundMode.disable();
    }
}

}
`

I'm still on this solution...

@mpfurnari Does wakelock help background mode works longer time in your case. I added power management's wakelock in my app too, but it doesn't help.

@ziyaddin Thanks. Do you mean latest "katzer" version or "tushe" version?

@n1705771 I mean latest "katzer" version.

I installed katzer version is: @ionic-native/background-mode": "^4.20.0"

You have installed the ionic wrapper for cordova plugin. You need to install the latest "katzer" version of cordova plugin itself by this command:
ionic cordova plugin add https://github.com/katzer/cordova-plugin-background-mode.git

@mpfurnari Does wakelock help background mode works longer time in your case? I added power management's wakelock in my app too, but it doesn't help.

I've found I have to use the wakelock to keep background communications going. I had tried a no-doze solution to get around issues caused by Android's doze feature (which seems to be the root of the communications stoppage), but those are a pain to manage from a user's perspective. From what I've tried, there's no easy way to turn off doze (ie disable battery optimization) without giving the user some complicated and device-specific instructions.  The wakelock solution is far from elegant, but it works for my app without additional burden on my users. I'm not an authority on all this... I'm just a developer trying to keep my app working for my customers...

@mpfurnari Thanks, I did the same thing in my ionic app, but it doesn't work well. My code is lie:
`if (this.platform.is('android')){
this.backgroundMode.enable();
  this.powerManagement.dim().then((value)=>{
        console.log('enablebackground: Wakelock acquired');
        this.powerManagement.setReleaseOnPause(false).then(()=>{
            console.log('enablebackground: setReleaseOnPause success');
        }).catch(()=>{
            console.log('enablebackground: setReleaseOnPause Failed to set');
        });
    }).catch(()=>{
      console.log('enablebackground: Failed to acquire wakelock');
    });

  this.backgroundMode.on("activate").subscribe(()=>{
    this.backgroundMode.disableWebViewOptimizations();
    console.log("background activate !!!!");

  });
  this.backgroundMode.on("deactivate").subscribe(()=>{
    console.log("background deactivate xxxx ");
    this.locationtracker.stopTracking();
    setTimeout(()=>{
      this.locationtracker.startTracking();
    }, 500);
  });
} else {
  this.backgroundMode.enable();
}
...

}`

It only works if device is plugged in power cable. I don't know why this happens...

It only works if device is plugged in power cable. I don't know why this happens...

It's working for me based on my comments on battery with no stoppage on Android 8.0 and 9.0

Possible fix some of you: https://github.com/katzer/cordova-plugin-background-mode/pull/435

@boedy I have changed the plugin.xml according to your commits, but it doesn't work for me. Is there any other code I need to modified?

No that should be it. To check if you did everything right, the configuration changes should also be added to the AndroidManifest in your android platform folder.

@boedy Thanks. Is there a plugin.xml file also in platforms/android?

I used kazer & tush fork, with and without powerManager and the best result that i got,
is like @n1705771  said, it works only when the device is plugged in power cable.
android 8

I used kazer & tush fork, with and without powerManager and the best result that i got,
is like @n1705771 said, it works only when the device is plugged in power cable.
android 8

I found I had to use this power management plugin: at.gofg.sportscomputer.powermanagement.

@mpfurnari Yes with it ,
and still not works,
"dependencies": {
    "@angular/common": "^7.2.11",
    "@angular/core": "^7.2.11",
    "@angular/forms": "^7.2.11",
    "@angular/http": "^7.2.11",
    "@angular/platform-browser": "^7.2.11",
    "@angular/platform-browser-dynamic": "^7.2.11",
    "@angular/router": "^7.2.11",
    "@ionic-native/background-mode": "^5.3.0",
    "@ionic-native/core": "^5.3.0",
    "@ionic-native/native-audio": "^5.3.0",
    "@ionic-native/native-storage": "^5.3.0",
    "@ionic-native/power-management": "^5.3.0",
    "@ionic-native/splash-screen": "^5.3.0",
    "@ionic-native/status-bar": "^5.3.0",
    "@ionic/angular": "^4.1.2",
    "cordova-android": "^7.1.4",
    "cordova-plugin-background-mode": "^0.7.2",
    "cordova-plugin-device": "^2.0.2",
    "cordova-plugin-ionic-keyboard": "^2.1.3",
    "cordova-plugin-ionic-webview": "^4.0.1",
    "cordova-plugin-nativeaudio": "git+https://github.com/TheMoroccan09/cordova-plugin-nativeaudio.git",
    "cordova-plugin-nativestorage": "^2.3.2",
    "cordova-plugin-powermanagement-orig": "git+https://github.com/boltex/cordova-plugin-powermanagement.git",
    "cordova-plugin-splashscreen": "^5.0.2",
    "cordova-plugin-statusbar": "^2.4.2",
    "cordova-plugin-whitelist": "^1.3.3",
    "core-js": "^2.5.4",
    "ng-circle-progress": "^1.4.0",
    "rxjs": "~6.3.3",
    "zone.js": "~0.8.29",
    "at.gofg.sportscomputer.powermanagement": "https://github.com/boltex/cordova-plugin-powermanagement.git"
  }

it works for you ?!!

import { PowerManagement } from '@ionic-native/power-management';
Thank you @mpfurnari for your explanations :-)

I just installed this
cordova plugin add https://github.com/boltex/cordova-plugin-powermanagement.git
Do I have also to install the normal @ionic-native/power-managemen?
Or should I change the above import for something different ?
Thanks in advance

@Entrecampos  not yet

@TheMoroccan09 It is working now in my Xiaomi 7.1.1 and not working in my cliente Galaxy S10+ 9
You can check the solutions for your mobile clicking in the corresponding icon here https://dontkillmyapp.com

Working on emulator Galaxy  9
with
 https://github.com/irceline/aq-mobile-be/issues/94#issuecomment-464293865

@Entrecampos
Thanks. for my Huawei Mate 10, I installed the latest plugin and added function:
  this.backgroundMode.disableBatteryOptimizations();

After turning off the power save mode in battery setting, it start works.

@Entrecampos I am curious if there is a way can automatically set the power save mode off when once the application is opened?

@n1705771
When I installed this https://github.com/lkonzen-garupa/cordova-plugin-background-mode
ask user permission to use battery in background.
https://github.com/katzer/cordova-plugin-background-mode/issues/430#issuecomment-484074971
ut sometimes works more than 4 minutes, sometimes doesn't still testing

@n1705771
When I installed
https://github.com/katzer/cordova-plugin-background-mode/issues/430#issuecomment-484074971

@Entrecampos and @mpfurnari, thanks guys for your investigation and sharing your solution.
Just wondering:
Is the disableBatteryOptimizations() and REQUEST_IGNORE_BATTERY_OPTIMIZATION permissions sufficient to solve the problem?
Or BackgroundMode still needs to be used with the PowerManagement code to make a viable solution?

Hi @8bhsolutions
I tried without disableBatteryOptimizations() and work only for 4 minutes.
I tried without background mode and did not work at all.
As soon as I changed to another app stoped working

Hi @Entrecampos,
What I meant was whether you have tried to run test without PowerManagement code.
ie: Just using disableBatteryOptimizations and REQUEST_IGNORE_BATTERY_OPTIMIZATION permissions.

I tried without this code and only work for 4 minutes
public dimPM() {
    this.powerManagement.dim().then((value) => {
      console.log('enablebackground: Wakelock acquired');
      this.powerManagement.setReleaseOnPause(false).then(() => {
        console.log('enablebackground: setReleaseOnPause success');
      }).catch(() => {
        console.log('enablebackground: setReleaseOnPause Failed to set');
      });
    }).catch(() => {
      console.log('enablebackground: Failed to acquire wakelock');
    });

    cordova.plugins.backgroundMode.on('activate').subscribe(() => {
      cordova.plugins.backgroundMode.disableWebViewOptimizations();
      console.log('background activate !!!!');

    });
    cordova.plugins.backgroundMode.on('deactivate').subscribe(() => {
      console.log('background deactivate xxxx ');
    });

  }

Oh damn. I was hoping for solution with the need for another plugin.
Thanks @Entrecampos

Totally agree!!!!
I really would love to see something better and hope that google store accept it.

On 6 May 2019, at 17:21, 8bhsolutions<EMAIL_ADDRESS>wrote:
Oh damn. I was hoping for solution with the need for another plugin.
Thanks @Entrecampos https://github.com/Entrecampos
—

I have the same problem with audio streaming

I've seen this:
https://altbeacon.github.io/android-beacon-library/foreground-service.html
so Android versions 8+ restrict services from running in the background to only 10 minutes after an app leaves the foreground.
... so the alternative is to use a foreground service:
A foreground service is differs from regular Android background services in that it shows a persistent notification showing your app icon and configurable text.
... I'm looking for a Cordova Plugin that manage the foreground service if Android 8+ or background service if Android < 8.

What I meant was whether you have tried to run test without PowerManagement code.
ie: Just using disableBatteryOptimizations and REQUEST_IGNORE_BATTERY_OPTIMIZATION permissions.

Sorry @8bhsolutions for the misleading information.
After adding
cordova.plugins.backgroundMode.disableBatteryOptimizations();
It is not necessary anymore this
 if (this.plt.is('android')) { this.dimPM(); }// <- HERE
Fo now is running more than 13 minutes. ... Let's see .. for today ...
So maybe is not necessary the powerManagement plugin.
I didn't uninstall it yet ...

Great @Entrecampos. Let us know your results, and what device you tested it on.
I tested it with Samsung S9+ (on Android 9), and it did not seem to work without the PowerManagement plugin. Not sure whether is it is a bug, the code cordova.plugins.backgroundMode.disableBatteryOptimizations(); does not actually disable battery optimisation on the S9+.
If your result is successful, it would be worthwhile for me to test again and if anyone else can also test on S9+ to verify my results.

Great @Entrecampos. Let us know your results, and what device you tested it on.
I tested it with Samsung S9+ (on Android 9), and it did not seem to work without the PowerManagement plugin. Not sure whether is it is a bug, the code cordova.plugins.backgroundMode.disableBatteryOptimizations(); does not actually disable battery optimisation on the S9+.
If your result is successful, it would be worthwhile for me to test again and if anyone else can also test on S9+ to verify my results.

I have android 7.1.1 Mi Max 2.
My Client has Samsung Galaxy S10+.
With him the problem was that was crashing the app as soon as he went to background. But this  https://github.com/lkonzen-garupa/cordova-plugin-background-mode solve it ...
I will ask him to test and let you know.

Seems to be broken on S9+ again.
My app seems to run on average 6-8 hours, on a few occasions I have seen the log of over 20 hours. But it will always get killed.
Even with the PowerManagement plugin, and manually disabled battery optimisation, and calling disableBatteryOptimizations + disableWebViewOptimizations.
I've added more code and plugins to my app, so it has gotten a lot more complex.
@Entrecampos @mpfurnari and anyone else experiencing same issue?

Seems to be broken on S9+ again.
My app seems to run on average 6-8 hours, on a few occasions I have seen the log of over 20 hours. But it will always get killed.
Even with the PowerManagement plugin, and manually disabled battery optimisation, and calling disableBatteryOptimizations + disableWebViewOptimizations.
I've added more code and plugins to my app, so it has gotten a lot more complex.
@Entrecampos @mpfurnari and anyone else experiencing same issue?

Did you activated "sticky" mode (ongoing) on localnotification plugin ?

@JuneTwooo Can you elaborate?
The notification from the background mode plugin is shown. The user can't swipe it away.
When the app dies, the notification is also gone.

@JuneTwooo Can you elaborate?
The notification from the background mode plugin is shown. The user can't swipe it away.
When the app dies, the notification is also gone.

Since Android 8, you have to use a persistent foreground notification. You can set it with https://github.com/katzer/cordova-plugin-local-notifications (with sticky: true) like that :
cordova.plugins.notification.local.schedule(
{
	title: 'my app',
	text: 'my text',
	icon: 'file://icon.png',
	smallIcon: 'res://icon.png',
	sticky: true,
	foreground: true
});

My app run till few week with that

Thanks @JuneTwooo
That's interesting info.
I don't use the local notification plugin.
I'll give it a go to see if it can keep my app alive.

@JuneTwooo .
So do you have background mode plugin notification showing ie: silent: false
and also show another notification from local notification plugin?

@JuneTwooo .
Can you clarify you setup to have you app run in the background?
Do you have background mode plugin notification showing ie: silent: false?
Do you have PowerManagement plugin as well?
And do you show another notification from local notification plugin?

I only use  background mode plugin (with silent:false) and local notification plugin (sticky: true)

Thanks.
Would that result in showing 2 notifications?

Thanks.
Would that result in showing 2 notifications?

Yes, but maybe you can set silence:true on background mode plugin, i have not tested that.
Another thing, i have spent a lot of time before i know of the foreground service too keep app runing in background, i use a forked plugin for background mode : https://bitbucket.org/TheBosZ/cordova-plugin-run-in-background/src

Thanks for the clarification.
I'll try with the forked plugin instead.

@JuneTwooo
Unfortunately, that didn't work for me. My app is still getting killed on the Samsung S9+
The pattern seems to be that the app is killed 7 hours after last interaction.
I have also created a new starter app, and added TheBosZ for + local notification. It follows the same pattern.
Maybe it is a new update on Samsung S9+?
Can I ask what is the Android version and device you are able to run for weeks?

@JuneTwooo
Unfortunately, that didn't work for me. My app is still getting killed on the Samsung S9+
The pattern seems to be that the app is killed 7 hours after last interaction.
I have also created a new starter app, and added TheBosZ for + local notification. It follows the same pattern.
Maybe it is a new update on Samsung S9+?
Can I ask what is the Android version and device you are able to run for weeks?

My app use websocket to stay connected from a server, i use 4 devices : 1 galaxy A5 2017 (oreo), OnePlus 5 (pie), a box tv android (x96 mini, nougat) and tablet galaxy tab S2 (oreo)

hmm.
I have a firebase connection in background as well. I assume that is a websocket as well.
Maybe it's just a Samsung S9 thing.
S6 on Android 7 has no problems with old code. Have been running for 4 days.

I can't get my app running after 7-9 mins with background geolocation updating via firebase on Android 8+ any one have an idea why is it so?
my app.component.ts
backgroundService() {
this.platform.ready().then(() => {

  cordova.plugins.backgroundMode.enable();
  cordova.plugins.backgroundMode.setDefaults({ silent: true });
  cordova.plugins.backgroundMode.overrideBackButton();

  this.powerManagement.acquire()
    .then(res => {
      console.log('Wakelock aquire')
    })
    .catch(res => console.log('Error Wakelock acquired'));

  this.powerManagement.setReleaseOnPause(false).then(
    res => console.log('setReleaseOnPause successfully'),
    () => {
      console.log('Failed to set');
    }
  );
  this.platform.pause.subscribe(() => { cordova.plugins.backgroundMode.moveToBackground(); });
  // 2) Now the app runs ins background but stays awake
  cordova.plugins.backgroundMode.on('activate', () => {

    cordova.plugins.backgroundMode.disableWebViewOptimizations();
    cordova.plugins.backgroundMode.disableBatteryOptimizations();

    //setInterval(() => {
    var dt = new Date();
    if (this.platform.is('android')) { this.dimPM(); }

    if (dt.getHours() >= 9 && dt.getHours() < 24) {
      if (localStorage.getItem("IsLoggedIn") == "true") {
        this.LocationtrackerService.startBackgroundGeolocation()

      }
    }
    else {
      this.LocationtrackerService.stopTracking();
    }

  });

  // 3) App is back to foreground
  cordova.plugins.backgroundMode.on('deactivate', () => {
    if (localStorage.getItem("IsLoggedIn") == "true") {
      this.LocationtrackerService.stopTracking();
    }

}
dimPM() {
if (this.powerManagement) {
console.log('powerManagement');
this.powerManagement.release().then(() => {
this.powerManagement.dim().then((v) => {
console.log('enablebackground: Wakelock acquired');
this.powerManagement.setReleaseOnPause(false).then(() => {
console.log('enablebackground: setReleaseOnPause success');
}).catch(() => {
console.log('enablebackground: setReleaseOnPause Failed to set');
});
}).catch((err) => {
console.log('enablebackground: Failed to acquire wakelock:', err);
});
});
}
}
my provider tracker.ts
startBackgroundGeolocation() {
this.backgroundGeolocation.configure({
  desiredAccuracy: 10,
  stationaryRadius: 5,
  distanceFilter: 0,
  // timeout: 20000,
  startForeground: true,
  locationProvider: 1,
  interval: (120 * 1000), //2mins in millis
  fastestInterval: (60 * 1000), // 1min in millis

  //fastestInterval: 5000,
  //activitiesInterval: 10000,
  //saveBatteryOnBackground:false,
  //enableHighAccuracy: true,
  //debug: false,   enable this hear sounds for background-geolocation life-cycle.
  //stopOnTerminate: false // enable this to clear background location settings when the app terminates
})
var i = 0;

this.backgroundGeolocation.on('location', (location) => {
  if (localStorage.getItem("IsLoggedIn") == "true") {
    console.log('Background Watch');
    this.zone.run(() => {
      this.sendGPS(location);
    });
    i++
  }
  else {
    console.log('Please Log in')
  }
}, (err) => {
  window.alert(err);
})

this.backgroundGeolocation.start();

let options = {
  frequency: 3000,
  enableHighAccuracy: true
};
setInterval(() => {
  this.watch = this.geolocation.watchPosition();
  this.subscription = this.watch.subscribe((data) => {
    console.log('Foreground Watch');
    this.sendGPS(data.coords);
  });
}, 100000);

}
stopTracking() {
this.backgroundGeolocation.stop();
let subscription = this.geolocation.watchPosition().subscribe(
(position) => { },
);
subscription.unsubscribe();
}
sendGPS(location) {
//using firebase to push the data
}

Try silent: false
You can't have silent foreground services.

Try silent: false
You can't have silent foreground services.

ok i will try n give it a go do u have any working solution of this?

no. My problem still exists on Samsung s9+.
No one else has replied, so I guess either no one else has tested in on S9+ or others are not experiencing my issue on S9+.
Either case, I am hoping it is because of codebase dependencies.
I am investigating my codebase to see if there are any conflicts, special cases with wake locks, support library versions, etc.

oh seems i am facing this problem in all devices above 8+

I've seen this:
https://altbeacon.github.io/android-beacon-library/foreground-service.html
so Android versions 8+ restrict services from running in the background to only 10 minutes after an app leaves the foreground.
... so the alternative is to use a foreground service:
A foreground service is differs from regular Android background services in that it shows a persistent notification showing your app icon and configurable text.
... I'm looking for a Cordova Plugin that manage the foreground service if Android 8+ or background service if Android < 8.

Did you found something @dariocavada ?

I've seen this:
https://altbeacon.github.io/android-beacon-library/foreground-service.html
so Android versions 8+ restrict services from running in the background to only 10 minutes after an app leaves the foreground.
... so the alternative is to use a foreground service:
A foreground service is differs from regular Android background services in that it shows a persistent notification showing your app icon and configurable text.
... I'm looking for a Cordova Plugin that manage the foreground service if Android 8+ or background service if Android < 8.

Did you found something @dariocavada ?

https://github.com/katzer/cordova-plugin-local-notifications (with sticky: true) like that :
cordova.plugins.notification.local.schedule(
{
title: 'my app',
text: 'my text',
icon: 'file://icon.png',
smallIcon: 'res://icon.png',
sticky: true,
foreground: true
});

i somehow managed to get it working by installing insomnia plugin my app now runs over 10+ mins on 8+

Thanks @JuneTwooo
Do you prefer

https://github.com/katzer/cordova-plugin-local-notifications

or

https://bitbucket.org/TheBosZ/cordova-plugin-run-in-background/src

?

Thanks @JuneTwooo
Do you prefer

https://github.com/katzer/cordova-plugin-local-notifications

or

https://bitbucket.org/TheBosZ/cordova-plugin-run-in-background/src

?

You have tu use both if you want to execute background javascript code

Sorry   😐 I wanted to ask:
https://github.com/katzer/cordova-plugin-background-mode
or
https://bitbucket.org/TheBosZ/cordova-plugin-run-in-background/src

Any one preferably second one
On Wed, 11 Sep 2019 at 7:23 PM, Ines Gomes<EMAIL_ADDRESS>wrote:

Sorry 😐 I wanted to ask:
https://github.com/katzer/cordova-plugin-background-mode
or
https://bitbucket.org/TheBosZ/cordova-plugin-run-in-background/src
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/katzer/cordova-plugin-background-mode/issues/400?email_source=notifications&email_token=AD4LOMOQAYNPHEEM55ZC4YDQJDZ6DA5CNFSM4FVGXMH2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD6OR7QA#issuecomment-530390976,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AD4LOMNK6MIHT7JKW5INCELQJDZ6DANCNFSM4FVGXMHQ
.

/TheBosZ/cordova-plugin-run-in-background/src

Currently i use TheBosZ one

Thanks a lot @JuneTwooo, @nadimnakade Is working great :-)
and spending much less battery and less plugins.
( with the power Management plugin was more battery consuming .)
I don't send the local notification, I set the sticky in the default options and working !!!
:-)
I set id=-1 because I am also sending some normal notifications not sticky
with id>=0 and would replace this sticky one
 const options = {
      id: -1,
      title: 'Nursecall Messaging Service',
      text: 'Running in Background Mode',
      hidden: false,
      silent: false,
      sticky: true,
      resume: false,
      foreground: true,
    };

    await cordova.plugins.backgroundMode.disableBatteryOptimizations();
    await cordova.plugins.backgroundMode.setDefaults(options);
    await cordova.plugins.backgroundMode.enable();

    cordova.plugins.backgroundMode.on('activate', () => {
      cordova.plugins.backgroundMode.disableWebViewOptimizations();
      console.log('background mode activate !!!');
    });

osum! great it worked :)
On Sat, Sep 14, 2019 at 1:25 PM Ines Gomes<EMAIL_ADDRESS>wrote:

Thanks a lot @JuneTwooo https://github.com/JuneTwooo, @nadimnakade
https://github.com/nadimnakade Is working great :-)
and spending much less battery and less plugins.
( with the power Management plugin was more battery consuming .)
I don't send the local notification, I set the sticky in the default
options and working !!!
:-)
I set id=-1 because I am also sending some normal notifications not sticky
with id>=0 and would replace this sticky one
const options = {
id: -1,
title: 'Nursecall Messaging Service',
text: 'Running in Background Mode',
hidden: false,
silent: false,
sticky: true,
resume: false,
foreground: true,
};
await cordova.plugins.backgroundMode.disableBatteryOptimizations();
await cordova.plugins.backgroundMode.setDefaults(options);
await cordova.plugins.backgroundMode.enable();

cordova.plugins.backgroundMode.on('activate', () => {
  cordova.plugins.backgroundMode.disableWebViewOptimizations();
  console.log('background mode activate !!!');
});

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/katzer/cordova-plugin-background-mode/issues/400?email_source=notifications&email_token=AD4LOMIO7EK3PN334TT3CTDQJSKF5A5CNFSM4FVGXMH2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD6WW2UI#issuecomment-531459409,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AD4LOMPDEZ2BVBMYPP6BHKDQJSKF5ANCNFSM4FVGXMHQ
.

Thanks. Background mode works well! I have another problem. In battery setting, If I set the application to be automatically launched, it will be very frequently automatically closed by my phone.  Even through I set the application to be manual launched, it is still automatically closed by my phone, not frequently, after running 10 hours maybe... I think this problem is related with background plugin. Does any one have the same issue?

@MInesGomes : i tried ur code its working but in my case watchPosition is not fire in background tell me what i do?

@MInesGomes : i tried ur code its working but in my case watchPosition is not fire in background tell me what i do?

Use this plugin: https://github.com/mauron85/cordova-plugin-background-geolocation
works very good.

@kapilSoni101 Is the "sticky " notification appearing ?
If not, you can try launch a notification to see if the local notification plugin is well installed?
  this.localNot.schedule(
      {
        id: -1,
        title: 'Nursecall Messaging Service',
        text: 'Running in Background Mode',
        sticky: true,
        foreground: true
      });

@MInesGomes:- thany for ur feedback I will use use notification plugin for if app is in background.
Do you know how to move map via user position currently marker is moved but I am also need to move to camera position via user position.
It possible for u to share the socket code?

@kapilSoni101 :-)
The socket code is to implement a chat, not geolocation.
So maybe @Taxi4you suggestion for this plugin https://github.com/mauron85/cordova-plugin-background-geolocation is a good idea? In future I will need to use also geolocation, but for now I don't have experience. Maybe then I wil ask you :-)

@MInesGomes:-

@MInesGomes:- I have already try backgroundGeolocation plugin but function is not fire if I am in background.
Then I already used watchPosition function but not worked in the Android 8 and 9 device I don't understand why?

Update for my issue, just info/reference for others that might find it useful.
I identified my issue was to due to updates to Chrome WebView and Play Services.
When Android/Google Play updates packages, all dependent apps are killed regardless of app process status.

@mpfurnari : Mam i tried above code and its working only in Oppo F1 pro devices but in Samsung,MI,Nokia app is crashed after login i got below error  in log:

Can u tell me how to fix above error?

@MInesGomes:- I have already try backgroundGeolocation plugin but function is not fire if I am in background.
Then I already used watchPosition function but not worked in the Android 8 and 9 device I don't understand why?

You can see why here: https://altbeacon.github.io/android-beacon-library/foreground-service.html

@MInesGomes - I have follow above link and issue is resolved but watch' position function not fire in background again ?

@kapilSoni101 I started now implementing geolocation and have the same problem. I was thinking in trying this plugin https://github.com/mauron85/cordova-plugin-background-geolocation. did you tried it?

@MInesGomes - yes I have tried above plugin but it's not working function is not fire.i am not understand what I do now for fire function in background?

@kapilSoni101 I think I found the solution you need to give ACCESS_BACKGROUND_LOCATION permission
In the file plugins/cordova-plugin-geolocation/plugin.xml you need to add:
       ` <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />`

See more here: https://developer.android.com/training/location/background

@MInesGomes - thanks for above Solution can you tell watch Position function is fire after set above line?

@kapilSoni101 yes

@MInesGomes - I have tried ur solution but again it's not working for me again after add above file

@MInesGomes In my application audio play perfectly but screen is off after 2-3 mint audio is pause then wake up the screen is work again this issue is Samsung s9,s10 android pie. I have install both plugin BackgroundMode and PowerManagement but issue not solve.
`constructor(private platform: Platform,
public apiService: ApiService,
public loadingController: LoadingController,
private musicControls: MusicControls,
private backgroundMode: BackgroundMode,
private powerManagement: PowerManagement) {
  if (this.platform.is('android')){
    this.backgroundMode.enable();

    this.powerManagement.dim().then((value)=>{
          console.log('enablebackground: Wakelock acquired');
          this.powerManagement.setReleaseOnPause(false).then(()=>{
              console.log('enablebackground: setReleaseOnPause success');
          }).catch(()=>{
              console.log('enablebackground: setReleaseOnPause Failed to set');
          });
      }).catch(()=>{
        console.log('enablebackground: Failed to acquire wakelock');
      });

    this.backgroundMode.on("activate").subscribe(()=>{
      this.backgroundMode.disableWebViewOptimizations();
      this.backgroundMode.disableBatteryOptimizations();
      console.log("background activate !!!!");

    });
    this.backgroundMode.on("deactivate").subscribe(()=>{
      console.log("background deactivate xxxx ");
    });
  } else {
    this.backgroundMode.enable();
  }

}`

Thanks a lot @JuneTwooo, @nadimnakade Is working great :-)
and spending much less battery and less plugins.
( with the power Management plugin was more battery consuming .)
I don't send the local notification, I set the sticky in the default options and working !!!
:-)
I set id=-1 because I am also sending some normal notifications not sticky
with id>=0 and would replace this sticky one
 const options = {
      id: -1,
      title: 'My App',
      text: 'Running in Background Mode',
      hidden: false,
      silent: false,
      sticky: true,
      resume: false,
      foreground: true,
    };

    await cordova.plugins.backgroundMode.setDefaults(options);
    await cordova.plugins.backgroundMode.enable();

    cordova.plugins.backgroundMode.on('activate', () => {
      cordova.plugins.backgroundMode.disableWebViewOptimizations();
      console.log('background mode activate !!!');
    });

Can you please tell me which Ionic version are you using?
I am facing issue with this.. I am using Ionic 3.
I have testing this plugin in Ionic 5 and it is working smooth.
Does ionic 3 supports this plugin? If Yes then please let me know.

I have used this on Ionic 3 app
On Tue, 26 May 2020 at 1:22 PM, shrekL<EMAIL_ADDRESS>wrote:

Thanks a lot @JuneTwooo https://github.com/JuneTwooo, @nadimnakade
https://github.com/nadimnakade Is working great :-)
and spending much less battery and less plugins.
( with the power Management plugin was more battery consuming .)
I don't send the local notification, I set the sticky in the default
options and working !!!
:-)
I set id=-1 because I am also sending some normal notifications not sticky
with id>=0 and would replace this sticky one
const options = {
id: -1,
title: 'My App',
text: 'Running in Background Mode',
hidden: false,
silent: false,
sticky: true,
resume: false,
foreground: true,
};
await cordova.plugins.backgroundMode.setDefaults(options);
await cordova.plugins.backgroundMode.enable();

cordova.plugins.backgroundMode.on('activate', () => {
  cordova.plugins.backgroundMode.disableWebViewOptimizations();
  console.log('background mode activate !!!');
});

Can you please tell me which Ionic version are you using?
I am facing issue with this.. I am using Ionic 3.
I have testing this plugin in Ionic 5 and it is working smooth.
Does ionic 3 supports this plugin? If Yes then please let me know.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/katzer/cordova-plugin-background-mode/issues/400#issuecomment-633868663,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/AD4LOMOWKGWOVLFFJXIWKUDRTNYNPANCNFSM4FVGXMHQ
.

Helpful codes here

APP NAME keeps stopping when background mode is active. APP crashes.

Olá @nadimnakade. É posível mostrar seu código?
Estou pegando a geolocalização em foreground e background mas não está funcionando.

Hello @nadimnakade. Is it possible to show your code?
I'm getting the geolocation in foreground and background but it isn't working.

Use this plugin and solved all problem =>
https://bitbucket.org/TheBosZ/cordova-plugin-run-in-background/src/master/


proposal: Change server port from 3000 -> 8080

What?
Proposing to change the server port from 3000 -> 8080 as frontend dev servers typically run on 3000 and are more likely to collide.
Why?
Had a local version of Plural FE running and ran into the following error since that app was already using port 3000.
Error: listen EADDRINUSE: address already in use :::3000
    at Server.setupListenHandle [as _listen2] (node:net:1380:16)
    at listenInCluster (node:net:1428:12)
    at Server.listen (node:net:1516:7)
    at Function.listen (/Users/alexfong/Documents/plural-energy/tap-cap-table/node_modules/express/lib/application.js:635:24)
    at file:///Users/alexfong/Documents/plural-energy/tap-cap-table/src/server.js:57:5
    at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:409:24)
    at async loadESM (node:internal/process/esm_loader:85:5)
    at async handleMainPromise (node:internal/modules/run_main:61:12)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1407:8)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  code: 'EADDRINUSE',
  errno: -48,
  syscall: 'listen',
  address: '::',
  port: 3000
}

Node.js v18.0.0
[nodemon] app crashed - waiting for file changes before starting...

Good call.


[QUESTION] Shaping Arabic Date

I am using SkiaSharp with SkiaSharp.Harfbuzz in a Xamarin App and it works fine with RTL languages like arabic.
I am currently facing a problem displaying an arabic date.
It works fine if it starts with arabic characters, but if it starts with a number it does not shape the text correctly.
The following date shows up correctly in canvas:
8 yluJ
In this example yluJ is July in arabic.
This date is not shaped correctly:
yluJ 8
I figured out it is a problem if the text starts with an LTR-Text following by an RTL text.
Is there any way to force SkiaSharp.Hafbuzz to use arabic shaping? Or is there any other way around this?

I need the actual encoded text to explain / investigate this further. In general HarfBuzz doesn't apply the BiDi algorithm als also just checks the first character of the text for Unicode properties. If the text starts with a LTR character the whole buffer is shaped with this direction.


list-clusters should display Config version

Description
As part of the work to implement the RFC for our revamped config handling (https://github.com/arkime/aws-aio/issues/80, https://github.com/arkime/aws-aio/issues/81), this task is to update list-clusters to display the deployed config version for each cluster.
Acceptance Criteria

list-clusters displays the currently-deployed configuration version for each cluster

Acceptance criteria met; resolving


Collect sub codes before calling top-phenotypic-query

[x] wait for https://github.com/Onto-Med/top-api/issues/135
[x] store flag in DB (default value is false)
[ ] collect sub codes if flag is true, before calling top-phenotypic-query

We might need to rethink this issue. @AlexU75 proposed the idea to distinguish between three cases:

use the code as is
include the whole sub tree
only include leafs of the sub tree

Aligned title and tasks to @RalphBln 's proposal on Slack.


Removes code associated with the ImagerySplitPosition

Follows up on https://github.com/CesiumGS/cesium/pull/10193 and removes all deprecated code.

Thanks for the pull request @sanjeetsuhag!

:heavy_check_mark: Signed CLA found.
:grey_question: CHANGES.md was not updated.

If this change updates the public API in any way, please add a bullet point to CHANGES.md.

:grey_question: Unit tests were not updated.

Make sure you've updated tests to reflect your changes, added tests for any new code, and ran the code coverage tool.

Reviewers, don't forget to make sure that:

[ ] Cesium Viewer works.
[ ] Works in 2D/CV.

Great, thanks @sanjeetsuhag !